xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 051d39bbeea3e1b0fd8395dc97be34acb3241891)
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);
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 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3821 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3822 		/* No reason to try to bring this address back. */
3823 		return;
3824 	}
3825 
3826 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3827 		goto alloc_fail;
3828 
3829 	if (ipif->ipif_arp_del_mp == NULL) {
3830 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3831 			goto alloc_fail;
3832 		ipif->ipif_arp_del_mp = arp_del_mp;
3833 	}
3834 
3835 	/* Setting the 'unverified' flag restarts DAD */
3836 	area = (area_t *)arp_add_mp->b_rptr;
3837 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3838 	    ACE_F_UNVERIFIED;
3839 	putnext(ill->ill_rq, arp_add_mp);
3840 	return;
3841 
3842 alloc_fail:
3843 	/* On allocation failure, just restart the timer */
3844 	freemsg(arp_add_mp);
3845 	if (ip_dup_recovery > 0) {
3846 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3847 		    MSEC_TO_TICK(ip_dup_recovery));
3848 	}
3849 }
3850 
3851 /*
3852  * This is for exclusive changes due to ARP.  Either tear down an interface due
3853  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3854  */
3855 /* ARGSUSED */
3856 static void
3857 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3858 {
3859 	ill_t	*ill = rq->q_ptr;
3860 	arh_t *arh;
3861 	ipaddr_t src;
3862 	ipif_t	*ipif;
3863 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3864 	char hbuf[MAC_STR_LEN];
3865 	char sbuf[INET_ADDRSTRLEN];
3866 	const char *failtype;
3867 	boolean_t bring_up;
3868 
3869 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3870 	case AR_CN_READY:
3871 		failtype = NULL;
3872 		bring_up = B_TRUE;
3873 		break;
3874 	case AR_CN_FAILED:
3875 		failtype = "in use";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	default:
3879 		failtype = "claimed";
3880 		bring_up = B_FALSE;
3881 		break;
3882 	}
3883 
3884 	arh = (arh_t *)mp->b_cont->b_rptr;
3885 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3886 
3887 	/* Handle failures due to probes */
3888 	if (src == 0) {
3889 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3890 		    IP_ADDR_LEN);
3891 	}
3892 
3893 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3894 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3895 	    sizeof (hbuf));
3896 	(void) ip_dot_addr(src, sbuf);
3897 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3898 
3899 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3900 		    ipif->ipif_lcl_addr != src) {
3901 			continue;
3902 		}
3903 
3904 		/*
3905 		 * If we failed on a recovery probe, then restart the timer to
3906 		 * try again later.
3907 		 */
3908 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3909 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3910 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3911 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3912 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3913 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If what we're trying to do has already been done, then do
3919 		 * nothing.
3920 		 */
3921 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3922 			continue;
3923 
3924 		if (ipif->ipif_id != 0) {
3925 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3926 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3927 			    ipif->ipif_id);
3928 		}
3929 		if (failtype == NULL) {
3930 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3931 			    ibuf);
3932 		} else {
3933 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3934 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3935 		}
3936 
3937 		if (bring_up) {
3938 			ASSERT(ill->ill_dl_up);
3939 			/*
3940 			 * Free up the ARP delete message so we can allocate
3941 			 * a fresh one through the normal path.
3942 			 */
3943 			freemsg(ipif->ipif_arp_del_mp);
3944 			ipif->ipif_arp_del_mp = NULL;
3945 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3946 			    EINPROGRESS) {
3947 				ipif->ipif_addr_ready = 1;
3948 				(void) ipif_up_done(ipif);
3949 			}
3950 			continue;
3951 		}
3952 
3953 		mutex_enter(&ill->ill_lock);
3954 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3955 		ipif->ipif_flags |= IPIF_DUPLICATE;
3956 		ill->ill_ipif_dup_count++;
3957 		mutex_exit(&ill->ill_lock);
3958 		/*
3959 		 * Already exclusive on the ill; no need to handle deferred
3960 		 * processing here.
3961 		 */
3962 		(void) ipif_down(ipif, NULL, NULL);
3963 		ipif_down_tail(ipif);
3964 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3965 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3966 		    ip_dup_recovery > 0) {
3967 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3968 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3969 		}
3970 	}
3971 	freemsg(mp);
3972 }
3973 
3974 /* ARGSUSED */
3975 static void
3976 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3977 {
3978 	ill_t	*ill = rq->q_ptr;
3979 	arh_t *arh;
3980 	ipaddr_t src;
3981 	ipif_t	*ipif;
3982 
3983 	arh = (arh_t *)mp->b_cont->b_rptr;
3984 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3985 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3986 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3987 			(void) ipif_resolver_up(ipif, Res_act_defend);
3988 	}
3989 	freemsg(mp);
3990 }
3991 
3992 /*
3993  * News from ARP.  ARP sends notification of interesting events down
3994  * to its clients using M_CTL messages with the interesting ARP packet
3995  * attached via b_cont.
3996  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3997  * queue as opposed to ARP sending the message to all the clients, i.e. all
3998  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3999  * table if a cache IRE is found to delete all the entries for the address in
4000  * the packet.
4001  */
4002 static void
4003 ip_arp_news(queue_t *q, mblk_t *mp)
4004 {
4005 	arcn_t		*arcn;
4006 	arh_t		*arh;
4007 	ire_t		*ire = NULL;
4008 	char		hbuf[MAC_STR_LEN];
4009 	char		sbuf[INET_ADDRSTRLEN];
4010 	ipaddr_t	src;
4011 	in6_addr_t	v6src;
4012 	boolean_t	isv6 = B_FALSE;
4013 	ipif_t		*ipif;
4014 	ill_t		*ill;
4015 
4016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4017 		if (q->q_next) {
4018 			putnext(q, mp);
4019 		} else
4020 			freemsg(mp);
4021 		return;
4022 	}
4023 	arh = (arh_t *)mp->b_cont->b_rptr;
4024 	/* Is it one we are interested in? */
4025 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4026 		isv6 = B_TRUE;
4027 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4028 		    IPV6_ADDR_LEN);
4029 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4030 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4031 		    IP_ADDR_LEN);
4032 	} else {
4033 		freemsg(mp);
4034 		return;
4035 	}
4036 
4037 	ill = q->q_ptr;
4038 
4039 	arcn = (arcn_t *)mp->b_rptr;
4040 	switch (arcn->arcn_code) {
4041 	case AR_CN_BOGON:
4042 		/*
4043 		 * Someone is sending ARP packets with a source protocol
4044 		 * address that we have published and for which we believe our
4045 		 * entry is authoritative and (when ill_arp_extend is set)
4046 		 * verified to be unique on the network.
4047 		 *
4048 		 * The ARP module internally handles the cases where the sender
4049 		 * is just probing (for DAD) and where the hardware address of
4050 		 * a non-authoritative entry has changed.  Thus, these are the
4051 		 * real conflicts, and we have to do resolution.
4052 		 *
4053 		 * We back away quickly from the address if it's from DHCP or
4054 		 * otherwise temporary and hasn't been used recently (or at
4055 		 * all).  We'd like to include "deprecated" addresses here as
4056 		 * well (as there's no real reason to defend something we're
4057 		 * discarding), but IPMP "reuses" this flag to mean something
4058 		 * other than the standard meaning.
4059 		 *
4060 		 * If the ARP module above is not extended (meaning that it
4061 		 * doesn't know how to defend the address), then we just log
4062 		 * the problem as we always did and continue on.  It's not
4063 		 * right, but there's little else we can do, and those old ATM
4064 		 * users are going away anyway.
4065 		 */
4066 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4067 		    hbuf, sizeof (hbuf));
4068 		(void) ip_dot_addr(src, sbuf);
4069 		if (isv6)
4070 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4071 		else
4072 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4073 
4074 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4075 			uint32_t now;
4076 			uint32_t maxage;
4077 			clock_t lused;
4078 			uint_t maxdefense;
4079 			uint_t defs;
4080 
4081 			/*
4082 			 * First, figure out if this address hasn't been used
4083 			 * in a while.  If it hasn't, then it's a better
4084 			 * candidate for abandoning.
4085 			 */
4086 			ipif = ire->ire_ipif;
4087 			ASSERT(ipif != NULL);
4088 			now = gethrestime_sec();
4089 			maxage = now - ire->ire_create_time;
4090 			if (maxage > ip_max_temp_idle)
4091 				maxage = ip_max_temp_idle;
4092 			lused = drv_hztousec(ddi_get_lbolt() -
4093 			    ire->ire_last_used_time) / MICROSEC + 1;
4094 			if (lused >= maxage && (ipif->ipif_flags &
4095 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4096 				maxdefense = ip_max_temp_defend;
4097 			else
4098 				maxdefense = ip_max_defend;
4099 
4100 			/*
4101 			 * Now figure out how many times we've defended
4102 			 * ourselves.  Ignore defenses that happened long in
4103 			 * the past.
4104 			 */
4105 			mutex_enter(&ire->ire_lock);
4106 			if ((defs = ire->ire_defense_count) > 0 &&
4107 			    now - ire->ire_defense_time > ip_defend_interval) {
4108 				ire->ire_defense_count = defs = 0;
4109 			}
4110 			ire->ire_defense_count++;
4111 			ire->ire_defense_time = now;
4112 			mutex_exit(&ire->ire_lock);
4113 			ill_refhold(ill);
4114 			ire_refrele(ire);
4115 
4116 			/*
4117 			 * If we've defended ourselves too many times already,
4118 			 * then give up and tear down the interface(s) using
4119 			 * this address.  Otherwise, defend by sending out a
4120 			 * gratuitous ARP.
4121 			 */
4122 			if (defs >= maxdefense && ill->ill_arp_extend) {
4123 				(void) qwriter_ip(NULL, ill, q, mp,
4124 				    ip_arp_excl, CUR_OP, B_FALSE);
4125 			} else {
4126 				cmn_err(CE_WARN,
4127 				    "node %s is using our IP address %s on %s",
4128 				    hbuf, sbuf, ill->ill_name);
4129 				/*
4130 				 * If this is an old (ATM) ARP module, then
4131 				 * don't try to defend the address.  Remain
4132 				 * compatible with the old behavior.  Defend
4133 				 * only with new ARP.
4134 				 */
4135 				if (ill->ill_arp_extend) {
4136 					(void) qwriter_ip(NULL, ill, q, mp,
4137 					    ip_arp_defend, CUR_OP, B_FALSE);
4138 				} else {
4139 					ill_refrele(ill);
4140 				}
4141 			}
4142 			return;
4143 		}
4144 		cmn_err(CE_WARN,
4145 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4146 		    hbuf, sbuf, ill->ill_name);
4147 		if (ire != NULL)
4148 			ire_refrele(ire);
4149 		break;
4150 	case AR_CN_ANNOUNCE:
4151 		if (isv6) {
4152 			/*
4153 			 * For XRESOLV interfaces.
4154 			 * Delete the IRE cache entry and NCE for this
4155 			 * v6 address
4156 			 */
4157 			ip_ire_clookup_and_delete_v6(&v6src);
4158 			/*
4159 			 * If v6src is a non-zero, it's a router address
4160 			 * as below. Do the same sort of thing to clean
4161 			 * out off-net IRE_CACHE entries that go through
4162 			 * the router.
4163 			 */
4164 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4165 				ire_walk_v6(ire_delete_cache_gw_v6,
4166 				    (char *)&v6src, ALL_ZONES);
4167 			}
4168 		} else {
4169 			nce_hw_map_t hwm;
4170 
4171 			/*
4172 			 * ARP gives us a copy of any packet where it thinks
4173 			 * the address has changed, so that we can update our
4174 			 * caches.  We're responsible for caching known answers
4175 			 * in the current design.  We check whether the
4176 			 * hardware address really has changed in all of our
4177 			 * entries that have cached this mapping, and if so, we
4178 			 * blow them away.  This way we will immediately pick
4179 			 * up the rare case of a host changing hardware
4180 			 * address.
4181 			 */
4182 			if (src == 0)
4183 				break;
4184 			hwm.hwm_addr = src;
4185 			hwm.hwm_hwlen = arh->arh_hlen;
4186 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4187 			ndp_walk_common(&ndp4, NULL,
4188 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4189 		}
4190 		break;
4191 	case AR_CN_READY:
4192 		/* No external v6 resolver has a contract to use this */
4193 		if (isv6)
4194 			break;
4195 		/* If the link is down, we'll retry this later */
4196 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4197 			break;
4198 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4199 		    NULL, NULL);
4200 		if (ipif != NULL) {
4201 			/*
4202 			 * If this is a duplicate recovery, then we now need to
4203 			 * go exclusive to bring this thing back up.
4204 			 */
4205 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4206 			    IPIF_DUPLICATE) {
4207 				ipif_refrele(ipif);
4208 				ill_refhold(ill);
4209 				(void) qwriter_ip(NULL, ill, q, mp,
4210 				    ip_arp_excl, CUR_OP, B_FALSE);
4211 				return;
4212 			}
4213 			/*
4214 			 * If this is the first notice that this address is
4215 			 * ready, then let the user know now.
4216 			 */
4217 			if ((ipif->ipif_flags & IPIF_UP) &&
4218 			    !ipif->ipif_addr_ready) {
4219 				ipif_mask_reply(ipif);
4220 				ip_rts_ifmsg(ipif);
4221 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4222 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4223 			}
4224 			ipif->ipif_addr_ready = 1;
4225 			ipif_refrele(ipif);
4226 		}
4227 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4228 		if (ire != NULL) {
4229 			ire->ire_defense_count = 0;
4230 			ire_refrele(ire);
4231 		}
4232 		break;
4233 	case AR_CN_FAILED:
4234 		/* No external v6 resolver has a contract to use this */
4235 		if (isv6)
4236 			break;
4237 		ill_refhold(ill);
4238 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4239 		    B_FALSE);
4240 		return;
4241 	}
4242 	freemsg(mp);
4243 }
4244 
4245 /*
4246  * Create a mblk suitable for carrying the interface index and/or source link
4247  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4248  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4249  * application.
4250  */
4251 mblk_t *
4252 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4253 {
4254 	mblk_t		*mp;
4255 	in_pktinfo_t	*pinfo;
4256 	ipha_t *ipha;
4257 	struct ether_header *pether;
4258 
4259 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4260 	if (mp == NULL) {
4261 		ip1dbg(("ip_add_info: allocation failure.\n"));
4262 		return (data_mp);
4263 	}
4264 
4265 	ipha	= (ipha_t *)data_mp->b_rptr;
4266 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4267 	bzero(pinfo, sizeof (in_pktinfo_t));
4268 	pinfo->in_pkt_flags = (uchar_t)flags;
4269 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4270 
4271 	if (flags & IPF_RECVIF)
4272 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (in_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		break;
4473 
4474 	case sizeof (ipa_conn_t):
4475 		ac = (ipa_conn_t *)ucp;
4476 		/* For raw socket, the local port is not set. */
4477 		if (ac->ac_lport == 0)
4478 			ac->ac_lport = connp->conn_lport;
4479 		/* Always verify destination reachability. */
4480 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4481 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4482 		    ipsec_policy_set, B_TRUE, B_TRUE);
4483 		break;
4484 
4485 	case sizeof (ipa_conn_x_t):
4486 		acx = (ipa_conn_x_t *)ucp;
4487 		/*
4488 		 * Whether or not to verify destination reachability depends
4489 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4490 		 */
4491 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4492 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4493 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4494 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4495 		break;
4496 	}
4497 	if (error == EINPROGRESS)
4498 		return (NULL);
4499 	else if (error != 0)
4500 		goto bad_addr;
4501 	/*
4502 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4503 	 * We can't do this in ip_bind_insert_ire because the policy
4504 	 * may not have been inherited at that point in time and hence
4505 	 * conn_out_enforce_policy may not be set.
4506 	 */
4507 	mp1 = mp->b_cont;
4508 	if (ire_requested && connp->conn_out_enforce_policy &&
4509 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4510 		ire_t *ire = (ire_t *)mp1->b_rptr;
4511 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4512 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4513 	}
4514 
4515 	/* Send it home. */
4516 	mp->b_datap->db_type = M_PCPROTO;
4517 	tbr->PRIM_type = T_BIND_ACK;
4518 	return (mp);
4519 
4520 bad_addr:
4521 	/*
4522 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4523 	 * a unix errno.
4524 	 */
4525 	if (error > 0)
4526 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4527 	else
4528 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4529 	return (mp);
4530 }
4531 
4532 /*
4533  * Here address is verified to be a valid local address.
4534  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4535  * address is also considered a valid local address.
4536  * In the case of a broadcast/multicast address, however, the
4537  * upper protocol is expected to reset the src address
4538  * to 0 if it sees a IRE_BROADCAST type returned so that
4539  * no packets are emitted with broadcast/multicast address as
4540  * source address (that violates hosts requirements RFC1122)
4541  * The addresses valid for bind are:
4542  *	(1) - INADDR_ANY (0)
4543  *	(2) - IP address of an UP interface
4544  *	(3) - IP address of a DOWN interface
4545  *	(4) - valid local IP broadcast addresses. In this case
4546  *	the conn will only receive packets destined to
4547  *	the specified broadcast address.
4548  *	(5) - a multicast address. In this case
4549  *	the conn will only receive packets destined to
4550  *	the specified multicast address. Note: the
4551  *	application still has to issue an
4552  *	IP_ADD_MEMBERSHIP socket option.
4553  *
4554  * On error, return -1 for TBADADDR otherwise pass the
4555  * errno with TSYSERR reply.
4556  *
4557  * In all the above cases, the bound address must be valid in the current zone.
4558  * When the address is loopback, multicast or broadcast, there might be many
4559  * matching IREs so bind has to look up based on the zone.
4560  *
4561  * Note: lport is in network byte order.
4562  */
4563 int
4564 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4565     boolean_t ire_requested, boolean_t ipsec_policy_set,
4566     boolean_t fanout_insert)
4567 {
4568 	int		error = 0;
4569 	ire_t		*src_ire;
4570 	mblk_t		*policy_mp;
4571 	ipif_t		*ipif;
4572 	zoneid_t	zoneid;
4573 
4574 	if (ipsec_policy_set) {
4575 		policy_mp = mp->b_cont;
4576 	}
4577 
4578 	/*
4579 	 * If it was previously connected, conn_fully_bound would have
4580 	 * been set.
4581 	 */
4582 	connp->conn_fully_bound = B_FALSE;
4583 
4584 	src_ire = NULL;
4585 	ipif = NULL;
4586 
4587 	zoneid = IPCL_ZONEID(connp);
4588 
4589 	if (src_addr) {
4590 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4591 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4592 		/*
4593 		 * If an address other than 0.0.0.0 is requested,
4594 		 * we verify that it is a valid address for bind
4595 		 * Note: Following code is in if-else-if form for
4596 		 * readability compared to a condition check.
4597 		 */
4598 		/* LINTED - statement has no consequent */
4599 		if (IRE_IS_LOCAL(src_ire)) {
4600 			/*
4601 			 * (2) Bind to address of local UP interface
4602 			 */
4603 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4604 			/*
4605 			 * (4) Bind to broadcast address
4606 			 * Note: permitted only from transports that
4607 			 * request IRE
4608 			 */
4609 			if (!ire_requested)
4610 				error = EADDRNOTAVAIL;
4611 		} else {
4612 			/*
4613 			 * (3) Bind to address of local DOWN interface
4614 			 * (ipif_lookup_addr() looks up all interfaces
4615 			 * but we do not get here for UP interfaces
4616 			 * - case (2) above)
4617 			 * We put the protocol byte back into the mblk
4618 			 * since we may come back via ip_wput_nondata()
4619 			 * later with this mblk if ipif_lookup_addr chooses
4620 			 * to defer processing.
4621 			 */
4622 			*mp->b_wptr++ = (char)connp->conn_ulp;
4623 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4624 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4625 			    &error)) != NULL) {
4626 				ipif_refrele(ipif);
4627 			} else if (error == EINPROGRESS) {
4628 				if (src_ire != NULL)
4629 					ire_refrele(src_ire);
4630 				return (EINPROGRESS);
4631 			} else if (CLASSD(src_addr)) {
4632 				error = 0;
4633 				if (src_ire != NULL)
4634 					ire_refrele(src_ire);
4635 				/*
4636 				 * (5) bind to multicast address.
4637 				 * Fake out the IRE returned to upper
4638 				 * layer to be a broadcast IRE.
4639 				 */
4640 				src_ire = ire_ctable_lookup(
4641 				    INADDR_BROADCAST, INADDR_ANY,
4642 				    IRE_BROADCAST, NULL, zoneid, NULL,
4643 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4644 				if (src_ire == NULL || !ire_requested)
4645 					error = EADDRNOTAVAIL;
4646 			} else {
4647 				/*
4648 				 * Not a valid address for bind
4649 				 */
4650 				error = EADDRNOTAVAIL;
4651 			}
4652 			/*
4653 			 * Just to keep it consistent with the processing in
4654 			 * ip_bind_v4()
4655 			 */
4656 			mp->b_wptr--;
4657 		}
4658 		if (error) {
4659 			/* Red Alert!  Attempting to be a bogon! */
4660 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4661 			    ntohl(src_addr)));
4662 			goto bad_addr;
4663 		}
4664 	}
4665 
4666 	/*
4667 	 * Allow setting new policies. For example, disconnects come
4668 	 * down as ipa_t bind. As we would have set conn_policy_cached
4669 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4670 	 * can change after the disconnect.
4671 	 */
4672 	connp->conn_policy_cached = B_FALSE;
4673 
4674 	/*
4675 	 * If not fanout_insert this was just an address verification
4676 	 */
4677 	if (fanout_insert) {
4678 		/*
4679 		 * The addresses have been verified. Time to insert in
4680 		 * the correct fanout list.
4681 		 */
4682 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4683 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4684 		connp->conn_lport = lport;
4685 		connp->conn_fport = 0;
4686 		/*
4687 		 * Do we need to add a check to reject Multicast packets
4688 		 *
4689 		 * We need to make sure that the conn_recv is set to a non-null
4690 		 * value before we insert the conn into the classifier table.
4691 		 * This is to avoid a race with an incoming packet which does an
4692 		 * ipcl_classify().
4693 		 */
4694 		if (*mp->b_wptr == IPPROTO_TCP)
4695 			connp->conn_recv = tcp_conn_request;
4696 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4697 	}
4698 
4699 	if (error == 0) {
4700 		if (ire_requested) {
4701 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4702 				error = -1;
4703 				/* Falls through to bad_addr */
4704 			}
4705 		} else if (ipsec_policy_set) {
4706 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4707 				error = -1;
4708 				/* Falls through to bad_addr */
4709 			}
4710 		}
4711 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4712 		connp->conn_recv = tcp_input;
4713 	}
4714 bad_addr:
4715 	if (error != 0) {
4716 		if (connp->conn_anon_port) {
4717 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4718 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4719 			    B_FALSE);
4720 		}
4721 		connp->conn_mlp_type = mlptSingle;
4722 	}
4723 	if (src_ire != NULL)
4724 		IRE_REFRELE(src_ire);
4725 	if (ipsec_policy_set) {
4726 		ASSERT(policy_mp == mp->b_cont);
4727 		ASSERT(policy_mp != NULL);
4728 		freeb(policy_mp);
4729 		/*
4730 		 * As of now assume that nothing else accompanies
4731 		 * IPSEC_POLICY_SET.
4732 		 */
4733 		mp->b_cont = NULL;
4734 	}
4735 	return (error);
4736 }
4737 
4738 /*
4739  * Verify that both the source and destination addresses
4740  * are valid.  If verify_dst is false, then the destination address may be
4741  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4742  * destination reachability, while tunnels do not.
4743  * Note that we allow connect to broadcast and multicast
4744  * addresses when ire_requested is set. Thus the ULP
4745  * has to check for IRE_BROADCAST and multicast.
4746  *
4747  * Returns zero if ok.
4748  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4749  * (for use with TSYSERR reply).
4750  *
4751  * Note: lport and fport are in network byte order.
4752  */
4753 int
4754 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4755     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4756     boolean_t ire_requested, boolean_t ipsec_policy_set,
4757     boolean_t fanout_insert, boolean_t verify_dst)
4758 {
4759 	ire_t		*src_ire;
4760 	ire_t		*dst_ire;
4761 	int		error = 0;
4762 	int 		protocol;
4763 	mblk_t		*policy_mp;
4764 	ire_t		*sire = NULL;
4765 	ire_t		*md_dst_ire = NULL;
4766 	ire_t		*lso_dst_ire = NULL;
4767 	ill_t		*ill = NULL;
4768 	zoneid_t	zoneid;
4769 	ipaddr_t	src_addr = *src_addrp;
4770 
4771 	src_ire = dst_ire = NULL;
4772 	protocol = *mp->b_wptr & 0xFF;
4773 
4774 	/*
4775 	 * If we never got a disconnect before, clear it now.
4776 	 */
4777 	connp->conn_fully_bound = B_FALSE;
4778 
4779 	if (ipsec_policy_set) {
4780 		policy_mp = mp->b_cont;
4781 	}
4782 
4783 	zoneid = IPCL_ZONEID(connp);
4784 
4785 	if (CLASSD(dst_addr)) {
4786 		/* Pick up an IRE_BROADCAST */
4787 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4788 		    NULL, zoneid, MBLK_GETLABEL(mp),
4789 		    (MATCH_IRE_RECURSIVE |
4790 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4791 		    MATCH_IRE_SECATTR));
4792 	} else {
4793 		/*
4794 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4795 		 * and onlink ipif is not found set ENETUNREACH error.
4796 		 */
4797 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4798 			ipif_t *ipif;
4799 
4800 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4801 			    dst_addr : connp->conn_nexthop_v4,
4802 			    connp->conn_zoneid);
4803 			if (ipif == NULL) {
4804 				error = ENETUNREACH;
4805 				goto bad_addr;
4806 			}
4807 			ipif_refrele(ipif);
4808 		}
4809 
4810 		if (connp->conn_nexthop_set) {
4811 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4812 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4813 			    MATCH_IRE_SECATTR);
4814 		} else {
4815 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4816 			    &sire, zoneid, MBLK_GETLABEL(mp),
4817 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4818 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4819 			    MATCH_IRE_SECATTR));
4820 		}
4821 	}
4822 	/*
4823 	 * dst_ire can't be a broadcast when not ire_requested.
4824 	 * We also prevent ire's with src address INADDR_ANY to
4825 	 * be used, which are created temporarily for
4826 	 * sending out packets from endpoints that have
4827 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4828 	 * reachable.  If verify_dst is false, the destination needn't be
4829 	 * reachable.
4830 	 *
4831 	 * If we match on a reject or black hole, then we've got a
4832 	 * local failure.  May as well fail out the connect() attempt,
4833 	 * since it's never going to succeed.
4834 	 */
4835 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4836 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4837 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4838 		/*
4839 		 * If we're verifying destination reachability, we always want
4840 		 * to complain here.
4841 		 *
4842 		 * If we're not verifying destination reachability but the
4843 		 * destination has a route, we still want to fail on the
4844 		 * temporary address and broadcast address tests.
4845 		 */
4846 		if (verify_dst || (dst_ire != NULL)) {
4847 			if (ip_debug > 2) {
4848 				pr_addr_dbg("ip_bind_connected: bad connected "
4849 				    "dst %s\n", AF_INET, &dst_addr);
4850 			}
4851 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4852 				error = ENETUNREACH;
4853 			else
4854 				error = EHOSTUNREACH;
4855 			goto bad_addr;
4856 		}
4857 	}
4858 
4859 	/*
4860 	 * We now know that routing will allow us to reach the destination.
4861 	 * Check whether Trusted Solaris policy allows communication with this
4862 	 * host, and pretend that the destination is unreachable if not.
4863 	 *
4864 	 * This is never a problem for TCP, since that transport is known to
4865 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4866 	 * handling.  If the remote is unreachable, it will be detected at that
4867 	 * point, so there's no reason to check it here.
4868 	 *
4869 	 * Note that for sendto (and other datagram-oriented friends), this
4870 	 * check is done as part of the data path label computation instead.
4871 	 * The check here is just to make non-TCP connect() report the right
4872 	 * error.
4873 	 */
4874 	if (dst_ire != NULL && is_system_labeled() &&
4875 	    !IPCL_IS_TCP(connp) &&
4876 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4877 	    connp->conn_mac_exempt) != 0) {
4878 		error = EHOSTUNREACH;
4879 		if (ip_debug > 2) {
4880 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4881 			    AF_INET, &dst_addr);
4882 		}
4883 		goto bad_addr;
4884 	}
4885 
4886 	/*
4887 	 * If the app does a connect(), it means that it will most likely
4888 	 * send more than 1 packet to the destination.  It makes sense
4889 	 * to clear the temporary flag.
4890 	 */
4891 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4892 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4893 		irb_t *irb = dst_ire->ire_bucket;
4894 
4895 		rw_enter(&irb->irb_lock, RW_WRITER);
4896 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4897 		irb->irb_tmp_ire_cnt--;
4898 		rw_exit(&irb->irb_lock);
4899 	}
4900 
4901 	/*
4902 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4903 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4904 	 * eligibility tests for passive connects are handled separately
4905 	 * through tcp_adapt_ire().  We do this before the source address
4906 	 * selection, because dst_ire may change after a call to
4907 	 * ipif_select_source().  This is a best-effort check, as the
4908 	 * packet for this connection may not actually go through
4909 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4910 	 * calling ip_newroute().  This is why we further check on the
4911 	 * IRE during LSO/Multidata packet transmission in
4912 	 * tcp_lsosend()/tcp_multisend().
4913 	 */
4914 	if (!ipsec_policy_set && dst_ire != NULL &&
4915 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4916 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4917 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4918 			lso_dst_ire = dst_ire;
4919 			IRE_REFHOLD(lso_dst_ire);
4920 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4921 			md_dst_ire = dst_ire;
4922 			IRE_REFHOLD(md_dst_ire);
4923 		}
4924 	}
4925 
4926 	if (dst_ire != NULL &&
4927 	    dst_ire->ire_type == IRE_LOCAL &&
4928 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4929 		/*
4930 		 * If the IRE belongs to a different zone, look for a matching
4931 		 * route in the forwarding table and use the source address from
4932 		 * that route.
4933 		 */
4934 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4935 		    zoneid, 0, NULL,
4936 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4937 		    MATCH_IRE_RJ_BHOLE);
4938 		if (src_ire == NULL) {
4939 			error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4942 			if (!(src_ire->ire_type & IRE_HOST))
4943 				error = ENETUNREACH;
4944 			else
4945 				error = EHOSTUNREACH;
4946 			goto bad_addr;
4947 		}
4948 		if (src_addr == INADDR_ANY)
4949 			src_addr = src_ire->ire_src_addr;
4950 		ire_refrele(src_ire);
4951 		src_ire = NULL;
4952 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4953 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4954 			src_addr = sire->ire_src_addr;
4955 			ire_refrele(dst_ire);
4956 			dst_ire = sire;
4957 			sire = NULL;
4958 		} else {
4959 			/*
4960 			 * Pick a source address so that a proper inbound
4961 			 * load spreading would happen.
4962 			 */
4963 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4964 			ipif_t *src_ipif = NULL;
4965 			ire_t *ipif_ire;
4966 
4967 			/*
4968 			 * Supply a local source address such that inbound
4969 			 * load spreading happens.
4970 			 *
4971 			 * Determine the best source address on this ill for
4972 			 * the destination.
4973 			 *
4974 			 * 1) For broadcast, we should return a broadcast ire
4975 			 *    found above so that upper layers know that the
4976 			 *    destination address is a broadcast address.
4977 			 *
4978 			 * 2) If this is part of a group, select a better
4979 			 *    source address so that better inbound load
4980 			 *    balancing happens. Do the same if the ipif
4981 			 *    is DEPRECATED.
4982 			 *
4983 			 * 3) If the outgoing interface is part of a usesrc
4984 			 *    group, then try selecting a source address from
4985 			 *    the usesrc ILL.
4986 			 */
4987 			if ((dst_ire->ire_zoneid != zoneid &&
4988 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4989 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4990 			    ((dst_ill->ill_group != NULL) ||
4991 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4992 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4993 				/*
4994 				 * If the destination is reachable via a
4995 				 * given gateway, the selected source address
4996 				 * should be in the same subnet as the gateway.
4997 				 * Otherwise, the destination is not reachable.
4998 				 *
4999 				 * If there are no interfaces on the same subnet
5000 				 * as the destination, ipif_select_source gives
5001 				 * first non-deprecated interface which might be
5002 				 * on a different subnet than the gateway.
5003 				 * This is not desirable. Hence pass the dst_ire
5004 				 * source address to ipif_select_source.
5005 				 * It is sure that the destination is reachable
5006 				 * with the dst_ire source address subnet.
5007 				 * So passing dst_ire source address to
5008 				 * ipif_select_source will make sure that the
5009 				 * selected source will be on the same subnet
5010 				 * as dst_ire source address.
5011 				 */
5012 				ipaddr_t saddr =
5013 				    dst_ire->ire_ipif->ipif_src_addr;
5014 				src_ipif = ipif_select_source(dst_ill,
5015 				    saddr, zoneid);
5016 				if (src_ipif != NULL) {
5017 					if (IS_VNI(src_ipif->ipif_ill)) {
5018 						/*
5019 						 * For VNI there is no
5020 						 * interface route
5021 						 */
5022 						src_addr =
5023 						    src_ipif->ipif_src_addr;
5024 					} else {
5025 						ipif_ire =
5026 						    ipif_to_ire(src_ipif);
5027 						if (ipif_ire != NULL) {
5028 							IRE_REFRELE(dst_ire);
5029 							dst_ire = ipif_ire;
5030 						}
5031 						src_addr =
5032 						    dst_ire->ire_src_addr;
5033 					}
5034 					ipif_refrele(src_ipif);
5035 				} else {
5036 					src_addr = dst_ire->ire_src_addr;
5037 				}
5038 			} else {
5039 				src_addr = dst_ire->ire_src_addr;
5040 			}
5041 		}
5042 	}
5043 
5044 	/*
5045 	 * We do ire_route_lookup() here (and not
5046 	 * interface lookup as we assert that
5047 	 * src_addr should only come from an
5048 	 * UP interface for hard binding.
5049 	 */
5050 	ASSERT(src_ire == NULL);
5051 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5052 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5053 	/* src_ire must be a local|loopback */
5054 	if (!IRE_IS_LOCAL(src_ire)) {
5055 		if (ip_debug > 2) {
5056 			pr_addr_dbg("ip_bind_connected: bad connected "
5057 			    "src %s\n", AF_INET, &src_addr);
5058 		}
5059 		error = EADDRNOTAVAIL;
5060 		goto bad_addr;
5061 	}
5062 
5063 	/*
5064 	 * If the source address is a loopback address, the
5065 	 * destination had best be local or multicast.
5066 	 * The transports that can't handle multicast will reject
5067 	 * those addresses.
5068 	 */
5069 	if (src_ire->ire_type == IRE_LOOPBACK &&
5070 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5071 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5072 		error = -1;
5073 		goto bad_addr;
5074 	}
5075 
5076 	/*
5077 	 * Allow setting new policies. For example, disconnects come
5078 	 * down as ipa_t bind. As we would have set conn_policy_cached
5079 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5080 	 * can change after the disconnect.
5081 	 */
5082 	connp->conn_policy_cached = B_FALSE;
5083 
5084 	/*
5085 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5086 	 * can handle their passed-in conn's.
5087 	 */
5088 
5089 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5090 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5091 	connp->conn_lport = lport;
5092 	connp->conn_fport = fport;
5093 	*src_addrp = src_addr;
5094 
5095 	ASSERT(!(ipsec_policy_set && ire_requested));
5096 	if (ire_requested) {
5097 		iulp_t *ulp_info = NULL;
5098 
5099 		/*
5100 		 * Note that sire will not be NULL if this is an off-link
5101 		 * connection and there is not cache for that dest yet.
5102 		 *
5103 		 * XXX Because of an existing bug, if there are multiple
5104 		 * default routes, the IRE returned now may not be the actual
5105 		 * default route used (default routes are chosen in a
5106 		 * round robin fashion).  So if the metrics for different
5107 		 * default routes are different, we may return the wrong
5108 		 * metrics.  This will not be a problem if the existing
5109 		 * bug is fixed.
5110 		 */
5111 		if (sire != NULL) {
5112 			ulp_info = &(sire->ire_uinfo);
5113 		}
5114 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5115 			error = -1;
5116 			goto bad_addr;
5117 		}
5118 	} else if (ipsec_policy_set) {
5119 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5120 			error = -1;
5121 			goto bad_addr;
5122 		}
5123 	}
5124 
5125 	/*
5126 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5127 	 * we'll cache that.  If we don't, we'll inherit global policy.
5128 	 *
5129 	 * We can't insert until the conn reflects the policy. Note that
5130 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5131 	 * connections where we don't have a policy. This is to prevent
5132 	 * global policy lookups in the inbound path.
5133 	 *
5134 	 * If we insert before we set conn_policy_cached,
5135 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5136 	 * because global policy cound be non-empty. We normally call
5137 	 * ipsec_check_policy() for conn_policy_cached connections only if
5138 	 * ipc_in_enforce_policy is set. But in this case,
5139 	 * conn_policy_cached can get set anytime since we made the
5140 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5141 	 * called, which will make the above assumption false.  Thus, we
5142 	 * need to insert after we set conn_policy_cached.
5143 	 */
5144 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5145 		goto bad_addr;
5146 
5147 	if (fanout_insert) {
5148 		/*
5149 		 * The addresses have been verified. Time to insert in
5150 		 * the correct fanout list.
5151 		 * We need to make sure that the conn_recv is set to a non-null
5152 		 * value before we insert into the classifier table to avoid a
5153 		 * race with an incoming packet which does an ipcl_classify().
5154 		 */
5155 		if (protocol == IPPROTO_TCP)
5156 			connp->conn_recv = tcp_input;
5157 		error = ipcl_conn_insert(connp, protocol, src_addr,
5158 		    dst_addr, connp->conn_ports);
5159 	}
5160 
5161 	if (error == 0) {
5162 		connp->conn_fully_bound = B_TRUE;
5163 		/*
5164 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5165 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5166 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5167 		 * ip_xxinfo_return(), which performs further checks
5168 		 * against them and upon success, returns the LSO/MDT info
5169 		 * mblk which we will attach to the bind acknowledgment.
5170 		 */
5171 		if (lso_dst_ire != NULL) {
5172 			mblk_t *lsoinfo_mp;
5173 
5174 			ASSERT(ill->ill_lso_capab != NULL);
5175 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5176 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5177 				linkb(mp, lsoinfo_mp);
5178 		} else if (md_dst_ire != NULL) {
5179 			mblk_t *mdinfo_mp;
5180 
5181 			ASSERT(ill->ill_mdt_capab != NULL);
5182 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5183 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5184 				linkb(mp, mdinfo_mp);
5185 		}
5186 	}
5187 bad_addr:
5188 	if (ipsec_policy_set) {
5189 		ASSERT(policy_mp == mp->b_cont);
5190 		ASSERT(policy_mp != NULL);
5191 		freeb(policy_mp);
5192 		/*
5193 		 * As of now assume that nothing else accompanies
5194 		 * IPSEC_POLICY_SET.
5195 		 */
5196 		mp->b_cont = NULL;
5197 	}
5198 	if (src_ire != NULL)
5199 		IRE_REFRELE(src_ire);
5200 	if (dst_ire != NULL)
5201 		IRE_REFRELE(dst_ire);
5202 	if (sire != NULL)
5203 		IRE_REFRELE(sire);
5204 	if (md_dst_ire != NULL)
5205 		IRE_REFRELE(md_dst_ire);
5206 	if (lso_dst_ire != NULL)
5207 		IRE_REFRELE(lso_dst_ire);
5208 	return (error);
5209 }
5210 
5211 /*
5212  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5213  * Prefers dst_ire over src_ire.
5214  */
5215 static boolean_t
5216 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5217 {
5218 	mblk_t	*mp1;
5219 	ire_t *ret_ire = NULL;
5220 
5221 	mp1 = mp->b_cont;
5222 	ASSERT(mp1 != NULL);
5223 
5224 	if (ire != NULL) {
5225 		/*
5226 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5227 		 * appended mblk. Its <upper protocol>'s
5228 		 * job to make sure there is room.
5229 		 */
5230 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5231 			return (0);
5232 
5233 		mp1->b_datap->db_type = IRE_DB_TYPE;
5234 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5235 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5236 		ret_ire = (ire_t *)mp1->b_rptr;
5237 		/*
5238 		 * Pass the latest setting of the ip_path_mtu_discovery and
5239 		 * copy the ulp info if any.
5240 		 */
5241 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5242 		    IPH_DF : 0;
5243 		if (ulp_info != NULL) {
5244 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5245 			    sizeof (iulp_t));
5246 		}
5247 		ret_ire->ire_mp = mp1;
5248 	} else {
5249 		/*
5250 		 * No IRE was found. Remove IRE mblk.
5251 		 */
5252 		mp->b_cont = mp1->b_cont;
5253 		freeb(mp1);
5254 	}
5255 
5256 	return (1);
5257 }
5258 
5259 /*
5260  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5261  * the final piece where we don't.  Return a pointer to the first mblk in the
5262  * result, and update the pointer to the next mblk to chew on.  If anything
5263  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5264  * NULL pointer.
5265  */
5266 mblk_t *
5267 ip_carve_mp(mblk_t **mpp, ssize_t len)
5268 {
5269 	mblk_t	*mp0;
5270 	mblk_t	*mp1;
5271 	mblk_t	*mp2;
5272 
5273 	if (!len || !mpp || !(mp0 = *mpp))
5274 		return (NULL);
5275 	/* If we aren't going to consume the first mblk, we need a dup. */
5276 	if (mp0->b_wptr - mp0->b_rptr > len) {
5277 		mp1 = dupb(mp0);
5278 		if (mp1) {
5279 			/* Partition the data between the two mblks. */
5280 			mp1->b_wptr = mp1->b_rptr + len;
5281 			mp0->b_rptr = mp1->b_wptr;
5282 			/*
5283 			 * after adjustments if mblk not consumed is now
5284 			 * unaligned, try to align it. If this fails free
5285 			 * all messages and let upper layer recover.
5286 			 */
5287 			if (!OK_32PTR(mp0->b_rptr)) {
5288 				if (!pullupmsg(mp0, -1)) {
5289 					freemsg(mp0);
5290 					freemsg(mp1);
5291 					*mpp = NULL;
5292 					return (NULL);
5293 				}
5294 			}
5295 		}
5296 		return (mp1);
5297 	}
5298 	/* Eat through as many mblks as we need to get len bytes. */
5299 	len -= mp0->b_wptr - mp0->b_rptr;
5300 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5301 		if (mp2->b_wptr - mp2->b_rptr > len) {
5302 			/*
5303 			 * We won't consume the entire last mblk.  Like
5304 			 * above, dup and partition it.
5305 			 */
5306 			mp1->b_cont = dupb(mp2);
5307 			mp1 = mp1->b_cont;
5308 			if (!mp1) {
5309 				/*
5310 				 * Trouble.  Rather than go to a lot of
5311 				 * trouble to clean up, we free the messages.
5312 				 * This won't be any worse than losing it on
5313 				 * the wire.
5314 				 */
5315 				freemsg(mp0);
5316 				freemsg(mp2);
5317 				*mpp = NULL;
5318 				return (NULL);
5319 			}
5320 			mp1->b_wptr = mp1->b_rptr + len;
5321 			mp2->b_rptr = mp1->b_wptr;
5322 			/*
5323 			 * after adjustments if mblk not consumed is now
5324 			 * unaligned, try to align it. If this fails free
5325 			 * all messages and let upper layer recover.
5326 			 */
5327 			if (!OK_32PTR(mp2->b_rptr)) {
5328 				if (!pullupmsg(mp2, -1)) {
5329 					freemsg(mp0);
5330 					freemsg(mp2);
5331 					*mpp = NULL;
5332 					return (NULL);
5333 				}
5334 			}
5335 			*mpp = mp2;
5336 			return (mp0);
5337 		}
5338 		/* Decrement len by the amount we just got. */
5339 		len -= mp2->b_wptr - mp2->b_rptr;
5340 	}
5341 	/*
5342 	 * len should be reduced to zero now.  If not our caller has
5343 	 * screwed up.
5344 	 */
5345 	if (len) {
5346 		/* Shouldn't happen! */
5347 		freemsg(mp0);
5348 		*mpp = NULL;
5349 		return (NULL);
5350 	}
5351 	/*
5352 	 * We consumed up to exactly the end of an mblk.  Detach the part
5353 	 * we are returning from the rest of the chain.
5354 	 */
5355 	mp1->b_cont = NULL;
5356 	*mpp = mp2;
5357 	return (mp0);
5358 }
5359 
5360 /* The ill stream is being unplumbed. Called from ip_close */
5361 int
5362 ip_modclose(ill_t *ill)
5363 {
5364 
5365 	boolean_t success;
5366 	ipsq_t	*ipsq;
5367 	ipif_t	*ipif;
5368 	queue_t	*q = ill->ill_rq;
5369 	hook_nic_event_t *info;
5370 	clock_t timeout;
5371 
5372 	/*
5373 	 * Wait for the ACKs of all deferred control messages to be processed.
5374 	 * In particular, we wait for a potential capability reset initiated
5375 	 * in ip_sioctl_plink() to complete before proceeding.
5376 	 *
5377 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5378 	 * in case the driver never replies.
5379 	 */
5380 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5381 	mutex_enter(&ill->ill_lock);
5382 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5383 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5384 			/* Timeout */
5385 			break;
5386 		}
5387 	}
5388 	mutex_exit(&ill->ill_lock);
5389 
5390 	/*
5391 	 * Forcibly enter the ipsq after some delay. This is to take
5392 	 * care of the case when some ioctl does not complete because
5393 	 * we sent a control message to the driver and it did not
5394 	 * send us a reply. We want to be able to at least unplumb
5395 	 * and replumb rather than force the user to reboot the system.
5396 	 */
5397 	success = ipsq_enter(ill, B_FALSE);
5398 
5399 	/*
5400 	 * Open/close/push/pop is guaranteed to be single threaded
5401 	 * per stream by STREAMS. FS guarantees that all references
5402 	 * from top are gone before close is called. So there can't
5403 	 * be another close thread that has set CONDEMNED on this ill.
5404 	 * and cause ipsq_enter to return failure.
5405 	 */
5406 	ASSERT(success);
5407 	ipsq = ill->ill_phyint->phyint_ipsq;
5408 
5409 	/*
5410 	 * Mark it condemned. No new reference will be made to this ill.
5411 	 * Lookup functions will return an error. Threads that try to
5412 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5413 	 * that the refcnt will drop down to zero.
5414 	 */
5415 	mutex_enter(&ill->ill_lock);
5416 	ill->ill_state_flags |= ILL_CONDEMNED;
5417 	for (ipif = ill->ill_ipif; ipif != NULL;
5418 	    ipif = ipif->ipif_next) {
5419 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5420 	}
5421 	/*
5422 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5423 	 * returns  error if ILL_CONDEMNED is set
5424 	 */
5425 	cv_broadcast(&ill->ill_cv);
5426 	mutex_exit(&ill->ill_lock);
5427 
5428 	/*
5429 	 * Send all the deferred control messages downstream which came in
5430 	 * during the small window right before ipsq_enter(). We do this
5431 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5432 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5433 	 */
5434 	ill_send_all_deferred_mp(ill);
5435 
5436 	/*
5437 	 * Shut down fragmentation reassembly.
5438 	 * ill_frag_timer won't start a timer again.
5439 	 * Now cancel any existing timer
5440 	 */
5441 	(void) untimeout(ill->ill_frag_timer_id);
5442 	(void) ill_frag_timeout(ill, 0);
5443 
5444 	/*
5445 	 * If MOVE was in progress, clear the
5446 	 * move_in_progress fields also.
5447 	 */
5448 	if (ill->ill_move_in_progress) {
5449 		ILL_CLEAR_MOVE(ill);
5450 	}
5451 
5452 	/*
5453 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5454 	 * this ill. Then wait for the refcnts to drop to zero.
5455 	 * ill_is_quiescent checks whether the ill is really quiescent.
5456 	 * Then make sure that threads that are waiting to enter the
5457 	 * ipsq have seen the error returned by ipsq_enter and have
5458 	 * gone away. Then we call ill_delete_tail which does the
5459 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5460 	 */
5461 	ill_delete(ill);
5462 	mutex_enter(&ill->ill_lock);
5463 	while (!ill_is_quiescent(ill))
5464 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5465 	while (ill->ill_waiters)
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 
5468 	mutex_exit(&ill->ill_lock);
5469 
5470 	/* qprocsoff is called in ill_delete_tail */
5471 	ill_delete_tail(ill);
5472 
5473 	/*
5474 	 * Walk through all upper (conn) streams and qenable
5475 	 * those that have queued data.
5476 	 * close synchronization needs this to
5477 	 * be done to ensure that all upper layers blocked
5478 	 * due to flow control to the closing device
5479 	 * get unblocked.
5480 	 */
5481 	ip1dbg(("ip_wsrv: walking\n"));
5482 	conn_walk_drain();
5483 
5484 	mutex_enter(&ip_mi_lock);
5485 	mi_close_unlink(&ip_g_head, (IDP)ill);
5486 	mutex_exit(&ip_mi_lock);
5487 
5488 	/*
5489 	 * credp could be null if the open didn't succeed and ip_modopen
5490 	 * itself calls ip_close.
5491 	 */
5492 	if (ill->ill_credp != NULL)
5493 		crfree(ill->ill_credp);
5494 
5495 	/*
5496 	 * Unhook the nic event message from the ill and enqueue it into the nic
5497 	 * event taskq.
5498 	 */
5499 	if ((info = ill->ill_nic_event_info) != NULL) {
5500 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5501 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5502 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5503 			if (info->hne_data != NULL)
5504 				kmem_free(info->hne_data, info->hne_datalen);
5505 			kmem_free(info, sizeof (hook_nic_event_t));
5506 		}
5507 		ill->ill_nic_event_info = NULL;
5508 	}
5509 
5510 	mi_close_free((IDP)ill);
5511 	q->q_ptr = WR(q)->q_ptr = NULL;
5512 
5513 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5514 
5515 	return (0);
5516 }
5517 
5518 /*
5519  * This is called as part of close() for both IP and UDP
5520  * in order to quiesce the conn.
5521  */
5522 void
5523 ip_quiesce_conn(conn_t *connp)
5524 {
5525 	boolean_t	drain_cleanup_reqd = B_FALSE;
5526 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5527 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5528 
5529 	ASSERT(!IPCL_IS_TCP(connp));
5530 
5531 	/*
5532 	 * Mark the conn as closing, and this conn must not be
5533 	 * inserted in future into any list. Eg. conn_drain_insert(),
5534 	 * won't insert this conn into the conn_drain_list.
5535 	 * Similarly ill_pending_mp_add() will not add any mp to
5536 	 * the pending mp list, after this conn has started closing.
5537 	 *
5538 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5539 	 * cannot get set henceforth.
5540 	 */
5541 	mutex_enter(&connp->conn_lock);
5542 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5543 	connp->conn_state_flags |= CONN_CLOSING;
5544 	if (connp->conn_idl != NULL)
5545 		drain_cleanup_reqd = B_TRUE;
5546 	if (connp->conn_oper_pending_ill != NULL)
5547 		conn_ioctl_cleanup_reqd = B_TRUE;
5548 	if (connp->conn_ilg_inuse != 0)
5549 		ilg_cleanup_reqd = B_TRUE;
5550 	mutex_exit(&connp->conn_lock);
5551 
5552 	if (IPCL_IS_UDP(connp))
5553 		udp_quiesce_conn(connp);
5554 
5555 	if (conn_ioctl_cleanup_reqd)
5556 		conn_ioctl_cleanup(connp);
5557 
5558 	if (is_system_labeled() && connp->conn_anon_port) {
5559 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5560 		    connp->conn_mlp_type, connp->conn_ulp,
5561 		    ntohs(connp->conn_lport), B_FALSE);
5562 		connp->conn_anon_port = 0;
5563 	}
5564 	connp->conn_mlp_type = mlptSingle;
5565 
5566 	/*
5567 	 * Remove this conn from any fanout list it is on.
5568 	 * and then wait for any threads currently operating
5569 	 * on this endpoint to finish
5570 	 */
5571 	ipcl_hash_remove(connp);
5572 
5573 	/*
5574 	 * Remove this conn from the drain list, and do
5575 	 * any other cleanup that may be required.
5576 	 * (Only non-tcp streams may have a non-null conn_idl.
5577 	 * TCP streams are never flow controlled, and
5578 	 * conn_idl will be null)
5579 	 */
5580 	if (drain_cleanup_reqd)
5581 		conn_drain_tail(connp, B_TRUE);
5582 
5583 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5584 		(void) ip_mrouter_done(NULL);
5585 
5586 	if (ilg_cleanup_reqd)
5587 		ilg_delete_all(connp);
5588 
5589 	conn_delete_ire(connp, NULL);
5590 
5591 	/*
5592 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5593 	 * callers from write side can't be there now because close
5594 	 * is in progress. The only other caller is ipcl_walk
5595 	 * which checks for the condemned flag.
5596 	 */
5597 	mutex_enter(&connp->conn_lock);
5598 	connp->conn_state_flags |= CONN_CONDEMNED;
5599 	while (connp->conn_ref != 1)
5600 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5601 	connp->conn_state_flags |= CONN_QUIESCED;
5602 	mutex_exit(&connp->conn_lock);
5603 }
5604 
5605 /* ARGSUSED */
5606 int
5607 ip_close(queue_t *q, int flags)
5608 {
5609 	conn_t		*connp;
5610 
5611 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5612 
5613 	/*
5614 	 * Call the appropriate delete routine depending on whether this is
5615 	 * a module or device.
5616 	 */
5617 	if (WR(q)->q_next != NULL) {
5618 		/* This is a module close */
5619 		return (ip_modclose((ill_t *)q->q_ptr));
5620 	}
5621 
5622 	connp = q->q_ptr;
5623 	ip_quiesce_conn(connp);
5624 
5625 	qprocsoff(q);
5626 
5627 	/*
5628 	 * Now we are truly single threaded on this stream, and can
5629 	 * delete the things hanging off the connp, and finally the connp.
5630 	 * We removed this connp from the fanout list, it cannot be
5631 	 * accessed thru the fanouts, and we already waited for the
5632 	 * conn_ref to drop to 0. We are already in close, so
5633 	 * there cannot be any other thread from the top. qprocsoff
5634 	 * has completed, and service has completed or won't run in
5635 	 * future.
5636 	 */
5637 	ASSERT(connp->conn_ref == 1);
5638 
5639 	/*
5640 	 * A conn which was previously marked as IPCL_UDP cannot
5641 	 * retain the flag because it would have been cleared by
5642 	 * udp_close().
5643 	 */
5644 	ASSERT(!IPCL_IS_UDP(connp));
5645 
5646 	if (connp->conn_latch != NULL) {
5647 		IPLATCH_REFRELE(connp->conn_latch);
5648 		connp->conn_latch = NULL;
5649 	}
5650 	if (connp->conn_policy != NULL) {
5651 		IPPH_REFRELE(connp->conn_policy);
5652 		connp->conn_policy = NULL;
5653 	}
5654 	if (connp->conn_ipsec_opt_mp != NULL) {
5655 		freemsg(connp->conn_ipsec_opt_mp);
5656 		connp->conn_ipsec_opt_mp = NULL;
5657 	}
5658 
5659 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5660 
5661 	connp->conn_ref--;
5662 	ipcl_conn_destroy(connp);
5663 
5664 	q->q_ptr = WR(q)->q_ptr = NULL;
5665 	return (0);
5666 }
5667 
5668 int
5669 ip_snmpmod_close(queue_t *q)
5670 {
5671 	conn_t *connp = Q_TO_CONN(q);
5672 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5673 
5674 	qprocsoff(q);
5675 
5676 	if (connp->conn_flags & IPCL_UDPMOD)
5677 		udp_close_free(connp);
5678 
5679 	if (connp->conn_cred != NULL) {
5680 		crfree(connp->conn_cred);
5681 		connp->conn_cred = NULL;
5682 	}
5683 	CONN_DEC_REF(connp);
5684 	q->q_ptr = WR(q)->q_ptr = NULL;
5685 	return (0);
5686 }
5687 
5688 /*
5689  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5690  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5691  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5692  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5693  * queues as we never enqueue messages there and we don't handle any ioctls.
5694  * Everything else is freed.
5695  */
5696 void
5697 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5698 {
5699 	conn_t	*connp = q->q_ptr;
5700 	pfi_t	setfn;
5701 	pfi_t	getfn;
5702 
5703 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5704 
5705 	switch (DB_TYPE(mp)) {
5706 	case M_PROTO:
5707 	case M_PCPROTO:
5708 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5709 		    ((((union T_primitives *)mp->b_rptr)->type ==
5710 			T_SVR4_OPTMGMT_REQ) ||
5711 		    (((union T_primitives *)mp->b_rptr)->type ==
5712 			T_OPTMGMT_REQ))) {
5713 			/*
5714 			 * This is the only TPI primitive supported. Its
5715 			 * handling does not require tcp_t, but it does require
5716 			 * conn_t to check permissions.
5717 			 */
5718 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5719 
5720 			if (connp->conn_flags & IPCL_TCPMOD) {
5721 				setfn = tcp_snmp_set;
5722 				getfn = tcp_snmp_get;
5723 			} else {
5724 				setfn = udp_snmp_set;
5725 				getfn = udp_snmp_get;
5726 			}
5727 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5728 				freemsg(mp);
5729 				return;
5730 			}
5731 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5732 		    != NULL)
5733 			qreply(q, mp);
5734 		break;
5735 	case M_FLUSH:
5736 	case M_IOCTL:
5737 		putnext(q, mp);
5738 		break;
5739 	default:
5740 		freemsg(mp);
5741 		break;
5742 	}
5743 }
5744 
5745 /* Return the IP checksum for the IP header at "iph". */
5746 uint16_t
5747 ip_csum_hdr(ipha_t *ipha)
5748 {
5749 	uint16_t	*uph;
5750 	uint32_t	sum;
5751 	int		opt_len;
5752 
5753 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5754 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5755 	uph = (uint16_t *)ipha;
5756 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5757 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5758 	if (opt_len > 0) {
5759 		do {
5760 			sum += uph[10];
5761 			sum += uph[11];
5762 			uph += 2;
5763 		} while (--opt_len);
5764 	}
5765 	sum = (sum & 0xFFFF) + (sum >> 16);
5766 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5767 	if (sum == 0xffff)
5768 		sum = 0;
5769 	return ((uint16_t)sum);
5770 }
5771 
5772 void
5773 ip_ddi_destroy(void)
5774 {
5775 	ipv4_hook_destroy();
5776 	ipv6_hook_destroy();
5777 	ip_net_destroy();
5778 
5779 	tnet_fini();
5780 	tcp_ddi_destroy();
5781 	sctp_ddi_destroy();
5782 	ipsec_loader_destroy();
5783 	ipsec_policy_destroy();
5784 	ipsec_kstat_destroy();
5785 	nd_free(&ip_g_nd);
5786 	mutex_destroy(&igmp_timer_lock);
5787 	mutex_destroy(&mld_timer_lock);
5788 	mutex_destroy(&igmp_slowtimeout_lock);
5789 	mutex_destroy(&mld_slowtimeout_lock);
5790 	mutex_destroy(&ip_mi_lock);
5791 	mutex_destroy(&rts_clients.connf_lock);
5792 	ip_ire_fini();
5793 	ip6_asp_free();
5794 	conn_drain_fini();
5795 	ipcl_destroy();
5796 	inet_minor_destroy(ip_minor_arena);
5797 	icmp_kstat_fini();
5798 	ip_kstat_fini();
5799 	rw_destroy(&ipsec_capab_ills_lock);
5800 	rw_destroy(&ill_g_usesrc_lock);
5801 	ip_drop_unregister(&ip_dropper);
5802 }
5803 
5804 
5805 void
5806 ip_ddi_init(void)
5807 {
5808 	TCP6_MAJ = ddi_name_to_major(TCP6);
5809 	TCP_MAJ	= ddi_name_to_major(TCP);
5810 	SCTP_MAJ = ddi_name_to_major(SCTP);
5811 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5812 
5813 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5814 
5815 	/* IP's IPsec code calls the packet dropper */
5816 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5817 
5818 	if (!ip_g_nd) {
5819 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5820 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5821 			nd_free(&ip_g_nd);
5822 		}
5823 	}
5824 
5825 	ipsec_loader_init();
5826 	ipsec_policy_init();
5827 	ipsec_kstat_init();
5828 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5829 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5830 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5831 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5832 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5833 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5834 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5835 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5836 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5837 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5838 
5839 	/*
5840 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5841 	 * initial devices: ip, ip6, tcp, tcp6.
5842 	 */
5843 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5844 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5845 		cmn_err(CE_PANIC,
5846 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5847 	}
5848 
5849 	ipcl_init();
5850 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5851 	ip_ire_init();
5852 	ip6_asp_init();
5853 	ipif_init();
5854 	conn_drain_init();
5855 	tcp_ddi_init();
5856 	sctp_ddi_init();
5857 
5858 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5859 
5860 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5861 		"net", KSTAT_TYPE_NAMED,
5862 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5863 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5864 		ip_kstat->ks_data = &ip_statistics;
5865 		kstat_install(ip_kstat);
5866 	}
5867 	ip_kstat_init();
5868 	ip6_kstat_init();
5869 	icmp_kstat_init();
5870 	ipsec_loader_start();
5871 	tnet_init();
5872 
5873 	ip_net_init();
5874 	ipv4_hook_init();
5875 	ipv6_hook_init();
5876 }
5877 
5878 /*
5879  * Allocate and initialize a DLPI template of the specified length.  (May be
5880  * called as writer.)
5881  */
5882 mblk_t *
5883 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5884 {
5885 	mblk_t	*mp;
5886 
5887 	mp = allocb(len, BPRI_MED);
5888 	if (!mp)
5889 		return (NULL);
5890 
5891 	/*
5892 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5893 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5894 	 * that other DLPI are M_PROTO.
5895 	 */
5896 	if (prim == DL_INFO_REQ) {
5897 		mp->b_datap->db_type = M_PCPROTO;
5898 	} else {
5899 		mp->b_datap->db_type = M_PROTO;
5900 	}
5901 
5902 	mp->b_wptr = mp->b_rptr + len;
5903 	bzero(mp->b_rptr, len);
5904 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5905 	return (mp);
5906 }
5907 
5908 const char *
5909 dlpi_prim_str(int prim)
5910 {
5911 	switch (prim) {
5912 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5913 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5914 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5915 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5916 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5917 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5918 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5919 	case DL_OK_ACK:		return ("DL_OK_ACK");
5920 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5921 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5922 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5923 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5924 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5925 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5926 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5927 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5928 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5929 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5930 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5931 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5932 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5933 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5934 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5935 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5936 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5937 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5938 	default:		return ("<unknown primitive>");
5939 	}
5940 }
5941 
5942 const char *
5943 dlpi_err_str(int err)
5944 {
5945 	switch (err) {
5946 	case DL_ACCESS:		return ("DL_ACCESS");
5947 	case DL_BADADDR:	return ("DL_BADADDR");
5948 	case DL_BADCORR:	return ("DL_BADCORR");
5949 	case DL_BADDATA:	return ("DL_BADDATA");
5950 	case DL_BADPPA:		return ("DL_BADPPA");
5951 	case DL_BADPRIM:	return ("DL_BADPRIM");
5952 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5953 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5954 	case DL_BADSAP:		return ("DL_BADSAP");
5955 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5956 	case DL_BOUND:		return ("DL_BOUND");
5957 	case DL_INITFAILED:	return ("DL_INITFAILED");
5958 	case DL_NOADDR:		return ("DL_NOADDR");
5959 	case DL_NOTINIT:	return ("DL_NOTINIT");
5960 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5961 	case DL_SYSERR:		return ("DL_SYSERR");
5962 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5963 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5964 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5965 	case DL_TOOMANY:	return ("DL_TOOMANY");
5966 	case DL_NOTENAB:	return ("DL_NOTENAB");
5967 	case DL_BUSY:		return ("DL_BUSY");
5968 	case DL_NOAUTO:		return ("DL_NOAUTO");
5969 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5970 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5971 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5972 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5973 	case DL_PENDING:	return ("DL_PENDING");
5974 	default:		return ("<unknown error>");
5975 	}
5976 }
5977 
5978 /*
5979  * Debug formatting routine.  Returns a character string representation of the
5980  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5981  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5982  *
5983  * Once the ndd table-printing interfaces are removed, this can be changed to
5984  * standard dotted-decimal form.
5985  */
5986 char *
5987 ip_dot_addr(ipaddr_t addr, char *buf)
5988 {
5989 	uint8_t *ap = (uint8_t *)&addr;
5990 
5991 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5992 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5993 	return (buf);
5994 }
5995 
5996 /*
5997  * Write the given MAC address as a printable string in the usual colon-
5998  * separated format.
5999  */
6000 const char *
6001 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6002 {
6003 	char *bp;
6004 
6005 	if (alen == 0 || buflen < 4)
6006 		return ("?");
6007 	bp = buf;
6008 	for (;;) {
6009 		/*
6010 		 * If there are more MAC address bytes available, but we won't
6011 		 * have any room to print them, then add "..." to the string
6012 		 * instead.  See below for the 'magic number' explanation.
6013 		 */
6014 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6015 			(void) strcpy(bp, "...");
6016 			break;
6017 		}
6018 		(void) sprintf(bp, "%02x", *addr++);
6019 		bp += 2;
6020 		if (--alen == 0)
6021 			break;
6022 		*bp++ = ':';
6023 		buflen -= 3;
6024 		/*
6025 		 * At this point, based on the first 'if' statement above,
6026 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6027 		 * buflen >= 4.  The first case leaves room for the final "xx"
6028 		 * number and trailing NUL byte.  The second leaves room for at
6029 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6030 		 * that statement.
6031 		 */
6032 	}
6033 	return (buf);
6034 }
6035 
6036 /*
6037  * Send an ICMP error after patching up the packet appropriately.  Returns
6038  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6039  */
6040 static boolean_t
6041 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6042     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6043 {
6044 	ipha_t *ipha;
6045 	mblk_t *first_mp;
6046 	boolean_t secure;
6047 	unsigned char db_type;
6048 
6049 	first_mp = mp;
6050 	if (mctl_present) {
6051 		mp = mp->b_cont;
6052 		secure = ipsec_in_is_secure(first_mp);
6053 		ASSERT(mp != NULL);
6054 	} else {
6055 		/*
6056 		 * If this is an ICMP error being reported - which goes
6057 		 * up as M_CTLs, we need to convert them to M_DATA till
6058 		 * we finish checking with global policy because
6059 		 * ipsec_check_global_policy() assumes M_DATA as clear
6060 		 * and M_CTL as secure.
6061 		 */
6062 		db_type = DB_TYPE(mp);
6063 		DB_TYPE(mp) = M_DATA;
6064 		secure = B_FALSE;
6065 	}
6066 	/*
6067 	 * We are generating an icmp error for some inbound packet.
6068 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6069 	 * Before we generate an error, check with global policy
6070 	 * to see whether this is allowed to enter the system. As
6071 	 * there is no "conn", we are checking with global policy.
6072 	 */
6073 	ipha = (ipha_t *)mp->b_rptr;
6074 	if (secure || ipsec_inbound_v4_policy_present) {
6075 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6076 		    ipha, NULL, mctl_present);
6077 		if (first_mp == NULL)
6078 			return (B_FALSE);
6079 	}
6080 
6081 	if (!mctl_present)
6082 		DB_TYPE(mp) = db_type;
6083 
6084 	if (flags & IP_FF_SEND_ICMP) {
6085 		if (flags & IP_FF_HDR_COMPLETE) {
6086 			if (ip_hdr_complete(ipha, zoneid)) {
6087 				freemsg(first_mp);
6088 				return (B_TRUE);
6089 			}
6090 		}
6091 		if (flags & IP_FF_CKSUM) {
6092 			/*
6093 			 * Have to correct checksum since
6094 			 * the packet might have been
6095 			 * fragmented and the reassembly code in ip_rput
6096 			 * does not restore the IP checksum.
6097 			 */
6098 			ipha->ipha_hdr_checksum = 0;
6099 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6100 		}
6101 		switch (icmp_type) {
6102 		case ICMP_DEST_UNREACHABLE:
6103 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6104 			break;
6105 		default:
6106 			freemsg(first_mp);
6107 			break;
6108 		}
6109 	} else {
6110 		freemsg(first_mp);
6111 		return (B_FALSE);
6112 	}
6113 
6114 	return (B_TRUE);
6115 }
6116 
6117 /*
6118  * Used to send an ICMP error message when a packet is received for
6119  * a protocol that is not supported. The mblk passed as argument
6120  * is consumed by this function.
6121  */
6122 void
6123 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6124 {
6125 	mblk_t *mp;
6126 	ipha_t *ipha;
6127 	ill_t *ill;
6128 	ipsec_in_t *ii;
6129 
6130 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6131 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6132 
6133 	mp = ipsec_mp->b_cont;
6134 	ipsec_mp->b_cont = NULL;
6135 	ipha = (ipha_t *)mp->b_rptr;
6136 	/* Get ill from index in ipsec_in_t. */
6137 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6138 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL);
6139 	if (ill != NULL) {
6140 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6141 			if (ip_fanout_send_icmp(q, mp, flags,
6142 			    ICMP_DEST_UNREACHABLE,
6143 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6144 				BUMP_MIB(ill->ill_ip_mib,
6145 				    ipIfStatsInUnknownProtos);
6146 			}
6147 		} else {
6148 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6149 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6150 			    0, B_FALSE, zoneid)) {
6151 				BUMP_MIB(ill->ill_ip_mib,
6152 				    ipIfStatsInUnknownProtos);
6153 			}
6154 		}
6155 		ill_refrele(ill);
6156 	} else { /* re-link for the freemsg() below. */
6157 		ipsec_mp->b_cont = mp;
6158 	}
6159 
6160 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6161 	freemsg(ipsec_mp);
6162 }
6163 
6164 /*
6165  * See if the inbound datagram has had IPsec processing applied to it.
6166  */
6167 boolean_t
6168 ipsec_in_is_secure(mblk_t *ipsec_mp)
6169 {
6170 	ipsec_in_t *ii;
6171 
6172 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6173 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6174 
6175 	if (ii->ipsec_in_loopback) {
6176 		return (ii->ipsec_in_secure);
6177 	} else {
6178 		return (ii->ipsec_in_ah_sa != NULL ||
6179 		    ii->ipsec_in_esp_sa != NULL ||
6180 		    ii->ipsec_in_decaps);
6181 	}
6182 }
6183 
6184 /*
6185  * Handle protocols with which IP is less intimate.  There
6186  * can be more than one stream bound to a particular
6187  * protocol.  When this is the case, normally each one gets a copy
6188  * of any incoming packets.
6189  *
6190  * IPSEC NOTE :
6191  *
6192  * Don't allow a secure packet going up a non-secure connection.
6193  * We don't allow this because
6194  *
6195  * 1) Reply might go out in clear which will be dropped at
6196  *    the sending side.
6197  * 2) If the reply goes out in clear it will give the
6198  *    adversary enough information for getting the key in
6199  *    most of the cases.
6200  *
6201  * Moreover getting a secure packet when we expect clear
6202  * implies that SA's were added without checking for
6203  * policy on both ends. This should not happen once ISAKMP
6204  * is used to negotiate SAs as SAs will be added only after
6205  * verifying the policy.
6206  *
6207  * NOTE : If the packet was tunneled and not multicast we only send
6208  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6209  * back to delivering packets to AF_INET6 raw sockets.
6210  *
6211  * IPQoS Notes:
6212  * Once we have determined the client, invoke IPPF processing.
6213  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6214  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6215  * ip_policy will be false.
6216  *
6217  * Zones notes:
6218  * Currently only applications in the global zone can create raw sockets for
6219  * protocols other than ICMP. So unlike the broadcast / multicast case of
6220  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6221  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6222  */
6223 static void
6224 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6225     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6226     zoneid_t zoneid)
6227 {
6228 	queue_t	*rq;
6229 	mblk_t	*mp1, *first_mp1;
6230 	uint_t	protocol = ipha->ipha_protocol;
6231 	ipaddr_t dst;
6232 	boolean_t one_only;
6233 	mblk_t *first_mp = mp;
6234 	boolean_t secure;
6235 	uint32_t ill_index;
6236 	conn_t	*connp, *first_connp, *next_connp;
6237 	connf_t	*connfp;
6238 	boolean_t shared_addr;
6239 	mib2_ipIfStatsEntry_t *mibptr;
6240 
6241 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
6242 	if (mctl_present) {
6243 		mp = first_mp->b_cont;
6244 		secure = ipsec_in_is_secure(first_mp);
6245 		ASSERT(mp != NULL);
6246 	} else {
6247 		secure = B_FALSE;
6248 	}
6249 	dst = ipha->ipha_dst;
6250 	/*
6251 	 * If the packet was tunneled and not multicast we only send to it
6252 	 * the first match.
6253 	 */
6254 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6255 	    !CLASSD(dst));
6256 
6257 	shared_addr = (zoneid == ALL_ZONES);
6258 	if (shared_addr) {
6259 		/*
6260 		 * We don't allow multilevel ports for raw IP, so no need to
6261 		 * check for that here.
6262 		 */
6263 		zoneid = tsol_packet_to_zoneid(mp);
6264 	}
6265 
6266 	connfp = &ipcl_proto_fanout[protocol];
6267 	mutex_enter(&connfp->connf_lock);
6268 	connp = connfp->connf_head;
6269 	for (connp = connfp->connf_head; connp != NULL;
6270 		connp = connp->conn_next) {
6271 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6272 		    zoneid) &&
6273 		    (!is_system_labeled() ||
6274 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6275 		    connp)))
6276 			break;
6277 	}
6278 
6279 	if (connp == NULL || connp->conn_upq == NULL) {
6280 		/*
6281 		 * No one bound to these addresses.  Is
6282 		 * there a client that wants all
6283 		 * unclaimed datagrams?
6284 		 */
6285 		mutex_exit(&connfp->connf_lock);
6286 		/*
6287 		 * Check for IPPROTO_ENCAP...
6288 		 */
6289 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6290 			/*
6291 			 * If an IPsec mblk is here on a multicast
6292 			 * tunnel (using ip_mroute stuff), check policy here,
6293 			 * THEN ship off to ip_mroute_decap().
6294 			 *
6295 			 * BTW,  If I match a configured IP-in-IP
6296 			 * tunnel, this path will not be reached, and
6297 			 * ip_mroute_decap will never be called.
6298 			 */
6299 			first_mp = ipsec_check_global_policy(first_mp, connp,
6300 			    ipha, NULL, mctl_present);
6301 			if (first_mp != NULL) {
6302 				if (mctl_present)
6303 					freeb(first_mp);
6304 				ip_mroute_decap(q, mp);
6305 			} /* Else we already freed everything! */
6306 		} else {
6307 			/*
6308 			 * Otherwise send an ICMP protocol unreachable.
6309 			 */
6310 			if (ip_fanout_send_icmp(q, first_mp, flags,
6311 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6312 			    mctl_present, zoneid)) {
6313 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6314 			}
6315 		}
6316 		return;
6317 	}
6318 	CONN_INC_REF(connp);
6319 	first_connp = connp;
6320 
6321 	/*
6322 	 * Only send message to one tunnel driver by immediately
6323 	 * terminating the loop.
6324 	 */
6325 	connp = one_only ? NULL : connp->conn_next;
6326 
6327 	for (;;) {
6328 		while (connp != NULL) {
6329 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6330 			    flags, zoneid) &&
6331 			    (!is_system_labeled() ||
6332 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6333 			    shared_addr, connp)))
6334 				break;
6335 			connp = connp->conn_next;
6336 		}
6337 
6338 		/*
6339 		 * Copy the packet.
6340 		 */
6341 		if (connp == NULL || connp->conn_upq == NULL ||
6342 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6343 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6344 			/*
6345 			 * No more interested clients or memory
6346 			 * allocation failed
6347 			 */
6348 			connp = first_connp;
6349 			break;
6350 		}
6351 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6352 		CONN_INC_REF(connp);
6353 		mutex_exit(&connfp->connf_lock);
6354 		rq = connp->conn_rq;
6355 		if (!canputnext(rq)) {
6356 			if (flags & IP_FF_RAWIP) {
6357 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6358 			} else {
6359 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6360 			}
6361 
6362 			freemsg(first_mp1);
6363 		} else {
6364 			/*
6365 			 * Don't enforce here if we're an actual tunnel -
6366 			 * let "tun" do it instead.
6367 			 */
6368 			if (!IPCL_IS_IPTUN(connp) &&
6369 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6370 				first_mp1 = ipsec_check_inbound_policy
6371 				    (first_mp1, connp, ipha, NULL,
6372 				    mctl_present);
6373 			}
6374 			if (first_mp1 != NULL) {
6375 				/*
6376 				 * ip_fanout_proto also gets called from
6377 				 * icmp_inbound_error_fanout, in which case
6378 				 * the msg type is M_CTL.  Don't add info
6379 				 * in this case for the time being. In future
6380 				 * when there is a need for knowing the
6381 				 * inbound iface index for ICMP error msgs,
6382 				 * then this can be changed.
6383 				 */
6384 				if ((connp->conn_recvif != 0) &&
6385 				    (mp->b_datap->db_type != M_CTL)) {
6386 					/*
6387 					 * the actual data will be
6388 					 * contained in b_cont upon
6389 					 * successful return of the
6390 					 * following call else
6391 					 * original mblk is returned
6392 					 */
6393 					ASSERT(recv_ill != NULL);
6394 					mp1 = ip_add_info(mp1, recv_ill,
6395 						IPF_RECVIF);
6396 				}
6397 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6398 				if (mctl_present)
6399 					freeb(first_mp1);
6400 				putnext(rq, mp1);
6401 			}
6402 		}
6403 		mutex_enter(&connfp->connf_lock);
6404 		/* Follow the next pointer before releasing the conn. */
6405 		next_connp = connp->conn_next;
6406 		CONN_DEC_REF(connp);
6407 		connp = next_connp;
6408 	}
6409 
6410 	/* Last one.  Send it upstream. */
6411 	mutex_exit(&connfp->connf_lock);
6412 
6413 	/*
6414 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6415 	 * will be set to false.
6416 	 */
6417 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6418 		ill_index = ill->ill_phyint->phyint_ifindex;
6419 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6420 		if (mp == NULL) {
6421 			CONN_DEC_REF(connp);
6422 			if (mctl_present) {
6423 				freeb(first_mp);
6424 			}
6425 			return;
6426 		}
6427 	}
6428 
6429 	rq = connp->conn_rq;
6430 	if (!canputnext(rq)) {
6431 		if (flags & IP_FF_RAWIP) {
6432 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6433 		} else {
6434 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6435 		}
6436 
6437 		freemsg(first_mp);
6438 	} else {
6439 		if (IPCL_IS_IPTUN(connp)) {
6440 			/*
6441 			 * Tunneled packet.  We enforce policy in the tunnel
6442 			 * module itself.
6443 			 *
6444 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6445 			 * a policy check.
6446 			 */
6447 			putnext(rq, first_mp);
6448 			CONN_DEC_REF(connp);
6449 			return;
6450 		}
6451 
6452 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6453 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6454 			    ipha, NULL, mctl_present);
6455 		}
6456 
6457 		if (first_mp != NULL) {
6458 			/*
6459 			 * ip_fanout_proto also gets called
6460 			 * from icmp_inbound_error_fanout, in
6461 			 * which case the msg type is M_CTL.
6462 			 * Don't add info in this case for time
6463 			 * being. In future when there is a
6464 			 * need for knowing the inbound iface
6465 			 * index for ICMP error msgs, then this
6466 			 * can be changed
6467 			 */
6468 			if ((connp->conn_recvif != 0) &&
6469 			    (mp->b_datap->db_type != M_CTL)) {
6470 				/*
6471 				 * the actual data will be contained in
6472 				 * b_cont upon successful return
6473 				 * of the following call else original
6474 				 * mblk is returned
6475 				 */
6476 				ASSERT(recv_ill != NULL);
6477 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6478 			}
6479 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6480 			putnext(rq, mp);
6481 			if (mctl_present)
6482 				freeb(first_mp);
6483 		}
6484 	}
6485 	CONN_DEC_REF(connp);
6486 }
6487 
6488 /*
6489  * Fanout for TCP packets
6490  * The caller puts <fport, lport> in the ports parameter.
6491  *
6492  * IPQoS Notes
6493  * Before sending it to the client, invoke IPPF processing.
6494  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6495  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6496  * ip_policy is false.
6497  */
6498 static void
6499 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6500     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6501 {
6502 	mblk_t  *first_mp;
6503 	boolean_t secure;
6504 	uint32_t ill_index;
6505 	int	ip_hdr_len;
6506 	tcph_t	*tcph;
6507 	boolean_t syn_present = B_FALSE;
6508 	conn_t	*connp;
6509 
6510 	ASSERT(recv_ill != NULL);
6511 
6512 	first_mp = mp;
6513 	if (mctl_present) {
6514 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6515 		mp = first_mp->b_cont;
6516 		secure = ipsec_in_is_secure(first_mp);
6517 		ASSERT(mp != NULL);
6518 	} else {
6519 		secure = B_FALSE;
6520 	}
6521 
6522 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6523 
6524 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6525 	    NULL) {
6526 		/*
6527 		 * No connected connection or listener. Send a
6528 		 * TH_RST via tcp_xmit_listeners_reset.
6529 		 */
6530 
6531 		/* Initiate IPPf processing, if needed. */
6532 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6533 			uint32_t ill_index;
6534 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6535 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6536 			if (first_mp == NULL)
6537 				return;
6538 		}
6539 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6540 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6541 		    zoneid));
6542 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6543 		return;
6544 	}
6545 
6546 	/*
6547 	 * Allocate the SYN for the TCP connection here itself
6548 	 */
6549 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6550 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6551 		if (IPCL_IS_TCP(connp)) {
6552 			squeue_t *sqp;
6553 
6554 			/*
6555 			 * For fused tcp loopback, assign the eager's
6556 			 * squeue to be that of the active connect's.
6557 			 * Note that we don't check for IP_FF_LOOPBACK
6558 			 * here since this routine gets called only
6559 			 * for loopback (unlike the IPv6 counterpart).
6560 			 */
6561 			ASSERT(Q_TO_CONN(q) != NULL);
6562 			if (do_tcp_fusion &&
6563 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6564 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6565 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6566 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6567 				sqp = Q_TO_CONN(q)->conn_sqp;
6568 			} else {
6569 				sqp = IP_SQUEUE_GET(lbolt);
6570 			}
6571 
6572 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6573 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6574 			syn_present = B_TRUE;
6575 		}
6576 	}
6577 
6578 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6579 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6580 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6581 		if ((flags & TH_RST) || (flags & TH_URG)) {
6582 			CONN_DEC_REF(connp);
6583 			freemsg(first_mp);
6584 			return;
6585 		}
6586 		if (flags & TH_ACK) {
6587 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6588 			CONN_DEC_REF(connp);
6589 			return;
6590 		}
6591 
6592 		CONN_DEC_REF(connp);
6593 		freemsg(first_mp);
6594 		return;
6595 	}
6596 
6597 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6598 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6599 		    NULL, mctl_present);
6600 		if (first_mp == NULL) {
6601 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6602 			CONN_DEC_REF(connp);
6603 			return;
6604 		}
6605 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6606 			ASSERT(syn_present);
6607 			if (mctl_present) {
6608 				ASSERT(first_mp != mp);
6609 				first_mp->b_datap->db_struioflag |=
6610 				    STRUIO_POLICY;
6611 			} else {
6612 				ASSERT(first_mp == mp);
6613 				mp->b_datap->db_struioflag &=
6614 				    ~STRUIO_EAGER;
6615 				mp->b_datap->db_struioflag |=
6616 				    STRUIO_POLICY;
6617 			}
6618 		} else {
6619 			/*
6620 			 * Discard first_mp early since we're dealing with a
6621 			 * fully-connected conn_t and tcp doesn't do policy in
6622 			 * this case.
6623 			 */
6624 			if (mctl_present) {
6625 				freeb(first_mp);
6626 				mctl_present = B_FALSE;
6627 			}
6628 			first_mp = mp;
6629 		}
6630 	}
6631 
6632 	/*
6633 	 * Initiate policy processing here if needed. If we get here from
6634 	 * icmp_inbound_error_fanout, ip_policy is false.
6635 	 */
6636 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6637 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6638 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6639 		if (mp == NULL) {
6640 			CONN_DEC_REF(connp);
6641 			if (mctl_present)
6642 				freeb(first_mp);
6643 			return;
6644 		} else if (mctl_present) {
6645 			ASSERT(first_mp != mp);
6646 			first_mp->b_cont = mp;
6647 		} else {
6648 			first_mp = mp;
6649 		}
6650 	}
6651 
6652 
6653 
6654 	/* Handle IPv6 socket options. */
6655 	if (!syn_present &&
6656 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6657 		/* Add header */
6658 		ASSERT(recv_ill != NULL);
6659 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6660 		if (mp == NULL) {
6661 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6662 			CONN_DEC_REF(connp);
6663 			if (mctl_present)
6664 				freeb(first_mp);
6665 			return;
6666 		} else if (mctl_present) {
6667 			/*
6668 			 * ip_add_info might return a new mp.
6669 			 */
6670 			ASSERT(first_mp != mp);
6671 			first_mp->b_cont = mp;
6672 		} else {
6673 			first_mp = mp;
6674 		}
6675 	}
6676 
6677 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6678 	if (IPCL_IS_TCP(connp)) {
6679 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6680 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6681 	} else {
6682 		putnext(connp->conn_rq, first_mp);
6683 		CONN_DEC_REF(connp);
6684 	}
6685 }
6686 
6687 /*
6688  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6689  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6690  * Caller is responsible for dropping references to the conn, and freeing
6691  * first_mp.
6692  *
6693  * IPQoS Notes
6694  * Before sending it to the client, invoke IPPF processing. Policy processing
6695  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6696  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6697  * ip_wput_local, ip_policy is false.
6698  */
6699 static void
6700 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6701     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6702     boolean_t ip_policy)
6703 {
6704 	boolean_t	mctl_present = (first_mp != NULL);
6705 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6706 	uint32_t	ill_index;
6707 
6708 	ASSERT(ill != NULL);
6709 
6710 	if (mctl_present)
6711 		first_mp->b_cont = mp;
6712 	else
6713 		first_mp = mp;
6714 
6715 	if (CONN_UDP_FLOWCTLD(connp)) {
6716 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6717 		freemsg(first_mp);
6718 		return;
6719 	}
6720 
6721 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6722 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6723 		    NULL, mctl_present);
6724 		if (first_mp == NULL) {
6725 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6726 			return;	/* Freed by ipsec_check_inbound_policy(). */
6727 		}
6728 	}
6729 	if (mctl_present)
6730 		freeb(first_mp);
6731 
6732 	if (connp->conn_recvif)
6733 		in_flags = IPF_RECVIF;
6734 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6735 		in_flags |= IPF_RECVSLLA;
6736 
6737 	/* Handle IPv6 options. */
6738 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6739 		in_flags |= IPF_RECVIF;
6740 
6741 	/*
6742 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6743 	 * freed if the packet is dropped. The caller will do so.
6744 	 */
6745 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6746 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6747 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6748 		if (mp == NULL) {
6749 			return;
6750 		}
6751 	}
6752 	if ((in_flags != 0) &&
6753 	    (mp->b_datap->db_type != M_CTL)) {
6754 		/*
6755 		 * The actual data will be contained in b_cont
6756 		 * upon successful return of the following call
6757 		 * else original mblk is returned
6758 		 */
6759 		ASSERT(recv_ill != NULL);
6760 		mp = ip_add_info(mp, recv_ill, in_flags);
6761 	}
6762 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
6763 	/* Send it upstream */
6764 	CONN_UDP_RECV(connp, mp);
6765 }
6766 
6767 /*
6768  * Fanout for UDP packets.
6769  * The caller puts <fport, lport> in the ports parameter.
6770  *
6771  * If SO_REUSEADDR is set all multicast and broadcast packets
6772  * will be delivered to all streams bound to the same port.
6773  *
6774  * Zones notes:
6775  * Multicast and broadcast packets will be distributed to streams in all zones.
6776  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6777  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6778  * packets. To maintain this behavior with multiple zones, the conns are grouped
6779  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6780  * each zone. If unset, all the following conns in the same zone are skipped.
6781  */
6782 static void
6783 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6784     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6785     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6786 {
6787 	uint32_t	dstport, srcport;
6788 	ipaddr_t	dst;
6789 	mblk_t		*first_mp;
6790 	boolean_t	secure;
6791 	in6_addr_t	v6src;
6792 	conn_t		*connp;
6793 	connf_t		*connfp;
6794 	conn_t		*first_connp;
6795 	conn_t		*next_connp;
6796 	mblk_t		*mp1, *first_mp1;
6797 	ipaddr_t	src;
6798 	zoneid_t	last_zoneid;
6799 	boolean_t	reuseaddr;
6800 	boolean_t	shared_addr;
6801 
6802 	first_mp = mp;
6803 	if (mctl_present) {
6804 		mp = first_mp->b_cont;
6805 		first_mp->b_cont = NULL;
6806 		secure = ipsec_in_is_secure(first_mp);
6807 		ASSERT(mp != NULL);
6808 	} else {
6809 		first_mp = NULL;
6810 		secure = B_FALSE;
6811 	}
6812 
6813 	/* Extract ports in net byte order */
6814 	dstport = htons(ntohl(ports) & 0xFFFF);
6815 	srcport = htons(ntohl(ports) >> 16);
6816 	dst = ipha->ipha_dst;
6817 	src = ipha->ipha_src;
6818 
6819 	shared_addr = (zoneid == ALL_ZONES);
6820 	if (shared_addr) {
6821 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6822 		if (zoneid == ALL_ZONES)
6823 			zoneid = tsol_packet_to_zoneid(mp);
6824 	}
6825 
6826 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6827 	mutex_enter(&connfp->connf_lock);
6828 	connp = connfp->connf_head;
6829 	if (!broadcast && !CLASSD(dst)) {
6830 		/*
6831 		 * Not broadcast or multicast. Send to the one (first)
6832 		 * client we find. No need to check conn_wantpacket()
6833 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6834 		 * IPv4 unicast packets.
6835 		 */
6836 		while ((connp != NULL) &&
6837 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6838 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6839 			connp = connp->conn_next;
6840 		}
6841 
6842 		if (connp == NULL || connp->conn_upq == NULL)
6843 			goto notfound;
6844 
6845 		if (is_system_labeled() &&
6846 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6847 		    connp))
6848 			goto notfound;
6849 
6850 		CONN_INC_REF(connp);
6851 		mutex_exit(&connfp->connf_lock);
6852 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
6853 		    flags, recv_ill, ip_policy);
6854 		IP_STAT(ip_udp_fannorm);
6855 		CONN_DEC_REF(connp);
6856 		return;
6857 	}
6858 
6859 	/*
6860 	 * Broadcast and multicast case
6861 	 *
6862 	 * Need to check conn_wantpacket().
6863 	 * If SO_REUSEADDR has been set on the first we send the
6864 	 * packet to all clients that have joined the group and
6865 	 * match the port.
6866 	 */
6867 
6868 	while (connp != NULL) {
6869 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6870 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6871 		    (!is_system_labeled() ||
6872 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6873 		    connp)))
6874 			break;
6875 		connp = connp->conn_next;
6876 	}
6877 
6878 	if (connp == NULL || connp->conn_upq == NULL)
6879 		goto notfound;
6880 
6881 	first_connp = connp;
6882 	/*
6883 	 * When SO_REUSEADDR is not set, send the packet only to the first
6884 	 * matching connection in its zone by keeping track of the zoneid.
6885 	 */
6886 	reuseaddr = first_connp->conn_reuseaddr;
6887 	last_zoneid = first_connp->conn_zoneid;
6888 
6889 	CONN_INC_REF(connp);
6890 	connp = connp->conn_next;
6891 	for (;;) {
6892 		while (connp != NULL) {
6893 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6894 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6895 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6896 			    (!is_system_labeled() ||
6897 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6898 			    shared_addr, connp)))
6899 				break;
6900 			connp = connp->conn_next;
6901 		}
6902 		/*
6903 		 * Just copy the data part alone. The mctl part is
6904 		 * needed just for verifying policy and it is never
6905 		 * sent up.
6906 		 */
6907 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6908 		    ((mp1 = copymsg(mp)) == NULL))) {
6909 			/*
6910 			 * No more interested clients or memory
6911 			 * allocation failed
6912 			 */
6913 			connp = first_connp;
6914 			break;
6915 		}
6916 		if (connp->conn_zoneid != last_zoneid) {
6917 			/*
6918 			 * Update the zoneid so that the packet isn't sent to
6919 			 * any more conns in the same zone unless SO_REUSEADDR
6920 			 * is set.
6921 			 */
6922 			reuseaddr = connp->conn_reuseaddr;
6923 			last_zoneid = connp->conn_zoneid;
6924 		}
6925 		if (first_mp != NULL) {
6926 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6927 			    ipsec_info_type == IPSEC_IN);
6928 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6929 			if (first_mp1 == NULL) {
6930 				freemsg(mp1);
6931 				connp = first_connp;
6932 				break;
6933 			}
6934 		} else {
6935 			first_mp1 = NULL;
6936 		}
6937 		CONN_INC_REF(connp);
6938 		mutex_exit(&connfp->connf_lock);
6939 		/*
6940 		 * IPQoS notes: We don't send the packet for policy
6941 		 * processing here, will do it for the last one (below).
6942 		 * i.e. we do it per-packet now, but if we do policy
6943 		 * processing per-conn, then we would need to do it
6944 		 * here too.
6945 		 */
6946 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
6947 		    ipha, flags, recv_ill, B_FALSE);
6948 		mutex_enter(&connfp->connf_lock);
6949 		/* Follow the next pointer before releasing the conn. */
6950 		next_connp = connp->conn_next;
6951 		IP_STAT(ip_udp_fanmb);
6952 		CONN_DEC_REF(connp);
6953 		connp = next_connp;
6954 	}
6955 
6956 	/* Last one.  Send it upstream. */
6957 	mutex_exit(&connfp->connf_lock);
6958 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
6959 	    recv_ill, ip_policy);
6960 	IP_STAT(ip_udp_fanmb);
6961 	CONN_DEC_REF(connp);
6962 	return;
6963 
6964 notfound:
6965 
6966 	mutex_exit(&connfp->connf_lock);
6967 	IP_STAT(ip_udp_fanothers);
6968 	/*
6969 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6970 	 * have already been matched above, since they live in the IPv4
6971 	 * fanout tables. This implies we only need to
6972 	 * check for IPv6 in6addr_any endpoints here.
6973 	 * Thus we compare using ipv6_all_zeros instead of the destination
6974 	 * address, except for the multicast group membership lookup which
6975 	 * uses the IPv4 destination.
6976 	 */
6977 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6978 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6979 	mutex_enter(&connfp->connf_lock);
6980 	connp = connfp->connf_head;
6981 	if (!broadcast && !CLASSD(dst)) {
6982 		while (connp != NULL) {
6983 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6984 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6985 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6986 			    !connp->conn_ipv6_v6only)
6987 				break;
6988 			connp = connp->conn_next;
6989 		}
6990 
6991 		if (connp != NULL && is_system_labeled() &&
6992 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6993 		    connp))
6994 			connp = NULL;
6995 
6996 		if (connp == NULL || connp->conn_upq == NULL) {
6997 			/*
6998 			 * No one bound to this port.  Is
6999 			 * there a client that wants all
7000 			 * unclaimed datagrams?
7001 			 */
7002 			mutex_exit(&connfp->connf_lock);
7003 
7004 			if (mctl_present)
7005 				first_mp->b_cont = mp;
7006 			else
7007 				first_mp = mp;
7008 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7009 				ip_fanout_proto(q, first_mp, ill, ipha,
7010 				    flags | IP_FF_RAWIP, mctl_present,
7011 				    ip_policy, recv_ill, zoneid);
7012 			} else {
7013 				if (ip_fanout_send_icmp(q, first_mp, flags,
7014 				    ICMP_DEST_UNREACHABLE,
7015 				    ICMP_PORT_UNREACHABLE,
7016 				    mctl_present, zoneid)) {
7017 					BUMP_MIB(ill->ill_ip_mib,
7018 					    udpIfStatsNoPorts);
7019 				}
7020 			}
7021 			return;
7022 		}
7023 
7024 		CONN_INC_REF(connp);
7025 		mutex_exit(&connfp->connf_lock);
7026 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7027 		    flags, recv_ill, ip_policy);
7028 		CONN_DEC_REF(connp);
7029 		return;
7030 	}
7031 	/*
7032 	 * IPv4 multicast packet being delivered to an AF_INET6
7033 	 * in6addr_any endpoint.
7034 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7035 	 * and not conn_wantpacket_v6() since any multicast membership is
7036 	 * for an IPv4-mapped multicast address.
7037 	 * The packet is sent to all clients in all zones that have joined the
7038 	 * group and match the port.
7039 	 */
7040 	while (connp != NULL) {
7041 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7042 		    srcport, v6src) &&
7043 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7044 		    (!is_system_labeled() ||
7045 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7046 		    connp)))
7047 			break;
7048 		connp = connp->conn_next;
7049 	}
7050 
7051 	if (connp == NULL || connp->conn_upq == NULL) {
7052 		/*
7053 		 * No one bound to this port.  Is
7054 		 * there a client that wants all
7055 		 * unclaimed datagrams?
7056 		 */
7057 		mutex_exit(&connfp->connf_lock);
7058 
7059 		if (mctl_present)
7060 			first_mp->b_cont = mp;
7061 		else
7062 			first_mp = mp;
7063 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7064 			ip_fanout_proto(q, first_mp, ill, ipha,
7065 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7066 			    recv_ill, zoneid);
7067 		} else {
7068 			/*
7069 			 * We used to attempt to send an icmp error here, but
7070 			 * since this is known to be a multicast packet
7071 			 * and we don't send icmp errors in response to
7072 			 * multicast, just drop the packet and give up sooner.
7073 			 */
7074 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7075 			freemsg(first_mp);
7076 		}
7077 		return;
7078 	}
7079 
7080 	first_connp = connp;
7081 
7082 	CONN_INC_REF(connp);
7083 	connp = connp->conn_next;
7084 	for (;;) {
7085 		while (connp != NULL) {
7086 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7087 			    ipv6_all_zeros, srcport, v6src) &&
7088 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7089 			    (!is_system_labeled() ||
7090 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7091 			    shared_addr, connp)))
7092 				break;
7093 			connp = connp->conn_next;
7094 		}
7095 		/*
7096 		 * Just copy the data part alone. The mctl part is
7097 		 * needed just for verifying policy and it is never
7098 		 * sent up.
7099 		 */
7100 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7101 		    ((mp1 = copymsg(mp)) == NULL))) {
7102 			/*
7103 			 * No more intested clients or memory
7104 			 * allocation failed
7105 			 */
7106 			connp = first_connp;
7107 			break;
7108 		}
7109 		if (first_mp != NULL) {
7110 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7111 			    ipsec_info_type == IPSEC_IN);
7112 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7113 			if (first_mp1 == NULL) {
7114 				freemsg(mp1);
7115 				connp = first_connp;
7116 				break;
7117 			}
7118 		} else {
7119 			first_mp1 = NULL;
7120 		}
7121 		CONN_INC_REF(connp);
7122 		mutex_exit(&connfp->connf_lock);
7123 		/*
7124 		 * IPQoS notes: We don't send the packet for policy
7125 		 * processing here, will do it for the last one (below).
7126 		 * i.e. we do it per-packet now, but if we do policy
7127 		 * processing per-conn, then we would need to do it
7128 		 * here too.
7129 		 */
7130 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7131 		    ipha, flags, recv_ill, B_FALSE);
7132 		mutex_enter(&connfp->connf_lock);
7133 		/* Follow the next pointer before releasing the conn. */
7134 		next_connp = connp->conn_next;
7135 		CONN_DEC_REF(connp);
7136 		connp = next_connp;
7137 	}
7138 
7139 	/* Last one.  Send it upstream. */
7140 	mutex_exit(&connfp->connf_lock);
7141 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7142 	    recv_ill, ip_policy);
7143 	CONN_DEC_REF(connp);
7144 }
7145 
7146 /*
7147  * Complete the ip_wput header so that it
7148  * is possible to generate ICMP
7149  * errors.
7150  */
7151 int
7152 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7153 {
7154 	ire_t *ire;
7155 
7156 	if (ipha->ipha_src == INADDR_ANY) {
7157 		ire = ire_lookup_local(zoneid);
7158 		if (ire == NULL) {
7159 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7160 			return (1);
7161 		}
7162 		ipha->ipha_src = ire->ire_addr;
7163 		ire_refrele(ire);
7164 	}
7165 	ipha->ipha_ttl = ip_def_ttl;
7166 	ipha->ipha_hdr_checksum = 0;
7167 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7168 	return (0);
7169 }
7170 
7171 /*
7172  * Nobody should be sending
7173  * packets up this stream
7174  */
7175 static void
7176 ip_lrput(queue_t *q, mblk_t *mp)
7177 {
7178 	mblk_t *mp1;
7179 
7180 	switch (mp->b_datap->db_type) {
7181 	case M_FLUSH:
7182 		/* Turn around */
7183 		if (*mp->b_rptr & FLUSHW) {
7184 			*mp->b_rptr &= ~FLUSHR;
7185 			qreply(q, mp);
7186 			return;
7187 		}
7188 		break;
7189 	}
7190 	/* Could receive messages that passed through ar_rput */
7191 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7192 		mp1->b_prev = mp1->b_next = NULL;
7193 	freemsg(mp);
7194 }
7195 
7196 /* Nobody should be sending packets down this stream */
7197 /* ARGSUSED */
7198 void
7199 ip_lwput(queue_t *q, mblk_t *mp)
7200 {
7201 	freemsg(mp);
7202 }
7203 
7204 /*
7205  * Move the first hop in any source route to ipha_dst and remove that part of
7206  * the source route.  Called by other protocols.  Errors in option formatting
7207  * are ignored - will be handled by ip_wput_options Return the final
7208  * destination (either ipha_dst or the last entry in a source route.)
7209  */
7210 ipaddr_t
7211 ip_massage_options(ipha_t *ipha)
7212 {
7213 	ipoptp_t	opts;
7214 	uchar_t		*opt;
7215 	uint8_t		optval;
7216 	uint8_t		optlen;
7217 	ipaddr_t	dst;
7218 	int		i;
7219 	ire_t		*ire;
7220 
7221 	ip2dbg(("ip_massage_options\n"));
7222 	dst = ipha->ipha_dst;
7223 	for (optval = ipoptp_first(&opts, ipha);
7224 	    optval != IPOPT_EOL;
7225 	    optval = ipoptp_next(&opts)) {
7226 		opt = opts.ipoptp_cur;
7227 		switch (optval) {
7228 			uint8_t off;
7229 		case IPOPT_SSRR:
7230 		case IPOPT_LSRR:
7231 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7232 				ip1dbg(("ip_massage_options: bad src route\n"));
7233 				break;
7234 			}
7235 			optlen = opts.ipoptp_len;
7236 			off = opt[IPOPT_OFFSET];
7237 			off--;
7238 		redo_srr:
7239 			if (optlen < IP_ADDR_LEN ||
7240 			    off > optlen - IP_ADDR_LEN) {
7241 				/* End of source route */
7242 				ip1dbg(("ip_massage_options: end of SR\n"));
7243 				break;
7244 			}
7245 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7246 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7247 			    ntohl(dst)));
7248 			/*
7249 			 * Check if our address is present more than
7250 			 * once as consecutive hops in source route.
7251 			 * XXX verify per-interface ip_forwarding
7252 			 * for source route?
7253 			 */
7254 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7255 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7256 			if (ire != NULL) {
7257 				ire_refrele(ire);
7258 				off += IP_ADDR_LEN;
7259 				goto redo_srr;
7260 			}
7261 			if (dst == htonl(INADDR_LOOPBACK)) {
7262 				ip1dbg(("ip_massage_options: loopback addr in "
7263 				    "source route!\n"));
7264 				break;
7265 			}
7266 			/*
7267 			 * Update ipha_dst to be the first hop and remove the
7268 			 * first hop from the source route (by overwriting
7269 			 * part of the option with NOP options).
7270 			 */
7271 			ipha->ipha_dst = dst;
7272 			/* Put the last entry in dst */
7273 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7274 			    3;
7275 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7276 
7277 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7278 			    ntohl(dst)));
7279 			/* Move down and overwrite */
7280 			opt[IP_ADDR_LEN] = opt[0];
7281 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7282 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7283 			for (i = 0; i < IP_ADDR_LEN; i++)
7284 				opt[i] = IPOPT_NOP;
7285 			break;
7286 		}
7287 	}
7288 	return (dst);
7289 }
7290 
7291 /*
7292  * This function's job is to forward data to the reverse tunnel (FA->HA)
7293  * after doing a few checks. It is assumed that the incoming interface
7294  * of the packet is always different than the outgoing interface and the
7295  * ire_type of the found ire has to be a non-resolver type.
7296  *
7297  * IPQoS notes
7298  * IP policy is invoked twice for a forwarded packet, once on the read side
7299  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7300  * enabled.
7301  */
7302 static void
7303 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7304 {
7305 	ipha_t		*ipha;
7306 	queue_t		*q;
7307 	uint32_t 	pkt_len;
7308 #define	rptr    ((uchar_t *)ipha)
7309 	uint32_t 	sum;
7310 	uint32_t 	max_frag;
7311 	mblk_t		*first_mp;
7312 	uint32_t	ill_index;
7313 	ipxmit_state_t	pktxmit_state;
7314 	ill_t		*out_ill;
7315 
7316 	ASSERT(ire != NULL);
7317 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7318 	ASSERT(ire->ire_stq != NULL);
7319 
7320 	/* Initiate read side IPPF processing */
7321 	if (IPP_ENABLED(IPP_FWD_IN)) {
7322 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7323 		ip_process(IPP_FWD_IN, &mp, ill_index);
7324 		if (mp == NULL) {
7325 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7326 			    "dropped during IPPF processing\n"));
7327 			return;
7328 		}
7329 	}
7330 
7331 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7332 		ILLF_ROUTER) == 0) ||
7333 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7334 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7335 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7336 		    "forwarding is not turned on\n"));
7337 		goto drop_pkt;
7338 	}
7339 
7340 	/*
7341 	 * Don't forward if the interface is down
7342 	 */
7343 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7344 		goto discard_pkt;
7345 	}
7346 
7347 	ipha = (ipha_t *)mp->b_rptr;
7348 	pkt_len = ntohs(ipha->ipha_length);
7349 	/* Adjust the checksum to reflect the ttl decrement. */
7350 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7351 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7352 	if (ipha->ipha_ttl-- <= 1) {
7353 		if (ip_csum_hdr(ipha)) {
7354 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7355 			goto drop_pkt;
7356 		}
7357 		q = ire->ire_stq;
7358 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7359 		    BPRI_HI)) == NULL) {
7360 			goto discard_pkt;
7361 		}
7362 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7363 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7364 		/* Sent by forwarding path, and router is global zone */
7365 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7366 		    GLOBAL_ZONEID);
7367 		return;
7368 	}
7369 
7370 	/* Get the ill_index of the ILL */
7371 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7372 
7373 	/*
7374 	 * This location is chosen for the placement of the forwarding hook
7375 	 * because at this point we know that we have a path out for the
7376 	 * packet but haven't yet applied any logic (such as fragmenting)
7377 	 * that happen as part of transmitting the packet out.
7378 	 */
7379 	out_ill = ire->ire_ipif->ipif_ill;
7380 
7381 	DTRACE_PROBE4(ip4__forwarding__start,
7382 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7383 
7384 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7385 	    in_ill, out_ill, ipha, mp, mp);
7386 
7387 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7388 
7389 	if (mp == NULL)
7390 		return;
7391 	pkt_len = ntohs(ipha->ipha_length);
7392 
7393 	/*
7394 	 * ip_mrtun_forward is only used by foreign agent to reverse
7395 	 * tunnel the incoming packet. So it does not do any option
7396 	 * processing for source routing.
7397 	 */
7398 	max_frag = ire->ire_max_frag;
7399 	if (pkt_len > max_frag) {
7400 		/*
7401 		 * It needs fragging on its way out.  We haven't
7402 		 * verified the header checksum yet.  Since we
7403 		 * are going to put a surely good checksum in the
7404 		 * outgoing header, we have to make sure that it
7405 		 * was good coming in.
7406 		 */
7407 		if (ip_csum_hdr(ipha)) {
7408 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7409 			goto drop_pkt;
7410 		}
7411 
7412 		/* Initiate write side IPPF processing */
7413 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7414 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7415 			if (mp == NULL) {
7416 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7417 				    "dropped/deferred during ip policy "\
7418 				    "processing\n"));
7419 				return;
7420 			}
7421 		}
7422 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7423 		    BPRI_HI)) == NULL) {
7424 			goto discard_pkt;
7425 		}
7426 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7427 		mp = first_mp;
7428 
7429 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7430 		return;
7431 	}
7432 
7433 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7434 
7435 	ASSERT(ire->ire_ipif != NULL);
7436 
7437 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7438 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7439 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7440 	    NULL, out_ill, ipha, mp, mp);
7441 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7442 	if (mp == NULL)
7443 		return;
7444 
7445 	/* Now send the packet to the tunnel interface */
7446 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7447 	q = ire->ire_stq;
7448 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7449 	if ((pktxmit_state == SEND_FAILED) ||
7450 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7451 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7452 		    q->q_ptr));
7453 	}
7454 
7455 	return;
7456 discard_pkt:
7457 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7458 drop_pkt:;
7459 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7460 	freemsg(mp);
7461 #undef	rptr
7462 }
7463 
7464 /*
7465  * Fills the ipsec_out_t data structure with appropriate fields and
7466  * prepends it to mp which contains the IP hdr + data that was meant
7467  * to be forwarded. Please note that ipsec_out_info data structure
7468  * is used here to communicate the outgoing ill path at ip_wput()
7469  * for the ICMP error packet. This has nothing to do with ipsec IP
7470  * security. ipsec_out_t is really used to pass the info to the module
7471  * IP where this information cannot be extracted from conn.
7472  * This functions is called by ip_mrtun_forward().
7473  */
7474 void
7475 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7476 {
7477 	ipsec_out_t	*io;
7478 
7479 	ASSERT(xmit_ill != NULL);
7480 	first_mp->b_datap->db_type = M_CTL;
7481 	first_mp->b_wptr += sizeof (ipsec_info_t);
7482 	/*
7483 	 * This is to pass info to ip_wput in absence of conn.
7484 	 * ipsec_out_secure will be B_FALSE because of this.
7485 	 * Thus ipsec_out_secure being B_FALSE indicates that
7486 	 * this is not IPSEC security related information.
7487 	 */
7488 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7489 	io = (ipsec_out_t *)first_mp->b_rptr;
7490 	io->ipsec_out_type = IPSEC_OUT;
7491 	io->ipsec_out_len = sizeof (ipsec_out_t);
7492 	first_mp->b_cont = mp;
7493 	io->ipsec_out_ill_index =
7494 	    xmit_ill->ill_phyint->phyint_ifindex;
7495 	io->ipsec_out_xmit_if = B_TRUE;
7496 }
7497 
7498 /*
7499  * Return the network mask
7500  * associated with the specified address.
7501  */
7502 ipaddr_t
7503 ip_net_mask(ipaddr_t addr)
7504 {
7505 	uchar_t	*up = (uchar_t *)&addr;
7506 	ipaddr_t mask = 0;
7507 	uchar_t	*maskp = (uchar_t *)&mask;
7508 
7509 #if defined(__i386) || defined(__amd64)
7510 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7511 #endif
7512 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7513 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7514 #endif
7515 	if (CLASSD(addr)) {
7516 		maskp[0] = 0xF0;
7517 		return (mask);
7518 	}
7519 	if (addr == 0)
7520 		return (0);
7521 	maskp[0] = 0xFF;
7522 	if ((up[0] & 0x80) == 0)
7523 		return (mask);
7524 
7525 	maskp[1] = 0xFF;
7526 	if ((up[0] & 0xC0) == 0x80)
7527 		return (mask);
7528 
7529 	maskp[2] = 0xFF;
7530 	if ((up[0] & 0xE0) == 0xC0)
7531 		return (mask);
7532 
7533 	/* Must be experimental or multicast, indicate as much */
7534 	return ((ipaddr_t)0);
7535 }
7536 
7537 /*
7538  * Select an ill for the packet by considering load spreading across
7539  * a different ill in the group if dst_ill is part of some group.
7540  */
7541 ill_t *
7542 ip_newroute_get_dst_ill(ill_t *dst_ill)
7543 {
7544 	ill_t *ill;
7545 
7546 	/*
7547 	 * We schedule irrespective of whether the source address is
7548 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7549 	 */
7550 	ill = illgrp_scheduler(dst_ill);
7551 	if (ill == NULL)
7552 		return (NULL);
7553 
7554 	/*
7555 	 * For groups with names ip_sioctl_groupname ensures that all
7556 	 * ills are of same type. For groups without names, ifgrp_insert
7557 	 * ensures this.
7558 	 */
7559 	ASSERT(dst_ill->ill_type == ill->ill_type);
7560 
7561 	return (ill);
7562 }
7563 
7564 /*
7565  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7566  */
7567 ill_t *
7568 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7569 {
7570 	ill_t *ret_ill;
7571 
7572 	ASSERT(ifindex != 0);
7573 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7574 	if (ret_ill == NULL ||
7575 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7576 		if (isv6) {
7577 			if (ill != NULL) {
7578 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7579 			} else {
7580 				BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
7581 			}
7582 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7583 			    "bad ifindex %d.\n", ifindex));
7584 		} else {
7585 			if (ill != NULL) {
7586 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7587 			} else {
7588 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
7589 			}
7590 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7591 			    "bad ifindex %d.\n", ifindex));
7592 		}
7593 		if (ret_ill != NULL)
7594 			ill_refrele(ret_ill);
7595 		freemsg(first_mp);
7596 		return (NULL);
7597 	}
7598 
7599 	return (ret_ill);
7600 }
7601 
7602 /*
7603  * IPv4 -
7604  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7605  * out a packet to a destination address for which we do not have specific
7606  * (or sufficient) routing information.
7607  *
7608  * NOTE : These are the scopes of some of the variables that point at IRE,
7609  *	  which needs to be followed while making any future modifications
7610  *	  to avoid memory leaks.
7611  *
7612  *	- ire and sire are the entries looked up initially by
7613  *	  ire_ftable_lookup.
7614  *	- ipif_ire is used to hold the interface ire associated with
7615  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7616  *	  it before branching out to error paths.
7617  *	- save_ire is initialized before ire_create, so that ire returned
7618  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7619  *	  before breaking out of the switch.
7620  *
7621  *	Thus on failures, we have to REFRELE only ire and sire, if they
7622  *	are not NULL.
7623  */
7624 void
7625 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7626     zoneid_t zoneid)
7627 {
7628 	areq_t	*areq;
7629 	ipaddr_t gw = 0;
7630 	ire_t	*ire = NULL;
7631 	mblk_t	*res_mp;
7632 	ipaddr_t *addrp;
7633 	ipaddr_t nexthop_addr;
7634 	ipif_t  *src_ipif = NULL;
7635 	ill_t	*dst_ill = NULL;
7636 	ipha_t  *ipha;
7637 	ire_t	*sire = NULL;
7638 	mblk_t	*first_mp;
7639 	ire_t	*save_ire;
7640 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7641 	ushort_t ire_marks = 0;
7642 	boolean_t mctl_present;
7643 	ipsec_out_t *io;
7644 	mblk_t	*saved_mp;
7645 	ire_t	*first_sire = NULL;
7646 	mblk_t	*copy_mp = NULL;
7647 	mblk_t	*xmit_mp = NULL;
7648 	ipaddr_t save_dst;
7649 	uint32_t multirt_flags =
7650 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7651 	boolean_t multirt_is_resolvable;
7652 	boolean_t multirt_resolve_next;
7653 	boolean_t do_attach_ill = B_FALSE;
7654 	boolean_t ip_nexthop = B_FALSE;
7655 	tsol_ire_gw_secattr_t *attrp = NULL;
7656 	tsol_gcgrp_t *gcgrp = NULL;
7657 	tsol_gcgrp_addr_t ga;
7658 
7659 	if (ip_debug > 2) {
7660 		/* ip1dbg */
7661 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7662 	}
7663 
7664 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7665 	if (mctl_present) {
7666 		io = (ipsec_out_t *)first_mp->b_rptr;
7667 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7668 		ASSERT(zoneid == io->ipsec_out_zoneid);
7669 		ASSERT(zoneid != ALL_ZONES);
7670 	}
7671 
7672 	ipha = (ipha_t *)mp->b_rptr;
7673 
7674 	/* All multicast lookups come through ip_newroute_ipif() */
7675 	if (CLASSD(dst)) {
7676 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7677 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7678 		freemsg(first_mp);
7679 		return;
7680 	}
7681 
7682 	if (mctl_present && io->ipsec_out_attach_if) {
7683 		/* ip_grab_attach_ill returns a held ill */
7684 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7685 		    io->ipsec_out_ill_index, B_FALSE);
7686 
7687 		/* Failure case frees things for us. */
7688 		if (attach_ill == NULL)
7689 			return;
7690 
7691 		/*
7692 		 * Check if we need an ire that will not be
7693 		 * looked up by anybody else i.e. HIDDEN.
7694 		 */
7695 		if (ill_is_probeonly(attach_ill))
7696 			ire_marks = IRE_MARK_HIDDEN;
7697 	}
7698 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7699 		ip_nexthop = B_TRUE;
7700 		nexthop_addr = io->ipsec_out_nexthop_addr;
7701 	}
7702 	/*
7703 	 * If this IRE is created for forwarding or it is not for
7704 	 * traffic for congestion controlled protocols, mark it as temporary.
7705 	 */
7706 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7707 		ire_marks |= IRE_MARK_TEMPORARY;
7708 
7709 	/*
7710 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7711 	 * chain until it gets the most specific information available.
7712 	 * For example, we know that there is no IRE_CACHE for this dest,
7713 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7714 	 * ire_ftable_lookup will look up the gateway, etc.
7715 	 * Check if in_ill != NULL. If it is true, the packet must be
7716 	 * from an incoming interface where RTA_SRCIFP is set.
7717 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7718 	 * to the destination, of equal netmask length in the forward table,
7719 	 * will be recursively explored. If no information is available
7720 	 * for the final gateway of that route, we force the returned ire
7721 	 * to be equal to sire using MATCH_IRE_PARENT.
7722 	 * At least, in this case we have a starting point (in the buckets)
7723 	 * to look for other routes to the destination in the forward table.
7724 	 * This is actually used only for multirouting, where a list
7725 	 * of routes has to be processed in sequence.
7726 	 *
7727 	 * In the process of coming up with the most specific information,
7728 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7729 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7730 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7731 	 * Two caveats when handling incomplete ire's in ip_newroute:
7732 	 * - we should be careful when accessing its ire_nce (specifically
7733 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7734 	 * - not all legacy code path callers are prepared to handle
7735 	 *   incomplete ire's, so we should not create/add incomplete
7736 	 *   ire_cache entries here. (See discussion about temporary solution
7737 	 *   further below).
7738 	 *
7739 	 * In order to minimize packet dropping, and to preserve existing
7740 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7741 	 * gateway, and instead use the IF_RESOLVER ire to send out
7742 	 * another request to ARP (this is achieved by passing the
7743 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7744 	 * arp response comes back in ip_wput_nondata, we will create
7745 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7746 	 *
7747 	 * Note that this is a temporary solution; the correct solution is
7748 	 * to create an incomplete  per-dst ire_cache entry, and send the
7749 	 * packet out when the gw's nce is resolved. In order to achieve this,
7750 	 * all packet processing must have been completed prior to calling
7751 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7752 	 * to be modified to accomodate this solution.
7753 	 */
7754 	if (in_ill != NULL) {
7755 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7756 		    in_ill, MATCH_IRE_TYPE);
7757 	} else if (ip_nexthop) {
7758 		/*
7759 		 * The first time we come here, we look for an IRE_INTERFACE
7760 		 * entry for the specified nexthop, set the dst to be the
7761 		 * nexthop address and create an IRE_CACHE entry for the
7762 		 * nexthop. The next time around, we are able to find an
7763 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7764 		 * nexthop address and create an IRE_CACHE entry for the
7765 		 * destination address via the specified nexthop.
7766 		 */
7767 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7768 		    MBLK_GETLABEL(mp));
7769 		if (ire != NULL) {
7770 			gw = nexthop_addr;
7771 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7772 		} else {
7773 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7774 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7775 			    MBLK_GETLABEL(mp),
7776 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7777 			if (ire != NULL) {
7778 				dst = nexthop_addr;
7779 			}
7780 		}
7781 	} else if (attach_ill == NULL) {
7782 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7783 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7784 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7785 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7786 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7787 	} else {
7788 		/*
7789 		 * attach_ill is set only for communicating with
7790 		 * on-link hosts. So, don't look for DEFAULT.
7791 		 */
7792 		ipif_t	*attach_ipif;
7793 
7794 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7795 		if (attach_ipif == NULL) {
7796 			ill_refrele(attach_ill);
7797 			goto icmp_err_ret;
7798 		}
7799 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7800 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7801 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7802 		    MATCH_IRE_SECATTR);
7803 		ipif_refrele(attach_ipif);
7804 	}
7805 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7806 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7807 
7808 	/*
7809 	 * This loop is run only once in most cases.
7810 	 * We loop to resolve further routes only when the destination
7811 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7812 	 */
7813 	do {
7814 		/* Clear the previous iteration's values */
7815 		if (src_ipif != NULL) {
7816 			ipif_refrele(src_ipif);
7817 			src_ipif = NULL;
7818 		}
7819 		if (dst_ill != NULL) {
7820 			ill_refrele(dst_ill);
7821 			dst_ill = NULL;
7822 		}
7823 
7824 		multirt_resolve_next = B_FALSE;
7825 		/*
7826 		 * We check if packets have to be multirouted.
7827 		 * In this case, given the current <ire, sire> couple,
7828 		 * we look for the next suitable <ire, sire>.
7829 		 * This check is done in ire_multirt_lookup(),
7830 		 * which applies various criteria to find the next route
7831 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7832 		 * unchanged if it detects it has not been tried yet.
7833 		 */
7834 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7835 			ip3dbg(("ip_newroute: starting next_resolution "
7836 			    "with first_mp %p, tag %d\n",
7837 			    (void *)first_mp,
7838 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7839 
7840 			ASSERT(sire != NULL);
7841 			multirt_is_resolvable =
7842 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7843 				MBLK_GETLABEL(mp));
7844 
7845 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7846 			    "ire %p, sire %p\n",
7847 			    multirt_is_resolvable,
7848 			    (void *)ire, (void *)sire));
7849 
7850 			if (!multirt_is_resolvable) {
7851 				/*
7852 				 * No more multirt route to resolve; give up
7853 				 * (all routes resolved or no more
7854 				 * resolvable routes).
7855 				 */
7856 				if (ire != NULL) {
7857 					ire_refrele(ire);
7858 					ire = NULL;
7859 				}
7860 			} else {
7861 				ASSERT(sire != NULL);
7862 				ASSERT(ire != NULL);
7863 				/*
7864 				 * We simply use first_sire as a flag that
7865 				 * indicates if a resolvable multirt route
7866 				 * has already been found.
7867 				 * If it is not the case, we may have to send
7868 				 * an ICMP error to report that the
7869 				 * destination is unreachable.
7870 				 * We do not IRE_REFHOLD first_sire.
7871 				 */
7872 				if (first_sire == NULL) {
7873 					first_sire = sire;
7874 				}
7875 			}
7876 		}
7877 		if (ire == NULL) {
7878 			if (ip_debug > 3) {
7879 				/* ip2dbg */
7880 				pr_addr_dbg("ip_newroute: "
7881 				    "can't resolve %s\n", AF_INET, &dst);
7882 			}
7883 			ip3dbg(("ip_newroute: "
7884 			    "ire %p, sire %p, first_sire %p\n",
7885 			    (void *)ire, (void *)sire, (void *)first_sire));
7886 
7887 			if (sire != NULL) {
7888 				ire_refrele(sire);
7889 				sire = NULL;
7890 			}
7891 
7892 			if (first_sire != NULL) {
7893 				/*
7894 				 * At least one multirt route has been found
7895 				 * in the same call to ip_newroute();
7896 				 * there is no need to report an ICMP error.
7897 				 * first_sire was not IRE_REFHOLDed.
7898 				 */
7899 				MULTIRT_DEBUG_UNTAG(first_mp);
7900 				freemsg(first_mp);
7901 				return;
7902 			}
7903 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7904 			    RTA_DST);
7905 			if (attach_ill != NULL)
7906 				ill_refrele(attach_ill);
7907 			goto icmp_err_ret;
7908 		}
7909 
7910 		/*
7911 		 * When RTA_SRCIFP is used to add a route, then an interface
7912 		 * route is added in the source interface's routing table.
7913 		 * If the outgoing interface of this route is of type
7914 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7915 		 * ire_nce->nce_res_mp is set to NULL.
7916 		 * Later, when this route is first used for forwarding
7917 		 * a packet, ip_newroute() is called
7918 		 * to resolve the hardware address of the outgoing ipif.
7919 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7920 		 * source interface based table. We only come here if the
7921 		 * outgoing interface is a resolver interface and we don't
7922 		 * have the ire_nce->nce_res_mp information yet.
7923 		 * If in_ill is not null that means it is called from
7924 		 * ip_rput.
7925 		 */
7926 
7927 		ASSERT(ire->ire_in_ill == NULL ||
7928 		    (ire->ire_type == IRE_IF_RESOLVER &&
7929 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7930 
7931 		/*
7932 		 * Verify that the returned IRE does not have either
7933 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7934 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7935 		 */
7936 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7937 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7938 			if (attach_ill != NULL)
7939 				ill_refrele(attach_ill);
7940 			goto icmp_err_ret;
7941 		}
7942 		/*
7943 		 * Increment the ire_ob_pkt_count field for ire if it is an
7944 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7945 		 * increment the same for the parent IRE, sire, if it is some
7946 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7947 		 * and HOST_REDIRECT).
7948 		 */
7949 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7950 			UPDATE_OB_PKT_COUNT(ire);
7951 			ire->ire_last_used_time = lbolt;
7952 		}
7953 
7954 		if (sire != NULL) {
7955 			gw = sire->ire_gateway_addr;
7956 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7957 			    IRE_INTERFACE)) == 0);
7958 			UPDATE_OB_PKT_COUNT(sire);
7959 			sire->ire_last_used_time = lbolt;
7960 		}
7961 		/*
7962 		 * We have a route to reach the destination.
7963 		 *
7964 		 * 1) If the interface is part of ill group, try to get a new
7965 		 *    ill taking load spreading into account.
7966 		 *
7967 		 * 2) After selecting the ill, get a source address that
7968 		 *    might create good inbound load spreading.
7969 		 *    ipif_select_source does this for us.
7970 		 *
7971 		 * If the application specified the ill (ifindex), we still
7972 		 * load spread. Only if the packets needs to go out
7973 		 * specifically on a given ill e.g. binding to
7974 		 * IPIF_NOFAILOVER address, then we don't try to use a
7975 		 * different ill for load spreading.
7976 		 */
7977 		if (attach_ill == NULL) {
7978 			/*
7979 			 * Don't perform outbound load spreading in the
7980 			 * case of an RTF_MULTIRT route, as we actually
7981 			 * typically want to replicate outgoing packets
7982 			 * through particular interfaces.
7983 			 */
7984 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7985 				dst_ill = ire->ire_ipif->ipif_ill;
7986 				/* for uniformity */
7987 				ill_refhold(dst_ill);
7988 			} else {
7989 				/*
7990 				 * If we are here trying to create an IRE_CACHE
7991 				 * for an offlink destination and have the
7992 				 * IRE_CACHE for the next hop and the latter is
7993 				 * using virtual IP source address selection i.e
7994 				 * it's ire->ire_ipif is pointing to a virtual
7995 				 * network interface (vni) then
7996 				 * ip_newroute_get_dst_ll() will return the vni
7997 				 * interface as the dst_ill. Since the vni is
7998 				 * virtual i.e not associated with any physical
7999 				 * interface, it cannot be the dst_ill, hence
8000 				 * in such a case call ip_newroute_get_dst_ll()
8001 				 * with the stq_ill instead of the ire_ipif ILL.
8002 				 * The function returns a refheld ill.
8003 				 */
8004 				if ((ire->ire_type == IRE_CACHE) &&
8005 				    IS_VNI(ire->ire_ipif->ipif_ill))
8006 					dst_ill = ip_newroute_get_dst_ill(
8007 						ire->ire_stq->q_ptr);
8008 				else
8009 					dst_ill = ip_newroute_get_dst_ill(
8010 						ire->ire_ipif->ipif_ill);
8011 			}
8012 			if (dst_ill == NULL) {
8013 				if (ip_debug > 2) {
8014 					pr_addr_dbg("ip_newroute: "
8015 					    "no dst ill for dst"
8016 					    " %s\n", AF_INET, &dst);
8017 				}
8018 				goto icmp_err_ret;
8019 			}
8020 		} else {
8021 			dst_ill = ire->ire_ipif->ipif_ill;
8022 			/* for uniformity */
8023 			ill_refhold(dst_ill);
8024 			/*
8025 			 * We should have found a route matching ill as we
8026 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8027 			 * Rather than asserting, when there is a mismatch,
8028 			 * we just drop the packet.
8029 			 */
8030 			if (dst_ill != attach_ill) {
8031 				ip0dbg(("ip_newroute: Packet dropped as "
8032 				    "IPIF_NOFAILOVER ill is %s, "
8033 				    "ire->ire_ipif->ipif_ill is %s\n",
8034 				    attach_ill->ill_name,
8035 				    dst_ill->ill_name));
8036 				ill_refrele(attach_ill);
8037 				goto icmp_err_ret;
8038 			}
8039 		}
8040 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8041 		if (attach_ill != NULL) {
8042 			ill_refrele(attach_ill);
8043 			attach_ill = NULL;
8044 			do_attach_ill = B_TRUE;
8045 		}
8046 		ASSERT(dst_ill != NULL);
8047 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8048 
8049 		/*
8050 		 * Pick the best source address from dst_ill.
8051 		 *
8052 		 * 1) If it is part of a multipathing group, we would
8053 		 *    like to spread the inbound packets across different
8054 		 *    interfaces. ipif_select_source picks a random source
8055 		 *    across the different ills in the group.
8056 		 *
8057 		 * 2) If it is not part of a multipathing group, we try
8058 		 *    to pick the source address from the destination
8059 		 *    route. Clustering assumes that when we have multiple
8060 		 *    prefixes hosted on an interface, the prefix of the
8061 		 *    source address matches the prefix of the destination
8062 		 *    route. We do this only if the address is not
8063 		 *    DEPRECATED.
8064 		 *
8065 		 * 3) If the conn is in a different zone than the ire, we
8066 		 *    need to pick a source address from the right zone.
8067 		 *
8068 		 * NOTE : If we hit case (1) above, the prefix of the source
8069 		 *	  address picked may not match the prefix of the
8070 		 *	  destination routes prefix as ipif_select_source
8071 		 *	  does not look at "dst" while picking a source
8072 		 *	  address.
8073 		 *	  If we want the same behavior as (2), we will need
8074 		 *	  to change the behavior of ipif_select_source.
8075 		 */
8076 		ASSERT(src_ipif == NULL);
8077 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8078 			/*
8079 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8080 			 * Check that the ipif matching the requested source
8081 			 * address still exists.
8082 			 */
8083 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8084 			    zoneid, NULL, NULL, NULL, NULL);
8085 		}
8086 		if (src_ipif == NULL) {
8087 			ire_marks |= IRE_MARK_USESRC_CHECK;
8088 			if ((dst_ill->ill_group != NULL) ||
8089 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8090 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8091 			    ire->ire_zoneid != ALL_ZONES) ||
8092 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8093 				/*
8094 				 * If the destination is reachable via a
8095 				 * given gateway, the selected source address
8096 				 * should be in the same subnet as the gateway.
8097 				 * Otherwise, the destination is not reachable.
8098 				 *
8099 				 * If there are no interfaces on the same subnet
8100 				 * as the destination, ipif_select_source gives
8101 				 * first non-deprecated interface which might be
8102 				 * on a different subnet than the gateway.
8103 				 * This is not desirable. Hence pass the dst_ire
8104 				 * source address to ipif_select_source.
8105 				 * It is sure that the destination is reachable
8106 				 * with the dst_ire source address subnet.
8107 				 * So passing dst_ire source address to
8108 				 * ipif_select_source will make sure that the
8109 				 * selected source will be on the same subnet
8110 				 * as dst_ire source address.
8111 				 */
8112 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8113 				src_ipif = ipif_select_source(dst_ill, saddr,
8114 				    zoneid);
8115 				if (src_ipif == NULL) {
8116 					if (ip_debug > 2) {
8117 						pr_addr_dbg("ip_newroute: "
8118 						    "no src for dst %s ",
8119 						    AF_INET, &dst);
8120 						printf("through interface %s\n",
8121 						    dst_ill->ill_name);
8122 					}
8123 					goto icmp_err_ret;
8124 				}
8125 			} else {
8126 				src_ipif = ire->ire_ipif;
8127 				ASSERT(src_ipif != NULL);
8128 				/* hold src_ipif for uniformity */
8129 				ipif_refhold(src_ipif);
8130 			}
8131 		}
8132 
8133 		/*
8134 		 * Assign a source address while we have the conn.
8135 		 * We can't have ip_wput_ire pick a source address when the
8136 		 * packet returns from arp since we need to look at
8137 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8138 		 * going through arp.
8139 		 *
8140 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8141 		 *	  it uses ip6i to store this information.
8142 		 */
8143 		if (ipha->ipha_src == INADDR_ANY &&
8144 		    (connp == NULL || !connp->conn_unspec_src)) {
8145 			ipha->ipha_src = src_ipif->ipif_src_addr;
8146 		}
8147 		if (ip_debug > 3) {
8148 			/* ip2dbg */
8149 			pr_addr_dbg("ip_newroute: first hop %s\n",
8150 			    AF_INET, &gw);
8151 		}
8152 		ip2dbg(("\tire type %s (%d)\n",
8153 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8154 
8155 		/*
8156 		 * The TTL of multirouted packets is bounded by the
8157 		 * ip_multirt_ttl ndd variable.
8158 		 */
8159 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8160 			/* Force TTL of multirouted packets */
8161 			if ((ip_multirt_ttl > 0) &&
8162 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8163 				ip2dbg(("ip_newroute: forcing multirt TTL "
8164 				    "to %d (was %d), dst 0x%08x\n",
8165 				    ip_multirt_ttl, ipha->ipha_ttl,
8166 				    ntohl(sire->ire_addr)));
8167 				ipha->ipha_ttl = ip_multirt_ttl;
8168 			}
8169 		}
8170 		/*
8171 		 * At this point in ip_newroute(), ire is either the
8172 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8173 		 * destination or an IRE_INTERFACE type that should be used
8174 		 * to resolve an on-subnet destination or an on-subnet
8175 		 * next-hop gateway.
8176 		 *
8177 		 * In the IRE_CACHE case, we have the following :
8178 		 *
8179 		 * 1) src_ipif - used for getting a source address.
8180 		 *
8181 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8182 		 *    means packets using this IRE_CACHE will go out on
8183 		 *    dst_ill.
8184 		 *
8185 		 * 3) The IRE sire will point to the prefix that is the
8186 		 *    longest  matching route for the destination. These
8187 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8188 		 *
8189 		 *    The newly created IRE_CACHE entry for the off-subnet
8190 		 *    destination is tied to both the prefix route and the
8191 		 *    interface route used to resolve the next-hop gateway
8192 		 *    via the ire_phandle and ire_ihandle fields,
8193 		 *    respectively.
8194 		 *
8195 		 * In the IRE_INTERFACE case, we have the following :
8196 		 *
8197 		 * 1) src_ipif - used for getting a source address.
8198 		 *
8199 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8200 		 *    means packets using the IRE_CACHE that we will build
8201 		 *    here will go out on dst_ill.
8202 		 *
8203 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8204 		 *    to be created will only be tied to the IRE_INTERFACE
8205 		 *    that was derived from the ire_ihandle field.
8206 		 *
8207 		 *    If sire is non-NULL, it means the destination is
8208 		 *    off-link and we will first create the IRE_CACHE for the
8209 		 *    gateway. Next time through ip_newroute, we will create
8210 		 *    the IRE_CACHE for the final destination as described
8211 		 *    above.
8212 		 *
8213 		 * In both cases, after the current resolution has been
8214 		 * completed (or possibly initialised, in the IRE_INTERFACE
8215 		 * case), the loop may be re-entered to attempt the resolution
8216 		 * of another RTF_MULTIRT route.
8217 		 *
8218 		 * When an IRE_CACHE entry for the off-subnet destination is
8219 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8220 		 * for further processing in emission loops.
8221 		 */
8222 		save_ire = ire;
8223 		switch (ire->ire_type) {
8224 		case IRE_CACHE: {
8225 			ire_t	*ipif_ire;
8226 			mblk_t	*ire_fp_mp;
8227 
8228 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8229 			if (gw == 0)
8230 				gw = ire->ire_gateway_addr;
8231 			/*
8232 			 * We need 3 ire's to create a new cache ire for an
8233 			 * off-link destination from the cache ire of the
8234 			 * gateway.
8235 			 *
8236 			 *	1. The prefix ire 'sire' (Note that this does
8237 			 *	   not apply to the conn_nexthop_set case)
8238 			 *	2. The cache ire of the gateway 'ire'
8239 			 *	3. The interface ire 'ipif_ire'
8240 			 *
8241 			 * We have (1) and (2). We lookup (3) below.
8242 			 *
8243 			 * If there is no interface route to the gateway,
8244 			 * it is a race condition, where we found the cache
8245 			 * but the interface route has been deleted.
8246 			 */
8247 			if (ip_nexthop) {
8248 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8249 			} else {
8250 				ipif_ire =
8251 				    ire_ihandle_lookup_offlink(ire, sire);
8252 			}
8253 			if (ipif_ire == NULL) {
8254 				ip1dbg(("ip_newroute: "
8255 				    "ire_ihandle_lookup_offlink failed\n"));
8256 				goto icmp_err_ret;
8257 			}
8258 			/*
8259 			 * XXX We are using the same res_mp
8260 			 * (DL_UNITDATA_REQ) though the save_ire is not
8261 			 * pointing at the same ill.
8262 			 * This is incorrect. We need to send it up to the
8263 			 * resolver to get the right res_mp. For ethernets
8264 			 * this may be okay (ill_type == DL_ETHER).
8265 			 */
8266 			res_mp = save_ire->ire_nce->nce_res_mp;
8267 			ire_fp_mp = NULL;
8268 			/*
8269 			 * save_ire's nce_fp_mp can't change since it is
8270 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8271 			 * LOCK_IRE_FP_MP does not do any useful work in
8272 			 * the case of IRE_CACHE. So we don't use it below.
8273 			 */
8274 			if (save_ire->ire_stq == dst_ill->ill_wq)
8275 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8276 
8277 			/*
8278 			 * Check cached gateway IRE for any security
8279 			 * attributes; if found, associate the gateway
8280 			 * credentials group to the destination IRE.
8281 			 */
8282 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8283 				mutex_enter(&attrp->igsa_lock);
8284 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8285 					GCGRP_REFHOLD(gcgrp);
8286 				mutex_exit(&attrp->igsa_lock);
8287 			}
8288 
8289 			ire = ire_create(
8290 			    (uchar_t *)&dst,		/* dest address */
8291 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8292 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8293 			    (uchar_t *)&gw,		/* gateway address */
8294 			    NULL,
8295 			    &save_ire->ire_max_frag,
8296 			    ire_fp_mp,			/* Fast Path header */
8297 			    dst_ill->ill_rq,		/* recv-from queue */
8298 			    dst_ill->ill_wq,		/* send-to queue */
8299 			    IRE_CACHE,			/* IRE type */
8300 			    res_mp,
8301 			    src_ipif,
8302 			    in_ill,			/* incoming ill */
8303 			    (sire != NULL) ?
8304 				sire->ire_mask : 0, 	/* Parent mask */
8305 			    (sire != NULL) ?
8306 				sire->ire_phandle : 0,  /* Parent handle */
8307 			    ipif_ire->ire_ihandle,	/* Interface handle */
8308 			    (sire != NULL) ? (sire->ire_flags &
8309 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8310 			    (sire != NULL) ?
8311 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8312 			    NULL,
8313 			    gcgrp);
8314 
8315 			if (ire == NULL) {
8316 				if (gcgrp != NULL) {
8317 					GCGRP_REFRELE(gcgrp);
8318 					gcgrp = NULL;
8319 				}
8320 				ire_refrele(ipif_ire);
8321 				ire_refrele(save_ire);
8322 				break;
8323 			}
8324 
8325 			/* reference now held by IRE */
8326 			gcgrp = NULL;
8327 
8328 			ire->ire_marks |= ire_marks;
8329 
8330 			/*
8331 			 * Prevent sire and ipif_ire from getting deleted.
8332 			 * The newly created ire is tied to both of them via
8333 			 * the phandle and ihandle respectively.
8334 			 */
8335 			if (sire != NULL) {
8336 				IRB_REFHOLD(sire->ire_bucket);
8337 				/* Has it been removed already ? */
8338 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8339 					IRB_REFRELE(sire->ire_bucket);
8340 					ire_refrele(ipif_ire);
8341 					ire_refrele(save_ire);
8342 					break;
8343 				}
8344 			}
8345 
8346 			IRB_REFHOLD(ipif_ire->ire_bucket);
8347 			/* Has it been removed already ? */
8348 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8349 				IRB_REFRELE(ipif_ire->ire_bucket);
8350 				if (sire != NULL)
8351 					IRB_REFRELE(sire->ire_bucket);
8352 				ire_refrele(ipif_ire);
8353 				ire_refrele(save_ire);
8354 				break;
8355 			}
8356 
8357 			xmit_mp = first_mp;
8358 			/*
8359 			 * In the case of multirouting, a copy
8360 			 * of the packet is done before its sending.
8361 			 * The copy is used to attempt another
8362 			 * route resolution, in a next loop.
8363 			 */
8364 			if (ire->ire_flags & RTF_MULTIRT) {
8365 				copy_mp = copymsg(first_mp);
8366 				if (copy_mp != NULL) {
8367 					xmit_mp = copy_mp;
8368 					MULTIRT_DEBUG_TAG(first_mp);
8369 				}
8370 			}
8371 			ire_add_then_send(q, ire, xmit_mp);
8372 			ire_refrele(save_ire);
8373 
8374 			/* Assert that sire is not deleted yet. */
8375 			if (sire != NULL) {
8376 				ASSERT(sire->ire_ptpn != NULL);
8377 				IRB_REFRELE(sire->ire_bucket);
8378 			}
8379 
8380 			/* Assert that ipif_ire is not deleted yet. */
8381 			ASSERT(ipif_ire->ire_ptpn != NULL);
8382 			IRB_REFRELE(ipif_ire->ire_bucket);
8383 			ire_refrele(ipif_ire);
8384 
8385 			/*
8386 			 * If copy_mp is not NULL, multirouting was
8387 			 * requested. We loop to initiate a next
8388 			 * route resolution attempt, starting from sire.
8389 			 */
8390 			if (copy_mp != NULL) {
8391 				/*
8392 				 * Search for the next unresolved
8393 				 * multirt route.
8394 				 */
8395 				copy_mp = NULL;
8396 				ipif_ire = NULL;
8397 				ire = NULL;
8398 				multirt_resolve_next = B_TRUE;
8399 				continue;
8400 			}
8401 			if (sire != NULL)
8402 				ire_refrele(sire);
8403 			ipif_refrele(src_ipif);
8404 			ill_refrele(dst_ill);
8405 			return;
8406 		}
8407 		case IRE_IF_NORESOLVER: {
8408 			/*
8409 			 * We have what we need to build an IRE_CACHE.
8410 			 *
8411 			 * Create a new res_mp with the IP gateway address
8412 			 * in destination address in the DLPI hdr if the
8413 			 * physical length is exactly 4 bytes.
8414 			 */
8415 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8416 				uchar_t *addr;
8417 
8418 				if (gw)
8419 					addr = (uchar_t *)&gw;
8420 				else
8421 					addr = (uchar_t *)&dst;
8422 
8423 				res_mp = ill_dlur_gen(addr,
8424 				    dst_ill->ill_phys_addr_length,
8425 				    dst_ill->ill_sap,
8426 				    dst_ill->ill_sap_length);
8427 
8428 				if (res_mp == NULL) {
8429 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8430 					break;
8431 				}
8432 			} else if (dst_ill->ill_resolver_mp == NULL) {
8433 				ip1dbg(("ip_newroute: dst_ill %p "
8434 				    "for IF_NORESOLV ire %p has "
8435 				    "no ill_resolver_mp\n",
8436 				    (void *)dst_ill, (void *)ire));
8437 				break;
8438 			} else {
8439 				res_mp = NULL;
8440 			}
8441 
8442 			/*
8443 			 * TSol note: We are creating the ire cache for the
8444 			 * destination 'dst'. If 'dst' is offlink, going
8445 			 * through the first hop 'gw', the security attributes
8446 			 * of 'dst' must be set to point to the gateway
8447 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8448 			 * is possible that 'dst' is a potential gateway that is
8449 			 * referenced by some route that has some security
8450 			 * attributes. Thus in the former case, we need to do a
8451 			 * gcgrp_lookup of 'gw' while in the latter case we
8452 			 * need to do gcgrp_lookup of 'dst' itself.
8453 			 */
8454 			ga.ga_af = AF_INET;
8455 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8456 			    &ga.ga_addr);
8457 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8458 
8459 			ire = ire_create(
8460 			    (uchar_t *)&dst,		/* dest address */
8461 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8462 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8463 			    (uchar_t *)&gw,		/* gateway address */
8464 			    NULL,
8465 			    &save_ire->ire_max_frag,
8466 			    NULL,			/* Fast Path header */
8467 			    dst_ill->ill_rq,		/* recv-from queue */
8468 			    dst_ill->ill_wq,		/* send-to queue */
8469 			    IRE_CACHE,
8470 			    res_mp,
8471 			    src_ipif,
8472 			    in_ill,			/* Incoming ill */
8473 			    save_ire->ire_mask,		/* Parent mask */
8474 			    (sire != NULL) ?		/* Parent handle */
8475 				sire->ire_phandle : 0,
8476 			    save_ire->ire_ihandle,	/* Interface handle */
8477 			    (sire != NULL) ? sire->ire_flags &
8478 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8479 			    &(save_ire->ire_uinfo),
8480 			    NULL,
8481 			    gcgrp);
8482 
8483 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8484 				freeb(res_mp);
8485 
8486 			if (ire == NULL) {
8487 				if (gcgrp != NULL) {
8488 					GCGRP_REFRELE(gcgrp);
8489 					gcgrp = NULL;
8490 				}
8491 				ire_refrele(save_ire);
8492 				break;
8493 			}
8494 
8495 			/* reference now held by IRE */
8496 			gcgrp = NULL;
8497 
8498 			ire->ire_marks |= ire_marks;
8499 
8500 			/* Prevent save_ire from getting deleted */
8501 			IRB_REFHOLD(save_ire->ire_bucket);
8502 			/* Has it been removed already ? */
8503 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8504 				IRB_REFRELE(save_ire->ire_bucket);
8505 				ire_refrele(save_ire);
8506 				break;
8507 			}
8508 
8509 			/*
8510 			 * In the case of multirouting, a copy
8511 			 * of the packet is made before it is sent.
8512 			 * The copy is used in the next
8513 			 * loop to attempt another resolution.
8514 			 */
8515 			xmit_mp = first_mp;
8516 			if ((sire != NULL) &&
8517 			    (sire->ire_flags & RTF_MULTIRT)) {
8518 				copy_mp = copymsg(first_mp);
8519 				if (copy_mp != NULL) {
8520 					xmit_mp = copy_mp;
8521 					MULTIRT_DEBUG_TAG(first_mp);
8522 				}
8523 			}
8524 			ire_add_then_send(q, ire, xmit_mp);
8525 
8526 			/* Assert that it is not deleted yet. */
8527 			ASSERT(save_ire->ire_ptpn != NULL);
8528 			IRB_REFRELE(save_ire->ire_bucket);
8529 			ire_refrele(save_ire);
8530 
8531 			if (copy_mp != NULL) {
8532 				/*
8533 				 * If we found a (no)resolver, we ignore any
8534 				 * trailing top priority IRE_CACHE in further
8535 				 * loops. This ensures that we do not omit any
8536 				 * (no)resolver.
8537 				 * This IRE_CACHE, if any, will be processed
8538 				 * by another thread entering ip_newroute().
8539 				 * IRE_CACHE entries, if any, will be processed
8540 				 * by another thread entering ip_newroute(),
8541 				 * (upon resolver response, for instance).
8542 				 * This aims to force parallel multirt
8543 				 * resolutions as soon as a packet must be sent.
8544 				 * In the best case, after the tx of only one
8545 				 * packet, all reachable routes are resolved.
8546 				 * Otherwise, the resolution of all RTF_MULTIRT
8547 				 * routes would require several emissions.
8548 				 */
8549 				multirt_flags &= ~MULTIRT_CACHEGW;
8550 
8551 				/*
8552 				 * Search for the next unresolved multirt
8553 				 * route.
8554 				 */
8555 				copy_mp = NULL;
8556 				save_ire = NULL;
8557 				ire = NULL;
8558 				multirt_resolve_next = B_TRUE;
8559 				continue;
8560 			}
8561 
8562 			/*
8563 			 * Don't need sire anymore
8564 			 */
8565 			if (sire != NULL)
8566 				ire_refrele(sire);
8567 
8568 			ipif_refrele(src_ipif);
8569 			ill_refrele(dst_ill);
8570 			return;
8571 		}
8572 		case IRE_IF_RESOLVER:
8573 			/*
8574 			 * We can't build an IRE_CACHE yet, but at least we
8575 			 * found a resolver that can help.
8576 			 */
8577 			res_mp = dst_ill->ill_resolver_mp;
8578 			if (!OK_RESOLVER_MP(res_mp))
8579 				break;
8580 
8581 			/*
8582 			 * To be at this point in the code with a non-zero gw
8583 			 * means that dst is reachable through a gateway that
8584 			 * we have never resolved.  By changing dst to the gw
8585 			 * addr we resolve the gateway first.
8586 			 * When ire_add_then_send() tries to put the IP dg
8587 			 * to dst, it will reenter ip_newroute() at which
8588 			 * time we will find the IRE_CACHE for the gw and
8589 			 * create another IRE_CACHE in case IRE_CACHE above.
8590 			 */
8591 			if (gw != INADDR_ANY) {
8592 				/*
8593 				 * The source ipif that was determined above was
8594 				 * relative to the destination address, not the
8595 				 * gateway's. If src_ipif was not taken out of
8596 				 * the IRE_IF_RESOLVER entry, we'll need to call
8597 				 * ipif_select_source() again.
8598 				 */
8599 				if (src_ipif != ire->ire_ipif) {
8600 					ipif_refrele(src_ipif);
8601 					src_ipif = ipif_select_source(dst_ill,
8602 					    gw, zoneid);
8603 					if (src_ipif == NULL) {
8604 						if (ip_debug > 2) {
8605 							pr_addr_dbg(
8606 							    "ip_newroute: no "
8607 							    "src for gw %s ",
8608 							    AF_INET, &gw);
8609 							printf("through "
8610 							    "interface %s\n",
8611 							    dst_ill->ill_name);
8612 						}
8613 						goto icmp_err_ret;
8614 					}
8615 				}
8616 				save_dst = dst;
8617 				dst = gw;
8618 				gw = INADDR_ANY;
8619 			}
8620 
8621 			/*
8622 			 * We obtain a partial IRE_CACHE which we will pass
8623 			 * along with the resolver query.  When the response
8624 			 * comes back it will be there ready for us to add.
8625 			 * The ire_max_frag is atomically set under the
8626 			 * irebucket lock in ire_add_v[46].
8627 			 */
8628 
8629 			ire = ire_create_mp(
8630 			    (uchar_t *)&dst,		/* dest address */
8631 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8632 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8633 			    (uchar_t *)&gw,		/* gateway address */
8634 			    NULL,			/* no in_src_addr */
8635 			    NULL,			/* ire_max_frag */
8636 			    NULL,			/* Fast Path header */
8637 			    dst_ill->ill_rq,		/* recv-from queue */
8638 			    dst_ill->ill_wq,		/* send-to queue */
8639 			    IRE_CACHE,
8640 			    NULL,
8641 			    src_ipif,			/* Interface ipif */
8642 			    in_ill,			/* Incoming ILL */
8643 			    save_ire->ire_mask,		/* Parent mask */
8644 			    0,
8645 			    save_ire->ire_ihandle,	/* Interface handle */
8646 			    0,				/* flags if any */
8647 			    &(save_ire->ire_uinfo),
8648 			    NULL,
8649 			    NULL);
8650 
8651 			if (ire == NULL) {
8652 				ire_refrele(save_ire);
8653 				break;
8654 			}
8655 
8656 			if ((sire != NULL) &&
8657 			    (sire->ire_flags & RTF_MULTIRT)) {
8658 				copy_mp = copymsg(first_mp);
8659 				if (copy_mp != NULL)
8660 					MULTIRT_DEBUG_TAG(copy_mp);
8661 			}
8662 
8663 			ire->ire_marks |= ire_marks;
8664 
8665 			/*
8666 			 * Construct message chain for the resolver
8667 			 * of the form:
8668 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8669 			 * Packet could contain a IPSEC_OUT mp.
8670 			 *
8671 			 * NOTE : ire will be added later when the response
8672 			 * comes back from ARP. If the response does not
8673 			 * come back, ARP frees the packet. For this reason,
8674 			 * we can't REFHOLD the bucket of save_ire to prevent
8675 			 * deletions. We may not be able to REFRELE the bucket
8676 			 * if the response never comes back. Thus, before
8677 			 * adding the ire, ire_add_v4 will make sure that the
8678 			 * interface route does not get deleted. This is the
8679 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8680 			 * where we can always prevent deletions because of
8681 			 * the synchronous nature of adding IRES i.e
8682 			 * ire_add_then_send is called after creating the IRE.
8683 			 */
8684 			ASSERT(ire->ire_mp != NULL);
8685 			ire->ire_mp->b_cont = first_mp;
8686 			/* Have saved_mp handy, for cleanup if canput fails */
8687 			saved_mp = mp;
8688 			mp = copyb(res_mp);
8689 			if (mp == NULL) {
8690 				/* Prepare for cleanup */
8691 				mp = saved_mp; /* pkt */
8692 				ire_delete(ire); /* ire_mp */
8693 				ire = NULL;
8694 				ire_refrele(save_ire);
8695 				if (copy_mp != NULL) {
8696 					MULTIRT_DEBUG_UNTAG(copy_mp);
8697 					freemsg(copy_mp);
8698 					copy_mp = NULL;
8699 				}
8700 				break;
8701 			}
8702 			linkb(mp, ire->ire_mp);
8703 
8704 			/*
8705 			 * Fill in the source and dest addrs for the resolver.
8706 			 * NOTE: this depends on memory layouts imposed by
8707 			 * ill_init().
8708 			 */
8709 			areq = (areq_t *)mp->b_rptr;
8710 			addrp = (ipaddr_t *)((char *)areq +
8711 			    areq->areq_sender_addr_offset);
8712 			if (do_attach_ill) {
8713 				/*
8714 				 * This is bind to no failover case.
8715 				 * arp packet also must go out on attach_ill.
8716 				 */
8717 				ASSERT(ipha->ipha_src != NULL);
8718 				*addrp = ipha->ipha_src;
8719 			} else {
8720 				*addrp = save_ire->ire_src_addr;
8721 			}
8722 
8723 			ire_refrele(save_ire);
8724 			addrp = (ipaddr_t *)((char *)areq +
8725 			    areq->areq_target_addr_offset);
8726 			*addrp = dst;
8727 			/* Up to the resolver. */
8728 			if (canputnext(dst_ill->ill_rq) &&
8729 			    !(dst_ill->ill_arp_closing)) {
8730 				putnext(dst_ill->ill_rq, mp);
8731 				ire = NULL;
8732 				if (copy_mp != NULL) {
8733 					/*
8734 					 * If we found a resolver, we ignore
8735 					 * any trailing top priority IRE_CACHE
8736 					 * in the further loops. This ensures
8737 					 * that we do not omit any resolver.
8738 					 * IRE_CACHE entries, if any, will be
8739 					 * processed next time we enter
8740 					 * ip_newroute().
8741 					 */
8742 					multirt_flags &= ~MULTIRT_CACHEGW;
8743 					/*
8744 					 * Search for the next unresolved
8745 					 * multirt route.
8746 					 */
8747 					first_mp = copy_mp;
8748 					copy_mp = NULL;
8749 					/* Prepare the next resolution loop. */
8750 					mp = first_mp;
8751 					EXTRACT_PKT_MP(mp, first_mp,
8752 					    mctl_present);
8753 					if (mctl_present)
8754 						io = (ipsec_out_t *)
8755 						    first_mp->b_rptr;
8756 					ipha = (ipha_t *)mp->b_rptr;
8757 
8758 					ASSERT(sire != NULL);
8759 
8760 					dst = save_dst;
8761 					multirt_resolve_next = B_TRUE;
8762 					continue;
8763 				}
8764 
8765 				if (sire != NULL)
8766 					ire_refrele(sire);
8767 
8768 				/*
8769 				 * The response will come back in ip_wput
8770 				 * with db_type IRE_DB_TYPE.
8771 				 */
8772 				ipif_refrele(src_ipif);
8773 				ill_refrele(dst_ill);
8774 				return;
8775 			} else {
8776 				/* Prepare for cleanup */
8777 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8778 				    mp);
8779 				mp->b_cont = NULL;
8780 				freeb(mp); /* areq */
8781 				/*
8782 				 * this is an ire that is not added to the
8783 				 * cache. ire_freemblk will handle the release
8784 				 * of any resources associated with the ire.
8785 				 */
8786 				ire_delete(ire); /* ire_mp */
8787 				mp = saved_mp; /* pkt */
8788 				ire = NULL;
8789 				if (copy_mp != NULL) {
8790 					MULTIRT_DEBUG_UNTAG(copy_mp);
8791 					freemsg(copy_mp);
8792 					copy_mp = NULL;
8793 				}
8794 				break;
8795 			}
8796 		default:
8797 			break;
8798 		}
8799 	} while (multirt_resolve_next);
8800 
8801 	ip1dbg(("ip_newroute: dropped\n"));
8802 	/* Did this packet originate externally? */
8803 	if (mp->b_prev) {
8804 		mp->b_next = NULL;
8805 		mp->b_prev = NULL;
8806 		if (in_ill != NULL) {
8807 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
8808 		} else {
8809 			BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
8810 		}
8811 	} else {
8812 		if (dst_ill != NULL) {
8813 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8814 		} else {
8815 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
8816 		}
8817 	}
8818 	ASSERT(copy_mp == NULL);
8819 	MULTIRT_DEBUG_UNTAG(first_mp);
8820 	freemsg(first_mp);
8821 	if (ire != NULL)
8822 		ire_refrele(ire);
8823 	if (sire != NULL)
8824 		ire_refrele(sire);
8825 	if (src_ipif != NULL)
8826 		ipif_refrele(src_ipif);
8827 	if (dst_ill != NULL)
8828 		ill_refrele(dst_ill);
8829 	return;
8830 
8831 icmp_err_ret:
8832 	ip1dbg(("ip_newroute: no route\n"));
8833 	if (src_ipif != NULL)
8834 		ipif_refrele(src_ipif);
8835 	if (dst_ill != NULL)
8836 		ill_refrele(dst_ill);
8837 	if (sire != NULL)
8838 		ire_refrele(sire);
8839 	/* Did this packet originate externally? */
8840 	if (mp->b_prev) {
8841 		mp->b_next = NULL;
8842 		mp->b_prev = NULL;
8843 		if (in_ill != NULL) {
8844 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
8845 		} else {
8846 			BUMP_MIB(&ip_mib, ipIfStatsInNoRoutes);
8847 		}
8848 		q = WR(q);
8849 	} else {
8850 		/*
8851 		 * There is no outgoing ill, so just increment the
8852 		 * system MIB.
8853 		 */
8854 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
8855 		/*
8856 		 * Since ip_wput() isn't close to finished, we fill
8857 		 * in enough of the header for credible error reporting.
8858 		 */
8859 		if (ip_hdr_complete(ipha, zoneid)) {
8860 			/* Failed */
8861 			MULTIRT_DEBUG_UNTAG(first_mp);
8862 			freemsg(first_mp);
8863 			if (ire != NULL)
8864 				ire_refrele(ire);
8865 			return;
8866 		}
8867 	}
8868 
8869 	/*
8870 	 * At this point we will have ire only if RTF_BLACKHOLE
8871 	 * or RTF_REJECT flags are set on the IRE. It will not
8872 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8873 	 */
8874 	if (ire != NULL) {
8875 		if (ire->ire_flags & RTF_BLACKHOLE) {
8876 			ire_refrele(ire);
8877 			MULTIRT_DEBUG_UNTAG(first_mp);
8878 			freemsg(first_mp);
8879 			return;
8880 		}
8881 		ire_refrele(ire);
8882 	}
8883 	if (ip_source_routed(ipha)) {
8884 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8885 		    zoneid);
8886 		return;
8887 	}
8888 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8889 }
8890 
8891 /*
8892  * IPv4 -
8893  * ip_newroute_ipif is called by ip_wput_multicast and
8894  * ip_rput_forward_multicast whenever we need to send
8895  * out a packet to a destination address for which we do not have specific
8896  * routing information. It is used when the packet will be sent out
8897  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8898  * socket option is set or icmp error message wants to go out on a particular
8899  * interface for a unicast packet.
8900  *
8901  * In most cases, the destination address is resolved thanks to the ipif
8902  * intrinsic resolver. However, there are some cases where the call to
8903  * ip_newroute_ipif must take into account the potential presence of
8904  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8905  * that uses the interface. This is specified through flags,
8906  * which can be a combination of:
8907  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8908  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8909  *   and flags. Additionally, the packet source address has to be set to
8910  *   the specified address. The caller is thus expected to set this flag
8911  *   if the packet has no specific source address yet.
8912  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8913  *   flag, the resulting ire will inherit the flag. All unresolved routes
8914  *   to the destination must be explored in the same call to
8915  *   ip_newroute_ipif().
8916  */
8917 static void
8918 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8919     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8920 {
8921 	areq_t	*areq;
8922 	ire_t	*ire = NULL;
8923 	mblk_t	*res_mp;
8924 	ipaddr_t *addrp;
8925 	mblk_t *first_mp;
8926 	ire_t	*save_ire = NULL;
8927 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8928 	ipif_t	*src_ipif = NULL;
8929 	ushort_t ire_marks = 0;
8930 	ill_t	*dst_ill = NULL;
8931 	boolean_t mctl_present;
8932 	ipsec_out_t *io;
8933 	ipha_t *ipha;
8934 	int	ihandle = 0;
8935 	mblk_t	*saved_mp;
8936 	ire_t   *fire = NULL;
8937 	mblk_t  *copy_mp = NULL;
8938 	boolean_t multirt_resolve_next;
8939 	ipaddr_t ipha_dst;
8940 
8941 	/*
8942 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8943 	 * here for uniformity
8944 	 */
8945 	ipif_refhold(ipif);
8946 
8947 	/*
8948 	 * This loop is run only once in most cases.
8949 	 * We loop to resolve further routes only when the destination
8950 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8951 	 */
8952 	do {
8953 		if (dst_ill != NULL) {
8954 			ill_refrele(dst_ill);
8955 			dst_ill = NULL;
8956 		}
8957 		if (src_ipif != NULL) {
8958 			ipif_refrele(src_ipif);
8959 			src_ipif = NULL;
8960 		}
8961 		multirt_resolve_next = B_FALSE;
8962 
8963 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8964 		    ipif->ipif_ill->ill_name));
8965 
8966 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8967 		if (mctl_present)
8968 			io = (ipsec_out_t *)first_mp->b_rptr;
8969 
8970 		ipha = (ipha_t *)mp->b_rptr;
8971 
8972 		/*
8973 		 * Save the packet destination address, we may need it after
8974 		 * the packet has been consumed.
8975 		 */
8976 		ipha_dst = ipha->ipha_dst;
8977 
8978 		/*
8979 		 * If the interface is a pt-pt interface we look for an
8980 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8981 		 * local_address and the pt-pt destination address. Otherwise
8982 		 * we just match the local address.
8983 		 * NOTE: dst could be different than ipha->ipha_dst in case
8984 		 * of sending igmp multicast packets over a point-to-point
8985 		 * connection.
8986 		 * Thus we must be careful enough to check ipha_dst to be a
8987 		 * multicast address, otherwise it will take xmit_if path for
8988 		 * multicast packets resulting into kernel stack overflow by
8989 		 * repeated calls to ip_newroute_ipif from ire_send().
8990 		 */
8991 		if (CLASSD(ipha_dst) &&
8992 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8993 			goto err_ret;
8994 		}
8995 
8996 		/*
8997 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8998 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8999 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9000 		 * propagate its flags to the new ire.
9001 		 */
9002 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9003 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9004 			ip2dbg(("ip_newroute_ipif: "
9005 			    "ipif_lookup_multi_ire("
9006 			    "ipif %p, dst %08x) = fire %p\n",
9007 			    (void *)ipif, ntohl(dst), (void *)fire));
9008 		}
9009 
9010 		if (mctl_present && io->ipsec_out_attach_if) {
9011 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9012 			    io->ipsec_out_ill_index, B_FALSE);
9013 
9014 			/* Failure case frees things for us. */
9015 			if (attach_ill == NULL) {
9016 				ipif_refrele(ipif);
9017 				if (fire != NULL)
9018 					ire_refrele(fire);
9019 				return;
9020 			}
9021 
9022 			/*
9023 			 * Check if we need an ire that will not be
9024 			 * looked up by anybody else i.e. HIDDEN.
9025 			 */
9026 			if (ill_is_probeonly(attach_ill)) {
9027 				ire_marks = IRE_MARK_HIDDEN;
9028 			}
9029 			/*
9030 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9031 			 * case.
9032 			 */
9033 			dst_ill = ipif->ipif_ill;
9034 			/* attach_ill has been refheld by ip_grab_attach_ill */
9035 			ASSERT(dst_ill == attach_ill);
9036 		} else {
9037 			/*
9038 			 * If this is set by IP_XMIT_IF, then make sure that
9039 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9040 			 * specified ill.
9041 			 */
9042 			ASSERT((connp == NULL) ||
9043 			    (connp->conn_xmit_if_ill == NULL) ||
9044 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9045 			/*
9046 			 * If the interface belongs to an interface group,
9047 			 * make sure the next possible interface in the group
9048 			 * is used.  This encourages load spreading among
9049 			 * peers in an interface group.
9050 			 * Note: load spreading is disabled for RTF_MULTIRT
9051 			 * routes.
9052 			 */
9053 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9054 			    (fire->ire_flags & RTF_MULTIRT)) {
9055 				/*
9056 				 * Don't perform outbound load spreading
9057 				 * in the case of an RTF_MULTIRT issued route,
9058 				 * we actually typically want to replicate
9059 				 * outgoing packets through particular
9060 				 * interfaces.
9061 				 */
9062 				dst_ill = ipif->ipif_ill;
9063 				ill_refhold(dst_ill);
9064 			} else {
9065 				dst_ill = ip_newroute_get_dst_ill(
9066 				    ipif->ipif_ill);
9067 			}
9068 			if (dst_ill == NULL) {
9069 				if (ip_debug > 2) {
9070 					pr_addr_dbg("ip_newroute_ipif: "
9071 					    "no dst ill for dst %s\n",
9072 					    AF_INET, &dst);
9073 				}
9074 				goto err_ret;
9075 			}
9076 		}
9077 
9078 		/*
9079 		 * Pick a source address preferring non-deprecated ones.
9080 		 * Unlike ip_newroute, we don't do any source address
9081 		 * selection here since for multicast it really does not help
9082 		 * in inbound load spreading as in the unicast case.
9083 		 */
9084 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9085 		    (fire->ire_flags & RTF_SETSRC)) {
9086 			/*
9087 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9088 			 * on that interface. This ire has RTF_SETSRC flag, so
9089 			 * the source address of the packet must be changed.
9090 			 * Check that the ipif matching the requested source
9091 			 * address still exists.
9092 			 */
9093 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9094 			    zoneid, NULL, NULL, NULL, NULL);
9095 		}
9096 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9097 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9098 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9099 		    (src_ipif == NULL)) {
9100 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9101 			if (src_ipif == NULL) {
9102 				if (ip_debug > 2) {
9103 					/* ip1dbg */
9104 					pr_addr_dbg("ip_newroute_ipif: "
9105 					    "no src for dst %s",
9106 					    AF_INET, &dst);
9107 				}
9108 				ip1dbg((" through interface %s\n",
9109 				    dst_ill->ill_name));
9110 				goto err_ret;
9111 			}
9112 			ipif_refrele(ipif);
9113 			ipif = src_ipif;
9114 			ipif_refhold(ipif);
9115 		}
9116 		if (src_ipif == NULL) {
9117 			src_ipif = ipif;
9118 			ipif_refhold(src_ipif);
9119 		}
9120 
9121 		/*
9122 		 * Assign a source address while we have the conn.
9123 		 * We can't have ip_wput_ire pick a source address when the
9124 		 * packet returns from arp since conn_unspec_src might be set
9125 		 * and we loose the conn when going through arp.
9126 		 */
9127 		if (ipha->ipha_src == INADDR_ANY &&
9128 		    (connp == NULL || !connp->conn_unspec_src)) {
9129 			ipha->ipha_src = src_ipif->ipif_src_addr;
9130 		}
9131 
9132 		/*
9133 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9134 		 * interface does not have an interface ire.
9135 		 * Example: Thousands of mobileip PPP interfaces to mobile
9136 		 * nodes. We don't want to create interface ires because
9137 		 * packets from other mobile nodes must not take the route
9138 		 * via interface ires to the visiting mobile node without
9139 		 * going through the home agent, in absence of mobileip
9140 		 * route optimization.
9141 		 */
9142 		if (CLASSD(ipha_dst) && (connp == NULL ||
9143 		    connp->conn_xmit_if_ill == NULL)) {
9144 			/* ipif_to_ire returns an held ire */
9145 			ire = ipif_to_ire(ipif);
9146 			if (ire == NULL)
9147 				goto err_ret;
9148 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9149 				goto err_ret;
9150 			/*
9151 			 * ihandle is needed when the ire is added to
9152 			 * cache table.
9153 			 */
9154 			save_ire = ire;
9155 			ihandle = save_ire->ire_ihandle;
9156 
9157 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9158 			    "flags %04x\n",
9159 			    (void *)ire, (void *)ipif, flags));
9160 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9161 			    (fire->ire_flags & RTF_MULTIRT)) {
9162 				/*
9163 				 * As requested by flags, an IRE_OFFSUBNET was
9164 				 * looked up on that interface. This ire has
9165 				 * RTF_MULTIRT flag, so the resolution loop will
9166 				 * be re-entered to resolve additional routes on
9167 				 * other interfaces. For that purpose, a copy of
9168 				 * the packet is performed at this point.
9169 				 */
9170 				fire->ire_last_used_time = lbolt;
9171 				copy_mp = copymsg(first_mp);
9172 				if (copy_mp) {
9173 					MULTIRT_DEBUG_TAG(copy_mp);
9174 				}
9175 			}
9176 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9177 			    (fire->ire_flags & RTF_SETSRC)) {
9178 				/*
9179 				 * As requested by flags, an IRE_OFFSUBET was
9180 				 * looked up on that interface. This ire has
9181 				 * RTF_SETSRC flag, so the source address of the
9182 				 * packet must be changed.
9183 				 */
9184 				ipha->ipha_src = fire->ire_src_addr;
9185 			}
9186 		} else {
9187 			ASSERT((connp == NULL) ||
9188 			    (connp->conn_xmit_if_ill != NULL) ||
9189 			    (connp->conn_dontroute));
9190 			/*
9191 			 * The only ways we can come here are:
9192 			 * 1) IP_XMIT_IF socket option is set
9193 			 * 2) ICMP error message generated from
9194 			 *    ip_mrtun_forward() routine and it needs
9195 			 *    to go through the specified ill.
9196 			 * 3) SO_DONTROUTE socket option is set
9197 			 * In all cases, the new ire will not be added
9198 			 * into cache table.
9199 			 */
9200 			ire_marks |= IRE_MARK_NOADD;
9201 		}
9202 
9203 		switch (ipif->ipif_net_type) {
9204 		case IRE_IF_NORESOLVER: {
9205 			/* We have what we need to build an IRE_CACHE. */
9206 			mblk_t	*res_mp;
9207 
9208 			/*
9209 			 * Create a new res_mp with the
9210 			 * IP gateway address as destination address in the
9211 			 * DLPI hdr if the physical length is exactly 4 bytes.
9212 			 */
9213 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9214 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9215 				    dst_ill->ill_phys_addr_length,
9216 				    dst_ill->ill_sap,
9217 				    dst_ill->ill_sap_length);
9218 			} else if (dst_ill->ill_resolver_mp == NULL) {
9219 				ip1dbg(("ip_newroute: dst_ill %p "
9220 				    "for IF_NORESOLV ire %p has "
9221 				    "no ill_resolver_mp\n",
9222 				    (void *)dst_ill, (void *)ire));
9223 				break;
9224 			} else {
9225 				/* use the value set in ip_ll_subnet_defaults */
9226 				res_mp = ill_dlur_gen(NULL,
9227 				    dst_ill->ill_phys_addr_length,
9228 				    dst_ill->ill_sap,
9229 				    dst_ill->ill_sap_length);
9230 			}
9231 
9232 			if (res_mp == NULL)
9233 				break;
9234 			/*
9235 			 * The new ire inherits the IRE_OFFSUBNET flags
9236 			 * and source address, if this was requested.
9237 			 */
9238 			ire = ire_create(
9239 			    (uchar_t *)&dst,		/* dest address */
9240 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9241 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9242 			    NULL,			/* gateway address */
9243 			    NULL,
9244 			    &ipif->ipif_mtu,
9245 			    NULL,			/* Fast Path header */
9246 			    dst_ill->ill_rq,		/* recv-from queue */
9247 			    dst_ill->ill_wq,		/* send-to queue */
9248 			    IRE_CACHE,
9249 			    res_mp,
9250 			    src_ipif,
9251 			    NULL,
9252 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9253 			    (fire != NULL) ?		/* Parent handle */
9254 				fire->ire_phandle : 0,
9255 			    ihandle,			/* Interface handle */
9256 			    (fire != NULL) ?
9257 				(fire->ire_flags &
9258 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9259 			    (save_ire == NULL ? &ire_uinfo_null :
9260 				&save_ire->ire_uinfo),
9261 			    NULL,
9262 			    NULL);
9263 
9264 			freeb(res_mp);
9265 
9266 			if (ire == NULL) {
9267 				if (save_ire != NULL)
9268 					ire_refrele(save_ire);
9269 				break;
9270 			}
9271 
9272 			ire->ire_marks |= ire_marks;
9273 
9274 			/*
9275 			 * If IRE_MARK_NOADD is set then we need to convert
9276 			 * the max_fragp to a useable value now. This is
9277 			 * normally done in ire_add_v[46]. We also need to
9278 			 * associate the ire with an nce (normally would be
9279 			 * done in ip_wput_nondata()).
9280 			 *
9281 			 * Note that IRE_MARK_NOADD packets created here
9282 			 * do not have a non-null ire_mp pointer. The null
9283 			 * value of ire_bucket indicates that they were
9284 			 * never added.
9285 			 */
9286 			if (ire->ire_marks & IRE_MARK_NOADD) {
9287 				uint_t  max_frag;
9288 
9289 				max_frag = *ire->ire_max_fragp;
9290 				ire->ire_max_fragp = NULL;
9291 				ire->ire_max_frag = max_frag;
9292 
9293 				if ((ire->ire_nce = ndp_lookup_v4(
9294 				    ire_to_ill(ire),
9295 				    (ire->ire_gateway_addr != INADDR_ANY ?
9296 				    &ire->ire_gateway_addr : &ire->ire_addr),
9297 				    B_FALSE)) == NULL) {
9298 					if (save_ire != NULL)
9299 						ire_refrele(save_ire);
9300 					break;
9301 				}
9302 				ASSERT(ire->ire_nce->nce_state ==
9303 				    ND_REACHABLE);
9304 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9305 			}
9306 
9307 			/* Prevent save_ire from getting deleted */
9308 			if (save_ire != NULL) {
9309 				IRB_REFHOLD(save_ire->ire_bucket);
9310 				/* Has it been removed already ? */
9311 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9312 					IRB_REFRELE(save_ire->ire_bucket);
9313 					ire_refrele(save_ire);
9314 					break;
9315 				}
9316 			}
9317 
9318 			ire_add_then_send(q, ire, first_mp);
9319 
9320 			/* Assert that save_ire is not deleted yet. */
9321 			if (save_ire != NULL) {
9322 				ASSERT(save_ire->ire_ptpn != NULL);
9323 				IRB_REFRELE(save_ire->ire_bucket);
9324 				ire_refrele(save_ire);
9325 				save_ire = NULL;
9326 			}
9327 			if (fire != NULL) {
9328 				ire_refrele(fire);
9329 				fire = NULL;
9330 			}
9331 
9332 			/*
9333 			 * the resolution loop is re-entered if this
9334 			 * was requested through flags and if we
9335 			 * actually are in a multirouting case.
9336 			 */
9337 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9338 				boolean_t need_resolve =
9339 				    ire_multirt_need_resolve(ipha_dst,
9340 					MBLK_GETLABEL(copy_mp));
9341 				if (!need_resolve) {
9342 					MULTIRT_DEBUG_UNTAG(copy_mp);
9343 					freemsg(copy_mp);
9344 					copy_mp = NULL;
9345 				} else {
9346 					/*
9347 					 * ipif_lookup_group() calls
9348 					 * ire_lookup_multi() that uses
9349 					 * ire_ftable_lookup() to find
9350 					 * an IRE_INTERFACE for the group.
9351 					 * In the multirt case,
9352 					 * ire_lookup_multi() then invokes
9353 					 * ire_multirt_lookup() to find
9354 					 * the next resolvable ire.
9355 					 * As a result, we obtain an new
9356 					 * interface, derived from the
9357 					 * next ire.
9358 					 */
9359 					ipif_refrele(ipif);
9360 					ipif = ipif_lookup_group(ipha_dst,
9361 					    zoneid);
9362 					ip2dbg(("ip_newroute_ipif: "
9363 					    "multirt dst %08x, ipif %p\n",
9364 					    htonl(dst), (void *)ipif));
9365 					if (ipif != NULL) {
9366 						mp = copy_mp;
9367 						copy_mp = NULL;
9368 						multirt_resolve_next = B_TRUE;
9369 						continue;
9370 					} else {
9371 						freemsg(copy_mp);
9372 					}
9373 				}
9374 			}
9375 			if (ipif != NULL)
9376 				ipif_refrele(ipif);
9377 			ill_refrele(dst_ill);
9378 			ipif_refrele(src_ipif);
9379 			return;
9380 		}
9381 		case IRE_IF_RESOLVER:
9382 			/*
9383 			 * We can't build an IRE_CACHE yet, but at least
9384 			 * we found a resolver that can help.
9385 			 */
9386 			res_mp = dst_ill->ill_resolver_mp;
9387 			if (!OK_RESOLVER_MP(res_mp))
9388 				break;
9389 
9390 			/*
9391 			 * We obtain a partial IRE_CACHE which we will pass
9392 			 * along with the resolver query.  When the response
9393 			 * comes back it will be there ready for us to add.
9394 			 * The new ire inherits the IRE_OFFSUBNET flags
9395 			 * and source address, if this was requested.
9396 			 * The ire_max_frag is atomically set under the
9397 			 * irebucket lock in ire_add_v[46]. Only in the
9398 			 * case of IRE_MARK_NOADD, we set it here itself.
9399 			 */
9400 			ire = ire_create_mp(
9401 			    (uchar_t *)&dst,		/* dest address */
9402 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9403 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9404 			    NULL,			/* gateway address */
9405 			    NULL,			/* no in_src_addr */
9406 			    (ire_marks & IRE_MARK_NOADD) ?
9407 				ipif->ipif_mtu : 0,	/* max_frag */
9408 			    NULL,			/* Fast path header */
9409 			    dst_ill->ill_rq,		/* recv-from queue */
9410 			    dst_ill->ill_wq,		/* send-to queue */
9411 			    IRE_CACHE,
9412 			    NULL,	/* let ire_nce_init figure res_mp out */
9413 			    src_ipif,
9414 			    NULL,
9415 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9416 			    (fire != NULL) ?		/* Parent handle */
9417 				fire->ire_phandle : 0,
9418 			    ihandle,			/* Interface handle */
9419 			    (fire != NULL) ?		/* flags if any */
9420 				(fire->ire_flags &
9421 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9422 			    (save_ire == NULL ? &ire_uinfo_null :
9423 				&save_ire->ire_uinfo),
9424 			    NULL,
9425 			    NULL);
9426 
9427 			if (save_ire != NULL) {
9428 				ire_refrele(save_ire);
9429 				save_ire = NULL;
9430 			}
9431 			if (ire == NULL)
9432 				break;
9433 
9434 			ire->ire_marks |= ire_marks;
9435 			/*
9436 			 * Construct message chain for the resolver of the
9437 			 * form:
9438 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9439 			 *
9440 			 * NOTE : ire will be added later when the response
9441 			 * comes back from ARP. If the response does not
9442 			 * come back, ARP frees the packet. For this reason,
9443 			 * we can't REFHOLD the bucket of save_ire to prevent
9444 			 * deletions. We may not be able to REFRELE the
9445 			 * bucket if the response never comes back.
9446 			 * Thus, before adding the ire, ire_add_v4 will make
9447 			 * sure that the interface route does not get deleted.
9448 			 * This is the only case unlike ip_newroute_v6,
9449 			 * ip_newroute_ipif_v6 where we can always prevent
9450 			 * deletions because ire_add_then_send is called after
9451 			 * creating the IRE.
9452 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9453 			 * does not add this IRE into the IRE CACHE.
9454 			 */
9455 			ASSERT(ire->ire_mp != NULL);
9456 			ire->ire_mp->b_cont = first_mp;
9457 			/* Have saved_mp handy, for cleanup if canput fails */
9458 			saved_mp = mp;
9459 			mp = copyb(res_mp);
9460 			if (mp == NULL) {
9461 				/* Prepare for cleanup */
9462 				mp = saved_mp; /* pkt */
9463 				ire_delete(ire); /* ire_mp */
9464 				ire = NULL;
9465 				if (copy_mp != NULL) {
9466 					MULTIRT_DEBUG_UNTAG(copy_mp);
9467 					freemsg(copy_mp);
9468 					copy_mp = NULL;
9469 				}
9470 				break;
9471 			}
9472 			linkb(mp, ire->ire_mp);
9473 
9474 			/*
9475 			 * Fill in the source and dest addrs for the resolver.
9476 			 * NOTE: this depends on memory layouts imposed by
9477 			 * ill_init().
9478 			 */
9479 			areq = (areq_t *)mp->b_rptr;
9480 			addrp = (ipaddr_t *)((char *)areq +
9481 			    areq->areq_sender_addr_offset);
9482 			*addrp = ire->ire_src_addr;
9483 			addrp = (ipaddr_t *)((char *)areq +
9484 			    areq->areq_target_addr_offset);
9485 			*addrp = dst;
9486 			/* Up to the resolver. */
9487 			if (canputnext(dst_ill->ill_rq) &&
9488 			    !(dst_ill->ill_arp_closing)) {
9489 				putnext(dst_ill->ill_rq, mp);
9490 				/*
9491 				 * The response will come back in ip_wput
9492 				 * with db_type IRE_DB_TYPE.
9493 				 */
9494 			} else {
9495 				mp->b_cont = NULL;
9496 				freeb(mp); /* areq */
9497 				ire_delete(ire); /* ire_mp */
9498 				saved_mp->b_next = NULL;
9499 				saved_mp->b_prev = NULL;
9500 				freemsg(first_mp); /* pkt */
9501 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9502 			}
9503 
9504 			if (fire != NULL) {
9505 				ire_refrele(fire);
9506 				fire = NULL;
9507 			}
9508 
9509 
9510 			/*
9511 			 * The resolution loop is re-entered if this was
9512 			 * requested through flags and we actually are
9513 			 * in a multirouting case.
9514 			 */
9515 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9516 				boolean_t need_resolve =
9517 				    ire_multirt_need_resolve(ipha_dst,
9518 					MBLK_GETLABEL(copy_mp));
9519 				if (!need_resolve) {
9520 					MULTIRT_DEBUG_UNTAG(copy_mp);
9521 					freemsg(copy_mp);
9522 					copy_mp = NULL;
9523 				} else {
9524 					/*
9525 					 * ipif_lookup_group() calls
9526 					 * ire_lookup_multi() that uses
9527 					 * ire_ftable_lookup() to find
9528 					 * an IRE_INTERFACE for the group.
9529 					 * In the multirt case,
9530 					 * ire_lookup_multi() then invokes
9531 					 * ire_multirt_lookup() to find
9532 					 * the next resolvable ire.
9533 					 * As a result, we obtain an new
9534 					 * interface, derived from the
9535 					 * next ire.
9536 					 */
9537 					ipif_refrele(ipif);
9538 					ipif = ipif_lookup_group(ipha_dst,
9539 					    zoneid);
9540 					if (ipif != NULL) {
9541 						mp = copy_mp;
9542 						copy_mp = NULL;
9543 						multirt_resolve_next = B_TRUE;
9544 						continue;
9545 					} else {
9546 						freemsg(copy_mp);
9547 					}
9548 				}
9549 			}
9550 			if (ipif != NULL)
9551 				ipif_refrele(ipif);
9552 			ill_refrele(dst_ill);
9553 			ipif_refrele(src_ipif);
9554 			return;
9555 		default:
9556 			break;
9557 		}
9558 	} while (multirt_resolve_next);
9559 
9560 err_ret:
9561 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9562 	if (fire != NULL)
9563 		ire_refrele(fire);
9564 	ipif_refrele(ipif);
9565 	/* Did this packet originate externally? */
9566 	if (dst_ill != NULL)
9567 		ill_refrele(dst_ill);
9568 	if (src_ipif != NULL)
9569 		ipif_refrele(src_ipif);
9570 	if (mp->b_prev || mp->b_next) {
9571 		mp->b_next = NULL;
9572 		mp->b_prev = NULL;
9573 	} else {
9574 		/*
9575 		 * Since ip_wput() isn't close to finished, we fill
9576 		 * in enough of the header for credible error reporting.
9577 		 */
9578 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9579 			/* Failed */
9580 			freemsg(first_mp);
9581 			if (ire != NULL)
9582 				ire_refrele(ire);
9583 			return;
9584 		}
9585 	}
9586 	/*
9587 	 * At this point we will have ire only if RTF_BLACKHOLE
9588 	 * or RTF_REJECT flags are set on the IRE. It will not
9589 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9590 	 */
9591 	if (ire != NULL) {
9592 		if (ire->ire_flags & RTF_BLACKHOLE) {
9593 			ire_refrele(ire);
9594 			freemsg(first_mp);
9595 			return;
9596 		}
9597 		ire_refrele(ire);
9598 	}
9599 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9600 }
9601 
9602 /* Name/Value Table Lookup Routine */
9603 char *
9604 ip_nv_lookup(nv_t *nv, int value)
9605 {
9606 	if (!nv)
9607 		return (NULL);
9608 	for (; nv->nv_name; nv++) {
9609 		if (nv->nv_value == value)
9610 			return (nv->nv_name);
9611 	}
9612 	return ("unknown");
9613 }
9614 
9615 /*
9616  * one day it can be patched to 1 from /etc/system for machines that have few
9617  * fast network interfaces feeding multiple cpus.
9618  */
9619 int ill_stream_putlocks = 0;
9620 
9621 /*
9622  * This is a module open, i.e. this is a control stream for access
9623  * to a DLPI device.  We allocate an ill_t as the instance data in
9624  * this case.
9625  */
9626 int
9627 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9628 {
9629 	uint32_t mem_cnt;
9630 	uint32_t cpu_cnt;
9631 	uint32_t min_cnt;
9632 	pgcnt_t mem_avail;
9633 	ill_t	*ill;
9634 	int	err;
9635 
9636 	/*
9637 	 * Prevent unprivileged processes from pushing IP so that
9638 	 * they can't send raw IP.
9639 	 */
9640 	if (secpolicy_net_rawaccess(credp) != 0)
9641 		return (EPERM);
9642 
9643 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9644 	q->q_ptr = WR(q)->q_ptr = ill;
9645 
9646 	/*
9647 	 * ill_init initializes the ill fields and then sends down
9648 	 * down a DL_INFO_REQ after calling qprocson.
9649 	 */
9650 	err = ill_init(q, ill);
9651 	if (err != 0) {
9652 		mi_free(ill);
9653 		q->q_ptr = NULL;
9654 		WR(q)->q_ptr = NULL;
9655 		return (err);
9656 	}
9657 
9658 	/* ill_init initializes the ipsq marking this thread as writer */
9659 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9660 	/* Wait for the DL_INFO_ACK */
9661 	mutex_enter(&ill->ill_lock);
9662 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9663 		/*
9664 		 * Return value of 0 indicates a pending signal.
9665 		 */
9666 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9667 		if (err == 0) {
9668 			mutex_exit(&ill->ill_lock);
9669 			(void) ip_close(q, 0);
9670 			return (EINTR);
9671 		}
9672 	}
9673 	mutex_exit(&ill->ill_lock);
9674 
9675 	/*
9676 	 * ip_rput_other could have set an error  in ill_error on
9677 	 * receipt of M_ERROR.
9678 	 */
9679 
9680 	err = ill->ill_error;
9681 	if (err != 0) {
9682 		(void) ip_close(q, 0);
9683 		return (err);
9684 	}
9685 
9686 	/*
9687 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9688 	 * size and the cpu speed of the machine. This is upper
9689 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9690 	 * and is lower bounded by the compile time value of
9691 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9692 	 * ip6_ire_max_bucket_cnt.
9693 	 */
9694 	mem_avail = kmem_avail();
9695 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9696 	    ip_cache_table_size / sizeof (ire_t);
9697 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9698 
9699 	min_cnt = MIN(cpu_cnt, mem_cnt);
9700 	if (min_cnt < ip_ire_min_bucket_cnt)
9701 		min_cnt = ip_ire_min_bucket_cnt;
9702 	if (ip_ire_max_bucket_cnt > min_cnt) {
9703 		ip_ire_max_bucket_cnt = min_cnt;
9704 	}
9705 
9706 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9707 	    ip6_cache_table_size / sizeof (ire_t);
9708 	min_cnt = MIN(cpu_cnt, mem_cnt);
9709 	if (min_cnt < ip6_ire_min_bucket_cnt)
9710 		min_cnt = ip6_ire_min_bucket_cnt;
9711 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9712 		ip6_ire_max_bucket_cnt = min_cnt;
9713 	}
9714 
9715 	ill->ill_credp = credp;
9716 	crhold(credp);
9717 
9718 	mutex_enter(&ip_mi_lock);
9719 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9720 	mutex_exit(&ip_mi_lock);
9721 	if (err) {
9722 		(void) ip_close(q, 0);
9723 		return (err);
9724 	}
9725 	return (0);
9726 }
9727 
9728 /* IP open routine. */
9729 int
9730 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9731 {
9732 	conn_t 		*connp;
9733 	major_t		maj;
9734 
9735 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9736 
9737 	/* Allow reopen. */
9738 	if (q->q_ptr != NULL)
9739 		return (0);
9740 
9741 	if (sflag & MODOPEN) {
9742 		/* This is a module open */
9743 		return (ip_modopen(q, devp, flag, sflag, credp));
9744 	}
9745 
9746 	/*
9747 	 * We are opening as a device. This is an IP client stream, and we
9748 	 * allocate an conn_t as the instance data.
9749 	 */
9750 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9751 	connp->conn_upq = q;
9752 	q->q_ptr = WR(q)->q_ptr = connp;
9753 
9754 	if (flag & SO_SOCKSTR)
9755 		connp->conn_flags |= IPCL_SOCKET;
9756 
9757 	/* Minor tells us which /dev entry was opened */
9758 	if (geteminor(*devp) == IPV6_MINOR) {
9759 		connp->conn_flags |= IPCL_ISV6;
9760 		connp->conn_af_isv6 = B_TRUE;
9761 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9762 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9763 	} else {
9764 		connp->conn_af_isv6 = B_FALSE;
9765 		connp->conn_pkt_isv6 = B_FALSE;
9766 	}
9767 
9768 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9769 		q->q_ptr = WR(q)->q_ptr = NULL;
9770 		CONN_DEC_REF(connp);
9771 		return (EBUSY);
9772 	}
9773 
9774 	maj = getemajor(*devp);
9775 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9776 
9777 	/*
9778 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9779 	 */
9780 	connp->conn_cred = credp;
9781 	crhold(connp->conn_cred);
9782 
9783 	/*
9784 	 * If the caller has the process-wide flag set, then default to MAC
9785 	 * exempt mode.  This allows read-down to unlabeled hosts.
9786 	 */
9787 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9788 		connp->conn_mac_exempt = B_TRUE;
9789 
9790 	connp->conn_zoneid = getzoneid();
9791 
9792 	/*
9793 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9794 	 * administrative ops.  In these cases, we just need a normal conn_t
9795 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9796 	 * an error will be returned.
9797 	 */
9798 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9799 		connp->conn_rq = q;
9800 		connp->conn_wq = WR(q);
9801 	} else {
9802 		connp->conn_ulp = IPPROTO_SCTP;
9803 		connp->conn_rq = connp->conn_wq = NULL;
9804 	}
9805 	/* Non-zero default values */
9806 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9807 
9808 	/*
9809 	 * Make the conn globally visible to walkers
9810 	 */
9811 	mutex_enter(&connp->conn_lock);
9812 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9813 	mutex_exit(&connp->conn_lock);
9814 	ASSERT(connp->conn_ref == 1);
9815 
9816 	qprocson(q);
9817 
9818 	return (0);
9819 }
9820 
9821 /*
9822  * Change q_qinfo based on the value of isv6.
9823  * This can not called on an ill queue.
9824  * Note that there is no race since either q_qinfo works for conn queues - it
9825  * is just an optimization to enter the best wput routine directly.
9826  */
9827 void
9828 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9829 {
9830 	ASSERT(q->q_flag & QREADR);
9831 	ASSERT(WR(q)->q_next == NULL);
9832 	ASSERT(q->q_ptr != NULL);
9833 
9834 	if (minor == IPV6_MINOR)  {
9835 		if (bump_mib)
9836 			BUMP_MIB(&ip6_mib, ipIfStatsOutSwitchIPVersion);
9837 		q->q_qinfo = &rinit_ipv6;
9838 		WR(q)->q_qinfo = &winit_ipv6;
9839 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9840 	} else {
9841 		if (bump_mib)
9842 			BUMP_MIB(&ip_mib, ipIfStatsOutSwitchIPVersion);
9843 		q->q_qinfo = &iprinit;
9844 		WR(q)->q_qinfo = &ipwinit;
9845 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9846 	}
9847 
9848 }
9849 
9850 /*
9851  * See if IPsec needs loading because of the options in mp.
9852  */
9853 static boolean_t
9854 ipsec_opt_present(mblk_t *mp)
9855 {
9856 	uint8_t *optcp, *next_optcp, *opt_endcp;
9857 	struct opthdr *opt;
9858 	struct T_opthdr *topt;
9859 	int opthdr_len;
9860 	t_uscalar_t optname, optlevel;
9861 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9862 	ipsec_req_t *ipsr;
9863 
9864 	/*
9865 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9866 	 * return TRUE.
9867 	 */
9868 
9869 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9870 	opt_endcp = optcp + tor->OPT_length;
9871 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9872 		opthdr_len = sizeof (struct T_opthdr);
9873 	} else {		/* O_OPTMGMT_REQ */
9874 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9875 		opthdr_len = sizeof (struct opthdr);
9876 	}
9877 	for (; optcp < opt_endcp; optcp = next_optcp) {
9878 		if (optcp + opthdr_len > opt_endcp)
9879 			return (B_FALSE);	/* Not enough option header. */
9880 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9881 			topt = (struct T_opthdr *)optcp;
9882 			optlevel = topt->level;
9883 			optname = topt->name;
9884 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9885 		} else {
9886 			opt = (struct opthdr *)optcp;
9887 			optlevel = opt->level;
9888 			optname = opt->name;
9889 			next_optcp = optcp + opthdr_len +
9890 			    _TPI_ALIGN_OPT(opt->len);
9891 		}
9892 		if ((next_optcp < optcp) || /* wraparound pointer space */
9893 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9894 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9895 			return (B_FALSE); /* bad option buffer */
9896 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9897 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9898 			/*
9899 			 * Check to see if it's an all-bypass or all-zeroes
9900 			 * IPsec request.  Don't bother loading IPsec if
9901 			 * the socket doesn't want to use it.  (A good example
9902 			 * is a bypass request.)
9903 			 *
9904 			 * Basically, if any of the non-NEVER bits are set,
9905 			 * load IPsec.
9906 			 */
9907 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9908 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9909 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9910 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9911 			    != 0)
9912 				return (B_TRUE);
9913 		}
9914 	}
9915 	return (B_FALSE);
9916 }
9917 
9918 /*
9919  * If conn is is waiting for ipsec to finish loading, kick it.
9920  */
9921 /* ARGSUSED */
9922 static void
9923 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9924 {
9925 	t_scalar_t	optreq_prim;
9926 	mblk_t		*mp;
9927 	cred_t		*cr;
9928 	int		err = 0;
9929 
9930 	/*
9931 	 * This function is called, after ipsec loading is complete.
9932 	 * Since IP checks exclusively and atomically (i.e it prevents
9933 	 * ipsec load from completing until ip_optcom_req completes)
9934 	 * whether ipsec load is complete, there cannot be a race with IP
9935 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9936 	 */
9937 	mutex_enter(&connp->conn_lock);
9938 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9939 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9940 		mp = connp->conn_ipsec_opt_mp;
9941 		connp->conn_ipsec_opt_mp = NULL;
9942 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9943 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9944 		mutex_exit(&connp->conn_lock);
9945 
9946 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9947 
9948 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9949 		if (optreq_prim == T_OPTMGMT_REQ) {
9950 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9951 			    &ip_opt_obj);
9952 		} else {
9953 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9954 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9955 			    &ip_opt_obj);
9956 		}
9957 		if (err != EINPROGRESS)
9958 			CONN_OPER_PENDING_DONE(connp);
9959 		return;
9960 	}
9961 	mutex_exit(&connp->conn_lock);
9962 }
9963 
9964 /*
9965  * Called from the ipsec_loader thread, outside any perimeter, to tell
9966  * ip qenable any of the queues waiting for the ipsec loader to
9967  * complete.
9968  *
9969  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9970  * are done with this lock held, so it's guaranteed that none of the
9971  * links will change along the way.
9972  */
9973 void
9974 ip_ipsec_load_complete()
9975 {
9976 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9977 }
9978 
9979 /*
9980  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9981  * determines the grp on which it has to become exclusive, queues the mp
9982  * and sq draining restarts the optmgmt
9983  */
9984 static boolean_t
9985 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9986 {
9987 	conn_t *connp;
9988 
9989 	/*
9990 	 * Take IPsec requests and treat them special.
9991 	 */
9992 	if (ipsec_opt_present(mp)) {
9993 		/* First check if IPsec is loaded. */
9994 		mutex_enter(&ipsec_loader_lock);
9995 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9996 			mutex_exit(&ipsec_loader_lock);
9997 			return (B_FALSE);
9998 		}
9999 		connp = Q_TO_CONN(q);
10000 		mutex_enter(&connp->conn_lock);
10001 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10002 
10003 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10004 		connp->conn_ipsec_opt_mp = mp;
10005 		mutex_exit(&connp->conn_lock);
10006 		mutex_exit(&ipsec_loader_lock);
10007 
10008 		ipsec_loader_loadnow();
10009 		return (B_TRUE);
10010 	}
10011 	return (B_FALSE);
10012 }
10013 
10014 /*
10015  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10016  * all of them are copied to the conn_t. If the req is "zero", the policy is
10017  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10018  * fields.
10019  * We keep only the latest setting of the policy and thus policy setting
10020  * is not incremental/cumulative.
10021  *
10022  * Requests to set policies with multiple alternative actions will
10023  * go through a different API.
10024  */
10025 int
10026 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10027 {
10028 	uint_t ah_req = 0;
10029 	uint_t esp_req = 0;
10030 	uint_t se_req = 0;
10031 	ipsec_selkey_t sel;
10032 	ipsec_act_t *actp = NULL;
10033 	uint_t nact;
10034 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10035 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10036 	ipsec_policy_root_t *pr;
10037 	ipsec_policy_head_t *ph;
10038 	int fam;
10039 	boolean_t is_pol_reset;
10040 	int error = 0;
10041 
10042 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10043 
10044 	/*
10045 	 * The IP_SEC_OPT option does not allow variable length parameters,
10046 	 * hence a request cannot be NULL.
10047 	 */
10048 	if (req == NULL)
10049 		return (EINVAL);
10050 
10051 	ah_req = req->ipsr_ah_req;
10052 	esp_req = req->ipsr_esp_req;
10053 	se_req = req->ipsr_self_encap_req;
10054 
10055 	/*
10056 	 * Are we dealing with a request to reset the policy (i.e.
10057 	 * zero requests).
10058 	 */
10059 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10060 	    (esp_req & REQ_MASK) == 0 &&
10061 	    (se_req & REQ_MASK) == 0);
10062 
10063 	if (!is_pol_reset) {
10064 		/*
10065 		 * If we couldn't load IPsec, fail with "protocol
10066 		 * not supported".
10067 		 * IPsec may not have been loaded for a request with zero
10068 		 * policies, so we don't fail in this case.
10069 		 */
10070 		mutex_enter(&ipsec_loader_lock);
10071 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10072 			mutex_exit(&ipsec_loader_lock);
10073 			return (EPROTONOSUPPORT);
10074 		}
10075 		mutex_exit(&ipsec_loader_lock);
10076 
10077 		/*
10078 		 * Test for valid requests. Invalid algorithms
10079 		 * need to be tested by IPSEC code because new
10080 		 * algorithms can be added dynamically.
10081 		 */
10082 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10083 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10084 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10085 			return (EINVAL);
10086 		}
10087 
10088 		/*
10089 		 * Only privileged users can issue these
10090 		 * requests.
10091 		 */
10092 		if (((ah_req & IPSEC_PREF_NEVER) ||
10093 		    (esp_req & IPSEC_PREF_NEVER) ||
10094 		    (se_req & IPSEC_PREF_NEVER)) &&
10095 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10096 			return (EPERM);
10097 		}
10098 
10099 		/*
10100 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10101 		 * are mutually exclusive.
10102 		 */
10103 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10104 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10105 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10106 			/* Both of them are set */
10107 			return (EINVAL);
10108 		}
10109 	}
10110 
10111 	mutex_enter(&connp->conn_lock);
10112 
10113 	/*
10114 	 * If we have already cached policies in ip_bind_connected*(), don't
10115 	 * let them change now. We cache policies for connections
10116 	 * whose src,dst [addr, port] is known.
10117 	 */
10118 	if (connp->conn_policy_cached) {
10119 		mutex_exit(&connp->conn_lock);
10120 		return (EINVAL);
10121 	}
10122 
10123 	/*
10124 	 * We have a zero policies, reset the connection policy if already
10125 	 * set. This will cause the connection to inherit the
10126 	 * global policy, if any.
10127 	 */
10128 	if (is_pol_reset) {
10129 		if (connp->conn_policy != NULL) {
10130 			IPPH_REFRELE(connp->conn_policy);
10131 			connp->conn_policy = NULL;
10132 		}
10133 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10134 		connp->conn_in_enforce_policy = B_FALSE;
10135 		connp->conn_out_enforce_policy = B_FALSE;
10136 		mutex_exit(&connp->conn_lock);
10137 		return (0);
10138 	}
10139 
10140 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10141 	if (ph == NULL)
10142 		goto enomem;
10143 
10144 	ipsec_actvec_from_req(req, &actp, &nact);
10145 	if (actp == NULL)
10146 		goto enomem;
10147 
10148 	/*
10149 	 * Always allocate IPv4 policy entries, since they can also
10150 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10151 	 */
10152 	bzero(&sel, sizeof (sel));
10153 	sel.ipsl_valid = IPSL_IPV4;
10154 
10155 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10156 	if (pin4 == NULL)
10157 		goto enomem;
10158 
10159 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10160 	if (pout4 == NULL)
10161 		goto enomem;
10162 
10163 	if (connp->conn_pkt_isv6) {
10164 		/*
10165 		 * We're looking at a v6 socket, also allocate the
10166 		 * v6-specific entries...
10167 		 */
10168 		sel.ipsl_valid = IPSL_IPV6;
10169 		pin6 = ipsec_policy_create(&sel, actp, nact,
10170 		    IPSEC_PRIO_SOCKET, NULL);
10171 		if (pin6 == NULL)
10172 			goto enomem;
10173 
10174 		pout6 = ipsec_policy_create(&sel, actp, nact,
10175 		    IPSEC_PRIO_SOCKET, NULL);
10176 		if (pout6 == NULL)
10177 			goto enomem;
10178 
10179 		/*
10180 		 * .. and file them away in the right place.
10181 		 */
10182 		fam = IPSEC_AF_V6;
10183 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10184 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10185 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10186 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10187 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10188 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10189 	}
10190 
10191 	ipsec_actvec_free(actp, nact);
10192 
10193 	/*
10194 	 * File the v4 policies.
10195 	 */
10196 	fam = IPSEC_AF_V4;
10197 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10198 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10199 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10200 
10201 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10202 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10203 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10204 
10205 	/*
10206 	 * If the requests need security, set enforce_policy.
10207 	 * If the requests are IPSEC_PREF_NEVER, one should
10208 	 * still set conn_out_enforce_policy so that an ipsec_out
10209 	 * gets attached in ip_wput. This is needed so that
10210 	 * for connections that we don't cache policy in ip_bind,
10211 	 * if global policy matches in ip_wput_attach_policy, we
10212 	 * don't wrongly inherit global policy. Similarly, we need
10213 	 * to set conn_in_enforce_policy also so that we don't verify
10214 	 * policy wrongly.
10215 	 */
10216 	if ((ah_req & REQ_MASK) != 0 ||
10217 	    (esp_req & REQ_MASK) != 0 ||
10218 	    (se_req & REQ_MASK) != 0) {
10219 		connp->conn_in_enforce_policy = B_TRUE;
10220 		connp->conn_out_enforce_policy = B_TRUE;
10221 		connp->conn_flags |= IPCL_CHECK_POLICY;
10222 	}
10223 
10224 	mutex_exit(&connp->conn_lock);
10225 	return (error);
10226 #undef REQ_MASK
10227 
10228 	/*
10229 	 * Common memory-allocation-failure exit path.
10230 	 */
10231 enomem:
10232 	mutex_exit(&connp->conn_lock);
10233 	if (actp != NULL)
10234 		ipsec_actvec_free(actp, nact);
10235 	if (pin4 != NULL)
10236 		IPPOL_REFRELE(pin4);
10237 	if (pout4 != NULL)
10238 		IPPOL_REFRELE(pout4);
10239 	if (pin6 != NULL)
10240 		IPPOL_REFRELE(pin6);
10241 	if (pout6 != NULL)
10242 		IPPOL_REFRELE(pout6);
10243 	return (ENOMEM);
10244 }
10245 
10246 /*
10247  * Only for options that pass in an IP addr. Currently only V4 options
10248  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10249  * So this function assumes level is IPPROTO_IP
10250  */
10251 int
10252 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10253     mblk_t *first_mp)
10254 {
10255 	ipif_t *ipif = NULL;
10256 	int error;
10257 	ill_t *ill;
10258 	int zoneid;
10259 
10260 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10261 
10262 	if (addr != INADDR_ANY || checkonly) {
10263 		ASSERT(connp != NULL);
10264 		zoneid = IPCL_ZONEID(connp);
10265 		if (option == IP_NEXTHOP) {
10266 			ipif = ipif_lookup_onlink_addr(addr,
10267 			    connp->conn_zoneid);
10268 		} else {
10269 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10270 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10271 			    &error);
10272 		}
10273 		if (ipif == NULL) {
10274 			if (error == EINPROGRESS)
10275 				return (error);
10276 			else if ((option == IP_MULTICAST_IF) ||
10277 			    (option == IP_NEXTHOP))
10278 				return (EHOSTUNREACH);
10279 			else
10280 				return (EINVAL);
10281 		} else if (checkonly) {
10282 			if (option == IP_MULTICAST_IF) {
10283 				ill = ipif->ipif_ill;
10284 				/* not supported by the virtual network iface */
10285 				if (IS_VNI(ill)) {
10286 					ipif_refrele(ipif);
10287 					return (EINVAL);
10288 				}
10289 			}
10290 			ipif_refrele(ipif);
10291 			return (0);
10292 		}
10293 		ill = ipif->ipif_ill;
10294 		mutex_enter(&connp->conn_lock);
10295 		mutex_enter(&ill->ill_lock);
10296 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10297 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10298 			mutex_exit(&ill->ill_lock);
10299 			mutex_exit(&connp->conn_lock);
10300 			ipif_refrele(ipif);
10301 			return (option == IP_MULTICAST_IF ?
10302 			    EHOSTUNREACH : EINVAL);
10303 		}
10304 	} else {
10305 		mutex_enter(&connp->conn_lock);
10306 	}
10307 
10308 	/* None of the options below are supported on the VNI */
10309 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10310 		mutex_exit(&ill->ill_lock);
10311 		mutex_exit(&connp->conn_lock);
10312 		ipif_refrele(ipif);
10313 		return (EINVAL);
10314 	}
10315 
10316 	switch (option) {
10317 	case IP_DONTFAILOVER_IF:
10318 		/*
10319 		 * This option is used by in.mpathd to ensure
10320 		 * that IPMP probe packets only go out on the
10321 		 * test interfaces. in.mpathd sets this option
10322 		 * on the non-failover interfaces.
10323 		 * For backward compatibility, this option
10324 		 * implicitly sets IP_MULTICAST_IF, as used
10325 		 * be done in bind(), so that ip_wput gets
10326 		 * this ipif to send mcast packets.
10327 		 */
10328 		if (ipif != NULL) {
10329 			ASSERT(addr != INADDR_ANY);
10330 			connp->conn_nofailover_ill = ipif->ipif_ill;
10331 			connp->conn_multicast_ipif = ipif;
10332 		} else {
10333 			ASSERT(addr == INADDR_ANY);
10334 			connp->conn_nofailover_ill = NULL;
10335 			connp->conn_multicast_ipif = NULL;
10336 		}
10337 		break;
10338 
10339 	case IP_MULTICAST_IF:
10340 		connp->conn_multicast_ipif = ipif;
10341 		break;
10342 	case IP_NEXTHOP:
10343 		connp->conn_nexthop_v4 = addr;
10344 		connp->conn_nexthop_set = B_TRUE;
10345 		break;
10346 	}
10347 
10348 	if (ipif != NULL) {
10349 		mutex_exit(&ill->ill_lock);
10350 		mutex_exit(&connp->conn_lock);
10351 		ipif_refrele(ipif);
10352 		return (0);
10353 	}
10354 	mutex_exit(&connp->conn_lock);
10355 	/* We succeded in cleared the option */
10356 	return (0);
10357 }
10358 
10359 /*
10360  * For options that pass in an ifindex specifying the ill. V6 options always
10361  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10362  */
10363 int
10364 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10365     int level, int option, mblk_t *first_mp)
10366 {
10367 	ill_t *ill = NULL;
10368 	int error = 0;
10369 
10370 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10371 	if (ifindex != 0) {
10372 		ASSERT(connp != NULL);
10373 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10374 		    first_mp, ip_restart_optmgmt, &error);
10375 		if (ill != NULL) {
10376 			if (checkonly) {
10377 				/* not supported by the virtual network iface */
10378 				if (IS_VNI(ill)) {
10379 					ill_refrele(ill);
10380 					return (EINVAL);
10381 				}
10382 				ill_refrele(ill);
10383 				return (0);
10384 			}
10385 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10386 			    0, NULL)) {
10387 				ill_refrele(ill);
10388 				ill = NULL;
10389 				mutex_enter(&connp->conn_lock);
10390 				goto setit;
10391 			}
10392 			mutex_enter(&connp->conn_lock);
10393 			mutex_enter(&ill->ill_lock);
10394 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10395 				mutex_exit(&ill->ill_lock);
10396 				mutex_exit(&connp->conn_lock);
10397 				ill_refrele(ill);
10398 				ill = NULL;
10399 				mutex_enter(&connp->conn_lock);
10400 			}
10401 			goto setit;
10402 		} else if (error == EINPROGRESS) {
10403 			return (error);
10404 		} else {
10405 			error = 0;
10406 		}
10407 	}
10408 	mutex_enter(&connp->conn_lock);
10409 setit:
10410 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10411 
10412 	/*
10413 	 * The options below assume that the ILL (if any) transmits and/or
10414 	 * receives traffic. Neither of which is true for the virtual network
10415 	 * interface, so fail setting these on a VNI.
10416 	 */
10417 	if (IS_VNI(ill)) {
10418 		ASSERT(ill != NULL);
10419 		mutex_exit(&ill->ill_lock);
10420 		mutex_exit(&connp->conn_lock);
10421 		ill_refrele(ill);
10422 		return (EINVAL);
10423 	}
10424 
10425 	if (level == IPPROTO_IP) {
10426 		switch (option) {
10427 		case IP_BOUND_IF:
10428 			connp->conn_incoming_ill = ill;
10429 			connp->conn_outgoing_ill = ill;
10430 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10431 			    0 : ifindex;
10432 			break;
10433 
10434 		case IP_XMIT_IF:
10435 			/*
10436 			 * Similar to IP_BOUND_IF, but this only
10437 			 * determines the outgoing interface for
10438 			 * unicast packets. Also no IRE_CACHE entry
10439 			 * is added for the destination of the
10440 			 * outgoing packets. This feature is needed
10441 			 * for mobile IP.
10442 			 */
10443 			connp->conn_xmit_if_ill = ill;
10444 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10445 			    0 : ifindex;
10446 			break;
10447 
10448 		case IP_MULTICAST_IF:
10449 			/*
10450 			 * This option is an internal special. The socket
10451 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10452 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10453 			 * specifies an ifindex and we try first on V6 ill's.
10454 			 * If we don't find one, we they try using on v4 ill's
10455 			 * intenally and we come here.
10456 			 */
10457 			if (!checkonly && ill != NULL) {
10458 				ipif_t	*ipif;
10459 				ipif = ill->ill_ipif;
10460 
10461 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10462 					mutex_exit(&ill->ill_lock);
10463 					mutex_exit(&connp->conn_lock);
10464 					ill_refrele(ill);
10465 					ill = NULL;
10466 					mutex_enter(&connp->conn_lock);
10467 				} else {
10468 					connp->conn_multicast_ipif = ipif;
10469 				}
10470 			}
10471 			break;
10472 		}
10473 	} else {
10474 		switch (option) {
10475 		case IPV6_BOUND_IF:
10476 			connp->conn_incoming_ill = ill;
10477 			connp->conn_outgoing_ill = ill;
10478 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10479 			    0 : ifindex;
10480 			break;
10481 
10482 		case IPV6_BOUND_PIF:
10483 			/*
10484 			 * Limit all transmit to this ill.
10485 			 * Unlike IPV6_BOUND_IF, using this option
10486 			 * prevents load spreading and failover from
10487 			 * happening when the interface is part of the
10488 			 * group. That's why we don't need to remember
10489 			 * the ifindex in orig_bound_ifindex as in
10490 			 * IPV6_BOUND_IF.
10491 			 */
10492 			connp->conn_outgoing_pill = ill;
10493 			break;
10494 
10495 		case IPV6_DONTFAILOVER_IF:
10496 			/*
10497 			 * This option is used by in.mpathd to ensure
10498 			 * that IPMP probe packets only go out on the
10499 			 * test interfaces. in.mpathd sets this option
10500 			 * on the non-failover interfaces.
10501 			 */
10502 			connp->conn_nofailover_ill = ill;
10503 			/*
10504 			 * For backward compatibility, this option
10505 			 * implicitly sets ip_multicast_ill as used in
10506 			 * IP_MULTICAST_IF so that ip_wput gets
10507 			 * this ipif to send mcast packets.
10508 			 */
10509 			connp->conn_multicast_ill = ill;
10510 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10511 			    0 : ifindex;
10512 			break;
10513 
10514 		case IPV6_MULTICAST_IF:
10515 			/*
10516 			 * Set conn_multicast_ill to be the IPv6 ill.
10517 			 * Set conn_multicast_ipif to be an IPv4 ipif
10518 			 * for ifindex to make IPv4 mapped addresses
10519 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10520 			 * Even if no IPv6 ill exists for the ifindex
10521 			 * we need to check for an IPv4 ifindex in order
10522 			 * for this to work with mapped addresses. In that
10523 			 * case only set conn_multicast_ipif.
10524 			 */
10525 			if (!checkonly) {
10526 				if (ifindex == 0) {
10527 					connp->conn_multicast_ill = NULL;
10528 					connp->conn_orig_multicast_ifindex = 0;
10529 					connp->conn_multicast_ipif = NULL;
10530 				} else if (ill != NULL) {
10531 					connp->conn_multicast_ill = ill;
10532 					connp->conn_orig_multicast_ifindex =
10533 					    ifindex;
10534 				}
10535 			}
10536 			break;
10537 		}
10538 	}
10539 
10540 	if (ill != NULL) {
10541 		mutex_exit(&ill->ill_lock);
10542 		mutex_exit(&connp->conn_lock);
10543 		ill_refrele(ill);
10544 		return (0);
10545 	}
10546 	mutex_exit(&connp->conn_lock);
10547 	/*
10548 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10549 	 * locate the ill and could not set the option (ifindex != 0)
10550 	 */
10551 	return (ifindex == 0 ? 0 : EINVAL);
10552 }
10553 
10554 /* This routine sets socket options. */
10555 /* ARGSUSED */
10556 int
10557 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10558     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10559     void *dummy, cred_t *cr, mblk_t *first_mp)
10560 {
10561 	int		*i1 = (int *)invalp;
10562 	conn_t		*connp = Q_TO_CONN(q);
10563 	int		error = 0;
10564 	boolean_t	checkonly;
10565 	ire_t		*ire;
10566 	boolean_t	found;
10567 
10568 	switch (optset_context) {
10569 
10570 	case SETFN_OPTCOM_CHECKONLY:
10571 		checkonly = B_TRUE;
10572 		/*
10573 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10574 		 * inlen != 0 implies value supplied and
10575 		 * 	we have to "pretend" to set it.
10576 		 * inlen == 0 implies that there is no
10577 		 * 	value part in T_CHECK request and just validation
10578 		 * done elsewhere should be enough, we just return here.
10579 		 */
10580 		if (inlen == 0) {
10581 			*outlenp = 0;
10582 			return (0);
10583 		}
10584 		break;
10585 	case SETFN_OPTCOM_NEGOTIATE:
10586 	case SETFN_UD_NEGOTIATE:
10587 	case SETFN_CONN_NEGOTIATE:
10588 		checkonly = B_FALSE;
10589 		break;
10590 	default:
10591 		/*
10592 		 * We should never get here
10593 		 */
10594 		*outlenp = 0;
10595 		return (EINVAL);
10596 	}
10597 
10598 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10599 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10600 
10601 	/*
10602 	 * For fixed length options, no sanity check
10603 	 * of passed in length is done. It is assumed *_optcom_req()
10604 	 * routines do the right thing.
10605 	 */
10606 
10607 	switch (level) {
10608 	case SOL_SOCKET:
10609 		/*
10610 		 * conn_lock protects the bitfields, and is used to
10611 		 * set the fields atomically.
10612 		 */
10613 		switch (name) {
10614 		case SO_BROADCAST:
10615 			if (!checkonly) {
10616 				/* TODO: use value someplace? */
10617 				mutex_enter(&connp->conn_lock);
10618 				connp->conn_broadcast = *i1 ? 1 : 0;
10619 				mutex_exit(&connp->conn_lock);
10620 			}
10621 			break;	/* goto sizeof (int) option return */
10622 		case SO_USELOOPBACK:
10623 			if (!checkonly) {
10624 				/* TODO: use value someplace? */
10625 				mutex_enter(&connp->conn_lock);
10626 				connp->conn_loopback = *i1 ? 1 : 0;
10627 				mutex_exit(&connp->conn_lock);
10628 			}
10629 			break;	/* goto sizeof (int) option return */
10630 		case SO_DONTROUTE:
10631 			if (!checkonly) {
10632 				mutex_enter(&connp->conn_lock);
10633 				connp->conn_dontroute = *i1 ? 1 : 0;
10634 				mutex_exit(&connp->conn_lock);
10635 			}
10636 			break;	/* goto sizeof (int) option return */
10637 		case SO_REUSEADDR:
10638 			if (!checkonly) {
10639 				mutex_enter(&connp->conn_lock);
10640 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10641 				mutex_exit(&connp->conn_lock);
10642 			}
10643 			break;	/* goto sizeof (int) option return */
10644 		case SO_PROTOTYPE:
10645 			if (!checkonly) {
10646 				mutex_enter(&connp->conn_lock);
10647 				connp->conn_proto = *i1;
10648 				mutex_exit(&connp->conn_lock);
10649 			}
10650 			break;	/* goto sizeof (int) option return */
10651 		case SO_ALLZONES:
10652 			if (!checkonly) {
10653 				mutex_enter(&connp->conn_lock);
10654 				if (IPCL_IS_BOUND(connp)) {
10655 					mutex_exit(&connp->conn_lock);
10656 					return (EINVAL);
10657 				}
10658 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10659 				mutex_exit(&connp->conn_lock);
10660 			}
10661 			break;	/* goto sizeof (int) option return */
10662 		case SO_ANON_MLP:
10663 			if (!checkonly) {
10664 				mutex_enter(&connp->conn_lock);
10665 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10666 				mutex_exit(&connp->conn_lock);
10667 			}
10668 			break;	/* goto sizeof (int) option return */
10669 		case SO_MAC_EXEMPT:
10670 			if (secpolicy_net_mac_aware(cr) != 0 ||
10671 			    IPCL_IS_BOUND(connp))
10672 				return (EACCES);
10673 			if (!checkonly) {
10674 				mutex_enter(&connp->conn_lock);
10675 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10676 				mutex_exit(&connp->conn_lock);
10677 			}
10678 			break;	/* goto sizeof (int) option return */
10679 		default:
10680 			/*
10681 			 * "soft" error (negative)
10682 			 * option not handled at this level
10683 			 * Note: Do not modify *outlenp
10684 			 */
10685 			return (-EINVAL);
10686 		}
10687 		break;
10688 	case IPPROTO_IP:
10689 		switch (name) {
10690 		case IP_NEXTHOP:
10691 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10692 				return (EPERM);
10693 			/* FALLTHRU */
10694 		case IP_MULTICAST_IF:
10695 		case IP_DONTFAILOVER_IF: {
10696 			ipaddr_t addr = *i1;
10697 
10698 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10699 			    first_mp);
10700 			if (error != 0)
10701 				return (error);
10702 			break;	/* goto sizeof (int) option return */
10703 		}
10704 
10705 		case IP_MULTICAST_TTL:
10706 			/* Recorded in transport above IP */
10707 			*outvalp = *invalp;
10708 			*outlenp = sizeof (uchar_t);
10709 			return (0);
10710 		case IP_MULTICAST_LOOP:
10711 			if (!checkonly) {
10712 				mutex_enter(&connp->conn_lock);
10713 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10714 				mutex_exit(&connp->conn_lock);
10715 			}
10716 			*outvalp = *invalp;
10717 			*outlenp = sizeof (uchar_t);
10718 			return (0);
10719 		case IP_ADD_MEMBERSHIP:
10720 		case MCAST_JOIN_GROUP:
10721 		case IP_DROP_MEMBERSHIP:
10722 		case MCAST_LEAVE_GROUP: {
10723 			struct ip_mreq *mreqp;
10724 			struct group_req *greqp;
10725 			ire_t *ire;
10726 			boolean_t done = B_FALSE;
10727 			ipaddr_t group, ifaddr;
10728 			struct sockaddr_in *sin;
10729 			uint32_t *ifindexp;
10730 			boolean_t mcast_opt = B_TRUE;
10731 			mcast_record_t fmode;
10732 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10733 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10734 
10735 			switch (name) {
10736 			case IP_ADD_MEMBERSHIP:
10737 				mcast_opt = B_FALSE;
10738 				/* FALLTHRU */
10739 			case MCAST_JOIN_GROUP:
10740 				fmode = MODE_IS_EXCLUDE;
10741 				optfn = ip_opt_add_group;
10742 				break;
10743 
10744 			case IP_DROP_MEMBERSHIP:
10745 				mcast_opt = B_FALSE;
10746 				/* FALLTHRU */
10747 			case MCAST_LEAVE_GROUP:
10748 				fmode = MODE_IS_INCLUDE;
10749 				optfn = ip_opt_delete_group;
10750 				break;
10751 			}
10752 
10753 			if (mcast_opt) {
10754 				greqp = (struct group_req *)i1;
10755 				sin = (struct sockaddr_in *)&greqp->gr_group;
10756 				if (sin->sin_family != AF_INET) {
10757 					*outlenp = 0;
10758 					return (ENOPROTOOPT);
10759 				}
10760 				group = (ipaddr_t)sin->sin_addr.s_addr;
10761 				ifaddr = INADDR_ANY;
10762 				ifindexp = &greqp->gr_interface;
10763 			} else {
10764 				mreqp = (struct ip_mreq *)i1;
10765 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10766 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10767 				ifindexp = NULL;
10768 			}
10769 
10770 			/*
10771 			 * In the multirouting case, we need to replicate
10772 			 * the request on all interfaces that will take part
10773 			 * in replication.  We do so because multirouting is
10774 			 * reflective, thus we will probably receive multi-
10775 			 * casts on those interfaces.
10776 			 * The ip_multirt_apply_membership() succeeds if the
10777 			 * operation succeeds on at least one interface.
10778 			 */
10779 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10780 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10781 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10782 			if (ire != NULL) {
10783 				if (ire->ire_flags & RTF_MULTIRT) {
10784 					error = ip_multirt_apply_membership(
10785 					    optfn, ire, connp, checkonly, group,
10786 					    fmode, INADDR_ANY, first_mp);
10787 					done = B_TRUE;
10788 				}
10789 				ire_refrele(ire);
10790 			}
10791 			if (!done) {
10792 				error = optfn(connp, checkonly, group, ifaddr,
10793 				    ifindexp, fmode, INADDR_ANY, first_mp);
10794 			}
10795 			if (error) {
10796 				/*
10797 				 * EINPROGRESS is a soft error, needs retry
10798 				 * so don't make *outlenp zero.
10799 				 */
10800 				if (error != EINPROGRESS)
10801 					*outlenp = 0;
10802 				return (error);
10803 			}
10804 			/* OK return - copy input buffer into output buffer */
10805 			if (invalp != outvalp) {
10806 				/* don't trust bcopy for identical src/dst */
10807 				bcopy(invalp, outvalp, inlen);
10808 			}
10809 			*outlenp = inlen;
10810 			return (0);
10811 		}
10812 		case IP_BLOCK_SOURCE:
10813 		case IP_UNBLOCK_SOURCE:
10814 		case IP_ADD_SOURCE_MEMBERSHIP:
10815 		case IP_DROP_SOURCE_MEMBERSHIP:
10816 		case MCAST_BLOCK_SOURCE:
10817 		case MCAST_UNBLOCK_SOURCE:
10818 		case MCAST_JOIN_SOURCE_GROUP:
10819 		case MCAST_LEAVE_SOURCE_GROUP: {
10820 			struct ip_mreq_source *imreqp;
10821 			struct group_source_req *gsreqp;
10822 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10823 			uint32_t ifindex = 0;
10824 			mcast_record_t fmode;
10825 			struct sockaddr_in *sin;
10826 			ire_t *ire;
10827 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10828 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10829 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10830 
10831 			switch (name) {
10832 			case IP_BLOCK_SOURCE:
10833 				mcast_opt = B_FALSE;
10834 				/* FALLTHRU */
10835 			case MCAST_BLOCK_SOURCE:
10836 				fmode = MODE_IS_EXCLUDE;
10837 				optfn = ip_opt_add_group;
10838 				break;
10839 
10840 			case IP_UNBLOCK_SOURCE:
10841 				mcast_opt = B_FALSE;
10842 				/* FALLTHRU */
10843 			case MCAST_UNBLOCK_SOURCE:
10844 				fmode = MODE_IS_EXCLUDE;
10845 				optfn = ip_opt_delete_group;
10846 				break;
10847 
10848 			case IP_ADD_SOURCE_MEMBERSHIP:
10849 				mcast_opt = B_FALSE;
10850 				/* FALLTHRU */
10851 			case MCAST_JOIN_SOURCE_GROUP:
10852 				fmode = MODE_IS_INCLUDE;
10853 				optfn = ip_opt_add_group;
10854 				break;
10855 
10856 			case IP_DROP_SOURCE_MEMBERSHIP:
10857 				mcast_opt = B_FALSE;
10858 				/* FALLTHRU */
10859 			case MCAST_LEAVE_SOURCE_GROUP:
10860 				fmode = MODE_IS_INCLUDE;
10861 				optfn = ip_opt_delete_group;
10862 				break;
10863 			}
10864 
10865 			if (mcast_opt) {
10866 				gsreqp = (struct group_source_req *)i1;
10867 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10868 					*outlenp = 0;
10869 					return (ENOPROTOOPT);
10870 				}
10871 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10872 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10873 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10874 				src = (ipaddr_t)sin->sin_addr.s_addr;
10875 				ifindex = gsreqp->gsr_interface;
10876 			} else {
10877 				imreqp = (struct ip_mreq_source *)i1;
10878 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10879 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10880 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10881 			}
10882 
10883 			/*
10884 			 * In the multirouting case, we need to replicate
10885 			 * the request as noted in the mcast cases above.
10886 			 */
10887 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10888 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10889 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10890 			if (ire != NULL) {
10891 				if (ire->ire_flags & RTF_MULTIRT) {
10892 					error = ip_multirt_apply_membership(
10893 					    optfn, ire, connp, checkonly, grp,
10894 					    fmode, src, first_mp);
10895 					done = B_TRUE;
10896 				}
10897 				ire_refrele(ire);
10898 			}
10899 			if (!done) {
10900 				error = optfn(connp, checkonly, grp, ifaddr,
10901 				    &ifindex, fmode, src, first_mp);
10902 			}
10903 			if (error != 0) {
10904 				/*
10905 				 * EINPROGRESS is a soft error, needs retry
10906 				 * so don't make *outlenp zero.
10907 				 */
10908 				if (error != EINPROGRESS)
10909 					*outlenp = 0;
10910 				return (error);
10911 			}
10912 			/* OK return - copy input buffer into output buffer */
10913 			if (invalp != outvalp) {
10914 				bcopy(invalp, outvalp, inlen);
10915 			}
10916 			*outlenp = inlen;
10917 			return (0);
10918 		}
10919 		case IP_SEC_OPT:
10920 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10921 			if (error != 0) {
10922 				*outlenp = 0;
10923 				return (error);
10924 			}
10925 			break;
10926 		case IP_HDRINCL:
10927 		case IP_OPTIONS:
10928 		case T_IP_OPTIONS:
10929 		case IP_TOS:
10930 		case T_IP_TOS:
10931 		case IP_TTL:
10932 		case IP_RECVDSTADDR:
10933 		case IP_RECVOPTS:
10934 			/* OK return - copy input buffer into output buffer */
10935 			if (invalp != outvalp) {
10936 				/* don't trust bcopy for identical src/dst */
10937 				bcopy(invalp, outvalp, inlen);
10938 			}
10939 			*outlenp = inlen;
10940 			return (0);
10941 		case IP_RECVIF:
10942 			/* Retrieve the inbound interface index */
10943 			if (!checkonly) {
10944 				mutex_enter(&connp->conn_lock);
10945 				connp->conn_recvif = *i1 ? 1 : 0;
10946 				mutex_exit(&connp->conn_lock);
10947 			}
10948 			break;	/* goto sizeof (int) option return */
10949 		case IP_RECVSLLA:
10950 			/* Retrieve the source link layer address */
10951 			if (!checkonly) {
10952 				mutex_enter(&connp->conn_lock);
10953 				connp->conn_recvslla = *i1 ? 1 : 0;
10954 				mutex_exit(&connp->conn_lock);
10955 			}
10956 			break;	/* goto sizeof (int) option return */
10957 		case MRT_INIT:
10958 		case MRT_DONE:
10959 		case MRT_ADD_VIF:
10960 		case MRT_DEL_VIF:
10961 		case MRT_ADD_MFC:
10962 		case MRT_DEL_MFC:
10963 		case MRT_ASSERT:
10964 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10965 				*outlenp = 0;
10966 				return (error);
10967 			}
10968 			error = ip_mrouter_set((int)name, q, checkonly,
10969 			    (uchar_t *)invalp, inlen, first_mp);
10970 			if (error) {
10971 				*outlenp = 0;
10972 				return (error);
10973 			}
10974 			/* OK return - copy input buffer into output buffer */
10975 			if (invalp != outvalp) {
10976 				/* don't trust bcopy for identical src/dst */
10977 				bcopy(invalp, outvalp, inlen);
10978 			}
10979 			*outlenp = inlen;
10980 			return (0);
10981 		case IP_BOUND_IF:
10982 		case IP_XMIT_IF:
10983 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10984 			    level, name, first_mp);
10985 			if (error != 0)
10986 				return (error);
10987 			break; 		/* goto sizeof (int) option return */
10988 
10989 		case IP_UNSPEC_SRC:
10990 			/* Allow sending with a zero source address */
10991 			if (!checkonly) {
10992 				mutex_enter(&connp->conn_lock);
10993 				connp->conn_unspec_src = *i1 ? 1 : 0;
10994 				mutex_exit(&connp->conn_lock);
10995 			}
10996 			break;	/* goto sizeof (int) option return */
10997 		default:
10998 			/*
10999 			 * "soft" error (negative)
11000 			 * option not handled at this level
11001 			 * Note: Do not modify *outlenp
11002 			 */
11003 			return (-EINVAL);
11004 		}
11005 		break;
11006 	case IPPROTO_IPV6:
11007 		switch (name) {
11008 		case IPV6_BOUND_IF:
11009 		case IPV6_BOUND_PIF:
11010 		case IPV6_DONTFAILOVER_IF:
11011 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11012 			    level, name, first_mp);
11013 			if (error != 0)
11014 				return (error);
11015 			break; 		/* goto sizeof (int) option return */
11016 
11017 		case IPV6_MULTICAST_IF:
11018 			/*
11019 			 * The only possible errors are EINPROGRESS and
11020 			 * EINVAL. EINPROGRESS will be restarted and is not
11021 			 * a hard error. We call this option on both V4 and V6
11022 			 * If both return EINVAL, then this call returns
11023 			 * EINVAL. If at least one of them succeeds we
11024 			 * return success.
11025 			 */
11026 			found = B_FALSE;
11027 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11028 			    level, name, first_mp);
11029 			if (error == EINPROGRESS)
11030 				return (error);
11031 			if (error == 0)
11032 				found = B_TRUE;
11033 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11034 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11035 			if (error == 0)
11036 				found = B_TRUE;
11037 			if (!found)
11038 				return (error);
11039 			break; 		/* goto sizeof (int) option return */
11040 
11041 		case IPV6_MULTICAST_HOPS:
11042 			/* Recorded in transport above IP */
11043 			break;	/* goto sizeof (int) option return */
11044 		case IPV6_MULTICAST_LOOP:
11045 			if (!checkonly) {
11046 				mutex_enter(&connp->conn_lock);
11047 				connp->conn_multicast_loop = *i1;
11048 				mutex_exit(&connp->conn_lock);
11049 			}
11050 			break;	/* goto sizeof (int) option return */
11051 		case IPV6_JOIN_GROUP:
11052 		case MCAST_JOIN_GROUP:
11053 		case IPV6_LEAVE_GROUP:
11054 		case MCAST_LEAVE_GROUP: {
11055 			struct ipv6_mreq *ip_mreqp;
11056 			struct group_req *greqp;
11057 			ire_t *ire;
11058 			boolean_t done = B_FALSE;
11059 			in6_addr_t groupv6;
11060 			uint32_t ifindex;
11061 			boolean_t mcast_opt = B_TRUE;
11062 			mcast_record_t fmode;
11063 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11064 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11065 
11066 			switch (name) {
11067 			case IPV6_JOIN_GROUP:
11068 				mcast_opt = B_FALSE;
11069 				/* FALLTHRU */
11070 			case MCAST_JOIN_GROUP:
11071 				fmode = MODE_IS_EXCLUDE;
11072 				optfn = ip_opt_add_group_v6;
11073 				break;
11074 
11075 			case IPV6_LEAVE_GROUP:
11076 				mcast_opt = B_FALSE;
11077 				/* FALLTHRU */
11078 			case MCAST_LEAVE_GROUP:
11079 				fmode = MODE_IS_INCLUDE;
11080 				optfn = ip_opt_delete_group_v6;
11081 				break;
11082 			}
11083 
11084 			if (mcast_opt) {
11085 				struct sockaddr_in *sin;
11086 				struct sockaddr_in6 *sin6;
11087 				greqp = (struct group_req *)i1;
11088 				if (greqp->gr_group.ss_family == AF_INET) {
11089 					sin = (struct sockaddr_in *)
11090 					    &(greqp->gr_group);
11091 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11092 					    &groupv6);
11093 				} else {
11094 					sin6 = (struct sockaddr_in6 *)
11095 					    &(greqp->gr_group);
11096 					groupv6 = sin6->sin6_addr;
11097 				}
11098 				ifindex = greqp->gr_interface;
11099 			} else {
11100 				ip_mreqp = (struct ipv6_mreq *)i1;
11101 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11102 				ifindex = ip_mreqp->ipv6mr_interface;
11103 			}
11104 			/*
11105 			 * In the multirouting case, we need to replicate
11106 			 * the request on all interfaces that will take part
11107 			 * in replication.  We do so because multirouting is
11108 			 * reflective, thus we will probably receive multi-
11109 			 * casts on those interfaces.
11110 			 * The ip_multirt_apply_membership_v6() succeeds if
11111 			 * the operation succeeds on at least one interface.
11112 			 */
11113 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11114 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11115 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11116 			if (ire != NULL) {
11117 				if (ire->ire_flags & RTF_MULTIRT) {
11118 					error = ip_multirt_apply_membership_v6(
11119 					    optfn, ire, connp, checkonly,
11120 					    &groupv6, fmode, &ipv6_all_zeros,
11121 					    first_mp);
11122 					done = B_TRUE;
11123 				}
11124 				ire_refrele(ire);
11125 			}
11126 			if (!done) {
11127 				error = optfn(connp, checkonly, &groupv6,
11128 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11129 			}
11130 			if (error) {
11131 				/*
11132 				 * EINPROGRESS is a soft error, needs retry
11133 				 * so don't make *outlenp zero.
11134 				 */
11135 				if (error != EINPROGRESS)
11136 					*outlenp = 0;
11137 				return (error);
11138 			}
11139 			/* OK return - copy input buffer into output buffer */
11140 			if (invalp != outvalp) {
11141 				/* don't trust bcopy for identical src/dst */
11142 				bcopy(invalp, outvalp, inlen);
11143 			}
11144 			*outlenp = inlen;
11145 			return (0);
11146 		}
11147 		case MCAST_BLOCK_SOURCE:
11148 		case MCAST_UNBLOCK_SOURCE:
11149 		case MCAST_JOIN_SOURCE_GROUP:
11150 		case MCAST_LEAVE_SOURCE_GROUP: {
11151 			struct group_source_req *gsreqp;
11152 			in6_addr_t v6grp, v6src;
11153 			uint32_t ifindex;
11154 			mcast_record_t fmode;
11155 			ire_t *ire;
11156 			boolean_t done = B_FALSE;
11157 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11158 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11159 
11160 			switch (name) {
11161 			case MCAST_BLOCK_SOURCE:
11162 				fmode = MODE_IS_EXCLUDE;
11163 				optfn = ip_opt_add_group_v6;
11164 				break;
11165 			case MCAST_UNBLOCK_SOURCE:
11166 				fmode = MODE_IS_EXCLUDE;
11167 				optfn = ip_opt_delete_group_v6;
11168 				break;
11169 			case MCAST_JOIN_SOURCE_GROUP:
11170 				fmode = MODE_IS_INCLUDE;
11171 				optfn = ip_opt_add_group_v6;
11172 				break;
11173 			case MCAST_LEAVE_SOURCE_GROUP:
11174 				fmode = MODE_IS_INCLUDE;
11175 				optfn = ip_opt_delete_group_v6;
11176 				break;
11177 			}
11178 
11179 			gsreqp = (struct group_source_req *)i1;
11180 			ifindex = gsreqp->gsr_interface;
11181 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11182 				struct sockaddr_in *s;
11183 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11184 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11185 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11186 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11187 			} else {
11188 				struct sockaddr_in6 *s6;
11189 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11190 				v6grp = s6->sin6_addr;
11191 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11192 				v6src = s6->sin6_addr;
11193 			}
11194 
11195 			/*
11196 			 * In the multirouting case, we need to replicate
11197 			 * the request as noted in the mcast cases above.
11198 			 */
11199 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11200 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11201 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11202 			if (ire != NULL) {
11203 				if (ire->ire_flags & RTF_MULTIRT) {
11204 					error = ip_multirt_apply_membership_v6(
11205 					    optfn, ire, connp, checkonly,
11206 					    &v6grp, fmode, &v6src, first_mp);
11207 					done = B_TRUE;
11208 				}
11209 				ire_refrele(ire);
11210 			}
11211 			if (!done) {
11212 				error = optfn(connp, checkonly, &v6grp,
11213 				    ifindex, fmode, &v6src, first_mp);
11214 			}
11215 			if (error != 0) {
11216 				/*
11217 				 * EINPROGRESS is a soft error, needs retry
11218 				 * so don't make *outlenp zero.
11219 				 */
11220 				if (error != EINPROGRESS)
11221 					*outlenp = 0;
11222 				return (error);
11223 			}
11224 			/* OK return - copy input buffer into output buffer */
11225 			if (invalp != outvalp) {
11226 				bcopy(invalp, outvalp, inlen);
11227 			}
11228 			*outlenp = inlen;
11229 			return (0);
11230 		}
11231 		case IPV6_UNICAST_HOPS:
11232 			/* Recorded in transport above IP */
11233 			break;	/* goto sizeof (int) option return */
11234 		case IPV6_UNSPEC_SRC:
11235 			/* Allow sending with a zero source address */
11236 			if (!checkonly) {
11237 				mutex_enter(&connp->conn_lock);
11238 				connp->conn_unspec_src = *i1 ? 1 : 0;
11239 				mutex_exit(&connp->conn_lock);
11240 			}
11241 			break;	/* goto sizeof (int) option return */
11242 		case IPV6_RECVPKTINFO:
11243 			if (!checkonly) {
11244 				mutex_enter(&connp->conn_lock);
11245 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11246 				mutex_exit(&connp->conn_lock);
11247 			}
11248 			break;	/* goto sizeof (int) option return */
11249 		case IPV6_RECVTCLASS:
11250 			if (!checkonly) {
11251 				if (*i1 < 0 || *i1 > 1) {
11252 					return (EINVAL);
11253 				}
11254 				mutex_enter(&connp->conn_lock);
11255 				connp->conn_ipv6_recvtclass = *i1;
11256 				mutex_exit(&connp->conn_lock);
11257 			}
11258 			break;
11259 		case IPV6_RECVPATHMTU:
11260 			if (!checkonly) {
11261 				if (*i1 < 0 || *i1 > 1) {
11262 					return (EINVAL);
11263 				}
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_ipv6_recvpathmtu = *i1;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;
11269 		case IPV6_RECVHOPLIMIT:
11270 			if (!checkonly) {
11271 				mutex_enter(&connp->conn_lock);
11272 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11273 				mutex_exit(&connp->conn_lock);
11274 			}
11275 			break;	/* goto sizeof (int) option return */
11276 		case IPV6_RECVHOPOPTS:
11277 			if (!checkonly) {
11278 				mutex_enter(&connp->conn_lock);
11279 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11280 				mutex_exit(&connp->conn_lock);
11281 			}
11282 			break;	/* goto sizeof (int) option return */
11283 		case IPV6_RECVDSTOPTS:
11284 			if (!checkonly) {
11285 				mutex_enter(&connp->conn_lock);
11286 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11287 				mutex_exit(&connp->conn_lock);
11288 			}
11289 			break;	/* goto sizeof (int) option return */
11290 		case IPV6_RECVRTHDR:
11291 			if (!checkonly) {
11292 				mutex_enter(&connp->conn_lock);
11293 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11294 				mutex_exit(&connp->conn_lock);
11295 			}
11296 			break;	/* goto sizeof (int) option return */
11297 		case IPV6_RECVRTHDRDSTOPTS:
11298 			if (!checkonly) {
11299 				mutex_enter(&connp->conn_lock);
11300 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11301 				mutex_exit(&connp->conn_lock);
11302 			}
11303 			break;	/* goto sizeof (int) option return */
11304 		case IPV6_PKTINFO:
11305 			if (inlen == 0)
11306 				return (-EINVAL);	/* clearing option */
11307 			error = ip6_set_pktinfo(cr, connp,
11308 			    (struct in6_pktinfo *)invalp, first_mp);
11309 			if (error != 0)
11310 				*outlenp = 0;
11311 			else
11312 				*outlenp = inlen;
11313 			return (error);
11314 		case IPV6_NEXTHOP: {
11315 			struct sockaddr_in6 *sin6;
11316 
11317 			/* Verify that the nexthop is reachable */
11318 			if (inlen == 0)
11319 				return (-EINVAL);	/* clearing option */
11320 
11321 			sin6 = (struct sockaddr_in6 *)invalp;
11322 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11323 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11324 			    NULL, MATCH_IRE_DEFAULT);
11325 
11326 			if (ire == NULL) {
11327 				*outlenp = 0;
11328 				return (EHOSTUNREACH);
11329 			}
11330 			ire_refrele(ire);
11331 			return (-EINVAL);
11332 		}
11333 		case IPV6_SEC_OPT:
11334 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11335 			if (error != 0) {
11336 				*outlenp = 0;
11337 				return (error);
11338 			}
11339 			break;
11340 		case IPV6_SRC_PREFERENCES: {
11341 			/*
11342 			 * This is implemented strictly in the ip module
11343 			 * (here and in tcp_opt_*() to accomodate tcp
11344 			 * sockets).  Modules above ip pass this option
11345 			 * down here since ip is the only one that needs to
11346 			 * be aware of source address preferences.
11347 			 *
11348 			 * This socket option only affects connected
11349 			 * sockets that haven't already bound to a specific
11350 			 * IPv6 address.  In other words, sockets that
11351 			 * don't call bind() with an address other than the
11352 			 * unspecified address and that call connect().
11353 			 * ip_bind_connected_v6() passes these preferences
11354 			 * to the ipif_select_source_v6() function.
11355 			 */
11356 			if (inlen != sizeof (uint32_t))
11357 				return (EINVAL);
11358 			error = ip6_set_src_preferences(connp,
11359 			    *(uint32_t *)invalp);
11360 			if (error != 0) {
11361 				*outlenp = 0;
11362 				return (error);
11363 			} else {
11364 				*outlenp = sizeof (uint32_t);
11365 			}
11366 			break;
11367 		}
11368 		case IPV6_V6ONLY:
11369 			if (*i1 < 0 || *i1 > 1) {
11370 				return (EINVAL);
11371 			}
11372 			mutex_enter(&connp->conn_lock);
11373 			connp->conn_ipv6_v6only = *i1;
11374 			mutex_exit(&connp->conn_lock);
11375 			break;
11376 		default:
11377 			return (-EINVAL);
11378 		}
11379 		break;
11380 	default:
11381 		/*
11382 		 * "soft" error (negative)
11383 		 * option not handled at this level
11384 		 * Note: Do not modify *outlenp
11385 		 */
11386 		return (-EINVAL);
11387 	}
11388 	/*
11389 	 * Common case of return from an option that is sizeof (int)
11390 	 */
11391 	*(int *)outvalp = *i1;
11392 	*outlenp = sizeof (int);
11393 	return (0);
11394 }
11395 
11396 /*
11397  * This routine gets default values of certain options whose default
11398  * values are maintained by protocol specific code
11399  */
11400 /* ARGSUSED */
11401 int
11402 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11403 {
11404 	int *i1 = (int *)ptr;
11405 
11406 	switch (level) {
11407 	case IPPROTO_IP:
11408 		switch (name) {
11409 		case IP_MULTICAST_TTL:
11410 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11411 			return (sizeof (uchar_t));
11412 		case IP_MULTICAST_LOOP:
11413 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11414 			return (sizeof (uchar_t));
11415 		default:
11416 			return (-1);
11417 		}
11418 	case IPPROTO_IPV6:
11419 		switch (name) {
11420 		case IPV6_UNICAST_HOPS:
11421 			*i1 = ipv6_def_hops;
11422 			return (sizeof (int));
11423 		case IPV6_MULTICAST_HOPS:
11424 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11425 			return (sizeof (int));
11426 		case IPV6_MULTICAST_LOOP:
11427 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11428 			return (sizeof (int));
11429 		case IPV6_V6ONLY:
11430 			*i1 = 1;
11431 			return (sizeof (int));
11432 		default:
11433 			return (-1);
11434 		}
11435 	default:
11436 		return (-1);
11437 	}
11438 	/* NOTREACHED */
11439 }
11440 
11441 /*
11442  * Given a destination address and a pointer to where to put the information
11443  * this routine fills in the mtuinfo.
11444  */
11445 int
11446 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11447     struct ip6_mtuinfo *mtuinfo)
11448 {
11449 	ire_t *ire;
11450 
11451 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11452 		return (-1);
11453 
11454 	bzero(mtuinfo, sizeof (*mtuinfo));
11455 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11456 	mtuinfo->ip6m_addr.sin6_port = port;
11457 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11458 
11459 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11460 	if (ire != NULL) {
11461 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11462 		ire_refrele(ire);
11463 	} else {
11464 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11465 	}
11466 	return (sizeof (struct ip6_mtuinfo));
11467 }
11468 
11469 /*
11470  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11471  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11472  * isn't.  This doesn't matter as the error checking is done properly for the
11473  * other MRT options coming in through ip_opt_set.
11474  */
11475 int
11476 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11477 {
11478 	conn_t		*connp = Q_TO_CONN(q);
11479 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11480 
11481 	switch (level) {
11482 	case IPPROTO_IP:
11483 		switch (name) {
11484 		case MRT_VERSION:
11485 		case MRT_ASSERT:
11486 			(void) ip_mrouter_get(name, q, ptr);
11487 			return (sizeof (int));
11488 		case IP_SEC_OPT:
11489 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11490 		case IP_NEXTHOP:
11491 			if (connp->conn_nexthop_set) {
11492 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11493 				return (sizeof (ipaddr_t));
11494 			} else
11495 				return (0);
11496 		default:
11497 			break;
11498 		}
11499 		break;
11500 	case IPPROTO_IPV6:
11501 		switch (name) {
11502 		case IPV6_SEC_OPT:
11503 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11504 		case IPV6_SRC_PREFERENCES: {
11505 			return (ip6_get_src_preferences(connp,
11506 			    (uint32_t *)ptr));
11507 		}
11508 		case IPV6_V6ONLY:
11509 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11510 			return (sizeof (int));
11511 		case IPV6_PATHMTU:
11512 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11513 				(struct ip6_mtuinfo *)ptr));
11514 		default:
11515 			break;
11516 		}
11517 		break;
11518 	default:
11519 		break;
11520 	}
11521 	return (-1);
11522 }
11523 
11524 /* Named Dispatch routine to get a current value out of our parameter table. */
11525 /* ARGSUSED */
11526 static int
11527 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11528 {
11529 	ipparam_t *ippa = (ipparam_t *)cp;
11530 
11531 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11532 	return (0);
11533 }
11534 
11535 /* ARGSUSED */
11536 static int
11537 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11538 {
11539 
11540 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11541 	return (0);
11542 }
11543 
11544 /*
11545  * Set ip{,6}_forwarding values.  This means walking through all of the
11546  * ill's and toggling their forwarding values.
11547  */
11548 /* ARGSUSED */
11549 static int
11550 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11551 {
11552 	long new_value;
11553 	int *forwarding_value = (int *)cp;
11554 	ill_t *walker;
11555 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11556 	ill_walk_context_t ctx;
11557 
11558 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11559 	    new_value < 0 || new_value > 1) {
11560 		return (EINVAL);
11561 	}
11562 
11563 	*forwarding_value = new_value;
11564 
11565 	/*
11566 	 * Regardless of the current value of ip_forwarding, set all per-ill
11567 	 * values of ip_forwarding to the value being set.
11568 	 *
11569 	 * Bring all the ill's up to date with the new global value.
11570 	 */
11571 	rw_enter(&ill_g_lock, RW_READER);
11572 
11573 	if (isv6)
11574 		walker = ILL_START_WALK_V6(&ctx);
11575 	else
11576 		walker = ILL_START_WALK_V4(&ctx);
11577 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11578 		(void) ill_forward_set(q, mp, (new_value != 0),
11579 		    (caddr_t)walker);
11580 	}
11581 	rw_exit(&ill_g_lock);
11582 
11583 	return (0);
11584 }
11585 
11586 /*
11587  * Walk through the param array specified registering each element with the
11588  * Named Dispatch handler. This is called only during init. So it is ok
11589  * not to acquire any locks
11590  */
11591 static boolean_t
11592 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11593     ipndp_t *ipnd, size_t ipnd_cnt)
11594 {
11595 	for (; ippa_cnt-- > 0; ippa++) {
11596 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11597 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11598 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11599 				nd_free(&ip_g_nd);
11600 				return (B_FALSE);
11601 			}
11602 		}
11603 	}
11604 
11605 	for (; ipnd_cnt-- > 0; ipnd++) {
11606 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11607 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11608 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11609 			    ipnd->ip_ndp_data)) {
11610 				nd_free(&ip_g_nd);
11611 				return (B_FALSE);
11612 			}
11613 		}
11614 	}
11615 
11616 	return (B_TRUE);
11617 }
11618 
11619 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11620 /* ARGSUSED */
11621 static int
11622 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11623 {
11624 	long		new_value;
11625 	ipparam_t	*ippa = (ipparam_t *)cp;
11626 
11627 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11628 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11629 		return (EINVAL);
11630 	}
11631 	ippa->ip_param_value = new_value;
11632 	return (0);
11633 }
11634 
11635 /*
11636  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11637  * When an ipf is passed here for the first time, if
11638  * we already have in-order fragments on the queue, we convert from the fast-
11639  * path reassembly scheme to the hard-case scheme.  From then on, additional
11640  * fragments are reassembled here.  We keep track of the start and end offsets
11641  * of each piece, and the number of holes in the chain.  When the hole count
11642  * goes to zero, we are done!
11643  *
11644  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11645  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11646  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11647  * after the call to ip_reassemble().
11648  */
11649 int
11650 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11651     size_t msg_len)
11652 {
11653 	uint_t	end;
11654 	mblk_t	*next_mp;
11655 	mblk_t	*mp1;
11656 	uint_t	offset;
11657 	boolean_t incr_dups = B_TRUE;
11658 	boolean_t offset_zero_seen = B_FALSE;
11659 	boolean_t pkt_boundary_checked = B_FALSE;
11660 
11661 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11662 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11663 
11664 	/* Add in byte count */
11665 	ipf->ipf_count += msg_len;
11666 	if (ipf->ipf_end) {
11667 		/*
11668 		 * We were part way through in-order reassembly, but now there
11669 		 * is a hole.  We walk through messages already queued, and
11670 		 * mark them for hard case reassembly.  We know that up till
11671 		 * now they were in order starting from offset zero.
11672 		 */
11673 		offset = 0;
11674 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11675 			IP_REASS_SET_START(mp1, offset);
11676 			if (offset == 0) {
11677 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11678 				offset = -ipf->ipf_nf_hdr_len;
11679 			}
11680 			offset += mp1->b_wptr - mp1->b_rptr;
11681 			IP_REASS_SET_END(mp1, offset);
11682 		}
11683 		/* One hole at the end. */
11684 		ipf->ipf_hole_cnt = 1;
11685 		/* Brand it as a hard case, forever. */
11686 		ipf->ipf_end = 0;
11687 	}
11688 	/* Walk through all the new pieces. */
11689 	do {
11690 		end = start + (mp->b_wptr - mp->b_rptr);
11691 		/*
11692 		 * If start is 0, decrease 'end' only for the first mblk of
11693 		 * the fragment. Otherwise 'end' can get wrong value in the
11694 		 * second pass of the loop if first mblk is exactly the
11695 		 * size of ipf_nf_hdr_len.
11696 		 */
11697 		if (start == 0 && !offset_zero_seen) {
11698 			/* First segment */
11699 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11700 			end -= ipf->ipf_nf_hdr_len;
11701 			offset_zero_seen = B_TRUE;
11702 		}
11703 		next_mp = mp->b_cont;
11704 		/*
11705 		 * We are checking to see if there is any interesing data
11706 		 * to process.  If there isn't and the mblk isn't the
11707 		 * one which carries the unfragmentable header then we
11708 		 * drop it.  It's possible to have just the unfragmentable
11709 		 * header come through without any data.  That needs to be
11710 		 * saved.
11711 		 *
11712 		 * If the assert at the top of this function holds then the
11713 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11714 		 * is infrequently traveled enough that the test is left in
11715 		 * to protect against future code changes which break that
11716 		 * invariant.
11717 		 */
11718 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11719 			/* Empty.  Blast it. */
11720 			IP_REASS_SET_START(mp, 0);
11721 			IP_REASS_SET_END(mp, 0);
11722 			/*
11723 			 * If the ipf points to the mblk we are about to free,
11724 			 * update ipf to point to the next mblk (or NULL
11725 			 * if none).
11726 			 */
11727 			if (ipf->ipf_mp->b_cont == mp)
11728 				ipf->ipf_mp->b_cont = next_mp;
11729 			freeb(mp);
11730 			continue;
11731 		}
11732 		mp->b_cont = NULL;
11733 		IP_REASS_SET_START(mp, start);
11734 		IP_REASS_SET_END(mp, end);
11735 		if (!ipf->ipf_tail_mp) {
11736 			ipf->ipf_tail_mp = mp;
11737 			ipf->ipf_mp->b_cont = mp;
11738 			if (start == 0 || !more) {
11739 				ipf->ipf_hole_cnt = 1;
11740 				/*
11741 				 * if the first fragment comes in more than one
11742 				 * mblk, this loop will be executed for each
11743 				 * mblk. Need to adjust hole count so exiting
11744 				 * this routine will leave hole count at 1.
11745 				 */
11746 				if (next_mp)
11747 					ipf->ipf_hole_cnt++;
11748 			} else
11749 				ipf->ipf_hole_cnt = 2;
11750 			continue;
11751 		} else if (ipf->ipf_last_frag_seen && !more &&
11752 			    !pkt_boundary_checked) {
11753 			/*
11754 			 * We check datagram boundary only if this fragment
11755 			 * claims to be the last fragment and we have seen a
11756 			 * last fragment in the past too. We do this only
11757 			 * once for a given fragment.
11758 			 *
11759 			 * start cannot be 0 here as fragments with start=0
11760 			 * and MF=0 gets handled as a complete packet. These
11761 			 * fragments should not reach here.
11762 			 */
11763 
11764 			if (start + msgdsize(mp) !=
11765 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11766 				/*
11767 				 * We have two fragments both of which claim
11768 				 * to be the last fragment but gives conflicting
11769 				 * information about the whole datagram size.
11770 				 * Something fishy is going on. Drop the
11771 				 * fragment and free up the reassembly list.
11772 				 */
11773 				return (IP_REASS_FAILED);
11774 			}
11775 
11776 			/*
11777 			 * We shouldn't come to this code block again for this
11778 			 * particular fragment.
11779 			 */
11780 			pkt_boundary_checked = B_TRUE;
11781 		}
11782 
11783 		/* New stuff at or beyond tail? */
11784 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11785 		if (start >= offset) {
11786 			if (ipf->ipf_last_frag_seen) {
11787 				/* current fragment is beyond last fragment */
11788 				return (IP_REASS_FAILED);
11789 			}
11790 			/* Link it on end. */
11791 			ipf->ipf_tail_mp->b_cont = mp;
11792 			ipf->ipf_tail_mp = mp;
11793 			if (more) {
11794 				if (start != offset)
11795 					ipf->ipf_hole_cnt++;
11796 			} else if (start == offset && next_mp == NULL)
11797 					ipf->ipf_hole_cnt--;
11798 			continue;
11799 		}
11800 		mp1 = ipf->ipf_mp->b_cont;
11801 		offset = IP_REASS_START(mp1);
11802 		/* New stuff at the front? */
11803 		if (start < offset) {
11804 			if (start == 0) {
11805 				if (end >= offset) {
11806 					/* Nailed the hole at the begining. */
11807 					ipf->ipf_hole_cnt--;
11808 				}
11809 			} else if (end < offset) {
11810 				/*
11811 				 * A hole, stuff, and a hole where there used
11812 				 * to be just a hole.
11813 				 */
11814 				ipf->ipf_hole_cnt++;
11815 			}
11816 			mp->b_cont = mp1;
11817 			/* Check for overlap. */
11818 			while (end > offset) {
11819 				if (end < IP_REASS_END(mp1)) {
11820 					mp->b_wptr -= end - offset;
11821 					IP_REASS_SET_END(mp, offset);
11822 					BUMP_MIB(ill->ill_ip_mib,
11823 					    ipIfStatsReasmPartDups);
11824 					break;
11825 				}
11826 				/* Did we cover another hole? */
11827 				if ((mp1->b_cont &&
11828 				    IP_REASS_END(mp1) !=
11829 				    IP_REASS_START(mp1->b_cont) &&
11830 				    end >= IP_REASS_START(mp1->b_cont)) ||
11831 				    (!ipf->ipf_last_frag_seen && !more)) {
11832 					ipf->ipf_hole_cnt--;
11833 				}
11834 				/* Clip out mp1. */
11835 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11836 					/*
11837 					 * After clipping out mp1, this guy
11838 					 * is now hanging off the end.
11839 					 */
11840 					ipf->ipf_tail_mp = mp;
11841 				}
11842 				IP_REASS_SET_START(mp1, 0);
11843 				IP_REASS_SET_END(mp1, 0);
11844 				/* Subtract byte count */
11845 				ipf->ipf_count -= mp1->b_datap->db_lim -
11846 				    mp1->b_datap->db_base;
11847 				freeb(mp1);
11848 				BUMP_MIB(ill->ill_ip_mib,
11849 				    ipIfStatsReasmPartDups);
11850 				mp1 = mp->b_cont;
11851 				if (!mp1)
11852 					break;
11853 				offset = IP_REASS_START(mp1);
11854 			}
11855 			ipf->ipf_mp->b_cont = mp;
11856 			continue;
11857 		}
11858 		/*
11859 		 * The new piece starts somewhere between the start of the head
11860 		 * and before the end of the tail.
11861 		 */
11862 		for (; mp1; mp1 = mp1->b_cont) {
11863 			offset = IP_REASS_END(mp1);
11864 			if (start < offset) {
11865 				if (end <= offset) {
11866 					/* Nothing new. */
11867 					IP_REASS_SET_START(mp, 0);
11868 					IP_REASS_SET_END(mp, 0);
11869 					/* Subtract byte count */
11870 					ipf->ipf_count -= mp->b_datap->db_lim -
11871 					    mp->b_datap->db_base;
11872 					if (incr_dups) {
11873 						ipf->ipf_num_dups++;
11874 						incr_dups = B_FALSE;
11875 					}
11876 					freeb(mp);
11877 					BUMP_MIB(ill->ill_ip_mib,
11878 					    ipIfStatsReasmDuplicates);
11879 					break;
11880 				}
11881 				/*
11882 				 * Trim redundant stuff off beginning of new
11883 				 * piece.
11884 				 */
11885 				IP_REASS_SET_START(mp, offset);
11886 				mp->b_rptr += offset - start;
11887 				BUMP_MIB(ill->ill_ip_mib,
11888 				    ipIfStatsReasmPartDups);
11889 				start = offset;
11890 				if (!mp1->b_cont) {
11891 					/*
11892 					 * After trimming, this guy is now
11893 					 * hanging off the end.
11894 					 */
11895 					mp1->b_cont = mp;
11896 					ipf->ipf_tail_mp = mp;
11897 					if (!more) {
11898 						ipf->ipf_hole_cnt--;
11899 					}
11900 					break;
11901 				}
11902 			}
11903 			if (start >= IP_REASS_START(mp1->b_cont))
11904 				continue;
11905 			/* Fill a hole */
11906 			if (start > offset)
11907 				ipf->ipf_hole_cnt++;
11908 			mp->b_cont = mp1->b_cont;
11909 			mp1->b_cont = mp;
11910 			mp1 = mp->b_cont;
11911 			offset = IP_REASS_START(mp1);
11912 			if (end >= offset) {
11913 				ipf->ipf_hole_cnt--;
11914 				/* Check for overlap. */
11915 				while (end > offset) {
11916 					if (end < IP_REASS_END(mp1)) {
11917 						mp->b_wptr -= end - offset;
11918 						IP_REASS_SET_END(mp, offset);
11919 						/*
11920 						 * TODO we might bump
11921 						 * this up twice if there is
11922 						 * overlap at both ends.
11923 						 */
11924 						BUMP_MIB(ill->ill_ip_mib,
11925 						    ipIfStatsReasmPartDups);
11926 						break;
11927 					}
11928 					/* Did we cover another hole? */
11929 					if ((mp1->b_cont &&
11930 					    IP_REASS_END(mp1)
11931 					    != IP_REASS_START(mp1->b_cont) &&
11932 					    end >=
11933 					    IP_REASS_START(mp1->b_cont)) ||
11934 					    (!ipf->ipf_last_frag_seen &&
11935 					    !more)) {
11936 						ipf->ipf_hole_cnt--;
11937 					}
11938 					/* Clip out mp1. */
11939 					if ((mp->b_cont = mp1->b_cont) ==
11940 					    NULL) {
11941 						/*
11942 						 * After clipping out mp1,
11943 						 * this guy is now hanging
11944 						 * off the end.
11945 						 */
11946 						ipf->ipf_tail_mp = mp;
11947 					}
11948 					IP_REASS_SET_START(mp1, 0);
11949 					IP_REASS_SET_END(mp1, 0);
11950 					/* Subtract byte count */
11951 					ipf->ipf_count -=
11952 					    mp1->b_datap->db_lim -
11953 					    mp1->b_datap->db_base;
11954 					freeb(mp1);
11955 					BUMP_MIB(ill->ill_ip_mib,
11956 					    ipIfStatsReasmPartDups);
11957 					mp1 = mp->b_cont;
11958 					if (!mp1)
11959 						break;
11960 					offset = IP_REASS_START(mp1);
11961 				}
11962 			}
11963 			break;
11964 		}
11965 	} while (start = end, mp = next_mp);
11966 
11967 	/* Fragment just processed could be the last one. Remember this fact */
11968 	if (!more)
11969 		ipf->ipf_last_frag_seen = B_TRUE;
11970 
11971 	/* Still got holes? */
11972 	if (ipf->ipf_hole_cnt)
11973 		return (IP_REASS_PARTIAL);
11974 	/* Clean up overloaded fields to avoid upstream disasters. */
11975 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11976 		IP_REASS_SET_START(mp1, 0);
11977 		IP_REASS_SET_END(mp1, 0);
11978 	}
11979 	return (IP_REASS_COMPLETE);
11980 }
11981 
11982 /*
11983  * ipsec processing for the fast path, used for input UDP Packets
11984  */
11985 static boolean_t
11986 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11987     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11988 {
11989 	uint32_t	ill_index;
11990 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11991 
11992 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11993 	/* The ill_index of the incoming ILL */
11994 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11995 
11996 	/* pass packet up to the transport */
11997 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11998 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11999 		    NULL, mctl_present);
12000 		if (*first_mpp == NULL) {
12001 			return (B_FALSE);
12002 		}
12003 	}
12004 
12005 	/* Initiate IPPF processing for fastpath UDP */
12006 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12007 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12008 		if (*mpp == NULL) {
12009 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12010 			    "deferred/dropped during IPPF processing\n"));
12011 			return (B_FALSE);
12012 		}
12013 	}
12014 	/*
12015 	 * We make the checks as below since we are in the fast path
12016 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12017 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12018 	 */
12019 	if (connp->conn_recvif || connp->conn_recvslla ||
12020 	    connp->conn_ipv6_recvpktinfo) {
12021 		if (connp->conn_recvif ||
12022 		    connp->conn_ipv6_recvpktinfo) {
12023 			in_flags = IPF_RECVIF;
12024 		}
12025 		if (connp->conn_recvslla) {
12026 			in_flags |= IPF_RECVSLLA;
12027 		}
12028 		/*
12029 		 * since in_flags are being set ill will be
12030 		 * referenced in ip_add_info, so it better not
12031 		 * be NULL.
12032 		 */
12033 		/*
12034 		 * the actual data will be contained in b_cont
12035 		 * upon successful return of the following call.
12036 		 * If the call fails then the original mblk is
12037 		 * returned.
12038 		 */
12039 		*mpp = ip_add_info(*mpp, ill, in_flags);
12040 	}
12041 
12042 	return (B_TRUE);
12043 }
12044 
12045 /*
12046  * Fragmentation reassembly.  Each ILL has a hash table for
12047  * queuing packets undergoing reassembly for all IPIFs
12048  * associated with the ILL.  The hash is based on the packet
12049  * IP ident field.  The ILL frag hash table was allocated
12050  * as a timer block at the time the ILL was created.  Whenever
12051  * there is anything on the reassembly queue, the timer will
12052  * be running.  Returns B_TRUE if successful else B_FALSE;
12053  * frees mp on failure.
12054  */
12055 static boolean_t
12056 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12057     uint32_t *cksum_val, uint16_t *cksum_flags)
12058 {
12059 	uint32_t	frag_offset_flags;
12060 	ill_t		*ill = (ill_t *)q->q_ptr;
12061 	mblk_t		*mp = *mpp;
12062 	mblk_t		*t_mp;
12063 	ipaddr_t	dst;
12064 	uint8_t		proto = ipha->ipha_protocol;
12065 	uint32_t	sum_val;
12066 	uint16_t	sum_flags;
12067 	ipf_t		*ipf;
12068 	ipf_t		**ipfp;
12069 	ipfb_t		*ipfb;
12070 	uint16_t	ident;
12071 	uint32_t	offset;
12072 	ipaddr_t	src;
12073 	uint_t		hdr_length;
12074 	uint32_t	end;
12075 	mblk_t		*mp1;
12076 	mblk_t		*tail_mp;
12077 	size_t		count;
12078 	size_t		msg_len;
12079 	uint8_t		ecn_info = 0;
12080 	uint32_t	packet_size;
12081 	boolean_t	pruned = B_FALSE;
12082 
12083 	if (cksum_val != NULL)
12084 		*cksum_val = 0;
12085 	if (cksum_flags != NULL)
12086 		*cksum_flags = 0;
12087 
12088 	/*
12089 	 * Drop the fragmented as early as possible, if
12090 	 * we don't have resource(s) to re-assemble.
12091 	 */
12092 	if (ip_reass_queue_bytes == 0) {
12093 		freemsg(mp);
12094 		return (B_FALSE);
12095 	}
12096 
12097 	/* Check for fragmentation offset; return if there's none */
12098 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12099 	    (IPH_MF | IPH_OFFSET)) == 0)
12100 		return (B_TRUE);
12101 
12102 	/*
12103 	 * We utilize hardware computed checksum info only for UDP since
12104 	 * IP fragmentation is a normal occurence for the protocol.  In
12105 	 * addition, checksum offload support for IP fragments carrying
12106 	 * UDP payload is commonly implemented across network adapters.
12107 	 */
12108 	ASSERT(ill != NULL);
12109 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12110 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12111 		mblk_t *mp1 = mp->b_cont;
12112 		int32_t len;
12113 
12114 		/* Record checksum information from the packet */
12115 		sum_val = (uint32_t)DB_CKSUM16(mp);
12116 		sum_flags = DB_CKSUMFLAGS(mp);
12117 
12118 		/* IP payload offset from beginning of mblk */
12119 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12120 
12121 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12122 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12123 		    offset >= DB_CKSUMSTART(mp) &&
12124 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12125 			uint32_t adj;
12126 			/*
12127 			 * Partial checksum has been calculated by hardware
12128 			 * and attached to the packet; in addition, any
12129 			 * prepended extraneous data is even byte aligned.
12130 			 * If any such data exists, we adjust the checksum;
12131 			 * this would also handle any postpended data.
12132 			 */
12133 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12134 			    mp, mp1, len, adj);
12135 
12136 			/* One's complement subtract extraneous checksum */
12137 			if (adj >= sum_val)
12138 				sum_val = ~(adj - sum_val) & 0xFFFF;
12139 			else
12140 				sum_val -= adj;
12141 		}
12142 	} else {
12143 		sum_val = 0;
12144 		sum_flags = 0;
12145 	}
12146 
12147 	/* Clear hardware checksumming flag */
12148 	DB_CKSUMFLAGS(mp) = 0;
12149 
12150 	ident = ipha->ipha_ident;
12151 	offset = (frag_offset_flags << 3) & 0xFFFF;
12152 	src = ipha->ipha_src;
12153 	dst = ipha->ipha_dst;
12154 	hdr_length = IPH_HDR_LENGTH(ipha);
12155 	end = ntohs(ipha->ipha_length) - hdr_length;
12156 
12157 	/* If end == 0 then we have a packet with no data, so just free it */
12158 	if (end == 0) {
12159 		freemsg(mp);
12160 		return (B_FALSE);
12161 	}
12162 
12163 	/* Record the ECN field info. */
12164 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12165 	if (offset != 0) {
12166 		/*
12167 		 * If this isn't the first piece, strip the header, and
12168 		 * add the offset to the end value.
12169 		 */
12170 		mp->b_rptr += hdr_length;
12171 		end += offset;
12172 	}
12173 
12174 	msg_len = MBLKSIZE(mp);
12175 	tail_mp = mp;
12176 	while (tail_mp->b_cont != NULL) {
12177 		tail_mp = tail_mp->b_cont;
12178 		msg_len += MBLKSIZE(tail_mp);
12179 	}
12180 
12181 	/* If the reassembly list for this ILL will get too big, prune it */
12182 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12183 	    ip_reass_queue_bytes) {
12184 		ill_frag_prune(ill,
12185 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12186 		    (ip_reass_queue_bytes - msg_len));
12187 		pruned = B_TRUE;
12188 	}
12189 
12190 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12191 	mutex_enter(&ipfb->ipfb_lock);
12192 
12193 	ipfp = &ipfb->ipfb_ipf;
12194 	/* Try to find an existing fragment queue for this packet. */
12195 	for (;;) {
12196 		ipf = ipfp[0];
12197 		if (ipf != NULL) {
12198 			/*
12199 			 * It has to match on ident and src/dst address.
12200 			 */
12201 			if (ipf->ipf_ident == ident &&
12202 			    ipf->ipf_src == src &&
12203 			    ipf->ipf_dst == dst &&
12204 			    ipf->ipf_protocol == proto) {
12205 				/*
12206 				 * If we have received too many
12207 				 * duplicate fragments for this packet
12208 				 * free it.
12209 				 */
12210 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12211 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12212 					freemsg(mp);
12213 					mutex_exit(&ipfb->ipfb_lock);
12214 					return (B_FALSE);
12215 				}
12216 				/* Found it. */
12217 				break;
12218 			}
12219 			ipfp = &ipf->ipf_hash_next;
12220 			continue;
12221 		}
12222 
12223 		/*
12224 		 * If we pruned the list, do we want to store this new
12225 		 * fragment?. We apply an optimization here based on the
12226 		 * fact that most fragments will be received in order.
12227 		 * So if the offset of this incoming fragment is zero,
12228 		 * it is the first fragment of a new packet. We will
12229 		 * keep it.  Otherwise drop the fragment, as we have
12230 		 * probably pruned the packet already (since the
12231 		 * packet cannot be found).
12232 		 */
12233 		if (pruned && offset != 0) {
12234 			mutex_exit(&ipfb->ipfb_lock);
12235 			freemsg(mp);
12236 			return (B_FALSE);
12237 		}
12238 
12239 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12240 			/*
12241 			 * Too many fragmented packets in this hash
12242 			 * bucket. Free the oldest.
12243 			 */
12244 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12245 		}
12246 
12247 		/* New guy.  Allocate a frag message. */
12248 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12249 		if (mp1 == NULL) {
12250 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12251 			freemsg(mp);
12252 reass_done:
12253 			mutex_exit(&ipfb->ipfb_lock);
12254 			return (B_FALSE);
12255 		}
12256 
12257 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12258 		mp1->b_cont = mp;
12259 
12260 		/* Initialize the fragment header. */
12261 		ipf = (ipf_t *)mp1->b_rptr;
12262 		ipf->ipf_mp = mp1;
12263 		ipf->ipf_ptphn = ipfp;
12264 		ipfp[0] = ipf;
12265 		ipf->ipf_hash_next = NULL;
12266 		ipf->ipf_ident = ident;
12267 		ipf->ipf_protocol = proto;
12268 		ipf->ipf_src = src;
12269 		ipf->ipf_dst = dst;
12270 		ipf->ipf_nf_hdr_len = 0;
12271 		/* Record reassembly start time. */
12272 		ipf->ipf_timestamp = gethrestime_sec();
12273 		/* Record ipf generation and account for frag header */
12274 		ipf->ipf_gen = ill->ill_ipf_gen++;
12275 		ipf->ipf_count = MBLKSIZE(mp1);
12276 		ipf->ipf_last_frag_seen = B_FALSE;
12277 		ipf->ipf_ecn = ecn_info;
12278 		ipf->ipf_num_dups = 0;
12279 		ipfb->ipfb_frag_pkts++;
12280 		ipf->ipf_checksum = 0;
12281 		ipf->ipf_checksum_flags = 0;
12282 
12283 		/* Store checksum value in fragment header */
12284 		if (sum_flags != 0) {
12285 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12286 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12287 			ipf->ipf_checksum = sum_val;
12288 			ipf->ipf_checksum_flags = sum_flags;
12289 		}
12290 
12291 		/*
12292 		 * We handle reassembly two ways.  In the easy case,
12293 		 * where all the fragments show up in order, we do
12294 		 * minimal bookkeeping, and just clip new pieces on
12295 		 * the end.  If we ever see a hole, then we go off
12296 		 * to ip_reassemble which has to mark the pieces and
12297 		 * keep track of the number of holes, etc.  Obviously,
12298 		 * the point of having both mechanisms is so we can
12299 		 * handle the easy case as efficiently as possible.
12300 		 */
12301 		if (offset == 0) {
12302 			/* Easy case, in-order reassembly so far. */
12303 			ipf->ipf_count += msg_len;
12304 			ipf->ipf_tail_mp = tail_mp;
12305 			/*
12306 			 * Keep track of next expected offset in
12307 			 * ipf_end.
12308 			 */
12309 			ipf->ipf_end = end;
12310 			ipf->ipf_nf_hdr_len = hdr_length;
12311 		} else {
12312 			/* Hard case, hole at the beginning. */
12313 			ipf->ipf_tail_mp = NULL;
12314 			/*
12315 			 * ipf_end == 0 means that we have given up
12316 			 * on easy reassembly.
12317 			 */
12318 			ipf->ipf_end = 0;
12319 
12320 			/* Forget checksum offload from now on */
12321 			ipf->ipf_checksum_flags = 0;
12322 
12323 			/*
12324 			 * ipf_hole_cnt is set by ip_reassemble.
12325 			 * ipf_count is updated by ip_reassemble.
12326 			 * No need to check for return value here
12327 			 * as we don't expect reassembly to complete
12328 			 * or fail for the first fragment itself.
12329 			 */
12330 			(void) ip_reassemble(mp, ipf,
12331 			    (frag_offset_flags & IPH_OFFSET) << 3,
12332 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12333 		}
12334 		/* Update per ipfb and ill byte counts */
12335 		ipfb->ipfb_count += ipf->ipf_count;
12336 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12337 		ill->ill_frag_count += ipf->ipf_count;
12338 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12339 		/* If the frag timer wasn't already going, start it. */
12340 		mutex_enter(&ill->ill_lock);
12341 		ill_frag_timer_start(ill);
12342 		mutex_exit(&ill->ill_lock);
12343 		goto reass_done;
12344 	}
12345 
12346 	/*
12347 	 * If the packet's flag has changed (it could be coming up
12348 	 * from an interface different than the previous, therefore
12349 	 * possibly different checksum capability), then forget about
12350 	 * any stored checksum states.  Otherwise add the value to
12351 	 * the existing one stored in the fragment header.
12352 	 */
12353 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12354 		sum_val += ipf->ipf_checksum;
12355 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12356 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12357 		ipf->ipf_checksum = sum_val;
12358 	} else if (ipf->ipf_checksum_flags != 0) {
12359 		/* Forget checksum offload from now on */
12360 		ipf->ipf_checksum_flags = 0;
12361 	}
12362 
12363 	/*
12364 	 * We have a new piece of a datagram which is already being
12365 	 * reassembled.  Update the ECN info if all IP fragments
12366 	 * are ECN capable.  If there is one which is not, clear
12367 	 * all the info.  If there is at least one which has CE
12368 	 * code point, IP needs to report that up to transport.
12369 	 */
12370 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12371 		if (ecn_info == IPH_ECN_CE)
12372 			ipf->ipf_ecn = IPH_ECN_CE;
12373 	} else {
12374 		ipf->ipf_ecn = IPH_ECN_NECT;
12375 	}
12376 	if (offset && ipf->ipf_end == offset) {
12377 		/* The new fragment fits at the end */
12378 		ipf->ipf_tail_mp->b_cont = mp;
12379 		/* Update the byte count */
12380 		ipf->ipf_count += msg_len;
12381 		/* Update per ipfb and ill byte counts */
12382 		ipfb->ipfb_count += msg_len;
12383 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12384 		ill->ill_frag_count += msg_len;
12385 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12386 		if (frag_offset_flags & IPH_MF) {
12387 			/* More to come. */
12388 			ipf->ipf_end = end;
12389 			ipf->ipf_tail_mp = tail_mp;
12390 			goto reass_done;
12391 		}
12392 	} else {
12393 		/* Go do the hard cases. */
12394 		int ret;
12395 
12396 		if (offset == 0)
12397 			ipf->ipf_nf_hdr_len = hdr_length;
12398 
12399 		/* Save current byte count */
12400 		count = ipf->ipf_count;
12401 		ret = ip_reassemble(mp, ipf,
12402 		    (frag_offset_flags & IPH_OFFSET) << 3,
12403 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12404 		/* Count of bytes added and subtracted (freeb()ed) */
12405 		count = ipf->ipf_count - count;
12406 		if (count) {
12407 			/* Update per ipfb and ill byte counts */
12408 			ipfb->ipfb_count += count;
12409 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12410 			ill->ill_frag_count += count;
12411 			ASSERT(ill->ill_frag_count > 0);
12412 		}
12413 		if (ret == IP_REASS_PARTIAL) {
12414 			goto reass_done;
12415 		} else if (ret == IP_REASS_FAILED) {
12416 			/* Reassembly failed. Free up all resources */
12417 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12418 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12419 				IP_REASS_SET_START(t_mp, 0);
12420 				IP_REASS_SET_END(t_mp, 0);
12421 			}
12422 			freemsg(mp);
12423 			goto reass_done;
12424 		}
12425 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12426 	}
12427 	/*
12428 	 * We have completed reassembly.  Unhook the frag header from
12429 	 * the reassembly list.
12430 	 *
12431 	 * Before we free the frag header, record the ECN info
12432 	 * to report back to the transport.
12433 	 */
12434 	ecn_info = ipf->ipf_ecn;
12435 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12436 	ipfp = ipf->ipf_ptphn;
12437 
12438 	/* We need to supply these to caller */
12439 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12440 		sum_val = ipf->ipf_checksum;
12441 	else
12442 		sum_val = 0;
12443 
12444 	mp1 = ipf->ipf_mp;
12445 	count = ipf->ipf_count;
12446 	ipf = ipf->ipf_hash_next;
12447 	if (ipf != NULL)
12448 		ipf->ipf_ptphn = ipfp;
12449 	ipfp[0] = ipf;
12450 	ill->ill_frag_count -= count;
12451 	ASSERT(ipfb->ipfb_count >= count);
12452 	ipfb->ipfb_count -= count;
12453 	ipfb->ipfb_frag_pkts--;
12454 	mutex_exit(&ipfb->ipfb_lock);
12455 	/* Ditch the frag header. */
12456 	mp = mp1->b_cont;
12457 
12458 	freeb(mp1);
12459 
12460 	/* Restore original IP length in header. */
12461 	packet_size = (uint32_t)msgdsize(mp);
12462 	if (packet_size > IP_MAXPACKET) {
12463 		freemsg(mp);
12464 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12465 		return (B_FALSE);
12466 	}
12467 
12468 	if (DB_REF(mp) > 1) {
12469 		mblk_t *mp2 = copymsg(mp);
12470 
12471 		freemsg(mp);
12472 		if (mp2 == NULL) {
12473 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12474 			return (B_FALSE);
12475 		}
12476 		mp = mp2;
12477 	}
12478 	ipha = (ipha_t *)mp->b_rptr;
12479 
12480 	ipha->ipha_length = htons((uint16_t)packet_size);
12481 	/* We're now complete, zip the frag state */
12482 	ipha->ipha_fragment_offset_and_flags = 0;
12483 	/* Record the ECN info. */
12484 	ipha->ipha_type_of_service &= 0xFC;
12485 	ipha->ipha_type_of_service |= ecn_info;
12486 	*mpp = mp;
12487 
12488 	/* Reassembly is successful; return checksum information if needed */
12489 	if (cksum_val != NULL)
12490 		*cksum_val = sum_val;
12491 	if (cksum_flags != NULL)
12492 		*cksum_flags = sum_flags;
12493 
12494 	return (B_TRUE);
12495 }
12496 
12497 /*
12498  * Perform ip header check sum update local options.
12499  * return B_TRUE if all is well, else return B_FALSE and release
12500  * the mp. caller is responsible for decrementing ire ref cnt.
12501  */
12502 static boolean_t
12503 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12504 {
12505 	mblk_t		*first_mp;
12506 	boolean_t	mctl_present;
12507 	uint16_t	sum;
12508 
12509 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12510 	/*
12511 	 * Don't do the checksum if it has gone through AH/ESP
12512 	 * processing.
12513 	 */
12514 	if (!mctl_present) {
12515 		sum = ip_csum_hdr(ipha);
12516 		if (sum != 0) {
12517 			if (ill != NULL) {
12518 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12519 			} else {
12520 				BUMP_MIB(&ip_mib, ipIfStatsInCksumErrs);
12521 			}
12522 			freemsg(first_mp);
12523 			return (B_FALSE);
12524 		}
12525 	}
12526 
12527 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12528 		if (mctl_present)
12529 			freeb(first_mp);
12530 		return (B_FALSE);
12531 	}
12532 
12533 	return (B_TRUE);
12534 }
12535 
12536 /*
12537  * All udp packet are delivered to the local host via this routine.
12538  */
12539 void
12540 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12541     ill_t *recv_ill)
12542 {
12543 	uint32_t	sum;
12544 	uint32_t	u1;
12545 	boolean_t	mctl_present;
12546 	conn_t		*connp;
12547 	mblk_t		*first_mp;
12548 	uint16_t	*up;
12549 	ill_t		*ill = (ill_t *)q->q_ptr;
12550 	uint16_t	reass_hck_flags = 0;
12551 
12552 #define	rptr    ((uchar_t *)ipha)
12553 
12554 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12555 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12556 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12557 	ASSERT(ill != NULL);
12558 
12559 	/*
12560 	 * FAST PATH for udp packets
12561 	 */
12562 
12563 	/* u1 is # words of IP options */
12564 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12565 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12566 
12567 	/* IP options present */
12568 	if (u1 != 0)
12569 		goto ipoptions;
12570 
12571 	/* Check the IP header checksum.  */
12572 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12573 		/* Clear the IP header h/w cksum flag */
12574 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12575 	} else {
12576 #define	uph	((uint16_t *)ipha)
12577 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12578 		    uph[6] + uph[7] + uph[8] + uph[9];
12579 #undef	uph
12580 		/* finish doing IP checksum */
12581 		sum = (sum & 0xFFFF) + (sum >> 16);
12582 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12583 		/*
12584 		 * Don't verify header checksum if this packet is coming
12585 		 * back from AH/ESP as we already did it.
12586 		 */
12587 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12588 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12589 			freemsg(first_mp);
12590 			return;
12591 		}
12592 	}
12593 
12594 	/*
12595 	 * Count for SNMP of inbound packets for ire.
12596 	 * if mctl is present this might be a secure packet and
12597 	 * has already been counted for in ip_proto_input().
12598 	 */
12599 	if (!mctl_present) {
12600 		UPDATE_IB_PKT_COUNT(ire);
12601 		ire->ire_last_used_time = lbolt;
12602 	}
12603 
12604 	/* packet part of fragmented IP packet? */
12605 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12606 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12607 		goto fragmented;
12608 	}
12609 
12610 	/* u1 = IP header length (20 bytes) */
12611 	u1 = IP_SIMPLE_HDR_LENGTH;
12612 
12613 	/* packet does not contain complete IP & UDP headers */
12614 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12615 		goto udppullup;
12616 
12617 	/* up points to UDP header */
12618 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12619 #define	iphs    ((uint16_t *)ipha)
12620 
12621 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12622 	if (up[3] != 0) {
12623 		mblk_t *mp1 = mp->b_cont;
12624 		boolean_t cksum_err;
12625 		uint16_t hck_flags = 0;
12626 
12627 		/* Pseudo-header checksum */
12628 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12629 		    iphs[9] + up[2];
12630 
12631 		/*
12632 		 * Revert to software checksum calculation if the interface
12633 		 * isn't capable of checksum offload or if IPsec is present.
12634 		 */
12635 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12636 			hck_flags = DB_CKSUMFLAGS(mp);
12637 
12638 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12639 			IP_STAT(ip_in_sw_cksum);
12640 
12641 		IP_CKSUM_RECV(hck_flags, u1,
12642 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12643 		    (int32_t)((uchar_t *)up - rptr),
12644 		    mp, mp1, cksum_err);
12645 
12646 		if (cksum_err) {
12647 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12648 			if (hck_flags & HCK_FULLCKSUM)
12649 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12650 			else if (hck_flags & HCK_PARTIALCKSUM)
12651 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12652 			else
12653 				IP_STAT(ip_udp_in_sw_cksum_err);
12654 
12655 			freemsg(first_mp);
12656 			return;
12657 		}
12658 	}
12659 
12660 	/* Non-fragmented broadcast or multicast packet? */
12661 	if (ire->ire_type == IRE_BROADCAST)
12662 		goto udpslowpath;
12663 
12664 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12665 	    ire->ire_zoneid)) != NULL) {
12666 		ASSERT(connp->conn_upq != NULL);
12667 		IP_STAT(ip_udp_fast_path);
12668 
12669 		if (CONN_UDP_FLOWCTLD(connp)) {
12670 			freemsg(mp);
12671 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12672 		} else {
12673 			if (!mctl_present) {
12674 				BUMP_MIB(ill->ill_ip_mib,
12675 				    ipIfStatsHCInDelivers);
12676 			}
12677 			/*
12678 			 * mp and first_mp can change.
12679 			 */
12680 			if (ip_udp_check(q, connp, recv_ill,
12681 			    ipha, &mp, &first_mp, mctl_present)) {
12682 				/* Send it upstream */
12683 				CONN_UDP_RECV(connp, mp);
12684 			}
12685 		}
12686 		/*
12687 		 * freeb() cannot deal with null mblk being passed
12688 		 * in and first_mp can be set to null in the call
12689 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12690 		 */
12691 		if (mctl_present && first_mp != NULL) {
12692 			freeb(first_mp);
12693 		}
12694 		CONN_DEC_REF(connp);
12695 		return;
12696 	}
12697 
12698 	/*
12699 	 * if we got here we know the packet is not fragmented and
12700 	 * has no options. The classifier could not find a conn_t and
12701 	 * most likely its an icmp packet so send it through slow path.
12702 	 */
12703 
12704 	goto udpslowpath;
12705 
12706 ipoptions:
12707 	if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
12708 		goto slow_done;
12709 	}
12710 
12711 	UPDATE_IB_PKT_COUNT(ire);
12712 	ire->ire_last_used_time = lbolt;
12713 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12714 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12715 fragmented:
12716 		/*
12717 		 * "sum" and "reass_hck_flags" are non-zero if the
12718 		 * reassembled packet has a valid hardware computed
12719 		 * checksum information associated with it.
12720 		 */
12721 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12722 			goto slow_done;
12723 		/*
12724 		 * Make sure that first_mp points back to mp as
12725 		 * the mp we came in with could have changed in
12726 		 * ip_rput_fragment().
12727 		 */
12728 		ASSERT(!mctl_present);
12729 		ipha = (ipha_t *)mp->b_rptr;
12730 		first_mp = mp;
12731 	}
12732 
12733 	/* Now we have a complete datagram, destined for this machine. */
12734 	u1 = IPH_HDR_LENGTH(ipha);
12735 	/* Pull up the UDP header, if necessary. */
12736 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12737 udppullup:
12738 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12739 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12740 			freemsg(first_mp);
12741 			goto slow_done;
12742 		}
12743 		ipha = (ipha_t *)mp->b_rptr;
12744 	}
12745 
12746 	/*
12747 	 * Validate the checksum for the reassembled packet; for the
12748 	 * pullup case we calculate the payload checksum in software.
12749 	 */
12750 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12751 	if (up[3] != 0) {
12752 		boolean_t cksum_err;
12753 
12754 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12755 			IP_STAT(ip_in_sw_cksum);
12756 
12757 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12758 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12759 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12760 		    iphs[9] + up[2], sum, cksum_err);
12761 
12762 		if (cksum_err) {
12763 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12764 
12765 			if (reass_hck_flags & HCK_FULLCKSUM)
12766 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12767 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12768 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12769 			else
12770 				IP_STAT(ip_udp_in_sw_cksum_err);
12771 
12772 			freemsg(first_mp);
12773 			goto slow_done;
12774 		}
12775 	}
12776 udpslowpath:
12777 
12778 	/* Clear hardware checksum flag to be safe */
12779 	DB_CKSUMFLAGS(mp) = 0;
12780 
12781 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12782 	    (ire->ire_type == IRE_BROADCAST),
12783 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12784 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12785 
12786 slow_done:
12787 	IP_STAT(ip_udp_slow_path);
12788 	return;
12789 
12790 #undef  iphs
12791 #undef  rptr
12792 }
12793 
12794 /* ARGSUSED */
12795 static mblk_t *
12796 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12797     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12798     ill_rx_ring_t *ill_ring)
12799 {
12800 	conn_t		*connp;
12801 	uint32_t	sum;
12802 	uint32_t	u1;
12803 	uint16_t	*up;
12804 	int		offset;
12805 	ssize_t		len;
12806 	mblk_t		*mp1;
12807 	boolean_t	syn_present = B_FALSE;
12808 	tcph_t		*tcph;
12809 	uint_t		ip_hdr_len;
12810 	ill_t		*ill = (ill_t *)q->q_ptr;
12811 	zoneid_t	zoneid = ire->ire_zoneid;
12812 	boolean_t	cksum_err;
12813 	uint16_t	hck_flags = 0;
12814 
12815 #define	rptr	((uchar_t *)ipha)
12816 
12817 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12818 	ASSERT(ill != NULL);
12819 
12820 	/*
12821 	 * FAST PATH for tcp packets
12822 	 */
12823 
12824 	/* u1 is # words of IP options */
12825 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12826 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12827 
12828 	/* IP options present */
12829 	if (u1) {
12830 		goto ipoptions;
12831 	} else {
12832 		/* Check the IP header checksum.  */
12833 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12834 			/* Clear the IP header h/w cksum flag */
12835 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12836 		} else {
12837 #define	uph	((uint16_t *)ipha)
12838 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12839 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12840 #undef	uph
12841 			/* finish doing IP checksum */
12842 			sum = (sum & 0xFFFF) + (sum >> 16);
12843 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12844 			/*
12845 			 * Don't verify header checksum if this packet
12846 			 * is coming back from AH/ESP as we already did it.
12847 			 */
12848 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12849 				BUMP_MIB(ill->ill_ip_mib,
12850 				    ipIfStatsInCksumErrs);
12851 				goto error;
12852 			}
12853 		}
12854 	}
12855 
12856 	if (!mctl_present) {
12857 		UPDATE_IB_PKT_COUNT(ire);
12858 		ire->ire_last_used_time = lbolt;
12859 	}
12860 
12861 	/* packet part of fragmented IP packet? */
12862 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12863 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12864 		goto fragmented;
12865 	}
12866 
12867 	/* u1 = IP header length (20 bytes) */
12868 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12869 
12870 	/* does packet contain IP+TCP headers? */
12871 	len = mp->b_wptr - rptr;
12872 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12873 		IP_STAT(ip_tcppullup);
12874 		goto tcppullup;
12875 	}
12876 
12877 	/* TCP options present? */
12878 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12879 
12880 	/*
12881 	 * If options need to be pulled up, then goto tcpoptions.
12882 	 * otherwise we are still in the fast path
12883 	 */
12884 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12885 		IP_STAT(ip_tcpoptions);
12886 		goto tcpoptions;
12887 	}
12888 
12889 	/* multiple mblks of tcp data? */
12890 	if ((mp1 = mp->b_cont) != NULL) {
12891 		/* more then two? */
12892 		if (mp1->b_cont != NULL) {
12893 			IP_STAT(ip_multipkttcp);
12894 			goto multipkttcp;
12895 		}
12896 		len += mp1->b_wptr - mp1->b_rptr;
12897 	}
12898 
12899 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12900 
12901 	/* part of pseudo checksum */
12902 
12903 	/* TCP datagram length */
12904 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12905 
12906 #define	iphs    ((uint16_t *)ipha)
12907 
12908 #ifdef	_BIG_ENDIAN
12909 	u1 += IPPROTO_TCP;
12910 #else
12911 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12912 #endif
12913 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12914 
12915 	/*
12916 	 * Revert to software checksum calculation if the interface
12917 	 * isn't capable of checksum offload or if IPsec is present.
12918 	 */
12919 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12920 		hck_flags = DB_CKSUMFLAGS(mp);
12921 
12922 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12923 		IP_STAT(ip_in_sw_cksum);
12924 
12925 	IP_CKSUM_RECV(hck_flags, u1,
12926 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12927 	    (int32_t)((uchar_t *)up - rptr),
12928 	    mp, mp1, cksum_err);
12929 
12930 	if (cksum_err) {
12931 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12932 
12933 		if (hck_flags & HCK_FULLCKSUM)
12934 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12935 		else if (hck_flags & HCK_PARTIALCKSUM)
12936 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12937 		else
12938 			IP_STAT(ip_tcp_in_sw_cksum_err);
12939 
12940 		goto error;
12941 	}
12942 
12943 try_again:
12944 
12945 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12946 	    NULL) {
12947 		/* Send the TH_RST */
12948 		goto no_conn;
12949 	}
12950 
12951 	/*
12952 	 * TCP FAST PATH for AF_INET socket.
12953 	 *
12954 	 * TCP fast path to avoid extra work. An AF_INET socket type
12955 	 * does not have facility to receive extra information via
12956 	 * ip_process or ip_add_info. Also, when the connection was
12957 	 * established, we made a check if this connection is impacted
12958 	 * by any global IPSec policy or per connection policy (a
12959 	 * policy that comes in effect later will not apply to this
12960 	 * connection). Since all this can be determined at the
12961 	 * connection establishment time, a quick check of flags
12962 	 * can avoid extra work.
12963 	 */
12964 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12965 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12966 		ASSERT(first_mp == mp);
12967 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12968 		SET_SQUEUE(mp, tcp_rput_data, connp);
12969 		return (mp);
12970 	}
12971 
12972 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12973 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12974 		if (IPCL_IS_TCP(connp)) {
12975 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12976 			DB_CKSUMSTART(mp) =
12977 			    (intptr_t)ip_squeue_get(ill_ring);
12978 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12979 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12980 				BUMP_MIB(ill->ill_ip_mib,
12981 				    ipIfStatsHCInDelivers);
12982 				SET_SQUEUE(mp, connp->conn_recv, connp);
12983 				return (mp);
12984 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12985 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12986 				BUMP_MIB(ill->ill_ip_mib,
12987 				    ipIfStatsHCInDelivers);
12988 				ip_squeue_enter_unbound++;
12989 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12990 				    connp);
12991 				return (mp);
12992 			}
12993 			syn_present = B_TRUE;
12994 		}
12995 
12996 	}
12997 
12998 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12999 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13000 
13001 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13002 		/* No need to send this packet to TCP */
13003 		if ((flags & TH_RST) || (flags & TH_URG)) {
13004 			CONN_DEC_REF(connp);
13005 			freemsg(first_mp);
13006 			return (NULL);
13007 		}
13008 		if (flags & TH_ACK) {
13009 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
13010 			CONN_DEC_REF(connp);
13011 			return (NULL);
13012 		}
13013 
13014 		CONN_DEC_REF(connp);
13015 		freemsg(first_mp);
13016 		return (NULL);
13017 	}
13018 
13019 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
13020 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13021 		    ipha, NULL, mctl_present);
13022 		if (first_mp == NULL) {
13023 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13024 			CONN_DEC_REF(connp);
13025 			return (NULL);
13026 		}
13027 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13028 			ASSERT(syn_present);
13029 			if (mctl_present) {
13030 				ASSERT(first_mp != mp);
13031 				first_mp->b_datap->db_struioflag |=
13032 				    STRUIO_POLICY;
13033 			} else {
13034 				ASSERT(first_mp == mp);
13035 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13036 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13037 			}
13038 		} else {
13039 			/*
13040 			 * Discard first_mp early since we're dealing with a
13041 			 * fully-connected conn_t and tcp doesn't do policy in
13042 			 * this case.
13043 			 */
13044 			if (mctl_present) {
13045 				freeb(first_mp);
13046 				mctl_present = B_FALSE;
13047 			}
13048 			first_mp = mp;
13049 		}
13050 	}
13051 
13052 	/* Initiate IPPF processing for fastpath */
13053 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13054 		uint32_t	ill_index;
13055 
13056 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13057 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13058 		if (mp == NULL) {
13059 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13060 			    "deferred/dropped during IPPF processing\n"));
13061 			CONN_DEC_REF(connp);
13062 			if (mctl_present)
13063 				freeb(first_mp);
13064 			return (NULL);
13065 		} else if (mctl_present) {
13066 			/*
13067 			 * ip_process might return a new mp.
13068 			 */
13069 			ASSERT(first_mp != mp);
13070 			first_mp->b_cont = mp;
13071 		} else {
13072 			first_mp = mp;
13073 		}
13074 
13075 	}
13076 
13077 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
13078 		mp = ip_add_info(mp, recv_ill, flags);
13079 		if (mp == NULL) {
13080 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13081 			CONN_DEC_REF(connp);
13082 			if (mctl_present)
13083 				freeb(first_mp);
13084 			return (NULL);
13085 		} else if (mctl_present) {
13086 			/*
13087 			 * ip_add_info might return a new mp.
13088 			 */
13089 			ASSERT(first_mp != mp);
13090 			first_mp->b_cont = mp;
13091 		} else {
13092 			first_mp = mp;
13093 		}
13094 	}
13095 
13096 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13097 	if (IPCL_IS_TCP(connp)) {
13098 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13099 		return (first_mp);
13100 	} else {
13101 		putnext(connp->conn_rq, first_mp);
13102 		CONN_DEC_REF(connp);
13103 		return (NULL);
13104 	}
13105 
13106 no_conn:
13107 	/* Initiate IPPf processing, if needed. */
13108 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13109 		uint32_t ill_index;
13110 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13111 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13112 		if (first_mp == NULL) {
13113 			return (NULL);
13114 		}
13115 	}
13116 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13117 
13118 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13119 	return (NULL);
13120 ipoptions:
13121 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire)) {
13122 		goto slow_done;
13123 	}
13124 
13125 	UPDATE_IB_PKT_COUNT(ire);
13126 	ire->ire_last_used_time = lbolt;
13127 
13128 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13129 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13130 fragmented:
13131 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13132 			if (mctl_present)
13133 				freeb(first_mp);
13134 			goto slow_done;
13135 		}
13136 		/*
13137 		 * Make sure that first_mp points back to mp as
13138 		 * the mp we came in with could have changed in
13139 		 * ip_rput_fragment().
13140 		 */
13141 		ASSERT(!mctl_present);
13142 		ipha = (ipha_t *)mp->b_rptr;
13143 		first_mp = mp;
13144 	}
13145 
13146 	/* Now we have a complete datagram, destined for this machine. */
13147 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13148 
13149 	len = mp->b_wptr - mp->b_rptr;
13150 	/* Pull up a minimal TCP header, if necessary. */
13151 	if (len < (u1 + 20)) {
13152 tcppullup:
13153 		if (!pullupmsg(mp, u1 + 20)) {
13154 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13155 			goto error;
13156 		}
13157 		ipha = (ipha_t *)mp->b_rptr;
13158 		len = mp->b_wptr - mp->b_rptr;
13159 	}
13160 
13161 	/*
13162 	 * Extract the offset field from the TCP header.  As usual, we
13163 	 * try to help the compiler more than the reader.
13164 	 */
13165 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13166 	if (offset != 5) {
13167 tcpoptions:
13168 		if (offset < 5) {
13169 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13170 			goto error;
13171 		}
13172 		/*
13173 		 * There must be TCP options.
13174 		 * Make sure we can grab them.
13175 		 */
13176 		offset <<= 2;
13177 		offset += u1;
13178 		if (len < offset) {
13179 			if (!pullupmsg(mp, offset)) {
13180 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13181 				goto error;
13182 			}
13183 			ipha = (ipha_t *)mp->b_rptr;
13184 			len = mp->b_wptr - rptr;
13185 		}
13186 	}
13187 
13188 	/* Get the total packet length in len, including headers. */
13189 	if (mp->b_cont) {
13190 multipkttcp:
13191 		len = msgdsize(mp);
13192 	}
13193 
13194 	/*
13195 	 * Check the TCP checksum by pulling together the pseudo-
13196 	 * header checksum, and passing it to ip_csum to be added in
13197 	 * with the TCP datagram.
13198 	 *
13199 	 * Since we are not using the hwcksum if available we must
13200 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13201 	 * If either of these fails along the way the mblk is freed.
13202 	 * If this logic ever changes and mblk is reused to say send
13203 	 * ICMP's back, then this flag may need to be cleared in
13204 	 * other places as well.
13205 	 */
13206 	DB_CKSUMFLAGS(mp) = 0;
13207 
13208 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13209 
13210 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13211 #ifdef	_BIG_ENDIAN
13212 	u1 += IPPROTO_TCP;
13213 #else
13214 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13215 #endif
13216 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13217 	/*
13218 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13219 	 */
13220 	IP_STAT(ip_in_sw_cksum);
13221 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13222 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13223 		goto error;
13224 	}
13225 
13226 	IP_STAT(ip_tcp_slow_path);
13227 	goto try_again;
13228 #undef  iphs
13229 #undef  rptr
13230 
13231 error:
13232 	freemsg(first_mp);
13233 slow_done:
13234 	return (NULL);
13235 }
13236 
13237 /* ARGSUSED */
13238 static void
13239 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13240     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13241 {
13242 	conn_t		*connp;
13243 	uint32_t	sum;
13244 	uint32_t	u1;
13245 	ssize_t		len;
13246 	sctp_hdr_t	*sctph;
13247 	zoneid_t	zoneid = ire->ire_zoneid;
13248 	uint32_t	pktsum;
13249 	uint32_t	calcsum;
13250 	uint32_t	ports;
13251 	uint_t		ipif_seqid;
13252 	in6_addr_t	map_src, map_dst;
13253 	ill_t		*ill = (ill_t *)q->q_ptr;
13254 
13255 #define	rptr	((uchar_t *)ipha)
13256 
13257 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13258 	ASSERT(ill != NULL);
13259 
13260 	/* u1 is # words of IP options */
13261 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13262 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13263 
13264 	/* IP options present */
13265 	if (u1 > 0) {
13266 		goto ipoptions;
13267 	} else {
13268 		/* Check the IP header checksum.  */
13269 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13270 #define	uph	((uint16_t *)ipha)
13271 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13272 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13273 #undef	uph
13274 			/* finish doing IP checksum */
13275 			sum = (sum & 0xFFFF) + (sum >> 16);
13276 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13277 			/*
13278 			 * Don't verify header checksum if this packet
13279 			 * is coming back from AH/ESP as we already did it.
13280 			 */
13281 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13282 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13283 				goto error;
13284 			}
13285 		}
13286 		/*
13287 		 * Since there is no SCTP h/w cksum support yet, just
13288 		 * clear the flag.
13289 		 */
13290 		DB_CKSUMFLAGS(mp) = 0;
13291 	}
13292 
13293 	/*
13294 	 * Don't verify header checksum if this packet is coming
13295 	 * back from AH/ESP as we already did it.
13296 	 */
13297 	if (!mctl_present) {
13298 		UPDATE_IB_PKT_COUNT(ire);
13299 		ire->ire_last_used_time = lbolt;
13300 	}
13301 
13302 	/* packet part of fragmented IP packet? */
13303 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13304 	if (u1 & (IPH_MF | IPH_OFFSET))
13305 		goto fragmented;
13306 
13307 	/* u1 = IP header length (20 bytes) */
13308 	u1 = IP_SIMPLE_HDR_LENGTH;
13309 
13310 find_sctp_client:
13311 	/* Pullup if we don't have the sctp common header. */
13312 	len = MBLKL(mp);
13313 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13314 		if (mp->b_cont == NULL ||
13315 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13317 			goto error;
13318 		}
13319 		ipha = (ipha_t *)mp->b_rptr;
13320 		len = MBLKL(mp);
13321 	}
13322 
13323 	sctph = (sctp_hdr_t *)(rptr + u1);
13324 #ifdef	DEBUG
13325 	if (!skip_sctp_cksum) {
13326 #endif
13327 		pktsum = sctph->sh_chksum;
13328 		sctph->sh_chksum = 0;
13329 		calcsum = sctp_cksum(mp, u1);
13330 		if (calcsum != pktsum) {
13331 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13332 			goto error;
13333 		}
13334 		sctph->sh_chksum = pktsum;
13335 #ifdef	DEBUG	/* skip_sctp_cksum */
13336 	}
13337 #endif
13338 	/* get the ports */
13339 	ports = *(uint32_t *)&sctph->sh_sport;
13340 
13341 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13342 	IRE_REFRELE(ire);
13343 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13344 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13345 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13346 	    mp)) == NULL) {
13347 		/* Check for raw socket or OOTB handling */
13348 		goto no_conn;
13349 	}
13350 
13351 	/* Found a client; up it goes */
13352 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13353 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13354 	return;
13355 
13356 no_conn:
13357 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13358 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13359 	return;
13360 
13361 ipoptions:
13362 	DB_CKSUMFLAGS(mp) = 0;
13363 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire))
13364 		goto slow_done;
13365 
13366 	UPDATE_IB_PKT_COUNT(ire);
13367 	ire->ire_last_used_time = lbolt;
13368 
13369 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13370 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13371 fragmented:
13372 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13373 			goto slow_done;
13374 		/*
13375 		 * Make sure that first_mp points back to mp as
13376 		 * the mp we came in with could have changed in
13377 		 * ip_rput_fragment().
13378 		 */
13379 		ASSERT(!mctl_present);
13380 		ipha = (ipha_t *)mp->b_rptr;
13381 		first_mp = mp;
13382 	}
13383 
13384 	/* Now we have a complete datagram, destined for this machine. */
13385 	u1 = IPH_HDR_LENGTH(ipha);
13386 	goto find_sctp_client;
13387 #undef  iphs
13388 #undef  rptr
13389 
13390 error:
13391 	freemsg(first_mp);
13392 slow_done:
13393 	IRE_REFRELE(ire);
13394 }
13395 
13396 #define	VER_BITS	0xF0
13397 #define	VERSION_6	0x60
13398 
13399 static boolean_t
13400 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13401     ipaddr_t *dstp)
13402 {
13403 	uint_t	opt_len;
13404 	ipha_t *ipha;
13405 	ssize_t len;
13406 	uint_t	pkt_len;
13407 
13408 	ASSERT(ill != NULL);
13409 	IP_STAT(ip_ipoptions);
13410 	ipha = *iphapp;
13411 
13412 #define	rptr    ((uchar_t *)ipha)
13413 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13414 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13415 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13416 		freemsg(mp);
13417 		return (B_FALSE);
13418 	}
13419 
13420 	/* multiple mblk or too short */
13421 	pkt_len = ntohs(ipha->ipha_length);
13422 
13423 	/* Get the number of words of IP options in the IP header. */
13424 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13425 	if (opt_len) {
13426 		/* IP Options present!  Validate and process. */
13427 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13428 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13429 			goto done;
13430 		}
13431 		/*
13432 		 * Recompute complete header length and make sure we
13433 		 * have access to all of it.
13434 		 */
13435 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13436 		if (len > (mp->b_wptr - rptr)) {
13437 			if (len > pkt_len) {
13438 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13439 				goto done;
13440 			}
13441 			if (!pullupmsg(mp, len)) {
13442 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13443 				goto done;
13444 			}
13445 			ipha = (ipha_t *)mp->b_rptr;
13446 		}
13447 		/*
13448 		 * Go off to ip_rput_options which returns the next hop
13449 		 * destination address, which may have been affected
13450 		 * by source routing.
13451 		 */
13452 		IP_STAT(ip_opt);
13453 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13454 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13455 			return (B_FALSE);
13456 		}
13457 	}
13458 	*iphapp = ipha;
13459 	return (B_TRUE);
13460 done:
13461 	/* clear b_prev - used by ip_mroute_decap */
13462 	mp->b_prev = NULL;
13463 	freemsg(mp);
13464 	return (B_FALSE);
13465 #undef  rptr
13466 }
13467 
13468 /*
13469  * Deal with the fact that there is no ire for the destination.
13470  * The incoming ill (in_ill) is passed in to ip_newroute only
13471  * in the case of packets coming from mobile ip forward tunnel.
13472  * It must be null otherwise.
13473  */
13474 static ire_t *
13475 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13476     ipaddr_t dst)
13477 {
13478 	ipha_t	*ipha;
13479 	ill_t	*ill;
13480 	ire_t	*ire;
13481 	boolean_t	check_multirt = B_FALSE;
13482 
13483 	ipha = (ipha_t *)mp->b_rptr;
13484 	ill = (ill_t *)q->q_ptr;
13485 
13486 	ASSERT(ill != NULL);
13487 	/*
13488 	 * No IRE for this destination, so it can't be for us.
13489 	 * Unless we are forwarding, drop the packet.
13490 	 * We have to let source routed packets through
13491 	 * since we don't yet know if they are 'ping -l'
13492 	 * packets i.e. if they will go out over the
13493 	 * same interface as they came in on.
13494 	 */
13495 	if (ll_multicast) {
13496 		freemsg(mp);
13497 		return (NULL);
13498 	}
13499 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13500 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13501 		freemsg(mp);
13502 		return (NULL);
13503 	}
13504 
13505 	/*
13506 	 * Mark this packet as having originated externally.
13507 	 *
13508 	 * For non-forwarding code path, ire_send later double
13509 	 * checks this interface to see if it is still exists
13510 	 * post-ARP resolution.
13511 	 *
13512 	 * Also, IPQOS uses this to differentiate between
13513 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13514 	 * QOS packet processing in ip_wput_attach_llhdr().
13515 	 * The QoS module can mark the b_band for a fastpath message
13516 	 * or the dl_priority field in a unitdata_req header for
13517 	 * CoS marking. This info can only be found in
13518 	 * ip_wput_attach_llhdr().
13519 	 */
13520 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13521 	/*
13522 	 * Clear the indication that this may have a hardware checksum
13523 	 * as we are not using it
13524 	 */
13525 	DB_CKSUMFLAGS(mp) = 0;
13526 
13527 	if (in_ill != NULL) {
13528 		/*
13529 		 * Now hand the packet to ip_newroute.
13530 		 */
13531 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13532 		return (NULL);
13533 	}
13534 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13535 	    MBLK_GETLABEL(mp));
13536 
13537 	if (ire == NULL && check_multirt) {
13538 		/* Let ip_newroute handle CGTP  */
13539 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13540 		return (NULL);
13541 	}
13542 
13543 	if (ire != NULL)
13544 		return (ire);
13545 
13546 	mp->b_prev = mp->b_next = 0;
13547 	/* send icmp unreachable */
13548 	q = WR(q);
13549 	/* Sent by forwarding path, and router is global zone */
13550 	if (ip_source_routed(ipha)) {
13551 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13552 		    GLOBAL_ZONEID);
13553 	} else {
13554 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13555 	}
13556 
13557 	return (NULL);
13558 
13559 }
13560 
13561 /*
13562  * check ip header length and align it.
13563  */
13564 static boolean_t
13565 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13566 {
13567 	ssize_t len;
13568 	ill_t *ill;
13569 	ipha_t	*ipha;
13570 
13571 	len = MBLKL(mp);
13572 
13573 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13574 		ill = (ill_t *)q->q_ptr;
13575 
13576 		if (!OK_32PTR(mp->b_rptr))
13577 			IP_STAT(ip_notaligned1);
13578 		else
13579 			IP_STAT(ip_notaligned2);
13580 		/* Guard against bogus device drivers */
13581 		if (len < 0) {
13582 			/* clear b_prev - used by ip_mroute_decap */
13583 			mp->b_prev = NULL;
13584 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13585 			freemsg(mp);
13586 			return (B_FALSE);
13587 		}
13588 
13589 		if (ip_rput_pullups++ == 0) {
13590 			ipha = (ipha_t *)mp->b_rptr;
13591 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13592 			    "ip_check_and_align_header: %s forced us to "
13593 			    " pullup pkt, hdr len %ld, hdr addr %p",
13594 			    ill->ill_name, len, ipha);
13595 		}
13596 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13597 			/* clear b_prev - used by ip_mroute_decap */
13598 			mp->b_prev = NULL;
13599 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13600 			freemsg(mp);
13601 			return (B_FALSE);
13602 		}
13603 	}
13604 	return (B_TRUE);
13605 }
13606 
13607 static boolean_t
13608 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13609 {
13610 	ill_group_t	*ill_group;
13611 	ill_group_t	*ire_group;
13612 	queue_t 	*q;
13613 	ill_t		*ire_ill;
13614 	uint_t		ill_ifindex;
13615 
13616 	q = *qp;
13617 	/*
13618 	 * We need to check to make sure the packet came in
13619 	 * on the queue associated with the destination IRE.
13620 	 * Note that for multicast packets and broadcast packets sent to
13621 	 * a broadcast address which is shared between multiple interfaces
13622 	 * we should not do this since we just got a random broadcast ire.
13623 	 */
13624 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13625 		boolean_t check_multi = B_TRUE;
13626 
13627 		/*
13628 		 * This packet came in on an interface other than the
13629 		 * one associated with the destination address.
13630 		 * "Gateway" it to the appropriate interface here.
13631 		 * As long as the ills belong to the same group,
13632 		 * we don't consider them to arriving on the wrong
13633 		 * interface. Thus, when the switch is doing inbound
13634 		 * load spreading, we won't drop packets when we
13635 		 * are doing strict multihoming checks. Note, the
13636 		 * same holds true for 'usesrc groups' where the
13637 		 * destination address may belong to another interface
13638 		 * to allow multipathing to happen
13639 		 */
13640 		ill_group = ill->ill_group;
13641 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13642 		ill_ifindex = ill->ill_usesrc_ifindex;
13643 		ire_group = ire_ill->ill_group;
13644 
13645 		/*
13646 		 * If it's part of the same IPMP group, or if it's a legal
13647 		 * address on the 'usesrc' interface, then bypass strict
13648 		 * checks.
13649 		 */
13650 		if (ill_group != NULL && ill_group == ire_group) {
13651 			check_multi = B_FALSE;
13652 		} else if (ill_ifindex != 0 &&
13653 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13654 			check_multi = B_FALSE;
13655 		}
13656 
13657 		if (check_multi &&
13658 		    ip_strict_dst_multihoming &&
13659 		    ((ill->ill_flags &
13660 		    ire->ire_ipif->ipif_ill->ill_flags &
13661 		    ILLF_ROUTER) == 0)) {
13662 			/* Drop packet */
13663 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13664 			freemsg(mp);
13665 			return (B_TRUE);
13666 		}
13667 
13668 		/*
13669 		 * Change the queue (for non-virtual destination network
13670 		 * interfaces) and ip_rput_local will be called with the right
13671 		 * queue
13672 		 */
13673 		q = ire->ire_rfq;
13674 	}
13675 	/* Must be broadcast.  We'll take it. */
13676 	*qp = q;
13677 	return (B_FALSE);
13678 }
13679 
13680 ire_t *
13681 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13682 {
13683 	ipha_t	*ipha;
13684 	ipaddr_t ip_dst, ip_src;
13685 	ire_t	*src_ire = NULL;
13686 	ill_t	*stq_ill;
13687 	uint_t	hlen;
13688 	uint_t	pkt_len;
13689 	uint32_t sum;
13690 	queue_t	*dev_q;
13691 	boolean_t check_multirt = B_FALSE;
13692 
13693 
13694 	ipha = (ipha_t *)mp->b_rptr;
13695 
13696 	/*
13697 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13698 	 * The loopback address check for both src and dst has already
13699 	 * been checked in ip_input
13700 	 */
13701 	ip_dst = ntohl(dst);
13702 	ip_src = ntohl(ipha->ipha_src);
13703 
13704 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13705 	    IN_CLASSD(ip_src)) {
13706 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13707 		goto drop;
13708 	}
13709 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13710 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13711 
13712 	if (src_ire != NULL) {
13713 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13714 		goto drop;
13715 	}
13716 
13717 
13718 	/* No ire cache of nexthop. So first create one  */
13719 	if (ire == NULL) {
13720 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13721 		/*
13722 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13723 		 * is not set. So upon return from ire_forward
13724 		 * check_multirt should remain as false.
13725 		 */
13726 		ASSERT(!check_multirt);
13727 		if (ire == NULL) {
13728 			/* An attempt was made to forward the packet */
13729 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13730 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13731 			mp->b_prev = mp->b_next = 0;
13732 			/* send icmp unreachable */
13733 			/* Sent by forwarding path, and router is global zone */
13734 			if (ip_source_routed(ipha)) {
13735 				icmp_unreachable(ill->ill_wq, mp,
13736 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13737 			} else {
13738 				icmp_unreachable(ill->ill_wq, mp,
13739 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13740 			}
13741 			return (ire);
13742 		}
13743 	}
13744 
13745 	/*
13746 	 * Forwarding fastpath exception case:
13747 	 * If either of the follwoing case is true, we take
13748 	 * the slowpath
13749 	 *	o forwarding is not enabled
13750 	 *	o incoming and outgoing interface are the same, or the same
13751 	 *	  IPMP group
13752 	 *	o corresponding ire is in incomplete state
13753 	 *	o packet needs fragmentation
13754 	 *
13755 	 * The codeflow from here on is thus:
13756 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13757 	 */
13758 	pkt_len = ntohs(ipha->ipha_length);
13759 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13760 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13761 	    !(ill->ill_flags & ILLF_ROUTER) ||
13762 	    (ill == stq_ill) ||
13763 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13764 	    (ire->ire_nce == NULL) ||
13765 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13766 	    (pkt_len > ire->ire_max_frag) ||
13767 	    ipha->ipha_ttl <= 1) {
13768 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13769 		    ipha, ill, B_FALSE);
13770 		return (ire);
13771 	}
13772 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13773 
13774 	DTRACE_PROBE4(ip4__forwarding__start,
13775 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13776 
13777 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13778 	    ill, stq_ill, ipha, mp, mp);
13779 
13780 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13781 
13782 	if (mp == NULL)
13783 		goto drop;
13784 
13785 	mp->b_datap->db_struioun.cksum.flags = 0;
13786 	/* Adjust the checksum to reflect the ttl decrement. */
13787 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13788 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13789 	ipha->ipha_ttl--;
13790 
13791 	dev_q = ire->ire_stq->q_next;
13792 	if ((dev_q->q_next != NULL ||
13793 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13794 		goto indiscard;
13795 	}
13796 
13797 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13798 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13799 
13800 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13801 		mblk_t *mpip = mp;
13802 
13803 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13804 		if (mp != NULL) {
13805 			DTRACE_PROBE4(ip4__physical__out__start,
13806 			    ill_t *, NULL, ill_t *, stq_ill,
13807 			    ipha_t *, ipha, mblk_t *, mp);
13808 			FW_HOOKS(ip4_physical_out_event,
13809 			    ipv4firewall_physical_out,
13810 			    NULL, stq_ill, ipha, mp, mpip);
13811 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13812 			    mp);
13813 			if (mp == NULL)
13814 				goto drop;
13815 
13816 			UPDATE_IB_PKT_COUNT(ire);
13817 			ire->ire_last_used_time = lbolt;
13818 			BUMP_MIB(stq_ill->ill_ip_mib,
13819 			    ipIfStatsHCOutForwDatagrams);
13820 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13821 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13822 			    pkt_len);
13823 			putnext(ire->ire_stq, mp);
13824 			return (ire);
13825 		}
13826 	}
13827 
13828 indiscard:
13829 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13830 drop:
13831 	if (mp != NULL)
13832 		freemsg(mp);
13833 	if (src_ire != NULL)
13834 		ire_refrele(src_ire);
13835 	return (ire);
13836 
13837 }
13838 
13839 /*
13840  * This function is called in the forwarding slowpath, when
13841  * either the ire lacks the link-layer address, or the packet needs
13842  * further processing(eg. fragmentation), before transmission.
13843  */
13844 
13845 static void
13846 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13847     ill_t *ill, boolean_t ll_multicast)
13848 {
13849 	ill_group_t	*ill_group;
13850 	ill_group_t	*ire_group;
13851 	queue_t		*dev_q;
13852 	ire_t		*src_ire;
13853 
13854 	ASSERT(ire->ire_stq != NULL);
13855 
13856 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13857 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13858 
13859 	if (ll_multicast != 0) {
13860 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13861 		goto drop_pkt;
13862 	}
13863 
13864 	/*
13865 	 * check if ipha_src is a broadcast address. Note that this
13866 	 * check is redundant when we get here from ip_fast_forward()
13867 	 * which has already done this check. However, since we can
13868 	 * also get here from ip_rput_process_broadcast() or, for
13869 	 * for the slow path through ip_fast_forward(), we perform
13870 	 * the check again for code-reusability
13871 	 */
13872 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13873 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13874 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13875 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13876 		if (src_ire != NULL)
13877 			ire_refrele(src_ire);
13878 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13879 		ip2dbg(("ip_rput_process_forward: Received packet with"
13880 		    " bad src/dst address on %s\n", ill->ill_name));
13881 		goto drop_pkt;
13882 	}
13883 
13884 	ill_group = ill->ill_group;
13885 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13886 	/*
13887 	 * Check if we want to forward this one at this time.
13888 	 * We allow source routed packets on a host provided that
13889 	 * they go out the same interface or same interface group
13890 	 * as they came in on.
13891 	 *
13892 	 * XXX To be quicker, we may wish to not chase pointers to
13893 	 * get the ILLF_ROUTER flag and instead store the
13894 	 * forwarding policy in the ire.  An unfortunate
13895 	 * side-effect of that would be requiring an ire flush
13896 	 * whenever the ILLF_ROUTER flag changes.
13897 	 */
13898 	if (((ill->ill_flags &
13899 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13900 	    ILLF_ROUTER) == 0) &&
13901 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13902 	    (ill_group != NULL && ill_group == ire_group)))) {
13903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13904 		if (ip_source_routed(ipha)) {
13905 			q = WR(q);
13906 			/*
13907 			 * Clear the indication that this may have
13908 			 * hardware checksum as we are not using it.
13909 			 */
13910 			DB_CKSUMFLAGS(mp) = 0;
13911 			/* Sent by forwarding path, and router is global zone */
13912 			icmp_unreachable(q, mp,
13913 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13914 			return;
13915 		}
13916 		goto drop_pkt;
13917 	}
13918 
13919 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13920 
13921 	/* Packet is being forwarded. Turning off hwcksum flag. */
13922 	DB_CKSUMFLAGS(mp) = 0;
13923 	if (ip_g_send_redirects) {
13924 		/*
13925 		 * Check whether the incoming interface and outgoing
13926 		 * interface is part of the same group. If so,
13927 		 * send redirects.
13928 		 *
13929 		 * Check the source address to see if it originated
13930 		 * on the same logical subnet it is going back out on.
13931 		 * If so, we should be able to send it a redirect.
13932 		 * Avoid sending a redirect if the destination
13933 		 * is directly connected (i.e., ipha_dst is the same
13934 		 * as ire_gateway_addr or the ire_addr of the
13935 		 * nexthop IRE_CACHE ), or if the packet was source
13936 		 * routed out this interface.
13937 		 */
13938 		ipaddr_t src, nhop;
13939 		mblk_t	*mp1;
13940 		ire_t	*nhop_ire = NULL;
13941 
13942 		/*
13943 		 * Check whether ire_rfq and q are from the same ill
13944 		 * or if they are not same, they at least belong
13945 		 * to the same group. If so, send redirects.
13946 		 */
13947 		if ((ire->ire_rfq == q ||
13948 		    (ill_group != NULL && ill_group == ire_group)) &&
13949 		    !ip_source_routed(ipha)) {
13950 
13951 			nhop = (ire->ire_gateway_addr != 0 ?
13952 			    ire->ire_gateway_addr : ire->ire_addr);
13953 
13954 			if (ipha->ipha_dst == nhop) {
13955 				/*
13956 				 * We avoid sending a redirect if the
13957 				 * destination is directly connected
13958 				 * because it is possible that multiple
13959 				 * IP subnets may have been configured on
13960 				 * the link, and the source may not
13961 				 * be on the same subnet as ip destination,
13962 				 * even though they are on the same
13963 				 * physical link.
13964 				 */
13965 				goto sendit;
13966 			}
13967 
13968 			src = ipha->ipha_src;
13969 
13970 			/*
13971 			 * We look up the interface ire for the nexthop,
13972 			 * to see if ipha_src is in the same subnet
13973 			 * as the nexthop.
13974 			 *
13975 			 * Note that, if, in the future, IRE_CACHE entries
13976 			 * are obsoleted,  this lookup will not be needed,
13977 			 * as the ire passed to this function will be the
13978 			 * same as the nhop_ire computed below.
13979 			 */
13980 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13981 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13982 			    0, NULL, MATCH_IRE_TYPE);
13983 
13984 			if (nhop_ire != NULL) {
13985 				if ((src & nhop_ire->ire_mask) ==
13986 				    (nhop & nhop_ire->ire_mask)) {
13987 					/*
13988 					 * The source is directly connected.
13989 					 * Just copy the ip header (which is
13990 					 * in the first mblk)
13991 					 */
13992 					mp1 = copyb(mp);
13993 					if (mp1 != NULL) {
13994 						icmp_send_redirect(WR(q), mp1,
13995 						    nhop);
13996 					}
13997 				}
13998 				ire_refrele(nhop_ire);
13999 			}
14000 		}
14001 	}
14002 sendit:
14003 	dev_q = ire->ire_stq->q_next;
14004 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14005 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14006 		freemsg(mp);
14007 		return;
14008 	}
14009 
14010 	ip_rput_forward(ire, ipha, mp, ill);
14011 	return;
14012 
14013 drop_pkt:
14014 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14015 	freemsg(mp);
14016 }
14017 
14018 ire_t *
14019 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14020     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14021 {
14022 	queue_t		*q;
14023 	uint16_t	hcksumflags;
14024 
14025 	q = *qp;
14026 
14027 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14028 
14029 	/*
14030 	 * Clear the indication that this may have hardware
14031 	 * checksum as we are not using it for forwarding.
14032 	 */
14033 	hcksumflags = DB_CKSUMFLAGS(mp);
14034 	DB_CKSUMFLAGS(mp) = 0;
14035 
14036 	/*
14037 	 * Directed broadcast forwarding: if the packet came in over a
14038 	 * different interface then it is routed out over we can forward it.
14039 	 */
14040 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14041 		ire_refrele(ire);
14042 		freemsg(mp);
14043 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14044 		return (NULL);
14045 	}
14046 	/*
14047 	 * For multicast we have set dst to be INADDR_BROADCAST
14048 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14049 	 * only for broadcast packets.
14050 	 */
14051 	if (!CLASSD(ipha->ipha_dst)) {
14052 		ire_t *new_ire;
14053 		ipif_t *ipif;
14054 		/*
14055 		 * For ill groups, as the switch duplicates broadcasts
14056 		 * across all the ports, we need to filter out and
14057 		 * send up only one copy. There is one copy for every
14058 		 * broadcast address on each ill. Thus, we look for a
14059 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14060 		 * later to see whether this ill is eligible to receive
14061 		 * them or not. ill_nominate_bcast_rcv() nominates only
14062 		 * one set of IREs for receiving.
14063 		 */
14064 
14065 		ipif = ipif_get_next_ipif(NULL, ill);
14066 		if (ipif == NULL) {
14067 			ire_refrele(ire);
14068 			freemsg(mp);
14069 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14070 			return (NULL);
14071 		}
14072 		new_ire = ire_ctable_lookup(dst, 0, 0,
14073 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
14074 		ipif_refrele(ipif);
14075 
14076 		if (new_ire != NULL) {
14077 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14078 				ire_refrele(ire);
14079 				ire_refrele(new_ire);
14080 				freemsg(mp);
14081 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14082 				return (NULL);
14083 			}
14084 			/*
14085 			 * In the special case of multirouted broadcast
14086 			 * packets, we unconditionally need to "gateway"
14087 			 * them to the appropriate interface here.
14088 			 * In the normal case, this cannot happen, because
14089 			 * there is no broadcast IRE tagged with the
14090 			 * RTF_MULTIRT flag.
14091 			 */
14092 			if (new_ire->ire_flags & RTF_MULTIRT) {
14093 				ire_refrele(new_ire);
14094 				if (ire->ire_rfq != NULL) {
14095 					q = ire->ire_rfq;
14096 					*qp = q;
14097 				}
14098 			} else {
14099 				ire_refrele(ire);
14100 				ire = new_ire;
14101 			}
14102 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14103 			if (!ip_g_forward_directed_bcast) {
14104 				/*
14105 				 * Free the message if
14106 				 * ip_g_forward_directed_bcast is turned
14107 				 * off for non-local broadcast.
14108 				 */
14109 				ire_refrele(ire);
14110 				freemsg(mp);
14111 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14112 				return (NULL);
14113 			}
14114 		} else {
14115 			/*
14116 			 * This CGTP packet successfully passed the
14117 			 * CGTP filter, but the related CGTP
14118 			 * broadcast IRE has not been found,
14119 			 * meaning that the redundant ipif is
14120 			 * probably down. However, if we discarded
14121 			 * this packet, its duplicate would be
14122 			 * filtered out by the CGTP filter so none
14123 			 * of them would get through. So we keep
14124 			 * going with this one.
14125 			 */
14126 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14127 			if (ire->ire_rfq != NULL) {
14128 				q = ire->ire_rfq;
14129 				*qp = q;
14130 			}
14131 		}
14132 	}
14133 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14134 		/*
14135 		 * Verify that there are not more then one
14136 		 * IRE_BROADCAST with this broadcast address which
14137 		 * has ire_stq set.
14138 		 * TODO: simplify, loop over all IRE's
14139 		 */
14140 		ire_t	*ire1;
14141 		int	num_stq = 0;
14142 		mblk_t	*mp1;
14143 
14144 		/* Find the first one with ire_stq set */
14145 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14146 		for (ire1 = ire; ire1 &&
14147 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14148 		    ire1 = ire1->ire_next)
14149 			;
14150 		if (ire1) {
14151 			ire_refrele(ire);
14152 			ire = ire1;
14153 			IRE_REFHOLD(ire);
14154 		}
14155 
14156 		/* Check if there are additional ones with stq set */
14157 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14158 			if (ire->ire_addr != ire1->ire_addr)
14159 				break;
14160 			if (ire1->ire_stq) {
14161 				num_stq++;
14162 				break;
14163 			}
14164 		}
14165 		rw_exit(&ire->ire_bucket->irb_lock);
14166 		if (num_stq == 1 && ire->ire_stq != NULL) {
14167 			ip1dbg(("ip_rput_process_broadcast: directed "
14168 			    "broadcast to 0x%x\n",
14169 			    ntohl(ire->ire_addr)));
14170 			mp1 = copymsg(mp);
14171 			if (mp1) {
14172 				switch (ipha->ipha_protocol) {
14173 				case IPPROTO_UDP:
14174 					ip_udp_input(q, mp1, ipha, ire, ill);
14175 					break;
14176 				default:
14177 					ip_proto_input(q, mp1, ipha, ire, ill);
14178 					break;
14179 				}
14180 			}
14181 			/*
14182 			 * Adjust ttl to 2 (1+1 - the forward engine
14183 			 * will decrement it by one.
14184 			 */
14185 			if (ip_csum_hdr(ipha)) {
14186 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14187 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14188 				freemsg(mp);
14189 				ire_refrele(ire);
14190 				return (NULL);
14191 			}
14192 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14193 			ipha->ipha_hdr_checksum = 0;
14194 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14195 			ip_rput_process_forward(q, mp, ire, ipha,
14196 			    ill, ll_multicast);
14197 			ire_refrele(ire);
14198 			return (NULL);
14199 		}
14200 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14201 		    ntohl(ire->ire_addr)));
14202 	}
14203 
14204 
14205 	/* Restore any hardware checksum flags */
14206 	DB_CKSUMFLAGS(mp) = hcksumflags;
14207 	return (ire);
14208 }
14209 
14210 /* ARGSUSED */
14211 static boolean_t
14212 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14213     int *ll_multicast, ipaddr_t *dstp)
14214 {
14215 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14216 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14217 	    ntohs(ipha->ipha_length));
14218 
14219 	/*
14220 	 * Forward packets only if we have joined the allmulti
14221 	 * group on this interface.
14222 	 */
14223 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14224 		int retval;
14225 
14226 		/*
14227 		 * Clear the indication that this may have hardware
14228 		 * checksum as we are not using it.
14229 		 */
14230 		DB_CKSUMFLAGS(mp) = 0;
14231 		retval = ip_mforward(ill, ipha, mp);
14232 		/* ip_mforward updates mib variables if needed */
14233 		/* clear b_prev - used by ip_mroute_decap */
14234 		mp->b_prev = NULL;
14235 
14236 		switch (retval) {
14237 		case 0:
14238 			/*
14239 			 * pkt is okay and arrived on phyint.
14240 			 *
14241 			 * If we are running as a multicast router
14242 			 * we need to see all IGMP and/or PIM packets.
14243 			 */
14244 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14245 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14246 				goto done;
14247 			}
14248 			break;
14249 		case -1:
14250 			/* pkt is mal-formed, toss it */
14251 			goto drop_pkt;
14252 		case 1:
14253 			/* pkt is okay and arrived on a tunnel */
14254 			/*
14255 			 * If we are running a multicast router
14256 			 *  we need to see all igmp packets.
14257 			 */
14258 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14259 				*dstp = INADDR_BROADCAST;
14260 				*ll_multicast = 1;
14261 				return (B_FALSE);
14262 			}
14263 
14264 			goto drop_pkt;
14265 		}
14266 	}
14267 
14268 	ILM_WALKER_HOLD(ill);
14269 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14270 		/*
14271 		 * This might just be caused by the fact that
14272 		 * multiple IP Multicast addresses map to the same
14273 		 * link layer multicast - no need to increment counter!
14274 		 */
14275 		ILM_WALKER_RELE(ill);
14276 		freemsg(mp);
14277 		return (B_TRUE);
14278 	}
14279 	ILM_WALKER_RELE(ill);
14280 done:
14281 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14282 	/*
14283 	 * This assumes the we deliver to all streams for multicast
14284 	 * and broadcast packets.
14285 	 */
14286 	*dstp = INADDR_BROADCAST;
14287 	*ll_multicast = 1;
14288 	return (B_FALSE);
14289 drop_pkt:
14290 	ip2dbg(("ip_rput: drop pkt\n"));
14291 	freemsg(mp);
14292 	return (B_TRUE);
14293 }
14294 
14295 static boolean_t
14296 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14297     int *ll_multicast, mblk_t **mpp)
14298 {
14299 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14300 	boolean_t must_copy = B_FALSE;
14301 	struct iocblk   *iocp;
14302 	ipha_t		*ipha;
14303 
14304 #define	rptr    ((uchar_t *)ipha)
14305 
14306 	first_mp = *first_mpp;
14307 	mp = *mpp;
14308 
14309 	ASSERT(first_mp == mp);
14310 
14311 	/*
14312 	 * if db_ref > 1 then copymsg and free original. Packet may be
14313 	 * changed and do not want other entity who has a reference to this
14314 	 * message to trip over the changes. This is a blind change because
14315 	 * trying to catch all places that might change packet is too
14316 	 * difficult (since it may be a module above this one)
14317 	 *
14318 	 * This corresponds to the non-fast path case. We walk down the full
14319 	 * chain in this case, and check the db_ref count of all the dblks,
14320 	 * and do a copymsg if required. It is possible that the db_ref counts
14321 	 * of the data blocks in the mblk chain can be different.
14322 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14323 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14324 	 * 'snoop' is running.
14325 	 */
14326 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14327 		if (mp1->b_datap->db_ref > 1) {
14328 			must_copy = B_TRUE;
14329 			break;
14330 		}
14331 	}
14332 
14333 	if (must_copy) {
14334 		mp1 = copymsg(mp);
14335 		if (mp1 == NULL) {
14336 			for (mp1 = mp; mp1 != NULL;
14337 			    mp1 = mp1->b_cont) {
14338 				mp1->b_next = NULL;
14339 				mp1->b_prev = NULL;
14340 			}
14341 			freemsg(mp);
14342 			if (ill != NULL) {
14343 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14344 			} else {
14345 				BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
14346 			}
14347 			return (B_TRUE);
14348 		}
14349 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14350 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14351 			/* Copy b_prev - used by ip_mroute_decap */
14352 			to_mp->b_prev = from_mp->b_prev;
14353 			from_mp->b_prev = NULL;
14354 		}
14355 		*first_mpp = first_mp = mp1;
14356 		freemsg(mp);
14357 		mp = mp1;
14358 		*mpp = mp1;
14359 	}
14360 
14361 	ipha = (ipha_t *)mp->b_rptr;
14362 
14363 	/*
14364 	 * previous code has a case for M_DATA.
14365 	 * We want to check how that happens.
14366 	 */
14367 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14368 	switch (first_mp->b_datap->db_type) {
14369 	case M_PROTO:
14370 	case M_PCPROTO:
14371 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14372 		    DL_UNITDATA_IND) {
14373 			/* Go handle anything other than data elsewhere. */
14374 			ip_rput_dlpi(q, mp);
14375 			return (B_TRUE);
14376 		}
14377 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14378 		/* Ditch the DLPI header. */
14379 		mp1 = mp->b_cont;
14380 		ASSERT(first_mp == mp);
14381 		*first_mpp = mp1;
14382 		freeb(mp);
14383 		*mpp = mp1;
14384 		return (B_FALSE);
14385 	case M_IOCACK:
14386 		ip1dbg(("got iocack "));
14387 		iocp = (struct iocblk *)mp->b_rptr;
14388 		switch (iocp->ioc_cmd) {
14389 		case DL_IOC_HDR_INFO:
14390 			ill = (ill_t *)q->q_ptr;
14391 			ill_fastpath_ack(ill, mp);
14392 			return (B_TRUE);
14393 		case SIOCSTUNPARAM:
14394 		case OSIOCSTUNPARAM:
14395 			/* Go through qwriter_ip */
14396 			break;
14397 		case SIOCGTUNPARAM:
14398 		case OSIOCGTUNPARAM:
14399 			ip_rput_other(NULL, q, mp, NULL);
14400 			return (B_TRUE);
14401 		default:
14402 			putnext(q, mp);
14403 			return (B_TRUE);
14404 		}
14405 		/* FALLTHRU */
14406 	case M_ERROR:
14407 	case M_HANGUP:
14408 		/*
14409 		 * Since this is on the ill stream we unconditionally
14410 		 * bump up the refcount
14411 		 */
14412 		ill_refhold(ill);
14413 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14414 		    B_FALSE);
14415 		return (B_TRUE);
14416 	case M_CTL:
14417 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14418 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14419 			IPHADA_M_CTL)) {
14420 			/*
14421 			 * It's an IPsec accelerated packet.
14422 			 * Make sure that the ill from which we received the
14423 			 * packet has enabled IPsec hardware acceleration.
14424 			 */
14425 			if (!(ill->ill_capabilities &
14426 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14427 				/* IPsec kstats: bean counter */
14428 				freemsg(mp);
14429 				return (B_TRUE);
14430 			}
14431 
14432 			/*
14433 			 * Make mp point to the mblk following the M_CTL,
14434 			 * then process according to type of mp.
14435 			 * After this processing, first_mp will point to
14436 			 * the data-attributes and mp to the pkt following
14437 			 * the M_CTL.
14438 			 */
14439 			mp = first_mp->b_cont;
14440 			if (mp == NULL) {
14441 				freemsg(first_mp);
14442 				return (B_TRUE);
14443 			}
14444 			/*
14445 			 * A Hardware Accelerated packet can only be M_DATA
14446 			 * ESP or AH packet.
14447 			 */
14448 			if (mp->b_datap->db_type != M_DATA) {
14449 				/* non-M_DATA IPsec accelerated packet */
14450 				IPSECHW_DEBUG(IPSECHW_PKT,
14451 				    ("non-M_DATA IPsec accelerated pkt\n"));
14452 				freemsg(first_mp);
14453 				return (B_TRUE);
14454 			}
14455 			ipha = (ipha_t *)mp->b_rptr;
14456 			if (ipha->ipha_protocol != IPPROTO_AH &&
14457 			    ipha->ipha_protocol != IPPROTO_ESP) {
14458 				IPSECHW_DEBUG(IPSECHW_PKT,
14459 				    ("non-M_DATA IPsec accelerated pkt\n"));
14460 				freemsg(first_mp);
14461 				return (B_TRUE);
14462 			}
14463 			*mpp = mp;
14464 			return (B_FALSE);
14465 		}
14466 		putnext(q, mp);
14467 		return (B_TRUE);
14468 	case M_FLUSH:
14469 		if (*mp->b_rptr & FLUSHW) {
14470 			*mp->b_rptr &= ~FLUSHR;
14471 			qreply(q, mp);
14472 			return (B_TRUE);
14473 		}
14474 		freemsg(mp);
14475 		return (B_TRUE);
14476 	case M_IOCNAK:
14477 		ip1dbg(("got iocnak "));
14478 		iocp = (struct iocblk *)mp->b_rptr;
14479 		switch (iocp->ioc_cmd) {
14480 		case DL_IOC_HDR_INFO:
14481 		case SIOCSTUNPARAM:
14482 		case OSIOCSTUNPARAM:
14483 			/*
14484 			 * Since this is on the ill stream we unconditionally
14485 			 * bump up the refcount
14486 			 */
14487 			ill_refhold(ill);
14488 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14489 			    CUR_OP, B_FALSE);
14490 			return (B_TRUE);
14491 		case SIOCGTUNPARAM:
14492 		case OSIOCGTUNPARAM:
14493 			ip_rput_other(NULL, q, mp, NULL);
14494 			return (B_TRUE);
14495 		default:
14496 			break;
14497 		}
14498 		/* FALLTHRU */
14499 	default:
14500 		putnext(q, mp);
14501 		return (B_TRUE);
14502 	}
14503 }
14504 
14505 /* Read side put procedure.  Packets coming from the wire arrive here. */
14506 void
14507 ip_rput(queue_t *q, mblk_t *mp)
14508 {
14509 	ill_t	*ill;
14510 	mblk_t	 *dmp = NULL;
14511 
14512 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14513 
14514 	ill = (ill_t *)q->q_ptr;
14515 
14516 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14517 		union DL_primitives *dl;
14518 
14519 		/*
14520 		 * Things are opening or closing. Only accept DLPI control
14521 		 * messages. In the open case, the ill->ill_ipif has not yet
14522 		 * been created. In the close case, things hanging off the
14523 		 * ill could have been freed already. In either case it
14524 		 * may not be safe to proceed further.
14525 		 */
14526 
14527 		dl = (union DL_primitives *)mp->b_rptr;
14528 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14529 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14530 			/*
14531 			 * Also SIOC[GS]TUN* ioctls can come here.
14532 			 */
14533 			inet_freemsg(mp);
14534 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14535 			    "ip_input_end: q %p (%S)", q, "uninit");
14536 			return;
14537 		}
14538 	}
14539 
14540 	/*
14541 	 * if db_ref > 1 then copymsg and free original. Packet may be
14542 	 * changed and we do not want the other entity who has a reference to
14543 	 * this message to trip over the changes. This is a blind change because
14544 	 * trying to catch all places that might change the packet is too
14545 	 * difficult.
14546 	 *
14547 	 * This corresponds to the fast path case, where we have a chain of
14548 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14549 	 * in the mblk chain. There doesn't seem to be a reason why a device
14550 	 * driver would send up data with varying db_ref counts in the mblk
14551 	 * chain. In any case the Fast path is a private interface, and our
14552 	 * drivers don't do such a thing. Given the above assumption, there is
14553 	 * no need to walk down the entire mblk chain (which could have a
14554 	 * potential performance problem)
14555 	 */
14556 	if (mp->b_datap->db_ref > 1) {
14557 		mblk_t  *mp1;
14558 		boolean_t adjusted = B_FALSE;
14559 		IP_STAT(ip_db_ref);
14560 
14561 		/*
14562 		 * The IP_RECVSLLA option depends on having the link layer
14563 		 * header. First check that:
14564 		 * a> the underlying device is of type ether, since this
14565 		 * option is currently supported only over ethernet.
14566 		 * b> there is enough room to copy over the link layer header.
14567 		 *
14568 		 * Once the checks are done, adjust rptr so that the link layer
14569 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14570 		 * be returned by some non-ethernet drivers but in this case the
14571 		 * second check will fail.
14572 		 */
14573 		if (ill->ill_type == IFT_ETHER &&
14574 		    (mp->b_rptr - mp->b_datap->db_base) >=
14575 		    sizeof (struct ether_header)) {
14576 			mp->b_rptr -= sizeof (struct ether_header);
14577 			adjusted = B_TRUE;
14578 		}
14579 		mp1 = copymsg(mp);
14580 		if (mp1 == NULL) {
14581 			mp->b_next = NULL;
14582 			/* clear b_prev - used by ip_mroute_decap */
14583 			mp->b_prev = NULL;
14584 			freemsg(mp);
14585 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14586 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14587 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14588 			return;
14589 		}
14590 		if (adjusted) {
14591 			/*
14592 			 * Copy is done. Restore the pointer in the _new_ mblk
14593 			 */
14594 			mp1->b_rptr += sizeof (struct ether_header);
14595 		}
14596 		/* Copy b_prev - used by ip_mroute_decap */
14597 		mp1->b_prev = mp->b_prev;
14598 		mp->b_prev = NULL;
14599 		freemsg(mp);
14600 		mp = mp1;
14601 	}
14602 	if (DB_TYPE(mp) == M_DATA) {
14603 		dmp = mp;
14604 	} else if (DB_TYPE(mp) == M_PROTO &&
14605 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14606 		dmp = mp->b_cont;
14607 	}
14608 	if (dmp != NULL) {
14609 		/*
14610 		 * IP header ptr not aligned?
14611 		 * OR IP header not complete in first mblk
14612 		 */
14613 		if (!OK_32PTR(dmp->b_rptr) ||
14614 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14615 			if (!ip_check_and_align_header(q, dmp))
14616 				return;
14617 		}
14618 	}
14619 
14620 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14621 	    "ip_rput_end: q %p (%S)", q, "end");
14622 
14623 	ip_input(ill, NULL, mp, NULL);
14624 }
14625 
14626 /*
14627  * Direct read side procedure capable of dealing with chains. GLDv3 based
14628  * drivers call this function directly with mblk chains while STREAMS
14629  * read side procedure ip_rput() calls this for single packet with ip_ring
14630  * set to NULL to process one packet at a time.
14631  *
14632  * The ill will always be valid if this function is called directly from
14633  * the driver.
14634  *
14635  * If ip_input() is called from GLDv3:
14636  *
14637  *   - This must be a non-VLAN IP stream.
14638  *   - 'mp' is either an untagged or a special priority-tagged packet.
14639  *   - Any VLAN tag that was in the MAC header has been stripped.
14640  *
14641  * Thus, there is no need to adjust b_rptr in this function.
14642  */
14643 /* ARGSUSED */
14644 void
14645 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14646     struct mac_header_info_s *mhip)
14647 {
14648 	ipaddr_t		dst = NULL;
14649 	ipaddr_t		prev_dst;
14650 	ire_t			*ire = NULL;
14651 	ipha_t			*ipha;
14652 	uint_t			pkt_len;
14653 	ssize_t			len;
14654 	uint_t			opt_len;
14655 	int			ll_multicast;
14656 	int			cgtp_flt_pkt;
14657 	queue_t			*q = ill->ill_rq;
14658 	squeue_t		*curr_sqp = NULL;
14659 	mblk_t 			*head = NULL;
14660 	mblk_t			*tail = NULL;
14661 	mblk_t			*first_mp;
14662 	mblk_t 			*mp;
14663 	int			cnt = 0;
14664 
14665 	ASSERT(mp_chain != NULL);
14666 	ASSERT(ill != NULL);
14667 
14668 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14669 
14670 #define	rptr	((uchar_t *)ipha)
14671 
14672 	while (mp_chain != NULL) {
14673 		first_mp = mp = mp_chain;
14674 		mp_chain = mp_chain->b_next;
14675 		mp->b_next = NULL;
14676 		ll_multicast = 0;
14677 
14678 		/*
14679 		 * We do ire caching from one iteration to
14680 		 * another. In the event the packet chain contains
14681 		 * all packets from the same dst, this caching saves
14682 		 * an ire_cache_lookup for each of the succeeding
14683 		 * packets in a packet chain.
14684 		 */
14685 		prev_dst = dst;
14686 
14687 		/*
14688 		 * ip_input fast path
14689 		 */
14690 
14691 		/* mblk type is not M_DATA */
14692 		if (mp->b_datap->db_type != M_DATA) {
14693 			if (ip_rput_process_notdata(q, &first_mp, ill,
14694 			    &ll_multicast, &mp))
14695 				continue;
14696 		}
14697 
14698 		/* Make sure its an M_DATA and that its aligned */
14699 		ASSERT(mp->b_datap->db_type == M_DATA);
14700 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14701 
14702 		ipha = (ipha_t *)mp->b_rptr;
14703 		len = mp->b_wptr - rptr;
14704 		pkt_len = ntohs(ipha->ipha_length);
14705 
14706 		/*
14707 		 * We must count all incoming packets, even if they end
14708 		 * up being dropped later on.
14709 		 */
14710 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14711 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14712 
14713 		/* multiple mblk or too short */
14714 		len -= pkt_len;
14715 		if (len != 0) {
14716 			/*
14717 			 * Make sure we have data length consistent
14718 			 * with the IP header.
14719 			 */
14720 			if (mp->b_cont == NULL) {
14721 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14722 					BUMP_MIB(ill->ill_ip_mib,
14723 					    ipIfStatsInHdrErrors);
14724 					ip2dbg(("ip_input: drop pkt\n"));
14725 					freemsg(mp);
14726 					continue;
14727 				}
14728 				mp->b_wptr = rptr + pkt_len;
14729 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14730 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14731 					BUMP_MIB(ill->ill_ip_mib,
14732 					    ipIfStatsInHdrErrors);
14733 					ip2dbg(("ip_input: drop pkt\n"));
14734 					freemsg(mp);
14735 					continue;
14736 				}
14737 				(void) adjmsg(mp, -len);
14738 				IP_STAT(ip_multimblk3);
14739 			}
14740 		}
14741 
14742 		/* Obtain the dst of the current packet */
14743 		dst = ipha->ipha_dst;
14744 
14745 		if (IP_LOOPBACK_ADDR(dst) ||
14746 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14747 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14748 			cmn_err(CE_CONT, "dst %X src %X\n",
14749 			    dst, ipha->ipha_src);
14750 			freemsg(mp);
14751 			continue;
14752 		}
14753 
14754 		/*
14755 		 * The event for packets being received from a 'physical'
14756 		 * interface is placed after validation of the source and/or
14757 		 * destination address as being local so that packets can be
14758 		 * redirected to loopback addresses using ipnat.
14759 		 */
14760 		DTRACE_PROBE4(ip4__physical__in__start,
14761 		    ill_t *, ill, ill_t *, NULL,
14762 		    ipha_t *, ipha, mblk_t *, first_mp);
14763 
14764 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14765 		    ill, NULL, ipha, first_mp, mp);
14766 
14767 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14768 
14769 		if (first_mp == NULL) {
14770 			continue;
14771 		}
14772 		dst = ipha->ipha_dst;
14773 
14774 		/*
14775 		 * Attach any necessary label information to
14776 		 * this packet
14777 		 */
14778 		if (is_system_labeled() &&
14779 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14780 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14781 			freemsg(mp);
14782 			continue;
14783 		}
14784 
14785 		/*
14786 		 * Reuse the cached ire only if the ipha_dst of the previous
14787 		 * packet is the same as the current packet AND it is not
14788 		 * INADDR_ANY.
14789 		 */
14790 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14791 		    (ire != NULL)) {
14792 			ire_refrele(ire);
14793 			ire = NULL;
14794 		}
14795 		opt_len = ipha->ipha_version_and_hdr_length -
14796 		    IP_SIMPLE_HDR_VERSION;
14797 
14798 		/*
14799 		 * Check to see if we can take the fastpath.
14800 		 * That is possible if the following conditions are met
14801 		 *	o Tsol disabled
14802 		 *	o CGTP disabled
14803 		 *	o ipp_action_count is 0
14804 		 *	o Mobile IP not running
14805 		 *	o no options in the packet
14806 		 *	o not a RSVP packet
14807 		 * 	o not a multicast packet
14808 		 */
14809 		if (!is_system_labeled() &&
14810 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14811 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14812 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14813 		    !ll_multicast && !CLASSD(dst)) {
14814 			if (ire == NULL)
14815 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14816 
14817 			/* incoming packet is for forwarding */
14818 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14819 				ire = ip_fast_forward(ire, dst, ill, mp);
14820 				continue;
14821 			}
14822 			/* incoming packet is for local consumption */
14823 			if (ire->ire_type & IRE_LOCAL)
14824 				goto local;
14825 		}
14826 
14827 		/*
14828 		 * Disable ire caching for anything more complex
14829 		 * than the simple fast path case we checked for above.
14830 		 */
14831 		if (ire != NULL) {
14832 			ire_refrele(ire);
14833 			ire = NULL;
14834 		}
14835 
14836 		/* Full-blown slow path */
14837 		if (opt_len != 0) {
14838 			if (len != 0)
14839 				IP_STAT(ip_multimblk4);
14840 			else
14841 				IP_STAT(ip_ipoptions);
14842 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
14843 			    &dst))
14844 				continue;
14845 		}
14846 
14847 		/*
14848 		 * Invoke the CGTP (multirouting) filtering module to process
14849 		 * the incoming packet. Packets identified as duplicates
14850 		 * must be discarded. Filtering is active only if the
14851 		 * the ip_cgtp_filter ndd variable is non-zero.
14852 		 */
14853 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14854 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14855 			cgtp_flt_pkt =
14856 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14857 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14858 				freemsg(first_mp);
14859 				continue;
14860 			}
14861 		}
14862 
14863 		/*
14864 		 * If rsvpd is running, let RSVP daemon handle its processing
14865 		 * and forwarding of RSVP multicast/unicast packets.
14866 		 * If rsvpd is not running but mrouted is running, RSVP
14867 		 * multicast packets are forwarded as multicast traffic
14868 		 * and RSVP unicast packets are forwarded by unicast router.
14869 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14870 		 * packets are not forwarded, but the unicast packets are
14871 		 * forwarded like unicast traffic.
14872 		 */
14873 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14874 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14875 			/* RSVP packet and rsvpd running. Treat as ours */
14876 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14877 			/*
14878 			 * This assumes that we deliver to all streams for
14879 			 * multicast and broadcast packets.
14880 			 * We have to force ll_multicast to 1 to handle the
14881 			 * M_DATA messages passed in from ip_mroute_decap.
14882 			 */
14883 			dst = INADDR_BROADCAST;
14884 			ll_multicast = 1;
14885 		} else if (CLASSD(dst)) {
14886 			/* packet is multicast */
14887 			mp->b_next = NULL;
14888 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14889 			    &ll_multicast, &dst))
14890 				continue;
14891 		}
14892 
14893 
14894 		/*
14895 		 * Check if the packet is coming from the Mobile IP
14896 		 * forward tunnel interface
14897 		 */
14898 		if (ill->ill_srcif_refcnt > 0) {
14899 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14900 			    NULL, ill, MATCH_IRE_TYPE);
14901 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14902 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14903 
14904 				/* We need to resolve the link layer info */
14905 				ire_refrele(ire);
14906 				ire = NULL;
14907 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14908 				    ll_multicast, dst);
14909 				continue;
14910 			}
14911 		}
14912 
14913 		if (ire == NULL) {
14914 			ire = ire_cache_lookup(dst, ALL_ZONES,
14915 			    MBLK_GETLABEL(mp));
14916 		}
14917 
14918 		/*
14919 		 * If mipagent is running and reverse tunnel is created as per
14920 		 * mobile node request, then any packet coming through the
14921 		 * incoming interface from the mobile-node, should be reverse
14922 		 * tunneled to it's home agent except those that are destined
14923 		 * to foreign agent only.
14924 		 * This needs source address based ire lookup. The routing
14925 		 * entries for source address based lookup are only created by
14926 		 * mipagent program only when a reverse tunnel is created.
14927 		 * Reference : RFC2002, RFC2344
14928 		 */
14929 		if (ill->ill_mrtun_refcnt > 0) {
14930 			ipaddr_t	srcaddr;
14931 			ire_t		*tmp_ire;
14932 
14933 			tmp_ire = ire;	/* Save, we might need it later */
14934 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14935 			    ire->ire_type != IRE_BROADCAST)) {
14936 				srcaddr = ipha->ipha_src;
14937 				ire = ire_mrtun_lookup(srcaddr, ill);
14938 				if (ire != NULL) {
14939 					/*
14940 					 * Should not be getting iphada packet
14941 					 * here. we should only get those for
14942 					 * IRE_LOCAL traffic, excluded above.
14943 					 * Fail-safe (drop packet) in the event
14944 					 * hardware is misbehaving.
14945 					 */
14946 					if (first_mp != mp) {
14947 						/* IPsec KSTATS: beancount me */
14948 						freemsg(first_mp);
14949 					} else {
14950 						/*
14951 						 * This packet must be forwarded
14952 						 * to Reverse Tunnel
14953 						 */
14954 						ip_mrtun_forward(ire, ill, mp);
14955 					}
14956 					ire_refrele(ire);
14957 					ire = NULL;
14958 					if (tmp_ire != NULL) {
14959 						ire_refrele(tmp_ire);
14960 						tmp_ire = NULL;
14961 					}
14962 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14963 					    "ip_input_end: q %p (%S)",
14964 					    q, "uninit");
14965 					continue;
14966 				}
14967 			}
14968 			/*
14969 			 * If this packet is from a non-mobilenode  or a
14970 			 * mobile-node which does not request reverse
14971 			 * tunnel service
14972 			 */
14973 			ire = tmp_ire;
14974 		}
14975 
14976 
14977 		/*
14978 		 * If we reach here that means the incoming packet satisfies
14979 		 * one of the following conditions:
14980 		 *   - packet is from a mobile node which does not request
14981 		 *	reverse tunnel
14982 		 *   - packet is from a non-mobile node, which is the most
14983 		 *	common case
14984 		 *   - packet is from a reverse tunnel enabled mobile node
14985 		 *	and destined to foreign agent only
14986 		 */
14987 
14988 		if (ire == NULL) {
14989 			/*
14990 			 * No IRE for this destination, so it can't be for us.
14991 			 * Unless we are forwarding, drop the packet.
14992 			 * We have to let source routed packets through
14993 			 * since we don't yet know if they are 'ping -l'
14994 			 * packets i.e. if they will go out over the
14995 			 * same interface as they came in on.
14996 			 */
14997 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14998 			if (ire == NULL)
14999 				continue;
15000 		}
15001 
15002 		/*
15003 		 * Broadcast IRE may indicate either broadcast or
15004 		 * multicast packet
15005 		 */
15006 		if (ire->ire_type == IRE_BROADCAST) {
15007 			/*
15008 			 * Skip broadcast checks if packet is UDP multicast;
15009 			 * we'd rather not enter ip_rput_process_broadcast()
15010 			 * unless the packet is broadcast for real, since
15011 			 * that routine is a no-op for multicast.
15012 			 */
15013 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15014 			    !CLASSD(ipha->ipha_dst)) {
15015 				ire = ip_rput_process_broadcast(&q, mp,
15016 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15017 				    ll_multicast);
15018 				if (ire == NULL)
15019 					continue;
15020 			}
15021 		} else if (ire->ire_stq != NULL) {
15022 			/* fowarding? */
15023 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15024 			    ll_multicast);
15025 			/* ip_rput_process_forward consumed the packet */
15026 			continue;
15027 		}
15028 
15029 local:
15030 		/* packet not for us */
15031 		if (ire->ire_rfq != q) {
15032 			if (ip_rput_notforus(&q, mp, ire, ill))
15033 				continue;
15034 		}
15035 
15036 		switch (ipha->ipha_protocol) {
15037 		case IPPROTO_TCP:
15038 			ASSERT(first_mp == mp);
15039 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15040 				mp, 0, q, ip_ring)) != NULL) {
15041 				if (curr_sqp == NULL) {
15042 					curr_sqp = GET_SQUEUE(mp);
15043 					ASSERT(cnt == 0);
15044 					cnt++;
15045 					head = tail = mp;
15046 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15047 					ASSERT(tail != NULL);
15048 					cnt++;
15049 					tail->b_next = mp;
15050 					tail = mp;
15051 				} else {
15052 					/*
15053 					 * A different squeue. Send the
15054 					 * chain for the previous squeue on
15055 					 * its way. This shouldn't happen
15056 					 * often unless interrupt binding
15057 					 * changes.
15058 					 */
15059 					IP_STAT(ip_input_multi_squeue);
15060 					squeue_enter_chain(curr_sqp, head,
15061 					    tail, cnt, SQTAG_IP_INPUT);
15062 					curr_sqp = GET_SQUEUE(mp);
15063 					head = mp;
15064 					tail = mp;
15065 					cnt = 1;
15066 				}
15067 			}
15068 			continue;
15069 		case IPPROTO_UDP:
15070 			ASSERT(first_mp == mp);
15071 			ip_udp_input(q, mp, ipha, ire, ill);
15072 			continue;
15073 		case IPPROTO_SCTP:
15074 			ASSERT(first_mp == mp);
15075 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15076 			    q, dst);
15077 			/* ire has been released by ip_sctp_input */
15078 			ire = NULL;
15079 			continue;
15080 		default:
15081 			ip_proto_input(q, first_mp, ipha, ire, ill);
15082 			continue;
15083 		}
15084 	}
15085 
15086 	if (ire != NULL)
15087 		ire_refrele(ire);
15088 
15089 	if (head != NULL)
15090 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15091 
15092 	/*
15093 	 * This code is there just to make netperf/ttcp look good.
15094 	 *
15095 	 * Its possible that after being in polling mode (and having cleared
15096 	 * the backlog), squeues have turned the interrupt frequency higher
15097 	 * to improve latency at the expense of more CPU utilization (less
15098 	 * packets per interrupts or more number of interrupts). Workloads
15099 	 * like ttcp/netperf do manage to tickle polling once in a while
15100 	 * but for the remaining time, stay in higher interrupt mode since
15101 	 * their packet arrival rate is pretty uniform and this shows up
15102 	 * as higher CPU utilization. Since people care about CPU utilization
15103 	 * while running netperf/ttcp, turn the interrupt frequency back to
15104 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15105 	 */
15106 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15107 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15108 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15109 			ip_ring->rr_blank(ip_ring->rr_handle,
15110 			    ip_ring->rr_normal_blank_time,
15111 			    ip_ring->rr_normal_pkt_cnt);
15112 		}
15113 	}
15114 
15115 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15116 	    "ip_input_end: q %p (%S)", q, "end");
15117 #undef	rptr
15118 }
15119 
15120 static void
15121 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15122     t_uscalar_t err)
15123 {
15124 	if (dl_err == DL_SYSERR) {
15125 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15126 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15127 		    ill->ill_name, dlpi_prim_str(prim), err);
15128 		return;
15129 	}
15130 
15131 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15132 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15133 	    dlpi_err_str(dl_err));
15134 }
15135 
15136 /*
15137  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15138  * than DL_UNITDATA_IND messages. If we need to process this message
15139  * exclusively, we call qwriter_ip, in which case we also need to call
15140  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15141  */
15142 void
15143 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15144 {
15145 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15146 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15147 	ill_t		*ill;
15148 
15149 	ip1dbg(("ip_rput_dlpi"));
15150 	ill = (ill_t *)q->q_ptr;
15151 	switch (dloa->dl_primitive) {
15152 	case DL_ERROR_ACK:
15153 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15154 		    "%s (0x%x), unix %u\n", ill->ill_name,
15155 		    dlpi_prim_str(dlea->dl_error_primitive),
15156 		    dlea->dl_error_primitive,
15157 		    dlpi_err_str(dlea->dl_errno),
15158 		    dlea->dl_errno,
15159 		    dlea->dl_unix_errno));
15160 		switch (dlea->dl_error_primitive) {
15161 		case DL_UNBIND_REQ:
15162 			mutex_enter(&ill->ill_lock);
15163 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15164 			cv_signal(&ill->ill_cv);
15165 			mutex_exit(&ill->ill_lock);
15166 			/* FALLTHRU */
15167 		case DL_NOTIFY_REQ:
15168 		case DL_ATTACH_REQ:
15169 		case DL_DETACH_REQ:
15170 		case DL_INFO_REQ:
15171 		case DL_BIND_REQ:
15172 		case DL_ENABMULTI_REQ:
15173 		case DL_PHYS_ADDR_REQ:
15174 		case DL_CAPABILITY_REQ:
15175 		case DL_CONTROL_REQ:
15176 			/*
15177 			 * Refhold the ill to match qwriter_ip which does a
15178 			 * refrele. Since this is on the ill stream we
15179 			 * unconditionally bump up the refcount without
15180 			 * checking for ILL_CAN_LOOKUP
15181 			 */
15182 			ill_refhold(ill);
15183 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15184 			    CUR_OP, B_FALSE);
15185 			return;
15186 		case DL_DISABMULTI_REQ:
15187 			freemsg(mp);	/* Don't want to pass this up */
15188 			return;
15189 		default:
15190 			break;
15191 		}
15192 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15193 		    dlea->dl_errno, dlea->dl_unix_errno);
15194 		freemsg(mp);
15195 		return;
15196 	case DL_INFO_ACK:
15197 	case DL_BIND_ACK:
15198 	case DL_PHYS_ADDR_ACK:
15199 	case DL_NOTIFY_ACK:
15200 	case DL_CAPABILITY_ACK:
15201 	case DL_CONTROL_ACK:
15202 		/*
15203 		 * Refhold the ill to match qwriter_ip which does a refrele
15204 		 * Since this is on the ill stream we unconditionally
15205 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15206 		 */
15207 		ill_refhold(ill);
15208 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15209 		    CUR_OP, B_FALSE);
15210 		return;
15211 	case DL_NOTIFY_IND:
15212 		ill_refhold(ill);
15213 		/*
15214 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15215 		 * relation to the current ioctl in progress (if any). Hence we
15216 		 * pass in NEW_OP in this case.
15217 		 */
15218 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15219 		    NEW_OP, B_FALSE);
15220 		return;
15221 	case DL_OK_ACK:
15222 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15223 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15224 		switch (dloa->dl_correct_primitive) {
15225 		case DL_UNBIND_REQ:
15226 			mutex_enter(&ill->ill_lock);
15227 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15228 			cv_signal(&ill->ill_cv);
15229 			mutex_exit(&ill->ill_lock);
15230 			/* FALLTHRU */
15231 		case DL_ATTACH_REQ:
15232 		case DL_DETACH_REQ:
15233 			/*
15234 			 * Refhold the ill to match qwriter_ip which does a
15235 			 * refrele. Since this is on the ill stream we
15236 			 * unconditionally bump up the refcount
15237 			 */
15238 			ill_refhold(ill);
15239 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15240 			    CUR_OP, B_FALSE);
15241 			return;
15242 		case DL_ENABMULTI_REQ:
15243 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15244 				ill->ill_dlpi_multicast_state = IDS_OK;
15245 			break;
15246 
15247 		}
15248 		break;
15249 	default:
15250 		break;
15251 	}
15252 	freemsg(mp);
15253 }
15254 
15255 /*
15256  * Handling of DLPI messages that require exclusive access to the ipsq.
15257  *
15258  * Need to do ill_pending_mp_release on ioctl completion, which could
15259  * happen here. (along with mi_copy_done)
15260  */
15261 /* ARGSUSED */
15262 static void
15263 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15264 {
15265 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15266 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15267 	int		err = 0;
15268 	ill_t		*ill;
15269 	ipif_t		*ipif = NULL;
15270 	mblk_t		*mp1 = NULL;
15271 	conn_t		*connp = NULL;
15272 	t_uscalar_t	physaddr_req;
15273 	mblk_t		*mp_hw;
15274 	union DL_primitives *dlp;
15275 	boolean_t	success;
15276 	boolean_t	ioctl_aborted = B_FALSE;
15277 	boolean_t	log = B_TRUE;
15278 	hook_nic_event_t	*info;
15279 
15280 	ip1dbg(("ip_rput_dlpi_writer .."));
15281 	ill = (ill_t *)q->q_ptr;
15282 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15283 
15284 	ASSERT(IAM_WRITER_ILL(ill));
15285 
15286 	/*
15287 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15288 	 * both are null or non-null. However we can assert that only
15289 	 * after grabbing the ipsq_lock. So we don't make any assertion
15290 	 * here and in other places in the code.
15291 	 */
15292 	ipif = ipsq->ipsq_pending_ipif;
15293 	/*
15294 	 * The current ioctl could have been aborted by the user and a new
15295 	 * ioctl to bring up another ill could have started. We could still
15296 	 * get a response from the driver later.
15297 	 */
15298 	if (ipif != NULL && ipif->ipif_ill != ill)
15299 		ioctl_aborted = B_TRUE;
15300 
15301 	switch (dloa->dl_primitive) {
15302 	case DL_ERROR_ACK:
15303 		switch (dlea->dl_error_primitive) {
15304 		case DL_UNBIND_REQ:
15305 		case DL_ATTACH_REQ:
15306 		case DL_DETACH_REQ:
15307 		case DL_INFO_REQ:
15308 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15309 			break;
15310 		case DL_NOTIFY_REQ:
15311 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15312 			log = B_FALSE;
15313 			break;
15314 		case DL_PHYS_ADDR_REQ:
15315 			/*
15316 			 * For IPv6 only, there are two additional
15317 			 * phys_addr_req's sent to the driver to get the
15318 			 * IPv6 token and lla. This allows IP to acquire
15319 			 * the hardware address format for a given interface
15320 			 * without having built in knowledge of the hardware
15321 			 * address. ill_phys_addr_pend keeps track of the last
15322 			 * DL_PAR sent so we know which response we are
15323 			 * dealing with. ill_dlpi_done will update
15324 			 * ill_phys_addr_pend when it sends the next req.
15325 			 * We don't complete the IOCTL until all three DL_PARs
15326 			 * have been attempted, so set *_len to 0 and break.
15327 			 */
15328 			physaddr_req = ill->ill_phys_addr_pend;
15329 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15330 			if (physaddr_req == DL_IPV6_TOKEN) {
15331 				ill->ill_token_length = 0;
15332 				log = B_FALSE;
15333 				break;
15334 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15335 				ill->ill_nd_lla_len = 0;
15336 				log = B_FALSE;
15337 				break;
15338 			}
15339 			/*
15340 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15341 			 * We presumably have an IOCTL hanging out waiting
15342 			 * for completion. Find it and complete the IOCTL
15343 			 * with the error noted.
15344 			 * However, ill_dl_phys was called on an ill queue
15345 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15346 			 * set. But the ioctl is known to be pending on ill_wq.
15347 			 */
15348 			if (!ill->ill_ifname_pending)
15349 				break;
15350 			ill->ill_ifname_pending = 0;
15351 			if (!ioctl_aborted)
15352 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15353 			if (mp1 != NULL) {
15354 				/*
15355 				 * This operation (SIOCSLIFNAME) must have
15356 				 * happened on the ill. Assert there is no conn
15357 				 */
15358 				ASSERT(connp == NULL);
15359 				q = ill->ill_wq;
15360 			}
15361 			break;
15362 		case DL_BIND_REQ:
15363 			ill_dlpi_done(ill, DL_BIND_REQ);
15364 			if (ill->ill_ifname_pending)
15365 				break;
15366 			/*
15367 			 * Something went wrong with the bind.  We presumably
15368 			 * have an IOCTL hanging out waiting for completion.
15369 			 * Find it, take down the interface that was coming
15370 			 * up, and complete the IOCTL with the error noted.
15371 			 */
15372 			if (!ioctl_aborted)
15373 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15374 			if (mp1 != NULL) {
15375 				/*
15376 				 * This operation (SIOCSLIFFLAGS) must have
15377 				 * happened from a conn.
15378 				 */
15379 				ASSERT(connp != NULL);
15380 				q = CONNP_TO_WQ(connp);
15381 				if (ill->ill_move_in_progress) {
15382 					ILL_CLEAR_MOVE(ill);
15383 				}
15384 				(void) ipif_down(ipif, NULL, NULL);
15385 				/* error is set below the switch */
15386 			}
15387 			break;
15388 		case DL_ENABMULTI_REQ:
15389 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15390 
15391 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15392 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15393 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15394 				ipif_t *ipif;
15395 
15396 				log = B_FALSE;
15397 				printf("ip: joining multicasts failed (%d)"
15398 				    " on %s - will use link layer "
15399 				    "broadcasts for multicast\n",
15400 				    dlea->dl_errno, ill->ill_name);
15401 
15402 				/*
15403 				 * Set up the multicast mapping alone.
15404 				 * writer, so ok to access ill->ill_ipif
15405 				 * without any lock.
15406 				 */
15407 				ipif = ill->ill_ipif;
15408 				mutex_enter(&ill->ill_phyint->phyint_lock);
15409 				ill->ill_phyint->phyint_flags |=
15410 				    PHYI_MULTI_BCAST;
15411 				mutex_exit(&ill->ill_phyint->phyint_lock);
15412 
15413 				if (!ill->ill_isv6) {
15414 					(void) ipif_arp_setup_multicast(ipif,
15415 					    NULL);
15416 				} else {
15417 					(void) ipif_ndp_setup_multicast(ipif,
15418 					    NULL);
15419 				}
15420 			}
15421 			freemsg(mp);	/* Don't want to pass this up */
15422 			return;
15423 		case DL_CAPABILITY_REQ:
15424 		case DL_CONTROL_REQ:
15425 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15426 			    "DL_CAPABILITY/CONTROL REQ\n"));
15427 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15428 			ill->ill_dlpi_capab_state = IDS_FAILED;
15429 			freemsg(mp);
15430 			return;
15431 		}
15432 		/*
15433 		 * Note the error for IOCTL completion (mp1 is set when
15434 		 * ready to complete ioctl). If ill_ifname_pending_err is
15435 		 * set, an error occured during plumbing (ill_ifname_pending),
15436 		 * so we want to report that error.
15437 		 *
15438 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15439 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15440 		 * expected to get errack'd if the driver doesn't support
15441 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15442 		 * if these error conditions are encountered.
15443 		 */
15444 		if (mp1 != NULL) {
15445 			if (ill->ill_ifname_pending_err != 0)  {
15446 				err = ill->ill_ifname_pending_err;
15447 				ill->ill_ifname_pending_err = 0;
15448 			} else {
15449 				err = dlea->dl_unix_errno ?
15450 				    dlea->dl_unix_errno : ENXIO;
15451 			}
15452 		/*
15453 		 * If we're plumbing an interface and an error hasn't already
15454 		 * been saved, set ill_ifname_pending_err to the error passed
15455 		 * up. Ignore the error if log is B_FALSE (see comment above).
15456 		 */
15457 		} else if (log && ill->ill_ifname_pending &&
15458 		    ill->ill_ifname_pending_err == 0) {
15459 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15460 			dlea->dl_unix_errno : ENXIO;
15461 		}
15462 
15463 		if (log)
15464 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15465 			    dlea->dl_errno, dlea->dl_unix_errno);
15466 		break;
15467 	case DL_CAPABILITY_ACK: {
15468 		boolean_t reneg_flag = B_FALSE;
15469 		/* Call a routine to handle this one. */
15470 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15471 		/*
15472 		 * Check if the ACK is due to renegotiation case since we
15473 		 * will need to send a new CAPABILITY_REQ later.
15474 		 */
15475 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15476 			/* This is the ack for a renogiation case */
15477 			reneg_flag = B_TRUE;
15478 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15479 		}
15480 		ill_capability_ack(ill, mp);
15481 		if (reneg_flag)
15482 			ill_capability_probe(ill);
15483 		break;
15484 	}
15485 	case DL_CONTROL_ACK:
15486 		/* We treat all of these as "fire and forget" */
15487 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15488 		break;
15489 	case DL_INFO_ACK:
15490 		/* Call a routine to handle this one. */
15491 		ill_dlpi_done(ill, DL_INFO_REQ);
15492 		ip_ll_subnet_defaults(ill, mp);
15493 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15494 		return;
15495 	case DL_BIND_ACK:
15496 		/*
15497 		 * We should have an IOCTL waiting on this unless
15498 		 * sent by ill_dl_phys, in which case just return
15499 		 */
15500 		ill_dlpi_done(ill, DL_BIND_REQ);
15501 		if (ill->ill_ifname_pending)
15502 			break;
15503 
15504 		if (!ioctl_aborted)
15505 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15506 		if (mp1 == NULL)
15507 			break;
15508 		ASSERT(connp != NULL);
15509 		q = CONNP_TO_WQ(connp);
15510 
15511 		/*
15512 		 * We are exclusive. So nothing can change even after
15513 		 * we get the pending mp. If need be we can put it back
15514 		 * and restart, as in calling ipif_arp_up()  below.
15515 		 */
15516 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15517 
15518 		mutex_enter(&ill->ill_lock);
15519 
15520 		ill->ill_dl_up = 1;
15521 
15522 		if ((info = ill->ill_nic_event_info) != NULL) {
15523 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15524 			    "attached for %s\n", info->hne_event,
15525 			    ill->ill_name));
15526 			if (info->hne_data != NULL)
15527 				kmem_free(info->hne_data, info->hne_datalen);
15528 			kmem_free(info, sizeof (hook_nic_event_t));
15529 		}
15530 
15531 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15532 		if (info != NULL) {
15533 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15534 			info->hne_lif = 0;
15535 			info->hne_event = NE_UP;
15536 			info->hne_data = NULL;
15537 			info->hne_datalen = 0;
15538 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15539 		} else
15540 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15541 			    "event information for %s (ENOMEM)\n",
15542 			    ill->ill_name));
15543 
15544 		ill->ill_nic_event_info = info;
15545 
15546 		mutex_exit(&ill->ill_lock);
15547 
15548 		/*
15549 		 * Now bring up the resolver; when that is complete, we'll
15550 		 * create IREs.  Note that we intentionally mirror what
15551 		 * ipif_up() would have done, because we got here by way of
15552 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15553 		 */
15554 		if (ill->ill_isv6) {
15555 			/*
15556 			 * v6 interfaces.
15557 			 * Unlike ARP which has to do another bind
15558 			 * and attach, once we get here we are
15559 			 * done with NDP. Except in the case of
15560 			 * ILLF_XRESOLV, in which case we send an
15561 			 * AR_INTERFACE_UP to the external resolver.
15562 			 * If all goes well, the ioctl will complete
15563 			 * in ip_rput(). If there's an error, we
15564 			 * complete it here.
15565 			 */
15566 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15567 			    B_FALSE);
15568 			if (err == 0) {
15569 				if (ill->ill_flags & ILLF_XRESOLV) {
15570 					mutex_enter(&connp->conn_lock);
15571 					mutex_enter(&ill->ill_lock);
15572 					success = ipsq_pending_mp_add(
15573 					    connp, ipif, q, mp1, 0);
15574 					mutex_exit(&ill->ill_lock);
15575 					mutex_exit(&connp->conn_lock);
15576 					if (success) {
15577 						err = ipif_resolver_up(ipif,
15578 						    Res_act_initial);
15579 						if (err == EINPROGRESS) {
15580 							freemsg(mp);
15581 							return;
15582 						}
15583 						ASSERT(err != 0);
15584 						mp1 = ipsq_pending_mp_get(ipsq,
15585 						    &connp);
15586 						ASSERT(mp1 != NULL);
15587 					} else {
15588 						/* conn has started closing */
15589 						err = EINTR;
15590 					}
15591 				} else { /* Non XRESOLV interface */
15592 					(void) ipif_resolver_up(ipif,
15593 					    Res_act_initial);
15594 					err = ipif_up_done_v6(ipif);
15595 				}
15596 			}
15597 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15598 			/*
15599 			 * ARP and other v4 external resolvers.
15600 			 * Leave the pending mblk intact so that
15601 			 * the ioctl completes in ip_rput().
15602 			 */
15603 			mutex_enter(&connp->conn_lock);
15604 			mutex_enter(&ill->ill_lock);
15605 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15606 			mutex_exit(&ill->ill_lock);
15607 			mutex_exit(&connp->conn_lock);
15608 			if (success) {
15609 				err = ipif_resolver_up(ipif, Res_act_initial);
15610 				if (err == EINPROGRESS) {
15611 					freemsg(mp);
15612 					return;
15613 				}
15614 				ASSERT(err != 0);
15615 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15616 			} else {
15617 				/* The conn has started closing */
15618 				err = EINTR;
15619 			}
15620 		} else {
15621 			/*
15622 			 * This one is complete. Reply to pending ioctl.
15623 			 */
15624 			(void) ipif_resolver_up(ipif, Res_act_initial);
15625 			err = ipif_up_done(ipif);
15626 		}
15627 
15628 		if ((err == 0) && (ill->ill_up_ipifs)) {
15629 			err = ill_up_ipifs(ill, q, mp1);
15630 			if (err == EINPROGRESS) {
15631 				freemsg(mp);
15632 				return;
15633 			}
15634 		}
15635 
15636 		if (ill->ill_up_ipifs) {
15637 			ill_group_cleanup(ill);
15638 		}
15639 
15640 		break;
15641 	case DL_NOTIFY_IND: {
15642 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15643 		ire_t *ire;
15644 		boolean_t need_ire_walk_v4 = B_FALSE;
15645 		boolean_t need_ire_walk_v6 = B_FALSE;
15646 
15647 		/*
15648 		 * Change the address everywhere we need to.
15649 		 * What we're getting here is a link-level addr or phys addr.
15650 		 * The new addr is at notify + notify->dl_addr_offset
15651 		 * The address length is notify->dl_addr_length;
15652 		 */
15653 		switch (notify->dl_notification) {
15654 		case DL_NOTE_PHYS_ADDR:
15655 			mp_hw = copyb(mp);
15656 			if (mp_hw == NULL) {
15657 				err = ENOMEM;
15658 				break;
15659 			}
15660 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15661 			/*
15662 			 * We currently don't support changing
15663 			 * the token via DL_NOTIFY_IND.
15664 			 * When we do support it, we have to consider
15665 			 * what the implications are with respect to
15666 			 * the token and the link local address.
15667 			 */
15668 			mutex_enter(&ill->ill_lock);
15669 			if (dlp->notify_ind.dl_data ==
15670 			    DL_IPV6_LINK_LAYER_ADDR) {
15671 				if (ill->ill_nd_lla_mp != NULL)
15672 					freemsg(ill->ill_nd_lla_mp);
15673 				ill->ill_nd_lla_mp = mp_hw;
15674 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15675 				    dlp->notify_ind.dl_addr_offset;
15676 				ill->ill_nd_lla_len =
15677 				    dlp->notify_ind.dl_addr_length -
15678 				    ABS(ill->ill_sap_length);
15679 				mutex_exit(&ill->ill_lock);
15680 				break;
15681 			} else if (dlp->notify_ind.dl_data ==
15682 			    DL_CURR_PHYS_ADDR) {
15683 				if (ill->ill_phys_addr_mp != NULL)
15684 					freemsg(ill->ill_phys_addr_mp);
15685 				ill->ill_phys_addr_mp = mp_hw;
15686 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15687 				    dlp->notify_ind.dl_addr_offset;
15688 				ill->ill_phys_addr_length =
15689 				    dlp->notify_ind.dl_addr_length -
15690 				    ABS(ill->ill_sap_length);
15691 				if (ill->ill_isv6 &&
15692 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15693 					if (ill->ill_nd_lla_mp != NULL)
15694 						freemsg(ill->ill_nd_lla_mp);
15695 					ill->ill_nd_lla_mp = copyb(mp_hw);
15696 					ill->ill_nd_lla = (uchar_t *)
15697 					    ill->ill_nd_lla_mp->b_rptr +
15698 					    dlp->notify_ind.dl_addr_offset;
15699 					ill->ill_nd_lla_len =
15700 					    ill->ill_phys_addr_length;
15701 				}
15702 			}
15703 			mutex_exit(&ill->ill_lock);
15704 			/*
15705 			 * Send out gratuitous arp request for our new
15706 			 * hardware address.
15707 			 */
15708 			for (ipif = ill->ill_ipif; ipif != NULL;
15709 			    ipif = ipif->ipif_next) {
15710 				if (!(ipif->ipif_flags & IPIF_UP))
15711 					continue;
15712 				if (ill->ill_isv6) {
15713 					ipif_ndp_down(ipif);
15714 					/*
15715 					 * Set B_TRUE to enable
15716 					 * ipif_ndp_up() to send out
15717 					 * unsolicited advertisements.
15718 					 */
15719 					err = ipif_ndp_up(ipif,
15720 					    &ipif->ipif_v6lcl_addr,
15721 					    B_TRUE);
15722 					if (err) {
15723 						ip1dbg((
15724 						    "ip_rput_dlpi_writer: "
15725 						    "Failed to update ndp "
15726 						    "err %d\n", err));
15727 					}
15728 				} else {
15729 					/*
15730 					 * IPv4 ARP case
15731 					 *
15732 					 * Set Res_act_move, as we only want
15733 					 * ipif_resolver_up to send an
15734 					 * AR_ENTRY_ADD request up to
15735 					 * ARP.
15736 					 */
15737 					err = ipif_resolver_up(ipif,
15738 					    Res_act_move);
15739 					if (err) {
15740 						ip1dbg((
15741 						    "ip_rput_dlpi_writer: "
15742 						    "Failed to update arp "
15743 						    "err %d\n", err));
15744 					}
15745 				}
15746 			}
15747 			/*
15748 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15749 			 * case so that all old fastpath information can be
15750 			 * purged from IRE caches.
15751 			 */
15752 		/* FALLTHRU */
15753 		case DL_NOTE_FASTPATH_FLUSH:
15754 			/*
15755 			 * Any fastpath probe sent henceforth will get the
15756 			 * new fp mp. So we first delete any ires that are
15757 			 * waiting for the fastpath. Then walk all ires and
15758 			 * delete the ire or delete the fp mp. In the case of
15759 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15760 			 * recreate the ire's without going through a complex
15761 			 * ipif up/down dance. So we don't delete the ire
15762 			 * itself, but just the nce_fp_mp for these 2 ire's
15763 			 * In the case of the other ire's we delete the ire's
15764 			 * themselves. Access to nce_fp_mp is completely
15765 			 * protected by ire_lock for IRE_MIPRTUN and
15766 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15767 			 * other cases for performance.
15768 			 */
15769 			if (ill->ill_isv6) {
15770 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15771 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15772 				    NULL);
15773 			} else {
15774 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15775 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15776 				    IRE_CACHE | IRE_BROADCAST,
15777 				    ire_fastpath_flush, NULL, ill);
15778 				mutex_enter(&ire_mrtun_lock);
15779 				if (ire_mrtun_count != 0) {
15780 					mutex_exit(&ire_mrtun_lock);
15781 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15782 					    IRE_MIPRTUN, ire_fastpath_flush,
15783 					    NULL, ill);
15784 				} else {
15785 					mutex_exit(&ire_mrtun_lock);
15786 				}
15787 			}
15788 			break;
15789 		case DL_NOTE_SDU_SIZE:
15790 			/*
15791 			 * Change the MTU size of the interface, of all
15792 			 * attached ipif's, and of all relevant ire's.  The
15793 			 * new value's a uint32_t at notify->dl_data.
15794 			 * Mtu change Vs. new ire creation - protocol below.
15795 			 *
15796 			 * a Mark the ipif as IPIF_CHANGING.
15797 			 * b Set the new mtu in the ipif.
15798 			 * c Change the ire_max_frag on all affected ires
15799 			 * d Unmark the IPIF_CHANGING
15800 			 *
15801 			 * To see how the protocol works, assume an interface
15802 			 * route is also being added simultaneously by
15803 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15804 			 * the ire. If the ire is created before step a,
15805 			 * it will be cleaned up by step c. If the ire is
15806 			 * created after step d, it will see the new value of
15807 			 * ipif_mtu. Any attempt to create the ire between
15808 			 * steps a to d will fail because of the IPIF_CHANGING
15809 			 * flag. Note that ire_create() is passed a pointer to
15810 			 * the ipif_mtu, and not the value. During ire_add
15811 			 * under the bucket lock, the ire_max_frag of the
15812 			 * new ire being created is set from the ipif/ire from
15813 			 * which it is being derived.
15814 			 */
15815 			mutex_enter(&ill->ill_lock);
15816 			ill->ill_max_frag = (uint_t)notify->dl_data;
15817 
15818 			/*
15819 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15820 			 * leave it alone
15821 			 */
15822 			if (ill->ill_mtu_userspecified) {
15823 				mutex_exit(&ill->ill_lock);
15824 				break;
15825 			}
15826 			ill->ill_max_mtu = ill->ill_max_frag;
15827 			if (ill->ill_isv6) {
15828 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15829 					ill->ill_max_mtu = IPV6_MIN_MTU;
15830 			} else {
15831 				if (ill->ill_max_mtu < IP_MIN_MTU)
15832 					ill->ill_max_mtu = IP_MIN_MTU;
15833 			}
15834 			for (ipif = ill->ill_ipif; ipif != NULL;
15835 			    ipif = ipif->ipif_next) {
15836 				/*
15837 				 * Don't override the mtu if the user
15838 				 * has explicitly set it.
15839 				 */
15840 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15841 					continue;
15842 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15843 				if (ipif->ipif_isv6)
15844 					ire = ipif_to_ire_v6(ipif);
15845 				else
15846 					ire = ipif_to_ire(ipif);
15847 				if (ire != NULL) {
15848 					ire->ire_max_frag = ipif->ipif_mtu;
15849 					ire_refrele(ire);
15850 				}
15851 				if (ipif->ipif_flags & IPIF_UP) {
15852 					if (ill->ill_isv6)
15853 						need_ire_walk_v6 = B_TRUE;
15854 					else
15855 						need_ire_walk_v4 = B_TRUE;
15856 				}
15857 			}
15858 			mutex_exit(&ill->ill_lock);
15859 			if (need_ire_walk_v4)
15860 				ire_walk_v4(ill_mtu_change, (char *)ill,
15861 				    ALL_ZONES);
15862 			if (need_ire_walk_v6)
15863 				ire_walk_v6(ill_mtu_change, (char *)ill,
15864 				    ALL_ZONES);
15865 			break;
15866 		case DL_NOTE_LINK_UP:
15867 		case DL_NOTE_LINK_DOWN: {
15868 			/*
15869 			 * We are writer. ill / phyint / ipsq assocs stable.
15870 			 * The RUNNING flag reflects the state of the link.
15871 			 */
15872 			phyint_t *phyint = ill->ill_phyint;
15873 			uint64_t new_phyint_flags;
15874 			boolean_t changed = B_FALSE;
15875 			boolean_t went_up;
15876 
15877 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15878 			mutex_enter(&phyint->phyint_lock);
15879 			new_phyint_flags = went_up ?
15880 			    phyint->phyint_flags | PHYI_RUNNING :
15881 			    phyint->phyint_flags & ~PHYI_RUNNING;
15882 			if (new_phyint_flags != phyint->phyint_flags) {
15883 				phyint->phyint_flags = new_phyint_flags;
15884 				changed = B_TRUE;
15885 			}
15886 			mutex_exit(&phyint->phyint_lock);
15887 			/*
15888 			 * ill_restart_dad handles the DAD restart and routing
15889 			 * socket notification logic.
15890 			 */
15891 			if (changed) {
15892 				ill_restart_dad(phyint->phyint_illv4, went_up);
15893 				ill_restart_dad(phyint->phyint_illv6, went_up);
15894 			}
15895 			break;
15896 		}
15897 		case DL_NOTE_PROMISC_ON_PHYS:
15898 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15899 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15900 			mutex_enter(&ill->ill_lock);
15901 			ill->ill_promisc_on_phys = B_TRUE;
15902 			mutex_exit(&ill->ill_lock);
15903 			break;
15904 		case DL_NOTE_PROMISC_OFF_PHYS:
15905 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15906 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15907 			mutex_enter(&ill->ill_lock);
15908 			ill->ill_promisc_on_phys = B_FALSE;
15909 			mutex_exit(&ill->ill_lock);
15910 			break;
15911 		case DL_NOTE_CAPAB_RENEG:
15912 			/*
15913 			 * Something changed on the driver side.
15914 			 * It wants us to renegotiate the capabilities
15915 			 * on this ill. The most likely cause is the
15916 			 * aggregation interface under us where a
15917 			 * port got added or went away.
15918 			 *
15919 			 * We reset the capabilities and set the
15920 			 * state to IDS_RENG so that when the ack
15921 			 * comes back, we can start the
15922 			 * renegotiation process.
15923 			 */
15924 			ill_capability_reset(ill);
15925 			ill->ill_dlpi_capab_state = IDS_RENEG;
15926 			break;
15927 		default:
15928 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15929 			    "type 0x%x for DL_NOTIFY_IND\n",
15930 			    notify->dl_notification));
15931 			break;
15932 		}
15933 
15934 		/*
15935 		 * As this is an asynchronous operation, we
15936 		 * should not call ill_dlpi_done
15937 		 */
15938 		break;
15939 	}
15940 	case DL_NOTIFY_ACK: {
15941 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15942 
15943 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15944 			ill->ill_note_link = 1;
15945 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15946 		break;
15947 	}
15948 	case DL_PHYS_ADDR_ACK: {
15949 		/*
15950 		 * We should have an IOCTL waiting on this when request
15951 		 * sent by ill_dl_phys.
15952 		 * However, ill_dl_phys was called on an ill queue (from
15953 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15954 		 * ioctl is known to be pending on ill_wq.
15955 		 * There are two additional phys_addr_req's sent to the
15956 		 * driver to get the token and lla. ill_phys_addr_pend
15957 		 * keeps track of the last one sent so we know which
15958 		 * response we are dealing with. ill_dlpi_done will
15959 		 * update ill_phys_addr_pend when it sends the next req.
15960 		 * We don't complete the IOCTL until all three DL_PARs
15961 		 * have been attempted.
15962 		 *
15963 		 * We don't need any lock to update ill_nd_lla* fields,
15964 		 * since the ill is not yet up, We grab the lock just
15965 		 * for uniformity with other code that accesses ill_nd_lla.
15966 		 */
15967 		physaddr_req = ill->ill_phys_addr_pend;
15968 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15969 		if (physaddr_req == DL_IPV6_TOKEN ||
15970 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15971 			if (physaddr_req == DL_IPV6_TOKEN) {
15972 				/*
15973 				 * bcopy to low-order bits of ill_token
15974 				 *
15975 				 * XXX Temporary hack - currently,
15976 				 * all known tokens are 64 bits,
15977 				 * so I'll cheat for the moment.
15978 				 */
15979 				dlp = (union DL_primitives *)mp->b_rptr;
15980 
15981 				mutex_enter(&ill->ill_lock);
15982 				bcopy((uchar_t *)(mp->b_rptr +
15983 				dlp->physaddr_ack.dl_addr_offset),
15984 				(void *)&ill->ill_token.s6_addr32[2],
15985 				dlp->physaddr_ack.dl_addr_length);
15986 				ill->ill_token_length =
15987 					dlp->physaddr_ack.dl_addr_length;
15988 				mutex_exit(&ill->ill_lock);
15989 			} else {
15990 				ASSERT(ill->ill_nd_lla_mp == NULL);
15991 				mp_hw = copyb(mp);
15992 				if (mp_hw == NULL) {
15993 					err = ENOMEM;
15994 					break;
15995 				}
15996 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15997 				mutex_enter(&ill->ill_lock);
15998 				ill->ill_nd_lla_mp = mp_hw;
15999 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
16000 				dlp->physaddr_ack.dl_addr_offset;
16001 				ill->ill_nd_lla_len =
16002 					dlp->physaddr_ack.dl_addr_length;
16003 				mutex_exit(&ill->ill_lock);
16004 			}
16005 			break;
16006 		}
16007 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
16008 		ASSERT(ill->ill_phys_addr_mp == NULL);
16009 		if (!ill->ill_ifname_pending)
16010 			break;
16011 		ill->ill_ifname_pending = 0;
16012 		if (!ioctl_aborted)
16013 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16014 		if (mp1 != NULL) {
16015 			ASSERT(connp == NULL);
16016 			q = ill->ill_wq;
16017 		}
16018 		/*
16019 		 * If any error acks received during the plumbing sequence,
16020 		 * ill_ifname_pending_err will be set. Break out and send up
16021 		 * the error to the pending ioctl.
16022 		 */
16023 		if (ill->ill_ifname_pending_err != 0) {
16024 			err = ill->ill_ifname_pending_err;
16025 			ill->ill_ifname_pending_err = 0;
16026 			break;
16027 		}
16028 		/*
16029 		 * Get the interface token.  If the zeroth interface
16030 		 * address is zero then set the address to the link local
16031 		 * address
16032 		 */
16033 		mp_hw = copyb(mp);
16034 		if (mp_hw == NULL) {
16035 			err = ENOMEM;
16036 			break;
16037 		}
16038 		dlp = (union DL_primitives *)mp_hw->b_rptr;
16039 		ill->ill_phys_addr_mp = mp_hw;
16040 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
16041 				dlp->physaddr_ack.dl_addr_offset;
16042 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
16043 		    ill->ill_phys_addr_length == 0 ||
16044 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16045 			/*
16046 			 * Compatibility: atun driver returns a length of 0.
16047 			 * ipdptp has an ill_phys_addr_length of zero(from
16048 			 * DL_BIND_ACK) but a non-zero length here.
16049 			 * ipd has an ill_phys_addr_length of 4(from
16050 			 * DL_BIND_ACK) but a non-zero length here.
16051 			 */
16052 			ill->ill_phys_addr = NULL;
16053 		} else if (dlp->physaddr_ack.dl_addr_length !=
16054 		    ill->ill_phys_addr_length) {
16055 			ip0dbg(("DL_PHYS_ADDR_ACK: "
16056 			    "Address length mismatch %d %d\n",
16057 			    dlp->physaddr_ack.dl_addr_length,
16058 			    ill->ill_phys_addr_length));
16059 			err = EINVAL;
16060 			break;
16061 		}
16062 		mutex_enter(&ill->ill_lock);
16063 		if (ill->ill_nd_lla_mp == NULL) {
16064 			ill->ill_nd_lla_mp = copyb(mp_hw);
16065 			if (ill->ill_nd_lla_mp == NULL) {
16066 				err = ENOMEM;
16067 				mutex_exit(&ill->ill_lock);
16068 				break;
16069 			}
16070 			ill->ill_nd_lla =
16071 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
16072 			    dlp->physaddr_ack.dl_addr_offset;
16073 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
16074 		}
16075 		mutex_exit(&ill->ill_lock);
16076 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16077 			(void) ill_setdefaulttoken(ill);
16078 
16079 		/*
16080 		 * If the ill zero interface has a zero address assign
16081 		 * it the proper link local address.
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) {
16107 		struct iocblk *iocp;
16108 		int mode;
16109 
16110 		/*
16111 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
16112 		 * SIOCSLIFNAME do a copyout.
16113 		 */
16114 		iocp = (struct iocblk *)mp1->b_rptr;
16115 
16116 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16117 		    iocp->ioc_cmd == SIOCSLIFNAME)
16118 			mode = COPYOUT;
16119 		else
16120 			mode = NO_COPYOUT;
16121 		/*
16122 		 * The ioctl must complete now without EINPROGRESS
16123 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16124 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16125 		 * stuck for ever in the ipsq.
16126 		 */
16127 		ASSERT(err != EINPROGRESS);
16128 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16129 
16130 	}
16131 }
16132 
16133 /*
16134  * ip_rput_other is called by ip_rput to handle messages modifying the global
16135  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16136  */
16137 /* ARGSUSED */
16138 void
16139 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16140 {
16141 	ill_t		*ill;
16142 	struct iocblk	*iocp;
16143 	mblk_t		*mp1;
16144 	conn_t		*connp = NULL;
16145 
16146 	ip1dbg(("ip_rput_other "));
16147 	ill = (ill_t *)q->q_ptr;
16148 	/*
16149 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16150 	 * in which case ipsq is NULL.
16151 	 */
16152 	if (ipsq != NULL) {
16153 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16154 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16155 	}
16156 
16157 	switch (mp->b_datap->db_type) {
16158 	case M_ERROR:
16159 	case M_HANGUP:
16160 		/*
16161 		 * The device has a problem.  We force the ILL down.  It can
16162 		 * be brought up again manually using SIOCSIFFLAGS (via
16163 		 * ifconfig or equivalent).
16164 		 */
16165 		ASSERT(ipsq != NULL);
16166 		if (mp->b_rptr < mp->b_wptr)
16167 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16168 		if (ill->ill_error == 0)
16169 			ill->ill_error = ENXIO;
16170 		if (!ill_down_start(q, mp))
16171 			return;
16172 		ipif_all_down_tail(ipsq, q, mp, NULL);
16173 		break;
16174 	case M_IOCACK:
16175 		iocp = (struct iocblk *)mp->b_rptr;
16176 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16177 		switch (iocp->ioc_cmd) {
16178 		case SIOCSTUNPARAM:
16179 		case OSIOCSTUNPARAM:
16180 			ASSERT(ipsq != NULL);
16181 			/*
16182 			 * Finish socket ioctl passed through to tun.
16183 			 * We should have an IOCTL waiting on this.
16184 			 */
16185 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16186 			if (ill->ill_isv6) {
16187 				struct iftun_req *ta;
16188 
16189 				/*
16190 				 * if a source or destination is
16191 				 * being set, try and set the link
16192 				 * local address for the tunnel
16193 				 */
16194 				ta = (struct iftun_req *)mp->b_cont->
16195 				    b_cont->b_rptr;
16196 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16197 					ipif_set_tun_llink(ill, ta);
16198 				}
16199 
16200 			}
16201 			if (mp1 != NULL) {
16202 				/*
16203 				 * Now copy back the b_next/b_prev used by
16204 				 * mi code for the mi_copy* functions.
16205 				 * See ip_sioctl_tunparam() for the reason.
16206 				 * Also protect against missing b_cont.
16207 				 */
16208 				if (mp->b_cont != NULL) {
16209 					mp->b_cont->b_next =
16210 					    mp1->b_cont->b_next;
16211 					mp->b_cont->b_prev =
16212 					    mp1->b_cont->b_prev;
16213 				}
16214 				inet_freemsg(mp1);
16215 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16216 				ASSERT(connp != NULL);
16217 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16218 				    iocp->ioc_error, NO_COPYOUT,
16219 				    ipsq->ipsq_current_ipif, ipsq);
16220 			} else {
16221 				ASSERT(connp == NULL);
16222 				putnext(q, mp);
16223 			}
16224 			break;
16225 		case SIOCGTUNPARAM:
16226 		case OSIOCGTUNPARAM:
16227 			/*
16228 			 * This is really M_IOCDATA from the tunnel driver.
16229 			 * convert back and complete the ioctl.
16230 			 * We should have an IOCTL waiting on this.
16231 			 */
16232 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16233 			if (mp1) {
16234 				/*
16235 				 * Now copy back the b_next/b_prev used by
16236 				 * mi code for the mi_copy* functions.
16237 				 * See ip_sioctl_tunparam() for the reason.
16238 				 * Also protect against missing b_cont.
16239 				 */
16240 				if (mp->b_cont != NULL) {
16241 					mp->b_cont->b_next =
16242 					    mp1->b_cont->b_next;
16243 					mp->b_cont->b_prev =
16244 					    mp1->b_cont->b_prev;
16245 				}
16246 				inet_freemsg(mp1);
16247 				if (iocp->ioc_error == 0)
16248 					mp->b_datap->db_type = M_IOCDATA;
16249 				ASSERT(connp != NULL);
16250 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16251 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16252 			} else {
16253 				ASSERT(connp == NULL);
16254 				putnext(q, mp);
16255 			}
16256 			break;
16257 		default:
16258 			break;
16259 		}
16260 		break;
16261 	case M_IOCNAK:
16262 		iocp = (struct iocblk *)mp->b_rptr;
16263 
16264 		switch (iocp->ioc_cmd) {
16265 		int mode;
16266 		ipif_t	*ipif;
16267 
16268 		case DL_IOC_HDR_INFO:
16269 			/*
16270 			 * If this was the first attempt turn of the
16271 			 * fastpath probing.
16272 			 */
16273 			mutex_enter(&ill->ill_lock);
16274 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16275 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16276 				mutex_exit(&ill->ill_lock);
16277 				ill_fastpath_nack(ill);
16278 				ip1dbg(("ip_rput: DLPI fastpath off on "
16279 				    "interface %s\n",
16280 				    ill->ill_name));
16281 			} else {
16282 				mutex_exit(&ill->ill_lock);
16283 			}
16284 			freemsg(mp);
16285 			break;
16286 		case SIOCSTUNPARAM:
16287 		case OSIOCSTUNPARAM:
16288 			ASSERT(ipsq != NULL);
16289 			/*
16290 			 * Finish socket ioctl passed through to tun
16291 			 * We should have an IOCTL waiting on this.
16292 			 */
16293 			/* FALLTHRU */
16294 		case SIOCGTUNPARAM:
16295 		case OSIOCGTUNPARAM:
16296 			/*
16297 			 * This is really M_IOCDATA from the tunnel driver.
16298 			 * convert back and complete the ioctl.
16299 			 * We should have an IOCTL waiting on this.
16300 			 */
16301 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16302 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16303 				mp1 = ill_pending_mp_get(ill, &connp,
16304 				    iocp->ioc_id);
16305 				mode = COPYOUT;
16306 				ipsq = NULL;
16307 				ipif = NULL;
16308 			} else {
16309 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16310 				mode = NO_COPYOUT;
16311 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16312 				ipif = ipsq->ipsq_current_ipif;
16313 			}
16314 			if (mp1 != NULL) {
16315 				/*
16316 				 * Now copy back the b_next/b_prev used by
16317 				 * mi code for the mi_copy* functions.
16318 				 * See ip_sioctl_tunparam() for the reason.
16319 				 * Also protect against missing b_cont.
16320 				 */
16321 				if (mp->b_cont != NULL) {
16322 					mp->b_cont->b_next =
16323 					    mp1->b_cont->b_next;
16324 					mp->b_cont->b_prev =
16325 					    mp1->b_cont->b_prev;
16326 				}
16327 				inet_freemsg(mp1);
16328 				if (iocp->ioc_error == 0)
16329 					iocp->ioc_error = EINVAL;
16330 				ASSERT(connp != NULL);
16331 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16332 				    iocp->ioc_error, mode, ipif, ipsq);
16333 			} else {
16334 				ASSERT(connp == NULL);
16335 				putnext(q, mp);
16336 			}
16337 			break;
16338 		default:
16339 			break;
16340 		}
16341 	default:
16342 		break;
16343 	}
16344 }
16345 
16346 /*
16347  * NOTE : This function does not ire_refrele the ire argument passed in.
16348  *
16349  * IPQoS notes
16350  * IP policy is invoked twice for a forwarded packet, once on the read side
16351  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16352  * enabled. An additional parameter, in_ill, has been added for this purpose.
16353  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16354  * because ip_mroute drops this information.
16355  *
16356  */
16357 void
16358 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16359 {
16360 	uint32_t	pkt_len;
16361 	queue_t	*q;
16362 	uint32_t	sum;
16363 #define	rptr	((uchar_t *)ipha)
16364 	uint32_t	max_frag;
16365 	uint32_t	ill_index;
16366 	ill_t		*out_ill;
16367 	mib2_ipIfStatsEntry_t *mibptr;
16368 
16369 	/* Get the ill_index of the incoming ILL */
16370 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16371 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ip_mib;
16372 
16373 	/* Initiate Read side IPPF processing */
16374 	if (IPP_ENABLED(IPP_FWD_IN)) {
16375 		ip_process(IPP_FWD_IN, &mp, ill_index);
16376 		if (mp == NULL) {
16377 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16378 			    "during IPPF processing\n"));
16379 			return;
16380 		}
16381 	}
16382 
16383 	pkt_len = ntohs(ipha->ipha_length);
16384 
16385 	/* Adjust the checksum to reflect the ttl decrement. */
16386 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16387 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16388 
16389 	if (ipha->ipha_ttl-- <= 1) {
16390 		if (ip_csum_hdr(ipha)) {
16391 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16392 			goto drop_pkt;
16393 		}
16394 		/*
16395 		 * Note: ire_stq this will be NULL for multicast
16396 		 * datagrams using the long path through arp (the IRE
16397 		 * is not an IRE_CACHE). This should not cause
16398 		 * problems since we don't generate ICMP errors for
16399 		 * multicast packets.
16400 		 */
16401 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16402 		q = ire->ire_stq;
16403 		if (q != NULL) {
16404 			/* Sent by forwarding path, and router is global zone */
16405 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16406 			    GLOBAL_ZONEID);
16407 		} else
16408 			freemsg(mp);
16409 		return;
16410 	}
16411 
16412 	/*
16413 	 * Don't forward if the interface is down
16414 	 */
16415 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16416 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16417 		ip2dbg(("ip_rput_forward:interface is down\n"));
16418 		goto drop_pkt;
16419 	}
16420 
16421 	/* Get the ill_index of the outgoing ILL */
16422 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16423 
16424 	out_ill = ire->ire_ipif->ipif_ill;
16425 
16426 	DTRACE_PROBE4(ip4__forwarding__start,
16427 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16428 
16429 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16430 	    in_ill, out_ill, ipha, mp, mp);
16431 
16432 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16433 
16434 	if (mp == NULL)
16435 		return;
16436 	pkt_len = ntohs(ipha->ipha_length);
16437 
16438 	if (is_system_labeled()) {
16439 		mblk_t *mp1;
16440 
16441 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16442 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16443 			goto drop_pkt;
16444 		}
16445 		/* Size may have changed */
16446 		mp = mp1;
16447 		ipha = (ipha_t *)mp->b_rptr;
16448 		pkt_len = ntohs(ipha->ipha_length);
16449 	}
16450 
16451 	/* Check if there are options to update */
16452 	if (!IS_SIMPLE_IPH(ipha)) {
16453 		if (ip_csum_hdr(ipha)) {
16454 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16455 			goto drop_pkt;
16456 		}
16457 		if (ip_rput_forward_options(mp, ipha, ire)) {
16458 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16459 			return;
16460 		}
16461 
16462 		ipha->ipha_hdr_checksum = 0;
16463 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16464 	}
16465 	max_frag = ire->ire_max_frag;
16466 	if (pkt_len > max_frag) {
16467 		/*
16468 		 * It needs fragging on its way out.  We haven't
16469 		 * verified the header checksum yet.  Since we
16470 		 * are going to put a surely good checksum in the
16471 		 * outgoing header, we have to make sure that it
16472 		 * was good coming in.
16473 		 */
16474 		if (ip_csum_hdr(ipha)) {
16475 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16476 			goto drop_pkt;
16477 		}
16478 		/* Initiate Write side IPPF processing */
16479 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16480 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16481 			if (mp == NULL) {
16482 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16483 				    " during IPPF processing\n"));
16484 				return;
16485 			}
16486 		}
16487 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16488 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16489 		return;
16490 	}
16491 
16492 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16493 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16494 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16495 	    NULL, out_ill, ipha, mp, mp);
16496 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16497 	if (mp == NULL)
16498 		return;
16499 
16500 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16501 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16502 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16503 	/* ip_xmit_v4 always consumes the packet */
16504 	return;
16505 
16506 drop_pkt:;
16507 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16508 	freemsg(mp);
16509 #undef	rptr
16510 }
16511 
16512 void
16513 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16514 {
16515 	ire_t	*ire;
16516 
16517 	ASSERT(!ipif->ipif_isv6);
16518 	/*
16519 	 * Find an IRE which matches the destination and the outgoing
16520 	 * queue in the cache table. All we need is an IRE_CACHE which
16521 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16522 	 * then it is enough to have some IRE_CACHE in the group.
16523 	 */
16524 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16525 		dst = ipif->ipif_pp_dst_addr;
16526 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16527 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16528 	if (ire == NULL) {
16529 		/*
16530 		 * Mark this packet to make it be delivered to
16531 		 * ip_rput_forward after the new ire has been
16532 		 * created.
16533 		 */
16534 		mp->b_prev = NULL;
16535 		mp->b_next = mp;
16536 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16537 		    NULL, 0, GLOBAL_ZONEID);
16538 	} else {
16539 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16540 		IRE_REFRELE(ire);
16541 	}
16542 }
16543 
16544 /* Update any source route, record route or timestamp options */
16545 static int
16546 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16547 {
16548 	ipoptp_t	opts;
16549 	uchar_t		*opt;
16550 	uint8_t		optval;
16551 	uint8_t		optlen;
16552 	ipaddr_t	dst;
16553 	uint32_t	ts;
16554 	ire_t		*dst_ire = NULL;
16555 	ire_t		*tmp_ire = NULL;
16556 	timestruc_t	now;
16557 
16558 	ip2dbg(("ip_rput_forward_options\n"));
16559 	dst = ipha->ipha_dst;
16560 	for (optval = ipoptp_first(&opts, ipha);
16561 	    optval != IPOPT_EOL;
16562 	    optval = ipoptp_next(&opts)) {
16563 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16564 		opt = opts.ipoptp_cur;
16565 		optlen = opts.ipoptp_len;
16566 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16567 		    optval, opts.ipoptp_len));
16568 		switch (optval) {
16569 			uint32_t off;
16570 		case IPOPT_SSRR:
16571 		case IPOPT_LSRR:
16572 			/* Check if adminstratively disabled */
16573 			if (!ip_forward_src_routed) {
16574 				if (ire->ire_stq != NULL) {
16575 					/*
16576 					 * Sent by forwarding path, and router
16577 					 * is global zone
16578 					 */
16579 					icmp_unreachable(ire->ire_stq, mp,
16580 					    ICMP_SOURCE_ROUTE_FAILED,
16581 					    GLOBAL_ZONEID);
16582 				} else {
16583 					ip0dbg(("ip_rput_forward_options: "
16584 					    "unable to send unreach\n"));
16585 					freemsg(mp);
16586 				}
16587 				return (-1);
16588 			}
16589 
16590 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16591 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16592 			if (dst_ire == NULL) {
16593 				/*
16594 				 * Must be partial since ip_rput_options
16595 				 * checked for strict.
16596 				 */
16597 				break;
16598 			}
16599 			off = opt[IPOPT_OFFSET];
16600 			off--;
16601 		redo_srr:
16602 			if (optlen < IP_ADDR_LEN ||
16603 			    off > optlen - IP_ADDR_LEN) {
16604 				/* End of source route */
16605 				ip1dbg((
16606 				    "ip_rput_forward_options: end of SR\n"));
16607 				ire_refrele(dst_ire);
16608 				break;
16609 			}
16610 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16611 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16612 			    IP_ADDR_LEN);
16613 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16614 			    ntohl(dst)));
16615 
16616 			/*
16617 			 * Check if our address is present more than
16618 			 * once as consecutive hops in source route.
16619 			 */
16620 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16621 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16622 			if (tmp_ire != NULL) {
16623 				ire_refrele(tmp_ire);
16624 				off += IP_ADDR_LEN;
16625 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16626 				goto redo_srr;
16627 			}
16628 			ipha->ipha_dst = dst;
16629 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16630 			ire_refrele(dst_ire);
16631 			break;
16632 		case IPOPT_RR:
16633 			off = opt[IPOPT_OFFSET];
16634 			off--;
16635 			if (optlen < IP_ADDR_LEN ||
16636 			    off > optlen - IP_ADDR_LEN) {
16637 				/* No more room - ignore */
16638 				ip1dbg((
16639 				    "ip_rput_forward_options: end of RR\n"));
16640 				break;
16641 			}
16642 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16643 			    IP_ADDR_LEN);
16644 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16645 			break;
16646 		case IPOPT_TS:
16647 			/* Insert timestamp if there is room */
16648 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16649 			case IPOPT_TS_TSONLY:
16650 				off = IPOPT_TS_TIMELEN;
16651 				break;
16652 			case IPOPT_TS_PRESPEC:
16653 			case IPOPT_TS_PRESPEC_RFC791:
16654 				/* Verify that the address matched */
16655 				off = opt[IPOPT_OFFSET] - 1;
16656 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16657 				dst_ire = ire_ctable_lookup(dst, 0,
16658 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16659 				    MATCH_IRE_TYPE);
16660 
16661 				if (dst_ire == NULL) {
16662 					/* Not for us */
16663 					break;
16664 				}
16665 				ire_refrele(dst_ire);
16666 				/* FALLTHRU */
16667 			case IPOPT_TS_TSANDADDR:
16668 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16669 				break;
16670 			default:
16671 				/*
16672 				 * ip_*put_options should have already
16673 				 * dropped this packet.
16674 				 */
16675 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16676 				    "unknown IT - bug in ip_rput_options?\n");
16677 				return (0);	/* Keep "lint" happy */
16678 			}
16679 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16680 				/* Increase overflow counter */
16681 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16682 				opt[IPOPT_POS_OV_FLG] =
16683 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16684 				    (off << 4));
16685 				break;
16686 			}
16687 			off = opt[IPOPT_OFFSET] - 1;
16688 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16689 			case IPOPT_TS_PRESPEC:
16690 			case IPOPT_TS_PRESPEC_RFC791:
16691 			case IPOPT_TS_TSANDADDR:
16692 				bcopy(&ire->ire_src_addr,
16693 				    (char *)opt + off, IP_ADDR_LEN);
16694 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16695 				/* FALLTHRU */
16696 			case IPOPT_TS_TSONLY:
16697 				off = opt[IPOPT_OFFSET] - 1;
16698 				/* Compute # of milliseconds since midnight */
16699 				gethrestime(&now);
16700 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16701 				    now.tv_nsec / (NANOSEC / MILLISEC);
16702 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16703 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16704 				break;
16705 			}
16706 			break;
16707 		}
16708 	}
16709 	return (0);
16710 }
16711 
16712 /*
16713  * This is called after processing at least one of AH/ESP headers.
16714  *
16715  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16716  * the actual, physical interface on which the packet was received,
16717  * but, when ip_strict_dst_multihoming is set to 1, could be the
16718  * interface which had the ipha_dst configured when the packet went
16719  * through ip_rput. The ill_index corresponding to the recv_ill
16720  * is saved in ipsec_in_rill_index
16721  */
16722 void
16723 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16724 {
16725 	mblk_t *mp;
16726 	ipaddr_t dst;
16727 	in6_addr_t *v6dstp;
16728 	ipha_t *ipha;
16729 	ip6_t *ip6h;
16730 	ipsec_in_t *ii;
16731 	boolean_t ill_need_rele = B_FALSE;
16732 	boolean_t rill_need_rele = B_FALSE;
16733 	boolean_t ire_need_rele = B_FALSE;
16734 
16735 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16736 	ASSERT(ii->ipsec_in_ill_index != 0);
16737 
16738 	mp = ipsec_mp->b_cont;
16739 	ASSERT(mp != NULL);
16740 
16741 
16742 	if (ill == NULL) {
16743 		ASSERT(recv_ill == NULL);
16744 		/*
16745 		 * We need to get the original queue on which ip_rput_local
16746 		 * or ip_rput_data_v6 was called.
16747 		 */
16748 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16749 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16750 		ill_need_rele = B_TRUE;
16751 
16752 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16753 			recv_ill = ill_lookup_on_ifindex(
16754 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16755 			    NULL, NULL, NULL, NULL);
16756 			rill_need_rele = B_TRUE;
16757 		} else {
16758 			recv_ill = ill;
16759 		}
16760 
16761 		if ((ill == NULL) || (recv_ill == NULL)) {
16762 			ip0dbg(("ip_fanout_proto_again: interface "
16763 			    "disappeared\n"));
16764 			if (ill != NULL)
16765 				ill_refrele(ill);
16766 			if (recv_ill != NULL)
16767 				ill_refrele(recv_ill);
16768 			freemsg(ipsec_mp);
16769 			return;
16770 		}
16771 	}
16772 
16773 	ASSERT(ill != NULL && recv_ill != NULL);
16774 
16775 	if (mp->b_datap->db_type == M_CTL) {
16776 		/*
16777 		 * AH/ESP is returning the ICMP message after
16778 		 * removing their headers. Fanout again till
16779 		 * it gets to the right protocol.
16780 		 */
16781 		if (ii->ipsec_in_v4) {
16782 			icmph_t *icmph;
16783 			int iph_hdr_length;
16784 			int hdr_length;
16785 
16786 			ipha = (ipha_t *)mp->b_rptr;
16787 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16788 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16789 			ipha = (ipha_t *)&icmph[1];
16790 			hdr_length = IPH_HDR_LENGTH(ipha);
16791 			/*
16792 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16793 			 * Reset the type to M_DATA.
16794 			 */
16795 			mp->b_datap->db_type = M_DATA;
16796 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16797 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16798 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16799 		} else {
16800 			icmp6_t *icmp6;
16801 			int hdr_length;
16802 
16803 			ip6h = (ip6_t *)mp->b_rptr;
16804 			/* Don't call hdr_length_v6() unless you have to. */
16805 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16806 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16807 			else
16808 				hdr_length = IPV6_HDR_LEN;
16809 
16810 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16811 			/*
16812 			 * icmp_inbound_error_fanout_v6 may need to do
16813 			 * pullupmsg.  Reset the type to M_DATA.
16814 			 */
16815 			mp->b_datap->db_type = M_DATA;
16816 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16817 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16818 		}
16819 		if (ill_need_rele)
16820 			ill_refrele(ill);
16821 		if (rill_need_rele)
16822 			ill_refrele(recv_ill);
16823 		return;
16824 	}
16825 
16826 	if (ii->ipsec_in_v4) {
16827 		ipha = (ipha_t *)mp->b_rptr;
16828 		dst = ipha->ipha_dst;
16829 		if (CLASSD(dst)) {
16830 			/*
16831 			 * Multicast has to be delivered to all streams.
16832 			 */
16833 			dst = INADDR_BROADCAST;
16834 		}
16835 
16836 		if (ire == NULL) {
16837 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16838 			    MBLK_GETLABEL(mp));
16839 			if (ire == NULL) {
16840 				if (ill_need_rele)
16841 					ill_refrele(ill);
16842 				if (rill_need_rele)
16843 					ill_refrele(recv_ill);
16844 				ip1dbg(("ip_fanout_proto_again: "
16845 				    "IRE not found"));
16846 				freemsg(ipsec_mp);
16847 				return;
16848 			}
16849 			ire_need_rele = B_TRUE;
16850 		}
16851 
16852 		switch (ipha->ipha_protocol) {
16853 			case IPPROTO_UDP:
16854 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16855 				    recv_ill);
16856 				if (ire_need_rele)
16857 					ire_refrele(ire);
16858 				break;
16859 			case IPPROTO_TCP:
16860 				if (!ire_need_rele)
16861 					IRE_REFHOLD(ire);
16862 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16863 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16864 				IRE_REFRELE(ire);
16865 				if (mp != NULL)
16866 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16867 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16868 				break;
16869 			case IPPROTO_SCTP:
16870 				if (!ire_need_rele)
16871 					IRE_REFHOLD(ire);
16872 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16873 				    ipsec_mp, 0, ill->ill_rq, dst);
16874 				break;
16875 			default:
16876 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16877 				    recv_ill);
16878 				if (ire_need_rele)
16879 					ire_refrele(ire);
16880 				break;
16881 		}
16882 	} else {
16883 		uint32_t rput_flags = 0;
16884 
16885 		ip6h = (ip6_t *)mp->b_rptr;
16886 		v6dstp = &ip6h->ip6_dst;
16887 		/*
16888 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16889 		 * address.
16890 		 *
16891 		 * Currently, we don't store that state in the IPSEC_IN
16892 		 * message, and we may need to.
16893 		 */
16894 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16895 		    IP6_IN_LLMCAST : 0);
16896 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16897 		    NULL, NULL);
16898 	}
16899 	if (ill_need_rele)
16900 		ill_refrele(ill);
16901 	if (rill_need_rele)
16902 		ill_refrele(recv_ill);
16903 }
16904 
16905 /*
16906  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16907  * returns 'true' if there are still fragments left on the queue, in
16908  * which case we restart the timer.
16909  */
16910 void
16911 ill_frag_timer(void *arg)
16912 {
16913 	ill_t	*ill = (ill_t *)arg;
16914 	boolean_t frag_pending;
16915 
16916 	mutex_enter(&ill->ill_lock);
16917 	ASSERT(!ill->ill_fragtimer_executing);
16918 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16919 		ill->ill_frag_timer_id = 0;
16920 		mutex_exit(&ill->ill_lock);
16921 		return;
16922 	}
16923 	ill->ill_fragtimer_executing = 1;
16924 	mutex_exit(&ill->ill_lock);
16925 
16926 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16927 
16928 	/*
16929 	 * Restart the timer, if we have fragments pending or if someone
16930 	 * wanted us to be scheduled again.
16931 	 */
16932 	mutex_enter(&ill->ill_lock);
16933 	ill->ill_fragtimer_executing = 0;
16934 	ill->ill_frag_timer_id = 0;
16935 	if (frag_pending || ill->ill_fragtimer_needrestart)
16936 		ill_frag_timer_start(ill);
16937 	mutex_exit(&ill->ill_lock);
16938 }
16939 
16940 void
16941 ill_frag_timer_start(ill_t *ill)
16942 {
16943 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16944 
16945 	/* If the ill is closing or opening don't proceed */
16946 	if (ill->ill_state_flags & ILL_CONDEMNED)
16947 		return;
16948 
16949 	if (ill->ill_fragtimer_executing) {
16950 		/*
16951 		 * ill_frag_timer is currently executing. Just record the
16952 		 * the fact that we want the timer to be restarted.
16953 		 * ill_frag_timer will post a timeout before it returns,
16954 		 * ensuring it will be called again.
16955 		 */
16956 		ill->ill_fragtimer_needrestart = 1;
16957 		return;
16958 	}
16959 
16960 	if (ill->ill_frag_timer_id == 0) {
16961 		/*
16962 		 * The timer is neither running nor is the timeout handler
16963 		 * executing. Post a timeout so that ill_frag_timer will be
16964 		 * called
16965 		 */
16966 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16967 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16968 		ill->ill_fragtimer_needrestart = 0;
16969 	}
16970 }
16971 
16972 /*
16973  * This routine is needed for loopback when forwarding multicasts.
16974  *
16975  * IPQoS Notes:
16976  * IPPF processing is done in fanout routines.
16977  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16978  * processing for IPSec packets is done when it comes back in clear.
16979  * NOTE : The callers of this function need to do the ire_refrele for the
16980  *	  ire that is being passed in.
16981  */
16982 void
16983 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16984     ill_t *recv_ill)
16985 {
16986 	ill_t	*ill = (ill_t *)q->q_ptr;
16987 	uint32_t	sum;
16988 	uint32_t	u1;
16989 	uint32_t	u2;
16990 	int		hdr_length;
16991 	boolean_t	mctl_present;
16992 	mblk_t		*first_mp = mp;
16993 	mblk_t		*hada_mp = NULL;
16994 	ipha_t		*inner_ipha;
16995 
16996 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16997 	    "ip_rput_locl_start: q %p", q);
16998 
16999 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17000 	ASSERT(ill != NULL);
17001 
17002 
17003 #define	rptr	((uchar_t *)ipha)
17004 #define	iphs	((uint16_t *)ipha)
17005 
17006 	/*
17007 	 * no UDP or TCP packet should come here anymore.
17008 	 */
17009 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17010 	    (ipha->ipha_protocol != IPPROTO_UDP));
17011 
17012 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17013 	if (mctl_present &&
17014 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17015 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17016 
17017 		/*
17018 		 * It's an IPsec accelerated packet.
17019 		 * Keep a pointer to the data attributes around until
17020 		 * we allocate the ipsec_info_t.
17021 		 */
17022 		IPSECHW_DEBUG(IPSECHW_PKT,
17023 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17024 		hada_mp = first_mp;
17025 		hada_mp->b_cont = NULL;
17026 		/*
17027 		 * Since it is accelerated, it comes directly from
17028 		 * the ill and the data attributes is followed by
17029 		 * the packet data.
17030 		 */
17031 		ASSERT(mp->b_datap->db_type != M_CTL);
17032 		first_mp = mp;
17033 		mctl_present = B_FALSE;
17034 	}
17035 
17036 	/*
17037 	 * IF M_CTL is not present, then ipsec_in_is_secure
17038 	 * should return B_TRUE. There is a case where loopback
17039 	 * packets has an M_CTL in the front with all the
17040 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17041 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17042 	 * packets never comes here, it is safe to ASSERT the
17043 	 * following.
17044 	 */
17045 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17046 
17047 
17048 	/* u1 is # words of IP options */
17049 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17050 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17051 
17052 	if (u1) {
17053 		if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
17054 			if (hada_mp != NULL)
17055 				freemsg(hada_mp);
17056 			return;
17057 		}
17058 	} else {
17059 		/* Check the IP header checksum.  */
17060 #define	uph	((uint16_t *)ipha)
17061 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17062 		    uph[6] + uph[7] + uph[8] + uph[9];
17063 #undef  uph
17064 		/* finish doing IP checksum */
17065 		sum = (sum & 0xFFFF) + (sum >> 16);
17066 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17067 		/*
17068 		 * Don't verify header checksum if this packet is coming
17069 		 * back from AH/ESP as we already did it.
17070 		 */
17071 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17072 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17073 			goto drop_pkt;
17074 		}
17075 	}
17076 
17077 	/*
17078 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17079 	 * might be called more than once for secure packets, count only
17080 	 * the first time.
17081 	 */
17082 	if (!mctl_present) {
17083 		UPDATE_IB_PKT_COUNT(ire);
17084 		ire->ire_last_used_time = lbolt;
17085 	}
17086 
17087 	/* Check for fragmentation offset. */
17088 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17089 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17090 	if (u1) {
17091 		/*
17092 		 * We re-assemble fragments before we do the AH/ESP
17093 		 * processing. Thus, M_CTL should not be present
17094 		 * while we are re-assembling.
17095 		 */
17096 		ASSERT(!mctl_present);
17097 		ASSERT(first_mp == mp);
17098 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17099 			return;
17100 		}
17101 		/*
17102 		 * Make sure that first_mp points back to mp as
17103 		 * the mp we came in with could have changed in
17104 		 * ip_rput_fragment().
17105 		 */
17106 		ipha = (ipha_t *)mp->b_rptr;
17107 		first_mp = mp;
17108 	}
17109 
17110 	/*
17111 	 * Clear hardware checksumming flag as it is currently only
17112 	 * used by TCP and UDP.
17113 	 */
17114 	DB_CKSUMFLAGS(mp) = 0;
17115 
17116 	/* Now we have a complete datagram, destined for this machine. */
17117 	u1 = IPH_HDR_LENGTH(ipha);
17118 	switch (ipha->ipha_protocol) {
17119 	case IPPROTO_ICMP: {
17120 		ire_t		*ire_zone;
17121 		ilm_t		*ilm;
17122 		mblk_t		*mp1;
17123 		zoneid_t	last_zoneid;
17124 
17125 		if (CLASSD(ipha->ipha_dst) &&
17126 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17127 			ASSERT(ire->ire_type == IRE_BROADCAST);
17128 			/*
17129 			 * In the multicast case, applications may have joined
17130 			 * the group from different zones, so we need to deliver
17131 			 * the packet to each of them. Loop through the
17132 			 * multicast memberships structures (ilm) on the receive
17133 			 * ill and send a copy of the packet up each matching
17134 			 * one. However, we don't do this for multicasts sent on
17135 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17136 			 * they must stay in the sender's zone.
17137 			 *
17138 			 * ilm_add_v6() ensures that ilms in the same zone are
17139 			 * contiguous in the ill_ilm list. We use this property
17140 			 * to avoid sending duplicates needed when two
17141 			 * applications in the same zone join the same group on
17142 			 * different logical interfaces: we ignore the ilm if
17143 			 * its zoneid is the same as the last matching one.
17144 			 * In addition, the sending of the packet for
17145 			 * ire_zoneid is delayed until all of the other ilms
17146 			 * have been exhausted.
17147 			 */
17148 			last_zoneid = -1;
17149 			ILM_WALKER_HOLD(recv_ill);
17150 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17151 			    ilm = ilm->ilm_next) {
17152 				if ((ilm->ilm_flags & ILM_DELETED) ||
17153 				    ipha->ipha_dst != ilm->ilm_addr ||
17154 				    ilm->ilm_zoneid == last_zoneid ||
17155 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17156 				    ilm->ilm_zoneid == ALL_ZONES ||
17157 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17158 					continue;
17159 				mp1 = ip_copymsg(first_mp);
17160 				if (mp1 == NULL)
17161 					continue;
17162 				icmp_inbound(q, mp1, B_TRUE, ill,
17163 				    0, sum, mctl_present, B_TRUE,
17164 				    recv_ill, ilm->ilm_zoneid);
17165 				last_zoneid = ilm->ilm_zoneid;
17166 			}
17167 			ILM_WALKER_RELE(recv_ill);
17168 		} else if (ire->ire_type == IRE_BROADCAST) {
17169 			/*
17170 			 * In the broadcast case, there may be many zones
17171 			 * which need a copy of the packet delivered to them.
17172 			 * There is one IRE_BROADCAST per broadcast address
17173 			 * and per zone; we walk those using a helper function.
17174 			 * In addition, the sending of the packet for ire is
17175 			 * delayed until all of the other ires have been
17176 			 * processed.
17177 			 */
17178 			IRB_REFHOLD(ire->ire_bucket);
17179 			ire_zone = NULL;
17180 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17181 			    ire)) != NULL) {
17182 				mp1 = ip_copymsg(first_mp);
17183 				if (mp1 == NULL)
17184 					continue;
17185 
17186 				UPDATE_IB_PKT_COUNT(ire_zone);
17187 				ire_zone->ire_last_used_time = lbolt;
17188 				icmp_inbound(q, mp1, B_TRUE, ill,
17189 				    0, sum, mctl_present, B_TRUE,
17190 				    recv_ill, ire_zone->ire_zoneid);
17191 			}
17192 			IRB_REFRELE(ire->ire_bucket);
17193 		}
17194 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17195 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17196 		    ire->ire_zoneid);
17197 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17198 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17199 		return;
17200 	}
17201 	case IPPROTO_IGMP:
17202 		/*
17203 		 * If we are not willing to accept IGMP packets in clear,
17204 		 * then check with global policy.
17205 		 */
17206 		if (igmp_accept_clear_messages == 0) {
17207 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17208 			    ipha, NULL, mctl_present);
17209 			if (first_mp == NULL)
17210 				return;
17211 		}
17212 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17213 			freemsg(first_mp);
17214 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17215 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17216 			return;
17217 		}
17218 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17219 			/* Bad packet - discarded by igmp_input */
17220 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17221 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17222 			if (mctl_present)
17223 				freeb(first_mp);
17224 			return;
17225 		}
17226 		/*
17227 		 * igmp_input() may have returned the pulled up message.
17228 		 * So first_mp and ipha need to be reinitialized.
17229 		 */
17230 		ipha = (ipha_t *)mp->b_rptr;
17231 		if (mctl_present)
17232 			first_mp->b_cont = mp;
17233 		else
17234 			first_mp = mp;
17235 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17236 			/* No user-level listener for IGMP packets */
17237 			goto drop_pkt;
17238 		}
17239 		/* deliver to local raw users */
17240 		break;
17241 	case IPPROTO_PIM:
17242 		/*
17243 		 * If we are not willing to accept PIM packets in clear,
17244 		 * then check with global policy.
17245 		 */
17246 		if (pim_accept_clear_messages == 0) {
17247 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17248 			    ipha, NULL, mctl_present);
17249 			if (first_mp == NULL)
17250 				return;
17251 		}
17252 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17253 			freemsg(first_mp);
17254 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17255 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17256 			return;
17257 		}
17258 		if (pim_input(q, mp) != 0) {
17259 			/* Bad packet - discarded by pim_input */
17260 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17261 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17262 			if (mctl_present)
17263 				freeb(first_mp);
17264 			return;
17265 		}
17266 
17267 		/*
17268 		 * pim_input() may have pulled up the message so ipha needs to
17269 		 * be reinitialized.
17270 		 */
17271 		ipha = (ipha_t *)mp->b_rptr;
17272 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17273 			/* No user-level listener for PIM packets */
17274 			goto drop_pkt;
17275 		}
17276 		/* deliver to local raw users */
17277 		break;
17278 	case IPPROTO_ENCAP:
17279 		/*
17280 		 * Handle self-encapsulated packets (IP-in-IP where
17281 		 * the inner addresses == the outer addresses).
17282 		 */
17283 		hdr_length = IPH_HDR_LENGTH(ipha);
17284 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17285 		    mp->b_wptr) {
17286 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17287 			    sizeof (ipha_t) - mp->b_rptr)) {
17288 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17289 				freemsg(first_mp);
17290 				return;
17291 			}
17292 			ipha = (ipha_t *)mp->b_rptr;
17293 		}
17294 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17295 		/*
17296 		 * Check the sanity of the inner IP header.
17297 		 */
17298 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17299 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17300 			freemsg(first_mp);
17301 			return;
17302 		}
17303 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17304 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17305 			freemsg(first_mp);
17306 			return;
17307 		}
17308 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17309 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17310 			ipsec_in_t *ii;
17311 
17312 			/*
17313 			 * Self-encapsulated tunnel packet. Remove
17314 			 * the outer IP header and fanout again.
17315 			 * We also need to make sure that the inner
17316 			 * header is pulled up until options.
17317 			 */
17318 			mp->b_rptr = (uchar_t *)inner_ipha;
17319 			ipha = inner_ipha;
17320 			hdr_length = IPH_HDR_LENGTH(ipha);
17321 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17322 				if (!pullupmsg(mp, (uchar_t *)ipha +
17323 				    + hdr_length - mp->b_rptr)) {
17324 					freemsg(first_mp);
17325 					return;
17326 				}
17327 				ipha = (ipha_t *)mp->b_rptr;
17328 			}
17329 			if (!mctl_present) {
17330 				ASSERT(first_mp == mp);
17331 				/*
17332 				 * This means that somebody is sending
17333 				 * Self-encapsualted packets without AH/ESP.
17334 				 * If AH/ESP was present, we would have already
17335 				 * allocated the first_mp.
17336 				 */
17337 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17338 				    NULL) {
17339 					ip1dbg(("ip_proto_input: IPSEC_IN "
17340 					    "allocation failure.\n"));
17341 					BUMP_MIB(ill->ill_ip_mib,
17342 					    ipIfStatsInDiscards);
17343 					freemsg(mp);
17344 					return;
17345 				}
17346 				first_mp->b_cont = mp;
17347 			}
17348 			/*
17349 			 * We generally store the ill_index if we need to
17350 			 * do IPSEC processing as we lose the ill queue when
17351 			 * we come back. But in this case, we never should
17352 			 * have to store the ill_index here as it should have
17353 			 * been stored previously when we processed the
17354 			 * AH/ESP header in this routine or for non-ipsec
17355 			 * cases, we still have the queue. But for some bad
17356 			 * packets from the wire, we can get to IPSEC after
17357 			 * this and we better store the index for that case.
17358 			 */
17359 			ill = (ill_t *)q->q_ptr;
17360 			ii = (ipsec_in_t *)first_mp->b_rptr;
17361 			ii->ipsec_in_ill_index =
17362 			    ill->ill_phyint->phyint_ifindex;
17363 			ii->ipsec_in_rill_index =
17364 			    recv_ill->ill_phyint->phyint_ifindex;
17365 			if (ii->ipsec_in_decaps) {
17366 				/*
17367 				 * This packet is self-encapsulated multiple
17368 				 * times. We don't want to recurse infinitely.
17369 				 * To keep it simple, drop the packet.
17370 				 */
17371 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17372 				freemsg(first_mp);
17373 				return;
17374 			}
17375 			ii->ipsec_in_decaps = B_TRUE;
17376 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17377 			    ire);
17378 			return;
17379 		}
17380 		break;
17381 	case IPPROTO_AH:
17382 	case IPPROTO_ESP: {
17383 		/*
17384 		 * Fast path for AH/ESP. If this is the first time
17385 		 * we are sending a datagram to AH/ESP, allocate
17386 		 * a IPSEC_IN message and prepend it. Otherwise,
17387 		 * just fanout.
17388 		 */
17389 
17390 		int ipsec_rc;
17391 		ipsec_in_t *ii;
17392 
17393 		IP_STAT(ipsec_proto_ahesp);
17394 		if (!mctl_present) {
17395 			ASSERT(first_mp == mp);
17396 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17397 				ip1dbg(("ip_proto_input: IPSEC_IN "
17398 				    "allocation failure.\n"));
17399 				freemsg(hada_mp); /* okay ifnull */
17400 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17401 				freemsg(mp);
17402 				return;
17403 			}
17404 			/*
17405 			 * Store the ill_index so that when we come back
17406 			 * from IPSEC we ride on the same queue.
17407 			 */
17408 			ill = (ill_t *)q->q_ptr;
17409 			ii = (ipsec_in_t *)first_mp->b_rptr;
17410 			ii->ipsec_in_ill_index =
17411 			    ill->ill_phyint->phyint_ifindex;
17412 			ii->ipsec_in_rill_index =
17413 			    recv_ill->ill_phyint->phyint_ifindex;
17414 			first_mp->b_cont = mp;
17415 			/*
17416 			 * Cache hardware acceleration info.
17417 			 */
17418 			if (hada_mp != NULL) {
17419 				IPSECHW_DEBUG(IPSECHW_PKT,
17420 				    ("ip_rput_local: caching data attr.\n"));
17421 				ii->ipsec_in_accelerated = B_TRUE;
17422 				ii->ipsec_in_da = hada_mp;
17423 				hada_mp = NULL;
17424 			}
17425 		} else {
17426 			ii = (ipsec_in_t *)first_mp->b_rptr;
17427 		}
17428 
17429 		if (!ipsec_loaded()) {
17430 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17431 			    ire->ire_zoneid);
17432 			return;
17433 		}
17434 
17435 		/* select inbound SA and have IPsec process the pkt */
17436 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17437 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17438 			if (esph == NULL)
17439 				return;
17440 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17441 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17442 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17443 			    first_mp, esph);
17444 		} else {
17445 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17446 			if (ah == NULL)
17447 				return;
17448 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17449 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17450 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17451 			    first_mp, ah);
17452 		}
17453 
17454 		switch (ipsec_rc) {
17455 		case IPSEC_STATUS_SUCCESS:
17456 			break;
17457 		case IPSEC_STATUS_FAILED:
17458 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17459 			/* FALLTHRU */
17460 		case IPSEC_STATUS_PENDING:
17461 			return;
17462 		}
17463 		/* we're done with IPsec processing, send it up */
17464 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17465 		return;
17466 	}
17467 	default:
17468 		break;
17469 	}
17470 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17471 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17472 		    ire->ire_zoneid));
17473 		goto drop_pkt;
17474 	}
17475 	/*
17476 	 * Handle protocols with which IP is less intimate.  There
17477 	 * can be more than one stream bound to a particular
17478 	 * protocol.  When this is the case, each one gets a copy
17479 	 * of any incoming packets.
17480 	 */
17481 	ip_fanout_proto(q, first_mp, ill, ipha,
17482 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17483 	    B_TRUE, recv_ill, ire->ire_zoneid);
17484 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17485 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17486 	return;
17487 
17488 drop_pkt:
17489 	freemsg(first_mp);
17490 	if (hada_mp != NULL)
17491 		freeb(hada_mp);
17492 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17493 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17494 #undef	rptr
17495 #undef  iphs
17496 
17497 }
17498 
17499 /*
17500  * Update any source route, record route or timestamp options.
17501  * Check that we are at end of strict source route.
17502  * The options have already been checked for sanity in ip_rput_options().
17503  */
17504 static boolean_t
17505 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17506 {
17507 	ipoptp_t	opts;
17508 	uchar_t		*opt;
17509 	uint8_t		optval;
17510 	uint8_t		optlen;
17511 	ipaddr_t	dst;
17512 	uint32_t	ts;
17513 	ire_t		*dst_ire;
17514 	timestruc_t	now;
17515 	zoneid_t	zoneid;
17516 	ill_t		*ill;
17517 
17518 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17519 
17520 	ip2dbg(("ip_rput_local_options\n"));
17521 
17522 	for (optval = ipoptp_first(&opts, ipha);
17523 	    optval != IPOPT_EOL;
17524 	    optval = ipoptp_next(&opts)) {
17525 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17526 		opt = opts.ipoptp_cur;
17527 		optlen = opts.ipoptp_len;
17528 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17529 		    optval, optlen));
17530 		switch (optval) {
17531 			uint32_t off;
17532 		case IPOPT_SSRR:
17533 		case IPOPT_LSRR:
17534 			off = opt[IPOPT_OFFSET];
17535 			off--;
17536 			if (optlen < IP_ADDR_LEN ||
17537 			    off > optlen - IP_ADDR_LEN) {
17538 				/* End of source route */
17539 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17540 				break;
17541 			}
17542 			/*
17543 			 * This will only happen if two consecutive entries
17544 			 * in the source route contains our address or if
17545 			 * it is a packet with a loose source route which
17546 			 * reaches us before consuming the whole source route
17547 			 */
17548 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17549 			if (optval == IPOPT_SSRR) {
17550 				goto bad_src_route;
17551 			}
17552 			/*
17553 			 * Hack: instead of dropping the packet truncate the
17554 			 * source route to what has been used by filling the
17555 			 * rest with IPOPT_NOP.
17556 			 */
17557 			opt[IPOPT_OLEN] = (uint8_t)off;
17558 			while (off < optlen) {
17559 				opt[off++] = IPOPT_NOP;
17560 			}
17561 			break;
17562 		case IPOPT_RR:
17563 			off = opt[IPOPT_OFFSET];
17564 			off--;
17565 			if (optlen < IP_ADDR_LEN ||
17566 			    off > optlen - IP_ADDR_LEN) {
17567 				/* No more room - ignore */
17568 				ip1dbg((
17569 				    "ip_rput_local_options: end of RR\n"));
17570 				break;
17571 			}
17572 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17573 			    IP_ADDR_LEN);
17574 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17575 			break;
17576 		case IPOPT_TS:
17577 			/* Insert timestamp if there is romm */
17578 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17579 			case IPOPT_TS_TSONLY:
17580 				off = IPOPT_TS_TIMELEN;
17581 				break;
17582 			case IPOPT_TS_PRESPEC:
17583 			case IPOPT_TS_PRESPEC_RFC791:
17584 				/* Verify that the address matched */
17585 				off = opt[IPOPT_OFFSET] - 1;
17586 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17587 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17588 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17589 				if (dst_ire == NULL) {
17590 					/* Not for us */
17591 					break;
17592 				}
17593 				ire_refrele(dst_ire);
17594 				/* FALLTHRU */
17595 			case IPOPT_TS_TSANDADDR:
17596 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17597 				break;
17598 			default:
17599 				/*
17600 				 * ip_*put_options should have already
17601 				 * dropped this packet.
17602 				 */
17603 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17604 				    "unknown IT - bug in ip_rput_options?\n");
17605 				return (B_TRUE);	/* Keep "lint" happy */
17606 			}
17607 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17608 				/* Increase overflow counter */
17609 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17610 				opt[IPOPT_POS_OV_FLG] =
17611 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17612 				    (off << 4));
17613 				break;
17614 			}
17615 			off = opt[IPOPT_OFFSET] - 1;
17616 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17617 			case IPOPT_TS_PRESPEC:
17618 			case IPOPT_TS_PRESPEC_RFC791:
17619 			case IPOPT_TS_TSANDADDR:
17620 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17621 				    IP_ADDR_LEN);
17622 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17623 				/* FALLTHRU */
17624 			case IPOPT_TS_TSONLY:
17625 				off = opt[IPOPT_OFFSET] - 1;
17626 				/* Compute # of milliseconds since midnight */
17627 				gethrestime(&now);
17628 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17629 				    now.tv_nsec / (NANOSEC / MILLISEC);
17630 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17631 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17632 				break;
17633 			}
17634 			break;
17635 		}
17636 	}
17637 	return (B_TRUE);
17638 
17639 bad_src_route:
17640 	q = WR(q);
17641 	if (q->q_next != NULL)
17642 		ill = q->q_ptr;
17643 	else
17644 		ill = NULL;
17645 
17646 	/* make sure we clear any indication of a hardware checksum */
17647 	DB_CKSUMFLAGS(mp) = 0;
17648 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17649 	if (zoneid == ALL_ZONES)
17650 		freemsg(mp);
17651 	else
17652 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17653 	return (B_FALSE);
17654 
17655 }
17656 
17657 /*
17658  * Process IP options in an inbound packet.  If an option affects the
17659  * effective destination address, return the next hop address via dstp.
17660  * Returns -1 if something fails in which case an ICMP error has been sent
17661  * and mp freed.
17662  */
17663 static int
17664 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17665 {
17666 	ipoptp_t	opts;
17667 	uchar_t		*opt;
17668 	uint8_t		optval;
17669 	uint8_t		optlen;
17670 	ipaddr_t	dst;
17671 	intptr_t	code = 0;
17672 	ire_t		*ire = NULL;
17673 	zoneid_t	zoneid;
17674 	ill_t		*ill;
17675 
17676 	ip2dbg(("ip_rput_options\n"));
17677 	dst = ipha->ipha_dst;
17678 	for (optval = ipoptp_first(&opts, ipha);
17679 	    optval != IPOPT_EOL;
17680 	    optval = ipoptp_next(&opts)) {
17681 		opt = opts.ipoptp_cur;
17682 		optlen = opts.ipoptp_len;
17683 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17684 		    optval, optlen));
17685 		/*
17686 		 * Note: we need to verify the checksum before we
17687 		 * modify anything thus this routine only extracts the next
17688 		 * hop dst from any source route.
17689 		 */
17690 		switch (optval) {
17691 			uint32_t off;
17692 		case IPOPT_SSRR:
17693 		case IPOPT_LSRR:
17694 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17695 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17696 			if (ire == NULL) {
17697 				if (optval == IPOPT_SSRR) {
17698 					ip1dbg(("ip_rput_options: not next"
17699 					    " strict source route 0x%x\n",
17700 					    ntohl(dst)));
17701 					code = (char *)&ipha->ipha_dst -
17702 					    (char *)ipha;
17703 					goto param_prob; /* RouterReq's */
17704 				}
17705 				ip2dbg(("ip_rput_options: "
17706 				    "not next source route 0x%x\n",
17707 				    ntohl(dst)));
17708 				break;
17709 			}
17710 			ire_refrele(ire);
17711 
17712 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17713 				ip1dbg((
17714 				    "ip_rput_options: bad option offset\n"));
17715 				code = (char *)&opt[IPOPT_OLEN] -
17716 				    (char *)ipha;
17717 				goto param_prob;
17718 			}
17719 			off = opt[IPOPT_OFFSET];
17720 			off--;
17721 		redo_srr:
17722 			if (optlen < IP_ADDR_LEN ||
17723 			    off > optlen - IP_ADDR_LEN) {
17724 				/* End of source route */
17725 				ip1dbg(("ip_rput_options: end of SR\n"));
17726 				break;
17727 			}
17728 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17729 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17730 			    ntohl(dst)));
17731 
17732 			/*
17733 			 * Check if our address is present more than
17734 			 * once as consecutive hops in source route.
17735 			 * XXX verify per-interface ip_forwarding
17736 			 * for source route?
17737 			 */
17738 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17739 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17740 
17741 			if (ire != NULL) {
17742 				ire_refrele(ire);
17743 				off += IP_ADDR_LEN;
17744 				goto redo_srr;
17745 			}
17746 
17747 			if (dst == htonl(INADDR_LOOPBACK)) {
17748 				ip1dbg(("ip_rput_options: loopback addr in "
17749 				    "source route!\n"));
17750 				goto bad_src_route;
17751 			}
17752 			/*
17753 			 * For strict: verify that dst is directly
17754 			 * reachable.
17755 			 */
17756 			if (optval == IPOPT_SSRR) {
17757 				ire = ire_ftable_lookup(dst, 0, 0,
17758 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17759 				    MBLK_GETLABEL(mp),
17760 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17761 				if (ire == NULL) {
17762 					ip1dbg(("ip_rput_options: SSRR not "
17763 					    "directly reachable: 0x%x\n",
17764 					    ntohl(dst)));
17765 					goto bad_src_route;
17766 				}
17767 				ire_refrele(ire);
17768 			}
17769 			/*
17770 			 * Defer update of the offset and the record route
17771 			 * until the packet is forwarded.
17772 			 */
17773 			break;
17774 		case IPOPT_RR:
17775 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17776 				ip1dbg((
17777 				    "ip_rput_options: bad option offset\n"));
17778 				code = (char *)&opt[IPOPT_OLEN] -
17779 				    (char *)ipha;
17780 				goto param_prob;
17781 			}
17782 			break;
17783 		case IPOPT_TS:
17784 			/*
17785 			 * Verify that length >= 5 and that there is either
17786 			 * room for another timestamp or that the overflow
17787 			 * counter is not maxed out.
17788 			 */
17789 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17790 			if (optlen < IPOPT_MINLEN_IT) {
17791 				goto param_prob;
17792 			}
17793 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17794 				ip1dbg((
17795 				    "ip_rput_options: bad option offset\n"));
17796 				code = (char *)&opt[IPOPT_OFFSET] -
17797 				    (char *)ipha;
17798 				goto param_prob;
17799 			}
17800 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17801 			case IPOPT_TS_TSONLY:
17802 				off = IPOPT_TS_TIMELEN;
17803 				break;
17804 			case IPOPT_TS_TSANDADDR:
17805 			case IPOPT_TS_PRESPEC:
17806 			case IPOPT_TS_PRESPEC_RFC791:
17807 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17808 				break;
17809 			default:
17810 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17811 				    (char *)ipha;
17812 				goto param_prob;
17813 			}
17814 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17815 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17816 				/*
17817 				 * No room and the overflow counter is 15
17818 				 * already.
17819 				 */
17820 				goto param_prob;
17821 			}
17822 			break;
17823 		}
17824 	}
17825 
17826 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17827 		*dstp = dst;
17828 		return (0);
17829 	}
17830 
17831 	ip1dbg(("ip_rput_options: error processing IP options."));
17832 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17833 
17834 param_prob:
17835 	q = WR(q);
17836 	if (q->q_next != NULL)
17837 		ill = q->q_ptr;
17838 	else
17839 		ill = NULL;
17840 
17841 	/* make sure we clear any indication of a hardware checksum */
17842 	DB_CKSUMFLAGS(mp) = 0;
17843 	/* Don't know whether this is for non-global or global/forwarding */
17844 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17845 	if (zoneid == ALL_ZONES)
17846 		freemsg(mp);
17847 	else
17848 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17849 	return (-1);
17850 
17851 bad_src_route:
17852 	q = WR(q);
17853 	if (q->q_next != NULL)
17854 		ill = q->q_ptr;
17855 	else
17856 		ill = NULL;
17857 
17858 	/* make sure we clear any indication of a hardware checksum */
17859 	DB_CKSUMFLAGS(mp) = 0;
17860 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17861 	if (zoneid == ALL_ZONES)
17862 		freemsg(mp);
17863 	else
17864 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17865 	return (-1);
17866 }
17867 
17868 /*
17869  * IP & ICMP info in >=14 msg's ...
17870  *  - ip fixed part (mib2_ip_t)
17871  *  - icmp fixed part (mib2_icmp_t)
17872  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17873  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17874  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17875  *  - ipRouteAttributeTable (ip 102)	labeled routes
17876  *  - ip multicast membership (ip_member_t)
17877  *  - ip multicast source filtering (ip_grpsrc_t)
17878  *  - igmp fixed part (struct igmpstat)
17879  *  - multicast routing stats (struct mrtstat)
17880  *  - multicast routing vifs (array of struct vifctl)
17881  *  - multicast routing routes (array of struct mfcctl)
17882  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17883  *					One per ill plus one generic
17884  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17885  *					One per ill plus one generic
17886  *  - ipv6RouteEntry			all IPv6 IREs
17887  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17888  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17889  *  - ipv6AddrEntry			all IPv6 ipifs
17890  *  - ipv6 multicast membership (ipv6_member_t)
17891  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17892  *
17893  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17894  *
17895  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17896  * already filled in by the caller.
17897  * Return value of 0 indicates that no messages were sent and caller
17898  * should free mpctl.
17899  */
17900 int
17901 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17902 {
17903 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17904 		return (0);
17905 	}
17906 
17907 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl)) == NULL) {
17908 		return (1);
17909 	}
17910 
17911 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17912 		return (1);
17913 	}
17914 
17915 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17916 		return (1);
17917 	}
17918 
17919 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17920 		return (1);
17921 	}
17922 
17923 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17924 		return (1);
17925 	}
17926 
17927 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17928 		return (1);
17929 	}
17930 
17931 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17932 		return (1);
17933 	}
17934 
17935 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17936 		return (1);
17937 	}
17938 
17939 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17940 		return (1);
17941 	}
17942 
17943 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17944 		return (1);
17945 	}
17946 
17947 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17948 		return (1);
17949 	}
17950 
17951 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17952 		return (1);
17953 	}
17954 
17955 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17956 		return (1);
17957 	}
17958 
17959 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17960 		return (1);
17961 	}
17962 
17963 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17964 		return (1);
17965 	}
17966 
17967 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17968 		return (1);
17969 	}
17970 
17971 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17972 		return (1);
17973 	}
17974 	freemsg(mpctl);
17975 	return (1);
17976 }
17977 
17978 
17979 /* Get global (legacy) IPv4 statistics */
17980 static mblk_t *
17981 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib)
17982 {
17983 	mib2_ip_t		old_ip_mib;
17984 	struct opthdr		*optp;
17985 	mblk_t			*mp2ctl;
17986 
17987 	/*
17988 	 * make a copy of the original message
17989 	 */
17990 	mp2ctl = copymsg(mpctl);
17991 
17992 	/* fixed length IP structure... */
17993 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17994 	optp->level = MIB2_IP;
17995 	optp->name = 0;
17996 	SET_MIB(old_ip_mib.ipForwarding,
17997 	    (WE_ARE_FORWARDING ? 1 : 2));
17998 	SET_MIB(old_ip_mib.ipDefaultTTL,
17999 	    (uint32_t)ip_def_ttl);
18000 	SET_MIB(old_ip_mib.ipReasmTimeout,
18001 	    ip_g_frag_timeout);
18002 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18003 	    sizeof (mib2_ipAddrEntry_t));
18004 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18005 	    sizeof (mib2_ipRouteEntry_t));
18006 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18007 	    sizeof (mib2_ipNetToMediaEntry_t));
18008 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18009 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18010 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18011 	    sizeof (mib2_ipAttributeEntry_t));
18012 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18013 
18014 	/*
18015 	 * Grab the statistics from the new IP MIB
18016 	 */
18017 	SET_MIB(old_ip_mib.ipInReceives,
18018 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18019 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18020 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18021 	SET_MIB(old_ip_mib.ipForwDatagrams,
18022 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18023 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18024 	    ipmib->ipIfStatsInUnknownProtos);
18025 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18026 	SET_MIB(old_ip_mib.ipInDelivers,
18027 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18028 	SET_MIB(old_ip_mib.ipOutRequests,
18029 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18030 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18031 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18032 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18033 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18034 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18035 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18036 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18037 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18038 
18039 	/* ipRoutingDiscards is not being used */
18040 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18041 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18042 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18043 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18044 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18045 	    ipmib->ipIfStatsReasmDuplicates);
18046 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18047 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18048 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18049 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18050 	SET_MIB(old_ip_mib.rawipInOverflows,
18051 	    ipmib->rawipIfStatsInOverflows);
18052 
18053 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18054 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18055 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18056 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18057 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18058 	    ipmib->ipIfStatsOutSwitchIPVersion);
18059 
18060 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18061 	    (int)sizeof (old_ip_mib))) {
18062 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18063 		    (uint_t)sizeof (old_ip_mib)));
18064 	}
18065 
18066 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18067 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18068 	    (int)optp->level, (int)optp->name, (int)optp->len));
18069 	qreply(q, mpctl);
18070 	return (mp2ctl);
18071 }
18072 
18073 /* Per interface IPv4 statistics */
18074 static mblk_t *
18075 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl)
18076 {
18077 	struct opthdr		*optp;
18078 	mblk_t			*mp2ctl;
18079 	ill_t			*ill;
18080 	ill_walk_context_t	ctx;
18081 	mblk_t			*mp_tail = NULL;
18082 	mib2_ipIfStatsEntry_t	global_ip_mib;
18083 
18084 	/*
18085 	 * Make a copy of the original message
18086 	 */
18087 	mp2ctl = copymsg(mpctl);
18088 
18089 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18090 	optp->level = MIB2_IP;
18091 	optp->name = MIB2_IP_TRAFFIC_STATS;
18092 	/* Include "unknown interface" ip_mib */
18093 	ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18094 	ip_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18095 	SET_MIB(ip_mib.ipIfStatsForwarding, (WE_ARE_FORWARDING ? 1 : 2));
18096 	SET_MIB(ip_mib.ipIfStatsDefaultTTL, (uint32_t)ip_def_ttl);
18097 	SET_MIB(ip_mib.ipIfStatsEntrySize, sizeof (mib2_ipIfStatsEntry_t));
18098 	SET_MIB(ip_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipAddrEntry_t));
18099 	SET_MIB(ip_mib.ipIfStatsRouteEntrySize, sizeof (mib2_ipRouteEntry_t));
18100 	SET_MIB(ip_mib.ipIfStatsNetToMediaEntrySize,
18101 	    sizeof (mib2_ipNetToMediaEntry_t));
18102 	SET_MIB(ip_mib.ipIfStatsMemberEntrySize, sizeof (ip_member_t));
18103 	SET_MIB(ip_mib.ipIfStatsGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18104 
18105 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip_mib,
18106 	    (int)sizeof (ip_mib))) {
18107 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18108 		    "failed to allocate %u bytes\n",
18109 		    (uint_t)sizeof (ip_mib)));
18110 	}
18111 
18112 	bcopy(&ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18113 
18114 	rw_enter(&ill_g_lock, RW_READER);
18115 	ill = ILL_START_WALK_V4(&ctx);
18116 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18117 		ill->ill_ip_mib->ipIfStatsIfIndex =
18118 		    ill->ill_phyint->phyint_ifindex;
18119 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18120 		    (WE_ARE_FORWARDING ? 1 : 2));
18121 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18122 		    (uint32_t)ip_def_ttl);
18123 
18124 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18125 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18126 		    (char *)ill->ill_ip_mib,
18127 		    (int)sizeof (*ill->ill_ip_mib))) {
18128 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18129 			    "failed to allocate %u bytes\n",
18130 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18131 		}
18132 	}
18133 	rw_exit(&ill_g_lock);
18134 
18135 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18136 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18137 	    "level %d, name %d, len %d\n",
18138 	    (int)optp->level, (int)optp->name, (int)optp->len));
18139 	qreply(q, mpctl);
18140 
18141 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib));
18142 }
18143 
18144 /* Global IPv4 ICMP statistics */
18145 static mblk_t *
18146 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
18147 {
18148 	struct opthdr		*optp;
18149 	mblk_t			*mp2ctl;
18150 
18151 	/*
18152 	 * Make a copy of the original message
18153 	 */
18154 	mp2ctl = copymsg(mpctl);
18155 
18156 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18157 	optp->level = MIB2_ICMP;
18158 	optp->name = 0;
18159 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
18160 	    (int)sizeof (icmp_mib))) {
18161 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18162 		    (uint_t)sizeof (icmp_mib)));
18163 	}
18164 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18165 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18166 	    (int)optp->level, (int)optp->name, (int)optp->len));
18167 	qreply(q, mpctl);
18168 	return (mp2ctl);
18169 }
18170 
18171 /* Global IPv4 IGMP statistics */
18172 static mblk_t *
18173 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
18174 {
18175 	struct opthdr		*optp;
18176 	mblk_t			*mp2ctl;
18177 
18178 	/*
18179 	 * make a copy of the original message
18180 	 */
18181 	mp2ctl = copymsg(mpctl);
18182 
18183 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18184 	optp->level = EXPER_IGMP;
18185 	optp->name = 0;
18186 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
18187 	    (int)sizeof (igmpstat))) {
18188 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18189 		    (uint_t)sizeof (igmpstat)));
18190 	}
18191 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18192 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18193 	    (int)optp->level, (int)optp->name, (int)optp->len));
18194 	qreply(q, mpctl);
18195 	return (mp2ctl);
18196 }
18197 
18198 /* Global IPv4 Multicast Routing statistics */
18199 static mblk_t *
18200 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
18201 {
18202 	struct opthdr		*optp;
18203 	mblk_t			*mp2ctl;
18204 
18205 	/*
18206 	 * make a copy of the original message
18207 	 */
18208 	mp2ctl = copymsg(mpctl);
18209 
18210 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18211 	optp->level = EXPER_DVMRP;
18212 	optp->name = 0;
18213 	if (!ip_mroute_stats(mpctl->b_cont)) {
18214 		ip0dbg(("ip_mroute_stats: failed\n"));
18215 	}
18216 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18217 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18218 	    (int)optp->level, (int)optp->name, (int)optp->len));
18219 	qreply(q, mpctl);
18220 	return (mp2ctl);
18221 }
18222 
18223 /* IPv4 address information */
18224 static mblk_t *
18225 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18226 {
18227 	struct opthdr		*optp;
18228 	mblk_t			*mp2ctl;
18229 	mblk_t			*mp_tail = NULL;
18230 	ill_t			*ill;
18231 	ipif_t			*ipif;
18232 	uint_t			bitval;
18233 	mib2_ipAddrEntry_t	mae;
18234 	zoneid_t		zoneid;
18235 	ill_walk_context_t ctx;
18236 
18237 	/*
18238 	 * make a copy of the original message
18239 	 */
18240 	mp2ctl = copymsg(mpctl);
18241 
18242 	/* ipAddrEntryTable */
18243 
18244 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18245 	optp->level = MIB2_IP;
18246 	optp->name = MIB2_IP_ADDR;
18247 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18248 
18249 	rw_enter(&ill_g_lock, RW_READER);
18250 	ill = ILL_START_WALK_V4(&ctx);
18251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18252 		for (ipif = ill->ill_ipif; ipif != NULL;
18253 		    ipif = ipif->ipif_next) {
18254 			if (ipif->ipif_zoneid != zoneid &&
18255 			    ipif->ipif_zoneid != ALL_ZONES)
18256 				continue;
18257 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18258 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18259 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18260 
18261 			(void) ipif_get_name(ipif,
18262 			    mae.ipAdEntIfIndex.o_bytes,
18263 			    OCTET_LENGTH);
18264 			mae.ipAdEntIfIndex.o_length =
18265 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18266 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18267 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18268 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18269 			mae.ipAdEntInfo.ae_subnet_len =
18270 			    ip_mask_to_plen(ipif->ipif_net_mask);
18271 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18272 			for (bitval = 1;
18273 			    bitval &&
18274 			    !(bitval & ipif->ipif_brd_addr);
18275 			    bitval <<= 1)
18276 				noop;
18277 			mae.ipAdEntBcastAddr = bitval;
18278 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18279 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18280 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18281 			mae.ipAdEntInfo.ae_broadcast_addr =
18282 			    ipif->ipif_brd_addr;
18283 			mae.ipAdEntInfo.ae_pp_dst_addr =
18284 			    ipif->ipif_pp_dst_addr;
18285 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18286 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18287 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18288 
18289 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18290 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18291 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18292 				    "allocate %u bytes\n",
18293 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18294 			}
18295 		}
18296 	}
18297 	rw_exit(&ill_g_lock);
18298 
18299 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18300 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18301 	    (int)optp->level, (int)optp->name, (int)optp->len));
18302 	qreply(q, mpctl);
18303 	return (mp2ctl);
18304 }
18305 
18306 /* IPv6 address information */
18307 static mblk_t *
18308 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18309 {
18310 	struct opthdr		*optp;
18311 	mblk_t			*mp2ctl;
18312 	mblk_t			*mp_tail = NULL;
18313 	ill_t			*ill;
18314 	ipif_t			*ipif;
18315 	mib2_ipv6AddrEntry_t	mae6;
18316 	zoneid_t		zoneid;
18317 	ill_walk_context_t	ctx;
18318 
18319 	/*
18320 	 * make a copy of the original message
18321 	 */
18322 	mp2ctl = copymsg(mpctl);
18323 
18324 	/* ipv6AddrEntryTable */
18325 
18326 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18327 	optp->level = MIB2_IP6;
18328 	optp->name = MIB2_IP6_ADDR;
18329 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18330 
18331 	rw_enter(&ill_g_lock, RW_READER);
18332 	ill = ILL_START_WALK_V6(&ctx);
18333 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18334 		for (ipif = ill->ill_ipif; ipif != NULL;
18335 		    ipif = ipif->ipif_next) {
18336 			if (ipif->ipif_zoneid != zoneid &&
18337 			    ipif->ipif_zoneid != ALL_ZONES)
18338 				continue;
18339 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18340 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18341 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18342 
18343 			(void) ipif_get_name(ipif,
18344 			    mae6.ipv6AddrIfIndex.o_bytes,
18345 			    OCTET_LENGTH);
18346 			mae6.ipv6AddrIfIndex.o_length =
18347 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18348 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18349 			mae6.ipv6AddrPfxLength =
18350 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18351 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18352 			mae6.ipv6AddrInfo.ae_subnet_len =
18353 			    mae6.ipv6AddrPfxLength;
18354 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18355 
18356 			/* Type: stateless(1), stateful(2), unknown(3) */
18357 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18358 				mae6.ipv6AddrType = 1;
18359 			else
18360 				mae6.ipv6AddrType = 2;
18361 			/* Anycast: true(1), false(2) */
18362 			if (ipif->ipif_flags & IPIF_ANYCAST)
18363 				mae6.ipv6AddrAnycastFlag = 1;
18364 			else
18365 				mae6.ipv6AddrAnycastFlag = 2;
18366 
18367 			/*
18368 			 * Address status: preferred(1), deprecated(2),
18369 			 * invalid(3), inaccessible(4), unknown(5)
18370 			 */
18371 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18372 				mae6.ipv6AddrStatus = 3;
18373 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18374 				mae6.ipv6AddrStatus = 2;
18375 			else
18376 				mae6.ipv6AddrStatus = 1;
18377 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18378 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18379 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18380 						ipif->ipif_v6pp_dst_addr;
18381 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18382 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18383 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18384 			mae6.ipv6AddrIdentifier = ill->ill_token;
18385 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18386 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18387 			mae6.ipv6AddrRetransmitTime =
18388 			    ill->ill_reachable_retrans_time;
18389 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18390 				(char *)&mae6,
18391 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18392 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18393 				    "allocate %u bytes\n",
18394 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18395 			}
18396 		}
18397 	}
18398 	rw_exit(&ill_g_lock);
18399 
18400 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18401 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18402 	    (int)optp->level, (int)optp->name, (int)optp->len));
18403 	qreply(q, mpctl);
18404 	return (mp2ctl);
18405 }
18406 
18407 /* IPv4 multicast group membership. */
18408 static mblk_t *
18409 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18410 {
18411 	struct opthdr		*optp;
18412 	mblk_t			*mp2ctl;
18413 	ill_t			*ill;
18414 	ipif_t			*ipif;
18415 	ilm_t			*ilm;
18416 	ip_member_t		ipm;
18417 	mblk_t			*mp_tail = NULL;
18418 	ill_walk_context_t	ctx;
18419 	zoneid_t		zoneid;
18420 
18421 	/*
18422 	 * make a copy of the original message
18423 	 */
18424 	mp2ctl = copymsg(mpctl);
18425 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18426 
18427 	/* ipGroupMember table */
18428 	optp = (struct opthdr *)&mpctl->b_rptr[
18429 	    sizeof (struct T_optmgmt_ack)];
18430 	optp->level = MIB2_IP;
18431 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18432 
18433 	rw_enter(&ill_g_lock, RW_READER);
18434 	ill = ILL_START_WALK_V4(&ctx);
18435 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18436 		ILM_WALKER_HOLD(ill);
18437 		for (ipif = ill->ill_ipif; ipif != NULL;
18438 		    ipif = ipif->ipif_next) {
18439 			if (ipif->ipif_zoneid != zoneid &&
18440 			    ipif->ipif_zoneid != ALL_ZONES)
18441 				continue;	/* not this zone */
18442 			(void) ipif_get_name(ipif,
18443 			    ipm.ipGroupMemberIfIndex.o_bytes,
18444 			    OCTET_LENGTH);
18445 			ipm.ipGroupMemberIfIndex.o_length =
18446 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18447 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18448 				ASSERT(ilm->ilm_ipif != NULL);
18449 				ASSERT(ilm->ilm_ill == NULL);
18450 				if (ilm->ilm_ipif != ipif)
18451 					continue;
18452 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18453 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18454 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18455 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18456 				    (char *)&ipm, (int)sizeof (ipm))) {
18457 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18458 					    "failed to allocate %u bytes\n",
18459 						(uint_t)sizeof (ipm)));
18460 				}
18461 			}
18462 		}
18463 		ILM_WALKER_RELE(ill);
18464 	}
18465 	rw_exit(&ill_g_lock);
18466 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18467 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18468 	    (int)optp->level, (int)optp->name, (int)optp->len));
18469 	qreply(q, mpctl);
18470 	return (mp2ctl);
18471 }
18472 
18473 /* IPv6 multicast group membership. */
18474 static mblk_t *
18475 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18476 {
18477 	struct opthdr		*optp;
18478 	mblk_t			*mp2ctl;
18479 	ill_t			*ill;
18480 	ilm_t			*ilm;
18481 	ipv6_member_t		ipm6;
18482 	mblk_t			*mp_tail = NULL;
18483 	ill_walk_context_t	ctx;
18484 	zoneid_t		zoneid;
18485 
18486 	/*
18487 	 * make a copy of the original message
18488 	 */
18489 	mp2ctl = copymsg(mpctl);
18490 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18491 
18492 	/* ip6GroupMember table */
18493 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18494 	optp->level = MIB2_IP6;
18495 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18496 
18497 	rw_enter(&ill_g_lock, RW_READER);
18498 	ill = ILL_START_WALK_V6(&ctx);
18499 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18500 		ILM_WALKER_HOLD(ill);
18501 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18502 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18503 			ASSERT(ilm->ilm_ipif == NULL);
18504 			ASSERT(ilm->ilm_ill != NULL);
18505 			if (ilm->ilm_zoneid != zoneid)
18506 				continue;	/* not this zone */
18507 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18508 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18509 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18510 			if (!snmp_append_data2(mpctl->b_cont,
18511 			    &mp_tail,
18512 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18513 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18514 				    "failed to allocate %u bytes\n",
18515 				    (uint_t)sizeof (ipm6)));
18516 			}
18517 		}
18518 		ILM_WALKER_RELE(ill);
18519 	}
18520 	rw_exit(&ill_g_lock);
18521 
18522 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18523 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18524 	    (int)optp->level, (int)optp->name, (int)optp->len));
18525 	qreply(q, mpctl);
18526 	return (mp2ctl);
18527 }
18528 
18529 /* IP multicast filtered sources */
18530 static mblk_t *
18531 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18532 {
18533 	struct opthdr		*optp;
18534 	mblk_t			*mp2ctl;
18535 	ill_t			*ill;
18536 	ipif_t			*ipif;
18537 	ilm_t			*ilm;
18538 	ip_grpsrc_t		ips;
18539 	mblk_t			*mp_tail = NULL;
18540 	ill_walk_context_t	ctx;
18541 	zoneid_t		zoneid;
18542 	int			i;
18543 	slist_t			*sl;
18544 
18545 	/*
18546 	 * make a copy of the original message
18547 	 */
18548 	mp2ctl = copymsg(mpctl);
18549 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18550 
18551 	/* ipGroupSource table */
18552 	optp = (struct opthdr *)&mpctl->b_rptr[
18553 	    sizeof (struct T_optmgmt_ack)];
18554 	optp->level = MIB2_IP;
18555 	optp->name = EXPER_IP_GROUP_SOURCES;
18556 
18557 	rw_enter(&ill_g_lock, RW_READER);
18558 	ill = ILL_START_WALK_V4(&ctx);
18559 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18560 		ILM_WALKER_HOLD(ill);
18561 		for (ipif = ill->ill_ipif; ipif != NULL;
18562 		    ipif = ipif->ipif_next) {
18563 			if (ipif->ipif_zoneid != zoneid)
18564 				continue;	/* not this zone */
18565 			(void) ipif_get_name(ipif,
18566 			    ips.ipGroupSourceIfIndex.o_bytes,
18567 			    OCTET_LENGTH);
18568 			ips.ipGroupSourceIfIndex.o_length =
18569 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18570 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18571 				ASSERT(ilm->ilm_ipif != NULL);
18572 				ASSERT(ilm->ilm_ill == NULL);
18573 				sl = ilm->ilm_filter;
18574 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18575 					continue;
18576 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18577 				for (i = 0; i < sl->sl_numsrc; i++) {
18578 					if (!IN6_IS_ADDR_V4MAPPED(
18579 					    &sl->sl_addr[i]))
18580 						continue;
18581 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18582 					    ips.ipGroupSourceAddress);
18583 					if (snmp_append_data2(mpctl->b_cont,
18584 					    &mp_tail, (char *)&ips,
18585 					    (int)sizeof (ips)) == 0) {
18586 						ip1dbg(("ip_snmp_get_mib2_"
18587 						    "ip_group_src: failed to "
18588 						    "allocate %u bytes\n",
18589 						    (uint_t)sizeof (ips)));
18590 					}
18591 				}
18592 			}
18593 		}
18594 		ILM_WALKER_RELE(ill);
18595 	}
18596 	rw_exit(&ill_g_lock);
18597 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18598 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18599 	    (int)optp->level, (int)optp->name, (int)optp->len));
18600 	qreply(q, mpctl);
18601 	return (mp2ctl);
18602 }
18603 
18604 /* IPv6 multicast filtered sources. */
18605 static mblk_t *
18606 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18607 {
18608 	struct opthdr		*optp;
18609 	mblk_t			*mp2ctl;
18610 	ill_t			*ill;
18611 	ilm_t			*ilm;
18612 	ipv6_grpsrc_t		ips6;
18613 	mblk_t			*mp_tail = NULL;
18614 	ill_walk_context_t	ctx;
18615 	zoneid_t		zoneid;
18616 	int			i;
18617 	slist_t			*sl;
18618 
18619 	/*
18620 	 * make a copy of the original message
18621 	 */
18622 	mp2ctl = copymsg(mpctl);
18623 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18624 
18625 	/* ip6GroupMember table */
18626 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18627 	optp->level = MIB2_IP6;
18628 	optp->name = EXPER_IP6_GROUP_SOURCES;
18629 
18630 	rw_enter(&ill_g_lock, RW_READER);
18631 	ill = ILL_START_WALK_V6(&ctx);
18632 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18633 		ILM_WALKER_HOLD(ill);
18634 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18635 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18636 			ASSERT(ilm->ilm_ipif == NULL);
18637 			ASSERT(ilm->ilm_ill != NULL);
18638 			sl = ilm->ilm_filter;
18639 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18640 				continue;
18641 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18642 			for (i = 0; i < sl->sl_numsrc; i++) {
18643 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18644 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18645 				    (char *)&ips6, (int)sizeof (ips6))) {
18646 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18647 					    "group_src: failed to allocate "
18648 					    "%u bytes\n",
18649 					    (uint_t)sizeof (ips6)));
18650 				}
18651 			}
18652 		}
18653 		ILM_WALKER_RELE(ill);
18654 	}
18655 	rw_exit(&ill_g_lock);
18656 
18657 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18658 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18659 	    (int)optp->level, (int)optp->name, (int)optp->len));
18660 	qreply(q, mpctl);
18661 	return (mp2ctl);
18662 }
18663 
18664 /* Multicast routing virtual interface table. */
18665 static mblk_t *
18666 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18667 {
18668 	struct opthdr		*optp;
18669 	mblk_t			*mp2ctl;
18670 
18671 	/*
18672 	 * make a copy of the original message
18673 	 */
18674 	mp2ctl = copymsg(mpctl);
18675 
18676 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18677 	optp->level = EXPER_DVMRP;
18678 	optp->name = EXPER_DVMRP_VIF;
18679 	if (!ip_mroute_vif(mpctl->b_cont)) {
18680 		ip0dbg(("ip_mroute_vif: failed\n"));
18681 	}
18682 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18683 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18684 	    (int)optp->level, (int)optp->name, (int)optp->len));
18685 	qreply(q, mpctl);
18686 	return (mp2ctl);
18687 }
18688 
18689 /* Multicast routing table. */
18690 static mblk_t *
18691 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18692 {
18693 	struct opthdr		*optp;
18694 	mblk_t			*mp2ctl;
18695 
18696 	/*
18697 	 * make a copy of the original message
18698 	 */
18699 	mp2ctl = copymsg(mpctl);
18700 
18701 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18702 	optp->level = EXPER_DVMRP;
18703 	optp->name = EXPER_DVMRP_MRT;
18704 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18705 		ip0dbg(("ip_mroute_mrt: failed\n"));
18706 	}
18707 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18708 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18709 	    (int)optp->level, (int)optp->name, (int)optp->len));
18710 	qreply(q, mpctl);
18711 	return (mp2ctl);
18712 }
18713 
18714 /*
18715  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18716  * in one IRE walk.
18717  */
18718 static mblk_t *
18719 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18720 {
18721 	struct opthdr	*optp;
18722 	mblk_t		*mp2ctl;	/* Returned */
18723 	mblk_t		*mp3ctl;	/* nettomedia */
18724 	mblk_t		*mp4ctl;	/* routeattrs */
18725 	iproutedata_t	ird;
18726 	zoneid_t	zoneid;
18727 
18728 	/*
18729 	 * make copies of the original message
18730 	 *	- mp2ctl is returned unchanged to the caller for his use
18731 	 *	- mpctl is sent upstream as ipRouteEntryTable
18732 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18733 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18734 	 */
18735 	mp2ctl = copymsg(mpctl);
18736 	mp3ctl = copymsg(mpctl);
18737 	mp4ctl = copymsg(mpctl);
18738 	if (mp3ctl == NULL || mp4ctl == NULL) {
18739 		freemsg(mp4ctl);
18740 		freemsg(mp3ctl);
18741 		freemsg(mp2ctl);
18742 		freemsg(mpctl);
18743 		return (NULL);
18744 	}
18745 
18746 	bzero(&ird, sizeof (ird));
18747 
18748 	ird.ird_route.lp_head = mpctl->b_cont;
18749 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18750 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18751 
18752 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18753 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18754 	if (zoneid == GLOBAL_ZONEID) {
18755 		/*
18756 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18757 		 * the sys_net_config privilege, it can only run in the global
18758 		 * zone, so we don't display these IREs in the other zones.
18759 		 */
18760 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18761 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18762 	}
18763 
18764 	/* ipRouteEntryTable in mpctl */
18765 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18766 	optp->level = MIB2_IP;
18767 	optp->name = MIB2_IP_ROUTE;
18768 	optp->len = msgdsize(ird.ird_route.lp_head);
18769 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18770 	    (int)optp->level, (int)optp->name, (int)optp->len));
18771 	qreply(q, mpctl);
18772 
18773 	/* ipNetToMediaEntryTable in mp3ctl */
18774 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18775 	optp->level = MIB2_IP;
18776 	optp->name = MIB2_IP_MEDIA;
18777 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18778 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18779 	    (int)optp->level, (int)optp->name, (int)optp->len));
18780 	qreply(q, mp3ctl);
18781 
18782 	/* ipRouteAttributeTable in mp4ctl */
18783 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18784 	optp->level = MIB2_IP;
18785 	optp->name = EXPER_IP_RTATTR;
18786 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18787 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18788 	    (int)optp->level, (int)optp->name, (int)optp->len));
18789 	if (optp->len == 0)
18790 		freemsg(mp4ctl);
18791 	else
18792 		qreply(q, mp4ctl);
18793 
18794 	return (mp2ctl);
18795 }
18796 
18797 /*
18798  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18799  * ipv6NetToMediaEntryTable in an NDP walk.
18800  */
18801 static mblk_t *
18802 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18803 {
18804 	struct opthdr	*optp;
18805 	mblk_t		*mp2ctl;	/* Returned */
18806 	mblk_t		*mp3ctl;	/* nettomedia */
18807 	mblk_t		*mp4ctl;	/* routeattrs */
18808 	iproutedata_t	ird;
18809 	zoneid_t	zoneid;
18810 
18811 	/*
18812 	 * make copies of the original message
18813 	 *	- mp2ctl is returned unchanged to the caller for his use
18814 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18815 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18816 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18817 	 */
18818 	mp2ctl = copymsg(mpctl);
18819 	mp3ctl = copymsg(mpctl);
18820 	mp4ctl = copymsg(mpctl);
18821 	if (mp3ctl == NULL || mp4ctl == NULL) {
18822 		freemsg(mp4ctl);
18823 		freemsg(mp3ctl);
18824 		freemsg(mp2ctl);
18825 		freemsg(mpctl);
18826 		return (NULL);
18827 	}
18828 
18829 	bzero(&ird, sizeof (ird));
18830 
18831 	ird.ird_route.lp_head = mpctl->b_cont;
18832 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18833 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18834 
18835 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18836 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18837 
18838 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18839 	optp->level = MIB2_IP6;
18840 	optp->name = MIB2_IP6_ROUTE;
18841 	optp->len = msgdsize(ird.ird_route.lp_head);
18842 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18843 	    (int)optp->level, (int)optp->name, (int)optp->len));
18844 	qreply(q, mpctl);
18845 
18846 	/* ipv6NetToMediaEntryTable in mp3ctl */
18847 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18848 
18849 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18850 	optp->level = MIB2_IP6;
18851 	optp->name = MIB2_IP6_MEDIA;
18852 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18853 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18854 	    (int)optp->level, (int)optp->name, (int)optp->len));
18855 	qreply(q, mp3ctl);
18856 
18857 	/* ipv6RouteAttributeTable in mp4ctl */
18858 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18859 	optp->level = MIB2_IP6;
18860 	optp->name = EXPER_IP_RTATTR;
18861 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18862 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18863 	    (int)optp->level, (int)optp->name, (int)optp->len));
18864 	if (optp->len == 0)
18865 		freemsg(mp4ctl);
18866 	else
18867 		qreply(q, mp4ctl);
18868 
18869 	return (mp2ctl);
18870 }
18871 
18872 /*
18873  * IPv6 mib: One per ill
18874  */
18875 static mblk_t *
18876 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18877 {
18878 	struct opthdr		*optp;
18879 	mblk_t			*mp2ctl;
18880 	ill_t			*ill;
18881 	ill_walk_context_t	ctx;
18882 	mblk_t			*mp_tail = NULL;
18883 
18884 	/*
18885 	 * Make a copy of the original message
18886 	 */
18887 	mp2ctl = copymsg(mpctl);
18888 
18889 	/* fixed length IPv6 structure ... */
18890 
18891 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18892 	optp->level = MIB2_IP6;
18893 	optp->name = 0;
18894 	/* Include "unknown interface" ip6_mib */
18895 	ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18896 	ip6_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18897 	SET_MIB(ip6_mib.ipIfStatsForwarding, ipv6_forward ? 1 : 2);
18898 	SET_MIB(ip6_mib.ipIfStatsDefaultHopLimit, ipv6_def_hops);
18899 	SET_MIB(ip6_mib.ipIfStatsEntrySize,
18900 	    sizeof (mib2_ipIfStatsEntry_t));
18901 	SET_MIB(ip6_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18902 	SET_MIB(ip6_mib.ipIfStatsRouteEntrySize,
18903 	    sizeof (mib2_ipv6RouteEntry_t));
18904 	SET_MIB(ip6_mib.ipIfStatsNetToMediaEntrySize,
18905 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18906 	SET_MIB(ip6_mib.ipIfStatsMemberEntrySize, sizeof (ipv6_member_t));
18907 	SET_MIB(ip6_mib.ipIfStatsGroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18908 
18909 	/*
18910 	 * Synchronize 64- and 32-bit counters
18911 	 */
18912 	SYNC32_MIB(&ip6_mib, ipIfStatsInReceives, ipIfStatsHCInReceives);
18913 	SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers, ipIfStatsHCInDelivers);
18914 	SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests, ipIfStatsHCOutRequests);
18915 	SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
18916 	    ipIfStatsHCOutForwDatagrams);
18917 	SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts, ipIfStatsHCOutMcastPkts);
18918 	SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts, ipIfStatsHCInMcastPkts);
18919 
18920 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18921 	    (int)sizeof (ip6_mib))) {
18922 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18923 		    (uint_t)sizeof (ip6_mib)));
18924 	}
18925 
18926 	rw_enter(&ill_g_lock, RW_READER);
18927 	ill = ILL_START_WALK_V6(&ctx);
18928 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18929 		ill->ill_ip_mib->ipIfStatsIfIndex =
18930 		    ill->ill_phyint->phyint_ifindex;
18931 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18932 		    ipv6_forward ? 1 : 2);
18933 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
18934 		    ill->ill_max_hops);
18935 
18936 		/*
18937 		 * Synchronize 64- and 32-bit counters
18938 		 */
18939 		SYNC32_MIB(&ip6_mib, ipIfStatsInReceives,
18940 		    ipIfStatsHCInReceives);
18941 		SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers,
18942 		    ipIfStatsHCInDelivers);
18943 		SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests,
18944 		    ipIfStatsHCOutRequests);
18945 		SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
18946 		    ipIfStatsHCOutForwDatagrams);
18947 		SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts,
18948 		    ipIfStatsHCOutMcastPkts);
18949 		SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts,
18950 		    ipIfStatsHCInMcastPkts);
18951 
18952 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18953 		    (char *)ill->ill_ip_mib,
18954 		    (int)sizeof (*ill->ill_ip_mib))) {
18955 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18956 				"%u bytes\n",
18957 				(uint_t)sizeof (*ill->ill_ip_mib)));
18958 		}
18959 	}
18960 	rw_exit(&ill_g_lock);
18961 
18962 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18963 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18964 	    (int)optp->level, (int)optp->name, (int)optp->len));
18965 	qreply(q, mpctl);
18966 	return (mp2ctl);
18967 }
18968 
18969 /*
18970  * ICMPv6 mib: One per ill
18971  */
18972 static mblk_t *
18973 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18974 {
18975 	struct opthdr		*optp;
18976 	mblk_t			*mp2ctl;
18977 	ill_t			*ill;
18978 	ill_walk_context_t	ctx;
18979 	mblk_t			*mp_tail = NULL;
18980 	/*
18981 	 * Make a copy of the original message
18982 	 */
18983 	mp2ctl = copymsg(mpctl);
18984 
18985 	/* fixed length ICMPv6 structure ... */
18986 
18987 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18988 	optp->level = MIB2_ICMP6;
18989 	optp->name = 0;
18990 	/* Include "unknown interface" icmp6_mib */
18991 	icmp6_mib.ipv6IfIcmpIfIndex = MIB2_UNKNOWN_INTERFACE; /* netstat flag */
18992 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18993 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18994 	    (int)sizeof (icmp6_mib))) {
18995 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18996 		    (uint_t)sizeof (icmp6_mib)));
18997 	}
18998 
18999 	rw_enter(&ill_g_lock, RW_READER);
19000 	ill = ILL_START_WALK_V6(&ctx);
19001 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19002 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19003 		    ill->ill_phyint->phyint_ifindex;
19004 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19005 		    (char *)ill->ill_icmp6_mib,
19006 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19007 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19008 			    "%u bytes\n",
19009 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19010 		}
19011 	}
19012 	rw_exit(&ill_g_lock);
19013 
19014 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19015 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19016 	    (int)optp->level, (int)optp->name, (int)optp->len));
19017 	qreply(q, mpctl);
19018 	return (mp2ctl);
19019 }
19020 
19021 /*
19022  * ire_walk routine to create both ipRouteEntryTable and
19023  * ipRouteAttributeTable in one IRE walk
19024  */
19025 static void
19026 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19027 {
19028 	ill_t				*ill;
19029 	ipif_t				*ipif;
19030 	mib2_ipRouteEntry_t		*re;
19031 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19032 	ipaddr_t			gw_addr;
19033 	tsol_ire_gw_secattr_t		*attrp;
19034 	tsol_gc_t			*gc = NULL;
19035 	tsol_gcgrp_t			*gcgrp = NULL;
19036 	uint_t				sacnt = 0;
19037 	int				i;
19038 
19039 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19040 
19041 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19042 		return;
19043 
19044 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19045 		mutex_enter(&attrp->igsa_lock);
19046 		if ((gc = attrp->igsa_gc) != NULL) {
19047 			gcgrp = gc->gc_grp;
19048 			ASSERT(gcgrp != NULL);
19049 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19050 			sacnt = 1;
19051 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19052 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19053 			gc = gcgrp->gcgrp_head;
19054 			sacnt = gcgrp->gcgrp_count;
19055 		}
19056 		mutex_exit(&attrp->igsa_lock);
19057 
19058 		/* do nothing if there's no gc to report */
19059 		if (gc == NULL) {
19060 			ASSERT(sacnt == 0);
19061 			if (gcgrp != NULL) {
19062 				/* we might as well drop the lock now */
19063 				rw_exit(&gcgrp->gcgrp_rwlock);
19064 				gcgrp = NULL;
19065 			}
19066 			attrp = NULL;
19067 		}
19068 
19069 		ASSERT(gc == NULL || (gcgrp != NULL &&
19070 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19071 	}
19072 	ASSERT(sacnt == 0 || gc != NULL);
19073 
19074 	if (sacnt != 0 &&
19075 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19076 		kmem_free(re, sizeof (*re));
19077 		rw_exit(&gcgrp->gcgrp_rwlock);
19078 		return;
19079 	}
19080 
19081 	/*
19082 	 * Return all IRE types for route table... let caller pick and choose
19083 	 */
19084 	re->ipRouteDest = ire->ire_addr;
19085 	ipif = ire->ire_ipif;
19086 	re->ipRouteIfIndex.o_length = 0;
19087 	if (ire->ire_type == IRE_CACHE) {
19088 		ill = (ill_t *)ire->ire_stq->q_ptr;
19089 		re->ipRouteIfIndex.o_length =
19090 		    ill->ill_name_length == 0 ? 0 :
19091 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19092 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19093 		    re->ipRouteIfIndex.o_length);
19094 	} else if (ipif != NULL) {
19095 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19096 		    OCTET_LENGTH);
19097 		re->ipRouteIfIndex.o_length =
19098 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19099 	}
19100 	re->ipRouteMetric1 = -1;
19101 	re->ipRouteMetric2 = -1;
19102 	re->ipRouteMetric3 = -1;
19103 	re->ipRouteMetric4 = -1;
19104 
19105 	gw_addr = ire->ire_gateway_addr;
19106 
19107 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19108 		re->ipRouteNextHop = ire->ire_src_addr;
19109 	else
19110 		re->ipRouteNextHop = gw_addr;
19111 	/* indirect(4), direct(3), or invalid(2) */
19112 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19113 		re->ipRouteType = 2;
19114 	else
19115 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19116 	re->ipRouteProto = -1;
19117 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19118 	re->ipRouteMask = ire->ire_mask;
19119 	re->ipRouteMetric5 = -1;
19120 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19121 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19122 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19123 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19124 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19125 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19126 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19127 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19128 	re->ipRouteInfo.re_in_ill.o_length = 0;
19129 
19130 	if (ire->ire_flags & RTF_DYNAMIC) {
19131 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19132 	} else {
19133 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19134 	}
19135 
19136 	if (ire->ire_in_ill != NULL) {
19137 		re->ipRouteInfo.re_in_ill.o_length =
19138 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19139 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19140 		bcopy(ire->ire_in_ill->ill_name,
19141 		    re->ipRouteInfo.re_in_ill.o_bytes,
19142 		    re->ipRouteInfo.re_in_ill.o_length);
19143 	}
19144 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19145 
19146 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19147 	    (char *)re, (int)sizeof (*re))) {
19148 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19149 		    (uint_t)sizeof (*re)));
19150 	}
19151 
19152 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19153 		iaeptr->iae_routeidx = ird->ird_idx;
19154 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19155 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19156 	}
19157 
19158 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19159 	    (char *)iae, sacnt * sizeof (*iae))) {
19160 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19161 		    (unsigned)(sacnt * sizeof (*iae))));
19162 	}
19163 
19164 	/* bump route index for next pass */
19165 	ird->ird_idx++;
19166 
19167 	kmem_free(re, sizeof (*re));
19168 	if (sacnt != 0)
19169 		kmem_free(iae, sacnt * sizeof (*iae));
19170 
19171 	if (gcgrp != NULL)
19172 		rw_exit(&gcgrp->gcgrp_rwlock);
19173 }
19174 
19175 /*
19176  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19177  */
19178 static void
19179 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19180 {
19181 	ill_t				*ill;
19182 	ipif_t				*ipif;
19183 	mib2_ipv6RouteEntry_t		*re;
19184 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19185 	in6_addr_t			gw_addr_v6;
19186 	tsol_ire_gw_secattr_t		*attrp;
19187 	tsol_gc_t			*gc = NULL;
19188 	tsol_gcgrp_t			*gcgrp = NULL;
19189 	uint_t				sacnt = 0;
19190 	int				i;
19191 
19192 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19193 
19194 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19195 		return;
19196 
19197 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19198 		mutex_enter(&attrp->igsa_lock);
19199 		if ((gc = attrp->igsa_gc) != NULL) {
19200 			gcgrp = gc->gc_grp;
19201 			ASSERT(gcgrp != NULL);
19202 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19203 			sacnt = 1;
19204 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19205 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19206 			gc = gcgrp->gcgrp_head;
19207 			sacnt = gcgrp->gcgrp_count;
19208 		}
19209 		mutex_exit(&attrp->igsa_lock);
19210 
19211 		/* do nothing if there's no gc to report */
19212 		if (gc == NULL) {
19213 			ASSERT(sacnt == 0);
19214 			if (gcgrp != NULL) {
19215 				/* we might as well drop the lock now */
19216 				rw_exit(&gcgrp->gcgrp_rwlock);
19217 				gcgrp = NULL;
19218 			}
19219 			attrp = NULL;
19220 		}
19221 
19222 		ASSERT(gc == NULL || (gcgrp != NULL &&
19223 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19224 	}
19225 	ASSERT(sacnt == 0 || gc != NULL);
19226 
19227 	if (sacnt != 0 &&
19228 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19229 		kmem_free(re, sizeof (*re));
19230 		rw_exit(&gcgrp->gcgrp_rwlock);
19231 		return;
19232 	}
19233 
19234 	/*
19235 	 * Return all IRE types for route table... let caller pick and choose
19236 	 */
19237 	re->ipv6RouteDest = ire->ire_addr_v6;
19238 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19239 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19240 	re->ipv6RouteIfIndex.o_length = 0;
19241 	ipif = ire->ire_ipif;
19242 	if (ire->ire_type == IRE_CACHE) {
19243 		ill = (ill_t *)ire->ire_stq->q_ptr;
19244 		re->ipv6RouteIfIndex.o_length =
19245 		    ill->ill_name_length == 0 ? 0 :
19246 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19247 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19248 		    re->ipv6RouteIfIndex.o_length);
19249 	} else if (ipif != NULL) {
19250 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19251 		    OCTET_LENGTH);
19252 		re->ipv6RouteIfIndex.o_length =
19253 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19254 	}
19255 
19256 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19257 
19258 	mutex_enter(&ire->ire_lock);
19259 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19260 	mutex_exit(&ire->ire_lock);
19261 
19262 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19263 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19264 	else
19265 		re->ipv6RouteNextHop = gw_addr_v6;
19266 
19267 	/* remote(4), local(3), or discard(2) */
19268 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19269 		re->ipv6RouteType = 2;
19270 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19271 		re->ipv6RouteType = 3;
19272 	else
19273 		re->ipv6RouteType = 4;
19274 
19275 	re->ipv6RouteProtocol	= -1;
19276 	re->ipv6RoutePolicy	= 0;
19277 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19278 	re->ipv6RouteNextHopRDI	= 0;
19279 	re->ipv6RouteWeight	= 0;
19280 	re->ipv6RouteMetric	= 0;
19281 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19282 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19283 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19284 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19285 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19286 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19287 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19288 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19289 
19290 	if (ire->ire_flags & RTF_DYNAMIC) {
19291 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19292 	} else {
19293 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19294 	}
19295 
19296 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19297 	    (char *)re, (int)sizeof (*re))) {
19298 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19299 		    (uint_t)sizeof (*re)));
19300 	}
19301 
19302 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19303 		iaeptr->iae_routeidx = ird->ird_idx;
19304 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19305 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19306 	}
19307 
19308 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19309 	    (char *)iae, sacnt * sizeof (*iae))) {
19310 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19311 		    (unsigned)(sacnt * sizeof (*iae))));
19312 	}
19313 
19314 	/* bump route index for next pass */
19315 	ird->ird_idx++;
19316 
19317 	kmem_free(re, sizeof (*re));
19318 	if (sacnt != 0)
19319 		kmem_free(iae, sacnt * sizeof (*iae));
19320 
19321 	if (gcgrp != NULL)
19322 		rw_exit(&gcgrp->gcgrp_rwlock);
19323 }
19324 
19325 /*
19326  * ndp_walk routine to create ipv6NetToMediaEntryTable
19327  */
19328 static int
19329 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19330 {
19331 	ill_t				*ill;
19332 	mib2_ipv6NetToMediaEntry_t	ntme;
19333 	dl_unitdata_req_t		*dl;
19334 
19335 	ill = nce->nce_ill;
19336 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19337 		return (0);
19338 
19339 	/*
19340 	 * Neighbor cache entry attached to IRE with on-link
19341 	 * destination.
19342 	 */
19343 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19344 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19345 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19346 	    (nce->nce_res_mp != NULL)) {
19347 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19348 		ntme.ipv6NetToMediaPhysAddress.o_length =
19349 		    dl->dl_dest_addr_length;
19350 	} else {
19351 		ntme.ipv6NetToMediaPhysAddress.o_length =
19352 		    ill->ill_phys_addr_length;
19353 	}
19354 	if (nce->nce_res_mp != NULL) {
19355 		bcopy((char *)nce->nce_res_mp->b_rptr +
19356 		    NCE_LL_ADDR_OFFSET(ill),
19357 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19358 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19359 	} else {
19360 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19361 		    ill->ill_phys_addr_length);
19362 	}
19363 	/*
19364 	 * Note: Returns ND_* states. Should be:
19365 	 * reachable(1), stale(2), delay(3), probe(4),
19366 	 * invalid(5), unknown(6)
19367 	 */
19368 	ntme.ipv6NetToMediaState = nce->nce_state;
19369 	ntme.ipv6NetToMediaLastUpdated = 0;
19370 
19371 	/* other(1), dynamic(2), static(3), local(4) */
19372 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19373 		ntme.ipv6NetToMediaType = 4;
19374 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19375 		ntme.ipv6NetToMediaType = 1;
19376 	} else {
19377 		ntme.ipv6NetToMediaType = 2;
19378 	}
19379 
19380 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19381 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19382 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19383 		    (uint_t)sizeof (ntme)));
19384 	}
19385 	return (0);
19386 }
19387 
19388 /*
19389  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19390  */
19391 /* ARGSUSED */
19392 int
19393 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19394 {
19395 	switch (level) {
19396 	case MIB2_IP:
19397 	case MIB2_ICMP:
19398 		switch (name) {
19399 		default:
19400 			break;
19401 		}
19402 		return (1);
19403 	default:
19404 		return (1);
19405 	}
19406 }
19407 
19408 /*
19409  * When there exists both a 64- and 32-bit counter of a particular type
19410  * (i.e., InReceives), only the 64-bit counters are added.
19411  */
19412 void
19413 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19414 {
19415 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19416 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19417 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19418 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19419 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19420 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19421 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19422 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19423 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19424 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19425 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19426 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19427 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19428 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19429 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19430 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19431 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19432 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19433 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19434 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19435 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19436 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19437 	    o2->ipIfStatsInWrongIPVersion);
19438 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19439 	    o2->ipIfStatsInWrongIPVersion);
19440 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19441 	    o2->ipIfStatsOutSwitchIPVersion);
19442 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19443 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19444 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19445 	    o2->ipIfStatsHCInForwDatagrams);
19446 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19447 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19448 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19449 	    o2->ipIfStatsHCOutForwDatagrams);
19450 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19451 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19452 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19453 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19454 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19455 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19456 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19457 	    o2->ipIfStatsHCOutMcastOctets);
19458 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19459 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19460 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19461 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19462 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19463 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19464 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19465 }
19466 
19467 void
19468 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19469 {
19470 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19471 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19472 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19473 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19474 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19475 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19476 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19477 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19478 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19479 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19480 	    o2->ipv6IfIcmpInRouterSolicits);
19481 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19482 	    o2->ipv6IfIcmpInRouterAdvertisements);
19483 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19484 	    o2->ipv6IfIcmpInNeighborSolicits);
19485 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19486 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19487 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19488 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19489 	    o2->ipv6IfIcmpInGroupMembQueries);
19490 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19491 	    o2->ipv6IfIcmpInGroupMembResponses);
19492 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19493 	    o2->ipv6IfIcmpInGroupMembReductions);
19494 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19495 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19496 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19497 	    o2->ipv6IfIcmpOutDestUnreachs);
19498 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19499 	    o2->ipv6IfIcmpOutAdminProhibs);
19500 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19501 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19502 	    o2->ipv6IfIcmpOutParmProblems);
19503 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19504 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19505 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19506 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19507 	    o2->ipv6IfIcmpOutRouterSolicits);
19508 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19509 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19510 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19511 	    o2->ipv6IfIcmpOutNeighborSolicits);
19512 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19513 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19514 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19515 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19516 	    o2->ipv6IfIcmpOutGroupMembQueries);
19517 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19518 	    o2->ipv6IfIcmpOutGroupMembResponses);
19519 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19520 	    o2->ipv6IfIcmpOutGroupMembReductions);
19521 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19522 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19523 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19524 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19525 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19526 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19527 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19528 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19529 	    o2->ipv6IfIcmpInGroupMembTotal);
19530 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19531 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19532 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19533 	    o2->ipv6IfIcmpInGroupMembBadReports);
19534 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19535 	    o2->ipv6IfIcmpInGroupMembOurReports);
19536 }
19537 
19538 /*
19539  * Called before the options are updated to check if this packet will
19540  * be source routed from here.
19541  * This routine assumes that the options are well formed i.e. that they
19542  * have already been checked.
19543  */
19544 static boolean_t
19545 ip_source_routed(ipha_t *ipha)
19546 {
19547 	ipoptp_t	opts;
19548 	uchar_t		*opt;
19549 	uint8_t		optval;
19550 	uint8_t		optlen;
19551 	ipaddr_t	dst;
19552 	ire_t		*ire;
19553 
19554 	if (IS_SIMPLE_IPH(ipha)) {
19555 		ip2dbg(("not source routed\n"));
19556 		return (B_FALSE);
19557 	}
19558 	dst = ipha->ipha_dst;
19559 	for (optval = ipoptp_first(&opts, ipha);
19560 	    optval != IPOPT_EOL;
19561 	    optval = ipoptp_next(&opts)) {
19562 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19563 		opt = opts.ipoptp_cur;
19564 		optlen = opts.ipoptp_len;
19565 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19566 		    optval, optlen));
19567 		switch (optval) {
19568 			uint32_t off;
19569 		case IPOPT_SSRR:
19570 		case IPOPT_LSRR:
19571 			/*
19572 			 * If dst is one of our addresses and there are some
19573 			 * entries left in the source route return (true).
19574 			 */
19575 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19576 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19577 			if (ire == NULL) {
19578 				ip2dbg(("ip_source_routed: not next"
19579 				    " source route 0x%x\n",
19580 				    ntohl(dst)));
19581 				return (B_FALSE);
19582 			}
19583 			ire_refrele(ire);
19584 			off = opt[IPOPT_OFFSET];
19585 			off--;
19586 			if (optlen < IP_ADDR_LEN ||
19587 			    off > optlen - IP_ADDR_LEN) {
19588 				/* End of source route */
19589 				ip1dbg(("ip_source_routed: end of SR\n"));
19590 				return (B_FALSE);
19591 			}
19592 			return (B_TRUE);
19593 		}
19594 	}
19595 	ip2dbg(("not source routed\n"));
19596 	return (B_FALSE);
19597 }
19598 
19599 /*
19600  * Check if the packet contains any source route.
19601  */
19602 static boolean_t
19603 ip_source_route_included(ipha_t *ipha)
19604 {
19605 	ipoptp_t	opts;
19606 	uint8_t		optval;
19607 
19608 	if (IS_SIMPLE_IPH(ipha))
19609 		return (B_FALSE);
19610 	for (optval = ipoptp_first(&opts, ipha);
19611 	    optval != IPOPT_EOL;
19612 	    optval = ipoptp_next(&opts)) {
19613 		switch (optval) {
19614 		case IPOPT_SSRR:
19615 		case IPOPT_LSRR:
19616 			return (B_TRUE);
19617 		}
19618 	}
19619 	return (B_FALSE);
19620 }
19621 
19622 /*
19623  * Called when the IRE expiration timer fires.
19624  */
19625 /* ARGSUSED */
19626 void
19627 ip_trash_timer_expire(void *args)
19628 {
19629 	int	flush_flag = 0;
19630 
19631 	/*
19632 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19633 	 * This lock makes sure that a new invocation of this function
19634 	 * that occurs due to an almost immediate timer firing will not
19635 	 * progress beyond this point until the current invocation is done
19636 	 */
19637 	mutex_enter(&ip_trash_timer_lock);
19638 	ip_ire_expire_id = 0;
19639 	mutex_exit(&ip_trash_timer_lock);
19640 
19641 	/* Periodic timer */
19642 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19643 		/*
19644 		 * Remove all IRE_CACHE entries since they might
19645 		 * contain arp information.
19646 		 */
19647 		flush_flag |= FLUSH_ARP_TIME;
19648 		ip_ire_arp_time_elapsed = 0;
19649 		IP_STAT(ip_ire_arp_timer_expired);
19650 	}
19651 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19652 		/* Remove all redirects */
19653 		flush_flag |= FLUSH_REDIRECT_TIME;
19654 		ip_ire_rd_time_elapsed = 0;
19655 		IP_STAT(ip_ire_redirect_timer_expired);
19656 	}
19657 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19658 		/* Increase path mtu */
19659 		flush_flag |= FLUSH_MTU_TIME;
19660 		ip_ire_pmtu_time_elapsed = 0;
19661 		IP_STAT(ip_ire_pmtu_timer_expired);
19662 	}
19663 
19664 	/*
19665 	 * Optimize for the case when there are no redirects in the
19666 	 * ftable, that is, no need to walk the ftable in that case.
19667 	 */
19668 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19669 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19670 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19671 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19672 	}
19673 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19674 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19675 		    ire_expire, (char *)(uintptr_t)flush_flag,
19676 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19677 	}
19678 	if (flush_flag & FLUSH_MTU_TIME) {
19679 		/*
19680 		 * Walk all IPv6 IRE's and update them
19681 		 * Note that ARP and redirect timers are not
19682 		 * needed since NUD handles stale entries.
19683 		 */
19684 		flush_flag = FLUSH_MTU_TIME;
19685 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19686 		    ALL_ZONES);
19687 	}
19688 
19689 	ip_ire_arp_time_elapsed += ip_timer_interval;
19690 	ip_ire_rd_time_elapsed += ip_timer_interval;
19691 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19692 
19693 	/*
19694 	 * Hold the lock to serialize timeout calls and prevent
19695 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19696 	 * for the timer to fire and a new invocation of this function
19697 	 * to start before the return value of timeout has been stored
19698 	 * in ip_ire_expire_id by the current invocation.
19699 	 */
19700 	mutex_enter(&ip_trash_timer_lock);
19701 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19702 	    MSEC_TO_TICK(ip_timer_interval));
19703 	mutex_exit(&ip_trash_timer_lock);
19704 }
19705 
19706 /*
19707  * Called by the memory allocator subsystem directly, when the system
19708  * is running low on memory.
19709  */
19710 /* ARGSUSED */
19711 void
19712 ip_trash_ire_reclaim(void *args)
19713 {
19714 	ire_cache_count_t icc;
19715 	ire_cache_reclaim_t icr;
19716 	ncc_cache_count_t ncc;
19717 	nce_cache_reclaim_t ncr;
19718 	uint_t delete_cnt;
19719 	/*
19720 	 * Memory reclaim call back.
19721 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19722 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19723 	 * entries, determine what fraction to free for
19724 	 * each category of IRE_CACHE entries giving absolute priority
19725 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19726 	 * entry will be freed unless all offlink entries are freed).
19727 	 */
19728 	icc.icc_total = 0;
19729 	icc.icc_unused = 0;
19730 	icc.icc_offlink = 0;
19731 	icc.icc_pmtu = 0;
19732 	icc.icc_onlink = 0;
19733 	ire_walk(ire_cache_count, (char *)&icc);
19734 
19735 	/*
19736 	 * Free NCEs for IPv6 like the onlink ires.
19737 	 */
19738 	ncc.ncc_total = 0;
19739 	ncc.ncc_host = 0;
19740 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19741 
19742 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19743 	    icc.icc_pmtu + icc.icc_onlink);
19744 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19745 	IP_STAT(ip_trash_ire_reclaim_calls);
19746 	if (delete_cnt == 0)
19747 		return;
19748 	IP_STAT(ip_trash_ire_reclaim_success);
19749 	/* Always delete all unused offlink entries */
19750 	icr.icr_unused = 1;
19751 	if (delete_cnt <= icc.icc_unused) {
19752 		/*
19753 		 * Only need to free unused entries.  In other words,
19754 		 * there are enough unused entries to free to meet our
19755 		 * target number of freed ire cache entries.
19756 		 */
19757 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19758 		ncr.ncr_host = 0;
19759 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19760 		/*
19761 		 * Only need to free unused entries, plus a fraction of offlink
19762 		 * entries.  It follows from the first if statement that
19763 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19764 		 */
19765 		delete_cnt -= icc.icc_unused;
19766 		/* Round up # deleted by truncating fraction */
19767 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19768 		icr.icr_pmtu = icr.icr_onlink = 0;
19769 		ncr.ncr_host = 0;
19770 	} else if (delete_cnt <=
19771 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19772 		/*
19773 		 * Free all unused and offlink entries, plus a fraction of
19774 		 * pmtu entries.  It follows from the previous if statement
19775 		 * that icc_pmtu is non-zero, and that
19776 		 * delete_cnt != icc_unused + icc_offlink.
19777 		 */
19778 		icr.icr_offlink = 1;
19779 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19780 		/* Round up # deleted by truncating fraction */
19781 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19782 		icr.icr_onlink = 0;
19783 		ncr.ncr_host = 0;
19784 	} else {
19785 		/*
19786 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19787 		 * of onlink entries.  If we're here, then we know that
19788 		 * icc_onlink is non-zero, and that
19789 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19790 		 */
19791 		icr.icr_offlink = icr.icr_pmtu = 1;
19792 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19793 		    icc.icc_pmtu;
19794 		/* Round up # deleted by truncating fraction */
19795 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19796 		/* Using the same delete fraction as for onlink IREs */
19797 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19798 	}
19799 #ifdef DEBUG
19800 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19801 	    "fractions %d/%d/%d/%d\n",
19802 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19803 	    icc.icc_unused, icc.icc_offlink,
19804 	    icc.icc_pmtu, icc.icc_onlink,
19805 	    icr.icr_unused, icr.icr_offlink,
19806 	    icr.icr_pmtu, icr.icr_onlink));
19807 #endif
19808 	ire_walk(ire_cache_reclaim, (char *)&icr);
19809 	if (ncr.ncr_host != 0)
19810 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19811 		    (uchar_t *)&ncr);
19812 #ifdef DEBUG
19813 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19814 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19815 	ire_walk(ire_cache_count, (char *)&icc);
19816 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19817 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19818 	    icc.icc_pmtu, icc.icc_onlink));
19819 #endif
19820 }
19821 
19822 /*
19823  * ip_unbind is called when a copy of an unbind request is received from the
19824  * upper level protocol.  We remove this conn from any fanout hash list it is
19825  * on, and zero out the bind information.  No reply is expected up above.
19826  */
19827 mblk_t *
19828 ip_unbind(queue_t *q, mblk_t *mp)
19829 {
19830 	conn_t	*connp = Q_TO_CONN(q);
19831 
19832 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19833 
19834 	if (is_system_labeled() && connp->conn_anon_port) {
19835 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19836 		    connp->conn_mlp_type, connp->conn_ulp,
19837 		    ntohs(connp->conn_lport), B_FALSE);
19838 		connp->conn_anon_port = 0;
19839 	}
19840 	connp->conn_mlp_type = mlptSingle;
19841 
19842 	ipcl_hash_remove(connp);
19843 
19844 	ASSERT(mp->b_cont == NULL);
19845 	/*
19846 	 * Convert mp into a T_OK_ACK
19847 	 */
19848 	mp = mi_tpi_ok_ack_alloc(mp);
19849 
19850 	/*
19851 	 * should not happen in practice... T_OK_ACK is smaller than the
19852 	 * original message.
19853 	 */
19854 	if (mp == NULL)
19855 		return (NULL);
19856 
19857 	/*
19858 	 * Don't bzero the ports if its TCP since TCP still needs the
19859 	 * lport to remove it from its own bind hash. TCP will do the
19860 	 * cleanup.
19861 	 */
19862 	if (!IPCL_IS_TCP(connp))
19863 		bzero(&connp->u_port, sizeof (connp->u_port));
19864 
19865 	return (mp);
19866 }
19867 
19868 /*
19869  * Write side put procedure.  Outbound data, IOCTLs, responses from
19870  * resolvers, etc, come down through here.
19871  *
19872  * arg2 is always a queue_t *.
19873  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19874  * the zoneid.
19875  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19876  */
19877 void
19878 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19879 {
19880 	conn_t		*connp = NULL;
19881 	queue_t		*q = (queue_t *)arg2;
19882 	ipha_t		*ipha;
19883 #define	rptr	((uchar_t *)ipha)
19884 	ire_t		*ire = NULL;
19885 	ire_t		*sctp_ire = NULL;
19886 	uint32_t	v_hlen_tos_len;
19887 	ipaddr_t	dst;
19888 	mblk_t		*first_mp = NULL;
19889 	boolean_t	mctl_present;
19890 	ipsec_out_t	*io;
19891 	int		match_flags;
19892 	ill_t		*attach_ill = NULL;
19893 					/* Bind to IPIF_NOFAILOVER ill etc. */
19894 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19895 	ipif_t		*dst_ipif;
19896 	boolean_t	multirt_need_resolve = B_FALSE;
19897 	mblk_t		*copy_mp = NULL;
19898 	int		err;
19899 	zoneid_t	zoneid;
19900 	int	adjust;
19901 	uint16_t iplen;
19902 	boolean_t	need_decref = B_FALSE;
19903 	boolean_t	ignore_dontroute = B_FALSE;
19904 	boolean_t	ignore_nexthop = B_FALSE;
19905 	boolean_t	ip_nexthop = B_FALSE;
19906 	ipaddr_t	nexthop_addr;
19907 
19908 #ifdef	_BIG_ENDIAN
19909 #define	V_HLEN	(v_hlen_tos_len >> 24)
19910 #else
19911 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19912 #endif
19913 
19914 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19915 	    "ip_wput_start: q %p", q);
19916 
19917 	/*
19918 	 * ip_wput fast path
19919 	 */
19920 
19921 	/* is packet from ARP ? */
19922 	if (q->q_next != NULL) {
19923 		zoneid = (zoneid_t)(uintptr_t)arg;
19924 		goto qnext;
19925 	}
19926 
19927 	connp = (conn_t *)arg;
19928 	ASSERT(connp != NULL);
19929 	zoneid = connp->conn_zoneid;
19930 
19931 	/* is queue flow controlled? */
19932 	if ((q->q_first != NULL || connp->conn_draining) &&
19933 	    (caller == IP_WPUT)) {
19934 		ASSERT(!need_decref);
19935 		(void) putq(q, mp);
19936 		return;
19937 	}
19938 
19939 	/* Multidata transmit? */
19940 	if (DB_TYPE(mp) == M_MULTIDATA) {
19941 		/*
19942 		 * We should never get here, since all Multidata messages
19943 		 * originating from tcp should have been directed over to
19944 		 * tcp_multisend() in the first place.
19945 		 */
19946 		BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
19947 		freemsg(mp);
19948 		return;
19949 	} else if (DB_TYPE(mp) != M_DATA)
19950 		goto notdata;
19951 
19952 	if (mp->b_flag & MSGHASREF) {
19953 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19954 		mp->b_flag &= ~MSGHASREF;
19955 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19956 		need_decref = B_TRUE;
19957 	}
19958 	ipha = (ipha_t *)mp->b_rptr;
19959 
19960 	/* is IP header non-aligned or mblk smaller than basic IP header */
19961 #ifndef SAFETY_BEFORE_SPEED
19962 	if (!OK_32PTR(rptr) ||
19963 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19964 		goto hdrtoosmall;
19965 #endif
19966 
19967 	ASSERT(OK_32PTR(ipha));
19968 
19969 	/*
19970 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19971 	 * wrong version, we'll catch it again in ip_output_v6.
19972 	 *
19973 	 * Note that this is *only* locally-generated output here, and never
19974 	 * forwarded data, and that we need to deal only with transports that
19975 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19976 	 * label.)
19977 	 */
19978 	if (is_system_labeled() &&
19979 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19980 	    !connp->conn_ulp_labeled) {
19981 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19982 		    connp->conn_mac_exempt);
19983 		ipha = (ipha_t *)mp->b_rptr;
19984 		if (err != 0) {
19985 			first_mp = mp;
19986 			if (err == EINVAL)
19987 				goto icmp_parameter_problem;
19988 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19989 			goto discard_pkt;
19990 		}
19991 		iplen = ntohs(ipha->ipha_length) + adjust;
19992 		ipha->ipha_length = htons(iplen);
19993 	}
19994 
19995 	/*
19996 	 * If there is a policy, try to attach an ipsec_out in
19997 	 * the front. At the end, first_mp either points to a
19998 	 * M_DATA message or IPSEC_OUT message linked to a
19999 	 * M_DATA message. We have to do it now as we might
20000 	 * lose the "conn" if we go through ip_newroute.
20001 	 */
20002 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20003 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20004 		    ipha->ipha_protocol)) == NULL)) {
20005 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20006 			if (need_decref)
20007 				CONN_DEC_REF(connp);
20008 			return;
20009 		} else {
20010 			ASSERT(mp->b_datap->db_type == M_CTL);
20011 			first_mp = mp;
20012 			mp = mp->b_cont;
20013 			mctl_present = B_TRUE;
20014 		}
20015 	} else {
20016 		first_mp = mp;
20017 		mctl_present = B_FALSE;
20018 	}
20019 
20020 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20021 
20022 	/* is wrong version or IP options present */
20023 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20024 		goto version_hdrlen_check;
20025 	dst = ipha->ipha_dst;
20026 
20027 	if (connp->conn_nofailover_ill != NULL) {
20028 		attach_ill = conn_get_held_ill(connp,
20029 		    &connp->conn_nofailover_ill, &err);
20030 		if (err == ILL_LOOKUP_FAILED) {
20031 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20032 			if (need_decref)
20033 				CONN_DEC_REF(connp);
20034 			freemsg(first_mp);
20035 			return;
20036 		}
20037 	}
20038 
20039 	/* is packet multicast? */
20040 	if (CLASSD(dst))
20041 		goto multicast;
20042 
20043 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20044 	    (connp->conn_nexthop_set)) {
20045 		/*
20046 		 * If the destination is a broadcast or a loopback
20047 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20048 		 * through the standard path. But in the case of local
20049 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20050 		 * the standard path not IP_XMIT_IF.
20051 		 */
20052 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20053 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20054 		    (ire->ire_type != IRE_LOOPBACK))) {
20055 			if ((connp->conn_dontroute ||
20056 			    connp->conn_nexthop_set) && (ire != NULL) &&
20057 			    (ire->ire_type == IRE_LOCAL))
20058 				goto standard_path;
20059 
20060 			if (ire != NULL) {
20061 				ire_refrele(ire);
20062 				/* No more access to ire */
20063 				ire = NULL;
20064 			}
20065 			/*
20066 			 * bypass routing checks and go directly to
20067 			 * interface.
20068 			 */
20069 			if (connp->conn_dontroute) {
20070 				goto dontroute;
20071 			} else if (connp->conn_nexthop_set) {
20072 				ip_nexthop = B_TRUE;
20073 				nexthop_addr = connp->conn_nexthop_v4;
20074 				goto send_from_ill;
20075 			}
20076 
20077 			/*
20078 			 * If IP_XMIT_IF socket option is set,
20079 			 * then we allow unicast and multicast
20080 			 * packets to go through the ill. It is
20081 			 * quite possible that the destination
20082 			 * is not in the ire cache table and we
20083 			 * do not want to go to ip_newroute()
20084 			 * instead we call ip_newroute_ipif.
20085 			 */
20086 			xmit_ill = conn_get_held_ill(connp,
20087 			    &connp->conn_xmit_if_ill, &err);
20088 			if (err == ILL_LOOKUP_FAILED) {
20089 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20090 				if (attach_ill != NULL)
20091 					ill_refrele(attach_ill);
20092 				if (need_decref)
20093 					CONN_DEC_REF(connp);
20094 				freemsg(first_mp);
20095 				return;
20096 			}
20097 			goto send_from_ill;
20098 		}
20099 standard_path:
20100 		/* Must be a broadcast, a loopback or a local ire */
20101 		if (ire != NULL) {
20102 			ire_refrele(ire);
20103 			/* No more access to ire */
20104 			ire = NULL;
20105 		}
20106 	}
20107 
20108 	if (attach_ill != NULL)
20109 		goto send_from_ill;
20110 
20111 	/*
20112 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20113 	 * this for the tcp global queue and listen end point
20114 	 * as it does not really have a real destination to
20115 	 * talk to.  This is also true for SCTP.
20116 	 */
20117 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20118 	    !connp->conn_fully_bound) {
20119 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20120 		if (ire == NULL)
20121 			goto noirefound;
20122 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20123 		    "ip_wput_end: q %p (%S)", q, "end");
20124 
20125 		/*
20126 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20127 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20128 		 */
20129 		if (ire->ire_flags & RTF_MULTIRT) {
20130 
20131 			/*
20132 			 * Force the TTL of multirouted packets if required.
20133 			 * The TTL of such packets is bounded by the
20134 			 * ip_multirt_ttl ndd variable.
20135 			 */
20136 			if ((ip_multirt_ttl > 0) &&
20137 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
20138 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20139 				    "(was %d), dst 0x%08x\n",
20140 				    ip_multirt_ttl, ipha->ipha_ttl,
20141 				    ntohl(ire->ire_addr)));
20142 				ipha->ipha_ttl = ip_multirt_ttl;
20143 			}
20144 			/*
20145 			 * We look at this point if there are pending
20146 			 * unresolved routes. ire_multirt_resolvable()
20147 			 * checks in O(n) that all IRE_OFFSUBNET ire
20148 			 * entries for the packet's destination and
20149 			 * flagged RTF_MULTIRT are currently resolved.
20150 			 * If some remain unresolved, we make a copy
20151 			 * of the current message. It will be used
20152 			 * to initiate additional route resolutions.
20153 			 */
20154 			multirt_need_resolve =
20155 			    ire_multirt_need_resolve(ire->ire_addr,
20156 			    MBLK_GETLABEL(first_mp));
20157 			ip2dbg(("ip_wput[TCP]: ire %p, "
20158 			    "multirt_need_resolve %d, first_mp %p\n",
20159 			    (void *)ire, multirt_need_resolve,
20160 			    (void *)first_mp));
20161 			if (multirt_need_resolve) {
20162 				copy_mp = copymsg(first_mp);
20163 				if (copy_mp != NULL) {
20164 					MULTIRT_DEBUG_TAG(copy_mp);
20165 				}
20166 			}
20167 		}
20168 
20169 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20170 
20171 		/*
20172 		 * Try to resolve another multiroute if
20173 		 * ire_multirt_need_resolve() deemed it necessary.
20174 		 */
20175 		if (copy_mp != NULL) {
20176 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20177 		}
20178 		if (need_decref)
20179 			CONN_DEC_REF(connp);
20180 		return;
20181 	}
20182 
20183 	/*
20184 	 * Access to conn_ire_cache. (protected by conn_lock)
20185 	 *
20186 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20187 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20188 	 * send a packet or two with the IRE_CACHE that is going away.
20189 	 * Access to the ire requires an ire refhold on the ire prior to
20190 	 * its use since an interface unplumb thread may delete the cached
20191 	 * ire and release the refhold at any time.
20192 	 *
20193 	 * Caching an ire in the conn_ire_cache
20194 	 *
20195 	 * o Caching an ire pointer in the conn requires a strict check for
20196 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20197 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20198 	 * in the conn is done after making sure under the bucket lock that the
20199 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20200 	 * caching an ire after the unplumb thread has cleaned up the conn.
20201 	 * If the conn does not send a packet subsequently the unplumb thread
20202 	 * will be hanging waiting for the ire count to drop to zero.
20203 	 *
20204 	 * o We also need to atomically test for a null conn_ire_cache and
20205 	 * set the conn_ire_cache under the the protection of the conn_lock
20206 	 * to avoid races among concurrent threads trying to simultaneously
20207 	 * cache an ire in the conn_ire_cache.
20208 	 */
20209 	mutex_enter(&connp->conn_lock);
20210 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20211 
20212 	if (ire != NULL && ire->ire_addr == dst &&
20213 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20214 
20215 		IRE_REFHOLD(ire);
20216 		mutex_exit(&connp->conn_lock);
20217 
20218 	} else {
20219 		boolean_t cached = B_FALSE;
20220 		connp->conn_ire_cache = NULL;
20221 		mutex_exit(&connp->conn_lock);
20222 		/* Release the old ire */
20223 		if (ire != NULL && sctp_ire == NULL)
20224 			IRE_REFRELE_NOTR(ire);
20225 
20226 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20227 		if (ire == NULL)
20228 			goto noirefound;
20229 		IRE_REFHOLD_NOTR(ire);
20230 
20231 		mutex_enter(&connp->conn_lock);
20232 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
20233 		    connp->conn_ire_cache == NULL) {
20234 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20235 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20236 				connp->conn_ire_cache = ire;
20237 				cached = B_TRUE;
20238 			}
20239 			rw_exit(&ire->ire_bucket->irb_lock);
20240 		}
20241 		mutex_exit(&connp->conn_lock);
20242 
20243 		/*
20244 		 * We can continue to use the ire but since it was
20245 		 * not cached, we should drop the extra reference.
20246 		 */
20247 		if (!cached)
20248 			IRE_REFRELE_NOTR(ire);
20249 	}
20250 
20251 
20252 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20253 	    "ip_wput_end: q %p (%S)", q, "end");
20254 
20255 	/*
20256 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20257 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20258 	 */
20259 	if (ire->ire_flags & RTF_MULTIRT) {
20260 
20261 		/*
20262 		 * Force the TTL of multirouted packets if required.
20263 		 * The TTL of such packets is bounded by the
20264 		 * ip_multirt_ttl ndd variable.
20265 		 */
20266 		if ((ip_multirt_ttl > 0) &&
20267 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20268 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20269 			    "(was %d), dst 0x%08x\n",
20270 			    ip_multirt_ttl, ipha->ipha_ttl,
20271 			    ntohl(ire->ire_addr)));
20272 			ipha->ipha_ttl = ip_multirt_ttl;
20273 		}
20274 
20275 		/*
20276 		 * At this point, we check to see if there are any pending
20277 		 * unresolved routes. ire_multirt_resolvable()
20278 		 * checks in O(n) that all IRE_OFFSUBNET ire
20279 		 * entries for the packet's destination and
20280 		 * flagged RTF_MULTIRT are currently resolved.
20281 		 * If some remain unresolved, we make a copy
20282 		 * of the current message. It will be used
20283 		 * to initiate additional route resolutions.
20284 		 */
20285 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20286 		    MBLK_GETLABEL(first_mp));
20287 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20288 		    "multirt_need_resolve %d, first_mp %p\n",
20289 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20290 		if (multirt_need_resolve) {
20291 			copy_mp = copymsg(first_mp);
20292 			if (copy_mp != NULL) {
20293 				MULTIRT_DEBUG_TAG(copy_mp);
20294 			}
20295 		}
20296 	}
20297 
20298 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20299 
20300 	/*
20301 	 * Try to resolve another multiroute if
20302 	 * ire_multirt_resolvable() deemed it necessary
20303 	 */
20304 	if (copy_mp != NULL) {
20305 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20306 	}
20307 	if (need_decref)
20308 		CONN_DEC_REF(connp);
20309 	return;
20310 
20311 qnext:
20312 	/*
20313 	 * Upper Level Protocols pass down complete IP datagrams
20314 	 * as M_DATA messages.	Everything else is a sideshow.
20315 	 *
20316 	 * 1) We could be re-entering ip_wput because of ip_neworute
20317 	 *    in which case we could have a IPSEC_OUT message. We
20318 	 *    need to pass through ip_wput like other datagrams and
20319 	 *    hence cannot branch to ip_wput_nondata.
20320 	 *
20321 	 * 2) ARP, AH, ESP, and other clients who are on the module
20322 	 *    instance of IP stream, give us something to deal with.
20323 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20324 	 *
20325 	 * 3) ICMP replies also could come here.
20326 	 */
20327 	if (DB_TYPE(mp) != M_DATA) {
20328 	    notdata:
20329 		if (DB_TYPE(mp) == M_CTL) {
20330 			/*
20331 			 * M_CTL messages are used by ARP, AH and ESP to
20332 			 * communicate with IP. We deal with IPSEC_IN and
20333 			 * IPSEC_OUT here. ip_wput_nondata handles other
20334 			 * cases.
20335 			 */
20336 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20337 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20338 				first_mp = mp->b_cont;
20339 				first_mp->b_flag &= ~MSGHASREF;
20340 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20341 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20342 				CONN_DEC_REF(connp);
20343 				connp = NULL;
20344 			}
20345 			if (ii->ipsec_info_type == IPSEC_IN) {
20346 				/*
20347 				 * Either this message goes back to
20348 				 * IPSEC for further processing or to
20349 				 * ULP after policy checks.
20350 				 */
20351 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20352 				return;
20353 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20354 				io = (ipsec_out_t *)ii;
20355 				if (io->ipsec_out_proc_begin) {
20356 					/*
20357 					 * IPSEC processing has already started.
20358 					 * Complete it.
20359 					 * IPQoS notes: We don't care what is
20360 					 * in ipsec_out_ill_index since this
20361 					 * won't be processed for IPQoS policies
20362 					 * in ipsec_out_process.
20363 					 */
20364 					ipsec_out_process(q, mp, NULL,
20365 					    io->ipsec_out_ill_index);
20366 					return;
20367 				} else {
20368 					connp = (q->q_next != NULL) ?
20369 					    NULL : Q_TO_CONN(q);
20370 					first_mp = mp;
20371 					mp = mp->b_cont;
20372 					mctl_present = B_TRUE;
20373 				}
20374 				zoneid = io->ipsec_out_zoneid;
20375 				ASSERT(zoneid != ALL_ZONES);
20376 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20377 				/*
20378 				 * It's an IPsec control message requesting
20379 				 * an SADB update to be sent to the IPsec
20380 				 * hardware acceleration capable ills.
20381 				 */
20382 				ipsec_ctl_t *ipsec_ctl =
20383 				    (ipsec_ctl_t *)mp->b_rptr;
20384 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20385 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20386 				mblk_t *cmp = mp->b_cont;
20387 
20388 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20389 				ASSERT(cmp != NULL);
20390 
20391 				freeb(mp);
20392 				ill_ipsec_capab_send_all(satype, cmp, sa);
20393 				return;
20394 			} else {
20395 				/*
20396 				 * This must be ARP or special TSOL signaling.
20397 				 */
20398 				ip_wput_nondata(NULL, q, mp, NULL);
20399 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20400 				    "ip_wput_end: q %p (%S)", q, "nondata");
20401 				return;
20402 			}
20403 		} else {
20404 			/*
20405 			 * This must be non-(ARP/AH/ESP) messages.
20406 			 */
20407 			ASSERT(!need_decref);
20408 			ip_wput_nondata(NULL, q, mp, NULL);
20409 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20410 			    "ip_wput_end: q %p (%S)", q, "nondata");
20411 			return;
20412 		}
20413 	} else {
20414 		first_mp = mp;
20415 		mctl_present = B_FALSE;
20416 	}
20417 
20418 	ASSERT(first_mp != NULL);
20419 	/*
20420 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20421 	 * to make sure that this packet goes out on the same interface it
20422 	 * came in. We handle that here.
20423 	 */
20424 	if (mctl_present) {
20425 		uint_t ifindex;
20426 
20427 		io = (ipsec_out_t *)first_mp->b_rptr;
20428 		if (io->ipsec_out_attach_if ||
20429 		    io->ipsec_out_xmit_if ||
20430 		    io->ipsec_out_ip_nexthop) {
20431 			ill_t	*ill;
20432 
20433 			/*
20434 			 * We may have lost the conn context if we are
20435 			 * coming here from ip_newroute(). Copy the
20436 			 * nexthop information.
20437 			 */
20438 			if (io->ipsec_out_ip_nexthop) {
20439 				ip_nexthop = B_TRUE;
20440 				nexthop_addr = io->ipsec_out_nexthop_addr;
20441 
20442 				ipha = (ipha_t *)mp->b_rptr;
20443 				dst = ipha->ipha_dst;
20444 				goto send_from_ill;
20445 			} else {
20446 				ASSERT(io->ipsec_out_ill_index != 0);
20447 				ifindex = io->ipsec_out_ill_index;
20448 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20449 				    NULL, NULL, NULL, NULL);
20450 				/*
20451 				 * ipsec_out_xmit_if bit is used to tell
20452 				 * ip_wput to use the ill to send outgoing data
20453 				 * as we have no conn when data comes from ICMP
20454 				 * error msg routines. Currently this feature is
20455 				 * only used by ip_mrtun_forward routine.
20456 				 */
20457 				if (io->ipsec_out_xmit_if) {
20458 					xmit_ill = ill;
20459 					if (xmit_ill == NULL) {
20460 						ip1dbg(("ip_output:bad ifindex "
20461 						    "for xmit_ill %d\n",
20462 						    ifindex));
20463 						freemsg(first_mp);
20464 						BUMP_MIB(&ip_mib,
20465 						    ipIfStatsOutDiscards);
20466 						ASSERT(!need_decref);
20467 						return;
20468 					}
20469 					/* Free up the ipsec_out_t mblk */
20470 					ASSERT(first_mp->b_cont == mp);
20471 					first_mp->b_cont = NULL;
20472 					freeb(first_mp);
20473 					/* Just send the IP header+ICMP+data */
20474 					first_mp = mp;
20475 					ipha = (ipha_t *)mp->b_rptr;
20476 					dst = ipha->ipha_dst;
20477 					goto send_from_ill;
20478 				} else {
20479 					attach_ill = ill;
20480 				}
20481 
20482 				if (attach_ill == NULL) {
20483 					ASSERT(xmit_ill == NULL);
20484 					ip1dbg(("ip_output: bad ifindex for "
20485 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20486 					    ifindex));
20487 					freemsg(first_mp);
20488 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20489 					ASSERT(!need_decref);
20490 					return;
20491 				}
20492 			}
20493 		}
20494 	}
20495 
20496 	ASSERT(xmit_ill == NULL);
20497 
20498 	/* We have a complete IP datagram heading outbound. */
20499 	ipha = (ipha_t *)mp->b_rptr;
20500 
20501 #ifndef SPEED_BEFORE_SAFETY
20502 	/*
20503 	 * Make sure we have a full-word aligned message and that at least
20504 	 * a simple IP header is accessible in the first message.  If not,
20505 	 * try a pullup.
20506 	 */
20507 	if (!OK_32PTR(rptr) ||
20508 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20509 	    hdrtoosmall:
20510 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20511 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20512 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20513 			if (first_mp == NULL)
20514 				first_mp = mp;
20515 			goto discard_pkt;
20516 		}
20517 
20518 		/* This function assumes that mp points to an IPv4 packet. */
20519 		if (is_system_labeled() && q->q_next == NULL &&
20520 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20521 		    !connp->conn_ulp_labeled) {
20522 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20523 			    &adjust, connp->conn_mac_exempt);
20524 			ipha = (ipha_t *)mp->b_rptr;
20525 			if (first_mp != NULL)
20526 				first_mp->b_cont = mp;
20527 			if (err != 0) {
20528 				if (first_mp == NULL)
20529 					first_mp = mp;
20530 				if (err == EINVAL)
20531 					goto icmp_parameter_problem;
20532 				ip2dbg(("ip_wput: label check failed (%d)\n",
20533 				    err));
20534 				goto discard_pkt;
20535 			}
20536 			iplen = ntohs(ipha->ipha_length) + adjust;
20537 			ipha->ipha_length = htons(iplen);
20538 		}
20539 
20540 		ipha = (ipha_t *)mp->b_rptr;
20541 		if (first_mp == NULL) {
20542 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20543 			/*
20544 			 * If we got here because of "goto hdrtoosmall"
20545 			 * We need to attach a IPSEC_OUT.
20546 			 */
20547 			if (connp->conn_out_enforce_policy) {
20548 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20549 				    NULL, ipha->ipha_protocol)) == NULL)) {
20550 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20551 					if (need_decref)
20552 						CONN_DEC_REF(connp);
20553 					return;
20554 				} else {
20555 					ASSERT(mp->b_datap->db_type == M_CTL);
20556 					first_mp = mp;
20557 					mp = mp->b_cont;
20558 					mctl_present = B_TRUE;
20559 				}
20560 			} else {
20561 				first_mp = mp;
20562 				mctl_present = B_FALSE;
20563 			}
20564 		}
20565 	}
20566 #endif
20567 
20568 	/* Most of the code below is written for speed, not readability */
20569 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20570 
20571 	/*
20572 	 * If ip_newroute() fails, we're going to need a full
20573 	 * header for the icmp wraparound.
20574 	 */
20575 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20576 		uint_t	v_hlen;
20577 	    version_hdrlen_check:
20578 		ASSERT(first_mp != NULL);
20579 		v_hlen = V_HLEN;
20580 		/*
20581 		 * siphon off IPv6 packets coming down from transport
20582 		 * layer modules here.
20583 		 * Note: high-order bit carries NUD reachability confirmation
20584 		 */
20585 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20586 			/*
20587 			 * XXX implement a IPv4 and IPv6 packet counter per
20588 			 * conn and switch when ratio exceeds e.g. 10:1
20589 			 */
20590 #ifdef notyet
20591 			if (q->q_next == NULL) /* Avoid ill queue */
20592 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20593 #endif
20594 			BUMP_MIB(&ip_mib, ipIfStatsOutWrongIPVersion);
20595 			ASSERT(xmit_ill == NULL);
20596 			if (attach_ill != NULL)
20597 				ill_refrele(attach_ill);
20598 			if (need_decref)
20599 				mp->b_flag |= MSGHASREF;
20600 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20601 			return;
20602 		}
20603 
20604 		if ((v_hlen >> 4) != IP_VERSION) {
20605 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20606 			    "ip_wput_end: q %p (%S)", q, "badvers");
20607 			goto discard_pkt;
20608 		}
20609 		/*
20610 		 * Is the header length at least 20 bytes?
20611 		 *
20612 		 * Are there enough bytes accessible in the header?  If
20613 		 * not, try a pullup.
20614 		 */
20615 		v_hlen &= 0xF;
20616 		v_hlen <<= 2;
20617 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20618 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20619 			    "ip_wput_end: q %p (%S)", q, "badlen");
20620 			goto discard_pkt;
20621 		}
20622 		if (v_hlen > (mp->b_wptr - rptr)) {
20623 			if (!pullupmsg(mp, v_hlen)) {
20624 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20625 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20626 				goto discard_pkt;
20627 			}
20628 			ipha = (ipha_t *)mp->b_rptr;
20629 		}
20630 		/*
20631 		 * Move first entry from any source route into ipha_dst and
20632 		 * verify the options
20633 		 */
20634 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20635 			ASSERT(xmit_ill == NULL);
20636 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20637 			if (attach_ill != NULL)
20638 				ill_refrele(attach_ill);
20639 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20640 			    "ip_wput_end: q %p (%S)", q, "badopts");
20641 			if (need_decref)
20642 				CONN_DEC_REF(connp);
20643 			return;
20644 		}
20645 	}
20646 	dst = ipha->ipha_dst;
20647 
20648 	/*
20649 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20650 	 * we have to run the packet through ip_newroute which will take
20651 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20652 	 * a resolver, or assigning a default gateway, etc.
20653 	 */
20654 	if (CLASSD(dst)) {
20655 		ipif_t	*ipif;
20656 		uint32_t setsrc = 0;
20657 
20658 	    multicast:
20659 		ASSERT(first_mp != NULL);
20660 		ASSERT(xmit_ill == NULL);
20661 		ip2dbg(("ip_wput: CLASSD\n"));
20662 		if (connp == NULL) {
20663 			/*
20664 			 * Use the first good ipif on the ill.
20665 			 * XXX Should this ever happen? (Appears
20666 			 * to show up with just ppp and no ethernet due
20667 			 * to in.rdisc.)
20668 			 * However, ire_send should be able to
20669 			 * call ip_wput_ire directly.
20670 			 *
20671 			 * XXX Also, this can happen for ICMP and other packets
20672 			 * with multicast source addresses.  Perhaps we should
20673 			 * fix things so that we drop the packet in question,
20674 			 * but for now, just run with it.
20675 			 */
20676 			ill_t *ill = (ill_t *)q->q_ptr;
20677 
20678 			/*
20679 			 * Don't honor attach_if for this case. If ill
20680 			 * is part of the group, ipif could belong to
20681 			 * any ill and we cannot maintain attach_ill
20682 			 * and ipif_ill same anymore and the assert
20683 			 * below would fail.
20684 			 */
20685 			if (mctl_present && io->ipsec_out_attach_if) {
20686 				io->ipsec_out_ill_index = 0;
20687 				io->ipsec_out_attach_if = B_FALSE;
20688 				ASSERT(attach_ill != NULL);
20689 				ill_refrele(attach_ill);
20690 				attach_ill = NULL;
20691 			}
20692 
20693 			ASSERT(attach_ill == NULL);
20694 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20695 			if (ipif == NULL) {
20696 				if (need_decref)
20697 					CONN_DEC_REF(connp);
20698 				freemsg(first_mp);
20699 				return;
20700 			}
20701 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20702 			    ntohl(dst), ill->ill_name));
20703 		} else {
20704 			/*
20705 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20706 			 * IP_XMIT_IF is honoured.
20707 			 * Block comment above this function explains the
20708 			 * locking mechanism used here
20709 			 */
20710 			xmit_ill = conn_get_held_ill(connp,
20711 			    &connp->conn_xmit_if_ill, &err);
20712 			if (err == ILL_LOOKUP_FAILED) {
20713 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20714 				BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20715 				goto drop_pkt;
20716 			}
20717 			if (xmit_ill == NULL) {
20718 				ipif = conn_get_held_ipif(connp,
20719 				    &connp->conn_multicast_ipif, &err);
20720 				if (err == IPIF_LOOKUP_FAILED) {
20721 					ip1dbg(("ip_wput: No ipif for "
20722 					    "multicast\n"));
20723 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20724 					goto drop_pkt;
20725 				}
20726 			}
20727 			if (xmit_ill != NULL) {
20728 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20729 				if (ipif == NULL) {
20730 					ip1dbg(("ip_wput: No ipif for "
20731 					    "IP_XMIT_IF\n"));
20732 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20733 					goto drop_pkt;
20734 				}
20735 			} else if (ipif == NULL || ipif->ipif_isv6) {
20736 				/*
20737 				 * We must do this ipif determination here
20738 				 * else we could pass through ip_newroute
20739 				 * and come back here without the conn context.
20740 				 *
20741 				 * Note: we do late binding i.e. we bind to
20742 				 * the interface when the first packet is sent.
20743 				 * For performance reasons we do not rebind on
20744 				 * each packet but keep the binding until the
20745 				 * next IP_MULTICAST_IF option.
20746 				 *
20747 				 * conn_multicast_{ipif,ill} are shared between
20748 				 * IPv4 and IPv6 and AF_INET6 sockets can
20749 				 * send both IPv4 and IPv6 packets. Hence
20750 				 * we have to check that "isv6" matches above.
20751 				 */
20752 				if (ipif != NULL)
20753 					ipif_refrele(ipif);
20754 				ipif = ipif_lookup_group(dst, zoneid);
20755 				if (ipif == NULL) {
20756 					ip1dbg(("ip_wput: No ipif for "
20757 					    "multicast\n"));
20758 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20759 					goto drop_pkt;
20760 				}
20761 				err = conn_set_held_ipif(connp,
20762 				    &connp->conn_multicast_ipif, ipif);
20763 				if (err == IPIF_LOOKUP_FAILED) {
20764 					ipif_refrele(ipif);
20765 					ip1dbg(("ip_wput: No ipif for "
20766 					    "multicast\n"));
20767 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20768 					goto drop_pkt;
20769 				}
20770 			}
20771 		}
20772 		ASSERT(!ipif->ipif_isv6);
20773 		/*
20774 		 * As we may lose the conn by the time we reach ip_wput_ire,
20775 		 * we copy conn_multicast_loop and conn_dontroute on to an
20776 		 * ipsec_out. In case if this datagram goes out secure,
20777 		 * we need the ill_index also. Copy that also into the
20778 		 * ipsec_out.
20779 		 */
20780 		if (mctl_present) {
20781 			io = (ipsec_out_t *)first_mp->b_rptr;
20782 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20783 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20784 		} else {
20785 			ASSERT(mp == first_mp);
20786 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20787 			    BPRI_HI)) == NULL) {
20788 				ipif_refrele(ipif);
20789 				first_mp = mp;
20790 				goto discard_pkt;
20791 			}
20792 			first_mp->b_datap->db_type = M_CTL;
20793 			first_mp->b_wptr += sizeof (ipsec_info_t);
20794 			/* ipsec_out_secure is B_FALSE now */
20795 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20796 			io = (ipsec_out_t *)first_mp->b_rptr;
20797 			io->ipsec_out_type = IPSEC_OUT;
20798 			io->ipsec_out_len = sizeof (ipsec_out_t);
20799 			io->ipsec_out_use_global_policy = B_TRUE;
20800 			first_mp->b_cont = mp;
20801 			mctl_present = B_TRUE;
20802 		}
20803 		if (attach_ill != NULL) {
20804 			ASSERT(attach_ill == ipif->ipif_ill);
20805 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20806 
20807 			/*
20808 			 * Check if we need an ire that will not be
20809 			 * looked up by anybody else i.e. HIDDEN.
20810 			 */
20811 			if (ill_is_probeonly(attach_ill)) {
20812 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20813 			}
20814 			io->ipsec_out_ill_index =
20815 			    attach_ill->ill_phyint->phyint_ifindex;
20816 			io->ipsec_out_attach_if = B_TRUE;
20817 		} else {
20818 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20819 			io->ipsec_out_ill_index =
20820 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20821 		}
20822 		if (connp != NULL) {
20823 			io->ipsec_out_multicast_loop =
20824 			    connp->conn_multicast_loop;
20825 			io->ipsec_out_dontroute = connp->conn_dontroute;
20826 			io->ipsec_out_zoneid = connp->conn_zoneid;
20827 		}
20828 		/*
20829 		 * If the application uses IP_MULTICAST_IF with
20830 		 * different logical addresses of the same ILL, we
20831 		 * need to make sure that the soruce address of
20832 		 * the packet matches the logical IP address used
20833 		 * in the option. We do it by initializing ipha_src
20834 		 * here. This should keep IPSEC also happy as
20835 		 * when we return from IPSEC processing, we don't
20836 		 * have to worry about getting the right address on
20837 		 * the packet. Thus it is sufficient to look for
20838 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20839 		 * MATCH_IRE_IPIF.
20840 		 *
20841 		 * NOTE : We need to do it for non-secure case also as
20842 		 * this might go out secure if there is a global policy
20843 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20844 		 * address, the source should be initialized already and
20845 		 * hence we won't be initializing here.
20846 		 *
20847 		 * As we do not have the ire yet, it is possible that
20848 		 * we set the source address here and then later discover
20849 		 * that the ire implies the source address to be assigned
20850 		 * through the RTF_SETSRC flag.
20851 		 * In that case, the setsrc variable will remind us
20852 		 * that overwritting the source address by the one
20853 		 * of the RTF_SETSRC-flagged ire is allowed.
20854 		 */
20855 		if (ipha->ipha_src == INADDR_ANY &&
20856 		    (connp == NULL || !connp->conn_unspec_src)) {
20857 			ipha->ipha_src = ipif->ipif_src_addr;
20858 			setsrc = RTF_SETSRC;
20859 		}
20860 		/*
20861 		 * Find an IRE which matches the destination and the outgoing
20862 		 * queue (i.e. the outgoing interface.)
20863 		 * For loopback use a unicast IP address for
20864 		 * the ire lookup.
20865 		 */
20866 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20867 		    PHYI_LOOPBACK) {
20868 			dst = ipif->ipif_lcl_addr;
20869 		}
20870 		/*
20871 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20872 		 * We don't need to lookup ire in ctable as the packet
20873 		 * needs to be sent to the destination through the specified
20874 		 * ill irrespective of ires in the cache table.
20875 		 */
20876 		ire = NULL;
20877 		if (xmit_ill == NULL) {
20878 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20879 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20880 		}
20881 
20882 		/*
20883 		 * refrele attach_ill as its not needed anymore.
20884 		 */
20885 		if (attach_ill != NULL) {
20886 			ill_refrele(attach_ill);
20887 			attach_ill = NULL;
20888 		}
20889 
20890 		if (ire == NULL) {
20891 			/*
20892 			 * Multicast loopback and multicast forwarding is
20893 			 * done in ip_wput_ire.
20894 			 *
20895 			 * Mark this packet to make it be delivered to
20896 			 * ip_wput_ire after the new ire has been
20897 			 * created.
20898 			 *
20899 			 * The call to ip_newroute_ipif takes into account
20900 			 * the setsrc reminder. In any case, we take care
20901 			 * of the RTF_MULTIRT flag.
20902 			 */
20903 			mp->b_prev = mp->b_next = NULL;
20904 			if (xmit_ill == NULL ||
20905 			    xmit_ill->ill_ipif_up_count > 0) {
20906 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20907 				    setsrc | RTF_MULTIRT, zoneid);
20908 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20909 				    "ip_wput_end: q %p (%S)", q, "noire");
20910 			} else {
20911 				freemsg(first_mp);
20912 			}
20913 			ipif_refrele(ipif);
20914 			if (xmit_ill != NULL)
20915 				ill_refrele(xmit_ill);
20916 			if (need_decref)
20917 				CONN_DEC_REF(connp);
20918 			return;
20919 		}
20920 
20921 		ipif_refrele(ipif);
20922 		ipif = NULL;
20923 		ASSERT(xmit_ill == NULL);
20924 
20925 		/*
20926 		 * Honor the RTF_SETSRC flag for multicast packets,
20927 		 * if allowed by the setsrc reminder.
20928 		 */
20929 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20930 			ipha->ipha_src = ire->ire_src_addr;
20931 		}
20932 
20933 		/*
20934 		 * Unconditionally force the TTL to 1 for
20935 		 * multirouted multicast packets:
20936 		 * multirouted multicast should not cross
20937 		 * multicast routers.
20938 		 */
20939 		if (ire->ire_flags & RTF_MULTIRT) {
20940 			if (ipha->ipha_ttl > 1) {
20941 				ip2dbg(("ip_wput: forcing multicast "
20942 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20943 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20944 				ipha->ipha_ttl = 1;
20945 			}
20946 		}
20947 	} else {
20948 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20949 		if ((ire != NULL) && (ire->ire_type &
20950 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20951 			ignore_dontroute = B_TRUE;
20952 			ignore_nexthop = B_TRUE;
20953 		}
20954 		if (ire != NULL) {
20955 			ire_refrele(ire);
20956 			ire = NULL;
20957 		}
20958 		/*
20959 		 * Guard against coming in from arp in which case conn is NULL.
20960 		 * Also guard against non M_DATA with dontroute set but
20961 		 * destined to local, loopback or broadcast addresses.
20962 		 */
20963 		if (connp != NULL && connp->conn_dontroute &&
20964 		    !ignore_dontroute) {
20965 dontroute:
20966 			/*
20967 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20968 			 * routing protocols from seeing false direct
20969 			 * connectivity.
20970 			 */
20971 			ipha->ipha_ttl = 1;
20972 			/*
20973 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20974 			 * along with SO_DONTROUTE, higher precedence is
20975 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20976 			 */
20977 			if (connp->conn_xmit_if_ill == NULL) {
20978 				/* If suitable ipif not found, drop packet */
20979 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20980 				if (dst_ipif == NULL) {
20981 					ip1dbg(("ip_wput: no route for "
20982 					    "dst using SO_DONTROUTE\n"));
20983 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20984 					mp->b_prev = mp->b_next = NULL;
20985 					if (first_mp == NULL)
20986 						first_mp = mp;
20987 					goto drop_pkt;
20988 				} else {
20989 					/*
20990 					 * If suitable ipif has been found, set
20991 					 * xmit_ill to the corresponding
20992 					 * ipif_ill because we'll be following
20993 					 * the IP_XMIT_IF logic.
20994 					 */
20995 					ASSERT(xmit_ill == NULL);
20996 					xmit_ill = dst_ipif->ipif_ill;
20997 					mutex_enter(&xmit_ill->ill_lock);
20998 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20999 						mutex_exit(&xmit_ill->ill_lock);
21000 						xmit_ill = NULL;
21001 						ipif_refrele(dst_ipif);
21002 						ip1dbg(("ip_wput: no route for"
21003 						    " dst using"
21004 						    " SO_DONTROUTE\n"));
21005 						BUMP_MIB(&ip_mib,
21006 						    ipIfStatsOutNoRoutes);
21007 						mp->b_prev = mp->b_next = NULL;
21008 						if (first_mp == NULL)
21009 							first_mp = mp;
21010 						goto drop_pkt;
21011 					}
21012 					ill_refhold_locked(xmit_ill);
21013 					mutex_exit(&xmit_ill->ill_lock);
21014 					ipif_refrele(dst_ipif);
21015 				}
21016 			}
21017 
21018 		}
21019 		/*
21020 		 * If we are bound to IPIF_NOFAILOVER address, look for
21021 		 * an IRE_CACHE matching the ill.
21022 		 */
21023 send_from_ill:
21024 		if (attach_ill != NULL) {
21025 			ipif_t	*attach_ipif;
21026 
21027 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21028 
21029 			/*
21030 			 * Check if we need an ire that will not be
21031 			 * looked up by anybody else i.e. HIDDEN.
21032 			 */
21033 			if (ill_is_probeonly(attach_ill)) {
21034 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21035 			}
21036 
21037 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21038 			if (attach_ipif == NULL) {
21039 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21040 				goto discard_pkt;
21041 			}
21042 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21043 			    zoneid, MBLK_GETLABEL(mp), match_flags);
21044 			ipif_refrele(attach_ipif);
21045 		} else if (xmit_ill != NULL || (connp != NULL &&
21046 			    connp->conn_xmit_if_ill != NULL)) {
21047 			/*
21048 			 * Mark this packet as originated locally
21049 			 */
21050 			mp->b_prev = mp->b_next = NULL;
21051 			/*
21052 			 * xmit_ill could be NULL if SO_DONTROUTE
21053 			 * is also set.
21054 			 */
21055 			if (xmit_ill == NULL) {
21056 				xmit_ill = conn_get_held_ill(connp,
21057 				    &connp->conn_xmit_if_ill, &err);
21058 				if (err == ILL_LOOKUP_FAILED) {
21059 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21060 					if (need_decref)
21061 						CONN_DEC_REF(connp);
21062 					freemsg(first_mp);
21063 					return;
21064 				}
21065 				if (xmit_ill == NULL) {
21066 					if (connp->conn_dontroute)
21067 						goto dontroute;
21068 					goto send_from_ill;
21069 				}
21070 			}
21071 			/*
21072 			 * could be SO_DONTROUTE case also.
21073 			 * check at least one interface is UP as
21074 			 * spcified by this ILL, and then call
21075 			 * ip_newroute_ipif()
21076 			 */
21077 			if (xmit_ill->ill_ipif_up_count > 0) {
21078 				ipif_t *ipif;
21079 
21080 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21081 				if (ipif != NULL) {
21082 					ip_newroute_ipif(q, first_mp, ipif,
21083 					    dst, connp, 0, zoneid);
21084 					ipif_refrele(ipif);
21085 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21086 				}
21087 			} else {
21088 				freemsg(first_mp);
21089 			}
21090 			ill_refrele(xmit_ill);
21091 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21092 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
21093 			if (need_decref)
21094 				CONN_DEC_REF(connp);
21095 			return;
21096 		} else if (ip_nexthop || (connp != NULL &&
21097 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21098 			if (!ip_nexthop) {
21099 				ip_nexthop = B_TRUE;
21100 				nexthop_addr = connp->conn_nexthop_v4;
21101 			}
21102 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21103 			    MATCH_IRE_GW;
21104 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21105 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
21106 		} else {
21107 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
21108 		}
21109 		if (!ire) {
21110 			/*
21111 			 * Make sure we don't load spread if this
21112 			 * is IPIF_NOFAILOVER case.
21113 			 */
21114 			if ((attach_ill != NULL) ||
21115 			    (ip_nexthop && !ignore_nexthop)) {
21116 				if (mctl_present) {
21117 					io = (ipsec_out_t *)first_mp->b_rptr;
21118 					ASSERT(first_mp->b_datap->db_type ==
21119 					    M_CTL);
21120 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21121 				} else {
21122 					ASSERT(mp == first_mp);
21123 					first_mp = allocb(
21124 					    sizeof (ipsec_info_t), BPRI_HI);
21125 					if (first_mp == NULL) {
21126 						first_mp = mp;
21127 						goto discard_pkt;
21128 					}
21129 					first_mp->b_datap->db_type = M_CTL;
21130 					first_mp->b_wptr +=
21131 					    sizeof (ipsec_info_t);
21132 					/* ipsec_out_secure is B_FALSE now */
21133 					bzero(first_mp->b_rptr,
21134 					    sizeof (ipsec_info_t));
21135 					io = (ipsec_out_t *)first_mp->b_rptr;
21136 					io->ipsec_out_type = IPSEC_OUT;
21137 					io->ipsec_out_len =
21138 					    sizeof (ipsec_out_t);
21139 					io->ipsec_out_use_global_policy =
21140 					    B_TRUE;
21141 					first_mp->b_cont = mp;
21142 					mctl_present = B_TRUE;
21143 				}
21144 				if (attach_ill != NULL) {
21145 					io->ipsec_out_ill_index = attach_ill->
21146 					    ill_phyint->phyint_ifindex;
21147 					io->ipsec_out_attach_if = B_TRUE;
21148 				} else {
21149 					io->ipsec_out_ip_nexthop = ip_nexthop;
21150 					io->ipsec_out_nexthop_addr =
21151 					    nexthop_addr;
21152 				}
21153 			}
21154 noirefound:
21155 			/*
21156 			 * Mark this packet as having originated on
21157 			 * this machine.  This will be noted in
21158 			 * ire_add_then_send, which needs to know
21159 			 * whether to run it back through ip_wput or
21160 			 * ip_rput following successful resolution.
21161 			 */
21162 			mp->b_prev = NULL;
21163 			mp->b_next = NULL;
21164 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
21165 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21166 			    "ip_wput_end: q %p (%S)", q, "newroute");
21167 			if (attach_ill != NULL)
21168 				ill_refrele(attach_ill);
21169 			if (xmit_ill != NULL)
21170 				ill_refrele(xmit_ill);
21171 			if (need_decref)
21172 				CONN_DEC_REF(connp);
21173 			return;
21174 		}
21175 	}
21176 
21177 	/* We now know where we are going with it. */
21178 
21179 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21180 	    "ip_wput_end: q %p (%S)", q, "end");
21181 
21182 	/*
21183 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21184 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21185 	 */
21186 	if (ire->ire_flags & RTF_MULTIRT) {
21187 		/*
21188 		 * Force the TTL of multirouted packets if required.
21189 		 * The TTL of such packets is bounded by the
21190 		 * ip_multirt_ttl ndd variable.
21191 		 */
21192 		if ((ip_multirt_ttl > 0) &&
21193 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
21194 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21195 			    "(was %d), dst 0x%08x\n",
21196 			    ip_multirt_ttl, ipha->ipha_ttl,
21197 			    ntohl(ire->ire_addr)));
21198 			ipha->ipha_ttl = ip_multirt_ttl;
21199 		}
21200 		/*
21201 		 * At this point, we check to see if there are any pending
21202 		 * unresolved routes. ire_multirt_resolvable()
21203 		 * checks in O(n) that all IRE_OFFSUBNET ire
21204 		 * entries for the packet's destination and
21205 		 * flagged RTF_MULTIRT are currently resolved.
21206 		 * If some remain unresolved, we make a copy
21207 		 * of the current message. It will be used
21208 		 * to initiate additional route resolutions.
21209 		 */
21210 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21211 		    MBLK_GETLABEL(first_mp));
21212 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21213 		    "multirt_need_resolve %d, first_mp %p\n",
21214 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21215 		if (multirt_need_resolve) {
21216 			copy_mp = copymsg(first_mp);
21217 			if (copy_mp != NULL) {
21218 				MULTIRT_DEBUG_TAG(copy_mp);
21219 			}
21220 		}
21221 	}
21222 
21223 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21224 	/*
21225 	 * Try to resolve another multiroute if
21226 	 * ire_multirt_resolvable() deemed it necessary.
21227 	 * At this point, we need to distinguish
21228 	 * multicasts from other packets. For multicasts,
21229 	 * we call ip_newroute_ipif() and request that both
21230 	 * multirouting and setsrc flags are checked.
21231 	 */
21232 	if (copy_mp != NULL) {
21233 		if (CLASSD(dst)) {
21234 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
21235 			if (ipif) {
21236 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21237 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
21238 				ipif_refrele(ipif);
21239 			} else {
21240 				MULTIRT_DEBUG_UNTAG(copy_mp);
21241 				freemsg(copy_mp);
21242 				copy_mp = NULL;
21243 			}
21244 		} else {
21245 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
21246 		}
21247 	}
21248 	if (attach_ill != NULL)
21249 		ill_refrele(attach_ill);
21250 	if (xmit_ill != NULL)
21251 		ill_refrele(xmit_ill);
21252 	if (need_decref)
21253 		CONN_DEC_REF(connp);
21254 	return;
21255 
21256 icmp_parameter_problem:
21257 	/* could not have originated externally */
21258 	ASSERT(mp->b_prev == NULL);
21259 	if (ip_hdr_complete(ipha, zoneid) == 0) {
21260 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21261 		/* it's the IP header length that's in trouble */
21262 		icmp_param_problem(q, first_mp, 0, zoneid);
21263 		first_mp = NULL;
21264 	}
21265 
21266 discard_pkt:
21267 	BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21268 drop_pkt:
21269 	ip1dbg(("ip_wput: dropped packet\n"));
21270 	if (ire != NULL)
21271 		ire_refrele(ire);
21272 	if (need_decref)
21273 		CONN_DEC_REF(connp);
21274 	freemsg(first_mp);
21275 	if (attach_ill != NULL)
21276 		ill_refrele(attach_ill);
21277 	if (xmit_ill != NULL)
21278 		ill_refrele(xmit_ill);
21279 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21280 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21281 }
21282 
21283 /*
21284  * If this is a conn_t queue, then we pass in the conn. This includes the
21285  * zoneid.
21286  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21287  * in which case we use the global zoneid since those are all part of
21288  * the global zone.
21289  */
21290 void
21291 ip_wput(queue_t *q, mblk_t *mp)
21292 {
21293 	if (CONN_Q(q))
21294 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21295 	else
21296 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21297 }
21298 
21299 /*
21300  *
21301  * The following rules must be observed when accessing any ipif or ill
21302  * that has been cached in the conn. Typically conn_nofailover_ill,
21303  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21304  *
21305  * Access: The ipif or ill pointed to from the conn can be accessed under
21306  * the protection of the conn_lock or after it has been refheld under the
21307  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21308  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21309  * The reason for this is that a concurrent unplumb could actually be
21310  * cleaning up these cached pointers by walking the conns and might have
21311  * finished cleaning up the conn in question. The macros check that an
21312  * unplumb has not yet started on the ipif or ill.
21313  *
21314  * Caching: An ipif or ill pointer may be cached in the conn only after
21315  * making sure that an unplumb has not started. So the caching is done
21316  * while holding both the conn_lock and the ill_lock and after using the
21317  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21318  * flag before starting the cleanup of conns.
21319  *
21320  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21321  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21322  * or a reference to the ipif or a reference to an ire that references the
21323  * ipif. An ipif does not change its ill except for failover/failback. Since
21324  * failover/failback happens only after bringing down the ipif and making sure
21325  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21326  * the above holds.
21327  */
21328 ipif_t *
21329 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21330 {
21331 	ipif_t	*ipif;
21332 	ill_t	*ill;
21333 
21334 	*err = 0;
21335 	rw_enter(&ill_g_lock, RW_READER);
21336 	mutex_enter(&connp->conn_lock);
21337 	ipif = *ipifp;
21338 	if (ipif != NULL) {
21339 		ill = ipif->ipif_ill;
21340 		mutex_enter(&ill->ill_lock);
21341 		if (IPIF_CAN_LOOKUP(ipif)) {
21342 			ipif_refhold_locked(ipif);
21343 			mutex_exit(&ill->ill_lock);
21344 			mutex_exit(&connp->conn_lock);
21345 			rw_exit(&ill_g_lock);
21346 			return (ipif);
21347 		} else {
21348 			*err = IPIF_LOOKUP_FAILED;
21349 		}
21350 		mutex_exit(&ill->ill_lock);
21351 	}
21352 	mutex_exit(&connp->conn_lock);
21353 	rw_exit(&ill_g_lock);
21354 	return (NULL);
21355 }
21356 
21357 ill_t *
21358 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21359 {
21360 	ill_t	*ill;
21361 
21362 	*err = 0;
21363 	mutex_enter(&connp->conn_lock);
21364 	ill = *illp;
21365 	if (ill != NULL) {
21366 		mutex_enter(&ill->ill_lock);
21367 		if (ILL_CAN_LOOKUP(ill)) {
21368 			ill_refhold_locked(ill);
21369 			mutex_exit(&ill->ill_lock);
21370 			mutex_exit(&connp->conn_lock);
21371 			return (ill);
21372 		} else {
21373 			*err = ILL_LOOKUP_FAILED;
21374 		}
21375 		mutex_exit(&ill->ill_lock);
21376 	}
21377 	mutex_exit(&connp->conn_lock);
21378 	return (NULL);
21379 }
21380 
21381 static int
21382 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21383 {
21384 	ill_t	*ill;
21385 
21386 	ill = ipif->ipif_ill;
21387 	mutex_enter(&connp->conn_lock);
21388 	mutex_enter(&ill->ill_lock);
21389 	if (IPIF_CAN_LOOKUP(ipif)) {
21390 		*ipifp = ipif;
21391 		mutex_exit(&ill->ill_lock);
21392 		mutex_exit(&connp->conn_lock);
21393 		return (0);
21394 	}
21395 	mutex_exit(&ill->ill_lock);
21396 	mutex_exit(&connp->conn_lock);
21397 	return (IPIF_LOOKUP_FAILED);
21398 }
21399 
21400 /*
21401  * This is called if the outbound datagram needs fragmentation.
21402  *
21403  * NOTE : This function does not ire_refrele the ire argument passed in.
21404  */
21405 static void
21406 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21407 {
21408 	ipha_t		*ipha;
21409 	mblk_t		*mp;
21410 	uint32_t	v_hlen_tos_len;
21411 	uint32_t	max_frag;
21412 	uint32_t	frag_flag;
21413 	boolean_t	dont_use;
21414 
21415 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21416 		mp = ipsec_mp->b_cont;
21417 	} else {
21418 		mp = ipsec_mp;
21419 	}
21420 
21421 	ipha = (ipha_t *)mp->b_rptr;
21422 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21423 
21424 #ifdef	_BIG_ENDIAN
21425 #define	V_HLEN	(v_hlen_tos_len >> 24)
21426 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21427 #else
21428 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21429 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21430 #endif
21431 
21432 #ifndef SPEED_BEFORE_SAFETY
21433 	/*
21434 	 * Check that ipha_length is consistent with
21435 	 * the mblk length
21436 	 */
21437 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21438 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21439 		    LENGTH, msgdsize(mp)));
21440 		freemsg(ipsec_mp);
21441 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21442 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21443 		    "packet length mismatch");
21444 		return;
21445 	}
21446 #endif
21447 	/*
21448 	 * Don't use frag_flag if pre-built packet or source
21449 	 * routed or if multicast (since multicast packets do not solicit
21450 	 * ICMP "packet too big" messages). Get the values of
21451 	 * max_frag and frag_flag atomically by acquiring the
21452 	 * ire_lock.
21453 	 */
21454 	mutex_enter(&ire->ire_lock);
21455 	max_frag = ire->ire_max_frag;
21456 	frag_flag = ire->ire_frag_flag;
21457 	mutex_exit(&ire->ire_lock);
21458 
21459 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21460 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21461 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21462 
21463 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21464 	    (dont_use ? 0 : frag_flag), zoneid);
21465 }
21466 
21467 /*
21468  * Used for deciding the MSS size for the upper layer. Thus
21469  * we need to check the outbound policy values in the conn.
21470  */
21471 int
21472 conn_ipsec_length(conn_t *connp)
21473 {
21474 	ipsec_latch_t *ipl;
21475 
21476 	ipl = connp->conn_latch;
21477 	if (ipl == NULL)
21478 		return (0);
21479 
21480 	if (ipl->ipl_out_policy == NULL)
21481 		return (0);
21482 
21483 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21484 }
21485 
21486 /*
21487  * Returns an estimate of the IPSEC headers size. This is used if
21488  * we don't want to call into IPSEC to get the exact size.
21489  */
21490 int
21491 ipsec_out_extra_length(mblk_t *ipsec_mp)
21492 {
21493 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21494 	ipsec_action_t *a;
21495 
21496 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21497 	if (!io->ipsec_out_secure)
21498 		return (0);
21499 
21500 	a = io->ipsec_out_act;
21501 
21502 	if (a == NULL) {
21503 		ASSERT(io->ipsec_out_policy != NULL);
21504 		a = io->ipsec_out_policy->ipsp_act;
21505 	}
21506 	ASSERT(a != NULL);
21507 
21508 	return (a->ipa_ovhd);
21509 }
21510 
21511 /*
21512  * Returns an estimate of the IPSEC headers size. This is used if
21513  * we don't want to call into IPSEC to get the exact size.
21514  */
21515 int
21516 ipsec_in_extra_length(mblk_t *ipsec_mp)
21517 {
21518 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21519 	ipsec_action_t *a;
21520 
21521 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21522 
21523 	a = ii->ipsec_in_action;
21524 	return (a == NULL ? 0 : a->ipa_ovhd);
21525 }
21526 
21527 /*
21528  * If there are any source route options, return the true final
21529  * destination. Otherwise, return the destination.
21530  */
21531 ipaddr_t
21532 ip_get_dst(ipha_t *ipha)
21533 {
21534 	ipoptp_t	opts;
21535 	uchar_t		*opt;
21536 	uint8_t		optval;
21537 	uint8_t		optlen;
21538 	ipaddr_t	dst;
21539 	uint32_t off;
21540 
21541 	dst = ipha->ipha_dst;
21542 
21543 	if (IS_SIMPLE_IPH(ipha))
21544 		return (dst);
21545 
21546 	for (optval = ipoptp_first(&opts, ipha);
21547 	    optval != IPOPT_EOL;
21548 	    optval = ipoptp_next(&opts)) {
21549 		opt = opts.ipoptp_cur;
21550 		optlen = opts.ipoptp_len;
21551 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21552 		switch (optval) {
21553 		case IPOPT_SSRR:
21554 		case IPOPT_LSRR:
21555 			off = opt[IPOPT_OFFSET];
21556 			/*
21557 			 * If one of the conditions is true, it means
21558 			 * end of options and dst already has the right
21559 			 * value.
21560 			 */
21561 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21562 				off = optlen - IP_ADDR_LEN;
21563 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21564 			}
21565 			return (dst);
21566 		default:
21567 			break;
21568 		}
21569 	}
21570 
21571 	return (dst);
21572 }
21573 
21574 mblk_t *
21575 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21576     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21577 {
21578 	ipsec_out_t	*io;
21579 	mblk_t		*first_mp;
21580 	boolean_t policy_present;
21581 
21582 	first_mp = mp;
21583 	if (mp->b_datap->db_type == M_CTL) {
21584 		io = (ipsec_out_t *)first_mp->b_rptr;
21585 		/*
21586 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21587 		 *
21588 		 * 1) There is per-socket policy (including cached global
21589 		 *    policy) or a policy on the IP-in-IP tunnel.
21590 		 * 2) There is no per-socket policy, but it is
21591 		 *    a multicast packet that needs to go out
21592 		 *    on a specific interface. This is the case
21593 		 *    where (ip_wput and ip_wput_multicast) attaches
21594 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21595 		 *
21596 		 * In case (2) we check with global policy to
21597 		 * see if there is a match and set the ill_index
21598 		 * appropriately so that we can lookup the ire
21599 		 * properly in ip_wput_ipsec_out.
21600 		 */
21601 
21602 		/*
21603 		 * ipsec_out_use_global_policy is set to B_FALSE
21604 		 * in ipsec_in_to_out(). Refer to that function for
21605 		 * details.
21606 		 */
21607 		if ((io->ipsec_out_latch == NULL) &&
21608 		    (io->ipsec_out_use_global_policy)) {
21609 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21610 				    ire, connp, unspec_src, zoneid));
21611 		}
21612 		if (!io->ipsec_out_secure) {
21613 			/*
21614 			 * If this is not a secure packet, drop
21615 			 * the IPSEC_OUT mp and treat it as a clear
21616 			 * packet. This happens when we are sending
21617 			 * a ICMP reply back to a clear packet. See
21618 			 * ipsec_in_to_out() for details.
21619 			 */
21620 			mp = first_mp->b_cont;
21621 			freeb(first_mp);
21622 		}
21623 		return (mp);
21624 	}
21625 	/*
21626 	 * See whether we need to attach a global policy here. We
21627 	 * don't depend on the conn (as it could be null) for deciding
21628 	 * what policy this datagram should go through because it
21629 	 * should have happened in ip_wput if there was some
21630 	 * policy. This normally happens for connections which are not
21631 	 * fully bound preventing us from caching policies in
21632 	 * ip_bind. Packets coming from the TCP listener/global queue
21633 	 * - which are non-hard_bound - could also be affected by
21634 	 * applying policy here.
21635 	 *
21636 	 * If this packet is coming from tcp global queue or listener,
21637 	 * we will be applying policy here.  This may not be *right*
21638 	 * if these packets are coming from the detached connection as
21639 	 * it could have gone in clear before. This happens only if a
21640 	 * TCP connection started when there is no policy and somebody
21641 	 * added policy before it became detached. Thus packets of the
21642 	 * detached connection could go out secure and the other end
21643 	 * would drop it because it will be expecting in clear. The
21644 	 * converse is not true i.e if somebody starts a TCP
21645 	 * connection and deletes the policy, all the packets will
21646 	 * still go out with the policy that existed before deleting
21647 	 * because ip_unbind sends up policy information which is used
21648 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21649 	 * TCP to attach a dummy IPSEC_OUT and set
21650 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21651 	 * affect performance for normal cases, we are not doing it.
21652 	 * Thus, set policy before starting any TCP connections.
21653 	 *
21654 	 * NOTE - We might apply policy even for a hard bound connection
21655 	 * - for which we cached policy in ip_bind - if somebody added
21656 	 * global policy after we inherited the policy in ip_bind.
21657 	 * This means that the packets that were going out in clear
21658 	 * previously would start going secure and hence get dropped
21659 	 * on the other side. To fix this, TCP attaches a dummy
21660 	 * ipsec_out and make sure that we don't apply global policy.
21661 	 */
21662 	if (ipha != NULL)
21663 		policy_present = ipsec_outbound_v4_policy_present;
21664 	else
21665 		policy_present = ipsec_outbound_v6_policy_present;
21666 	if (!policy_present)
21667 		return (mp);
21668 
21669 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21670 		    zoneid));
21671 }
21672 
21673 ire_t *
21674 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21675 {
21676 	ipaddr_t addr;
21677 	ire_t *save_ire;
21678 	irb_t *irb;
21679 	ill_group_t *illgrp;
21680 	int	err;
21681 
21682 	save_ire = ire;
21683 	addr = ire->ire_addr;
21684 
21685 	ASSERT(ire->ire_type == IRE_BROADCAST);
21686 
21687 	illgrp = connp->conn_outgoing_ill->ill_group;
21688 	if (illgrp == NULL) {
21689 		*conn_outgoing_ill = conn_get_held_ill(connp,
21690 		    &connp->conn_outgoing_ill, &err);
21691 		if (err == ILL_LOOKUP_FAILED) {
21692 			ire_refrele(save_ire);
21693 			return (NULL);
21694 		}
21695 		return (save_ire);
21696 	}
21697 	/*
21698 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21699 	 * If it is part of the group, we need to send on the ire
21700 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21701 	 * to this group. This is okay as IP_BOUND_IF really means
21702 	 * any ill in the group. We depend on the fact that the
21703 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21704 	 * if such an ire exists. This is possible only if you have
21705 	 * at least one ill in the group that has not failed.
21706 	 *
21707 	 * First get to the ire that matches the address and group.
21708 	 *
21709 	 * We don't look for an ire with a matching zoneid because a given zone
21710 	 * won't always have broadcast ires on all ills in the group.
21711 	 */
21712 	irb = ire->ire_bucket;
21713 	rw_enter(&irb->irb_lock, RW_READER);
21714 	if (ire->ire_marks & IRE_MARK_NORECV) {
21715 		/*
21716 		 * If the current zone only has an ire broadcast for this
21717 		 * address marked NORECV, the ire we want is ahead in the
21718 		 * bucket, so we look it up deliberately ignoring the zoneid.
21719 		 */
21720 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21721 			if (ire->ire_addr != addr)
21722 				continue;
21723 			/* skip over deleted ires */
21724 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21725 				continue;
21726 		}
21727 	}
21728 	while (ire != NULL) {
21729 		/*
21730 		 * If a new interface is coming up, we could end up
21731 		 * seeing the loopback ire and the non-loopback ire
21732 		 * may not have been added yet. So check for ire_stq
21733 		 */
21734 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21735 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21736 			break;
21737 		}
21738 		ire = ire->ire_next;
21739 	}
21740 	if (ire != NULL && ire->ire_addr == addr &&
21741 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21742 		IRE_REFHOLD(ire);
21743 		rw_exit(&irb->irb_lock);
21744 		ire_refrele(save_ire);
21745 		*conn_outgoing_ill = ire_to_ill(ire);
21746 		/*
21747 		 * Refhold the ill to make the conn_outgoing_ill
21748 		 * independent of the ire. ip_wput_ire goes in a loop
21749 		 * and may refrele the ire. Since we have an ire at this
21750 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21751 		 */
21752 		ill_refhold(*conn_outgoing_ill);
21753 		return (ire);
21754 	}
21755 	rw_exit(&irb->irb_lock);
21756 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21757 	/*
21758 	 * If we can't find a suitable ire, return the original ire.
21759 	 */
21760 	return (save_ire);
21761 }
21762 
21763 /*
21764  * This function does the ire_refrele of the ire passed in as the
21765  * argument. As this function looks up more ires i.e broadcast ires,
21766  * it needs to REFRELE them. Currently, for simplicity we don't
21767  * differentiate the one passed in and looked up here. We always
21768  * REFRELE.
21769  * IPQoS Notes:
21770  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21771  * IPSec packets are done in ipsec_out_process.
21772  *
21773  */
21774 void
21775 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21776     zoneid_t zoneid)
21777 {
21778 	ipha_t		*ipha;
21779 #define	rptr	((uchar_t *)ipha)
21780 	queue_t		*stq;
21781 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21782 	uint32_t	v_hlen_tos_len;
21783 	uint32_t	ttl_protocol;
21784 	ipaddr_t	src;
21785 	ipaddr_t	dst;
21786 	uint32_t	cksum;
21787 	ipaddr_t	orig_src;
21788 	ire_t		*ire1;
21789 	mblk_t		*next_mp;
21790 	uint_t		hlen;
21791 	uint16_t	*up;
21792 	uint32_t	max_frag = ire->ire_max_frag;
21793 	ill_t		*ill = ire_to_ill(ire);
21794 	int		clusterwide;
21795 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21796 	int		ipsec_len;
21797 	mblk_t		*first_mp;
21798 	ipsec_out_t	*io;
21799 	boolean_t	conn_dontroute;		/* conn value for multicast */
21800 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21801 	boolean_t	multicast_forward;	/* Should we forward ? */
21802 	boolean_t	unspec_src;
21803 	ill_t		*conn_outgoing_ill = NULL;
21804 	ill_t		*ire_ill;
21805 	ill_t		*ire1_ill;
21806 	ill_t		*out_ill;
21807 	uint32_t 	ill_index = 0;
21808 	boolean_t	multirt_send = B_FALSE;
21809 	int		err;
21810 	ipxmit_state_t	pktxmit_state;
21811 
21812 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21813 	    "ip_wput_ire_start: q %p", q);
21814 
21815 	multicast_forward = B_FALSE;
21816 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21817 
21818 	if (ire->ire_flags & RTF_MULTIRT) {
21819 		/*
21820 		 * Multirouting case. The bucket where ire is stored
21821 		 * probably holds other RTF_MULTIRT flagged ire
21822 		 * to the destination. In this call to ip_wput_ire,
21823 		 * we attempt to send the packet through all
21824 		 * those ires. Thus, we first ensure that ire is the
21825 		 * first RTF_MULTIRT ire in the bucket,
21826 		 * before walking the ire list.
21827 		 */
21828 		ire_t *first_ire;
21829 		irb_t *irb = ire->ire_bucket;
21830 		ASSERT(irb != NULL);
21831 
21832 		/* Make sure we do not omit any multiroute ire. */
21833 		IRB_REFHOLD(irb);
21834 		for (first_ire = irb->irb_ire;
21835 		    first_ire != NULL;
21836 		    first_ire = first_ire->ire_next) {
21837 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21838 			    (first_ire->ire_addr == ire->ire_addr) &&
21839 			    !(first_ire->ire_marks &
21840 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21841 				break;
21842 		}
21843 
21844 		if ((first_ire != NULL) && (first_ire != ire)) {
21845 			IRE_REFHOLD(first_ire);
21846 			ire_refrele(ire);
21847 			ire = first_ire;
21848 			ill = ire_to_ill(ire);
21849 		}
21850 		IRB_REFRELE(irb);
21851 	}
21852 
21853 	/*
21854 	 * conn_outgoing_ill is used only in the broadcast loop.
21855 	 * for performance we don't grab the mutexs in the fastpath
21856 	 */
21857 	if ((connp != NULL) &&
21858 	    (connp->conn_xmit_if_ill == NULL) &&
21859 	    (ire->ire_type == IRE_BROADCAST) &&
21860 	    ((connp->conn_nofailover_ill != NULL) ||
21861 	    (connp->conn_outgoing_ill != NULL))) {
21862 		/*
21863 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21864 		 * option. So, see if this endpoint is bound to a
21865 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21866 		 * that if the interface is failed, we will still send
21867 		 * the packet on the same ill which is what we want.
21868 		 */
21869 		conn_outgoing_ill = conn_get_held_ill(connp,
21870 		    &connp->conn_nofailover_ill, &err);
21871 		if (err == ILL_LOOKUP_FAILED) {
21872 			ire_refrele(ire);
21873 			freemsg(mp);
21874 			return;
21875 		}
21876 		if (conn_outgoing_ill == NULL) {
21877 			/*
21878 			 * Choose a good ill in the group to send the
21879 			 * packets on.
21880 			 */
21881 			ire = conn_set_outgoing_ill(connp, ire,
21882 			    &conn_outgoing_ill);
21883 			if (ire == NULL) {
21884 				freemsg(mp);
21885 				return;
21886 			}
21887 		}
21888 	}
21889 
21890 	if (mp->b_datap->db_type != M_CTL) {
21891 		ipha = (ipha_t *)mp->b_rptr;
21892 	} else {
21893 		io = (ipsec_out_t *)mp->b_rptr;
21894 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21895 		ASSERT(zoneid == io->ipsec_out_zoneid);
21896 		ASSERT(zoneid != ALL_ZONES);
21897 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21898 		dst = ipha->ipha_dst;
21899 		/*
21900 		 * For the multicast case, ipsec_out carries conn_dontroute and
21901 		 * conn_multicast_loop as conn may not be available here. We
21902 		 * need this for multicast loopback and forwarding which is done
21903 		 * later in the code.
21904 		 */
21905 		if (CLASSD(dst)) {
21906 			conn_dontroute = io->ipsec_out_dontroute;
21907 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21908 			/*
21909 			 * If conn_dontroute is not set or conn_multicast_loop
21910 			 * is set, we need to do forwarding/loopback. For
21911 			 * datagrams from ip_wput_multicast, conn_dontroute is
21912 			 * set to B_TRUE and conn_multicast_loop is set to
21913 			 * B_FALSE so that we neither do forwarding nor
21914 			 * loopback.
21915 			 */
21916 			if (!conn_dontroute || conn_multicast_loop)
21917 				multicast_forward = B_TRUE;
21918 		}
21919 	}
21920 
21921 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21922 	    ire->ire_zoneid != ALL_ZONES) {
21923 		/*
21924 		 * When a zone sends a packet to another zone, we try to deliver
21925 		 * the packet under the same conditions as if the destination
21926 		 * was a real node on the network. To do so, we look for a
21927 		 * matching route in the forwarding table.
21928 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21929 		 * ip_newroute() does.
21930 		 * Note that IRE_LOCAL are special, since they are used
21931 		 * when the zoneid doesn't match in some cases. This means that
21932 		 * we need to handle ipha_src differently since ire_src_addr
21933 		 * belongs to the receiving zone instead of the sending zone.
21934 		 * When ip_restrict_interzone_loopback is set, then
21935 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21936 		 * for loopback between zones when the logical "Ethernet" would
21937 		 * have looped them back.
21938 		 */
21939 		ire_t *src_ire;
21940 
21941 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21942 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21943 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21944 		if (src_ire != NULL &&
21945 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21946 		    (!ip_restrict_interzone_loopback ||
21947 		    ire_local_same_ill_group(ire, src_ire))) {
21948 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21949 				ipha->ipha_src = src_ire->ire_src_addr;
21950 			ire_refrele(src_ire);
21951 		} else {
21952 			ire_refrele(ire);
21953 			if (conn_outgoing_ill != NULL)
21954 				ill_refrele(conn_outgoing_ill);
21955 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21956 			if (src_ire != NULL) {
21957 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21958 					ire_refrele(src_ire);
21959 					freemsg(mp);
21960 					return;
21961 				}
21962 				ire_refrele(src_ire);
21963 			}
21964 			if (ip_hdr_complete(ipha, zoneid)) {
21965 				/* Failed */
21966 				freemsg(mp);
21967 				return;
21968 			}
21969 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21970 			return;
21971 		}
21972 	}
21973 
21974 	if (mp->b_datap->db_type == M_CTL ||
21975 	    ipsec_outbound_v4_policy_present) {
21976 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21977 		    unspec_src, zoneid);
21978 		if (mp == NULL) {
21979 			ire_refrele(ire);
21980 			if (conn_outgoing_ill != NULL)
21981 				ill_refrele(conn_outgoing_ill);
21982 			return;
21983 		}
21984 	}
21985 
21986 	first_mp = mp;
21987 	ipsec_len = 0;
21988 
21989 	if (first_mp->b_datap->db_type == M_CTL) {
21990 		io = (ipsec_out_t *)first_mp->b_rptr;
21991 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21992 		mp = first_mp->b_cont;
21993 		ipsec_len = ipsec_out_extra_length(first_mp);
21994 		ASSERT(ipsec_len >= 0);
21995 		/* We already picked up the zoneid from the M_CTL above */
21996 		ASSERT(zoneid == io->ipsec_out_zoneid);
21997 		ASSERT(zoneid != ALL_ZONES);
21998 
21999 		/*
22000 		 * Drop M_CTL here if IPsec processing is not needed.
22001 		 * (Non-IPsec use of M_CTL extracted any information it
22002 		 * needed above).
22003 		 */
22004 		if (ipsec_len == 0) {
22005 			freeb(first_mp);
22006 			first_mp = mp;
22007 		}
22008 	}
22009 
22010 	/*
22011 	 * Fast path for ip_wput_ire
22012 	 */
22013 
22014 	ipha = (ipha_t *)mp->b_rptr;
22015 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22016 	dst = ipha->ipha_dst;
22017 
22018 	/*
22019 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22020 	 * if the socket is a SOCK_RAW type. The transport checksum should
22021 	 * be provided in the pre-built packet, so we don't need to compute it.
22022 	 * Also, other application set flags, like DF, should not be altered.
22023 	 * Other transport MUST pass down zero.
22024 	 */
22025 	ip_hdr_included = ipha->ipha_ident;
22026 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22027 
22028 	if (CLASSD(dst)) {
22029 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22030 		    ntohl(dst),
22031 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22032 		    ntohl(ire->ire_addr)));
22033 	}
22034 
22035 /* Macros to extract header fields from data already in registers */
22036 #ifdef	_BIG_ENDIAN
22037 #define	V_HLEN	(v_hlen_tos_len >> 24)
22038 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22039 #define	PROTO	(ttl_protocol & 0xFF)
22040 #else
22041 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22042 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22043 #define	PROTO	(ttl_protocol >> 8)
22044 #endif
22045 
22046 
22047 	orig_src = src = ipha->ipha_src;
22048 	/* (The loop back to "another" is explained down below.) */
22049 another:;
22050 	/*
22051 	 * Assign an ident value for this packet.  We assign idents on
22052 	 * a per destination basis out of the IRE.  There could be
22053 	 * other threads targeting the same destination, so we have to
22054 	 * arrange for a atomic increment.  Note that we use a 32-bit
22055 	 * atomic add because it has better performance than its
22056 	 * 16-bit sibling.
22057 	 *
22058 	 * If running in cluster mode and if the source address
22059 	 * belongs to a replicated service then vector through
22060 	 * cl_inet_ipident vector to allocate ip identifier
22061 	 * NOTE: This is a contract private interface with the
22062 	 * clustering group.
22063 	 */
22064 	clusterwide = 0;
22065 	if (cl_inet_ipident) {
22066 		ASSERT(cl_inet_isclusterwide);
22067 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22068 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22069 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22070 			    AF_INET, (uint8_t *)(uintptr_t)src,
22071 			    (uint8_t *)(uintptr_t)dst);
22072 			clusterwide = 1;
22073 		}
22074 	}
22075 	if (!clusterwide) {
22076 		ipha->ipha_ident =
22077 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22078 	}
22079 
22080 #ifndef _BIG_ENDIAN
22081 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22082 #endif
22083 
22084 	/*
22085 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22086 	 * This is needed to obey conn_unspec_src when packets go through
22087 	 * ip_newroute + arp.
22088 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22089 	 */
22090 	if (src == INADDR_ANY && !unspec_src) {
22091 		/*
22092 		 * Assign the appropriate source address from the IRE if none
22093 		 * was specified.
22094 		 */
22095 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22096 
22097 		/*
22098 		 * With IP multipathing, broadcast packets are sent on the ire
22099 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22100 		 * the group. However, this ire might not be in the same zone so
22101 		 * we can't always use its source address. We look for a
22102 		 * broadcast ire in the same group and in the right zone.
22103 		 */
22104 		if (ire->ire_type == IRE_BROADCAST &&
22105 		    ire->ire_zoneid != zoneid) {
22106 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22107 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22108 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
22109 			if (src_ire != NULL) {
22110 				src = src_ire->ire_src_addr;
22111 				ire_refrele(src_ire);
22112 			} else {
22113 				ire_refrele(ire);
22114 				if (conn_outgoing_ill != NULL)
22115 					ill_refrele(conn_outgoing_ill);
22116 				freemsg(first_mp);
22117 				if (ill != NULL) {
22118 					BUMP_MIB(ill->ill_ip_mib,
22119 					    ipIfStatsOutDiscards);
22120 				} else {
22121 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
22122 				}
22123 				return;
22124 			}
22125 		} else {
22126 			src = ire->ire_src_addr;
22127 		}
22128 
22129 		if (connp == NULL) {
22130 			ip1dbg(("ip_wput_ire: no connp and no src "
22131 			    "address for dst 0x%x, using src 0x%x\n",
22132 			    ntohl(dst),
22133 			    ntohl(src)));
22134 		}
22135 		ipha->ipha_src = src;
22136 	}
22137 	stq = ire->ire_stq;
22138 
22139 	/*
22140 	 * We only allow ire chains for broadcasts since there will
22141 	 * be multiple IRE_CACHE entries for the same multicast
22142 	 * address (one per ipif).
22143 	 */
22144 	next_mp = NULL;
22145 
22146 	/* broadcast packet */
22147 	if (ire->ire_type == IRE_BROADCAST)
22148 		goto broadcast;
22149 
22150 	/* loopback ? */
22151 	if (stq == NULL)
22152 		goto nullstq;
22153 
22154 	/* The ill_index for outbound ILL */
22155 	ill_index = Q_TO_INDEX(stq);
22156 
22157 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22158 	ttl_protocol = ((uint16_t *)ipha)[4];
22159 
22160 	/* pseudo checksum (do it in parts for IP header checksum) */
22161 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22162 
22163 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22164 		queue_t *dev_q = stq->q_next;
22165 
22166 		/* flow controlled */
22167 		if ((dev_q->q_next || dev_q->q_first) &&
22168 		    !canput(dev_q))
22169 			goto blocked;
22170 		if ((PROTO == IPPROTO_UDP) &&
22171 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22172 			hlen = (V_HLEN & 0xF) << 2;
22173 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22174 			if (*up != 0) {
22175 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22176 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22177 				/* Software checksum? */
22178 				if (DB_CKSUMFLAGS(mp) == 0) {
22179 					IP_STAT(ip_out_sw_cksum);
22180 					IP_STAT_UPDATE(
22181 					    ip_udp_out_sw_cksum_bytes,
22182 					    LENGTH - hlen);
22183 				}
22184 			}
22185 		}
22186 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22187 		hlen = (V_HLEN & 0xF) << 2;
22188 		if (PROTO == IPPROTO_TCP) {
22189 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22190 			/*
22191 			 * The packet header is processed once and for all, even
22192 			 * in the multirouting case. We disable hardware
22193 			 * checksum if the packet is multirouted, as it will be
22194 			 * replicated via several interfaces, and not all of
22195 			 * them may have this capability.
22196 			 */
22197 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22198 			    LENGTH, max_frag, ipsec_len, cksum);
22199 			/* Software checksum? */
22200 			if (DB_CKSUMFLAGS(mp) == 0) {
22201 				IP_STAT(ip_out_sw_cksum);
22202 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22203 				    LENGTH - hlen);
22204 			}
22205 		} else {
22206 			sctp_hdr_t	*sctph;
22207 
22208 			ASSERT(PROTO == IPPROTO_SCTP);
22209 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22210 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22211 			/*
22212 			 * Zero out the checksum field to ensure proper
22213 			 * checksum calculation.
22214 			 */
22215 			sctph->sh_chksum = 0;
22216 #ifdef	DEBUG
22217 			if (!skip_sctp_cksum)
22218 #endif
22219 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22220 		}
22221 	}
22222 
22223 	/*
22224 	 * If this is a multicast packet and originated from ip_wput
22225 	 * we need to do loopback and forwarding checks. If it comes
22226 	 * from ip_wput_multicast, we SHOULD not do this.
22227 	 */
22228 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22229 
22230 	/* checksum */
22231 	cksum += ttl_protocol;
22232 
22233 	/* fragment the packet */
22234 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22235 		goto fragmentit;
22236 	/*
22237 	 * Don't use frag_flag if packet is pre-built or source
22238 	 * routed or if multicast (since multicast packets do
22239 	 * not solicit ICMP "packet too big" messages).
22240 	 */
22241 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22242 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22243 	    !ip_source_route_included(ipha)) &&
22244 	    !CLASSD(ipha->ipha_dst))
22245 		ipha->ipha_fragment_offset_and_flags |=
22246 		    htons(ire->ire_frag_flag);
22247 
22248 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22249 		/* calculate IP header checksum */
22250 		cksum += ipha->ipha_ident;
22251 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22252 		cksum += ipha->ipha_fragment_offset_and_flags;
22253 
22254 		/* IP options present */
22255 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22256 		if (hlen)
22257 			goto checksumoptions;
22258 
22259 		/* calculate hdr checksum */
22260 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22261 		cksum = ~(cksum + (cksum >> 16));
22262 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22263 	}
22264 	if (ipsec_len != 0) {
22265 		/*
22266 		 * We will do the rest of the processing after
22267 		 * we come back from IPSEC in ip_wput_ipsec_out().
22268 		 */
22269 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22270 
22271 		io = (ipsec_out_t *)first_mp->b_rptr;
22272 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22273 				ill_phyint->phyint_ifindex;
22274 
22275 		ipsec_out_process(q, first_mp, ire, ill_index);
22276 		ire_refrele(ire);
22277 		if (conn_outgoing_ill != NULL)
22278 			ill_refrele(conn_outgoing_ill);
22279 		return;
22280 	}
22281 
22282 	/*
22283 	 * In most cases, the emission loop below is entered only
22284 	 * once. Only in the case where the ire holds the
22285 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22286 	 * flagged ires in the bucket, and send the packet
22287 	 * through all crossed RTF_MULTIRT routes.
22288 	 */
22289 	if (ire->ire_flags & RTF_MULTIRT) {
22290 		multirt_send = B_TRUE;
22291 	}
22292 	do {
22293 		if (multirt_send) {
22294 			irb_t *irb;
22295 			/*
22296 			 * We are in a multiple send case, need to get
22297 			 * the next ire and make a duplicate of the packet.
22298 			 * ire1 holds here the next ire to process in the
22299 			 * bucket. If multirouting is expected,
22300 			 * any non-RTF_MULTIRT ire that has the
22301 			 * right destination address is ignored.
22302 			 */
22303 			irb = ire->ire_bucket;
22304 			ASSERT(irb != NULL);
22305 
22306 			IRB_REFHOLD(irb);
22307 			for (ire1 = ire->ire_next;
22308 			    ire1 != NULL;
22309 			    ire1 = ire1->ire_next) {
22310 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22311 					continue;
22312 				if (ire1->ire_addr != ire->ire_addr)
22313 					continue;
22314 				if (ire1->ire_marks &
22315 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22316 					continue;
22317 
22318 				/* Got one */
22319 				IRE_REFHOLD(ire1);
22320 				break;
22321 			}
22322 			IRB_REFRELE(irb);
22323 
22324 			if (ire1 != NULL) {
22325 				next_mp = copyb(mp);
22326 				if ((next_mp == NULL) ||
22327 				    ((mp->b_cont != NULL) &&
22328 				    ((next_mp->b_cont =
22329 				    dupmsg(mp->b_cont)) == NULL))) {
22330 					freemsg(next_mp);
22331 					next_mp = NULL;
22332 					ire_refrele(ire1);
22333 					ire1 = NULL;
22334 				}
22335 			}
22336 
22337 			/* Last multiroute ire; don't loop anymore. */
22338 			if (ire1 == NULL) {
22339 				multirt_send = B_FALSE;
22340 			}
22341 		}
22342 
22343 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22344 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22345 		    mblk_t *, mp);
22346 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
22347 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
22348 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22349 		if (mp == NULL)
22350 			goto release_ire_and_ill;
22351 
22352 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22353 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22354 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22355 		if ((pktxmit_state == SEND_FAILED) ||
22356 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22357 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22358 			    "- packet dropped\n"));
22359 release_ire_and_ill:
22360 			ire_refrele(ire);
22361 			if (next_mp != NULL) {
22362 				freemsg(next_mp);
22363 				ire_refrele(ire1);
22364 			}
22365 			if (conn_outgoing_ill != NULL)
22366 				ill_refrele(conn_outgoing_ill);
22367 			return;
22368 		}
22369 
22370 		if (CLASSD(dst)) {
22371 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22372 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22373 			    ntohs(ipha->ipha_length));
22374 		}
22375 
22376 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22377 		    "ip_wput_ire_end: q %p (%S)",
22378 		    q, "last copy out");
22379 		IRE_REFRELE(ire);
22380 
22381 		if (multirt_send) {
22382 			ASSERT(ire1);
22383 			/*
22384 			 * Proceed with the next RTF_MULTIRT ire,
22385 			 * Also set up the send-to queue accordingly.
22386 			 */
22387 			ire = ire1;
22388 			ire1 = NULL;
22389 			stq = ire->ire_stq;
22390 			mp = next_mp;
22391 			next_mp = NULL;
22392 			ipha = (ipha_t *)mp->b_rptr;
22393 			ill_index = Q_TO_INDEX(stq);
22394 			ill = (ill_t *)stq->q_ptr;
22395 		}
22396 	} while (multirt_send);
22397 	if (conn_outgoing_ill != NULL)
22398 		ill_refrele(conn_outgoing_ill);
22399 	return;
22400 
22401 	/*
22402 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22403 	 */
22404 broadcast:
22405 	{
22406 		/*
22407 		 * Avoid broadcast storms by setting the ttl to 1
22408 		 * for broadcasts. This parameter can be set
22409 		 * via ndd, so make sure that for the SO_DONTROUTE
22410 		 * case that ipha_ttl is always set to 1.
22411 		 * In the event that we are replying to incoming
22412 		 * ICMP packets, conn could be NULL.
22413 		 */
22414 		if ((connp != NULL) && connp->conn_dontroute)
22415 			ipha->ipha_ttl = 1;
22416 		else
22417 			ipha->ipha_ttl = ip_broadcast_ttl;
22418 
22419 		/*
22420 		 * Note that we are not doing a IRB_REFHOLD here.
22421 		 * Actually we don't care if the list changes i.e
22422 		 * if somebody deletes an IRE from the list while
22423 		 * we drop the lock, the next time we come around
22424 		 * ire_next will be NULL and hence we won't send
22425 		 * out multiple copies which is fine.
22426 		 */
22427 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22428 		ire1 = ire->ire_next;
22429 		if (conn_outgoing_ill != NULL) {
22430 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22431 				ASSERT(ire1 == ire->ire_next);
22432 				if (ire1 != NULL && ire1->ire_addr == dst) {
22433 					ire_refrele(ire);
22434 					ire = ire1;
22435 					IRE_REFHOLD(ire);
22436 					ire1 = ire->ire_next;
22437 					continue;
22438 				}
22439 				rw_exit(&ire->ire_bucket->irb_lock);
22440 				/* Did not find a matching ill */
22441 				ip1dbg(("ip_wput_ire: broadcast with no "
22442 				    "matching IP_BOUND_IF ill %s\n",
22443 				    conn_outgoing_ill->ill_name));
22444 				freemsg(first_mp);
22445 				if (ire != NULL)
22446 					ire_refrele(ire);
22447 				ill_refrele(conn_outgoing_ill);
22448 				return;
22449 			}
22450 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22451 			/*
22452 			 * If the next IRE has the same address and is not one
22453 			 * of the two copies that we need to send, try to see
22454 			 * whether this copy should be sent at all. This
22455 			 * assumes that we insert loopbacks first and then
22456 			 * non-loopbacks. This is acheived by inserting the
22457 			 * loopback always before non-loopback.
22458 			 * This is used to send a single copy of a broadcast
22459 			 * packet out all physical interfaces that have an
22460 			 * matching IRE_BROADCAST while also looping
22461 			 * back one copy (to ip_wput_local) for each
22462 			 * matching physical interface. However, we avoid
22463 			 * sending packets out different logical that match by
22464 			 * having ipif_up/ipif_down supress duplicate
22465 			 * IRE_BROADCASTS.
22466 			 *
22467 			 * This feature is currently used to get broadcasts
22468 			 * sent to multiple interfaces, when the broadcast
22469 			 * address being used applies to multiple interfaces.
22470 			 * For example, a whole net broadcast will be
22471 			 * replicated on every connected subnet of
22472 			 * the target net.
22473 			 *
22474 			 * Each zone has its own set of IRE_BROADCASTs, so that
22475 			 * we're able to distribute inbound packets to multiple
22476 			 * zones who share a broadcast address. We avoid looping
22477 			 * back outbound packets in different zones but on the
22478 			 * same ill, as the application would see duplicates.
22479 			 *
22480 			 * If the interfaces are part of the same group,
22481 			 * we would want to send only one copy out for
22482 			 * whole group.
22483 			 *
22484 			 * This logic assumes that ire_add_v4() groups the
22485 			 * IRE_BROADCAST entries so that those with the same
22486 			 * ire_addr and ill_group are kept together.
22487 			 */
22488 			ire_ill = ire->ire_ipif->ipif_ill;
22489 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22490 				if (ire_ill->ill_group != NULL &&
22491 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22492 					/*
22493 					 * If the current zone only has an ire
22494 					 * broadcast for this address marked
22495 					 * NORECV, the ire we want is ahead in
22496 					 * the bucket, so we look it up
22497 					 * deliberately ignoring the zoneid.
22498 					 */
22499 					for (ire1 = ire->ire_bucket->irb_ire;
22500 					    ire1 != NULL;
22501 					    ire1 = ire1->ire_next) {
22502 						ire1_ill =
22503 						    ire1->ire_ipif->ipif_ill;
22504 						if (ire1->ire_addr != dst)
22505 							continue;
22506 						/* skip over the current ire */
22507 						if (ire1 == ire)
22508 							continue;
22509 						/* skip over deleted ires */
22510 						if (ire1->ire_marks &
22511 						    IRE_MARK_CONDEMNED)
22512 							continue;
22513 						/*
22514 						 * non-loopback ire in our
22515 						 * group: use it for the next
22516 						 * pass in the loop
22517 						 */
22518 						if (ire1->ire_stq != NULL &&
22519 						    ire1_ill->ill_group ==
22520 						    ire_ill->ill_group)
22521 							break;
22522 					}
22523 				}
22524 			} else {
22525 				while (ire1 != NULL && ire1->ire_addr == dst) {
22526 					ire1_ill = ire1->ire_ipif->ipif_ill;
22527 					/*
22528 					 * We can have two broadcast ires on the
22529 					 * same ill in different zones; here
22530 					 * we'll send a copy of the packet on
22531 					 * each ill and the fanout code will
22532 					 * call conn_wantpacket() to check that
22533 					 * the zone has the broadcast address
22534 					 * configured on the ill. If the two
22535 					 * ires are in the same group we only
22536 					 * send one copy up.
22537 					 */
22538 					if (ire1_ill != ire_ill &&
22539 					    (ire1_ill->ill_group == NULL ||
22540 					    ire_ill->ill_group == NULL ||
22541 					    ire1_ill->ill_group !=
22542 					    ire_ill->ill_group)) {
22543 						break;
22544 					}
22545 					ire1 = ire1->ire_next;
22546 				}
22547 			}
22548 		}
22549 		ASSERT(multirt_send == B_FALSE);
22550 		if (ire1 != NULL && ire1->ire_addr == dst) {
22551 			if ((ire->ire_flags & RTF_MULTIRT) &&
22552 			    (ire1->ire_flags & RTF_MULTIRT)) {
22553 				/*
22554 				 * We are in the multirouting case.
22555 				 * The message must be sent at least
22556 				 * on both ires. These ires have been
22557 				 * inserted AFTER the standard ones
22558 				 * in ip_rt_add(). There are thus no
22559 				 * other ire entries for the destination
22560 				 * address in the rest of the bucket
22561 				 * that do not have the RTF_MULTIRT
22562 				 * flag. We don't process a copy
22563 				 * of the message here. This will be
22564 				 * done in the final sending loop.
22565 				 */
22566 				multirt_send = B_TRUE;
22567 			} else {
22568 				next_mp = ip_copymsg(first_mp);
22569 				if (next_mp != NULL)
22570 					IRE_REFHOLD(ire1);
22571 			}
22572 		}
22573 		rw_exit(&ire->ire_bucket->irb_lock);
22574 	}
22575 
22576 	if (stq) {
22577 		/*
22578 		 * A non-NULL send-to queue means this packet is going
22579 		 * out of this machine.
22580 		 */
22581 		out_ill = (ill_t *)stq->q_ptr;
22582 
22583 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22584 		ttl_protocol = ((uint16_t *)ipha)[4];
22585 		/*
22586 		 * We accumulate the pseudo header checksum in cksum.
22587 		 * This is pretty hairy code, so watch close.  One
22588 		 * thing to keep in mind is that UDP and TCP have
22589 		 * stored their respective datagram lengths in their
22590 		 * checksum fields.  This lines things up real nice.
22591 		 */
22592 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22593 		    (src >> 16) + (src & 0xFFFF);
22594 		/*
22595 		 * We assume the udp checksum field contains the
22596 		 * length, so to compute the pseudo header checksum,
22597 		 * all we need is the protocol number and src/dst.
22598 		 */
22599 		/* Provide the checksums for UDP and TCP. */
22600 		if ((PROTO == IPPROTO_TCP) &&
22601 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22602 			/* hlen gets the number of uchar_ts in the IP header */
22603 			hlen = (V_HLEN & 0xF) << 2;
22604 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22605 			IP_STAT(ip_out_sw_cksum);
22606 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22607 			    LENGTH - hlen);
22608 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22609 			if (*up == 0)
22610 				*up = 0xFFFF;
22611 		} else if (PROTO == IPPROTO_SCTP &&
22612 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22613 			sctp_hdr_t	*sctph;
22614 
22615 			hlen = (V_HLEN & 0xF) << 2;
22616 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22617 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22618 			sctph->sh_chksum = 0;
22619 #ifdef	DEBUG
22620 			if (!skip_sctp_cksum)
22621 #endif
22622 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22623 		} else {
22624 			queue_t *dev_q = stq->q_next;
22625 
22626 			if ((dev_q->q_next || dev_q->q_first) &&
22627 			    !canput(dev_q)) {
22628 			    blocked:
22629 				ipha->ipha_ident = ip_hdr_included;
22630 				/*
22631 				 * If we don't have a conn to apply
22632 				 * backpressure, free the message.
22633 				 * In the ire_send path, we don't know
22634 				 * the position to requeue the packet. Rather
22635 				 * than reorder packets, we just drop this
22636 				 * packet.
22637 				 */
22638 				if (ip_output_queue && connp != NULL &&
22639 				    caller != IRE_SEND) {
22640 					if (caller == IP_WSRV) {
22641 						connp->conn_did_putbq = 1;
22642 						(void) putbq(connp->conn_wq,
22643 						    first_mp);
22644 						conn_drain_insert(connp);
22645 						/*
22646 						 * This is the service thread,
22647 						 * and the queue is already
22648 						 * noenabled. The check for
22649 						 * canput and the putbq is not
22650 						 * atomic. So we need to check
22651 						 * again.
22652 						 */
22653 						if (canput(stq->q_next))
22654 							connp->conn_did_putbq
22655 							    = 0;
22656 						IP_STAT(ip_conn_flputbq);
22657 					} else {
22658 						/*
22659 						 * We are not the service proc.
22660 						 * ip_wsrv will be scheduled or
22661 						 * is already running.
22662 						 */
22663 						(void) putq(connp->conn_wq,
22664 						    first_mp);
22665 					}
22666 				} else {
22667 					out_ill = (ill_t *)stq->q_ptr;
22668 					BUMP_MIB(out_ill->ill_ip_mib,
22669 					    ipIfStatsOutDiscards);
22670 					freemsg(first_mp);
22671 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22672 					    "ip_wput_ire_end: q %p (%S)",
22673 					    q, "discard");
22674 				}
22675 				ire_refrele(ire);
22676 				if (next_mp) {
22677 					ire_refrele(ire1);
22678 					freemsg(next_mp);
22679 				}
22680 				if (conn_outgoing_ill != NULL)
22681 					ill_refrele(conn_outgoing_ill);
22682 				return;
22683 			}
22684 			if ((PROTO == IPPROTO_UDP) &&
22685 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22686 				/*
22687 				 * hlen gets the number of uchar_ts in the
22688 				 * IP header
22689 				 */
22690 				hlen = (V_HLEN & 0xF) << 2;
22691 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22692 				max_frag = ire->ire_max_frag;
22693 				if (*up != 0) {
22694 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22695 					    up, PROTO, hlen, LENGTH, max_frag,
22696 					    ipsec_len, cksum);
22697 					/* Software checksum? */
22698 					if (DB_CKSUMFLAGS(mp) == 0) {
22699 						IP_STAT(ip_out_sw_cksum);
22700 						IP_STAT_UPDATE(
22701 						    ip_udp_out_sw_cksum_bytes,
22702 						    LENGTH - hlen);
22703 					}
22704 				}
22705 			}
22706 		}
22707 		/*
22708 		 * Need to do this even when fragmenting. The local
22709 		 * loopback can be done without computing checksums
22710 		 * but forwarding out other interface must be done
22711 		 * after the IP checksum (and ULP checksums) have been
22712 		 * computed.
22713 		 *
22714 		 * NOTE : multicast_forward is set only if this packet
22715 		 * originated from ip_wput. For packets originating from
22716 		 * ip_wput_multicast, it is not set.
22717 		 */
22718 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22719 		    multi_loopback:
22720 			ip2dbg(("ip_wput: multicast, loop %d\n",
22721 			    conn_multicast_loop));
22722 
22723 			/*  Forget header checksum offload */
22724 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22725 
22726 			/*
22727 			 * Local loopback of multicasts?  Check the
22728 			 * ill.
22729 			 *
22730 			 * Note that the loopback function will not come
22731 			 * in through ip_rput - it will only do the
22732 			 * client fanout thus we need to do an mforward
22733 			 * as well.  The is different from the BSD
22734 			 * logic.
22735 			 */
22736 			if (ill != NULL) {
22737 				ilm_t	*ilm;
22738 
22739 				ILM_WALKER_HOLD(ill);
22740 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22741 				    ALL_ZONES);
22742 				ILM_WALKER_RELE(ill);
22743 				if (ilm != NULL) {
22744 					/*
22745 					 * Pass along the virtual output q.
22746 					 * ip_wput_local() will distribute the
22747 					 * packet to all the matching zones,
22748 					 * except the sending zone when
22749 					 * IP_MULTICAST_LOOP is false.
22750 					 */
22751 					ip_multicast_loopback(q, ill, first_mp,
22752 					    conn_multicast_loop ? 0 :
22753 					    IP_FF_NO_MCAST_LOOP, zoneid);
22754 				}
22755 			}
22756 			if (ipha->ipha_ttl == 0) {
22757 				/*
22758 				 * 0 => only to this host i.e. we are
22759 				 * done. We are also done if this was the
22760 				 * loopback interface since it is sufficient
22761 				 * to loopback one copy of a multicast packet.
22762 				 */
22763 				freemsg(first_mp);
22764 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22765 				    "ip_wput_ire_end: q %p (%S)",
22766 				    q, "loopback");
22767 				ire_refrele(ire);
22768 				if (conn_outgoing_ill != NULL)
22769 					ill_refrele(conn_outgoing_ill);
22770 				return;
22771 			}
22772 			/*
22773 			 * ILLF_MULTICAST is checked in ip_newroute
22774 			 * i.e. we don't need to check it here since
22775 			 * all IRE_CACHEs come from ip_newroute.
22776 			 * For multicast traffic, SO_DONTROUTE is interpreted
22777 			 * to mean only send the packet out the interface
22778 			 * (optionally specified with IP_MULTICAST_IF)
22779 			 * and do not forward it out additional interfaces.
22780 			 * RSVP and the rsvp daemon is an example of a
22781 			 * protocol and user level process that
22782 			 * handles it's own routing. Hence, it uses the
22783 			 * SO_DONTROUTE option to accomplish this.
22784 			 */
22785 
22786 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22787 				/* Unconditionally redo the checksum */
22788 				ipha->ipha_hdr_checksum = 0;
22789 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22790 
22791 				/*
22792 				 * If this needs to go out secure, we need
22793 				 * to wait till we finish the IPSEC
22794 				 * processing.
22795 				 */
22796 				if (ipsec_len == 0 &&
22797 				    ip_mforward(ill, ipha, mp)) {
22798 					freemsg(first_mp);
22799 					ip1dbg(("ip_wput: mforward failed\n"));
22800 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22801 					    "ip_wput_ire_end: q %p (%S)",
22802 					    q, "mforward failed");
22803 					ire_refrele(ire);
22804 					if (conn_outgoing_ill != NULL)
22805 						ill_refrele(conn_outgoing_ill);
22806 					return;
22807 				}
22808 			}
22809 		}
22810 		max_frag = ire->ire_max_frag;
22811 		cksum += ttl_protocol;
22812 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22813 			/* No fragmentation required for this one. */
22814 			/*
22815 			 * Don't use frag_flag if packet is pre-built or source
22816 			 * routed or if multicast (since multicast packets do
22817 			 * not solicit ICMP "packet too big" messages).
22818 			 */
22819 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22820 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22821 			    !ip_source_route_included(ipha)) &&
22822 			    !CLASSD(ipha->ipha_dst))
22823 				ipha->ipha_fragment_offset_and_flags |=
22824 				    htons(ire->ire_frag_flag);
22825 
22826 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22827 				/* Complete the IP header checksum. */
22828 				cksum += ipha->ipha_ident;
22829 				cksum += (v_hlen_tos_len >> 16)+
22830 				    (v_hlen_tos_len & 0xFFFF);
22831 				cksum += ipha->ipha_fragment_offset_and_flags;
22832 				hlen = (V_HLEN & 0xF) -
22833 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22834 				if (hlen) {
22835 				    checksumoptions:
22836 					/*
22837 					 * Account for the IP Options in the IP
22838 					 * header checksum.
22839 					 */
22840 					up = (uint16_t *)(rptr+
22841 					    IP_SIMPLE_HDR_LENGTH);
22842 					do {
22843 						cksum += up[0];
22844 						cksum += up[1];
22845 						up += 2;
22846 					} while (--hlen);
22847 				}
22848 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22849 				cksum = ~(cksum + (cksum >> 16));
22850 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22851 			}
22852 			if (ipsec_len != 0) {
22853 				ipsec_out_process(q, first_mp, ire, ill_index);
22854 				if (!next_mp) {
22855 					ire_refrele(ire);
22856 					if (conn_outgoing_ill != NULL)
22857 						ill_refrele(conn_outgoing_ill);
22858 					return;
22859 				}
22860 				goto next;
22861 			}
22862 
22863 			/*
22864 			 * multirt_send has already been handled
22865 			 * for broadcast, but not yet for multicast
22866 			 * or IP options.
22867 			 */
22868 			if (next_mp == NULL) {
22869 				if (ire->ire_flags & RTF_MULTIRT) {
22870 					multirt_send = B_TRUE;
22871 				}
22872 			}
22873 
22874 			/*
22875 			 * In most cases, the emission loop below is
22876 			 * entered only once. Only in the case where
22877 			 * the ire holds the RTF_MULTIRT flag, do we loop
22878 			 * to process all RTF_MULTIRT ires in the bucket,
22879 			 * and send the packet through all crossed
22880 			 * RTF_MULTIRT routes.
22881 			 */
22882 			do {
22883 				if (multirt_send) {
22884 					irb_t *irb;
22885 
22886 					irb = ire->ire_bucket;
22887 					ASSERT(irb != NULL);
22888 					/*
22889 					 * We are in a multiple send case,
22890 					 * need to get the next IRE and make
22891 					 * a duplicate of the packet.
22892 					 */
22893 					IRB_REFHOLD(irb);
22894 					for (ire1 = ire->ire_next;
22895 					    ire1 != NULL;
22896 					    ire1 = ire1->ire_next) {
22897 						if (!(ire1->ire_flags &
22898 						    RTF_MULTIRT))
22899 							continue;
22900 						if (ire1->ire_addr !=
22901 						    ire->ire_addr)
22902 							continue;
22903 						if (ire1->ire_marks &
22904 						    (IRE_MARK_CONDEMNED|
22905 							IRE_MARK_HIDDEN))
22906 							continue;
22907 
22908 						/* Got one */
22909 						IRE_REFHOLD(ire1);
22910 						break;
22911 					}
22912 					IRB_REFRELE(irb);
22913 
22914 					if (ire1 != NULL) {
22915 						next_mp = copyb(mp);
22916 						if ((next_mp == NULL) ||
22917 						    ((mp->b_cont != NULL) &&
22918 						    ((next_mp->b_cont =
22919 						    dupmsg(mp->b_cont))
22920 						    == NULL))) {
22921 							freemsg(next_mp);
22922 							next_mp = NULL;
22923 							ire_refrele(ire1);
22924 							ire1 = NULL;
22925 						}
22926 					}
22927 
22928 					/*
22929 					 * Last multiroute ire; don't loop
22930 					 * anymore. The emission is over
22931 					 * and next_mp is NULL.
22932 					 */
22933 					if (ire1 == NULL) {
22934 						multirt_send = B_FALSE;
22935 					}
22936 				}
22937 
22938 				out_ill = ire->ire_ipif->ipif_ill;
22939 				DTRACE_PROBE4(ip4__physical__out__start,
22940 				    ill_t *, NULL,
22941 				    ill_t *, out_ill,
22942 				    ipha_t *, ipha, mblk_t *, mp);
22943 				FW_HOOKS(ip4_physical_out_event,
22944 				    ipv4firewall_physical_out,
22945 				    NULL, out_ill, ipha, mp, mp);
22946 				DTRACE_PROBE1(ip4__physical__out__end,
22947 				    mblk_t *, mp);
22948 				if (mp == NULL)
22949 					goto release_ire_and_ill_2;
22950 
22951 				ASSERT(ipsec_len == 0);
22952 				mp->b_prev =
22953 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22954 				DTRACE_PROBE2(ip__xmit__2,
22955 				    mblk_t *, mp, ire_t *, ire);
22956 				pktxmit_state = ip_xmit_v4(mp, ire,
22957 				    NULL, B_TRUE);
22958 				if ((pktxmit_state == SEND_FAILED) ||
22959 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22960 release_ire_and_ill_2:
22961 					if (next_mp) {
22962 						freemsg(next_mp);
22963 						ire_refrele(ire1);
22964 					}
22965 					ire_refrele(ire);
22966 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22967 					    "ip_wput_ire_end: q %p (%S)",
22968 					    q, "discard MDATA");
22969 					if (conn_outgoing_ill != NULL)
22970 						ill_refrele(conn_outgoing_ill);
22971 					return;
22972 				}
22973 
22974 				if (CLASSD(dst)) {
22975 					BUMP_MIB(out_ill->ill_ip_mib,
22976 					    ipIfStatsHCOutMcastPkts);
22977 					UPDATE_MIB(out_ill->ill_ip_mib,
22978 					    ipIfStatsHCOutMcastOctets,
22979 					    ntohs(ipha->ipha_length));
22980 				} else if (ire->ire_type == IRE_BROADCAST) {
22981 					BUMP_MIB(out_ill->ill_ip_mib,
22982 					    ipIfStatsHCOutBcastPkts);
22983 				}
22984 
22985 				if (multirt_send) {
22986 					/*
22987 					 * We are in a multiple send case,
22988 					 * need to re-enter the sending loop
22989 					 * using the next ire.
22990 					 */
22991 					ire_refrele(ire);
22992 					ire = ire1;
22993 					stq = ire->ire_stq;
22994 					mp = next_mp;
22995 					next_mp = NULL;
22996 					ipha = (ipha_t *)mp->b_rptr;
22997 					ill_index = Q_TO_INDEX(stq);
22998 				}
22999 			} while (multirt_send);
23000 
23001 			if (!next_mp) {
23002 				/*
23003 				 * Last copy going out (the ultra-common
23004 				 * case).  Note that we intentionally replicate
23005 				 * the putnext rather than calling it before
23006 				 * the next_mp check in hopes of a little
23007 				 * tail-call action out of the compiler.
23008 				 */
23009 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23010 				    "ip_wput_ire_end: q %p (%S)",
23011 				    q, "last copy out(1)");
23012 				ire_refrele(ire);
23013 				if (conn_outgoing_ill != NULL)
23014 					ill_refrele(conn_outgoing_ill);
23015 				return;
23016 			}
23017 			/* More copies going out below. */
23018 		} else {
23019 			int offset;
23020 		    fragmentit:
23021 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23022 			/*
23023 			 * If this would generate a icmp_frag_needed message,
23024 			 * we need to handle it before we do the IPSEC
23025 			 * processing. Otherwise, we need to strip the IPSEC
23026 			 * headers before we send up the message to the ULPs
23027 			 * which becomes messy and difficult.
23028 			 */
23029 			if (ipsec_len != 0) {
23030 				if ((max_frag < (unsigned int)(LENGTH +
23031 				    ipsec_len)) && (offset & IPH_DF)) {
23032 					out_ill = (ill_t *)stq->q_ptr;
23033 					BUMP_MIB(out_ill->ill_ip_mib,
23034 					    ipIfStatsOutFragFails);
23035 					BUMP_MIB(out_ill->ill_ip_mib,
23036 					    ipIfStatsOutFragReqds);
23037 					ipha->ipha_hdr_checksum = 0;
23038 					ipha->ipha_hdr_checksum =
23039 					    (uint16_t)ip_csum_hdr(ipha);
23040 					icmp_frag_needed(ire->ire_stq, first_mp,
23041 					    max_frag, zoneid);
23042 					if (!next_mp) {
23043 						ire_refrele(ire);
23044 						if (conn_outgoing_ill != NULL) {
23045 							ill_refrele(
23046 							    conn_outgoing_ill);
23047 						}
23048 						return;
23049 					}
23050 				} else {
23051 					/*
23052 					 * This won't cause a icmp_frag_needed
23053 					 * message. to be generated. Send it on
23054 					 * the wire. Note that this could still
23055 					 * cause fragmentation and all we
23056 					 * do is the generation of the message
23057 					 * to the ULP if needed before IPSEC.
23058 					 */
23059 					if (!next_mp) {
23060 						ipsec_out_process(q, first_mp,
23061 						    ire, ill_index);
23062 						TRACE_2(TR_FAC_IP,
23063 						    TR_IP_WPUT_IRE_END,
23064 						    "ip_wput_ire_end: q %p "
23065 						    "(%S)", q,
23066 						    "last ipsec_out_process");
23067 						ire_refrele(ire);
23068 						if (conn_outgoing_ill != NULL) {
23069 							ill_refrele(
23070 							    conn_outgoing_ill);
23071 						}
23072 						return;
23073 					}
23074 					ipsec_out_process(q, first_mp,
23075 					    ire, ill_index);
23076 				}
23077 			} else {
23078 				/*
23079 				 * Initiate IPPF processing. For
23080 				 * fragmentable packets we finish
23081 				 * all QOS packet processing before
23082 				 * calling:
23083 				 * ip_wput_ire_fragmentit->ip_wput_frag
23084 				 */
23085 
23086 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23087 					ip_process(IPP_LOCAL_OUT, &mp,
23088 					    ill_index);
23089 					if (mp == NULL) {
23090 						out_ill = (ill_t *)stq->q_ptr;
23091 						BUMP_MIB(out_ill->ill_ip_mib,
23092 						    ipIfStatsOutDiscards);
23093 						if (next_mp != NULL) {
23094 							freemsg(next_mp);
23095 							ire_refrele(ire1);
23096 						}
23097 						ire_refrele(ire);
23098 						TRACE_2(TR_FAC_IP,
23099 						    TR_IP_WPUT_IRE_END,
23100 						    "ip_wput_ire: q %p (%S)",
23101 						    q, "discard MDATA");
23102 						if (conn_outgoing_ill != NULL) {
23103 							ill_refrele(
23104 							    conn_outgoing_ill);
23105 						}
23106 						return;
23107 					}
23108 				}
23109 				if (!next_mp) {
23110 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23111 					    "ip_wput_ire_end: q %p (%S)",
23112 					    q, "last fragmentation");
23113 					ip_wput_ire_fragmentit(mp, ire,
23114 					    zoneid);
23115 					ire_refrele(ire);
23116 					if (conn_outgoing_ill != NULL)
23117 						ill_refrele(conn_outgoing_ill);
23118 					return;
23119 				}
23120 				ip_wput_ire_fragmentit(mp, ire, zoneid);
23121 			}
23122 		}
23123 	} else {
23124 	    nullstq:
23125 		/* A NULL stq means the destination address is local. */
23126 		UPDATE_OB_PKT_COUNT(ire);
23127 		ire->ire_last_used_time = lbolt;
23128 		ASSERT(ire->ire_ipif != NULL);
23129 		if (!next_mp) {
23130 			/*
23131 			 * Is there an "in" and "out" for traffic local
23132 			 * to a host (loopback)?  The code in Solaris doesn't
23133 			 * explicitly draw a line in its code for in vs out,
23134 			 * so we've had to draw a line in the sand: ip_wput_ire
23135 			 * is considered to be the "output" side and
23136 			 * ip_wput_local to be the "input" side.
23137 			 */
23138 			out_ill = ire->ire_ipif->ipif_ill;
23139 
23140 			DTRACE_PROBE4(ip4__loopback__out__start,
23141 			    ill_t *, NULL, ill_t *, out_ill,
23142 			    ipha_t *, ipha, mblk_t *, first_mp);
23143 
23144 			FW_HOOKS(ip4_loopback_out_event,
23145 			    ipv4firewall_loopback_out,
23146 			    NULL, out_ill, ipha, first_mp, mp);
23147 
23148 			DTRACE_PROBE1(ip4__loopback__out_end,
23149 			    mblk_t *, first_mp);
23150 
23151 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23152 			    "ip_wput_ire_end: q %p (%S)",
23153 			    q, "local address");
23154 
23155 			if (first_mp != NULL)
23156 				ip_wput_local(q, out_ill, ipha,
23157 				    first_mp, ire, 0, ire->ire_zoneid);
23158 			ire_refrele(ire);
23159 			if (conn_outgoing_ill != NULL)
23160 				ill_refrele(conn_outgoing_ill);
23161 			return;
23162 		}
23163 
23164 		out_ill = ire->ire_ipif->ipif_ill;
23165 
23166 		DTRACE_PROBE4(ip4__loopback__out__start,
23167 		    ill_t *, NULL, ill_t *, out_ill,
23168 		    ipha_t *, ipha, mblk_t *, first_mp);
23169 
23170 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
23171 		    NULL, out_ill, ipha, first_mp, mp);
23172 
23173 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23174 
23175 		if (first_mp != NULL)
23176 			ip_wput_local(q, out_ill, ipha,
23177 			    first_mp, ire, 0, ire->ire_zoneid);
23178 	}
23179 next:
23180 	/*
23181 	 * More copies going out to additional interfaces.
23182 	 * ire1 has already been held. We don't need the
23183 	 * "ire" anymore.
23184 	 */
23185 	ire_refrele(ire);
23186 	ire = ire1;
23187 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23188 	mp = next_mp;
23189 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23190 	ill = ire_to_ill(ire);
23191 	first_mp = mp;
23192 	if (ipsec_len != 0) {
23193 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23194 		mp = mp->b_cont;
23195 	}
23196 	dst = ire->ire_addr;
23197 	ipha = (ipha_t *)mp->b_rptr;
23198 	/*
23199 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23200 	 * Restore ipha_ident "no checksum" flag.
23201 	 */
23202 	src = orig_src;
23203 	ipha->ipha_ident = ip_hdr_included;
23204 	goto another;
23205 
23206 #undef	rptr
23207 #undef	Q_TO_INDEX
23208 }
23209 
23210 /*
23211  * Routine to allocate a message that is used to notify the ULP about MDT.
23212  * The caller may provide a pointer to the link-layer MDT capabilities,
23213  * or NULL if MDT is to be disabled on the stream.
23214  */
23215 mblk_t *
23216 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23217 {
23218 	mblk_t *mp;
23219 	ip_mdt_info_t *mdti;
23220 	ill_mdt_capab_t *idst;
23221 
23222 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23223 		DB_TYPE(mp) = M_CTL;
23224 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23225 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23226 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23227 		idst = &(mdti->mdt_capab);
23228 
23229 		/*
23230 		 * If the caller provides us with the capability, copy
23231 		 * it over into our notification message; otherwise
23232 		 * we zero out the capability portion.
23233 		 */
23234 		if (isrc != NULL)
23235 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23236 		else
23237 			bzero((caddr_t)idst, sizeof (*idst));
23238 	}
23239 	return (mp);
23240 }
23241 
23242 /*
23243  * Routine which determines whether MDT can be enabled on the destination
23244  * IRE and IPC combination, and if so, allocates and returns the MDT
23245  * notification mblk that may be used by ULP.  We also check if we need to
23246  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23247  * MDT usage in the past have been lifted.  This gets called during IP
23248  * and ULP binding.
23249  */
23250 mblk_t *
23251 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23252     ill_mdt_capab_t *mdt_cap)
23253 {
23254 	mblk_t *mp;
23255 	boolean_t rc = B_FALSE;
23256 
23257 	ASSERT(dst_ire != NULL);
23258 	ASSERT(connp != NULL);
23259 	ASSERT(mdt_cap != NULL);
23260 
23261 	/*
23262 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23263 	 * Multidata, which is handled in tcp_multisend().  This
23264 	 * is the reason why we do all these checks here, to ensure
23265 	 * that we don't enable Multidata for the cases which we
23266 	 * can't handle at the moment.
23267 	 */
23268 	do {
23269 		/* Only do TCP at the moment */
23270 		if (connp->conn_ulp != IPPROTO_TCP)
23271 			break;
23272 
23273 		/*
23274 		 * IPSEC outbound policy present?  Note that we get here
23275 		 * after calling ipsec_conn_cache_policy() where the global
23276 		 * policy checking is performed.  conn_latch will be
23277 		 * non-NULL as long as there's a policy defined,
23278 		 * i.e. conn_out_enforce_policy may be NULL in such case
23279 		 * when the connection is non-secure, and hence we check
23280 		 * further if the latch refers to an outbound policy.
23281 		 */
23282 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23283 			break;
23284 
23285 		/* CGTP (multiroute) is enabled? */
23286 		if (dst_ire->ire_flags & RTF_MULTIRT)
23287 			break;
23288 
23289 		/* Outbound IPQoS enabled? */
23290 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23291 			/*
23292 			 * In this case, we disable MDT for this and all
23293 			 * future connections going over the interface.
23294 			 */
23295 			mdt_cap->ill_mdt_on = 0;
23296 			break;
23297 		}
23298 
23299 		/* socket option(s) present? */
23300 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23301 			break;
23302 
23303 		rc = B_TRUE;
23304 	/* CONSTCOND */
23305 	} while (0);
23306 
23307 	/* Remember the result */
23308 	connp->conn_mdt_ok = rc;
23309 
23310 	if (!rc)
23311 		return (NULL);
23312 	else if (!mdt_cap->ill_mdt_on) {
23313 		/*
23314 		 * If MDT has been previously turned off in the past, and we
23315 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23316 		 * then enable it for this interface.
23317 		 */
23318 		mdt_cap->ill_mdt_on = 1;
23319 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23320 		    "interface %s\n", ill_name));
23321 	}
23322 
23323 	/* Allocate the MDT info mblk */
23324 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23325 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23326 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23327 		return (NULL);
23328 	}
23329 	return (mp);
23330 }
23331 
23332 /*
23333  * Routine to allocate a message that is used to notify the ULP about LSO.
23334  * The caller may provide a pointer to the link-layer LSO capabilities,
23335  * or NULL if LSO is to be disabled on the stream.
23336  */
23337 mblk_t *
23338 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23339 {
23340 	mblk_t *mp;
23341 	ip_lso_info_t *lsoi;
23342 	ill_lso_capab_t *idst;
23343 
23344 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23345 		DB_TYPE(mp) = M_CTL;
23346 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23347 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23348 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23349 		idst = &(lsoi->lso_capab);
23350 
23351 		/*
23352 		 * If the caller provides us with the capability, copy
23353 		 * it over into our notification message; otherwise
23354 		 * we zero out the capability portion.
23355 		 */
23356 		if (isrc != NULL)
23357 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23358 		else
23359 			bzero((caddr_t)idst, sizeof (*idst));
23360 	}
23361 	return (mp);
23362 }
23363 
23364 /*
23365  * Routine which determines whether LSO can be enabled on the destination
23366  * IRE and IPC combination, and if so, allocates and returns the LSO
23367  * notification mblk that may be used by ULP.  We also check if we need to
23368  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23369  * LSO usage in the past have been lifted.  This gets called during IP
23370  * and ULP binding.
23371  */
23372 mblk_t *
23373 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23374     ill_lso_capab_t *lso_cap)
23375 {
23376 	mblk_t *mp;
23377 
23378 	ASSERT(dst_ire != NULL);
23379 	ASSERT(connp != NULL);
23380 	ASSERT(lso_cap != NULL);
23381 
23382 	connp->conn_lso_ok = B_TRUE;
23383 
23384 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23385 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23386 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23387 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23388 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
23389 		connp->conn_lso_ok = B_FALSE;
23390 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23391 			/*
23392 			 * Disable LSO for this and all future connections going
23393 			 * over the interface.
23394 			 */
23395 			lso_cap->ill_lso_on = 0;
23396 		}
23397 	}
23398 
23399 	if (!connp->conn_lso_ok)
23400 		return (NULL);
23401 	else if (!lso_cap->ill_lso_on) {
23402 		/*
23403 		 * If LSO has been previously turned off in the past, and we
23404 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23405 		 * then enable it for this interface.
23406 		 */
23407 		lso_cap->ill_lso_on = 1;
23408 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23409 		    ill_name));
23410 	}
23411 
23412 	/* Allocate the LSO info mblk */
23413 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23414 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23415 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23416 
23417 	return (mp);
23418 }
23419 
23420 /*
23421  * Create destination address attribute, and fill it with the physical
23422  * destination address and SAP taken from the template DL_UNITDATA_REQ
23423  * message block.
23424  */
23425 boolean_t
23426 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23427 {
23428 	dl_unitdata_req_t *dlurp;
23429 	pattr_t *pa;
23430 	pattrinfo_t pa_info;
23431 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23432 	uint_t das_len, das_off;
23433 
23434 	ASSERT(dlmp != NULL);
23435 
23436 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23437 	das_len = dlurp->dl_dest_addr_length;
23438 	das_off = dlurp->dl_dest_addr_offset;
23439 
23440 	pa_info.type = PATTR_DSTADDRSAP;
23441 	pa_info.len = sizeof (**das) + das_len - 1;
23442 
23443 	/* create and associate the attribute */
23444 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23445 	if (pa != NULL) {
23446 		ASSERT(*das != NULL);
23447 		(*das)->addr_is_group = 0;
23448 		(*das)->addr_len = (uint8_t)das_len;
23449 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23450 	}
23451 
23452 	return (pa != NULL);
23453 }
23454 
23455 /*
23456  * Create hardware checksum attribute and fill it with the values passed.
23457  */
23458 boolean_t
23459 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23460     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23461 {
23462 	pattr_t *pa;
23463 	pattrinfo_t pa_info;
23464 
23465 	ASSERT(mmd != NULL);
23466 
23467 	pa_info.type = PATTR_HCKSUM;
23468 	pa_info.len = sizeof (pattr_hcksum_t);
23469 
23470 	/* create and associate the attribute */
23471 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23472 	if (pa != NULL) {
23473 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23474 
23475 		hck->hcksum_start_offset = start_offset;
23476 		hck->hcksum_stuff_offset = stuff_offset;
23477 		hck->hcksum_end_offset = end_offset;
23478 		hck->hcksum_flags = flags;
23479 	}
23480 	return (pa != NULL);
23481 }
23482 
23483 /*
23484  * Create zerocopy attribute and fill it with the specified flags
23485  */
23486 boolean_t
23487 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23488 {
23489 	pattr_t *pa;
23490 	pattrinfo_t pa_info;
23491 
23492 	ASSERT(mmd != NULL);
23493 	pa_info.type = PATTR_ZCOPY;
23494 	pa_info.len = sizeof (pattr_zcopy_t);
23495 
23496 	/* create and associate the attribute */
23497 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23498 	if (pa != NULL) {
23499 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23500 
23501 		zcopy->zcopy_flags = flags;
23502 	}
23503 	return (pa != NULL);
23504 }
23505 
23506 /*
23507  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23508  * block chain. We could rewrite to handle arbitrary message block chains but
23509  * that would make the code complicated and slow. Right now there three
23510  * restrictions:
23511  *
23512  *   1. The first message block must contain the complete IP header and
23513  *	at least 1 byte of payload data.
23514  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23515  *	so that we can use a single Multidata message.
23516  *   3. No frag must be distributed over two or more message blocks so
23517  *	that we don't need more than two packet descriptors per frag.
23518  *
23519  * The above restrictions allow us to support userland applications (which
23520  * will send down a single message block) and NFS over UDP (which will
23521  * send down a chain of at most three message blocks).
23522  *
23523  * We also don't use MDT for payloads with less than or equal to
23524  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23525  */
23526 boolean_t
23527 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23528 {
23529 	int	blocks;
23530 	ssize_t	total, missing, size;
23531 
23532 	ASSERT(mp != NULL);
23533 	ASSERT(hdr_len > 0);
23534 
23535 	size = MBLKL(mp) - hdr_len;
23536 	if (size <= 0)
23537 		return (B_FALSE);
23538 
23539 	/* The first mblk contains the header and some payload. */
23540 	blocks = 1;
23541 	total = size;
23542 	size %= len;
23543 	missing = (size == 0) ? 0 : (len - size);
23544 	mp = mp->b_cont;
23545 
23546 	while (mp != NULL) {
23547 		/*
23548 		 * Give up if we encounter a zero length message block.
23549 		 * In practice, this should rarely happen and therefore
23550 		 * not worth the trouble of freeing and re-linking the
23551 		 * mblk from the chain to handle such case.
23552 		 */
23553 		if ((size = MBLKL(mp)) == 0)
23554 			return (B_FALSE);
23555 
23556 		/* Too many payload buffers for a single Multidata message? */
23557 		if (++blocks > MULTIDATA_MAX_PBUFS)
23558 			return (B_FALSE);
23559 
23560 		total += size;
23561 		/* Is a frag distributed over two or more message blocks? */
23562 		if (missing > size)
23563 			return (B_FALSE);
23564 		size -= missing;
23565 
23566 		size %= len;
23567 		missing = (size == 0) ? 0 : (len - size);
23568 
23569 		mp = mp->b_cont;
23570 	}
23571 
23572 	return (total > ip_wput_frag_mdt_min);
23573 }
23574 
23575 /*
23576  * Outbound IPv4 fragmentation routine using MDT.
23577  */
23578 static void
23579 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23580     uint32_t frag_flag, int offset)
23581 {
23582 	ipha_t		*ipha_orig;
23583 	int		i1, ip_data_end;
23584 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23585 	mblk_t		*hdr_mp, *md_mp = NULL;
23586 	unsigned char	*hdr_ptr, *pld_ptr;
23587 	multidata_t	*mmd;
23588 	ip_pdescinfo_t	pdi;
23589 	ill_t		*ill;
23590 
23591 	ASSERT(DB_TYPE(mp) == M_DATA);
23592 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23593 
23594 	ill = ire_to_ill(ire);
23595 	ASSERT(ill != NULL);
23596 
23597 	ipha_orig = (ipha_t *)mp->b_rptr;
23598 	mp->b_rptr += sizeof (ipha_t);
23599 
23600 	/* Calculate how many packets we will send out */
23601 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23602 	pkts = (i1 + len - 1) / len;
23603 	ASSERT(pkts > 1);
23604 
23605 	/* Allocate a message block which will hold all the IP Headers. */
23606 	wroff = ip_wroff_extra;
23607 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23608 
23609 	i1 = pkts * hdr_chunk_len;
23610 	/*
23611 	 * Create the header buffer, Multidata and destination address
23612 	 * and SAP attribute that should be associated with it.
23613 	 */
23614 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23615 	    ((hdr_mp->b_wptr += i1),
23616 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23617 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23618 		freemsg(mp);
23619 		if (md_mp == NULL) {
23620 			freemsg(hdr_mp);
23621 		} else {
23622 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23623 			freemsg(md_mp);
23624 		}
23625 		IP_STAT(ip_frag_mdt_allocfail);
23626 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23627 		return;
23628 	}
23629 	IP_STAT(ip_frag_mdt_allocd);
23630 
23631 	/*
23632 	 * Add a payload buffer to the Multidata; this operation must not
23633 	 * fail, or otherwise our logic in this routine is broken.  There
23634 	 * is no memory allocation done by the routine, so any returned
23635 	 * failure simply tells us that we've done something wrong.
23636 	 *
23637 	 * A failure tells us that either we're adding the same payload
23638 	 * buffer more than once, or we're trying to add more buffers than
23639 	 * allowed.  None of the above cases should happen, and we panic
23640 	 * because either there's horrible heap corruption, and/or
23641 	 * programming mistake.
23642 	 */
23643 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23644 		goto pbuf_panic;
23645 
23646 	hdr_ptr = hdr_mp->b_rptr;
23647 	pld_ptr = mp->b_rptr;
23648 
23649 	/* Establish the ending byte offset, based on the starting offset. */
23650 	offset <<= 3;
23651 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23652 	    IP_SIMPLE_HDR_LENGTH;
23653 
23654 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23655 
23656 	while (pld_ptr < mp->b_wptr) {
23657 		ipha_t		*ipha;
23658 		uint16_t	offset_and_flags;
23659 		uint16_t	ip_len;
23660 		int		error;
23661 
23662 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23663 		ipha = (ipha_t *)(hdr_ptr + wroff);
23664 		ASSERT(OK_32PTR(ipha));
23665 		*ipha = *ipha_orig;
23666 
23667 		if (ip_data_end - offset > len) {
23668 			offset_and_flags = IPH_MF;
23669 		} else {
23670 			/*
23671 			 * Last frag. Set len to the length of this last piece.
23672 			 */
23673 			len = ip_data_end - offset;
23674 			/* A frag of a frag might have IPH_MF non-zero */
23675 			offset_and_flags =
23676 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23677 			    IPH_MF;
23678 		}
23679 		offset_and_flags |= (uint16_t)(offset >> 3);
23680 		offset_and_flags |= (uint16_t)frag_flag;
23681 		/* Store the offset and flags in the IP header. */
23682 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23683 
23684 		/* Store the length in the IP header. */
23685 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23686 		ipha->ipha_length = htons(ip_len);
23687 
23688 		/*
23689 		 * Set the IP header checksum.  Note that mp is just
23690 		 * the header, so this is easy to pass to ip_csum.
23691 		 */
23692 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23693 
23694 		/*
23695 		 * Record offset and size of header and data of the next packet
23696 		 * in the multidata message.
23697 		 */
23698 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23699 		PDESC_PLD_INIT(&pdi);
23700 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23701 		ASSERT(i1 > 0);
23702 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23703 		if (i1 == len) {
23704 			pld_ptr += len;
23705 		} else {
23706 			i1 = len - i1;
23707 			mp = mp->b_cont;
23708 			ASSERT(mp != NULL);
23709 			ASSERT(MBLKL(mp) >= i1);
23710 			/*
23711 			 * Attach the next payload message block to the
23712 			 * multidata message.
23713 			 */
23714 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23715 				goto pbuf_panic;
23716 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23717 			pld_ptr = mp->b_rptr + i1;
23718 		}
23719 
23720 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23721 		    KM_NOSLEEP)) == NULL) {
23722 			/*
23723 			 * Any failure other than ENOMEM indicates that we
23724 			 * have passed in invalid pdesc info or parameters
23725 			 * to mmd_addpdesc, which must not happen.
23726 			 *
23727 			 * EINVAL is a result of failure on boundary checks
23728 			 * against the pdesc info contents.  It should not
23729 			 * happen, and we panic because either there's
23730 			 * horrible heap corruption, and/or programming
23731 			 * mistake.
23732 			 */
23733 			if (error != ENOMEM) {
23734 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23735 				    "pdesc logic error detected for "
23736 				    "mmd %p pinfo %p (%d)\n",
23737 				    (void *)mmd, (void *)&pdi, error);
23738 				/* NOTREACHED */
23739 			}
23740 			IP_STAT(ip_frag_mdt_addpdescfail);
23741 			/* Free unattached payload message blocks as well */
23742 			md_mp->b_cont = mp->b_cont;
23743 			goto free_mmd;
23744 		}
23745 
23746 		/* Advance fragment offset. */
23747 		offset += len;
23748 
23749 		/* Advance to location for next header in the buffer. */
23750 		hdr_ptr += hdr_chunk_len;
23751 
23752 		/* Did we reach the next payload message block? */
23753 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23754 			mp = mp->b_cont;
23755 			/*
23756 			 * Attach the next message block with payload
23757 			 * data to the multidata message.
23758 			 */
23759 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23760 				goto pbuf_panic;
23761 			pld_ptr = mp->b_rptr;
23762 		}
23763 	}
23764 
23765 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23766 	ASSERT(mp->b_wptr == pld_ptr);
23767 
23768 	/* Update IP statistics */
23769 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23770 
23771 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23772 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23773 
23774 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23775 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23776 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23777 
23778 	if (pkt_type == OB_PKT) {
23779 		ire->ire_ob_pkt_count += pkts;
23780 		if (ire->ire_ipif != NULL)
23781 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23782 	} else {
23783 		/*
23784 		 * The type is IB_PKT in the forwarding path and in
23785 		 * the mobile IP case when the packet is being reverse-
23786 		 * tunneled to the home agent.
23787 		 */
23788 		ire->ire_ib_pkt_count += pkts;
23789 		ASSERT(!IRE_IS_LOCAL(ire));
23790 		if (ire->ire_type & IRE_BROADCAST) {
23791 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23792 		} else {
23793 			UPDATE_MIB(ill->ill_ip_mib,
23794 			    ipIfStatsHCOutForwDatagrams, pkts);
23795 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23796 		}
23797 	}
23798 	ire->ire_last_used_time = lbolt;
23799 	/* Send it down */
23800 	putnext(ire->ire_stq, md_mp);
23801 	return;
23802 
23803 pbuf_panic:
23804 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23805 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23806 	    pbuf_idx);
23807 	/* NOTREACHED */
23808 }
23809 
23810 /*
23811  * Outbound IP fragmentation routine.
23812  *
23813  * NOTE : This routine does not ire_refrele the ire that is passed in
23814  * as the argument.
23815  */
23816 static void
23817 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23818     uint32_t frag_flag, zoneid_t zoneid)
23819 {
23820 	int		i1;
23821 	mblk_t		*ll_hdr_mp;
23822 	int 		ll_hdr_len;
23823 	int		hdr_len;
23824 	mblk_t		*hdr_mp;
23825 	ipha_t		*ipha;
23826 	int		ip_data_end;
23827 	int		len;
23828 	mblk_t		*mp = mp_orig, *mp1;
23829 	int		offset;
23830 	queue_t		*q;
23831 	uint32_t	v_hlen_tos_len;
23832 	mblk_t		*first_mp;
23833 	boolean_t	mctl_present;
23834 	ill_t		*ill;
23835 	ill_t		*out_ill;
23836 	mblk_t		*xmit_mp;
23837 	mblk_t		*carve_mp;
23838 	ire_t		*ire1 = NULL;
23839 	ire_t		*save_ire = NULL;
23840 	mblk_t  	*next_mp = NULL;
23841 	boolean_t	last_frag = B_FALSE;
23842 	boolean_t	multirt_send = B_FALSE;
23843 	ire_t		*first_ire = NULL;
23844 	irb_t		*irb = NULL;
23845 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23846 
23847 	ill = ire_to_ill(ire);
23848 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
23849 
23850 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23851 
23852 	/*
23853 	 * IPSEC does not allow hw accelerated packets to be fragmented
23854 	 * This check is made in ip_wput_ipsec_out prior to coming here
23855 	 * via ip_wput_ire_fragmentit.
23856 	 *
23857 	 * If at this point we have an ire whose ARP request has not
23858 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23859 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23860 	 * This packet and all fragmentable packets for this ire will
23861 	 * continue to get dropped while ire_nce->nce_state remains in
23862 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23863 	 * ND_REACHABLE, all subsquent large packets for this ire will
23864 	 * get fragemented and sent out by this function.
23865 	 */
23866 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23867 		/* If nce_state is ND_INITIAL, trigger ARP query */
23868 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23869 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23870 		    " -  dropping packet\n"));
23871 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23872 		freemsg(mp);
23873 		return;
23874 	}
23875 
23876 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23877 	    "ip_wput_frag_start:");
23878 
23879 	if (mp->b_datap->db_type == M_CTL) {
23880 		first_mp = mp;
23881 		mp_orig = mp = mp->b_cont;
23882 		mctl_present = B_TRUE;
23883 	} else {
23884 		first_mp = mp;
23885 		mctl_present = B_FALSE;
23886 	}
23887 
23888 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23889 	ipha = (ipha_t *)mp->b_rptr;
23890 
23891 	/*
23892 	 * If the Don't Fragment flag is on, generate an ICMP destination
23893 	 * unreachable, fragmentation needed.
23894 	 */
23895 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23896 	if (offset & IPH_DF) {
23897 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23898 		/*
23899 		 * Need to compute hdr checksum if called from ip_wput_ire.
23900 		 * Note that ip_rput_forward verifies the checksum before
23901 		 * calling this routine so in that case this is a noop.
23902 		 */
23903 		ipha->ipha_hdr_checksum = 0;
23904 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23905 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23906 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23907 		    "ip_wput_frag_end:(%S)",
23908 		    "don't fragment");
23909 		return;
23910 	}
23911 	if (mctl_present)
23912 		freeb(first_mp);
23913 	/*
23914 	 * Establish the starting offset.  May not be zero if we are fragging
23915 	 * a fragment that is being forwarded.
23916 	 */
23917 	offset = offset & IPH_OFFSET;
23918 
23919 	/* TODO why is this test needed? */
23920 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23921 	if (((max_frag - LENGTH) & ~7) < 8) {
23922 		/* TODO: notify ulp somehow */
23923 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23924 		freemsg(mp);
23925 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23926 		    "ip_wput_frag_end:(%S)",
23927 		    "len < 8");
23928 		return;
23929 	}
23930 
23931 	hdr_len = (V_HLEN & 0xF) << 2;
23932 
23933 	ipha->ipha_hdr_checksum = 0;
23934 
23935 	/*
23936 	 * Establish the number of bytes maximum per frag, after putting
23937 	 * in the header.
23938 	 */
23939 	len = (max_frag - hdr_len) & ~7;
23940 
23941 	/* Check if we can use MDT to send out the frags. */
23942 	ASSERT(!IRE_IS_LOCAL(ire));
23943 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23944 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23945 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
23946 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23947 		ASSERT(ill->ill_mdt_capab != NULL);
23948 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23949 			/*
23950 			 * If MDT has been previously turned off in the past,
23951 			 * and we currently can do MDT (due to IPQoS policy
23952 			 * removal, etc.) then enable it for this interface.
23953 			 */
23954 			ill->ill_mdt_capab->ill_mdt_on = 1;
23955 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23956 			    ill->ill_name));
23957 		}
23958 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23959 		    offset);
23960 		return;
23961 	}
23962 
23963 	/* Get a copy of the header for the trailing frags */
23964 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23965 	if (!hdr_mp) {
23966 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23967 		freemsg(mp);
23968 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23969 		    "ip_wput_frag_end:(%S)",
23970 		    "couldn't copy hdr");
23971 		return;
23972 	}
23973 	if (DB_CRED(mp) != NULL)
23974 		mblk_setcred(hdr_mp, DB_CRED(mp));
23975 
23976 	/* Store the starting offset, with the MoreFrags flag. */
23977 	i1 = offset | IPH_MF | frag_flag;
23978 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23979 
23980 	/* Establish the ending byte offset, based on the starting offset. */
23981 	offset <<= 3;
23982 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23983 
23984 	/* Store the length of the first fragment in the IP header. */
23985 	i1 = len + hdr_len;
23986 	ASSERT(i1 <= IP_MAXPACKET);
23987 	ipha->ipha_length = htons((uint16_t)i1);
23988 
23989 	/*
23990 	 * Compute the IP header checksum for the first frag.  We have to
23991 	 * watch out that we stop at the end of the header.
23992 	 */
23993 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23994 
23995 	/*
23996 	 * Now carve off the first frag.  Note that this will include the
23997 	 * original IP header.
23998 	 */
23999 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24000 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24001 		freeb(hdr_mp);
24002 		freemsg(mp_orig);
24003 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24004 		    "ip_wput_frag_end:(%S)",
24005 		    "couldn't carve first");
24006 		return;
24007 	}
24008 
24009 	/*
24010 	 * Multirouting case. Each fragment is replicated
24011 	 * via all non-condemned RTF_MULTIRT routes
24012 	 * currently resolved.
24013 	 * We ensure that first_ire is the first RTF_MULTIRT
24014 	 * ire in the bucket.
24015 	 */
24016 	if (ire->ire_flags & RTF_MULTIRT) {
24017 		irb = ire->ire_bucket;
24018 		ASSERT(irb != NULL);
24019 
24020 		multirt_send = B_TRUE;
24021 
24022 		/* Make sure we do not omit any multiroute ire. */
24023 		IRB_REFHOLD(irb);
24024 		for (first_ire = irb->irb_ire;
24025 		    first_ire != NULL;
24026 		    first_ire = first_ire->ire_next) {
24027 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24028 			    (first_ire->ire_addr == ire->ire_addr) &&
24029 			    !(first_ire->ire_marks &
24030 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24031 				break;
24032 		}
24033 
24034 		if (first_ire != NULL) {
24035 			if (first_ire != ire) {
24036 				IRE_REFHOLD(first_ire);
24037 				/*
24038 				 * Do not release the ire passed in
24039 				 * as the argument.
24040 				 */
24041 				ire = first_ire;
24042 			} else {
24043 				first_ire = NULL;
24044 			}
24045 		}
24046 		IRB_REFRELE(irb);
24047 
24048 		/*
24049 		 * Save the first ire; we will need to restore it
24050 		 * for the trailing frags.
24051 		 * We REFHOLD save_ire, as each iterated ire will be
24052 		 * REFRELEd.
24053 		 */
24054 		save_ire = ire;
24055 		IRE_REFHOLD(save_ire);
24056 	}
24057 
24058 	/*
24059 	 * First fragment emission loop.
24060 	 * In most cases, the emission loop below is entered only
24061 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24062 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24063 	 * bucket, and send the fragment through all crossed
24064 	 * RTF_MULTIRT routes.
24065 	 */
24066 	do {
24067 		if (ire->ire_flags & RTF_MULTIRT) {
24068 			/*
24069 			 * We are in a multiple send case, need to get
24070 			 * the next ire and make a copy of the packet.
24071 			 * ire1 holds here the next ire to process in the
24072 			 * bucket. If multirouting is expected,
24073 			 * any non-RTF_MULTIRT ire that has the
24074 			 * right destination address is ignored.
24075 			 *
24076 			 * We have to take into account the MTU of
24077 			 * each walked ire. max_frag is set by the
24078 			 * the caller and generally refers to
24079 			 * the primary ire entry. Here we ensure that
24080 			 * no route with a lower MTU will be used, as
24081 			 * fragments are carved once for all ires,
24082 			 * then replicated.
24083 			 */
24084 			ASSERT(irb != NULL);
24085 			IRB_REFHOLD(irb);
24086 			for (ire1 = ire->ire_next;
24087 			    ire1 != NULL;
24088 			    ire1 = ire1->ire_next) {
24089 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24090 					continue;
24091 				if (ire1->ire_addr != ire->ire_addr)
24092 					continue;
24093 				if (ire1->ire_marks &
24094 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24095 					continue;
24096 				/*
24097 				 * Ensure we do not exceed the MTU
24098 				 * of the next route.
24099 				 */
24100 				if (ire1->ire_max_frag < max_frag) {
24101 					ip_multirt_bad_mtu(ire1, max_frag);
24102 					continue;
24103 				}
24104 
24105 				/* Got one. */
24106 				IRE_REFHOLD(ire1);
24107 				break;
24108 			}
24109 			IRB_REFRELE(irb);
24110 
24111 			if (ire1 != NULL) {
24112 				next_mp = copyb(mp);
24113 				if ((next_mp == NULL) ||
24114 				    ((mp->b_cont != NULL) &&
24115 				    ((next_mp->b_cont =
24116 				    dupmsg(mp->b_cont)) == NULL))) {
24117 					freemsg(next_mp);
24118 					next_mp = NULL;
24119 					ire_refrele(ire1);
24120 					ire1 = NULL;
24121 				}
24122 			}
24123 
24124 			/* Last multiroute ire; don't loop anymore. */
24125 			if (ire1 == NULL) {
24126 				multirt_send = B_FALSE;
24127 			}
24128 		}
24129 
24130 		ll_hdr_len = 0;
24131 		LOCK_IRE_FP_MP(ire);
24132 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24133 		if (ll_hdr_mp != NULL) {
24134 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24135 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24136 		} else {
24137 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24138 		}
24139 
24140 		/* If there is a transmit header, get a copy for this frag. */
24141 		/*
24142 		 * TODO: should check db_ref before calling ip_carve_mp since
24143 		 * it might give us a dup.
24144 		 */
24145 		if (!ll_hdr_mp) {
24146 			/* No xmit header. */
24147 			xmit_mp = mp;
24148 
24149 		/* We have a link-layer header that can fit in our mblk. */
24150 		} else if (mp->b_datap->db_ref == 1 &&
24151 		    ll_hdr_len != 0 &&
24152 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24153 			/* M_DATA fastpath */
24154 			mp->b_rptr -= ll_hdr_len;
24155 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24156 			xmit_mp = mp;
24157 
24158 		/* Corner case if copyb has failed */
24159 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24160 			UNLOCK_IRE_FP_MP(ire);
24161 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24162 			freeb(hdr_mp);
24163 			freemsg(mp);
24164 			freemsg(mp_orig);
24165 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24166 			    "ip_wput_frag_end:(%S)",
24167 			    "discard");
24168 
24169 			if (multirt_send) {
24170 				ASSERT(ire1);
24171 				ASSERT(next_mp);
24172 
24173 				freemsg(next_mp);
24174 				ire_refrele(ire1);
24175 			}
24176 			if (save_ire != NULL)
24177 				IRE_REFRELE(save_ire);
24178 
24179 			if (first_ire != NULL)
24180 				ire_refrele(first_ire);
24181 			return;
24182 
24183 		/*
24184 		 * Case of res_mp OR the fastpath mp can't fit
24185 		 * in the mblk
24186 		 */
24187 		} else {
24188 			xmit_mp->b_cont = mp;
24189 			if (DB_CRED(mp) != NULL)
24190 				mblk_setcred(xmit_mp, DB_CRED(mp));
24191 			/*
24192 			 * Get priority marking, if any.
24193 			 * We propagate the CoS marking from the
24194 			 * original packet that went to QoS processing
24195 			 * in ip_wput_ire to the newly carved mp.
24196 			 */
24197 			if (DB_TYPE(xmit_mp) == M_DATA)
24198 				xmit_mp->b_band = mp->b_band;
24199 		}
24200 		UNLOCK_IRE_FP_MP(ire);
24201 
24202 		q = ire->ire_stq;
24203 		out_ill = (ill_t *)q->q_ptr;
24204 
24205 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24206 
24207 		DTRACE_PROBE4(ip4__physical__out__start,
24208 		    ill_t *, NULL, ill_t *, out_ill,
24209 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24210 
24211 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
24212 		    NULL, out_ill, ipha, xmit_mp, mp);
24213 
24214 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24215 
24216 		if (xmit_mp != NULL) {
24217 			putnext(q, xmit_mp);
24218 
24219 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24220 			UPDATE_MIB(out_ill->ill_ip_mib,
24221 			    ipIfStatsHCOutOctets, i1);
24222 
24223 			if (pkt_type != OB_PKT) {
24224 				/*
24225 				 * Update the packet count and MIB stats
24226 				 * of trailing RTF_MULTIRT ires.
24227 				 */
24228 				UPDATE_OB_PKT_COUNT(ire);
24229 				BUMP_MIB(out_ill->ill_ip_mib,
24230 				    ipIfStatsOutFragReqds);
24231 			}
24232 		}
24233 
24234 		if (multirt_send) {
24235 			/*
24236 			 * We are in a multiple send case; look for
24237 			 * the next ire and re-enter the loop.
24238 			 */
24239 			ASSERT(ire1);
24240 			ASSERT(next_mp);
24241 			/* REFRELE the current ire before looping */
24242 			ire_refrele(ire);
24243 			ire = ire1;
24244 			ire1 = NULL;
24245 			mp = next_mp;
24246 			next_mp = NULL;
24247 		}
24248 	} while (multirt_send);
24249 
24250 	ASSERT(ire1 == NULL);
24251 
24252 	/* Restore the original ire; we need it for the trailing frags */
24253 	if (save_ire != NULL) {
24254 		/* REFRELE the last iterated ire */
24255 		ire_refrele(ire);
24256 		/* save_ire has been REFHOLDed */
24257 		ire = save_ire;
24258 		save_ire = NULL;
24259 		q = ire->ire_stq;
24260 	}
24261 
24262 	if (pkt_type == OB_PKT) {
24263 		UPDATE_OB_PKT_COUNT(ire);
24264 	} else {
24265 		out_ill = (ill_t *)q->q_ptr;
24266 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24267 		UPDATE_IB_PKT_COUNT(ire);
24268 	}
24269 
24270 	/* Advance the offset to the second frag starting point. */
24271 	offset += len;
24272 	/*
24273 	 * Update hdr_len from the copied header - there might be less options
24274 	 * in the later fragments.
24275 	 */
24276 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24277 	/* Loop until done. */
24278 	for (;;) {
24279 		uint16_t	offset_and_flags;
24280 		uint16_t	ip_len;
24281 
24282 		if (ip_data_end - offset > len) {
24283 			/*
24284 			 * Carve off the appropriate amount from the original
24285 			 * datagram.
24286 			 */
24287 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24288 				mp = NULL;
24289 				break;
24290 			}
24291 			/*
24292 			 * More frags after this one.  Get another copy
24293 			 * of the header.
24294 			 */
24295 			if (carve_mp->b_datap->db_ref == 1 &&
24296 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24297 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24298 				/* Inline IP header */
24299 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24300 				    hdr_mp->b_rptr;
24301 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24302 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24303 				mp = carve_mp;
24304 			} else {
24305 				if (!(mp = copyb(hdr_mp))) {
24306 					freemsg(carve_mp);
24307 					break;
24308 				}
24309 				/* Get priority marking, if any. */
24310 				mp->b_band = carve_mp->b_band;
24311 				mp->b_cont = carve_mp;
24312 			}
24313 			ipha = (ipha_t *)mp->b_rptr;
24314 			offset_and_flags = IPH_MF;
24315 		} else {
24316 			/*
24317 			 * Last frag.  Consume the header. Set len to
24318 			 * the length of this last piece.
24319 			 */
24320 			len = ip_data_end - offset;
24321 
24322 			/*
24323 			 * Carve off the appropriate amount from the original
24324 			 * datagram.
24325 			 */
24326 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24327 				mp = NULL;
24328 				break;
24329 			}
24330 			if (carve_mp->b_datap->db_ref == 1 &&
24331 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24332 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24333 				/* Inline IP header */
24334 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24335 				    hdr_mp->b_rptr;
24336 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24337 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24338 				mp = carve_mp;
24339 				freeb(hdr_mp);
24340 				hdr_mp = mp;
24341 			} else {
24342 				mp = hdr_mp;
24343 				/* Get priority marking, if any. */
24344 				mp->b_band = carve_mp->b_band;
24345 				mp->b_cont = carve_mp;
24346 			}
24347 			ipha = (ipha_t *)mp->b_rptr;
24348 			/* A frag of a frag might have IPH_MF non-zero */
24349 			offset_and_flags =
24350 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24351 			    IPH_MF;
24352 		}
24353 		offset_and_flags |= (uint16_t)(offset >> 3);
24354 		offset_and_flags |= (uint16_t)frag_flag;
24355 		/* Store the offset and flags in the IP header. */
24356 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24357 
24358 		/* Store the length in the IP header. */
24359 		ip_len = (uint16_t)(len + hdr_len);
24360 		ipha->ipha_length = htons(ip_len);
24361 
24362 		/*
24363 		 * Set the IP header checksum.	Note that mp is just
24364 		 * the header, so this is easy to pass to ip_csum.
24365 		 */
24366 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24367 
24368 		/* Attach a transmit header, if any, and ship it. */
24369 		if (pkt_type == OB_PKT) {
24370 			UPDATE_OB_PKT_COUNT(ire);
24371 		} else {
24372 			out_ill = (ill_t *)q->q_ptr;
24373 			BUMP_MIB(out_ill->ill_ip_mib,
24374 			    ipIfStatsHCOutForwDatagrams);
24375 			UPDATE_IB_PKT_COUNT(ire);
24376 		}
24377 
24378 		if (ire->ire_flags & RTF_MULTIRT) {
24379 			irb = ire->ire_bucket;
24380 			ASSERT(irb != NULL);
24381 
24382 			multirt_send = B_TRUE;
24383 
24384 			/*
24385 			 * Save the original ire; we will need to restore it
24386 			 * for the tailing frags.
24387 			 */
24388 			save_ire = ire;
24389 			IRE_REFHOLD(save_ire);
24390 		}
24391 		/*
24392 		 * Emission loop for this fragment, similar
24393 		 * to what is done for the first fragment.
24394 		 */
24395 		do {
24396 			if (multirt_send) {
24397 				/*
24398 				 * We are in a multiple send case, need to get
24399 				 * the next ire and make a copy of the packet.
24400 				 */
24401 				ASSERT(irb != NULL);
24402 				IRB_REFHOLD(irb);
24403 				for (ire1 = ire->ire_next;
24404 				    ire1 != NULL;
24405 				    ire1 = ire1->ire_next) {
24406 					if (!(ire1->ire_flags & RTF_MULTIRT))
24407 						continue;
24408 					if (ire1->ire_addr != ire->ire_addr)
24409 						continue;
24410 					if (ire1->ire_marks &
24411 					    (IRE_MARK_CONDEMNED|
24412 						IRE_MARK_HIDDEN))
24413 						continue;
24414 					/*
24415 					 * Ensure we do not exceed the MTU
24416 					 * of the next route.
24417 					 */
24418 					if (ire1->ire_max_frag < max_frag) {
24419 						ip_multirt_bad_mtu(ire1,
24420 						    max_frag);
24421 						continue;
24422 					}
24423 
24424 					/* Got one. */
24425 					IRE_REFHOLD(ire1);
24426 					break;
24427 				}
24428 				IRB_REFRELE(irb);
24429 
24430 				if (ire1 != NULL) {
24431 					next_mp = copyb(mp);
24432 					if ((next_mp == NULL) ||
24433 					    ((mp->b_cont != NULL) &&
24434 					    ((next_mp->b_cont =
24435 					    dupmsg(mp->b_cont)) == NULL))) {
24436 						freemsg(next_mp);
24437 						next_mp = NULL;
24438 						ire_refrele(ire1);
24439 						ire1 = NULL;
24440 					}
24441 				}
24442 
24443 				/* Last multiroute ire; don't loop anymore. */
24444 				if (ire1 == NULL) {
24445 					multirt_send = B_FALSE;
24446 				}
24447 			}
24448 
24449 			/* Update transmit header */
24450 			ll_hdr_len = 0;
24451 			LOCK_IRE_FP_MP(ire);
24452 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24453 			if (ll_hdr_mp != NULL) {
24454 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24455 				ll_hdr_len = MBLKL(ll_hdr_mp);
24456 			} else {
24457 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24458 			}
24459 
24460 			if (!ll_hdr_mp) {
24461 				xmit_mp = mp;
24462 
24463 			/*
24464 			 * We have link-layer header that can fit in
24465 			 * our mblk.
24466 			 */
24467 			} else if (mp->b_datap->db_ref == 1 &&
24468 			    ll_hdr_len != 0 &&
24469 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24470 				/* M_DATA fastpath */
24471 				mp->b_rptr -= ll_hdr_len;
24472 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24473 				    ll_hdr_len);
24474 				xmit_mp = mp;
24475 
24476 			/*
24477 			 * Case of res_mp OR the fastpath mp can't fit
24478 			 * in the mblk
24479 			 */
24480 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24481 				xmit_mp->b_cont = mp;
24482 				if (DB_CRED(mp) != NULL)
24483 					mblk_setcred(xmit_mp, DB_CRED(mp));
24484 				/* Get priority marking, if any. */
24485 				if (DB_TYPE(xmit_mp) == M_DATA)
24486 					xmit_mp->b_band = mp->b_band;
24487 
24488 			/* Corner case if copyb failed */
24489 			} else {
24490 				/*
24491 				 * Exit both the replication and
24492 				 * fragmentation loops.
24493 				 */
24494 				UNLOCK_IRE_FP_MP(ire);
24495 				goto drop_pkt;
24496 			}
24497 			UNLOCK_IRE_FP_MP(ire);
24498 
24499 			mp1 = mp;
24500 			out_ill = (ill_t *)q->q_ptr;
24501 
24502 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24503 
24504 			DTRACE_PROBE4(ip4__physical__out__start,
24505 			    ill_t *, NULL, ill_t *, out_ill,
24506 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24507 
24508 			FW_HOOKS(ip4_physical_out_event,
24509 			    ipv4firewall_physical_out,
24510 			    NULL, out_ill, ipha, xmit_mp, mp);
24511 
24512 			DTRACE_PROBE1(ip4__physical__out__end,
24513 			    mblk_t *, xmit_mp);
24514 
24515 			if (mp != mp1 && hdr_mp == mp1)
24516 				hdr_mp = mp;
24517 			if (mp != mp1 && mp_orig == mp1)
24518 				mp_orig = mp;
24519 
24520 			if (xmit_mp != NULL) {
24521 				putnext(q, xmit_mp);
24522 
24523 				BUMP_MIB(out_ill->ill_ip_mib,
24524 				    ipIfStatsHCOutTransmits);
24525 				UPDATE_MIB(out_ill->ill_ip_mib,
24526 				    ipIfStatsHCOutOctets, ip_len);
24527 
24528 				if (pkt_type != OB_PKT) {
24529 					/*
24530 					 * Update the packet count of trailing
24531 					 * RTF_MULTIRT ires.
24532 					 */
24533 					UPDATE_OB_PKT_COUNT(ire);
24534 				}
24535 			}
24536 
24537 			/* All done if we just consumed the hdr_mp. */
24538 			if (mp == hdr_mp) {
24539 				last_frag = B_TRUE;
24540 				BUMP_MIB(out_ill->ill_ip_mib,
24541 				    ipIfStatsOutFragOKs);
24542 			}
24543 
24544 			if (multirt_send) {
24545 				/*
24546 				 * We are in a multiple send case; look for
24547 				 * the next ire and re-enter the loop.
24548 				 */
24549 				ASSERT(ire1);
24550 				ASSERT(next_mp);
24551 				/* REFRELE the current ire before looping */
24552 				ire_refrele(ire);
24553 				ire = ire1;
24554 				ire1 = NULL;
24555 				q = ire->ire_stq;
24556 				mp = next_mp;
24557 				next_mp = NULL;
24558 			}
24559 		} while (multirt_send);
24560 		/*
24561 		 * Restore the original ire; we need it for the
24562 		 * trailing frags
24563 		 */
24564 		if (save_ire != NULL) {
24565 			ASSERT(ire1 == NULL);
24566 			/* REFRELE the last iterated ire */
24567 			ire_refrele(ire);
24568 			/* save_ire has been REFHOLDed */
24569 			ire = save_ire;
24570 			q = ire->ire_stq;
24571 			save_ire = NULL;
24572 		}
24573 
24574 		if (last_frag) {
24575 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24576 			    "ip_wput_frag_end:(%S)",
24577 			    "consumed hdr_mp");
24578 
24579 			if (first_ire != NULL)
24580 				ire_refrele(first_ire);
24581 			return;
24582 		}
24583 		/* Otherwise, advance and loop. */
24584 		offset += len;
24585 	}
24586 
24587 drop_pkt:
24588 	/* Clean up following allocation failure. */
24589 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24590 	freemsg(mp);
24591 	if (mp != hdr_mp)
24592 		freeb(hdr_mp);
24593 	if (mp != mp_orig)
24594 		freemsg(mp_orig);
24595 
24596 	if (save_ire != NULL)
24597 		IRE_REFRELE(save_ire);
24598 	if (first_ire != NULL)
24599 		ire_refrele(first_ire);
24600 
24601 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24602 	    "ip_wput_frag_end:(%S)",
24603 	    "end--alloc failure");
24604 }
24605 
24606 /*
24607  * Copy the header plus those options which have the copy bit set
24608  */
24609 static mblk_t *
24610 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24611 {
24612 	mblk_t	*mp;
24613 	uchar_t	*up;
24614 
24615 	/*
24616 	 * Quick check if we need to look for options without the copy bit
24617 	 * set
24618 	 */
24619 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24620 	if (!mp)
24621 		return (mp);
24622 	mp->b_rptr += ip_wroff_extra;
24623 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24624 		bcopy(rptr, mp->b_rptr, hdr_len);
24625 		mp->b_wptr += hdr_len + ip_wroff_extra;
24626 		return (mp);
24627 	}
24628 	up  = mp->b_rptr;
24629 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24630 	up += IP_SIMPLE_HDR_LENGTH;
24631 	rptr += IP_SIMPLE_HDR_LENGTH;
24632 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24633 	while (hdr_len > 0) {
24634 		uint32_t optval;
24635 		uint32_t optlen;
24636 
24637 		optval = *rptr;
24638 		if (optval == IPOPT_EOL)
24639 			break;
24640 		if (optval == IPOPT_NOP)
24641 			optlen = 1;
24642 		else
24643 			optlen = rptr[1];
24644 		if (optval & IPOPT_COPY) {
24645 			bcopy(rptr, up, optlen);
24646 			up += optlen;
24647 		}
24648 		rptr += optlen;
24649 		hdr_len -= optlen;
24650 	}
24651 	/*
24652 	 * Make sure that we drop an even number of words by filling
24653 	 * with EOL to the next word boundary.
24654 	 */
24655 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24656 	    hdr_len & 0x3; hdr_len++)
24657 		*up++ = IPOPT_EOL;
24658 	mp->b_wptr = up;
24659 	/* Update header length */
24660 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24661 	return (mp);
24662 }
24663 
24664 /*
24665  * Delivery to local recipients including fanout to multiple recipients.
24666  * Does not do checksumming of UDP/TCP.
24667  * Note: q should be the read side queue for either the ill or conn.
24668  * Note: rq should be the read side q for the lower (ill) stream.
24669  * We don't send packets to IPPF processing, thus the last argument
24670  * to all the fanout calls are B_FALSE.
24671  */
24672 void
24673 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24674     int fanout_flags, zoneid_t zoneid)
24675 {
24676 	uint32_t	protocol;
24677 	mblk_t		*first_mp;
24678 	boolean_t	mctl_present;
24679 	int		ire_type;
24680 #define	rptr	((uchar_t *)ipha)
24681 
24682 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24683 	    "ip_wput_local_start: q %p", q);
24684 
24685 	if (ire != NULL) {
24686 		ire_type = ire->ire_type;
24687 	} else {
24688 		/*
24689 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24690 		 * packet is not multicast, we can't tell the ire type.
24691 		 */
24692 		ASSERT(CLASSD(ipha->ipha_dst));
24693 		ire_type = IRE_BROADCAST;
24694 	}
24695 
24696 	first_mp = mp;
24697 	if (first_mp->b_datap->db_type == M_CTL) {
24698 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24699 		if (!io->ipsec_out_secure) {
24700 			/*
24701 			 * This ipsec_out_t was allocated in ip_wput
24702 			 * for multicast packets to store the ill_index.
24703 			 * As this is being delivered locally, we don't
24704 			 * need this anymore.
24705 			 */
24706 			mp = first_mp->b_cont;
24707 			freeb(first_mp);
24708 			first_mp = mp;
24709 			mctl_present = B_FALSE;
24710 		} else {
24711 			/*
24712 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24713 			 * security properties for the looped-back packet.
24714 			 */
24715 			mctl_present = B_TRUE;
24716 			mp = first_mp->b_cont;
24717 			ASSERT(mp != NULL);
24718 			ipsec_out_to_in(first_mp);
24719 		}
24720 	} else {
24721 		mctl_present = B_FALSE;
24722 	}
24723 
24724 	DTRACE_PROBE4(ip4__loopback__in__start,
24725 	    ill_t *, ill, ill_t *, NULL,
24726 	    ipha_t *, ipha, mblk_t *, first_mp);
24727 
24728 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24729 	    ill, NULL, ipha, first_mp, mp);
24730 
24731 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24732 
24733 	if (first_mp == NULL)
24734 		return;
24735 
24736 	loopback_packets++;
24737 
24738 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24739 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24740 	if (!IS_SIMPLE_IPH(ipha)) {
24741 		ip_wput_local_options(ipha);
24742 	}
24743 
24744 	protocol = ipha->ipha_protocol;
24745 	switch (protocol) {
24746 	case IPPROTO_ICMP: {
24747 		ire_t		*ire_zone;
24748 		ilm_t		*ilm;
24749 		mblk_t		*mp1;
24750 		zoneid_t	last_zoneid;
24751 
24752 		if (CLASSD(ipha->ipha_dst) &&
24753 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24754 			ASSERT(ire_type == IRE_BROADCAST);
24755 			/*
24756 			 * In the multicast case, applications may have joined
24757 			 * the group from different zones, so we need to deliver
24758 			 * the packet to each of them. Loop through the
24759 			 * multicast memberships structures (ilm) on the receive
24760 			 * ill and send a copy of the packet up each matching
24761 			 * one. However, we don't do this for multicasts sent on
24762 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24763 			 * they must stay in the sender's zone.
24764 			 *
24765 			 * ilm_add_v6() ensures that ilms in the same zone are
24766 			 * contiguous in the ill_ilm list. We use this property
24767 			 * to avoid sending duplicates needed when two
24768 			 * applications in the same zone join the same group on
24769 			 * different logical interfaces: we ignore the ilm if
24770 			 * it's zoneid is the same as the last matching one.
24771 			 * In addition, the sending of the packet for
24772 			 * ire_zoneid is delayed until all of the other ilms
24773 			 * have been exhausted.
24774 			 */
24775 			last_zoneid = -1;
24776 			ILM_WALKER_HOLD(ill);
24777 			for (ilm = ill->ill_ilm; ilm != NULL;
24778 			    ilm = ilm->ilm_next) {
24779 				if ((ilm->ilm_flags & ILM_DELETED) ||
24780 				    ipha->ipha_dst != ilm->ilm_addr ||
24781 				    ilm->ilm_zoneid == last_zoneid ||
24782 				    ilm->ilm_zoneid == zoneid ||
24783 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24784 					continue;
24785 				mp1 = ip_copymsg(first_mp);
24786 				if (mp1 == NULL)
24787 					continue;
24788 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24789 				    mctl_present, B_FALSE, ill,
24790 				    ilm->ilm_zoneid);
24791 				last_zoneid = ilm->ilm_zoneid;
24792 			}
24793 			ILM_WALKER_RELE(ill);
24794 			/*
24795 			 * Loopback case: the sending endpoint has
24796 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24797 			 * dispatch the multicast packet to the sending zone.
24798 			 */
24799 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24800 				freemsg(first_mp);
24801 				return;
24802 			}
24803 		} else if (ire_type == IRE_BROADCAST) {
24804 			/*
24805 			 * In the broadcast case, there may be many zones
24806 			 * which need a copy of the packet delivered to them.
24807 			 * There is one IRE_BROADCAST per broadcast address
24808 			 * and per zone; we walk those using a helper function.
24809 			 * In addition, the sending of the packet for zoneid is
24810 			 * delayed until all of the other ires have been
24811 			 * processed.
24812 			 */
24813 			IRB_REFHOLD(ire->ire_bucket);
24814 			ire_zone = NULL;
24815 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24816 			    ire)) != NULL) {
24817 				mp1 = ip_copymsg(first_mp);
24818 				if (mp1 == NULL)
24819 					continue;
24820 
24821 				UPDATE_IB_PKT_COUNT(ire_zone);
24822 				ire_zone->ire_last_used_time = lbolt;
24823 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24824 				    mctl_present, B_FALSE, ill,
24825 				    ire_zone->ire_zoneid);
24826 			}
24827 			IRB_REFRELE(ire->ire_bucket);
24828 		}
24829 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24830 		    0, mctl_present, B_FALSE, ill, zoneid);
24831 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24832 		    "ip_wput_local_end: q %p (%S)",
24833 		    q, "icmp");
24834 		return;
24835 	}
24836 	case IPPROTO_IGMP:
24837 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24838 			/* Bad packet - discarded by igmp_input */
24839 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24840 			    "ip_wput_local_end: q %p (%S)",
24841 			    q, "igmp_input--bad packet");
24842 			if (mctl_present)
24843 				freeb(first_mp);
24844 			return;
24845 		}
24846 		/*
24847 		 * igmp_input() may have returned the pulled up message.
24848 		 * So first_mp and ipha need to be reinitialized.
24849 		 */
24850 		ipha = (ipha_t *)mp->b_rptr;
24851 		if (mctl_present)
24852 			first_mp->b_cont = mp;
24853 		else
24854 			first_mp = mp;
24855 		/* deliver to local raw users */
24856 		break;
24857 	case IPPROTO_ENCAP:
24858 		/*
24859 		 * This case is covered by either ip_fanout_proto, or by
24860 		 * the above security processing for self-tunneled packets.
24861 		 */
24862 		break;
24863 	case IPPROTO_UDP: {
24864 		uint16_t	*up;
24865 		uint32_t	ports;
24866 
24867 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24868 		    UDP_PORTS_OFFSET);
24869 		/* Force a 'valid' checksum. */
24870 		up[3] = 0;
24871 
24872 		ports = *(uint32_t *)up;
24873 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24874 		    (ire_type == IRE_BROADCAST),
24875 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24876 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24877 		    ill, zoneid);
24878 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24879 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24880 		return;
24881 	}
24882 	case IPPROTO_TCP: {
24883 
24884 		/*
24885 		 * For TCP, discard broadcast packets.
24886 		 */
24887 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24888 			freemsg(first_mp);
24889 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
24890 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24891 			return;
24892 		}
24893 
24894 		if (mp->b_datap->db_type == M_DATA) {
24895 			/*
24896 			 * M_DATA mblk, so init mblk (chain) for no struio().
24897 			 */
24898 			mblk_t	*mp1 = mp;
24899 
24900 			do
24901 				mp1->b_datap->db_struioflag = 0;
24902 			while ((mp1 = mp1->b_cont) != NULL);
24903 		}
24904 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24905 		    <= mp->b_wptr);
24906 		ip_fanout_tcp(q, first_mp, ill, ipha,
24907 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24908 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24909 		    mctl_present, B_FALSE, zoneid);
24910 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24911 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24912 		return;
24913 	}
24914 	case IPPROTO_SCTP:
24915 	{
24916 		uint32_t	ports;
24917 
24918 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24919 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24920 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24921 		    IP_FF_IP6INFO,
24922 		    mctl_present, B_FALSE, 0, zoneid);
24923 		return;
24924 	}
24925 
24926 	default:
24927 		break;
24928 	}
24929 	/*
24930 	 * Find a client for some other protocol.  We give
24931 	 * copies to multiple clients, if more than one is
24932 	 * bound.
24933 	 */
24934 	ip_fanout_proto(q, first_mp, ill, ipha,
24935 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24936 	    mctl_present, B_FALSE, ill, zoneid);
24937 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24938 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24939 #undef	rptr
24940 }
24941 
24942 /*
24943  * Update any source route, record route, or timestamp options.
24944  * Check that we are at end of strict source route.
24945  * The options have been sanity checked by ip_wput_options().
24946  */
24947 static void
24948 ip_wput_local_options(ipha_t *ipha)
24949 {
24950 	ipoptp_t	opts;
24951 	uchar_t		*opt;
24952 	uint8_t		optval;
24953 	uint8_t		optlen;
24954 	ipaddr_t	dst;
24955 	uint32_t	ts;
24956 	ire_t		*ire;
24957 	timestruc_t	now;
24958 
24959 	ip2dbg(("ip_wput_local_options\n"));
24960 	for (optval = ipoptp_first(&opts, ipha);
24961 	    optval != IPOPT_EOL;
24962 	    optval = ipoptp_next(&opts)) {
24963 		opt = opts.ipoptp_cur;
24964 		optlen = opts.ipoptp_len;
24965 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24966 		switch (optval) {
24967 			uint32_t off;
24968 		case IPOPT_SSRR:
24969 		case IPOPT_LSRR:
24970 			off = opt[IPOPT_OFFSET];
24971 			off--;
24972 			if (optlen < IP_ADDR_LEN ||
24973 			    off > optlen - IP_ADDR_LEN) {
24974 				/* End of source route */
24975 				break;
24976 			}
24977 			/*
24978 			 * This will only happen if two consecutive entries
24979 			 * in the source route contains our address or if
24980 			 * it is a packet with a loose source route which
24981 			 * reaches us before consuming the whole source route
24982 			 */
24983 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24984 			if (optval == IPOPT_SSRR) {
24985 				return;
24986 			}
24987 			/*
24988 			 * Hack: instead of dropping the packet truncate the
24989 			 * source route to what has been used by filling the
24990 			 * rest with IPOPT_NOP.
24991 			 */
24992 			opt[IPOPT_OLEN] = (uint8_t)off;
24993 			while (off < optlen) {
24994 				opt[off++] = IPOPT_NOP;
24995 			}
24996 			break;
24997 		case IPOPT_RR:
24998 			off = opt[IPOPT_OFFSET];
24999 			off--;
25000 			if (optlen < IP_ADDR_LEN ||
25001 			    off > optlen - IP_ADDR_LEN) {
25002 				/* No more room - ignore */
25003 				ip1dbg((
25004 				    "ip_wput_forward_options: end of RR\n"));
25005 				break;
25006 			}
25007 			dst = htonl(INADDR_LOOPBACK);
25008 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25009 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25010 			break;
25011 		case IPOPT_TS:
25012 			/* Insert timestamp if there is romm */
25013 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25014 			case IPOPT_TS_TSONLY:
25015 				off = IPOPT_TS_TIMELEN;
25016 				break;
25017 			case IPOPT_TS_PRESPEC:
25018 			case IPOPT_TS_PRESPEC_RFC791:
25019 				/* Verify that the address matched */
25020 				off = opt[IPOPT_OFFSET] - 1;
25021 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25022 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25023 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
25024 				if (ire == NULL) {
25025 					/* Not for us */
25026 					break;
25027 				}
25028 				ire_refrele(ire);
25029 				/* FALLTHRU */
25030 			case IPOPT_TS_TSANDADDR:
25031 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25032 				break;
25033 			default:
25034 				/*
25035 				 * ip_*put_options should have already
25036 				 * dropped this packet.
25037 				 */
25038 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25039 				    "unknown IT - bug in ip_wput_options?\n");
25040 				return;	/* Keep "lint" happy */
25041 			}
25042 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25043 				/* Increase overflow counter */
25044 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25045 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25046 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25047 				    (off << 4);
25048 				break;
25049 			}
25050 			off = opt[IPOPT_OFFSET] - 1;
25051 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25052 			case IPOPT_TS_PRESPEC:
25053 			case IPOPT_TS_PRESPEC_RFC791:
25054 			case IPOPT_TS_TSANDADDR:
25055 				dst = htonl(INADDR_LOOPBACK);
25056 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25057 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25058 				/* FALLTHRU */
25059 			case IPOPT_TS_TSONLY:
25060 				off = opt[IPOPT_OFFSET] - 1;
25061 				/* Compute # of milliseconds since midnight */
25062 				gethrestime(&now);
25063 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25064 				    now.tv_nsec / (NANOSEC / MILLISEC);
25065 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25066 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25067 				break;
25068 			}
25069 			break;
25070 		}
25071 	}
25072 }
25073 
25074 /*
25075  * Send out a multicast packet on interface ipif.
25076  * The sender does not have an conn.
25077  * Caller verifies that this isn't a PHYI_LOOPBACK.
25078  */
25079 void
25080 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25081 {
25082 	ipha_t	*ipha;
25083 	ire_t	*ire;
25084 	ipaddr_t	dst;
25085 	mblk_t		*first_mp;
25086 
25087 	/* igmp_sendpkt always allocates a ipsec_out_t */
25088 	ASSERT(mp->b_datap->db_type == M_CTL);
25089 	ASSERT(!ipif->ipif_isv6);
25090 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25091 
25092 	first_mp = mp;
25093 	mp = first_mp->b_cont;
25094 	ASSERT(mp->b_datap->db_type == M_DATA);
25095 	ipha = (ipha_t *)mp->b_rptr;
25096 
25097 	/*
25098 	 * Find an IRE which matches the destination and the outgoing
25099 	 * queue (i.e. the outgoing interface.)
25100 	 */
25101 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25102 		dst = ipif->ipif_pp_dst_addr;
25103 	else
25104 		dst = ipha->ipha_dst;
25105 	/*
25106 	 * The source address has already been initialized by the
25107 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25108 	 * be sufficient rather than MATCH_IRE_IPIF.
25109 	 *
25110 	 * This function is used for sending IGMP packets. We need
25111 	 * to make sure that we send the packet out of the interface
25112 	 * (ipif->ipif_ill) where we joined the group. This is to
25113 	 * prevent from switches doing IGMP snooping to send us multicast
25114 	 * packets for a given group on the interface we have joined.
25115 	 * If we can't find an ire, igmp_sendpkt has already initialized
25116 	 * ipsec_out_attach_if so that this will not be load spread in
25117 	 * ip_newroute_ipif.
25118 	 */
25119 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25120 	    MATCH_IRE_ILL);
25121 	if (!ire) {
25122 		/*
25123 		 * Mark this packet to make it be delivered to
25124 		 * ip_wput_ire after the new ire has been
25125 		 * created.
25126 		 */
25127 		mp->b_prev = NULL;
25128 		mp->b_next = NULL;
25129 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25130 		    zoneid);
25131 		return;
25132 	}
25133 
25134 	/*
25135 	 * Honor the RTF_SETSRC flag; this is the only case
25136 	 * where we force this addr whatever the current src addr is,
25137 	 * because this address is set by igmp_sendpkt(), and
25138 	 * cannot be specified by any user.
25139 	 */
25140 	if (ire->ire_flags & RTF_SETSRC) {
25141 		ipha->ipha_src = ire->ire_src_addr;
25142 	}
25143 
25144 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25145 }
25146 
25147 /*
25148  * NOTE : This function does not ire_refrele the ire argument passed in.
25149  *
25150  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25151  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25152  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25153  * the ire_lock to access the nce_fp_mp in this case.
25154  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25155  * prepending a fastpath message IPQoS processing must precede it, we also set
25156  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25157  * (IPQoS might have set the b_band for CoS marking).
25158  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25159  * must follow it so that IPQoS can mark the dl_priority field for CoS
25160  * marking, if needed.
25161  */
25162 static mblk_t *
25163 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25164 {
25165 	uint_t	hlen;
25166 	ipha_t *ipha;
25167 	mblk_t *mp1;
25168 	boolean_t qos_done = B_FALSE;
25169 	uchar_t	*ll_hdr;
25170 
25171 #define	rptr	((uchar_t *)ipha)
25172 
25173 	ipha = (ipha_t *)mp->b_rptr;
25174 	hlen = 0;
25175 	LOCK_IRE_FP_MP(ire);
25176 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25177 		ASSERT(DB_TYPE(mp1) == M_DATA);
25178 		/* Initiate IPPF processing */
25179 		if ((proc != 0) && IPP_ENABLED(proc)) {
25180 			UNLOCK_IRE_FP_MP(ire);
25181 			ip_process(proc, &mp, ill_index);
25182 			if (mp == NULL)
25183 				return (NULL);
25184 
25185 			ipha = (ipha_t *)mp->b_rptr;
25186 			LOCK_IRE_FP_MP(ire);
25187 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25188 				qos_done = B_TRUE;
25189 				goto no_fp_mp;
25190 			}
25191 			ASSERT(DB_TYPE(mp1) == M_DATA);
25192 		}
25193 		hlen = MBLKL(mp1);
25194 		/*
25195 		 * Check if we have enough room to prepend fastpath
25196 		 * header
25197 		 */
25198 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25199 			ll_hdr = rptr - hlen;
25200 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25201 			/*
25202 			 * Set the b_rptr to the start of the link layer
25203 			 * header
25204 			 */
25205 			mp->b_rptr = ll_hdr;
25206 			mp1 = mp;
25207 		} else {
25208 			mp1 = copyb(mp1);
25209 			if (mp1 == NULL)
25210 				goto unlock_err;
25211 			mp1->b_band = mp->b_band;
25212 			mp1->b_cont = mp;
25213 			/*
25214 			 * certain system generated traffic may not
25215 			 * have cred/label in ip header block. This
25216 			 * is true even for a labeled system. But for
25217 			 * labeled traffic, inherit the label in the
25218 			 * new header.
25219 			 */
25220 			if (DB_CRED(mp) != NULL)
25221 				mblk_setcred(mp1, DB_CRED(mp));
25222 			/*
25223 			 * XXX disable ICK_VALID and compute checksum
25224 			 * here; can happen if nce_fp_mp changes and
25225 			 * it can't be copied now due to insufficient
25226 			 * space. (unlikely, fp mp can change, but it
25227 			 * does not increase in length)
25228 			 */
25229 		}
25230 		UNLOCK_IRE_FP_MP(ire);
25231 	} else {
25232 no_fp_mp:
25233 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25234 		if (mp1 == NULL) {
25235 unlock_err:
25236 			UNLOCK_IRE_FP_MP(ire);
25237 			freemsg(mp);
25238 			return (NULL);
25239 		}
25240 		UNLOCK_IRE_FP_MP(ire);
25241 		mp1->b_cont = mp;
25242 		/*
25243 		 * certain system generated traffic may not
25244 		 * have cred/label in ip header block. This
25245 		 * is true even for a labeled system. But for
25246 		 * labeled traffic, inherit the label in the
25247 		 * new header.
25248 		 */
25249 		if (DB_CRED(mp) != NULL)
25250 			mblk_setcred(mp1, DB_CRED(mp));
25251 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
25252 			ip_process(proc, &mp1, ill_index);
25253 			if (mp1 == NULL)
25254 				return (NULL);
25255 		}
25256 	}
25257 	return (mp1);
25258 #undef rptr
25259 }
25260 
25261 /*
25262  * Finish the outbound IPsec processing for an IPv6 packet. This function
25263  * is called from ipsec_out_process() if the IPsec packet was processed
25264  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25265  * asynchronously.
25266  */
25267 void
25268 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25269     ire_t *ire_arg)
25270 {
25271 	in6_addr_t *v6dstp;
25272 	ire_t *ire;
25273 	mblk_t *mp;
25274 	ip6_t *ip6h1;
25275 	uint_t	ill_index;
25276 	ipsec_out_t *io;
25277 	boolean_t attach_if, hwaccel;
25278 	uint32_t flags = IP6_NO_IPPOLICY;
25279 	int match_flags;
25280 	zoneid_t zoneid;
25281 	boolean_t ill_need_rele = B_FALSE;
25282 	boolean_t ire_need_rele = B_FALSE;
25283 
25284 	mp = ipsec_mp->b_cont;
25285 	ip6h1 = (ip6_t *)mp->b_rptr;
25286 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25287 	ill_index = io->ipsec_out_ill_index;
25288 	if (io->ipsec_out_reachable) {
25289 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25290 	}
25291 	attach_if = io->ipsec_out_attach_if;
25292 	hwaccel = io->ipsec_out_accelerated;
25293 	zoneid = io->ipsec_out_zoneid;
25294 	ASSERT(zoneid != ALL_ZONES);
25295 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25296 	/* Multicast addresses should have non-zero ill_index. */
25297 	v6dstp = &ip6h->ip6_dst;
25298 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25299 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25300 	ASSERT(!attach_if || ill_index != 0);
25301 	if (ill_index != 0) {
25302 		if (ill == NULL) {
25303 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25304 			    B_TRUE);
25305 
25306 			/* Failure case frees things for us. */
25307 			if (ill == NULL)
25308 				return;
25309 
25310 			ill_need_rele = B_TRUE;
25311 		}
25312 		/*
25313 		 * If this packet needs to go out on a particular interface
25314 		 * honor it.
25315 		 */
25316 		if (attach_if) {
25317 			match_flags = MATCH_IRE_ILL;
25318 
25319 			/*
25320 			 * Check if we need an ire that will not be
25321 			 * looked up by anybody else i.e. HIDDEN.
25322 			 */
25323 			if (ill_is_probeonly(ill)) {
25324 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25325 			}
25326 		}
25327 	}
25328 	ASSERT(mp != NULL);
25329 
25330 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25331 		boolean_t unspec_src;
25332 		ipif_t	*ipif;
25333 
25334 		/*
25335 		 * Use the ill_index to get the right ill.
25336 		 */
25337 		unspec_src = io->ipsec_out_unspec_src;
25338 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25339 		if (ipif == NULL) {
25340 			if (ill_need_rele)
25341 				ill_refrele(ill);
25342 			freemsg(ipsec_mp);
25343 			return;
25344 		}
25345 
25346 		if (ire_arg != NULL) {
25347 			ire = ire_arg;
25348 		} else {
25349 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25350 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25351 			ire_need_rele = B_TRUE;
25352 		}
25353 		if (ire != NULL) {
25354 			ipif_refrele(ipif);
25355 			/*
25356 			 * XXX Do the multicast forwarding now, as the IPSEC
25357 			 * processing has been done.
25358 			 */
25359 			goto send;
25360 		}
25361 
25362 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25363 		mp->b_prev = NULL;
25364 		mp->b_next = NULL;
25365 
25366 		/*
25367 		 * If the IPsec packet was processed asynchronously,
25368 		 * drop it now.
25369 		 */
25370 		if (q == NULL) {
25371 			if (ill_need_rele)
25372 				ill_refrele(ill);
25373 			freemsg(ipsec_mp);
25374 			return;
25375 		}
25376 
25377 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25378 		    unspec_src, zoneid);
25379 		ipif_refrele(ipif);
25380 	} else {
25381 		if (attach_if) {
25382 			ipif_t	*ipif;
25383 
25384 			ipif = ipif_get_next_ipif(NULL, ill);
25385 			if (ipif == NULL) {
25386 				if (ill_need_rele)
25387 					ill_refrele(ill);
25388 				freemsg(ipsec_mp);
25389 				return;
25390 			}
25391 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25392 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25393 			ire_need_rele = B_TRUE;
25394 			ipif_refrele(ipif);
25395 		} else {
25396 			if (ire_arg != NULL) {
25397 				ire = ire_arg;
25398 			} else {
25399 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
25400 				ire_need_rele = B_TRUE;
25401 			}
25402 		}
25403 		if (ire != NULL)
25404 			goto send;
25405 		/*
25406 		 * ire disappeared underneath.
25407 		 *
25408 		 * What we need to do here is the ip_newroute
25409 		 * logic to get the ire without doing the IPSEC
25410 		 * processing. Follow the same old path. But this
25411 		 * time, ip_wput or ire_add_then_send will call us
25412 		 * directly as all the IPSEC operations are done.
25413 		 */
25414 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25415 		mp->b_prev = NULL;
25416 		mp->b_next = NULL;
25417 
25418 		/*
25419 		 * If the IPsec packet was processed asynchronously,
25420 		 * drop it now.
25421 		 */
25422 		if (q == NULL) {
25423 			if (ill_need_rele)
25424 				ill_refrele(ill);
25425 			freemsg(ipsec_mp);
25426 			return;
25427 		}
25428 
25429 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25430 		    zoneid);
25431 	}
25432 	if (ill != NULL && ill_need_rele)
25433 		ill_refrele(ill);
25434 	return;
25435 send:
25436 	if (ill != NULL && ill_need_rele)
25437 		ill_refrele(ill);
25438 
25439 	/* Local delivery */
25440 	if (ire->ire_stq == NULL) {
25441 		ill_t	*out_ill;
25442 		ASSERT(q != NULL);
25443 
25444 		/* PFHooks: LOOPBACK_OUT */
25445 		out_ill = ire->ire_ipif->ipif_ill;
25446 
25447 		DTRACE_PROBE4(ip6__loopback__out__start,
25448 		    ill_t *, NULL, ill_t *, out_ill,
25449 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25450 
25451 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25452 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25453 
25454 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25455 
25456 		if (ipsec_mp != NULL)
25457 			ip_wput_local_v6(RD(q), out_ill,
25458 			    ip6h, ipsec_mp, ire, 0);
25459 		if (ire_need_rele)
25460 			ire_refrele(ire);
25461 		return;
25462 	}
25463 	/*
25464 	 * Everything is done. Send it out on the wire.
25465 	 * We force the insertion of a fragment header using the
25466 	 * IPH_FRAG_HDR flag in two cases:
25467 	 * - after reception of an ICMPv6 "packet too big" message
25468 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25469 	 * - for multirouted IPv6 packets, so that the receiver can
25470 	 *   discard duplicates according to their fragment identifier
25471 	 */
25472 	/* XXX fix flow control problems. */
25473 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25474 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25475 		if (hwaccel) {
25476 			/*
25477 			 * hardware acceleration does not handle these
25478 			 * "slow path" cases.
25479 			 */
25480 			/* IPsec KSTATS: should bump bean counter here. */
25481 			if (ire_need_rele)
25482 				ire_refrele(ire);
25483 			freemsg(ipsec_mp);
25484 			return;
25485 		}
25486 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25487 		    (mp->b_cont ? msgdsize(mp) :
25488 		    mp->b_wptr - (uchar_t *)ip6h)) {
25489 			/* IPsec KSTATS: should bump bean counter here. */
25490 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25491 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25492 			    msgdsize(mp)));
25493 			if (ire_need_rele)
25494 				ire_refrele(ire);
25495 			freemsg(ipsec_mp);
25496 			return;
25497 		}
25498 		ASSERT(mp->b_prev == NULL);
25499 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25500 		    ntohs(ip6h->ip6_plen) +
25501 		    IPV6_HDR_LEN, ire->ire_max_frag));
25502 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25503 		    ire->ire_max_frag);
25504 	} else {
25505 		UPDATE_OB_PKT_COUNT(ire);
25506 		ire->ire_last_used_time = lbolt;
25507 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25508 	}
25509 	if (ire_need_rele)
25510 		ire_refrele(ire);
25511 	freeb(ipsec_mp);
25512 }
25513 
25514 void
25515 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25516 {
25517 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25518 	da_ipsec_t *hada;	/* data attributes */
25519 	ill_t *ill = (ill_t *)q->q_ptr;
25520 
25521 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25522 
25523 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25524 		/* IPsec KSTATS: Bump lose counter here! */
25525 		freemsg(mp);
25526 		return;
25527 	}
25528 
25529 	/*
25530 	 * It's an IPsec packet that must be
25531 	 * accelerated by the Provider, and the
25532 	 * outbound ill is IPsec acceleration capable.
25533 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25534 	 * to the ill.
25535 	 * IPsec KSTATS: should bump packet counter here.
25536 	 */
25537 
25538 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25539 	if (hada_mp == NULL) {
25540 		/* IPsec KSTATS: should bump packet counter here. */
25541 		freemsg(mp);
25542 		return;
25543 	}
25544 
25545 	hada_mp->b_datap->db_type = M_CTL;
25546 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25547 	hada_mp->b_cont = mp;
25548 
25549 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25550 	bzero(hada, sizeof (da_ipsec_t));
25551 	hada->da_type = IPHADA_M_CTL;
25552 
25553 	putnext(q, hada_mp);
25554 }
25555 
25556 /*
25557  * Finish the outbound IPsec processing. This function is called from
25558  * ipsec_out_process() if the IPsec packet was processed
25559  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25560  * asynchronously.
25561  */
25562 void
25563 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25564     ire_t *ire_arg)
25565 {
25566 	uint32_t v_hlen_tos_len;
25567 	ipaddr_t	dst;
25568 	ipif_t	*ipif = NULL;
25569 	ire_t *ire;
25570 	ire_t *ire1 = NULL;
25571 	mblk_t *next_mp = NULL;
25572 	uint32_t max_frag;
25573 	boolean_t multirt_send = B_FALSE;
25574 	mblk_t *mp;
25575 	mblk_t *mp1;
25576 	ipha_t *ipha1;
25577 	uint_t	ill_index;
25578 	ipsec_out_t *io;
25579 	boolean_t attach_if;
25580 	int match_flags, offset;
25581 	irb_t *irb = NULL;
25582 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25583 	zoneid_t zoneid;
25584 	uint32_t cksum;
25585 	uint16_t *up;
25586 	ipxmit_state_t	pktxmit_state;
25587 #ifdef	_BIG_ENDIAN
25588 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25589 #else
25590 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25591 #endif
25592 
25593 	mp = ipsec_mp->b_cont;
25594 	ipha1 = (ipha_t *)mp->b_rptr;
25595 	ASSERT(mp != NULL);
25596 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25597 	dst = ipha->ipha_dst;
25598 
25599 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25600 	ill_index = io->ipsec_out_ill_index;
25601 	attach_if = io->ipsec_out_attach_if;
25602 	zoneid = io->ipsec_out_zoneid;
25603 	ASSERT(zoneid != ALL_ZONES);
25604 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25605 	if (ill_index != 0) {
25606 		if (ill == NULL) {
25607 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25608 			    ill_index, B_FALSE);
25609 
25610 			/* Failure case frees things for us. */
25611 			if (ill == NULL)
25612 				return;
25613 
25614 			ill_need_rele = B_TRUE;
25615 		}
25616 		/*
25617 		 * If this packet needs to go out on a particular interface
25618 		 * honor it.
25619 		 */
25620 		if (attach_if) {
25621 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25622 
25623 			/*
25624 			 * Check if we need an ire that will not be
25625 			 * looked up by anybody else i.e. HIDDEN.
25626 			 */
25627 			if (ill_is_probeonly(ill)) {
25628 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25629 			}
25630 		}
25631 	}
25632 
25633 	if (CLASSD(dst)) {
25634 		boolean_t conn_dontroute;
25635 		/*
25636 		 * Use the ill_index to get the right ipif.
25637 		 */
25638 		conn_dontroute = io->ipsec_out_dontroute;
25639 		if (ill_index == 0)
25640 			ipif = ipif_lookup_group(dst, zoneid);
25641 		else
25642 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25643 		if (ipif == NULL) {
25644 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25645 			    " multicast\n"));
25646 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
25647 			freemsg(ipsec_mp);
25648 			goto done;
25649 		}
25650 		/*
25651 		 * ipha_src has already been intialized with the
25652 		 * value of the ipif in ip_wput. All we need now is
25653 		 * an ire to send this downstream.
25654 		 */
25655 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25656 		    MBLK_GETLABEL(mp), match_flags);
25657 		if (ire != NULL) {
25658 			ill_t *ill1;
25659 			/*
25660 			 * Do the multicast forwarding now, as the IPSEC
25661 			 * processing has been done.
25662 			 */
25663 			if (ip_g_mrouter && !conn_dontroute &&
25664 			    (ill1 = ire_to_ill(ire))) {
25665 				if (ip_mforward(ill1, ipha, mp)) {
25666 					freemsg(ipsec_mp);
25667 					ip1dbg(("ip_wput_ipsec_out: mforward "
25668 					    "failed\n"));
25669 					ire_refrele(ire);
25670 					goto done;
25671 				}
25672 			}
25673 			goto send;
25674 		}
25675 
25676 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25677 		mp->b_prev = NULL;
25678 		mp->b_next = NULL;
25679 
25680 		/*
25681 		 * If the IPsec packet was processed asynchronously,
25682 		 * drop it now.
25683 		 */
25684 		if (q == NULL) {
25685 			freemsg(ipsec_mp);
25686 			goto done;
25687 		}
25688 
25689 		/*
25690 		 * We may be using a wrong ipif to create the ire.
25691 		 * But it is okay as the source address is assigned
25692 		 * for the packet already. Next outbound packet would
25693 		 * create the IRE with the right IPIF in ip_wput.
25694 		 *
25695 		 * Also handle RTF_MULTIRT routes.
25696 		 */
25697 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25698 		    zoneid);
25699 	} else {
25700 		if (attach_if) {
25701 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25702 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25703 		} else {
25704 			if (ire_arg != NULL) {
25705 				ire = ire_arg;
25706 				ire_need_rele = B_FALSE;
25707 			} else {
25708 				ire = ire_cache_lookup(dst, zoneid,
25709 				    MBLK_GETLABEL(mp));
25710 			}
25711 		}
25712 		if (ire != NULL) {
25713 			goto send;
25714 		}
25715 
25716 		/*
25717 		 * ire disappeared underneath.
25718 		 *
25719 		 * What we need to do here is the ip_newroute
25720 		 * logic to get the ire without doing the IPSEC
25721 		 * processing. Follow the same old path. But this
25722 		 * time, ip_wput or ire_add_then_put will call us
25723 		 * directly as all the IPSEC operations are done.
25724 		 */
25725 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25726 		mp->b_prev = NULL;
25727 		mp->b_next = NULL;
25728 
25729 		/*
25730 		 * If the IPsec packet was processed asynchronously,
25731 		 * drop it now.
25732 		 */
25733 		if (q == NULL) {
25734 			freemsg(ipsec_mp);
25735 			goto done;
25736 		}
25737 
25738 		/*
25739 		 * Since we're going through ip_newroute() again, we
25740 		 * need to make sure we don't:
25741 		 *
25742 		 *	1.) Trigger the ASSERT() with the ipha_ident
25743 		 *	    overloading.
25744 		 *	2.) Redo transport-layer checksumming, since we've
25745 		 *	    already done all that to get this far.
25746 		 *
25747 		 * The easiest way not do either of the above is to set
25748 		 * the ipha_ident field to IP_HDR_INCLUDED.
25749 		 */
25750 		ipha->ipha_ident = IP_HDR_INCLUDED;
25751 		ip_newroute(q, ipsec_mp, dst, NULL,
25752 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25753 	}
25754 	goto done;
25755 send:
25756 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25757 		/*
25758 		 * ESP NAT-Traversal packet.
25759 		 *
25760 		 * Just do software checksum for now.
25761 		 */
25762 
25763 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25764 		IP_STAT(ip_out_sw_cksum);
25765 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25766 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25767 #define	iphs	((uint16_t *)ipha)
25768 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25769 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25770 		    IP_SIMPLE_HDR_LENGTH);
25771 #undef iphs
25772 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25773 			cksum = 0xFFFF;
25774 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25775 			if (mp1->b_wptr - mp1->b_rptr >=
25776 			    offset + sizeof (uint16_t)) {
25777 				up = (uint16_t *)(mp1->b_rptr + offset);
25778 				*up = cksum;
25779 				break;	/* out of for loop */
25780 			} else {
25781 				offset -= (mp->b_wptr - mp->b_rptr);
25782 			}
25783 	} /* Otherwise, just keep the all-zero checksum. */
25784 
25785 	if (ire->ire_stq == NULL) {
25786 		ill_t	*out_ill;
25787 		/*
25788 		 * Loopbacks go through ip_wput_local except for one case.
25789 		 * We come here if we generate a icmp_frag_needed message
25790 		 * after IPSEC processing is over. When this function calls
25791 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25792 		 * icmp_frag_needed. The message generated comes back here
25793 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25794 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25795 		 * source address as it is usually set in ip_wput_ire. As
25796 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25797 		 * and we end up here. We can't enter ip_wput_ire once the
25798 		 * IPSEC processing is over and hence we need to do it here.
25799 		 */
25800 		ASSERT(q != NULL);
25801 		UPDATE_OB_PKT_COUNT(ire);
25802 		ire->ire_last_used_time = lbolt;
25803 		if (ipha->ipha_src == 0)
25804 			ipha->ipha_src = ire->ire_src_addr;
25805 
25806 		/* PFHooks: LOOPBACK_OUT */
25807 		out_ill = ire->ire_ipif->ipif_ill;
25808 
25809 		DTRACE_PROBE4(ip4__loopback__out__start,
25810 		    ill_t *, NULL, ill_t *, out_ill,
25811 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25812 
25813 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25814 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25815 
25816 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25817 
25818 		if (ipsec_mp != NULL)
25819 			ip_wput_local(RD(q), out_ill,
25820 			    ipha, ipsec_mp, ire, 0, zoneid);
25821 		if (ire_need_rele)
25822 			ire_refrele(ire);
25823 		goto done;
25824 	}
25825 
25826 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25827 		/*
25828 		 * We are through with IPSEC processing.
25829 		 * Fragment this and send it on the wire.
25830 		 */
25831 		if (io->ipsec_out_accelerated) {
25832 			/*
25833 			 * The packet has been accelerated but must
25834 			 * be fragmented. This should not happen
25835 			 * since AH and ESP must not accelerate
25836 			 * packets that need fragmentation, however
25837 			 * the configuration could have changed
25838 			 * since the AH or ESP processing.
25839 			 * Drop packet.
25840 			 * IPsec KSTATS: bump bean counter here.
25841 			 */
25842 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25843 			    "fragmented accelerated packet!\n"));
25844 			freemsg(ipsec_mp);
25845 		} else {
25846 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25847 		}
25848 		if (ire_need_rele)
25849 			ire_refrele(ire);
25850 		goto done;
25851 	}
25852 
25853 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25854 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25855 	    (void *)ire->ire_ipif, (void *)ipif));
25856 
25857 	/*
25858 	 * Multiroute the secured packet, unless IPsec really
25859 	 * requires the packet to go out only through a particular
25860 	 * interface.
25861 	 */
25862 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25863 		ire_t *first_ire;
25864 		irb = ire->ire_bucket;
25865 		ASSERT(irb != NULL);
25866 		/*
25867 		 * This ire has been looked up as the one that
25868 		 * goes through the given ipif;
25869 		 * make sure we do not omit any other multiroute ire
25870 		 * that may be present in the bucket before this one.
25871 		 */
25872 		IRB_REFHOLD(irb);
25873 		for (first_ire = irb->irb_ire;
25874 		    first_ire != NULL;
25875 		    first_ire = first_ire->ire_next) {
25876 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25877 			    (first_ire->ire_addr == ire->ire_addr) &&
25878 			    !(first_ire->ire_marks &
25879 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25880 				break;
25881 		}
25882 
25883 		if ((first_ire != NULL) && (first_ire != ire)) {
25884 			/*
25885 			 * Don't change the ire if the packet must
25886 			 * be fragmented if sent via this new one.
25887 			 */
25888 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25889 				IRE_REFHOLD(first_ire);
25890 				if (ire_need_rele)
25891 					ire_refrele(ire);
25892 				else
25893 					ire_need_rele = B_TRUE;
25894 				ire = first_ire;
25895 			}
25896 		}
25897 		IRB_REFRELE(irb);
25898 
25899 		multirt_send = B_TRUE;
25900 		max_frag = ire->ire_max_frag;
25901 	} else {
25902 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25903 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25904 			    "flag, attach_if %d\n", attach_if));
25905 		}
25906 	}
25907 
25908 	/*
25909 	 * In most cases, the emission loop below is entered only once.
25910 	 * Only in the case where the ire holds the RTF_MULTIRT
25911 	 * flag, we loop to process all RTF_MULTIRT ires in the
25912 	 * bucket, and send the packet through all crossed
25913 	 * RTF_MULTIRT routes.
25914 	 */
25915 	do {
25916 		if (multirt_send) {
25917 			/*
25918 			 * ire1 holds here the next ire to process in the
25919 			 * bucket. If multirouting is expected,
25920 			 * any non-RTF_MULTIRT ire that has the
25921 			 * right destination address is ignored.
25922 			 */
25923 			ASSERT(irb != NULL);
25924 			IRB_REFHOLD(irb);
25925 			for (ire1 = ire->ire_next;
25926 			    ire1 != NULL;
25927 			    ire1 = ire1->ire_next) {
25928 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25929 					continue;
25930 				if (ire1->ire_addr != ire->ire_addr)
25931 					continue;
25932 				if (ire1->ire_marks &
25933 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25934 					continue;
25935 				/* No loopback here */
25936 				if (ire1->ire_stq == NULL)
25937 					continue;
25938 				/*
25939 				 * Ensure we do not exceed the MTU
25940 				 * of the next route.
25941 				 */
25942 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25943 					ip_multirt_bad_mtu(ire1, max_frag);
25944 					continue;
25945 				}
25946 
25947 				IRE_REFHOLD(ire1);
25948 				break;
25949 			}
25950 			IRB_REFRELE(irb);
25951 			if (ire1 != NULL) {
25952 				/*
25953 				 * We are in a multiple send case, need to
25954 				 * make a copy of the packet.
25955 				 */
25956 				next_mp = copymsg(ipsec_mp);
25957 				if (next_mp == NULL) {
25958 					ire_refrele(ire1);
25959 					ire1 = NULL;
25960 				}
25961 			}
25962 		}
25963 		/*
25964 		 * Everything is done. Send it out on the wire
25965 		 *
25966 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25967 		 * either send it on the wire or, in the case of
25968 		 * HW acceleration, call ipsec_hw_putnext.
25969 		 */
25970 		if (ire->ire_nce &&
25971 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25972 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25973 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25974 			/*
25975 			 * If ire's link-layer is unresolved (this
25976 			 * would only happen if the incomplete ire
25977 			 * was added to cachetable via forwarding path)
25978 			 * don't bother going to ip_xmit_v4. Just drop the
25979 			 * packet.
25980 			 * There is a slight risk here, in that, if we
25981 			 * have the forwarding path create an incomplete
25982 			 * IRE, then until the IRE is completed, any
25983 			 * transmitted IPSEC packets will be dropped
25984 			 * instead of being queued waiting for resolution.
25985 			 *
25986 			 * But the likelihood of a forwarding packet and a wput
25987 			 * packet sending to the same dst at the same time
25988 			 * and there not yet be an ARP entry for it is small.
25989 			 * Furthermore, if this actually happens, it might
25990 			 * be likely that wput would generate multiple
25991 			 * packets (and forwarding would also have a train
25992 			 * of packets) for that destination. If this is
25993 			 * the case, some of them would have been dropped
25994 			 * anyway, since ARP only queues a few packets while
25995 			 * waiting for resolution
25996 			 *
25997 			 * NOTE: We should really call ip_xmit_v4,
25998 			 * and let it queue the packet and send the
25999 			 * ARP query and have ARP come back thus:
26000 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26001 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26002 			 * hw accel work. But it's too complex to get
26003 			 * the IPsec hw  acceleration approach to fit
26004 			 * well with ip_xmit_v4 doing ARP without
26005 			 * doing IPSEC simplification. For now, we just
26006 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26007 			 * that we can continue with the send on the next
26008 			 * attempt.
26009 			 *
26010 			 * XXX THis should be revisited, when
26011 			 * the IPsec/IP interaction is cleaned up
26012 			 */
26013 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26014 			    " - dropping packet\n"));
26015 			freemsg(ipsec_mp);
26016 			/*
26017 			 * Call ip_xmit_v4() to trigger ARP query
26018 			 * in case the nce_state is ND_INITIAL
26019 			 */
26020 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26021 			goto drop_pkt;
26022 		}
26023 
26024 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26025 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26026 		    mblk_t *, mp);
26027 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
26028 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
26029 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26030 		if (mp == NULL)
26031 			goto drop_pkt;
26032 
26033 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26034 		pktxmit_state = ip_xmit_v4(mp, ire,
26035 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26036 
26037 		if ((pktxmit_state ==  SEND_FAILED) ||
26038 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26039 
26040 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26041 drop_pkt:
26042 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26043 			    ipIfStatsOutDiscards);
26044 			if (ire_need_rele)
26045 				ire_refrele(ire);
26046 			if (ire1 != NULL) {
26047 				ire_refrele(ire1);
26048 				freemsg(next_mp);
26049 			}
26050 			goto done;
26051 		}
26052 
26053 		freeb(ipsec_mp);
26054 		if (ire_need_rele)
26055 			ire_refrele(ire);
26056 
26057 		if (ire1 != NULL) {
26058 			ire = ire1;
26059 			ire_need_rele = B_TRUE;
26060 			ASSERT(next_mp);
26061 			ipsec_mp = next_mp;
26062 			mp = ipsec_mp->b_cont;
26063 			ire1 = NULL;
26064 			next_mp = NULL;
26065 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26066 		} else {
26067 			multirt_send = B_FALSE;
26068 		}
26069 	} while (multirt_send);
26070 done:
26071 	if (ill != NULL && ill_need_rele)
26072 		ill_refrele(ill);
26073 	if (ipif != NULL)
26074 		ipif_refrele(ipif);
26075 }
26076 
26077 /*
26078  * Get the ill corresponding to the specified ire, and compare its
26079  * capabilities with the protocol and algorithms specified by the
26080  * the SA obtained from ipsec_out. If they match, annotate the
26081  * ipsec_out structure to indicate that the packet needs acceleration.
26082  *
26083  *
26084  * A packet is eligible for outbound hardware acceleration if the
26085  * following conditions are satisfied:
26086  *
26087  * 1. the packet will not be fragmented
26088  * 2. the provider supports the algorithm
26089  * 3. there is no pending control message being exchanged
26090  * 4. snoop is not attached
26091  * 5. the destination address is not a broadcast or multicast address.
26092  *
26093  * Rationale:
26094  *	- Hardware drivers do not support fragmentation with
26095  *	  the current interface.
26096  *	- snoop, multicast, and broadcast may result in exposure of
26097  *	  a cleartext datagram.
26098  * We check all five of these conditions here.
26099  *
26100  * XXX would like to nuke "ire_t *" parameter here; problem is that
26101  * IRE is only way to figure out if a v4 address is a broadcast and
26102  * thus ineligible for acceleration...
26103  */
26104 static void
26105 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26106 {
26107 	ipsec_out_t *io;
26108 	mblk_t *data_mp;
26109 	uint_t plen, overhead;
26110 
26111 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26112 		return;
26113 
26114 	if (ill == NULL)
26115 		return;
26116 
26117 	/*
26118 	 * Destination address is a broadcast or multicast.  Punt.
26119 	 */
26120 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26121 	    IRE_LOCAL)))
26122 		return;
26123 
26124 	data_mp = ipsec_mp->b_cont;
26125 
26126 	if (ill->ill_isv6) {
26127 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26128 
26129 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26130 			return;
26131 
26132 		plen = ip6h->ip6_plen;
26133 	} else {
26134 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26135 
26136 		if (CLASSD(ipha->ipha_dst))
26137 			return;
26138 
26139 		plen = ipha->ipha_length;
26140 	}
26141 	/*
26142 	 * Is there a pending DLPI control message being exchanged
26143 	 * between IP/IPsec and the DLS Provider? If there is, it
26144 	 * could be a SADB update, and the state of the DLS Provider
26145 	 * SADB might not be in sync with the SADB maintained by
26146 	 * IPsec. To avoid dropping packets or using the wrong keying
26147 	 * material, we do not accelerate this packet.
26148 	 */
26149 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26150 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26151 		    "ill_dlpi_pending! don't accelerate packet\n"));
26152 		return;
26153 	}
26154 
26155 	/*
26156 	 * Is the Provider in promiscous mode? If it does, we don't
26157 	 * accelerate the packet since it will bounce back up to the
26158 	 * listeners in the clear.
26159 	 */
26160 	if (ill->ill_promisc_on_phys) {
26161 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26162 		    "ill in promiscous mode, don't accelerate packet\n"));
26163 		return;
26164 	}
26165 
26166 	/*
26167 	 * Will the packet require fragmentation?
26168 	 */
26169 
26170 	/*
26171 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26172 	 * as is used elsewhere.
26173 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26174 	 *	+ 2-byte trailer
26175 	 */
26176 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26177 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26178 
26179 	if ((plen + overhead) > ill->ill_max_mtu)
26180 		return;
26181 
26182 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26183 
26184 	/*
26185 	 * Can the ill accelerate this IPsec protocol and algorithm
26186 	 * specified by the SA?
26187 	 */
26188 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26189 	    ill->ill_isv6, sa)) {
26190 		return;
26191 	}
26192 
26193 	/*
26194 	 * Tell AH or ESP that the outbound ill is capable of
26195 	 * accelerating this packet.
26196 	 */
26197 	io->ipsec_out_is_capab_ill = B_TRUE;
26198 }
26199 
26200 /*
26201  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26202  *
26203  * If this function returns B_TRUE, the requested SA's have been filled
26204  * into the ipsec_out_*_sa pointers.
26205  *
26206  * If the function returns B_FALSE, the packet has been "consumed", most
26207  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26208  *
26209  * The SA references created by the protocol-specific "select"
26210  * function will be released when the ipsec_mp is freed, thanks to the
26211  * ipsec_out_free destructor -- see spd.c.
26212  */
26213 static boolean_t
26214 ipsec_out_select_sa(mblk_t *ipsec_mp)
26215 {
26216 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26217 	ipsec_out_t *io;
26218 	ipsec_policy_t *pp;
26219 	ipsec_action_t *ap;
26220 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26221 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26222 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26223 
26224 	if (!io->ipsec_out_secure) {
26225 		/*
26226 		 * We came here by mistake.
26227 		 * Don't bother with ipsec processing
26228 		 * We should "discourage" this path in the future.
26229 		 */
26230 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26231 		return (B_FALSE);
26232 	}
26233 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26234 	ASSERT((io->ipsec_out_policy != NULL) ||
26235 	    (io->ipsec_out_act != NULL));
26236 
26237 	ASSERT(io->ipsec_out_failed == B_FALSE);
26238 
26239 	/*
26240 	 * IPSEC processing has started.
26241 	 */
26242 	io->ipsec_out_proc_begin = B_TRUE;
26243 	ap = io->ipsec_out_act;
26244 	if (ap == NULL) {
26245 		pp = io->ipsec_out_policy;
26246 		ASSERT(pp != NULL);
26247 		ap = pp->ipsp_act;
26248 		ASSERT(ap != NULL);
26249 	}
26250 
26251 	/*
26252 	 * We have an action.  now, let's select SA's.
26253 	 * (In the future, we can cache this in the conn_t..)
26254 	 */
26255 	if (ap->ipa_want_esp) {
26256 		if (io->ipsec_out_esp_sa == NULL) {
26257 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26258 			    IPPROTO_ESP);
26259 		}
26260 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26261 	}
26262 
26263 	if (ap->ipa_want_ah) {
26264 		if (io->ipsec_out_ah_sa == NULL) {
26265 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26266 			    IPPROTO_AH);
26267 		}
26268 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26269 		/*
26270 		 * The ESP and AH processing order needs to be preserved
26271 		 * when both protocols are required (ESP should be applied
26272 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26273 		 * when both ESP and AH are required, and an AH ACQUIRE
26274 		 * is needed.
26275 		 */
26276 		if (ap->ipa_want_esp && need_ah_acquire)
26277 			need_esp_acquire = B_TRUE;
26278 	}
26279 
26280 	/*
26281 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26282 	 * Release SAs that got referenced, but will not be used until we
26283 	 * acquire _all_ of the SAs we need.
26284 	 */
26285 	if (need_ah_acquire || need_esp_acquire) {
26286 		if (io->ipsec_out_ah_sa != NULL) {
26287 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26288 			io->ipsec_out_ah_sa = NULL;
26289 		}
26290 		if (io->ipsec_out_esp_sa != NULL) {
26291 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26292 			io->ipsec_out_esp_sa = NULL;
26293 		}
26294 
26295 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26296 		return (B_FALSE);
26297 	}
26298 
26299 	return (B_TRUE);
26300 }
26301 
26302 /*
26303  * Process an IPSEC_OUT message and see what you can
26304  * do with it.
26305  * IPQoS Notes:
26306  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26307  * IPSec.
26308  * XXX would like to nuke ire_t.
26309  * XXX ill_index better be "real"
26310  */
26311 void
26312 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26313 {
26314 	ipsec_out_t *io;
26315 	ipsec_policy_t *pp;
26316 	ipsec_action_t *ap;
26317 	ipha_t *ipha;
26318 	ip6_t *ip6h;
26319 	mblk_t *mp;
26320 	ill_t *ill;
26321 	zoneid_t zoneid;
26322 	ipsec_status_t ipsec_rc;
26323 	boolean_t ill_need_rele = B_FALSE;
26324 
26325 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26326 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26327 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26328 	mp = ipsec_mp->b_cont;
26329 
26330 	/*
26331 	 * Initiate IPPF processing. We do it here to account for packets
26332 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26333 	 * We can check for ipsec_out_proc_begin even for such packets, as
26334 	 * they will always be false (asserted below).
26335 	 */
26336 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
26337 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26338 		    io->ipsec_out_ill_index : ill_index);
26339 		if (mp == NULL) {
26340 			ip2dbg(("ipsec_out_process: packet dropped "\
26341 			    "during IPPF processing\n"));
26342 			freeb(ipsec_mp);
26343 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26344 			return;
26345 		}
26346 	}
26347 
26348 	if (!io->ipsec_out_secure) {
26349 		/*
26350 		 * We came here by mistake.
26351 		 * Don't bother with ipsec processing
26352 		 * Should "discourage" this path in the future.
26353 		 */
26354 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26355 		goto done;
26356 	}
26357 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26358 	ASSERT((io->ipsec_out_policy != NULL) ||
26359 	    (io->ipsec_out_act != NULL));
26360 	ASSERT(io->ipsec_out_failed == B_FALSE);
26361 
26362 	if (!ipsec_loaded()) {
26363 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26364 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26365 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26366 		} else {
26367 			BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
26368 		}
26369 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26370 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
26371 		return;
26372 	}
26373 
26374 	/*
26375 	 * IPSEC processing has started.
26376 	 */
26377 	io->ipsec_out_proc_begin = B_TRUE;
26378 	ap = io->ipsec_out_act;
26379 	if (ap == NULL) {
26380 		pp = io->ipsec_out_policy;
26381 		ASSERT(pp != NULL);
26382 		ap = pp->ipsp_act;
26383 		ASSERT(ap != NULL);
26384 	}
26385 
26386 	/*
26387 	 * Save the outbound ill index. When the packet comes back
26388 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26389 	 * before sending it the accelerated packet.
26390 	 */
26391 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26392 		int ifindex;
26393 		ill = ire_to_ill(ire);
26394 		ifindex = ill->ill_phyint->phyint_ifindex;
26395 		io->ipsec_out_capab_ill_index = ifindex;
26396 	}
26397 
26398 	/*
26399 	 * The order of processing is first insert a IP header if needed.
26400 	 * Then insert the ESP header and then the AH header.
26401 	 */
26402 	if ((io->ipsec_out_se_done == B_FALSE) &&
26403 	    (ap->ipa_want_se)) {
26404 		/*
26405 		 * First get the outer IP header before sending
26406 		 * it to ESP.
26407 		 */
26408 		ipha_t *oipha, *iipha;
26409 		mblk_t *outer_mp, *inner_mp;
26410 
26411 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26412 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26413 			    "ipsec_out_process: "
26414 			    "Self-Encapsulation failed: Out of memory\n");
26415 			freemsg(ipsec_mp);
26416 			if (ill != NULL) {
26417 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26418 			} else {
26419 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26420 			}
26421 			return;
26422 		}
26423 		inner_mp = ipsec_mp->b_cont;
26424 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26425 		oipha = (ipha_t *)outer_mp->b_rptr;
26426 		iipha = (ipha_t *)inner_mp->b_rptr;
26427 		*oipha = *iipha;
26428 		outer_mp->b_wptr += sizeof (ipha_t);
26429 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26430 		    sizeof (ipha_t));
26431 		oipha->ipha_protocol = IPPROTO_ENCAP;
26432 		oipha->ipha_version_and_hdr_length =
26433 		    IP_SIMPLE_HDR_VERSION;
26434 		oipha->ipha_hdr_checksum = 0;
26435 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26436 		outer_mp->b_cont = inner_mp;
26437 		ipsec_mp->b_cont = outer_mp;
26438 
26439 		io->ipsec_out_se_done = B_TRUE;
26440 		io->ipsec_out_tunnel = B_TRUE;
26441 	}
26442 
26443 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26444 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26445 	    !ipsec_out_select_sa(ipsec_mp))
26446 		return;
26447 
26448 	/*
26449 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26450 	 * to do the heavy lifting.
26451 	 */
26452 	zoneid = io->ipsec_out_zoneid;
26453 	ASSERT(zoneid != ALL_ZONES);
26454 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26455 		ASSERT(io->ipsec_out_esp_sa != NULL);
26456 		io->ipsec_out_esp_done = B_TRUE;
26457 		/*
26458 		 * Note that since hw accel can only apply one transform,
26459 		 * not two, we skip hw accel for ESP if we also have AH
26460 		 * This is an design limitation of the interface
26461 		 * which should be revisited.
26462 		 */
26463 		ASSERT(ire != NULL);
26464 		if (io->ipsec_out_ah_sa == NULL) {
26465 			ill = (ill_t *)ire->ire_stq->q_ptr;
26466 			ipsec_out_is_accelerated(ipsec_mp,
26467 			    io->ipsec_out_esp_sa, ill, ire);
26468 		}
26469 
26470 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26471 		switch (ipsec_rc) {
26472 		case IPSEC_STATUS_SUCCESS:
26473 			break;
26474 		case IPSEC_STATUS_FAILED:
26475 			if (ill != NULL) {
26476 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26477 			} else {
26478 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26479 			}
26480 			/* FALLTHRU */
26481 		case IPSEC_STATUS_PENDING:
26482 			return;
26483 		}
26484 	}
26485 
26486 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26487 		ASSERT(io->ipsec_out_ah_sa != NULL);
26488 		io->ipsec_out_ah_done = B_TRUE;
26489 		if (ire == NULL) {
26490 			int idx = io->ipsec_out_capab_ill_index;
26491 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26492 			    NULL, NULL, NULL, NULL);
26493 			ill_need_rele = B_TRUE;
26494 		} else {
26495 			ill = (ill_t *)ire->ire_stq->q_ptr;
26496 		}
26497 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26498 		    ire);
26499 
26500 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26501 		switch (ipsec_rc) {
26502 		case IPSEC_STATUS_SUCCESS:
26503 			break;
26504 		case IPSEC_STATUS_FAILED:
26505 			if (ill != NULL) {
26506 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26507 			} else {
26508 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26509 			}
26510 			/* FALLTHRU */
26511 		case IPSEC_STATUS_PENDING:
26512 			if (ill != NULL && ill_need_rele)
26513 				ill_refrele(ill);
26514 			return;
26515 		}
26516 	}
26517 	/*
26518 	 * We are done with IPSEC processing. Send it over
26519 	 * the wire.
26520 	 */
26521 done:
26522 	mp = ipsec_mp->b_cont;
26523 	ipha = (ipha_t *)mp->b_rptr;
26524 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26525 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26526 	} else {
26527 		ip6h = (ip6_t *)ipha;
26528 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26529 	}
26530 	if (ill != NULL && ill_need_rele)
26531 		ill_refrele(ill);
26532 }
26533 
26534 /* ARGSUSED */
26535 void
26536 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26537 {
26538 	opt_restart_t	*or;
26539 	int	err;
26540 	conn_t	*connp;
26541 
26542 	ASSERT(CONN_Q(q));
26543 	connp = Q_TO_CONN(q);
26544 
26545 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26546 	or = (opt_restart_t *)first_mp->b_rptr;
26547 	/*
26548 	 * We don't need to pass any credentials here since this is just
26549 	 * a restart. The credentials are passed in when svr4_optcom_req
26550 	 * is called the first time (from ip_wput_nondata).
26551 	 */
26552 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26553 		err = svr4_optcom_req(q, first_mp, NULL,
26554 		    &ip_opt_obj);
26555 	} else {
26556 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26557 		err = tpi_optcom_req(q, first_mp, NULL,
26558 		    &ip_opt_obj);
26559 	}
26560 	if (err != EINPROGRESS) {
26561 		/* operation is done */
26562 		CONN_OPER_PENDING_DONE(connp);
26563 	}
26564 }
26565 
26566 /*
26567  * ioctls that go through a down/up sequence may need to wait for the down
26568  * to complete. This involves waiting for the ire and ipif refcnts to go down
26569  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26570  */
26571 /* ARGSUSED */
26572 void
26573 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26574 {
26575 	struct iocblk *iocp;
26576 	mblk_t *mp1;
26577 	ipif_t	*ipif;
26578 	ip_ioctl_cmd_t *ipip;
26579 	int err;
26580 	sin_t	*sin;
26581 	struct lifreq *lifr;
26582 	struct ifreq *ifr;
26583 
26584 	iocp = (struct iocblk *)mp->b_rptr;
26585 	ASSERT(ipsq != NULL);
26586 	/* Existence of mp1 verified in ip_wput_nondata */
26587 	mp1 = mp->b_cont->b_cont;
26588 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26589 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26590 		ill_t *ill;
26591 		/*
26592 		 * Special case where ipsq_current_ipif may not be set.
26593 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26594 		 * ill could also have become part of a ipmp group in the
26595 		 * process, we are here as were not able to complete the
26596 		 * operation in ipif_set_values because we could not become
26597 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26598 		 * will not be set so we need to set it.
26599 		 */
26600 		ill = (ill_t *)q->q_ptr;
26601 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26602 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26603 	}
26604 
26605 	ipif = ipsq->ipsq_current_ipif;
26606 	ASSERT(ipif != NULL);
26607 	if (ipip->ipi_cmd_type == IF_CMD) {
26608 		/* This a old style SIOC[GS]IF* command */
26609 		ifr = (struct ifreq *)mp1->b_rptr;
26610 		sin = (sin_t *)&ifr->ifr_addr;
26611 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26612 		/* This a new style SIOC[GS]LIF* command */
26613 		lifr = (struct lifreq *)mp1->b_rptr;
26614 		sin = (sin_t *)&lifr->lifr_addr;
26615 	} else {
26616 		sin = NULL;
26617 	}
26618 
26619 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26620 	    (void *)mp1->b_rptr);
26621 
26622 	/* SIOCLIFREMOVEIF could have removed the ipif */
26623 	ip_ioctl_finish(q, mp, err,
26624 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26625 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26626 }
26627 
26628 /*
26629  * ioctl processing
26630  *
26631  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26632  * the ioctl command in the ioctl tables and determines the copyin data size
26633  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26634  * size.
26635  *
26636  * ioctl processing then continues when the M_IOCDATA makes its way down.
26637  * Now the ioctl is looked up again in the ioctl table, and its properties are
26638  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26639  * and the general ioctl processing function ip_process_ioctl is called.
26640  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26641  * so goes thru the serialization primitive ipsq_try_enter. Then the
26642  * appropriate function to handle the ioctl is called based on the entry in
26643  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26644  * which also refreleases the 'conn' that was refheld at the start of the
26645  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26646  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26647  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26648  *
26649  * Many exclusive ioctls go thru an internal down up sequence as part of
26650  * the operation. For example an attempt to change the IP address of an
26651  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26652  * does all the cleanup such as deleting all ires that use this address.
26653  * Then we need to wait till all references to the interface go away.
26654  */
26655 void
26656 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26657 {
26658 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26659 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26660 	cmd_info_t ci;
26661 	int err;
26662 	boolean_t entered_ipsq = B_FALSE;
26663 
26664 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26665 
26666 	if (ipip == NULL)
26667 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26668 
26669 	/*
26670 	 * SIOCLIFADDIF needs to go thru a special path since the
26671 	 * ill may not exist yet. This happens in the case of lo0
26672 	 * which is created using this ioctl.
26673 	 */
26674 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26675 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26676 		ip_ioctl_finish(q, mp, err,
26677 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26678 		    NULL, NULL);
26679 		return;
26680 	}
26681 
26682 	ci.ci_ipif = NULL;
26683 	switch (ipip->ipi_cmd_type) {
26684 	case IF_CMD:
26685 	case LIF_CMD:
26686 		/*
26687 		 * ioctls that pass in a [l]ifreq appear here.
26688 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26689 		 * ci.ci_ipif
26690 		 */
26691 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26692 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26693 		if (err != 0) {
26694 			ip_ioctl_finish(q, mp, err,
26695 			    ipip->ipi_flags & IPI_GET_CMD ?
26696 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26697 			return;
26698 		}
26699 		ASSERT(ci.ci_ipif != NULL);
26700 		break;
26701 
26702 	case TUN_CMD:
26703 		/*
26704 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26705 		 * a refheld ipif in ci.ci_ipif
26706 		 */
26707 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26708 		if (err != 0) {
26709 			ip_ioctl_finish(q, mp, err,
26710 			    ipip->ipi_flags & IPI_GET_CMD ?
26711 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26712 			return;
26713 		}
26714 		ASSERT(ci.ci_ipif != NULL);
26715 		break;
26716 
26717 	case MISC_CMD:
26718 		/*
26719 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26720 		 * For eg. SIOCGLIFCONF will appear here.
26721 		 */
26722 		switch (ipip->ipi_cmd) {
26723 		case IF_UNITSEL:
26724 			/* ioctl comes down the ill */
26725 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26726 			ipif_refhold(ci.ci_ipif);
26727 			break;
26728 		case SIOCGMSFILTER:
26729 		case SIOCSMSFILTER:
26730 		case SIOCGIPMSFILTER:
26731 		case SIOCSIPMSFILTER:
26732 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26733 			    ip_process_ioctl);
26734 			if (err != 0) {
26735 				ip_ioctl_finish(q, mp, err,
26736 				    ipip->ipi_flags & IPI_GET_CMD ?
26737 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26738 				return;
26739 			}
26740 			break;
26741 		}
26742 		err = 0;
26743 		ci.ci_sin = NULL;
26744 		ci.ci_sin6 = NULL;
26745 		ci.ci_lifr = NULL;
26746 		break;
26747 	}
26748 
26749 	/*
26750 	 * If ipsq is non-null, we are already being called exclusively
26751 	 */
26752 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26753 	if (!(ipip->ipi_flags & IPI_WR)) {
26754 		/*
26755 		 * A return value of EINPROGRESS means the ioctl is
26756 		 * either queued and waiting for some reason or has
26757 		 * already completed.
26758 		 */
26759 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26760 		    ci.ci_lifr);
26761 		if (ci.ci_ipif != NULL)
26762 			ipif_refrele(ci.ci_ipif);
26763 		ip_ioctl_finish(q, mp, err,
26764 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26765 		    NULL, NULL);
26766 		return;
26767 	}
26768 
26769 	ASSERT(ci.ci_ipif != NULL);
26770 
26771 	if (ipsq == NULL) {
26772 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26773 		    ip_process_ioctl, NEW_OP, B_TRUE);
26774 		entered_ipsq = B_TRUE;
26775 	}
26776 	/*
26777 	 * Release the ipif so that ipif_down and friends that wait for
26778 	 * references to go away are not misled about the current ipif_refcnt
26779 	 * values. We are writer so we can access the ipif even after releasing
26780 	 * the ipif.
26781 	 */
26782 	ipif_refrele(ci.ci_ipif);
26783 	if (ipsq == NULL)
26784 		return;
26785 
26786 	mutex_enter(&ipsq->ipsq_lock);
26787 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26788 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26789 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26790 	mutex_exit(&ipsq->ipsq_lock);
26791 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26792 	/*
26793 	 * For most set ioctls that come here, this serves as a single point
26794 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26795 	 * be any new references to the ipif. This helps functions that go
26796 	 * through this path and end up trying to wait for the refcnts
26797 	 * associated with the ipif to go down to zero. Some exceptions are
26798 	 * Failover, Failback, and Groupname commands that operate on more than
26799 	 * just the ci.ci_ipif. These commands internally determine the
26800 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26801 	 * flags on that set. Another exception is the Removeif command that
26802 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26803 	 * ipif to operate on.
26804 	 */
26805 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26806 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26807 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26808 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26809 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26810 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26811 
26812 	/*
26813 	 * A return value of EINPROGRESS means the ioctl is
26814 	 * either queued and waiting for some reason or has
26815 	 * already completed.
26816 	 */
26817 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26818 	    ci.ci_lifr);
26819 
26820 	/* SIOCLIFREMOVEIF could have removed the ipif */
26821 	ip_ioctl_finish(q, mp, err,
26822 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26823 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26824 
26825 	if (entered_ipsq)
26826 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26827 }
26828 
26829 /*
26830  * Complete the ioctl. Typically ioctls use the mi package and need to
26831  * do mi_copyout/mi_copy_done.
26832  */
26833 void
26834 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26835     ipif_t *ipif, ipsq_t *ipsq)
26836 {
26837 	conn_t	*connp = NULL;
26838 	hook_nic_event_t *info;
26839 
26840 	if (err == EINPROGRESS)
26841 		return;
26842 
26843 	if (CONN_Q(q)) {
26844 		connp = Q_TO_CONN(q);
26845 		ASSERT(connp->conn_ref >= 2);
26846 	}
26847 
26848 	switch (mode) {
26849 	case COPYOUT:
26850 		if (err == 0)
26851 			mi_copyout(q, mp);
26852 		else
26853 			mi_copy_done(q, mp, err);
26854 		break;
26855 
26856 	case NO_COPYOUT:
26857 		mi_copy_done(q, mp, err);
26858 		break;
26859 
26860 	default:
26861 		/* An ioctl aborted through a conn close would take this path */
26862 		break;
26863 	}
26864 
26865 	/*
26866 	 * The refhold placed at the start of the ioctl is released here.
26867 	 */
26868 	if (connp != NULL)
26869 		CONN_OPER_PENDING_DONE(connp);
26870 
26871 	/*
26872 	 * If the ioctl were an exclusive ioctl it would have set
26873 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26874 	 */
26875 	if (ipif != NULL) {
26876 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26877 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26878 
26879 		/*
26880 		 * Unhook the nic event message from the ill and enqueue it into
26881 		 * the nic event taskq.
26882 		 */
26883 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26884 			if (ddi_taskq_dispatch(eventq_queue_nic,
26885 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26886 			    == DDI_FAILURE) {
26887 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26888 				    "failed\n"));
26889 				if (info->hne_data != NULL)
26890 					kmem_free(info->hne_data,
26891 					    info->hne_datalen);
26892 				kmem_free(info, sizeof (hook_nic_event_t));
26893 			}
26894 
26895 			ipif->ipif_ill->ill_nic_event_info = NULL;
26896 		}
26897 
26898 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26899 	}
26900 
26901 	/*
26902 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26903 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26904 	 * entering the ipsq
26905 	 */
26906 	if (ipsq != NULL) {
26907 		mutex_enter(&ipsq->ipsq_lock);
26908 		ipsq->ipsq_current_ipif = NULL;
26909 		mutex_exit(&ipsq->ipsq_lock);
26910 	}
26911 }
26912 
26913 /*
26914  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26915  */
26916 /* ARGSUSED */
26917 void
26918 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26919 {
26920 	conn_t *connp = arg;
26921 	tcp_t	*tcp;
26922 
26923 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26924 	tcp = connp->conn_tcp;
26925 
26926 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26927 		freemsg(mp);
26928 	else
26929 		tcp_rput_other(tcp, mp);
26930 	CONN_OPER_PENDING_DONE(connp);
26931 }
26932 
26933 /* Called from ip_wput for all non data messages */
26934 /* ARGSUSED */
26935 void
26936 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26937 {
26938 	mblk_t		*mp1;
26939 	ire_t		*ire, *fake_ire;
26940 	ill_t		*ill;
26941 	struct iocblk	*iocp;
26942 	ip_ioctl_cmd_t	*ipip;
26943 	cred_t		*cr;
26944 	conn_t		*connp = NULL;
26945 	int		cmd, err;
26946 	nce_t		*nce;
26947 	ipif_t		*ipif;
26948 
26949 	if (CONN_Q(q))
26950 		connp = Q_TO_CONN(q);
26951 
26952 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26953 
26954 	/* Check if it is a queue to /dev/sctp. */
26955 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26956 	    connp->conn_rq == NULL) {
26957 		sctp_wput(q, mp);
26958 		return;
26959 	}
26960 
26961 	switch (DB_TYPE(mp)) {
26962 	case M_IOCTL:
26963 		/*
26964 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26965 		 * will arrange to copy in associated control structures.
26966 		 */
26967 		ip_sioctl_copyin_setup(q, mp);
26968 		return;
26969 	case M_IOCDATA:
26970 		/*
26971 		 * Ensure that this is associated with one of our trans-
26972 		 * parent ioctls.  If it's not ours, discard it if we're
26973 		 * running as a driver, or pass it on if we're a module.
26974 		 */
26975 		iocp = (struct iocblk *)mp->b_rptr;
26976 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26977 		if (ipip == NULL) {
26978 			if (q->q_next == NULL) {
26979 				goto nak;
26980 			} else {
26981 				putnext(q, mp);
26982 			}
26983 			return;
26984 		} else if ((q->q_next != NULL) &&
26985 		    !(ipip->ipi_flags & IPI_MODOK)) {
26986 			/*
26987 			 * the ioctl is one we recognise, but is not
26988 			 * consumed by IP as a module, pass M_IOCDATA
26989 			 * for processing downstream, but only for
26990 			 * common Streams ioctls.
26991 			 */
26992 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26993 				putnext(q, mp);
26994 				return;
26995 			} else {
26996 				goto nak;
26997 			}
26998 		}
26999 
27000 		/* IOCTL continuation following copyin or copyout. */
27001 		if (mi_copy_state(q, mp, NULL) == -1) {
27002 			/*
27003 			 * The copy operation failed.  mi_copy_state already
27004 			 * cleaned up, so we're out of here.
27005 			 */
27006 			return;
27007 		}
27008 		/*
27009 		 * If we just completed a copy in, we become writer and
27010 		 * continue processing in ip_sioctl_copyin_done.  If it
27011 		 * was a copy out, we call mi_copyout again.  If there is
27012 		 * nothing more to copy out, it will complete the IOCTL.
27013 		 */
27014 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27015 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27016 				mi_copy_done(q, mp, EPROTO);
27017 				return;
27018 			}
27019 			/*
27020 			 * Check for cases that need more copying.  A return
27021 			 * value of 0 means a second copyin has been started,
27022 			 * so we return; a return value of 1 means no more
27023 			 * copying is needed, so we continue.
27024 			 */
27025 			cmd = iocp->ioc_cmd;
27026 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27027 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27028 			    MI_COPY_COUNT(mp) == 1) {
27029 				if (ip_copyin_msfilter(q, mp) == 0)
27030 					return;
27031 			}
27032 			/*
27033 			 * Refhold the conn, till the ioctl completes. This is
27034 			 * needed in case the ioctl ends up in the pending mp
27035 			 * list. Every mp in the ill_pending_mp list and
27036 			 * the ipsq_pending_mp must have a refhold on the conn
27037 			 * to resume processing. The refhold is released when
27038 			 * the ioctl completes. (normally or abnormally)
27039 			 * In all cases ip_ioctl_finish is called to finish
27040 			 * the ioctl.
27041 			 */
27042 			if (connp != NULL) {
27043 				/* This is not a reentry */
27044 				ASSERT(ipsq == NULL);
27045 				CONN_INC_REF(connp);
27046 			} else {
27047 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27048 					mi_copy_done(q, mp, EINVAL);
27049 					return;
27050 				}
27051 			}
27052 
27053 			ip_process_ioctl(ipsq, q, mp, ipip);
27054 
27055 		} else {
27056 			mi_copyout(q, mp);
27057 		}
27058 		return;
27059 nak:
27060 		iocp->ioc_error = EINVAL;
27061 		mp->b_datap->db_type = M_IOCNAK;
27062 		iocp->ioc_count = 0;
27063 		qreply(q, mp);
27064 		return;
27065 
27066 	case M_IOCNAK:
27067 		/*
27068 		 * The only way we could get here is if a resolver didn't like
27069 		 * an IOCTL we sent it.	 This shouldn't happen.
27070 		 */
27071 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27072 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27073 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27074 		freemsg(mp);
27075 		return;
27076 	case M_IOCACK:
27077 		/* Finish socket ioctls passed through to ARP. */
27078 		ip_sioctl_iocack(q, mp);
27079 		return;
27080 	case M_FLUSH:
27081 		if (*mp->b_rptr & FLUSHW)
27082 			flushq(q, FLUSHALL);
27083 		if (q->q_next) {
27084 			/*
27085 			 * M_FLUSH is sent up to IP by some drivers during
27086 			 * unbind. ip_rput has already replied to it. We are
27087 			 * here for the M_FLUSH that we originated in IP
27088 			 * before sending the unbind request to the driver.
27089 			 * Just free it as we don't queue packets in IP
27090 			 * on the write side of the device instance.
27091 			 */
27092 			freemsg(mp);
27093 			return;
27094 		}
27095 		if (*mp->b_rptr & FLUSHR) {
27096 			*mp->b_rptr &= ~FLUSHW;
27097 			qreply(q, mp);
27098 			return;
27099 		}
27100 		freemsg(mp);
27101 		return;
27102 	case IRE_DB_REQ_TYPE:
27103 		/* An Upper Level Protocol wants a copy of an IRE. */
27104 		ip_ire_req(q, mp);
27105 		return;
27106 	case M_CTL:
27107 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27108 			break;
27109 
27110 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27111 		    TUN_HELLO) {
27112 			ASSERT(connp != NULL);
27113 			connp->conn_flags |= IPCL_IPTUN;
27114 			freeb(mp);
27115 			return;
27116 		}
27117 
27118 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27119 		    IP_ULP_OUT_LABELED) {
27120 			out_labeled_t *olp;
27121 
27122 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27123 				break;
27124 			olp = (out_labeled_t *)mp->b_rptr;
27125 			connp->conn_ulp_labeled = olp->out_qnext == q;
27126 			freemsg(mp);
27127 			return;
27128 		}
27129 
27130 		/* M_CTL messages are used by ARP to tell us things. */
27131 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27132 			break;
27133 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27134 		case AR_ENTRY_SQUERY:
27135 			ip_wput_ctl(q, mp);
27136 			return;
27137 		case AR_CLIENT_NOTIFY:
27138 			ip_arp_news(q, mp);
27139 			return;
27140 		case AR_DLPIOP_DONE:
27141 			ASSERT(q->q_next != NULL);
27142 			ill = (ill_t *)q->q_ptr;
27143 			/* qwriter_ip releases the refhold */
27144 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27145 			ill_refhold(ill);
27146 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27147 			    CUR_OP, B_FALSE);
27148 			return;
27149 		case AR_ARP_CLOSING:
27150 			/*
27151 			 * ARP (above us) is closing. If no ARP bringup is
27152 			 * currently pending, ack the message so that ARP
27153 			 * can complete its close. Also mark ill_arp_closing
27154 			 * so that new ARP bringups will fail. If any
27155 			 * ARP bringup is currently in progress, we will
27156 			 * ack this when the current ARP bringup completes.
27157 			 */
27158 			ASSERT(q->q_next != NULL);
27159 			ill = (ill_t *)q->q_ptr;
27160 			mutex_enter(&ill->ill_lock);
27161 			ill->ill_arp_closing = 1;
27162 			if (!ill->ill_arp_bringup_pending) {
27163 				mutex_exit(&ill->ill_lock);
27164 				qreply(q, mp);
27165 			} else {
27166 				mutex_exit(&ill->ill_lock);
27167 				freemsg(mp);
27168 			}
27169 			return;
27170 		case AR_ARP_EXTEND:
27171 			/*
27172 			 * The ARP module above us is capable of duplicate
27173 			 * address detection.  Old ATM drivers will not send
27174 			 * this message.
27175 			 */
27176 			ASSERT(q->q_next != NULL);
27177 			ill = (ill_t *)q->q_ptr;
27178 			ill->ill_arp_extend = B_TRUE;
27179 			freemsg(mp);
27180 			return;
27181 		default:
27182 			break;
27183 		}
27184 		break;
27185 	case M_PROTO:
27186 	case M_PCPROTO:
27187 		/*
27188 		 * The only PROTO messages we expect are ULP binds and
27189 		 * copies of option negotiation acknowledgements.
27190 		 */
27191 		switch (((union T_primitives *)mp->b_rptr)->type) {
27192 		case O_T_BIND_REQ:
27193 		case T_BIND_REQ: {
27194 			/* Request can get queued in bind */
27195 			ASSERT(connp != NULL);
27196 			/*
27197 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27198 			 * instead of going through this path.  We only get
27199 			 * here in the following cases:
27200 			 *
27201 			 * a. Bind retries, where ipsq is non-NULL.
27202 			 * b. T_BIND_REQ is issued from non TCP/UDP
27203 			 *    transport, e.g. icmp for raw socket,
27204 			 *    in which case ipsq will be NULL.
27205 			 */
27206 			ASSERT(ipsq != NULL ||
27207 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27208 
27209 			/* Don't increment refcnt if this is a re-entry */
27210 			if (ipsq == NULL)
27211 				CONN_INC_REF(connp);
27212 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27213 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27214 			if (mp == NULL)
27215 				return;
27216 			if (IPCL_IS_TCP(connp)) {
27217 				/*
27218 				 * In the case of TCP endpoint we
27219 				 * come here only for bind retries
27220 				 */
27221 				ASSERT(ipsq != NULL);
27222 				CONN_INC_REF(connp);
27223 				squeue_fill(connp->conn_sqp, mp,
27224 				    ip_resume_tcp_bind, connp,
27225 				    SQTAG_BIND_RETRY);
27226 				return;
27227 			} else if (IPCL_IS_UDP(connp)) {
27228 				/*
27229 				 * In the case of UDP endpoint we
27230 				 * come here only for bind retries
27231 				 */
27232 				ASSERT(ipsq != NULL);
27233 				udp_resume_bind(connp, mp);
27234 				return;
27235 			}
27236 			qreply(q, mp);
27237 			CONN_OPER_PENDING_DONE(connp);
27238 			return;
27239 		}
27240 		case T_SVR4_OPTMGMT_REQ:
27241 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27242 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27243 
27244 			ASSERT(connp != NULL);
27245 			if (!snmpcom_req(q, mp, ip_snmp_set,
27246 			    ip_snmp_get, cr)) {
27247 				/*
27248 				 * Call svr4_optcom_req so that it can
27249 				 * generate the ack. We don't come here
27250 				 * if this operation is being restarted.
27251 				 * ip_restart_optmgmt will drop the conn ref.
27252 				 * In the case of ipsec option after the ipsec
27253 				 * load is complete conn_restart_ipsec_waiter
27254 				 * drops the conn ref.
27255 				 */
27256 				ASSERT(ipsq == NULL);
27257 				CONN_INC_REF(connp);
27258 				if (ip_check_for_ipsec_opt(q, mp))
27259 					return;
27260 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27261 				if (err != EINPROGRESS) {
27262 					/* Operation is done */
27263 					CONN_OPER_PENDING_DONE(connp);
27264 				}
27265 			}
27266 			return;
27267 		case T_OPTMGMT_REQ:
27268 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27269 			/*
27270 			 * Note: No snmpcom_req support through new
27271 			 * T_OPTMGMT_REQ.
27272 			 * Call tpi_optcom_req so that it can
27273 			 * generate the ack.
27274 			 */
27275 			ASSERT(connp != NULL);
27276 			ASSERT(ipsq == NULL);
27277 			/*
27278 			 * We don't come here for restart. ip_restart_optmgmt
27279 			 * will drop the conn ref. In the case of ipsec option
27280 			 * after the ipsec load is complete
27281 			 * conn_restart_ipsec_waiter drops the conn ref.
27282 			 */
27283 			CONN_INC_REF(connp);
27284 			if (ip_check_for_ipsec_opt(q, mp))
27285 				return;
27286 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27287 			if (err != EINPROGRESS) {
27288 				/* Operation is done */
27289 				CONN_OPER_PENDING_DONE(connp);
27290 			}
27291 			return;
27292 		case T_UNBIND_REQ:
27293 			mp = ip_unbind(q, mp);
27294 			qreply(q, mp);
27295 			return;
27296 		default:
27297 			/*
27298 			 * Have to drop any DLPI messages coming down from
27299 			 * arp (such as an info_req which would cause ip
27300 			 * to receive an extra info_ack if it was passed
27301 			 * through.
27302 			 */
27303 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27304 			    (int)*(uint_t *)mp->b_rptr));
27305 			freemsg(mp);
27306 			return;
27307 		}
27308 		/* NOTREACHED */
27309 	case IRE_DB_TYPE: {
27310 		nce_t		*nce;
27311 		ill_t		*ill;
27312 		in6_addr_t	gw_addr_v6;
27313 
27314 
27315 		/*
27316 		 * This is a response back from a resolver.  It
27317 		 * consists of a message chain containing:
27318 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27319 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27320 		 * The LL_HDR_MBLK is the DLPI header to use to get
27321 		 * the attached packet, and subsequent ones for the
27322 		 * same destination, transmitted.
27323 		 */
27324 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27325 			break;
27326 		/*
27327 		 * First, check to make sure the resolution succeeded.
27328 		 * If it failed, the second mblk will be empty.
27329 		 * If it is, free the chain, dropping the packet.
27330 		 * (We must ire_delete the ire; that frees the ire mblk)
27331 		 * We're doing this now to support PVCs for ATM; it's
27332 		 * a partial xresolv implementation. When we fully implement
27333 		 * xresolv interfaces, instead of freeing everything here
27334 		 * we'll initiate neighbor discovery.
27335 		 *
27336 		 * For v4 (ARP and other external resolvers) the resolver
27337 		 * frees the message, so no check is needed. This check
27338 		 * is required, though, for a full xresolve implementation.
27339 		 * Including this code here now both shows how external
27340 		 * resolvers can NACK a resolution request using an
27341 		 * existing design that has no specific provisions for NACKs,
27342 		 * and also takes into account that the current non-ARP
27343 		 * external resolver has been coded to use this method of
27344 		 * NACKing for all IPv6 (xresolv) cases,
27345 		 * whether our xresolv implementation is complete or not.
27346 		 *
27347 		 */
27348 		ire = (ire_t *)mp->b_rptr;
27349 		ill = ire_to_ill(ire);
27350 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27351 		if (mp1->b_rptr == mp1->b_wptr) {
27352 			if (ire->ire_ipversion == IPV6_VERSION) {
27353 				/*
27354 				 * XRESOLV interface.
27355 				 */
27356 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27357 				mutex_enter(&ire->ire_lock);
27358 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27359 				mutex_exit(&ire->ire_lock);
27360 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27361 					nce = ndp_lookup_v6(ill,
27362 					    &ire->ire_addr_v6, B_FALSE);
27363 				} else {
27364 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27365 					    B_FALSE);
27366 				}
27367 				if (nce != NULL) {
27368 					nce_resolv_failed(nce);
27369 					ndp_delete(nce);
27370 					NCE_REFRELE(nce);
27371 				}
27372 			}
27373 			mp->b_cont = NULL;
27374 			freemsg(mp1);		/* frees the pkt as well */
27375 			ASSERT(ire->ire_nce == NULL);
27376 			ire_delete((ire_t *)mp->b_rptr);
27377 			return;
27378 		}
27379 
27380 		/*
27381 		 * Split them into IRE_MBLK and pkt and feed it into
27382 		 * ire_add_then_send. Then in ire_add_then_send
27383 		 * the IRE will be added, and then the packet will be
27384 		 * run back through ip_wput. This time it will make
27385 		 * it to the wire.
27386 		 */
27387 		mp->b_cont = NULL;
27388 		mp = mp1->b_cont;		/* now, mp points to pkt */
27389 		mp1->b_cont = NULL;
27390 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27391 		if (ire->ire_ipversion == IPV6_VERSION) {
27392 			/*
27393 			 * XRESOLV interface. Find the nce and put a copy
27394 			 * of the dl_unitdata_req in nce_res_mp
27395 			 */
27396 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27397 			mutex_enter(&ire->ire_lock);
27398 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27399 			mutex_exit(&ire->ire_lock);
27400 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27401 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27402 				    B_FALSE);
27403 			} else {
27404 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27405 			}
27406 			if (nce != NULL) {
27407 				/*
27408 				 * We have to protect nce_res_mp here
27409 				 * from being accessed by other threads
27410 				 * while we change the mblk pointer.
27411 				 * Other functions will also lock the nce when
27412 				 * accessing nce_res_mp.
27413 				 *
27414 				 * The reason we change the mblk pointer
27415 				 * here rather than copying the resolved address
27416 				 * into the template is that, unlike with
27417 				 * ethernet, we have no guarantee that the
27418 				 * resolved address length will be
27419 				 * smaller than or equal to the lla length
27420 				 * with which the template was allocated,
27421 				 * (for ethernet, they're equal)
27422 				 * so we have to use the actual resolved
27423 				 * address mblk - which holds the real
27424 				 * dl_unitdata_req with the resolved address.
27425 				 *
27426 				 * Doing this is the same behavior as was
27427 				 * previously used in the v4 ARP case.
27428 				 */
27429 				mutex_enter(&nce->nce_lock);
27430 				if (nce->nce_res_mp != NULL)
27431 					freemsg(nce->nce_res_mp);
27432 				nce->nce_res_mp = mp1;
27433 				mutex_exit(&nce->nce_lock);
27434 				/*
27435 				 * We do a fastpath probe here because
27436 				 * we have resolved the address without
27437 				 * using Neighbor Discovery.
27438 				 * In the non-XRESOLV v6 case, the fastpath
27439 				 * probe is done right after neighbor
27440 				 * discovery completes.
27441 				 */
27442 				if (nce->nce_res_mp != NULL) {
27443 					int res;
27444 					nce_fastpath_list_add(nce);
27445 					res = ill_fastpath_probe(ill,
27446 					    nce->nce_res_mp);
27447 					if (res != 0 && res != EAGAIN)
27448 						nce_fastpath_list_delete(nce);
27449 				}
27450 
27451 				ire_add_then_send(q, ire, mp);
27452 				/*
27453 				 * Now we have to clean out any packets
27454 				 * that may have been queued on the nce
27455 				 * while it was waiting for address resolution
27456 				 * to complete.
27457 				 */
27458 				mutex_enter(&nce->nce_lock);
27459 				mp1 = nce->nce_qd_mp;
27460 				nce->nce_qd_mp = NULL;
27461 				mutex_exit(&nce->nce_lock);
27462 				while (mp1 != NULL) {
27463 					mblk_t *nxt_mp;
27464 					queue_t *fwdq = NULL;
27465 					ill_t   *inbound_ill;
27466 					uint_t ifindex;
27467 
27468 					nxt_mp = mp1->b_next;
27469 					mp1->b_next = NULL;
27470 					/*
27471 					 * Retrieve ifindex stored in
27472 					 * ip_rput_data_v6()
27473 					 */
27474 					ifindex =
27475 					    (uint_t)(uintptr_t)mp1->b_prev;
27476 					inbound_ill =
27477 						ill_lookup_on_ifindex(ifindex,
27478 						    B_TRUE, NULL, NULL, NULL,
27479 						    NULL);
27480 					mp1->b_prev = NULL;
27481 					if (inbound_ill != NULL)
27482 						fwdq = inbound_ill->ill_rq;
27483 
27484 					if (fwdq != NULL) {
27485 						put(fwdq, mp1);
27486 						ill_refrele(inbound_ill);
27487 					} else
27488 						put(WR(ill->ill_rq), mp1);
27489 					mp1 = nxt_mp;
27490 				}
27491 				NCE_REFRELE(nce);
27492 			} else {	/* nce is NULL; clean up */
27493 				ire_delete(ire);
27494 				freemsg(mp);
27495 				freemsg(mp1);
27496 				return;
27497 			}
27498 		} else {
27499 			nce_t *arpce;
27500 			/*
27501 			 * Link layer resolution succeeded. Recompute the
27502 			 * ire_nce.
27503 			 */
27504 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27505 			if ((arpce = ndp_lookup_v4(ill,
27506 			    (ire->ire_gateway_addr != INADDR_ANY ?
27507 			    &ire->ire_gateway_addr : &ire->ire_addr),
27508 			    B_FALSE)) == NULL) {
27509 				freeb(ire->ire_mp);
27510 				freeb(mp1);
27511 				freemsg(mp);
27512 				return;
27513 			}
27514 			mutex_enter(&arpce->nce_lock);
27515 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27516 			if (arpce->nce_state == ND_REACHABLE) {
27517 				/*
27518 				 * Someone resolved this before us;
27519 				 * cleanup the res_mp. Since ire has
27520 				 * not been added yet, the call to ire_add_v4
27521 				 * from ire_add_then_send (when a dup is
27522 				 * detected) will clean up the ire.
27523 				 */
27524 				freeb(mp1);
27525 			} else {
27526 				if (arpce->nce_res_mp != NULL)
27527 					freemsg(arpce->nce_res_mp);
27528 				arpce->nce_res_mp = mp1;
27529 				arpce->nce_state = ND_REACHABLE;
27530 			}
27531 			mutex_exit(&arpce->nce_lock);
27532 			if (ire->ire_marks & IRE_MARK_NOADD) {
27533 				/*
27534 				 * this ire will not be added to the ire
27535 				 * cache table, so we can set the ire_nce
27536 				 * here, as there are no atomicity constraints.
27537 				 */
27538 				ire->ire_nce = arpce;
27539 				/*
27540 				 * We are associating this nce with the ire
27541 				 * so change the nce ref taken in
27542 				 * ndp_lookup_v4() from
27543 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27544 				 */
27545 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27546 			} else {
27547 				NCE_REFRELE(arpce);
27548 			}
27549 			ire_add_then_send(q, ire, mp);
27550 		}
27551 		return;	/* All is well, the packet has been sent. */
27552 	}
27553 	case IRE_ARPRESOLVE_TYPE: {
27554 
27555 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27556 			break;
27557 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27558 		mp->b_cont = NULL;
27559 		/*
27560 		 * First, check to make sure the resolution succeeded.
27561 		 * If it failed, the second mblk will be empty.
27562 		 */
27563 		if (mp1->b_rptr == mp1->b_wptr) {
27564 			/* cleanup  the incomplete ire, free queued packets */
27565 			freemsg(mp); /* fake ire */
27566 			freeb(mp1);  /* dl_unitdata response */
27567 			return;
27568 		}
27569 
27570 		/*
27571 		 * update any incomplete nce_t found. we lookup the ctable
27572 		 * and find the nce from the ire->ire_nce because we need
27573 		 * to pass the ire to ip_xmit_v4 later, and can find both
27574 		 * ire and nce in one lookup from the ctable.
27575 		 */
27576 		fake_ire = (ire_t *)mp->b_rptr;
27577 		/*
27578 		 * By the time we come back here from ARP
27579 		 * the logical outgoing interface  of the incomplete ire
27580 		 * we added in ire_forward could have disappeared,
27581 		 * causing the incomplete ire to also have
27582 		 * dissapeared. So we need to retreive the
27583 		 * proper ipif for the ire  before looking
27584 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27585 		 */
27586 		ill = q->q_ptr;
27587 
27588 		/* Get the outgoing ipif */
27589 		mutex_enter(&ill->ill_lock);
27590 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27591 			mutex_exit(&ill->ill_lock);
27592 			freemsg(mp); /* fake ire */
27593 			freeb(mp1);  /* dl_unitdata response */
27594 			return;
27595 		}
27596 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27597 
27598 		if (ipif == NULL) {
27599 			mutex_exit(&ill->ill_lock);
27600 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27601 			freemsg(mp);
27602 			freeb(mp1);
27603 			return;
27604 		}
27605 		ipif_refhold_locked(ipif);
27606 		mutex_exit(&ill->ill_lock);
27607 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27608 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27609 		    ipif, fake_ire->ire_zoneid, NULL,
27610 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27611 		ipif_refrele(ipif);
27612 		if (ire == NULL) {
27613 			/*
27614 			 * no ire was found; check if there is an nce
27615 			 * for this lookup; if it has no ire's pointing at it
27616 			 * cleanup.
27617 			 */
27618 			if ((nce = ndp_lookup_v4(ill,
27619 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27620 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27621 			    B_FALSE)) != NULL) {
27622 				/*
27623 				 * cleanup: just reset nce.
27624 				 * We check for refcnt 2 (one for the nce
27625 				 * hash list + 1 for the ref taken by
27626 				 * ndp_lookup_v4) to ensure that there are
27627 				 * no ire's pointing at the nce.
27628 				 */
27629 				if (nce->nce_refcnt == 2) {
27630 					nce = nce_reinit(nce);
27631 				}
27632 				if (nce != NULL)
27633 					NCE_REFRELE(nce);
27634 			}
27635 			freeb(mp1);  /* dl_unitdata response */
27636 			freemsg(mp); /* fake ire */
27637 			return;
27638 		}
27639 		nce = ire->ire_nce;
27640 		DTRACE_PROBE2(ire__arpresolve__type,
27641 		    ire_t *, ire, nce_t *, nce);
27642 		ASSERT(nce->nce_state != ND_INITIAL);
27643 		mutex_enter(&nce->nce_lock);
27644 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27645 		if (nce->nce_state == ND_REACHABLE) {
27646 			/*
27647 			 * Someone resolved this before us;
27648 			 * our response is not needed any more.
27649 			 */
27650 			mutex_exit(&nce->nce_lock);
27651 			freeb(mp1);  /* dl_unitdata response */
27652 		} else {
27653 			if (nce->nce_res_mp != NULL) {
27654 				freemsg(nce->nce_res_mp);
27655 				/* existing dl_unitdata template */
27656 			}
27657 			nce->nce_res_mp = mp1;
27658 			nce->nce_state = ND_REACHABLE;
27659 			mutex_exit(&nce->nce_lock);
27660 			ire_fastpath(ire);
27661 		}
27662 		/*
27663 		 * The cached nce_t has been updated to be reachable;
27664 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27665 		 */
27666 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27667 		freemsg(mp);
27668 		/*
27669 		 * send out queued packets.
27670 		 */
27671 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27672 
27673 		IRE_REFRELE(ire);
27674 		return;
27675 	}
27676 	default:
27677 		break;
27678 	}
27679 	if (q->q_next) {
27680 		putnext(q, mp);
27681 	} else
27682 		freemsg(mp);
27683 }
27684 
27685 /*
27686  * Process IP options in an outbound packet.  Modify the destination if there
27687  * is a source route option.
27688  * Returns non-zero if something fails in which case an ICMP error has been
27689  * sent and mp freed.
27690  */
27691 static int
27692 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27693     boolean_t mctl_present, zoneid_t zoneid)
27694 {
27695 	ipoptp_t	opts;
27696 	uchar_t		*opt;
27697 	uint8_t		optval;
27698 	uint8_t		optlen;
27699 	ipaddr_t	dst;
27700 	intptr_t	code = 0;
27701 	mblk_t		*mp;
27702 	ire_t		*ire = NULL;
27703 
27704 	ip2dbg(("ip_wput_options\n"));
27705 	mp = ipsec_mp;
27706 	if (mctl_present) {
27707 		mp = ipsec_mp->b_cont;
27708 	}
27709 
27710 	dst = ipha->ipha_dst;
27711 	for (optval = ipoptp_first(&opts, ipha);
27712 	    optval != IPOPT_EOL;
27713 	    optval = ipoptp_next(&opts)) {
27714 		opt = opts.ipoptp_cur;
27715 		optlen = opts.ipoptp_len;
27716 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27717 		    optval, optlen));
27718 		switch (optval) {
27719 			uint32_t off;
27720 		case IPOPT_SSRR:
27721 		case IPOPT_LSRR:
27722 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27723 				ip1dbg((
27724 				    "ip_wput_options: bad option offset\n"));
27725 				code = (char *)&opt[IPOPT_OLEN] -
27726 				    (char *)ipha;
27727 				goto param_prob;
27728 			}
27729 			off = opt[IPOPT_OFFSET];
27730 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27731 			    ntohl(dst)));
27732 			/*
27733 			 * For strict: verify that dst is directly
27734 			 * reachable.
27735 			 */
27736 			if (optval == IPOPT_SSRR) {
27737 				ire = ire_ftable_lookup(dst, 0, 0,
27738 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27739 				    MBLK_GETLABEL(mp),
27740 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27741 				if (ire == NULL) {
27742 					ip1dbg(("ip_wput_options: SSRR not"
27743 					    " directly reachable: 0x%x\n",
27744 					    ntohl(dst)));
27745 					goto bad_src_route;
27746 				}
27747 				ire_refrele(ire);
27748 			}
27749 			break;
27750 		case IPOPT_RR:
27751 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27752 				ip1dbg((
27753 				    "ip_wput_options: bad option offset\n"));
27754 				code = (char *)&opt[IPOPT_OLEN] -
27755 				    (char *)ipha;
27756 				goto param_prob;
27757 			}
27758 			break;
27759 		case IPOPT_TS:
27760 			/*
27761 			 * Verify that length >=5 and that there is either
27762 			 * room for another timestamp or that the overflow
27763 			 * counter is not maxed out.
27764 			 */
27765 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27766 			if (optlen < IPOPT_MINLEN_IT) {
27767 				goto param_prob;
27768 			}
27769 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27770 				ip1dbg((
27771 				    "ip_wput_options: bad option offset\n"));
27772 				code = (char *)&opt[IPOPT_OFFSET] -
27773 				    (char *)ipha;
27774 				goto param_prob;
27775 			}
27776 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27777 			case IPOPT_TS_TSONLY:
27778 				off = IPOPT_TS_TIMELEN;
27779 				break;
27780 			case IPOPT_TS_TSANDADDR:
27781 			case IPOPT_TS_PRESPEC:
27782 			case IPOPT_TS_PRESPEC_RFC791:
27783 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27784 				break;
27785 			default:
27786 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27787 				    (char *)ipha;
27788 				goto param_prob;
27789 			}
27790 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27791 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27792 				/*
27793 				 * No room and the overflow counter is 15
27794 				 * already.
27795 				 */
27796 				goto param_prob;
27797 			}
27798 			break;
27799 		}
27800 	}
27801 
27802 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27803 		return (0);
27804 
27805 	ip1dbg(("ip_wput_options: error processing IP options."));
27806 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27807 
27808 param_prob:
27809 	/*
27810 	 * Since ip_wput() isn't close to finished, we fill
27811 	 * in enough of the header for credible error reporting.
27812 	 */
27813 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27814 		/* Failed */
27815 		freemsg(ipsec_mp);
27816 		return (-1);
27817 	}
27818 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27819 	return (-1);
27820 
27821 bad_src_route:
27822 	/*
27823 	 * Since ip_wput() isn't close to finished, we fill
27824 	 * in enough of the header for credible error reporting.
27825 	 */
27826 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27827 		/* Failed */
27828 		freemsg(ipsec_mp);
27829 		return (-1);
27830 	}
27831 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27832 	return (-1);
27833 }
27834 
27835 /*
27836  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27837  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27838  * thru /etc/system.
27839  */
27840 #define	CONN_MAXDRAINCNT	64
27841 
27842 static void
27843 conn_drain_init(void)
27844 {
27845 	int i;
27846 
27847 	conn_drain_list_cnt = conn_drain_nthreads;
27848 
27849 	if ((conn_drain_list_cnt == 0) ||
27850 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27851 		/*
27852 		 * Default value of the number of drainers is the
27853 		 * number of cpus, subject to maximum of 8 drainers.
27854 		 */
27855 		if (boot_max_ncpus != -1)
27856 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27857 		else
27858 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27859 	}
27860 
27861 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27862 	    KM_SLEEP);
27863 
27864 	for (i = 0; i < conn_drain_list_cnt; i++) {
27865 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27866 		    MUTEX_DEFAULT, NULL);
27867 	}
27868 }
27869 
27870 static void
27871 conn_drain_fini(void)
27872 {
27873 	int i;
27874 
27875 	for (i = 0; i < conn_drain_list_cnt; i++)
27876 		mutex_destroy(&conn_drain_list[i].idl_lock);
27877 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27878 	conn_drain_list = NULL;
27879 }
27880 
27881 /*
27882  * Note: For an overview of how flowcontrol is handled in IP please see the
27883  * IP Flowcontrol notes at the top of this file.
27884  *
27885  * Flow control has blocked us from proceeding. Insert the given conn in one
27886  * of the conn drain lists. These conn wq's will be qenabled later on when
27887  * STREAMS flow control does a backenable. conn_walk_drain will enable
27888  * the first conn in each of these drain lists. Each of these qenabled conns
27889  * in turn enables the next in the list, after it runs, or when it closes,
27890  * thus sustaining the drain process.
27891  *
27892  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27893  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27894  * running at any time, on a given conn, since there can be only 1 service proc
27895  * running on a queue at any time.
27896  */
27897 void
27898 conn_drain_insert(conn_t *connp)
27899 {
27900 	idl_t	*idl;
27901 	uint_t	index;
27902 
27903 	mutex_enter(&connp->conn_lock);
27904 	if (connp->conn_state_flags & CONN_CLOSING) {
27905 		/*
27906 		 * The conn is closing as a result of which CONN_CLOSING
27907 		 * is set. Return.
27908 		 */
27909 		mutex_exit(&connp->conn_lock);
27910 		return;
27911 	} else if (connp->conn_idl == NULL) {
27912 		/*
27913 		 * Assign the next drain list round robin. We dont' use
27914 		 * a lock, and thus it may not be strictly round robin.
27915 		 * Atomicity of load/stores is enough to make sure that
27916 		 * conn_drain_list_index is always within bounds.
27917 		 */
27918 		index = conn_drain_list_index;
27919 		ASSERT(index < conn_drain_list_cnt);
27920 		connp->conn_idl = &conn_drain_list[index];
27921 		index++;
27922 		if (index == conn_drain_list_cnt)
27923 			index = 0;
27924 		conn_drain_list_index = index;
27925 	}
27926 	mutex_exit(&connp->conn_lock);
27927 
27928 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27929 	if ((connp->conn_drain_prev != NULL) ||
27930 	    (connp->conn_state_flags & CONN_CLOSING)) {
27931 		/*
27932 		 * The conn is already in the drain list, OR
27933 		 * the conn is closing. We need to check again for
27934 		 * the closing case again since close can happen
27935 		 * after we drop the conn_lock, and before we
27936 		 * acquire the CONN_DRAIN_LIST_LOCK.
27937 		 */
27938 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27939 		return;
27940 	} else {
27941 		idl = connp->conn_idl;
27942 	}
27943 
27944 	/*
27945 	 * The conn is not in the drain list. Insert it at the
27946 	 * tail of the drain list. The drain list is circular
27947 	 * and doubly linked. idl_conn points to the 1st element
27948 	 * in the list.
27949 	 */
27950 	if (idl->idl_conn == NULL) {
27951 		idl->idl_conn = connp;
27952 		connp->conn_drain_next = connp;
27953 		connp->conn_drain_prev = connp;
27954 	} else {
27955 		conn_t *head = idl->idl_conn;
27956 
27957 		connp->conn_drain_next = head;
27958 		connp->conn_drain_prev = head->conn_drain_prev;
27959 		head->conn_drain_prev->conn_drain_next = connp;
27960 		head->conn_drain_prev = connp;
27961 	}
27962 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27963 }
27964 
27965 /*
27966  * This conn is closing, and we are called from ip_close. OR
27967  * This conn has been serviced by ip_wsrv, and we need to do the tail
27968  * processing.
27969  * If this conn is part of the drain list, we may need to sustain the drain
27970  * process by qenabling the next conn in the drain list. We may also need to
27971  * remove this conn from the list, if it is done.
27972  */
27973 static void
27974 conn_drain_tail(conn_t *connp, boolean_t closing)
27975 {
27976 	idl_t *idl;
27977 
27978 	/*
27979 	 * connp->conn_idl is stable at this point, and no lock is needed
27980 	 * to check it. If we are called from ip_close, close has already
27981 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27982 	 * called us only because conn_idl is non-null. If we are called thru
27983 	 * service, conn_idl could be null, but it cannot change because
27984 	 * service is single-threaded per queue, and there cannot be another
27985 	 * instance of service trying to call conn_drain_insert on this conn
27986 	 * now.
27987 	 */
27988 	ASSERT(!closing || (connp->conn_idl != NULL));
27989 
27990 	/*
27991 	 * If connp->conn_idl is null, the conn has not been inserted into any
27992 	 * drain list even once since creation of the conn. Just return.
27993 	 */
27994 	if (connp->conn_idl == NULL)
27995 		return;
27996 
27997 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27998 
27999 	if (connp->conn_drain_prev == NULL) {
28000 		/* This conn is currently not in the drain list.  */
28001 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28002 		return;
28003 	}
28004 	idl = connp->conn_idl;
28005 	if (idl->idl_conn_draining == connp) {
28006 		/*
28007 		 * This conn is the current drainer. If this is the last conn
28008 		 * in the drain list, we need to do more checks, in the 'if'
28009 		 * below. Otherwwise we need to just qenable the next conn,
28010 		 * to sustain the draining, and is handled in the 'else'
28011 		 * below.
28012 		 */
28013 		if (connp->conn_drain_next == idl->idl_conn) {
28014 			/*
28015 			 * This conn is the last in this list. This round
28016 			 * of draining is complete. If idl_repeat is set,
28017 			 * it means another flow enabling has happened from
28018 			 * the driver/streams and we need to another round
28019 			 * of draining.
28020 			 * If there are more than 2 conns in the drain list,
28021 			 * do a left rotate by 1, so that all conns except the
28022 			 * conn at the head move towards the head by 1, and the
28023 			 * the conn at the head goes to the tail. This attempts
28024 			 * a more even share for all queues that are being
28025 			 * drained.
28026 			 */
28027 			if ((connp->conn_drain_next != connp) &&
28028 			    (idl->idl_conn->conn_drain_next != connp)) {
28029 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28030 			}
28031 			if (idl->idl_repeat) {
28032 				qenable(idl->idl_conn->conn_wq);
28033 				idl->idl_conn_draining = idl->idl_conn;
28034 				idl->idl_repeat = 0;
28035 			} else {
28036 				idl->idl_conn_draining = NULL;
28037 			}
28038 		} else {
28039 			/*
28040 			 * If the next queue that we are now qenable'ing,
28041 			 * is closing, it will remove itself from this list
28042 			 * and qenable the subsequent queue in ip_close().
28043 			 * Serialization is acheived thru idl_lock.
28044 			 */
28045 			qenable(connp->conn_drain_next->conn_wq);
28046 			idl->idl_conn_draining = connp->conn_drain_next;
28047 		}
28048 	}
28049 	if (!connp->conn_did_putbq || closing) {
28050 		/*
28051 		 * Remove ourself from the drain list, if we did not do
28052 		 * a putbq, or if the conn is closing.
28053 		 * Note: It is possible that q->q_first is non-null. It means
28054 		 * that these messages landed after we did a enableok() in
28055 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28056 		 * service them.
28057 		 */
28058 		if (connp->conn_drain_next == connp) {
28059 			/* Singleton in the list */
28060 			ASSERT(connp->conn_drain_prev == connp);
28061 			idl->idl_conn = NULL;
28062 			idl->idl_conn_draining = NULL;
28063 		} else {
28064 			connp->conn_drain_prev->conn_drain_next =
28065 			    connp->conn_drain_next;
28066 			connp->conn_drain_next->conn_drain_prev =
28067 			    connp->conn_drain_prev;
28068 			if (idl->idl_conn == connp)
28069 				idl->idl_conn = connp->conn_drain_next;
28070 			ASSERT(idl->idl_conn_draining != connp);
28071 
28072 		}
28073 		connp->conn_drain_next = NULL;
28074 		connp->conn_drain_prev = NULL;
28075 	}
28076 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28077 }
28078 
28079 /*
28080  * Write service routine. Shared perimeter entry point.
28081  * ip_wsrv can be called in any of the following ways.
28082  * 1. The device queue's messages has fallen below the low water mark
28083  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28084  *    the drain lists and backenable the first conn in each list.
28085  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28086  *    qenabled non-tcp upper layers. We start dequeing messages and call
28087  *    ip_wput for each message.
28088  */
28089 
28090 void
28091 ip_wsrv(queue_t *q)
28092 {
28093 	conn_t	*connp;
28094 	ill_t	*ill;
28095 	mblk_t	*mp;
28096 
28097 	if (q->q_next) {
28098 		ill = (ill_t *)q->q_ptr;
28099 		if (ill->ill_state_flags == 0) {
28100 			/*
28101 			 * The device flow control has opened up.
28102 			 * Walk through conn drain lists and qenable the
28103 			 * first conn in each list. This makes sense only
28104 			 * if the stream is fully plumbed and setup.
28105 			 * Hence the if check above.
28106 			 */
28107 			ip1dbg(("ip_wsrv: walking\n"));
28108 			conn_walk_drain();
28109 		}
28110 		return;
28111 	}
28112 
28113 	connp = Q_TO_CONN(q);
28114 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28115 
28116 	/*
28117 	 * 1. Set conn_draining flag to signal that service is active.
28118 	 *
28119 	 * 2. ip_output determines whether it has been called from service,
28120 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28121 	 *    has been called from service.
28122 	 *
28123 	 * 3. Message ordering is preserved by the following logic.
28124 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28125 	 *    the message at the tail, if conn_draining is set (i.e. service
28126 	 *    is running) or if q->q_first is non-null.
28127 	 *
28128 	 *    ii. If ip_output is called from service, and if ip_output cannot
28129 	 *    putnext due to flow control, it does a putbq.
28130 	 *
28131 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28132 	 *    (causing an infinite loop).
28133 	 */
28134 	ASSERT(!connp->conn_did_putbq);
28135 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28136 		connp->conn_draining = 1;
28137 		noenable(q);
28138 		while ((mp = getq(q)) != NULL) {
28139 			ASSERT(CONN_Q(q));
28140 
28141 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28142 			if (connp->conn_did_putbq) {
28143 				/* ip_wput did a putbq */
28144 				break;
28145 			}
28146 		}
28147 		/*
28148 		 * At this point, a thread coming down from top, calling
28149 		 * ip_wput, may end up queueing the message. We have not yet
28150 		 * enabled the queue, so ip_wsrv won't be called again.
28151 		 * To avoid this race, check q->q_first again (in the loop)
28152 		 * If the other thread queued the message before we call
28153 		 * enableok(), we will catch it in the q->q_first check.
28154 		 * If the other thread queues the message after we call
28155 		 * enableok(), ip_wsrv will be called again by STREAMS.
28156 		 */
28157 		connp->conn_draining = 0;
28158 		enableok(q);
28159 	}
28160 
28161 	/* Enable the next conn for draining */
28162 	conn_drain_tail(connp, B_FALSE);
28163 
28164 	connp->conn_did_putbq = 0;
28165 }
28166 
28167 /*
28168  * Walk the list of all conn's calling the function provided with the
28169  * specified argument for each.	 Note that this only walks conn's that
28170  * have been bound.
28171  * Applies to both IPv4 and IPv6.
28172  */
28173 static void
28174 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
28175 {
28176 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
28177 	    func, arg, zoneid);
28178 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
28179 	    func, arg, zoneid);
28180 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
28181 	    func, arg, zoneid);
28182 	conn_walk_fanout_table(ipcl_proto_fanout,
28183 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
28184 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
28185 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
28186 }
28187 
28188 /*
28189  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28190  * of conns that need to be drained, check if drain is already in progress.
28191  * If so set the idl_repeat bit, indicating that the last conn in the list
28192  * needs to reinitiate the drain once again, for the list. If drain is not
28193  * in progress for the list, initiate the draining, by qenabling the 1st
28194  * conn in the list. The drain is self-sustaining, each qenabled conn will
28195  * in turn qenable the next conn, when it is done/blocked/closing.
28196  */
28197 static void
28198 conn_walk_drain(void)
28199 {
28200 	int i;
28201 	idl_t *idl;
28202 
28203 	IP_STAT(ip_conn_walk_drain);
28204 
28205 	for (i = 0; i < conn_drain_list_cnt; i++) {
28206 		idl = &conn_drain_list[i];
28207 		mutex_enter(&idl->idl_lock);
28208 		if (idl->idl_conn == NULL) {
28209 			mutex_exit(&idl->idl_lock);
28210 			continue;
28211 		}
28212 		/*
28213 		 * If this list is not being drained currently by
28214 		 * an ip_wsrv thread, start the process.
28215 		 */
28216 		if (idl->idl_conn_draining == NULL) {
28217 			ASSERT(idl->idl_repeat == 0);
28218 			qenable(idl->idl_conn->conn_wq);
28219 			idl->idl_conn_draining = idl->idl_conn;
28220 		} else {
28221 			idl->idl_repeat = 1;
28222 		}
28223 		mutex_exit(&idl->idl_lock);
28224 	}
28225 }
28226 
28227 /*
28228  * Walk an conn hash table of `count' buckets, calling func for each entry.
28229  */
28230 static void
28231 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28232     zoneid_t zoneid)
28233 {
28234 	conn_t	*connp;
28235 
28236 	while (count-- > 0) {
28237 		mutex_enter(&connfp->connf_lock);
28238 		for (connp = connfp->connf_head; connp != NULL;
28239 		    connp = connp->conn_next) {
28240 			if (zoneid == GLOBAL_ZONEID ||
28241 			    zoneid == connp->conn_zoneid) {
28242 				CONN_INC_REF(connp);
28243 				mutex_exit(&connfp->connf_lock);
28244 				(*func)(connp, arg);
28245 				mutex_enter(&connfp->connf_lock);
28246 				CONN_DEC_REF(connp);
28247 			}
28248 		}
28249 		mutex_exit(&connfp->connf_lock);
28250 		connfp++;
28251 	}
28252 }
28253 
28254 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28255 static void
28256 conn_report1(conn_t *connp, void *mp)
28257 {
28258 	char	buf1[INET6_ADDRSTRLEN];
28259 	char	buf2[INET6_ADDRSTRLEN];
28260 	uint_t	print_len, buf_len;
28261 
28262 	ASSERT(connp != NULL);
28263 
28264 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28265 	if (buf_len <= 0)
28266 		return;
28267 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28268 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28269 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28270 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28271 	    "%5d %s/%05d %s/%05d\n",
28272 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28273 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28274 	    buf1, connp->conn_lport,
28275 	    buf2, connp->conn_fport);
28276 	if (print_len < buf_len) {
28277 		((mblk_t *)mp)->b_wptr += print_len;
28278 	} else {
28279 		((mblk_t *)mp)->b_wptr += buf_len;
28280 	}
28281 }
28282 
28283 /*
28284  * Named Dispatch routine to produce a formatted report on all conns
28285  * that are listed in one of the fanout tables.
28286  * This report is accessed by using the ndd utility to "get" ND variable
28287  * "ip_conn_status".
28288  */
28289 /* ARGSUSED */
28290 static int
28291 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28292 {
28293 	(void) mi_mpprintf(mp,
28294 	    "CONN      " MI_COL_HDRPAD_STR
28295 	    "rfq      " MI_COL_HDRPAD_STR
28296 	    "stq      " MI_COL_HDRPAD_STR
28297 	    " zone local                 remote");
28298 
28299 	/*
28300 	 * Because of the ndd constraint, at most we can have 64K buffer
28301 	 * to put in all conn info.  So to be more efficient, just
28302 	 * allocate a 64K buffer here, assuming we need that large buffer.
28303 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28304 	 */
28305 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28306 		/* The following may work even if we cannot get a large buf. */
28307 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28308 		return (0);
28309 	}
28310 
28311 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
28312 	return (0);
28313 }
28314 
28315 /*
28316  * Determine if the ill and multicast aspects of that packets
28317  * "matches" the conn.
28318  */
28319 boolean_t
28320 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28321     zoneid_t zoneid)
28322 {
28323 	ill_t *in_ill;
28324 	boolean_t found;
28325 	ipif_t *ipif;
28326 	ire_t *ire;
28327 	ipaddr_t dst, src;
28328 
28329 	dst = ipha->ipha_dst;
28330 	src = ipha->ipha_src;
28331 
28332 	/*
28333 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28334 	 * unicast, broadcast and multicast reception to
28335 	 * conn_incoming_ill. conn_wantpacket itself is called
28336 	 * only for BROADCAST and multicast.
28337 	 *
28338 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28339 	 *    is part of a group. Hence, we should be receiving
28340 	 *    just one copy of broadcast for the whole group.
28341 	 *    Thus, if it is part of the group the packet could
28342 	 *    come on any ill of the group and hence we need a
28343 	 *    match on the group. Otherwise, match on ill should
28344 	 *    be sufficient.
28345 	 *
28346 	 * 2) ip_rput does not suppress duplicate multicast packets.
28347 	 *    If there are two interfaces in a ill group and we have
28348 	 *    2 applications (conns) joined a multicast group G on
28349 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28350 	 *    will give us two packets because we join G on both the
28351 	 *    interfaces rather than nominating just one interface
28352 	 *    for receiving multicast like broadcast above. So,
28353 	 *    we have to call ilg_lookup_ill to filter out duplicate
28354 	 *    copies, if ill is part of a group.
28355 	 */
28356 	in_ill = connp->conn_incoming_ill;
28357 	if (in_ill != NULL) {
28358 		if (in_ill->ill_group == NULL) {
28359 			if (in_ill != ill)
28360 				return (B_FALSE);
28361 		} else if (in_ill->ill_group != ill->ill_group) {
28362 			return (B_FALSE);
28363 		}
28364 	}
28365 
28366 	if (!CLASSD(dst)) {
28367 		if (IPCL_ZONE_MATCH(connp, zoneid))
28368 			return (B_TRUE);
28369 		/*
28370 		 * The conn is in a different zone; we need to check that this
28371 		 * broadcast address is configured in the application's zone and
28372 		 * on one ill in the group.
28373 		 */
28374 		ipif = ipif_get_next_ipif(NULL, ill);
28375 		if (ipif == NULL)
28376 			return (B_FALSE);
28377 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28378 		    connp->conn_zoneid, NULL,
28379 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
28380 		ipif_refrele(ipif);
28381 		if (ire != NULL) {
28382 			ire_refrele(ire);
28383 			return (B_TRUE);
28384 		} else {
28385 			return (B_FALSE);
28386 		}
28387 	}
28388 
28389 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28390 	    connp->conn_zoneid == zoneid) {
28391 		/*
28392 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28393 		 * disabled, therefore we don't dispatch the multicast packet to
28394 		 * the sending zone.
28395 		 */
28396 		return (B_FALSE);
28397 	}
28398 
28399 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28400 	    connp->conn_zoneid != zoneid) {
28401 		/*
28402 		 * Multicast packet on the loopback interface: we only match
28403 		 * conns who joined the group in the specified zone.
28404 		 */
28405 		return (B_FALSE);
28406 	}
28407 
28408 	if (connp->conn_multi_router) {
28409 		/* multicast packet and multicast router socket: send up */
28410 		return (B_TRUE);
28411 	}
28412 
28413 	mutex_enter(&connp->conn_lock);
28414 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28415 	mutex_exit(&connp->conn_lock);
28416 	return (found);
28417 }
28418 
28419 /*
28420  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28421  */
28422 /* ARGSUSED */
28423 static void
28424 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28425 {
28426 	ill_t *ill = (ill_t *)q->q_ptr;
28427 	mblk_t	*mp1, *mp2;
28428 	ipif_t  *ipif;
28429 	int err = 0;
28430 	conn_t *connp = NULL;
28431 	ipsq_t	*ipsq;
28432 	arc_t	*arc;
28433 
28434 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28435 
28436 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28437 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28438 
28439 	ASSERT(IAM_WRITER_ILL(ill));
28440 	mp2 = mp->b_cont;
28441 	mp->b_cont = NULL;
28442 
28443 	/*
28444 	 * We have now received the arp bringup completion message
28445 	 * from ARP. Mark the arp bringup as done. Also if the arp
28446 	 * stream has already started closing, send up the AR_ARP_CLOSING
28447 	 * ack now since ARP is waiting in close for this ack.
28448 	 */
28449 	mutex_enter(&ill->ill_lock);
28450 	ill->ill_arp_bringup_pending = 0;
28451 	if (ill->ill_arp_closing) {
28452 		mutex_exit(&ill->ill_lock);
28453 		/* Let's reuse the mp for sending the ack */
28454 		arc = (arc_t *)mp->b_rptr;
28455 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28456 		arc->arc_cmd = AR_ARP_CLOSING;
28457 		qreply(q, mp);
28458 	} else {
28459 		mutex_exit(&ill->ill_lock);
28460 		freeb(mp);
28461 	}
28462 
28463 	/* We should have an IOCTL waiting on this. */
28464 	ipsq = ill->ill_phyint->phyint_ipsq;
28465 	ipif = ipsq->ipsq_pending_ipif;
28466 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28467 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
28468 	if (mp1 == NULL) {
28469 		/* bringup was aborted by the user */
28470 		freemsg(mp2);
28471 		return;
28472 	}
28473 	ASSERT(connp != NULL);
28474 	q = CONNP_TO_WQ(connp);
28475 	/*
28476 	 * If the DL_BIND_REQ fails, it is noted
28477 	 * in arc_name_offset.
28478 	 */
28479 	err = *((int *)mp2->b_rptr);
28480 	if (err == 0) {
28481 		if (ipif->ipif_isv6) {
28482 			if ((err = ipif_up_done_v6(ipif)) != 0)
28483 				ip0dbg(("ip_arp_done: init failed\n"));
28484 		} else {
28485 			if ((err = ipif_up_done(ipif)) != 0)
28486 				ip0dbg(("ip_arp_done: init failed\n"));
28487 		}
28488 	} else {
28489 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28490 	}
28491 
28492 	freemsg(mp2);
28493 
28494 	if ((err == 0) && (ill->ill_up_ipifs)) {
28495 		err = ill_up_ipifs(ill, q, mp1);
28496 		if (err == EINPROGRESS)
28497 			return;
28498 	}
28499 
28500 	if (ill->ill_up_ipifs) {
28501 		ill_group_cleanup(ill);
28502 	}
28503 
28504 	/*
28505 	 * The ioctl must complete now without EINPROGRESS
28506 	 * since ipsq_pending_mp_get has removed the ioctl mblk
28507 	 * from ipsq_pending_mp. Otherwise the ioctl will be
28508 	 * stuck for ever in the ipsq.
28509 	 */
28510 	ASSERT(err != EINPROGRESS);
28511 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
28512 }
28513 
28514 /* Allocate the private structure */
28515 static int
28516 ip_priv_alloc(void **bufp)
28517 {
28518 	void	*buf;
28519 
28520 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28521 		return (ENOMEM);
28522 
28523 	*bufp = buf;
28524 	return (0);
28525 }
28526 
28527 /* Function to delete the private structure */
28528 void
28529 ip_priv_free(void *buf)
28530 {
28531 	ASSERT(buf != NULL);
28532 	kmem_free(buf, sizeof (ip_priv_t));
28533 }
28534 
28535 /*
28536  * The entry point for IPPF processing.
28537  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28538  * routine just returns.
28539  *
28540  * When called, ip_process generates an ipp_packet_t structure
28541  * which holds the state information for this packet and invokes the
28542  * the classifier (via ipp_packet_process). The classification, depending on
28543  * configured filters, results in a list of actions for this packet. Invoking
28544  * an action may cause the packet to be dropped, in which case the resulting
28545  * mblk (*mpp) is NULL. proc indicates the callout position for
28546  * this packet and ill_index is the interface this packet on or will leave
28547  * on (inbound and outbound resp.).
28548  */
28549 void
28550 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28551 {
28552 	mblk_t		*mp;
28553 	ip_priv_t	*priv;
28554 	ipp_action_id_t	aid;
28555 	int		rc = 0;
28556 	ipp_packet_t	*pp;
28557 #define	IP_CLASS	"ip"
28558 
28559 	/* If the classifier is not loaded, return  */
28560 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28561 		return;
28562 	}
28563 
28564 	mp = *mpp;
28565 	ASSERT(mp != NULL);
28566 
28567 	/* Allocate the packet structure */
28568 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28569 	if (rc != 0) {
28570 		*mpp = NULL;
28571 		freemsg(mp);
28572 		return;
28573 	}
28574 
28575 	/* Allocate the private structure */
28576 	rc = ip_priv_alloc((void **)&priv);
28577 	if (rc != 0) {
28578 		*mpp = NULL;
28579 		freemsg(mp);
28580 		ipp_packet_free(pp);
28581 		return;
28582 	}
28583 	priv->proc = proc;
28584 	priv->ill_index = ill_index;
28585 	ipp_packet_set_private(pp, priv, ip_priv_free);
28586 	ipp_packet_set_data(pp, mp);
28587 
28588 	/* Invoke the classifier */
28589 	rc = ipp_packet_process(&pp);
28590 	if (pp != NULL) {
28591 		mp = ipp_packet_get_data(pp);
28592 		ipp_packet_free(pp);
28593 		if (rc != 0) {
28594 			freemsg(mp);
28595 			*mpp = NULL;
28596 		}
28597 	} else {
28598 		*mpp = NULL;
28599 	}
28600 #undef	IP_CLASS
28601 }
28602 
28603 /*
28604  * Propagate a multicast group membership operation (add/drop) on
28605  * all the interfaces crossed by the related multirt routes.
28606  * The call is considered successful if the operation succeeds
28607  * on at least one interface.
28608  */
28609 static int
28610 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28611     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28612     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28613     mblk_t *first_mp)
28614 {
28615 	ire_t		*ire_gw;
28616 	irb_t		*irb;
28617 	int		error = 0;
28618 	opt_restart_t	*or;
28619 
28620 	irb = ire->ire_bucket;
28621 	ASSERT(irb != NULL);
28622 
28623 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28624 
28625 	or = (opt_restart_t *)first_mp->b_rptr;
28626 	IRB_REFHOLD(irb);
28627 	for (; ire != NULL; ire = ire->ire_next) {
28628 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28629 			continue;
28630 		if (ire->ire_addr != group)
28631 			continue;
28632 
28633 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28634 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28635 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28636 		/* No resolver exists for the gateway; skip this ire. */
28637 		if (ire_gw == NULL)
28638 			continue;
28639 
28640 		/*
28641 		 * This function can return EINPROGRESS. If so the operation
28642 		 * will be restarted from ip_restart_optmgmt which will
28643 		 * call ip_opt_set and option processing will restart for
28644 		 * this option. So we may end up calling 'fn' more than once.
28645 		 * This requires that 'fn' is idempotent except for the
28646 		 * return value. The operation is considered a success if
28647 		 * it succeeds at least once on any one interface.
28648 		 */
28649 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28650 		    NULL, fmode, src, first_mp);
28651 		if (error == 0)
28652 			or->or_private = CGTP_MCAST_SUCCESS;
28653 
28654 		if (ip_debug > 0) {
28655 			ulong_t	off;
28656 			char	*ksym;
28657 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28658 			ip2dbg(("ip_multirt_apply_membership: "
28659 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28660 			    "error %d [success %u]\n",
28661 			    ksym ? ksym : "?",
28662 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28663 			    error, or->or_private));
28664 		}
28665 
28666 		ire_refrele(ire_gw);
28667 		if (error == EINPROGRESS) {
28668 			IRB_REFRELE(irb);
28669 			return (error);
28670 		}
28671 	}
28672 	IRB_REFRELE(irb);
28673 	/*
28674 	 * Consider the call as successful if we succeeded on at least
28675 	 * one interface. Otherwise, return the last encountered error.
28676 	 */
28677 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28678 }
28679 
28680 
28681 /*
28682  * Issue a warning regarding a route crossing an interface with an
28683  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28684  * amount of time is logged.
28685  */
28686 static void
28687 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28688 {
28689 	hrtime_t	current = gethrtime();
28690 	char		buf[INET_ADDRSTRLEN];
28691 
28692 	/* Convert interval in ms to hrtime in ns */
28693 	if (multirt_bad_mtu_last_time +
28694 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28695 	    current) {
28696 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28697 		    "to %s, incorrect MTU %u (expected %u)\n",
28698 		    ip_dot_addr(ire->ire_addr, buf),
28699 		    ire->ire_max_frag, max_frag);
28700 
28701 		multirt_bad_mtu_last_time = current;
28702 	}
28703 }
28704 
28705 
28706 /*
28707  * Get the CGTP (multirouting) filtering status.
28708  * If 0, the CGTP hooks are transparent.
28709  */
28710 /* ARGSUSED */
28711 static int
28712 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28713 {
28714 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28715 
28716 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28717 	return (0);
28718 }
28719 
28720 
28721 /*
28722  * Set the CGTP (multirouting) filtering status.
28723  * If the status is changed from active to transparent
28724  * or from transparent to active, forward the new status
28725  * to the filtering module (if loaded).
28726  */
28727 /* ARGSUSED */
28728 static int
28729 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28730     cred_t *ioc_cr)
28731 {
28732 	long		new_value;
28733 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28734 
28735 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28736 	    new_value < 0 || new_value > 1) {
28737 		return (EINVAL);
28738 	}
28739 
28740 	/*
28741 	 * Do not enable CGTP filtering - thus preventing the hooks
28742 	 * from being invoked - if the version number of the
28743 	 * filtering module hooks does not match.
28744 	 */
28745 	if ((ip_cgtp_filter_ops != NULL) &&
28746 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28747 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28748 		    "(module hooks version %d, expecting %d)\n",
28749 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28750 		return (ENOTSUP);
28751 	}
28752 
28753 	if ((!*ip_cgtp_filter_value) && new_value) {
28754 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28755 		    ip_cgtp_filter_ops == NULL ?
28756 		    " (module not loaded)" : "");
28757 	}
28758 	if (*ip_cgtp_filter_value && (!new_value)) {
28759 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28760 		    ip_cgtp_filter_ops == NULL ?
28761 		    " (module not loaded)" : "");
28762 	}
28763 
28764 	if (ip_cgtp_filter_ops != NULL) {
28765 		int	res;
28766 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28767 			return (res);
28768 		}
28769 	}
28770 
28771 	*ip_cgtp_filter_value = (boolean_t)new_value;
28772 
28773 	return (0);
28774 }
28775 
28776 
28777 /*
28778  * Return the expected CGTP hooks version number.
28779  */
28780 int
28781 ip_cgtp_filter_supported(void)
28782 {
28783 	return (ip_cgtp_filter_rev);
28784 }
28785 
28786 
28787 /*
28788  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28789  * or by invoking this function. In the first case, the version number
28790  * of the registered structure is checked at hooks activation time
28791  * in ip_cgtp_filter_set().
28792  */
28793 int
28794 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28795 {
28796 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28797 		return (ENOTSUP);
28798 
28799 	ip_cgtp_filter_ops = ops;
28800 	return (0);
28801 }
28802 
28803 static squeue_func_t
28804 ip_squeue_switch(int val)
28805 {
28806 	squeue_func_t rval = squeue_fill;
28807 
28808 	switch (val) {
28809 	case IP_SQUEUE_ENTER_NODRAIN:
28810 		rval = squeue_enter_nodrain;
28811 		break;
28812 	case IP_SQUEUE_ENTER:
28813 		rval = squeue_enter;
28814 		break;
28815 	default:
28816 		break;
28817 	}
28818 	return (rval);
28819 }
28820 
28821 /* ARGSUSED */
28822 static int
28823 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28824     caddr_t addr, cred_t *cr)
28825 {
28826 	int *v = (int *)addr;
28827 	long new_value;
28828 
28829 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28830 		return (EINVAL);
28831 
28832 	ip_input_proc = ip_squeue_switch(new_value);
28833 	*v = new_value;
28834 	return (0);
28835 }
28836 
28837 /* ARGSUSED */
28838 static int
28839 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28840     caddr_t addr, cred_t *cr)
28841 {
28842 	int *v = (int *)addr;
28843 	long new_value;
28844 
28845 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28846 		return (EINVAL);
28847 
28848 	*v = new_value;
28849 	return (0);
28850 }
28851 
28852 static void
28853 ip_kstat_init(void)
28854 {
28855 	ip_named_kstat_t template = {
28856 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28857 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28858 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
28859 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28860 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28861 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
28862 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28863 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28864 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
28865 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
28866 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28867 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28868 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28869 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28870 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28871 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28872 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28873 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28874 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28875 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28876 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28877 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28878 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28879 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28880 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28881 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28882 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28883 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28884 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28885 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28886 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28887 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28888 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28889 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28890 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28891 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28892 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28893 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28894 	};
28895 
28896 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28897 					NUM_OF_FIELDS(ip_named_kstat_t),
28898 					0);
28899 	if (!ip_mibkp)
28900 		return;
28901 
28902 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28903 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28904 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28905 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28906 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28907 
28908 	template.netToMediaEntrySize.value.i32 =
28909 		sizeof (mib2_ipNetToMediaEntry_t);
28910 
28911 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28912 
28913 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28914 
28915 	ip_mibkp->ks_update = ip_kstat_update;
28916 
28917 	kstat_install(ip_mibkp);
28918 }
28919 
28920 static void
28921 ip_kstat_fini(void)
28922 {
28923 
28924 	if (ip_mibkp != NULL) {
28925 		kstat_delete(ip_mibkp);
28926 		ip_mibkp = NULL;
28927 	}
28928 }
28929 
28930 static int
28931 ip_kstat_update(kstat_t *kp, int rw)
28932 {
28933 	ip_named_kstat_t *ipkp;
28934 	mib2_ipIfStatsEntry_t ipmib;
28935 	ill_walk_context_t ctx;
28936 	ill_t *ill;
28937 
28938 	if (!kp || !kp->ks_data)
28939 		return (EIO);
28940 
28941 	if (rw == KSTAT_WRITE)
28942 		return (EACCES);
28943 
28944 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28945 
28946 	bcopy(&ip_mib, &ipmib, sizeof (ipmib));
28947 	rw_enter(&ill_g_lock, RW_READER);
28948 	ill = ILL_START_WALK_V4(&ctx);
28949 	for (; ill != NULL; ill = ill_next(&ctx, ill))
28950 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
28951 	rw_exit(&ill_g_lock);
28952 
28953 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
28954 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
28955 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
28956 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
28957 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
28958 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
28959 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
28960 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
28961 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
28962 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
28963 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
28964 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
28965 	ipkp->reasmTimeout.value.ui32 =		ip_g_frag_timeout;
28966 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
28967 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
28968 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
28969 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
28970 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
28971 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
28972 
28973 	ipkp->routingDiscards.value.ui32 =	0;
28974 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
28975 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
28976 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
28977 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
28978 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
28979 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
28980 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
28981 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
28982 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
28983 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
28984 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
28985 
28986 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
28987 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
28988 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
28989 
28990 	return (0);
28991 }
28992 
28993 static void
28994 icmp_kstat_init(void)
28995 {
28996 	icmp_named_kstat_t template = {
28997 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28998 		{ "inErrors",		KSTAT_DATA_UINT32 },
28999 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29000 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29001 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29002 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29003 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29004 		{ "inEchos",		KSTAT_DATA_UINT32 },
29005 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29006 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29007 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29008 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29009 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29010 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29011 		{ "outErrors",		KSTAT_DATA_UINT32 },
29012 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29013 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29014 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29015 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29016 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29017 		{ "outEchos",		KSTAT_DATA_UINT32 },
29018 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29019 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29020 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29021 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29022 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29023 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29024 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29025 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29026 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29027 		{ "outDrops",		KSTAT_DATA_UINT32 },
29028 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29029 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29030 	};
29031 
29032 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29033 					NUM_OF_FIELDS(icmp_named_kstat_t),
29034 					0);
29035 	if (icmp_mibkp == NULL)
29036 		return;
29037 
29038 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
29039 
29040 	icmp_mibkp->ks_update = icmp_kstat_update;
29041 
29042 	kstat_install(icmp_mibkp);
29043 }
29044 
29045 static void
29046 icmp_kstat_fini(void)
29047 {
29048 
29049 	if (icmp_mibkp != NULL) {
29050 		kstat_delete(icmp_mibkp);
29051 		icmp_mibkp = NULL;
29052 	}
29053 }
29054 
29055 static int
29056 icmp_kstat_update(kstat_t *kp, int rw)
29057 {
29058 	icmp_named_kstat_t *icmpkp;
29059 
29060 	if ((kp == NULL) || (kp->ks_data == NULL))
29061 		return (EIO);
29062 
29063 	if (rw == KSTAT_WRITE)
29064 		return (EACCES);
29065 
29066 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29067 
29068 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
29069 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
29070 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
29071 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
29072 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
29073 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
29074 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
29075 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
29076 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
29077 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
29078 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
29079 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
29080 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
29081 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
29082 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
29083 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
29084 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
29085 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
29086 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
29087 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
29088 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
29089 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
29090 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
29091 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
29092 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
29093 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
29094 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
29095 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
29096 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
29097 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
29098 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
29099 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
29100 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
29101 
29102 	return (0);
29103 }
29104 
29105 /*
29106  * This is the fanout function for raw socket opened for SCTP.  Note
29107  * that it is called after SCTP checks that there is no socket which
29108  * wants a packet.  Then before SCTP handles this out of the blue packet,
29109  * this function is called to see if there is any raw socket for SCTP.
29110  * If there is and it is bound to the correct address, the packet will
29111  * be sent to that socket.  Note that only one raw socket can be bound to
29112  * a port.  This is assured in ipcl_sctp_hash_insert();
29113  */
29114 void
29115 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29116     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29117     uint_t ipif_seqid, zoneid_t zoneid)
29118 {
29119 	conn_t		*connp;
29120 	queue_t		*rq;
29121 	mblk_t		*first_mp;
29122 	boolean_t	secure;
29123 	ip6_t		*ip6h;
29124 
29125 	first_mp = mp;
29126 	if (mctl_present) {
29127 		mp = first_mp->b_cont;
29128 		secure = ipsec_in_is_secure(first_mp);
29129 		ASSERT(mp != NULL);
29130 	} else {
29131 		secure = B_FALSE;
29132 	}
29133 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29134 
29135 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
29136 	if (connp == NULL) {
29137 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
29138 		    mctl_present);
29139 		return;
29140 	}
29141 	rq = connp->conn_rq;
29142 	if (!canputnext(rq)) {
29143 		CONN_DEC_REF(connp);
29144 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29145 		freemsg(first_mp);
29146 		return;
29147 	}
29148 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
29149 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
29150 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29151 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29152 		if (first_mp == NULL) {
29153 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29154 			CONN_DEC_REF(connp);
29155 			return;
29156 		}
29157 	}
29158 	/*
29159 	 * We probably should not send M_CTL message up to
29160 	 * raw socket.
29161 	 */
29162 	if (mctl_present)
29163 		freeb(first_mp);
29164 
29165 	/* Initiate IPPF processing here if needed. */
29166 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
29167 	    (!isv4 && IP6_IN_IPP(flags))) {
29168 		ip_process(IPP_LOCAL_IN, &mp,
29169 		    recv_ill->ill_phyint->phyint_ifindex);
29170 		if (mp == NULL) {
29171 			CONN_DEC_REF(connp);
29172 			return;
29173 		}
29174 	}
29175 
29176 	if (connp->conn_recvif || connp->conn_recvslla ||
29177 	    ((connp->conn_ipv6_recvpktinfo ||
29178 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29179 	    (flags & IP_FF_IP6INFO))) {
29180 		int in_flags = 0;
29181 
29182 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
29183 			in_flags = IPF_RECVIF;
29184 		}
29185 		if (connp->conn_recvslla) {
29186 			in_flags |= IPF_RECVSLLA;
29187 		}
29188 		if (isv4) {
29189 			mp = ip_add_info(mp, recv_ill, in_flags);
29190 		} else {
29191 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29192 			if (mp == NULL) {
29193 				BUMP_MIB(recv_ill->ill_ip_mib,
29194 				    ipIfStatsInDiscards);
29195 				CONN_DEC_REF(connp);
29196 				return;
29197 			}
29198 		}
29199 	}
29200 
29201 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29202 	/*
29203 	 * We are sending the IPSEC_IN message also up. Refer
29204 	 * to comments above this function.
29205 	 */
29206 	putnext(rq, mp);
29207 	CONN_DEC_REF(connp);
29208 }
29209 
29210 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29211 {									\
29212 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29213 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29214 }
29215 /*
29216  * This function should be called only if all packet processing
29217  * including fragmentation is complete. Callers of this function
29218  * must set mp->b_prev to one of these values:
29219  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29220  * prior to handing over the mp as first argument to this function.
29221  *
29222  * If the ire passed by caller is incomplete, this function
29223  * queues the packet and if necessary, sends ARP request and bails.
29224  * If the ire passed is fully resolved, we simply prepend
29225  * the link-layer header to the packet, do ipsec hw acceleration
29226  * work if necessary, and send the packet out on the wire.
29227  *
29228  * NOTE: IPSEC will only call this function with fully resolved
29229  * ires if hw acceleration is involved.
29230  * TODO list :
29231  * 	a Handle M_MULTIDATA so that
29232  *	  tcp_multisend->tcp_multisend_data can
29233  *	  call ip_xmit_v4 directly
29234  *	b Handle post-ARP work for fragments so that
29235  *	  ip_wput_frag can call this function.
29236  */
29237 ipxmit_state_t
29238 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29239 {
29240 	nce_t		*arpce;
29241 	queue_t		*q;
29242 	int		ill_index;
29243 	mblk_t		*nxt_mp, *first_mp;
29244 	boolean_t	xmit_drop = B_FALSE;
29245 	ip_proc_t	proc;
29246 	ill_t		*out_ill;
29247 	int		pkt_len;
29248 
29249 	arpce = ire->ire_nce;
29250 	ASSERT(arpce != NULL);
29251 
29252 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29253 
29254 	mutex_enter(&arpce->nce_lock);
29255 	switch (arpce->nce_state) {
29256 	case ND_REACHABLE:
29257 		/* If there are other queued packets, queue this packet */
29258 		if (arpce->nce_qd_mp != NULL) {
29259 			if (mp != NULL)
29260 				nce_queue_mp_common(arpce, mp, B_FALSE);
29261 			mp = arpce->nce_qd_mp;
29262 		}
29263 		arpce->nce_qd_mp = NULL;
29264 		mutex_exit(&arpce->nce_lock);
29265 
29266 		/*
29267 		 * Flush the queue.  In the common case, where the
29268 		 * ARP is already resolved,  it will go through the
29269 		 * while loop only once.
29270 		 */
29271 		while (mp != NULL) {
29272 
29273 			nxt_mp = mp->b_next;
29274 			mp->b_next = NULL;
29275 			ASSERT(mp->b_datap->db_type != M_CTL);
29276 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29277 			/*
29278 			 * This info is needed for IPQOS to do COS marking
29279 			 * in ip_wput_attach_llhdr->ip_process.
29280 			 */
29281 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29282 			mp->b_prev = NULL;
29283 
29284 			/* set up ill index for outbound qos processing */
29285 			out_ill = ire->ire_ipif->ipif_ill;
29286 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29287 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29288 			    ill_index);
29289 			if (first_mp == NULL) {
29290 				xmit_drop = B_TRUE;
29291 				BUMP_MIB(out_ill->ill_ip_mib,
29292 				    ipIfStatsOutDiscards);
29293 				goto next_mp;
29294 			}
29295 			/* non-ipsec hw accel case */
29296 			if (io == NULL || !io->ipsec_out_accelerated) {
29297 				/* send it */
29298 				q = ire->ire_stq;
29299 				if (proc == IPP_FWD_OUT) {
29300 					UPDATE_IB_PKT_COUNT(ire);
29301 				} else {
29302 					UPDATE_OB_PKT_COUNT(ire);
29303 				}
29304 				ire->ire_last_used_time = lbolt;
29305 
29306 				if (flow_ctl_enabled || canputnext(q))  {
29307 					if (proc == IPP_FWD_OUT) {
29308 						BUMP_MIB(out_ill->ill_ip_mib,
29309 						ipIfStatsHCOutForwDatagrams);
29310 					}
29311 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29312 					    pkt_len);
29313 
29314 					putnext(q, first_mp);
29315 				} else {
29316 					BUMP_MIB(out_ill->ill_ip_mib,
29317 					    ipIfStatsOutDiscards);
29318 					xmit_drop = B_TRUE;
29319 					freemsg(first_mp);
29320 				}
29321 			} else {
29322 				/*
29323 				 * Safety Pup says: make sure this
29324 				 *  is going to the right interface!
29325 				 */
29326 				ill_t *ill1 =
29327 				    (ill_t *)ire->ire_stq->q_ptr;
29328 				int ifindex =
29329 				    ill1->ill_phyint->phyint_ifindex;
29330 				if (ifindex !=
29331 				    io->ipsec_out_capab_ill_index) {
29332 					xmit_drop = B_TRUE;
29333 					freemsg(mp);
29334 				} else {
29335 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29336 					    pkt_len);
29337 					ipsec_hw_putnext(ire->ire_stq, mp);
29338 				}
29339 			}
29340 next_mp:
29341 			mp = nxt_mp;
29342 		} /* while (mp != NULL) */
29343 		if (xmit_drop)
29344 			return (SEND_FAILED);
29345 		else
29346 			return (SEND_PASSED);
29347 
29348 	case ND_INITIAL:
29349 	case ND_INCOMPLETE:
29350 
29351 		/*
29352 		 * While we do send off packets to dests that
29353 		 * use fully-resolved CGTP routes, we do not
29354 		 * handle unresolved CGTP routes.
29355 		 */
29356 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29357 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29358 
29359 		if (mp != NULL) {
29360 			/* queue the packet */
29361 			nce_queue_mp_common(arpce, mp, B_FALSE);
29362 		}
29363 
29364 		if (arpce->nce_state == ND_INCOMPLETE) {
29365 			mutex_exit(&arpce->nce_lock);
29366 			DTRACE_PROBE3(ip__xmit__incomplete,
29367 			    (ire_t *), ire, (mblk_t *), mp,
29368 			    (ipsec_out_t *), io);
29369 			return (LOOKUP_IN_PROGRESS);
29370 		}
29371 
29372 		arpce->nce_state = ND_INCOMPLETE;
29373 		mutex_exit(&arpce->nce_lock);
29374 		/*
29375 		 * Note that ire_add() (called from ire_forward())
29376 		 * holds a ref on the ire until ARP is completed.
29377 		 */
29378 
29379 		ire_arpresolve(ire, ire_to_ill(ire));
29380 		return (LOOKUP_IN_PROGRESS);
29381 	default:
29382 		ASSERT(0);
29383 		mutex_exit(&arpce->nce_lock);
29384 		return (LLHDR_RESLV_FAILED);
29385 	}
29386 }
29387 
29388 #undef	UPDATE_IP_MIB_OB_COUNTERS
29389 
29390 /*
29391  * Return B_TRUE if the buffers differ in length or content.
29392  * This is used for comparing extension header buffers.
29393  * Note that an extension header would be declared different
29394  * even if all that changed was the next header value in that header i.e.
29395  * what really changed is the next extension header.
29396  */
29397 boolean_t
29398 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29399     uint_t blen)
29400 {
29401 	if (!b_valid)
29402 		blen = 0;
29403 
29404 	if (alen != blen)
29405 		return (B_TRUE);
29406 	if (alen == 0)
29407 		return (B_FALSE);	/* Both zero length */
29408 	return (bcmp(abuf, bbuf, alen));
29409 }
29410 
29411 /*
29412  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29413  * Return B_FALSE if memory allocation fails - don't change any state!
29414  */
29415 boolean_t
29416 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29417     const void *src, uint_t srclen)
29418 {
29419 	void *dst;
29420 
29421 	if (!src_valid)
29422 		srclen = 0;
29423 
29424 	ASSERT(*dstlenp == 0);
29425 	if (src != NULL && srclen != 0) {
29426 		dst = mi_alloc(srclen, BPRI_MED);
29427 		if (dst == NULL)
29428 			return (B_FALSE);
29429 	} else {
29430 		dst = NULL;
29431 	}
29432 	if (*dstp != NULL)
29433 		mi_free(*dstp);
29434 	*dstp = dst;
29435 	*dstlenp = dst == NULL ? 0 : srclen;
29436 	return (B_TRUE);
29437 }
29438 
29439 /*
29440  * Replace what is in *dst, *dstlen with the source.
29441  * Assumes ip_allocbuf has already been called.
29442  */
29443 void
29444 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29445     const void *src, uint_t srclen)
29446 {
29447 	if (!src_valid)
29448 		srclen = 0;
29449 
29450 	ASSERT(*dstlenp == srclen);
29451 	if (src != NULL && srclen != 0)
29452 		bcopy(src, *dstp, srclen);
29453 }
29454 
29455 /*
29456  * Free the storage pointed to by the members of an ip6_pkt_t.
29457  */
29458 void
29459 ip6_pkt_free(ip6_pkt_t *ipp)
29460 {
29461 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29462 
29463 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29464 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29465 		ipp->ipp_hopopts = NULL;
29466 		ipp->ipp_hopoptslen = 0;
29467 	}
29468 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29469 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29470 		ipp->ipp_rtdstopts = NULL;
29471 		ipp->ipp_rtdstoptslen = 0;
29472 	}
29473 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29474 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29475 		ipp->ipp_dstopts = NULL;
29476 		ipp->ipp_dstoptslen = 0;
29477 	}
29478 	if (ipp->ipp_fields & IPPF_RTHDR) {
29479 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29480 		ipp->ipp_rthdr = NULL;
29481 		ipp->ipp_rthdrlen = 0;
29482 	}
29483 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29484 	    IPPF_RTHDR);
29485 }
29486