xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 4cb70d33a0347eb8a72054ff37d58fb4b7fb185f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_ftable.h>
87 #include <inet/ip_rts.h>
88 #include <inet/optcom.h>
89 #include <inet/ip_ndp.h>
90 #include <inet/ip_listutils.h>
91 #include <netinet/igmp.h>
92 #include <netinet/ip_mroute.h>
93 #include <inet/ipp_common.h>
94 
95 #include <net/pfkeyv2.h>
96 #include <inet/ipsec_info.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <sys/iphada.h>
100 #include <inet/tun.h>
101 #include <inet/ipdrop.h>
102 
103 #include <sys/ethernet.h>
104 #include <net/if_types.h>
105 #include <sys/cpuvar.h>
106 
107 #include <ipp/ipp.h>
108 #include <ipp/ipp_impl.h>
109 #include <ipp/ipgpc/ipgpc.h>
110 
111 #include <sys/multidata.h>
112 #include <sys/pattr.h>
113 
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 
119 #include <sys/tsol/label.h>
120 #include <sys/tsol/tnet.h>
121 
122 #include <rpc/pmap_prot.h>
123 
124 /*
125  * Values for squeue switch:
126  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
127  * IP_SQUEUE_ENTER: squeue_enter
128  * IP_SQUEUE_FILL: squeue_fill
129  */
130 int ip_squeue_enter = 2;
131 squeue_func_t ip_input_proc;
132 /*
133  * IP statistics.
134  */
135 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
136 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 typedef struct ip_stat {
140 	kstat_named_t	ipsec_fanout_proto;
141 	kstat_named_t	ip_udp_fannorm;
142 	kstat_named_t	ip_udp_fanmb;
143 	kstat_named_t	ip_udp_fanothers;
144 	kstat_named_t	ip_udp_fast_path;
145 	kstat_named_t	ip_udp_slow_path;
146 	kstat_named_t	ip_udp_input_err;
147 	kstat_named_t	ip_tcppullup;
148 	kstat_named_t	ip_tcpoptions;
149 	kstat_named_t	ip_multipkttcp;
150 	kstat_named_t	ip_tcp_fast_path;
151 	kstat_named_t	ip_tcp_slow_path;
152 	kstat_named_t	ip_tcp_input_error;
153 	kstat_named_t	ip_db_ref;
154 	kstat_named_t	ip_notaligned1;
155 	kstat_named_t	ip_notaligned2;
156 	kstat_named_t	ip_multimblk3;
157 	kstat_named_t	ip_multimblk4;
158 	kstat_named_t	ip_ipoptions;
159 	kstat_named_t	ip_classify_fail;
160 	kstat_named_t	ip_opt;
161 	kstat_named_t	ip_udp_rput_local;
162 	kstat_named_t	ipsec_proto_ahesp;
163 	kstat_named_t	ip_conn_flputbq;
164 	kstat_named_t	ip_conn_walk_drain;
165 	kstat_named_t   ip_out_sw_cksum;
166 	kstat_named_t   ip_in_sw_cksum;
167 	kstat_named_t   ip_trash_ire_reclaim_calls;
168 	kstat_named_t   ip_trash_ire_reclaim_success;
169 	kstat_named_t   ip_ire_arp_timer_expired;
170 	kstat_named_t   ip_ire_redirect_timer_expired;
171 	kstat_named_t	ip_ire_pmtu_timer_expired;
172 	kstat_named_t	ip_input_multi_squeue;
173 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
174 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
175 	kstat_named_t	ip_tcp_in_sw_cksum_err;
176 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
177 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
178 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
179 	kstat_named_t	ip_udp_in_sw_cksum_err;
180 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
181 	kstat_named_t	ip_frag_mdt_pkt_out;
182 	kstat_named_t	ip_frag_mdt_discarded;
183 	kstat_named_t	ip_frag_mdt_allocfail;
184 	kstat_named_t	ip_frag_mdt_addpdescfail;
185 	kstat_named_t	ip_frag_mdt_allocd;
186 } ip_stat_t;
187 
188 static ip_stat_t ip_statistics = {
189 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
190 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
191 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
192 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
196 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
197 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
198 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
201 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
202 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
203 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
204 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
205 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
206 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
207 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
208 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
209 	{ "ip_opt",				KSTAT_DATA_UINT64 },
210 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
211 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
212 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
213 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
214 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
215 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
216 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
217 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
218 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
219 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
220 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
221 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
222 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
223 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
224 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
226 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
228 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
230 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
231 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
232 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
235 };
236 
237 static kstat_t *ip_kstat;
238 
239 #define	TCP6 "tcp6"
240 #define	TCP "tcp"
241 #define	SCTP "sctp"
242 #define	SCTP6 "sctp6"
243 
244 major_t TCP6_MAJ;
245 major_t TCP_MAJ;
246 major_t SCTP_MAJ;
247 major_t SCTP6_MAJ;
248 
249 int ip_poll_normal_ms = 100;
250 int ip_poll_normal_ticks = 0;
251 
252 /*
253  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
254  */
255 
256 struct listptr_s {
257 	mblk_t	*lp_head;	/* pointer to the head of the list */
258 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
259 };
260 
261 typedef struct listptr_s listptr_t;
262 
263 /*
264  * This is used by ip_snmp_get_mib2_ip_route_media and
265  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
266  */
267 typedef struct iproutedata_s {
268 	uint_t		ird_idx;
269 	listptr_t	ird_route;	/* ipRouteEntryTable */
270 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
271 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
272 } iproutedata_t;
273 
274 /*
275  * Cluster specific hooks. These should be NULL when booted as a non-cluster
276  */
277 
278 /*
279  * Hook functions to enable cluster networking
280  * On non-clustered systems these vectors must always be NULL.
281  *
282  * Hook function to Check ip specified ip address is a shared ip address
283  * in the cluster
284  *
285  */
286 int (*cl_inet_isclusterwide)(uint8_t protocol,
287     sa_family_t addr_family, uint8_t *laddrp) = NULL;
288 
289 /*
290  * Hook function to generate cluster wide ip fragment identifier
291  */
292 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
293     uint8_t *laddrp, uint8_t *faddrp) = NULL;
294 
295 /*
296  * Synchronization notes:
297  *
298  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
299  * MT level protection given by STREAMS. IP uses a combination of its own
300  * internal serialization mechanism and standard Solaris locking techniques.
301  * The internal serialization is per phyint (no IPMP) or per IPMP group.
302  * This is used to serialize plumbing operations, IPMP operations, certain
303  * multicast operations, most set ioctls, igmp/mld timers etc.
304  *
305  * Plumbing is a long sequence of operations involving message
306  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
307  * involved in plumbing operations. A natural model is to serialize these
308  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
309  * parallel without any interference. But various set ioctls on hme0 are best
310  * serialized. However if the system uses IPMP, the operations are easier if
311  * they are serialized on a per IPMP group basis since IPMP operations
312  * happen across ill's of a group. Thus the lowest common denominator is to
313  * serialize most set ioctls, multicast join/leave operations, IPMP operations
314  * igmp/mld timer operations, and processing of DLPI control messages received
315  * from drivers on a per IPMP group basis. If the system does not employ
316  * IPMP the serialization is on a per phyint basis. This serialization is
317  * provided by the ipsq_t and primitives operating on this. Details can
318  * be found in ip_if.c above the core primitives operating on ipsq_t.
319  *
320  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
321  * Simiarly lookup of an ire by a thread also returns a refheld ire.
322  * In addition ipif's and ill's referenced by the ire are also indirectly
323  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
324  * the ipif's address or netmask change as long as an ipif is refheld
325  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
326  * address of an ipif has to go through the ipsq_t. This ensures that only
327  * 1 such exclusive operation proceeds at any time on the ipif. It then
328  * deletes all ires associated with this ipif, and waits for all refcnts
329  * associated with this ipif to come down to zero. The address is changed
330  * only after the ipif has been quiesced. Then the ipif is brought up again.
331  * More details are described above the comment in ip_sioctl_flags.
332  *
333  * Packet processing is based mostly on IREs and are fully multi-threaded
334  * using standard Solaris MT techniques.
335  *
336  * There are explicit locks in IP to handle:
337  * - The ip_g_head list maintained by mi_open_link() and friends.
338  *
339  * - The reassembly data structures (one lock per hash bucket)
340  *
341  * - conn_lock is meant to protect conn_t fields. The fields actually
342  *   protected by conn_lock are documented in the conn_t definition.
343  *
344  * - ire_lock to protect some of the fields of the ire, IRE tables
345  *   (one lock per hash bucket). Refer to ip_ire.c for details.
346  *
347  * - ndp_g_lock and nce_lock for protecting NCEs.
348  *
349  * - ill_lock protects fields of the ill and ipif. Details in ip.h
350  *
351  * - ill_g_lock: This is a global reader/writer lock. Protects the following
352  *	* The AVL tree based global multi list of all ills.
353  *	* The linked list of all ipifs of an ill
354  *	* The <ill-ipsq> mapping
355  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
356  *	* The illgroup list threaded by ill_group_next.
357  *	* <ill-phyint> association
358  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
359  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
360  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
361  *   will all have to hold the ill_g_lock as writer for the actual duration
362  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
363  *   may be found in the IPMP section.
364  *
365  * - ill_lock:  This is a per ill mutex.
366  *   It protects some members of the ill and is documented below.
367  *   It also protects the <ill-ipsq> mapping
368  *   It also protects the illgroup list threaded by ill_group_next.
369  *   It also protects the <ill-phyint> assoc.
370  *   It also protects the list of ipifs hanging off the ill.
371  *
372  * - ipsq_lock: This is a per ipsq_t mutex lock.
373  *   This protects all the other members of the ipsq struct except
374  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
375  *
376  * - illgrp_lock: This is a per ill_group mutex lock.
377  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
378  *   which dictates which is the next ill in an ill_group that is to be chosen
379  *   for sending outgoing packets, through creation of an IRE_CACHE that
380  *   references this ill.
381  *
382  * - phyint_lock: This is a per phyint mutex lock. Protects just the
383  *   phyint_flags
384  *
385  * - ip_g_nd_lock: This is a global reader/writer lock.
386  *   Any call to nd_load to load a new parameter to the ND table must hold the
387  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
388  *   as reader.
389  *
390  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
391  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
392  *   uniqueness check also done atomically.
393  *
394  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
395  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
396  *   as a writer when adding or deleting elements from these lists, and
397  *   as a reader when walking these lists to send a SADB update to the
398  *   IPsec capable ills.
399  *
400  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
401  *   group list linked by ill_usesrc_grp_next. It also protects the
402  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
403  *   group is being added or deleted.  This lock is taken as a reader when
404  *   walking the list/group(eg: to get the number of members in a usesrc group).
405  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
406  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
407  *   example, it is not necessary to take this lock in the initial portion
408  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
409  *   ip_sioctl_flags since the these operations are executed exclusively and
410  *   that ensures that the "usesrc group state" cannot change. The "usesrc
411  *   group state" change can happen only in the latter part of
412  *   ip_sioctl_slifusesrc and in ill_delete.
413  *
414  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
415  *
416  * To change the <ill-phyint> association, the ill_g_lock must be held
417  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
418  * must be held.
419  *
420  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
421  * and the ill_lock of the ill in question must be held.
422  *
423  * To change the <ill-illgroup> association the ill_g_lock must be held as
424  * writer and the ill_lock of the ill in question must be held.
425  *
426  * To add or delete an ipif from the list of ipifs hanging off the ill,
427  * ill_g_lock (writer) and ill_lock must be held and the thread must be
428  * a writer on the associated ipsq,.
429  *
430  * To add or delete an ill to the system, the ill_g_lock must be held as
431  * writer and the thread must be a writer on the associated ipsq.
432  *
433  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
434  * must be a writer on the associated ipsq.
435  *
436  * Lock hierarchy
437  *
438  * Some lock hierarchy scenarios are listed below.
439  *
440  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
441  * ill_g_lock -> illgrp_lock -> ill_lock
442  * ill_g_lock -> ill_lock(s) -> phyint_lock
443  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
444  * ill_g_lock -> ip_addr_avail_lock
445  * conn_lock -> irb_lock -> ill_lock -> ire_lock
446  * ill_g_lock -> ip_g_nd_lock
447  *
448  * When more than 1 ill lock is needed to be held, all ill lock addresses
449  * are sorted on address and locked starting from highest addressed lock
450  * downward.
451  *
452  * Mobile-IP scenarios
453  *
454  * irb_lock -> ill_lock -> ire_mrtun_lock
455  * irb_lock -> ill_lock -> ire_srcif_table_lock
456  *
457  * IPsec scenarios
458  *
459  * ipsa_lock -> ill_g_lock -> ill_lock
460  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
461  * ipsec_capab_ills_lock -> ipsa_lock
462  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
463  *
464  * Trusted Solaris scenarios
465  *
466  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
467  * igsa_lock -> gcdb_lock
468  * gcgrp_rwlock -> ire_lock
469  * gcgrp_rwlock -> gcdb_lock
470  *
471  *
472  * Routing/forwarding table locking notes:
473  *
474  * Lock acquisition order: Radix tree lock, irb_lock.
475  * Requirements:
476  * i.  Walker must not hold any locks during the walker callback.
477  * ii  Walker must not see a truncated tree during the walk because of any node
478  *     deletion.
479  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
480  *     in many places in the code to walk the irb list. Thus even if all the
481  *     ires in a bucket have been deleted, we still can't free the radix node
482  *     until the ires have actually been inactive'd (freed).
483  *
484  * Tree traversal - Need to hold the global tree lock in read mode.
485  * Before dropping the global tree lock, need to either increment the ire_refcnt
486  * to ensure that the radix node can't be deleted.
487  *
488  * Tree add - Need to hold the global tree lock in write mode to add a
489  * radix node. To prevent the node from being deleted, increment the
490  * irb_refcnt, after the node is added to the tree. The ire itself is
491  * added later while holding the irb_lock, but not the tree lock.
492  *
493  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
494  * All associated ires must be inactive (i.e. freed), and irb_refcnt
495  * must be zero.
496  *
497  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
498  * global tree lock (read mode) for traversal.
499  *
500  * IPSEC notes :
501  *
502  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
503  * in front of the actual packet. For outbound datagrams, the M_CTL
504  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
505  * information used by the IPSEC code for applying the right level of
506  * protection. The information initialized by IP in the ipsec_out_t
507  * is determined by the per-socket policy or global policy in the system.
508  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
509  * ipsec_info.h) which starts out with nothing in it. It gets filled
510  * with the right information if it goes through the AH/ESP code, which
511  * happens if the incoming packet is secure. The information initialized
512  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
513  * the policy requirements needed by per-socket policy or global policy
514  * is met or not.
515  *
516  * If there is both per-socket policy (set using setsockopt) and there
517  * is also global policy match for the 5 tuples of the socket,
518  * ipsec_override_policy() makes the decision of which one to use.
519  *
520  * For fully connected sockets i.e dst, src [addr, port] is known,
521  * conn_policy_cached is set indicating that policy has been cached.
522  * conn_in_enforce_policy may or may not be set depending on whether
523  * there is a global policy match or per-socket policy match.
524  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
525  * Once the right policy is set on the conn_t, policy cannot change for
526  * this socket. This makes life simpler for TCP (UDP ?) where
527  * re-transmissions go out with the same policy. For symmetry, policy
528  * is cached for fully connected UDP sockets also. Thus if policy is cached,
529  * it also implies that policy is latched i.e policy cannot change
530  * on these sockets. As we have the right policy on the conn, we don't
531  * have to lookup global policy for every outbound and inbound datagram
532  * and thus serving as an optimization. Note that a global policy change
533  * does not affect fully connected sockets if they have policy. If fully
534  * connected sockets did not have any policy associated with it, global
535  * policy change may affect them.
536  *
537  * IP Flow control notes:
538  *
539  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
540  * cannot be sent down to the driver by IP, because of a canput failure, IP
541  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
542  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
543  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
544  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
545  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
546  * the queued messages, and removes the conn from the drain list, if all
547  * messages were drained. It also qenables the next conn in the drain list to
548  * continue the drain process.
549  *
550  * In reality the drain list is not a single list, but a configurable number
551  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
552  * list. If the ip_wsrv of the next qenabled conn does not run, because the
553  * stream closes, ip_close takes responsibility to qenable the next conn in
554  * the drain list. The directly called ip_wput path always does a putq, if
555  * it cannot putnext. Thus synchronization problems are handled between
556  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
557  * functions that manipulate this drain list. Furthermore conn_drain_insert
558  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
559  * running on a queue at any time. conn_drain_tail can be simultaneously called
560  * from both ip_wsrv and ip_close.
561  *
562  * IPQOS notes:
563  *
564  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
565  * and IPQoS modules. IPPF includes hooks in IP at different control points
566  * (callout positions) which direct packets to IPQoS modules for policy
567  * processing. Policies, if present, are global.
568  *
569  * The callout positions are located in the following paths:
570  *		o local_in (packets destined for this host)
571  *		o local_out (packets orginating from this host )
572  *		o fwd_in  (packets forwarded by this m/c - inbound)
573  *		o fwd_out (packets forwarded by this m/c - outbound)
574  * Hooks at these callout points can be enabled/disabled using the ndd variable
575  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
576  * By default all the callout positions are enabled.
577  *
578  * Outbound (local_out)
579  * Hooks are placed in ip_wput_ire and ipsec_out_process.
580  *
581  * Inbound (local_in)
582  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
583  * TCP and UDP fanout routines.
584  *
585  * Forwarding (in and out)
586  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
587  *
588  * IP Policy Framework processing (IPPF processing)
589  * Policy processing for a packet is initiated by ip_process, which ascertains
590  * that the classifier (ipgpc) is loaded and configured, failing which the
591  * packet resumes normal processing in IP. If the clasifier is present, the
592  * packet is acted upon by one or more IPQoS modules (action instances), per
593  * filters configured in ipgpc and resumes normal IP processing thereafter.
594  * An action instance can drop a packet in course of its processing.
595  *
596  * A boolean variable, ip_policy, is used in all the fanout routines that can
597  * invoke ip_process for a packet. This variable indicates if the packet should
598  * to be sent for policy processing. The variable is set to B_TRUE by default,
599  * i.e. when the routines are invoked in the normal ip procesing path for a
600  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
601  * ip_policy is set to B_FALSE for all the routines called in these two
602  * functions because, in the former case,  we don't process loopback traffic
603  * currently while in the latter, the packets have already been processed in
604  * icmp_inbound.
605  *
606  * Zones notes:
607  *
608  * The partitioning rules for networking are as follows:
609  * 1) Packets coming from a zone must have a source address belonging to that
610  * zone.
611  * 2) Packets coming from a zone can only be sent on a physical interface on
612  * which the zone has an IP address.
613  * 3) Between two zones on the same machine, packet delivery is only allowed if
614  * there's a matching route for the destination and zone in the forwarding
615  * table.
616  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
617  * different zones can bind to the same port with the wildcard address
618  * (INADDR_ANY).
619  *
620  * The granularity of interface partitioning is at the logical interface level.
621  * Therefore, every zone has its own IP addresses, and incoming packets can be
622  * attributed to a zone unambiguously. A logical interface is placed into a zone
623  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
624  * structure. Rule (1) is implemented by modifying the source address selection
625  * algorithm so that the list of eligible addresses is filtered based on the
626  * sending process zone.
627  *
628  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
629  * across all zones, depending on their type. Here is the break-up:
630  *
631  * IRE type				Shared/exclusive
632  * --------				----------------
633  * IRE_BROADCAST			Exclusive
634  * IRE_DEFAULT (default routes)		Shared (*)
635  * IRE_LOCAL				Exclusive
636  * IRE_LOOPBACK				Exclusive
637  * IRE_PREFIX (net routes)		Shared (*)
638  * IRE_CACHE				Exclusive
639  * IRE_IF_NORESOLVER (interface routes)	Exclusive
640  * IRE_IF_RESOLVER (interface routes)	Exclusive
641  * IRE_HOST (host routes)		Shared (*)
642  *
643  * (*) A zone can only use a default or off-subnet route if the gateway is
644  * directly reachable from the zone, that is, if the gateway's address matches
645  * one of the zone's logical interfaces.
646  *
647  * Multiple zones can share a common broadcast address; typically all zones
648  * share the 255.255.255.255 address. Incoming as well as locally originated
649  * broadcast packets must be dispatched to all the zones on the broadcast
650  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
651  * since some zones may not be on the 10.16.72/24 network. To handle this, each
652  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
653  * sent to every zone that has an IRE_BROADCAST entry for the destination
654  * address on the input ill, see conn_wantpacket().
655  *
656  * Applications in different zones can join the same multicast group address.
657  * For IPv4, group memberships are per-logical interface, so they're already
658  * inherently part of a zone. For IPv6, group memberships are per-physical
659  * interface, so we distinguish IPv6 group memberships based on group address,
660  * interface and zoneid. In both cases, received multicast packets are sent to
661  * every zone for which a group membership entry exists. On IPv6 we need to
662  * check that the target zone still has an address on the receiving physical
663  * interface; it could have been removed since the application issued the
664  * IPV6_JOIN_GROUP.
665  */
666 
667 /*
668  * Squeue Fanout flags:
669  *	0: No fanout.
670  *	1: Fanout across all squeues
671  */
672 boolean_t	ip_squeue_fanout = 0;
673 
674 /*
675  * Maximum dups allowed per packet.
676  */
677 uint_t ip_max_frag_dups = 10;
678 
679 #define	IS_SIMPLE_IPH(ipha)						\
680 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
681 
682 /* RFC1122 Conformance */
683 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
684 
685 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
686 
687 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
688 
689 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
690 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
691 
692 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
693 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
694     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
695 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
696 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
697 		    mblk_t *, int);
698 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
699 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
700 		    ill_t *, zoneid_t);
701 static void	icmp_options_update(ipha_t *);
702 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
703 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
704 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
705 static void	icmp_redirect(mblk_t *);
706 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
707 
708 static void	ip_arp_news(queue_t *, mblk_t *);
709 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
710 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
711 char		*ip_dot_addr(ipaddr_t, char *);
712 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
713 int		ip_close(queue_t *, int);
714 static char	*ip_dot_saddr(uchar_t *, char *);
715 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
716 		    boolean_t, boolean_t, ill_t *, zoneid_t);
717 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
718 		    boolean_t, boolean_t, zoneid_t);
719 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
720 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
721 static void	ip_lrput(queue_t *, mblk_t *);
722 ipaddr_t	ip_massage_options(ipha_t *);
723 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
724 ipaddr_t	ip_net_mask(ipaddr_t);
725 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
726 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
727 		    conn_t *, uint32_t);
728 char		*ip_nv_lookup(nv_t *, int);
729 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
730 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
731 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
732 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
733 			    size_t);
734 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
735 void	ip_rput(queue_t *, mblk_t *);
736 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
737 		    void *dummy_arg);
738 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
739 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
740 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
741 			    ire_t *);
742 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
743 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
744 		    uint16_t *);
745 int		ip_snmp_get(queue_t *, mblk_t *);
746 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
747 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
748 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
749 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
750 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
751 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
752 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
753 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
754 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
755 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
756 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
757 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
758 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
759 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
760 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
761 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
762 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
763 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
764 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
765 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
766 static boolean_t	ip_source_routed(ipha_t *);
767 static boolean_t	ip_source_route_included(ipha_t *);
768 
769 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
770 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
771 static void	ip_wput_local_options(ipha_t *);
772 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
773     zoneid_t);
774 
775 static void	conn_drain_init(void);
776 static void	conn_drain_fini(void);
777 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
778 
779 static void	conn_walk_drain(void);
780 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
781     zoneid_t);
782 
783 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
784     zoneid_t);
785 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
786     void *dummy_arg);
787 
788 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
789 
790 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
791     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
792     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
793 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
794 
795 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
796 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
797     caddr_t, cred_t *);
798 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
799     caddr_t cp, cred_t *cr);
800 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
801     cred_t *);
802 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
803     caddr_t cp, cred_t *cr);
804 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
805     cred_t *);
806 static squeue_func_t ip_squeue_switch(int);
807 
808 static void	ip_kstat_init(void);
809 static void	ip_kstat_fini(void);
810 static int	ip_kstat_update(kstat_t *kp, int rw);
811 static void	icmp_kstat_init(void);
812 static void	icmp_kstat_fini(void);
813 static int	icmp_kstat_update(kstat_t *kp, int rw);
814 
815 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
816 
817 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
818     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
819 
820 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
821 
822 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
823     ipha_t *, ill_t *, boolean_t);
824 
825 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
826 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
827 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
828 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
829 
830 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
831 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
832 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
833 
834 /* How long, in seconds, we allow frags to hang around. */
835 #define	IP_FRAG_TIMEOUT	60
836 
837 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
838 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
839 
840 /*
841  * Threshold which determines whether MDT should be used when
842  * generating IP fragments; payload size must be greater than
843  * this threshold for MDT to take place.
844  */
845 #define	IP_WPUT_FRAG_MDT_MIN	32768
846 
847 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
848 
849 /* Protected by ip_mi_lock */
850 static void	*ip_g_head;		/* Instance Data List Head */
851 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
852 
853 /* Only modified during _init and _fini thus no locking is needed. */
854 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
855 
856 
857 static long ip_rput_pullups;
858 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
859 
860 vmem_t *ip_minor_arena;
861 
862 /*
863  * MIB-2 stuff for SNMP (both IP and ICMP)
864  */
865 mib2_ip_t	ip_mib;
866 mib2_icmp_t	icmp_mib;
867 
868 #ifdef DEBUG
869 uint32_t ipsechw_debug = 0;
870 #endif
871 
872 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
873 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
874 
875 uint_t	loopback_packets = 0;
876 
877 /*
878  * Multirouting/CGTP stuff
879  */
880 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
881 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
882 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
883 /* Interval (in ms) between consecutive 'bad MTU' warnings */
884 hrtime_t ip_multirt_log_interval = 1000;
885 /* Time since last warning issued. */
886 static hrtime_t	multirt_bad_mtu_last_time = 0;
887 
888 kmutex_t ip_trash_timer_lock;
889 krwlock_t ip_g_nd_lock;
890 
891 /*
892  * XXX following really should only be in a header. Would need more
893  * header and .c clean up first.
894  */
895 extern optdb_obj_t	ip_opt_obj;
896 
897 ulong_t ip_squeue_enter_unbound = 0;
898 
899 /*
900  * Named Dispatch Parameter Table.
901  * All of these are alterable, within the min/max values given, at run time.
902  */
903 static ipparam_t	lcl_param_arr[] = {
904 	/* min	max	value	name */
905 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
906 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
907 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
908 	{  0,	1,	0,	"ip_respond_to_timestamp"},
909 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
910 	{  0,	1,	1,	"ip_send_redirects"},
911 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
912 	{  0,	10,	0,	"ip_debug"},
913 	{  0,	10,	0,	"ip_mrtdebug"},
914 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
915 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
916 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
917 	{  1,	255,	255,	"ip_def_ttl" },
918 	{  0,	1,	0,	"ip_forward_src_routed"},
919 	{  0,	256,	32,	"ip_wroff_extra" },
920 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
921 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
922 	{  0,	1,	1,	"ip_path_mtu_discovery" },
923 	{  0,	240,	30,	"ip_ignore_delete_time" },
924 	{  0,	1,	0,	"ip_ignore_redirect" },
925 	{  0,	1,	1,	"ip_output_queue" },
926 	{  1,	254,	1,	"ip_broadcast_ttl" },
927 	{  0,	99999,	100,	"ip_icmp_err_interval" },
928 	{  1,	99999,	10,	"ip_icmp_err_burst" },
929 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
930 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
931 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
932 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
933 	{  0,	1,	1,	"icmp_accept_clear_messages" },
934 	{  0,	1,	1,	"igmp_accept_clear_messages" },
935 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
936 				"ip_ndp_delay_first_probe_time"},
937 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
938 				"ip_ndp_max_unicast_solicit"},
939 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
940 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
941 	{  0,	1,	0,	"ip6_forward_src_routed"},
942 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
943 	{  0,	1,	1,	"ip6_send_redirects"},
944 	{  0,	1,	0,	"ip6_ignore_redirect" },
945 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
946 
947 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
948 
949 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
950 
951 	{  0,	1,	1,	"pim_accept_clear_messages" },
952 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
953 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
954 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
955 	{  0,	15,	0,	"ip_policy_mask" },
956 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
957 	{  0,	255,	1,	"ip_multirt_ttl" },
958 	{  0,	1,	1,	"ip_multidata_outbound" },
959 #ifdef DEBUG
960 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
961 #endif
962 };
963 
964 ipparam_t	*ip_param_arr = lcl_param_arr;
965 
966 /* Extended NDP table */
967 static ipndp_t	lcl_ndp_arr[] = {
968 	/* getf			setf		data			name */
969 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
970 	    "ip_forwarding" },
971 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
972 	    "ip6_forwarding" },
973 	{  ip_ill_report,	NULL,		NULL,
974 	    "ip_ill_status" },
975 	{  ip_ipif_report,	NULL,		NULL,
976 	    "ip_ipif_status" },
977 	{  ip_ire_report,	NULL,		NULL,
978 	    "ipv4_ire_status" },
979 	{  ip_ire_report_mrtun,	NULL,		NULL,
980 	    "ipv4_mrtun_ire_status" },
981 	{  ip_ire_report_srcif,	NULL,		NULL,
982 	    "ipv4_srcif_ire_status" },
983 	{  ip_ire_report_v6,	NULL,		NULL,
984 	    "ipv6_ire_status" },
985 	{  ip_conn_report,	NULL,		NULL,
986 	    "ip_conn_status" },
987 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
988 	    "ip_rput_pullups" },
989 	{  ndp_report,		NULL,		NULL,
990 	    "ip_ndp_cache_report" },
991 	{  ip_srcid_report,	NULL,		NULL,
992 	    "ip_srcid_status" },
993 	{ ip_param_generic_get, ip_squeue_profile_set,
994 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
995 	{ ip_param_generic_get, ip_squeue_bind_set,
996 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
997 	{ ip_param_generic_get, ip_input_proc_set,
998 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
999 	{ ip_param_generic_get, ip_int_set,
1000 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1001 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1002 	    "ip_cgtp_filter" },
1003 	{ ip_param_generic_get, ip_int_set,
1004 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1005 };
1006 
1007 /*
1008  * ip_g_forward controls IP forwarding.  It takes two values:
1009  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1010  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1011  *
1012  * RFC1122 says there must be a configuration switch to control forwarding,
1013  * but that the default MUST be to not forward packets ever.  Implicit
1014  * control based on configuration of multiple interfaces MUST NOT be
1015  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1016  * and, in fact, it was the default.  That capability is now provided in the
1017  * /etc/rc2.d/S69inet script.
1018  */
1019 int ip_g_forward = IP_FORWARD_DEFAULT;
1020 
1021 /* It also has an IPv6 counterpart. */
1022 
1023 int ipv6_forward = IP_FORWARD_DEFAULT;
1024 
1025 /* Following line is external, and in ip.h.  Normally marked with * *. */
1026 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
1027 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
1028 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
1029 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
1030 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
1031 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
1032 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
1033 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
1034 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
1035 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
1036 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
1037 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
1038 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
1039 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
1040 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
1041 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
1042 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
1043 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
1044 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
1045 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
1046 #define	ip_output_queue			ip_param_arr[20].ip_param_value
1047 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
1048 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
1049 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
1050 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
1051 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
1052 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
1053 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
1054 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
1055 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
1056 
1057 /* IPv6 configuration knobs */
1058 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1059 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1060 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1061 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1062 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1063 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1064 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1065 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1066 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1067 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1068 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1069 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1070 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1071 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1072 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1073 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1074 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1075 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1076 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1077 #ifdef DEBUG
1078 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1079 #else
1080 #define	ipv6_drop_inbound_icmpv6	0
1081 #endif
1082 
1083 
1084 /*
1085  * Table of IP ioctls encoding the various properties of the ioctl and
1086  * indexed based on the last byte of the ioctl command. Occasionally there
1087  * is a clash, and there is more than 1 ioctl with the same last byte.
1088  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1089  * ioctls are encoded in the misc table. An entry in the ndx table is
1090  * retrieved by indexing on the last byte of the ioctl command and comparing
1091  * the ioctl command with the value in the ndx table. In the event of a
1092  * mismatch the misc table is then searched sequentially for the desired
1093  * ioctl command.
1094  *
1095  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1096  */
1097 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1098 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 
1109 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1110 			MISC_CMD, ip_siocaddrt, NULL },
1111 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1112 			MISC_CMD, ip_siocdelrt, NULL },
1113 
1114 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1115 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1116 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1117 			IF_CMD, ip_sioctl_get_addr, NULL },
1118 
1119 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1120 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1121 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1124 
1125 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1126 			IPI_PRIV | IPI_WR | IPI_REPL,
1127 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1128 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1129 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1130 			IF_CMD, ip_sioctl_get_flags, NULL },
1131 
1132 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* copyin size cannot be coded for SIOCGIFCONF */
1136 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1137 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1138 
1139 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1140 			IF_CMD, ip_sioctl_mtu, NULL },
1141 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1142 			IF_CMD, ip_sioctl_get_mtu, NULL },
1143 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1144 			IPI_GET_CMD | IPI_REPL,
1145 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1146 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1147 			IF_CMD, ip_sioctl_brdaddr, NULL },
1148 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1149 			IPI_GET_CMD | IPI_REPL,
1150 			IF_CMD, ip_sioctl_get_netmask, NULL },
1151 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1152 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1153 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			IF_CMD, ip_sioctl_get_metric, NULL },
1156 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1157 			IF_CMD, ip_sioctl_metric, NULL },
1158 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 
1160 	/* See 166-168 below for extended SIOC*XARP ioctls */
1161 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1162 			MISC_CMD, ip_sioctl_arp, NULL },
1163 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1164 			MISC_CMD, ip_sioctl_arp, NULL },
1165 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1166 			MISC_CMD, ip_sioctl_arp, NULL },
1167 
1168 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 
1190 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1191 			MISC_CMD, if_unitsel, if_unitsel_restart },
1192 
1193 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 
1212 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1213 			IPI_PRIV | IPI_WR | IPI_MODOK,
1214 			IF_CMD, ip_sioctl_sifname, NULL },
1215 
1216 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1217 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 
1230 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1231 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1232 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1233 			IF_CMD, ip_sioctl_get_muxid, NULL },
1234 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1235 			IPI_PRIV | IPI_WR | IPI_REPL,
1236 			IF_CMD, ip_sioctl_muxid, NULL },
1237 
1238 	/* Both if and lif variants share same func */
1239 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1240 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1241 	/* Both if and lif variants share same func */
1242 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1243 			IPI_PRIV | IPI_WR | IPI_REPL,
1244 			IF_CMD, ip_sioctl_slifindex, NULL },
1245 
1246 	/* copyin size cannot be coded for SIOCGIFCONF */
1247 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1248 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1249 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1255 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1256 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1257 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1258 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1259 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1260 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1264 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1265 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1266 
1267 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1268 			IPI_PRIV | IPI_WR | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_removeif,
1270 			ip_sioctl_removeif_restart },
1271 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1272 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_addif, NULL },
1274 #define	SIOCLIFADDR_NDX 112
1275 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1276 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1277 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1278 			IPI_GET_CMD | IPI_REPL,
1279 			LIF_CMD, ip_sioctl_get_addr, NULL },
1280 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1281 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1282 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1283 			IPI_GET_CMD | IPI_REPL,
1284 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1285 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1286 			IPI_PRIV | IPI_WR | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1288 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1289 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1290 			LIF_CMD, ip_sioctl_get_flags, NULL },
1291 
1292 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1293 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1294 
1295 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1296 			ip_sioctl_get_lifconf, NULL },
1297 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1298 			LIF_CMD, ip_sioctl_mtu, NULL },
1299 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1300 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1301 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1302 			IPI_GET_CMD | IPI_REPL,
1303 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1304 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1305 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1306 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1307 			IPI_GET_CMD | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1309 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1310 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1311 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1312 			IPI_GET_CMD | IPI_REPL,
1313 			LIF_CMD, ip_sioctl_get_metric, NULL },
1314 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1315 			LIF_CMD, ip_sioctl_metric, NULL },
1316 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1317 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_slifname,
1319 			ip_sioctl_slifname_restart },
1320 
1321 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1322 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1323 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1324 			IPI_GET_CMD | IPI_REPL,
1325 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1326 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1327 			IPI_PRIV | IPI_WR | IPI_REPL,
1328 			LIF_CMD, ip_sioctl_muxid, NULL },
1329 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1330 			IPI_GET_CMD | IPI_REPL,
1331 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1332 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1333 			IPI_PRIV | IPI_WR | IPI_REPL,
1334 			LIF_CMD, ip_sioctl_slifindex, 0 },
1335 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_token, NULL },
1337 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1338 			IPI_GET_CMD | IPI_REPL,
1339 			LIF_CMD, ip_sioctl_get_token, NULL },
1340 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1341 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1342 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1343 			IPI_GET_CMD | IPI_REPL,
1344 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1345 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1346 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1347 
1348 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1349 			IPI_GET_CMD | IPI_REPL,
1350 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1351 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1352 			LIF_CMD, ip_siocdelndp_v6, NULL },
1353 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1354 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1355 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1356 			LIF_CMD, ip_siocsetndp_v6, NULL },
1357 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1358 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1359 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1360 			MISC_CMD, ip_sioctl_tonlink, NULL },
1361 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1362 			MISC_CMD, ip_sioctl_tmysite, NULL },
1363 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1364 			TUN_CMD, ip_sioctl_tunparam, NULL },
1365 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1366 			IPI_PRIV | IPI_WR,
1367 			TUN_CMD, ip_sioctl_tunparam, NULL },
1368 
1369 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1370 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1371 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1372 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1373 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1374 
1375 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1376 			IPI_PRIV | IPI_WR | IPI_REPL,
1377 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1378 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1379 			IPI_PRIV | IPI_WR | IPI_REPL,
1380 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1381 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1382 			IPI_PRIV | IPI_WR,
1383 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1384 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1385 			IPI_GET_CMD | IPI_REPL,
1386 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1387 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1388 			IPI_GET_CMD | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1390 
1391 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1392 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1393 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1394 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1395 
1396 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1397 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1398 
1399 	/* These are handled in ip_sioctl_copyin_setup itself */
1400 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1401 			MISC_CMD, NULL, NULL },
1402 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1403 			MISC_CMD, NULL, NULL },
1404 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1405 
1406 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1407 			ip_sioctl_get_lifconf, NULL },
1408 
1409 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1410 			MISC_CMD, ip_sioctl_xarp, NULL },
1411 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1412 			MISC_CMD, ip_sioctl_xarp, NULL },
1413 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1414 			MISC_CMD, ip_sioctl_xarp, NULL },
1415 
1416 	/* SIOCPOPSOCKFS is not handled by IP */
1417 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1418 
1419 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1420 			IPI_GET_CMD | IPI_REPL,
1421 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1422 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1423 			IPI_PRIV | IPI_WR | IPI_REPL,
1424 			LIF_CMD, ip_sioctl_slifzone,
1425 			ip_sioctl_slifzone_restart },
1426 	/* 172-174 are SCTP ioctls and not handled by IP */
1427 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1428 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1429 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1430 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1431 			IPI_GET_CMD, LIF_CMD,
1432 			ip_sioctl_get_lifusesrc, 0 },
1433 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1434 			IPI_PRIV | IPI_WR,
1435 			LIF_CMD, ip_sioctl_slifusesrc,
1436 			NULL },
1437 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1438 			ip_sioctl_get_lifsrcof, NULL },
1439 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1440 			MISC_CMD, ip_sioctl_msfilter, NULL },
1441 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1442 			MISC_CMD, ip_sioctl_msfilter, NULL },
1443 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1444 			MISC_CMD, ip_sioctl_msfilter, NULL },
1445 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1446 			MISC_CMD, ip_sioctl_msfilter, NULL },
1447 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1448 			ip_sioctl_set_ipmpfailback, NULL }
1449 };
1450 
1451 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1452 
1453 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1454 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1455 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1456 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1457 		TUN_CMD, ip_sioctl_tunparam, NULL },
1458 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1459 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1460 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1461 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1462 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1463 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1464 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1465 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1466 		MISC_CMD, mrt_ioctl},
1467 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1468 		MISC_CMD, mrt_ioctl},
1469 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1470 		MISC_CMD, mrt_ioctl}
1471 };
1472 
1473 int ip_misc_ioctl_count =
1474     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1475 
1476 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1477 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1478 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1479 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1480 					/* Settable in /etc/system */
1481 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1482 
1483 /* Defined in ip_ire.c */
1484 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1485 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1486 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1487 
1488 static nv_t	ire_nv_arr[] = {
1489 	{ IRE_BROADCAST, "BROADCAST" },
1490 	{ IRE_LOCAL, "LOCAL" },
1491 	{ IRE_LOOPBACK, "LOOPBACK" },
1492 	{ IRE_CACHE, "CACHE" },
1493 	{ IRE_DEFAULT, "DEFAULT" },
1494 	{ IRE_PREFIX, "PREFIX" },
1495 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1496 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1497 	{ IRE_HOST, "HOST" },
1498 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1499 	{ 0 }
1500 };
1501 
1502 nv_t	*ire_nv_tbl = ire_nv_arr;
1503 
1504 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1505 extern krwlock_t ipsec_capab_ills_lock;
1506 
1507 /* Packet dropper for IP IPsec processing failures */
1508 ipdropper_t ip_dropper;
1509 
1510 /* Simple ICMP IP Header Template */
1511 static ipha_t icmp_ipha = {
1512 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1513 };
1514 
1515 struct module_info ip_mod_info = {
1516 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1517 };
1518 
1519 static struct qinit rinit = {
1520 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1521 	&ip_mod_info
1522 };
1523 
1524 static struct qinit winit = {
1525 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1526 	&ip_mod_info
1527 };
1528 
1529 static struct qinit lrinit = {
1530 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1531 	&ip_mod_info
1532 };
1533 
1534 static struct qinit lwinit = {
1535 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1536 	&ip_mod_info
1537 };
1538 
1539 struct streamtab ipinfo = {
1540 	&rinit, &winit, &lrinit, &lwinit
1541 };
1542 
1543 #ifdef	DEBUG
1544 static boolean_t skip_sctp_cksum = B_FALSE;
1545 #endif
1546 /*
1547  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1548  */
1549 mblk_t *
1550 ip_copymsg(mblk_t *mp)
1551 {
1552 	mblk_t *nmp;
1553 	ipsec_info_t *in;
1554 
1555 	if (mp->b_datap->db_type != M_CTL)
1556 		return (copymsg(mp));
1557 
1558 	in = (ipsec_info_t *)mp->b_rptr;
1559 
1560 	/*
1561 	 * Note that M_CTL is also used for delivering ICMP error messages
1562 	 * upstream to transport layers.
1563 	 */
1564 	if (in->ipsec_info_type != IPSEC_OUT &&
1565 	    in->ipsec_info_type != IPSEC_IN)
1566 		return (copymsg(mp));
1567 
1568 	nmp = copymsg(mp->b_cont);
1569 
1570 	if (in->ipsec_info_type == IPSEC_OUT)
1571 		return (ipsec_out_tag(mp, nmp));
1572 	else
1573 		return (ipsec_in_tag(mp, nmp));
1574 }
1575 
1576 /* Generate an ICMP fragmentation needed message. */
1577 static void
1578 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1579 {
1580 	icmph_t	icmph;
1581 	mblk_t *first_mp;
1582 	boolean_t mctl_present;
1583 
1584 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1585 
1586 	if (!(mp = icmp_pkt_err_ok(mp))) {
1587 		if (mctl_present)
1588 			freeb(first_mp);
1589 		return;
1590 	}
1591 
1592 	bzero(&icmph, sizeof (icmph_t));
1593 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1594 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1595 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1596 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1597 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1598 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1599 }
1600 
1601 /*
1602  * icmp_inbound deals with ICMP messages in the following ways.
1603  *
1604  * 1) It needs to send a reply back and possibly delivering it
1605  *    to the "interested" upper clients.
1606  * 2) It needs to send it to the upper clients only.
1607  * 3) It needs to change some values in IP only.
1608  * 4) It needs to change some values in IP and upper layers e.g TCP.
1609  *
1610  * We need to accomodate icmp messages coming in clear until we get
1611  * everything secure from the wire. If icmp_accept_clear_messages
1612  * is zero we check with the global policy and act accordingly. If
1613  * it is non-zero, we accept the message without any checks. But
1614  * *this does not mean* that this will be delivered to the upper
1615  * clients. By accepting we might send replies back, change our MTU
1616  * value etc. but delivery to the ULP/clients depends on their policy
1617  * dispositions.
1618  *
1619  * We handle the above 4 cases in the context of IPSEC in the
1620  * following way :
1621  *
1622  * 1) Send the reply back in the same way as the request came in.
1623  *    If it came in encrypted, it goes out encrypted. If it came in
1624  *    clear, it goes out in clear. Thus, this will prevent chosen
1625  *    plain text attack.
1626  * 2) The client may or may not expect things to come in secure.
1627  *    If it comes in secure, the policy constraints are checked
1628  *    before delivering it to the upper layers. If it comes in
1629  *    clear, ipsec_inbound_accept_clear will decide whether to
1630  *    accept this in clear or not. In both the cases, if the returned
1631  *    message (IP header + 8 bytes) that caused the icmp message has
1632  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1633  *    sending up. If there are only 8 bytes of returned message, then
1634  *    upper client will not be notified.
1635  * 3) Check with global policy to see whether it matches the constaints.
1636  *    But this will be done only if icmp_accept_messages_in_clear is
1637  *    zero.
1638  * 4) If we need to change both in IP and ULP, then the decision taken
1639  *    while affecting the values in IP and while delivering up to TCP
1640  *    should be the same.
1641  *
1642  * 	There are two cases.
1643  *
1644  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1645  *	   failed), we will not deliver it to the ULP, even though they
1646  *	   are *willing* to accept in *clear*. This is fine as our global
1647  *	   disposition to icmp messages asks us reject the datagram.
1648  *
1649  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1650  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1651  *	   to deliver it to ULP (policy failed), it can lead to
1652  *	   consistency problems. The cases known at this time are
1653  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1654  *	   values :
1655  *
1656  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1657  *	     and Upper layer rejects. Then the communication will
1658  *	     come to a stop. This is solved by making similar decisions
1659  *	     at both levels. Currently, when we are unable to deliver
1660  *	     to the Upper Layer (due to policy failures) while IP has
1661  *	     adjusted ire_max_frag, the next outbound datagram would
1662  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1663  *	     will be with the right level of protection. Thus the right
1664  *	     value will be communicated even if we are not able to
1665  *	     communicate when we get from the wire initially. But this
1666  *	     assumes there would be at least one outbound datagram after
1667  *	     IP has adjusted its ire_max_frag value. To make things
1668  *	     simpler, we accept in clear after the validation of
1669  *	     AH/ESP headers.
1670  *
1671  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1672  *	     upper layer depending on the level of protection the upper
1673  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1674  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1675  *	     should be accepted in clear when the Upper layer expects secure.
1676  *	     Thus the communication may get aborted by some bad ICMP
1677  *	     packets.
1678  *
1679  * IPQoS Notes:
1680  * The only instance when a packet is sent for processing is when there
1681  * isn't an ICMP client and if we are interested in it.
1682  * If there is a client, IPPF processing will take place in the
1683  * ip_fanout_proto routine.
1684  *
1685  * Zones notes:
1686  * The packet is only processed in the context of the specified zone: typically
1687  * only this zone will reply to an echo request, and only interested clients in
1688  * this zone will receive a copy of the packet. This means that the caller must
1689  * call icmp_inbound() for each relevant zone.
1690  */
1691 static void
1692 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1693     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1694     ill_t *recv_ill, zoneid_t zoneid)
1695 {
1696 	icmph_t	*icmph;
1697 	ipha_t	*ipha;
1698 	int	iph_hdr_length;
1699 	int	hdr_length;
1700 	boolean_t	interested;
1701 	uint32_t	ts;
1702 	uchar_t	*wptr;
1703 	ipif_t	*ipif;
1704 	mblk_t *first_mp;
1705 	ipsec_in_t *ii;
1706 	ire_t *src_ire;
1707 	boolean_t onlink;
1708 	timestruc_t now;
1709 	uint32_t ill_index;
1710 
1711 	ASSERT(ill != NULL);
1712 
1713 	first_mp = mp;
1714 	if (mctl_present) {
1715 		mp = first_mp->b_cont;
1716 		ASSERT(mp != NULL);
1717 	}
1718 
1719 	ipha = (ipha_t *)mp->b_rptr;
1720 	if (icmp_accept_clear_messages == 0) {
1721 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1722 		    ipha, NULL, mctl_present);
1723 		if (first_mp == NULL)
1724 			return;
1725 	}
1726 
1727 	/*
1728 	 * On a labeled system, we have to check whether the zone itself is
1729 	 * permitted to receive raw traffic.
1730 	 */
1731 	if (is_system_labeled()) {
1732 		if (zoneid == ALL_ZONES)
1733 			zoneid = tsol_packet_to_zoneid(mp);
1734 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1735 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1736 			    zoneid));
1737 			BUMP_MIB(&icmp_mib, icmpInErrors);
1738 			freemsg(first_mp);
1739 			return;
1740 		}
1741 	}
1742 
1743 	/*
1744 	 * We have accepted the ICMP message. It means that we will
1745 	 * respond to the packet if needed. It may not be delivered
1746 	 * to the upper client depending on the policy constraints
1747 	 * and the disposition in ipsec_inbound_accept_clear.
1748 	 */
1749 
1750 	ASSERT(ill != NULL);
1751 
1752 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1753 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1754 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1755 		/* Last chance to get real. */
1756 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1757 			BUMP_MIB(&icmp_mib, icmpInErrors);
1758 			freemsg(first_mp);
1759 			return;
1760 		}
1761 		/* Refresh iph following the pullup. */
1762 		ipha = (ipha_t *)mp->b_rptr;
1763 	}
1764 	/* ICMP header checksum, including checksum field, should be zero. */
1765 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1766 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1767 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1768 		freemsg(first_mp);
1769 		return;
1770 	}
1771 	/* The IP header will always be a multiple of four bytes */
1772 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1773 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1774 	    icmph->icmph_code));
1775 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1776 	/* We will set "interested" to "true" if we want a copy */
1777 	interested = B_FALSE;
1778 	switch (icmph->icmph_type) {
1779 	case ICMP_ECHO_REPLY:
1780 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1781 		break;
1782 	case ICMP_DEST_UNREACHABLE:
1783 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1784 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1785 		interested = B_TRUE;	/* Pass up to transport */
1786 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1787 		break;
1788 	case ICMP_SOURCE_QUENCH:
1789 		interested = B_TRUE;	/* Pass up to transport */
1790 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1791 		break;
1792 	case ICMP_REDIRECT:
1793 		if (!ip_ignore_redirect)
1794 			interested = B_TRUE;
1795 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1796 		break;
1797 	case ICMP_ECHO_REQUEST:
1798 		/*
1799 		 * Whether to respond to echo requests that come in as IP
1800 		 * broadcasts or as IP multicast is subject to debate
1801 		 * (what isn't?).  We aim to please, you pick it.
1802 		 * Default is do it.
1803 		 */
1804 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1805 			/* unicast: always respond */
1806 			interested = B_TRUE;
1807 		} else if (CLASSD(ipha->ipha_dst)) {
1808 			/* multicast: respond based on tunable */
1809 			interested = ip_g_resp_to_echo_mcast;
1810 		} else if (broadcast) {
1811 			/* broadcast: respond based on tunable */
1812 			interested = ip_g_resp_to_echo_bcast;
1813 		}
1814 		BUMP_MIB(&icmp_mib, icmpInEchos);
1815 		break;
1816 	case ICMP_ROUTER_ADVERTISEMENT:
1817 	case ICMP_ROUTER_SOLICITATION:
1818 		break;
1819 	case ICMP_TIME_EXCEEDED:
1820 		interested = B_TRUE;	/* Pass up to transport */
1821 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1822 		break;
1823 	case ICMP_PARAM_PROBLEM:
1824 		interested = B_TRUE;	/* Pass up to transport */
1825 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1826 		break;
1827 	case ICMP_TIME_STAMP_REQUEST:
1828 		/* Response to Time Stamp Requests is local policy. */
1829 		if (ip_g_resp_to_timestamp &&
1830 		    /* So is whether to respond if it was an IP broadcast. */
1831 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1832 			int tstamp_len = 3 * sizeof (uint32_t);
1833 
1834 			if (wptr +  tstamp_len > mp->b_wptr) {
1835 				if (!pullupmsg(mp, wptr + tstamp_len -
1836 				    mp->b_rptr)) {
1837 					BUMP_MIB(&ip_mib, ipInDiscards);
1838 					freemsg(first_mp);
1839 					return;
1840 				}
1841 				/* Refresh ipha following the pullup. */
1842 				ipha = (ipha_t *)mp->b_rptr;
1843 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1844 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1845 			}
1846 			interested = B_TRUE;
1847 		}
1848 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1849 		break;
1850 	case ICMP_TIME_STAMP_REPLY:
1851 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1852 		break;
1853 	case ICMP_INFO_REQUEST:
1854 		/* Per RFC 1122 3.2.2.7, ignore this. */
1855 	case ICMP_INFO_REPLY:
1856 		break;
1857 	case ICMP_ADDRESS_MASK_REQUEST:
1858 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1859 		    /* TODO m_pullup of complete header? */
1860 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1861 			interested = B_TRUE;
1862 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1863 		break;
1864 	case ICMP_ADDRESS_MASK_REPLY:
1865 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1866 		break;
1867 	default:
1868 		interested = B_TRUE;	/* Pass up to transport */
1869 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1870 		break;
1871 	}
1872 	/* See if there is an ICMP client. */
1873 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1874 		/* If there is an ICMP client and we want one too, copy it. */
1875 		mblk_t *first_mp1;
1876 
1877 		if (!interested) {
1878 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1879 			    ip_policy, recv_ill, zoneid);
1880 			return;
1881 		}
1882 		first_mp1 = ip_copymsg(first_mp);
1883 		if (first_mp1 != NULL) {
1884 			ip_fanout_proto(q, first_mp1, ill, ipha,
1885 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1886 		}
1887 	} else if (!interested) {
1888 		freemsg(first_mp);
1889 		return;
1890 	} else {
1891 		/*
1892 		 * Initiate policy processing for this packet if ip_policy
1893 		 * is true.
1894 		 */
1895 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1896 			ill_index = ill->ill_phyint->phyint_ifindex;
1897 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1898 			if (mp == NULL) {
1899 				if (mctl_present) {
1900 					freeb(first_mp);
1901 				}
1902 				BUMP_MIB(&icmp_mib, icmpInErrors);
1903 				return;
1904 			}
1905 		}
1906 	}
1907 	/* We want to do something with it. */
1908 	/* Check db_ref to make sure we can modify the packet. */
1909 	if (mp->b_datap->db_ref > 1) {
1910 		mblk_t	*first_mp1;
1911 
1912 		first_mp1 = ip_copymsg(first_mp);
1913 		freemsg(first_mp);
1914 		if (!first_mp1) {
1915 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1916 			return;
1917 		}
1918 		first_mp = first_mp1;
1919 		if (mctl_present) {
1920 			mp = first_mp->b_cont;
1921 			ASSERT(mp != NULL);
1922 		} else {
1923 			mp = first_mp;
1924 		}
1925 		ipha = (ipha_t *)mp->b_rptr;
1926 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1927 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1928 	}
1929 	switch (icmph->icmph_type) {
1930 	case ICMP_ADDRESS_MASK_REQUEST:
1931 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1932 		if (ipif == NULL) {
1933 			freemsg(first_mp);
1934 			return;
1935 		}
1936 		/*
1937 		 * outging interface must be IPv4
1938 		 */
1939 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1940 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1941 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1942 		ipif_refrele(ipif);
1943 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1944 		break;
1945 	case ICMP_ECHO_REQUEST:
1946 		icmph->icmph_type = ICMP_ECHO_REPLY;
1947 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1948 		break;
1949 	case ICMP_TIME_STAMP_REQUEST: {
1950 		uint32_t *tsp;
1951 
1952 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1953 		tsp = (uint32_t *)wptr;
1954 		tsp++;		/* Skip past 'originate time' */
1955 		/* Compute # of milliseconds since midnight */
1956 		gethrestime(&now);
1957 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1958 		    now.tv_nsec / (NANOSEC / MILLISEC);
1959 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1960 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1961 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1962 		break;
1963 	}
1964 	default:
1965 		ipha = (ipha_t *)&icmph[1];
1966 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1967 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1968 				BUMP_MIB(&ip_mib, ipInDiscards);
1969 				freemsg(first_mp);
1970 				return;
1971 			}
1972 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1973 			ipha = (ipha_t *)&icmph[1];
1974 		}
1975 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1976 			BUMP_MIB(&ip_mib, ipInDiscards);
1977 			freemsg(first_mp);
1978 			return;
1979 		}
1980 		hdr_length = IPH_HDR_LENGTH(ipha);
1981 		if (hdr_length < sizeof (ipha_t)) {
1982 			BUMP_MIB(&ip_mib, ipInDiscards);
1983 			freemsg(first_mp);
1984 			return;
1985 		}
1986 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1987 			if (!pullupmsg(mp,
1988 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1989 				BUMP_MIB(&ip_mib, ipInDiscards);
1990 				freemsg(first_mp);
1991 				return;
1992 			}
1993 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1994 			ipha = (ipha_t *)&icmph[1];
1995 		}
1996 		switch (icmph->icmph_type) {
1997 		case ICMP_REDIRECT:
1998 			/*
1999 			 * As there is no upper client to deliver, we don't
2000 			 * need the first_mp any more.
2001 			 */
2002 			if (mctl_present) {
2003 				freeb(first_mp);
2004 			}
2005 			icmp_redirect(mp);
2006 			return;
2007 		case ICMP_DEST_UNREACHABLE:
2008 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2009 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2010 				    zoneid, mp, iph_hdr_length)) {
2011 					freemsg(first_mp);
2012 					return;
2013 				}
2014 				/*
2015 				 * icmp_inbound_too_big() may alter mp.
2016 				 * Resynch ipha and icmph accordingly.
2017 				 */
2018 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2019 				ipha = (ipha_t *)&icmph[1];
2020 			}
2021 			/* FALLTHRU */
2022 		default :
2023 			/*
2024 			 * IPQoS notes: Since we have already done IPQoS
2025 			 * processing we don't want to do it again in
2026 			 * the fanout routines called by
2027 			 * icmp_inbound_error_fanout, hence the last
2028 			 * argument, ip_policy, is B_FALSE.
2029 			 */
2030 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2031 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2032 			    B_FALSE, recv_ill, zoneid);
2033 		}
2034 		return;
2035 	}
2036 	/* Send out an ICMP packet */
2037 	icmph->icmph_checksum = 0;
2038 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2039 	if (icmph->icmph_checksum == 0)
2040 		icmph->icmph_checksum = 0xFFFF;
2041 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2042 		ipif_t	*ipif_chosen;
2043 		/*
2044 		 * Make it look like it was directed to us, so we don't look
2045 		 * like a fool with a broadcast or multicast source address.
2046 		 */
2047 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2048 		/*
2049 		 * Make sure that we haven't grabbed an interface that's DOWN.
2050 		 */
2051 		if (ipif != NULL) {
2052 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2053 			    ipha->ipha_src, zoneid);
2054 			if (ipif_chosen != NULL) {
2055 				ipif_refrele(ipif);
2056 				ipif = ipif_chosen;
2057 			}
2058 		}
2059 		if (ipif == NULL) {
2060 			ip0dbg(("icmp_inbound: "
2061 			    "No source for broadcast/multicast:\n"
2062 			    "\tsrc 0x%x dst 0x%x ill %p "
2063 			    "ipif_lcl_addr 0x%x\n",
2064 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2065 			    (void *)ill,
2066 			    ill->ill_ipif->ipif_lcl_addr));
2067 			freemsg(first_mp);
2068 			return;
2069 		}
2070 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2071 		ipha->ipha_dst = ipif->ipif_src_addr;
2072 		ipif_refrele(ipif);
2073 	}
2074 	/* Reset time to live. */
2075 	ipha->ipha_ttl = ip_def_ttl;
2076 	{
2077 		/* Swap source and destination addresses */
2078 		ipaddr_t tmp;
2079 
2080 		tmp = ipha->ipha_src;
2081 		ipha->ipha_src = ipha->ipha_dst;
2082 		ipha->ipha_dst = tmp;
2083 	}
2084 	ipha->ipha_ident = 0;
2085 	if (!IS_SIMPLE_IPH(ipha))
2086 		icmp_options_update(ipha);
2087 
2088 	/*
2089 	 * ICMP echo replies should go out on the same interface
2090 	 * the request came on as probes used by in.mpathd for detecting
2091 	 * NIC failures are ECHO packets. We turn-off load spreading
2092 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2093 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2094 	 * function. This is in turn handled by ip_wput and ip_newroute
2095 	 * to make sure that the packet goes out on the interface it came
2096 	 * in on. If we don't turnoff load spreading, the packets might get
2097 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2098 	 * to go out and in.mpathd would wrongly detect a failure or
2099 	 * mis-detect a NIC failure for link failure. As load spreading
2100 	 * can happen only if ill_group is not NULL, we do only for
2101 	 * that case and this does not affect the normal case.
2102 	 *
2103 	 * We turn off load spreading only on echo packets that came from
2104 	 * on-link hosts. If the interface route has been deleted, this will
2105 	 * not be enforced as we can't do much. For off-link hosts, as the
2106 	 * default routes in IPv4 does not typically have an ire_ipif
2107 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2108 	 * Moreover, expecting a default route through this interface may
2109 	 * not be correct. We use ipha_dst because of the swap above.
2110 	 */
2111 	onlink = B_FALSE;
2112 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2113 		/*
2114 		 * First, we need to make sure that it is not one of our
2115 		 * local addresses. If we set onlink when it is one of
2116 		 * our local addresses, we will end up creating IRE_CACHES
2117 		 * for one of our local addresses. Then, we will never
2118 		 * accept packets for them afterwards.
2119 		 */
2120 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2121 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2122 		if (src_ire == NULL) {
2123 			ipif = ipif_get_next_ipif(NULL, ill);
2124 			if (ipif == NULL) {
2125 				BUMP_MIB(&ip_mib, ipInDiscards);
2126 				freemsg(mp);
2127 				return;
2128 			}
2129 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2130 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2131 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2132 			ipif_refrele(ipif);
2133 			if (src_ire != NULL) {
2134 				onlink = B_TRUE;
2135 				ire_refrele(src_ire);
2136 			}
2137 		} else {
2138 			ire_refrele(src_ire);
2139 		}
2140 	}
2141 	if (!mctl_present) {
2142 		/*
2143 		 * This packet should go out the same way as it
2144 		 * came in i.e in clear. To make sure that global
2145 		 * policy will not be applied to this in ip_wput_ire,
2146 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2147 		 */
2148 		ASSERT(first_mp == mp);
2149 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2150 			BUMP_MIB(&ip_mib, ipInDiscards);
2151 			freemsg(mp);
2152 			return;
2153 		}
2154 		ii = (ipsec_in_t *)first_mp->b_rptr;
2155 
2156 		/* This is not a secure packet */
2157 		ii->ipsec_in_secure = B_FALSE;
2158 		if (onlink) {
2159 			ii->ipsec_in_attach_if = B_TRUE;
2160 			ii->ipsec_in_ill_index =
2161 			    ill->ill_phyint->phyint_ifindex;
2162 			ii->ipsec_in_rill_index =
2163 			    recv_ill->ill_phyint->phyint_ifindex;
2164 		}
2165 		first_mp->b_cont = mp;
2166 	} else if (onlink) {
2167 		ii = (ipsec_in_t *)first_mp->b_rptr;
2168 		ii->ipsec_in_attach_if = B_TRUE;
2169 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2170 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2171 	} else {
2172 		ii = (ipsec_in_t *)first_mp->b_rptr;
2173 	}
2174 	ii->ipsec_in_zoneid = zoneid;
2175 	ASSERT(zoneid != ALL_ZONES);
2176 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2177 		BUMP_MIB(&ip_mib, ipInDiscards);
2178 		return;
2179 	}
2180 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2181 	put(WR(q), first_mp);
2182 }
2183 
2184 static ipaddr_t
2185 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2186 {
2187 	conn_t *connp;
2188 	connf_t *connfp;
2189 	ipaddr_t nexthop_addr = INADDR_ANY;
2190 	int hdr_length = IPH_HDR_LENGTH(ipha);
2191 	uint16_t *up;
2192 	uint32_t ports;
2193 
2194 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2195 	switch (ipha->ipha_protocol) {
2196 		case IPPROTO_TCP:
2197 		{
2198 			tcph_t *tcph;
2199 
2200 			/* do a reverse lookup */
2201 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2202 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2203 			    TCPS_LISTEN);
2204 			break;
2205 		}
2206 		case IPPROTO_UDP:
2207 		{
2208 			uint32_t dstport, srcport;
2209 
2210 			((uint16_t *)&ports)[0] = up[1];
2211 			((uint16_t *)&ports)[1] = up[0];
2212 
2213 			/* Extract ports in net byte order */
2214 			dstport = htons(ntohl(ports) & 0xFFFF);
2215 			srcport = htons(ntohl(ports) >> 16);
2216 
2217 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2218 			mutex_enter(&connfp->connf_lock);
2219 			connp = connfp->connf_head;
2220 
2221 			/* do a reverse lookup */
2222 			while ((connp != NULL) &&
2223 			    (!IPCL_UDP_MATCH(connp, dstport,
2224 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2225 			    connp->conn_zoneid != zoneid)) {
2226 				connp = connp->conn_next;
2227 			}
2228 			if (connp != NULL)
2229 				CONN_INC_REF(connp);
2230 			mutex_exit(&connfp->connf_lock);
2231 			break;
2232 		}
2233 		case IPPROTO_SCTP:
2234 		{
2235 			in6_addr_t map_src, map_dst;
2236 
2237 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2238 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2239 			((uint16_t *)&ports)[0] = up[1];
2240 			((uint16_t *)&ports)[1] = up[0];
2241 
2242 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2243 			    0, zoneid)) == NULL) {
2244 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2245 				    zoneid, ports, ipha);
2246 			} else {
2247 				CONN_INC_REF(connp);
2248 				SCTP_REFRELE(CONN2SCTP(connp));
2249 			}
2250 			break;
2251 		}
2252 		default:
2253 		{
2254 			ipha_t ripha;
2255 
2256 			ripha.ipha_src = ipha->ipha_dst;
2257 			ripha.ipha_dst = ipha->ipha_src;
2258 			ripha.ipha_protocol = ipha->ipha_protocol;
2259 
2260 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2261 			mutex_enter(&connfp->connf_lock);
2262 			connp = connfp->connf_head;
2263 			for (connp = connfp->connf_head; connp != NULL;
2264 			    connp = connp->conn_next) {
2265 				if (IPCL_PROTO_MATCH(connp,
2266 				    ipha->ipha_protocol, &ripha, ill,
2267 				    0, zoneid)) {
2268 					CONN_INC_REF(connp);
2269 					break;
2270 				}
2271 			}
2272 			mutex_exit(&connfp->connf_lock);
2273 		}
2274 	}
2275 	if (connp != NULL) {
2276 		if (connp->conn_nexthop_set)
2277 			nexthop_addr = connp->conn_nexthop_v4;
2278 		CONN_DEC_REF(connp);
2279 	}
2280 	return (nexthop_addr);
2281 }
2282 
2283 /* Table from RFC 1191 */
2284 static int icmp_frag_size_table[] =
2285 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2286 
2287 /*
2288  * Process received ICMP Packet too big.
2289  * After updating any IRE it does the fanout to any matching transport streams.
2290  * Assumes the message has been pulled up till the IP header that caused
2291  * the error.
2292  *
2293  * Returns B_FALSE on failure and B_TRUE on success.
2294  */
2295 static boolean_t
2296 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2297     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2298 {
2299 	ire_t	*ire, *first_ire;
2300 	int	mtu;
2301 	int	hdr_length;
2302 	ipaddr_t nexthop_addr;
2303 
2304 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2305 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2306 
2307 	hdr_length = IPH_HDR_LENGTH(ipha);
2308 
2309 	/* Drop if the original packet contained a source route */
2310 	if (ip_source_route_included(ipha)) {
2311 		return (B_FALSE);
2312 	}
2313 	/*
2314 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2315 	 * header.
2316 	 */
2317 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2318 	    mp->b_wptr) {
2319 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2320 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2321 			BUMP_MIB(&ip_mib, ipInDiscards);
2322 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2323 			return (B_FALSE);
2324 		}
2325 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2326 		ipha = (ipha_t *)&icmph[1];
2327 	}
2328 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2329 	if (nexthop_addr != INADDR_ANY) {
2330 		/* nexthop set */
2331 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2332 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2333 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2334 	} else {
2335 		/* nexthop not set */
2336 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2337 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2338 	}
2339 
2340 	if (!first_ire) {
2341 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2342 		    ntohl(ipha->ipha_dst)));
2343 		return (B_FALSE);
2344 	}
2345 	/* Check for MTU discovery advice as described in RFC 1191 */
2346 	mtu = ntohs(icmph->icmph_du_mtu);
2347 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2348 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2349 	    ire = ire->ire_next) {
2350 		/*
2351 		 * Look for the connection to which this ICMP message is
2352 		 * directed. If it has the IP_NEXTHOP option set, then the
2353 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2354 		 * option. Else the search is limited to regular IREs.
2355 		 */
2356 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2357 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2358 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2359 		    (nexthop_addr != INADDR_ANY)))
2360 			continue;
2361 
2362 		mutex_enter(&ire->ire_lock);
2363 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2364 			/* Reduce the IRE max frag value as advised. */
2365 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2366 			    mtu, ire->ire_max_frag));
2367 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2368 		} else {
2369 			uint32_t length;
2370 			int	i;
2371 
2372 			/*
2373 			 * Use the table from RFC 1191 to figure out
2374 			 * the next "plateau" based on the length in
2375 			 * the original IP packet.
2376 			 */
2377 			length = ntohs(ipha->ipha_length);
2378 			if (ire->ire_max_frag <= length &&
2379 			    ire->ire_max_frag >= length - hdr_length) {
2380 				/*
2381 				 * Handle broken BSD 4.2 systems that
2382 				 * return the wrong iph_length in ICMP
2383 				 * errors.
2384 				 */
2385 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2386 				    length, ire->ire_max_frag));
2387 				length -= hdr_length;
2388 			}
2389 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2390 				if (length > icmp_frag_size_table[i])
2391 					break;
2392 			}
2393 			if (i == A_CNT(icmp_frag_size_table)) {
2394 				/* Smaller than 68! */
2395 				ip1dbg(("Too big for packet size %d\n",
2396 				    length));
2397 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2398 				ire->ire_frag_flag = 0;
2399 			} else {
2400 				mtu = icmp_frag_size_table[i];
2401 				ip1dbg(("Calculated mtu %d, packet size %d, "
2402 				    "before %d", mtu, length,
2403 				    ire->ire_max_frag));
2404 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2405 				ip1dbg((", after %d\n", ire->ire_max_frag));
2406 			}
2407 			/* Record the new max frag size for the ULP. */
2408 			icmph->icmph_du_zero = 0;
2409 			icmph->icmph_du_mtu =
2410 			    htons((uint16_t)ire->ire_max_frag);
2411 		}
2412 		mutex_exit(&ire->ire_lock);
2413 	}
2414 	rw_exit(&first_ire->ire_bucket->irb_lock);
2415 	ire_refrele(first_ire);
2416 	return (B_TRUE);
2417 }
2418 
2419 /*
2420  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2421  * calls this function.
2422  */
2423 static mblk_t *
2424 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2425 {
2426 	ipha_t *ipha;
2427 	icmph_t *icmph;
2428 	ipha_t *in_ipha;
2429 	int length;
2430 
2431 	ASSERT(mp->b_datap->db_type == M_DATA);
2432 
2433 	/*
2434 	 * For Self-encapsulated packets, we added an extra IP header
2435 	 * without the options. Inner IP header is the one from which
2436 	 * the outer IP header was formed. Thus, we need to remove the
2437 	 * outer IP header. To do this, we pullup the whole message
2438 	 * and overlay whatever follows the outer IP header over the
2439 	 * outer IP header.
2440 	 */
2441 
2442 	if (!pullupmsg(mp, -1)) {
2443 		BUMP_MIB(&ip_mib, ipInDiscards);
2444 		return (NULL);
2445 	}
2446 
2447 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2448 	ipha = (ipha_t *)&icmph[1];
2449 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2450 
2451 	/*
2452 	 * The length that we want to overlay is following the inner
2453 	 * IP header. Subtracting the IP header + icmp header + outer
2454 	 * IP header's length should give us the length that we want to
2455 	 * overlay.
2456 	 */
2457 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2458 	    hdr_length;
2459 	/*
2460 	 * Overlay whatever follows the inner header over the
2461 	 * outer header.
2462 	 */
2463 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2464 
2465 	/* Set the wptr to account for the outer header */
2466 	mp->b_wptr -= hdr_length;
2467 	return (mp);
2468 }
2469 
2470 /*
2471  * Try to pass the ICMP message upstream in case the ULP cares.
2472  *
2473  * If the packet that caused the ICMP error is secure, we send
2474  * it to AH/ESP to make sure that the attached packet has a
2475  * valid association. ipha in the code below points to the
2476  * IP header of the packet that caused the error.
2477  *
2478  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2479  * in the context of IPSEC. Normally we tell the upper layer
2480  * whenever we send the ire (including ip_bind), the IPSEC header
2481  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2482  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2483  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2484  * same thing. As TCP has the IPSEC options size that needs to be
2485  * adjusted, we just pass the MTU unchanged.
2486  *
2487  * IFN could have been generated locally or by some router.
2488  *
2489  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2490  *	    This happens because IP adjusted its value of MTU on an
2491  *	    earlier IFN message and could not tell the upper layer,
2492  *	    the new adjusted value of MTU e.g. Packet was encrypted
2493  *	    or there was not enough information to fanout to upper
2494  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2495  *	    generates the IFN, where IPSEC processing has *not* been
2496  *	    done.
2497  *
2498  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2499  *	    could have generated this. This happens because ire_max_frag
2500  *	    value in IP was set to a new value, while the IPSEC processing
2501  *	    was being done and after we made the fragmentation check in
2502  *	    ip_wput_ire. Thus on return from IPSEC processing,
2503  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2504  *	    and generates the IFN. As IPSEC processing is over, we fanout
2505  *	    to AH/ESP to remove the header.
2506  *
2507  *	    In both these cases, ipsec_in_loopback will be set indicating
2508  *	    that IFN was generated locally.
2509  *
2510  * ROUTER : IFN could be secure or non-secure.
2511  *
2512  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2513  *	      packet in error has AH/ESP headers to validate the AH/ESP
2514  *	      headers. AH/ESP will verify whether there is a valid SA or
2515  *	      not and send it back. We will fanout again if we have more
2516  *	      data in the packet.
2517  *
2518  *	      If the packet in error does not have AH/ESP, we handle it
2519  *	      like any other case.
2520  *
2521  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2522  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2523  *	      for validation. AH/ESP will verify whether there is a
2524  *	      valid SA or not and send it back. We will fanout again if
2525  *	      we have more data in the packet.
2526  *
2527  *	      If the packet in error does not have AH/ESP, we handle it
2528  *	      like any other case.
2529  */
2530 static void
2531 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2532     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2533     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2534     zoneid_t zoneid)
2535 {
2536 	uint16_t *up;	/* Pointer to ports in ULP header */
2537 	uint32_t ports;	/* reversed ports for fanout */
2538 	ipha_t ripha;	/* With reversed addresses */
2539 	mblk_t *first_mp;
2540 	ipsec_in_t *ii;
2541 	tcph_t	*tcph;
2542 	conn_t	*connp;
2543 
2544 	first_mp = mp;
2545 	if (mctl_present) {
2546 		mp = first_mp->b_cont;
2547 		ASSERT(mp != NULL);
2548 
2549 		ii = (ipsec_in_t *)first_mp->b_rptr;
2550 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2551 	} else {
2552 		ii = NULL;
2553 	}
2554 
2555 	switch (ipha->ipha_protocol) {
2556 	case IPPROTO_UDP:
2557 		/*
2558 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2559 		 * transport header.
2560 		 */
2561 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2562 		    mp->b_wptr) {
2563 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2564 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2565 				BUMP_MIB(&ip_mib, ipInDiscards);
2566 				goto drop_pkt;
2567 			}
2568 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2569 			ipha = (ipha_t *)&icmph[1];
2570 		}
2571 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2572 
2573 		/*
2574 		 * Attempt to find a client stream based on port.
2575 		 * Note that we do a reverse lookup since the header is
2576 		 * in the form we sent it out.
2577 		 * The ripha header is only used for the IP_UDP_MATCH and we
2578 		 * only set the src and dst addresses and protocol.
2579 		 */
2580 		ripha.ipha_src = ipha->ipha_dst;
2581 		ripha.ipha_dst = ipha->ipha_src;
2582 		ripha.ipha_protocol = ipha->ipha_protocol;
2583 		((uint16_t *)&ports)[0] = up[1];
2584 		((uint16_t *)&ports)[1] = up[0];
2585 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2586 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2587 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2588 		    icmph->icmph_type, icmph->icmph_code));
2589 
2590 		/* Have to change db_type after any pullupmsg */
2591 		DB_TYPE(mp) = M_CTL;
2592 
2593 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2594 		    mctl_present, ip_policy, recv_ill, zoneid);
2595 		return;
2596 
2597 	case IPPROTO_TCP:
2598 		/*
2599 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2600 		 * transport header.
2601 		 */
2602 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2603 		    mp->b_wptr) {
2604 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2605 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2606 				BUMP_MIB(&ip_mib, ipInDiscards);
2607 				goto drop_pkt;
2608 			}
2609 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2610 			ipha = (ipha_t *)&icmph[1];
2611 		}
2612 		/*
2613 		 * Find a TCP client stream for this packet.
2614 		 * Note that we do a reverse lookup since the header is
2615 		 * in the form we sent it out.
2616 		 */
2617 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2618 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2619 		if (connp == NULL) {
2620 			BUMP_MIB(&ip_mib, ipInDiscards);
2621 			goto drop_pkt;
2622 		}
2623 
2624 		/* Have to change db_type after any pullupmsg */
2625 		DB_TYPE(mp) = M_CTL;
2626 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2627 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2628 		return;
2629 
2630 	case IPPROTO_SCTP:
2631 		/*
2632 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2633 		 * transport header.
2634 		 */
2635 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2636 		    mp->b_wptr) {
2637 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2638 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2639 				BUMP_MIB(&ip_mib, ipInDiscards);
2640 				goto drop_pkt;
2641 			}
2642 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2643 			ipha = (ipha_t *)&icmph[1];
2644 		}
2645 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2646 		/*
2647 		 * Find a SCTP client stream for this packet.
2648 		 * Note that we do a reverse lookup since the header is
2649 		 * in the form we sent it out.
2650 		 * The ripha header is only used for the matching and we
2651 		 * only set the src and dst addresses, protocol, and version.
2652 		 */
2653 		ripha.ipha_src = ipha->ipha_dst;
2654 		ripha.ipha_dst = ipha->ipha_src;
2655 		ripha.ipha_protocol = ipha->ipha_protocol;
2656 		ripha.ipha_version_and_hdr_length =
2657 		    ipha->ipha_version_and_hdr_length;
2658 		((uint16_t *)&ports)[0] = up[1];
2659 		((uint16_t *)&ports)[1] = up[0];
2660 
2661 		/* Have to change db_type after any pullupmsg */
2662 		DB_TYPE(mp) = M_CTL;
2663 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2664 		    mctl_present, ip_policy, 0, zoneid);
2665 		return;
2666 
2667 	case IPPROTO_ESP:
2668 	case IPPROTO_AH: {
2669 		int ipsec_rc;
2670 
2671 		/*
2672 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2673 		 * We will re-use the IPSEC_IN if it is already present as
2674 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2675 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2676 		 * one and attach it in the front.
2677 		 */
2678 		if (ii != NULL) {
2679 			/*
2680 			 * ip_fanout_proto_again converts the ICMP errors
2681 			 * that come back from AH/ESP to M_DATA so that
2682 			 * if it is non-AH/ESP and we do a pullupmsg in
2683 			 * this function, it would work. Convert it back
2684 			 * to M_CTL before we send up as this is a ICMP
2685 			 * error. This could have been generated locally or
2686 			 * by some router. Validate the inner IPSEC
2687 			 * headers.
2688 			 *
2689 			 * NOTE : ill_index is used by ip_fanout_proto_again
2690 			 * to locate the ill.
2691 			 */
2692 			ASSERT(ill != NULL);
2693 			ii->ipsec_in_ill_index =
2694 			    ill->ill_phyint->phyint_ifindex;
2695 			ii->ipsec_in_rill_index =
2696 			    recv_ill->ill_phyint->phyint_ifindex;
2697 			DB_TYPE(first_mp->b_cont) = M_CTL;
2698 		} else {
2699 			/*
2700 			 * IPSEC_IN is not present. We attach a ipsec_in
2701 			 * message and send up to IPSEC for validating
2702 			 * and removing the IPSEC headers. Clear
2703 			 * ipsec_in_secure so that when we return
2704 			 * from IPSEC, we don't mistakenly think that this
2705 			 * is a secure packet came from the network.
2706 			 *
2707 			 * NOTE : ill_index is used by ip_fanout_proto_again
2708 			 * to locate the ill.
2709 			 */
2710 			ASSERT(first_mp == mp);
2711 			first_mp = ipsec_in_alloc(B_TRUE);
2712 			if (first_mp == NULL) {
2713 				freemsg(mp);
2714 				BUMP_MIB(&ip_mib, ipInDiscards);
2715 				return;
2716 			}
2717 			ii = (ipsec_in_t *)first_mp->b_rptr;
2718 
2719 			/* This is not a secure packet */
2720 			ii->ipsec_in_secure = B_FALSE;
2721 			first_mp->b_cont = mp;
2722 			DB_TYPE(mp) = M_CTL;
2723 			ASSERT(ill != NULL);
2724 			ii->ipsec_in_ill_index =
2725 			    ill->ill_phyint->phyint_ifindex;
2726 			ii->ipsec_in_rill_index =
2727 			    recv_ill->ill_phyint->phyint_ifindex;
2728 		}
2729 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2730 
2731 		if (!ipsec_loaded()) {
2732 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2733 			return;
2734 		}
2735 
2736 		if (ipha->ipha_protocol == IPPROTO_ESP)
2737 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2738 		else
2739 			ipsec_rc = ipsecah_icmp_error(first_mp);
2740 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2741 			return;
2742 
2743 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2744 		return;
2745 	}
2746 	default:
2747 		/*
2748 		 * The ripha header is only used for the lookup and we
2749 		 * only set the src and dst addresses and protocol.
2750 		 */
2751 		ripha.ipha_src = ipha->ipha_dst;
2752 		ripha.ipha_dst = ipha->ipha_src;
2753 		ripha.ipha_protocol = ipha->ipha_protocol;
2754 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2755 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2756 		    ntohl(ipha->ipha_dst),
2757 		    icmph->icmph_type, icmph->icmph_code));
2758 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2759 			ipha_t *in_ipha;
2760 
2761 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2762 			    mp->b_wptr) {
2763 				if (!pullupmsg(mp, (uchar_t *)ipha +
2764 				    hdr_length + sizeof (ipha_t) -
2765 				    mp->b_rptr)) {
2766 
2767 					BUMP_MIB(&ip_mib, ipInDiscards);
2768 					goto drop_pkt;
2769 				}
2770 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2771 				ipha = (ipha_t *)&icmph[1];
2772 			}
2773 			/*
2774 			 * Caller has verified that length has to be
2775 			 * at least the size of IP header.
2776 			 */
2777 			ASSERT(hdr_length >= sizeof (ipha_t));
2778 			/*
2779 			 * Check the sanity of the inner IP header like
2780 			 * we did for the outer header.
2781 			 */
2782 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2783 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2784 				BUMP_MIB(&ip_mib, ipInDiscards);
2785 				goto drop_pkt;
2786 			}
2787 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2788 				BUMP_MIB(&ip_mib, ipInDiscards);
2789 				goto drop_pkt;
2790 			}
2791 			/* Check for Self-encapsulated tunnels */
2792 			if (in_ipha->ipha_src == ipha->ipha_src &&
2793 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2794 
2795 				mp = icmp_inbound_self_encap_error(mp,
2796 				    iph_hdr_length, hdr_length);
2797 				if (mp == NULL)
2798 					goto drop_pkt;
2799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2800 				ipha = (ipha_t *)&icmph[1];
2801 				hdr_length = IPH_HDR_LENGTH(ipha);
2802 				/*
2803 				 * The packet in error is self-encapsualted.
2804 				 * And we are finding it further encapsulated
2805 				 * which we could not have possibly generated.
2806 				 */
2807 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2808 					BUMP_MIB(&ip_mib, ipInDiscards);
2809 					goto drop_pkt;
2810 				}
2811 				icmp_inbound_error_fanout(q, ill, first_mp,
2812 				    icmph, ipha, iph_hdr_length, hdr_length,
2813 				    mctl_present, ip_policy, recv_ill, zoneid);
2814 				return;
2815 			}
2816 		}
2817 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2818 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2819 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2820 		    ii != NULL &&
2821 		    ii->ipsec_in_loopback &&
2822 		    ii->ipsec_in_secure) {
2823 			/*
2824 			 * For IP tunnels that get a looped-back
2825 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2826 			 * reported new MTU to take into account the IPsec
2827 			 * headers protecting this configured tunnel.
2828 			 *
2829 			 * This allows the tunnel module (tun.c) to blindly
2830 			 * accept the MTU reported in an ICMP "too big"
2831 			 * message.
2832 			 *
2833 			 * Non-looped back ICMP messages will just be
2834 			 * handled by the security protocols (if needed),
2835 			 * and the first subsequent packet will hit this
2836 			 * path.
2837 			 */
2838 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2839 			    ipsec_in_extra_length(first_mp));
2840 		}
2841 		/* Have to change db_type after any pullupmsg */
2842 		DB_TYPE(mp) = M_CTL;
2843 
2844 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2845 		    ip_policy, recv_ill, zoneid);
2846 		return;
2847 	}
2848 	/* NOTREACHED */
2849 drop_pkt:;
2850 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2851 	freemsg(first_mp);
2852 }
2853 
2854 /*
2855  * Common IP options parser.
2856  *
2857  * Setup routine: fill in *optp with options-parsing state, then
2858  * tail-call ipoptp_next to return the first option.
2859  */
2860 uint8_t
2861 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2862 {
2863 	uint32_t totallen; /* total length of all options */
2864 
2865 	totallen = ipha->ipha_version_and_hdr_length -
2866 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2867 	totallen <<= 2;
2868 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2869 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2870 	optp->ipoptp_flags = 0;
2871 	return (ipoptp_next(optp));
2872 }
2873 
2874 /*
2875  * Common IP options parser: extract next option.
2876  */
2877 uint8_t
2878 ipoptp_next(ipoptp_t *optp)
2879 {
2880 	uint8_t *end = optp->ipoptp_end;
2881 	uint8_t *cur = optp->ipoptp_next;
2882 	uint8_t opt, len, pointer;
2883 
2884 	/*
2885 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2886 	 * has been corrupted.
2887 	 */
2888 	ASSERT(cur <= end);
2889 
2890 	if (cur == end)
2891 		return (IPOPT_EOL);
2892 
2893 	opt = cur[IPOPT_OPTVAL];
2894 
2895 	/*
2896 	 * Skip any NOP options.
2897 	 */
2898 	while (opt == IPOPT_NOP) {
2899 		cur++;
2900 		if (cur == end)
2901 			return (IPOPT_EOL);
2902 		opt = cur[IPOPT_OPTVAL];
2903 	}
2904 
2905 	if (opt == IPOPT_EOL)
2906 		return (IPOPT_EOL);
2907 
2908 	/*
2909 	 * Option requiring a length.
2910 	 */
2911 	if ((cur + 1) >= end) {
2912 		optp->ipoptp_flags |= IPOPTP_ERROR;
2913 		return (IPOPT_EOL);
2914 	}
2915 	len = cur[IPOPT_OLEN];
2916 	if (len < 2) {
2917 		optp->ipoptp_flags |= IPOPTP_ERROR;
2918 		return (IPOPT_EOL);
2919 	}
2920 	optp->ipoptp_cur = cur;
2921 	optp->ipoptp_len = len;
2922 	optp->ipoptp_next = cur + len;
2923 	if (cur + len > end) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 
2928 	/*
2929 	 * For the options which require a pointer field, make sure
2930 	 * its there, and make sure it points to either something
2931 	 * inside this option, or the end of the option.
2932 	 */
2933 	switch (opt) {
2934 	case IPOPT_RR:
2935 	case IPOPT_TS:
2936 	case IPOPT_LSRR:
2937 	case IPOPT_SSRR:
2938 		if (len <= IPOPT_OFFSET) {
2939 			optp->ipoptp_flags |= IPOPTP_ERROR;
2940 			return (opt);
2941 		}
2942 		pointer = cur[IPOPT_OFFSET];
2943 		if (pointer - 1 > len) {
2944 			optp->ipoptp_flags |= IPOPTP_ERROR;
2945 			return (opt);
2946 		}
2947 		break;
2948 	}
2949 
2950 	/*
2951 	 * Sanity check the pointer field based on the type of the
2952 	 * option.
2953 	 */
2954 	switch (opt) {
2955 	case IPOPT_RR:
2956 	case IPOPT_SSRR:
2957 	case IPOPT_LSRR:
2958 		if (pointer < IPOPT_MINOFF_SR)
2959 			optp->ipoptp_flags |= IPOPTP_ERROR;
2960 		break;
2961 	case IPOPT_TS:
2962 		if (pointer < IPOPT_MINOFF_IT)
2963 			optp->ipoptp_flags |= IPOPTP_ERROR;
2964 		/*
2965 		 * Note that the Internet Timestamp option also
2966 		 * contains two four bit fields (the Overflow field,
2967 		 * and the Flag field), which follow the pointer
2968 		 * field.  We don't need to check that these fields
2969 		 * fall within the length of the option because this
2970 		 * was implicitely done above.  We've checked that the
2971 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2972 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2973 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2974 		 */
2975 		ASSERT(len > IPOPT_POS_OV_FLG);
2976 		break;
2977 	}
2978 
2979 	return (opt);
2980 }
2981 
2982 /*
2983  * Use the outgoing IP header to create an IP_OPTIONS option the way
2984  * it was passed down from the application.
2985  */
2986 int
2987 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2988 {
2989 	ipoptp_t	opts;
2990 	const uchar_t	*opt;
2991 	uint8_t		optval;
2992 	uint8_t		optlen;
2993 	uint32_t	len = 0;
2994 	uchar_t	*buf1 = buf;
2995 
2996 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2997 	len += IP_ADDR_LEN;
2998 	bzero(buf1, IP_ADDR_LEN);
2999 
3000 	/*
3001 	 * OK to cast away const here, as we don't store through the returned
3002 	 * opts.ipoptp_cur pointer.
3003 	 */
3004 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3005 	    optval != IPOPT_EOL;
3006 	    optval = ipoptp_next(&opts)) {
3007 		int	off;
3008 
3009 		opt = opts.ipoptp_cur;
3010 		optlen = opts.ipoptp_len;
3011 		switch (optval) {
3012 		case IPOPT_SSRR:
3013 		case IPOPT_LSRR:
3014 
3015 			/*
3016 			 * Insert ipha_dst as the first entry in the source
3017 			 * route and move down the entries on step.
3018 			 * The last entry gets placed at buf1.
3019 			 */
3020 			buf[IPOPT_OPTVAL] = optval;
3021 			buf[IPOPT_OLEN] = optlen;
3022 			buf[IPOPT_OFFSET] = optlen;
3023 
3024 			off = optlen - IP_ADDR_LEN;
3025 			if (off < 0) {
3026 				/* No entries in source route */
3027 				break;
3028 			}
3029 			/* Last entry in source route */
3030 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3031 			off -= IP_ADDR_LEN;
3032 
3033 			while (off > 0) {
3034 				bcopy(opt + off,
3035 				    buf + off + IP_ADDR_LEN,
3036 				    IP_ADDR_LEN);
3037 				off -= IP_ADDR_LEN;
3038 			}
3039 			/* ipha_dst into first slot */
3040 			bcopy(&ipha->ipha_dst,
3041 			    buf + off + IP_ADDR_LEN,
3042 			    IP_ADDR_LEN);
3043 			buf += optlen;
3044 			len += optlen;
3045 			break;
3046 
3047 		case IPOPT_COMSEC:
3048 		case IPOPT_SECURITY:
3049 			/* if passing up a label is not ok, then remove */
3050 			if (is_system_labeled())
3051 				break;
3052 			/* FALLTHROUGH */
3053 		default:
3054 			bcopy(opt, buf, optlen);
3055 			buf += optlen;
3056 			len += optlen;
3057 			break;
3058 		}
3059 	}
3060 done:
3061 	/* Pad the resulting options */
3062 	while (len & 0x3) {
3063 		*buf++ = IPOPT_EOL;
3064 		len++;
3065 	}
3066 	return (len);
3067 }
3068 
3069 /*
3070  * Update any record route or timestamp options to include this host.
3071  * Reverse any source route option.
3072  * This routine assumes that the options are well formed i.e. that they
3073  * have already been checked.
3074  */
3075 static void
3076 icmp_options_update(ipha_t *ipha)
3077 {
3078 	ipoptp_t	opts;
3079 	uchar_t		*opt;
3080 	uint8_t		optval;
3081 	ipaddr_t	src;		/* Our local address */
3082 	ipaddr_t	dst;
3083 
3084 	ip2dbg(("icmp_options_update\n"));
3085 	src = ipha->ipha_src;
3086 	dst = ipha->ipha_dst;
3087 
3088 	for (optval = ipoptp_first(&opts, ipha);
3089 	    optval != IPOPT_EOL;
3090 	    optval = ipoptp_next(&opts)) {
3091 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3092 		opt = opts.ipoptp_cur;
3093 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3094 		    optval, opts.ipoptp_len));
3095 		switch (optval) {
3096 			int off1, off2;
3097 		case IPOPT_SSRR:
3098 		case IPOPT_LSRR:
3099 			/*
3100 			 * Reverse the source route.  The first entry
3101 			 * should be the next to last one in the current
3102 			 * source route (the last entry is our address).
3103 			 * The last entry should be the final destination.
3104 			 */
3105 			off1 = IPOPT_MINOFF_SR - 1;
3106 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3107 			if (off2 < 0) {
3108 				/* No entries in source route */
3109 				ip1dbg((
3110 				    "icmp_options_update: bad src route\n"));
3111 				break;
3112 			}
3113 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3114 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3115 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3116 			off2 -= IP_ADDR_LEN;
3117 
3118 			while (off1 < off2) {
3119 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3120 				bcopy((char *)opt + off2, (char *)opt + off1,
3121 				    IP_ADDR_LEN);
3122 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3123 				off1 += IP_ADDR_LEN;
3124 				off2 -= IP_ADDR_LEN;
3125 			}
3126 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3127 			break;
3128 		}
3129 	}
3130 }
3131 
3132 /*
3133  * Process received ICMP Redirect messages.
3134  */
3135 /* ARGSUSED */
3136 static void
3137 icmp_redirect(mblk_t *mp)
3138 {
3139 	ipha_t	*ipha;
3140 	int	iph_hdr_length;
3141 	icmph_t	*icmph;
3142 	ipha_t	*ipha_err;
3143 	ire_t	*ire;
3144 	ire_t	*prev_ire;
3145 	ire_t	*save_ire;
3146 	ipaddr_t  src, dst, gateway;
3147 	iulp_t	ulp_info = { 0 };
3148 	int	error;
3149 
3150 	ipha = (ipha_t *)mp->b_rptr;
3151 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3152 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3153 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3154 		BUMP_MIB(&icmp_mib, icmpInErrors);
3155 		freemsg(mp);
3156 		return;
3157 	}
3158 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3159 	ipha_err = (ipha_t *)&icmph[1];
3160 	src = ipha->ipha_src;
3161 	dst = ipha_err->ipha_dst;
3162 	gateway = icmph->icmph_rd_gateway;
3163 	/* Make sure the new gateway is reachable somehow. */
3164 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3165 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3166 	/*
3167 	 * Make sure we had a route for the dest in question and that
3168 	 * that route was pointing to the old gateway (the source of the
3169 	 * redirect packet.)
3170 	 */
3171 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3172 	    NULL, MATCH_IRE_GW);
3173 	/*
3174 	 * Check that
3175 	 *	the redirect was not from ourselves
3176 	 *	the new gateway and the old gateway are directly reachable
3177 	 */
3178 	if (!prev_ire ||
3179 	    !ire ||
3180 	    ire->ire_type == IRE_LOCAL) {
3181 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3182 		freemsg(mp);
3183 		if (ire != NULL)
3184 			ire_refrele(ire);
3185 		if (prev_ire != NULL)
3186 			ire_refrele(prev_ire);
3187 		return;
3188 	}
3189 
3190 	/*
3191 	 * Should we use the old ULP info to create the new gateway?  From
3192 	 * a user's perspective, we should inherit the info so that it
3193 	 * is a "smooth" transition.  If we do not do that, then new
3194 	 * connections going thru the new gateway will have no route metrics,
3195 	 * which is counter-intuitive to user.  From a network point of
3196 	 * view, this may or may not make sense even though the new gateway
3197 	 * is still directly connected to us so the route metrics should not
3198 	 * change much.
3199 	 *
3200 	 * But if the old ire_uinfo is not initialized, we do another
3201 	 * recursive lookup on the dest using the new gateway.  There may
3202 	 * be a route to that.  If so, use it to initialize the redirect
3203 	 * route.
3204 	 */
3205 	if (prev_ire->ire_uinfo.iulp_set) {
3206 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3207 	} else {
3208 		ire_t *tmp_ire;
3209 		ire_t *sire;
3210 
3211 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3212 		    ALL_ZONES, 0, NULL,
3213 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3214 		if (sire != NULL) {
3215 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3216 			/*
3217 			 * If sire != NULL, ire_ftable_lookup() should not
3218 			 * return a NULL value.
3219 			 */
3220 			ASSERT(tmp_ire != NULL);
3221 			ire_refrele(tmp_ire);
3222 			ire_refrele(sire);
3223 		} else if (tmp_ire != NULL) {
3224 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3225 			    sizeof (iulp_t));
3226 			ire_refrele(tmp_ire);
3227 		}
3228 	}
3229 	if (prev_ire->ire_type == IRE_CACHE)
3230 		ire_delete(prev_ire);
3231 	ire_refrele(prev_ire);
3232 	/*
3233 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3234 	 * require TOS routing
3235 	 */
3236 	switch (icmph->icmph_code) {
3237 	case 0:
3238 	case 1:
3239 		/* TODO: TOS specificity for cases 2 and 3 */
3240 	case 2:
3241 	case 3:
3242 		break;
3243 	default:
3244 		freemsg(mp);
3245 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3246 		ire_refrele(ire);
3247 		return;
3248 	}
3249 	/*
3250 	 * Create a Route Association.  This will allow us to remember that
3251 	 * someone we believe told us to use the particular gateway.
3252 	 */
3253 	save_ire = ire;
3254 	ire = ire_create(
3255 		(uchar_t *)&dst,			/* dest addr */
3256 		(uchar_t *)&ip_g_all_ones,		/* mask */
3257 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3258 		(uchar_t *)&gateway,			/* gateway addr */
3259 		NULL,					/* no in_srcaddr */
3260 		&save_ire->ire_max_frag,		/* max frag */
3261 		NULL,					/* Fast Path header */
3262 		NULL,					/* no rfq */
3263 		NULL,					/* no stq */
3264 		IRE_HOST_REDIRECT,
3265 		NULL,
3266 		NULL,
3267 		NULL,
3268 		0,
3269 		0,
3270 		0,
3271 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3272 		&ulp_info,
3273 		NULL,
3274 		NULL);
3275 
3276 	if (ire == NULL) {
3277 		freemsg(mp);
3278 		ire_refrele(save_ire);
3279 		return;
3280 	}
3281 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3282 	ire_refrele(save_ire);
3283 	atomic_inc_32(&ip_redirect_cnt);
3284 
3285 	if (error == 0) {
3286 		ire_refrele(ire);		/* Held in ire_add_v4 */
3287 		/* tell routing sockets that we received a redirect */
3288 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3289 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3290 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3291 	}
3292 
3293 	/*
3294 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3295 	 * This together with the added IRE has the effect of
3296 	 * modifying an existing redirect.
3297 	 */
3298 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3299 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3300 	if (prev_ire) {
3301 		ire_delete(prev_ire);
3302 		ire_refrele(prev_ire);
3303 	}
3304 
3305 	freemsg(mp);
3306 }
3307 
3308 /*
3309  * Generate an ICMP parameter problem message.
3310  */
3311 static void
3312 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3313 {
3314 	icmph_t	icmph;
3315 	boolean_t mctl_present;
3316 	mblk_t *first_mp;
3317 
3318 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3319 
3320 	if (!(mp = icmp_pkt_err_ok(mp))) {
3321 		if (mctl_present)
3322 			freeb(first_mp);
3323 		return;
3324 	}
3325 
3326 	bzero(&icmph, sizeof (icmph_t));
3327 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3328 	icmph.icmph_pp_ptr = ptr;
3329 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3330 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3331 }
3332 
3333 /*
3334  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3335  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3336  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3337  * an icmp error packet can be sent.
3338  * Assigns an appropriate source address to the packet. If ipha_dst is
3339  * one of our addresses use it for source. Otherwise pick a source based
3340  * on a route lookup back to ipha_src.
3341  * Note that ipha_src must be set here since the
3342  * packet is likely to arrive on an ill queue in ip_wput() which will
3343  * not set a source address.
3344  */
3345 static void
3346 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3347     boolean_t mctl_present)
3348 {
3349 	ipaddr_t dst;
3350 	icmph_t	*icmph;
3351 	ipha_t	*ipha;
3352 	uint_t	len_needed;
3353 	size_t	msg_len;
3354 	mblk_t	*mp1;
3355 	ipaddr_t src;
3356 	ire_t	*ire;
3357 	mblk_t *ipsec_mp;
3358 	ipsec_out_t	*io = NULL;
3359 	boolean_t xmit_if_on = B_FALSE;
3360 	zoneid_t	zoneid;
3361 
3362 	if (mctl_present) {
3363 		/*
3364 		 * If it is :
3365 		 *
3366 		 * 1) a IPSEC_OUT, then this is caused by outbound
3367 		 *    datagram originating on this host. IPSEC processing
3368 		 *    may or may not have been done. Refer to comments above
3369 		 *    icmp_inbound_error_fanout for details.
3370 		 *
3371 		 * 2) a IPSEC_IN if we are generating a icmp_message
3372 		 *    for an incoming datagram destined for us i.e called
3373 		 *    from ip_fanout_send_icmp.
3374 		 */
3375 		ipsec_info_t *in;
3376 		ipsec_mp = mp;
3377 		mp = ipsec_mp->b_cont;
3378 
3379 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3380 		ipha = (ipha_t *)mp->b_rptr;
3381 
3382 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3383 		    in->ipsec_info_type == IPSEC_IN);
3384 
3385 		if (in->ipsec_info_type == IPSEC_IN) {
3386 			/*
3387 			 * Convert the IPSEC_IN to IPSEC_OUT.
3388 			 */
3389 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3390 				BUMP_MIB(&ip_mib, ipOutDiscards);
3391 				return;
3392 			}
3393 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3394 		} else {
3395 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3396 			io = (ipsec_out_t *)in;
3397 			if (io->ipsec_out_xmit_if)
3398 				xmit_if_on = B_TRUE;
3399 			/*
3400 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3401 			 * ire lookup.
3402 			 */
3403 			io->ipsec_out_proc_begin = B_FALSE;
3404 		}
3405 		zoneid = io->ipsec_out_zoneid;
3406 		ASSERT(zoneid != ALL_ZONES);
3407 	} else {
3408 		/*
3409 		 * This is in clear. The icmp message we are building
3410 		 * here should go out in clear.
3411 		 *
3412 		 * Pardon the convolution of it all, but it's easier to
3413 		 * allocate a "use cleartext" IPSEC_IN message and convert
3414 		 * it than it is to allocate a new one.
3415 		 */
3416 		ipsec_in_t *ii;
3417 		ASSERT(DB_TYPE(mp) == M_DATA);
3418 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3419 			freemsg(mp);
3420 			BUMP_MIB(&ip_mib, ipOutDiscards);
3421 			return;
3422 		}
3423 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3424 
3425 		/* This is not a secure packet */
3426 		ii->ipsec_in_secure = B_FALSE;
3427 		if (CONN_Q(q)) {
3428 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3429 		} else {
3430 			zoneid = GLOBAL_ZONEID;
3431 		}
3432 		ii->ipsec_in_zoneid = zoneid;
3433 		ASSERT(zoneid != ALL_ZONES);
3434 		ipsec_mp->b_cont = mp;
3435 		ipha = (ipha_t *)mp->b_rptr;
3436 		/*
3437 		 * Convert the IPSEC_IN to IPSEC_OUT.
3438 		 */
3439 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3440 			BUMP_MIB(&ip_mib, ipOutDiscards);
3441 			return;
3442 		}
3443 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3444 	}
3445 
3446 	/* Remember our eventual destination */
3447 	dst = ipha->ipha_src;
3448 
3449 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3450 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3451 	if (ire != NULL &&
3452 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3453 		src = ipha->ipha_dst;
3454 	} else if (!xmit_if_on) {
3455 		if (ire != NULL)
3456 			ire_refrele(ire);
3457 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3458 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3459 		if (ire == NULL) {
3460 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3461 			freemsg(ipsec_mp);
3462 			return;
3463 		}
3464 		src = ire->ire_src_addr;
3465 	} else {
3466 		ipif_t	*ipif = NULL;
3467 		ill_t	*ill;
3468 		/*
3469 		 * This must be an ICMP error coming from
3470 		 * ip_mrtun_forward(). The src addr should
3471 		 * be equal to the IP-addr of the outgoing
3472 		 * interface.
3473 		 */
3474 		if (io == NULL) {
3475 			/* This is not a IPSEC_OUT type control msg */
3476 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3477 			freemsg(ipsec_mp);
3478 			return;
3479 		}
3480 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3481 		    NULL, NULL, NULL, NULL);
3482 		if (ill != NULL) {
3483 			ipif = ipif_get_next_ipif(NULL, ill);
3484 			ill_refrele(ill);
3485 		}
3486 		if (ipif == NULL) {
3487 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3488 			freemsg(ipsec_mp);
3489 			return;
3490 		}
3491 		src = ipif->ipif_src_addr;
3492 		ipif_refrele(ipif);
3493 	}
3494 
3495 	if (ire != NULL)
3496 		ire_refrele(ire);
3497 
3498 	/*
3499 	 * Check if we can send back more then 8 bytes in addition
3500 	 * to the IP header. We will include as much as 64 bytes.
3501 	 */
3502 	len_needed = IPH_HDR_LENGTH(ipha);
3503 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3504 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3505 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3506 	}
3507 	len_needed += ip_icmp_return;
3508 	msg_len = msgdsize(mp);
3509 	if (msg_len > len_needed) {
3510 		(void) adjmsg(mp, len_needed - msg_len);
3511 		msg_len = len_needed;
3512 	}
3513 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3514 	if (mp1 == NULL) {
3515 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3516 		freemsg(ipsec_mp);
3517 		return;
3518 	}
3519 	/*
3520 	 * On an unlabeled system, dblks don't necessarily have creds.
3521 	 */
3522 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3523 	if (DB_CRED(mp) != NULL)
3524 		mblk_setcred(mp1, DB_CRED(mp));
3525 	mp1->b_cont = mp;
3526 	mp = mp1;
3527 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3528 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3529 	    io->ipsec_out_type == IPSEC_OUT);
3530 	ipsec_mp->b_cont = mp;
3531 
3532 	/*
3533 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3534 	 * node generates be accepted in peace by all on-host destinations.
3535 	 * If we do NOT assume that all on-host destinations trust
3536 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3537 	 * (Look for ipsec_out_icmp_loopback).
3538 	 */
3539 	io->ipsec_out_icmp_loopback = B_TRUE;
3540 
3541 	ipha = (ipha_t *)mp->b_rptr;
3542 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3543 	*ipha = icmp_ipha;
3544 	ipha->ipha_src = src;
3545 	ipha->ipha_dst = dst;
3546 	ipha->ipha_ttl = ip_def_ttl;
3547 	msg_len += sizeof (icmp_ipha) + len;
3548 	if (msg_len > IP_MAXPACKET) {
3549 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3550 		msg_len = IP_MAXPACKET;
3551 	}
3552 	ipha->ipha_length = htons((uint16_t)msg_len);
3553 	icmph = (icmph_t *)&ipha[1];
3554 	bcopy(stuff, icmph, len);
3555 	icmph->icmph_checksum = 0;
3556 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3557 	if (icmph->icmph_checksum == 0)
3558 		icmph->icmph_checksum = 0xFFFF;
3559 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3560 	put(q, ipsec_mp);
3561 }
3562 
3563 /*
3564  * Determine if an ICMP error packet can be sent given the rate limit.
3565  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3566  * in milliseconds) and a burst size. Burst size number of packets can
3567  * be sent arbitrarely closely spaced.
3568  * The state is tracked using two variables to implement an approximate
3569  * token bucket filter:
3570  *	icmp_pkt_err_last - lbolt value when the last burst started
3571  *	icmp_pkt_err_sent - number of packets sent in current burst
3572  */
3573 boolean_t
3574 icmp_err_rate_limit(void)
3575 {
3576 	clock_t now = TICK_TO_MSEC(lbolt);
3577 	uint_t refilled; /* Number of packets refilled in tbf since last */
3578 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3579 
3580 	if (err_interval == 0)
3581 		return (B_FALSE);
3582 
3583 	if (icmp_pkt_err_last > now) {
3584 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3585 		icmp_pkt_err_last = 0;
3586 		icmp_pkt_err_sent = 0;
3587 	}
3588 	/*
3589 	 * If we are in a burst update the token bucket filter.
3590 	 * Update the "last" time to be close to "now" but make sure
3591 	 * we don't loose precision.
3592 	 */
3593 	if (icmp_pkt_err_sent != 0) {
3594 		refilled = (now - icmp_pkt_err_last)/err_interval;
3595 		if (refilled > icmp_pkt_err_sent) {
3596 			icmp_pkt_err_sent = 0;
3597 		} else {
3598 			icmp_pkt_err_sent -= refilled;
3599 			icmp_pkt_err_last += refilled * err_interval;
3600 		}
3601 	}
3602 	if (icmp_pkt_err_sent == 0) {
3603 		/* Start of new burst */
3604 		icmp_pkt_err_last = now;
3605 	}
3606 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3607 		icmp_pkt_err_sent++;
3608 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3609 		    icmp_pkt_err_sent));
3610 		return (B_FALSE);
3611 	}
3612 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3613 	return (B_TRUE);
3614 }
3615 
3616 /*
3617  * Check if it is ok to send an IPv4 ICMP error packet in
3618  * response to the IPv4 packet in mp.
3619  * Free the message and return null if no
3620  * ICMP error packet should be sent.
3621  */
3622 static mblk_t *
3623 icmp_pkt_err_ok(mblk_t *mp)
3624 {
3625 	icmph_t	*icmph;
3626 	ipha_t	*ipha;
3627 	uint_t	len_needed;
3628 	ire_t	*src_ire;
3629 	ire_t	*dst_ire;
3630 
3631 	if (!mp)
3632 		return (NULL);
3633 	ipha = (ipha_t *)mp->b_rptr;
3634 	if (ip_csum_hdr(ipha)) {
3635 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3636 		freemsg(mp);
3637 		return (NULL);
3638 	}
3639 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3640 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3641 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3642 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3643 	if (src_ire != NULL || dst_ire != NULL ||
3644 	    CLASSD(ipha->ipha_dst) ||
3645 	    CLASSD(ipha->ipha_src) ||
3646 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3647 		/* Note: only errors to the fragment with offset 0 */
3648 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3649 		freemsg(mp);
3650 		if (src_ire != NULL)
3651 			ire_refrele(src_ire);
3652 		if (dst_ire != NULL)
3653 			ire_refrele(dst_ire);
3654 		return (NULL);
3655 	}
3656 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3657 		/*
3658 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3659 		 * errors in response to any ICMP errors.
3660 		 */
3661 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3662 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3663 			if (!pullupmsg(mp, len_needed)) {
3664 				BUMP_MIB(&icmp_mib, icmpInErrors);
3665 				freemsg(mp);
3666 				return (NULL);
3667 			}
3668 			ipha = (ipha_t *)mp->b_rptr;
3669 		}
3670 		icmph = (icmph_t *)
3671 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3672 		switch (icmph->icmph_type) {
3673 		case ICMP_DEST_UNREACHABLE:
3674 		case ICMP_SOURCE_QUENCH:
3675 		case ICMP_TIME_EXCEEDED:
3676 		case ICMP_PARAM_PROBLEM:
3677 		case ICMP_REDIRECT:
3678 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3679 			freemsg(mp);
3680 			return (NULL);
3681 		default:
3682 			break;
3683 		}
3684 	}
3685 	/*
3686 	 * If this is a labeled system, then check to see if we're allowed to
3687 	 * send a response to this particular sender.  If not, then just drop.
3688 	 */
3689 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3690 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3691 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3692 		freemsg(mp);
3693 		return (NULL);
3694 	}
3695 	if (icmp_err_rate_limit()) {
3696 		/*
3697 		 * Only send ICMP error packets every so often.
3698 		 * This should be done on a per port/source basis,
3699 		 * but for now this will suffice.
3700 		 */
3701 		freemsg(mp);
3702 		return (NULL);
3703 	}
3704 	return (mp);
3705 }
3706 
3707 /*
3708  * Generate an ICMP redirect message.
3709  */
3710 static void
3711 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3712 {
3713 	icmph_t	icmph;
3714 
3715 	/*
3716 	 * We are called from ip_rput where we could
3717 	 * not have attached an IPSEC_IN.
3718 	 */
3719 	ASSERT(mp->b_datap->db_type == M_DATA);
3720 
3721 	if (!(mp = icmp_pkt_err_ok(mp))) {
3722 		return;
3723 	}
3724 
3725 	bzero(&icmph, sizeof (icmph_t));
3726 	icmph.icmph_type = ICMP_REDIRECT;
3727 	icmph.icmph_code = 1;
3728 	icmph.icmph_rd_gateway = gateway;
3729 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3730 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3731 }
3732 
3733 /*
3734  * Generate an ICMP time exceeded message.
3735  */
3736 void
3737 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3738 {
3739 	icmph_t	icmph;
3740 	boolean_t mctl_present;
3741 	mblk_t *first_mp;
3742 
3743 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3744 
3745 	if (!(mp = icmp_pkt_err_ok(mp))) {
3746 		if (mctl_present)
3747 			freeb(first_mp);
3748 		return;
3749 	}
3750 
3751 	bzero(&icmph, sizeof (icmph_t));
3752 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3753 	icmph.icmph_code = code;
3754 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3755 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3756 }
3757 
3758 /*
3759  * Generate an ICMP unreachable message.
3760  */
3761 void
3762 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3763 {
3764 	icmph_t	icmph;
3765 	mblk_t *first_mp;
3766 	boolean_t mctl_present;
3767 
3768 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3769 
3770 	if (!(mp = icmp_pkt_err_ok(mp))) {
3771 		if (mctl_present)
3772 			freeb(first_mp);
3773 		return;
3774 	}
3775 
3776 	bzero(&icmph, sizeof (icmph_t));
3777 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3778 	icmph.icmph_code = code;
3779 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3780 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3781 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3782 }
3783 
3784 /*
3785  * News from ARP.  ARP sends notification of interesting events down
3786  * to its clients using M_CTL messages with the interesting ARP packet
3787  * attached via b_cont.
3788  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3789  * queue as opposed to ARP sending the message to all the clients, i.e. all
3790  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3791  * table if a cache IRE is found to delete all the entries for the address in
3792  * the packet.
3793  */
3794 static void
3795 ip_arp_news(queue_t *q, mblk_t *mp)
3796 {
3797 	arcn_t		*arcn;
3798 	arh_t		*arh;
3799 	char		*cp1;
3800 	uchar_t		*cp2;
3801 	ire_t		*ire = NULL;
3802 	int		i1;
3803 	char		hbuf[128];
3804 	char		sbuf[16];
3805 	ipaddr_t	src;
3806 	in6_addr_t	v6src;
3807 	boolean_t	isv6 = B_FALSE;
3808 
3809 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3810 		if (q->q_next) {
3811 			putnext(q, mp);
3812 		} else
3813 			freemsg(mp);
3814 		return;
3815 	}
3816 	arh = (arh_t *)mp->b_cont->b_rptr;
3817 	/* Is it one we are interested in? */
3818 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3819 		isv6 = B_TRUE;
3820 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3821 		    IPV6_ADDR_LEN);
3822 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3823 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3824 		    IP_ADDR_LEN);
3825 	} else {
3826 		freemsg(mp);
3827 		return;
3828 	}
3829 
3830 	arcn = (arcn_t *)mp->b_rptr;
3831 	switch (arcn->arcn_code) {
3832 	case AR_CN_BOGON:
3833 		/*
3834 		 * Someone is sending ARP packets with a source protocol
3835 		 * address which we have published.  Either they are
3836 		 * pretending to be us, or we have been asked to proxy
3837 		 * for a machine that can do fine for itself, or two
3838 		 * different machines are providing proxy service for the
3839 		 * same protocol address, or something.  We try and do
3840 		 * something appropriate here.
3841 		 */
3842 		cp2 = (uchar_t *)&arh[1];
3843 		cp1 = hbuf;
3844 		*cp1 = '\0';
3845 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3846 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3847 		if (cp1 != hbuf)
3848 			cp1[-1] = '\0';
3849 		(void) ip_dot_addr(src, sbuf);
3850 		if (isv6)
3851 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
3852 		else
3853 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
3854 
3855 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3856 			cmn_err(CE_WARN,
3857 			    "IP: Hardware address '%s' trying"
3858 			    " to be our address %s!",
3859 			    hbuf, sbuf);
3860 		} else {
3861 			cmn_err(CE_WARN,
3862 			    "IP: Proxy ARP problem?  "
3863 			    "Hardware address '%s' thinks it is %s",
3864 			    hbuf, sbuf);
3865 		}
3866 		if (ire != NULL)
3867 			ire_refrele(ire);
3868 		break;
3869 	case AR_CN_ANNOUNCE:
3870 		if (isv6) {
3871 			/*
3872 			 * For XRESOLV interfaces.
3873 			 * Delete the IRE cache entry and NCE for this
3874 			 * v6 address
3875 			 */
3876 			ip_ire_clookup_and_delete_v6(&v6src);
3877 			/*
3878 			 * If v6src is a non-zero, it's a router address
3879 			 * as below. Do the same sort of thing to clean
3880 			 * out off-net IRE_CACHE entries that go through
3881 			 * the router.
3882 			 */
3883 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3884 				ire_walk_v6(ire_delete_cache_gw_v6,
3885 				    (char *)&v6src, ALL_ZONES);
3886 			}
3887 			break;
3888 		}
3889 		/*
3890 		 * ARP gives us a copy of any broadcast packet with identical
3891 		 * sender and receiver protocol address, in
3892 		 * case we want to intuit something from it.  Such a packet
3893 		 * usually means that a machine has just come up on the net.
3894 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3895 		 * immediately pick up the rare case of a host changing
3896 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3897 		 *
3898 		 * The address in "src" may be an entry for a router.
3899 		 * (Default router, or non-default router.)  If
3900 		 * that's true, then any off-net IRE_CACHE entries
3901 		 * that go through the router with address "src"
3902 		 * must be clobbered.  Use ire_walk to achieve this
3903 		 * goal.
3904 		 *
3905 		 * It should be possible to determine if the address
3906 		 * in src is or is not for a router.  This way,
3907 		 * the ire_walk() isn't called all of the time here.
3908 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3909 		 * as it would remove all IRE_CACHE entries for onlink
3910 		 * destinations. All onlink destinations have
3911 		 * ire_gateway_addr == 0.
3912 		 *
3913 		 *
3914 		 * The ip_ire_clookup_and_delete() call deletes
3915 		 * the nce and all relevant ire cache entries that
3916 		 * are associated with that nce.
3917 		 * The ire_walk_v4->ire_delete_cache_gw() call
3918 		 * will delete the appropriate redirect ires.
3919 		 */
3920 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3921 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3922 		    0, NULL, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3923 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3924 			    ALL_ZONES);
3925 		}
3926 		/* From ire_ftable_lookup */
3927 		if (ire != NULL)
3928 			ire_refrele(ire);
3929 		break;
3930 	default:
3931 		if (ire != NULL)
3932 			ire_refrele(ire);
3933 		break;
3934 	}
3935 	freemsg(mp);
3936 }
3937 
3938 /*
3939  * Create a mblk suitable for carrying the interface index and/or source link
3940  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3941  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3942  * application.
3943  */
3944 mblk_t *
3945 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3946 {
3947 	mblk_t		*mp;
3948 	in_pktinfo_t	*pinfo;
3949 	ipha_t *ipha;
3950 	struct ether_header *pether;
3951 
3952 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3953 	if (mp == NULL) {
3954 		ip1dbg(("ip_add_info: allocation failure.\n"));
3955 		return (data_mp);
3956 	}
3957 
3958 	ipha	= (ipha_t *)data_mp->b_rptr;
3959 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3960 	bzero(pinfo, sizeof (in_pktinfo_t));
3961 	pinfo->in_pkt_flags = (uchar_t)flags;
3962 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3963 
3964 	if (flags & IPF_RECVIF)
3965 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3966 
3967 	pether = (struct ether_header *)((char *)ipha
3968 	    - sizeof (struct ether_header));
3969 	/*
3970 	 * Make sure the interface is an ethernet type, since this option
3971 	 * is currently supported only on this type of interface. Also make
3972 	 * sure we are pointing correctly above db_base.
3973 	 */
3974 
3975 	if ((flags & IPF_RECVSLLA) &&
3976 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3977 	    (ill->ill_type == IFT_ETHER) &&
3978 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3979 
3980 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3981 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3982 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3983 	} else {
3984 		/*
3985 		 * Clear the bit. Indicate to upper layer that IP is not
3986 		 * sending this ancillary info.
3987 		 */
3988 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3989 	}
3990 
3991 	mp->b_datap->db_type = M_CTL;
3992 	mp->b_wptr += sizeof (in_pktinfo_t);
3993 	mp->b_cont = data_mp;
3994 
3995 	return (mp);
3996 }
3997 
3998 /*
3999  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4000  * part of the bind request.
4001  */
4002 
4003 boolean_t
4004 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4005 {
4006 	ipsec_in_t *ii;
4007 
4008 	ASSERT(policy_mp != NULL);
4009 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4010 
4011 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4012 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4013 
4014 	connp->conn_policy = ii->ipsec_in_policy;
4015 	ii->ipsec_in_policy = NULL;
4016 
4017 	if (ii->ipsec_in_action != NULL) {
4018 		if (connp->conn_latch == NULL) {
4019 			connp->conn_latch = iplatch_create();
4020 			if (connp->conn_latch == NULL)
4021 				return (B_FALSE);
4022 		}
4023 		ipsec_latch_inbound(connp->conn_latch, ii);
4024 	}
4025 	return (B_TRUE);
4026 }
4027 
4028 /*
4029  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4030  * and to arrange for power-fanout assist.  The ULP is identified by
4031  * adding a single byte at the end of the original bind message.
4032  * A ULP other than UDP or TCP that wishes to be recognized passes
4033  * down a bind with a zero length address.
4034  *
4035  * The binding works as follows:
4036  * - A zero byte address means just bind to the protocol.
4037  * - A four byte address is treated as a request to validate
4038  *   that the address is a valid local address, appropriate for
4039  *   an application to bind to. This does not affect any fanout
4040  *   information in IP.
4041  * - A sizeof sin_t byte address is used to bind to only the local address
4042  *   and port.
4043  * - A sizeof ipa_conn_t byte address contains complete fanout information
4044  *   consisting of local and remote addresses and ports.  In
4045  *   this case, the addresses are both validated as appropriate
4046  *   for this operation, and, if so, the information is retained
4047  *   for use in the inbound fanout.
4048  *
4049  * The ULP (except in the zero-length bind) can append an
4050  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4051  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4052  * a copy of the source or destination IRE (source for local bind;
4053  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4054  * policy information contained should be copied on to the conn.
4055  *
4056  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4057  */
4058 mblk_t *
4059 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4060 {
4061 	ssize_t		len;
4062 	struct T_bind_req	*tbr;
4063 	sin_t		*sin;
4064 	ipa_conn_t	*ac;
4065 	uchar_t		*ucp;
4066 	mblk_t		*mp1;
4067 	boolean_t	ire_requested;
4068 	boolean_t	ipsec_policy_set = B_FALSE;
4069 	int		error = 0;
4070 	int		protocol;
4071 	ipa_conn_x_t	*acx;
4072 
4073 	ASSERT(!connp->conn_af_isv6);
4074 	connp->conn_pkt_isv6 = B_FALSE;
4075 
4076 	len = MBLKL(mp);
4077 	if (len < (sizeof (*tbr) + 1)) {
4078 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4079 		    "ip_bind: bogus msg, len %ld", len);
4080 		/* XXX: Need to return something better */
4081 		goto bad_addr;
4082 	}
4083 	/* Back up and extract the protocol identifier. */
4084 	mp->b_wptr--;
4085 	protocol = *mp->b_wptr & 0xFF;
4086 	tbr = (struct T_bind_req *)mp->b_rptr;
4087 	/* Reset the message type in preparation for shipping it back. */
4088 	DB_TYPE(mp) = M_PCPROTO;
4089 
4090 	connp->conn_ulp = (uint8_t)protocol;
4091 
4092 	/*
4093 	 * Check for a zero length address.  This is from a protocol that
4094 	 * wants to register to receive all packets of its type.
4095 	 */
4096 	if (tbr->ADDR_length == 0) {
4097 		/*
4098 		 * These protocols are now intercepted in ip_bind_v6().
4099 		 * Reject protocol-level binds here for now.
4100 		 *
4101 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4102 		 * so that the protocol type cannot be SCTP.
4103 		 */
4104 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4105 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4106 			goto bad_addr;
4107 		}
4108 
4109 		/*
4110 		 *
4111 		 * The udp module never sends down a zero-length address,
4112 		 * and allowing this on a labeled system will break MLP
4113 		 * functionality.
4114 		 */
4115 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4116 			goto bad_addr;
4117 
4118 		if (connp->conn_mac_exempt)
4119 			goto bad_addr;
4120 
4121 		/* No hash here really.  The table is big enough. */
4122 		connp->conn_srcv6 = ipv6_all_zeros;
4123 
4124 		ipcl_proto_insert(connp, protocol);
4125 
4126 		tbr->PRIM_type = T_BIND_ACK;
4127 		return (mp);
4128 	}
4129 
4130 	/* Extract the address pointer from the message. */
4131 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4132 	    tbr->ADDR_length);
4133 	if (ucp == NULL) {
4134 		ip1dbg(("ip_bind: no address\n"));
4135 		goto bad_addr;
4136 	}
4137 	if (!OK_32PTR(ucp)) {
4138 		ip1dbg(("ip_bind: unaligned address\n"));
4139 		goto bad_addr;
4140 	}
4141 	/*
4142 	 * Check for trailing mps.
4143 	 */
4144 
4145 	mp1 = mp->b_cont;
4146 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4147 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4148 
4149 	switch (tbr->ADDR_length) {
4150 	default:
4151 		ip1dbg(("ip_bind: bad address length %d\n",
4152 		    (int)tbr->ADDR_length));
4153 		goto bad_addr;
4154 
4155 	case IP_ADDR_LEN:
4156 		/* Verification of local address only */
4157 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4158 		    ire_requested, ipsec_policy_set, B_FALSE);
4159 		break;
4160 
4161 	case sizeof (sin_t):
4162 		sin = (sin_t *)ucp;
4163 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4164 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4165 		if (protocol == IPPROTO_TCP)
4166 			connp->conn_recv = tcp_conn_request;
4167 		break;
4168 
4169 	case sizeof (ipa_conn_t):
4170 		ac = (ipa_conn_t *)ucp;
4171 		/* For raw socket, the local port is not set. */
4172 		if (ac->ac_lport == 0)
4173 			ac->ac_lport = connp->conn_lport;
4174 		/* Always verify destination reachability. */
4175 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4176 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4177 		    ipsec_policy_set, B_TRUE, B_TRUE);
4178 		if (protocol == IPPROTO_TCP)
4179 			connp->conn_recv = tcp_input;
4180 		break;
4181 
4182 	case sizeof (ipa_conn_x_t):
4183 		acx = (ipa_conn_x_t *)ucp;
4184 		/*
4185 		 * Whether or not to verify destination reachability depends
4186 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4187 		 */
4188 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4189 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4190 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4191 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4192 		if (protocol == IPPROTO_TCP)
4193 			connp->conn_recv = tcp_input;
4194 		break;
4195 	}
4196 	if (error == EINPROGRESS)
4197 		return (NULL);
4198 	else if (error != 0)
4199 		goto bad_addr;
4200 	/*
4201 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4202 	 * We can't do this in ip_bind_insert_ire because the policy
4203 	 * may not have been inherited at that point in time and hence
4204 	 * conn_out_enforce_policy may not be set.
4205 	 */
4206 	mp1 = mp->b_cont;
4207 	if (ire_requested && connp->conn_out_enforce_policy &&
4208 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4209 		ire_t *ire = (ire_t *)mp1->b_rptr;
4210 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4211 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4212 	}
4213 
4214 	/* Send it home. */
4215 	mp->b_datap->db_type = M_PCPROTO;
4216 	tbr->PRIM_type = T_BIND_ACK;
4217 	return (mp);
4218 
4219 bad_addr:
4220 	/*
4221 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4222 	 * a unix errno.
4223 	 */
4224 	if (error > 0)
4225 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4226 	else
4227 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4228 	return (mp);
4229 }
4230 
4231 /*
4232  * Here address is verified to be a valid local address.
4233  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4234  * address is also considered a valid local address.
4235  * In the case of a broadcast/multicast address, however, the
4236  * upper protocol is expected to reset the src address
4237  * to 0 if it sees a IRE_BROADCAST type returned so that
4238  * no packets are emitted with broadcast/multicast address as
4239  * source address (that violates hosts requirements RFC1122)
4240  * The addresses valid for bind are:
4241  *	(1) - INADDR_ANY (0)
4242  *	(2) - IP address of an UP interface
4243  *	(3) - IP address of a DOWN interface
4244  *	(4) - valid local IP broadcast addresses. In this case
4245  *	the conn will only receive packets destined to
4246  *	the specified broadcast address.
4247  *	(5) - a multicast address. In this case
4248  *	the conn will only receive packets destined to
4249  *	the specified multicast address. Note: the
4250  *	application still has to issue an
4251  *	IP_ADD_MEMBERSHIP socket option.
4252  *
4253  * On error, return -1 for TBADADDR otherwise pass the
4254  * errno with TSYSERR reply.
4255  *
4256  * In all the above cases, the bound address must be valid in the current zone.
4257  * When the address is loopback, multicast or broadcast, there might be many
4258  * matching IREs so bind has to look up based on the zone.
4259  *
4260  * Note: lport is in network byte order.
4261  */
4262 int
4263 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4264     boolean_t ire_requested, boolean_t ipsec_policy_set,
4265     boolean_t fanout_insert)
4266 {
4267 	int		error = 0;
4268 	ire_t		*src_ire;
4269 	mblk_t		*policy_mp;
4270 	ipif_t		*ipif;
4271 	zoneid_t	zoneid;
4272 
4273 	if (ipsec_policy_set) {
4274 		policy_mp = mp->b_cont;
4275 	}
4276 
4277 	/*
4278 	 * If it was previously connected, conn_fully_bound would have
4279 	 * been set.
4280 	 */
4281 	connp->conn_fully_bound = B_FALSE;
4282 
4283 	src_ire = NULL;
4284 	ipif = NULL;
4285 
4286 	zoneid = IPCL_ZONEID(connp);
4287 
4288 	if (src_addr) {
4289 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4290 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4291 		/*
4292 		 * If an address other than 0.0.0.0 is requested,
4293 		 * we verify that it is a valid address for bind
4294 		 * Note: Following code is in if-else-if form for
4295 		 * readability compared to a condition check.
4296 		 */
4297 		/* LINTED - statement has no consequent */
4298 		if (IRE_IS_LOCAL(src_ire)) {
4299 			/*
4300 			 * (2) Bind to address of local UP interface
4301 			 */
4302 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4303 			/*
4304 			 * (4) Bind to broadcast address
4305 			 * Note: permitted only from transports that
4306 			 * request IRE
4307 			 */
4308 			if (!ire_requested)
4309 				error = EADDRNOTAVAIL;
4310 		} else {
4311 			/*
4312 			 * (3) Bind to address of local DOWN interface
4313 			 * (ipif_lookup_addr() looks up all interfaces
4314 			 * but we do not get here for UP interfaces
4315 			 * - case (2) above)
4316 			 * We put the protocol byte back into the mblk
4317 			 * since we may come back via ip_wput_nondata()
4318 			 * later with this mblk if ipif_lookup_addr chooses
4319 			 * to defer processing.
4320 			 */
4321 			*mp->b_wptr++ = (char)connp->conn_ulp;
4322 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4323 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4324 			    &error)) != NULL) {
4325 				ipif_refrele(ipif);
4326 			} else if (error == EINPROGRESS) {
4327 				if (src_ire != NULL)
4328 					ire_refrele(src_ire);
4329 				return (EINPROGRESS);
4330 			} else if (CLASSD(src_addr)) {
4331 				error = 0;
4332 				if (src_ire != NULL)
4333 					ire_refrele(src_ire);
4334 				/*
4335 				 * (5) bind to multicast address.
4336 				 * Fake out the IRE returned to upper
4337 				 * layer to be a broadcast IRE.
4338 				 */
4339 				src_ire = ire_ctable_lookup(
4340 				    INADDR_BROADCAST, INADDR_ANY,
4341 				    IRE_BROADCAST, NULL, zoneid, NULL,
4342 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4343 				if (src_ire == NULL || !ire_requested)
4344 					error = EADDRNOTAVAIL;
4345 			} else {
4346 				/*
4347 				 * Not a valid address for bind
4348 				 */
4349 				error = EADDRNOTAVAIL;
4350 			}
4351 			/*
4352 			 * Just to keep it consistent with the processing in
4353 			 * ip_bind_v4()
4354 			 */
4355 			mp->b_wptr--;
4356 		}
4357 		if (error) {
4358 			/* Red Alert!  Attempting to be a bogon! */
4359 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4360 			    ntohl(src_addr)));
4361 			goto bad_addr;
4362 		}
4363 	}
4364 
4365 	/*
4366 	 * Allow setting new policies. For example, disconnects come
4367 	 * down as ipa_t bind. As we would have set conn_policy_cached
4368 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4369 	 * can change after the disconnect.
4370 	 */
4371 	connp->conn_policy_cached = B_FALSE;
4372 
4373 	/*
4374 	 * If not fanout_insert this was just an address verification
4375 	 */
4376 	if (fanout_insert) {
4377 		/*
4378 		 * The addresses have been verified. Time to insert in
4379 		 * the correct fanout list.
4380 		 */
4381 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4382 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4383 		connp->conn_lport = lport;
4384 		connp->conn_fport = 0;
4385 		/*
4386 		 * Do we need to add a check to reject Multicast packets
4387 		 */
4388 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4389 	}
4390 
4391 	if (error == 0) {
4392 		if (ire_requested) {
4393 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4394 				error = -1;
4395 				/* Falls through to bad_addr */
4396 			}
4397 		} else if (ipsec_policy_set) {
4398 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4399 				error = -1;
4400 				/* Falls through to bad_addr */
4401 			}
4402 		}
4403 	}
4404 bad_addr:
4405 	if (error != 0) {
4406 		if (connp->conn_anon_port) {
4407 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4408 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4409 			    B_FALSE);
4410 		}
4411 		connp->conn_mlp_type = mlptSingle;
4412 	}
4413 	if (src_ire != NULL)
4414 		IRE_REFRELE(src_ire);
4415 	if (ipsec_policy_set) {
4416 		ASSERT(policy_mp == mp->b_cont);
4417 		ASSERT(policy_mp != NULL);
4418 		freeb(policy_mp);
4419 		/*
4420 		 * As of now assume that nothing else accompanies
4421 		 * IPSEC_POLICY_SET.
4422 		 */
4423 		mp->b_cont = NULL;
4424 	}
4425 	return (error);
4426 }
4427 
4428 /*
4429  * Verify that both the source and destination addresses
4430  * are valid.  If verify_dst is false, then the destination address may be
4431  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4432  * destination reachability, while tunnels do not.
4433  * Note that we allow connect to broadcast and multicast
4434  * addresses when ire_requested is set. Thus the ULP
4435  * has to check for IRE_BROADCAST and multicast.
4436  *
4437  * Returns zero if ok.
4438  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4439  * (for use with TSYSERR reply).
4440  *
4441  * Note: lport and fport are in network byte order.
4442  */
4443 int
4444 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4445     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4446     boolean_t ire_requested, boolean_t ipsec_policy_set,
4447     boolean_t fanout_insert, boolean_t verify_dst)
4448 {
4449 	ire_t		*src_ire;
4450 	ire_t		*dst_ire;
4451 	int		error = 0;
4452 	int 		protocol;
4453 	mblk_t		*policy_mp;
4454 	ire_t		*sire = NULL;
4455 	ire_t		*md_dst_ire = NULL;
4456 	ill_t		*md_ill = NULL;
4457 	zoneid_t	zoneid;
4458 	ipaddr_t	src_addr = *src_addrp;
4459 
4460 	src_ire = dst_ire = NULL;
4461 	protocol = *mp->b_wptr & 0xFF;
4462 
4463 	/*
4464 	 * If we never got a disconnect before, clear it now.
4465 	 */
4466 	connp->conn_fully_bound = B_FALSE;
4467 
4468 	if (ipsec_policy_set) {
4469 		policy_mp = mp->b_cont;
4470 	}
4471 
4472 	zoneid = IPCL_ZONEID(connp);
4473 
4474 	if (CLASSD(dst_addr)) {
4475 		/* Pick up an IRE_BROADCAST */
4476 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4477 		    NULL, zoneid, MBLK_GETLABEL(mp),
4478 		    (MATCH_IRE_RECURSIVE |
4479 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4480 		    MATCH_IRE_SECATTR));
4481 	} else {
4482 		/*
4483 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4484 		 * and onlink ipif is not found set ENETUNREACH error.
4485 		 */
4486 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4487 			ipif_t *ipif;
4488 
4489 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4490 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4491 			if (ipif == NULL) {
4492 				error = ENETUNREACH;
4493 				goto bad_addr;
4494 			}
4495 			ipif_refrele(ipif);
4496 		}
4497 
4498 		if (connp->conn_nexthop_set) {
4499 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4500 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4501 			    MATCH_IRE_SECATTR);
4502 		} else {
4503 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4504 			    &sire, zoneid, MBLK_GETLABEL(mp),
4505 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4506 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4507 			    MATCH_IRE_SECATTR));
4508 		}
4509 	}
4510 	/*
4511 	 * dst_ire can't be a broadcast when not ire_requested.
4512 	 * We also prevent ire's with src address INADDR_ANY to
4513 	 * be used, which are created temporarily for
4514 	 * sending out packets from endpoints that have
4515 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4516 	 * reachable.  If verify_dst is false, the destination needn't be
4517 	 * reachable.
4518 	 *
4519 	 * If we match on a reject or black hole, then we've got a
4520 	 * local failure.  May as well fail out the connect() attempt,
4521 	 * since it's never going to succeed.
4522 	 */
4523 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4524 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4525 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4526 		/*
4527 		 * If we're verifying destination reachability, we always want
4528 		 * to complain here.
4529 		 *
4530 		 * If we're not verifying destination reachability but the
4531 		 * destination has a route, we still want to fail on the
4532 		 * temporary address and broadcast address tests.
4533 		 */
4534 		if (verify_dst || (dst_ire != NULL)) {
4535 			if (ip_debug > 2) {
4536 				pr_addr_dbg("ip_bind_connected: bad connected "
4537 				    "dst %s\n", AF_INET, &dst_addr);
4538 			}
4539 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4540 				error = ENETUNREACH;
4541 			else
4542 				error = EHOSTUNREACH;
4543 			goto bad_addr;
4544 		}
4545 	}
4546 
4547 	/*
4548 	 * We now know that routing will allow us to reach the destination.
4549 	 * Check whether Trusted Solaris policy allows communication with this
4550 	 * host, and pretend that the destination is unreachable if not.
4551 	 *
4552 	 * This is never a problem for TCP, since that transport is known to
4553 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4554 	 * handling.  If the remote is unreachable, it will be detected at that
4555 	 * point, so there's no reason to check it here.
4556 	 *
4557 	 * Note that for sendto (and other datagram-oriented friends), this
4558 	 * check is done as part of the data path label computation instead.
4559 	 * The check here is just to make non-TCP connect() report the right
4560 	 * error.
4561 	 */
4562 	if (dst_ire != NULL && is_system_labeled() &&
4563 	    !IPCL_IS_TCP(connp) &&
4564 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4565 	    connp->conn_mac_exempt) != 0) {
4566 		error = EHOSTUNREACH;
4567 		if (ip_debug > 2) {
4568 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4569 			    AF_INET, &dst_addr);
4570 		}
4571 		goto bad_addr;
4572 	}
4573 
4574 	/*
4575 	 * If the app does a connect(), it means that it will most likely
4576 	 * send more than 1 packet to the destination.  It makes sense
4577 	 * to clear the temporary flag.
4578 	 */
4579 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4580 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4581 		irb_t *irb = dst_ire->ire_bucket;
4582 
4583 		rw_enter(&irb->irb_lock, RW_WRITER);
4584 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4585 		irb->irb_tmp_ire_cnt--;
4586 		rw_exit(&irb->irb_lock);
4587 	}
4588 
4589 	/*
4590 	 * See if we should notify ULP about MDT; we do this whether or not
4591 	 * ire_requested is TRUE, in order to handle active connects; MDT
4592 	 * eligibility tests for passive connects are handled separately
4593 	 * through tcp_adapt_ire().  We do this before the source address
4594 	 * selection, because dst_ire may change after a call to
4595 	 * ipif_select_source().  This is a best-effort check, as the
4596 	 * packet for this connection may not actually go through
4597 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4598 	 * calling ip_newroute().  This is why we further check on the
4599 	 * IRE during Multidata packet transmission in tcp_multisend().
4600 	 */
4601 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4602 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4603 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4604 	    ILL_MDT_CAPABLE(md_ill)) {
4605 		md_dst_ire = dst_ire;
4606 		IRE_REFHOLD(md_dst_ire);
4607 	}
4608 
4609 	if (dst_ire != NULL &&
4610 	    dst_ire->ire_type == IRE_LOCAL &&
4611 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4612 		/*
4613 		 * If the IRE belongs to a different zone, look for a matching
4614 		 * route in the forwarding table and use the source address from
4615 		 * that route.
4616 		 */
4617 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4618 		    zoneid, 0, NULL,
4619 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4620 		    MATCH_IRE_RJ_BHOLE);
4621 		if (src_ire == NULL) {
4622 			error = EHOSTUNREACH;
4623 			goto bad_addr;
4624 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4625 			if (!(src_ire->ire_type & IRE_HOST))
4626 				error = ENETUNREACH;
4627 			else
4628 				error = EHOSTUNREACH;
4629 			goto bad_addr;
4630 		}
4631 		if (src_addr == INADDR_ANY)
4632 			src_addr = src_ire->ire_src_addr;
4633 		ire_refrele(src_ire);
4634 		src_ire = NULL;
4635 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4636 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4637 			src_addr = sire->ire_src_addr;
4638 			ire_refrele(dst_ire);
4639 			dst_ire = sire;
4640 			sire = NULL;
4641 		} else {
4642 			/*
4643 			 * Pick a source address so that a proper inbound
4644 			 * load spreading would happen.
4645 			 */
4646 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4647 			ipif_t *src_ipif = NULL;
4648 			ire_t *ipif_ire;
4649 
4650 			/*
4651 			 * Supply a local source address such that inbound
4652 			 * load spreading happens.
4653 			 *
4654 			 * Determine the best source address on this ill for
4655 			 * the destination.
4656 			 *
4657 			 * 1) For broadcast, we should return a broadcast ire
4658 			 *    found above so that upper layers know that the
4659 			 *    destination address is a broadcast address.
4660 			 *
4661 			 * 2) If this is part of a group, select a better
4662 			 *    source address so that better inbound load
4663 			 *    balancing happens. Do the same if the ipif
4664 			 *    is DEPRECATED.
4665 			 *
4666 			 * 3) If the outgoing interface is part of a usesrc
4667 			 *    group, then try selecting a source address from
4668 			 *    the usesrc ILL.
4669 			 */
4670 			if ((dst_ire->ire_zoneid != zoneid &&
4671 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4672 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4673 			    ((dst_ill->ill_group != NULL) ||
4674 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4675 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4676 				/*
4677 				 * If the destination is reachable via a
4678 				 * given gateway, the selected source address
4679 				 * should be in the same subnet as the gateway.
4680 				 * Otherwise, the destination is not reachable.
4681 				 *
4682 				 * If there are no interfaces on the same subnet
4683 				 * as the destination, ipif_select_source gives
4684 				 * first non-deprecated interface which might be
4685 				 * on a different subnet than the gateway.
4686 				 * This is not desirable. Hence pass the dst_ire
4687 				 * source address to ipif_select_source.
4688 				 * It is sure that the destination is reachable
4689 				 * with the dst_ire source address subnet.
4690 				 * So passing dst_ire source address to
4691 				 * ipif_select_source will make sure that the
4692 				 * selected source will be on the same subnet
4693 				 * as dst_ire source address.
4694 				 */
4695 				ipaddr_t saddr =
4696 				    dst_ire->ire_ipif->ipif_src_addr;
4697 				src_ipif = ipif_select_source(dst_ill,
4698 				    saddr, zoneid);
4699 				if (src_ipif != NULL) {
4700 					if (IS_VNI(src_ipif->ipif_ill)) {
4701 						/*
4702 						 * For VNI there is no
4703 						 * interface route
4704 						 */
4705 						src_addr =
4706 						    src_ipif->ipif_src_addr;
4707 					} else {
4708 						ipif_ire =
4709 						    ipif_to_ire(src_ipif);
4710 						if (ipif_ire != NULL) {
4711 							IRE_REFRELE(dst_ire);
4712 							dst_ire = ipif_ire;
4713 						}
4714 						src_addr =
4715 						    dst_ire->ire_src_addr;
4716 					}
4717 					ipif_refrele(src_ipif);
4718 				} else {
4719 					src_addr = dst_ire->ire_src_addr;
4720 				}
4721 			} else {
4722 				src_addr = dst_ire->ire_src_addr;
4723 			}
4724 		}
4725 	}
4726 
4727 	/*
4728 	 * We do ire_route_lookup() here (and not
4729 	 * interface lookup as we assert that
4730 	 * src_addr should only come from an
4731 	 * UP interface for hard binding.
4732 	 */
4733 	ASSERT(src_ire == NULL);
4734 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4735 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4736 	/* src_ire must be a local|loopback */
4737 	if (!IRE_IS_LOCAL(src_ire)) {
4738 		if (ip_debug > 2) {
4739 			pr_addr_dbg("ip_bind_connected: bad connected "
4740 			    "src %s\n", AF_INET, &src_addr);
4741 		}
4742 		error = EADDRNOTAVAIL;
4743 		goto bad_addr;
4744 	}
4745 
4746 	/*
4747 	 * If the source address is a loopback address, the
4748 	 * destination had best be local or multicast.
4749 	 * The transports that can't handle multicast will reject
4750 	 * those addresses.
4751 	 */
4752 	if (src_ire->ire_type == IRE_LOOPBACK &&
4753 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4754 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4755 		error = -1;
4756 		goto bad_addr;
4757 	}
4758 
4759 	/*
4760 	 * Allow setting new policies. For example, disconnects come
4761 	 * down as ipa_t bind. As we would have set conn_policy_cached
4762 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4763 	 * can change after the disconnect.
4764 	 */
4765 	connp->conn_policy_cached = B_FALSE;
4766 
4767 	/*
4768 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4769 	 * can handle their passed-in conn's.
4770 	 */
4771 
4772 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4773 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4774 	connp->conn_lport = lport;
4775 	connp->conn_fport = fport;
4776 	*src_addrp = src_addr;
4777 
4778 	ASSERT(!(ipsec_policy_set && ire_requested));
4779 	if (ire_requested) {
4780 		iulp_t *ulp_info = NULL;
4781 
4782 		/*
4783 		 * Note that sire will not be NULL if this is an off-link
4784 		 * connection and there is not cache for that dest yet.
4785 		 *
4786 		 * XXX Because of an existing bug, if there are multiple
4787 		 * default routes, the IRE returned now may not be the actual
4788 		 * default route used (default routes are chosen in a
4789 		 * round robin fashion).  So if the metrics for different
4790 		 * default routes are different, we may return the wrong
4791 		 * metrics.  This will not be a problem if the existing
4792 		 * bug is fixed.
4793 		 */
4794 		if (sire != NULL) {
4795 			ulp_info = &(sire->ire_uinfo);
4796 		}
4797 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4798 			error = -1;
4799 			goto bad_addr;
4800 		}
4801 	} else if (ipsec_policy_set) {
4802 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4803 			error = -1;
4804 			goto bad_addr;
4805 		}
4806 	}
4807 
4808 	/*
4809 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4810 	 * we'll cache that.  If we don't, we'll inherit global policy.
4811 	 *
4812 	 * We can't insert until the conn reflects the policy. Note that
4813 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4814 	 * connections where we don't have a policy. This is to prevent
4815 	 * global policy lookups in the inbound path.
4816 	 *
4817 	 * If we insert before we set conn_policy_cached,
4818 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4819 	 * because global policy cound be non-empty. We normally call
4820 	 * ipsec_check_policy() for conn_policy_cached connections only if
4821 	 * ipc_in_enforce_policy is set. But in this case,
4822 	 * conn_policy_cached can get set anytime since we made the
4823 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4824 	 * called, which will make the above assumption false.  Thus, we
4825 	 * need to insert after we set conn_policy_cached.
4826 	 */
4827 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4828 		goto bad_addr;
4829 
4830 	if (fanout_insert) {
4831 		/*
4832 		 * The addresses have been verified. Time to insert in
4833 		 * the correct fanout list.
4834 		 */
4835 		error = ipcl_conn_insert(connp, protocol, src_addr,
4836 		    dst_addr, connp->conn_ports);
4837 	}
4838 
4839 	if (error == 0) {
4840 		connp->conn_fully_bound = B_TRUE;
4841 		/*
4842 		 * Our initial checks for MDT have passed; the IRE is not
4843 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4844 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4845 		 * ip_mdinfo_return(), which performs further checks
4846 		 * against them and upon success, returns the MDT info
4847 		 * mblk which we will attach to the bind acknowledgment.
4848 		 */
4849 		if (md_dst_ire != NULL) {
4850 			mblk_t *mdinfo_mp;
4851 
4852 			ASSERT(md_ill != NULL);
4853 			ASSERT(md_ill->ill_mdt_capab != NULL);
4854 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4855 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4856 				linkb(mp, mdinfo_mp);
4857 		}
4858 	}
4859 bad_addr:
4860 	if (ipsec_policy_set) {
4861 		ASSERT(policy_mp == mp->b_cont);
4862 		ASSERT(policy_mp != NULL);
4863 		freeb(policy_mp);
4864 		/*
4865 		 * As of now assume that nothing else accompanies
4866 		 * IPSEC_POLICY_SET.
4867 		 */
4868 		mp->b_cont = NULL;
4869 	}
4870 	if (src_ire != NULL)
4871 		IRE_REFRELE(src_ire);
4872 	if (dst_ire != NULL)
4873 		IRE_REFRELE(dst_ire);
4874 	if (sire != NULL)
4875 		IRE_REFRELE(sire);
4876 	if (md_dst_ire != NULL)
4877 		IRE_REFRELE(md_dst_ire);
4878 	return (error);
4879 }
4880 
4881 /*
4882  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4883  * Prefers dst_ire over src_ire.
4884  */
4885 static boolean_t
4886 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4887 {
4888 	mblk_t	*mp1;
4889 	ire_t *ret_ire = NULL;
4890 
4891 	mp1 = mp->b_cont;
4892 	ASSERT(mp1 != NULL);
4893 
4894 	if (ire != NULL) {
4895 		/*
4896 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4897 		 * appended mblk. Its <upper protocol>'s
4898 		 * job to make sure there is room.
4899 		 */
4900 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4901 			return (0);
4902 
4903 		mp1->b_datap->db_type = IRE_DB_TYPE;
4904 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4905 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4906 		ret_ire = (ire_t *)mp1->b_rptr;
4907 		/*
4908 		 * Pass the latest setting of the ip_path_mtu_discovery and
4909 		 * copy the ulp info if any.
4910 		 */
4911 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4912 		    IPH_DF : 0;
4913 		if (ulp_info != NULL) {
4914 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4915 			    sizeof (iulp_t));
4916 		}
4917 		ret_ire->ire_mp = mp1;
4918 	} else {
4919 		/*
4920 		 * No IRE was found. Remove IRE mblk.
4921 		 */
4922 		mp->b_cont = mp1->b_cont;
4923 		freeb(mp1);
4924 	}
4925 
4926 	return (1);
4927 }
4928 
4929 /*
4930  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4931  * the final piece where we don't.  Return a pointer to the first mblk in the
4932  * result, and update the pointer to the next mblk to chew on.  If anything
4933  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4934  * NULL pointer.
4935  */
4936 mblk_t *
4937 ip_carve_mp(mblk_t **mpp, ssize_t len)
4938 {
4939 	mblk_t	*mp0;
4940 	mblk_t	*mp1;
4941 	mblk_t	*mp2;
4942 
4943 	if (!len || !mpp || !(mp0 = *mpp))
4944 		return (NULL);
4945 	/* If we aren't going to consume the first mblk, we need a dup. */
4946 	if (mp0->b_wptr - mp0->b_rptr > len) {
4947 		mp1 = dupb(mp0);
4948 		if (mp1) {
4949 			/* Partition the data between the two mblks. */
4950 			mp1->b_wptr = mp1->b_rptr + len;
4951 			mp0->b_rptr = mp1->b_wptr;
4952 			/*
4953 			 * after adjustments if mblk not consumed is now
4954 			 * unaligned, try to align it. If this fails free
4955 			 * all messages and let upper layer recover.
4956 			 */
4957 			if (!OK_32PTR(mp0->b_rptr)) {
4958 				if (!pullupmsg(mp0, -1)) {
4959 					freemsg(mp0);
4960 					freemsg(mp1);
4961 					*mpp = NULL;
4962 					return (NULL);
4963 				}
4964 			}
4965 		}
4966 		return (mp1);
4967 	}
4968 	/* Eat through as many mblks as we need to get len bytes. */
4969 	len -= mp0->b_wptr - mp0->b_rptr;
4970 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4971 		if (mp2->b_wptr - mp2->b_rptr > len) {
4972 			/*
4973 			 * We won't consume the entire last mblk.  Like
4974 			 * above, dup and partition it.
4975 			 */
4976 			mp1->b_cont = dupb(mp2);
4977 			mp1 = mp1->b_cont;
4978 			if (!mp1) {
4979 				/*
4980 				 * Trouble.  Rather than go to a lot of
4981 				 * trouble to clean up, we free the messages.
4982 				 * This won't be any worse than losing it on
4983 				 * the wire.
4984 				 */
4985 				freemsg(mp0);
4986 				freemsg(mp2);
4987 				*mpp = NULL;
4988 				return (NULL);
4989 			}
4990 			mp1->b_wptr = mp1->b_rptr + len;
4991 			mp2->b_rptr = mp1->b_wptr;
4992 			/*
4993 			 * after adjustments if mblk not consumed is now
4994 			 * unaligned, try to align it. If this fails free
4995 			 * all messages and let upper layer recover.
4996 			 */
4997 			if (!OK_32PTR(mp2->b_rptr)) {
4998 				if (!pullupmsg(mp2, -1)) {
4999 					freemsg(mp0);
5000 					freemsg(mp2);
5001 					*mpp = NULL;
5002 					return (NULL);
5003 				}
5004 			}
5005 			*mpp = mp2;
5006 			return (mp0);
5007 		}
5008 		/* Decrement len by the amount we just got. */
5009 		len -= mp2->b_wptr - mp2->b_rptr;
5010 	}
5011 	/*
5012 	 * len should be reduced to zero now.  If not our caller has
5013 	 * screwed up.
5014 	 */
5015 	if (len) {
5016 		/* Shouldn't happen! */
5017 		freemsg(mp0);
5018 		*mpp = NULL;
5019 		return (NULL);
5020 	}
5021 	/*
5022 	 * We consumed up to exactly the end of an mblk.  Detach the part
5023 	 * we are returning from the rest of the chain.
5024 	 */
5025 	mp1->b_cont = NULL;
5026 	*mpp = mp2;
5027 	return (mp0);
5028 }
5029 
5030 /* The ill stream is being unplumbed. Called from ip_close */
5031 int
5032 ip_modclose(ill_t *ill)
5033 {
5034 
5035 	boolean_t success;
5036 	ipsq_t	*ipsq;
5037 	ipif_t	*ipif;
5038 	queue_t	*q = ill->ill_rq;
5039 
5040 	/*
5041 	 * Forcibly enter the ipsq after some delay. This is to take
5042 	 * care of the case when some ioctl does not complete because
5043 	 * we sent a control message to the driver and it did not
5044 	 * send us a reply. We want to be able to at least unplumb
5045 	 * and replumb rather than force the user to reboot the system.
5046 	 */
5047 	success = ipsq_enter(ill, B_FALSE);
5048 
5049 	/*
5050 	 * Open/close/push/pop is guaranteed to be single threaded
5051 	 * per stream by STREAMS. FS guarantees that all references
5052 	 * from top are gone before close is called. So there can't
5053 	 * be another close thread that has set CONDEMNED on this ill.
5054 	 * and cause ipsq_enter to return failure.
5055 	 */
5056 	ASSERT(success);
5057 	ipsq = ill->ill_phyint->phyint_ipsq;
5058 
5059 	/*
5060 	 * Mark it condemned. No new reference will be made to this ill.
5061 	 * Lookup functions will return an error. Threads that try to
5062 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5063 	 * that the refcnt will drop down to zero.
5064 	 */
5065 	mutex_enter(&ill->ill_lock);
5066 	ill->ill_state_flags |= ILL_CONDEMNED;
5067 	for (ipif = ill->ill_ipif; ipif != NULL;
5068 	    ipif = ipif->ipif_next) {
5069 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5070 	}
5071 	/*
5072 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5073 	 * returns  error if ILL_CONDEMNED is set
5074 	 */
5075 	cv_broadcast(&ill->ill_cv);
5076 	mutex_exit(&ill->ill_lock);
5077 
5078 	/*
5079 	 * Shut down fragmentation reassembly.
5080 	 * ill_frag_timer won't start a timer again.
5081 	 * Now cancel any existing timer
5082 	 */
5083 	(void) untimeout(ill->ill_frag_timer_id);
5084 	(void) ill_frag_timeout(ill, 0);
5085 
5086 	/*
5087 	 * If MOVE was in progress, clear the
5088 	 * move_in_progress fields also.
5089 	 */
5090 	if (ill->ill_move_in_progress) {
5091 		ILL_CLEAR_MOVE(ill);
5092 	}
5093 
5094 	/*
5095 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5096 	 * this ill. Then wait for the refcnts to drop to zero.
5097 	 * ill_is_quiescent checks whether the ill is really quiescent.
5098 	 * Then make sure that threads that are waiting to enter the
5099 	 * ipsq have seen the error returned by ipsq_enter and have
5100 	 * gone away. Then we call ill_delete_tail which does the
5101 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5102 	 */
5103 	ill_delete(ill);
5104 	mutex_enter(&ill->ill_lock);
5105 	while (!ill_is_quiescent(ill))
5106 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5107 	while (ill->ill_waiters)
5108 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5109 
5110 	mutex_exit(&ill->ill_lock);
5111 
5112 	/* qprocsoff is called in ill_delete_tail */
5113 	ill_delete_tail(ill);
5114 
5115 	/*
5116 	 * Walk through all upper (conn) streams and qenable
5117 	 * those that have queued data.
5118 	 * close synchronization needs this to
5119 	 * be done to ensure that all upper layers blocked
5120 	 * due to flow control to the closing device
5121 	 * get unblocked.
5122 	 */
5123 	ip1dbg(("ip_wsrv: walking\n"));
5124 	conn_walk_drain();
5125 
5126 	mutex_enter(&ip_mi_lock);
5127 	mi_close_unlink(&ip_g_head, (IDP)ill);
5128 	mutex_exit(&ip_mi_lock);
5129 
5130 	/*
5131 	 * credp could be null if the open didn't succeed and ip_modopen
5132 	 * itself calls ip_close.
5133 	 */
5134 	if (ill->ill_credp != NULL)
5135 		crfree(ill->ill_credp);
5136 
5137 	mi_close_free((IDP)ill);
5138 	q->q_ptr = WR(q)->q_ptr = NULL;
5139 
5140 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5141 
5142 	return (0);
5143 }
5144 
5145 /*
5146  * This is called as part of close() for both IP and UDP
5147  * in order to quiesce the conn.
5148  */
5149 void
5150 ip_quiesce_conn(conn_t *connp)
5151 {
5152 	boolean_t	drain_cleanup_reqd = B_FALSE;
5153 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5154 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5155 
5156 	ASSERT(!IPCL_IS_TCP(connp));
5157 
5158 	/*
5159 	 * Mark the conn as closing, and this conn must not be
5160 	 * inserted in future into any list. Eg. conn_drain_insert(),
5161 	 * won't insert this conn into the conn_drain_list.
5162 	 * Similarly ill_pending_mp_add() will not add any mp to
5163 	 * the pending mp list, after this conn has started closing.
5164 	 *
5165 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5166 	 * cannot get set henceforth.
5167 	 */
5168 	mutex_enter(&connp->conn_lock);
5169 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5170 	connp->conn_state_flags |= CONN_CLOSING;
5171 	if (connp->conn_idl != NULL)
5172 		drain_cleanup_reqd = B_TRUE;
5173 	if (connp->conn_oper_pending_ill != NULL)
5174 		conn_ioctl_cleanup_reqd = B_TRUE;
5175 	if (connp->conn_ilg_inuse != 0)
5176 		ilg_cleanup_reqd = B_TRUE;
5177 	mutex_exit(&connp->conn_lock);
5178 
5179 	if (IPCL_IS_UDP(connp))
5180 		udp_quiesce_conn(connp);
5181 
5182 	if (conn_ioctl_cleanup_reqd)
5183 		conn_ioctl_cleanup(connp);
5184 
5185 	if (is_system_labeled() && connp->conn_anon_port) {
5186 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5187 		    connp->conn_mlp_type, connp->conn_ulp,
5188 		    ntohs(connp->conn_lport), B_FALSE);
5189 		connp->conn_anon_port = 0;
5190 	}
5191 	connp->conn_mlp_type = mlptSingle;
5192 
5193 	/*
5194 	 * Remove this conn from any fanout list it is on.
5195 	 * and then wait for any threads currently operating
5196 	 * on this endpoint to finish
5197 	 */
5198 	ipcl_hash_remove(connp);
5199 
5200 	/*
5201 	 * Remove this conn from the drain list, and do
5202 	 * any other cleanup that may be required.
5203 	 * (Only non-tcp streams may have a non-null conn_idl.
5204 	 * TCP streams are never flow controlled, and
5205 	 * conn_idl will be null)
5206 	 */
5207 	if (drain_cleanup_reqd)
5208 		conn_drain_tail(connp, B_TRUE);
5209 
5210 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5211 		(void) ip_mrouter_done(NULL);
5212 
5213 	if (ilg_cleanup_reqd)
5214 		ilg_delete_all(connp);
5215 
5216 	conn_delete_ire(connp, NULL);
5217 
5218 	/*
5219 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5220 	 * callers from write side can't be there now because close
5221 	 * is in progress. The only other caller is ipcl_walk
5222 	 * which checks for the condemned flag.
5223 	 */
5224 	mutex_enter(&connp->conn_lock);
5225 	connp->conn_state_flags |= CONN_CONDEMNED;
5226 	while (connp->conn_ref != 1)
5227 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5228 	connp->conn_state_flags |= CONN_QUIESCED;
5229 	mutex_exit(&connp->conn_lock);
5230 }
5231 
5232 /* ARGSUSED */
5233 int
5234 ip_close(queue_t *q, int flags)
5235 {
5236 	conn_t		*connp;
5237 
5238 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5239 
5240 	/*
5241 	 * Call the appropriate delete routine depending on whether this is
5242 	 * a module or device.
5243 	 */
5244 	if (WR(q)->q_next != NULL) {
5245 		/* This is a module close */
5246 		return (ip_modclose((ill_t *)q->q_ptr));
5247 	}
5248 
5249 	connp = q->q_ptr;
5250 	ip_quiesce_conn(connp);
5251 
5252 	qprocsoff(q);
5253 
5254 	/*
5255 	 * Now we are truly single threaded on this stream, and can
5256 	 * delete the things hanging off the connp, and finally the connp.
5257 	 * We removed this connp from the fanout list, it cannot be
5258 	 * accessed thru the fanouts, and we already waited for the
5259 	 * conn_ref to drop to 0. We are already in close, so
5260 	 * there cannot be any other thread from the top. qprocsoff
5261 	 * has completed, and service has completed or won't run in
5262 	 * future.
5263 	 */
5264 	ASSERT(connp->conn_ref == 1);
5265 
5266 	/*
5267 	 * A conn which was previously marked as IPCL_UDP cannot
5268 	 * retain the flag because it would have been cleared by
5269 	 * udp_close().
5270 	 */
5271 	ASSERT(!IPCL_IS_UDP(connp));
5272 
5273 	if (connp->conn_latch != NULL) {
5274 		IPLATCH_REFRELE(connp->conn_latch);
5275 		connp->conn_latch = NULL;
5276 	}
5277 	if (connp->conn_policy != NULL) {
5278 		IPPH_REFRELE(connp->conn_policy);
5279 		connp->conn_policy = NULL;
5280 	}
5281 	if (connp->conn_ipsec_opt_mp != NULL) {
5282 		freemsg(connp->conn_ipsec_opt_mp);
5283 		connp->conn_ipsec_opt_mp = NULL;
5284 	}
5285 
5286 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5287 
5288 	connp->conn_ref--;
5289 	ipcl_conn_destroy(connp);
5290 
5291 	q->q_ptr = WR(q)->q_ptr = NULL;
5292 	return (0);
5293 }
5294 
5295 int
5296 ip_snmpmod_close(queue_t *q)
5297 {
5298 	conn_t *connp = Q_TO_CONN(q);
5299 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5300 
5301 	qprocsoff(q);
5302 
5303 	if (connp->conn_flags & IPCL_UDPMOD)
5304 		udp_close_free(connp);
5305 
5306 	if (connp->conn_cred != NULL) {
5307 		crfree(connp->conn_cred);
5308 		connp->conn_cred = NULL;
5309 	}
5310 	CONN_DEC_REF(connp);
5311 	q->q_ptr = WR(q)->q_ptr = NULL;
5312 	return (0);
5313 }
5314 
5315 /*
5316  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5317  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5318  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5319  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5320  * queues as we never enqueue messages there and we don't handle any ioctls.
5321  * Everything else is freed.
5322  */
5323 void
5324 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5325 {
5326 	conn_t	*connp = q->q_ptr;
5327 	pfi_t	setfn;
5328 	pfi_t	getfn;
5329 
5330 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5331 
5332 	switch (DB_TYPE(mp)) {
5333 	case M_PROTO:
5334 	case M_PCPROTO:
5335 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5336 		    ((((union T_primitives *)mp->b_rptr)->type ==
5337 			T_SVR4_OPTMGMT_REQ) ||
5338 		    (((union T_primitives *)mp->b_rptr)->type ==
5339 			T_OPTMGMT_REQ))) {
5340 			/*
5341 			 * This is the only TPI primitive supported. Its
5342 			 * handling does not require tcp_t, but it does require
5343 			 * conn_t to check permissions.
5344 			 */
5345 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5346 
5347 			if (connp->conn_flags & IPCL_TCPMOD) {
5348 				setfn = tcp_snmp_set;
5349 				getfn = tcp_snmp_get;
5350 			} else {
5351 				setfn = udp_snmp_set;
5352 				getfn = udp_snmp_get;
5353 			}
5354 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5355 				freemsg(mp);
5356 				return;
5357 			}
5358 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5359 		    != NULL)
5360 			qreply(q, mp);
5361 		break;
5362 	case M_FLUSH:
5363 	case M_IOCTL:
5364 		putnext(q, mp);
5365 		break;
5366 	default:
5367 		freemsg(mp);
5368 		break;
5369 	}
5370 }
5371 
5372 /* Return the IP checksum for the IP header at "iph". */
5373 uint16_t
5374 ip_csum_hdr(ipha_t *ipha)
5375 {
5376 	uint16_t	*uph;
5377 	uint32_t	sum;
5378 	int		opt_len;
5379 
5380 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5381 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5382 	uph = (uint16_t *)ipha;
5383 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5384 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5385 	if (opt_len > 0) {
5386 		do {
5387 			sum += uph[10];
5388 			sum += uph[11];
5389 			uph += 2;
5390 		} while (--opt_len);
5391 	}
5392 	sum = (sum & 0xFFFF) + (sum >> 16);
5393 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5394 	if (sum == 0xffff)
5395 		sum = 0;
5396 	return ((uint16_t)sum);
5397 }
5398 
5399 void
5400 ip_ddi_destroy(void)
5401 {
5402 	tnet_fini();
5403 	tcp_ddi_destroy();
5404 	sctp_ddi_destroy();
5405 	ipsec_loader_destroy();
5406 	ipsec_policy_destroy();
5407 	ipsec_kstat_destroy();
5408 	nd_free(&ip_g_nd);
5409 	mutex_destroy(&igmp_timer_lock);
5410 	mutex_destroy(&mld_timer_lock);
5411 	mutex_destroy(&igmp_slowtimeout_lock);
5412 	mutex_destroy(&mld_slowtimeout_lock);
5413 	mutex_destroy(&ip_mi_lock);
5414 	mutex_destroy(&rts_clients.connf_lock);
5415 	ip_ire_fini();
5416 	ip6_asp_free();
5417 	conn_drain_fini();
5418 	ipcl_destroy();
5419 	inet_minor_destroy(ip_minor_arena);
5420 	icmp_kstat_fini();
5421 	ip_kstat_fini();
5422 	rw_destroy(&ipsec_capab_ills_lock);
5423 	rw_destroy(&ill_g_usesrc_lock);
5424 	ip_drop_unregister(&ip_dropper);
5425 }
5426 
5427 
5428 void
5429 ip_ddi_init(void)
5430 {
5431 	TCP6_MAJ = ddi_name_to_major(TCP6);
5432 	TCP_MAJ	= ddi_name_to_major(TCP);
5433 	SCTP_MAJ = ddi_name_to_major(SCTP);
5434 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5435 
5436 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5437 
5438 	/* IP's IPsec code calls the packet dropper */
5439 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5440 
5441 	if (!ip_g_nd) {
5442 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5443 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5444 			nd_free(&ip_g_nd);
5445 		}
5446 	}
5447 
5448 	ipsec_loader_init();
5449 	ipsec_policy_init();
5450 	ipsec_kstat_init();
5451 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5452 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5453 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5454 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5455 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5456 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5457 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5458 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5459 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5460 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5461 
5462 	/*
5463 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5464 	 * initial devices: ip, ip6, tcp, tcp6.
5465 	 */
5466 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5467 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5468 		cmn_err(CE_PANIC,
5469 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5470 	}
5471 
5472 	ipcl_init();
5473 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5474 	ip_ire_init();
5475 	ip6_asp_init();
5476 	ipif_init();
5477 	conn_drain_init();
5478 	tcp_ddi_init();
5479 	sctp_ddi_init();
5480 
5481 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5482 
5483 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5484 		"net", KSTAT_TYPE_NAMED,
5485 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5486 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5487 		ip_kstat->ks_data = &ip_statistics;
5488 		kstat_install(ip_kstat);
5489 	}
5490 	ip_kstat_init();
5491 	ip6_kstat_init();
5492 	icmp_kstat_init();
5493 	ipsec_loader_start();
5494 	tnet_init();
5495 }
5496 
5497 /*
5498  * Allocate and initialize a DLPI template of the specified length.  (May be
5499  * called as writer.)
5500  */
5501 mblk_t *
5502 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5503 {
5504 	mblk_t	*mp;
5505 
5506 	mp = allocb(len, BPRI_MED);
5507 	if (!mp)
5508 		return (NULL);
5509 
5510 	/*
5511 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5512 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5513 	 * that other DLPI are M_PROTO.
5514 	 */
5515 	if (prim == DL_INFO_REQ) {
5516 		mp->b_datap->db_type = M_PCPROTO;
5517 	} else {
5518 		mp->b_datap->db_type = M_PROTO;
5519 	}
5520 
5521 	mp->b_wptr = mp->b_rptr + len;
5522 	bzero(mp->b_rptr, len);
5523 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5524 	return (mp);
5525 }
5526 
5527 const char *
5528 dlpi_prim_str(int prim)
5529 {
5530 	switch (prim) {
5531 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5532 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5533 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5534 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5535 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5536 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5537 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5538 	case DL_OK_ACK:		return ("DL_OK_ACK");
5539 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5540 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5541 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5542 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5543 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5544 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5545 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5546 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5547 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5548 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5549 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5550 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5551 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5552 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5553 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5554 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5555 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5556 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5557 	default:		return ("<unknown primitive>");
5558 	}
5559 }
5560 
5561 const char *
5562 dlpi_err_str(int err)
5563 {
5564 	switch (err) {
5565 	case DL_ACCESS:		return ("DL_ACCESS");
5566 	case DL_BADADDR:	return ("DL_BADADDR");
5567 	case DL_BADCORR:	return ("DL_BADCORR");
5568 	case DL_BADDATA:	return ("DL_BADDATA");
5569 	case DL_BADPPA:		return ("DL_BADPPA");
5570 	case DL_BADPRIM:	return ("DL_BADPRIM");
5571 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5572 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5573 	case DL_BADSAP:		return ("DL_BADSAP");
5574 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5575 	case DL_BOUND:		return ("DL_BOUND");
5576 	case DL_INITFAILED:	return ("DL_INITFAILED");
5577 	case DL_NOADDR:		return ("DL_NOADDR");
5578 	case DL_NOTINIT:	return ("DL_NOTINIT");
5579 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5580 	case DL_SYSERR:		return ("DL_SYSERR");
5581 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5582 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5583 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5584 	case DL_TOOMANY:	return ("DL_TOOMANY");
5585 	case DL_NOTENAB:	return ("DL_NOTENAB");
5586 	case DL_BUSY:		return ("DL_BUSY");
5587 	case DL_NOAUTO:		return ("DL_NOAUTO");
5588 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5589 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5590 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5591 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5592 	case DL_PENDING:	return ("DL_PENDING");
5593 	default:		return ("<unknown error>");
5594 	}
5595 }
5596 
5597 /*
5598  * Debug formatting routine.  Returns a character string representation of the
5599  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5600  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5601  */
5602 char *
5603 ip_dot_addr(ipaddr_t addr, char *buf)
5604 {
5605 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5606 }
5607 
5608 /*
5609  * Debug formatting routine.  Returns a character string representation of the
5610  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5611  * as a pointer.  The "xxx" parts including left zero padding so the final
5612  * string will fit easily in tables.  It would be nice to take a padding
5613  * length argument instead.
5614  */
5615 static char *
5616 ip_dot_saddr(uchar_t *addr, char *buf)
5617 {
5618 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5619 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5620 	return (buf);
5621 }
5622 
5623 /*
5624  * Send an ICMP error after patching up the packet appropriately.  Returns
5625  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5626  */
5627 static boolean_t
5628 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5629     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5630 {
5631 	ipha_t *ipha;
5632 	mblk_t *first_mp;
5633 	boolean_t secure;
5634 	unsigned char db_type;
5635 
5636 	first_mp = mp;
5637 	if (mctl_present) {
5638 		mp = mp->b_cont;
5639 		secure = ipsec_in_is_secure(first_mp);
5640 		ASSERT(mp != NULL);
5641 	} else {
5642 		/*
5643 		 * If this is an ICMP error being reported - which goes
5644 		 * up as M_CTLs, we need to convert them to M_DATA till
5645 		 * we finish checking with global policy because
5646 		 * ipsec_check_global_policy() assumes M_DATA as clear
5647 		 * and M_CTL as secure.
5648 		 */
5649 		db_type = DB_TYPE(mp);
5650 		DB_TYPE(mp) = M_DATA;
5651 		secure = B_FALSE;
5652 	}
5653 	/*
5654 	 * We are generating an icmp error for some inbound packet.
5655 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5656 	 * Before we generate an error, check with global policy
5657 	 * to see whether this is allowed to enter the system. As
5658 	 * there is no "conn", we are checking with global policy.
5659 	 */
5660 	ipha = (ipha_t *)mp->b_rptr;
5661 	if (secure || ipsec_inbound_v4_policy_present) {
5662 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5663 		    ipha, NULL, mctl_present);
5664 		if (first_mp == NULL)
5665 			return (B_FALSE);
5666 	}
5667 
5668 	if (!mctl_present)
5669 		DB_TYPE(mp) = db_type;
5670 
5671 	if (flags & IP_FF_SEND_ICMP) {
5672 		if (flags & IP_FF_HDR_COMPLETE) {
5673 			if (ip_hdr_complete(ipha, zoneid)) {
5674 				freemsg(first_mp);
5675 				return (B_TRUE);
5676 			}
5677 		}
5678 		if (flags & IP_FF_CKSUM) {
5679 			/*
5680 			 * Have to correct checksum since
5681 			 * the packet might have been
5682 			 * fragmented and the reassembly code in ip_rput
5683 			 * does not restore the IP checksum.
5684 			 */
5685 			ipha->ipha_hdr_checksum = 0;
5686 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5687 		}
5688 		switch (icmp_type) {
5689 		case ICMP_DEST_UNREACHABLE:
5690 			icmp_unreachable(WR(q), first_mp, icmp_code);
5691 			break;
5692 		default:
5693 			freemsg(first_mp);
5694 			break;
5695 		}
5696 	} else {
5697 		freemsg(first_mp);
5698 		return (B_FALSE);
5699 	}
5700 
5701 	return (B_TRUE);
5702 }
5703 
5704 /*
5705  * Used to send an ICMP error message when a packet is received for
5706  * a protocol that is not supported. The mblk passed as argument
5707  * is consumed by this function.
5708  */
5709 void
5710 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5711 {
5712 	mblk_t *mp;
5713 	ipha_t *ipha;
5714 	ill_t *ill;
5715 	ipsec_in_t *ii;
5716 
5717 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5718 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5719 
5720 	mp = ipsec_mp->b_cont;
5721 	ipsec_mp->b_cont = NULL;
5722 	ipha = (ipha_t *)mp->b_rptr;
5723 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5724 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5725 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5726 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5727 		}
5728 	} else {
5729 		/* Get ill from index in ipsec_in_t. */
5730 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5731 		    B_TRUE, NULL, NULL, NULL, NULL);
5732 		if (ill != NULL) {
5733 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5734 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5735 			    0, B_FALSE, zoneid)) {
5736 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5737 			}
5738 
5739 			ill_refrele(ill);
5740 		} else { /* re-link for the freemsg() below. */
5741 			ipsec_mp->b_cont = mp;
5742 		}
5743 	}
5744 
5745 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5746 	freemsg(ipsec_mp);
5747 }
5748 
5749 /*
5750  * See if the inbound datagram has had IPsec processing applied to it.
5751  */
5752 boolean_t
5753 ipsec_in_is_secure(mblk_t *ipsec_mp)
5754 {
5755 	ipsec_in_t *ii;
5756 
5757 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5758 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5759 
5760 	if (ii->ipsec_in_loopback) {
5761 		return (ii->ipsec_in_secure);
5762 	} else {
5763 		return (ii->ipsec_in_ah_sa != NULL ||
5764 		    ii->ipsec_in_esp_sa != NULL ||
5765 		    ii->ipsec_in_decaps);
5766 	}
5767 }
5768 
5769 /*
5770  * Handle protocols with which IP is less intimate.  There
5771  * can be more than one stream bound to a particular
5772  * protocol.  When this is the case, normally each one gets a copy
5773  * of any incoming packets.
5774  *
5775  * IPSEC NOTE :
5776  *
5777  * Don't allow a secure packet going up a non-secure connection.
5778  * We don't allow this because
5779  *
5780  * 1) Reply might go out in clear which will be dropped at
5781  *    the sending side.
5782  * 2) If the reply goes out in clear it will give the
5783  *    adversary enough information for getting the key in
5784  *    most of the cases.
5785  *
5786  * Moreover getting a secure packet when we expect clear
5787  * implies that SA's were added without checking for
5788  * policy on both ends. This should not happen once ISAKMP
5789  * is used to negotiate SAs as SAs will be added only after
5790  * verifying the policy.
5791  *
5792  * NOTE : If the packet was tunneled and not multicast we only send
5793  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5794  * back to delivering packets to AF_INET6 raw sockets.
5795  *
5796  * IPQoS Notes:
5797  * Once we have determined the client, invoke IPPF processing.
5798  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5799  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5800  * ip_policy will be false.
5801  *
5802  * Zones notes:
5803  * Currently only applications in the global zone can create raw sockets for
5804  * protocols other than ICMP. So unlike the broadcast / multicast case of
5805  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5806  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5807  */
5808 static void
5809 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5810     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5811     zoneid_t zoneid)
5812 {
5813 	queue_t	*rq;
5814 	mblk_t	*mp1, *first_mp1;
5815 	uint_t	protocol = ipha->ipha_protocol;
5816 	ipaddr_t dst;
5817 	boolean_t one_only;
5818 	mblk_t *first_mp = mp;
5819 	boolean_t secure;
5820 	uint32_t ill_index;
5821 	conn_t	*connp, *first_connp, *next_connp;
5822 	connf_t	*connfp;
5823 	boolean_t shared_addr;
5824 
5825 	if (mctl_present) {
5826 		mp = first_mp->b_cont;
5827 		secure = ipsec_in_is_secure(first_mp);
5828 		ASSERT(mp != NULL);
5829 	} else {
5830 		secure = B_FALSE;
5831 	}
5832 	dst = ipha->ipha_dst;
5833 	/*
5834 	 * If the packet was tunneled and not multicast we only send to it
5835 	 * the first match.
5836 	 */
5837 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5838 	    !CLASSD(dst));
5839 
5840 	shared_addr = (zoneid == ALL_ZONES);
5841 	if (shared_addr) {
5842 		/*
5843 		 * We don't allow multilevel ports for raw IP, so no need to
5844 		 * check for that here.
5845 		 */
5846 		zoneid = tsol_packet_to_zoneid(mp);
5847 	}
5848 
5849 	connfp = &ipcl_proto_fanout[protocol];
5850 	mutex_enter(&connfp->connf_lock);
5851 	connp = connfp->connf_head;
5852 	for (connp = connfp->connf_head; connp != NULL;
5853 		connp = connp->conn_next) {
5854 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
5855 		    zoneid) &&
5856 		    (!is_system_labeled() ||
5857 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
5858 		    connp)))
5859 			break;
5860 	}
5861 
5862 	if (connp == NULL || connp->conn_upq == NULL) {
5863 		/*
5864 		 * No one bound to these addresses.  Is
5865 		 * there a client that wants all
5866 		 * unclaimed datagrams?
5867 		 */
5868 		mutex_exit(&connfp->connf_lock);
5869 		/*
5870 		 * Check for IPPROTO_ENCAP...
5871 		 */
5872 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5873 			/*
5874 			 * XXX If an IPsec mblk is here on a multicast
5875 			 * tunnel (using ip_mroute stuff), what should
5876 			 * I do?
5877 			 *
5878 			 * For now, just free the IPsec mblk before
5879 			 * passing it up to the multicast routing
5880 			 * stuff.
5881 			 *
5882 			 * BTW,  If I match a configured IP-in-IP
5883 			 * tunnel, ip_mroute_decap will never be
5884 			 * called.
5885 			 */
5886 			if (mp != first_mp)
5887 				freeb(first_mp);
5888 			ip_mroute_decap(q, mp);
5889 		} else {
5890 			/*
5891 			 * Otherwise send an ICMP protocol unreachable.
5892 			 */
5893 			if (ip_fanout_send_icmp(q, first_mp, flags,
5894 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5895 			    mctl_present, zoneid)) {
5896 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5897 			}
5898 		}
5899 		return;
5900 	}
5901 	CONN_INC_REF(connp);
5902 	first_connp = connp;
5903 
5904 	/*
5905 	 * Only send message to one tunnel driver by immediately
5906 	 * terminating the loop.
5907 	 */
5908 	connp = one_only ? NULL : connp->conn_next;
5909 
5910 	for (;;) {
5911 		while (connp != NULL) {
5912 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5913 			    flags, zoneid) &&
5914 			    (!is_system_labeled() ||
5915 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
5916 			    shared_addr, connp)))
5917 				break;
5918 			connp = connp->conn_next;
5919 		}
5920 
5921 		/*
5922 		 * Copy the packet.
5923 		 */
5924 		if (connp == NULL || connp->conn_upq == NULL ||
5925 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5926 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5927 			/*
5928 			 * No more interested clients or memory
5929 			 * allocation failed
5930 			 */
5931 			connp = first_connp;
5932 			break;
5933 		}
5934 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5935 		CONN_INC_REF(connp);
5936 		mutex_exit(&connfp->connf_lock);
5937 		rq = connp->conn_rq;
5938 		if (!canputnext(rq)) {
5939 			if (flags & IP_FF_RAWIP) {
5940 				BUMP_MIB(&ip_mib, rawipInOverflows);
5941 			} else {
5942 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5943 			}
5944 
5945 			freemsg(first_mp1);
5946 		} else {
5947 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5948 				first_mp1 = ipsec_check_inbound_policy
5949 				    (first_mp1, connp, ipha, NULL,
5950 				    mctl_present);
5951 			}
5952 			if (first_mp1 != NULL) {
5953 				/*
5954 				 * ip_fanout_proto also gets called from
5955 				 * icmp_inbound_error_fanout, in which case
5956 				 * the msg type is M_CTL.  Don't add info
5957 				 * in this case for the time being. In future
5958 				 * when there is a need for knowing the
5959 				 * inbound iface index for ICMP error msgs,
5960 				 * then this can be changed.
5961 				 */
5962 				if ((connp->conn_recvif != 0) &&
5963 				    (mp->b_datap->db_type != M_CTL)) {
5964 					/*
5965 					 * the actual data will be
5966 					 * contained in b_cont upon
5967 					 * successful return of the
5968 					 * following call else
5969 					 * original mblk is returned
5970 					 */
5971 					ASSERT(recv_ill != NULL);
5972 					mp1 = ip_add_info(mp1, recv_ill,
5973 						IPF_RECVIF);
5974 				}
5975 				BUMP_MIB(&ip_mib, ipInDelivers);
5976 				if (mctl_present)
5977 					freeb(first_mp1);
5978 				putnext(rq, mp1);
5979 			}
5980 		}
5981 		mutex_enter(&connfp->connf_lock);
5982 		/* Follow the next pointer before releasing the conn. */
5983 		next_connp = connp->conn_next;
5984 		CONN_DEC_REF(connp);
5985 		connp = next_connp;
5986 	}
5987 
5988 	/* Last one.  Send it upstream. */
5989 	mutex_exit(&connfp->connf_lock);
5990 
5991 	/*
5992 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5993 	 * will be set to false.
5994 	 */
5995 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5996 		ill_index = ill->ill_phyint->phyint_ifindex;
5997 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5998 		if (mp == NULL) {
5999 			CONN_DEC_REF(connp);
6000 			if (mctl_present) {
6001 				freeb(first_mp);
6002 			}
6003 			return;
6004 		}
6005 	}
6006 
6007 	rq = connp->conn_rq;
6008 	if (!canputnext(rq)) {
6009 		if (flags & IP_FF_RAWIP) {
6010 			BUMP_MIB(&ip_mib, rawipInOverflows);
6011 		} else {
6012 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6013 		}
6014 
6015 		freemsg(first_mp);
6016 	} else {
6017 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6018 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6019 			    ipha, NULL, mctl_present);
6020 		}
6021 		if (first_mp != NULL) {
6022 			/*
6023 			 * ip_fanout_proto also gets called
6024 			 * from icmp_inbound_error_fanout, in
6025 			 * which case the msg type is M_CTL.
6026 			 * Don't add info in this case for time
6027 			 * being. In future when there is a
6028 			 * need for knowing the inbound iface
6029 			 * index for ICMP error msgs, then this
6030 			 * can be changed
6031 			 */
6032 			if ((connp->conn_recvif != 0) &&
6033 			    (mp->b_datap->db_type != M_CTL)) {
6034 				/*
6035 				 * the actual data will be contained in
6036 				 * b_cont upon successful return
6037 				 * of the following call else original
6038 				 * mblk is returned
6039 				 */
6040 				ASSERT(recv_ill != NULL);
6041 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6042 			}
6043 			BUMP_MIB(&ip_mib, ipInDelivers);
6044 			putnext(rq, mp);
6045 			if (mctl_present)
6046 				freeb(first_mp);
6047 		}
6048 	}
6049 	CONN_DEC_REF(connp);
6050 }
6051 
6052 /*
6053  * Fanout for TCP packets
6054  * The caller puts <fport, lport> in the ports parameter.
6055  *
6056  * IPQoS Notes
6057  * Before sending it to the client, invoke IPPF processing.
6058  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6059  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6060  * ip_policy is false.
6061  */
6062 static void
6063 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6064     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6065 {
6066 	mblk_t  *first_mp;
6067 	boolean_t secure;
6068 	uint32_t ill_index;
6069 	int	ip_hdr_len;
6070 	tcph_t	*tcph;
6071 	boolean_t syn_present = B_FALSE;
6072 	conn_t	*connp;
6073 
6074 	first_mp = mp;
6075 	if (mctl_present) {
6076 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6077 		mp = first_mp->b_cont;
6078 		secure = ipsec_in_is_secure(first_mp);
6079 		ASSERT(mp != NULL);
6080 	} else {
6081 		secure = B_FALSE;
6082 	}
6083 
6084 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6085 
6086 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6087 	    NULL) {
6088 		/*
6089 		 * No connected connection or listener. Send a
6090 		 * TH_RST via tcp_xmit_listeners_reset.
6091 		 */
6092 
6093 		/* Initiate IPPf processing, if needed. */
6094 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6095 			uint32_t ill_index;
6096 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6097 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6098 			if (first_mp == NULL)
6099 				return;
6100 		}
6101 		BUMP_MIB(&ip_mib, ipInDelivers);
6102 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6103 		    zoneid));
6104 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6105 		return;
6106 	}
6107 
6108 	/*
6109 	 * Allocate the SYN for the TCP connection here itself
6110 	 */
6111 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6112 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6113 		if (IPCL_IS_TCP(connp)) {
6114 			squeue_t *sqp;
6115 
6116 			/*
6117 			 * For fused tcp loopback, assign the eager's
6118 			 * squeue to be that of the active connect's.
6119 			 * Note that we don't check for IP_FF_LOOPBACK
6120 			 * here since this routine gets called only
6121 			 * for loopback (unlike the IPv6 counterpart).
6122 			 */
6123 			ASSERT(Q_TO_CONN(q) != NULL);
6124 			if (do_tcp_fusion &&
6125 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6126 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6127 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6128 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6129 				sqp = Q_TO_CONN(q)->conn_sqp;
6130 			} else {
6131 				sqp = IP_SQUEUE_GET(lbolt);
6132 			}
6133 
6134 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6135 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6136 			syn_present = B_TRUE;
6137 		}
6138 	}
6139 
6140 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6141 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6142 		if ((flags & TH_RST) || (flags & TH_URG)) {
6143 			CONN_DEC_REF(connp);
6144 			freemsg(first_mp);
6145 			return;
6146 		}
6147 		if (flags & TH_ACK) {
6148 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6149 			CONN_DEC_REF(connp);
6150 			return;
6151 		}
6152 
6153 		CONN_DEC_REF(connp);
6154 		freemsg(first_mp);
6155 		return;
6156 	}
6157 
6158 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6159 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6160 		    NULL, mctl_present);
6161 		if (first_mp == NULL) {
6162 			CONN_DEC_REF(connp);
6163 			return;
6164 		}
6165 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6166 			ASSERT(syn_present);
6167 			if (mctl_present) {
6168 				ASSERT(first_mp != mp);
6169 				first_mp->b_datap->db_struioflag |=
6170 				    STRUIO_POLICY;
6171 			} else {
6172 				ASSERT(first_mp == mp);
6173 				mp->b_datap->db_struioflag &=
6174 				    ~STRUIO_EAGER;
6175 				mp->b_datap->db_struioflag |=
6176 				    STRUIO_POLICY;
6177 			}
6178 		} else {
6179 			/*
6180 			 * Discard first_mp early since we're dealing with a
6181 			 * fully-connected conn_t and tcp doesn't do policy in
6182 			 * this case.
6183 			 */
6184 			if (mctl_present) {
6185 				freeb(first_mp);
6186 				mctl_present = B_FALSE;
6187 			}
6188 			first_mp = mp;
6189 		}
6190 	}
6191 
6192 	/*
6193 	 * Initiate policy processing here if needed. If we get here from
6194 	 * icmp_inbound_error_fanout, ip_policy is false.
6195 	 */
6196 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6197 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6198 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6199 		if (mp == NULL) {
6200 			CONN_DEC_REF(connp);
6201 			if (mctl_present)
6202 				freeb(first_mp);
6203 			return;
6204 		} else if (mctl_present) {
6205 			ASSERT(first_mp != mp);
6206 			first_mp->b_cont = mp;
6207 		} else {
6208 			first_mp = mp;
6209 		}
6210 	}
6211 
6212 
6213 
6214 	/* Handle IPv6 socket options. */
6215 	if (!syn_present &&
6216 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6217 		/* Add header */
6218 		ASSERT(recv_ill != NULL);
6219 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6220 		if (mp == NULL) {
6221 			CONN_DEC_REF(connp);
6222 			if (mctl_present)
6223 				freeb(first_mp);
6224 			return;
6225 		} else if (mctl_present) {
6226 			/*
6227 			 * ip_add_info might return a new mp.
6228 			 */
6229 			ASSERT(first_mp != mp);
6230 			first_mp->b_cont = mp;
6231 		} else {
6232 			first_mp = mp;
6233 		}
6234 	}
6235 
6236 	BUMP_MIB(&ip_mib, ipInDelivers);
6237 	if (IPCL_IS_TCP(connp)) {
6238 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6239 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6240 	} else {
6241 		putnext(connp->conn_rq, first_mp);
6242 		CONN_DEC_REF(connp);
6243 	}
6244 }
6245 
6246 /*
6247  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6248  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6249  * Caller is responsible for dropping references to the conn, and freeing
6250  * first_mp.
6251  *
6252  * IPQoS Notes
6253  * Before sending it to the client, invoke IPPF processing. Policy processing
6254  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6255  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6256  * ip_wput_local, ip_policy is false.
6257  */
6258 static void
6259 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6260     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6261     boolean_t ip_policy)
6262 {
6263 	boolean_t	mctl_present = (first_mp != NULL);
6264 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6265 	uint32_t	ill_index;
6266 
6267 	if (mctl_present)
6268 		first_mp->b_cont = mp;
6269 	else
6270 		first_mp = mp;
6271 
6272 	if (CONN_UDP_FLOWCTLD(connp)) {
6273 		BUMP_MIB(&ip_mib, udpInOverflows);
6274 		freemsg(first_mp);
6275 		return;
6276 	}
6277 
6278 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6279 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6280 		    NULL, mctl_present);
6281 		if (first_mp == NULL)
6282 			return;	/* Freed by ipsec_check_inbound_policy(). */
6283 	}
6284 	if (mctl_present)
6285 		freeb(first_mp);
6286 
6287 	if (connp->conn_recvif)
6288 		in_flags = IPF_RECVIF;
6289 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6290 		in_flags |= IPF_RECVSLLA;
6291 
6292 	/* Handle IPv6 options. */
6293 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6294 		in_flags |= IPF_RECVIF;
6295 
6296 	/*
6297 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6298 	 * freed if the packet is dropped. The caller will do so.
6299 	 */
6300 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6301 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6302 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6303 		if (mp == NULL) {
6304 			return;
6305 		}
6306 	}
6307 	if ((in_flags != 0) &&
6308 	    (mp->b_datap->db_type != M_CTL)) {
6309 		/*
6310 		 * The actual data will be contained in b_cont
6311 		 * upon successful return of the following call
6312 		 * else original mblk is returned
6313 		 */
6314 		ASSERT(recv_ill != NULL);
6315 		mp = ip_add_info(mp, recv_ill, in_flags);
6316 	}
6317 	BUMP_MIB(&ip_mib, ipInDelivers);
6318 
6319 	/* Send it upstream */
6320 	CONN_UDP_RECV(connp, mp);
6321 }
6322 
6323 /*
6324  * Fanout for UDP packets.
6325  * The caller puts <fport, lport> in the ports parameter.
6326  *
6327  * If SO_REUSEADDR is set all multicast and broadcast packets
6328  * will be delivered to all streams bound to the same port.
6329  *
6330  * Zones notes:
6331  * Multicast and broadcast packets will be distributed to streams in all zones.
6332  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6333  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6334  * packets. To maintain this behavior with multiple zones, the conns are grouped
6335  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6336  * each zone. If unset, all the following conns in the same zone are skipped.
6337  */
6338 static void
6339 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6340     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6341     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6342 {
6343 	uint32_t	dstport, srcport;
6344 	ipaddr_t	dst;
6345 	mblk_t		*first_mp;
6346 	boolean_t	secure;
6347 	in6_addr_t	v6src;
6348 	conn_t		*connp;
6349 	connf_t		*connfp;
6350 	conn_t		*first_connp;
6351 	conn_t		*next_connp;
6352 	mblk_t		*mp1, *first_mp1;
6353 	ipaddr_t	src;
6354 	zoneid_t	last_zoneid;
6355 	boolean_t	reuseaddr;
6356 	boolean_t	shared_addr;
6357 
6358 	first_mp = mp;
6359 	if (mctl_present) {
6360 		mp = first_mp->b_cont;
6361 		first_mp->b_cont = NULL;
6362 		secure = ipsec_in_is_secure(first_mp);
6363 		ASSERT(mp != NULL);
6364 	} else {
6365 		first_mp = NULL;
6366 		secure = B_FALSE;
6367 	}
6368 
6369 	/* Extract ports in net byte order */
6370 	dstport = htons(ntohl(ports) & 0xFFFF);
6371 	srcport = htons(ntohl(ports) >> 16);
6372 	dst = ipha->ipha_dst;
6373 	src = ipha->ipha_src;
6374 
6375 	shared_addr = (zoneid == ALL_ZONES);
6376 	if (shared_addr) {
6377 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6378 		if (zoneid == ALL_ZONES)
6379 			zoneid = tsol_packet_to_zoneid(mp);
6380 	}
6381 
6382 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6383 	mutex_enter(&connfp->connf_lock);
6384 	connp = connfp->connf_head;
6385 	if (!broadcast && !CLASSD(dst)) {
6386 		/*
6387 		 * Not broadcast or multicast. Send to the one (first)
6388 		 * client we find. No need to check conn_wantpacket()
6389 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6390 		 * IPv4 unicast packets.
6391 		 */
6392 		while ((connp != NULL) &&
6393 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6394 		    srcport, src) ||
6395 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6396 			connp = connp->conn_next;
6397 		}
6398 
6399 		if (connp == NULL || connp->conn_upq == NULL)
6400 			goto notfound;
6401 
6402 		if (is_system_labeled() &&
6403 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6404 		    connp))
6405 			goto notfound;
6406 
6407 		CONN_INC_REF(connp);
6408 		mutex_exit(&connfp->connf_lock);
6409 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6410 		    recv_ill, ip_policy);
6411 		IP_STAT(ip_udp_fannorm);
6412 		CONN_DEC_REF(connp);
6413 		return;
6414 	}
6415 
6416 	/*
6417 	 * Broadcast and multicast case
6418 	 *
6419 	 * Need to check conn_wantpacket().
6420 	 * If SO_REUSEADDR has been set on the first we send the
6421 	 * packet to all clients that have joined the group and
6422 	 * match the port.
6423 	 */
6424 
6425 	while (connp != NULL) {
6426 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6427 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6428 		    (!is_system_labeled() ||
6429 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6430 		    connp)))
6431 			break;
6432 		connp = connp->conn_next;
6433 	}
6434 
6435 	if (connp == NULL || connp->conn_upq == NULL)
6436 		goto notfound;
6437 
6438 	first_connp = connp;
6439 	/*
6440 	 * When SO_REUSEADDR is not set, send the packet only to the first
6441 	 * matching connection in its zone by keeping track of the zoneid.
6442 	 */
6443 	reuseaddr = first_connp->conn_reuseaddr;
6444 	last_zoneid = first_connp->conn_zoneid;
6445 
6446 	CONN_INC_REF(connp);
6447 	connp = connp->conn_next;
6448 	for (;;) {
6449 		while (connp != NULL) {
6450 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6451 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6452 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6453 			    (!is_system_labeled() ||
6454 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6455 			    shared_addr, connp)))
6456 				break;
6457 			connp = connp->conn_next;
6458 		}
6459 		/*
6460 		 * Just copy the data part alone. The mctl part is
6461 		 * needed just for verifying policy and it is never
6462 		 * sent up.
6463 		 */
6464 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6465 		    ((mp1 = copymsg(mp)) == NULL))) {
6466 			/*
6467 			 * No more interested clients or memory
6468 			 * allocation failed
6469 			 */
6470 			connp = first_connp;
6471 			break;
6472 		}
6473 		if (connp->conn_zoneid != last_zoneid) {
6474 			/*
6475 			 * Update the zoneid so that the packet isn't sent to
6476 			 * any more conns in the same zone unless SO_REUSEADDR
6477 			 * is set.
6478 			 */
6479 			reuseaddr = connp->conn_reuseaddr;
6480 			last_zoneid = connp->conn_zoneid;
6481 		}
6482 		if (first_mp != NULL) {
6483 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6484 			    ipsec_info_type == IPSEC_IN);
6485 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6486 			if (first_mp1 == NULL) {
6487 				freemsg(mp1);
6488 				connp = first_connp;
6489 				break;
6490 			}
6491 		} else {
6492 			first_mp1 = NULL;
6493 		}
6494 		CONN_INC_REF(connp);
6495 		mutex_exit(&connfp->connf_lock);
6496 		/*
6497 		 * IPQoS notes: We don't send the packet for policy
6498 		 * processing here, will do it for the last one (below).
6499 		 * i.e. we do it per-packet now, but if we do policy
6500 		 * processing per-conn, then we would need to do it
6501 		 * here too.
6502 		 */
6503 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6504 		    ipha, flags, recv_ill, B_FALSE);
6505 		mutex_enter(&connfp->connf_lock);
6506 		/* Follow the next pointer before releasing the conn. */
6507 		next_connp = connp->conn_next;
6508 		IP_STAT(ip_udp_fanmb);
6509 		CONN_DEC_REF(connp);
6510 		connp = next_connp;
6511 	}
6512 
6513 	/* Last one.  Send it upstream. */
6514 	mutex_exit(&connfp->connf_lock);
6515 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6516 	    ip_policy);
6517 	IP_STAT(ip_udp_fanmb);
6518 	CONN_DEC_REF(connp);
6519 	return;
6520 
6521 notfound:
6522 
6523 	mutex_exit(&connfp->connf_lock);
6524 	IP_STAT(ip_udp_fanothers);
6525 	/*
6526 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6527 	 * have already been matched above, since they live in the IPv4
6528 	 * fanout tables. This implies we only need to
6529 	 * check for IPv6 in6addr_any endpoints here.
6530 	 * Thus we compare using ipv6_all_zeros instead of the destination
6531 	 * address, except for the multicast group membership lookup which
6532 	 * uses the IPv4 destination.
6533 	 */
6534 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6535 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6536 	mutex_enter(&connfp->connf_lock);
6537 	connp = connfp->connf_head;
6538 	if (!broadcast && !CLASSD(dst)) {
6539 		while (connp != NULL) {
6540 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6541 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6542 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6543 			    !connp->conn_ipv6_v6only)
6544 				break;
6545 			connp = connp->conn_next;
6546 		}
6547 
6548 		if (connp != NULL && is_system_labeled() &&
6549 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6550 		    connp))
6551 			connp = NULL;
6552 
6553 		if (connp == NULL || connp->conn_upq == NULL) {
6554 			/*
6555 			 * No one bound to this port.  Is
6556 			 * there a client that wants all
6557 			 * unclaimed datagrams?
6558 			 */
6559 			mutex_exit(&connfp->connf_lock);
6560 
6561 			if (mctl_present)
6562 				first_mp->b_cont = mp;
6563 			else
6564 				first_mp = mp;
6565 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6566 				ip_fanout_proto(q, first_mp, ill, ipha,
6567 				    flags | IP_FF_RAWIP, mctl_present,
6568 				    ip_policy, recv_ill, zoneid);
6569 			} else {
6570 				if (ip_fanout_send_icmp(q, first_mp, flags,
6571 				    ICMP_DEST_UNREACHABLE,
6572 				    ICMP_PORT_UNREACHABLE,
6573 				    mctl_present, zoneid)) {
6574 					BUMP_MIB(&ip_mib, udpNoPorts);
6575 				}
6576 			}
6577 			return;
6578 		}
6579 
6580 		CONN_INC_REF(connp);
6581 		mutex_exit(&connfp->connf_lock);
6582 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6583 		    recv_ill, ip_policy);
6584 		CONN_DEC_REF(connp);
6585 		return;
6586 	}
6587 	/*
6588 	 * IPv4 multicast packet being delivered to an AF_INET6
6589 	 * in6addr_any endpoint.
6590 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6591 	 * and not conn_wantpacket_v6() since any multicast membership is
6592 	 * for an IPv4-mapped multicast address.
6593 	 * The packet is sent to all clients in all zones that have joined the
6594 	 * group and match the port.
6595 	 */
6596 	while (connp != NULL) {
6597 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6598 		    srcport, v6src) &&
6599 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6600 		    (!is_system_labeled() ||
6601 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6602 		    connp)))
6603 			break;
6604 		connp = connp->conn_next;
6605 	}
6606 
6607 	if (connp == NULL || connp->conn_upq == NULL) {
6608 		/*
6609 		 * No one bound to this port.  Is
6610 		 * there a client that wants all
6611 		 * unclaimed datagrams?
6612 		 */
6613 		mutex_exit(&connfp->connf_lock);
6614 
6615 		if (mctl_present)
6616 			first_mp->b_cont = mp;
6617 		else
6618 			first_mp = mp;
6619 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6620 			ip_fanout_proto(q, first_mp, ill, ipha,
6621 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6622 			    recv_ill, zoneid);
6623 		} else {
6624 			/*
6625 			 * We used to attempt to send an icmp error here, but
6626 			 * since this is known to be a multicast packet
6627 			 * and we don't send icmp errors in response to
6628 			 * multicast, just drop the packet and give up sooner.
6629 			 */
6630 			BUMP_MIB(&ip_mib, udpNoPorts);
6631 			freemsg(first_mp);
6632 		}
6633 		return;
6634 	}
6635 
6636 	first_connp = connp;
6637 
6638 	CONN_INC_REF(connp);
6639 	connp = connp->conn_next;
6640 	for (;;) {
6641 		while (connp != NULL) {
6642 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6643 			    ipv6_all_zeros, srcport, v6src) &&
6644 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6645 			    (!is_system_labeled() ||
6646 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6647 			    shared_addr, connp)))
6648 				break;
6649 			connp = connp->conn_next;
6650 		}
6651 		/*
6652 		 * Just copy the data part alone. The mctl part is
6653 		 * needed just for verifying policy and it is never
6654 		 * sent up.
6655 		 */
6656 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6657 		    ((mp1 = copymsg(mp)) == NULL))) {
6658 			/*
6659 			 * No more intested clients or memory
6660 			 * allocation failed
6661 			 */
6662 			connp = first_connp;
6663 			break;
6664 		}
6665 		if (first_mp != NULL) {
6666 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6667 			    ipsec_info_type == IPSEC_IN);
6668 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6669 			if (first_mp1 == NULL) {
6670 				freemsg(mp1);
6671 				connp = first_connp;
6672 				break;
6673 			}
6674 		} else {
6675 			first_mp1 = NULL;
6676 		}
6677 		CONN_INC_REF(connp);
6678 		mutex_exit(&connfp->connf_lock);
6679 		/*
6680 		 * IPQoS notes: We don't send the packet for policy
6681 		 * processing here, will do it for the last one (below).
6682 		 * i.e. we do it per-packet now, but if we do policy
6683 		 * processing per-conn, then we would need to do it
6684 		 * here too.
6685 		 */
6686 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6687 		    ipha, flags, recv_ill, B_FALSE);
6688 		mutex_enter(&connfp->connf_lock);
6689 		/* Follow the next pointer before releasing the conn. */
6690 		next_connp = connp->conn_next;
6691 		CONN_DEC_REF(connp);
6692 		connp = next_connp;
6693 	}
6694 
6695 	/* Last one.  Send it upstream. */
6696 	mutex_exit(&connfp->connf_lock);
6697 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6698 	    ip_policy);
6699 	CONN_DEC_REF(connp);
6700 }
6701 
6702 /*
6703  * Complete the ip_wput header so that it
6704  * is possible to generate ICMP
6705  * errors.
6706  */
6707 int
6708 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6709 {
6710 	ire_t *ire;
6711 
6712 	if (ipha->ipha_src == INADDR_ANY) {
6713 		ire = ire_lookup_local(zoneid);
6714 		if (ire == NULL) {
6715 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6716 			return (1);
6717 		}
6718 		ipha->ipha_src = ire->ire_addr;
6719 		ire_refrele(ire);
6720 	}
6721 	ipha->ipha_ttl = ip_def_ttl;
6722 	ipha->ipha_hdr_checksum = 0;
6723 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6724 	return (0);
6725 }
6726 
6727 /*
6728  * Nobody should be sending
6729  * packets up this stream
6730  */
6731 static void
6732 ip_lrput(queue_t *q, mblk_t *mp)
6733 {
6734 	mblk_t *mp1;
6735 
6736 	switch (mp->b_datap->db_type) {
6737 	case M_FLUSH:
6738 		/* Turn around */
6739 		if (*mp->b_rptr & FLUSHW) {
6740 			*mp->b_rptr &= ~FLUSHR;
6741 			qreply(q, mp);
6742 			return;
6743 		}
6744 		break;
6745 	}
6746 	/* Could receive messages that passed through ar_rput */
6747 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6748 		mp1->b_prev = mp1->b_next = NULL;
6749 	freemsg(mp);
6750 }
6751 
6752 /* Nobody should be sending packets down this stream */
6753 /* ARGSUSED */
6754 void
6755 ip_lwput(queue_t *q, mblk_t *mp)
6756 {
6757 	freemsg(mp);
6758 }
6759 
6760 /*
6761  * Move the first hop in any source route to ipha_dst and remove that part of
6762  * the source route.  Called by other protocols.  Errors in option formatting
6763  * are ignored - will be handled by ip_wput_options Return the final
6764  * destination (either ipha_dst or the last entry in a source route.)
6765  */
6766 ipaddr_t
6767 ip_massage_options(ipha_t *ipha)
6768 {
6769 	ipoptp_t	opts;
6770 	uchar_t		*opt;
6771 	uint8_t		optval;
6772 	uint8_t		optlen;
6773 	ipaddr_t	dst;
6774 	int		i;
6775 	ire_t		*ire;
6776 
6777 	ip2dbg(("ip_massage_options\n"));
6778 	dst = ipha->ipha_dst;
6779 	for (optval = ipoptp_first(&opts, ipha);
6780 	    optval != IPOPT_EOL;
6781 	    optval = ipoptp_next(&opts)) {
6782 		opt = opts.ipoptp_cur;
6783 		switch (optval) {
6784 			uint8_t off;
6785 		case IPOPT_SSRR:
6786 		case IPOPT_LSRR:
6787 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6788 				ip1dbg(("ip_massage_options: bad src route\n"));
6789 				break;
6790 			}
6791 			optlen = opts.ipoptp_len;
6792 			off = opt[IPOPT_OFFSET];
6793 			off--;
6794 		redo_srr:
6795 			if (optlen < IP_ADDR_LEN ||
6796 			    off > optlen - IP_ADDR_LEN) {
6797 				/* End of source route */
6798 				ip1dbg(("ip_massage_options: end of SR\n"));
6799 				break;
6800 			}
6801 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6802 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6803 			    ntohl(dst)));
6804 			/*
6805 			 * Check if our address is present more than
6806 			 * once as consecutive hops in source route.
6807 			 * XXX verify per-interface ip_forwarding
6808 			 * for source route?
6809 			 */
6810 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6811 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
6812 			if (ire != NULL) {
6813 				ire_refrele(ire);
6814 				off += IP_ADDR_LEN;
6815 				goto redo_srr;
6816 			}
6817 			if (dst == htonl(INADDR_LOOPBACK)) {
6818 				ip1dbg(("ip_massage_options: loopback addr in "
6819 				    "source route!\n"));
6820 				break;
6821 			}
6822 			/*
6823 			 * Update ipha_dst to be the first hop and remove the
6824 			 * first hop from the source route (by overwriting
6825 			 * part of the option with NOP options).
6826 			 */
6827 			ipha->ipha_dst = dst;
6828 			/* Put the last entry in dst */
6829 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6830 			    3;
6831 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6832 
6833 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6834 			    ntohl(dst)));
6835 			/* Move down and overwrite */
6836 			opt[IP_ADDR_LEN] = opt[0];
6837 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6838 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6839 			for (i = 0; i < IP_ADDR_LEN; i++)
6840 				opt[i] = IPOPT_NOP;
6841 			break;
6842 		}
6843 	}
6844 	return (dst);
6845 }
6846 
6847 /*
6848  * This function's job is to forward data to the reverse tunnel (FA->HA)
6849  * after doing a few checks. It is assumed that the incoming interface
6850  * of the packet is always different than the outgoing interface and the
6851  * ire_type of the found ire has to be a non-resolver type.
6852  *
6853  * IPQoS notes
6854  * IP policy is invoked twice for a forwarded packet, once on the read side
6855  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6856  * enabled.
6857  */
6858 static void
6859 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6860 {
6861 	ipha_t		*ipha;
6862 	queue_t		*q;
6863 	uint32_t 	pkt_len;
6864 #define	rptr    ((uchar_t *)ipha)
6865 	uint32_t 	sum;
6866 	uint32_t 	max_frag;
6867 	mblk_t		*first_mp;
6868 	uint32_t	ill_index;
6869 	ipxmit_state_t	pktxmit_state;
6870 
6871 	ASSERT(ire != NULL);
6872 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6873 	ASSERT(ire->ire_stq != NULL);
6874 
6875 	/* Initiate read side IPPF processing */
6876 	if (IPP_ENABLED(IPP_FWD_IN)) {
6877 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6878 		ip_process(IPP_FWD_IN, &mp, ill_index);
6879 		if (mp == NULL) {
6880 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6881 			    "dropped during IPPF processing\n"));
6882 			return;
6883 		}
6884 	}
6885 
6886 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6887 		ILLF_ROUTER) == 0) ||
6888 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6889 		BUMP_MIB(&ip_mib, ipForwProhibits);
6890 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6891 		    "forwarding is not turned on\n"));
6892 		goto drop_pkt;
6893 	}
6894 
6895 	/*
6896 	 * Don't forward if the interface is down
6897 	 */
6898 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6899 		BUMP_MIB(&ip_mib, ipInDiscards);
6900 		goto drop_pkt;
6901 	}
6902 
6903 	ipha = (ipha_t *)mp->b_rptr;
6904 	pkt_len = ntohs(ipha->ipha_length);
6905 	/* Adjust the checksum to reflect the ttl decrement. */
6906 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6907 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6908 	if (ipha->ipha_ttl-- <= 1) {
6909 		if (ip_csum_hdr(ipha)) {
6910 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6911 			goto drop_pkt;
6912 		}
6913 		q = ire->ire_stq;
6914 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6915 		    BPRI_HI)) == NULL) {
6916 			goto drop_pkt;
6917 		}
6918 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6919 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6920 
6921 		return;
6922 	}
6923 
6924 	/* Get the ill_index of the ILL */
6925 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6926 
6927 	/*
6928 	 * ip_mrtun_forward is only used by foreign agent to reverse
6929 	 * tunnel the incoming packet. So it does not do any option
6930 	 * processing for source routing.
6931 	 */
6932 	max_frag = ire->ire_max_frag;
6933 	if (pkt_len > max_frag) {
6934 		/*
6935 		 * It needs fragging on its way out.  We haven't
6936 		 * verified the header checksum yet.  Since we
6937 		 * are going to put a surely good checksum in the
6938 		 * outgoing header, we have to make sure that it
6939 		 * was good coming in.
6940 		 */
6941 		if (ip_csum_hdr(ipha)) {
6942 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6943 			goto drop_pkt;
6944 		}
6945 
6946 		/* Initiate write side IPPF processing */
6947 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6948 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6949 			if (mp == NULL) {
6950 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6951 				    "dropped/deferred during ip policy "\
6952 				    "processing\n"));
6953 				return;
6954 			}
6955 		}
6956 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6957 		    BPRI_HI)) == NULL) {
6958 			goto drop_pkt;
6959 		}
6960 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6961 		mp = first_mp;
6962 
6963 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6964 		return;
6965 	}
6966 
6967 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6968 
6969 	ASSERT(ire->ire_ipif != NULL);
6970 
6971 	/* Now send the packet to the tunnel interface */
6972 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
6973 	q = ire->ire_stq;
6974 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
6975 	if ((pktxmit_state == SEND_FAILED) ||
6976 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
6977 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
6978 		    q->q_ptr));
6979 	}
6980 
6981 	return;
6982 
6983 drop_pkt:;
6984 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6985 	freemsg(mp);
6986 #undef	rptr
6987 }
6988 
6989 /*
6990  * Fills the ipsec_out_t data structure with appropriate fields and
6991  * prepends it to mp which contains the IP hdr + data that was meant
6992  * to be forwarded. Please note that ipsec_out_info data structure
6993  * is used here to communicate the outgoing ill path at ip_wput()
6994  * for the ICMP error packet. This has nothing to do with ipsec IP
6995  * security. ipsec_out_t is really used to pass the info to the module
6996  * IP where this information cannot be extracted from conn.
6997  * This functions is called by ip_mrtun_forward().
6998  */
6999 void
7000 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7001 {
7002 	ipsec_out_t	*io;
7003 
7004 	ASSERT(xmit_ill != NULL);
7005 	first_mp->b_datap->db_type = M_CTL;
7006 	first_mp->b_wptr += sizeof (ipsec_info_t);
7007 	/*
7008 	 * This is to pass info to ip_wput in absence of conn.
7009 	 * ipsec_out_secure will be B_FALSE because of this.
7010 	 * Thus ipsec_out_secure being B_FALSE indicates that
7011 	 * this is not IPSEC security related information.
7012 	 */
7013 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7014 	io = (ipsec_out_t *)first_mp->b_rptr;
7015 	io->ipsec_out_type = IPSEC_OUT;
7016 	io->ipsec_out_len = sizeof (ipsec_out_t);
7017 	first_mp->b_cont = mp;
7018 	io->ipsec_out_ill_index =
7019 	    xmit_ill->ill_phyint->phyint_ifindex;
7020 	io->ipsec_out_xmit_if = B_TRUE;
7021 }
7022 
7023 /*
7024  * Return the network mask
7025  * associated with the specified address.
7026  */
7027 ipaddr_t
7028 ip_net_mask(ipaddr_t addr)
7029 {
7030 	uchar_t	*up = (uchar_t *)&addr;
7031 	ipaddr_t mask = 0;
7032 	uchar_t	*maskp = (uchar_t *)&mask;
7033 
7034 #if defined(__i386) || defined(__amd64)
7035 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7036 #endif
7037 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7038 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7039 #endif
7040 	if (CLASSD(addr)) {
7041 		maskp[0] = 0xF0;
7042 		return (mask);
7043 	}
7044 	if (addr == 0)
7045 		return (0);
7046 	maskp[0] = 0xFF;
7047 	if ((up[0] & 0x80) == 0)
7048 		return (mask);
7049 
7050 	maskp[1] = 0xFF;
7051 	if ((up[0] & 0xC0) == 0x80)
7052 		return (mask);
7053 
7054 	maskp[2] = 0xFF;
7055 	if ((up[0] & 0xE0) == 0xC0)
7056 		return (mask);
7057 
7058 	/* Must be experimental or multicast, indicate as much */
7059 	return ((ipaddr_t)0);
7060 }
7061 
7062 /*
7063  * Select an ill for the packet by considering load spreading across
7064  * a different ill in the group if dst_ill is part of some group.
7065  */
7066 ill_t *
7067 ip_newroute_get_dst_ill(ill_t *dst_ill)
7068 {
7069 	ill_t *ill;
7070 
7071 	/*
7072 	 * We schedule irrespective of whether the source address is
7073 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7074 	 */
7075 	ill = illgrp_scheduler(dst_ill);
7076 	if (ill == NULL)
7077 		return (NULL);
7078 
7079 	/*
7080 	 * For groups with names ip_sioctl_groupname ensures that all
7081 	 * ills are of same type. For groups without names, ifgrp_insert
7082 	 * ensures this.
7083 	 */
7084 	ASSERT(dst_ill->ill_type == ill->ill_type);
7085 
7086 	return (ill);
7087 }
7088 
7089 /*
7090  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7091  */
7092 ill_t *
7093 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7094 {
7095 	ill_t *ret_ill;
7096 
7097 	ASSERT(ifindex != 0);
7098 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7099 	if (ret_ill == NULL ||
7100 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7101 		if (isv6) {
7102 			if (ill != NULL) {
7103 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7104 			} else {
7105 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7106 			}
7107 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7108 			    "bad ifindex %d.\n", ifindex));
7109 		} else {
7110 			BUMP_MIB(&ip_mib, ipOutDiscards);
7111 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7112 			    "bad ifindex %d.\n", ifindex));
7113 		}
7114 		if (ret_ill != NULL)
7115 			ill_refrele(ret_ill);
7116 		freemsg(first_mp);
7117 		return (NULL);
7118 	}
7119 
7120 	return (ret_ill);
7121 }
7122 
7123 /*
7124  * IPv4 -
7125  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7126  * out a packet to a destination address for which we do not have specific
7127  * (or sufficient) routing information.
7128  *
7129  * NOTE : These are the scopes of some of the variables that point at IRE,
7130  *	  which needs to be followed while making any future modifications
7131  *	  to avoid memory leaks.
7132  *
7133  *	- ire and sire are the entries looked up initially by
7134  *	  ire_ftable_lookup.
7135  *	- ipif_ire is used to hold the interface ire associated with
7136  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7137  *	  it before branching out to error paths.
7138  *	- save_ire is initialized before ire_create, so that ire returned
7139  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7140  *	  before breaking out of the switch.
7141  *
7142  *	Thus on failures, we have to REFRELE only ire and sire, if they
7143  *	are not NULL.
7144  */
7145 void
7146 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
7147 {
7148 	areq_t	*areq;
7149 	ipaddr_t gw = 0;
7150 	ire_t	*ire = NULL;
7151 	mblk_t	*res_mp;
7152 	ipaddr_t *addrp;
7153 	ipaddr_t nexthop_addr;
7154 	ipif_t  *src_ipif = NULL;
7155 	ill_t	*dst_ill = NULL;
7156 	ipha_t  *ipha;
7157 	ire_t	*sire = NULL;
7158 	mblk_t	*first_mp;
7159 	ire_t	*save_ire;
7160 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7161 	ushort_t ire_marks = 0;
7162 	boolean_t mctl_present;
7163 	ipsec_out_t *io;
7164 	mblk_t	*saved_mp;
7165 	ire_t	*first_sire = NULL;
7166 	mblk_t	*copy_mp = NULL;
7167 	mblk_t	*xmit_mp = NULL;
7168 	ipaddr_t save_dst;
7169 	uint32_t multirt_flags =
7170 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7171 	boolean_t multirt_is_resolvable;
7172 	boolean_t multirt_resolve_next;
7173 	boolean_t do_attach_ill = B_FALSE;
7174 	boolean_t ip_nexthop = B_FALSE;
7175 	zoneid_t zoneid;
7176 	tsol_ire_gw_secattr_t *attrp = NULL;
7177 	tsol_gcgrp_t *gcgrp = NULL;
7178 	tsol_gcgrp_addr_t ga;
7179 
7180 	if (ip_debug > 2) {
7181 		/* ip1dbg */
7182 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7183 	}
7184 
7185 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7186 	if (mctl_present) {
7187 		io = (ipsec_out_t *)first_mp->b_rptr;
7188 		zoneid = io->ipsec_out_zoneid;
7189 		ASSERT(zoneid != ALL_ZONES);
7190 	} else if (connp != NULL) {
7191 		zoneid = connp->conn_zoneid;
7192 	} else {
7193 		zoneid = GLOBAL_ZONEID;
7194 	}
7195 
7196 	ipha = (ipha_t *)mp->b_rptr;
7197 
7198 	/* All multicast lookups come through ip_newroute_ipif() */
7199 	if (CLASSD(dst)) {
7200 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7201 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7202 		freemsg(first_mp);
7203 		return;
7204 	}
7205 
7206 	if (mctl_present && io->ipsec_out_attach_if) {
7207 		/* ip_grab_attach_ill returns a held ill */
7208 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7209 		    io->ipsec_out_ill_index, B_FALSE);
7210 
7211 		/* Failure case frees things for us. */
7212 		if (attach_ill == NULL)
7213 			return;
7214 
7215 		/*
7216 		 * Check if we need an ire that will not be
7217 		 * looked up by anybody else i.e. HIDDEN.
7218 		 */
7219 		if (ill_is_probeonly(attach_ill))
7220 			ire_marks = IRE_MARK_HIDDEN;
7221 	}
7222 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7223 		ip_nexthop = B_TRUE;
7224 		nexthop_addr = io->ipsec_out_nexthop_addr;
7225 	}
7226 	/*
7227 	 * If this IRE is created for forwarding or it is not for
7228 	 * traffic for congestion controlled protocols, mark it as temporary.
7229 	 */
7230 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7231 		ire_marks |= IRE_MARK_TEMPORARY;
7232 
7233 	/*
7234 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7235 	 * chain until it gets the most specific information available.
7236 	 * For example, we know that there is no IRE_CACHE for this dest,
7237 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7238 	 * ire_ftable_lookup will look up the gateway, etc.
7239 	 * Check if in_ill != NULL. If it is true, the packet must be
7240 	 * from an incoming interface where RTA_SRCIFP is set.
7241 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7242 	 * to the destination, of equal netmask length in the forward table,
7243 	 * will be recursively explored. If no information is available
7244 	 * for the final gateway of that route, we force the returned ire
7245 	 * to be equal to sire using MATCH_IRE_PARENT.
7246 	 * At least, in this case we have a starting point (in the buckets)
7247 	 * to look for other routes to the destination in the forward table.
7248 	 * This is actually used only for multirouting, where a list
7249 	 * of routes has to be processed in sequence.
7250 	 *
7251 	 * In the process of coming up with the most specific information,
7252 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7253 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7254 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7255 	 * Two caveats when handling incomplete ire's in ip_newroute:
7256 	 * - we should be careful when accessing its ire_nce (specifically
7257 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7258 	 * - not all legacy code path callers are prepared to handle
7259 	 *   incomplete ire's, so we should not create/add incomplete
7260 	 *   ire_cache entries here. (See discussion about temporary solution
7261 	 *   further below).
7262 	 *
7263 	 * In order to minimize packet dropping, and to preserve existing
7264 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7265 	 * gateway, and instead use the IF_RESOLVER ire to send out
7266 	 * another request to ARP (this is achieved by passing the
7267 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7268 	 * arp response comes back in ip_wput_nondata, we will create
7269 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7270 	 *
7271 	 * Note that this is a temporary solution; the correct solution is
7272 	 * to create an incomplete  per-dst ire_cache entry, and send the
7273 	 * packet out when the gw's nce is resolved. In order to achieve this,
7274 	 * all packet processing must have been completed prior to calling
7275 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7276 	 * to be modified to accomodate this solution.
7277 	 */
7278 	if (in_ill != NULL) {
7279 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7280 		    in_ill, MATCH_IRE_TYPE);
7281 	} else if (ip_nexthop) {
7282 		/*
7283 		 * The first time we come here, we look for an IRE_INTERFACE
7284 		 * entry for the specified nexthop, set the dst to be the
7285 		 * nexthop address and create an IRE_CACHE entry for the
7286 		 * nexthop. The next time around, we are able to find an
7287 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7288 		 * nexthop address and create an IRE_CACHE entry for the
7289 		 * destination address via the specified nexthop.
7290 		 */
7291 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7292 		    MBLK_GETLABEL(mp));
7293 		if (ire != NULL) {
7294 			gw = nexthop_addr;
7295 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7296 		} else {
7297 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7298 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7299 			    MBLK_GETLABEL(mp),
7300 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7301 			if (ire != NULL) {
7302 				dst = nexthop_addr;
7303 			}
7304 		}
7305 	} else if (attach_ill == NULL) {
7306 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7307 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7308 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7309 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7310 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7311 	} else {
7312 		/*
7313 		 * attach_ill is set only for communicating with
7314 		 * on-link hosts. So, don't look for DEFAULT.
7315 		 */
7316 		ipif_t	*attach_ipif;
7317 
7318 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7319 		if (attach_ipif == NULL) {
7320 			ill_refrele(attach_ill);
7321 			goto icmp_err_ret;
7322 		}
7323 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7324 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7325 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7326 		    MATCH_IRE_SECATTR);
7327 		ipif_refrele(attach_ipif);
7328 	}
7329 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7330 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7331 
7332 	/*
7333 	 * This loop is run only once in most cases.
7334 	 * We loop to resolve further routes only when the destination
7335 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7336 	 */
7337 	do {
7338 		/* Clear the previous iteration's values */
7339 		if (src_ipif != NULL) {
7340 			ipif_refrele(src_ipif);
7341 			src_ipif = NULL;
7342 		}
7343 		if (dst_ill != NULL) {
7344 			ill_refrele(dst_ill);
7345 			dst_ill = NULL;
7346 		}
7347 
7348 		multirt_resolve_next = B_FALSE;
7349 		/*
7350 		 * We check if packets have to be multirouted.
7351 		 * In this case, given the current <ire, sire> couple,
7352 		 * we look for the next suitable <ire, sire>.
7353 		 * This check is done in ire_multirt_lookup(),
7354 		 * which applies various criteria to find the next route
7355 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7356 		 * unchanged if it detects it has not been tried yet.
7357 		 */
7358 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7359 			ip3dbg(("ip_newroute: starting next_resolution "
7360 			    "with first_mp %p, tag %d\n",
7361 			    (void *)first_mp,
7362 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7363 
7364 			ASSERT(sire != NULL);
7365 			multirt_is_resolvable =
7366 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7367 				MBLK_GETLABEL(mp));
7368 
7369 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7370 			    "ire %p, sire %p\n",
7371 			    multirt_is_resolvable,
7372 			    (void *)ire, (void *)sire));
7373 
7374 			if (!multirt_is_resolvable) {
7375 				/*
7376 				 * No more multirt route to resolve; give up
7377 				 * (all routes resolved or no more
7378 				 * resolvable routes).
7379 				 */
7380 				if (ire != NULL) {
7381 					ire_refrele(ire);
7382 					ire = NULL;
7383 				}
7384 			} else {
7385 				ASSERT(sire != NULL);
7386 				ASSERT(ire != NULL);
7387 				/*
7388 				 * We simply use first_sire as a flag that
7389 				 * indicates if a resolvable multirt route
7390 				 * has already been found.
7391 				 * If it is not the case, we may have to send
7392 				 * an ICMP error to report that the
7393 				 * destination is unreachable.
7394 				 * We do not IRE_REFHOLD first_sire.
7395 				 */
7396 				if (first_sire == NULL) {
7397 					first_sire = sire;
7398 				}
7399 			}
7400 		}
7401 		if (ire == NULL) {
7402 			if (ip_debug > 3) {
7403 				/* ip2dbg */
7404 				pr_addr_dbg("ip_newroute: "
7405 				    "can't resolve %s\n", AF_INET, &dst);
7406 			}
7407 			ip3dbg(("ip_newroute: "
7408 			    "ire %p, sire %p, first_sire %p\n",
7409 			    (void *)ire, (void *)sire, (void *)first_sire));
7410 
7411 			if (sire != NULL) {
7412 				ire_refrele(sire);
7413 				sire = NULL;
7414 			}
7415 
7416 			if (first_sire != NULL) {
7417 				/*
7418 				 * At least one multirt route has been found
7419 				 * in the same call to ip_newroute();
7420 				 * there is no need to report an ICMP error.
7421 				 * first_sire was not IRE_REFHOLDed.
7422 				 */
7423 				MULTIRT_DEBUG_UNTAG(first_mp);
7424 				freemsg(first_mp);
7425 				return;
7426 			}
7427 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7428 			    RTA_DST);
7429 			if (attach_ill != NULL)
7430 				ill_refrele(attach_ill);
7431 			goto icmp_err_ret;
7432 		}
7433 
7434 		/*
7435 		 * When RTA_SRCIFP is used to add a route, then an interface
7436 		 * route is added in the source interface's routing table.
7437 		 * If the outgoing interface of this route is of type
7438 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7439 		 * ire_nce->nce_res_mp is set to NULL.
7440 		 * Later, when this route is first used for forwarding
7441 		 * a packet, ip_newroute() is called
7442 		 * to resolve the hardware address of the outgoing ipif.
7443 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7444 		 * source interface based table. We only come here if the
7445 		 * outgoing interface is a resolver interface and we don't
7446 		 * have the ire_nce->nce_res_mp information yet.
7447 		 * If in_ill is not null that means it is called from
7448 		 * ip_rput.
7449 		 */
7450 
7451 		ASSERT(ire->ire_in_ill == NULL ||
7452 		    (ire->ire_type == IRE_IF_RESOLVER &&
7453 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7454 
7455 		/*
7456 		 * Verify that the returned IRE does not have either
7457 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7458 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7459 		 */
7460 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7461 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7462 			if (attach_ill != NULL)
7463 				ill_refrele(attach_ill);
7464 			goto icmp_err_ret;
7465 		}
7466 		/*
7467 		 * Increment the ire_ob_pkt_count field for ire if it is an
7468 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7469 		 * increment the same for the parent IRE, sire, if it is some
7470 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7471 		 * and HOST_REDIRECT).
7472 		 */
7473 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7474 			UPDATE_OB_PKT_COUNT(ire);
7475 			ire->ire_last_used_time = lbolt;
7476 		}
7477 
7478 		if (sire != NULL) {
7479 			gw = sire->ire_gateway_addr;
7480 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7481 			    IRE_INTERFACE)) == 0);
7482 			UPDATE_OB_PKT_COUNT(sire);
7483 			sire->ire_last_used_time = lbolt;
7484 		}
7485 		/*
7486 		 * We have a route to reach the destination.
7487 		 *
7488 		 * 1) If the interface is part of ill group, try to get a new
7489 		 *    ill taking load spreading into account.
7490 		 *
7491 		 * 2) After selecting the ill, get a source address that
7492 		 *    might create good inbound load spreading.
7493 		 *    ipif_select_source does this for us.
7494 		 *
7495 		 * If the application specified the ill (ifindex), we still
7496 		 * load spread. Only if the packets needs to go out
7497 		 * specifically on a given ill e.g. binding to
7498 		 * IPIF_NOFAILOVER address, then we don't try to use a
7499 		 * different ill for load spreading.
7500 		 */
7501 		if (attach_ill == NULL) {
7502 			/*
7503 			 * Don't perform outbound load spreading in the
7504 			 * case of an RTF_MULTIRT route, as we actually
7505 			 * typically want to replicate outgoing packets
7506 			 * through particular interfaces.
7507 			 */
7508 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7509 				dst_ill = ire->ire_ipif->ipif_ill;
7510 				/* for uniformity */
7511 				ill_refhold(dst_ill);
7512 			} else {
7513 				/*
7514 				 * If we are here trying to create an IRE_CACHE
7515 				 * for an offlink destination and have the
7516 				 * IRE_CACHE for the next hop and the latter is
7517 				 * using virtual IP source address selection i.e
7518 				 * it's ire->ire_ipif is pointing to a virtual
7519 				 * network interface (vni) then
7520 				 * ip_newroute_get_dst_ll() will return the vni
7521 				 * interface as the dst_ill. Since the vni is
7522 				 * virtual i.e not associated with any physical
7523 				 * interface, it cannot be the dst_ill, hence
7524 				 * in such a case call ip_newroute_get_dst_ll()
7525 				 * with the stq_ill instead of the ire_ipif ILL.
7526 				 * The function returns a refheld ill.
7527 				 */
7528 				if ((ire->ire_type == IRE_CACHE) &&
7529 				    IS_VNI(ire->ire_ipif->ipif_ill))
7530 					dst_ill = ip_newroute_get_dst_ill(
7531 						ire->ire_stq->q_ptr);
7532 				else
7533 					dst_ill = ip_newroute_get_dst_ill(
7534 						ire->ire_ipif->ipif_ill);
7535 			}
7536 			if (dst_ill == NULL) {
7537 				if (ip_debug > 2) {
7538 					pr_addr_dbg("ip_newroute: "
7539 					    "no dst ill for dst"
7540 					    " %s\n", AF_INET, &dst);
7541 				}
7542 				goto icmp_err_ret;
7543 			}
7544 		} else {
7545 			dst_ill = ire->ire_ipif->ipif_ill;
7546 			/* for uniformity */
7547 			ill_refhold(dst_ill);
7548 			/*
7549 			 * We should have found a route matching ill as we
7550 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7551 			 * Rather than asserting, when there is a mismatch,
7552 			 * we just drop the packet.
7553 			 */
7554 			if (dst_ill != attach_ill) {
7555 				ip0dbg(("ip_newroute: Packet dropped as "
7556 				    "IPIF_NOFAILOVER ill is %s, "
7557 				    "ire->ire_ipif->ipif_ill is %s\n",
7558 				    attach_ill->ill_name,
7559 				    dst_ill->ill_name));
7560 				ill_refrele(attach_ill);
7561 				goto icmp_err_ret;
7562 			}
7563 		}
7564 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7565 		if (attach_ill != NULL) {
7566 			ill_refrele(attach_ill);
7567 			attach_ill = NULL;
7568 			do_attach_ill = B_TRUE;
7569 		}
7570 		ASSERT(dst_ill != NULL);
7571 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7572 
7573 		/*
7574 		 * Pick the best source address from dst_ill.
7575 		 *
7576 		 * 1) If it is part of a multipathing group, we would
7577 		 *    like to spread the inbound packets across different
7578 		 *    interfaces. ipif_select_source picks a random source
7579 		 *    across the different ills in the group.
7580 		 *
7581 		 * 2) If it is not part of a multipathing group, we try
7582 		 *    to pick the source address from the destination
7583 		 *    route. Clustering assumes that when we have multiple
7584 		 *    prefixes hosted on an interface, the prefix of the
7585 		 *    source address matches the prefix of the destination
7586 		 *    route. We do this only if the address is not
7587 		 *    DEPRECATED.
7588 		 *
7589 		 * 3) If the conn is in a different zone than the ire, we
7590 		 *    need to pick a source address from the right zone.
7591 		 *
7592 		 * NOTE : If we hit case (1) above, the prefix of the source
7593 		 *	  address picked may not match the prefix of the
7594 		 *	  destination routes prefix as ipif_select_source
7595 		 *	  does not look at "dst" while picking a source
7596 		 *	  address.
7597 		 *	  If we want the same behavior as (2), we will need
7598 		 *	  to change the behavior of ipif_select_source.
7599 		 */
7600 		ASSERT(src_ipif == NULL);
7601 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7602 			/*
7603 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7604 			 * Check that the ipif matching the requested source
7605 			 * address still exists.
7606 			 */
7607 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7608 			    zoneid, NULL, NULL, NULL, NULL);
7609 		}
7610 		if (src_ipif == NULL) {
7611 			ire_marks |= IRE_MARK_USESRC_CHECK;
7612 			if ((dst_ill->ill_group != NULL) ||
7613 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7614 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7615 			    ire->ire_zoneid != ALL_ZONES) ||
7616 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7617 				/*
7618 				 * If the destination is reachable via a
7619 				 * given gateway, the selected source address
7620 				 * should be in the same subnet as the gateway.
7621 				 * Otherwise, the destination is not reachable.
7622 				 *
7623 				 * If there are no interfaces on the same subnet
7624 				 * as the destination, ipif_select_source gives
7625 				 * first non-deprecated interface which might be
7626 				 * on a different subnet than the gateway.
7627 				 * This is not desirable. Hence pass the dst_ire
7628 				 * source address to ipif_select_source.
7629 				 * It is sure that the destination is reachable
7630 				 * with the dst_ire source address subnet.
7631 				 * So passing dst_ire source address to
7632 				 * ipif_select_source will make sure that the
7633 				 * selected source will be on the same subnet
7634 				 * as dst_ire source address.
7635 				 */
7636 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7637 				src_ipif = ipif_select_source(dst_ill, saddr,
7638 				    zoneid);
7639 				if (src_ipif == NULL) {
7640 					if (ip_debug > 2) {
7641 						pr_addr_dbg("ip_newroute: "
7642 						    "no src for dst %s ",
7643 						    AF_INET, &dst);
7644 						printf("through interface %s\n",
7645 						    dst_ill->ill_name);
7646 					}
7647 					goto icmp_err_ret;
7648 				}
7649 			} else {
7650 				src_ipif = ire->ire_ipif;
7651 				ASSERT(src_ipif != NULL);
7652 				/* hold src_ipif for uniformity */
7653 				ipif_refhold(src_ipif);
7654 			}
7655 		}
7656 
7657 		/*
7658 		 * Assign a source address while we have the conn.
7659 		 * We can't have ip_wput_ire pick a source address when the
7660 		 * packet returns from arp since we need to look at
7661 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7662 		 * going through arp.
7663 		 *
7664 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7665 		 *	  it uses ip6i to store this information.
7666 		 */
7667 		if (ipha->ipha_src == INADDR_ANY &&
7668 		    (connp == NULL || !connp->conn_unspec_src)) {
7669 			ipha->ipha_src = src_ipif->ipif_src_addr;
7670 		}
7671 		if (ip_debug > 3) {
7672 			/* ip2dbg */
7673 			pr_addr_dbg("ip_newroute: first hop %s\n",
7674 			    AF_INET, &gw);
7675 		}
7676 		ip2dbg(("\tire type %s (%d)\n",
7677 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7678 
7679 		/*
7680 		 * The TTL of multirouted packets is bounded by the
7681 		 * ip_multirt_ttl ndd variable.
7682 		 */
7683 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7684 			/* Force TTL of multirouted packets */
7685 			if ((ip_multirt_ttl > 0) &&
7686 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7687 				ip2dbg(("ip_newroute: forcing multirt TTL "
7688 				    "to %d (was %d), dst 0x%08x\n",
7689 				    ip_multirt_ttl, ipha->ipha_ttl,
7690 				    ntohl(sire->ire_addr)));
7691 				ipha->ipha_ttl = ip_multirt_ttl;
7692 			}
7693 		}
7694 		/*
7695 		 * At this point in ip_newroute(), ire is either the
7696 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7697 		 * destination or an IRE_INTERFACE type that should be used
7698 		 * to resolve an on-subnet destination or an on-subnet
7699 		 * next-hop gateway.
7700 		 *
7701 		 * In the IRE_CACHE case, we have the following :
7702 		 *
7703 		 * 1) src_ipif - used for getting a source address.
7704 		 *
7705 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7706 		 *    means packets using this IRE_CACHE will go out on
7707 		 *    dst_ill.
7708 		 *
7709 		 * 3) The IRE sire will point to the prefix that is the
7710 		 *    longest  matching route for the destination. These
7711 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7712 		 *    and IRE_HOST_REDIRECT.
7713 		 *
7714 		 *    The newly created IRE_CACHE entry for the off-subnet
7715 		 *    destination is tied to both the prefix route and the
7716 		 *    interface route used to resolve the next-hop gateway
7717 		 *    via the ire_phandle and ire_ihandle fields,
7718 		 *    respectively.
7719 		 *
7720 		 * In the IRE_INTERFACE case, we have the following :
7721 		 *
7722 		 * 1) src_ipif - used for getting a source address.
7723 		 *
7724 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7725 		 *    means packets using the IRE_CACHE that we will build
7726 		 *    here will go out on dst_ill.
7727 		 *
7728 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7729 		 *    to be created will only be tied to the IRE_INTERFACE
7730 		 *    that was derived from the ire_ihandle field.
7731 		 *
7732 		 *    If sire is non-NULL, it means the destination is
7733 		 *    off-link and we will first create the IRE_CACHE for the
7734 		 *    gateway. Next time through ip_newroute, we will create
7735 		 *    the IRE_CACHE for the final destination as described
7736 		 *    above.
7737 		 *
7738 		 * In both cases, after the current resolution has been
7739 		 * completed (or possibly initialised, in the IRE_INTERFACE
7740 		 * case), the loop may be re-entered to attempt the resolution
7741 		 * of another RTF_MULTIRT route.
7742 		 *
7743 		 * When an IRE_CACHE entry for the off-subnet destination is
7744 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7745 		 * for further processing in emission loops.
7746 		 */
7747 		save_ire = ire;
7748 		switch (ire->ire_type) {
7749 		case IRE_CACHE: {
7750 			ire_t	*ipif_ire;
7751 			mblk_t	*ire_fp_mp;
7752 
7753 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
7754 			if (gw == 0)
7755 				gw = ire->ire_gateway_addr;
7756 			/*
7757 			 * We need 3 ire's to create a new cache ire for an
7758 			 * off-link destination from the cache ire of the
7759 			 * gateway.
7760 			 *
7761 			 *	1. The prefix ire 'sire' (Note that this does
7762 			 *	   not apply to the conn_nexthop_set case)
7763 			 *	2. The cache ire of the gateway 'ire'
7764 			 *	3. The interface ire 'ipif_ire'
7765 			 *
7766 			 * We have (1) and (2). We lookup (3) below.
7767 			 *
7768 			 * If there is no interface route to the gateway,
7769 			 * it is a race condition, where we found the cache
7770 			 * but the interface route has been deleted.
7771 			 */
7772 			if (ip_nexthop) {
7773 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7774 			} else {
7775 				ipif_ire =
7776 				    ire_ihandle_lookup_offlink(ire, sire);
7777 			}
7778 			if (ipif_ire == NULL) {
7779 				ip1dbg(("ip_newroute: "
7780 				    "ire_ihandle_lookup_offlink failed\n"));
7781 				goto icmp_err_ret;
7782 			}
7783 			/*
7784 			 * XXX We are using the same res_mp
7785 			 * (DL_UNITDATA_REQ) though the save_ire is not
7786 			 * pointing at the same ill.
7787 			 * This is incorrect. We need to send it up to the
7788 			 * resolver to get the right res_mp. For ethernets
7789 			 * this may be okay (ill_type == DL_ETHER).
7790 			 */
7791 			res_mp = save_ire->ire_nce->nce_res_mp;
7792 			ire_fp_mp = NULL;
7793 			/*
7794 			 * save_ire's nce_fp_mp can't change since it is
7795 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7796 			 * LOCK_IRE_FP_MP does not do any useful work in
7797 			 * the case of IRE_CACHE. So we don't use it below.
7798 			 */
7799 			if (save_ire->ire_stq == dst_ill->ill_wq)
7800 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
7801 
7802 			/*
7803 			 * Check cached gateway IRE for any security
7804 			 * attributes; if found, associate the gateway
7805 			 * credentials group to the destination IRE.
7806 			 */
7807 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
7808 				mutex_enter(&attrp->igsa_lock);
7809 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
7810 					GCGRP_REFHOLD(gcgrp);
7811 				mutex_exit(&attrp->igsa_lock);
7812 			}
7813 
7814 			ire = ire_create(
7815 			    (uchar_t *)&dst,		/* dest address */
7816 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7817 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7818 			    (uchar_t *)&gw,		/* gateway address */
7819 			    NULL,
7820 			    &save_ire->ire_max_frag,
7821 			    ire_fp_mp,			/* Fast Path header */
7822 			    dst_ill->ill_rq,		/* recv-from queue */
7823 			    dst_ill->ill_wq,		/* send-to queue */
7824 			    IRE_CACHE,			/* IRE type */
7825 			    res_mp,
7826 			    src_ipif,
7827 			    in_ill,			/* incoming ill */
7828 			    (sire != NULL) ?
7829 				sire->ire_mask : 0, 	/* Parent mask */
7830 			    (sire != NULL) ?
7831 				sire->ire_phandle : 0,  /* Parent handle */
7832 			    ipif_ire->ire_ihandle,	/* Interface handle */
7833 			    (sire != NULL) ? (sire->ire_flags &
7834 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7835 			    (sire != NULL) ?
7836 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
7837 			    NULL,
7838 			    gcgrp);
7839 
7840 			if (ire == NULL) {
7841 				if (gcgrp != NULL) {
7842 					GCGRP_REFRELE(gcgrp);
7843 					gcgrp = NULL;
7844 				}
7845 				ire_refrele(ipif_ire);
7846 				ire_refrele(save_ire);
7847 				break;
7848 			}
7849 
7850 			/* reference now held by IRE */
7851 			gcgrp = NULL;
7852 
7853 			ire->ire_marks |= ire_marks;
7854 
7855 			/*
7856 			 * Prevent sire and ipif_ire from getting deleted.
7857 			 * The newly created ire is tied to both of them via
7858 			 * the phandle and ihandle respectively.
7859 			 */
7860 			if (sire != NULL) {
7861 				IRB_REFHOLD(sire->ire_bucket);
7862 				/* Has it been removed already ? */
7863 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7864 					IRB_REFRELE(sire->ire_bucket);
7865 					ire_refrele(ipif_ire);
7866 					ire_refrele(save_ire);
7867 					break;
7868 				}
7869 			}
7870 
7871 			IRB_REFHOLD(ipif_ire->ire_bucket);
7872 			/* Has it been removed already ? */
7873 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7874 				IRB_REFRELE(ipif_ire->ire_bucket);
7875 				if (sire != NULL)
7876 					IRB_REFRELE(sire->ire_bucket);
7877 				ire_refrele(ipif_ire);
7878 				ire_refrele(save_ire);
7879 				break;
7880 			}
7881 
7882 			xmit_mp = first_mp;
7883 			/*
7884 			 * In the case of multirouting, a copy
7885 			 * of the packet is done before its sending.
7886 			 * The copy is used to attempt another
7887 			 * route resolution, in a next loop.
7888 			 */
7889 			if (ire->ire_flags & RTF_MULTIRT) {
7890 				copy_mp = copymsg(first_mp);
7891 				if (copy_mp != NULL) {
7892 					xmit_mp = copy_mp;
7893 					MULTIRT_DEBUG_TAG(first_mp);
7894 				}
7895 			}
7896 			ire_add_then_send(q, ire, xmit_mp);
7897 			ire_refrele(save_ire);
7898 
7899 			/* Assert that sire is not deleted yet. */
7900 			if (sire != NULL) {
7901 				ASSERT(sire->ire_ptpn != NULL);
7902 				IRB_REFRELE(sire->ire_bucket);
7903 			}
7904 
7905 			/* Assert that ipif_ire is not deleted yet. */
7906 			ASSERT(ipif_ire->ire_ptpn != NULL);
7907 			IRB_REFRELE(ipif_ire->ire_bucket);
7908 			ire_refrele(ipif_ire);
7909 
7910 			/*
7911 			 * If copy_mp is not NULL, multirouting was
7912 			 * requested. We loop to initiate a next
7913 			 * route resolution attempt, starting from sire.
7914 			 */
7915 			if (copy_mp != NULL) {
7916 				/*
7917 				 * Search for the next unresolved
7918 				 * multirt route.
7919 				 */
7920 				copy_mp = NULL;
7921 				ipif_ire = NULL;
7922 				ire = NULL;
7923 				multirt_resolve_next = B_TRUE;
7924 				continue;
7925 			}
7926 			if (sire != NULL)
7927 				ire_refrele(sire);
7928 			ipif_refrele(src_ipif);
7929 			ill_refrele(dst_ill);
7930 			return;
7931 		}
7932 		case IRE_IF_NORESOLVER: {
7933 			/*
7934 			 * We have what we need to build an IRE_CACHE.
7935 			 *
7936 			 * Create a new res_mp with the IP gateway address
7937 			 * in destination address in the DLPI hdr if the
7938 			 * physical length is exactly 4 bytes.
7939 			 */
7940 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7941 				uchar_t *addr;
7942 
7943 				if (gw)
7944 					addr = (uchar_t *)&gw;
7945 				else
7946 					addr = (uchar_t *)&dst;
7947 
7948 				res_mp = ill_dlur_gen(addr,
7949 				    dst_ill->ill_phys_addr_length,
7950 				    dst_ill->ill_sap,
7951 				    dst_ill->ill_sap_length);
7952 
7953 				if (res_mp == NULL) {
7954 					ip1dbg(("ip_newroute: res_mp NULL\n"));
7955 					break;
7956 				}
7957 			} else {
7958 				res_mp = NULL;
7959 			}
7960 
7961 			/*
7962 			 * TSol note: We are creating the ire cache for the
7963 			 * destination 'dst'. If 'dst' is offlink, going
7964 			 * through the first hop 'gw', the security attributes
7965 			 * of 'dst' must be set to point to the gateway
7966 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
7967 			 * is possible that 'dst' is a potential gateway that is
7968 			 * referenced by some route that has some security
7969 			 * attributes. Thus in the former case, we need to do a
7970 			 * gcgrp_lookup of 'gw' while in the latter case we
7971 			 * need to do gcgrp_lookup of 'dst' itself.
7972 			 */
7973 			ga.ga_af = AF_INET;
7974 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
7975 			    &ga.ga_addr);
7976 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
7977 
7978 			ire = ire_create(
7979 			    (uchar_t *)&dst,		/* dest address */
7980 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7981 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7982 			    (uchar_t *)&gw,		/* gateway address */
7983 			    NULL,
7984 			    &save_ire->ire_max_frag,
7985 			    NULL,			/* Fast Path header */
7986 			    dst_ill->ill_rq,		/* recv-from queue */
7987 			    dst_ill->ill_wq,		/* send-to queue */
7988 			    IRE_CACHE,
7989 			    res_mp,
7990 			    src_ipif,
7991 			    in_ill,			/* Incoming ill */
7992 			    save_ire->ire_mask,		/* Parent mask */
7993 			    (sire != NULL) ?		/* Parent handle */
7994 				sire->ire_phandle : 0,
7995 			    save_ire->ire_ihandle,	/* Interface handle */
7996 			    (sire != NULL) ? sire->ire_flags &
7997 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7998 			    &(save_ire->ire_uinfo),
7999 			    NULL,
8000 			    gcgrp);
8001 
8002 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8003 				freeb(res_mp);
8004 
8005 			if (ire == NULL) {
8006 				if (gcgrp != NULL) {
8007 					GCGRP_REFRELE(gcgrp);
8008 					gcgrp = NULL;
8009 				}
8010 				ire_refrele(save_ire);
8011 				break;
8012 			}
8013 
8014 			/* reference now held by IRE */
8015 			gcgrp = NULL;
8016 
8017 			ire->ire_marks |= ire_marks;
8018 
8019 			/* Prevent save_ire from getting deleted */
8020 			IRB_REFHOLD(save_ire->ire_bucket);
8021 			/* Has it been removed already ? */
8022 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8023 				IRB_REFRELE(save_ire->ire_bucket);
8024 				ire_refrele(save_ire);
8025 				break;
8026 			}
8027 
8028 			/*
8029 			 * In the case of multirouting, a copy
8030 			 * of the packet is made before it is sent.
8031 			 * The copy is used in the next
8032 			 * loop to attempt another resolution.
8033 			 */
8034 			xmit_mp = first_mp;
8035 			if ((sire != NULL) &&
8036 			    (sire->ire_flags & RTF_MULTIRT)) {
8037 				copy_mp = copymsg(first_mp);
8038 				if (copy_mp != NULL) {
8039 					xmit_mp = copy_mp;
8040 					MULTIRT_DEBUG_TAG(first_mp);
8041 				}
8042 			}
8043 			ire_add_then_send(q, ire, xmit_mp);
8044 
8045 			/* Assert that it is not deleted yet. */
8046 			ASSERT(save_ire->ire_ptpn != NULL);
8047 			IRB_REFRELE(save_ire->ire_bucket);
8048 			ire_refrele(save_ire);
8049 
8050 			if (copy_mp != NULL) {
8051 				/*
8052 				 * If we found a (no)resolver, we ignore any
8053 				 * trailing top priority IRE_CACHE in further
8054 				 * loops. This ensures that we do not omit any
8055 				 * (no)resolver.
8056 				 * This IRE_CACHE, if any, will be processed
8057 				 * by another thread entering ip_newroute().
8058 				 * IRE_CACHE entries, if any, will be processed
8059 				 * by another thread entering ip_newroute(),
8060 				 * (upon resolver response, for instance).
8061 				 * This aims to force parallel multirt
8062 				 * resolutions as soon as a packet must be sent.
8063 				 * In the best case, after the tx of only one
8064 				 * packet, all reachable routes are resolved.
8065 				 * Otherwise, the resolution of all RTF_MULTIRT
8066 				 * routes would require several emissions.
8067 				 */
8068 				multirt_flags &= ~MULTIRT_CACHEGW;
8069 
8070 				/*
8071 				 * Search for the next unresolved multirt
8072 				 * route.
8073 				 */
8074 				copy_mp = NULL;
8075 				save_ire = NULL;
8076 				ire = NULL;
8077 				multirt_resolve_next = B_TRUE;
8078 				continue;
8079 			}
8080 
8081 			/*
8082 			 * Don't need sire anymore
8083 			 */
8084 			if (sire != NULL)
8085 				ire_refrele(sire);
8086 
8087 			ipif_refrele(src_ipif);
8088 			ill_refrele(dst_ill);
8089 			return;
8090 		}
8091 		case IRE_IF_RESOLVER:
8092 			/*
8093 			 * We can't build an IRE_CACHE yet, but at least we
8094 			 * found a resolver that can help.
8095 			 */
8096 			res_mp = dst_ill->ill_resolver_mp;
8097 			if (!OK_RESOLVER_MP(res_mp))
8098 				break;
8099 
8100 			/*
8101 			 * To be at this point in the code with a non-zero gw
8102 			 * means that dst is reachable through a gateway that
8103 			 * we have never resolved.  By changing dst to the gw
8104 			 * addr we resolve the gateway first.
8105 			 * When ire_add_then_send() tries to put the IP dg
8106 			 * to dst, it will reenter ip_newroute() at which
8107 			 * time we will find the IRE_CACHE for the gw and
8108 			 * create another IRE_CACHE in case IRE_CACHE above.
8109 			 */
8110 			if (gw != INADDR_ANY) {
8111 				/*
8112 				 * The source ipif that was determined above was
8113 				 * relative to the destination address, not the
8114 				 * gateway's. If src_ipif was not taken out of
8115 				 * the IRE_IF_RESOLVER entry, we'll need to call
8116 				 * ipif_select_source() again.
8117 				 */
8118 				if (src_ipif != ire->ire_ipif) {
8119 					ipif_refrele(src_ipif);
8120 					src_ipif = ipif_select_source(dst_ill,
8121 					    gw, zoneid);
8122 					if (src_ipif == NULL) {
8123 						if (ip_debug > 2) {
8124 							pr_addr_dbg(
8125 							    "ip_newroute: no "
8126 							    "src for gw %s ",
8127 							    AF_INET, &gw);
8128 							printf("through "
8129 							    "interface %s\n",
8130 							    dst_ill->ill_name);
8131 						}
8132 						goto icmp_err_ret;
8133 					}
8134 				}
8135 				save_dst = dst;
8136 				dst = gw;
8137 				gw = INADDR_ANY;
8138 			}
8139 
8140 			/*
8141 			 * We obtain a partial IRE_CACHE which we will pass
8142 			 * along with the resolver query.  When the response
8143 			 * comes back it will be there ready for us to add.
8144 			 * The ire_max_frag is atomically set under the
8145 			 * irebucket lock in ire_add_v[46].
8146 			 */
8147 
8148 			ire = ire_create_mp(
8149 			    (uchar_t *)&dst,		/* dest address */
8150 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8151 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8152 			    (uchar_t *)&gw,		/* gateway address */
8153 			    NULL,			/* no in_src_addr */
8154 			    NULL,			/* ire_max_frag */
8155 			    NULL,			/* Fast Path header */
8156 			    dst_ill->ill_rq,		/* recv-from queue */
8157 			    dst_ill->ill_wq,		/* send-to queue */
8158 			    IRE_CACHE,
8159 			    NULL,
8160 			    src_ipif,			/* Interface ipif */
8161 			    in_ill,			/* Incoming ILL */
8162 			    save_ire->ire_mask,		/* Parent mask */
8163 			    0,
8164 			    save_ire->ire_ihandle,	/* Interface handle */
8165 			    0,				/* flags if any */
8166 			    &(save_ire->ire_uinfo),
8167 			    NULL,
8168 			    NULL);
8169 
8170 			if (ire == NULL) {
8171 				ire_refrele(save_ire);
8172 				break;
8173 			}
8174 
8175 			if ((sire != NULL) &&
8176 			    (sire->ire_flags & RTF_MULTIRT)) {
8177 				copy_mp = copymsg(first_mp);
8178 				if (copy_mp != NULL)
8179 					MULTIRT_DEBUG_TAG(copy_mp);
8180 			}
8181 
8182 			ire->ire_marks |= ire_marks;
8183 
8184 			/*
8185 			 * Construct message chain for the resolver
8186 			 * of the form:
8187 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8188 			 * Packet could contain a IPSEC_OUT mp.
8189 			 *
8190 			 * NOTE : ire will be added later when the response
8191 			 * comes back from ARP. If the response does not
8192 			 * come back, ARP frees the packet. For this reason,
8193 			 * we can't REFHOLD the bucket of save_ire to prevent
8194 			 * deletions. We may not be able to REFRELE the bucket
8195 			 * if the response never comes back. Thus, before
8196 			 * adding the ire, ire_add_v4 will make sure that the
8197 			 * interface route does not get deleted. This is the
8198 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8199 			 * where we can always prevent deletions because of
8200 			 * the synchronous nature of adding IRES i.e
8201 			 * ire_add_then_send is called after creating the IRE.
8202 			 */
8203 			ASSERT(ire->ire_mp != NULL);
8204 			ire->ire_mp->b_cont = first_mp;
8205 			/* Have saved_mp handy, for cleanup if canput fails */
8206 			saved_mp = mp;
8207 			mp = copyb(res_mp);
8208 			ASSERT(mp != NULL);
8209 			linkb(mp, ire->ire_mp);
8210 
8211 
8212 			/*
8213 			 * Fill in the source and dest addrs for the resolver.
8214 			 * NOTE: this depends on memory layouts imposed by
8215 			 * ill_init().
8216 			 */
8217 			areq = (areq_t *)mp->b_rptr;
8218 			addrp = (ipaddr_t *)((char *)areq +
8219 			    areq->areq_sender_addr_offset);
8220 			if (do_attach_ill) {
8221 				/*
8222 				 * This is bind to no failover case.
8223 				 * arp packet also must go out on attach_ill.
8224 				 */
8225 				ASSERT(ipha->ipha_src != NULL);
8226 				*addrp = ipha->ipha_src;
8227 			} else {
8228 				*addrp = save_ire->ire_src_addr;
8229 			}
8230 
8231 			ire_refrele(save_ire);
8232 			addrp = (ipaddr_t *)((char *)areq +
8233 			    areq->areq_target_addr_offset);
8234 			*addrp = dst;
8235 			/* Up to the resolver. */
8236 			if (canputnext(dst_ill->ill_rq) &&
8237 			    !(dst_ill->ill_arp_closing)) {
8238 				putnext(dst_ill->ill_rq, mp);
8239 				ire = NULL;
8240 				if (copy_mp != NULL) {
8241 					/*
8242 					 * If we found a resolver, we ignore
8243 					 * any trailing top priority IRE_CACHE
8244 					 * in the further loops. This ensures
8245 					 * that we do not omit any resolver.
8246 					 * IRE_CACHE entries, if any, will be
8247 					 * processed next time we enter
8248 					 * ip_newroute().
8249 					 */
8250 					multirt_flags &= ~MULTIRT_CACHEGW;
8251 					/*
8252 					 * Search for the next unresolved
8253 					 * multirt route.
8254 					 */
8255 					first_mp = copy_mp;
8256 					copy_mp = NULL;
8257 					/* Prepare the next resolution loop. */
8258 					mp = first_mp;
8259 					EXTRACT_PKT_MP(mp, first_mp,
8260 					    mctl_present);
8261 					if (mctl_present)
8262 						io = (ipsec_out_t *)
8263 						    first_mp->b_rptr;
8264 					ipha = (ipha_t *)mp->b_rptr;
8265 
8266 					ASSERT(sire != NULL);
8267 
8268 					dst = save_dst;
8269 					multirt_resolve_next = B_TRUE;
8270 					continue;
8271 				}
8272 
8273 				if (sire != NULL)
8274 					ire_refrele(sire);
8275 
8276 				/*
8277 				 * The response will come back in ip_wput
8278 				 * with db_type IRE_DB_TYPE.
8279 				 */
8280 				ipif_refrele(src_ipif);
8281 				ill_refrele(dst_ill);
8282 				return;
8283 			} else {
8284 				/* Prepare for cleanup */
8285 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8286 				    mp);
8287 				mp->b_cont = NULL;
8288 				freeb(mp); /* areq */
8289 				/*
8290 				 * this is an ire that is not added to the
8291 				 * cache. ire_freemblk will handle the release
8292 				 * of any resources associated with the ire.
8293 				 */
8294 				ire_delete(ire); /* ire_mp */
8295 				mp = saved_mp; /* pkt */
8296 				ire = NULL;
8297 				if (copy_mp != NULL) {
8298 					MULTIRT_DEBUG_UNTAG(copy_mp);
8299 					freemsg(copy_mp);
8300 					copy_mp = NULL;
8301 				}
8302 				break;
8303 			}
8304 		default:
8305 			break;
8306 		}
8307 	} while (multirt_resolve_next);
8308 
8309 	ip1dbg(("ip_newroute: dropped\n"));
8310 	/* Did this packet originate externally? */
8311 	if (mp->b_prev) {
8312 		mp->b_next = NULL;
8313 		mp->b_prev = NULL;
8314 		BUMP_MIB(&ip_mib, ipInDiscards);
8315 	} else {
8316 		BUMP_MIB(&ip_mib, ipOutDiscards);
8317 	}
8318 	ASSERT(copy_mp == NULL);
8319 	MULTIRT_DEBUG_UNTAG(first_mp);
8320 	freemsg(first_mp);
8321 	if (ire != NULL)
8322 		ire_refrele(ire);
8323 	if (sire != NULL)
8324 		ire_refrele(sire);
8325 	if (src_ipif != NULL)
8326 		ipif_refrele(src_ipif);
8327 	if (dst_ill != NULL)
8328 		ill_refrele(dst_ill);
8329 	return;
8330 
8331 icmp_err_ret:
8332 	ip1dbg(("ip_newroute: no route\n"));
8333 	if (src_ipif != NULL)
8334 		ipif_refrele(src_ipif);
8335 	if (dst_ill != NULL)
8336 		ill_refrele(dst_ill);
8337 	if (sire != NULL)
8338 		ire_refrele(sire);
8339 	/* Did this packet originate externally? */
8340 	if (mp->b_prev) {
8341 		mp->b_next = NULL;
8342 		mp->b_prev = NULL;
8343 		/* XXX ipInNoRoutes */
8344 		q = WR(q);
8345 	} else {
8346 		/*
8347 		 * Since ip_wput() isn't close to finished, we fill
8348 		 * in enough of the header for credible error reporting.
8349 		 */
8350 		if (ip_hdr_complete(ipha, zoneid)) {
8351 			/* Failed */
8352 			MULTIRT_DEBUG_UNTAG(first_mp);
8353 			freemsg(first_mp);
8354 			if (ire != NULL)
8355 				ire_refrele(ire);
8356 			return;
8357 		}
8358 	}
8359 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8360 
8361 	/*
8362 	 * At this point we will have ire only if RTF_BLACKHOLE
8363 	 * or RTF_REJECT flags are set on the IRE. It will not
8364 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8365 	 */
8366 	if (ire != NULL) {
8367 		if (ire->ire_flags & RTF_BLACKHOLE) {
8368 			ire_refrele(ire);
8369 			MULTIRT_DEBUG_UNTAG(first_mp);
8370 			freemsg(first_mp);
8371 			return;
8372 		}
8373 		ire_refrele(ire);
8374 	}
8375 	if (ip_source_routed(ipha)) {
8376 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8377 		return;
8378 	}
8379 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8380 }
8381 
8382 /*
8383  * IPv4 -
8384  * ip_newroute_ipif is called by ip_wput_multicast and
8385  * ip_rput_forward_multicast whenever we need to send
8386  * out a packet to a destination address for which we do not have specific
8387  * routing information. It is used when the packet will be sent out
8388  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8389  * socket option is set or icmp error message wants to go out on a particular
8390  * interface for a unicast packet.
8391  *
8392  * In most cases, the destination address is resolved thanks to the ipif
8393  * intrinsic resolver. However, there are some cases where the call to
8394  * ip_newroute_ipif must take into account the potential presence of
8395  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8396  * that uses the interface. This is specified through flags,
8397  * which can be a combination of:
8398  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8399  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8400  *   and flags. Additionally, the packet source address has to be set to
8401  *   the specified address. The caller is thus expected to set this flag
8402  *   if the packet has no specific source address yet.
8403  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8404  *   flag, the resulting ire will inherit the flag. All unresolved routes
8405  *   to the destination must be explored in the same call to
8406  *   ip_newroute_ipif().
8407  */
8408 static void
8409 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8410     conn_t *connp, uint32_t flags)
8411 {
8412 	areq_t	*areq;
8413 	ire_t	*ire = NULL;
8414 	mblk_t	*res_mp;
8415 	ipaddr_t *addrp;
8416 	mblk_t *first_mp;
8417 	ire_t	*save_ire = NULL;
8418 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8419 	ipif_t	*src_ipif = NULL;
8420 	ushort_t ire_marks = 0;
8421 	ill_t	*dst_ill = NULL;
8422 	boolean_t mctl_present;
8423 	ipsec_out_t *io;
8424 	ipha_t *ipha;
8425 	int	ihandle = 0;
8426 	mblk_t	*saved_mp;
8427 	ire_t   *fire = NULL;
8428 	mblk_t  *copy_mp = NULL;
8429 	boolean_t multirt_resolve_next;
8430 	ipaddr_t ipha_dst;
8431 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8432 
8433 	/*
8434 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8435 	 * here for uniformity
8436 	 */
8437 	ipif_refhold(ipif);
8438 
8439 	/*
8440 	 * This loop is run only once in most cases.
8441 	 * We loop to resolve further routes only when the destination
8442 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8443 	 */
8444 	do {
8445 		if (dst_ill != NULL) {
8446 			ill_refrele(dst_ill);
8447 			dst_ill = NULL;
8448 		}
8449 		if (src_ipif != NULL) {
8450 			ipif_refrele(src_ipif);
8451 			src_ipif = NULL;
8452 		}
8453 		multirt_resolve_next = B_FALSE;
8454 
8455 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8456 		    ipif->ipif_ill->ill_name));
8457 
8458 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8459 		if (mctl_present)
8460 			io = (ipsec_out_t *)first_mp->b_rptr;
8461 
8462 		ipha = (ipha_t *)mp->b_rptr;
8463 
8464 		/*
8465 		 * Save the packet destination address, we may need it after
8466 		 * the packet has been consumed.
8467 		 */
8468 		ipha_dst = ipha->ipha_dst;
8469 
8470 		/*
8471 		 * If the interface is a pt-pt interface we look for an
8472 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8473 		 * local_address and the pt-pt destination address. Otherwise
8474 		 * we just match the local address.
8475 		 * NOTE: dst could be different than ipha->ipha_dst in case
8476 		 * of sending igmp multicast packets over a point-to-point
8477 		 * connection.
8478 		 * Thus we must be careful enough to check ipha_dst to be a
8479 		 * multicast address, otherwise it will take xmit_if path for
8480 		 * multicast packets resulting into kernel stack overflow by
8481 		 * repeated calls to ip_newroute_ipif from ire_send().
8482 		 */
8483 		if (CLASSD(ipha_dst) &&
8484 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8485 			goto err_ret;
8486 		}
8487 
8488 		/*
8489 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8490 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8491 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8492 		 * propagate its flags to the new ire.
8493 		 */
8494 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8495 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8496 			ip2dbg(("ip_newroute_ipif: "
8497 			    "ipif_lookup_multi_ire("
8498 			    "ipif %p, dst %08x) = fire %p\n",
8499 			    (void *)ipif, ntohl(dst), (void *)fire));
8500 		}
8501 
8502 		if (mctl_present && io->ipsec_out_attach_if) {
8503 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8504 			    io->ipsec_out_ill_index, B_FALSE);
8505 
8506 			/* Failure case frees things for us. */
8507 			if (attach_ill == NULL) {
8508 				ipif_refrele(ipif);
8509 				if (fire != NULL)
8510 					ire_refrele(fire);
8511 				return;
8512 			}
8513 
8514 			/*
8515 			 * Check if we need an ire that will not be
8516 			 * looked up by anybody else i.e. HIDDEN.
8517 			 */
8518 			if (ill_is_probeonly(attach_ill)) {
8519 				ire_marks = IRE_MARK_HIDDEN;
8520 			}
8521 			/*
8522 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8523 			 * case.
8524 			 */
8525 			dst_ill = ipif->ipif_ill;
8526 			/* attach_ill has been refheld by ip_grab_attach_ill */
8527 			ASSERT(dst_ill == attach_ill);
8528 		} else {
8529 			/*
8530 			 * If this is set by IP_XMIT_IF, then make sure that
8531 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8532 			 * specified ill.
8533 			 */
8534 			ASSERT((connp == NULL) ||
8535 			    (connp->conn_xmit_if_ill == NULL) ||
8536 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8537 			/*
8538 			 * If the interface belongs to an interface group,
8539 			 * make sure the next possible interface in the group
8540 			 * is used.  This encourages load spreading among
8541 			 * peers in an interface group.
8542 			 * Note: load spreading is disabled for RTF_MULTIRT
8543 			 * routes.
8544 			 */
8545 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8546 			    (fire->ire_flags & RTF_MULTIRT)) {
8547 				/*
8548 				 * Don't perform outbound load spreading
8549 				 * in the case of an RTF_MULTIRT issued route,
8550 				 * we actually typically want to replicate
8551 				 * outgoing packets through particular
8552 				 * interfaces.
8553 				 */
8554 				dst_ill = ipif->ipif_ill;
8555 				ill_refhold(dst_ill);
8556 			} else {
8557 				dst_ill = ip_newroute_get_dst_ill(
8558 				    ipif->ipif_ill);
8559 			}
8560 			if (dst_ill == NULL) {
8561 				if (ip_debug > 2) {
8562 					pr_addr_dbg("ip_newroute_ipif: "
8563 					    "no dst ill for dst %s\n",
8564 					    AF_INET, &dst);
8565 				}
8566 				goto err_ret;
8567 			}
8568 		}
8569 
8570 		/*
8571 		 * Pick a source address preferring non-deprecated ones.
8572 		 * Unlike ip_newroute, we don't do any source address
8573 		 * selection here since for multicast it really does not help
8574 		 * in inbound load spreading as in the unicast case.
8575 		 */
8576 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8577 		    (fire->ire_flags & RTF_SETSRC)) {
8578 			/*
8579 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8580 			 * on that interface. This ire has RTF_SETSRC flag, so
8581 			 * the source address of the packet must be changed.
8582 			 * Check that the ipif matching the requested source
8583 			 * address still exists.
8584 			 */
8585 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8586 			    zoneid, NULL, NULL, NULL, NULL);
8587 		}
8588 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8589 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8590 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8591 		    (src_ipif == NULL)) {
8592 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8593 			if (src_ipif == NULL) {
8594 				if (ip_debug > 2) {
8595 					/* ip1dbg */
8596 					pr_addr_dbg("ip_newroute_ipif: "
8597 					    "no src for dst %s",
8598 					    AF_INET, &dst);
8599 				}
8600 				ip1dbg((" through interface %s\n",
8601 				    dst_ill->ill_name));
8602 				goto err_ret;
8603 			}
8604 			ipif_refrele(ipif);
8605 			ipif = src_ipif;
8606 			ipif_refhold(ipif);
8607 		}
8608 		if (src_ipif == NULL) {
8609 			src_ipif = ipif;
8610 			ipif_refhold(src_ipif);
8611 		}
8612 
8613 		/*
8614 		 * Assign a source address while we have the conn.
8615 		 * We can't have ip_wput_ire pick a source address when the
8616 		 * packet returns from arp since conn_unspec_src might be set
8617 		 * and we loose the conn when going through arp.
8618 		 */
8619 		if (ipha->ipha_src == INADDR_ANY &&
8620 		    (connp == NULL || !connp->conn_unspec_src)) {
8621 			ipha->ipha_src = src_ipif->ipif_src_addr;
8622 		}
8623 
8624 		/*
8625 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8626 		 * interface does not have an interface ire.
8627 		 * Example: Thousands of mobileip PPP interfaces to mobile
8628 		 * nodes. We don't want to create interface ires because
8629 		 * packets from other mobile nodes must not take the route
8630 		 * via interface ires to the visiting mobile node without
8631 		 * going through the home agent, in absence of mobileip
8632 		 * route optimization.
8633 		 */
8634 		if (CLASSD(ipha_dst) && (connp == NULL ||
8635 		    connp->conn_xmit_if_ill == NULL)) {
8636 			/* ipif_to_ire returns an held ire */
8637 			ire = ipif_to_ire(ipif);
8638 			if (ire == NULL)
8639 				goto err_ret;
8640 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8641 				goto err_ret;
8642 			/*
8643 			 * ihandle is needed when the ire is added to
8644 			 * cache table.
8645 			 */
8646 			save_ire = ire;
8647 			ihandle = save_ire->ire_ihandle;
8648 
8649 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8650 			    "flags %04x\n",
8651 			    (void *)ire, (void *)ipif, flags));
8652 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8653 			    (fire->ire_flags & RTF_MULTIRT)) {
8654 				/*
8655 				 * As requested by flags, an IRE_OFFSUBNET was
8656 				 * looked up on that interface. This ire has
8657 				 * RTF_MULTIRT flag, so the resolution loop will
8658 				 * be re-entered to resolve additional routes on
8659 				 * other interfaces. For that purpose, a copy of
8660 				 * the packet is performed at this point.
8661 				 */
8662 				fire->ire_last_used_time = lbolt;
8663 				copy_mp = copymsg(first_mp);
8664 				if (copy_mp) {
8665 					MULTIRT_DEBUG_TAG(copy_mp);
8666 				}
8667 			}
8668 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8669 			    (fire->ire_flags & RTF_SETSRC)) {
8670 				/*
8671 				 * As requested by flags, an IRE_OFFSUBET was
8672 				 * looked up on that interface. This ire has
8673 				 * RTF_SETSRC flag, so the source address of the
8674 				 * packet must be changed.
8675 				 */
8676 				ipha->ipha_src = fire->ire_src_addr;
8677 			}
8678 		} else {
8679 			ASSERT((connp == NULL) ||
8680 			    (connp->conn_xmit_if_ill != NULL) ||
8681 			    (connp->conn_dontroute));
8682 			/*
8683 			 * The only ways we can come here are:
8684 			 * 1) IP_XMIT_IF socket option is set
8685 			 * 2) ICMP error message generated from
8686 			 *    ip_mrtun_forward() routine and it needs
8687 			 *    to go through the specified ill.
8688 			 * 3) SO_DONTROUTE socket option is set
8689 			 * In all cases, the new ire will not be added
8690 			 * into cache table.
8691 			 */
8692 			ire_marks |= IRE_MARK_NOADD;
8693 		}
8694 
8695 		switch (ipif->ipif_net_type) {
8696 		case IRE_IF_NORESOLVER: {
8697 			/* We have what we need to build an IRE_CACHE. */
8698 			mblk_t	*res_mp;
8699 
8700 			/*
8701 			 * Create a new res_mp with the
8702 			 * IP gateway address as destination address in the
8703 			 * DLPI hdr if the physical length is exactly 4 bytes.
8704 			 */
8705 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8706 				res_mp = ill_dlur_gen((uchar_t *)&dst,
8707 				    dst_ill->ill_phys_addr_length,
8708 				    dst_ill->ill_sap,
8709 				    dst_ill->ill_sap_length);
8710 			} else {
8711 				/* use the value set in ip_ll_subnet_defaults */
8712 				res_mp = ill_dlur_gen(NULL,
8713 				    dst_ill->ill_phys_addr_length,
8714 				    dst_ill->ill_sap,
8715 				    dst_ill->ill_sap_length);
8716 			}
8717 
8718 			if (res_mp == NULL)
8719 				break;
8720 			/*
8721 			 * The new ire inherits the IRE_OFFSUBNET flags
8722 			 * and source address, if this was requested.
8723 			 */
8724 			ire = ire_create(
8725 			    (uchar_t *)&dst,		/* dest address */
8726 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8727 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8728 			    NULL,			/* gateway address */
8729 			    NULL,
8730 			    &ipif->ipif_mtu,
8731 			    NULL,			/* Fast Path header */
8732 			    dst_ill->ill_rq,		/* recv-from queue */
8733 			    dst_ill->ill_wq,		/* send-to queue */
8734 			    IRE_CACHE,
8735 			    res_mp,
8736 			    src_ipif,
8737 			    NULL,
8738 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8739 			    (fire != NULL) ?		/* Parent handle */
8740 				fire->ire_phandle : 0,
8741 			    ihandle,			/* Interface handle */
8742 			    (fire != NULL) ?
8743 				(fire->ire_flags &
8744 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8745 			    (save_ire == NULL ? &ire_uinfo_null :
8746 				&save_ire->ire_uinfo),
8747 			    NULL,
8748 			    NULL);
8749 
8750 			freeb(res_mp);
8751 
8752 			if (ire == NULL) {
8753 				if (save_ire != NULL)
8754 					ire_refrele(save_ire);
8755 				break;
8756 			}
8757 
8758 			ire->ire_marks |= ire_marks;
8759 
8760 			/*
8761 			 * If IRE_MARK_NOADD is set then we need to convert
8762 			 * the max_fragp to a useable value now. This is
8763 			 * normally done in ire_add_v[46]. We also need to
8764 			 * associate the ire with an nce (normally would be
8765 			 * done in ip_wput_nondata()).
8766 			 *
8767 			 * Note that IRE_MARK_NOADD packets created here
8768 			 * do not have a non-null ire_mp pointer. The null
8769 			 * value of ire_bucket indicates that they were
8770 			 * never added.
8771 			 */
8772 			if (ire->ire_marks & IRE_MARK_NOADD) {
8773 				uint_t  max_frag;
8774 
8775 				max_frag = *ire->ire_max_fragp;
8776 				ire->ire_max_fragp = NULL;
8777 				ire->ire_max_frag = max_frag;
8778 
8779 				if ((ire->ire_nce = ndp_lookup_v4(
8780 				    ire_to_ill(ire),
8781 				    (ire->ire_gateway_addr != INADDR_ANY ?
8782 				    &ire->ire_gateway_addr : &ire->ire_addr),
8783 				    B_FALSE)) == NULL) {
8784 					if (save_ire != NULL)
8785 						ire_refrele(save_ire);
8786 					break;
8787 				}
8788 				ASSERT(ire->ire_nce->nce_state ==
8789 				    ND_REACHABLE);
8790 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
8791 			}
8792 
8793 			/* Prevent save_ire from getting deleted */
8794 			if (save_ire != NULL) {
8795 				IRB_REFHOLD(save_ire->ire_bucket);
8796 				/* Has it been removed already ? */
8797 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8798 					IRB_REFRELE(save_ire->ire_bucket);
8799 					ire_refrele(save_ire);
8800 					break;
8801 				}
8802 			}
8803 
8804 			ire_add_then_send(q, ire, first_mp);
8805 
8806 			/* Assert that save_ire is not deleted yet. */
8807 			if (save_ire != NULL) {
8808 				ASSERT(save_ire->ire_ptpn != NULL);
8809 				IRB_REFRELE(save_ire->ire_bucket);
8810 				ire_refrele(save_ire);
8811 				save_ire = NULL;
8812 			}
8813 			if (fire != NULL) {
8814 				ire_refrele(fire);
8815 				fire = NULL;
8816 			}
8817 
8818 			/*
8819 			 * the resolution loop is re-entered if this
8820 			 * was requested through flags and if we
8821 			 * actually are in a multirouting case.
8822 			 */
8823 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8824 				boolean_t need_resolve =
8825 				    ire_multirt_need_resolve(ipha_dst,
8826 					MBLK_GETLABEL(copy_mp));
8827 				if (!need_resolve) {
8828 					MULTIRT_DEBUG_UNTAG(copy_mp);
8829 					freemsg(copy_mp);
8830 					copy_mp = NULL;
8831 				} else {
8832 					/*
8833 					 * ipif_lookup_group() calls
8834 					 * ire_lookup_multi() that uses
8835 					 * ire_ftable_lookup() to find
8836 					 * an IRE_INTERFACE for the group.
8837 					 * In the multirt case,
8838 					 * ire_lookup_multi() then invokes
8839 					 * ire_multirt_lookup() to find
8840 					 * the next resolvable ire.
8841 					 * As a result, we obtain an new
8842 					 * interface, derived from the
8843 					 * next ire.
8844 					 */
8845 					ipif_refrele(ipif);
8846 					ipif = ipif_lookup_group(ipha_dst,
8847 					    zoneid);
8848 					ip2dbg(("ip_newroute_ipif: "
8849 					    "multirt dst %08x, ipif %p\n",
8850 					    htonl(dst), (void *)ipif));
8851 					if (ipif != NULL) {
8852 						mp = copy_mp;
8853 						copy_mp = NULL;
8854 						multirt_resolve_next = B_TRUE;
8855 						continue;
8856 					} else {
8857 						freemsg(copy_mp);
8858 					}
8859 				}
8860 			}
8861 			if (ipif != NULL)
8862 				ipif_refrele(ipif);
8863 			ill_refrele(dst_ill);
8864 			ipif_refrele(src_ipif);
8865 			return;
8866 		}
8867 		case IRE_IF_RESOLVER:
8868 			/*
8869 			 * We can't build an IRE_CACHE yet, but at least
8870 			 * we found a resolver that can help.
8871 			 */
8872 			res_mp = dst_ill->ill_resolver_mp;
8873 			if (!OK_RESOLVER_MP(res_mp))
8874 				break;
8875 
8876 			/*
8877 			 * We obtain a partial IRE_CACHE which we will pass
8878 			 * along with the resolver query.  When the response
8879 			 * comes back it will be there ready for us to add.
8880 			 * The new ire inherits the IRE_OFFSUBNET flags
8881 			 * and source address, if this was requested.
8882 			 * The ire_max_frag is atomically set under the
8883 			 * irebucket lock in ire_add_v[46]. Only in the
8884 			 * case of IRE_MARK_NOADD, we set it here itself.
8885 			 */
8886 			ire = ire_create_mp(
8887 			    (uchar_t *)&dst,		/* dest address */
8888 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8889 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8890 			    NULL,			/* gateway address */
8891 			    NULL,			/* no in_src_addr */
8892 			    (ire_marks & IRE_MARK_NOADD) ?
8893 				ipif->ipif_mtu : 0,	/* max_frag */
8894 			    NULL,			/* Fast path header */
8895 			    dst_ill->ill_rq,		/* recv-from queue */
8896 			    dst_ill->ill_wq,		/* send-to queue */
8897 			    IRE_CACHE,
8898 			    NULL,	/* let ire_nce_init figure res_mp out */
8899 			    src_ipif,
8900 			    NULL,
8901 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8902 			    (fire != NULL) ?		/* Parent handle */
8903 				fire->ire_phandle : 0,
8904 			    ihandle,			/* Interface handle */
8905 			    (fire != NULL) ?		/* flags if any */
8906 				(fire->ire_flags &
8907 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8908 			    (save_ire == NULL ? &ire_uinfo_null :
8909 				&save_ire->ire_uinfo),
8910 			    NULL,
8911 			    NULL);
8912 
8913 			if (save_ire != NULL) {
8914 				ire_refrele(save_ire);
8915 				save_ire = NULL;
8916 			}
8917 			if (ire == NULL)
8918 				break;
8919 
8920 			ire->ire_marks |= ire_marks;
8921 			/*
8922 			 * Construct message chain for the resolver of the
8923 			 * form:
8924 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8925 			 *
8926 			 * NOTE : ire will be added later when the response
8927 			 * comes back from ARP. If the response does not
8928 			 * come back, ARP frees the packet. For this reason,
8929 			 * we can't REFHOLD the bucket of save_ire to prevent
8930 			 * deletions. We may not be able to REFRELE the
8931 			 * bucket if the response never comes back.
8932 			 * Thus, before adding the ire, ire_add_v4 will make
8933 			 * sure that the interface route does not get deleted.
8934 			 * This is the only case unlike ip_newroute_v6,
8935 			 * ip_newroute_ipif_v6 where we can always prevent
8936 			 * deletions because ire_add_then_send is called after
8937 			 * creating the IRE.
8938 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8939 			 * does not add this IRE into the IRE CACHE.
8940 			 */
8941 			ASSERT(ire->ire_mp != NULL);
8942 			ire->ire_mp->b_cont = first_mp;
8943 			/* Have saved_mp handy, for cleanup if canput fails */
8944 			saved_mp = mp;
8945 			mp = copyb(res_mp);
8946 			ASSERT(mp != NULL);
8947 			linkb(mp, ire->ire_mp);
8948 
8949 			/*
8950 			 * Fill in the source and dest addrs for the resolver.
8951 			 * NOTE: this depends on memory layouts imposed by
8952 			 * ill_init().
8953 			 */
8954 			areq = (areq_t *)mp->b_rptr;
8955 			addrp = (ipaddr_t *)((char *)areq +
8956 			    areq->areq_sender_addr_offset);
8957 			*addrp = ire->ire_src_addr;
8958 			addrp = (ipaddr_t *)((char *)areq +
8959 			    areq->areq_target_addr_offset);
8960 			*addrp = dst;
8961 			/* Up to the resolver. */
8962 			if (canputnext(dst_ill->ill_rq) &&
8963 			    !(dst_ill->ill_arp_closing)) {
8964 				putnext(dst_ill->ill_rq, mp);
8965 				/*
8966 				 * The response will come back in ip_wput
8967 				 * with db_type IRE_DB_TYPE.
8968 				 */
8969 			} else {
8970 				mp->b_cont = NULL;
8971 				freeb(mp); /* areq */
8972 				ire_delete(ire); /* ire_mp */
8973 				saved_mp->b_next = NULL;
8974 				saved_mp->b_prev = NULL;
8975 				freemsg(first_mp); /* pkt */
8976 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8977 			}
8978 
8979 			if (fire != NULL) {
8980 				ire_refrele(fire);
8981 				fire = NULL;
8982 			}
8983 
8984 
8985 			/*
8986 			 * The resolution loop is re-entered if this was
8987 			 * requested through flags and we actually are
8988 			 * in a multirouting case.
8989 			 */
8990 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8991 				boolean_t need_resolve =
8992 				    ire_multirt_need_resolve(ipha_dst,
8993 					MBLK_GETLABEL(copy_mp));
8994 				if (!need_resolve) {
8995 					MULTIRT_DEBUG_UNTAG(copy_mp);
8996 					freemsg(copy_mp);
8997 					copy_mp = NULL;
8998 				} else {
8999 					/*
9000 					 * ipif_lookup_group() calls
9001 					 * ire_lookup_multi() that uses
9002 					 * ire_ftable_lookup() to find
9003 					 * an IRE_INTERFACE for the group.
9004 					 * In the multirt case,
9005 					 * ire_lookup_multi() then invokes
9006 					 * ire_multirt_lookup() to find
9007 					 * the next resolvable ire.
9008 					 * As a result, we obtain an new
9009 					 * interface, derived from the
9010 					 * next ire.
9011 					 */
9012 					ipif_refrele(ipif);
9013 					ipif = ipif_lookup_group(ipha_dst,
9014 					    zoneid);
9015 					if (ipif != NULL) {
9016 						mp = copy_mp;
9017 						copy_mp = NULL;
9018 						multirt_resolve_next = B_TRUE;
9019 						continue;
9020 					} else {
9021 						freemsg(copy_mp);
9022 					}
9023 				}
9024 			}
9025 			if (ipif != NULL)
9026 				ipif_refrele(ipif);
9027 			ill_refrele(dst_ill);
9028 			ipif_refrele(src_ipif);
9029 			return;
9030 		default:
9031 			break;
9032 		}
9033 	} while (multirt_resolve_next);
9034 
9035 err_ret:
9036 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9037 	if (fire != NULL)
9038 		ire_refrele(fire);
9039 	ipif_refrele(ipif);
9040 	/* Did this packet originate externally? */
9041 	if (dst_ill != NULL)
9042 		ill_refrele(dst_ill);
9043 	if (src_ipif != NULL)
9044 		ipif_refrele(src_ipif);
9045 	if (mp->b_prev || mp->b_next) {
9046 		mp->b_next = NULL;
9047 		mp->b_prev = NULL;
9048 	} else {
9049 		/*
9050 		 * Since ip_wput() isn't close to finished, we fill
9051 		 * in enough of the header for credible error reporting.
9052 		 */
9053 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9054 			/* Failed */
9055 			freemsg(first_mp);
9056 			if (ire != NULL)
9057 				ire_refrele(ire);
9058 			return;
9059 		}
9060 	}
9061 	/*
9062 	 * At this point we will have ire only if RTF_BLACKHOLE
9063 	 * or RTF_REJECT flags are set on the IRE. It will not
9064 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9065 	 */
9066 	if (ire != NULL) {
9067 		if (ire->ire_flags & RTF_BLACKHOLE) {
9068 			ire_refrele(ire);
9069 			freemsg(first_mp);
9070 			return;
9071 		}
9072 		ire_refrele(ire);
9073 	}
9074 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
9075 }
9076 
9077 /* Name/Value Table Lookup Routine */
9078 char *
9079 ip_nv_lookup(nv_t *nv, int value)
9080 {
9081 	if (!nv)
9082 		return (NULL);
9083 	for (; nv->nv_name; nv++) {
9084 		if (nv->nv_value == value)
9085 			return (nv->nv_name);
9086 	}
9087 	return ("unknown");
9088 }
9089 
9090 /*
9091  * one day it can be patched to 1 from /etc/system for machines that have few
9092  * fast network interfaces feeding multiple cpus.
9093  */
9094 int ill_stream_putlocks = 0;
9095 
9096 /*
9097  * This is a module open, i.e. this is a control stream for access
9098  * to a DLPI device.  We allocate an ill_t as the instance data in
9099  * this case.
9100  */
9101 int
9102 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9103 {
9104 	uint32_t mem_cnt;
9105 	uint32_t cpu_cnt;
9106 	uint32_t min_cnt;
9107 	pgcnt_t mem_avail;
9108 	ill_t	*ill;
9109 	int	err;
9110 
9111 	/*
9112 	 * Prevent unprivileged processes from pushing IP so that
9113 	 * they can't send raw IP.
9114 	 */
9115 	if (secpolicy_net_rawaccess(credp) != 0)
9116 		return (EPERM);
9117 
9118 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9119 	q->q_ptr = WR(q)->q_ptr = ill;
9120 
9121 	/*
9122 	 * ill_init initializes the ill fields and then sends down
9123 	 * down a DL_INFO_REQ after calling qprocson.
9124 	 */
9125 	err = ill_init(q, ill);
9126 	if (err != 0) {
9127 		mi_free(ill);
9128 		q->q_ptr = NULL;
9129 		WR(q)->q_ptr = NULL;
9130 		return (err);
9131 	}
9132 
9133 	/* ill_init initializes the ipsq marking this thread as writer */
9134 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9135 	/* Wait for the DL_INFO_ACK */
9136 	mutex_enter(&ill->ill_lock);
9137 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9138 		/*
9139 		 * Return value of 0 indicates a pending signal.
9140 		 */
9141 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9142 		if (err == 0) {
9143 			mutex_exit(&ill->ill_lock);
9144 			(void) ip_close(q, 0);
9145 			return (EINTR);
9146 		}
9147 	}
9148 	mutex_exit(&ill->ill_lock);
9149 
9150 	/*
9151 	 * ip_rput_other could have set an error  in ill_error on
9152 	 * receipt of M_ERROR.
9153 	 */
9154 
9155 	err = ill->ill_error;
9156 	if (err != 0) {
9157 		(void) ip_close(q, 0);
9158 		return (err);
9159 	}
9160 
9161 	/*
9162 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9163 	 * size and the cpu speed of the machine. This is upper
9164 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9165 	 * and is lower bounded by the compile time value of
9166 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9167 	 * ip6_ire_max_bucket_cnt.
9168 	 */
9169 	mem_avail = kmem_avail();
9170 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9171 	    ip_cache_table_size / sizeof (ire_t);
9172 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9173 
9174 	min_cnt = MIN(cpu_cnt, mem_cnt);
9175 	if (min_cnt < ip_ire_min_bucket_cnt)
9176 		min_cnt = ip_ire_min_bucket_cnt;
9177 	if (ip_ire_max_bucket_cnt > min_cnt) {
9178 		ip_ire_max_bucket_cnt = min_cnt;
9179 	}
9180 
9181 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9182 	    ip6_cache_table_size / sizeof (ire_t);
9183 	min_cnt = MIN(cpu_cnt, mem_cnt);
9184 	if (min_cnt < ip6_ire_min_bucket_cnt)
9185 		min_cnt = ip6_ire_min_bucket_cnt;
9186 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9187 		ip6_ire_max_bucket_cnt = min_cnt;
9188 	}
9189 
9190 	ill->ill_credp = credp;
9191 	crhold(credp);
9192 
9193 	mutex_enter(&ip_mi_lock);
9194 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9195 	mutex_exit(&ip_mi_lock);
9196 	if (err) {
9197 		(void) ip_close(q, 0);
9198 		return (err);
9199 	}
9200 	return (0);
9201 }
9202 
9203 /* IP open routine. */
9204 int
9205 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9206 {
9207 	conn_t 		*connp;
9208 	major_t		maj;
9209 
9210 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9211 
9212 	/* Allow reopen. */
9213 	if (q->q_ptr != NULL)
9214 		return (0);
9215 
9216 	if (sflag & MODOPEN) {
9217 		/* This is a module open */
9218 		return (ip_modopen(q, devp, flag, sflag, credp));
9219 	}
9220 
9221 	/*
9222 	 * We are opening as a device. This is an IP client stream, and we
9223 	 * allocate an conn_t as the instance data.
9224 	 */
9225 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9226 	connp->conn_upq = q;
9227 	q->q_ptr = WR(q)->q_ptr = connp;
9228 
9229 	if (flag & SO_SOCKSTR)
9230 		connp->conn_flags |= IPCL_SOCKET;
9231 
9232 	/* Minor tells us which /dev entry was opened */
9233 	if (geteminor(*devp) == IPV6_MINOR) {
9234 		connp->conn_flags |= IPCL_ISV6;
9235 		connp->conn_af_isv6 = B_TRUE;
9236 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9237 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9238 	} else {
9239 		connp->conn_af_isv6 = B_FALSE;
9240 		connp->conn_pkt_isv6 = B_FALSE;
9241 	}
9242 
9243 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9244 		q->q_ptr = WR(q)->q_ptr = NULL;
9245 		CONN_DEC_REF(connp);
9246 		return (EBUSY);
9247 	}
9248 
9249 	maj = getemajor(*devp);
9250 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9251 
9252 	/*
9253 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9254 	 */
9255 	connp->conn_cred = credp;
9256 	crhold(connp->conn_cred);
9257 
9258 	/*
9259 	 * If the caller has the process-wide flag set, then default to MAC
9260 	 * exempt mode.  This allows read-down to unlabeled hosts.
9261 	 */
9262 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9263 		connp->conn_mac_exempt = B_TRUE;
9264 
9265 	connp->conn_zoneid = getzoneid();
9266 
9267 	/*
9268 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9269 	 * administrative ops.  In these cases, we just need a normal conn_t
9270 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9271 	 * an error will be returned.
9272 	 */
9273 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9274 		connp->conn_rq = q;
9275 		connp->conn_wq = WR(q);
9276 	} else {
9277 		connp->conn_ulp = IPPROTO_SCTP;
9278 		connp->conn_rq = connp->conn_wq = NULL;
9279 	}
9280 	/* Non-zero default values */
9281 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9282 
9283 	/*
9284 	 * Make the conn globally visible to walkers
9285 	 */
9286 	mutex_enter(&connp->conn_lock);
9287 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9288 	mutex_exit(&connp->conn_lock);
9289 	ASSERT(connp->conn_ref == 1);
9290 
9291 	qprocson(q);
9292 
9293 	return (0);
9294 }
9295 
9296 /*
9297  * Change q_qinfo based on the value of isv6.
9298  * This can not called on an ill queue.
9299  * Note that there is no race since either q_qinfo works for conn queues - it
9300  * is just an optimization to enter the best wput routine directly.
9301  */
9302 void
9303 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9304 {
9305 	ASSERT(q->q_flag & QREADR);
9306 	ASSERT(WR(q)->q_next == NULL);
9307 	ASSERT(q->q_ptr != NULL);
9308 
9309 	if (minor == IPV6_MINOR)  {
9310 		if (bump_mib)
9311 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9312 		q->q_qinfo = &rinit_ipv6;
9313 		WR(q)->q_qinfo = &winit_ipv6;
9314 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9315 	} else {
9316 		if (bump_mib)
9317 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9318 		q->q_qinfo = &rinit;
9319 		WR(q)->q_qinfo = &winit;
9320 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9321 	}
9322 
9323 }
9324 
9325 /*
9326  * See if IPsec needs loading because of the options in mp.
9327  */
9328 static boolean_t
9329 ipsec_opt_present(mblk_t *mp)
9330 {
9331 	uint8_t *optcp, *next_optcp, *opt_endcp;
9332 	struct opthdr *opt;
9333 	struct T_opthdr *topt;
9334 	int opthdr_len;
9335 	t_uscalar_t optname, optlevel;
9336 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9337 	ipsec_req_t *ipsr;
9338 
9339 	/*
9340 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9341 	 * return TRUE.
9342 	 */
9343 
9344 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9345 	opt_endcp = optcp + tor->OPT_length;
9346 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9347 		opthdr_len = sizeof (struct T_opthdr);
9348 	} else {		/* O_OPTMGMT_REQ */
9349 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9350 		opthdr_len = sizeof (struct opthdr);
9351 	}
9352 	for (; optcp < opt_endcp; optcp = next_optcp) {
9353 		if (optcp + opthdr_len > opt_endcp)
9354 			return (B_FALSE);	/* Not enough option header. */
9355 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9356 			topt = (struct T_opthdr *)optcp;
9357 			optlevel = topt->level;
9358 			optname = topt->name;
9359 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9360 		} else {
9361 			opt = (struct opthdr *)optcp;
9362 			optlevel = opt->level;
9363 			optname = opt->name;
9364 			next_optcp = optcp + opthdr_len +
9365 			    _TPI_ALIGN_OPT(opt->len);
9366 		}
9367 		if ((next_optcp < optcp) || /* wraparound pointer space */
9368 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9369 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9370 			return (B_FALSE); /* bad option buffer */
9371 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9372 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9373 			/*
9374 			 * Check to see if it's an all-bypass or all-zeroes
9375 			 * IPsec request.  Don't bother loading IPsec if
9376 			 * the socket doesn't want to use it.  (A good example
9377 			 * is a bypass request.)
9378 			 *
9379 			 * Basically, if any of the non-NEVER bits are set,
9380 			 * load IPsec.
9381 			 */
9382 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9383 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9384 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9385 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9386 			    != 0)
9387 				return (B_TRUE);
9388 		}
9389 	}
9390 	return (B_FALSE);
9391 }
9392 
9393 /*
9394  * If conn is is waiting for ipsec to finish loading, kick it.
9395  */
9396 /* ARGSUSED */
9397 static void
9398 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9399 {
9400 	t_scalar_t	optreq_prim;
9401 	mblk_t		*mp;
9402 	cred_t		*cr;
9403 	int		err = 0;
9404 
9405 	/*
9406 	 * This function is called, after ipsec loading is complete.
9407 	 * Since IP checks exclusively and atomically (i.e it prevents
9408 	 * ipsec load from completing until ip_optcom_req completes)
9409 	 * whether ipsec load is complete, there cannot be a race with IP
9410 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9411 	 */
9412 	mutex_enter(&connp->conn_lock);
9413 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9414 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9415 		mp = connp->conn_ipsec_opt_mp;
9416 		connp->conn_ipsec_opt_mp = NULL;
9417 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9418 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9419 		mutex_exit(&connp->conn_lock);
9420 
9421 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9422 
9423 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9424 		if (optreq_prim == T_OPTMGMT_REQ) {
9425 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9426 			    &ip_opt_obj);
9427 		} else {
9428 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9429 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9430 			    &ip_opt_obj);
9431 		}
9432 		if (err != EINPROGRESS)
9433 			CONN_OPER_PENDING_DONE(connp);
9434 		return;
9435 	}
9436 	mutex_exit(&connp->conn_lock);
9437 }
9438 
9439 /*
9440  * Called from the ipsec_loader thread, outside any perimeter, to tell
9441  * ip qenable any of the queues waiting for the ipsec loader to
9442  * complete.
9443  *
9444  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9445  * are done with this lock held, so it's guaranteed that none of the
9446  * links will change along the way.
9447  */
9448 void
9449 ip_ipsec_load_complete()
9450 {
9451 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9452 }
9453 
9454 /*
9455  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9456  * determines the grp on which it has to become exclusive, queues the mp
9457  * and sq draining restarts the optmgmt
9458  */
9459 static boolean_t
9460 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9461 {
9462 	conn_t *connp;
9463 
9464 	/*
9465 	 * Take IPsec requests and treat them special.
9466 	 */
9467 	if (ipsec_opt_present(mp)) {
9468 		/* First check if IPsec is loaded. */
9469 		mutex_enter(&ipsec_loader_lock);
9470 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9471 			mutex_exit(&ipsec_loader_lock);
9472 			return (B_FALSE);
9473 		}
9474 		connp = Q_TO_CONN(q);
9475 		mutex_enter(&connp->conn_lock);
9476 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9477 
9478 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9479 		connp->conn_ipsec_opt_mp = mp;
9480 		mutex_exit(&connp->conn_lock);
9481 		mutex_exit(&ipsec_loader_lock);
9482 
9483 		ipsec_loader_loadnow();
9484 		return (B_TRUE);
9485 	}
9486 	return (B_FALSE);
9487 }
9488 
9489 /*
9490  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9491  * all of them are copied to the conn_t. If the req is "zero", the policy is
9492  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9493  * fields.
9494  * We keep only the latest setting of the policy and thus policy setting
9495  * is not incremental/cumulative.
9496  *
9497  * Requests to set policies with multiple alternative actions will
9498  * go through a different API.
9499  */
9500 int
9501 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9502 {
9503 	uint_t ah_req = 0;
9504 	uint_t esp_req = 0;
9505 	uint_t se_req = 0;
9506 	ipsec_selkey_t sel;
9507 	ipsec_act_t *actp = NULL;
9508 	uint_t nact;
9509 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9510 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9511 	ipsec_policy_root_t *pr;
9512 	ipsec_policy_head_t *ph;
9513 	int fam;
9514 	boolean_t is_pol_reset;
9515 	int error = 0;
9516 
9517 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9518 
9519 	/*
9520 	 * The IP_SEC_OPT option does not allow variable length parameters,
9521 	 * hence a request cannot be NULL.
9522 	 */
9523 	if (req == NULL)
9524 		return (EINVAL);
9525 
9526 	ah_req = req->ipsr_ah_req;
9527 	esp_req = req->ipsr_esp_req;
9528 	se_req = req->ipsr_self_encap_req;
9529 
9530 	/*
9531 	 * Are we dealing with a request to reset the policy (i.e.
9532 	 * zero requests).
9533 	 */
9534 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9535 	    (esp_req & REQ_MASK) == 0 &&
9536 	    (se_req & REQ_MASK) == 0);
9537 
9538 	if (!is_pol_reset) {
9539 		/*
9540 		 * If we couldn't load IPsec, fail with "protocol
9541 		 * not supported".
9542 		 * IPsec may not have been loaded for a request with zero
9543 		 * policies, so we don't fail in this case.
9544 		 */
9545 		mutex_enter(&ipsec_loader_lock);
9546 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9547 			mutex_exit(&ipsec_loader_lock);
9548 			return (EPROTONOSUPPORT);
9549 		}
9550 		mutex_exit(&ipsec_loader_lock);
9551 
9552 		/*
9553 		 * Test for valid requests. Invalid algorithms
9554 		 * need to be tested by IPSEC code because new
9555 		 * algorithms can be added dynamically.
9556 		 */
9557 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9558 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9559 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9560 			return (EINVAL);
9561 		}
9562 
9563 		/*
9564 		 * Only privileged users can issue these
9565 		 * requests.
9566 		 */
9567 		if (((ah_req & IPSEC_PREF_NEVER) ||
9568 		    (esp_req & IPSEC_PREF_NEVER) ||
9569 		    (se_req & IPSEC_PREF_NEVER)) &&
9570 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9571 			return (EPERM);
9572 		}
9573 
9574 		/*
9575 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9576 		 * are mutually exclusive.
9577 		 */
9578 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9579 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9580 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9581 			/* Both of them are set */
9582 			return (EINVAL);
9583 		}
9584 	}
9585 
9586 	mutex_enter(&connp->conn_lock);
9587 
9588 	/*
9589 	 * If we have already cached policies in ip_bind_connected*(), don't
9590 	 * let them change now. We cache policies for connections
9591 	 * whose src,dst [addr, port] is known.  The exception to this is
9592 	 * tunnels.  Tunnels are allowed to change policies after having
9593 	 * become fully bound.
9594 	 */
9595 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9596 		mutex_exit(&connp->conn_lock);
9597 		return (EINVAL);
9598 	}
9599 
9600 	/*
9601 	 * We have a zero policies, reset the connection policy if already
9602 	 * set. This will cause the connection to inherit the
9603 	 * global policy, if any.
9604 	 */
9605 	if (is_pol_reset) {
9606 		if (connp->conn_policy != NULL) {
9607 			IPPH_REFRELE(connp->conn_policy);
9608 			connp->conn_policy = NULL;
9609 		}
9610 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9611 		connp->conn_in_enforce_policy = B_FALSE;
9612 		connp->conn_out_enforce_policy = B_FALSE;
9613 		mutex_exit(&connp->conn_lock);
9614 		return (0);
9615 	}
9616 
9617 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9618 	if (ph == NULL)
9619 		goto enomem;
9620 
9621 	ipsec_actvec_from_req(req, &actp, &nact);
9622 	if (actp == NULL)
9623 		goto enomem;
9624 
9625 	/*
9626 	 * Always allocate IPv4 policy entries, since they can also
9627 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9628 	 */
9629 	bzero(&sel, sizeof (sel));
9630 	sel.ipsl_valid = IPSL_IPV4;
9631 
9632 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9633 	if (pin4 == NULL)
9634 		goto enomem;
9635 
9636 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9637 	if (pout4 == NULL)
9638 		goto enomem;
9639 
9640 	if (connp->conn_pkt_isv6) {
9641 		/*
9642 		 * We're looking at a v6 socket, also allocate the
9643 		 * v6-specific entries...
9644 		 */
9645 		sel.ipsl_valid = IPSL_IPV6;
9646 		pin6 = ipsec_policy_create(&sel, actp, nact,
9647 		    IPSEC_PRIO_SOCKET);
9648 		if (pin6 == NULL)
9649 			goto enomem;
9650 
9651 		pout6 = ipsec_policy_create(&sel, actp, nact,
9652 		    IPSEC_PRIO_SOCKET);
9653 		if (pout6 == NULL)
9654 			goto enomem;
9655 
9656 		/*
9657 		 * .. and file them away in the right place.
9658 		 */
9659 		fam = IPSEC_AF_V6;
9660 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9661 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9662 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9663 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9664 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9665 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9666 	}
9667 
9668 	ipsec_actvec_free(actp, nact);
9669 
9670 	/*
9671 	 * File the v4 policies.
9672 	 */
9673 	fam = IPSEC_AF_V4;
9674 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9675 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9676 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9677 
9678 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9679 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9680 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9681 
9682 	/*
9683 	 * If the requests need security, set enforce_policy.
9684 	 * If the requests are IPSEC_PREF_NEVER, one should
9685 	 * still set conn_out_enforce_policy so that an ipsec_out
9686 	 * gets attached in ip_wput. This is needed so that
9687 	 * for connections that we don't cache policy in ip_bind,
9688 	 * if global policy matches in ip_wput_attach_policy, we
9689 	 * don't wrongly inherit global policy. Similarly, we need
9690 	 * to set conn_in_enforce_policy also so that we don't verify
9691 	 * policy wrongly.
9692 	 */
9693 	if ((ah_req & REQ_MASK) != 0 ||
9694 	    (esp_req & REQ_MASK) != 0 ||
9695 	    (se_req & REQ_MASK) != 0) {
9696 		connp->conn_in_enforce_policy = B_TRUE;
9697 		connp->conn_out_enforce_policy = B_TRUE;
9698 		connp->conn_flags |= IPCL_CHECK_POLICY;
9699 	}
9700 
9701 	/*
9702 	 * Tunnels are allowed to set policy after having been fully bound.
9703 	 * If that's the case, cache policy here.
9704 	 */
9705 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9706 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9707 
9708 	mutex_exit(&connp->conn_lock);
9709 	return (error);
9710 #undef REQ_MASK
9711 
9712 	/*
9713 	 * Common memory-allocation-failure exit path.
9714 	 */
9715 enomem:
9716 	mutex_exit(&connp->conn_lock);
9717 	if (actp != NULL)
9718 		ipsec_actvec_free(actp, nact);
9719 	if (pin4 != NULL)
9720 		IPPOL_REFRELE(pin4);
9721 	if (pout4 != NULL)
9722 		IPPOL_REFRELE(pout4);
9723 	if (pin6 != NULL)
9724 		IPPOL_REFRELE(pin6);
9725 	if (pout6 != NULL)
9726 		IPPOL_REFRELE(pout6);
9727 	return (ENOMEM);
9728 }
9729 
9730 /*
9731  * Only for options that pass in an IP addr. Currently only V4 options
9732  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9733  * So this function assumes level is IPPROTO_IP
9734  */
9735 int
9736 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9737     mblk_t *first_mp)
9738 {
9739 	ipif_t *ipif = NULL;
9740 	int error;
9741 	ill_t *ill;
9742 	int zoneid;
9743 
9744 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9745 
9746 	if (addr != INADDR_ANY || checkonly) {
9747 		ASSERT(connp != NULL);
9748 		zoneid = IPCL_ZONEID(connp);
9749 		if (option == IP_NEXTHOP) {
9750 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
9751 		} else {
9752 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
9753 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9754 			    &error);
9755 		}
9756 		if (ipif == NULL) {
9757 			if (error == EINPROGRESS)
9758 				return (error);
9759 			else if ((option == IP_MULTICAST_IF) ||
9760 			    (option == IP_NEXTHOP))
9761 				return (EHOSTUNREACH);
9762 			else
9763 				return (EINVAL);
9764 		} else if (checkonly) {
9765 			if (option == IP_MULTICAST_IF) {
9766 				ill = ipif->ipif_ill;
9767 				/* not supported by the virtual network iface */
9768 				if (IS_VNI(ill)) {
9769 					ipif_refrele(ipif);
9770 					return (EINVAL);
9771 				}
9772 			}
9773 			ipif_refrele(ipif);
9774 			return (0);
9775 		}
9776 		ill = ipif->ipif_ill;
9777 		mutex_enter(&connp->conn_lock);
9778 		mutex_enter(&ill->ill_lock);
9779 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9780 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9781 			mutex_exit(&ill->ill_lock);
9782 			mutex_exit(&connp->conn_lock);
9783 			ipif_refrele(ipif);
9784 			return (option == IP_MULTICAST_IF ?
9785 			    EHOSTUNREACH : EINVAL);
9786 		}
9787 	} else {
9788 		mutex_enter(&connp->conn_lock);
9789 	}
9790 
9791 	/* None of the options below are supported on the VNI */
9792 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9793 		mutex_exit(&ill->ill_lock);
9794 		mutex_exit(&connp->conn_lock);
9795 		ipif_refrele(ipif);
9796 		return (EINVAL);
9797 	}
9798 
9799 	switch (option) {
9800 	case IP_DONTFAILOVER_IF:
9801 		/*
9802 		 * This option is used by in.mpathd to ensure
9803 		 * that IPMP probe packets only go out on the
9804 		 * test interfaces. in.mpathd sets this option
9805 		 * on the non-failover interfaces.
9806 		 * For backward compatibility, this option
9807 		 * implicitly sets IP_MULTICAST_IF, as used
9808 		 * be done in bind(), so that ip_wput gets
9809 		 * this ipif to send mcast packets.
9810 		 */
9811 		if (ipif != NULL) {
9812 			ASSERT(addr != INADDR_ANY);
9813 			connp->conn_nofailover_ill = ipif->ipif_ill;
9814 			connp->conn_multicast_ipif = ipif;
9815 		} else {
9816 			ASSERT(addr == INADDR_ANY);
9817 			connp->conn_nofailover_ill = NULL;
9818 			connp->conn_multicast_ipif = NULL;
9819 		}
9820 		break;
9821 
9822 	case IP_MULTICAST_IF:
9823 		connp->conn_multicast_ipif = ipif;
9824 		break;
9825 	case IP_NEXTHOP:
9826 		connp->conn_nexthop_v4 = addr;
9827 		connp->conn_nexthop_set = B_TRUE;
9828 		break;
9829 	}
9830 
9831 	if (ipif != NULL) {
9832 		mutex_exit(&ill->ill_lock);
9833 		mutex_exit(&connp->conn_lock);
9834 		ipif_refrele(ipif);
9835 		return (0);
9836 	}
9837 	mutex_exit(&connp->conn_lock);
9838 	/* We succeded in cleared the option */
9839 	return (0);
9840 }
9841 
9842 /*
9843  * For options that pass in an ifindex specifying the ill. V6 options always
9844  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9845  */
9846 int
9847 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9848     int level, int option, mblk_t *first_mp)
9849 {
9850 	ill_t *ill = NULL;
9851 	int error = 0;
9852 
9853 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9854 	if (ifindex != 0) {
9855 		ASSERT(connp != NULL);
9856 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9857 		    first_mp, ip_restart_optmgmt, &error);
9858 		if (ill != NULL) {
9859 			if (checkonly) {
9860 				/* not supported by the virtual network iface */
9861 				if (IS_VNI(ill)) {
9862 					ill_refrele(ill);
9863 					return (EINVAL);
9864 				}
9865 				ill_refrele(ill);
9866 				return (0);
9867 			}
9868 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9869 			    0, NULL)) {
9870 				ill_refrele(ill);
9871 				ill = NULL;
9872 				mutex_enter(&connp->conn_lock);
9873 				goto setit;
9874 			}
9875 			mutex_enter(&connp->conn_lock);
9876 			mutex_enter(&ill->ill_lock);
9877 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9878 				mutex_exit(&ill->ill_lock);
9879 				mutex_exit(&connp->conn_lock);
9880 				ill_refrele(ill);
9881 				ill = NULL;
9882 				mutex_enter(&connp->conn_lock);
9883 			}
9884 			goto setit;
9885 		} else if (error == EINPROGRESS) {
9886 			return (error);
9887 		} else {
9888 			error = 0;
9889 		}
9890 	}
9891 	mutex_enter(&connp->conn_lock);
9892 setit:
9893 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9894 
9895 	/*
9896 	 * The options below assume that the ILL (if any) transmits and/or
9897 	 * receives traffic. Neither of which is true for the virtual network
9898 	 * interface, so fail setting these on a VNI.
9899 	 */
9900 	if (IS_VNI(ill)) {
9901 		ASSERT(ill != NULL);
9902 		mutex_exit(&ill->ill_lock);
9903 		mutex_exit(&connp->conn_lock);
9904 		ill_refrele(ill);
9905 		return (EINVAL);
9906 	}
9907 
9908 	if (level == IPPROTO_IP) {
9909 		switch (option) {
9910 		case IP_BOUND_IF:
9911 			connp->conn_incoming_ill = ill;
9912 			connp->conn_outgoing_ill = ill;
9913 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9914 			    0 : ifindex;
9915 			break;
9916 
9917 		case IP_XMIT_IF:
9918 			/*
9919 			 * Similar to IP_BOUND_IF, but this only
9920 			 * determines the outgoing interface for
9921 			 * unicast packets. Also no IRE_CACHE entry
9922 			 * is added for the destination of the
9923 			 * outgoing packets. This feature is needed
9924 			 * for mobile IP.
9925 			 */
9926 			connp->conn_xmit_if_ill = ill;
9927 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9928 			    0 : ifindex;
9929 			break;
9930 
9931 		case IP_MULTICAST_IF:
9932 			/*
9933 			 * This option is an internal special. The socket
9934 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9935 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9936 			 * specifies an ifindex and we try first on V6 ill's.
9937 			 * If we don't find one, we they try using on v4 ill's
9938 			 * intenally and we come here.
9939 			 */
9940 			if (!checkonly && ill != NULL) {
9941 				ipif_t	*ipif;
9942 				ipif = ill->ill_ipif;
9943 
9944 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9945 					mutex_exit(&ill->ill_lock);
9946 					mutex_exit(&connp->conn_lock);
9947 					ill_refrele(ill);
9948 					ill = NULL;
9949 					mutex_enter(&connp->conn_lock);
9950 				} else {
9951 					connp->conn_multicast_ipif = ipif;
9952 				}
9953 			}
9954 			break;
9955 		}
9956 	} else {
9957 		switch (option) {
9958 		case IPV6_BOUND_IF:
9959 			connp->conn_incoming_ill = ill;
9960 			connp->conn_outgoing_ill = ill;
9961 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9962 			    0 : ifindex;
9963 			break;
9964 
9965 		case IPV6_BOUND_PIF:
9966 			/*
9967 			 * Limit all transmit to this ill.
9968 			 * Unlike IPV6_BOUND_IF, using this option
9969 			 * prevents load spreading and failover from
9970 			 * happening when the interface is part of the
9971 			 * group. That's why we don't need to remember
9972 			 * the ifindex in orig_bound_ifindex as in
9973 			 * IPV6_BOUND_IF.
9974 			 */
9975 			connp->conn_outgoing_pill = ill;
9976 			break;
9977 
9978 		case IPV6_DONTFAILOVER_IF:
9979 			/*
9980 			 * This option is used by in.mpathd to ensure
9981 			 * that IPMP probe packets only go out on the
9982 			 * test interfaces. in.mpathd sets this option
9983 			 * on the non-failover interfaces.
9984 			 */
9985 			connp->conn_nofailover_ill = ill;
9986 			/*
9987 			 * For backward compatibility, this option
9988 			 * implicitly sets ip_multicast_ill as used in
9989 			 * IP_MULTICAST_IF so that ip_wput gets
9990 			 * this ipif to send mcast packets.
9991 			 */
9992 			connp->conn_multicast_ill = ill;
9993 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9994 			    0 : ifindex;
9995 			break;
9996 
9997 		case IPV6_MULTICAST_IF:
9998 			/*
9999 			 * Set conn_multicast_ill to be the IPv6 ill.
10000 			 * Set conn_multicast_ipif to be an IPv4 ipif
10001 			 * for ifindex to make IPv4 mapped addresses
10002 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10003 			 * Even if no IPv6 ill exists for the ifindex
10004 			 * we need to check for an IPv4 ifindex in order
10005 			 * for this to work with mapped addresses. In that
10006 			 * case only set conn_multicast_ipif.
10007 			 */
10008 			if (!checkonly) {
10009 				if (ifindex == 0) {
10010 					connp->conn_multicast_ill = NULL;
10011 					connp->conn_orig_multicast_ifindex = 0;
10012 					connp->conn_multicast_ipif = NULL;
10013 				} else if (ill != NULL) {
10014 					connp->conn_multicast_ill = ill;
10015 					connp->conn_orig_multicast_ifindex =
10016 					    ifindex;
10017 				}
10018 			}
10019 			break;
10020 		}
10021 	}
10022 
10023 	if (ill != NULL) {
10024 		mutex_exit(&ill->ill_lock);
10025 		mutex_exit(&connp->conn_lock);
10026 		ill_refrele(ill);
10027 		return (0);
10028 	}
10029 	mutex_exit(&connp->conn_lock);
10030 	/*
10031 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10032 	 * locate the ill and could not set the option (ifindex != 0)
10033 	 */
10034 	return (ifindex == 0 ? 0 : EINVAL);
10035 }
10036 
10037 /* This routine sets socket options. */
10038 /* ARGSUSED */
10039 int
10040 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10041     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10042     void *dummy, cred_t *cr, mblk_t *first_mp)
10043 {
10044 	int		*i1 = (int *)invalp;
10045 	conn_t		*connp = Q_TO_CONN(q);
10046 	int		error = 0;
10047 	boolean_t	checkonly;
10048 	ire_t		*ire;
10049 	boolean_t	found;
10050 
10051 	switch (optset_context) {
10052 
10053 	case SETFN_OPTCOM_CHECKONLY:
10054 		checkonly = B_TRUE;
10055 		/*
10056 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10057 		 * inlen != 0 implies value supplied and
10058 		 * 	we have to "pretend" to set it.
10059 		 * inlen == 0 implies that there is no
10060 		 * 	value part in T_CHECK request and just validation
10061 		 * done elsewhere should be enough, we just return here.
10062 		 */
10063 		if (inlen == 0) {
10064 			*outlenp = 0;
10065 			return (0);
10066 		}
10067 		break;
10068 	case SETFN_OPTCOM_NEGOTIATE:
10069 	case SETFN_UD_NEGOTIATE:
10070 	case SETFN_CONN_NEGOTIATE:
10071 		checkonly = B_FALSE;
10072 		break;
10073 	default:
10074 		/*
10075 		 * We should never get here
10076 		 */
10077 		*outlenp = 0;
10078 		return (EINVAL);
10079 	}
10080 
10081 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10082 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10083 
10084 	/*
10085 	 * For fixed length options, no sanity check
10086 	 * of passed in length is done. It is assumed *_optcom_req()
10087 	 * routines do the right thing.
10088 	 */
10089 
10090 	switch (level) {
10091 	case SOL_SOCKET:
10092 		/*
10093 		 * conn_lock protects the bitfields, and is used to
10094 		 * set the fields atomically.
10095 		 */
10096 		switch (name) {
10097 		case SO_BROADCAST:
10098 			if (!checkonly) {
10099 				/* TODO: use value someplace? */
10100 				mutex_enter(&connp->conn_lock);
10101 				connp->conn_broadcast = *i1 ? 1 : 0;
10102 				mutex_exit(&connp->conn_lock);
10103 			}
10104 			break;	/* goto sizeof (int) option return */
10105 		case SO_USELOOPBACK:
10106 			if (!checkonly) {
10107 				/* TODO: use value someplace? */
10108 				mutex_enter(&connp->conn_lock);
10109 				connp->conn_loopback = *i1 ? 1 : 0;
10110 				mutex_exit(&connp->conn_lock);
10111 			}
10112 			break;	/* goto sizeof (int) option return */
10113 		case SO_DONTROUTE:
10114 			if (!checkonly) {
10115 				mutex_enter(&connp->conn_lock);
10116 				connp->conn_dontroute = *i1 ? 1 : 0;
10117 				mutex_exit(&connp->conn_lock);
10118 			}
10119 			break;	/* goto sizeof (int) option return */
10120 		case SO_REUSEADDR:
10121 			if (!checkonly) {
10122 				mutex_enter(&connp->conn_lock);
10123 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10124 				mutex_exit(&connp->conn_lock);
10125 			}
10126 			break;	/* goto sizeof (int) option return */
10127 		case SO_PROTOTYPE:
10128 			if (!checkonly) {
10129 				mutex_enter(&connp->conn_lock);
10130 				connp->conn_proto = *i1;
10131 				mutex_exit(&connp->conn_lock);
10132 			}
10133 			break;	/* goto sizeof (int) option return */
10134 		case SO_ALLZONES:
10135 			if (!checkonly) {
10136 				mutex_enter(&connp->conn_lock);
10137 				if (IPCL_IS_BOUND(connp)) {
10138 					mutex_exit(&connp->conn_lock);
10139 					return (EINVAL);
10140 				}
10141 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10142 				mutex_exit(&connp->conn_lock);
10143 			}
10144 			break;	/* goto sizeof (int) option return */
10145 		case SO_ANON_MLP:
10146 			if (!checkonly) {
10147 				mutex_enter(&connp->conn_lock);
10148 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10149 				mutex_exit(&connp->conn_lock);
10150 			}
10151 			break;	/* goto sizeof (int) option return */
10152 		case SO_MAC_EXEMPT:
10153 			if (secpolicy_net_mac_aware(cr) != 0 ||
10154 			    IPCL_IS_BOUND(connp))
10155 				return (EACCES);
10156 			if (!checkonly) {
10157 				mutex_enter(&connp->conn_lock);
10158 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10159 				mutex_exit(&connp->conn_lock);
10160 			}
10161 			break;	/* goto sizeof (int) option return */
10162 		default:
10163 			/*
10164 			 * "soft" error (negative)
10165 			 * option not handled at this level
10166 			 * Note: Do not modify *outlenp
10167 			 */
10168 			return (-EINVAL);
10169 		}
10170 		break;
10171 	case IPPROTO_IP:
10172 		switch (name) {
10173 		case IP_NEXTHOP:
10174 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10175 				return (EPERM);
10176 			/* FALLTHRU */
10177 		case IP_MULTICAST_IF:
10178 		case IP_DONTFAILOVER_IF: {
10179 			ipaddr_t addr = *i1;
10180 
10181 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10182 			    first_mp);
10183 			if (error != 0)
10184 				return (error);
10185 			break;	/* goto sizeof (int) option return */
10186 		}
10187 
10188 		case IP_MULTICAST_TTL:
10189 			/* Recorded in transport above IP */
10190 			*outvalp = *invalp;
10191 			*outlenp = sizeof (uchar_t);
10192 			return (0);
10193 		case IP_MULTICAST_LOOP:
10194 			if (!checkonly) {
10195 				mutex_enter(&connp->conn_lock);
10196 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10197 				mutex_exit(&connp->conn_lock);
10198 			}
10199 			*outvalp = *invalp;
10200 			*outlenp = sizeof (uchar_t);
10201 			return (0);
10202 		case IP_ADD_MEMBERSHIP:
10203 		case MCAST_JOIN_GROUP:
10204 		case IP_DROP_MEMBERSHIP:
10205 		case MCAST_LEAVE_GROUP: {
10206 			struct ip_mreq *mreqp;
10207 			struct group_req *greqp;
10208 			ire_t *ire;
10209 			boolean_t done = B_FALSE;
10210 			ipaddr_t group, ifaddr;
10211 			struct sockaddr_in *sin;
10212 			uint32_t *ifindexp;
10213 			boolean_t mcast_opt = B_TRUE;
10214 			mcast_record_t fmode;
10215 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10216 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10217 
10218 			switch (name) {
10219 			case IP_ADD_MEMBERSHIP:
10220 				mcast_opt = B_FALSE;
10221 				/* FALLTHRU */
10222 			case MCAST_JOIN_GROUP:
10223 				fmode = MODE_IS_EXCLUDE;
10224 				optfn = ip_opt_add_group;
10225 				break;
10226 
10227 			case IP_DROP_MEMBERSHIP:
10228 				mcast_opt = B_FALSE;
10229 				/* FALLTHRU */
10230 			case MCAST_LEAVE_GROUP:
10231 				fmode = MODE_IS_INCLUDE;
10232 				optfn = ip_opt_delete_group;
10233 				break;
10234 			}
10235 
10236 			if (mcast_opt) {
10237 				greqp = (struct group_req *)i1;
10238 				sin = (struct sockaddr_in *)&greqp->gr_group;
10239 				if (sin->sin_family != AF_INET) {
10240 					*outlenp = 0;
10241 					return (ENOPROTOOPT);
10242 				}
10243 				group = (ipaddr_t)sin->sin_addr.s_addr;
10244 				ifaddr = INADDR_ANY;
10245 				ifindexp = &greqp->gr_interface;
10246 			} else {
10247 				mreqp = (struct ip_mreq *)i1;
10248 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10249 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10250 				ifindexp = NULL;
10251 			}
10252 
10253 			/*
10254 			 * In the multirouting case, we need to replicate
10255 			 * the request on all interfaces that will take part
10256 			 * in replication.  We do so because multirouting is
10257 			 * reflective, thus we will probably receive multi-
10258 			 * casts on those interfaces.
10259 			 * The ip_multirt_apply_membership() succeeds if the
10260 			 * operation succeeds on at least one interface.
10261 			 */
10262 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10263 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10264 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10265 			if (ire != NULL) {
10266 				if (ire->ire_flags & RTF_MULTIRT) {
10267 					error = ip_multirt_apply_membership(
10268 					    optfn, ire, connp, checkonly, group,
10269 					    fmode, INADDR_ANY, first_mp);
10270 					done = B_TRUE;
10271 				}
10272 				ire_refrele(ire);
10273 			}
10274 			if (!done) {
10275 				error = optfn(connp, checkonly, group, ifaddr,
10276 				    ifindexp, fmode, INADDR_ANY, first_mp);
10277 			}
10278 			if (error) {
10279 				/*
10280 				 * EINPROGRESS is a soft error, needs retry
10281 				 * so don't make *outlenp zero.
10282 				 */
10283 				if (error != EINPROGRESS)
10284 					*outlenp = 0;
10285 				return (error);
10286 			}
10287 			/* OK return - copy input buffer into output buffer */
10288 			if (invalp != outvalp) {
10289 				/* don't trust bcopy for identical src/dst */
10290 				bcopy(invalp, outvalp, inlen);
10291 			}
10292 			*outlenp = inlen;
10293 			return (0);
10294 		}
10295 		case IP_BLOCK_SOURCE:
10296 		case IP_UNBLOCK_SOURCE:
10297 		case IP_ADD_SOURCE_MEMBERSHIP:
10298 		case IP_DROP_SOURCE_MEMBERSHIP:
10299 		case MCAST_BLOCK_SOURCE:
10300 		case MCAST_UNBLOCK_SOURCE:
10301 		case MCAST_JOIN_SOURCE_GROUP:
10302 		case MCAST_LEAVE_SOURCE_GROUP: {
10303 			struct ip_mreq_source *imreqp;
10304 			struct group_source_req *gsreqp;
10305 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10306 			uint32_t ifindex = 0;
10307 			mcast_record_t fmode;
10308 			struct sockaddr_in *sin;
10309 			ire_t *ire;
10310 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10311 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10312 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10313 
10314 			switch (name) {
10315 			case IP_BLOCK_SOURCE:
10316 				mcast_opt = B_FALSE;
10317 				/* FALLTHRU */
10318 			case MCAST_BLOCK_SOURCE:
10319 				fmode = MODE_IS_EXCLUDE;
10320 				optfn = ip_opt_add_group;
10321 				break;
10322 
10323 			case IP_UNBLOCK_SOURCE:
10324 				mcast_opt = B_FALSE;
10325 				/* FALLTHRU */
10326 			case MCAST_UNBLOCK_SOURCE:
10327 				fmode = MODE_IS_EXCLUDE;
10328 				optfn = ip_opt_delete_group;
10329 				break;
10330 
10331 			case IP_ADD_SOURCE_MEMBERSHIP:
10332 				mcast_opt = B_FALSE;
10333 				/* FALLTHRU */
10334 			case MCAST_JOIN_SOURCE_GROUP:
10335 				fmode = MODE_IS_INCLUDE;
10336 				optfn = ip_opt_add_group;
10337 				break;
10338 
10339 			case IP_DROP_SOURCE_MEMBERSHIP:
10340 				mcast_opt = B_FALSE;
10341 				/* FALLTHRU */
10342 			case MCAST_LEAVE_SOURCE_GROUP:
10343 				fmode = MODE_IS_INCLUDE;
10344 				optfn = ip_opt_delete_group;
10345 				break;
10346 			}
10347 
10348 			if (mcast_opt) {
10349 				gsreqp = (struct group_source_req *)i1;
10350 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10351 					*outlenp = 0;
10352 					return (ENOPROTOOPT);
10353 				}
10354 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10355 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10356 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10357 				src = (ipaddr_t)sin->sin_addr.s_addr;
10358 				ifindex = gsreqp->gsr_interface;
10359 			} else {
10360 				imreqp = (struct ip_mreq_source *)i1;
10361 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10362 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10363 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10364 			}
10365 
10366 			/*
10367 			 * In the multirouting case, we need to replicate
10368 			 * the request as noted in the mcast cases above.
10369 			 */
10370 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10371 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10372 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10373 			if (ire != NULL) {
10374 				if (ire->ire_flags & RTF_MULTIRT) {
10375 					error = ip_multirt_apply_membership(
10376 					    optfn, ire, connp, checkonly, grp,
10377 					    fmode, src, first_mp);
10378 					done = B_TRUE;
10379 				}
10380 				ire_refrele(ire);
10381 			}
10382 			if (!done) {
10383 				error = optfn(connp, checkonly, grp, ifaddr,
10384 				    &ifindex, fmode, src, first_mp);
10385 			}
10386 			if (error != 0) {
10387 				/*
10388 				 * EINPROGRESS is a soft error, needs retry
10389 				 * so don't make *outlenp zero.
10390 				 */
10391 				if (error != EINPROGRESS)
10392 					*outlenp = 0;
10393 				return (error);
10394 			}
10395 			/* OK return - copy input buffer into output buffer */
10396 			if (invalp != outvalp) {
10397 				bcopy(invalp, outvalp, inlen);
10398 			}
10399 			*outlenp = inlen;
10400 			return (0);
10401 		}
10402 		case IP_SEC_OPT:
10403 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10404 			if (error != 0) {
10405 				*outlenp = 0;
10406 				return (error);
10407 			}
10408 			break;
10409 		case IP_HDRINCL:
10410 		case IP_OPTIONS:
10411 		case T_IP_OPTIONS:
10412 		case IP_TOS:
10413 		case T_IP_TOS:
10414 		case IP_TTL:
10415 		case IP_RECVDSTADDR:
10416 		case IP_RECVOPTS:
10417 			/* OK return - copy input buffer into output buffer */
10418 			if (invalp != outvalp) {
10419 				/* don't trust bcopy for identical src/dst */
10420 				bcopy(invalp, outvalp, inlen);
10421 			}
10422 			*outlenp = inlen;
10423 			return (0);
10424 		case IP_RECVIF:
10425 			/* Retrieve the inbound interface index */
10426 			if (!checkonly) {
10427 				mutex_enter(&connp->conn_lock);
10428 				connp->conn_recvif = *i1 ? 1 : 0;
10429 				mutex_exit(&connp->conn_lock);
10430 			}
10431 			break;	/* goto sizeof (int) option return */
10432 		case IP_RECVSLLA:
10433 			/* Retrieve the source link layer address */
10434 			if (!checkonly) {
10435 				mutex_enter(&connp->conn_lock);
10436 				connp->conn_recvslla = *i1 ? 1 : 0;
10437 				mutex_exit(&connp->conn_lock);
10438 			}
10439 			break;	/* goto sizeof (int) option return */
10440 		case MRT_INIT:
10441 		case MRT_DONE:
10442 		case MRT_ADD_VIF:
10443 		case MRT_DEL_VIF:
10444 		case MRT_ADD_MFC:
10445 		case MRT_DEL_MFC:
10446 		case MRT_ASSERT:
10447 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10448 				*outlenp = 0;
10449 				return (error);
10450 			}
10451 			error = ip_mrouter_set((int)name, q, checkonly,
10452 			    (uchar_t *)invalp, inlen, first_mp);
10453 			if (error) {
10454 				*outlenp = 0;
10455 				return (error);
10456 			}
10457 			/* OK return - copy input buffer into output buffer */
10458 			if (invalp != outvalp) {
10459 				/* don't trust bcopy for identical src/dst */
10460 				bcopy(invalp, outvalp, inlen);
10461 			}
10462 			*outlenp = inlen;
10463 			return (0);
10464 		case IP_BOUND_IF:
10465 		case IP_XMIT_IF:
10466 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10467 			    level, name, first_mp);
10468 			if (error != 0)
10469 				return (error);
10470 			break; 		/* goto sizeof (int) option return */
10471 
10472 		case IP_UNSPEC_SRC:
10473 			/* Allow sending with a zero source address */
10474 			if (!checkonly) {
10475 				mutex_enter(&connp->conn_lock);
10476 				connp->conn_unspec_src = *i1 ? 1 : 0;
10477 				mutex_exit(&connp->conn_lock);
10478 			}
10479 			break;	/* goto sizeof (int) option return */
10480 		default:
10481 			/*
10482 			 * "soft" error (negative)
10483 			 * option not handled at this level
10484 			 * Note: Do not modify *outlenp
10485 			 */
10486 			return (-EINVAL);
10487 		}
10488 		break;
10489 	case IPPROTO_IPV6:
10490 		switch (name) {
10491 		case IPV6_BOUND_IF:
10492 		case IPV6_BOUND_PIF:
10493 		case IPV6_DONTFAILOVER_IF:
10494 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10495 			    level, name, first_mp);
10496 			if (error != 0)
10497 				return (error);
10498 			break; 		/* goto sizeof (int) option return */
10499 
10500 		case IPV6_MULTICAST_IF:
10501 			/*
10502 			 * The only possible errors are EINPROGRESS and
10503 			 * EINVAL. EINPROGRESS will be restarted and is not
10504 			 * a hard error. We call this option on both V4 and V6
10505 			 * If both return EINVAL, then this call returns
10506 			 * EINVAL. If at least one of them succeeds we
10507 			 * return success.
10508 			 */
10509 			found = B_FALSE;
10510 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10511 			    level, name, first_mp);
10512 			if (error == EINPROGRESS)
10513 				return (error);
10514 			if (error == 0)
10515 				found = B_TRUE;
10516 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10517 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10518 			if (error == 0)
10519 				found = B_TRUE;
10520 			if (!found)
10521 				return (error);
10522 			break; 		/* goto sizeof (int) option return */
10523 
10524 		case IPV6_MULTICAST_HOPS:
10525 			/* Recorded in transport above IP */
10526 			break;	/* goto sizeof (int) option return */
10527 		case IPV6_MULTICAST_LOOP:
10528 			if (!checkonly) {
10529 				mutex_enter(&connp->conn_lock);
10530 				connp->conn_multicast_loop = *i1;
10531 				mutex_exit(&connp->conn_lock);
10532 			}
10533 			break;	/* goto sizeof (int) option return */
10534 		case IPV6_JOIN_GROUP:
10535 		case MCAST_JOIN_GROUP:
10536 		case IPV6_LEAVE_GROUP:
10537 		case MCAST_LEAVE_GROUP: {
10538 			struct ipv6_mreq *ip_mreqp;
10539 			struct group_req *greqp;
10540 			ire_t *ire;
10541 			boolean_t done = B_FALSE;
10542 			in6_addr_t groupv6;
10543 			uint32_t ifindex;
10544 			boolean_t mcast_opt = B_TRUE;
10545 			mcast_record_t fmode;
10546 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10547 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10548 
10549 			switch (name) {
10550 			case IPV6_JOIN_GROUP:
10551 				mcast_opt = B_FALSE;
10552 				/* FALLTHRU */
10553 			case MCAST_JOIN_GROUP:
10554 				fmode = MODE_IS_EXCLUDE;
10555 				optfn = ip_opt_add_group_v6;
10556 				break;
10557 
10558 			case IPV6_LEAVE_GROUP:
10559 				mcast_opt = B_FALSE;
10560 				/* FALLTHRU */
10561 			case MCAST_LEAVE_GROUP:
10562 				fmode = MODE_IS_INCLUDE;
10563 				optfn = ip_opt_delete_group_v6;
10564 				break;
10565 			}
10566 
10567 			if (mcast_opt) {
10568 				struct sockaddr_in *sin;
10569 				struct sockaddr_in6 *sin6;
10570 				greqp = (struct group_req *)i1;
10571 				if (greqp->gr_group.ss_family == AF_INET) {
10572 					sin = (struct sockaddr_in *)
10573 					    &(greqp->gr_group);
10574 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10575 					    &groupv6);
10576 				} else {
10577 					sin6 = (struct sockaddr_in6 *)
10578 					    &(greqp->gr_group);
10579 					groupv6 = sin6->sin6_addr;
10580 				}
10581 				ifindex = greqp->gr_interface;
10582 			} else {
10583 				ip_mreqp = (struct ipv6_mreq *)i1;
10584 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10585 				ifindex = ip_mreqp->ipv6mr_interface;
10586 			}
10587 			/*
10588 			 * In the multirouting case, we need to replicate
10589 			 * the request on all interfaces that will take part
10590 			 * in replication.  We do so because multirouting is
10591 			 * reflective, thus we will probably receive multi-
10592 			 * casts on those interfaces.
10593 			 * The ip_multirt_apply_membership_v6() succeeds if
10594 			 * the operation succeeds on at least one interface.
10595 			 */
10596 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10597 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10598 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10599 			if (ire != NULL) {
10600 				if (ire->ire_flags & RTF_MULTIRT) {
10601 					error = ip_multirt_apply_membership_v6(
10602 					    optfn, ire, connp, checkonly,
10603 					    &groupv6, fmode, &ipv6_all_zeros,
10604 					    first_mp);
10605 					done = B_TRUE;
10606 				}
10607 				ire_refrele(ire);
10608 			}
10609 			if (!done) {
10610 				error = optfn(connp, checkonly, &groupv6,
10611 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10612 			}
10613 			if (error) {
10614 				/*
10615 				 * EINPROGRESS is a soft error, needs retry
10616 				 * so don't make *outlenp zero.
10617 				 */
10618 				if (error != EINPROGRESS)
10619 					*outlenp = 0;
10620 				return (error);
10621 			}
10622 			/* OK return - copy input buffer into output buffer */
10623 			if (invalp != outvalp) {
10624 				/* don't trust bcopy for identical src/dst */
10625 				bcopy(invalp, outvalp, inlen);
10626 			}
10627 			*outlenp = inlen;
10628 			return (0);
10629 		}
10630 		case MCAST_BLOCK_SOURCE:
10631 		case MCAST_UNBLOCK_SOURCE:
10632 		case MCAST_JOIN_SOURCE_GROUP:
10633 		case MCAST_LEAVE_SOURCE_GROUP: {
10634 			struct group_source_req *gsreqp;
10635 			in6_addr_t v6grp, v6src;
10636 			uint32_t ifindex;
10637 			mcast_record_t fmode;
10638 			ire_t *ire;
10639 			boolean_t done = B_FALSE;
10640 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10641 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10642 
10643 			switch (name) {
10644 			case MCAST_BLOCK_SOURCE:
10645 				fmode = MODE_IS_EXCLUDE;
10646 				optfn = ip_opt_add_group_v6;
10647 				break;
10648 			case MCAST_UNBLOCK_SOURCE:
10649 				fmode = MODE_IS_EXCLUDE;
10650 				optfn = ip_opt_delete_group_v6;
10651 				break;
10652 			case MCAST_JOIN_SOURCE_GROUP:
10653 				fmode = MODE_IS_INCLUDE;
10654 				optfn = ip_opt_add_group_v6;
10655 				break;
10656 			case MCAST_LEAVE_SOURCE_GROUP:
10657 				fmode = MODE_IS_INCLUDE;
10658 				optfn = ip_opt_delete_group_v6;
10659 				break;
10660 			}
10661 
10662 			gsreqp = (struct group_source_req *)i1;
10663 			ifindex = gsreqp->gsr_interface;
10664 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10665 				struct sockaddr_in *s;
10666 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10667 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10668 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10669 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10670 			} else {
10671 				struct sockaddr_in6 *s6;
10672 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10673 				v6grp = s6->sin6_addr;
10674 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10675 				v6src = s6->sin6_addr;
10676 			}
10677 
10678 			/*
10679 			 * In the multirouting case, we need to replicate
10680 			 * the request as noted in the mcast cases above.
10681 			 */
10682 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10683 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10684 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10685 			if (ire != NULL) {
10686 				if (ire->ire_flags & RTF_MULTIRT) {
10687 					error = ip_multirt_apply_membership_v6(
10688 					    optfn, ire, connp, checkonly,
10689 					    &v6grp, fmode, &v6src, first_mp);
10690 					done = B_TRUE;
10691 				}
10692 				ire_refrele(ire);
10693 			}
10694 			if (!done) {
10695 				error = optfn(connp, checkonly, &v6grp,
10696 				    ifindex, fmode, &v6src, first_mp);
10697 			}
10698 			if (error != 0) {
10699 				/*
10700 				 * EINPROGRESS is a soft error, needs retry
10701 				 * so don't make *outlenp zero.
10702 				 */
10703 				if (error != EINPROGRESS)
10704 					*outlenp = 0;
10705 				return (error);
10706 			}
10707 			/* OK return - copy input buffer into output buffer */
10708 			if (invalp != outvalp) {
10709 				bcopy(invalp, outvalp, inlen);
10710 			}
10711 			*outlenp = inlen;
10712 			return (0);
10713 		}
10714 		case IPV6_UNICAST_HOPS:
10715 			/* Recorded in transport above IP */
10716 			break;	/* goto sizeof (int) option return */
10717 		case IPV6_UNSPEC_SRC:
10718 			/* Allow sending with a zero source address */
10719 			if (!checkonly) {
10720 				mutex_enter(&connp->conn_lock);
10721 				connp->conn_unspec_src = *i1 ? 1 : 0;
10722 				mutex_exit(&connp->conn_lock);
10723 			}
10724 			break;	/* goto sizeof (int) option return */
10725 		case IPV6_RECVPKTINFO:
10726 			if (!checkonly) {
10727 				mutex_enter(&connp->conn_lock);
10728 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10729 				mutex_exit(&connp->conn_lock);
10730 			}
10731 			break;	/* goto sizeof (int) option return */
10732 		case IPV6_RECVTCLASS:
10733 			if (!checkonly) {
10734 				if (*i1 < 0 || *i1 > 1) {
10735 					return (EINVAL);
10736 				}
10737 				mutex_enter(&connp->conn_lock);
10738 				connp->conn_ipv6_recvtclass = *i1;
10739 				mutex_exit(&connp->conn_lock);
10740 			}
10741 			break;
10742 		case IPV6_RECVPATHMTU:
10743 			if (!checkonly) {
10744 				if (*i1 < 0 || *i1 > 1) {
10745 					return (EINVAL);
10746 				}
10747 				mutex_enter(&connp->conn_lock);
10748 				connp->conn_ipv6_recvpathmtu = *i1;
10749 				mutex_exit(&connp->conn_lock);
10750 			}
10751 			break;
10752 		case IPV6_RECVHOPLIMIT:
10753 			if (!checkonly) {
10754 				mutex_enter(&connp->conn_lock);
10755 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10756 				mutex_exit(&connp->conn_lock);
10757 			}
10758 			break;	/* goto sizeof (int) option return */
10759 		case IPV6_RECVHOPOPTS:
10760 			if (!checkonly) {
10761 				mutex_enter(&connp->conn_lock);
10762 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10763 				mutex_exit(&connp->conn_lock);
10764 			}
10765 			break;	/* goto sizeof (int) option return */
10766 		case IPV6_RECVDSTOPTS:
10767 			if (!checkonly) {
10768 				mutex_enter(&connp->conn_lock);
10769 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10770 				mutex_exit(&connp->conn_lock);
10771 			}
10772 			break;	/* goto sizeof (int) option return */
10773 		case IPV6_RECVRTHDR:
10774 			if (!checkonly) {
10775 				mutex_enter(&connp->conn_lock);
10776 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10777 				mutex_exit(&connp->conn_lock);
10778 			}
10779 			break;	/* goto sizeof (int) option return */
10780 		case IPV6_RECVRTHDRDSTOPTS:
10781 			if (!checkonly) {
10782 				mutex_enter(&connp->conn_lock);
10783 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10784 				mutex_exit(&connp->conn_lock);
10785 			}
10786 			break;	/* goto sizeof (int) option return */
10787 		case IPV6_PKTINFO:
10788 			if (inlen == 0)
10789 				return (-EINVAL);	/* clearing option */
10790 			error = ip6_set_pktinfo(cr, connp,
10791 			    (struct in6_pktinfo *)invalp, first_mp);
10792 			if (error != 0)
10793 				*outlenp = 0;
10794 			else
10795 				*outlenp = inlen;
10796 			return (error);
10797 		case IPV6_NEXTHOP: {
10798 			struct sockaddr_in6 *sin6;
10799 
10800 			/* Verify that the nexthop is reachable */
10801 			if (inlen == 0)
10802 				return (-EINVAL);	/* clearing option */
10803 
10804 			sin6 = (struct sockaddr_in6 *)invalp;
10805 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10806 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10807 			    NULL, MATCH_IRE_DEFAULT);
10808 
10809 			if (ire == NULL) {
10810 				*outlenp = 0;
10811 				return (EHOSTUNREACH);
10812 			}
10813 			ire_refrele(ire);
10814 			return (-EINVAL);
10815 		}
10816 		case IPV6_SEC_OPT:
10817 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10818 			if (error != 0) {
10819 				*outlenp = 0;
10820 				return (error);
10821 			}
10822 			break;
10823 		case IPV6_SRC_PREFERENCES: {
10824 			/*
10825 			 * This is implemented strictly in the ip module
10826 			 * (here and in tcp_opt_*() to accomodate tcp
10827 			 * sockets).  Modules above ip pass this option
10828 			 * down here since ip is the only one that needs to
10829 			 * be aware of source address preferences.
10830 			 *
10831 			 * This socket option only affects connected
10832 			 * sockets that haven't already bound to a specific
10833 			 * IPv6 address.  In other words, sockets that
10834 			 * don't call bind() with an address other than the
10835 			 * unspecified address and that call connect().
10836 			 * ip_bind_connected_v6() passes these preferences
10837 			 * to the ipif_select_source_v6() function.
10838 			 */
10839 			if (inlen != sizeof (uint32_t))
10840 				return (EINVAL);
10841 			error = ip6_set_src_preferences(connp,
10842 			    *(uint32_t *)invalp);
10843 			if (error != 0) {
10844 				*outlenp = 0;
10845 				return (error);
10846 			} else {
10847 				*outlenp = sizeof (uint32_t);
10848 			}
10849 			break;
10850 		}
10851 		case IPV6_V6ONLY:
10852 			if (*i1 < 0 || *i1 > 1) {
10853 				return (EINVAL);
10854 			}
10855 			mutex_enter(&connp->conn_lock);
10856 			connp->conn_ipv6_v6only = *i1;
10857 			mutex_exit(&connp->conn_lock);
10858 			break;
10859 		default:
10860 			return (-EINVAL);
10861 		}
10862 		break;
10863 	default:
10864 		/*
10865 		 * "soft" error (negative)
10866 		 * option not handled at this level
10867 		 * Note: Do not modify *outlenp
10868 		 */
10869 		return (-EINVAL);
10870 	}
10871 	/*
10872 	 * Common case of return from an option that is sizeof (int)
10873 	 */
10874 	*(int *)outvalp = *i1;
10875 	*outlenp = sizeof (int);
10876 	return (0);
10877 }
10878 
10879 /*
10880  * This routine gets default values of certain options whose default
10881  * values are maintained by protocol specific code
10882  */
10883 /* ARGSUSED */
10884 int
10885 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10886 {
10887 	int *i1 = (int *)ptr;
10888 
10889 	switch (level) {
10890 	case IPPROTO_IP:
10891 		switch (name) {
10892 		case IP_MULTICAST_TTL:
10893 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10894 			return (sizeof (uchar_t));
10895 		case IP_MULTICAST_LOOP:
10896 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10897 			return (sizeof (uchar_t));
10898 		default:
10899 			return (-1);
10900 		}
10901 	case IPPROTO_IPV6:
10902 		switch (name) {
10903 		case IPV6_UNICAST_HOPS:
10904 			*i1 = ipv6_def_hops;
10905 			return (sizeof (int));
10906 		case IPV6_MULTICAST_HOPS:
10907 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10908 			return (sizeof (int));
10909 		case IPV6_MULTICAST_LOOP:
10910 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10911 			return (sizeof (int));
10912 		case IPV6_V6ONLY:
10913 			*i1 = 1;
10914 			return (sizeof (int));
10915 		default:
10916 			return (-1);
10917 		}
10918 	default:
10919 		return (-1);
10920 	}
10921 	/* NOTREACHED */
10922 }
10923 
10924 /*
10925  * Given a destination address and a pointer to where to put the information
10926  * this routine fills in the mtuinfo.
10927  */
10928 int
10929 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10930     struct ip6_mtuinfo *mtuinfo)
10931 {
10932 	ire_t *ire;
10933 
10934 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10935 		return (-1);
10936 
10937 	bzero(mtuinfo, sizeof (*mtuinfo));
10938 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10939 	mtuinfo->ip6m_addr.sin6_port = port;
10940 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10941 
10942 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10943 	if (ire != NULL) {
10944 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10945 		ire_refrele(ire);
10946 	} else {
10947 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10948 	}
10949 	return (sizeof (struct ip6_mtuinfo));
10950 }
10951 
10952 /*
10953  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10954  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10955  * isn't.  This doesn't matter as the error checking is done properly for the
10956  * other MRT options coming in through ip_opt_set.
10957  */
10958 int
10959 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10960 {
10961 	conn_t		*connp = Q_TO_CONN(q);
10962 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10963 
10964 	switch (level) {
10965 	case IPPROTO_IP:
10966 		switch (name) {
10967 		case MRT_VERSION:
10968 		case MRT_ASSERT:
10969 			(void) ip_mrouter_get(name, q, ptr);
10970 			return (sizeof (int));
10971 		case IP_SEC_OPT:
10972 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10973 		case IP_NEXTHOP:
10974 			if (connp->conn_nexthop_set) {
10975 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10976 				return (sizeof (ipaddr_t));
10977 			} else
10978 				return (0);
10979 		default:
10980 			break;
10981 		}
10982 		break;
10983 	case IPPROTO_IPV6:
10984 		switch (name) {
10985 		case IPV6_SEC_OPT:
10986 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10987 		case IPV6_SRC_PREFERENCES: {
10988 			return (ip6_get_src_preferences(connp,
10989 			    (uint32_t *)ptr));
10990 		}
10991 		case IPV6_V6ONLY:
10992 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10993 			return (sizeof (int));
10994 		case IPV6_PATHMTU:
10995 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10996 				(struct ip6_mtuinfo *)ptr));
10997 		default:
10998 			break;
10999 		}
11000 		break;
11001 	default:
11002 		break;
11003 	}
11004 	return (-1);
11005 }
11006 
11007 /* Named Dispatch routine to get a current value out of our parameter table. */
11008 /* ARGSUSED */
11009 static int
11010 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11011 {
11012 	ipparam_t *ippa = (ipparam_t *)cp;
11013 
11014 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11015 	return (0);
11016 }
11017 
11018 /* ARGSUSED */
11019 static int
11020 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11021 {
11022 
11023 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11024 	return (0);
11025 }
11026 
11027 /*
11028  * Set ip{,6}_forwarding values.  This means walking through all of the
11029  * ill's and toggling their forwarding values.
11030  */
11031 /* ARGSUSED */
11032 static int
11033 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11034 {
11035 	long new_value;
11036 	int *forwarding_value = (int *)cp;
11037 	ill_t *walker;
11038 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11039 	ill_walk_context_t ctx;
11040 
11041 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11042 	    new_value < 0 || new_value > 1) {
11043 		return (EINVAL);
11044 	}
11045 
11046 	*forwarding_value = new_value;
11047 
11048 	/*
11049 	 * Regardless of the current value of ip_forwarding, set all per-ill
11050 	 * values of ip_forwarding to the value being set.
11051 	 *
11052 	 * Bring all the ill's up to date with the new global value.
11053 	 */
11054 	rw_enter(&ill_g_lock, RW_READER);
11055 
11056 	if (isv6)
11057 		walker = ILL_START_WALK_V6(&ctx);
11058 	else
11059 		walker = ILL_START_WALK_V4(&ctx);
11060 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11061 		(void) ill_forward_set(q, mp, (new_value != 0),
11062 		    (caddr_t)walker);
11063 	}
11064 	rw_exit(&ill_g_lock);
11065 
11066 	return (0);
11067 }
11068 
11069 /*
11070  * Walk through the param array specified registering each element with the
11071  * Named Dispatch handler. This is called only during init. So it is ok
11072  * not to acquire any locks
11073  */
11074 static boolean_t
11075 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11076     ipndp_t *ipnd, size_t ipnd_cnt)
11077 {
11078 	for (; ippa_cnt-- > 0; ippa++) {
11079 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11080 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11081 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11082 				nd_free(&ip_g_nd);
11083 				return (B_FALSE);
11084 			}
11085 		}
11086 	}
11087 
11088 	for (; ipnd_cnt-- > 0; ipnd++) {
11089 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11090 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11091 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11092 			    ipnd->ip_ndp_data)) {
11093 				nd_free(&ip_g_nd);
11094 				return (B_FALSE);
11095 			}
11096 		}
11097 	}
11098 
11099 	return (B_TRUE);
11100 }
11101 
11102 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11103 /* ARGSUSED */
11104 static int
11105 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11106 {
11107 	long		new_value;
11108 	ipparam_t	*ippa = (ipparam_t *)cp;
11109 
11110 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11111 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11112 		return (EINVAL);
11113 	}
11114 	ippa->ip_param_value = new_value;
11115 	return (0);
11116 }
11117 
11118 /*
11119  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11120  * When an ipf is passed here for the first time, if
11121  * we already have in-order fragments on the queue, we convert from the fast-
11122  * path reassembly scheme to the hard-case scheme.  From then on, additional
11123  * fragments are reassembled here.  We keep track of the start and end offsets
11124  * of each piece, and the number of holes in the chain.  When the hole count
11125  * goes to zero, we are done!
11126  *
11127  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11128  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11129  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11130  * after the call to ip_reassemble().
11131  */
11132 int
11133 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11134     size_t msg_len)
11135 {
11136 	uint_t	end;
11137 	mblk_t	*next_mp;
11138 	mblk_t	*mp1;
11139 	uint_t	offset;
11140 	boolean_t incr_dups = B_TRUE;
11141 	boolean_t offset_zero_seen = B_FALSE;
11142 	boolean_t pkt_boundary_checked = B_FALSE;
11143 
11144 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11145 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11146 
11147 	/* Add in byte count */
11148 	ipf->ipf_count += msg_len;
11149 	if (ipf->ipf_end) {
11150 		/*
11151 		 * We were part way through in-order reassembly, but now there
11152 		 * is a hole.  We walk through messages already queued, and
11153 		 * mark them for hard case reassembly.  We know that up till
11154 		 * now they were in order starting from offset zero.
11155 		 */
11156 		offset = 0;
11157 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11158 			IP_REASS_SET_START(mp1, offset);
11159 			if (offset == 0) {
11160 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11161 				offset = -ipf->ipf_nf_hdr_len;
11162 			}
11163 			offset += mp1->b_wptr - mp1->b_rptr;
11164 			IP_REASS_SET_END(mp1, offset);
11165 		}
11166 		/* One hole at the end. */
11167 		ipf->ipf_hole_cnt = 1;
11168 		/* Brand it as a hard case, forever. */
11169 		ipf->ipf_end = 0;
11170 	}
11171 	/* Walk through all the new pieces. */
11172 	do {
11173 		end = start + (mp->b_wptr - mp->b_rptr);
11174 		/*
11175 		 * If start is 0, decrease 'end' only for the first mblk of
11176 		 * the fragment. Otherwise 'end' can get wrong value in the
11177 		 * second pass of the loop if first mblk is exactly the
11178 		 * size of ipf_nf_hdr_len.
11179 		 */
11180 		if (start == 0 && !offset_zero_seen) {
11181 			/* First segment */
11182 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11183 			end -= ipf->ipf_nf_hdr_len;
11184 			offset_zero_seen = B_TRUE;
11185 		}
11186 		next_mp = mp->b_cont;
11187 		/*
11188 		 * We are checking to see if there is any interesing data
11189 		 * to process.  If there isn't and the mblk isn't the
11190 		 * one which carries the unfragmentable header then we
11191 		 * drop it.  It's possible to have just the unfragmentable
11192 		 * header come through without any data.  That needs to be
11193 		 * saved.
11194 		 *
11195 		 * If the assert at the top of this function holds then the
11196 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11197 		 * is infrequently traveled enough that the test is left in
11198 		 * to protect against future code changes which break that
11199 		 * invariant.
11200 		 */
11201 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11202 			/* Empty.  Blast it. */
11203 			IP_REASS_SET_START(mp, 0);
11204 			IP_REASS_SET_END(mp, 0);
11205 			/*
11206 			 * If the ipf points to the mblk we are about to free,
11207 			 * update ipf to point to the next mblk (or NULL
11208 			 * if none).
11209 			 */
11210 			if (ipf->ipf_mp->b_cont == mp)
11211 				ipf->ipf_mp->b_cont = next_mp;
11212 			freeb(mp);
11213 			continue;
11214 		}
11215 		mp->b_cont = NULL;
11216 		IP_REASS_SET_START(mp, start);
11217 		IP_REASS_SET_END(mp, end);
11218 		if (!ipf->ipf_tail_mp) {
11219 			ipf->ipf_tail_mp = mp;
11220 			ipf->ipf_mp->b_cont = mp;
11221 			if (start == 0 || !more) {
11222 				ipf->ipf_hole_cnt = 1;
11223 				/*
11224 				 * if the first fragment comes in more than one
11225 				 * mblk, this loop will be executed for each
11226 				 * mblk. Need to adjust hole count so exiting
11227 				 * this routine will leave hole count at 1.
11228 				 */
11229 				if (next_mp)
11230 					ipf->ipf_hole_cnt++;
11231 			} else
11232 				ipf->ipf_hole_cnt = 2;
11233 			continue;
11234 		} else if (ipf->ipf_last_frag_seen && !more &&
11235 			    !pkt_boundary_checked) {
11236 			/*
11237 			 * We check datagram boundary only if this fragment
11238 			 * claims to be the last fragment and we have seen a
11239 			 * last fragment in the past too. We do this only
11240 			 * once for a given fragment.
11241 			 *
11242 			 * start cannot be 0 here as fragments with start=0
11243 			 * and MF=0 gets handled as a complete packet. These
11244 			 * fragments should not reach here.
11245 			 */
11246 
11247 			if (start + msgdsize(mp) !=
11248 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11249 				/*
11250 				 * We have two fragments both of which claim
11251 				 * to be the last fragment but gives conflicting
11252 				 * information about the whole datagram size.
11253 				 * Something fishy is going on. Drop the
11254 				 * fragment and free up the reassembly list.
11255 				 */
11256 				return (IP_REASS_FAILED);
11257 			}
11258 
11259 			/*
11260 			 * We shouldn't come to this code block again for this
11261 			 * particular fragment.
11262 			 */
11263 			pkt_boundary_checked = B_TRUE;
11264 		}
11265 
11266 		/* New stuff at or beyond tail? */
11267 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11268 		if (start >= offset) {
11269 			if (ipf->ipf_last_frag_seen) {
11270 				/* current fragment is beyond last fragment */
11271 				return (IP_REASS_FAILED);
11272 			}
11273 			/* Link it on end. */
11274 			ipf->ipf_tail_mp->b_cont = mp;
11275 			ipf->ipf_tail_mp = mp;
11276 			if (more) {
11277 				if (start != offset)
11278 					ipf->ipf_hole_cnt++;
11279 			} else if (start == offset && next_mp == NULL)
11280 					ipf->ipf_hole_cnt--;
11281 			continue;
11282 		}
11283 		mp1 = ipf->ipf_mp->b_cont;
11284 		offset = IP_REASS_START(mp1);
11285 		/* New stuff at the front? */
11286 		if (start < offset) {
11287 			if (start == 0) {
11288 				if (end >= offset) {
11289 					/* Nailed the hole at the begining. */
11290 					ipf->ipf_hole_cnt--;
11291 				}
11292 			} else if (end < offset) {
11293 				/*
11294 				 * A hole, stuff, and a hole where there used
11295 				 * to be just a hole.
11296 				 */
11297 				ipf->ipf_hole_cnt++;
11298 			}
11299 			mp->b_cont = mp1;
11300 			/* Check for overlap. */
11301 			while (end > offset) {
11302 				if (end < IP_REASS_END(mp1)) {
11303 					mp->b_wptr -= end - offset;
11304 					IP_REASS_SET_END(mp, offset);
11305 					if (ill->ill_isv6) {
11306 						BUMP_MIB(ill->ill_ip6_mib,
11307 						    ipv6ReasmPartDups);
11308 					} else {
11309 						BUMP_MIB(&ip_mib,
11310 						    ipReasmPartDups);
11311 					}
11312 					break;
11313 				}
11314 				/* Did we cover another hole? */
11315 				if ((mp1->b_cont &&
11316 				    IP_REASS_END(mp1) !=
11317 				    IP_REASS_START(mp1->b_cont) &&
11318 				    end >= IP_REASS_START(mp1->b_cont)) ||
11319 				    (!ipf->ipf_last_frag_seen && !more)) {
11320 					ipf->ipf_hole_cnt--;
11321 				}
11322 				/* Clip out mp1. */
11323 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11324 					/*
11325 					 * After clipping out mp1, this guy
11326 					 * is now hanging off the end.
11327 					 */
11328 					ipf->ipf_tail_mp = mp;
11329 				}
11330 				IP_REASS_SET_START(mp1, 0);
11331 				IP_REASS_SET_END(mp1, 0);
11332 				/* Subtract byte count */
11333 				ipf->ipf_count -= mp1->b_datap->db_lim -
11334 				    mp1->b_datap->db_base;
11335 				freeb(mp1);
11336 				if (ill->ill_isv6) {
11337 					BUMP_MIB(ill->ill_ip6_mib,
11338 					    ipv6ReasmPartDups);
11339 				} else {
11340 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11341 				}
11342 				mp1 = mp->b_cont;
11343 				if (!mp1)
11344 					break;
11345 				offset = IP_REASS_START(mp1);
11346 			}
11347 			ipf->ipf_mp->b_cont = mp;
11348 			continue;
11349 		}
11350 		/*
11351 		 * The new piece starts somewhere between the start of the head
11352 		 * and before the end of the tail.
11353 		 */
11354 		for (; mp1; mp1 = mp1->b_cont) {
11355 			offset = IP_REASS_END(mp1);
11356 			if (start < offset) {
11357 				if (end <= offset) {
11358 					/* Nothing new. */
11359 					IP_REASS_SET_START(mp, 0);
11360 					IP_REASS_SET_END(mp, 0);
11361 					/* Subtract byte count */
11362 					ipf->ipf_count -= mp->b_datap->db_lim -
11363 					    mp->b_datap->db_base;
11364 					if (incr_dups) {
11365 						ipf->ipf_num_dups++;
11366 						incr_dups = B_FALSE;
11367 					}
11368 					freeb(mp);
11369 					if (ill->ill_isv6) {
11370 						BUMP_MIB(ill->ill_ip6_mib,
11371 						    ipv6ReasmDuplicates);
11372 					} else {
11373 						BUMP_MIB(&ip_mib,
11374 						    ipReasmDuplicates);
11375 					}
11376 					break;
11377 				}
11378 				/*
11379 				 * Trim redundant stuff off beginning of new
11380 				 * piece.
11381 				 */
11382 				IP_REASS_SET_START(mp, offset);
11383 				mp->b_rptr += offset - start;
11384 				if (ill->ill_isv6) {
11385 					BUMP_MIB(ill->ill_ip6_mib,
11386 					    ipv6ReasmPartDups);
11387 				} else {
11388 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11389 				}
11390 				start = offset;
11391 				if (!mp1->b_cont) {
11392 					/*
11393 					 * After trimming, this guy is now
11394 					 * hanging off the end.
11395 					 */
11396 					mp1->b_cont = mp;
11397 					ipf->ipf_tail_mp = mp;
11398 					if (!more) {
11399 						ipf->ipf_hole_cnt--;
11400 					}
11401 					break;
11402 				}
11403 			}
11404 			if (start >= IP_REASS_START(mp1->b_cont))
11405 				continue;
11406 			/* Fill a hole */
11407 			if (start > offset)
11408 				ipf->ipf_hole_cnt++;
11409 			mp->b_cont = mp1->b_cont;
11410 			mp1->b_cont = mp;
11411 			mp1 = mp->b_cont;
11412 			offset = IP_REASS_START(mp1);
11413 			if (end >= offset) {
11414 				ipf->ipf_hole_cnt--;
11415 				/* Check for overlap. */
11416 				while (end > offset) {
11417 					if (end < IP_REASS_END(mp1)) {
11418 						mp->b_wptr -= end - offset;
11419 						IP_REASS_SET_END(mp, offset);
11420 						/*
11421 						 * TODO we might bump
11422 						 * this up twice if there is
11423 						 * overlap at both ends.
11424 						 */
11425 						if (ill->ill_isv6) {
11426 							BUMP_MIB(
11427 							    ill->ill_ip6_mib,
11428 							    ipv6ReasmPartDups);
11429 						} else {
11430 							BUMP_MIB(&ip_mib,
11431 							    ipReasmPartDups);
11432 						}
11433 						break;
11434 					}
11435 					/* Did we cover another hole? */
11436 					if ((mp1->b_cont &&
11437 					    IP_REASS_END(mp1)
11438 					    != IP_REASS_START(mp1->b_cont) &&
11439 					    end >=
11440 					    IP_REASS_START(mp1->b_cont)) ||
11441 					    (!ipf->ipf_last_frag_seen &&
11442 					    !more)) {
11443 						ipf->ipf_hole_cnt--;
11444 					}
11445 					/* Clip out mp1. */
11446 					if ((mp->b_cont = mp1->b_cont) ==
11447 					    NULL) {
11448 						/*
11449 						 * After clipping out mp1,
11450 						 * this guy is now hanging
11451 						 * off the end.
11452 						 */
11453 						ipf->ipf_tail_mp = mp;
11454 					}
11455 					IP_REASS_SET_START(mp1, 0);
11456 					IP_REASS_SET_END(mp1, 0);
11457 					/* Subtract byte count */
11458 					ipf->ipf_count -=
11459 					    mp1->b_datap->db_lim -
11460 					    mp1->b_datap->db_base;
11461 					freeb(mp1);
11462 					if (ill->ill_isv6) {
11463 						BUMP_MIB(ill->ill_ip6_mib,
11464 						    ipv6ReasmPartDups);
11465 					} else {
11466 						BUMP_MIB(&ip_mib,
11467 						    ipReasmPartDups);
11468 					}
11469 					mp1 = mp->b_cont;
11470 					if (!mp1)
11471 						break;
11472 					offset = IP_REASS_START(mp1);
11473 				}
11474 			}
11475 			break;
11476 		}
11477 	} while (start = end, mp = next_mp);
11478 
11479 	/* Fragment just processed could be the last one. Remember this fact */
11480 	if (!more)
11481 		ipf->ipf_last_frag_seen = B_TRUE;
11482 
11483 	/* Still got holes? */
11484 	if (ipf->ipf_hole_cnt)
11485 		return (IP_REASS_PARTIAL);
11486 	/* Clean up overloaded fields to avoid upstream disasters. */
11487 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11488 		IP_REASS_SET_START(mp1, 0);
11489 		IP_REASS_SET_END(mp1, 0);
11490 	}
11491 	return (IP_REASS_COMPLETE);
11492 }
11493 
11494 /*
11495  * ipsec processing for the fast path, used for input UDP Packets
11496  */
11497 static boolean_t
11498 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11499     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11500 {
11501 	uint32_t	ill_index;
11502 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11503 
11504 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11505 	/* The ill_index of the incoming ILL */
11506 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11507 
11508 	/* pass packet up to the transport */
11509 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11510 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11511 		    NULL, mctl_present);
11512 		if (*first_mpp == NULL) {
11513 			return (B_FALSE);
11514 		}
11515 	}
11516 
11517 	/* Initiate IPPF processing for fastpath UDP */
11518 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11519 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11520 		if (*mpp == NULL) {
11521 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11522 			    "deferred/dropped during IPPF processing\n"));
11523 			return (B_FALSE);
11524 		}
11525 	}
11526 	/*
11527 	 * We make the checks as below since we are in the fast path
11528 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11529 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11530 	 */
11531 	if (connp->conn_recvif || connp->conn_recvslla ||
11532 	    connp->conn_ipv6_recvpktinfo) {
11533 		if (connp->conn_recvif ||
11534 		    connp->conn_ipv6_recvpktinfo) {
11535 			in_flags = IPF_RECVIF;
11536 		}
11537 		if (connp->conn_recvslla) {
11538 			in_flags |= IPF_RECVSLLA;
11539 		}
11540 		/*
11541 		 * since in_flags are being set ill will be
11542 		 * referenced in ip_add_info, so it better not
11543 		 * be NULL.
11544 		 */
11545 		/*
11546 		 * the actual data will be contained in b_cont
11547 		 * upon successful return of the following call.
11548 		 * If the call fails then the original mblk is
11549 		 * returned.
11550 		 */
11551 		*mpp = ip_add_info(*mpp, ill, in_flags);
11552 	}
11553 
11554 	return (B_TRUE);
11555 }
11556 
11557 /*
11558  * Fragmentation reassembly.  Each ILL has a hash table for
11559  * queuing packets undergoing reassembly for all IPIFs
11560  * associated with the ILL.  The hash is based on the packet
11561  * IP ident field.  The ILL frag hash table was allocated
11562  * as a timer block at the time the ILL was created.  Whenever
11563  * there is anything on the reassembly queue, the timer will
11564  * be running.  Returns B_TRUE if successful else B_FALSE;
11565  * frees mp on failure.
11566  */
11567 static boolean_t
11568 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11569     uint32_t *cksum_val, uint16_t *cksum_flags)
11570 {
11571 	uint32_t	frag_offset_flags;
11572 	ill_t		*ill = (ill_t *)q->q_ptr;
11573 	mblk_t		*mp = *mpp;
11574 	mblk_t		*t_mp;
11575 	ipaddr_t	dst;
11576 	uint8_t		proto = ipha->ipha_protocol;
11577 	uint32_t	sum_val;
11578 	uint16_t	sum_flags;
11579 	ipf_t		*ipf;
11580 	ipf_t		**ipfp;
11581 	ipfb_t		*ipfb;
11582 	uint16_t	ident;
11583 	uint32_t	offset;
11584 	ipaddr_t	src;
11585 	uint_t		hdr_length;
11586 	uint32_t	end;
11587 	mblk_t		*mp1;
11588 	mblk_t		*tail_mp;
11589 	size_t		count;
11590 	size_t		msg_len;
11591 	uint8_t		ecn_info = 0;
11592 	uint32_t	packet_size;
11593 	boolean_t	pruned = B_FALSE;
11594 
11595 	if (cksum_val != NULL)
11596 		*cksum_val = 0;
11597 	if (cksum_flags != NULL)
11598 		*cksum_flags = 0;
11599 
11600 	/*
11601 	 * Drop the fragmented as early as possible, if
11602 	 * we don't have resource(s) to re-assemble.
11603 	 */
11604 	if (ip_reass_queue_bytes == 0) {
11605 		freemsg(mp);
11606 		return (B_FALSE);
11607 	}
11608 
11609 	/* Check for fragmentation offset; return if there's none */
11610 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11611 	    (IPH_MF | IPH_OFFSET)) == 0)
11612 		return (B_TRUE);
11613 
11614 	/*
11615 	 * We utilize hardware computed checksum info only for UDP since
11616 	 * IP fragmentation is a normal occurence for the protocol.  In
11617 	 * addition, checksum offload support for IP fragments carrying
11618 	 * UDP payload is commonly implemented across network adapters.
11619 	 */
11620 	ASSERT(ill != NULL);
11621 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11622 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11623 		mblk_t *mp1 = mp->b_cont;
11624 		int32_t len;
11625 
11626 		/* Record checksum information from the packet */
11627 		sum_val = (uint32_t)DB_CKSUM16(mp);
11628 		sum_flags = DB_CKSUMFLAGS(mp);
11629 
11630 		/* IP payload offset from beginning of mblk */
11631 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11632 
11633 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11634 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11635 		    offset >= DB_CKSUMSTART(mp) &&
11636 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11637 			uint32_t adj;
11638 			/*
11639 			 * Partial checksum has been calculated by hardware
11640 			 * and attached to the packet; in addition, any
11641 			 * prepended extraneous data is even byte aligned.
11642 			 * If any such data exists, we adjust the checksum;
11643 			 * this would also handle any postpended data.
11644 			 */
11645 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11646 			    mp, mp1, len, adj);
11647 
11648 			/* One's complement subtract extraneous checksum */
11649 			if (adj >= sum_val)
11650 				sum_val = ~(adj - sum_val) & 0xFFFF;
11651 			else
11652 				sum_val -= adj;
11653 		}
11654 	} else {
11655 		sum_val = 0;
11656 		sum_flags = 0;
11657 	}
11658 
11659 	/* Clear hardware checksumming flag */
11660 	DB_CKSUMFLAGS(mp) = 0;
11661 
11662 	ident = ipha->ipha_ident;
11663 	offset = (frag_offset_flags << 3) & 0xFFFF;
11664 	src = ipha->ipha_src;
11665 	dst = ipha->ipha_dst;
11666 	hdr_length = IPH_HDR_LENGTH(ipha);
11667 	end = ntohs(ipha->ipha_length) - hdr_length;
11668 
11669 	/* If end == 0 then we have a packet with no data, so just free it */
11670 	if (end == 0) {
11671 		freemsg(mp);
11672 		return (B_FALSE);
11673 	}
11674 
11675 	/* Record the ECN field info. */
11676 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11677 	if (offset != 0) {
11678 		/*
11679 		 * If this isn't the first piece, strip the header, and
11680 		 * add the offset to the end value.
11681 		 */
11682 		mp->b_rptr += hdr_length;
11683 		end += offset;
11684 	}
11685 
11686 	msg_len = MBLKSIZE(mp);
11687 	tail_mp = mp;
11688 	while (tail_mp->b_cont != NULL) {
11689 		tail_mp = tail_mp->b_cont;
11690 		msg_len += MBLKSIZE(tail_mp);
11691 	}
11692 
11693 	/* If the reassembly list for this ILL will get too big, prune it */
11694 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11695 	    ip_reass_queue_bytes) {
11696 		ill_frag_prune(ill,
11697 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11698 		    (ip_reass_queue_bytes - msg_len));
11699 		pruned = B_TRUE;
11700 	}
11701 
11702 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11703 	mutex_enter(&ipfb->ipfb_lock);
11704 
11705 	ipfp = &ipfb->ipfb_ipf;
11706 	/* Try to find an existing fragment queue for this packet. */
11707 	for (;;) {
11708 		ipf = ipfp[0];
11709 		if (ipf != NULL) {
11710 			/*
11711 			 * It has to match on ident and src/dst address.
11712 			 */
11713 			if (ipf->ipf_ident == ident &&
11714 			    ipf->ipf_src == src &&
11715 			    ipf->ipf_dst == dst &&
11716 			    ipf->ipf_protocol == proto) {
11717 				/*
11718 				 * If we have received too many
11719 				 * duplicate fragments for this packet
11720 				 * free it.
11721 				 */
11722 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11723 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11724 					freemsg(mp);
11725 					mutex_exit(&ipfb->ipfb_lock);
11726 					return (B_FALSE);
11727 				}
11728 				/* Found it. */
11729 				break;
11730 			}
11731 			ipfp = &ipf->ipf_hash_next;
11732 			continue;
11733 		}
11734 
11735 		/*
11736 		 * If we pruned the list, do we want to store this new
11737 		 * fragment?. We apply an optimization here based on the
11738 		 * fact that most fragments will be received in order.
11739 		 * So if the offset of this incoming fragment is zero,
11740 		 * it is the first fragment of a new packet. We will
11741 		 * keep it.  Otherwise drop the fragment, as we have
11742 		 * probably pruned the packet already (since the
11743 		 * packet cannot be found).
11744 		 */
11745 		if (pruned && offset != 0) {
11746 			mutex_exit(&ipfb->ipfb_lock);
11747 			freemsg(mp);
11748 			return (B_FALSE);
11749 		}
11750 
11751 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11752 			/*
11753 			 * Too many fragmented packets in this hash
11754 			 * bucket. Free the oldest.
11755 			 */
11756 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11757 		}
11758 
11759 		/* New guy.  Allocate a frag message. */
11760 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11761 		if (mp1 == NULL) {
11762 			BUMP_MIB(&ip_mib, ipInDiscards);
11763 			freemsg(mp);
11764 reass_done:
11765 			mutex_exit(&ipfb->ipfb_lock);
11766 			return (B_FALSE);
11767 		}
11768 
11769 
11770 		BUMP_MIB(&ip_mib, ipReasmReqds);
11771 		mp1->b_cont = mp;
11772 
11773 		/* Initialize the fragment header. */
11774 		ipf = (ipf_t *)mp1->b_rptr;
11775 		ipf->ipf_mp = mp1;
11776 		ipf->ipf_ptphn = ipfp;
11777 		ipfp[0] = ipf;
11778 		ipf->ipf_hash_next = NULL;
11779 		ipf->ipf_ident = ident;
11780 		ipf->ipf_protocol = proto;
11781 		ipf->ipf_src = src;
11782 		ipf->ipf_dst = dst;
11783 		ipf->ipf_nf_hdr_len = 0;
11784 		/* Record reassembly start time. */
11785 		ipf->ipf_timestamp = gethrestime_sec();
11786 		/* Record ipf generation and account for frag header */
11787 		ipf->ipf_gen = ill->ill_ipf_gen++;
11788 		ipf->ipf_count = MBLKSIZE(mp1);
11789 		ipf->ipf_last_frag_seen = B_FALSE;
11790 		ipf->ipf_ecn = ecn_info;
11791 		ipf->ipf_num_dups = 0;
11792 		ipfb->ipfb_frag_pkts++;
11793 		ipf->ipf_checksum = 0;
11794 		ipf->ipf_checksum_flags = 0;
11795 
11796 		/* Store checksum value in fragment header */
11797 		if (sum_flags != 0) {
11798 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11799 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11800 			ipf->ipf_checksum = sum_val;
11801 			ipf->ipf_checksum_flags = sum_flags;
11802 		}
11803 
11804 		/*
11805 		 * We handle reassembly two ways.  In the easy case,
11806 		 * where all the fragments show up in order, we do
11807 		 * minimal bookkeeping, and just clip new pieces on
11808 		 * the end.  If we ever see a hole, then we go off
11809 		 * to ip_reassemble which has to mark the pieces and
11810 		 * keep track of the number of holes, etc.  Obviously,
11811 		 * the point of having both mechanisms is so we can
11812 		 * handle the easy case as efficiently as possible.
11813 		 */
11814 		if (offset == 0) {
11815 			/* Easy case, in-order reassembly so far. */
11816 			ipf->ipf_count += msg_len;
11817 			ipf->ipf_tail_mp = tail_mp;
11818 			/*
11819 			 * Keep track of next expected offset in
11820 			 * ipf_end.
11821 			 */
11822 			ipf->ipf_end = end;
11823 			ipf->ipf_nf_hdr_len = hdr_length;
11824 		} else {
11825 			/* Hard case, hole at the beginning. */
11826 			ipf->ipf_tail_mp = NULL;
11827 			/*
11828 			 * ipf_end == 0 means that we have given up
11829 			 * on easy reassembly.
11830 			 */
11831 			ipf->ipf_end = 0;
11832 
11833 			/* Forget checksum offload from now on */
11834 			ipf->ipf_checksum_flags = 0;
11835 
11836 			/*
11837 			 * ipf_hole_cnt is set by ip_reassemble.
11838 			 * ipf_count is updated by ip_reassemble.
11839 			 * No need to check for return value here
11840 			 * as we don't expect reassembly to complete
11841 			 * or fail for the first fragment itself.
11842 			 */
11843 			(void) ip_reassemble(mp, ipf,
11844 			    (frag_offset_flags & IPH_OFFSET) << 3,
11845 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11846 		}
11847 		/* Update per ipfb and ill byte counts */
11848 		ipfb->ipfb_count += ipf->ipf_count;
11849 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11850 		ill->ill_frag_count += ipf->ipf_count;
11851 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11852 		/* If the frag timer wasn't already going, start it. */
11853 		mutex_enter(&ill->ill_lock);
11854 		ill_frag_timer_start(ill);
11855 		mutex_exit(&ill->ill_lock);
11856 		goto reass_done;
11857 	}
11858 
11859 	/*
11860 	 * If the packet's flag has changed (it could be coming up
11861 	 * from an interface different than the previous, therefore
11862 	 * possibly different checksum capability), then forget about
11863 	 * any stored checksum states.  Otherwise add the value to
11864 	 * the existing one stored in the fragment header.
11865 	 */
11866 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11867 		sum_val += ipf->ipf_checksum;
11868 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11869 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11870 		ipf->ipf_checksum = sum_val;
11871 	} else if (ipf->ipf_checksum_flags != 0) {
11872 		/* Forget checksum offload from now on */
11873 		ipf->ipf_checksum_flags = 0;
11874 	}
11875 
11876 	/*
11877 	 * We have a new piece of a datagram which is already being
11878 	 * reassembled.  Update the ECN info if all IP fragments
11879 	 * are ECN capable.  If there is one which is not, clear
11880 	 * all the info.  If there is at least one which has CE
11881 	 * code point, IP needs to report that up to transport.
11882 	 */
11883 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11884 		if (ecn_info == IPH_ECN_CE)
11885 			ipf->ipf_ecn = IPH_ECN_CE;
11886 	} else {
11887 		ipf->ipf_ecn = IPH_ECN_NECT;
11888 	}
11889 	if (offset && ipf->ipf_end == offset) {
11890 		/* The new fragment fits at the end */
11891 		ipf->ipf_tail_mp->b_cont = mp;
11892 		/* Update the byte count */
11893 		ipf->ipf_count += msg_len;
11894 		/* Update per ipfb and ill byte counts */
11895 		ipfb->ipfb_count += msg_len;
11896 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11897 		ill->ill_frag_count += msg_len;
11898 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11899 		if (frag_offset_flags & IPH_MF) {
11900 			/* More to come. */
11901 			ipf->ipf_end = end;
11902 			ipf->ipf_tail_mp = tail_mp;
11903 			goto reass_done;
11904 		}
11905 	} else {
11906 		/* Go do the hard cases. */
11907 		int ret;
11908 
11909 		if (offset == 0)
11910 			ipf->ipf_nf_hdr_len = hdr_length;
11911 
11912 		/* Save current byte count */
11913 		count = ipf->ipf_count;
11914 		ret = ip_reassemble(mp, ipf,
11915 		    (frag_offset_flags & IPH_OFFSET) << 3,
11916 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11917 		/* Count of bytes added and subtracted (freeb()ed) */
11918 		count = ipf->ipf_count - count;
11919 		if (count) {
11920 			/* Update per ipfb and ill byte counts */
11921 			ipfb->ipfb_count += count;
11922 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11923 			ill->ill_frag_count += count;
11924 			ASSERT(ill->ill_frag_count > 0);
11925 		}
11926 		if (ret == IP_REASS_PARTIAL) {
11927 			goto reass_done;
11928 		} else if (ret == IP_REASS_FAILED) {
11929 			/* Reassembly failed. Free up all resources */
11930 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11931 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11932 				IP_REASS_SET_START(t_mp, 0);
11933 				IP_REASS_SET_END(t_mp, 0);
11934 			}
11935 			freemsg(mp);
11936 			goto reass_done;
11937 		}
11938 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11939 	}
11940 	/*
11941 	 * We have completed reassembly.  Unhook the frag header from
11942 	 * the reassembly list.
11943 	 *
11944 	 * Before we free the frag header, record the ECN info
11945 	 * to report back to the transport.
11946 	 */
11947 	ecn_info = ipf->ipf_ecn;
11948 	BUMP_MIB(&ip_mib, ipReasmOKs);
11949 	ipfp = ipf->ipf_ptphn;
11950 
11951 	/* We need to supply these to caller */
11952 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11953 		sum_val = ipf->ipf_checksum;
11954 	else
11955 		sum_val = 0;
11956 
11957 	mp1 = ipf->ipf_mp;
11958 	count = ipf->ipf_count;
11959 	ipf = ipf->ipf_hash_next;
11960 	if (ipf != NULL)
11961 		ipf->ipf_ptphn = ipfp;
11962 	ipfp[0] = ipf;
11963 	ill->ill_frag_count -= count;
11964 	ASSERT(ipfb->ipfb_count >= count);
11965 	ipfb->ipfb_count -= count;
11966 	ipfb->ipfb_frag_pkts--;
11967 	mutex_exit(&ipfb->ipfb_lock);
11968 	/* Ditch the frag header. */
11969 	mp = mp1->b_cont;
11970 
11971 	freeb(mp1);
11972 
11973 	/* Restore original IP length in header. */
11974 	packet_size = (uint32_t)msgdsize(mp);
11975 	if (packet_size > IP_MAXPACKET) {
11976 		freemsg(mp);
11977 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11978 		return (B_FALSE);
11979 	}
11980 
11981 	if (DB_REF(mp) > 1) {
11982 		mblk_t *mp2 = copymsg(mp);
11983 
11984 		freemsg(mp);
11985 		if (mp2 == NULL) {
11986 			BUMP_MIB(&ip_mib, ipInDiscards);
11987 			return (B_FALSE);
11988 		}
11989 		mp = mp2;
11990 	}
11991 	ipha = (ipha_t *)mp->b_rptr;
11992 
11993 	ipha->ipha_length = htons((uint16_t)packet_size);
11994 	/* We're now complete, zip the frag state */
11995 	ipha->ipha_fragment_offset_and_flags = 0;
11996 	/* Record the ECN info. */
11997 	ipha->ipha_type_of_service &= 0xFC;
11998 	ipha->ipha_type_of_service |= ecn_info;
11999 	*mpp = mp;
12000 
12001 	/* Reassembly is successful; return checksum information if needed */
12002 	if (cksum_val != NULL)
12003 		*cksum_val = sum_val;
12004 	if (cksum_flags != NULL)
12005 		*cksum_flags = sum_flags;
12006 
12007 	return (B_TRUE);
12008 }
12009 
12010 /*
12011  * Perform ip header check sum update local options.
12012  * return B_TRUE if all is well, else return B_FALSE and release
12013  * the mp. caller is responsible for decrementing ire ref cnt.
12014  */
12015 static boolean_t
12016 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12017 {
12018 	mblk_t		*first_mp;
12019 	boolean_t	mctl_present;
12020 	uint16_t	sum;
12021 
12022 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12023 	/*
12024 	 * Don't do the checksum if it has gone through AH/ESP
12025 	 * processing.
12026 	 */
12027 	if (!mctl_present) {
12028 		sum = ip_csum_hdr(ipha);
12029 		if (sum != 0) {
12030 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12031 			freemsg(first_mp);
12032 			return (B_FALSE);
12033 		}
12034 	}
12035 
12036 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12037 		if (mctl_present)
12038 			freeb(first_mp);
12039 		return (B_FALSE);
12040 	}
12041 
12042 	return (B_TRUE);
12043 }
12044 
12045 /*
12046  * All udp packet are delivered to the local host via this routine.
12047  */
12048 void
12049 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12050     ill_t *recv_ill)
12051 {
12052 	uint32_t	sum;
12053 	uint32_t	u1;
12054 	boolean_t	mctl_present;
12055 	conn_t		*connp;
12056 	mblk_t		*first_mp;
12057 	uint16_t	*up;
12058 	ill_t		*ill = (ill_t *)q->q_ptr;
12059 	uint16_t	reass_hck_flags = 0;
12060 
12061 #define	rptr    ((uchar_t *)ipha)
12062 
12063 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12064 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12065 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12066 
12067 	/*
12068 	 * FAST PATH for udp packets
12069 	 */
12070 
12071 	/* u1 is # words of IP options */
12072 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12073 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12074 
12075 	/* IP options present */
12076 	if (u1 != 0)
12077 		goto ipoptions;
12078 
12079 	/* Check the IP header checksum.  */
12080 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12081 		/* Clear the IP header h/w cksum flag */
12082 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12083 	} else {
12084 #define	uph	((uint16_t *)ipha)
12085 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12086 		    uph[6] + uph[7] + uph[8] + uph[9];
12087 #undef	uph
12088 		/* finish doing IP checksum */
12089 		sum = (sum & 0xFFFF) + (sum >> 16);
12090 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12091 		/*
12092 		 * Don't verify header checksum if this packet is coming
12093 		 * back from AH/ESP as we already did it.
12094 		 */
12095 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12096 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12097 			freemsg(first_mp);
12098 			return;
12099 		}
12100 	}
12101 
12102 	/*
12103 	 * Count for SNMP of inbound packets for ire.
12104 	 * if mctl is present this might be a secure packet and
12105 	 * has already been counted for in ip_proto_input().
12106 	 */
12107 	if (!mctl_present) {
12108 		UPDATE_IB_PKT_COUNT(ire);
12109 		ire->ire_last_used_time = lbolt;
12110 	}
12111 
12112 	/* packet part of fragmented IP packet? */
12113 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12114 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12115 		goto fragmented;
12116 	}
12117 
12118 	/* u1 = IP header length (20 bytes) */
12119 	u1 = IP_SIMPLE_HDR_LENGTH;
12120 
12121 	/* packet does not contain complete IP & UDP headers */
12122 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12123 		goto udppullup;
12124 
12125 	/* up points to UDP header */
12126 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12127 #define	iphs    ((uint16_t *)ipha)
12128 
12129 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12130 	if (up[3] != 0) {
12131 		mblk_t *mp1 = mp->b_cont;
12132 		boolean_t cksum_err;
12133 		uint16_t hck_flags = 0;
12134 
12135 		/* Pseudo-header checksum */
12136 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12137 		    iphs[9] + up[2];
12138 
12139 		/*
12140 		 * Revert to software checksum calculation if the interface
12141 		 * isn't capable of checksum offload or if IPsec is present.
12142 		 */
12143 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12144 			hck_flags = DB_CKSUMFLAGS(mp);
12145 
12146 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12147 			IP_STAT(ip_in_sw_cksum);
12148 
12149 		IP_CKSUM_RECV(hck_flags, u1,
12150 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12151 		    (int32_t)((uchar_t *)up - rptr),
12152 		    mp, mp1, cksum_err);
12153 
12154 		if (cksum_err) {
12155 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12156 
12157 			if (hck_flags & HCK_FULLCKSUM)
12158 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12159 			else if (hck_flags & HCK_PARTIALCKSUM)
12160 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12161 			else
12162 				IP_STAT(ip_udp_in_sw_cksum_err);
12163 
12164 			freemsg(first_mp);
12165 			return;
12166 		}
12167 	}
12168 
12169 	/* Non-fragmented broadcast or multicast packet? */
12170 	if (ire->ire_type == IRE_BROADCAST)
12171 		goto udpslowpath;
12172 
12173 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12174 	    ire->ire_zoneid)) != NULL) {
12175 		ASSERT(connp->conn_upq != NULL);
12176 		IP_STAT(ip_udp_fast_path);
12177 
12178 		if (CONN_UDP_FLOWCTLD(connp)) {
12179 			freemsg(mp);
12180 			BUMP_MIB(&ip_mib, udpInOverflows);
12181 		} else {
12182 			if (!mctl_present) {
12183 				BUMP_MIB(&ip_mib, ipInDelivers);
12184 			}
12185 			/*
12186 			 * mp and first_mp can change.
12187 			 */
12188 			if (ip_udp_check(q, connp, recv_ill,
12189 			    ipha, &mp, &first_mp, mctl_present)) {
12190 				/* Send it upstream */
12191 				CONN_UDP_RECV(connp, mp);
12192 			}
12193 		}
12194 		/*
12195 		 * freeb() cannot deal with null mblk being passed
12196 		 * in and first_mp can be set to null in the call
12197 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12198 		 */
12199 		if (mctl_present && first_mp != NULL) {
12200 			freeb(first_mp);
12201 		}
12202 		CONN_DEC_REF(connp);
12203 		return;
12204 	}
12205 
12206 	/*
12207 	 * if we got here we know the packet is not fragmented and
12208 	 * has no options. The classifier could not find a conn_t and
12209 	 * most likely its an icmp packet so send it through slow path.
12210 	 */
12211 
12212 	goto udpslowpath;
12213 
12214 ipoptions:
12215 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12216 		goto slow_done;
12217 	}
12218 
12219 	UPDATE_IB_PKT_COUNT(ire);
12220 	ire->ire_last_used_time = lbolt;
12221 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12222 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12223 fragmented:
12224 		/*
12225 		 * "sum" and "reass_hck_flags" are non-zero if the
12226 		 * reassembled packet has a valid hardware computed
12227 		 * checksum information associated with it.
12228 		 */
12229 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12230 			goto slow_done;
12231 		/*
12232 		 * Make sure that first_mp points back to mp as
12233 		 * the mp we came in with could have changed in
12234 		 * ip_rput_fragment().
12235 		 */
12236 		ASSERT(!mctl_present);
12237 		ipha = (ipha_t *)mp->b_rptr;
12238 		first_mp = mp;
12239 	}
12240 
12241 	/* Now we have a complete datagram, destined for this machine. */
12242 	u1 = IPH_HDR_LENGTH(ipha);
12243 	/* Pull up the UDP header, if necessary. */
12244 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12245 udppullup:
12246 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12247 			BUMP_MIB(&ip_mib, ipInDiscards);
12248 			freemsg(first_mp);
12249 			goto slow_done;
12250 		}
12251 		ipha = (ipha_t *)mp->b_rptr;
12252 	}
12253 
12254 	/*
12255 	 * Validate the checksum for the reassembled packet; for the
12256 	 * pullup case we calculate the payload checksum in software.
12257 	 */
12258 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12259 	if (up[3] != 0) {
12260 		boolean_t cksum_err;
12261 
12262 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12263 			IP_STAT(ip_in_sw_cksum);
12264 
12265 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12266 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12267 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12268 		    iphs[9] + up[2], sum, cksum_err);
12269 
12270 		if (cksum_err) {
12271 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12272 
12273 			if (reass_hck_flags & HCK_FULLCKSUM)
12274 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12275 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12276 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12277 			else
12278 				IP_STAT(ip_udp_in_sw_cksum_err);
12279 
12280 			freemsg(first_mp);
12281 			goto slow_done;
12282 		}
12283 	}
12284 udpslowpath:
12285 
12286 	/* Clear hardware checksum flag to be safe */
12287 	DB_CKSUMFLAGS(mp) = 0;
12288 
12289 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12290 	    (ire->ire_type == IRE_BROADCAST),
12291 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12292 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12293 
12294 slow_done:
12295 	IP_STAT(ip_udp_slow_path);
12296 	return;
12297 
12298 #undef  iphs
12299 #undef  rptr
12300 }
12301 
12302 /* ARGSUSED */
12303 static mblk_t *
12304 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12305     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12306     ill_rx_ring_t *ill_ring)
12307 {
12308 	conn_t		*connp;
12309 	uint32_t	sum;
12310 	uint32_t	u1;
12311 	uint16_t	*up;
12312 	int		offset;
12313 	ssize_t		len;
12314 	mblk_t		*mp1;
12315 	boolean_t	syn_present = B_FALSE;
12316 	tcph_t		*tcph;
12317 	uint_t		ip_hdr_len;
12318 	ill_t		*ill = (ill_t *)q->q_ptr;
12319 	zoneid_t	zoneid = ire->ire_zoneid;
12320 	boolean_t	cksum_err;
12321 	uint16_t	hck_flags = 0;
12322 
12323 #define	rptr	((uchar_t *)ipha)
12324 
12325 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12326 
12327 	/*
12328 	 * FAST PATH for tcp packets
12329 	 */
12330 
12331 	/* u1 is # words of IP options */
12332 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12333 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12334 
12335 	/* IP options present */
12336 	if (u1) {
12337 		goto ipoptions;
12338 	} else {
12339 		/* Check the IP header checksum.  */
12340 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12341 			/* Clear the IP header h/w cksum flag */
12342 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12343 		} else {
12344 #define	uph	((uint16_t *)ipha)
12345 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12346 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12347 #undef	uph
12348 			/* finish doing IP checksum */
12349 			sum = (sum & 0xFFFF) + (sum >> 16);
12350 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12351 			/*
12352 			 * Don't verify header checksum if this packet
12353 			 * is coming back from AH/ESP as we already did it.
12354 			 */
12355 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12356 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12357 				goto error;
12358 			}
12359 		}
12360 	}
12361 
12362 	if (!mctl_present) {
12363 		UPDATE_IB_PKT_COUNT(ire);
12364 		ire->ire_last_used_time = lbolt;
12365 	}
12366 
12367 	/* packet part of fragmented IP packet? */
12368 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12369 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12370 		goto fragmented;
12371 	}
12372 
12373 	/* u1 = IP header length (20 bytes) */
12374 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12375 
12376 	/* does packet contain IP+TCP headers? */
12377 	len = mp->b_wptr - rptr;
12378 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12379 		IP_STAT(ip_tcppullup);
12380 		goto tcppullup;
12381 	}
12382 
12383 	/* TCP options present? */
12384 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12385 
12386 	/*
12387 	 * If options need to be pulled up, then goto tcpoptions.
12388 	 * otherwise we are still in the fast path
12389 	 */
12390 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12391 		IP_STAT(ip_tcpoptions);
12392 		goto tcpoptions;
12393 	}
12394 
12395 	/* multiple mblks of tcp data? */
12396 	if ((mp1 = mp->b_cont) != NULL) {
12397 		/* more then two? */
12398 		if (mp1->b_cont != NULL) {
12399 			IP_STAT(ip_multipkttcp);
12400 			goto multipkttcp;
12401 		}
12402 		len += mp1->b_wptr - mp1->b_rptr;
12403 	}
12404 
12405 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12406 
12407 	/* part of pseudo checksum */
12408 
12409 	/* TCP datagram length */
12410 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12411 
12412 #define	iphs    ((uint16_t *)ipha)
12413 
12414 #ifdef	_BIG_ENDIAN
12415 	u1 += IPPROTO_TCP;
12416 #else
12417 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12418 #endif
12419 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12420 
12421 	/*
12422 	 * Revert to software checksum calculation if the interface
12423 	 * isn't capable of checksum offload or if IPsec is present.
12424 	 */
12425 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12426 		hck_flags = DB_CKSUMFLAGS(mp);
12427 
12428 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12429 		IP_STAT(ip_in_sw_cksum);
12430 
12431 	IP_CKSUM_RECV(hck_flags, u1,
12432 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12433 	    (int32_t)((uchar_t *)up - rptr),
12434 	    mp, mp1, cksum_err);
12435 
12436 	if (cksum_err) {
12437 		BUMP_MIB(&ip_mib, tcpInErrs);
12438 
12439 		if (hck_flags & HCK_FULLCKSUM)
12440 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12441 		else if (hck_flags & HCK_PARTIALCKSUM)
12442 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12443 		else
12444 			IP_STAT(ip_tcp_in_sw_cksum_err);
12445 
12446 		goto error;
12447 	}
12448 
12449 try_again:
12450 
12451 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12452 	    NULL) {
12453 		/* Send the TH_RST */
12454 		goto no_conn;
12455 	}
12456 
12457 	/*
12458 	 * TCP FAST PATH for AF_INET socket.
12459 	 *
12460 	 * TCP fast path to avoid extra work. An AF_INET socket type
12461 	 * does not have facility to receive extra information via
12462 	 * ip_process or ip_add_info. Also, when the connection was
12463 	 * established, we made a check if this connection is impacted
12464 	 * by any global IPSec policy or per connection policy (a
12465 	 * policy that comes in effect later will not apply to this
12466 	 * connection). Since all this can be determined at the
12467 	 * connection establishment time, a quick check of flags
12468 	 * can avoid extra work.
12469 	 */
12470 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12471 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12472 		ASSERT(first_mp == mp);
12473 		SET_SQUEUE(mp, tcp_rput_data, connp);
12474 		return (mp);
12475 	}
12476 
12477 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12478 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12479 		if (IPCL_IS_TCP(connp)) {
12480 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12481 			DB_CKSUMSTART(mp) =
12482 			    (intptr_t)ip_squeue_get(ill_ring);
12483 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12484 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12485 				SET_SQUEUE(mp, connp->conn_recv, connp);
12486 				return (mp);
12487 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12488 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12489 				ip_squeue_enter_unbound++;
12490 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12491 				    connp);
12492 				return (mp);
12493 			}
12494 			syn_present = B_TRUE;
12495 		}
12496 
12497 	}
12498 
12499 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12500 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12501 
12502 		/* No need to send this packet to TCP */
12503 		if ((flags & TH_RST) || (flags & TH_URG)) {
12504 			CONN_DEC_REF(connp);
12505 			freemsg(first_mp);
12506 			return (NULL);
12507 		}
12508 		if (flags & TH_ACK) {
12509 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12510 			CONN_DEC_REF(connp);
12511 			return (NULL);
12512 		}
12513 
12514 		CONN_DEC_REF(connp);
12515 		freemsg(first_mp);
12516 		return (NULL);
12517 	}
12518 
12519 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12520 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12521 		    ipha, NULL, mctl_present);
12522 		if (first_mp == NULL) {
12523 			CONN_DEC_REF(connp);
12524 			return (NULL);
12525 		}
12526 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12527 			ASSERT(syn_present);
12528 			if (mctl_present) {
12529 				ASSERT(first_mp != mp);
12530 				first_mp->b_datap->db_struioflag |=
12531 				    STRUIO_POLICY;
12532 			} else {
12533 				ASSERT(first_mp == mp);
12534 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12535 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12536 			}
12537 		} else {
12538 			/*
12539 			 * Discard first_mp early since we're dealing with a
12540 			 * fully-connected conn_t and tcp doesn't do policy in
12541 			 * this case.
12542 			 */
12543 			if (mctl_present) {
12544 				freeb(first_mp);
12545 				mctl_present = B_FALSE;
12546 			}
12547 			first_mp = mp;
12548 		}
12549 	}
12550 
12551 	/* Initiate IPPF processing for fastpath */
12552 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12553 		uint32_t	ill_index;
12554 
12555 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12556 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12557 		if (mp == NULL) {
12558 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12559 			    "deferred/dropped during IPPF processing\n"));
12560 			CONN_DEC_REF(connp);
12561 			if (mctl_present)
12562 				freeb(first_mp);
12563 			return (NULL);
12564 		} else if (mctl_present) {
12565 			/*
12566 			 * ip_process might return a new mp.
12567 			 */
12568 			ASSERT(first_mp != mp);
12569 			first_mp->b_cont = mp;
12570 		} else {
12571 			first_mp = mp;
12572 		}
12573 
12574 	}
12575 
12576 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12577 		mp = ip_add_info(mp, recv_ill, flags);
12578 		if (mp == NULL) {
12579 			CONN_DEC_REF(connp);
12580 			if (mctl_present)
12581 				freeb(first_mp);
12582 			return (NULL);
12583 		} else if (mctl_present) {
12584 			/*
12585 			 * ip_add_info might return a new mp.
12586 			 */
12587 			ASSERT(first_mp != mp);
12588 			first_mp->b_cont = mp;
12589 		} else {
12590 			first_mp = mp;
12591 		}
12592 	}
12593 
12594 	if (IPCL_IS_TCP(connp)) {
12595 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12596 		return (first_mp);
12597 	} else {
12598 		putnext(connp->conn_rq, first_mp);
12599 		CONN_DEC_REF(connp);
12600 		return (NULL);
12601 	}
12602 
12603 no_conn:
12604 	/* Initiate IPPf processing, if needed. */
12605 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12606 		uint32_t ill_index;
12607 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12608 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12609 		if (first_mp == NULL) {
12610 			return (NULL);
12611 		}
12612 	}
12613 	BUMP_MIB(&ip_mib, ipInDelivers);
12614 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12615 	return (NULL);
12616 ipoptions:
12617 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12618 		goto slow_done;
12619 	}
12620 
12621 	UPDATE_IB_PKT_COUNT(ire);
12622 	ire->ire_last_used_time = lbolt;
12623 
12624 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12625 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12626 fragmented:
12627 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12628 			if (mctl_present)
12629 				freeb(first_mp);
12630 			goto slow_done;
12631 		}
12632 		/*
12633 		 * Make sure that first_mp points back to mp as
12634 		 * the mp we came in with could have changed in
12635 		 * ip_rput_fragment().
12636 		 */
12637 		ASSERT(!mctl_present);
12638 		ipha = (ipha_t *)mp->b_rptr;
12639 		first_mp = mp;
12640 	}
12641 
12642 	/* Now we have a complete datagram, destined for this machine. */
12643 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12644 
12645 	len = mp->b_wptr - mp->b_rptr;
12646 	/* Pull up a minimal TCP header, if necessary. */
12647 	if (len < (u1 + 20)) {
12648 tcppullup:
12649 		if (!pullupmsg(mp, u1 + 20)) {
12650 			BUMP_MIB(&ip_mib, ipInDiscards);
12651 			goto error;
12652 		}
12653 		ipha = (ipha_t *)mp->b_rptr;
12654 		len = mp->b_wptr - mp->b_rptr;
12655 	}
12656 
12657 	/*
12658 	 * Extract the offset field from the TCP header.  As usual, we
12659 	 * try to help the compiler more than the reader.
12660 	 */
12661 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12662 	if (offset != 5) {
12663 tcpoptions:
12664 		if (offset < 5) {
12665 			BUMP_MIB(&ip_mib, ipInDiscards);
12666 			goto error;
12667 		}
12668 		/*
12669 		 * There must be TCP options.
12670 		 * Make sure we can grab them.
12671 		 */
12672 		offset <<= 2;
12673 		offset += u1;
12674 		if (len < offset) {
12675 			if (!pullupmsg(mp, offset)) {
12676 				BUMP_MIB(&ip_mib, ipInDiscards);
12677 				goto error;
12678 			}
12679 			ipha = (ipha_t *)mp->b_rptr;
12680 			len = mp->b_wptr - rptr;
12681 		}
12682 	}
12683 
12684 	/* Get the total packet length in len, including headers. */
12685 	if (mp->b_cont) {
12686 multipkttcp:
12687 		len = msgdsize(mp);
12688 	}
12689 
12690 	/*
12691 	 * Check the TCP checksum by pulling together the pseudo-
12692 	 * header checksum, and passing it to ip_csum to be added in
12693 	 * with the TCP datagram.
12694 	 *
12695 	 * Since we are not using the hwcksum if available we must
12696 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12697 	 * If either of these fails along the way the mblk is freed.
12698 	 * If this logic ever changes and mblk is reused to say send
12699 	 * ICMP's back, then this flag may need to be cleared in
12700 	 * other places as well.
12701 	 */
12702 	DB_CKSUMFLAGS(mp) = 0;
12703 
12704 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12705 
12706 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12707 #ifdef	_BIG_ENDIAN
12708 	u1 += IPPROTO_TCP;
12709 #else
12710 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12711 #endif
12712 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12713 	/*
12714 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12715 	 */
12716 	IP_STAT(ip_in_sw_cksum);
12717 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12718 		BUMP_MIB(&ip_mib, tcpInErrs);
12719 		goto error;
12720 	}
12721 
12722 	IP_STAT(ip_tcp_slow_path);
12723 	goto try_again;
12724 #undef  iphs
12725 #undef  rptr
12726 
12727 error:
12728 	freemsg(first_mp);
12729 slow_done:
12730 	return (NULL);
12731 }
12732 
12733 /* ARGSUSED */
12734 static void
12735 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12736     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12737 {
12738 	conn_t		*connp;
12739 	uint32_t	sum;
12740 	uint32_t	u1;
12741 	ssize_t		len;
12742 	sctp_hdr_t	*sctph;
12743 	zoneid_t	zoneid = ire->ire_zoneid;
12744 	uint32_t	pktsum;
12745 	uint32_t	calcsum;
12746 	uint32_t	ports;
12747 	uint_t		ipif_seqid;
12748 	in6_addr_t	map_src, map_dst;
12749 	ill_t		*ill = (ill_t *)q->q_ptr;
12750 
12751 #define	rptr	((uchar_t *)ipha)
12752 
12753 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12754 
12755 	/* u1 is # words of IP options */
12756 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12757 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12758 
12759 	/* IP options present */
12760 	if (u1 > 0) {
12761 		goto ipoptions;
12762 	} else {
12763 		/* Check the IP header checksum.  */
12764 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12765 #define	uph	((uint16_t *)ipha)
12766 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12767 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12768 #undef	uph
12769 			/* finish doing IP checksum */
12770 			sum = (sum & 0xFFFF) + (sum >> 16);
12771 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12772 			/*
12773 			 * Don't verify header checksum if this packet
12774 			 * is coming back from AH/ESP as we already did it.
12775 			 */
12776 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12777 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12778 				goto error;
12779 			}
12780 		}
12781 		/*
12782 		 * Since there is no SCTP h/w cksum support yet, just
12783 		 * clear the flag.
12784 		 */
12785 		DB_CKSUMFLAGS(mp) = 0;
12786 	}
12787 
12788 	/*
12789 	 * Don't verify header checksum if this packet is coming
12790 	 * back from AH/ESP as we already did it.
12791 	 */
12792 	if (!mctl_present) {
12793 		UPDATE_IB_PKT_COUNT(ire);
12794 		ire->ire_last_used_time = lbolt;
12795 	}
12796 
12797 	/* packet part of fragmented IP packet? */
12798 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12799 	if (u1 & (IPH_MF | IPH_OFFSET))
12800 		goto fragmented;
12801 
12802 	/* u1 = IP header length (20 bytes) */
12803 	u1 = IP_SIMPLE_HDR_LENGTH;
12804 
12805 find_sctp_client:
12806 	/* Pullup if we don't have the sctp common header. */
12807 	len = MBLKL(mp);
12808 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12809 		if (mp->b_cont == NULL ||
12810 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12811 			BUMP_MIB(&ip_mib, ipInDiscards);
12812 			goto error;
12813 		}
12814 		ipha = (ipha_t *)mp->b_rptr;
12815 		len = MBLKL(mp);
12816 	}
12817 
12818 	sctph = (sctp_hdr_t *)(rptr + u1);
12819 #ifdef	DEBUG
12820 	if (!skip_sctp_cksum) {
12821 #endif
12822 		pktsum = sctph->sh_chksum;
12823 		sctph->sh_chksum = 0;
12824 		calcsum = sctp_cksum(mp, u1);
12825 		if (calcsum != pktsum) {
12826 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12827 			goto error;
12828 		}
12829 		sctph->sh_chksum = pktsum;
12830 #ifdef	DEBUG	/* skip_sctp_cksum */
12831 	}
12832 #endif
12833 	/* get the ports */
12834 	ports = *(uint32_t *)&sctph->sh_sport;
12835 
12836 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12837 	IRE_REFRELE(ire);
12838 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12839 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12840 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12841 	    mp)) == NULL) {
12842 		/* Check for raw socket or OOTB handling */
12843 		goto no_conn;
12844 	}
12845 
12846 	/* Found a client; up it goes */
12847 	BUMP_MIB(&ip_mib, ipInDelivers);
12848 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12849 	return;
12850 
12851 no_conn:
12852 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12853 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12854 	return;
12855 
12856 ipoptions:
12857 	DB_CKSUMFLAGS(mp) = 0;
12858 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12859 		goto slow_done;
12860 
12861 	UPDATE_IB_PKT_COUNT(ire);
12862 	ire->ire_last_used_time = lbolt;
12863 
12864 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12865 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12866 fragmented:
12867 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12868 			goto slow_done;
12869 		/*
12870 		 * Make sure that first_mp points back to mp as
12871 		 * the mp we came in with could have changed in
12872 		 * ip_rput_fragment().
12873 		 */
12874 		ASSERT(!mctl_present);
12875 		ipha = (ipha_t *)mp->b_rptr;
12876 		first_mp = mp;
12877 	}
12878 
12879 	/* Now we have a complete datagram, destined for this machine. */
12880 	u1 = IPH_HDR_LENGTH(ipha);
12881 	goto find_sctp_client;
12882 #undef  iphs
12883 #undef  rptr
12884 
12885 error:
12886 	freemsg(first_mp);
12887 slow_done:
12888 	IRE_REFRELE(ire);
12889 }
12890 
12891 #define	VER_BITS	0xF0
12892 #define	VERSION_6	0x60
12893 
12894 static boolean_t
12895 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12896     ipaddr_t *dstp)
12897 {
12898 	uint_t	opt_len;
12899 	ipha_t *ipha;
12900 	ssize_t len;
12901 	uint_t	pkt_len;
12902 
12903 	IP_STAT(ip_ipoptions);
12904 	ipha = *iphapp;
12905 
12906 #define	rptr    ((uchar_t *)ipha)
12907 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12908 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12909 		BUMP_MIB(&ip_mib, ipInIPv6);
12910 		freemsg(mp);
12911 		return (B_FALSE);
12912 	}
12913 
12914 	/* multiple mblk or too short */
12915 	pkt_len = ntohs(ipha->ipha_length);
12916 
12917 	/* Get the number of words of IP options in the IP header. */
12918 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12919 	if (opt_len) {
12920 		/* IP Options present!  Validate and process. */
12921 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12922 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12923 			goto done;
12924 		}
12925 		/*
12926 		 * Recompute complete header length and make sure we
12927 		 * have access to all of it.
12928 		 */
12929 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12930 		if (len > (mp->b_wptr - rptr)) {
12931 			if (len > pkt_len) {
12932 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12933 				goto done;
12934 			}
12935 			if (!pullupmsg(mp, len)) {
12936 				BUMP_MIB(&ip_mib, ipInDiscards);
12937 				goto done;
12938 			}
12939 			ipha = (ipha_t *)mp->b_rptr;
12940 		}
12941 		/*
12942 		 * Go off to ip_rput_options which returns the next hop
12943 		 * destination address, which may have been affected
12944 		 * by source routing.
12945 		 */
12946 		IP_STAT(ip_opt);
12947 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12948 			return (B_FALSE);
12949 		}
12950 	}
12951 	*iphapp = ipha;
12952 	return (B_TRUE);
12953 done:
12954 	/* clear b_prev - used by ip_mroute_decap */
12955 	mp->b_prev = NULL;
12956 	freemsg(mp);
12957 	return (B_FALSE);
12958 #undef  rptr
12959 }
12960 
12961 /*
12962  * Deal with the fact that there is no ire for the destination.
12963  * The incoming ill (in_ill) is passed in to ip_newroute only
12964  * in the case of packets coming from mobile ip forward tunnel.
12965  * It must be null otherwise.
12966  */
12967 static ire_t *
12968 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12969     ipaddr_t dst)
12970 {
12971 	ipha_t	*ipha;
12972 	ill_t	*ill;
12973 	ire_t	*ire;
12974 	boolean_t	check_multirt = B_FALSE;
12975 
12976 	ipha = (ipha_t *)mp->b_rptr;
12977 	ill = (ill_t *)q->q_ptr;
12978 
12979 	ASSERT(ill != NULL);
12980 	/*
12981 	 * No IRE for this destination, so it can't be for us.
12982 	 * Unless we are forwarding, drop the packet.
12983 	 * We have to let source routed packets through
12984 	 * since we don't yet know if they are 'ping -l'
12985 	 * packets i.e. if they will go out over the
12986 	 * same interface as they came in on.
12987 	 */
12988 	if (ll_multicast) {
12989 		freemsg(mp);
12990 		return (NULL);
12991 	}
12992 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12993 		BUMP_MIB(&ip_mib, ipForwProhibits);
12994 		freemsg(mp);
12995 		return (NULL);
12996 	}
12997 
12998 	/*
12999 	 * Mark this packet as having originated externally.
13000 	 *
13001 	 * For non-forwarding code path, ire_send later double
13002 	 * checks this interface to see if it is still exists
13003 	 * post-ARP resolution.
13004 	 *
13005 	 * Also, IPQOS uses this to differentiate between
13006 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13007 	 * QOS packet processing in ip_wput_attach_llhdr().
13008 	 * The QoS module can mark the b_band for a fastpath message
13009 	 * or the dl_priority field in a unitdata_req header for
13010 	 * CoS marking. This info can only be found in
13011 	 * ip_wput_attach_llhdr().
13012 	 */
13013 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13014 	/*
13015 	 * Clear the indication that this may have a hardware checksum
13016 	 * as we are not using it
13017 	 */
13018 	DB_CKSUMFLAGS(mp) = 0;
13019 
13020 	if (in_ill != NULL) {
13021 		/*
13022 		 * Now hand the packet to ip_newroute.
13023 		 */
13024 		ip_newroute(q, mp, dst, in_ill, NULL);
13025 		return (NULL);
13026 	}
13027 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13028 	    MBLK_GETLABEL(mp));
13029 
13030 	if (ire == NULL && check_multirt) {
13031 		/* Let ip_newroute handle CGTP  */
13032 		ip_newroute(q, mp, dst, in_ill, NULL);
13033 		return (NULL);
13034 	}
13035 
13036 	if (ire != NULL)
13037 		return (ire);
13038 
13039 	mp->b_prev = mp->b_next = 0;
13040 	/* send icmp unreachable */
13041 	q = WR(q);
13042 	if (ip_source_routed(ipha))
13043 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
13044 	else
13045 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
13046 
13047 	return (NULL);
13048 
13049 }
13050 
13051 /*
13052  * check ip header length and align it.
13053  */
13054 static boolean_t
13055 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13056 {
13057 	ssize_t len;
13058 	ill_t *ill;
13059 	ipha_t	*ipha;
13060 
13061 	len = MBLKL(mp);
13062 
13063 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13064 		if (!OK_32PTR(mp->b_rptr))
13065 			IP_STAT(ip_notaligned1);
13066 		else
13067 			IP_STAT(ip_notaligned2);
13068 		/* Guard against bogus device drivers */
13069 		if (len < 0) {
13070 			/* clear b_prev - used by ip_mroute_decap */
13071 			mp->b_prev = NULL;
13072 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13073 			freemsg(mp);
13074 			return (B_FALSE);
13075 		}
13076 
13077 		if (ip_rput_pullups++ == 0) {
13078 			ill = (ill_t *)q->q_ptr;
13079 			ipha = (ipha_t *)mp->b_rptr;
13080 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13081 			    "ip_check_and_align_header: %s forced us to "
13082 			    " pullup pkt, hdr len %ld, hdr addr %p",
13083 			    ill->ill_name, len, ipha);
13084 		}
13085 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13086 			/* clear b_prev - used by ip_mroute_decap */
13087 			mp->b_prev = NULL;
13088 			BUMP_MIB(&ip_mib, ipInDiscards);
13089 			freemsg(mp);
13090 			return (B_FALSE);
13091 		}
13092 	}
13093 	return (B_TRUE);
13094 }
13095 
13096 static boolean_t
13097 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13098 {
13099 	ill_group_t	*ill_group;
13100 	ill_group_t	*ire_group;
13101 	queue_t 	*q;
13102 	ill_t		*ire_ill;
13103 	uint_t		ill_ifindex;
13104 
13105 	q = *qp;
13106 	/*
13107 	 * We need to check to make sure the packet came in
13108 	 * on the queue associated with the destination IRE.
13109 	 * Note that for multicast packets and broadcast packets sent to
13110 	 * a broadcast address which is shared between multiple interfaces
13111 	 * we should not do this since we just got a random broadcast ire.
13112 	 */
13113 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13114 		boolean_t check_multi = B_TRUE;
13115 
13116 		/*
13117 		 * This packet came in on an interface other than the
13118 		 * one associated with the destination address.
13119 		 * "Gateway" it to the appropriate interface here.
13120 		 * As long as the ills belong to the same group,
13121 		 * we don't consider them to arriving on the wrong
13122 		 * interface. Thus, when the switch is doing inbound
13123 		 * load spreading, we won't drop packets when we
13124 		 * are doing strict multihoming checks. Note, the
13125 		 * same holds true for 'usesrc groups' where the
13126 		 * destination address may belong to another interface
13127 		 * to allow multipathing to happen
13128 		 */
13129 		ill_group = ill->ill_group;
13130 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13131 		ill_ifindex = ill->ill_usesrc_ifindex;
13132 		ire_group = ire_ill->ill_group;
13133 
13134 		/*
13135 		 * If it's part of the same IPMP group, or if it's a legal
13136 		 * address on the 'usesrc' interface, then bypass strict
13137 		 * checks.
13138 		 */
13139 		if (ill_group != NULL && ill_group == ire_group) {
13140 			check_multi = B_FALSE;
13141 		} else if (ill_ifindex != 0 &&
13142 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13143 			check_multi = B_FALSE;
13144 		}
13145 
13146 		if (check_multi &&
13147 		    ip_strict_dst_multihoming &&
13148 		    ((ill->ill_flags &
13149 		    ire->ire_ipif->ipif_ill->ill_flags &
13150 		    ILLF_ROUTER) == 0)) {
13151 			/* Drop packet */
13152 			BUMP_MIB(&ip_mib, ipForwProhibits);
13153 			freemsg(mp);
13154 			return (B_TRUE);
13155 		}
13156 
13157 		/*
13158 		 * Change the queue (for non-virtual destination network
13159 		 * interfaces) and ip_rput_local will be called with the right
13160 		 * queue
13161 		 */
13162 		q = ire->ire_rfq;
13163 	}
13164 	/* Must be broadcast.  We'll take it. */
13165 	*qp = q;
13166 	return (B_FALSE);
13167 }
13168 
13169 #define	SEND_PKT(ire, mp)			\
13170 {						\
13171 	UPDATE_IB_PKT_COUNT(ire);		\
13172 	(ire)->ire_last_used_time = lbolt;	\
13173 	BUMP_MIB(&ip_mib, ipForwDatagrams);	\
13174 	putnext((ire)->ire_stq, mp);		\
13175 }
13176 
13177 ire_t *
13178 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13179 {
13180 	ipha_t	*ipha;
13181 	ipaddr_t ip_dst, ip_src;
13182 	ire_t	*src_ire;
13183 	ill_t	*stq_ill;
13184 	uint_t	hlen;
13185 	uint32_t sum;
13186 	queue_t	*dev_q;
13187 	boolean_t check_multirt = B_FALSE;
13188 
13189 
13190 	ipha = (ipha_t *)mp->b_rptr;
13191 
13192 	/*
13193 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13194 	 * The loopback address check for both src and dst has already
13195 	 * been checked in ip_input
13196 	 */
13197 	ip_dst = ntohl(dst);
13198 	ip_src = ntohl(ipha->ipha_src);
13199 
13200 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13201 	    IN_CLASSD(ip_src)) {
13202 		BUMP_MIB(&ip_mib, ipForwProhibits);
13203 		goto drop;
13204 	}
13205 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13206 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13207 
13208 	if (src_ire != NULL) {
13209 		BUMP_MIB(&ip_mib, ipForwProhibits);
13210 		goto drop;
13211 	}
13212 
13213 	/* No ire cache of nexthop. So first create one  */
13214 	if (ire == NULL) {
13215 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13216 		/*
13217 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13218 		 * is not set. So upon return from ire_forward
13219 		 * check_multirt should remain as false.
13220 		 */
13221 		ASSERT(!check_multirt);
13222 		if (ire == NULL) {
13223 			BUMP_MIB(&ip_mib, ipInDiscards);
13224 			mp->b_prev = mp->b_next = 0;
13225 			/* send icmp unreachable */
13226 			if (ip_source_routed(ipha)) {
13227 				icmp_unreachable(ill->ill_wq, mp,
13228 				    ICMP_SOURCE_ROUTE_FAILED);
13229 			} else {
13230 				icmp_unreachable(ill->ill_wq, mp,
13231 				    ICMP_HOST_UNREACHABLE);
13232 			}
13233 			return (ire);
13234 		}
13235 	}
13236 
13237 	/*
13238 	 * Forwarding fastpath exception case:
13239 	 * If either of the follwoing case is true, we take
13240 	 * the slowpath
13241 	 *	o forwarding is not enabled
13242 	 *	o IPMP is enabled
13243 	 *	o corresponding ire is in incomplete state
13244 	 *	o packet needs fragmentation
13245 	 *
13246 	 * The codeflow from here on is thus:
13247 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13248 	 */
13249 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13250 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13251 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13252 	    (ire->ire_nce == NULL) ||
13253 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13254 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13255 	    ipha->ipha_ttl <= 1) {
13256 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13257 		    ipha, ill, B_FALSE);
13258 		return (ire);
13259 	}
13260 
13261 	mp->b_datap->db_struioun.cksum.flags = 0;
13262 	/* Adjust the checksum to reflect the ttl decrement. */
13263 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13264 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13265 	ipha->ipha_ttl--;
13266 
13267 	dev_q = ire->ire_stq->q_next;
13268 	if ((dev_q->q_next != NULL ||
13269 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13270 		goto indiscard;
13271 	}
13272 
13273 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13274 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13275 
13276 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13277 		mp = ip_wput_attach_llhdr(mp, ire, 0, 0);
13278 		if (mp != NULL) {
13279 			SEND_PKT(ire, mp);
13280 			return (ire);
13281 		}
13282 	}
13283 
13284 indiscard:
13285 	BUMP_MIB(&ip_mib, ipInDiscards);
13286 drop:
13287 	if (mp != NULL)
13288 		freemsg(mp);
13289 	if (src_ire != NULL)
13290 		ire_refrele(src_ire);
13291 	return (ire);
13292 
13293 }
13294 
13295 /*
13296  * This function is called in the forwarding slowpath, when
13297  * either the ire lacks the link-layer address, or the packet needs
13298  * further processing(eg. fragmentation), before transmission.
13299  */
13300 static void
13301 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13302     ill_t *ill, boolean_t ll_multicast)
13303 {
13304 	ill_group_t	*ill_group;
13305 	ill_group_t	*ire_group;
13306 	queue_t		*dev_q;
13307 	ire_t		*src_ire;
13308 
13309 	ASSERT(ire->ire_stq != NULL);
13310 
13311 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13312 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13313 
13314 	if (ll_multicast != 0)
13315 		goto drop_pkt;
13316 
13317 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13318 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13319 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13320 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13321 		if (src_ire != NULL)
13322 			ire_refrele(src_ire);
13323 		BUMP_MIB(&ip_mib, ipForwProhibits);
13324 		ip2dbg(("ip_rput_process_forward: Received packet with"
13325 		    " bad src/dst address on %s\n", ill->ill_name));
13326 	}
13327 
13328 	ill_group = ill->ill_group;
13329 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13330 	/*
13331 	 * Check if we want to forward this one at this time.
13332 	 * We allow source routed packets on a host provided that
13333 	 * they go out the same interface or same interface group
13334 	 * as they came in on.
13335 	 *
13336 	 * XXX To be quicker, we may wish to not chase pointers to
13337 	 * get the ILLF_ROUTER flag and instead store the
13338 	 * forwarding policy in the ire.  An unfortunate
13339 	 * side-effect of that would be requiring an ire flush
13340 	 * whenever the ILLF_ROUTER flag changes.
13341 	 */
13342 	if (((ill->ill_flags &
13343 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13344 	    ILLF_ROUTER) == 0) &&
13345 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13346 	    (ill_group != NULL && ill_group == ire_group)))) {
13347 		BUMP_MIB(&ip_mib, ipForwProhibits);
13348 		if (ip_source_routed(ipha)) {
13349 			q = WR(q);
13350 			/*
13351 			 * Clear the indication that this may have
13352 			 * hardware checksum as we are not using it.
13353 			 */
13354 			DB_CKSUMFLAGS(mp) = 0;
13355 			icmp_unreachable(q, mp,
13356 			    ICMP_SOURCE_ROUTE_FAILED);
13357 			return;
13358 		}
13359 		goto drop_pkt;
13360 	}
13361 
13362 	/* Packet is being forwarded. Turning off hwcksum flag. */
13363 	DB_CKSUMFLAGS(mp) = 0;
13364 	if (ip_g_send_redirects) {
13365 		/*
13366 		 * Check whether the incoming interface and outgoing
13367 		 * interface is part of the same group. If so,
13368 		 * send redirects.
13369 		 *
13370 		 * Check the source address to see if it originated
13371 		 * on the same logical subnet it is going back out on.
13372 		 * If so, we should be able to send it a redirect.
13373 		 * Avoid sending a redirect if the destination
13374 		 * is directly connected (gw_addr == 0),
13375 		 * or if the packet was source routed out this
13376 		 * interface.
13377 		 */
13378 		ipaddr_t src;
13379 		mblk_t	*mp1;
13380 		ire_t	*src_ire = NULL;
13381 
13382 		/*
13383 		 * Check whether ire_rfq and q are from the same ill
13384 		 * or if they are not same, they at least belong
13385 		 * to the same group. If so, send redirects.
13386 		 */
13387 		if ((ire->ire_rfq == q ||
13388 		    (ill_group != NULL && ill_group == ire_group)) &&
13389 		    (ire->ire_gateway_addr != 0) &&
13390 		    !ip_source_routed(ipha)) {
13391 
13392 			src = ipha->ipha_src;
13393 			src_ire = ire_ftable_lookup(src, 0, 0,
13394 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13395 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13396 
13397 			if (src_ire != NULL) {
13398 				/*
13399 				 * The source is directly connected.
13400 				 * Just copy the ip header (which is
13401 				 * in the first mblk)
13402 				 */
13403 				mp1 = copyb(mp);
13404 				if (mp1 != NULL) {
13405 					icmp_send_redirect(WR(q), mp1,
13406 					    ire->ire_gateway_addr);
13407 				}
13408 				ire_refrele(src_ire);
13409 			}
13410 		}
13411 	}
13412 
13413 	dev_q = ire->ire_stq->q_next;
13414 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13415 		BUMP_MIB(&ip_mib, ipInDiscards);
13416 		freemsg(mp);
13417 		return;
13418 	}
13419 
13420 	ip_rput_forward(ire, ipha, mp, ill);
13421 	return;
13422 
13423 drop_pkt:
13424 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13425 	freemsg(mp);
13426 }
13427 
13428 ire_t *
13429 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13430     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13431 {
13432 	queue_t		*q;
13433 	uint16_t	hcksumflags;
13434 
13435 	q = *qp;
13436 
13437 	/*
13438 	 * Clear the indication that this may have hardware
13439 	 * checksum as we are not using it for forwarding.
13440 	 */
13441 	hcksumflags = DB_CKSUMFLAGS(mp);
13442 	DB_CKSUMFLAGS(mp) = 0;
13443 
13444 	/*
13445 	 * Directed broadcast forwarding: if the packet came in over a
13446 	 * different interface then it is routed out over we can forward it.
13447 	 */
13448 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13449 		ire_refrele(ire);
13450 		freemsg(mp);
13451 		BUMP_MIB(&ip_mib, ipInDiscards);
13452 		return (NULL);
13453 	}
13454 	/*
13455 	 * For multicast we have set dst to be INADDR_BROADCAST
13456 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13457 	 * only for broadcast packets.
13458 	 */
13459 	if (!CLASSD(ipha->ipha_dst)) {
13460 		ire_t *new_ire;
13461 		ipif_t *ipif;
13462 		/*
13463 		 * For ill groups, as the switch duplicates broadcasts
13464 		 * across all the ports, we need to filter out and
13465 		 * send up only one copy. There is one copy for every
13466 		 * broadcast address on each ill. Thus, we look for a
13467 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13468 		 * later to see whether this ill is eligible to receive
13469 		 * them or not. ill_nominate_bcast_rcv() nominates only
13470 		 * one set of IREs for receiving.
13471 		 */
13472 
13473 		ipif = ipif_get_next_ipif(NULL, ill);
13474 		if (ipif == NULL) {
13475 			ire_refrele(ire);
13476 			freemsg(mp);
13477 			BUMP_MIB(&ip_mib, ipInDiscards);
13478 			return (NULL);
13479 		}
13480 		new_ire = ire_ctable_lookup(dst, 0, 0,
13481 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13482 		ipif_refrele(ipif);
13483 
13484 		if (new_ire != NULL) {
13485 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13486 				ire_refrele(ire);
13487 				ire_refrele(new_ire);
13488 				freemsg(mp);
13489 				BUMP_MIB(&ip_mib, ipInDiscards);
13490 				return (NULL);
13491 			}
13492 			/*
13493 			 * In the special case of multirouted broadcast
13494 			 * packets, we unconditionally need to "gateway"
13495 			 * them to the appropriate interface here.
13496 			 * In the normal case, this cannot happen, because
13497 			 * there is no broadcast IRE tagged with the
13498 			 * RTF_MULTIRT flag.
13499 			 */
13500 			if (new_ire->ire_flags & RTF_MULTIRT) {
13501 				ire_refrele(new_ire);
13502 				if (ire->ire_rfq != NULL) {
13503 					q = ire->ire_rfq;
13504 					*qp = q;
13505 				}
13506 			} else {
13507 				ire_refrele(ire);
13508 				ire = new_ire;
13509 			}
13510 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13511 			if (!ip_g_forward_directed_bcast) {
13512 				/*
13513 				 * Free the message if
13514 				 * ip_g_forward_directed_bcast is turned
13515 				 * off for non-local broadcast.
13516 				 */
13517 				ire_refrele(ire);
13518 				freemsg(mp);
13519 				BUMP_MIB(&ip_mib, ipInDiscards);
13520 				return (NULL);
13521 			}
13522 		} else {
13523 			/*
13524 			 * This CGTP packet successfully passed the
13525 			 * CGTP filter, but the related CGTP
13526 			 * broadcast IRE has not been found,
13527 			 * meaning that the redundant ipif is
13528 			 * probably down. However, if we discarded
13529 			 * this packet, its duplicate would be
13530 			 * filtered out by the CGTP filter so none
13531 			 * of them would get through. So we keep
13532 			 * going with this one.
13533 			 */
13534 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13535 			if (ire->ire_rfq != NULL) {
13536 				q = ire->ire_rfq;
13537 				*qp = q;
13538 			}
13539 		}
13540 	}
13541 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13542 		/*
13543 		 * Verify that there are not more then one
13544 		 * IRE_BROADCAST with this broadcast address which
13545 		 * has ire_stq set.
13546 		 * TODO: simplify, loop over all IRE's
13547 		 */
13548 		ire_t	*ire1;
13549 		int	num_stq = 0;
13550 		mblk_t	*mp1;
13551 
13552 		/* Find the first one with ire_stq set */
13553 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13554 		for (ire1 = ire; ire1 &&
13555 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13556 		    ire1 = ire1->ire_next)
13557 			;
13558 		if (ire1) {
13559 			ire_refrele(ire);
13560 			ire = ire1;
13561 			IRE_REFHOLD(ire);
13562 		}
13563 
13564 		/* Check if there are additional ones with stq set */
13565 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13566 			if (ire->ire_addr != ire1->ire_addr)
13567 				break;
13568 			if (ire1->ire_stq) {
13569 				num_stq++;
13570 				break;
13571 			}
13572 		}
13573 		rw_exit(&ire->ire_bucket->irb_lock);
13574 		if (num_stq == 1 && ire->ire_stq != NULL) {
13575 			ip1dbg(("ip_rput_process_broadcast: directed "
13576 			    "broadcast to 0x%x\n",
13577 			    ntohl(ire->ire_addr)));
13578 			mp1 = copymsg(mp);
13579 			if (mp1) {
13580 				switch (ipha->ipha_protocol) {
13581 				case IPPROTO_UDP:
13582 					ip_udp_input(q, mp1, ipha, ire, ill);
13583 					break;
13584 				default:
13585 					ip_proto_input(q, mp1, ipha, ire, ill);
13586 					break;
13587 				}
13588 			}
13589 			/*
13590 			 * Adjust ttl to 2 (1+1 - the forward engine
13591 			 * will decrement it by one.
13592 			 */
13593 			if (ip_csum_hdr(ipha)) {
13594 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13595 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13596 				freemsg(mp);
13597 				ire_refrele(ire);
13598 				return (NULL);
13599 			}
13600 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13601 			ipha->ipha_hdr_checksum = 0;
13602 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13603 			ip_rput_process_forward(q, mp, ire, ipha,
13604 			    ill, ll_multicast);
13605 			ire_refrele(ire);
13606 			return (NULL);
13607 		}
13608 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13609 		    ntohl(ire->ire_addr)));
13610 	}
13611 
13612 
13613 	/* Restore any hardware checksum flags */
13614 	DB_CKSUMFLAGS(mp) = hcksumflags;
13615 	return (ire);
13616 }
13617 
13618 /* ARGSUSED */
13619 static boolean_t
13620 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13621     int *ll_multicast, ipaddr_t *dstp)
13622 {
13623 	/*
13624 	 * Forward packets only if we have joined the allmulti
13625 	 * group on this interface.
13626 	 */
13627 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13628 		int retval;
13629 
13630 		/*
13631 		 * Clear the indication that this may have hardware
13632 		 * checksum as we are not using it.
13633 		 */
13634 		DB_CKSUMFLAGS(mp) = 0;
13635 		retval = ip_mforward(ill, ipha, mp);
13636 		/* ip_mforward updates mib variables if needed */
13637 		/* clear b_prev - used by ip_mroute_decap */
13638 		mp->b_prev = NULL;
13639 
13640 		switch (retval) {
13641 		case 0:
13642 			/*
13643 			 * pkt is okay and arrived on phyint.
13644 			 *
13645 			 * If we are running as a multicast router
13646 			 * we need to see all IGMP and/or PIM packets.
13647 			 */
13648 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13649 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13650 				goto done;
13651 			}
13652 			break;
13653 		case -1:
13654 			/* pkt is mal-formed, toss it */
13655 			goto drop_pkt;
13656 		case 1:
13657 			/* pkt is okay and arrived on a tunnel */
13658 			/*
13659 			 * If we are running a multicast router
13660 			 *  we need to see all igmp packets.
13661 			 */
13662 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13663 				*dstp = INADDR_BROADCAST;
13664 				*ll_multicast = 1;
13665 				return (B_FALSE);
13666 			}
13667 
13668 			goto drop_pkt;
13669 		}
13670 	}
13671 
13672 	ILM_WALKER_HOLD(ill);
13673 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13674 		/*
13675 		 * This might just be caused by the fact that
13676 		 * multiple IP Multicast addresses map to the same
13677 		 * link layer multicast - no need to increment counter!
13678 		 */
13679 		ILM_WALKER_RELE(ill);
13680 		freemsg(mp);
13681 		return (B_TRUE);
13682 	}
13683 	ILM_WALKER_RELE(ill);
13684 done:
13685 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13686 	/*
13687 	 * This assumes the we deliver to all streams for multicast
13688 	 * and broadcast packets.
13689 	 */
13690 	*dstp = INADDR_BROADCAST;
13691 	*ll_multicast = 1;
13692 	return (B_FALSE);
13693 drop_pkt:
13694 	ip2dbg(("ip_rput: drop pkt\n"));
13695 	freemsg(mp);
13696 	return (B_TRUE);
13697 }
13698 
13699 static boolean_t
13700 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13701     int *ll_multicast, mblk_t **mpp)
13702 {
13703 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13704 	boolean_t must_copy = B_FALSE;
13705 	struct iocblk   *iocp;
13706 	ipha_t		*ipha;
13707 
13708 #define	rptr    ((uchar_t *)ipha)
13709 
13710 	first_mp = *first_mpp;
13711 	mp = *mpp;
13712 
13713 	ASSERT(first_mp == mp);
13714 
13715 	/*
13716 	 * if db_ref > 1 then copymsg and free original. Packet may be
13717 	 * changed and do not want other entity who has a reference to this
13718 	 * message to trip over the changes. This is a blind change because
13719 	 * trying to catch all places that might change packet is too
13720 	 * difficult (since it may be a module above this one)
13721 	 *
13722 	 * This corresponds to the non-fast path case. We walk down the full
13723 	 * chain in this case, and check the db_ref count of all the dblks,
13724 	 * and do a copymsg if required. It is possible that the db_ref counts
13725 	 * of the data blocks in the mblk chain can be different.
13726 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13727 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13728 	 * 'snoop' is running.
13729 	 */
13730 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13731 		if (mp1->b_datap->db_ref > 1) {
13732 			must_copy = B_TRUE;
13733 			break;
13734 		}
13735 	}
13736 
13737 	if (must_copy) {
13738 		mp1 = copymsg(mp);
13739 		if (mp1 == NULL) {
13740 			for (mp1 = mp; mp1 != NULL;
13741 			    mp1 = mp1->b_cont) {
13742 				mp1->b_next = NULL;
13743 				mp1->b_prev = NULL;
13744 			}
13745 			freemsg(mp);
13746 			BUMP_MIB(&ip_mib, ipInDiscards);
13747 			return (B_TRUE);
13748 		}
13749 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13750 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13751 			/* Copy b_prev - used by ip_mroute_decap */
13752 			to_mp->b_prev = from_mp->b_prev;
13753 			from_mp->b_prev = NULL;
13754 		}
13755 		*first_mpp = first_mp = mp1;
13756 		freemsg(mp);
13757 		mp = mp1;
13758 		*mpp = mp1;
13759 	}
13760 
13761 	ipha = (ipha_t *)mp->b_rptr;
13762 
13763 	/*
13764 	 * previous code has a case for M_DATA.
13765 	 * We want to check how that happens.
13766 	 */
13767 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13768 	switch (first_mp->b_datap->db_type) {
13769 	case M_PROTO:
13770 	case M_PCPROTO:
13771 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13772 		    DL_UNITDATA_IND) {
13773 			/* Go handle anything other than data elsewhere. */
13774 			ip_rput_dlpi(q, mp);
13775 			return (B_TRUE);
13776 		}
13777 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13778 		/* Ditch the DLPI header. */
13779 		mp1 = mp->b_cont;
13780 		ASSERT(first_mp == mp);
13781 		*first_mpp = mp1;
13782 		freeb(mp);
13783 		*mpp = mp1;
13784 		return (B_FALSE);
13785 	case M_IOCACK:
13786 		ip1dbg(("got iocack "));
13787 		iocp = (struct iocblk *)mp->b_rptr;
13788 		switch (iocp->ioc_cmd) {
13789 		case DL_IOC_HDR_INFO:
13790 			ill = (ill_t *)q->q_ptr;
13791 			ill_fastpath_ack(ill, mp);
13792 			return (B_TRUE);
13793 		case SIOCSTUNPARAM:
13794 		case OSIOCSTUNPARAM:
13795 			/* Go through qwriter_ip */
13796 			break;
13797 		case SIOCGTUNPARAM:
13798 		case OSIOCGTUNPARAM:
13799 			ip_rput_other(NULL, q, mp, NULL);
13800 			return (B_TRUE);
13801 		default:
13802 			putnext(q, mp);
13803 			return (B_TRUE);
13804 		}
13805 		/* FALLTHRU */
13806 	case M_ERROR:
13807 	case M_HANGUP:
13808 		/*
13809 		 * Since this is on the ill stream we unconditionally
13810 		 * bump up the refcount
13811 		 */
13812 		ill_refhold(ill);
13813 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13814 		    B_FALSE);
13815 		return (B_TRUE);
13816 	case M_CTL:
13817 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13818 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13819 			IPHADA_M_CTL)) {
13820 			/*
13821 			 * It's an IPsec accelerated packet.
13822 			 * Make sure that the ill from which we received the
13823 			 * packet has enabled IPsec hardware acceleration.
13824 			 */
13825 			if (!(ill->ill_capabilities &
13826 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13827 				/* IPsec kstats: bean counter */
13828 				freemsg(mp);
13829 				return (B_TRUE);
13830 			}
13831 
13832 			/*
13833 			 * Make mp point to the mblk following the M_CTL,
13834 			 * then process according to type of mp.
13835 			 * After this processing, first_mp will point to
13836 			 * the data-attributes and mp to the pkt following
13837 			 * the M_CTL.
13838 			 */
13839 			mp = first_mp->b_cont;
13840 			if (mp == NULL) {
13841 				freemsg(first_mp);
13842 				return (B_TRUE);
13843 			}
13844 			/*
13845 			 * A Hardware Accelerated packet can only be M_DATA
13846 			 * ESP or AH packet.
13847 			 */
13848 			if (mp->b_datap->db_type != M_DATA) {
13849 				/* non-M_DATA IPsec accelerated packet */
13850 				IPSECHW_DEBUG(IPSECHW_PKT,
13851 				    ("non-M_DATA IPsec accelerated pkt\n"));
13852 				freemsg(first_mp);
13853 				return (B_TRUE);
13854 			}
13855 			ipha = (ipha_t *)mp->b_rptr;
13856 			if (ipha->ipha_protocol != IPPROTO_AH &&
13857 			    ipha->ipha_protocol != IPPROTO_ESP) {
13858 				IPSECHW_DEBUG(IPSECHW_PKT,
13859 				    ("non-M_DATA IPsec accelerated pkt\n"));
13860 				freemsg(first_mp);
13861 				return (B_TRUE);
13862 			}
13863 			*mpp = mp;
13864 			return (B_FALSE);
13865 		}
13866 		putnext(q, mp);
13867 		return (B_TRUE);
13868 	case M_FLUSH:
13869 		if (*mp->b_rptr & FLUSHW) {
13870 			*mp->b_rptr &= ~FLUSHR;
13871 			qreply(q, mp);
13872 			return (B_TRUE);
13873 		}
13874 		freemsg(mp);
13875 		return (B_TRUE);
13876 	case M_IOCNAK:
13877 		ip1dbg(("got iocnak "));
13878 		iocp = (struct iocblk *)mp->b_rptr;
13879 		switch (iocp->ioc_cmd) {
13880 		case DL_IOC_HDR_INFO:
13881 		case SIOCSTUNPARAM:
13882 		case OSIOCSTUNPARAM:
13883 			/*
13884 			 * Since this is on the ill stream we unconditionally
13885 			 * bump up the refcount
13886 			 */
13887 			ill_refhold(ill);
13888 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13889 			    CUR_OP, B_FALSE);
13890 			return (B_TRUE);
13891 		case SIOCGTUNPARAM:
13892 		case OSIOCGTUNPARAM:
13893 			ip_rput_other(NULL, q, mp, NULL);
13894 			return (B_TRUE);
13895 		default:
13896 			break;
13897 		}
13898 		/* FALLTHRU */
13899 	default:
13900 		putnext(q, mp);
13901 		return (B_TRUE);
13902 	}
13903 }
13904 
13905 /* Read side put procedure.  Packets coming from the wire arrive here. */
13906 void
13907 ip_rput(queue_t *q, mblk_t *mp)
13908 {
13909 	ill_t	*ill;
13910 	mblk_t	 *dmp = NULL;
13911 
13912 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13913 
13914 	ill = (ill_t *)q->q_ptr;
13915 
13916 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13917 		union DL_primitives *dl;
13918 
13919 		/*
13920 		 * Things are opening or closing. Only accept DLPI control
13921 		 * messages. In the open case, the ill->ill_ipif has not yet
13922 		 * been created. In the close case, things hanging off the
13923 		 * ill could have been freed already. In either case it
13924 		 * may not be safe to proceed further.
13925 		 */
13926 
13927 		dl = (union DL_primitives *)mp->b_rptr;
13928 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13929 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13930 			/*
13931 			 * Also SIOC[GS]TUN* ioctls can come here.
13932 			 */
13933 			inet_freemsg(mp);
13934 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13935 			    "ip_input_end: q %p (%S)", q, "uninit");
13936 			return;
13937 		}
13938 	}
13939 
13940 	/*
13941 	 * if db_ref > 1 then copymsg and free original. Packet may be
13942 	 * changed and we do not want the other entity who has a reference to
13943 	 * this message to trip over the changes. This is a blind change because
13944 	 * trying to catch all places that might change the packet is too
13945 	 * difficult.
13946 	 *
13947 	 * This corresponds to the fast path case, where we have a chain of
13948 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13949 	 * in the mblk chain. There doesn't seem to be a reason why a device
13950 	 * driver would send up data with varying db_ref counts in the mblk
13951 	 * chain. In any case the Fast path is a private interface, and our
13952 	 * drivers don't do such a thing. Given the above assumption, there is
13953 	 * no need to walk down the entire mblk chain (which could have a
13954 	 * potential performance problem)
13955 	 */
13956 	if (mp->b_datap->db_ref > 1) {
13957 		mblk_t  *mp1;
13958 		boolean_t adjusted = B_FALSE;
13959 		IP_STAT(ip_db_ref);
13960 
13961 		/*
13962 		 * The IP_RECVSLLA option depends on having the link layer
13963 		 * header. First check that:
13964 		 * a> the underlying device is of type ether, since this
13965 		 * option is currently supported only over ethernet.
13966 		 * b> there is enough room to copy over the link layer header.
13967 		 *
13968 		 * Once the checks are done, adjust rptr so that the link layer
13969 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13970 		 * be returned by some non-ethernet drivers but in this case the
13971 		 * second check will fail.
13972 		 */
13973 		if (ill->ill_type == IFT_ETHER &&
13974 		    (mp->b_rptr - mp->b_datap->db_base) >=
13975 		    sizeof (struct ether_header)) {
13976 			mp->b_rptr -= sizeof (struct ether_header);
13977 			adjusted = B_TRUE;
13978 		}
13979 		mp1 = copymsg(mp);
13980 		if (mp1 == NULL) {
13981 			mp->b_next = NULL;
13982 			/* clear b_prev - used by ip_mroute_decap */
13983 			mp->b_prev = NULL;
13984 			freemsg(mp);
13985 			BUMP_MIB(&ip_mib, ipInDiscards);
13986 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13987 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13988 			return;
13989 		}
13990 		if (adjusted) {
13991 			/*
13992 			 * Copy is done. Restore the pointer in the _new_ mblk
13993 			 */
13994 			mp1->b_rptr += sizeof (struct ether_header);
13995 		}
13996 		/* Copy b_prev - used by ip_mroute_decap */
13997 		mp1->b_prev = mp->b_prev;
13998 		mp->b_prev = NULL;
13999 		freemsg(mp);
14000 		mp = mp1;
14001 	}
14002 	if (DB_TYPE(mp) == M_DATA) {
14003 		dmp = mp;
14004 	} else if (DB_TYPE(mp) == M_PROTO &&
14005 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14006 		dmp = mp->b_cont;
14007 	}
14008 	if (dmp != NULL) {
14009 		/*
14010 		 * IP header ptr not aligned?
14011 		 * OR IP header not complete in first mblk
14012 		 */
14013 		if (!OK_32PTR(dmp->b_rptr) ||
14014 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14015 			if (!ip_check_and_align_header(q, dmp))
14016 				return;
14017 		}
14018 	}
14019 
14020 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14021 	    "ip_rput_end: q %p (%S)", q, "end");
14022 
14023 	ip_input(ill, NULL, mp, 0);
14024 }
14025 
14026 /*
14027  * Direct read side procedure capable of dealing with chains. GLDv3 based
14028  * drivers call this function directly with mblk chains while STREAMS
14029  * read side procedure ip_rput() calls this for single packet with ip_ring
14030  * set to NULL to process one packet at a time.
14031  *
14032  * The ill will always be valid if this function is called directly from
14033  * the driver.
14034  */
14035 /* ARGSUSED */
14036 void
14037 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
14038 {
14039 	ipaddr_t		dst = NULL;
14040 	ipaddr_t		prev_dst;
14041 	ire_t			*ire = NULL;
14042 	ipha_t			*ipha;
14043 	uint_t			pkt_len;
14044 	ssize_t			len;
14045 	uint_t			opt_len;
14046 	int			ll_multicast;
14047 	int			cgtp_flt_pkt;
14048 	queue_t			*q = ill->ill_rq;
14049 	squeue_t		*curr_sqp = NULL;
14050 	mblk_t 			*head = NULL;
14051 	mblk_t			*tail = NULL;
14052 	mblk_t			*first_mp;
14053 	mblk_t 			*mp;
14054 	int			cnt = 0;
14055 
14056 	ASSERT(mp_chain != NULL);
14057 	ASSERT(ill != NULL);
14058 
14059 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14060 
14061 #define	rptr	((uchar_t *)ipha)
14062 
14063 	while (mp_chain != NULL) {
14064 		first_mp = mp = mp_chain;
14065 		mp_chain = mp_chain->b_next;
14066 		mp->b_next = NULL;
14067 		ll_multicast = 0;
14068 
14069 		/*
14070 		 * We do ire caching from one iteration to
14071 		 * another. In the event the packet chain contains
14072 		 * all packets from the same dst, this caching saves
14073 		 * an ire_cache_lookup for each of the succeeding
14074 		 * packets in a packet chain.
14075 		 */
14076 		prev_dst = dst;
14077 
14078 		/*
14079 		 * ip_input fast path
14080 		 */
14081 
14082 		/* mblk type is not M_DATA */
14083 		if (mp->b_datap->db_type != M_DATA) {
14084 			if (ip_rput_process_notdata(q, &first_mp, ill,
14085 			    &ll_multicast, &mp))
14086 				continue;
14087 		}
14088 
14089 		/* Make sure its an M_DATA and that its aligned */
14090 		ASSERT(mp->b_datap->db_type == M_DATA);
14091 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14092 
14093 		ipha = (ipha_t *)mp->b_rptr;
14094 		len = mp->b_wptr - rptr;
14095 
14096 		BUMP_MIB(&ip_mib, ipInReceives);
14097 
14098 
14099 		/* multiple mblk or too short */
14100 		pkt_len = ntohs(ipha->ipha_length);
14101 		len -= pkt_len;
14102 		if (len != 0) {
14103 			/*
14104 			 * Make sure we have data length consistent
14105 			 * with the IP header.
14106 			 */
14107 			if (mp->b_cont == NULL) {
14108 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14109 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14110 					ip2dbg(("ip_input: drop pkt\n"));
14111 					freemsg(mp);
14112 					continue;
14113 				}
14114 				mp->b_wptr = rptr + pkt_len;
14115 			} else if (len += msgdsize(mp->b_cont)) {
14116 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14117 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14118 					ip2dbg(("ip_input: drop pkt\n"));
14119 					freemsg(mp);
14120 					continue;
14121 				}
14122 				(void) adjmsg(mp, -len);
14123 				IP_STAT(ip_multimblk3);
14124 			}
14125 		}
14126 
14127 		/* Obtain the dst of the current packet */
14128 		dst = ipha->ipha_dst;
14129 
14130 		if (IP_LOOPBACK_ADDR(dst) ||
14131 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14132 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14133 			cmn_err(CE_CONT, "dst %X src %X\n",
14134 			    dst, ipha->ipha_src);
14135 			freemsg(mp);
14136 			continue;
14137 		}
14138 
14139 		/*
14140 		 * Attach any necessary label information to
14141 		 * this packet
14142 		 */
14143 		if (is_system_labeled() &&
14144 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14145 			BUMP_MIB(&ip_mib, ipInDiscards);
14146 			freemsg(mp);
14147 			continue;
14148 		}
14149 
14150 		/*
14151 		 * Reuse the cached ire only if the ipha_dst of the previous
14152 		 * packet is the same as the current packet AND it is not
14153 		 * INADDR_ANY.
14154 		 */
14155 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14156 		    (ire != NULL)) {
14157 			ire_refrele(ire);
14158 			ire = NULL;
14159 		}
14160 		opt_len = ipha->ipha_version_and_hdr_length -
14161 		    IP_SIMPLE_HDR_VERSION;
14162 
14163 		/*
14164 		 * Check to see if we can take the fastpath.
14165 		 * That is possible if the following conditions are met
14166 		 *	o Tsol disabled
14167 		 *	o CGTP disabled
14168 		 *	o ipp_action_count is 0
14169 		 *	o Mobile IP not running
14170 		 *	o no options in the packet
14171 		 *	o not a RSVP packet
14172 		 * 	o not a multicast packet
14173 		 */
14174 		if (!is_system_labeled() &&
14175 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14176 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14177 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14178 		    !ll_multicast && !CLASSD(dst)) {
14179 			if (ire == NULL)
14180 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14181 
14182 			/* incoming packet is for forwarding */
14183 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14184 				ire = ip_fast_forward(ire, dst, ill, mp);
14185 				continue;
14186 			}
14187 			/* incoming packet is for local consumption */
14188 			if (ire->ire_type & IRE_LOCAL)
14189 				goto local;
14190 		}
14191 
14192 		/*
14193 		 * Disable ire caching for anything more complex
14194 		 * than the simple fast path case we checked for above.
14195 		 */
14196 		if (ire != NULL) {
14197 			ire_refrele(ire);
14198 			ire = NULL;
14199 		}
14200 
14201 		/* Full-blown slow path */
14202 		if (opt_len != 0) {
14203 			if (len != 0)
14204 				IP_STAT(ip_multimblk4);
14205 			else
14206 				IP_STAT(ip_ipoptions);
14207 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14208 				continue;
14209 		}
14210 
14211 		/*
14212 		 * Invoke the CGTP (multirouting) filtering module to process
14213 		 * the incoming packet. Packets identified as duplicates
14214 		 * must be discarded. Filtering is active only if the
14215 		 * the ip_cgtp_filter ndd variable is non-zero.
14216 		 */
14217 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14218 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14219 			cgtp_flt_pkt =
14220 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14221 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14222 				freemsg(first_mp);
14223 				continue;
14224 			}
14225 		}
14226 
14227 		/*
14228 		 * If rsvpd is running, let RSVP daemon handle its processing
14229 		 * and forwarding of RSVP multicast/unicast packets.
14230 		 * If rsvpd is not running but mrouted is running, RSVP
14231 		 * multicast packets are forwarded as multicast traffic
14232 		 * and RSVP unicast packets are forwarded by unicast router.
14233 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14234 		 * packets are not forwarded, but the unicast packets are
14235 		 * forwarded like unicast traffic.
14236 		 */
14237 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14238 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14239 			/* RSVP packet and rsvpd running. Treat as ours */
14240 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14241 			/*
14242 			 * This assumes that we deliver to all streams for
14243 			 * multicast and broadcast packets.
14244 			 * We have to force ll_multicast to 1 to handle the
14245 			 * M_DATA messages passed in from ip_mroute_decap.
14246 			 */
14247 			dst = INADDR_BROADCAST;
14248 			ll_multicast = 1;
14249 		} else if (CLASSD(dst)) {
14250 			/* packet is multicast */
14251 			mp->b_next = NULL;
14252 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14253 			    &ll_multicast, &dst))
14254 				continue;
14255 		}
14256 
14257 
14258 		/*
14259 		 * Check if the packet is coming from the Mobile IP
14260 		 * forward tunnel interface
14261 		 */
14262 		if (ill->ill_srcif_refcnt > 0) {
14263 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14264 			    NULL, ill, MATCH_IRE_TYPE);
14265 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14266 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14267 
14268 				/* We need to resolve the link layer info */
14269 				ire_refrele(ire);
14270 				ire = NULL;
14271 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14272 				    ll_multicast, dst);
14273 				continue;
14274 			}
14275 		}
14276 
14277 		if (ire == NULL) {
14278 			ire = ire_cache_lookup(dst, ALL_ZONES,
14279 			    MBLK_GETLABEL(mp));
14280 		}
14281 
14282 		/*
14283 		 * If mipagent is running and reverse tunnel is created as per
14284 		 * mobile node request, then any packet coming through the
14285 		 * incoming interface from the mobile-node, should be reverse
14286 		 * tunneled to it's home agent except those that are destined
14287 		 * to foreign agent only.
14288 		 * This needs source address based ire lookup. The routing
14289 		 * entries for source address based lookup are only created by
14290 		 * mipagent program only when a reverse tunnel is created.
14291 		 * Reference : RFC2002, RFC2344
14292 		 */
14293 		if (ill->ill_mrtun_refcnt > 0) {
14294 			ipaddr_t	srcaddr;
14295 			ire_t		*tmp_ire;
14296 
14297 			tmp_ire = ire;	/* Save, we might need it later */
14298 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14299 			    ire->ire_type != IRE_BROADCAST)) {
14300 				srcaddr = ipha->ipha_src;
14301 				ire = ire_mrtun_lookup(srcaddr, ill);
14302 				if (ire != NULL) {
14303 					/*
14304 					 * Should not be getting iphada packet
14305 					 * here. we should only get those for
14306 					 * IRE_LOCAL traffic, excluded above.
14307 					 * Fail-safe (drop packet) in the event
14308 					 * hardware is misbehaving.
14309 					 */
14310 					if (first_mp != mp) {
14311 						/* IPsec KSTATS: beancount me */
14312 						freemsg(first_mp);
14313 					} else {
14314 						/*
14315 						 * This packet must be forwarded
14316 						 * to Reverse Tunnel
14317 						 */
14318 						ip_mrtun_forward(ire, ill, mp);
14319 					}
14320 					ire_refrele(ire);
14321 					ire = NULL;
14322 					if (tmp_ire != NULL) {
14323 						ire_refrele(tmp_ire);
14324 						tmp_ire = NULL;
14325 					}
14326 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14327 					    "ip_input_end: q %p (%S)",
14328 					    q, "uninit");
14329 					continue;
14330 				}
14331 			}
14332 			/*
14333 			 * If this packet is from a non-mobilenode  or a
14334 			 * mobile-node which does not request reverse
14335 			 * tunnel service
14336 			 */
14337 			ire = tmp_ire;
14338 		}
14339 
14340 
14341 		/*
14342 		 * If we reach here that means the incoming packet satisfies
14343 		 * one of the following conditions:
14344 		 *   - packet is from a mobile node which does not request
14345 		 *	reverse tunnel
14346 		 *   - packet is from a non-mobile node, which is the most
14347 		 *	common case
14348 		 *   - packet is from a reverse tunnel enabled mobile node
14349 		 *	and destined to foreign agent only
14350 		 */
14351 
14352 		if (ire == NULL) {
14353 			/*
14354 			 * No IRE for this destination, so it can't be for us.
14355 			 * Unless we are forwarding, drop the packet.
14356 			 * We have to let source routed packets through
14357 			 * since we don't yet know if they are 'ping -l'
14358 			 * packets i.e. if they will go out over the
14359 			 * same interface as they came in on.
14360 			 */
14361 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14362 			if (ire == NULL)
14363 				continue;
14364 		}
14365 
14366 		/*
14367 		 * Broadcast IRE may indicate either broadcast or
14368 		 * multicast packet
14369 		 */
14370 		if (ire->ire_type == IRE_BROADCAST) {
14371 			/*
14372 			 * Skip broadcast checks if packet is UDP multicast;
14373 			 * we'd rather not enter ip_rput_process_broadcast()
14374 			 * unless the packet is broadcast for real, since
14375 			 * that routine is a no-op for multicast.
14376 			 */
14377 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14378 			    !CLASSD(ipha->ipha_dst)) {
14379 				ire = ip_rput_process_broadcast(&q, mp,
14380 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14381 				    ll_multicast);
14382 				if (ire == NULL)
14383 					continue;
14384 			}
14385 		} else if (ire->ire_stq != NULL) {
14386 			/* fowarding? */
14387 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14388 			    ll_multicast);
14389 			/* ip_rput_process_forward consumed the packet */
14390 			continue;
14391 		}
14392 
14393 local:
14394 		/* packet not for us */
14395 		if (ire->ire_rfq != q) {
14396 			if (ip_rput_notforus(&q, mp, ire, ill))
14397 				continue;
14398 		}
14399 
14400 		switch (ipha->ipha_protocol) {
14401 		case IPPROTO_TCP:
14402 			ASSERT(first_mp == mp);
14403 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14404 				mp, 0, q, ip_ring)) != NULL) {
14405 				if (curr_sqp == NULL) {
14406 					curr_sqp = GET_SQUEUE(mp);
14407 					ASSERT(cnt == 0);
14408 					cnt++;
14409 					head = tail = mp;
14410 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14411 					ASSERT(tail != NULL);
14412 					cnt++;
14413 					tail->b_next = mp;
14414 					tail = mp;
14415 				} else {
14416 					/*
14417 					 * A different squeue. Send the
14418 					 * chain for the previous squeue on
14419 					 * its way. This shouldn't happen
14420 					 * often unless interrupt binding
14421 					 * changes.
14422 					 */
14423 					IP_STAT(ip_input_multi_squeue);
14424 					squeue_enter_chain(curr_sqp, head,
14425 					    tail, cnt, SQTAG_IP_INPUT);
14426 					curr_sqp = GET_SQUEUE(mp);
14427 					head = mp;
14428 					tail = mp;
14429 					cnt = 1;
14430 				}
14431 			}
14432 			continue;
14433 		case IPPROTO_UDP:
14434 			ASSERT(first_mp == mp);
14435 			ip_udp_input(q, mp, ipha, ire, ill);
14436 			continue;
14437 		case IPPROTO_SCTP:
14438 			ASSERT(first_mp == mp);
14439 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14440 			    q, dst);
14441 			/* ire has been released by ip_sctp_input */
14442 			ire = NULL;
14443 			continue;
14444 		default:
14445 			ip_proto_input(q, first_mp, ipha, ire, ill);
14446 			continue;
14447 		}
14448 	}
14449 
14450 	if (ire != NULL)
14451 		ire_refrele(ire);
14452 
14453 	if (head != NULL)
14454 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14455 
14456 	/*
14457 	 * This code is there just to make netperf/ttcp look good.
14458 	 *
14459 	 * Its possible that after being in polling mode (and having cleared
14460 	 * the backlog), squeues have turned the interrupt frequency higher
14461 	 * to improve latency at the expense of more CPU utilization (less
14462 	 * packets per interrupts or more number of interrupts). Workloads
14463 	 * like ttcp/netperf do manage to tickle polling once in a while
14464 	 * but for the remaining time, stay in higher interrupt mode since
14465 	 * their packet arrival rate is pretty uniform and this shows up
14466 	 * as higher CPU utilization. Since people care about CPU utilization
14467 	 * while running netperf/ttcp, turn the interrupt frequency back to
14468 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14469 	 */
14470 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14471 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14472 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14473 			ip_ring->rr_blank(ip_ring->rr_handle,
14474 			    ip_ring->rr_normal_blank_time,
14475 			    ip_ring->rr_normal_pkt_cnt);
14476 		}
14477 	}
14478 
14479 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14480 	    "ip_input_end: q %p (%S)", q, "end");
14481 #undef	rptr
14482 }
14483 
14484 static void
14485 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14486     t_uscalar_t err)
14487 {
14488 	if (dl_err == DL_SYSERR) {
14489 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14490 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14491 		    ill->ill_name, dlpi_prim_str(prim), err);
14492 		return;
14493 	}
14494 
14495 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14496 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14497 	    dlpi_err_str(dl_err));
14498 }
14499 
14500 /*
14501  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14502  * than DL_UNITDATA_IND messages. If we need to process this message
14503  * exclusively, we call qwriter_ip, in which case we also need to call
14504  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14505  */
14506 void
14507 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14508 {
14509 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14510 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14511 	ill_t		*ill;
14512 
14513 	ip1dbg(("ip_rput_dlpi"));
14514 	ill = (ill_t *)q->q_ptr;
14515 	switch (dloa->dl_primitive) {
14516 	case DL_ERROR_ACK:
14517 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14518 		    "%s (0x%x), unix %u\n", ill->ill_name,
14519 		    dlpi_prim_str(dlea->dl_error_primitive),
14520 		    dlea->dl_error_primitive,
14521 		    dlpi_err_str(dlea->dl_errno),
14522 		    dlea->dl_errno,
14523 		    dlea->dl_unix_errno));
14524 		switch (dlea->dl_error_primitive) {
14525 		case DL_UNBIND_REQ:
14526 			mutex_enter(&ill->ill_lock);
14527 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14528 			cv_signal(&ill->ill_cv);
14529 			mutex_exit(&ill->ill_lock);
14530 			/* FALLTHRU */
14531 		case DL_NOTIFY_REQ:
14532 		case DL_ATTACH_REQ:
14533 		case DL_DETACH_REQ:
14534 		case DL_INFO_REQ:
14535 		case DL_BIND_REQ:
14536 		case DL_ENABMULTI_REQ:
14537 		case DL_PHYS_ADDR_REQ:
14538 		case DL_CAPABILITY_REQ:
14539 		case DL_CONTROL_REQ:
14540 			/*
14541 			 * Refhold the ill to match qwriter_ip which does a
14542 			 * refrele. Since this is on the ill stream we
14543 			 * unconditionally bump up the refcount without
14544 			 * checking for ILL_CAN_LOOKUP
14545 			 */
14546 			ill_refhold(ill);
14547 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14548 			    CUR_OP, B_FALSE);
14549 			return;
14550 		case DL_DISABMULTI_REQ:
14551 			freemsg(mp);	/* Don't want to pass this up */
14552 			return;
14553 		default:
14554 			break;
14555 		}
14556 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14557 		    dlea->dl_errno, dlea->dl_unix_errno);
14558 		freemsg(mp);
14559 		return;
14560 	case DL_INFO_ACK:
14561 	case DL_BIND_ACK:
14562 	case DL_PHYS_ADDR_ACK:
14563 	case DL_NOTIFY_ACK:
14564 	case DL_CAPABILITY_ACK:
14565 	case DL_CONTROL_ACK:
14566 		/*
14567 		 * Refhold the ill to match qwriter_ip which does a refrele
14568 		 * Since this is on the ill stream we unconditionally
14569 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14570 		 */
14571 		ill_refhold(ill);
14572 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14573 		    CUR_OP, B_FALSE);
14574 		return;
14575 	case DL_NOTIFY_IND:
14576 		ill_refhold(ill);
14577 		/*
14578 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14579 		 * relation to the current ioctl in progress (if any). Hence we
14580 		 * pass in NEW_OP in this case.
14581 		 */
14582 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14583 		    NEW_OP, B_FALSE);
14584 		return;
14585 	case DL_OK_ACK:
14586 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14587 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14588 		switch (dloa->dl_correct_primitive) {
14589 		case DL_UNBIND_REQ:
14590 			mutex_enter(&ill->ill_lock);
14591 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14592 			cv_signal(&ill->ill_cv);
14593 			mutex_exit(&ill->ill_lock);
14594 			/* FALLTHRU */
14595 		case DL_ATTACH_REQ:
14596 		case DL_DETACH_REQ:
14597 			/*
14598 			 * Refhold the ill to match qwriter_ip which does a
14599 			 * refrele. Since this is on the ill stream we
14600 			 * unconditionally bump up the refcount
14601 			 */
14602 			ill_refhold(ill);
14603 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14604 			    CUR_OP, B_FALSE);
14605 			return;
14606 		case DL_ENABMULTI_REQ:
14607 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14608 				ill->ill_dlpi_multicast_state = IDMS_OK;
14609 			break;
14610 
14611 		}
14612 		break;
14613 	default:
14614 		break;
14615 	}
14616 	freemsg(mp);
14617 }
14618 
14619 /*
14620  * Handling of DLPI messages that require exclusive access to the ipsq.
14621  *
14622  * Need to do ill_pending_mp_release on ioctl completion, which could
14623  * happen here. (along with mi_copy_done)
14624  */
14625 /* ARGSUSED */
14626 static void
14627 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14628 {
14629 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14630 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14631 	int		err = 0;
14632 	ill_t		*ill;
14633 	ipif_t		*ipif = NULL;
14634 	mblk_t		*mp1 = NULL;
14635 	conn_t		*connp = NULL;
14636 	t_uscalar_t	physaddr_req;
14637 	mblk_t		*mp_hw;
14638 	union DL_primitives *dlp;
14639 	boolean_t	success;
14640 	boolean_t	ioctl_aborted = B_FALSE;
14641 	boolean_t	log = B_TRUE;
14642 
14643 	ip1dbg(("ip_rput_dlpi_writer .."));
14644 	ill = (ill_t *)q->q_ptr;
14645 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14646 
14647 	ASSERT(IAM_WRITER_ILL(ill));
14648 
14649 	/*
14650 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14651 	 * both are null or non-null. However we can assert that only
14652 	 * after grabbing the ipsq_lock. So we don't make any assertion
14653 	 * here and in other places in the code.
14654 	 */
14655 	ipif = ipsq->ipsq_pending_ipif;
14656 	/*
14657 	 * The current ioctl could have been aborted by the user and a new
14658 	 * ioctl to bring up another ill could have started. We could still
14659 	 * get a response from the driver later.
14660 	 */
14661 	if (ipif != NULL && ipif->ipif_ill != ill)
14662 		ioctl_aborted = B_TRUE;
14663 
14664 	switch (dloa->dl_primitive) {
14665 	case DL_ERROR_ACK:
14666 		switch (dlea->dl_error_primitive) {
14667 		case DL_UNBIND_REQ:
14668 		case DL_ATTACH_REQ:
14669 		case DL_DETACH_REQ:
14670 		case DL_INFO_REQ:
14671 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14672 			break;
14673 		case DL_NOTIFY_REQ:
14674 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14675 			log = B_FALSE;
14676 			break;
14677 		case DL_PHYS_ADDR_REQ:
14678 			/*
14679 			 * For IPv6 only, there are two additional
14680 			 * phys_addr_req's sent to the driver to get the
14681 			 * IPv6 token and lla. This allows IP to acquire
14682 			 * the hardware address format for a given interface
14683 			 * without having built in knowledge of the hardware
14684 			 * address. ill_phys_addr_pend keeps track of the last
14685 			 * DL_PAR sent so we know which response we are
14686 			 * dealing with. ill_dlpi_done will update
14687 			 * ill_phys_addr_pend when it sends the next req.
14688 			 * We don't complete the IOCTL until all three DL_PARs
14689 			 * have been attempted, so set *_len to 0 and break.
14690 			 */
14691 			physaddr_req = ill->ill_phys_addr_pend;
14692 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14693 			if (physaddr_req == DL_IPV6_TOKEN) {
14694 				ill->ill_token_length = 0;
14695 				log = B_FALSE;
14696 				break;
14697 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14698 				ill->ill_nd_lla_len = 0;
14699 				log = B_FALSE;
14700 				break;
14701 			}
14702 			/*
14703 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14704 			 * We presumably have an IOCTL hanging out waiting
14705 			 * for completion. Find it and complete the IOCTL
14706 			 * with the error noted.
14707 			 * However, ill_dl_phys was called on an ill queue
14708 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14709 			 * set. But the ioctl is known to be pending on ill_wq.
14710 			 */
14711 			if (!ill->ill_ifname_pending)
14712 				break;
14713 			ill->ill_ifname_pending = 0;
14714 			if (!ioctl_aborted)
14715 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14716 			if (mp1 != NULL) {
14717 				/*
14718 				 * This operation (SIOCSLIFNAME) must have
14719 				 * happened on the ill. Assert there is no conn
14720 				 */
14721 				ASSERT(connp == NULL);
14722 				q = ill->ill_wq;
14723 			}
14724 			break;
14725 		case DL_BIND_REQ:
14726 			ill_dlpi_done(ill, DL_BIND_REQ);
14727 			if (ill->ill_ifname_pending)
14728 				break;
14729 			/*
14730 			 * Something went wrong with the bind.  We presumably
14731 			 * have an IOCTL hanging out waiting for completion.
14732 			 * Find it, take down the interface that was coming
14733 			 * up, and complete the IOCTL with the error noted.
14734 			 */
14735 			if (!ioctl_aborted)
14736 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14737 			if (mp1 != NULL) {
14738 				/*
14739 				 * This operation (SIOCSLIFFLAGS) must have
14740 				 * happened from a conn.
14741 				 */
14742 				ASSERT(connp != NULL);
14743 				q = CONNP_TO_WQ(connp);
14744 				if (ill->ill_move_in_progress) {
14745 					ILL_CLEAR_MOVE(ill);
14746 				}
14747 				(void) ipif_down(ipif, NULL, NULL);
14748 				/* error is set below the switch */
14749 			}
14750 			break;
14751 		case DL_ENABMULTI_REQ:
14752 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14753 
14754 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14755 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14756 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14757 				ipif_t *ipif;
14758 
14759 				log = B_FALSE;
14760 				printf("ip: joining multicasts failed (%d)"
14761 				    " on %s - will use link layer "
14762 				    "broadcasts for multicast\n",
14763 				    dlea->dl_errno, ill->ill_name);
14764 
14765 				/*
14766 				 * Set up the multicast mapping alone.
14767 				 * writer, so ok to access ill->ill_ipif
14768 				 * without any lock.
14769 				 */
14770 				ipif = ill->ill_ipif;
14771 				mutex_enter(&ill->ill_phyint->phyint_lock);
14772 				ill->ill_phyint->phyint_flags |=
14773 				    PHYI_MULTI_BCAST;
14774 				mutex_exit(&ill->ill_phyint->phyint_lock);
14775 
14776 				if (!ill->ill_isv6) {
14777 					(void) ipif_arp_setup_multicast(ipif,
14778 					    NULL);
14779 				} else {
14780 					(void) ipif_ndp_setup_multicast(ipif,
14781 					    NULL);
14782 				}
14783 			}
14784 			freemsg(mp);	/* Don't want to pass this up */
14785 			return;
14786 		case DL_CAPABILITY_REQ:
14787 		case DL_CONTROL_REQ:
14788 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14789 			    "DL_CAPABILITY/CONTROL REQ\n"));
14790 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14791 			ill->ill_capab_state = IDMS_FAILED;
14792 			freemsg(mp);
14793 			return;
14794 		}
14795 		/*
14796 		 * Note the error for IOCTL completion (mp1 is set when
14797 		 * ready to complete ioctl). If ill_ifname_pending_err is
14798 		 * set, an error occured during plumbing (ill_ifname_pending),
14799 		 * so we want to report that error.
14800 		 *
14801 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14802 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14803 		 * expected to get errack'd if the driver doesn't support
14804 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14805 		 * if these error conditions are encountered.
14806 		 */
14807 		if (mp1 != NULL) {
14808 			if (ill->ill_ifname_pending_err != 0)  {
14809 				err = ill->ill_ifname_pending_err;
14810 				ill->ill_ifname_pending_err = 0;
14811 			} else {
14812 				err = dlea->dl_unix_errno ?
14813 				    dlea->dl_unix_errno : ENXIO;
14814 			}
14815 		/*
14816 		 * If we're plumbing an interface and an error hasn't already
14817 		 * been saved, set ill_ifname_pending_err to the error passed
14818 		 * up. Ignore the error if log is B_FALSE (see comment above).
14819 		 */
14820 		} else if (log && ill->ill_ifname_pending &&
14821 		    ill->ill_ifname_pending_err == 0) {
14822 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14823 			dlea->dl_unix_errno : ENXIO;
14824 		}
14825 
14826 		if (log)
14827 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14828 			    dlea->dl_errno, dlea->dl_unix_errno);
14829 		break;
14830 	case DL_CAPABILITY_ACK: {
14831 		boolean_t reneg_flag = B_FALSE;
14832 		/* Call a routine to handle this one. */
14833 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14834 		/*
14835 		 * Check if the ACK is due to renegotiation case since we
14836 		 * will need to send a new CAPABILITY_REQ later.
14837 		 */
14838 		if (ill->ill_capab_state == IDMS_RENEG) {
14839 			/* This is the ack for a renogiation case */
14840 			reneg_flag = B_TRUE;
14841 			ill->ill_capab_state = IDMS_UNKNOWN;
14842 		}
14843 		ill_capability_ack(ill, mp);
14844 		if (reneg_flag)
14845 			ill_capability_probe(ill);
14846 		break;
14847 	}
14848 	case DL_CONTROL_ACK:
14849 		/* We treat all of these as "fire and forget" */
14850 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14851 		break;
14852 	case DL_INFO_ACK:
14853 		/* Call a routine to handle this one. */
14854 		ill_dlpi_done(ill, DL_INFO_REQ);
14855 		ip_ll_subnet_defaults(ill, mp);
14856 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14857 		return;
14858 	case DL_BIND_ACK:
14859 		/*
14860 		 * We should have an IOCTL waiting on this unless
14861 		 * sent by ill_dl_phys, in which case just return
14862 		 */
14863 		ill_dlpi_done(ill, DL_BIND_REQ);
14864 		if (ill->ill_ifname_pending)
14865 			break;
14866 
14867 		if (!ioctl_aborted)
14868 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14869 		if (mp1 == NULL)
14870 			break;
14871 		ASSERT(connp != NULL);
14872 		q = CONNP_TO_WQ(connp);
14873 
14874 		/*
14875 		 * We are exclusive. So nothing can change even after
14876 		 * we get the pending mp. If need be we can put it back
14877 		 * and restart, as in calling ipif_arp_up()  below.
14878 		 */
14879 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14880 
14881 		mutex_enter(&ill->ill_lock);
14882 		ill->ill_dl_up = 1;
14883 		mutex_exit(&ill->ill_lock);
14884 
14885 		/*
14886 		 * Now bring up the resolver, when that is
14887 		 * done we'll create IREs and we are done.
14888 		 */
14889 		if (ill->ill_isv6) {
14890 			/*
14891 			 * v6 interfaces.
14892 			 * Unlike ARP which has to do another bind
14893 			 * and attach, once we get here we are
14894 			 * done withh NDP. Except in the case of
14895 			 * ILLF_XRESOLV, in which case we send an
14896 			 * AR_INTERFACE_UP to the external resolver.
14897 			 * If all goes well, the ioctl will complete
14898 			 * in ip_rput(). If there's an error, we
14899 			 * complete it here.
14900 			 */
14901 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14902 			    B_FALSE);
14903 			if (err == 0) {
14904 				if (ill->ill_flags & ILLF_XRESOLV) {
14905 					mutex_enter(&connp->conn_lock);
14906 					mutex_enter(&ill->ill_lock);
14907 					success = ipsq_pending_mp_add(
14908 					    connp, ipif, q, mp1, 0);
14909 					mutex_exit(&ill->ill_lock);
14910 					mutex_exit(&connp->conn_lock);
14911 					if (success) {
14912 						err = ipif_resolver_up(ipif,
14913 						    B_FALSE);
14914 						if (err == EINPROGRESS) {
14915 							freemsg(mp);
14916 							return;
14917 						}
14918 						ASSERT(err != 0);
14919 						mp1 = ipsq_pending_mp_get(ipsq,
14920 						    &connp);
14921 						ASSERT(mp1 != NULL);
14922 					} else {
14923 						/* conn has started closing */
14924 						err = EINTR;
14925 					}
14926 				} else { /* Non XRESOLV interface */
14927 					err = ipif_up_done_v6(ipif);
14928 				}
14929 			}
14930 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14931 			/*
14932 			 * ARP and other v4 external resolvers.
14933 			 * Leave the pending mblk intact so that
14934 			 * the ioctl completes in ip_rput().
14935 			 */
14936 			mutex_enter(&connp->conn_lock);
14937 			mutex_enter(&ill->ill_lock);
14938 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14939 			mutex_exit(&ill->ill_lock);
14940 			mutex_exit(&connp->conn_lock);
14941 			if (success) {
14942 				err = ipif_resolver_up(ipif, B_FALSE);
14943 				if (err == EINPROGRESS) {
14944 					freemsg(mp);
14945 					return;
14946 				}
14947 				ASSERT(err != 0);
14948 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14949 			} else {
14950 				/* The conn has started closing */
14951 				err = EINTR;
14952 			}
14953 		} else {
14954 			/*
14955 			 * This one is complete. Reply to pending ioctl.
14956 			 */
14957 			err = ipif_up_done(ipif);
14958 		}
14959 
14960 		if ((err == 0) && (ill->ill_up_ipifs)) {
14961 			err = ill_up_ipifs(ill, q, mp1);
14962 			if (err == EINPROGRESS) {
14963 				freemsg(mp);
14964 				return;
14965 			}
14966 		}
14967 
14968 		if (ill->ill_up_ipifs) {
14969 			ill_group_cleanup(ill);
14970 		}
14971 
14972 		break;
14973 	case DL_NOTIFY_IND: {
14974 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14975 		ire_t *ire;
14976 		boolean_t need_ire_walk_v4 = B_FALSE;
14977 		boolean_t need_ire_walk_v6 = B_FALSE;
14978 
14979 		/*
14980 		 * Change the address everywhere we need to.
14981 		 * What we're getting here is a link-level addr or phys addr.
14982 		 * The new addr is at notify + notify->dl_addr_offset
14983 		 * The address length is notify->dl_addr_length;
14984 		 */
14985 		switch (notify->dl_notification) {
14986 		case DL_NOTE_PHYS_ADDR:
14987 			mp_hw = copyb(mp);
14988 			if (mp_hw == NULL) {
14989 				err = ENOMEM;
14990 				break;
14991 			}
14992 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14993 			/*
14994 			 * We currently don't support changing
14995 			 * the token via DL_NOTIFY_IND.
14996 			 * When we do support it, we have to consider
14997 			 * what the implications are with respect to
14998 			 * the token and the link local address.
14999 			 */
15000 			mutex_enter(&ill->ill_lock);
15001 			if (dlp->notify_ind.dl_data ==
15002 			    DL_IPV6_LINK_LAYER_ADDR) {
15003 				if (ill->ill_nd_lla_mp != NULL)
15004 					freemsg(ill->ill_nd_lla_mp);
15005 				ill->ill_nd_lla_mp = mp_hw;
15006 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15007 				    dlp->notify_ind.dl_addr_offset;
15008 				ill->ill_nd_lla_len =
15009 				    dlp->notify_ind.dl_addr_length -
15010 				    ABS(ill->ill_sap_length);
15011 				mutex_exit(&ill->ill_lock);
15012 				break;
15013 			} else if (dlp->notify_ind.dl_data ==
15014 			    DL_CURR_PHYS_ADDR) {
15015 				if (ill->ill_phys_addr_mp != NULL)
15016 					freemsg(ill->ill_phys_addr_mp);
15017 				ill->ill_phys_addr_mp = mp_hw;
15018 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15019 				    dlp->notify_ind.dl_addr_offset;
15020 				ill->ill_phys_addr_length =
15021 				    dlp->notify_ind.dl_addr_length -
15022 				    ABS(ill->ill_sap_length);
15023 				if (ill->ill_isv6 &&
15024 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15025 					if (ill->ill_nd_lla_mp != NULL)
15026 						freemsg(ill->ill_nd_lla_mp);
15027 					ill->ill_nd_lla_mp = copyb(mp_hw);
15028 					ill->ill_nd_lla = (uchar_t *)
15029 					    ill->ill_nd_lla_mp->b_rptr +
15030 					    dlp->notify_ind.dl_addr_offset;
15031 					ill->ill_nd_lla_len =
15032 					    ill->ill_phys_addr_length;
15033 				}
15034 			}
15035 			mutex_exit(&ill->ill_lock);
15036 			/*
15037 			 * Send out gratuitous arp request for our new
15038 			 * hardware address.
15039 			 */
15040 			for (ipif = ill->ill_ipif; ipif != NULL;
15041 			    ipif = ipif->ipif_next) {
15042 				if (!(ipif->ipif_flags & IPIF_UP))
15043 					continue;
15044 				if (ill->ill_isv6) {
15045 					ipif_ndp_down(ipif);
15046 					/*
15047 					 * Set B_TRUE to enable
15048 					 * ipif_ndp_up() to send out
15049 					 * unsolicited advertisements.
15050 					 */
15051 					err = ipif_ndp_up(ipif,
15052 					    &ipif->ipif_v6lcl_addr,
15053 					    B_TRUE);
15054 					if (err) {
15055 						ip1dbg((
15056 						    "ip_rput_dlpi_writer: "
15057 						    "Failed to update ndp "
15058 						    "err %d\n", err));
15059 					}
15060 				} else {
15061 					/*
15062 					 * IPv4 ARP case
15063 					 *
15064 					 * Set B_TRUE, as we only want
15065 					 * ipif_resolver_up to send an
15066 					 * AR_ENTRY_ADD request up to
15067 					 * ARP.
15068 					 */
15069 					err = ipif_resolver_up(ipif,
15070 					    B_TRUE);
15071 					if (err) {
15072 						ip1dbg((
15073 						    "ip_rput_dlpi_writer: "
15074 						    "Failed to update arp "
15075 						    "err %d\n", err));
15076 					}
15077 				}
15078 			}
15079 			/*
15080 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15081 			 * case so that all old fastpath information can be
15082 			 * purged from IRE caches.
15083 			 */
15084 		/* FALLTHRU */
15085 		case DL_NOTE_FASTPATH_FLUSH:
15086 			/*
15087 			 * Any fastpath probe sent henceforth will get the
15088 			 * new fp mp. So we first delete any ires that are
15089 			 * waiting for the fastpath. Then walk all ires and
15090 			 * delete the ire or delete the fp mp. In the case of
15091 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15092 			 * recreate the ire's without going through a complex
15093 			 * ipif up/down dance. So we don't delete the ire
15094 			 * itself, but just the nce_fp_mp for these 2 ire's
15095 			 * In the case of the other ire's we delete the ire's
15096 			 * themselves. Access to nce_fp_mp is completely
15097 			 * protected by ire_lock for IRE_MIPRTUN and
15098 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15099 			 * other cases for performance.
15100 			 */
15101 			if (ill->ill_isv6) {
15102 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15103 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15104 				    NULL);
15105 			} else {
15106 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15107 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15108 				    IRE_CACHE | IRE_BROADCAST,
15109 				    ire_fastpath_flush, NULL, ill);
15110 				mutex_enter(&ire_mrtun_lock);
15111 				if (ire_mrtun_count != 0) {
15112 					mutex_exit(&ire_mrtun_lock);
15113 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15114 					    IRE_MIPRTUN, ire_fastpath_flush,
15115 					    NULL, ill);
15116 				} else {
15117 					mutex_exit(&ire_mrtun_lock);
15118 				}
15119 			}
15120 			break;
15121 		case DL_NOTE_SDU_SIZE:
15122 			/*
15123 			 * Change the MTU size of the interface, of all
15124 			 * attached ipif's, and of all relevant ire's.  The
15125 			 * new value's a uint32_t at notify->dl_data.
15126 			 * Mtu change Vs. new ire creation - protocol below.
15127 			 *
15128 			 * a Mark the ipif as IPIF_CHANGING.
15129 			 * b Set the new mtu in the ipif.
15130 			 * c Change the ire_max_frag on all affected ires
15131 			 * d Unmark the IPIF_CHANGING
15132 			 *
15133 			 * To see how the protocol works, assume an interface
15134 			 * route is also being added simultaneously by
15135 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15136 			 * the ire. If the ire is created before step a,
15137 			 * it will be cleaned up by step c. If the ire is
15138 			 * created after step d, it will see the new value of
15139 			 * ipif_mtu. Any attempt to create the ire between
15140 			 * steps a to d will fail because of the IPIF_CHANGING
15141 			 * flag. Note that ire_create() is passed a pointer to
15142 			 * the ipif_mtu, and not the value. During ire_add
15143 			 * under the bucket lock, the ire_max_frag of the
15144 			 * new ire being created is set from the ipif/ire from
15145 			 * which it is being derived.
15146 			 */
15147 			mutex_enter(&ill->ill_lock);
15148 			ill->ill_max_frag = (uint_t)notify->dl_data;
15149 
15150 			/*
15151 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15152 			 * leave it alone
15153 			 */
15154 			if (ill->ill_mtu_userspecified) {
15155 				mutex_exit(&ill->ill_lock);
15156 				break;
15157 			}
15158 			ill->ill_max_mtu = ill->ill_max_frag;
15159 			if (ill->ill_isv6) {
15160 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15161 					ill->ill_max_mtu = IPV6_MIN_MTU;
15162 			} else {
15163 				if (ill->ill_max_mtu < IP_MIN_MTU)
15164 					ill->ill_max_mtu = IP_MIN_MTU;
15165 			}
15166 			for (ipif = ill->ill_ipif; ipif != NULL;
15167 			    ipif = ipif->ipif_next) {
15168 				/*
15169 				 * Don't override the mtu if the user
15170 				 * has explicitly set it.
15171 				 */
15172 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15173 					continue;
15174 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15175 				if (ipif->ipif_isv6)
15176 					ire = ipif_to_ire_v6(ipif);
15177 				else
15178 					ire = ipif_to_ire(ipif);
15179 				if (ire != NULL) {
15180 					ire->ire_max_frag = ipif->ipif_mtu;
15181 					ire_refrele(ire);
15182 				}
15183 				if (ipif->ipif_flags & IPIF_UP) {
15184 					if (ill->ill_isv6)
15185 						need_ire_walk_v6 = B_TRUE;
15186 					else
15187 						need_ire_walk_v4 = B_TRUE;
15188 				}
15189 			}
15190 			mutex_exit(&ill->ill_lock);
15191 			if (need_ire_walk_v4)
15192 				ire_walk_v4(ill_mtu_change, (char *)ill,
15193 				    ALL_ZONES);
15194 			if (need_ire_walk_v6)
15195 				ire_walk_v6(ill_mtu_change, (char *)ill,
15196 				    ALL_ZONES);
15197 			break;
15198 		case DL_NOTE_LINK_UP:
15199 		case DL_NOTE_LINK_DOWN: {
15200 			/*
15201 			 * We are writer. ill / phyint / ipsq assocs stable.
15202 			 * The RUNNING flag reflects the state of the link.
15203 			 */
15204 			phyint_t *phyint = ill->ill_phyint;
15205 			uint64_t new_phyint_flags;
15206 			boolean_t changed = B_FALSE;
15207 
15208 			mutex_enter(&phyint->phyint_lock);
15209 			new_phyint_flags =
15210 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
15211 			    phyint->phyint_flags | PHYI_RUNNING :
15212 			    phyint->phyint_flags & ~PHYI_RUNNING;
15213 			if (new_phyint_flags != phyint->phyint_flags) {
15214 				phyint->phyint_flags = new_phyint_flags;
15215 				changed = B_TRUE;
15216 			}
15217 			mutex_exit(&phyint->phyint_lock);
15218 			/*
15219 			 * If the flags have changed, send a message to
15220 			 * the routing socket.
15221 			 */
15222 			if (changed) {
15223 				if (phyint->phyint_illv4 != NULL) {
15224 					ip_rts_ifmsg(
15225 					    phyint->phyint_illv4->ill_ipif);
15226 				}
15227 				if (phyint->phyint_illv6 != NULL) {
15228 					ip_rts_ifmsg(
15229 					    phyint->phyint_illv6->ill_ipif);
15230 				}
15231 			}
15232 			break;
15233 		}
15234 		case DL_NOTE_PROMISC_ON_PHYS:
15235 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15236 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15237 			mutex_enter(&ill->ill_lock);
15238 			ill->ill_promisc_on_phys = B_TRUE;
15239 			mutex_exit(&ill->ill_lock);
15240 			break;
15241 		case DL_NOTE_PROMISC_OFF_PHYS:
15242 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15243 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15244 			mutex_enter(&ill->ill_lock);
15245 			ill->ill_promisc_on_phys = B_FALSE;
15246 			mutex_exit(&ill->ill_lock);
15247 			break;
15248 		case DL_NOTE_CAPAB_RENEG:
15249 			/*
15250 			 * Something changed on the driver side.
15251 			 * It wants us to renegotiate the capabilities
15252 			 * on this ill. The most likely cause is the
15253 			 * aggregation interface under us where a
15254 			 * port got added or went away.
15255 			 *
15256 			 * We reset the capabilities and set the
15257 			 * state to IDMS_RENG so that when the ack
15258 			 * comes back, we can start the
15259 			 * renegotiation process.
15260 			 */
15261 			ill_capability_reset(ill);
15262 			ill->ill_capab_state = IDMS_RENEG;
15263 			break;
15264 		default:
15265 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15266 			    "type 0x%x for DL_NOTIFY_IND\n",
15267 			    notify->dl_notification));
15268 			break;
15269 		}
15270 
15271 		/*
15272 		 * As this is an asynchronous operation, we
15273 		 * should not call ill_dlpi_done
15274 		 */
15275 		break;
15276 	}
15277 	case DL_NOTIFY_ACK:
15278 		/*
15279 		 * Don't really need to check for what notifications
15280 		 * are supported; we'll process what gets sent upstream,
15281 		 * and we know it'll be something we support changing
15282 		 * based on our DL_NOTIFY_REQ.
15283 		 */
15284 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15285 		break;
15286 	case DL_PHYS_ADDR_ACK: {
15287 		/*
15288 		 * We should have an IOCTL waiting on this when request
15289 		 * sent by ill_dl_phys.
15290 		 * However, ill_dl_phys was called on an ill queue (from
15291 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15292 		 * ioctl is known to be pending on ill_wq.
15293 		 * There are two additional phys_addr_req's sent to the
15294 		 * driver to get the token and lla. ill_phys_addr_pend
15295 		 * keeps track of the last one sent so we know which
15296 		 * response we are dealing with. ill_dlpi_done will
15297 		 * update ill_phys_addr_pend when it sends the next req.
15298 		 * We don't complete the IOCTL until all three DL_PARs
15299 		 * have been attempted.
15300 		 *
15301 		 * We don't need any lock to update ill_nd_lla* fields,
15302 		 * since the ill is not yet up, We grab the lock just
15303 		 * for uniformity with other code that accesses ill_nd_lla.
15304 		 */
15305 		physaddr_req = ill->ill_phys_addr_pend;
15306 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15307 		if (physaddr_req == DL_IPV6_TOKEN ||
15308 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15309 			if (physaddr_req == DL_IPV6_TOKEN) {
15310 				/*
15311 				 * bcopy to low-order bits of ill_token
15312 				 *
15313 				 * XXX Temporary hack - currently,
15314 				 * all known tokens are 64 bits,
15315 				 * so I'll cheat for the moment.
15316 				 */
15317 				dlp = (union DL_primitives *)mp->b_rptr;
15318 
15319 				mutex_enter(&ill->ill_lock);
15320 				bcopy((uchar_t *)(mp->b_rptr +
15321 				dlp->physaddr_ack.dl_addr_offset),
15322 				(void *)&ill->ill_token.s6_addr32[2],
15323 				dlp->physaddr_ack.dl_addr_length);
15324 				ill->ill_token_length =
15325 					dlp->physaddr_ack.dl_addr_length;
15326 				mutex_exit(&ill->ill_lock);
15327 			} else {
15328 				ASSERT(ill->ill_nd_lla_mp == NULL);
15329 				mp_hw = copyb(mp);
15330 				if (mp_hw == NULL) {
15331 					err = ENOMEM;
15332 					break;
15333 				}
15334 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15335 				mutex_enter(&ill->ill_lock);
15336 				ill->ill_nd_lla_mp = mp_hw;
15337 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15338 				dlp->physaddr_ack.dl_addr_offset;
15339 				ill->ill_nd_lla_len =
15340 					dlp->physaddr_ack.dl_addr_length;
15341 				mutex_exit(&ill->ill_lock);
15342 			}
15343 			break;
15344 		}
15345 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15346 		ASSERT(ill->ill_phys_addr_mp == NULL);
15347 		if (!ill->ill_ifname_pending)
15348 			break;
15349 		ill->ill_ifname_pending = 0;
15350 		if (!ioctl_aborted)
15351 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15352 		if (mp1 != NULL) {
15353 			ASSERT(connp == NULL);
15354 			q = ill->ill_wq;
15355 		}
15356 		/*
15357 		 * If any error acks received during the plumbing sequence,
15358 		 * ill_ifname_pending_err will be set. Break out and send up
15359 		 * the error to the pending ioctl.
15360 		 */
15361 		if (ill->ill_ifname_pending_err != 0) {
15362 			err = ill->ill_ifname_pending_err;
15363 			ill->ill_ifname_pending_err = 0;
15364 			break;
15365 		}
15366 		/*
15367 		 * Get the interface token.  If the zeroth interface
15368 		 * address is zero then set the address to the link local
15369 		 * address
15370 		 */
15371 		mp_hw = copyb(mp);
15372 		if (mp_hw == NULL) {
15373 			err = ENOMEM;
15374 			break;
15375 		}
15376 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15377 		ill->ill_phys_addr_mp = mp_hw;
15378 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15379 				dlp->physaddr_ack.dl_addr_offset;
15380 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15381 		    ill->ill_phys_addr_length == 0 ||
15382 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15383 			/*
15384 			 * Compatibility: atun driver returns a length of 0.
15385 			 * ipdptp has an ill_phys_addr_length of zero(from
15386 			 * DL_BIND_ACK) but a non-zero length here.
15387 			 * ipd has an ill_phys_addr_length of 4(from
15388 			 * DL_BIND_ACK) but a non-zero length here.
15389 			 */
15390 			ill->ill_phys_addr = NULL;
15391 		} else if (dlp->physaddr_ack.dl_addr_length !=
15392 		    ill->ill_phys_addr_length) {
15393 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15394 			    "Address length mismatch %d %d\n",
15395 			    dlp->physaddr_ack.dl_addr_length,
15396 			    ill->ill_phys_addr_length));
15397 			err = EINVAL;
15398 			break;
15399 		}
15400 		mutex_enter(&ill->ill_lock);
15401 		if (ill->ill_nd_lla_mp == NULL) {
15402 			ill->ill_nd_lla_mp = copyb(mp_hw);
15403 			if (ill->ill_nd_lla_mp == NULL) {
15404 				err = ENOMEM;
15405 				mutex_exit(&ill->ill_lock);
15406 				break;
15407 			}
15408 			ill->ill_nd_lla =
15409 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15410 			    dlp->physaddr_ack.dl_addr_offset;
15411 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15412 		}
15413 		mutex_exit(&ill->ill_lock);
15414 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15415 			(void) ill_setdefaulttoken(ill);
15416 
15417 		/*
15418 		 * If the ill zero interface has a zero address assign
15419 		 * it the proper link local address.
15420 		 */
15421 		ASSERT(ill->ill_ipif->ipif_id == 0);
15422 		if (ipif != NULL &&
15423 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15424 			(void) ipif_setlinklocal(ipif);
15425 		break;
15426 	}
15427 	case DL_OK_ACK:
15428 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15429 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15430 		    dloa->dl_correct_primitive));
15431 		switch (dloa->dl_correct_primitive) {
15432 		case DL_UNBIND_REQ:
15433 		case DL_ATTACH_REQ:
15434 		case DL_DETACH_REQ:
15435 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15436 			break;
15437 		}
15438 		break;
15439 	default:
15440 		break;
15441 	}
15442 
15443 	freemsg(mp);
15444 	if (mp1) {
15445 		struct iocblk *iocp;
15446 		int mode;
15447 
15448 		/*
15449 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15450 		 * SIOCSLIFNAME do a copyout.
15451 		 */
15452 		iocp = (struct iocblk *)mp1->b_rptr;
15453 
15454 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15455 		    iocp->ioc_cmd == SIOCSLIFNAME)
15456 			mode = COPYOUT;
15457 		else
15458 			mode = NO_COPYOUT;
15459 		/*
15460 		 * The ioctl must complete now without EINPROGRESS
15461 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15462 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15463 		 * stuck for ever in the ipsq.
15464 		 */
15465 		ASSERT(err != EINPROGRESS);
15466 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15467 
15468 	}
15469 }
15470 
15471 /*
15472  * ip_rput_other is called by ip_rput to handle messages modifying the global
15473  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15474  */
15475 /* ARGSUSED */
15476 void
15477 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15478 {
15479 	ill_t		*ill;
15480 	struct iocblk	*iocp;
15481 	mblk_t		*mp1;
15482 	conn_t		*connp = NULL;
15483 
15484 	ip1dbg(("ip_rput_other "));
15485 	ill = (ill_t *)q->q_ptr;
15486 	/*
15487 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15488 	 * in which case ipsq is NULL.
15489 	 */
15490 	if (ipsq != NULL) {
15491 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15492 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15493 	}
15494 
15495 	switch (mp->b_datap->db_type) {
15496 	case M_ERROR:
15497 	case M_HANGUP:
15498 		/*
15499 		 * The device has a problem.  We force the ILL down.  It can
15500 		 * be brought up again manually using SIOCSIFFLAGS (via
15501 		 * ifconfig or equivalent).
15502 		 */
15503 		ASSERT(ipsq != NULL);
15504 		if (mp->b_rptr < mp->b_wptr)
15505 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15506 		if (ill->ill_error == 0)
15507 			ill->ill_error = ENXIO;
15508 		if (!ill_down_start(q, mp))
15509 			return;
15510 		ipif_all_down_tail(ipsq, q, mp, NULL);
15511 		break;
15512 	case M_IOCACK:
15513 		iocp = (struct iocblk *)mp->b_rptr;
15514 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15515 		switch (iocp->ioc_cmd) {
15516 		case SIOCSTUNPARAM:
15517 		case OSIOCSTUNPARAM:
15518 			ASSERT(ipsq != NULL);
15519 			/*
15520 			 * Finish socket ioctl passed through to tun.
15521 			 * We should have an IOCTL waiting on this.
15522 			 */
15523 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15524 			if (ill->ill_isv6) {
15525 				struct iftun_req *ta;
15526 
15527 				/*
15528 				 * if a source or destination is
15529 				 * being set, try and set the link
15530 				 * local address for the tunnel
15531 				 */
15532 				ta = (struct iftun_req *)mp->b_cont->
15533 				    b_cont->b_rptr;
15534 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15535 					ipif_set_tun_llink(ill, ta);
15536 				}
15537 
15538 			}
15539 			if (mp1 != NULL) {
15540 				/*
15541 				 * Now copy back the b_next/b_prev used by
15542 				 * mi code for the mi_copy* functions.
15543 				 * See ip_sioctl_tunparam() for the reason.
15544 				 * Also protect against missing b_cont.
15545 				 */
15546 				if (mp->b_cont != NULL) {
15547 					mp->b_cont->b_next =
15548 					    mp1->b_cont->b_next;
15549 					mp->b_cont->b_prev =
15550 					    mp1->b_cont->b_prev;
15551 				}
15552 				inet_freemsg(mp1);
15553 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15554 				ASSERT(connp != NULL);
15555 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15556 				    iocp->ioc_error, NO_COPYOUT,
15557 				    ipsq->ipsq_current_ipif, ipsq);
15558 			} else {
15559 				ASSERT(connp == NULL);
15560 				putnext(q, mp);
15561 			}
15562 			break;
15563 		case SIOCGTUNPARAM:
15564 		case OSIOCGTUNPARAM:
15565 			/*
15566 			 * This is really M_IOCDATA from the tunnel driver.
15567 			 * convert back and complete the ioctl.
15568 			 * We should have an IOCTL waiting on this.
15569 			 */
15570 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15571 			if (mp1) {
15572 				/*
15573 				 * Now copy back the b_next/b_prev used by
15574 				 * mi code for the mi_copy* functions.
15575 				 * See ip_sioctl_tunparam() for the reason.
15576 				 * Also protect against missing b_cont.
15577 				 */
15578 				if (mp->b_cont != NULL) {
15579 					mp->b_cont->b_next =
15580 					    mp1->b_cont->b_next;
15581 					mp->b_cont->b_prev =
15582 					    mp1->b_cont->b_prev;
15583 				}
15584 				inet_freemsg(mp1);
15585 				if (iocp->ioc_error == 0)
15586 					mp->b_datap->db_type = M_IOCDATA;
15587 				ASSERT(connp != NULL);
15588 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15589 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15590 			} else {
15591 				ASSERT(connp == NULL);
15592 				putnext(q, mp);
15593 			}
15594 			break;
15595 		default:
15596 			break;
15597 		}
15598 		break;
15599 	case M_IOCNAK:
15600 		iocp = (struct iocblk *)mp->b_rptr;
15601 
15602 		switch (iocp->ioc_cmd) {
15603 		int mode;
15604 		ipif_t	*ipif;
15605 
15606 		case DL_IOC_HDR_INFO:
15607 			/*
15608 			 * If this was the first attempt turn of the
15609 			 * fastpath probing.
15610 			 */
15611 			mutex_enter(&ill->ill_lock);
15612 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15613 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15614 				mutex_exit(&ill->ill_lock);
15615 				ill_fastpath_nack(ill);
15616 				ip1dbg(("ip_rput: DLPI fastpath off on "
15617 				    "interface %s\n",
15618 				    ill->ill_name));
15619 			} else {
15620 				mutex_exit(&ill->ill_lock);
15621 			}
15622 			freemsg(mp);
15623 			break;
15624 		case SIOCSTUNPARAM:
15625 		case OSIOCSTUNPARAM:
15626 			ASSERT(ipsq != NULL);
15627 			/*
15628 			 * Finish socket ioctl passed through to tun
15629 			 * We should have an IOCTL waiting on this.
15630 			 */
15631 			/* FALLTHRU */
15632 		case SIOCGTUNPARAM:
15633 		case OSIOCGTUNPARAM:
15634 			/*
15635 			 * This is really M_IOCDATA from the tunnel driver.
15636 			 * convert back and complete the ioctl.
15637 			 * We should have an IOCTL waiting on this.
15638 			 */
15639 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15640 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15641 				mp1 = ill_pending_mp_get(ill, &connp,
15642 				    iocp->ioc_id);
15643 				mode = COPYOUT;
15644 				ipsq = NULL;
15645 				ipif = NULL;
15646 			} else {
15647 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15648 				mode = NO_COPYOUT;
15649 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15650 				ipif = ipsq->ipsq_current_ipif;
15651 			}
15652 			if (mp1 != NULL) {
15653 				/*
15654 				 * Now copy back the b_next/b_prev used by
15655 				 * mi code for the mi_copy* functions.
15656 				 * See ip_sioctl_tunparam() for the reason.
15657 				 * Also protect against missing b_cont.
15658 				 */
15659 				if (mp->b_cont != NULL) {
15660 					mp->b_cont->b_next =
15661 					    mp1->b_cont->b_next;
15662 					mp->b_cont->b_prev =
15663 					    mp1->b_cont->b_prev;
15664 				}
15665 				inet_freemsg(mp1);
15666 				if (iocp->ioc_error == 0)
15667 					iocp->ioc_error = EINVAL;
15668 				ASSERT(connp != NULL);
15669 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15670 				    iocp->ioc_error, mode, ipif, ipsq);
15671 			} else {
15672 				ASSERT(connp == NULL);
15673 				putnext(q, mp);
15674 			}
15675 			break;
15676 		default:
15677 			break;
15678 		}
15679 	default:
15680 		break;
15681 	}
15682 }
15683 
15684 /*
15685  * NOTE : This function does not ire_refrele the ire argument passed in.
15686  *
15687  * IPQoS notes
15688  * IP policy is invoked twice for a forwarded packet, once on the read side
15689  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15690  * enabled. An additional parameter, in_ill, has been added for this purpose.
15691  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15692  * because ip_mroute drops this information.
15693  *
15694  */
15695 void
15696 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15697 {
15698 	uint32_t	pkt_len;
15699 	queue_t	*q;
15700 	uint32_t	sum;
15701 #define	rptr	((uchar_t *)ipha)
15702 	uint32_t	max_frag;
15703 	uint32_t	ill_index;
15704 
15705 	/* Get the ill_index of the incoming ILL */
15706 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15707 
15708 	/* Initiate Read side IPPF processing */
15709 	if (IPP_ENABLED(IPP_FWD_IN)) {
15710 		ip_process(IPP_FWD_IN, &mp, ill_index);
15711 		if (mp == NULL) {
15712 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15713 			    "during IPPF processing\n"));
15714 			return;
15715 		}
15716 	}
15717 
15718 	pkt_len = ntohs(ipha->ipha_length);
15719 
15720 	/* Adjust the checksum to reflect the ttl decrement. */
15721 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15722 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15723 
15724 	if (ipha->ipha_ttl-- <= 1) {
15725 		if (ip_csum_hdr(ipha)) {
15726 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15727 			goto drop_pkt;
15728 		}
15729 		/*
15730 		 * Note: ire_stq this will be NULL for multicast
15731 		 * datagrams using the long path through arp (the IRE
15732 		 * is not an IRE_CACHE). This should not cause
15733 		 * problems since we don't generate ICMP errors for
15734 		 * multicast packets.
15735 		 */
15736 		q = ire->ire_stq;
15737 		if (q)
15738 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15739 		else
15740 			freemsg(mp);
15741 		return;
15742 	}
15743 
15744 	/*
15745 	 * Don't forward if the interface is down
15746 	 */
15747 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15748 		BUMP_MIB(&ip_mib, ipInDiscards);
15749 		ip2dbg(("ip_rput_forward:interface is down\n"));
15750 		goto drop_pkt;
15751 	}
15752 
15753 	/* Get the ill_index of the outgoing ILL */
15754 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15755 
15756 	if (is_system_labeled()) {
15757 		mblk_t *mp1;
15758 
15759 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15760 			BUMP_MIB(&ip_mib, ipForwProhibits);
15761 			goto drop_pkt;
15762 		}
15763 		/* Size may have changed */
15764 		mp = mp1;
15765 		ipha = (ipha_t *)mp->b_rptr;
15766 		pkt_len = ntohs(ipha->ipha_length);
15767 	}
15768 
15769 	/* Check if there are options to update */
15770 	if (!IS_SIMPLE_IPH(ipha)) {
15771 		if (ip_csum_hdr(ipha)) {
15772 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15773 			goto drop_pkt;
15774 		}
15775 		if (ip_rput_forward_options(mp, ipha, ire)) {
15776 			return;
15777 		}
15778 
15779 		ipha->ipha_hdr_checksum = 0;
15780 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15781 	}
15782 	max_frag = ire->ire_max_frag;
15783 	if (pkt_len > max_frag) {
15784 		/*
15785 		 * It needs fragging on its way out.  We haven't
15786 		 * verified the header checksum yet.  Since we
15787 		 * are going to put a surely good checksum in the
15788 		 * outgoing header, we have to make sure that it
15789 		 * was good coming in.
15790 		 */
15791 		if (ip_csum_hdr(ipha)) {
15792 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15793 			goto drop_pkt;
15794 		}
15795 		/* Initiate Write side IPPF processing */
15796 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15797 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15798 			if (mp == NULL) {
15799 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15800 				    " during IPPF processing\n"));
15801 				return;
15802 			}
15803 		}
15804 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15805 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
15806 		return;
15807 	}
15808 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
15809 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
15810 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
15811 	/* ip_xmit_v4 always consumes the packet */
15812 	return;
15813 
15814 drop_pkt:;
15815 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15816 	freemsg(mp);
15817 #undef	rptr
15818 }
15819 
15820 void
15821 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15822 {
15823 	ire_t	*ire;
15824 
15825 	ASSERT(!ipif->ipif_isv6);
15826 	/*
15827 	 * Find an IRE which matches the destination and the outgoing
15828 	 * queue in the cache table. All we need is an IRE_CACHE which
15829 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15830 	 * then it is enough to have some IRE_CACHE in the group.
15831 	 */
15832 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15833 		dst = ipif->ipif_pp_dst_addr;
15834 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15835 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15836 	if (ire == NULL) {
15837 		/*
15838 		 * Mark this packet to make it be delivered to
15839 		 * ip_rput_forward after the new ire has been
15840 		 * created.
15841 		 */
15842 		mp->b_prev = NULL;
15843 		mp->b_next = mp;
15844 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15845 		    NULL, 0);
15846 	} else {
15847 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15848 		IRE_REFRELE(ire);
15849 	}
15850 }
15851 
15852 /* Update any source route, record route or timestamp options */
15853 static int
15854 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15855 {
15856 	ipoptp_t	opts;
15857 	uchar_t		*opt;
15858 	uint8_t		optval;
15859 	uint8_t		optlen;
15860 	ipaddr_t	dst;
15861 	uint32_t	ts;
15862 	ire_t		*dst_ire = NULL;
15863 	ire_t		*tmp_ire = NULL;
15864 	timestruc_t	now;
15865 
15866 	ip2dbg(("ip_rput_forward_options\n"));
15867 	dst = ipha->ipha_dst;
15868 	for (optval = ipoptp_first(&opts, ipha);
15869 	    optval != IPOPT_EOL;
15870 	    optval = ipoptp_next(&opts)) {
15871 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15872 		opt = opts.ipoptp_cur;
15873 		optlen = opts.ipoptp_len;
15874 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15875 		    optval, opts.ipoptp_len));
15876 		switch (optval) {
15877 			uint32_t off;
15878 		case IPOPT_SSRR:
15879 		case IPOPT_LSRR:
15880 			/* Check if adminstratively disabled */
15881 			if (!ip_forward_src_routed) {
15882 				BUMP_MIB(&ip_mib, ipForwProhibits);
15883 				if (ire->ire_stq)
15884 					icmp_unreachable(ire->ire_stq, mp,
15885 					    ICMP_SOURCE_ROUTE_FAILED);
15886 				else {
15887 					ip0dbg(("ip_rput_forward_options: "
15888 					    "unable to send unreach\n"));
15889 					freemsg(mp);
15890 				}
15891 				return (-1);
15892 			}
15893 
15894 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15895 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15896 			if (dst_ire == NULL) {
15897 				/*
15898 				 * Must be partial since ip_rput_options
15899 				 * checked for strict.
15900 				 */
15901 				break;
15902 			}
15903 			off = opt[IPOPT_OFFSET];
15904 			off--;
15905 		redo_srr:
15906 			if (optlen < IP_ADDR_LEN ||
15907 			    off > optlen - IP_ADDR_LEN) {
15908 				/* End of source route */
15909 				ip1dbg((
15910 				    "ip_rput_forward_options: end of SR\n"));
15911 				ire_refrele(dst_ire);
15912 				break;
15913 			}
15914 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15915 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15916 			    IP_ADDR_LEN);
15917 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15918 			    ntohl(dst)));
15919 
15920 			/*
15921 			 * Check if our address is present more than
15922 			 * once as consecutive hops in source route.
15923 			 */
15924 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15925 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15926 			if (tmp_ire != NULL) {
15927 				ire_refrele(tmp_ire);
15928 				off += IP_ADDR_LEN;
15929 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15930 				goto redo_srr;
15931 			}
15932 			ipha->ipha_dst = dst;
15933 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15934 			ire_refrele(dst_ire);
15935 			break;
15936 		case IPOPT_RR:
15937 			off = opt[IPOPT_OFFSET];
15938 			off--;
15939 			if (optlen < IP_ADDR_LEN ||
15940 			    off > optlen - IP_ADDR_LEN) {
15941 				/* No more room - ignore */
15942 				ip1dbg((
15943 				    "ip_rput_forward_options: end of RR\n"));
15944 				break;
15945 			}
15946 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15947 			    IP_ADDR_LEN);
15948 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15949 			break;
15950 		case IPOPT_TS:
15951 			/* Insert timestamp if there is room */
15952 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15953 			case IPOPT_TS_TSONLY:
15954 				off = IPOPT_TS_TIMELEN;
15955 				break;
15956 			case IPOPT_TS_PRESPEC:
15957 			case IPOPT_TS_PRESPEC_RFC791:
15958 				/* Verify that the address matched */
15959 				off = opt[IPOPT_OFFSET] - 1;
15960 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15961 				dst_ire = ire_ctable_lookup(dst, 0,
15962 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15963 				    MATCH_IRE_TYPE);
15964 
15965 				if (dst_ire == NULL) {
15966 					/* Not for us */
15967 					break;
15968 				}
15969 				ire_refrele(dst_ire);
15970 				/* FALLTHRU */
15971 			case IPOPT_TS_TSANDADDR:
15972 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15973 				break;
15974 			default:
15975 				/*
15976 				 * ip_*put_options should have already
15977 				 * dropped this packet.
15978 				 */
15979 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15980 				    "unknown IT - bug in ip_rput_options?\n");
15981 				return (0);	/* Keep "lint" happy */
15982 			}
15983 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15984 				/* Increase overflow counter */
15985 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15986 				opt[IPOPT_POS_OV_FLG] =
15987 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15988 				    (off << 4));
15989 				break;
15990 			}
15991 			off = opt[IPOPT_OFFSET] - 1;
15992 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15993 			case IPOPT_TS_PRESPEC:
15994 			case IPOPT_TS_PRESPEC_RFC791:
15995 			case IPOPT_TS_TSANDADDR:
15996 				bcopy(&ire->ire_src_addr,
15997 				    (char *)opt + off, IP_ADDR_LEN);
15998 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15999 				/* FALLTHRU */
16000 			case IPOPT_TS_TSONLY:
16001 				off = opt[IPOPT_OFFSET] - 1;
16002 				/* Compute # of milliseconds since midnight */
16003 				gethrestime(&now);
16004 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16005 				    now.tv_nsec / (NANOSEC / MILLISEC);
16006 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16007 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16008 				break;
16009 			}
16010 			break;
16011 		}
16012 	}
16013 	return (0);
16014 }
16015 
16016 /*
16017  * This is called after processing at least one of AH/ESP headers.
16018  *
16019  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16020  * the actual, physical interface on which the packet was received,
16021  * but, when ip_strict_dst_multihoming is set to 1, could be the
16022  * interface which had the ipha_dst configured when the packet went
16023  * through ip_rput. The ill_index corresponding to the recv_ill
16024  * is saved in ipsec_in_rill_index
16025  */
16026 void
16027 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16028 {
16029 	mblk_t *mp;
16030 	ipaddr_t dst;
16031 	in6_addr_t *v6dstp;
16032 	ipha_t *ipha;
16033 	ip6_t *ip6h;
16034 	ipsec_in_t *ii;
16035 	boolean_t ill_need_rele = B_FALSE;
16036 	boolean_t rill_need_rele = B_FALSE;
16037 	boolean_t ire_need_rele = B_FALSE;
16038 
16039 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16040 	ASSERT(ii->ipsec_in_ill_index != 0);
16041 
16042 	mp = ipsec_mp->b_cont;
16043 	ASSERT(mp != NULL);
16044 
16045 
16046 	if (ill == NULL) {
16047 		ASSERT(recv_ill == NULL);
16048 		/*
16049 		 * We need to get the original queue on which ip_rput_local
16050 		 * or ip_rput_data_v6 was called.
16051 		 */
16052 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16053 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16054 		ill_need_rele = B_TRUE;
16055 
16056 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16057 			recv_ill = ill_lookup_on_ifindex(
16058 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16059 			    NULL, NULL, NULL, NULL);
16060 			rill_need_rele = B_TRUE;
16061 		} else {
16062 			recv_ill = ill;
16063 		}
16064 
16065 		if ((ill == NULL) || (recv_ill == NULL)) {
16066 			ip0dbg(("ip_fanout_proto_again: interface "
16067 			    "disappeared\n"));
16068 			if (ill != NULL)
16069 				ill_refrele(ill);
16070 			if (recv_ill != NULL)
16071 				ill_refrele(recv_ill);
16072 			freemsg(ipsec_mp);
16073 			return;
16074 		}
16075 	}
16076 
16077 	ASSERT(ill != NULL && recv_ill != NULL);
16078 
16079 	if (mp->b_datap->db_type == M_CTL) {
16080 		/*
16081 		 * AH/ESP is returning the ICMP message after
16082 		 * removing their headers. Fanout again till
16083 		 * it gets to the right protocol.
16084 		 */
16085 		if (ii->ipsec_in_v4) {
16086 			icmph_t *icmph;
16087 			int iph_hdr_length;
16088 			int hdr_length;
16089 
16090 			ipha = (ipha_t *)mp->b_rptr;
16091 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16092 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16093 			ipha = (ipha_t *)&icmph[1];
16094 			hdr_length = IPH_HDR_LENGTH(ipha);
16095 			/*
16096 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16097 			 * Reset the type to M_DATA.
16098 			 */
16099 			mp->b_datap->db_type = M_DATA;
16100 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16101 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16102 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16103 		} else {
16104 			icmp6_t *icmp6;
16105 			int hdr_length;
16106 
16107 			ip6h = (ip6_t *)mp->b_rptr;
16108 			/* Don't call hdr_length_v6() unless you have to. */
16109 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16110 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16111 			else
16112 				hdr_length = IPV6_HDR_LEN;
16113 
16114 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16115 			/*
16116 			 * icmp_inbound_error_fanout_v6 may need to do
16117 			 * pullupmsg.  Reset the type to M_DATA.
16118 			 */
16119 			mp->b_datap->db_type = M_DATA;
16120 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16121 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16122 		}
16123 		if (ill_need_rele)
16124 			ill_refrele(ill);
16125 		if (rill_need_rele)
16126 			ill_refrele(recv_ill);
16127 		return;
16128 	}
16129 
16130 	if (ii->ipsec_in_v4) {
16131 		ipha = (ipha_t *)mp->b_rptr;
16132 		dst = ipha->ipha_dst;
16133 		if (CLASSD(dst)) {
16134 			/*
16135 			 * Multicast has to be delivered to all streams.
16136 			 */
16137 			dst = INADDR_BROADCAST;
16138 		}
16139 
16140 		if (ire == NULL) {
16141 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16142 			    MBLK_GETLABEL(mp));
16143 			if (ire == NULL) {
16144 				if (ill_need_rele)
16145 					ill_refrele(ill);
16146 				if (rill_need_rele)
16147 					ill_refrele(recv_ill);
16148 				ip1dbg(("ip_fanout_proto_again: "
16149 				    "IRE not found"));
16150 				freemsg(ipsec_mp);
16151 				return;
16152 			}
16153 			ire_need_rele = B_TRUE;
16154 		}
16155 
16156 		switch (ipha->ipha_protocol) {
16157 			case IPPROTO_UDP:
16158 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16159 				    recv_ill);
16160 				if (ire_need_rele)
16161 					ire_refrele(ire);
16162 				break;
16163 			case IPPROTO_TCP:
16164 				if (!ire_need_rele)
16165 					IRE_REFHOLD(ire);
16166 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16167 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16168 				IRE_REFRELE(ire);
16169 				if (mp != NULL)
16170 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16171 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16172 				break;
16173 			case IPPROTO_SCTP:
16174 				if (!ire_need_rele)
16175 					IRE_REFHOLD(ire);
16176 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16177 				    ipsec_mp, 0, ill->ill_rq, dst);
16178 				break;
16179 			default:
16180 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16181 				    recv_ill);
16182 				if (ire_need_rele)
16183 					ire_refrele(ire);
16184 				break;
16185 		}
16186 	} else {
16187 		uint32_t rput_flags = 0;
16188 
16189 		ip6h = (ip6_t *)mp->b_rptr;
16190 		v6dstp = &ip6h->ip6_dst;
16191 		/*
16192 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16193 		 * address.
16194 		 *
16195 		 * Currently, we don't store that state in the IPSEC_IN
16196 		 * message, and we may need to.
16197 		 */
16198 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16199 		    IP6_IN_LLMCAST : 0);
16200 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16201 		    NULL);
16202 	}
16203 	if (ill_need_rele)
16204 		ill_refrele(ill);
16205 	if (rill_need_rele)
16206 		ill_refrele(recv_ill);
16207 }
16208 
16209 /*
16210  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16211  * returns 'true' if there are still fragments left on the queue, in
16212  * which case we restart the timer.
16213  */
16214 void
16215 ill_frag_timer(void *arg)
16216 {
16217 	ill_t	*ill = (ill_t *)arg;
16218 	boolean_t frag_pending;
16219 
16220 	mutex_enter(&ill->ill_lock);
16221 	ASSERT(!ill->ill_fragtimer_executing);
16222 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16223 		ill->ill_frag_timer_id = 0;
16224 		mutex_exit(&ill->ill_lock);
16225 		return;
16226 	}
16227 	ill->ill_fragtimer_executing = 1;
16228 	mutex_exit(&ill->ill_lock);
16229 
16230 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16231 
16232 	/*
16233 	 * Restart the timer, if we have fragments pending or if someone
16234 	 * wanted us to be scheduled again.
16235 	 */
16236 	mutex_enter(&ill->ill_lock);
16237 	ill->ill_fragtimer_executing = 0;
16238 	ill->ill_frag_timer_id = 0;
16239 	if (frag_pending || ill->ill_fragtimer_needrestart)
16240 		ill_frag_timer_start(ill);
16241 	mutex_exit(&ill->ill_lock);
16242 }
16243 
16244 void
16245 ill_frag_timer_start(ill_t *ill)
16246 {
16247 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16248 
16249 	/* If the ill is closing or opening don't proceed */
16250 	if (ill->ill_state_flags & ILL_CONDEMNED)
16251 		return;
16252 
16253 	if (ill->ill_fragtimer_executing) {
16254 		/*
16255 		 * ill_frag_timer is currently executing. Just record the
16256 		 * the fact that we want the timer to be restarted.
16257 		 * ill_frag_timer will post a timeout before it returns,
16258 		 * ensuring it will be called again.
16259 		 */
16260 		ill->ill_fragtimer_needrestart = 1;
16261 		return;
16262 	}
16263 
16264 	if (ill->ill_frag_timer_id == 0) {
16265 		/*
16266 		 * The timer is neither running nor is the timeout handler
16267 		 * executing. Post a timeout so that ill_frag_timer will be
16268 		 * called
16269 		 */
16270 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16271 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16272 		ill->ill_fragtimer_needrestart = 0;
16273 	}
16274 }
16275 
16276 /*
16277  * This routine is needed for loopback when forwarding multicasts.
16278  *
16279  * IPQoS Notes:
16280  * IPPF processing is done in fanout routines.
16281  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16282  * processing for IPSec packets is done when it comes back in clear.
16283  * NOTE : The callers of this function need to do the ire_refrele for the
16284  *	  ire that is being passed in.
16285  */
16286 void
16287 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16288     ill_t *recv_ill)
16289 {
16290 	ill_t	*ill = (ill_t *)q->q_ptr;
16291 	uint32_t	sum;
16292 	uint32_t	u1;
16293 	uint32_t	u2;
16294 	int		hdr_length;
16295 	boolean_t	mctl_present;
16296 	mblk_t		*first_mp = mp;
16297 	mblk_t		*hada_mp = NULL;
16298 	ipha_t		*inner_ipha;
16299 
16300 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16301 	    "ip_rput_locl_start: q %p", q);
16302 
16303 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16304 
16305 
16306 #define	rptr	((uchar_t *)ipha)
16307 #define	iphs	((uint16_t *)ipha)
16308 
16309 	/*
16310 	 * no UDP or TCP packet should come here anymore.
16311 	 */
16312 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16313 	    (ipha->ipha_protocol != IPPROTO_UDP));
16314 
16315 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16316 	if (mctl_present &&
16317 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16318 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16319 
16320 		/*
16321 		 * It's an IPsec accelerated packet.
16322 		 * Keep a pointer to the data attributes around until
16323 		 * we allocate the ipsec_info_t.
16324 		 */
16325 		IPSECHW_DEBUG(IPSECHW_PKT,
16326 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16327 		hada_mp = first_mp;
16328 		hada_mp->b_cont = NULL;
16329 		/*
16330 		 * Since it is accelerated, it comes directly from
16331 		 * the ill and the data attributes is followed by
16332 		 * the packet data.
16333 		 */
16334 		ASSERT(mp->b_datap->db_type != M_CTL);
16335 		first_mp = mp;
16336 		mctl_present = B_FALSE;
16337 	}
16338 
16339 	/*
16340 	 * IF M_CTL is not present, then ipsec_in_is_secure
16341 	 * should return B_TRUE. There is a case where loopback
16342 	 * packets has an M_CTL in the front with all the
16343 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16344 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16345 	 * packets never comes here, it is safe to ASSERT the
16346 	 * following.
16347 	 */
16348 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16349 
16350 
16351 	/* u1 is # words of IP options */
16352 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16353 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16354 
16355 	if (u1) {
16356 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16357 			if (hada_mp != NULL)
16358 				freemsg(hada_mp);
16359 			return;
16360 		}
16361 	} else {
16362 		/* Check the IP header checksum.  */
16363 #define	uph	((uint16_t *)ipha)
16364 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16365 		    uph[6] + uph[7] + uph[8] + uph[9];
16366 #undef  uph
16367 		/* finish doing IP checksum */
16368 		sum = (sum & 0xFFFF) + (sum >> 16);
16369 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16370 		/*
16371 		 * Don't verify header checksum if this packet is coming
16372 		 * back from AH/ESP as we already did it.
16373 		 */
16374 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16375 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16376 			goto drop_pkt;
16377 		}
16378 	}
16379 
16380 	/*
16381 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16382 	 * might be called more than once for secure packets, count only
16383 	 * the first time.
16384 	 */
16385 	if (!mctl_present) {
16386 		UPDATE_IB_PKT_COUNT(ire);
16387 		ire->ire_last_used_time = lbolt;
16388 	}
16389 
16390 	/* Check for fragmentation offset. */
16391 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16392 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16393 	if (u1) {
16394 		/*
16395 		 * We re-assemble fragments before we do the AH/ESP
16396 		 * processing. Thus, M_CTL should not be present
16397 		 * while we are re-assembling.
16398 		 */
16399 		ASSERT(!mctl_present);
16400 		ASSERT(first_mp == mp);
16401 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16402 			return;
16403 		}
16404 		/*
16405 		 * Make sure that first_mp points back to mp as
16406 		 * the mp we came in with could have changed in
16407 		 * ip_rput_fragment().
16408 		 */
16409 		ipha = (ipha_t *)mp->b_rptr;
16410 		first_mp = mp;
16411 	}
16412 
16413 	/*
16414 	 * Clear hardware checksumming flag as it is currently only
16415 	 * used by TCP and UDP.
16416 	 */
16417 	DB_CKSUMFLAGS(mp) = 0;
16418 
16419 	/* Now we have a complete datagram, destined for this machine. */
16420 	u1 = IPH_HDR_LENGTH(ipha);
16421 	switch (ipha->ipha_protocol) {
16422 	case IPPROTO_ICMP: {
16423 		ire_t		*ire_zone;
16424 		ilm_t		*ilm;
16425 		mblk_t		*mp1;
16426 		zoneid_t	last_zoneid;
16427 
16428 		if (CLASSD(ipha->ipha_dst) &&
16429 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16430 			ASSERT(ire->ire_type == IRE_BROADCAST);
16431 			/*
16432 			 * In the multicast case, applications may have joined
16433 			 * the group from different zones, so we need to deliver
16434 			 * the packet to each of them. Loop through the
16435 			 * multicast memberships structures (ilm) on the receive
16436 			 * ill and send a copy of the packet up each matching
16437 			 * one. However, we don't do this for multicasts sent on
16438 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16439 			 * they must stay in the sender's zone.
16440 			 *
16441 			 * ilm_add_v6() ensures that ilms in the same zone are
16442 			 * contiguous in the ill_ilm list. We use this property
16443 			 * to avoid sending duplicates needed when two
16444 			 * applications in the same zone join the same group on
16445 			 * different logical interfaces: we ignore the ilm if
16446 			 * its zoneid is the same as the last matching one.
16447 			 * In addition, the sending of the packet for
16448 			 * ire_zoneid is delayed until all of the other ilms
16449 			 * have been exhausted.
16450 			 */
16451 			last_zoneid = -1;
16452 			ILM_WALKER_HOLD(recv_ill);
16453 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16454 			    ilm = ilm->ilm_next) {
16455 				if ((ilm->ilm_flags & ILM_DELETED) ||
16456 				    ipha->ipha_dst != ilm->ilm_addr ||
16457 				    ilm->ilm_zoneid == last_zoneid ||
16458 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16459 				    ilm->ilm_zoneid == ALL_ZONES ||
16460 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16461 					continue;
16462 				mp1 = ip_copymsg(first_mp);
16463 				if (mp1 == NULL)
16464 					continue;
16465 				icmp_inbound(q, mp1, B_TRUE, ill,
16466 				    0, sum, mctl_present, B_TRUE,
16467 				    recv_ill, ilm->ilm_zoneid);
16468 				last_zoneid = ilm->ilm_zoneid;
16469 			}
16470 			ILM_WALKER_RELE(recv_ill);
16471 		} else if (ire->ire_type == IRE_BROADCAST) {
16472 			/*
16473 			 * In the broadcast case, there may be many zones
16474 			 * which need a copy of the packet delivered to them.
16475 			 * There is one IRE_BROADCAST per broadcast address
16476 			 * and per zone; we walk those using a helper function.
16477 			 * In addition, the sending of the packet for ire is
16478 			 * delayed until all of the other ires have been
16479 			 * processed.
16480 			 */
16481 			IRB_REFHOLD(ire->ire_bucket);
16482 			ire_zone = NULL;
16483 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16484 			    ire)) != NULL) {
16485 				mp1 = ip_copymsg(first_mp);
16486 				if (mp1 == NULL)
16487 					continue;
16488 
16489 				UPDATE_IB_PKT_COUNT(ire_zone);
16490 				ire_zone->ire_last_used_time = lbolt;
16491 				icmp_inbound(q, mp1, B_TRUE, ill,
16492 				    0, sum, mctl_present, B_TRUE,
16493 				    recv_ill, ire_zone->ire_zoneid);
16494 			}
16495 			IRB_REFRELE(ire->ire_bucket);
16496 		}
16497 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16498 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16499 		    ire->ire_zoneid);
16500 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16501 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16502 		return;
16503 	}
16504 	case IPPROTO_IGMP:
16505 		/*
16506 		 * If we are not willing to accept IGMP packets in clear,
16507 		 * then check with global policy.
16508 		 */
16509 		if (igmp_accept_clear_messages == 0) {
16510 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16511 			    ipha, NULL, mctl_present);
16512 			if (first_mp == NULL)
16513 				return;
16514 		}
16515 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16516 			freemsg(first_mp);
16517 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16518 			BUMP_MIB(&ip_mib, ipInDiscards);
16519 			return;
16520 		}
16521 		if (igmp_input(q, mp, ill)) {
16522 			/* Bad packet - discarded by igmp_input */
16523 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16524 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16525 			if (mctl_present)
16526 				freeb(first_mp);
16527 			return;
16528 		}
16529 		/*
16530 		 * igmp_input() may have pulled up the message so ipha needs to
16531 		 * be reinitialized.
16532 		 */
16533 		ipha = (ipha_t *)mp->b_rptr;
16534 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16535 			/* No user-level listener for IGMP packets */
16536 			goto drop_pkt;
16537 		}
16538 		/* deliver to local raw users */
16539 		break;
16540 	case IPPROTO_PIM:
16541 		/*
16542 		 * If we are not willing to accept PIM packets in clear,
16543 		 * then check with global policy.
16544 		 */
16545 		if (pim_accept_clear_messages == 0) {
16546 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16547 			    ipha, NULL, mctl_present);
16548 			if (first_mp == NULL)
16549 				return;
16550 		}
16551 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16552 			freemsg(first_mp);
16553 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16554 			BUMP_MIB(&ip_mib, ipInDiscards);
16555 			return;
16556 		}
16557 		if (pim_input(q, mp) != 0) {
16558 			/* Bad packet - discarded by pim_input */
16559 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16560 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16561 			if (mctl_present)
16562 				freeb(first_mp);
16563 			return;
16564 		}
16565 
16566 		/*
16567 		 * pim_input() may have pulled up the message so ipha needs to
16568 		 * be reinitialized.
16569 		 */
16570 		ipha = (ipha_t *)mp->b_rptr;
16571 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16572 			/* No user-level listener for PIM packets */
16573 			goto drop_pkt;
16574 		}
16575 		/* deliver to local raw users */
16576 		break;
16577 	case IPPROTO_ENCAP:
16578 		/*
16579 		 * Handle self-encapsulated packets (IP-in-IP where
16580 		 * the inner addresses == the outer addresses).
16581 		 */
16582 		hdr_length = IPH_HDR_LENGTH(ipha);
16583 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16584 		    mp->b_wptr) {
16585 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16586 			    sizeof (ipha_t) - mp->b_rptr)) {
16587 				BUMP_MIB(&ip_mib, ipInDiscards);
16588 				freemsg(first_mp);
16589 				return;
16590 			}
16591 			ipha = (ipha_t *)mp->b_rptr;
16592 		}
16593 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16594 		/*
16595 		 * Check the sanity of the inner IP header.
16596 		 */
16597 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16598 			BUMP_MIB(&ip_mib, ipInDiscards);
16599 			freemsg(first_mp);
16600 			return;
16601 		}
16602 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16603 			BUMP_MIB(&ip_mib, ipInDiscards);
16604 			freemsg(first_mp);
16605 			return;
16606 		}
16607 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16608 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16609 			ipsec_in_t *ii;
16610 
16611 			/*
16612 			 * Self-encapsulated tunnel packet. Remove
16613 			 * the outer IP header and fanout again.
16614 			 * We also need to make sure that the inner
16615 			 * header is pulled up until options.
16616 			 */
16617 			mp->b_rptr = (uchar_t *)inner_ipha;
16618 			ipha = inner_ipha;
16619 			hdr_length = IPH_HDR_LENGTH(ipha);
16620 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16621 				if (!pullupmsg(mp, (uchar_t *)ipha +
16622 				    + hdr_length - mp->b_rptr)) {
16623 					freemsg(first_mp);
16624 					return;
16625 				}
16626 				ipha = (ipha_t *)mp->b_rptr;
16627 			}
16628 			if (!mctl_present) {
16629 				ASSERT(first_mp == mp);
16630 				/*
16631 				 * This means that somebody is sending
16632 				 * Self-encapsualted packets without AH/ESP.
16633 				 * If AH/ESP was present, we would have already
16634 				 * allocated the first_mp.
16635 				 */
16636 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16637 				    NULL) {
16638 					ip1dbg(("ip_proto_input: IPSEC_IN "
16639 					    "allocation failure.\n"));
16640 					BUMP_MIB(&ip_mib, ipInDiscards);
16641 					freemsg(mp);
16642 					return;
16643 				}
16644 				first_mp->b_cont = mp;
16645 			}
16646 			/*
16647 			 * We generally store the ill_index if we need to
16648 			 * do IPSEC processing as we lose the ill queue when
16649 			 * we come back. But in this case, we never should
16650 			 * have to store the ill_index here as it should have
16651 			 * been stored previously when we processed the
16652 			 * AH/ESP header in this routine or for non-ipsec
16653 			 * cases, we still have the queue. But for some bad
16654 			 * packets from the wire, we can get to IPSEC after
16655 			 * this and we better store the index for that case.
16656 			 */
16657 			ill = (ill_t *)q->q_ptr;
16658 			ii = (ipsec_in_t *)first_mp->b_rptr;
16659 			ii->ipsec_in_ill_index =
16660 			    ill->ill_phyint->phyint_ifindex;
16661 			ii->ipsec_in_rill_index =
16662 			    recv_ill->ill_phyint->phyint_ifindex;
16663 			if (ii->ipsec_in_decaps) {
16664 				/*
16665 				 * This packet is self-encapsulated multiple
16666 				 * times. We don't want to recurse infinitely.
16667 				 * To keep it simple, drop the packet.
16668 				 */
16669 				BUMP_MIB(&ip_mib, ipInDiscards);
16670 				freemsg(first_mp);
16671 				return;
16672 			}
16673 			ii->ipsec_in_decaps = B_TRUE;
16674 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16675 			return;
16676 		}
16677 		break;
16678 	case IPPROTO_AH:
16679 	case IPPROTO_ESP: {
16680 		/*
16681 		 * Fast path for AH/ESP. If this is the first time
16682 		 * we are sending a datagram to AH/ESP, allocate
16683 		 * a IPSEC_IN message and prepend it. Otherwise,
16684 		 * just fanout.
16685 		 */
16686 
16687 		int ipsec_rc;
16688 		ipsec_in_t *ii;
16689 
16690 		IP_STAT(ipsec_proto_ahesp);
16691 		if (!mctl_present) {
16692 			ASSERT(first_mp == mp);
16693 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16694 				ip1dbg(("ip_proto_input: IPSEC_IN "
16695 				    "allocation failure.\n"));
16696 				freemsg(hada_mp); /* okay ifnull */
16697 				BUMP_MIB(&ip_mib, ipInDiscards);
16698 				freemsg(mp);
16699 				return;
16700 			}
16701 			/*
16702 			 * Store the ill_index so that when we come back
16703 			 * from IPSEC we ride on the same queue.
16704 			 */
16705 			ill = (ill_t *)q->q_ptr;
16706 			ii = (ipsec_in_t *)first_mp->b_rptr;
16707 			ii->ipsec_in_ill_index =
16708 			    ill->ill_phyint->phyint_ifindex;
16709 			ii->ipsec_in_rill_index =
16710 			    recv_ill->ill_phyint->phyint_ifindex;
16711 			first_mp->b_cont = mp;
16712 			/*
16713 			 * Cache hardware acceleration info.
16714 			 */
16715 			if (hada_mp != NULL) {
16716 				IPSECHW_DEBUG(IPSECHW_PKT,
16717 				    ("ip_rput_local: caching data attr.\n"));
16718 				ii->ipsec_in_accelerated = B_TRUE;
16719 				ii->ipsec_in_da = hada_mp;
16720 				hada_mp = NULL;
16721 			}
16722 		} else {
16723 			ii = (ipsec_in_t *)first_mp->b_rptr;
16724 		}
16725 
16726 		if (!ipsec_loaded()) {
16727 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16728 			    ire->ire_zoneid);
16729 			return;
16730 		}
16731 
16732 		/* select inbound SA and have IPsec process the pkt */
16733 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16734 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16735 			if (esph == NULL)
16736 				return;
16737 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16738 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16739 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16740 			    first_mp, esph);
16741 		} else {
16742 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16743 			if (ah == NULL)
16744 				return;
16745 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16746 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16747 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16748 			    first_mp, ah);
16749 		}
16750 
16751 		switch (ipsec_rc) {
16752 		case IPSEC_STATUS_SUCCESS:
16753 			break;
16754 		case IPSEC_STATUS_FAILED:
16755 			BUMP_MIB(&ip_mib, ipInDiscards);
16756 			/* FALLTHRU */
16757 		case IPSEC_STATUS_PENDING:
16758 			return;
16759 		}
16760 		/* we're done with IPsec processing, send it up */
16761 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16762 		return;
16763 	}
16764 	default:
16765 		break;
16766 	}
16767 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16768 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16769 		    ire->ire_zoneid));
16770 		goto drop_pkt;
16771 	}
16772 	/*
16773 	 * Handle protocols with which IP is less intimate.  There
16774 	 * can be more than one stream bound to a particular
16775 	 * protocol.  When this is the case, each one gets a copy
16776 	 * of any incoming packets.
16777 	 */
16778 	ip_fanout_proto(q, first_mp, ill, ipha,
16779 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16780 	    B_TRUE, recv_ill, ire->ire_zoneid);
16781 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16782 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16783 	return;
16784 
16785 drop_pkt:
16786 	freemsg(first_mp);
16787 	if (hada_mp != NULL)
16788 		freeb(hada_mp);
16789 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16790 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16791 #undef	rptr
16792 #undef  iphs
16793 
16794 }
16795 
16796 /*
16797  * Update any source route, record route or timestamp options.
16798  * Check that we are at end of strict source route.
16799  * The options have already been checked for sanity in ip_rput_options().
16800  */
16801 static boolean_t
16802 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16803 {
16804 	ipoptp_t	opts;
16805 	uchar_t		*opt;
16806 	uint8_t		optval;
16807 	uint8_t		optlen;
16808 	ipaddr_t	dst;
16809 	uint32_t	ts;
16810 	ire_t		*dst_ire;
16811 	timestruc_t	now;
16812 
16813 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16814 
16815 	ip2dbg(("ip_rput_local_options\n"));
16816 
16817 	for (optval = ipoptp_first(&opts, ipha);
16818 	    optval != IPOPT_EOL;
16819 	    optval = ipoptp_next(&opts)) {
16820 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16821 		opt = opts.ipoptp_cur;
16822 		optlen = opts.ipoptp_len;
16823 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16824 		    optval, optlen));
16825 		switch (optval) {
16826 			uint32_t off;
16827 		case IPOPT_SSRR:
16828 		case IPOPT_LSRR:
16829 			off = opt[IPOPT_OFFSET];
16830 			off--;
16831 			if (optlen < IP_ADDR_LEN ||
16832 			    off > optlen - IP_ADDR_LEN) {
16833 				/* End of source route */
16834 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16835 				break;
16836 			}
16837 			/*
16838 			 * This will only happen if two consecutive entries
16839 			 * in the source route contains our address or if
16840 			 * it is a packet with a loose source route which
16841 			 * reaches us before consuming the whole source route
16842 			 */
16843 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16844 			if (optval == IPOPT_SSRR) {
16845 				goto bad_src_route;
16846 			}
16847 			/*
16848 			 * Hack: instead of dropping the packet truncate the
16849 			 * source route to what has been used by filling the
16850 			 * rest with IPOPT_NOP.
16851 			 */
16852 			opt[IPOPT_OLEN] = (uint8_t)off;
16853 			while (off < optlen) {
16854 				opt[off++] = IPOPT_NOP;
16855 			}
16856 			break;
16857 		case IPOPT_RR:
16858 			off = opt[IPOPT_OFFSET];
16859 			off--;
16860 			if (optlen < IP_ADDR_LEN ||
16861 			    off > optlen - IP_ADDR_LEN) {
16862 				/* No more room - ignore */
16863 				ip1dbg((
16864 				    "ip_rput_local_options: end of RR\n"));
16865 				break;
16866 			}
16867 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16868 			    IP_ADDR_LEN);
16869 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16870 			break;
16871 		case IPOPT_TS:
16872 			/* Insert timestamp if there is romm */
16873 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16874 			case IPOPT_TS_TSONLY:
16875 				off = IPOPT_TS_TIMELEN;
16876 				break;
16877 			case IPOPT_TS_PRESPEC:
16878 			case IPOPT_TS_PRESPEC_RFC791:
16879 				/* Verify that the address matched */
16880 				off = opt[IPOPT_OFFSET] - 1;
16881 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16882 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16883 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16884 				if (dst_ire == NULL) {
16885 					/* Not for us */
16886 					break;
16887 				}
16888 				ire_refrele(dst_ire);
16889 				/* FALLTHRU */
16890 			case IPOPT_TS_TSANDADDR:
16891 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16892 				break;
16893 			default:
16894 				/*
16895 				 * ip_*put_options should have already
16896 				 * dropped this packet.
16897 				 */
16898 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16899 				    "unknown IT - bug in ip_rput_options?\n");
16900 				return (B_TRUE);	/* Keep "lint" happy */
16901 			}
16902 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16903 				/* Increase overflow counter */
16904 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16905 				opt[IPOPT_POS_OV_FLG] =
16906 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16907 				    (off << 4));
16908 				break;
16909 			}
16910 			off = opt[IPOPT_OFFSET] - 1;
16911 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16912 			case IPOPT_TS_PRESPEC:
16913 			case IPOPT_TS_PRESPEC_RFC791:
16914 			case IPOPT_TS_TSANDADDR:
16915 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16916 				    IP_ADDR_LEN);
16917 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16918 				/* FALLTHRU */
16919 			case IPOPT_TS_TSONLY:
16920 				off = opt[IPOPT_OFFSET] - 1;
16921 				/* Compute # of milliseconds since midnight */
16922 				gethrestime(&now);
16923 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16924 				    now.tv_nsec / (NANOSEC / MILLISEC);
16925 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16926 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16927 				break;
16928 			}
16929 			break;
16930 		}
16931 	}
16932 	return (B_TRUE);
16933 
16934 bad_src_route:
16935 	q = WR(q);
16936 	/* make sure we clear any indication of a hardware checksum */
16937 	DB_CKSUMFLAGS(mp) = 0;
16938 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16939 	return (B_FALSE);
16940 
16941 }
16942 
16943 /*
16944  * Process IP options in an inbound packet.  If an option affects the
16945  * effective destination address, return the next hop address via dstp.
16946  * Returns -1 if something fails in which case an ICMP error has been sent
16947  * and mp freed.
16948  */
16949 static int
16950 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16951 {
16952 	ipoptp_t	opts;
16953 	uchar_t		*opt;
16954 	uint8_t		optval;
16955 	uint8_t		optlen;
16956 	ipaddr_t	dst;
16957 	intptr_t	code = 0;
16958 	ire_t		*ire = NULL;
16959 
16960 	ip2dbg(("ip_rput_options\n"));
16961 	dst = ipha->ipha_dst;
16962 	for (optval = ipoptp_first(&opts, ipha);
16963 	    optval != IPOPT_EOL;
16964 	    optval = ipoptp_next(&opts)) {
16965 		opt = opts.ipoptp_cur;
16966 		optlen = opts.ipoptp_len;
16967 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16968 		    optval, optlen));
16969 		/*
16970 		 * Note: we need to verify the checksum before we
16971 		 * modify anything thus this routine only extracts the next
16972 		 * hop dst from any source route.
16973 		 */
16974 		switch (optval) {
16975 			uint32_t off;
16976 		case IPOPT_SSRR:
16977 		case IPOPT_LSRR:
16978 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16979 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16980 			if (ire == NULL) {
16981 				if (optval == IPOPT_SSRR) {
16982 					ip1dbg(("ip_rput_options: not next"
16983 					    " strict source route 0x%x\n",
16984 					    ntohl(dst)));
16985 					code = (char *)&ipha->ipha_dst -
16986 					    (char *)ipha;
16987 					goto param_prob; /* RouterReq's */
16988 				}
16989 				ip2dbg(("ip_rput_options: "
16990 				    "not next source route 0x%x\n",
16991 				    ntohl(dst)));
16992 				break;
16993 			}
16994 			ire_refrele(ire);
16995 
16996 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16997 				ip1dbg((
16998 				    "ip_rput_options: bad option offset\n"));
16999 				code = (char *)&opt[IPOPT_OLEN] -
17000 				    (char *)ipha;
17001 				goto param_prob;
17002 			}
17003 			off = opt[IPOPT_OFFSET];
17004 			off--;
17005 		redo_srr:
17006 			if (optlen < IP_ADDR_LEN ||
17007 			    off > optlen - IP_ADDR_LEN) {
17008 				/* End of source route */
17009 				ip1dbg(("ip_rput_options: end of SR\n"));
17010 				break;
17011 			}
17012 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17013 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17014 			    ntohl(dst)));
17015 
17016 			/*
17017 			 * Check if our address is present more than
17018 			 * once as consecutive hops in source route.
17019 			 * XXX verify per-interface ip_forwarding
17020 			 * for source route?
17021 			 */
17022 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17023 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17024 
17025 			if (ire != NULL) {
17026 				ire_refrele(ire);
17027 				off += IP_ADDR_LEN;
17028 				goto redo_srr;
17029 			}
17030 
17031 			if (dst == htonl(INADDR_LOOPBACK)) {
17032 				ip1dbg(("ip_rput_options: loopback addr in "
17033 				    "source route!\n"));
17034 				goto bad_src_route;
17035 			}
17036 			/*
17037 			 * For strict: verify that dst is directly
17038 			 * reachable.
17039 			 */
17040 			if (optval == IPOPT_SSRR) {
17041 				ire = ire_ftable_lookup(dst, 0, 0,
17042 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17043 				    MBLK_GETLABEL(mp),
17044 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17045 				if (ire == NULL) {
17046 					ip1dbg(("ip_rput_options: SSRR not "
17047 					    "directly reachable: 0x%x\n",
17048 					    ntohl(dst)));
17049 					goto bad_src_route;
17050 				}
17051 				ire_refrele(ire);
17052 			}
17053 			/*
17054 			 * Defer update of the offset and the record route
17055 			 * until the packet is forwarded.
17056 			 */
17057 			break;
17058 		case IPOPT_RR:
17059 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17060 				ip1dbg((
17061 				    "ip_rput_options: bad option offset\n"));
17062 				code = (char *)&opt[IPOPT_OLEN] -
17063 				    (char *)ipha;
17064 				goto param_prob;
17065 			}
17066 			break;
17067 		case IPOPT_TS:
17068 			/*
17069 			 * Verify that length >= 5 and that there is either
17070 			 * room for another timestamp or that the overflow
17071 			 * counter is not maxed out.
17072 			 */
17073 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17074 			if (optlen < IPOPT_MINLEN_IT) {
17075 				goto param_prob;
17076 			}
17077 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17078 				ip1dbg((
17079 				    "ip_rput_options: bad option offset\n"));
17080 				code = (char *)&opt[IPOPT_OFFSET] -
17081 				    (char *)ipha;
17082 				goto param_prob;
17083 			}
17084 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17085 			case IPOPT_TS_TSONLY:
17086 				off = IPOPT_TS_TIMELEN;
17087 				break;
17088 			case IPOPT_TS_TSANDADDR:
17089 			case IPOPT_TS_PRESPEC:
17090 			case IPOPT_TS_PRESPEC_RFC791:
17091 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17092 				break;
17093 			default:
17094 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17095 				    (char *)ipha;
17096 				goto param_prob;
17097 			}
17098 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17099 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17100 				/*
17101 				 * No room and the overflow counter is 15
17102 				 * already.
17103 				 */
17104 				goto param_prob;
17105 			}
17106 			break;
17107 		}
17108 	}
17109 
17110 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17111 		*dstp = dst;
17112 		return (0);
17113 	}
17114 
17115 	ip1dbg(("ip_rput_options: error processing IP options."));
17116 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17117 
17118 param_prob:
17119 	q = WR(q);
17120 	/* make sure we clear any indication of a hardware checksum */
17121 	DB_CKSUMFLAGS(mp) = 0;
17122 	icmp_param_problem(q, mp, (uint8_t)code);
17123 	return (-1);
17124 
17125 bad_src_route:
17126 	q = WR(q);
17127 	/* make sure we clear any indication of a hardware checksum */
17128 	DB_CKSUMFLAGS(mp) = 0;
17129 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
17130 	return (-1);
17131 }
17132 
17133 /*
17134  * IP & ICMP info in >=14 msg's ...
17135  *  - ip fixed part (mib2_ip_t)
17136  *  - icmp fixed part (mib2_icmp_t)
17137  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17138  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17139  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17140  *  - ipRouteAttributeTable (ip 102)	labeled routes
17141  *  - ip multicast membership (ip_member_t)
17142  *  - ip multicast source filtering (ip_grpsrc_t)
17143  *  - igmp fixed part (struct igmpstat)
17144  *  - multicast routing stats (struct mrtstat)
17145  *  - multicast routing vifs (array of struct vifctl)
17146  *  - multicast routing routes (array of struct mfcctl)
17147  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17148  *					One per ill plus one generic
17149  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17150  *					One per ill plus one generic
17151  *  - ipv6RouteEntry			all IPv6 IREs
17152  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17153  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17154  *  - ipv6AddrEntry			all IPv6 ipifs
17155  *  - ipv6 multicast membership (ipv6_member_t)
17156  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17157  *
17158  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17159  * already present.
17160  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17161  * already filled in by the caller.
17162  * Return value of 0 indicates that no messages were sent and caller
17163  * should free mpctl.
17164  */
17165 int
17166 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17167 {
17168 
17169 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17170 		return (0);
17171 	}
17172 
17173 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17174 		return (1);
17175 	}
17176 
17177 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17178 		return (1);
17179 	}
17180 
17181 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17182 		return (1);
17183 	}
17184 
17185 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17186 		return (1);
17187 	}
17188 
17189 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17190 		return (1);
17191 	}
17192 
17193 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17194 		return (1);
17195 	}
17196 
17197 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17198 		return (1);
17199 	}
17200 
17201 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17202 		return (1);
17203 	}
17204 
17205 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17206 		return (1);
17207 	}
17208 
17209 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17210 		return (1);
17211 	}
17212 
17213 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17214 		return (1);
17215 	}
17216 
17217 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17218 		return (1);
17219 	}
17220 
17221 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17222 		return (1);
17223 	}
17224 
17225 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17226 		return (1);
17227 	}
17228 
17229 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17230 		return (1);
17231 	}
17232 
17233 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17234 		return (1);
17235 	}
17236 
17237 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17238 		return (1);
17239 	}
17240 	freemsg(mpctl);
17241 	return (1);
17242 }
17243 
17244 
17245 /* Get global IPv4 statistics */
17246 static mblk_t *
17247 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17248 {
17249 	struct opthdr		*optp;
17250 	mblk_t			*mp2ctl;
17251 
17252 	/*
17253 	 * make a copy of the original message
17254 	 */
17255 	mp2ctl = copymsg(mpctl);
17256 
17257 	/* fixed length IP structure... */
17258 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17259 	optp->level = MIB2_IP;
17260 	optp->name = 0;
17261 	SET_MIB(ip_mib.ipForwarding,
17262 	    (WE_ARE_FORWARDING ? 1 : 2));
17263 	SET_MIB(ip_mib.ipDefaultTTL,
17264 	    (uint32_t)ip_def_ttl);
17265 	SET_MIB(ip_mib.ipReasmTimeout,
17266 	    ip_g_frag_timeout);
17267 	SET_MIB(ip_mib.ipAddrEntrySize,
17268 	    sizeof (mib2_ipAddrEntry_t));
17269 	SET_MIB(ip_mib.ipRouteEntrySize,
17270 	    sizeof (mib2_ipRouteEntry_t));
17271 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17272 	    sizeof (mib2_ipNetToMediaEntry_t));
17273 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17274 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17275 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17276 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17277 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17278 	    (int)sizeof (ip_mib))) {
17279 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17280 		    (uint_t)sizeof (ip_mib)));
17281 	}
17282 
17283 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17284 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17285 	    (int)optp->level, (int)optp->name, (int)optp->len));
17286 	qreply(q, mpctl);
17287 	return (mp2ctl);
17288 }
17289 
17290 /* Global IPv4 ICMP statistics */
17291 static mblk_t *
17292 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17293 {
17294 	struct opthdr		*optp;
17295 	mblk_t			*mp2ctl;
17296 
17297 	/*
17298 	 * Make a copy of the original message
17299 	 */
17300 	mp2ctl = copymsg(mpctl);
17301 
17302 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17303 	optp->level = MIB2_ICMP;
17304 	optp->name = 0;
17305 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17306 	    (int)sizeof (icmp_mib))) {
17307 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17308 		    (uint_t)sizeof (icmp_mib)));
17309 	}
17310 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17311 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17312 	    (int)optp->level, (int)optp->name, (int)optp->len));
17313 	qreply(q, mpctl);
17314 	return (mp2ctl);
17315 }
17316 
17317 /* Global IPv4 IGMP statistics */
17318 static mblk_t *
17319 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17320 {
17321 	struct opthdr		*optp;
17322 	mblk_t			*mp2ctl;
17323 
17324 	/*
17325 	 * make a copy of the original message
17326 	 */
17327 	mp2ctl = copymsg(mpctl);
17328 
17329 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17330 	optp->level = EXPER_IGMP;
17331 	optp->name = 0;
17332 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17333 	    (int)sizeof (igmpstat))) {
17334 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17335 		    (uint_t)sizeof (igmpstat)));
17336 	}
17337 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17338 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17339 	    (int)optp->level, (int)optp->name, (int)optp->len));
17340 	qreply(q, mpctl);
17341 	return (mp2ctl);
17342 }
17343 
17344 /* Global IPv4 Multicast Routing statistics */
17345 static mblk_t *
17346 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17347 {
17348 	struct opthdr		*optp;
17349 	mblk_t			*mp2ctl;
17350 
17351 	/*
17352 	 * make a copy of the original message
17353 	 */
17354 	mp2ctl = copymsg(mpctl);
17355 
17356 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17357 	optp->level = EXPER_DVMRP;
17358 	optp->name = 0;
17359 	if (!ip_mroute_stats(mpctl->b_cont)) {
17360 		ip0dbg(("ip_mroute_stats: failed\n"));
17361 	}
17362 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17363 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17364 	    (int)optp->level, (int)optp->name, (int)optp->len));
17365 	qreply(q, mpctl);
17366 	return (mp2ctl);
17367 }
17368 
17369 /* IPv4 address information */
17370 static mblk_t *
17371 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17372 {
17373 	struct opthdr		*optp;
17374 	mblk_t			*mp2ctl;
17375 	mblk_t			*mp_tail = NULL;
17376 	ill_t			*ill;
17377 	ipif_t			*ipif;
17378 	uint_t			bitval;
17379 	mib2_ipAddrEntry_t	mae;
17380 	zoneid_t		zoneid;
17381 	ill_walk_context_t ctx;
17382 
17383 	/*
17384 	 * make a copy of the original message
17385 	 */
17386 	mp2ctl = copymsg(mpctl);
17387 
17388 	/* ipAddrEntryTable */
17389 
17390 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17391 	optp->level = MIB2_IP;
17392 	optp->name = MIB2_IP_ADDR;
17393 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17394 
17395 	rw_enter(&ill_g_lock, RW_READER);
17396 	ill = ILL_START_WALK_V4(&ctx);
17397 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17398 		for (ipif = ill->ill_ipif; ipif != NULL;
17399 		    ipif = ipif->ipif_next) {
17400 			if (ipif->ipif_zoneid != zoneid &&
17401 			    ipif->ipif_zoneid != ALL_ZONES)
17402 				continue;
17403 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17404 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17405 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17406 
17407 			(void) ipif_get_name(ipif,
17408 			    mae.ipAdEntIfIndex.o_bytes,
17409 			    OCTET_LENGTH);
17410 			mae.ipAdEntIfIndex.o_length =
17411 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17412 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17413 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17414 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17415 			mae.ipAdEntInfo.ae_subnet_len =
17416 			    ip_mask_to_plen(ipif->ipif_net_mask);
17417 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17418 			for (bitval = 1;
17419 			    bitval &&
17420 			    !(bitval & ipif->ipif_brd_addr);
17421 			    bitval <<= 1)
17422 				noop;
17423 			mae.ipAdEntBcastAddr = bitval;
17424 			mae.ipAdEntReasmMaxSize = 65535;
17425 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17426 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17427 			mae.ipAdEntInfo.ae_broadcast_addr =
17428 			    ipif->ipif_brd_addr;
17429 			mae.ipAdEntInfo.ae_pp_dst_addr =
17430 			    ipif->ipif_pp_dst_addr;
17431 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17432 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17433 
17434 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17435 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17436 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17437 				    "allocate %u bytes\n",
17438 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17439 			}
17440 		}
17441 	}
17442 	rw_exit(&ill_g_lock);
17443 
17444 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17445 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17446 	    (int)optp->level, (int)optp->name, (int)optp->len));
17447 	qreply(q, mpctl);
17448 	return (mp2ctl);
17449 }
17450 
17451 /* IPv6 address information */
17452 static mblk_t *
17453 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17454 {
17455 	struct opthdr		*optp;
17456 	mblk_t			*mp2ctl;
17457 	mblk_t			*mp_tail = NULL;
17458 	ill_t			*ill;
17459 	ipif_t			*ipif;
17460 	mib2_ipv6AddrEntry_t	mae6;
17461 	zoneid_t		zoneid;
17462 	ill_walk_context_t	ctx;
17463 
17464 	/*
17465 	 * make a copy of the original message
17466 	 */
17467 	mp2ctl = copymsg(mpctl);
17468 
17469 	/* ipv6AddrEntryTable */
17470 
17471 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17472 	optp->level = MIB2_IP6;
17473 	optp->name = MIB2_IP6_ADDR;
17474 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17475 
17476 	rw_enter(&ill_g_lock, RW_READER);
17477 	ill = ILL_START_WALK_V6(&ctx);
17478 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17479 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17480 			if (ipif->ipif_zoneid != zoneid &&
17481 			    ipif->ipif_zoneid != ALL_ZONES)
17482 				continue;
17483 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17484 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17485 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17486 
17487 			(void) ipif_get_name(ipif,
17488 			    mae6.ipv6AddrIfIndex.o_bytes,
17489 			    OCTET_LENGTH);
17490 			mae6.ipv6AddrIfIndex.o_length =
17491 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17492 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17493 			mae6.ipv6AddrPfxLength =
17494 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17495 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17496 			mae6.ipv6AddrInfo.ae_subnet_len =
17497 			    mae6.ipv6AddrPfxLength;
17498 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17499 
17500 			/* Type: stateless(1), stateful(2), unknown(3) */
17501 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17502 				mae6.ipv6AddrType = 1;
17503 			else
17504 				mae6.ipv6AddrType = 2;
17505 			/* Anycast: true(1), false(2) */
17506 			if (ipif->ipif_flags & IPIF_ANYCAST)
17507 				mae6.ipv6AddrAnycastFlag = 1;
17508 			else
17509 				mae6.ipv6AddrAnycastFlag = 2;
17510 
17511 			/*
17512 			 * Address status: preferred(1), deprecated(2),
17513 			 * invalid(3), inaccessible(4), unknown(5)
17514 			 */
17515 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17516 				mae6.ipv6AddrStatus = 3;
17517 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17518 				mae6.ipv6AddrStatus = 2;
17519 			else
17520 				mae6.ipv6AddrStatus = 1;
17521 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17522 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17523 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17524 						ipif->ipif_v6pp_dst_addr;
17525 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17526 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17527 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17528 				(char *)&mae6,
17529 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17530 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17531 				    "allocate %u bytes\n",
17532 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17533 			}
17534 		}
17535 	}
17536 	rw_exit(&ill_g_lock);
17537 
17538 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17539 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17540 	    (int)optp->level, (int)optp->name, (int)optp->len));
17541 	qreply(q, mpctl);
17542 	return (mp2ctl);
17543 }
17544 
17545 /* IPv4 multicast group membership. */
17546 static mblk_t *
17547 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17548 {
17549 	struct opthdr		*optp;
17550 	mblk_t			*mp2ctl;
17551 	ill_t			*ill;
17552 	ipif_t			*ipif;
17553 	ilm_t			*ilm;
17554 	ip_member_t		ipm;
17555 	mblk_t			*mp_tail = NULL;
17556 	ill_walk_context_t	ctx;
17557 	zoneid_t		zoneid;
17558 
17559 	/*
17560 	 * make a copy of the original message
17561 	 */
17562 	mp2ctl = copymsg(mpctl);
17563 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17564 
17565 	/* ipGroupMember table */
17566 	optp = (struct opthdr *)&mpctl->b_rptr[
17567 	    sizeof (struct T_optmgmt_ack)];
17568 	optp->level = MIB2_IP;
17569 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17570 
17571 	rw_enter(&ill_g_lock, RW_READER);
17572 	ill = ILL_START_WALK_V4(&ctx);
17573 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17574 		ILM_WALKER_HOLD(ill);
17575 		for (ipif = ill->ill_ipif; ipif != NULL;
17576 		    ipif = ipif->ipif_next) {
17577 			if (ipif->ipif_zoneid != zoneid &&
17578 			    ipif->ipif_zoneid != ALL_ZONES)
17579 				continue;	/* not this zone */
17580 			(void) ipif_get_name(ipif,
17581 			    ipm.ipGroupMemberIfIndex.o_bytes,
17582 			    OCTET_LENGTH);
17583 			ipm.ipGroupMemberIfIndex.o_length =
17584 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17585 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17586 				ASSERT(ilm->ilm_ipif != NULL);
17587 				ASSERT(ilm->ilm_ill == NULL);
17588 				if (ilm->ilm_ipif != ipif)
17589 					continue;
17590 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17591 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17592 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17593 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17594 				    (char *)&ipm, (int)sizeof (ipm))) {
17595 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17596 					    "failed to allocate %u bytes\n",
17597 						(uint_t)sizeof (ipm)));
17598 				}
17599 			}
17600 		}
17601 		ILM_WALKER_RELE(ill);
17602 	}
17603 	rw_exit(&ill_g_lock);
17604 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17605 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17606 	    (int)optp->level, (int)optp->name, (int)optp->len));
17607 	qreply(q, mpctl);
17608 	return (mp2ctl);
17609 }
17610 
17611 /* IPv6 multicast group membership. */
17612 static mblk_t *
17613 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17614 {
17615 	struct opthdr		*optp;
17616 	mblk_t			*mp2ctl;
17617 	ill_t			*ill;
17618 	ilm_t			*ilm;
17619 	ipv6_member_t		ipm6;
17620 	mblk_t			*mp_tail = NULL;
17621 	ill_walk_context_t	ctx;
17622 	zoneid_t		zoneid;
17623 
17624 	/*
17625 	 * make a copy of the original message
17626 	 */
17627 	mp2ctl = copymsg(mpctl);
17628 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17629 
17630 	/* ip6GroupMember table */
17631 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17632 	optp->level = MIB2_IP6;
17633 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17634 
17635 	rw_enter(&ill_g_lock, RW_READER);
17636 	ill = ILL_START_WALK_V6(&ctx);
17637 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17638 		ILM_WALKER_HOLD(ill);
17639 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17640 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17641 			ASSERT(ilm->ilm_ipif == NULL);
17642 			ASSERT(ilm->ilm_ill != NULL);
17643 			if (ilm->ilm_zoneid != zoneid)
17644 				continue;	/* not this zone */
17645 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17646 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17647 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17648 			if (!snmp_append_data2(mpctl->b_cont,
17649 			    &mp_tail,
17650 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17651 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17652 				    "failed to allocate %u bytes\n",
17653 				    (uint_t)sizeof (ipm6)));
17654 			}
17655 		}
17656 		ILM_WALKER_RELE(ill);
17657 	}
17658 	rw_exit(&ill_g_lock);
17659 
17660 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17661 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17662 	    (int)optp->level, (int)optp->name, (int)optp->len));
17663 	qreply(q, mpctl);
17664 	return (mp2ctl);
17665 }
17666 
17667 /* IP multicast filtered sources */
17668 static mblk_t *
17669 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17670 {
17671 	struct opthdr		*optp;
17672 	mblk_t			*mp2ctl;
17673 	ill_t			*ill;
17674 	ipif_t			*ipif;
17675 	ilm_t			*ilm;
17676 	ip_grpsrc_t		ips;
17677 	mblk_t			*mp_tail = NULL;
17678 	ill_walk_context_t	ctx;
17679 	zoneid_t		zoneid;
17680 	int			i;
17681 	slist_t			*sl;
17682 
17683 	/*
17684 	 * make a copy of the original message
17685 	 */
17686 	mp2ctl = copymsg(mpctl);
17687 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17688 
17689 	/* ipGroupSource table */
17690 	optp = (struct opthdr *)&mpctl->b_rptr[
17691 	    sizeof (struct T_optmgmt_ack)];
17692 	optp->level = MIB2_IP;
17693 	optp->name = EXPER_IP_GROUP_SOURCES;
17694 
17695 	rw_enter(&ill_g_lock, RW_READER);
17696 	ill = ILL_START_WALK_V4(&ctx);
17697 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17698 		ILM_WALKER_HOLD(ill);
17699 		for (ipif = ill->ill_ipif; ipif != NULL;
17700 		    ipif = ipif->ipif_next) {
17701 			if (ipif->ipif_zoneid != zoneid)
17702 				continue;	/* not this zone */
17703 			(void) ipif_get_name(ipif,
17704 			    ips.ipGroupSourceIfIndex.o_bytes,
17705 			    OCTET_LENGTH);
17706 			ips.ipGroupSourceIfIndex.o_length =
17707 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17708 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17709 				ASSERT(ilm->ilm_ipif != NULL);
17710 				ASSERT(ilm->ilm_ill == NULL);
17711 				sl = ilm->ilm_filter;
17712 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17713 					continue;
17714 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17715 				for (i = 0; i < sl->sl_numsrc; i++) {
17716 					if (!IN6_IS_ADDR_V4MAPPED(
17717 					    &sl->sl_addr[i]))
17718 						continue;
17719 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17720 					    ips.ipGroupSourceAddress);
17721 					if (snmp_append_data2(mpctl->b_cont,
17722 					    &mp_tail, (char *)&ips,
17723 					    (int)sizeof (ips)) == 0) {
17724 						ip1dbg(("ip_snmp_get_mib2_"
17725 						    "ip_group_src: failed to "
17726 						    "allocate %u bytes\n",
17727 						    (uint_t)sizeof (ips)));
17728 					}
17729 				}
17730 			}
17731 		}
17732 		ILM_WALKER_RELE(ill);
17733 	}
17734 	rw_exit(&ill_g_lock);
17735 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17736 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17737 	    (int)optp->level, (int)optp->name, (int)optp->len));
17738 	qreply(q, mpctl);
17739 	return (mp2ctl);
17740 }
17741 
17742 /* IPv6 multicast filtered sources. */
17743 static mblk_t *
17744 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17745 {
17746 	struct opthdr		*optp;
17747 	mblk_t			*mp2ctl;
17748 	ill_t			*ill;
17749 	ilm_t			*ilm;
17750 	ipv6_grpsrc_t		ips6;
17751 	mblk_t			*mp_tail = NULL;
17752 	ill_walk_context_t	ctx;
17753 	zoneid_t		zoneid;
17754 	int			i;
17755 	slist_t			*sl;
17756 
17757 	/*
17758 	 * make a copy of the original message
17759 	 */
17760 	mp2ctl = copymsg(mpctl);
17761 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17762 
17763 	/* ip6GroupMember table */
17764 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17765 	optp->level = MIB2_IP6;
17766 	optp->name = EXPER_IP6_GROUP_SOURCES;
17767 
17768 	rw_enter(&ill_g_lock, RW_READER);
17769 	ill = ILL_START_WALK_V6(&ctx);
17770 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17771 		ILM_WALKER_HOLD(ill);
17772 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17773 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17774 			ASSERT(ilm->ilm_ipif == NULL);
17775 			ASSERT(ilm->ilm_ill != NULL);
17776 			sl = ilm->ilm_filter;
17777 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17778 				continue;
17779 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17780 			for (i = 0; i < sl->sl_numsrc; i++) {
17781 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17782 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17783 				    (char *)&ips6, (int)sizeof (ips6))) {
17784 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17785 					    "group_src: failed to allocate "
17786 					    "%u bytes\n",
17787 					    (uint_t)sizeof (ips6)));
17788 				}
17789 			}
17790 		}
17791 		ILM_WALKER_RELE(ill);
17792 	}
17793 	rw_exit(&ill_g_lock);
17794 
17795 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17796 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17797 	    (int)optp->level, (int)optp->name, (int)optp->len));
17798 	qreply(q, mpctl);
17799 	return (mp2ctl);
17800 }
17801 
17802 /* Multicast routing virtual interface table. */
17803 static mblk_t *
17804 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17805 {
17806 	struct opthdr		*optp;
17807 	mblk_t			*mp2ctl;
17808 
17809 	/*
17810 	 * make a copy of the original message
17811 	 */
17812 	mp2ctl = copymsg(mpctl);
17813 
17814 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17815 	optp->level = EXPER_DVMRP;
17816 	optp->name = EXPER_DVMRP_VIF;
17817 	if (!ip_mroute_vif(mpctl->b_cont)) {
17818 		ip0dbg(("ip_mroute_vif: failed\n"));
17819 	}
17820 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17821 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17822 	    (int)optp->level, (int)optp->name, (int)optp->len));
17823 	qreply(q, mpctl);
17824 	return (mp2ctl);
17825 }
17826 
17827 /* Multicast routing table. */
17828 static mblk_t *
17829 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17830 {
17831 	struct opthdr		*optp;
17832 	mblk_t			*mp2ctl;
17833 
17834 	/*
17835 	 * make a copy of the original message
17836 	 */
17837 	mp2ctl = copymsg(mpctl);
17838 
17839 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17840 	optp->level = EXPER_DVMRP;
17841 	optp->name = EXPER_DVMRP_MRT;
17842 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17843 		ip0dbg(("ip_mroute_mrt: failed\n"));
17844 	}
17845 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17846 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17847 	    (int)optp->level, (int)optp->name, (int)optp->len));
17848 	qreply(q, mpctl);
17849 	return (mp2ctl);
17850 }
17851 
17852 /*
17853  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17854  * in one IRE walk.
17855  */
17856 static mblk_t *
17857 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17858 {
17859 	struct opthdr	*optp;
17860 	mblk_t		*mp2ctl;	/* Returned */
17861 	mblk_t		*mp3ctl;	/* nettomedia */
17862 	mblk_t		*mp4ctl;	/* routeattrs */
17863 	iproutedata_t	ird;
17864 	zoneid_t	zoneid;
17865 
17866 	/*
17867 	 * make copies of the original message
17868 	 *	- mp2ctl is returned unchanged to the caller for his use
17869 	 *	- mpctl is sent upstream as ipRouteEntryTable
17870 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17871 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17872 	 */
17873 	mp2ctl = copymsg(mpctl);
17874 	mp3ctl = copymsg(mpctl);
17875 	mp4ctl = copymsg(mpctl);
17876 	if (mp3ctl == NULL || mp4ctl == NULL) {
17877 		freemsg(mp4ctl);
17878 		freemsg(mp3ctl);
17879 		freemsg(mp2ctl);
17880 		freemsg(mpctl);
17881 		return (NULL);
17882 	}
17883 
17884 	bzero(&ird, sizeof (ird));
17885 
17886 	ird.ird_route.lp_head = mpctl->b_cont;
17887 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17888 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17889 
17890 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17891 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17892 	if (zoneid == GLOBAL_ZONEID) {
17893 		/*
17894 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17895 		 * the sys_net_config privilege, it can only run in the global
17896 		 * zone, so we don't display these IREs in the other zones.
17897 		 */
17898 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17899 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17900 	}
17901 
17902 	/* ipRouteEntryTable in mpctl */
17903 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17904 	optp->level = MIB2_IP;
17905 	optp->name = MIB2_IP_ROUTE;
17906 	optp->len = msgdsize(ird.ird_route.lp_head);
17907 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17908 	    (int)optp->level, (int)optp->name, (int)optp->len));
17909 	qreply(q, mpctl);
17910 
17911 	/* ipNetToMediaEntryTable in mp3ctl */
17912 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17913 	optp->level = MIB2_IP;
17914 	optp->name = MIB2_IP_MEDIA;
17915 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17916 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17917 	    (int)optp->level, (int)optp->name, (int)optp->len));
17918 	qreply(q, mp3ctl);
17919 
17920 	/* ipRouteAttributeTable in mp4ctl */
17921 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17922 	optp->level = MIB2_IP;
17923 	optp->name = EXPER_IP_RTATTR;
17924 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17925 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17926 	    (int)optp->level, (int)optp->name, (int)optp->len));
17927 	if (optp->len == 0)
17928 		freemsg(mp4ctl);
17929 	else
17930 		qreply(q, mp4ctl);
17931 
17932 	return (mp2ctl);
17933 }
17934 
17935 /*
17936  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17937  * ipv6NetToMediaEntryTable in an NDP walk.
17938  */
17939 static mblk_t *
17940 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17941 {
17942 	struct opthdr	*optp;
17943 	mblk_t		*mp2ctl;	/* Returned */
17944 	mblk_t		*mp3ctl;	/* nettomedia */
17945 	mblk_t		*mp4ctl;	/* routeattrs */
17946 	iproutedata_t	ird;
17947 	zoneid_t	zoneid;
17948 
17949 	/*
17950 	 * make copies of the original message
17951 	 *	- mp2ctl is returned unchanged to the caller for his use
17952 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17953 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17954 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17955 	 */
17956 	mp2ctl = copymsg(mpctl);
17957 	mp3ctl = copymsg(mpctl);
17958 	mp4ctl = copymsg(mpctl);
17959 	if (mp3ctl == NULL || mp4ctl == NULL) {
17960 		freemsg(mp4ctl);
17961 		freemsg(mp3ctl);
17962 		freemsg(mp2ctl);
17963 		freemsg(mpctl);
17964 		return (NULL);
17965 	}
17966 
17967 	bzero(&ird, sizeof (ird));
17968 
17969 	ird.ird_route.lp_head = mpctl->b_cont;
17970 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17971 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17972 
17973 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17974 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17975 
17976 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17977 	optp->level = MIB2_IP6;
17978 	optp->name = MIB2_IP6_ROUTE;
17979 	optp->len = msgdsize(ird.ird_route.lp_head);
17980 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17981 	    (int)optp->level, (int)optp->name, (int)optp->len));
17982 	qreply(q, mpctl);
17983 
17984 	/* ipv6NetToMediaEntryTable in mp3ctl */
17985 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17986 
17987 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17988 	optp->level = MIB2_IP6;
17989 	optp->name = MIB2_IP6_MEDIA;
17990 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17991 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17992 	    (int)optp->level, (int)optp->name, (int)optp->len));
17993 	qreply(q, mp3ctl);
17994 
17995 	/* ipv6RouteAttributeTable in mp4ctl */
17996 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17997 	optp->level = MIB2_IP6;
17998 	optp->name = EXPER_IP_RTATTR;
17999 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18000 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18001 	    (int)optp->level, (int)optp->name, (int)optp->len));
18002 	if (optp->len == 0)
18003 		freemsg(mp4ctl);
18004 	else
18005 		qreply(q, mp4ctl);
18006 
18007 	return (mp2ctl);
18008 }
18009 
18010 /*
18011  * ICMPv6 mib: One per ill
18012  */
18013 static mblk_t *
18014 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18015 {
18016 	struct opthdr		*optp;
18017 	mblk_t			*mp2ctl;
18018 	ill_t			*ill;
18019 	ill_walk_context_t	ctx;
18020 	mblk_t			*mp_tail = NULL;
18021 
18022 	/*
18023 	 * Make a copy of the original message
18024 	 */
18025 	mp2ctl = copymsg(mpctl);
18026 
18027 	/* fixed length IPv6 structure ... */
18028 
18029 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18030 	optp->level = MIB2_IP6;
18031 	optp->name = 0;
18032 	/* Include "unknown interface" ip6_mib */
18033 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18034 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18035 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18036 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18037 	    sizeof (mib2_ipv6IfStatsEntry_t));
18038 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18039 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18040 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18041 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18042 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18043 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18044 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18045 	    (int)sizeof (ip6_mib))) {
18046 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18047 		    (uint_t)sizeof (ip6_mib)));
18048 	}
18049 
18050 	rw_enter(&ill_g_lock, RW_READER);
18051 	ill = ILL_START_WALK_V6(&ctx);
18052 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18053 		ill->ill_ip6_mib->ipv6IfIndex =
18054 		    ill->ill_phyint->phyint_ifindex;
18055 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18056 		    ipv6_forward ? 1 : 2);
18057 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18058 		    ill->ill_max_hops);
18059 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18060 		    sizeof (mib2_ipv6IfStatsEntry_t));
18061 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18062 		    sizeof (mib2_ipv6AddrEntry_t));
18063 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18064 		    sizeof (mib2_ipv6RouteEntry_t));
18065 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18066 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18067 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18068 		    sizeof (ipv6_member_t));
18069 
18070 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18071 		    (char *)ill->ill_ip6_mib,
18072 		    (int)sizeof (*ill->ill_ip6_mib))) {
18073 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18074 				"%u bytes\n",
18075 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18076 		}
18077 	}
18078 	rw_exit(&ill_g_lock);
18079 
18080 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18081 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18082 	    (int)optp->level, (int)optp->name, (int)optp->len));
18083 	qreply(q, mpctl);
18084 	return (mp2ctl);
18085 }
18086 
18087 /*
18088  * ICMPv6 mib: One per ill
18089  */
18090 static mblk_t *
18091 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18092 {
18093 	struct opthdr		*optp;
18094 	mblk_t			*mp2ctl;
18095 	ill_t			*ill;
18096 	ill_walk_context_t	ctx;
18097 	mblk_t			*mp_tail = NULL;
18098 	/*
18099 	 * Make a copy of the original message
18100 	 */
18101 	mp2ctl = copymsg(mpctl);
18102 
18103 	/* fixed length ICMPv6 structure ... */
18104 
18105 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18106 	optp->level = MIB2_ICMP6;
18107 	optp->name = 0;
18108 	/* Include "unknown interface" icmp6_mib */
18109 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18110 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18111 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18112 	    (int)sizeof (icmp6_mib))) {
18113 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18114 		    (uint_t)sizeof (icmp6_mib)));
18115 	}
18116 
18117 	rw_enter(&ill_g_lock, RW_READER);
18118 	ill = ILL_START_WALK_V6(&ctx);
18119 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18120 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18121 		    ill->ill_phyint->phyint_ifindex;
18122 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18123 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18124 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18125 		    (char *)ill->ill_icmp6_mib,
18126 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18127 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18128 			    "%u bytes\n",
18129 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18130 		}
18131 	}
18132 	rw_exit(&ill_g_lock);
18133 
18134 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18135 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18136 	    (int)optp->level, (int)optp->name, (int)optp->len));
18137 	qreply(q, mpctl);
18138 	return (mp2ctl);
18139 }
18140 
18141 /*
18142  * ire_walk routine to create both ipRouteEntryTable and
18143  * ipNetToMediaEntryTable in one IRE walk
18144  */
18145 static void
18146 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18147 {
18148 	ill_t				*ill;
18149 	ipif_t				*ipif;
18150 	mblk_t				*llmp;
18151 	dl_unitdata_req_t		*dlup;
18152 	mib2_ipRouteEntry_t		*re;
18153 	mib2_ipNetToMediaEntry_t	ntme;
18154 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18155 	ipaddr_t			gw_addr;
18156 	tsol_ire_gw_secattr_t		*attrp;
18157 	tsol_gc_t			*gc = NULL;
18158 	tsol_gcgrp_t			*gcgrp = NULL;
18159 	uint_t				sacnt = 0;
18160 	int				i;
18161 
18162 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18163 
18164 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18165 		return;
18166 
18167 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18168 		mutex_enter(&attrp->igsa_lock);
18169 		if ((gc = attrp->igsa_gc) != NULL) {
18170 			gcgrp = gc->gc_grp;
18171 			ASSERT(gcgrp != NULL);
18172 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18173 			sacnt = 1;
18174 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18175 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18176 			gc = gcgrp->gcgrp_head;
18177 			sacnt = gcgrp->gcgrp_count;
18178 		}
18179 		mutex_exit(&attrp->igsa_lock);
18180 
18181 		/* do nothing if there's no gc to report */
18182 		if (gc == NULL) {
18183 			ASSERT(sacnt == 0);
18184 			if (gcgrp != NULL) {
18185 				/* we might as well drop the lock now */
18186 				rw_exit(&gcgrp->gcgrp_rwlock);
18187 				gcgrp = NULL;
18188 			}
18189 			attrp = NULL;
18190 		}
18191 
18192 		ASSERT(gc == NULL || (gcgrp != NULL &&
18193 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18194 	}
18195 	ASSERT(sacnt == 0 || gc != NULL);
18196 
18197 	if (sacnt != 0 &&
18198 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18199 		kmem_free(re, sizeof (*re));
18200 		rw_exit(&gcgrp->gcgrp_rwlock);
18201 		return;
18202 	}
18203 
18204 	/*
18205 	 * Return all IRE types for route table... let caller pick and choose
18206 	 */
18207 	re->ipRouteDest = ire->ire_addr;
18208 	ipif = ire->ire_ipif;
18209 	re->ipRouteIfIndex.o_length = 0;
18210 	if (ire->ire_type == IRE_CACHE) {
18211 		ill = (ill_t *)ire->ire_stq->q_ptr;
18212 		re->ipRouteIfIndex.o_length =
18213 		    ill->ill_name_length == 0 ? 0 :
18214 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18215 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18216 		    re->ipRouteIfIndex.o_length);
18217 	} else if (ipif != NULL) {
18218 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18219 		    OCTET_LENGTH);
18220 		re->ipRouteIfIndex.o_length =
18221 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18222 	}
18223 	re->ipRouteMetric1 = -1;
18224 	re->ipRouteMetric2 = -1;
18225 	re->ipRouteMetric3 = -1;
18226 	re->ipRouteMetric4 = -1;
18227 
18228 	gw_addr = ire->ire_gateway_addr;
18229 
18230 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18231 		re->ipRouteNextHop = ire->ire_src_addr;
18232 	else
18233 		re->ipRouteNextHop = gw_addr;
18234 	/* indirect(4), direct(3), or invalid(2) */
18235 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18236 		re->ipRouteType = 2;
18237 	else
18238 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18239 	re->ipRouteProto = -1;
18240 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18241 	re->ipRouteMask = ire->ire_mask;
18242 	re->ipRouteMetric5 = -1;
18243 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18244 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18245 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18246 	if (ire->ire_nce &&
18247 	    ire->ire_nce->nce_state == ND_REACHABLE)
18248 		llmp = ire->ire_nce->nce_res_mp;
18249 	else
18250 		llmp = NULL;
18251 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18252 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18253 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18254 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18255 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18256 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18257 	re->ipRouteInfo.re_in_ill.o_length = 0;
18258 	if (ire->ire_in_ill != NULL) {
18259 		re->ipRouteInfo.re_in_ill.o_length =
18260 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18261 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18262 		bcopy(ire->ire_in_ill->ill_name,
18263 		    re->ipRouteInfo.re_in_ill.o_bytes,
18264 		    re->ipRouteInfo.re_in_ill.o_length);
18265 	}
18266 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18267 
18268 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18269 	    (char *)re, (int)sizeof (*re))) {
18270 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18271 		    (uint_t)sizeof (*re)));
18272 	}
18273 
18274 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18275 		iaeptr->iae_routeidx = ird->ird_idx;
18276 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18277 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18278 	}
18279 
18280 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18281 	    (char *)iae, sacnt * sizeof (*iae))) {
18282 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18283 		    (unsigned)(sacnt * sizeof (*iae))));
18284 	}
18285 
18286 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18287 		goto done;
18288 	/*
18289 	 * only IRE_CACHE entries that are for a directly connected subnet
18290 	 * get appended to net -> phys addr table
18291 	 * (others in arp)
18292 	 */
18293 	ntme.ipNetToMediaIfIndex.o_length = 0;
18294 	ill = ire_to_ill(ire);
18295 	ASSERT(ill != NULL);
18296 	ntme.ipNetToMediaIfIndex.o_length =
18297 	    ill->ill_name_length == 0 ? 0 :
18298 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18299 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18300 		    ntme.ipNetToMediaIfIndex.o_length);
18301 
18302 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18303 	if (llmp) {
18304 		uchar_t *addr;
18305 
18306 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18307 		/* Remove sap from  address */
18308 		if (ill->ill_sap_length < 0)
18309 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18310 		else
18311 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18312 			    ill->ill_sap_length;
18313 
18314 		ntme.ipNetToMediaPhysAddress.o_length =
18315 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18316 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18317 		    ntme.ipNetToMediaPhysAddress.o_length);
18318 	}
18319 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18320 	/* assume dynamic (may be changed in arp) */
18321 	ntme.ipNetToMediaType = 3;
18322 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18323 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18324 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18325 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18326 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18327 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18328 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18329 		    (uint_t)sizeof (ntme)));
18330 	}
18331 done:
18332 	/* bump route index for next pass */
18333 	ird->ird_idx++;
18334 
18335 	kmem_free(re, sizeof (*re));
18336 	if (sacnt != 0)
18337 		kmem_free(iae, sacnt * sizeof (*iae));
18338 
18339 	if (gcgrp != NULL)
18340 		rw_exit(&gcgrp->gcgrp_rwlock);
18341 }
18342 
18343 /*
18344  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18345  */
18346 static void
18347 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18348 {
18349 	ill_t				*ill;
18350 	ipif_t				*ipif;
18351 	mib2_ipv6RouteEntry_t		*re;
18352 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18353 	in6_addr_t			gw_addr_v6;
18354 	tsol_ire_gw_secattr_t		*attrp;
18355 	tsol_gc_t			*gc = NULL;
18356 	tsol_gcgrp_t			*gcgrp = NULL;
18357 	uint_t				sacnt = 0;
18358 	int				i;
18359 
18360 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18361 
18362 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18363 		return;
18364 
18365 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18366 		mutex_enter(&attrp->igsa_lock);
18367 		if ((gc = attrp->igsa_gc) != NULL) {
18368 			gcgrp = gc->gc_grp;
18369 			ASSERT(gcgrp != NULL);
18370 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18371 			sacnt = 1;
18372 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18373 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18374 			gc = gcgrp->gcgrp_head;
18375 			sacnt = gcgrp->gcgrp_count;
18376 		}
18377 		mutex_exit(&attrp->igsa_lock);
18378 
18379 		/* do nothing if there's no gc to report */
18380 		if (gc == NULL) {
18381 			ASSERT(sacnt == 0);
18382 			if (gcgrp != NULL) {
18383 				/* we might as well drop the lock now */
18384 				rw_exit(&gcgrp->gcgrp_rwlock);
18385 				gcgrp = NULL;
18386 			}
18387 			attrp = NULL;
18388 		}
18389 
18390 		ASSERT(gc == NULL || (gcgrp != NULL &&
18391 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18392 	}
18393 	ASSERT(sacnt == 0 || gc != NULL);
18394 
18395 	if (sacnt != 0 &&
18396 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18397 		kmem_free(re, sizeof (*re));
18398 		rw_exit(&gcgrp->gcgrp_rwlock);
18399 		return;
18400 	}
18401 
18402 	/*
18403 	 * Return all IRE types for route table... let caller pick and choose
18404 	 */
18405 	re->ipv6RouteDest = ire->ire_addr_v6;
18406 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18407 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18408 	re->ipv6RouteIfIndex.o_length = 0;
18409 	ipif = ire->ire_ipif;
18410 	if (ire->ire_type == IRE_CACHE) {
18411 		ill = (ill_t *)ire->ire_stq->q_ptr;
18412 		re->ipv6RouteIfIndex.o_length =
18413 		    ill->ill_name_length == 0 ? 0 :
18414 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18415 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18416 		    re->ipv6RouteIfIndex.o_length);
18417 	} else if (ipif != NULL) {
18418 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18419 		    OCTET_LENGTH);
18420 		re->ipv6RouteIfIndex.o_length =
18421 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18422 	}
18423 
18424 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18425 
18426 	mutex_enter(&ire->ire_lock);
18427 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18428 	mutex_exit(&ire->ire_lock);
18429 
18430 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18431 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18432 	else
18433 		re->ipv6RouteNextHop = gw_addr_v6;
18434 
18435 	/* remote(4), local(3), or discard(2) */
18436 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18437 		re->ipv6RouteType = 2;
18438 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18439 		re->ipv6RouteType = 3;
18440 	else
18441 		re->ipv6RouteType = 4;
18442 
18443 	re->ipv6RouteProtocol	= -1;
18444 	re->ipv6RoutePolicy	= 0;
18445 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18446 	re->ipv6RouteNextHopRDI	= 0;
18447 	re->ipv6RouteWeight	= 0;
18448 	re->ipv6RouteMetric	= 0;
18449 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18450 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18451 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18452 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18453 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18454 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18455 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18456 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18457 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18458 
18459 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18460 	    (char *)re, (int)sizeof (*re))) {
18461 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18462 		    (uint_t)sizeof (*re)));
18463 	}
18464 
18465 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18466 		iaeptr->iae_routeidx = ird->ird_idx;
18467 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18468 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18469 	}
18470 
18471 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18472 	    (char *)iae, sacnt * sizeof (*iae))) {
18473 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18474 		    (unsigned)(sacnt * sizeof (*iae))));
18475 	}
18476 
18477 	/* bump route index for next pass */
18478 	ird->ird_idx++;
18479 
18480 	kmem_free(re, sizeof (*re));
18481 	if (sacnt != 0)
18482 		kmem_free(iae, sacnt * sizeof (*iae));
18483 
18484 	if (gcgrp != NULL)
18485 		rw_exit(&gcgrp->gcgrp_rwlock);
18486 }
18487 
18488 /*
18489  * ndp_walk routine to create ipv6NetToMediaEntryTable
18490  */
18491 static int
18492 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18493 {
18494 	ill_t				*ill;
18495 	mib2_ipv6NetToMediaEntry_t	ntme;
18496 	dl_unitdata_req_t		*dl;
18497 
18498 	ill = nce->nce_ill;
18499 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18500 		return (0);
18501 
18502 	/*
18503 	 * Neighbor cache entry attached to IRE with on-link
18504 	 * destination.
18505 	 */
18506 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18507 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18508 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18509 	    (nce->nce_res_mp != NULL)) {
18510 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18511 		ntme.ipv6NetToMediaPhysAddress.o_length =
18512 		    dl->dl_dest_addr_length;
18513 	} else {
18514 		ntme.ipv6NetToMediaPhysAddress.o_length =
18515 		    ill->ill_phys_addr_length;
18516 	}
18517 	if (nce->nce_res_mp != NULL) {
18518 		bcopy((char *)nce->nce_res_mp->b_rptr +
18519 		    NCE_LL_ADDR_OFFSET(ill),
18520 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18521 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18522 	} else {
18523 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18524 		    ill->ill_phys_addr_length);
18525 	}
18526 	/*
18527 	 * Note: Returns ND_* states. Should be:
18528 	 * reachable(1), stale(2), delay(3), probe(4),
18529 	 * invalid(5), unknown(6)
18530 	 */
18531 	ntme.ipv6NetToMediaState = nce->nce_state;
18532 	ntme.ipv6NetToMediaLastUpdated = 0;
18533 
18534 	/* other(1), dynamic(2), static(3), local(4) */
18535 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18536 		ntme.ipv6NetToMediaType = 4;
18537 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18538 		ntme.ipv6NetToMediaType = 1;
18539 	} else {
18540 		ntme.ipv6NetToMediaType = 2;
18541 	}
18542 
18543 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18544 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18545 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18546 		    (uint_t)sizeof (ntme)));
18547 	}
18548 	return (0);
18549 }
18550 
18551 /*
18552  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18553  */
18554 /* ARGSUSED */
18555 int
18556 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18557 {
18558 	switch (level) {
18559 	case MIB2_IP:
18560 	case MIB2_ICMP:
18561 		switch (name) {
18562 		default:
18563 			break;
18564 		}
18565 		return (1);
18566 	default:
18567 		return (1);
18568 	}
18569 }
18570 
18571 /*
18572  * Called before the options are updated to check if this packet will
18573  * be source routed from here.
18574  * This routine assumes that the options are well formed i.e. that they
18575  * have already been checked.
18576  */
18577 static boolean_t
18578 ip_source_routed(ipha_t *ipha)
18579 {
18580 	ipoptp_t	opts;
18581 	uchar_t		*opt;
18582 	uint8_t		optval;
18583 	uint8_t		optlen;
18584 	ipaddr_t	dst;
18585 	ire_t		*ire;
18586 
18587 	if (IS_SIMPLE_IPH(ipha)) {
18588 		ip2dbg(("not source routed\n"));
18589 		return (B_FALSE);
18590 	}
18591 	dst = ipha->ipha_dst;
18592 	for (optval = ipoptp_first(&opts, ipha);
18593 	    optval != IPOPT_EOL;
18594 	    optval = ipoptp_next(&opts)) {
18595 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18596 		opt = opts.ipoptp_cur;
18597 		optlen = opts.ipoptp_len;
18598 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18599 		    optval, optlen));
18600 		switch (optval) {
18601 			uint32_t off;
18602 		case IPOPT_SSRR:
18603 		case IPOPT_LSRR:
18604 			/*
18605 			 * If dst is one of our addresses and there are some
18606 			 * entries left in the source route return (true).
18607 			 */
18608 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18609 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18610 			if (ire == NULL) {
18611 				ip2dbg(("ip_source_routed: not next"
18612 				    " source route 0x%x\n",
18613 				    ntohl(dst)));
18614 				return (B_FALSE);
18615 			}
18616 			ire_refrele(ire);
18617 			off = opt[IPOPT_OFFSET];
18618 			off--;
18619 			if (optlen < IP_ADDR_LEN ||
18620 			    off > optlen - IP_ADDR_LEN) {
18621 				/* End of source route */
18622 				ip1dbg(("ip_source_routed: end of SR\n"));
18623 				return (B_FALSE);
18624 			}
18625 			return (B_TRUE);
18626 		}
18627 	}
18628 	ip2dbg(("not source routed\n"));
18629 	return (B_FALSE);
18630 }
18631 
18632 /*
18633  * Check if the packet contains any source route.
18634  */
18635 static boolean_t
18636 ip_source_route_included(ipha_t *ipha)
18637 {
18638 	ipoptp_t	opts;
18639 	uint8_t		optval;
18640 
18641 	if (IS_SIMPLE_IPH(ipha))
18642 		return (B_FALSE);
18643 	for (optval = ipoptp_first(&opts, ipha);
18644 	    optval != IPOPT_EOL;
18645 	    optval = ipoptp_next(&opts)) {
18646 		switch (optval) {
18647 		case IPOPT_SSRR:
18648 		case IPOPT_LSRR:
18649 			return (B_TRUE);
18650 		}
18651 	}
18652 	return (B_FALSE);
18653 }
18654 
18655 /*
18656  * Called when the IRE expiration timer fires.
18657  */
18658 /* ARGSUSED */
18659 void
18660 ip_trash_timer_expire(void *args)
18661 {
18662 	int	flush_flag = 0;
18663 
18664 	/*
18665 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18666 	 * This lock makes sure that a new invocation of this function
18667 	 * that occurs due to an almost immediate timer firing will not
18668 	 * progress beyond this point until the current invocation is done
18669 	 */
18670 	mutex_enter(&ip_trash_timer_lock);
18671 	ip_ire_expire_id = 0;
18672 	mutex_exit(&ip_trash_timer_lock);
18673 
18674 	/* Periodic timer */
18675 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18676 		/*
18677 		 * Remove all IRE_CACHE entries since they might
18678 		 * contain arp information.
18679 		 */
18680 		flush_flag |= FLUSH_ARP_TIME;
18681 		ip_ire_arp_time_elapsed = 0;
18682 		IP_STAT(ip_ire_arp_timer_expired);
18683 	}
18684 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18685 		/* Remove all redirects */
18686 		flush_flag |= FLUSH_REDIRECT_TIME;
18687 		ip_ire_rd_time_elapsed = 0;
18688 		IP_STAT(ip_ire_redirect_timer_expired);
18689 	}
18690 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18691 		/* Increase path mtu */
18692 		flush_flag |= FLUSH_MTU_TIME;
18693 		ip_ire_pmtu_time_elapsed = 0;
18694 		IP_STAT(ip_ire_pmtu_timer_expired);
18695 	}
18696 
18697 	/*
18698 	 * Optimize for the case when there are no redirects in the
18699 	 * ftable, that is, no need to walk the ftable in that case.
18700 	 */
18701 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
18702 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
18703 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
18704 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
18705 	}
18706 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
18707 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
18708 		    ire_expire, (char *)(uintptr_t)flush_flag,
18709 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
18710 	}
18711 	if (flush_flag & FLUSH_MTU_TIME) {
18712 		/*
18713 		 * Walk all IPv6 IRE's and update them
18714 		 * Note that ARP and redirect timers are not
18715 		 * needed since NUD handles stale entries.
18716 		 */
18717 		flush_flag = FLUSH_MTU_TIME;
18718 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18719 		    ALL_ZONES);
18720 	}
18721 
18722 	ip_ire_arp_time_elapsed += ip_timer_interval;
18723 	ip_ire_rd_time_elapsed += ip_timer_interval;
18724 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18725 
18726 	/*
18727 	 * Hold the lock to serialize timeout calls and prevent
18728 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18729 	 * for the timer to fire and a new invocation of this function
18730 	 * to start before the return value of timeout has been stored
18731 	 * in ip_ire_expire_id by the current invocation.
18732 	 */
18733 	mutex_enter(&ip_trash_timer_lock);
18734 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18735 	    MSEC_TO_TICK(ip_timer_interval));
18736 	mutex_exit(&ip_trash_timer_lock);
18737 }
18738 
18739 /*
18740  * Called by the memory allocator subsystem directly, when the system
18741  * is running low on memory.
18742  */
18743 /* ARGSUSED */
18744 void
18745 ip_trash_ire_reclaim(void *args)
18746 {
18747 	ire_cache_count_t icc;
18748 	ire_cache_reclaim_t icr;
18749 	ncc_cache_count_t ncc;
18750 	nce_cache_reclaim_t ncr;
18751 	uint_t delete_cnt;
18752 	/*
18753 	 * Memory reclaim call back.
18754 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18755 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18756 	 * entries, determine what fraction to free for
18757 	 * each category of IRE_CACHE entries giving absolute priority
18758 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18759 	 * entry will be freed unless all offlink entries are freed).
18760 	 */
18761 	icc.icc_total = 0;
18762 	icc.icc_unused = 0;
18763 	icc.icc_offlink = 0;
18764 	icc.icc_pmtu = 0;
18765 	icc.icc_onlink = 0;
18766 	ire_walk(ire_cache_count, (char *)&icc);
18767 
18768 	/*
18769 	 * Free NCEs for IPv6 like the onlink ires.
18770 	 */
18771 	ncc.ncc_total = 0;
18772 	ncc.ncc_host = 0;
18773 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18774 
18775 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18776 	    icc.icc_pmtu + icc.icc_onlink);
18777 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18778 	IP_STAT(ip_trash_ire_reclaim_calls);
18779 	if (delete_cnt == 0)
18780 		return;
18781 	IP_STAT(ip_trash_ire_reclaim_success);
18782 	/* Always delete all unused offlink entries */
18783 	icr.icr_unused = 1;
18784 	if (delete_cnt <= icc.icc_unused) {
18785 		/*
18786 		 * Only need to free unused entries.  In other words,
18787 		 * there are enough unused entries to free to meet our
18788 		 * target number of freed ire cache entries.
18789 		 */
18790 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18791 		ncr.ncr_host = 0;
18792 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18793 		/*
18794 		 * Only need to free unused entries, plus a fraction of offlink
18795 		 * entries.  It follows from the first if statement that
18796 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18797 		 */
18798 		delete_cnt -= icc.icc_unused;
18799 		/* Round up # deleted by truncating fraction */
18800 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18801 		icr.icr_pmtu = icr.icr_onlink = 0;
18802 		ncr.ncr_host = 0;
18803 	} else if (delete_cnt <=
18804 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18805 		/*
18806 		 * Free all unused and offlink entries, plus a fraction of
18807 		 * pmtu entries.  It follows from the previous if statement
18808 		 * that icc_pmtu is non-zero, and that
18809 		 * delete_cnt != icc_unused + icc_offlink.
18810 		 */
18811 		icr.icr_offlink = 1;
18812 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18813 		/* Round up # deleted by truncating fraction */
18814 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18815 		icr.icr_onlink = 0;
18816 		ncr.ncr_host = 0;
18817 	} else {
18818 		/*
18819 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18820 		 * of onlink entries.  If we're here, then we know that
18821 		 * icc_onlink is non-zero, and that
18822 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18823 		 */
18824 		icr.icr_offlink = icr.icr_pmtu = 1;
18825 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18826 		    icc.icc_pmtu;
18827 		/* Round up # deleted by truncating fraction */
18828 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18829 		/* Using the same delete fraction as for onlink IREs */
18830 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18831 	}
18832 #ifdef DEBUG
18833 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18834 	    "fractions %d/%d/%d/%d\n",
18835 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18836 	    icc.icc_unused, icc.icc_offlink,
18837 	    icc.icc_pmtu, icc.icc_onlink,
18838 	    icr.icr_unused, icr.icr_offlink,
18839 	    icr.icr_pmtu, icr.icr_onlink));
18840 #endif
18841 	ire_walk(ire_cache_reclaim, (char *)&icr);
18842 	if (ncr.ncr_host != 0)
18843 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18844 		    (uchar_t *)&ncr);
18845 #ifdef DEBUG
18846 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18847 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18848 	ire_walk(ire_cache_count, (char *)&icc);
18849 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18850 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18851 	    icc.icc_pmtu, icc.icc_onlink));
18852 #endif
18853 }
18854 
18855 /*
18856  * ip_unbind is called when a copy of an unbind request is received from the
18857  * upper level protocol.  We remove this conn from any fanout hash list it is
18858  * on, and zero out the bind information.  No reply is expected up above.
18859  */
18860 mblk_t *
18861 ip_unbind(queue_t *q, mblk_t *mp)
18862 {
18863 	conn_t	*connp = Q_TO_CONN(q);
18864 
18865 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18866 
18867 	if (is_system_labeled() && connp->conn_anon_port) {
18868 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18869 		    connp->conn_mlp_type, connp->conn_ulp,
18870 		    ntohs(connp->conn_lport), B_FALSE);
18871 		connp->conn_anon_port = 0;
18872 	}
18873 	connp->conn_mlp_type = mlptSingle;
18874 
18875 	ipcl_hash_remove(connp);
18876 
18877 	ASSERT(mp->b_cont == NULL);
18878 	/*
18879 	 * Convert mp into a T_OK_ACK
18880 	 */
18881 	mp = mi_tpi_ok_ack_alloc(mp);
18882 
18883 	/*
18884 	 * should not happen in practice... T_OK_ACK is smaller than the
18885 	 * original message.
18886 	 */
18887 	if (mp == NULL)
18888 		return (NULL);
18889 
18890 	/*
18891 	 * Don't bzero the ports if its TCP since TCP still needs the
18892 	 * lport to remove it from its own bind hash. TCP will do the
18893 	 * cleanup.
18894 	 */
18895 	if (!IPCL_IS_TCP(connp))
18896 		bzero(&connp->u_port, sizeof (connp->u_port));
18897 
18898 	return (mp);
18899 }
18900 
18901 /*
18902  * Write side put procedure.  Outbound data, IOCTLs, responses from
18903  * resolvers, etc, come down through here.
18904  */
18905 void
18906 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18907 {
18908 	conn_t		*connp = NULL;
18909 	queue_t		*q = (queue_t *)arg2;
18910 	ipha_t		*ipha;
18911 #define	rptr	((uchar_t *)ipha)
18912 	ire_t		*ire = NULL;
18913 	ire_t		*sctp_ire = NULL;
18914 	uint32_t	v_hlen_tos_len;
18915 	ipaddr_t	dst;
18916 	mblk_t		*first_mp = NULL;
18917 	boolean_t	mctl_present;
18918 	ipsec_out_t	*io;
18919 	int		match_flags;
18920 	ill_t		*attach_ill = NULL;
18921 					/* Bind to IPIF_NOFAILOVER ill etc. */
18922 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18923 	ipif_t		*dst_ipif;
18924 	boolean_t	multirt_need_resolve = B_FALSE;
18925 	mblk_t		*copy_mp = NULL;
18926 	int		err;
18927 	zoneid_t	zoneid;
18928 	int	adjust;
18929 	uint16_t iplen;
18930 	boolean_t	need_decref = B_FALSE;
18931 	boolean_t	ignore_dontroute = B_FALSE;
18932 	boolean_t	ignore_nexthop = B_FALSE;
18933 	boolean_t	ip_nexthop = B_FALSE;
18934 	ipaddr_t	nexthop_addr;
18935 
18936 #ifdef	_BIG_ENDIAN
18937 #define	V_HLEN	(v_hlen_tos_len >> 24)
18938 #else
18939 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18940 #endif
18941 
18942 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18943 	    "ip_wput_start: q %p", q);
18944 
18945 	/*
18946 	 * ip_wput fast path
18947 	 */
18948 
18949 	/* is packet from ARP ? */
18950 	if (q->q_next != NULL)
18951 		goto qnext;
18952 
18953 	connp = (conn_t *)arg;
18954 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18955 
18956 	/* is queue flow controlled? */
18957 	if ((q->q_first != NULL || connp->conn_draining) &&
18958 	    (caller == IP_WPUT)) {
18959 		ASSERT(!need_decref);
18960 		(void) putq(q, mp);
18961 		return;
18962 	}
18963 
18964 	/* Multidata transmit? */
18965 	if (DB_TYPE(mp) == M_MULTIDATA) {
18966 		/*
18967 		 * We should never get here, since all Multidata messages
18968 		 * originating from tcp should have been directed over to
18969 		 * tcp_multisend() in the first place.
18970 		 */
18971 		BUMP_MIB(&ip_mib, ipOutDiscards);
18972 		freemsg(mp);
18973 		return;
18974 	} else if (DB_TYPE(mp) != M_DATA)
18975 		goto notdata;
18976 
18977 	if (mp->b_flag & MSGHASREF) {
18978 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18979 		mp->b_flag &= ~MSGHASREF;
18980 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18981 		need_decref = B_TRUE;
18982 	}
18983 	ipha = (ipha_t *)mp->b_rptr;
18984 
18985 	/* is IP header non-aligned or mblk smaller than basic IP header */
18986 #ifndef SAFETY_BEFORE_SPEED
18987 	if (!OK_32PTR(rptr) ||
18988 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18989 		goto hdrtoosmall;
18990 #endif
18991 
18992 	ASSERT(OK_32PTR(ipha));
18993 
18994 	/*
18995 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18996 	 * wrong version, we'll catch it again in ip_output_v6.
18997 	 *
18998 	 * Note that this is *only* locally-generated output here, and never
18999 	 * forwarded data, and that we need to deal only with transports that
19000 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19001 	 * label.)
19002 	 */
19003 	if (is_system_labeled() &&
19004 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19005 	    !connp->conn_ulp_labeled) {
19006 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19007 		    connp->conn_mac_exempt);
19008 		ipha = (ipha_t *)mp->b_rptr;
19009 		if (err != 0) {
19010 			first_mp = mp;
19011 			if (err == EINVAL)
19012 				goto icmp_parameter_problem;
19013 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19014 			goto drop_pkt;
19015 		}
19016 		iplen = ntohs(ipha->ipha_length) + adjust;
19017 		ipha->ipha_length = htons(iplen);
19018 	}
19019 
19020 	/*
19021 	 * If there is a policy, try to attach an ipsec_out in
19022 	 * the front. At the end, first_mp either points to a
19023 	 * M_DATA message or IPSEC_OUT message linked to a
19024 	 * M_DATA message. We have to do it now as we might
19025 	 * lose the "conn" if we go through ip_newroute.
19026 	 */
19027 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19028 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19029 		    ipha->ipha_protocol)) == NULL)) {
19030 			if (need_decref)
19031 				CONN_DEC_REF(connp);
19032 			return;
19033 		} else {
19034 			ASSERT(mp->b_datap->db_type == M_CTL);
19035 			first_mp = mp;
19036 			mp = mp->b_cont;
19037 			mctl_present = B_TRUE;
19038 		}
19039 	} else {
19040 		first_mp = mp;
19041 		mctl_present = B_FALSE;
19042 	}
19043 
19044 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19045 
19046 	/* is wrong version or IP options present */
19047 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19048 		goto version_hdrlen_check;
19049 	dst = ipha->ipha_dst;
19050 
19051 	if (connp->conn_nofailover_ill != NULL) {
19052 		attach_ill = conn_get_held_ill(connp,
19053 		    &connp->conn_nofailover_ill, &err);
19054 		if (err == ILL_LOOKUP_FAILED) {
19055 			if (need_decref)
19056 				CONN_DEC_REF(connp);
19057 			freemsg(first_mp);
19058 			return;
19059 		}
19060 	}
19061 
19062 	/* is packet multicast? */
19063 	if (CLASSD(dst))
19064 		goto multicast;
19065 
19066 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19067 	    (connp->conn_nexthop_set)) {
19068 		/*
19069 		 * If the destination is a broadcast or a loopback
19070 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19071 		 * through the standard path. But in the case of local
19072 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19073 		 * the standard path not IP_XMIT_IF.
19074 		 */
19075 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19076 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19077 		    (ire->ire_type != IRE_LOOPBACK))) {
19078 			if ((connp->conn_dontroute ||
19079 			    connp->conn_nexthop_set) && (ire != NULL) &&
19080 			    (ire->ire_type == IRE_LOCAL))
19081 				goto standard_path;
19082 
19083 			if (ire != NULL) {
19084 				ire_refrele(ire);
19085 				/* No more access to ire */
19086 				ire = NULL;
19087 			}
19088 			/*
19089 			 * bypass routing checks and go directly to
19090 			 * interface.
19091 			 */
19092 			if (connp->conn_dontroute) {
19093 				goto dontroute;
19094 			} else if (connp->conn_nexthop_set) {
19095 				ip_nexthop = B_TRUE;
19096 				nexthop_addr = connp->conn_nexthop_v4;
19097 				goto send_from_ill;
19098 			}
19099 
19100 			/*
19101 			 * If IP_XMIT_IF socket option is set,
19102 			 * then we allow unicast and multicast
19103 			 * packets to go through the ill. It is
19104 			 * quite possible that the destination
19105 			 * is not in the ire cache table and we
19106 			 * do not want to go to ip_newroute()
19107 			 * instead we call ip_newroute_ipif.
19108 			 */
19109 			xmit_ill = conn_get_held_ill(connp,
19110 			    &connp->conn_xmit_if_ill, &err);
19111 			if (err == ILL_LOOKUP_FAILED) {
19112 				if (attach_ill != NULL)
19113 					ill_refrele(attach_ill);
19114 				if (need_decref)
19115 					CONN_DEC_REF(connp);
19116 				freemsg(first_mp);
19117 				return;
19118 			}
19119 			goto send_from_ill;
19120 		}
19121 standard_path:
19122 		/* Must be a broadcast, a loopback or a local ire */
19123 		if (ire != NULL) {
19124 			ire_refrele(ire);
19125 			/* No more access to ire */
19126 			ire = NULL;
19127 		}
19128 	}
19129 
19130 	if (attach_ill != NULL)
19131 		goto send_from_ill;
19132 
19133 	/*
19134 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19135 	 * this for the tcp global queue and listen end point
19136 	 * as it does not really have a real destination to
19137 	 * talk to.  This is also true for SCTP.
19138 	 */
19139 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19140 	    !connp->conn_fully_bound) {
19141 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19142 		if (ire == NULL)
19143 			goto noirefound;
19144 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19145 		    "ip_wput_end: q %p (%S)", q, "end");
19146 
19147 		/*
19148 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19149 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19150 		 */
19151 		if (ire->ire_flags & RTF_MULTIRT) {
19152 
19153 			/*
19154 			 * Force the TTL of multirouted packets if required.
19155 			 * The TTL of such packets is bounded by the
19156 			 * ip_multirt_ttl ndd variable.
19157 			 */
19158 			if ((ip_multirt_ttl > 0) &&
19159 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19160 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19161 				    "(was %d), dst 0x%08x\n",
19162 				    ip_multirt_ttl, ipha->ipha_ttl,
19163 				    ntohl(ire->ire_addr)));
19164 				ipha->ipha_ttl = ip_multirt_ttl;
19165 			}
19166 			/*
19167 			 * We look at this point if there are pending
19168 			 * unresolved routes. ire_multirt_resolvable()
19169 			 * checks in O(n) that all IRE_OFFSUBNET ire
19170 			 * entries for the packet's destination and
19171 			 * flagged RTF_MULTIRT are currently resolved.
19172 			 * If some remain unresolved, we make a copy
19173 			 * of the current message. It will be used
19174 			 * to initiate additional route resolutions.
19175 			 */
19176 			multirt_need_resolve =
19177 			    ire_multirt_need_resolve(ire->ire_addr,
19178 			    MBLK_GETLABEL(first_mp));
19179 			ip2dbg(("ip_wput[TCP]: ire %p, "
19180 			    "multirt_need_resolve %d, first_mp %p\n",
19181 			    (void *)ire, multirt_need_resolve,
19182 			    (void *)first_mp));
19183 			if (multirt_need_resolve) {
19184 				copy_mp = copymsg(first_mp);
19185 				if (copy_mp != NULL) {
19186 					MULTIRT_DEBUG_TAG(copy_mp);
19187 				}
19188 			}
19189 		}
19190 
19191 		ip_wput_ire(q, first_mp, ire, connp, caller);
19192 
19193 		/*
19194 		 * Try to resolve another multiroute if
19195 		 * ire_multirt_need_resolve() deemed it necessary.
19196 		 */
19197 		if (copy_mp != NULL) {
19198 			ip_newroute(q, copy_mp, dst, NULL, connp);
19199 		}
19200 		if (need_decref)
19201 			CONN_DEC_REF(connp);
19202 		return;
19203 	}
19204 
19205 	/*
19206 	 * Access to conn_ire_cache. (protected by conn_lock)
19207 	 *
19208 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19209 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19210 	 * send a packet or two with the IRE_CACHE that is going away.
19211 	 * Access to the ire requires an ire refhold on the ire prior to
19212 	 * its use since an interface unplumb thread may delete the cached
19213 	 * ire and release the refhold at any time.
19214 	 *
19215 	 * Caching an ire in the conn_ire_cache
19216 	 *
19217 	 * o Caching an ire pointer in the conn requires a strict check for
19218 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19219 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19220 	 * in the conn is done after making sure under the bucket lock that the
19221 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19222 	 * caching an ire after the unplumb thread has cleaned up the conn.
19223 	 * If the conn does not send a packet subsequently the unplumb thread
19224 	 * will be hanging waiting for the ire count to drop to zero.
19225 	 *
19226 	 * o We also need to atomically test for a null conn_ire_cache and
19227 	 * set the conn_ire_cache under the the protection of the conn_lock
19228 	 * to avoid races among concurrent threads trying to simultaneously
19229 	 * cache an ire in the conn_ire_cache.
19230 	 */
19231 	mutex_enter(&connp->conn_lock);
19232 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19233 
19234 	if (ire != NULL && ire->ire_addr == dst &&
19235 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19236 
19237 		IRE_REFHOLD(ire);
19238 		mutex_exit(&connp->conn_lock);
19239 
19240 	} else {
19241 		boolean_t cached = B_FALSE;
19242 		connp->conn_ire_cache = NULL;
19243 		mutex_exit(&connp->conn_lock);
19244 		/* Release the old ire */
19245 		if (ire != NULL && sctp_ire == NULL)
19246 			IRE_REFRELE_NOTR(ire);
19247 
19248 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19249 		if (ire == NULL)
19250 			goto noirefound;
19251 		IRE_REFHOLD_NOTR(ire);
19252 
19253 		mutex_enter(&connp->conn_lock);
19254 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19255 		    connp->conn_ire_cache == NULL) {
19256 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19257 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19258 				connp->conn_ire_cache = ire;
19259 				cached = B_TRUE;
19260 			}
19261 			rw_exit(&ire->ire_bucket->irb_lock);
19262 		}
19263 		mutex_exit(&connp->conn_lock);
19264 
19265 		/*
19266 		 * We can continue to use the ire but since it was
19267 		 * not cached, we should drop the extra reference.
19268 		 */
19269 		if (!cached)
19270 			IRE_REFRELE_NOTR(ire);
19271 	}
19272 
19273 
19274 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19275 	    "ip_wput_end: q %p (%S)", q, "end");
19276 
19277 	/*
19278 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19279 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19280 	 */
19281 	if (ire->ire_flags & RTF_MULTIRT) {
19282 
19283 		/*
19284 		 * Force the TTL of multirouted packets if required.
19285 		 * The TTL of such packets is bounded by the
19286 		 * ip_multirt_ttl ndd variable.
19287 		 */
19288 		if ((ip_multirt_ttl > 0) &&
19289 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19290 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19291 			    "(was %d), dst 0x%08x\n",
19292 			    ip_multirt_ttl, ipha->ipha_ttl,
19293 			    ntohl(ire->ire_addr)));
19294 			ipha->ipha_ttl = ip_multirt_ttl;
19295 		}
19296 
19297 		/*
19298 		 * At this point, we check to see if there are any pending
19299 		 * unresolved routes. ire_multirt_resolvable()
19300 		 * checks in O(n) that all IRE_OFFSUBNET ire
19301 		 * entries for the packet's destination and
19302 		 * flagged RTF_MULTIRT are currently resolved.
19303 		 * If some remain unresolved, we make a copy
19304 		 * of the current message. It will be used
19305 		 * to initiate additional route resolutions.
19306 		 */
19307 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19308 		    MBLK_GETLABEL(first_mp));
19309 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19310 		    "multirt_need_resolve %d, first_mp %p\n",
19311 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19312 		if (multirt_need_resolve) {
19313 			copy_mp = copymsg(first_mp);
19314 			if (copy_mp != NULL) {
19315 				MULTIRT_DEBUG_TAG(copy_mp);
19316 			}
19317 		}
19318 	}
19319 
19320 	ip_wput_ire(q, first_mp, ire, connp, caller);
19321 
19322 	/*
19323 	 * Try to resolve another multiroute if
19324 	 * ire_multirt_resolvable() deemed it necessary
19325 	 */
19326 	if (copy_mp != NULL) {
19327 		ip_newroute(q, copy_mp, dst, NULL, connp);
19328 	}
19329 	if (need_decref)
19330 		CONN_DEC_REF(connp);
19331 	return;
19332 
19333 qnext:
19334 	/*
19335 	 * Upper Level Protocols pass down complete IP datagrams
19336 	 * as M_DATA messages.	Everything else is a sideshow.
19337 	 *
19338 	 * 1) We could be re-entering ip_wput because of ip_neworute
19339 	 *    in which case we could have a IPSEC_OUT message. We
19340 	 *    need to pass through ip_wput like other datagrams and
19341 	 *    hence cannot branch to ip_wput_nondata.
19342 	 *
19343 	 * 2) ARP, AH, ESP, and other clients who are on the module
19344 	 *    instance of IP stream, give us something to deal with.
19345 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19346 	 *
19347 	 * 3) ICMP replies also could come here.
19348 	 */
19349 	if (DB_TYPE(mp) != M_DATA) {
19350 	    notdata:
19351 		if (DB_TYPE(mp) == M_CTL) {
19352 			/*
19353 			 * M_CTL messages are used by ARP, AH and ESP to
19354 			 * communicate with IP. We deal with IPSEC_IN and
19355 			 * IPSEC_OUT here. ip_wput_nondata handles other
19356 			 * cases.
19357 			 */
19358 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19359 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19360 				first_mp = mp->b_cont;
19361 				first_mp->b_flag &= ~MSGHASREF;
19362 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19363 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19364 				CONN_DEC_REF(connp);
19365 				connp = NULL;
19366 			}
19367 			if (ii->ipsec_info_type == IPSEC_IN) {
19368 				/*
19369 				 * Either this message goes back to
19370 				 * IPSEC for further processing or to
19371 				 * ULP after policy checks.
19372 				 */
19373 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19374 				return;
19375 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19376 				io = (ipsec_out_t *)ii;
19377 				if (io->ipsec_out_proc_begin) {
19378 					/*
19379 					 * IPSEC processing has already started.
19380 					 * Complete it.
19381 					 * IPQoS notes: We don't care what is
19382 					 * in ipsec_out_ill_index since this
19383 					 * won't be processed for IPQoS policies
19384 					 * in ipsec_out_process.
19385 					 */
19386 					ipsec_out_process(q, mp, NULL,
19387 					    io->ipsec_out_ill_index);
19388 					return;
19389 				} else {
19390 					connp = (q->q_next != NULL) ?
19391 					    NULL : Q_TO_CONN(q);
19392 					first_mp = mp;
19393 					mp = mp->b_cont;
19394 					mctl_present = B_TRUE;
19395 				}
19396 				zoneid = io->ipsec_out_zoneid;
19397 				ASSERT(zoneid != ALL_ZONES);
19398 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19399 				/*
19400 				 * It's an IPsec control message requesting
19401 				 * an SADB update to be sent to the IPsec
19402 				 * hardware acceleration capable ills.
19403 				 */
19404 				ipsec_ctl_t *ipsec_ctl =
19405 				    (ipsec_ctl_t *)mp->b_rptr;
19406 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19407 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19408 				mblk_t *cmp = mp->b_cont;
19409 
19410 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19411 				ASSERT(cmp != NULL);
19412 
19413 				freeb(mp);
19414 				ill_ipsec_capab_send_all(satype, cmp, sa);
19415 				return;
19416 			} else {
19417 				/*
19418 				 * This must be ARP or special TSOL signaling.
19419 				 */
19420 				ip_wput_nondata(NULL, q, mp, NULL);
19421 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19422 				    "ip_wput_end: q %p (%S)", q, "nondata");
19423 				return;
19424 			}
19425 		} else {
19426 			/*
19427 			 * This must be non-(ARP/AH/ESP) messages.
19428 			 */
19429 			ASSERT(!need_decref);
19430 			ip_wput_nondata(NULL, q, mp, NULL);
19431 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19432 			    "ip_wput_end: q %p (%S)", q, "nondata");
19433 			return;
19434 		}
19435 	} else {
19436 		first_mp = mp;
19437 		mctl_present = B_FALSE;
19438 	}
19439 
19440 	ASSERT(first_mp != NULL);
19441 	/*
19442 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19443 	 * to make sure that this packet goes out on the same interface it
19444 	 * came in. We handle that here.
19445 	 */
19446 	if (mctl_present) {
19447 		uint_t ifindex;
19448 
19449 		io = (ipsec_out_t *)first_mp->b_rptr;
19450 		if (io->ipsec_out_attach_if ||
19451 		    io->ipsec_out_xmit_if ||
19452 		    io->ipsec_out_ip_nexthop) {
19453 			ill_t	*ill;
19454 
19455 			/*
19456 			 * We may have lost the conn context if we are
19457 			 * coming here from ip_newroute(). Copy the
19458 			 * nexthop information.
19459 			 */
19460 			if (io->ipsec_out_ip_nexthop) {
19461 				ip_nexthop = B_TRUE;
19462 				nexthop_addr = io->ipsec_out_nexthop_addr;
19463 
19464 				ipha = (ipha_t *)mp->b_rptr;
19465 				dst = ipha->ipha_dst;
19466 				goto send_from_ill;
19467 			} else {
19468 				ASSERT(io->ipsec_out_ill_index != 0);
19469 				ifindex = io->ipsec_out_ill_index;
19470 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19471 				    NULL, NULL, NULL, NULL);
19472 				/*
19473 				 * ipsec_out_xmit_if bit is used to tell
19474 				 * ip_wput to use the ill to send outgoing data
19475 				 * as we have no conn when data comes from ICMP
19476 				 * error msg routines. Currently this feature is
19477 				 * only used by ip_mrtun_forward routine.
19478 				 */
19479 				if (io->ipsec_out_xmit_if) {
19480 					xmit_ill = ill;
19481 					if (xmit_ill == NULL) {
19482 						ip1dbg(("ip_output:bad ifindex "
19483 						    "for xmit_ill %d\n",
19484 						    ifindex));
19485 						freemsg(first_mp);
19486 						BUMP_MIB(&ip_mib,
19487 						    ipOutDiscards);
19488 						ASSERT(!need_decref);
19489 						return;
19490 					}
19491 					/* Free up the ipsec_out_t mblk */
19492 					ASSERT(first_mp->b_cont == mp);
19493 					first_mp->b_cont = NULL;
19494 					freeb(first_mp);
19495 					/* Just send the IP header+ICMP+data */
19496 					first_mp = mp;
19497 					ipha = (ipha_t *)mp->b_rptr;
19498 					dst = ipha->ipha_dst;
19499 					goto send_from_ill;
19500 				} else {
19501 					attach_ill = ill;
19502 				}
19503 
19504 				if (attach_ill == NULL) {
19505 					ASSERT(xmit_ill == NULL);
19506 					ip1dbg(("ip_output: bad ifindex for "
19507 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19508 					    ifindex));
19509 					freemsg(first_mp);
19510 					BUMP_MIB(&ip_mib, ipOutDiscards);
19511 					ASSERT(!need_decref);
19512 					return;
19513 				}
19514 			}
19515 		}
19516 	}
19517 
19518 	ASSERT(xmit_ill == NULL);
19519 
19520 	/* We have a complete IP datagram heading outbound. */
19521 	ipha = (ipha_t *)mp->b_rptr;
19522 
19523 #ifndef SPEED_BEFORE_SAFETY
19524 	/*
19525 	 * Make sure we have a full-word aligned message and that at least
19526 	 * a simple IP header is accessible in the first message.  If not,
19527 	 * try a pullup.
19528 	 */
19529 	if (!OK_32PTR(rptr) ||
19530 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19531 	    hdrtoosmall:
19532 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19533 			BUMP_MIB(&ip_mib, ipOutDiscards);
19534 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19535 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19536 			if (first_mp == NULL)
19537 				first_mp = mp;
19538 			goto drop_pkt;
19539 		}
19540 
19541 		/* This function assumes that mp points to an IPv4 packet. */
19542 		if (is_system_labeled() && q->q_next == NULL &&
19543 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19544 		    !connp->conn_ulp_labeled) {
19545 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19546 			    &adjust, connp->conn_mac_exempt);
19547 			ipha = (ipha_t *)mp->b_rptr;
19548 			if (first_mp != NULL)
19549 				first_mp->b_cont = mp;
19550 			if (err != 0) {
19551 				if (first_mp == NULL)
19552 					first_mp = mp;
19553 				if (err == EINVAL)
19554 					goto icmp_parameter_problem;
19555 				ip2dbg(("ip_wput: label check failed (%d)\n",
19556 				    err));
19557 				goto drop_pkt;
19558 			}
19559 			iplen = ntohs(ipha->ipha_length) + adjust;
19560 			ipha->ipha_length = htons(iplen);
19561 		}
19562 
19563 		ipha = (ipha_t *)mp->b_rptr;
19564 		if (first_mp == NULL) {
19565 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19566 			/*
19567 			 * If we got here because of "goto hdrtoosmall"
19568 			 * We need to attach a IPSEC_OUT.
19569 			 */
19570 			if (connp->conn_out_enforce_policy) {
19571 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19572 				    NULL, ipha->ipha_protocol)) == NULL)) {
19573 					if (need_decref)
19574 						CONN_DEC_REF(connp);
19575 					return;
19576 				} else {
19577 					ASSERT(mp->b_datap->db_type == M_CTL);
19578 					first_mp = mp;
19579 					mp = mp->b_cont;
19580 					mctl_present = B_TRUE;
19581 				}
19582 			} else {
19583 				first_mp = mp;
19584 				mctl_present = B_FALSE;
19585 			}
19586 		}
19587 	}
19588 #endif
19589 
19590 	/* Most of the code below is written for speed, not readability */
19591 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19592 
19593 	/*
19594 	 * If ip_newroute() fails, we're going to need a full
19595 	 * header for the icmp wraparound.
19596 	 */
19597 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19598 		uint_t	v_hlen;
19599 	    version_hdrlen_check:
19600 		ASSERT(first_mp != NULL);
19601 		v_hlen = V_HLEN;
19602 		/*
19603 		 * siphon off IPv6 packets coming down from transport
19604 		 * layer modules here.
19605 		 * Note: high-order bit carries NUD reachability confirmation
19606 		 */
19607 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19608 			/*
19609 			 * XXX implement a IPv4 and IPv6 packet counter per
19610 			 * conn and switch when ratio exceeds e.g. 10:1
19611 			 */
19612 #ifdef notyet
19613 			if (q->q_next == NULL) /* Avoid ill queue */
19614 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19615 #endif
19616 			BUMP_MIB(&ip_mib, ipOutIPv6);
19617 			ASSERT(xmit_ill == NULL);
19618 			if (attach_ill != NULL)
19619 				ill_refrele(attach_ill);
19620 			if (need_decref)
19621 				mp->b_flag |= MSGHASREF;
19622 			(void) ip_output_v6(connp, first_mp, q, caller);
19623 			return;
19624 		}
19625 
19626 		if ((v_hlen >> 4) != IP_VERSION) {
19627 			BUMP_MIB(&ip_mib, ipOutDiscards);
19628 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19629 			    "ip_wput_end: q %p (%S)", q, "badvers");
19630 			goto drop_pkt;
19631 		}
19632 		/*
19633 		 * Is the header length at least 20 bytes?
19634 		 *
19635 		 * Are there enough bytes accessible in the header?  If
19636 		 * not, try a pullup.
19637 		 */
19638 		v_hlen &= 0xF;
19639 		v_hlen <<= 2;
19640 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19641 			BUMP_MIB(&ip_mib, ipOutDiscards);
19642 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19643 			    "ip_wput_end: q %p (%S)", q, "badlen");
19644 			goto drop_pkt;
19645 		}
19646 		if (v_hlen > (mp->b_wptr - rptr)) {
19647 			if (!pullupmsg(mp, v_hlen)) {
19648 				BUMP_MIB(&ip_mib, ipOutDiscards);
19649 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19650 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19651 				goto drop_pkt;
19652 			}
19653 			ipha = (ipha_t *)mp->b_rptr;
19654 		}
19655 		/*
19656 		 * Move first entry from any source route into ipha_dst and
19657 		 * verify the options
19658 		 */
19659 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19660 			ASSERT(xmit_ill == NULL);
19661 			if (attach_ill != NULL)
19662 				ill_refrele(attach_ill);
19663 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19664 			    "ip_wput_end: q %p (%S)", q, "badopts");
19665 			if (need_decref)
19666 				CONN_DEC_REF(connp);
19667 			return;
19668 		}
19669 	}
19670 	dst = ipha->ipha_dst;
19671 
19672 	/*
19673 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19674 	 * we have to run the packet through ip_newroute which will take
19675 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19676 	 * a resolver, or assigning a default gateway, etc.
19677 	 */
19678 	if (CLASSD(dst)) {
19679 		ipif_t	*ipif;
19680 		uint32_t setsrc = 0;
19681 
19682 	    multicast:
19683 		ASSERT(first_mp != NULL);
19684 		ASSERT(xmit_ill == NULL);
19685 		ip2dbg(("ip_wput: CLASSD\n"));
19686 		if (connp == NULL) {
19687 			/*
19688 			 * Use the first good ipif on the ill.
19689 			 * XXX Should this ever happen? (Appears
19690 			 * to show up with just ppp and no ethernet due
19691 			 * to in.rdisc.)
19692 			 * However, ire_send should be able to
19693 			 * call ip_wput_ire directly.
19694 			 *
19695 			 * XXX Also, this can happen for ICMP and other packets
19696 			 * with multicast source addresses.  Perhaps we should
19697 			 * fix things so that we drop the packet in question,
19698 			 * but for now, just run with it.
19699 			 */
19700 			ill_t *ill = (ill_t *)q->q_ptr;
19701 
19702 			/*
19703 			 * Don't honor attach_if for this case. If ill
19704 			 * is part of the group, ipif could belong to
19705 			 * any ill and we cannot maintain attach_ill
19706 			 * and ipif_ill same anymore and the assert
19707 			 * below would fail.
19708 			 */
19709 			if (mctl_present) {
19710 				io->ipsec_out_ill_index = 0;
19711 				io->ipsec_out_attach_if = B_FALSE;
19712 				ASSERT(attach_ill != NULL);
19713 				ill_refrele(attach_ill);
19714 				attach_ill = NULL;
19715 			}
19716 
19717 			ASSERT(attach_ill == NULL);
19718 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19719 			if (ipif == NULL) {
19720 				if (need_decref)
19721 					CONN_DEC_REF(connp);
19722 				freemsg(first_mp);
19723 				return;
19724 			}
19725 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19726 			    ntohl(dst), ill->ill_name));
19727 		} else {
19728 			/*
19729 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19730 			 * IP_XMIT_IF is honoured.
19731 			 * Block comment above this function explains the
19732 			 * locking mechanism used here
19733 			 */
19734 			xmit_ill = conn_get_held_ill(connp,
19735 			    &connp->conn_xmit_if_ill, &err);
19736 			if (err == ILL_LOOKUP_FAILED) {
19737 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19738 				goto drop_pkt;
19739 			}
19740 			if (xmit_ill == NULL) {
19741 				ipif = conn_get_held_ipif(connp,
19742 				    &connp->conn_multicast_ipif, &err);
19743 				if (err == IPIF_LOOKUP_FAILED) {
19744 					ip1dbg(("ip_wput: No ipif for "
19745 					    "multicast\n"));
19746 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19747 					goto drop_pkt;
19748 				}
19749 			}
19750 			if (xmit_ill != NULL) {
19751 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19752 				if (ipif == NULL) {
19753 					ip1dbg(("ip_wput: No ipif for "
19754 					    "IP_XMIT_IF\n"));
19755 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19756 					goto drop_pkt;
19757 				}
19758 			} else if (ipif == NULL || ipif->ipif_isv6) {
19759 				/*
19760 				 * We must do this ipif determination here
19761 				 * else we could pass through ip_newroute
19762 				 * and come back here without the conn context.
19763 				 *
19764 				 * Note: we do late binding i.e. we bind to
19765 				 * the interface when the first packet is sent.
19766 				 * For performance reasons we do not rebind on
19767 				 * each packet but keep the binding until the
19768 				 * next IP_MULTICAST_IF option.
19769 				 *
19770 				 * conn_multicast_{ipif,ill} are shared between
19771 				 * IPv4 and IPv6 and AF_INET6 sockets can
19772 				 * send both IPv4 and IPv6 packets. Hence
19773 				 * we have to check that "isv6" matches above.
19774 				 */
19775 				if (ipif != NULL)
19776 					ipif_refrele(ipif);
19777 				ipif = ipif_lookup_group(dst, zoneid);
19778 				if (ipif == NULL) {
19779 					ip1dbg(("ip_wput: No ipif for "
19780 					    "multicast\n"));
19781 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19782 					goto drop_pkt;
19783 				}
19784 				err = conn_set_held_ipif(connp,
19785 				    &connp->conn_multicast_ipif, ipif);
19786 				if (err == IPIF_LOOKUP_FAILED) {
19787 					ipif_refrele(ipif);
19788 					ip1dbg(("ip_wput: No ipif for "
19789 					    "multicast\n"));
19790 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19791 					goto drop_pkt;
19792 				}
19793 			}
19794 		}
19795 		ASSERT(!ipif->ipif_isv6);
19796 		/*
19797 		 * As we may lose the conn by the time we reach ip_wput_ire,
19798 		 * we copy conn_multicast_loop and conn_dontroute on to an
19799 		 * ipsec_out. In case if this datagram goes out secure,
19800 		 * we need the ill_index also. Copy that also into the
19801 		 * ipsec_out.
19802 		 */
19803 		if (mctl_present) {
19804 			io = (ipsec_out_t *)first_mp->b_rptr;
19805 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19806 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19807 		} else {
19808 			ASSERT(mp == first_mp);
19809 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19810 			    BPRI_HI)) == NULL) {
19811 				ipif_refrele(ipif);
19812 				first_mp = mp;
19813 				goto drop_pkt;
19814 			}
19815 			first_mp->b_datap->db_type = M_CTL;
19816 			first_mp->b_wptr += sizeof (ipsec_info_t);
19817 			/* ipsec_out_secure is B_FALSE now */
19818 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19819 			io = (ipsec_out_t *)first_mp->b_rptr;
19820 			io->ipsec_out_type = IPSEC_OUT;
19821 			io->ipsec_out_len = sizeof (ipsec_out_t);
19822 			io->ipsec_out_use_global_policy = B_TRUE;
19823 			first_mp->b_cont = mp;
19824 			mctl_present = B_TRUE;
19825 		}
19826 		if (attach_ill != NULL) {
19827 			ASSERT(attach_ill == ipif->ipif_ill);
19828 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19829 
19830 			/*
19831 			 * Check if we need an ire that will not be
19832 			 * looked up by anybody else i.e. HIDDEN.
19833 			 */
19834 			if (ill_is_probeonly(attach_ill)) {
19835 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19836 			}
19837 			io->ipsec_out_ill_index =
19838 			    attach_ill->ill_phyint->phyint_ifindex;
19839 			io->ipsec_out_attach_if = B_TRUE;
19840 		} else {
19841 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19842 			io->ipsec_out_ill_index =
19843 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19844 		}
19845 		if (connp != NULL) {
19846 			io->ipsec_out_multicast_loop =
19847 			    connp->conn_multicast_loop;
19848 			io->ipsec_out_dontroute = connp->conn_dontroute;
19849 			io->ipsec_out_zoneid = connp->conn_zoneid;
19850 		}
19851 		/*
19852 		 * If the application uses IP_MULTICAST_IF with
19853 		 * different logical addresses of the same ILL, we
19854 		 * need to make sure that the soruce address of
19855 		 * the packet matches the logical IP address used
19856 		 * in the option. We do it by initializing ipha_src
19857 		 * here. This should keep IPSEC also happy as
19858 		 * when we return from IPSEC processing, we don't
19859 		 * have to worry about getting the right address on
19860 		 * the packet. Thus it is sufficient to look for
19861 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19862 		 * MATCH_IRE_IPIF.
19863 		 *
19864 		 * NOTE : We need to do it for non-secure case also as
19865 		 * this might go out secure if there is a global policy
19866 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19867 		 * address, the source should be initialized already and
19868 		 * hence we won't be initializing here.
19869 		 *
19870 		 * As we do not have the ire yet, it is possible that
19871 		 * we set the source address here and then later discover
19872 		 * that the ire implies the source address to be assigned
19873 		 * through the RTF_SETSRC flag.
19874 		 * In that case, the setsrc variable will remind us
19875 		 * that overwritting the source address by the one
19876 		 * of the RTF_SETSRC-flagged ire is allowed.
19877 		 */
19878 		if (ipha->ipha_src == INADDR_ANY &&
19879 		    (connp == NULL || !connp->conn_unspec_src)) {
19880 			ipha->ipha_src = ipif->ipif_src_addr;
19881 			setsrc = RTF_SETSRC;
19882 		}
19883 		/*
19884 		 * Find an IRE which matches the destination and the outgoing
19885 		 * queue (i.e. the outgoing interface.)
19886 		 * For loopback use a unicast IP address for
19887 		 * the ire lookup.
19888 		 */
19889 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19890 		    PHYI_LOOPBACK) {
19891 			dst = ipif->ipif_lcl_addr;
19892 		}
19893 		/*
19894 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19895 		 * We don't need to lookup ire in ctable as the packet
19896 		 * needs to be sent to the destination through the specified
19897 		 * ill irrespective of ires in the cache table.
19898 		 */
19899 		ire = NULL;
19900 		if (xmit_ill == NULL) {
19901 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19902 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19903 		}
19904 
19905 		/*
19906 		 * refrele attach_ill as its not needed anymore.
19907 		 */
19908 		if (attach_ill != NULL) {
19909 			ill_refrele(attach_ill);
19910 			attach_ill = NULL;
19911 		}
19912 
19913 		if (ire == NULL) {
19914 			/*
19915 			 * Multicast loopback and multicast forwarding is
19916 			 * done in ip_wput_ire.
19917 			 *
19918 			 * Mark this packet to make it be delivered to
19919 			 * ip_wput_ire after the new ire has been
19920 			 * created.
19921 			 *
19922 			 * The call to ip_newroute_ipif takes into account
19923 			 * the setsrc reminder. In any case, we take care
19924 			 * of the RTF_MULTIRT flag.
19925 			 */
19926 			mp->b_prev = mp->b_next = NULL;
19927 			if (xmit_ill == NULL ||
19928 			    xmit_ill->ill_ipif_up_count > 0) {
19929 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19930 				    setsrc | RTF_MULTIRT);
19931 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19932 				    "ip_wput_end: q %p (%S)", q, "noire");
19933 			} else {
19934 				freemsg(first_mp);
19935 			}
19936 			ipif_refrele(ipif);
19937 			if (xmit_ill != NULL)
19938 				ill_refrele(xmit_ill);
19939 			if (need_decref)
19940 				CONN_DEC_REF(connp);
19941 			return;
19942 		}
19943 
19944 		ipif_refrele(ipif);
19945 		ipif = NULL;
19946 		ASSERT(xmit_ill == NULL);
19947 
19948 		/*
19949 		 * Honor the RTF_SETSRC flag for multicast packets,
19950 		 * if allowed by the setsrc reminder.
19951 		 */
19952 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19953 			ipha->ipha_src = ire->ire_src_addr;
19954 		}
19955 
19956 		/*
19957 		 * Unconditionally force the TTL to 1 for
19958 		 * multirouted multicast packets:
19959 		 * multirouted multicast should not cross
19960 		 * multicast routers.
19961 		 */
19962 		if (ire->ire_flags & RTF_MULTIRT) {
19963 			if (ipha->ipha_ttl > 1) {
19964 				ip2dbg(("ip_wput: forcing multicast "
19965 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19966 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19967 				ipha->ipha_ttl = 1;
19968 			}
19969 		}
19970 	} else {
19971 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19972 		if ((ire != NULL) && (ire->ire_type &
19973 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19974 			ignore_dontroute = B_TRUE;
19975 			ignore_nexthop = B_TRUE;
19976 		}
19977 		if (ire != NULL) {
19978 			ire_refrele(ire);
19979 			ire = NULL;
19980 		}
19981 		/*
19982 		 * Guard against coming in from arp in which case conn is NULL.
19983 		 * Also guard against non M_DATA with dontroute set but
19984 		 * destined to local, loopback or broadcast addresses.
19985 		 */
19986 		if (connp != NULL && connp->conn_dontroute &&
19987 		    !ignore_dontroute) {
19988 dontroute:
19989 			/*
19990 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19991 			 * routing protocols from seeing false direct
19992 			 * connectivity.
19993 			 */
19994 			ipha->ipha_ttl = 1;
19995 			/*
19996 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19997 			 * along with SO_DONTROUTE, higher precedence is
19998 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19999 			 */
20000 			if (connp->conn_xmit_if_ill == NULL) {
20001 				/* If suitable ipif not found, drop packet */
20002 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20003 				if (dst_ipif == NULL) {
20004 					ip1dbg(("ip_wput: no route for "
20005 					    "dst using SO_DONTROUTE\n"));
20006 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20007 					mp->b_prev = mp->b_next = NULL;
20008 					if (first_mp == NULL)
20009 						first_mp = mp;
20010 					goto drop_pkt;
20011 				} else {
20012 					/*
20013 					 * If suitable ipif has been found, set
20014 					 * xmit_ill to the corresponding
20015 					 * ipif_ill because we'll be following
20016 					 * the IP_XMIT_IF logic.
20017 					 */
20018 					ASSERT(xmit_ill == NULL);
20019 					xmit_ill = dst_ipif->ipif_ill;
20020 					mutex_enter(&xmit_ill->ill_lock);
20021 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20022 						mutex_exit(&xmit_ill->ill_lock);
20023 						xmit_ill = NULL;
20024 						ipif_refrele(dst_ipif);
20025 						ip1dbg(("ip_wput: no route for"
20026 						    " dst using"
20027 						    " SO_DONTROUTE\n"));
20028 						BUMP_MIB(&ip_mib,
20029 						    ipOutNoRoutes);
20030 						mp->b_prev = mp->b_next = NULL;
20031 						if (first_mp == NULL)
20032 							first_mp = mp;
20033 						goto drop_pkt;
20034 					}
20035 					ill_refhold_locked(xmit_ill);
20036 					mutex_exit(&xmit_ill->ill_lock);
20037 					ipif_refrele(dst_ipif);
20038 				}
20039 			}
20040 
20041 		}
20042 		/*
20043 		 * If we are bound to IPIF_NOFAILOVER address, look for
20044 		 * an IRE_CACHE matching the ill.
20045 		 */
20046 send_from_ill:
20047 		if (attach_ill != NULL) {
20048 			ipif_t	*attach_ipif;
20049 
20050 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20051 
20052 			/*
20053 			 * Check if we need an ire that will not be
20054 			 * looked up by anybody else i.e. HIDDEN.
20055 			 */
20056 			if (ill_is_probeonly(attach_ill)) {
20057 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20058 			}
20059 
20060 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20061 			if (attach_ipif == NULL) {
20062 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20063 				goto drop_pkt;
20064 			}
20065 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20066 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20067 			ipif_refrele(attach_ipif);
20068 		} else if (xmit_ill != NULL || (connp != NULL &&
20069 			    connp->conn_xmit_if_ill != NULL)) {
20070 			/*
20071 			 * Mark this packet as originated locally
20072 			 */
20073 			mp->b_prev = mp->b_next = NULL;
20074 			/*
20075 			 * xmit_ill could be NULL if SO_DONTROUTE
20076 			 * is also set.
20077 			 */
20078 			if (xmit_ill == NULL) {
20079 				xmit_ill = conn_get_held_ill(connp,
20080 				    &connp->conn_xmit_if_ill, &err);
20081 				if (err == ILL_LOOKUP_FAILED) {
20082 					if (need_decref)
20083 						CONN_DEC_REF(connp);
20084 					freemsg(first_mp);
20085 					return;
20086 				}
20087 				if (xmit_ill == NULL) {
20088 					if (connp->conn_dontroute)
20089 						goto dontroute;
20090 					goto send_from_ill;
20091 				}
20092 			}
20093 			/*
20094 			 * could be SO_DONTROUTE case also.
20095 			 * check at least one interface is UP as
20096 			 * spcified by this ILL, and then call
20097 			 * ip_newroute_ipif()
20098 			 */
20099 			if (xmit_ill->ill_ipif_up_count > 0) {
20100 				ipif_t *ipif;
20101 
20102 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20103 				if (ipif != NULL) {
20104 					ip_newroute_ipif(q, first_mp, ipif,
20105 					    dst, connp, 0);
20106 					ipif_refrele(ipif);
20107 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20108 				}
20109 			} else {
20110 				freemsg(first_mp);
20111 			}
20112 			ill_refrele(xmit_ill);
20113 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20114 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20115 			if (need_decref)
20116 				CONN_DEC_REF(connp);
20117 			return;
20118 		} else if (ip_nexthop || (connp != NULL &&
20119 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20120 			if (!ip_nexthop) {
20121 				ip_nexthop = B_TRUE;
20122 				nexthop_addr = connp->conn_nexthop_v4;
20123 			}
20124 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20125 			    MATCH_IRE_GW;
20126 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20127 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20128 		} else {
20129 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20130 		}
20131 		if (!ire) {
20132 			/*
20133 			 * Make sure we don't load spread if this
20134 			 * is IPIF_NOFAILOVER case.
20135 			 */
20136 			if ((attach_ill != NULL) ||
20137 			    (ip_nexthop && !ignore_nexthop)) {
20138 				if (mctl_present) {
20139 					io = (ipsec_out_t *)first_mp->b_rptr;
20140 					ASSERT(first_mp->b_datap->db_type ==
20141 					    M_CTL);
20142 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20143 				} else {
20144 					ASSERT(mp == first_mp);
20145 					first_mp = allocb(
20146 					    sizeof (ipsec_info_t), BPRI_HI);
20147 					if (first_mp == NULL) {
20148 						first_mp = mp;
20149 						goto drop_pkt;
20150 					}
20151 					first_mp->b_datap->db_type = M_CTL;
20152 					first_mp->b_wptr +=
20153 					    sizeof (ipsec_info_t);
20154 					/* ipsec_out_secure is B_FALSE now */
20155 					bzero(first_mp->b_rptr,
20156 					    sizeof (ipsec_info_t));
20157 					io = (ipsec_out_t *)first_mp->b_rptr;
20158 					io->ipsec_out_type = IPSEC_OUT;
20159 					io->ipsec_out_len =
20160 					    sizeof (ipsec_out_t);
20161 					io->ipsec_out_use_global_policy =
20162 					    B_TRUE;
20163 					first_mp->b_cont = mp;
20164 					mctl_present = B_TRUE;
20165 				}
20166 				if (attach_ill != NULL) {
20167 					io->ipsec_out_ill_index = attach_ill->
20168 					    ill_phyint->phyint_ifindex;
20169 					io->ipsec_out_attach_if = B_TRUE;
20170 				} else {
20171 					io->ipsec_out_ip_nexthop = ip_nexthop;
20172 					io->ipsec_out_nexthop_addr =
20173 					    nexthop_addr;
20174 				}
20175 			}
20176 noirefound:
20177 			/*
20178 			 * Mark this packet as having originated on
20179 			 * this machine.  This will be noted in
20180 			 * ire_add_then_send, which needs to know
20181 			 * whether to run it back through ip_wput or
20182 			 * ip_rput following successful resolution.
20183 			 */
20184 			mp->b_prev = NULL;
20185 			mp->b_next = NULL;
20186 			ip_newroute(q, first_mp, dst, NULL, connp);
20187 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20188 			    "ip_wput_end: q %p (%S)", q, "newroute");
20189 			if (attach_ill != NULL)
20190 				ill_refrele(attach_ill);
20191 			if (xmit_ill != NULL)
20192 				ill_refrele(xmit_ill);
20193 			if (need_decref)
20194 				CONN_DEC_REF(connp);
20195 			return;
20196 		}
20197 	}
20198 
20199 	/* We now know where we are going with it. */
20200 
20201 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20202 	    "ip_wput_end: q %p (%S)", q, "end");
20203 
20204 	/*
20205 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20206 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20207 	 */
20208 	if (ire->ire_flags & RTF_MULTIRT) {
20209 		/*
20210 		 * Force the TTL of multirouted packets if required.
20211 		 * The TTL of such packets is bounded by the
20212 		 * ip_multirt_ttl ndd variable.
20213 		 */
20214 		if ((ip_multirt_ttl > 0) &&
20215 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20216 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20217 			    "(was %d), dst 0x%08x\n",
20218 			    ip_multirt_ttl, ipha->ipha_ttl,
20219 			    ntohl(ire->ire_addr)));
20220 			ipha->ipha_ttl = ip_multirt_ttl;
20221 		}
20222 		/*
20223 		 * At this point, we check to see if there are any pending
20224 		 * unresolved routes. ire_multirt_resolvable()
20225 		 * checks in O(n) that all IRE_OFFSUBNET ire
20226 		 * entries for the packet's destination and
20227 		 * flagged RTF_MULTIRT are currently resolved.
20228 		 * If some remain unresolved, we make a copy
20229 		 * of the current message. It will be used
20230 		 * to initiate additional route resolutions.
20231 		 */
20232 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20233 		    MBLK_GETLABEL(first_mp));
20234 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20235 		    "multirt_need_resolve %d, first_mp %p\n",
20236 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20237 		if (multirt_need_resolve) {
20238 			copy_mp = copymsg(first_mp);
20239 			if (copy_mp != NULL) {
20240 				MULTIRT_DEBUG_TAG(copy_mp);
20241 			}
20242 		}
20243 	}
20244 
20245 	ip_wput_ire(q, first_mp, ire, connp, caller);
20246 	/*
20247 	 * Try to resolve another multiroute if
20248 	 * ire_multirt_resolvable() deemed it necessary.
20249 	 * At this point, we need to distinguish
20250 	 * multicasts from other packets. For multicasts,
20251 	 * we call ip_newroute_ipif() and request that both
20252 	 * multirouting and setsrc flags are checked.
20253 	 */
20254 	if (copy_mp != NULL) {
20255 		if (CLASSD(dst)) {
20256 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20257 			if (ipif) {
20258 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20259 				    RTF_SETSRC | RTF_MULTIRT);
20260 				ipif_refrele(ipif);
20261 			} else {
20262 				MULTIRT_DEBUG_UNTAG(copy_mp);
20263 				freemsg(copy_mp);
20264 				copy_mp = NULL;
20265 			}
20266 		} else {
20267 			ip_newroute(q, copy_mp, dst, NULL, connp);
20268 		}
20269 	}
20270 	if (attach_ill != NULL)
20271 		ill_refrele(attach_ill);
20272 	if (xmit_ill != NULL)
20273 		ill_refrele(xmit_ill);
20274 	if (need_decref)
20275 		CONN_DEC_REF(connp);
20276 	return;
20277 
20278 icmp_parameter_problem:
20279 	/* could not have originated externally */
20280 	ASSERT(mp->b_prev == NULL);
20281 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20282 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20283 		/* it's the IP header length that's in trouble */
20284 		icmp_param_problem(q, first_mp, 0);
20285 		first_mp = NULL;
20286 	}
20287 
20288 drop_pkt:
20289 	ip1dbg(("ip_wput: dropped packet\n"));
20290 	if (ire != NULL)
20291 		ire_refrele(ire);
20292 	if (need_decref)
20293 		CONN_DEC_REF(connp);
20294 	freemsg(first_mp);
20295 	if (attach_ill != NULL)
20296 		ill_refrele(attach_ill);
20297 	if (xmit_ill != NULL)
20298 		ill_refrele(xmit_ill);
20299 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20300 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20301 }
20302 
20303 void
20304 ip_wput(queue_t *q, mblk_t *mp)
20305 {
20306 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20307 }
20308 
20309 /*
20310  *
20311  * The following rules must be observed when accessing any ipif or ill
20312  * that has been cached in the conn. Typically conn_nofailover_ill,
20313  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20314  *
20315  * Access: The ipif or ill pointed to from the conn can be accessed under
20316  * the protection of the conn_lock or after it has been refheld under the
20317  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20318  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20319  * The reason for this is that a concurrent unplumb could actually be
20320  * cleaning up these cached pointers by walking the conns and might have
20321  * finished cleaning up the conn in question. The macros check that an
20322  * unplumb has not yet started on the ipif or ill.
20323  *
20324  * Caching: An ipif or ill pointer may be cached in the conn only after
20325  * making sure that an unplumb has not started. So the caching is done
20326  * while holding both the conn_lock and the ill_lock and after using the
20327  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20328  * flag before starting the cleanup of conns.
20329  *
20330  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20331  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20332  * or a reference to the ipif or a reference to an ire that references the
20333  * ipif. An ipif does not change its ill except for failover/failback. Since
20334  * failover/failback happens only after bringing down the ipif and making sure
20335  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20336  * the above holds.
20337  */
20338 ipif_t *
20339 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20340 {
20341 	ipif_t	*ipif;
20342 	ill_t	*ill;
20343 
20344 	*err = 0;
20345 	rw_enter(&ill_g_lock, RW_READER);
20346 	mutex_enter(&connp->conn_lock);
20347 	ipif = *ipifp;
20348 	if (ipif != NULL) {
20349 		ill = ipif->ipif_ill;
20350 		mutex_enter(&ill->ill_lock);
20351 		if (IPIF_CAN_LOOKUP(ipif)) {
20352 			ipif_refhold_locked(ipif);
20353 			mutex_exit(&ill->ill_lock);
20354 			mutex_exit(&connp->conn_lock);
20355 			rw_exit(&ill_g_lock);
20356 			return (ipif);
20357 		} else {
20358 			*err = IPIF_LOOKUP_FAILED;
20359 		}
20360 		mutex_exit(&ill->ill_lock);
20361 	}
20362 	mutex_exit(&connp->conn_lock);
20363 	rw_exit(&ill_g_lock);
20364 	return (NULL);
20365 }
20366 
20367 ill_t *
20368 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20369 {
20370 	ill_t	*ill;
20371 
20372 	*err = 0;
20373 	mutex_enter(&connp->conn_lock);
20374 	ill = *illp;
20375 	if (ill != NULL) {
20376 		mutex_enter(&ill->ill_lock);
20377 		if (ILL_CAN_LOOKUP(ill)) {
20378 			ill_refhold_locked(ill);
20379 			mutex_exit(&ill->ill_lock);
20380 			mutex_exit(&connp->conn_lock);
20381 			return (ill);
20382 		} else {
20383 			*err = ILL_LOOKUP_FAILED;
20384 		}
20385 		mutex_exit(&ill->ill_lock);
20386 	}
20387 	mutex_exit(&connp->conn_lock);
20388 	return (NULL);
20389 }
20390 
20391 static int
20392 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20393 {
20394 	ill_t	*ill;
20395 
20396 	ill = ipif->ipif_ill;
20397 	mutex_enter(&connp->conn_lock);
20398 	mutex_enter(&ill->ill_lock);
20399 	if (IPIF_CAN_LOOKUP(ipif)) {
20400 		*ipifp = ipif;
20401 		mutex_exit(&ill->ill_lock);
20402 		mutex_exit(&connp->conn_lock);
20403 		return (0);
20404 	}
20405 	mutex_exit(&ill->ill_lock);
20406 	mutex_exit(&connp->conn_lock);
20407 	return (IPIF_LOOKUP_FAILED);
20408 }
20409 
20410 /*
20411  * This is called if the outbound datagram needs fragmentation.
20412  *
20413  * NOTE : This function does not ire_refrele the ire argument passed in.
20414  */
20415 static void
20416 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20417 {
20418 	ipha_t		*ipha;
20419 	mblk_t		*mp;
20420 	uint32_t	v_hlen_tos_len;
20421 	uint32_t	max_frag;
20422 	uint32_t	frag_flag;
20423 	boolean_t	dont_use;
20424 
20425 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20426 		mp = ipsec_mp->b_cont;
20427 	} else {
20428 		mp = ipsec_mp;
20429 	}
20430 
20431 	ipha = (ipha_t *)mp->b_rptr;
20432 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20433 
20434 #ifdef	_BIG_ENDIAN
20435 #define	V_HLEN	(v_hlen_tos_len >> 24)
20436 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20437 #else
20438 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20439 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20440 #endif
20441 
20442 #ifndef SPEED_BEFORE_SAFETY
20443 	/*
20444 	 * Check that ipha_length is consistent with
20445 	 * the mblk length
20446 	 */
20447 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20448 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20449 		    LENGTH, msgdsize(mp)));
20450 		freemsg(ipsec_mp);
20451 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20452 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20453 		    "packet length mismatch");
20454 		return;
20455 	}
20456 #endif
20457 	/*
20458 	 * Don't use frag_flag if pre-built packet or source
20459 	 * routed or if multicast (since multicast packets do not solicit
20460 	 * ICMP "packet too big" messages). Get the values of
20461 	 * max_frag and frag_flag atomically by acquiring the
20462 	 * ire_lock.
20463 	 */
20464 	mutex_enter(&ire->ire_lock);
20465 	max_frag = ire->ire_max_frag;
20466 	frag_flag = ire->ire_frag_flag;
20467 	mutex_exit(&ire->ire_lock);
20468 
20469 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20470 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20471 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20472 
20473 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20474 	    (dont_use ? 0 : frag_flag));
20475 }
20476 
20477 /*
20478  * Used for deciding the MSS size for the upper layer. Thus
20479  * we need to check the outbound policy values in the conn.
20480  */
20481 int
20482 conn_ipsec_length(conn_t *connp)
20483 {
20484 	ipsec_latch_t *ipl;
20485 
20486 	ipl = connp->conn_latch;
20487 	if (ipl == NULL)
20488 		return (0);
20489 
20490 	if (ipl->ipl_out_policy == NULL)
20491 		return (0);
20492 
20493 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20494 }
20495 
20496 /*
20497  * Returns an estimate of the IPSEC headers size. This is used if
20498  * we don't want to call into IPSEC to get the exact size.
20499  */
20500 int
20501 ipsec_out_extra_length(mblk_t *ipsec_mp)
20502 {
20503 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20504 	ipsec_action_t *a;
20505 
20506 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20507 	if (!io->ipsec_out_secure)
20508 		return (0);
20509 
20510 	a = io->ipsec_out_act;
20511 
20512 	if (a == NULL) {
20513 		ASSERT(io->ipsec_out_policy != NULL);
20514 		a = io->ipsec_out_policy->ipsp_act;
20515 	}
20516 	ASSERT(a != NULL);
20517 
20518 	return (a->ipa_ovhd);
20519 }
20520 
20521 /*
20522  * Returns an estimate of the IPSEC headers size. This is used if
20523  * we don't want to call into IPSEC to get the exact size.
20524  */
20525 int
20526 ipsec_in_extra_length(mblk_t *ipsec_mp)
20527 {
20528 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20529 	ipsec_action_t *a;
20530 
20531 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20532 
20533 	a = ii->ipsec_in_action;
20534 	return (a == NULL ? 0 : a->ipa_ovhd);
20535 }
20536 
20537 /*
20538  * If there are any source route options, return the true final
20539  * destination. Otherwise, return the destination.
20540  */
20541 ipaddr_t
20542 ip_get_dst(ipha_t *ipha)
20543 {
20544 	ipoptp_t	opts;
20545 	uchar_t		*opt;
20546 	uint8_t		optval;
20547 	uint8_t		optlen;
20548 	ipaddr_t	dst;
20549 	uint32_t off;
20550 
20551 	dst = ipha->ipha_dst;
20552 
20553 	if (IS_SIMPLE_IPH(ipha))
20554 		return (dst);
20555 
20556 	for (optval = ipoptp_first(&opts, ipha);
20557 	    optval != IPOPT_EOL;
20558 	    optval = ipoptp_next(&opts)) {
20559 		opt = opts.ipoptp_cur;
20560 		optlen = opts.ipoptp_len;
20561 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20562 		switch (optval) {
20563 		case IPOPT_SSRR:
20564 		case IPOPT_LSRR:
20565 			off = opt[IPOPT_OFFSET];
20566 			/*
20567 			 * If one of the conditions is true, it means
20568 			 * end of options and dst already has the right
20569 			 * value.
20570 			 */
20571 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20572 				off = optlen - IP_ADDR_LEN;
20573 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20574 			}
20575 			return (dst);
20576 		default:
20577 			break;
20578 		}
20579 	}
20580 
20581 	return (dst);
20582 }
20583 
20584 mblk_t *
20585 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20586     conn_t *connp, boolean_t unspec_src)
20587 {
20588 	ipsec_out_t	*io;
20589 	mblk_t		*first_mp;
20590 	boolean_t policy_present;
20591 
20592 	first_mp = mp;
20593 	if (mp->b_datap->db_type == M_CTL) {
20594 		io = (ipsec_out_t *)first_mp->b_rptr;
20595 		/*
20596 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20597 		 *
20598 		 * 1) There is per-socket policy (including cached global
20599 		 *    policy).
20600 		 * 2) There is no per-socket policy, but it is
20601 		 *    a multicast packet that needs to go out
20602 		 *    on a specific interface. This is the case
20603 		 *    where (ip_wput and ip_wput_multicast) attaches
20604 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20605 		 *
20606 		 * In case (2) we check with global policy to
20607 		 * see if there is a match and set the ill_index
20608 		 * appropriately so that we can lookup the ire
20609 		 * properly in ip_wput_ipsec_out.
20610 		 */
20611 
20612 		/*
20613 		 * ipsec_out_use_global_policy is set to B_FALSE
20614 		 * in ipsec_in_to_out(). Refer to that function for
20615 		 * details.
20616 		 */
20617 		if ((io->ipsec_out_latch == NULL) &&
20618 		    (io->ipsec_out_use_global_policy)) {
20619 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20620 			    ire, connp, unspec_src));
20621 		}
20622 		if (!io->ipsec_out_secure) {
20623 			/*
20624 			 * If this is not a secure packet, drop
20625 			 * the IPSEC_OUT mp and treat it as a clear
20626 			 * packet. This happens when we are sending
20627 			 * a ICMP reply back to a clear packet. See
20628 			 * ipsec_in_to_out() for details.
20629 			 */
20630 			mp = first_mp->b_cont;
20631 			freeb(first_mp);
20632 		}
20633 		return (mp);
20634 	}
20635 	/*
20636 	 * See whether we need to attach a global policy here. We
20637 	 * don't depend on the conn (as it could be null) for deciding
20638 	 * what policy this datagram should go through because it
20639 	 * should have happened in ip_wput if there was some
20640 	 * policy. This normally happens for connections which are not
20641 	 * fully bound preventing us from caching policies in
20642 	 * ip_bind. Packets coming from the TCP listener/global queue
20643 	 * - which are non-hard_bound - could also be affected by
20644 	 * applying policy here.
20645 	 *
20646 	 * If this packet is coming from tcp global queue or listener,
20647 	 * we will be applying policy here.  This may not be *right*
20648 	 * if these packets are coming from the detached connection as
20649 	 * it could have gone in clear before. This happens only if a
20650 	 * TCP connection started when there is no policy and somebody
20651 	 * added policy before it became detached. Thus packets of the
20652 	 * detached connection could go out secure and the other end
20653 	 * would drop it because it will be expecting in clear. The
20654 	 * converse is not true i.e if somebody starts a TCP
20655 	 * connection and deletes the policy, all the packets will
20656 	 * still go out with the policy that existed before deleting
20657 	 * because ip_unbind sends up policy information which is used
20658 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20659 	 * TCP to attach a dummy IPSEC_OUT and set
20660 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20661 	 * affect performance for normal cases, we are not doing it.
20662 	 * Thus, set policy before starting any TCP connections.
20663 	 *
20664 	 * NOTE - We might apply policy even for a hard bound connection
20665 	 * - for which we cached policy in ip_bind - if somebody added
20666 	 * global policy after we inherited the policy in ip_bind.
20667 	 * This means that the packets that were going out in clear
20668 	 * previously would start going secure and hence get dropped
20669 	 * on the other side. To fix this, TCP attaches a dummy
20670 	 * ipsec_out and make sure that we don't apply global policy.
20671 	 */
20672 	if (ipha != NULL)
20673 		policy_present = ipsec_outbound_v4_policy_present;
20674 	else
20675 		policy_present = ipsec_outbound_v6_policy_present;
20676 	if (!policy_present)
20677 		return (mp);
20678 
20679 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20680 }
20681 
20682 ire_t *
20683 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20684 {
20685 	ipaddr_t addr;
20686 	ire_t *save_ire;
20687 	irb_t *irb;
20688 	ill_group_t *illgrp;
20689 	int	err;
20690 
20691 	save_ire = ire;
20692 	addr = ire->ire_addr;
20693 
20694 	ASSERT(ire->ire_type == IRE_BROADCAST);
20695 
20696 	illgrp = connp->conn_outgoing_ill->ill_group;
20697 	if (illgrp == NULL) {
20698 		*conn_outgoing_ill = conn_get_held_ill(connp,
20699 		    &connp->conn_outgoing_ill, &err);
20700 		if (err == ILL_LOOKUP_FAILED) {
20701 			ire_refrele(save_ire);
20702 			return (NULL);
20703 		}
20704 		return (save_ire);
20705 	}
20706 	/*
20707 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20708 	 * If it is part of the group, we need to send on the ire
20709 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20710 	 * to this group. This is okay as IP_BOUND_IF really means
20711 	 * any ill in the group. We depend on the fact that the
20712 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20713 	 * if such an ire exists. This is possible only if you have
20714 	 * at least one ill in the group that has not failed.
20715 	 *
20716 	 * First get to the ire that matches the address and group.
20717 	 *
20718 	 * We don't look for an ire with a matching zoneid because a given zone
20719 	 * won't always have broadcast ires on all ills in the group.
20720 	 */
20721 	irb = ire->ire_bucket;
20722 	rw_enter(&irb->irb_lock, RW_READER);
20723 	if (ire->ire_marks & IRE_MARK_NORECV) {
20724 		/*
20725 		 * If the current zone only has an ire broadcast for this
20726 		 * address marked NORECV, the ire we want is ahead in the
20727 		 * bucket, so we look it up deliberately ignoring the zoneid.
20728 		 */
20729 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20730 			if (ire->ire_addr != addr)
20731 				continue;
20732 			/* skip over deleted ires */
20733 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20734 				continue;
20735 		}
20736 	}
20737 	while (ire != NULL) {
20738 		/*
20739 		 * If a new interface is coming up, we could end up
20740 		 * seeing the loopback ire and the non-loopback ire
20741 		 * may not have been added yet. So check for ire_stq
20742 		 */
20743 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20744 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20745 			break;
20746 		}
20747 		ire = ire->ire_next;
20748 	}
20749 	if (ire != NULL && ire->ire_addr == addr &&
20750 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20751 		IRE_REFHOLD(ire);
20752 		rw_exit(&irb->irb_lock);
20753 		ire_refrele(save_ire);
20754 		*conn_outgoing_ill = ire_to_ill(ire);
20755 		/*
20756 		 * Refhold the ill to make the conn_outgoing_ill
20757 		 * independent of the ire. ip_wput_ire goes in a loop
20758 		 * and may refrele the ire. Since we have an ire at this
20759 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20760 		 */
20761 		ill_refhold(*conn_outgoing_ill);
20762 		return (ire);
20763 	}
20764 	rw_exit(&irb->irb_lock);
20765 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20766 	/*
20767 	 * If we can't find a suitable ire, return the original ire.
20768 	 */
20769 	return (save_ire);
20770 }
20771 
20772 /*
20773  * This function does the ire_refrele of the ire passed in as the
20774  * argument. As this function looks up more ires i.e broadcast ires,
20775  * it needs to REFRELE them. Currently, for simplicity we don't
20776  * differentiate the one passed in and looked up here. We always
20777  * REFRELE.
20778  * IPQoS Notes:
20779  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20780  * IPSec packets are done in ipsec_out_process.
20781  *
20782  */
20783 void
20784 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20785 {
20786 	ipha_t		*ipha;
20787 #define	rptr	((uchar_t *)ipha)
20788 	queue_t		*stq;
20789 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20790 	uint32_t	v_hlen_tos_len;
20791 	uint32_t	ttl_protocol;
20792 	ipaddr_t	src;
20793 	ipaddr_t	dst;
20794 	uint32_t	cksum;
20795 	ipaddr_t	orig_src;
20796 	ire_t		*ire1;
20797 	mblk_t		*next_mp;
20798 	uint_t		hlen;
20799 	uint16_t	*up;
20800 	uint32_t	max_frag = ire->ire_max_frag;
20801 	ill_t		*ill = ire_to_ill(ire);
20802 	int		clusterwide;
20803 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20804 	int		ipsec_len;
20805 	mblk_t		*first_mp;
20806 	ipsec_out_t	*io;
20807 	boolean_t	conn_dontroute;		/* conn value for multicast */
20808 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20809 	boolean_t	multicast_forward;	/* Should we forward ? */
20810 	boolean_t	unspec_src;
20811 	ill_t		*conn_outgoing_ill = NULL;
20812 	ill_t		*ire_ill;
20813 	ill_t		*ire1_ill;
20814 	uint32_t 	ill_index = 0;
20815 	boolean_t	multirt_send = B_FALSE;
20816 	int		err;
20817 	zoneid_t	zoneid;
20818 	ipxmit_state_t	pktxmit_state;
20819 
20820 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20821 	    "ip_wput_ire_start: q %p", q);
20822 
20823 	multicast_forward = B_FALSE;
20824 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20825 
20826 	if (ire->ire_flags & RTF_MULTIRT) {
20827 		/*
20828 		 * Multirouting case. The bucket where ire is stored
20829 		 * probably holds other RTF_MULTIRT flagged ire
20830 		 * to the destination. In this call to ip_wput_ire,
20831 		 * we attempt to send the packet through all
20832 		 * those ires. Thus, we first ensure that ire is the
20833 		 * first RTF_MULTIRT ire in the bucket,
20834 		 * before walking the ire list.
20835 		 */
20836 		ire_t *first_ire;
20837 		irb_t *irb = ire->ire_bucket;
20838 		ASSERT(irb != NULL);
20839 
20840 		/* Make sure we do not omit any multiroute ire. */
20841 		IRB_REFHOLD(irb);
20842 		for (first_ire = irb->irb_ire;
20843 		    first_ire != NULL;
20844 		    first_ire = first_ire->ire_next) {
20845 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20846 			    (first_ire->ire_addr == ire->ire_addr) &&
20847 			    !(first_ire->ire_marks &
20848 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20849 				break;
20850 		}
20851 
20852 		if ((first_ire != NULL) && (first_ire != ire)) {
20853 			IRE_REFHOLD(first_ire);
20854 			ire_refrele(ire);
20855 			ire = first_ire;
20856 			ill = ire_to_ill(ire);
20857 		}
20858 		IRB_REFRELE(irb);
20859 	}
20860 
20861 	/*
20862 	 * conn_outgoing_ill is used only in the broadcast loop.
20863 	 * for performance we don't grab the mutexs in the fastpath
20864 	 */
20865 	if ((connp != NULL) &&
20866 	    (connp->conn_xmit_if_ill == NULL) &&
20867 	    (ire->ire_type == IRE_BROADCAST) &&
20868 	    ((connp->conn_nofailover_ill != NULL) ||
20869 	    (connp->conn_outgoing_ill != NULL))) {
20870 		/*
20871 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20872 		 * option. So, see if this endpoint is bound to a
20873 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20874 		 * that if the interface is failed, we will still send
20875 		 * the packet on the same ill which is what we want.
20876 		 */
20877 		conn_outgoing_ill = conn_get_held_ill(connp,
20878 		    &connp->conn_nofailover_ill, &err);
20879 		if (err == ILL_LOOKUP_FAILED) {
20880 			ire_refrele(ire);
20881 			freemsg(mp);
20882 			return;
20883 		}
20884 		if (conn_outgoing_ill == NULL) {
20885 			/*
20886 			 * Choose a good ill in the group to send the
20887 			 * packets on.
20888 			 */
20889 			ire = conn_set_outgoing_ill(connp, ire,
20890 			    &conn_outgoing_ill);
20891 			if (ire == NULL) {
20892 				freemsg(mp);
20893 				return;
20894 			}
20895 		}
20896 	}
20897 
20898 	if (mp->b_datap->db_type != M_CTL) {
20899 		ipha = (ipha_t *)mp->b_rptr;
20900 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20901 	} else {
20902 		io = (ipsec_out_t *)mp->b_rptr;
20903 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20904 		zoneid = io->ipsec_out_zoneid;
20905 		ASSERT(zoneid != ALL_ZONES);
20906 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20907 		dst = ipha->ipha_dst;
20908 		/*
20909 		 * For the multicast case, ipsec_out carries conn_dontroute and
20910 		 * conn_multicast_loop as conn may not be available here. We
20911 		 * need this for multicast loopback and forwarding which is done
20912 		 * later in the code.
20913 		 */
20914 		if (CLASSD(dst)) {
20915 			conn_dontroute = io->ipsec_out_dontroute;
20916 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20917 			/*
20918 			 * If conn_dontroute is not set or conn_multicast_loop
20919 			 * is set, we need to do forwarding/loopback. For
20920 			 * datagrams from ip_wput_multicast, conn_dontroute is
20921 			 * set to B_TRUE and conn_multicast_loop is set to
20922 			 * B_FALSE so that we neither do forwarding nor
20923 			 * loopback.
20924 			 */
20925 			if (!conn_dontroute || conn_multicast_loop)
20926 				multicast_forward = B_TRUE;
20927 		}
20928 	}
20929 
20930 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20931 	    ire->ire_zoneid != ALL_ZONES) {
20932 		/*
20933 		 * When a zone sends a packet to another zone, we try to deliver
20934 		 * the packet under the same conditions as if the destination
20935 		 * was a real node on the network. To do so, we look for a
20936 		 * matching route in the forwarding table.
20937 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20938 		 * ip_newroute() does.
20939 		 */
20940 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20941 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20942 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20943 		if (src_ire != NULL &&
20944 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20945 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20946 				ipha->ipha_src = src_ire->ire_src_addr;
20947 			ire_refrele(src_ire);
20948 		} else {
20949 			ire_refrele(ire);
20950 			if (conn_outgoing_ill != NULL)
20951 				ill_refrele(conn_outgoing_ill);
20952 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20953 			if (src_ire != NULL) {
20954 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20955 					ire_refrele(src_ire);
20956 					freemsg(mp);
20957 					return;
20958 				}
20959 				ire_refrele(src_ire);
20960 			}
20961 			if (ip_hdr_complete(ipha, zoneid)) {
20962 				/* Failed */
20963 				freemsg(mp);
20964 				return;
20965 			}
20966 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20967 			return;
20968 		}
20969 	}
20970 
20971 	if (mp->b_datap->db_type == M_CTL ||
20972 	    ipsec_outbound_v4_policy_present) {
20973 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20974 		    unspec_src);
20975 		if (mp == NULL) {
20976 			ire_refrele(ire);
20977 			if (conn_outgoing_ill != NULL)
20978 				ill_refrele(conn_outgoing_ill);
20979 			return;
20980 		}
20981 	}
20982 
20983 	first_mp = mp;
20984 	ipsec_len = 0;
20985 
20986 	if (first_mp->b_datap->db_type == M_CTL) {
20987 		io = (ipsec_out_t *)first_mp->b_rptr;
20988 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20989 		mp = first_mp->b_cont;
20990 		ipsec_len = ipsec_out_extra_length(first_mp);
20991 		ASSERT(ipsec_len >= 0);
20992 		zoneid = io->ipsec_out_zoneid;
20993 		ASSERT(zoneid != ALL_ZONES);
20994 
20995 		/*
20996 		 * Drop M_CTL here if IPsec processing is not needed.
20997 		 * (Non-IPsec use of M_CTL extracted any information it
20998 		 * needed above).
20999 		 */
21000 		if (ipsec_len == 0) {
21001 			freeb(first_mp);
21002 			first_mp = mp;
21003 		}
21004 	}
21005 
21006 	/*
21007 	 * Fast path for ip_wput_ire
21008 	 */
21009 
21010 	ipha = (ipha_t *)mp->b_rptr;
21011 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21012 	dst = ipha->ipha_dst;
21013 
21014 	/*
21015 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21016 	 * if the socket is a SOCK_RAW type. The transport checksum should
21017 	 * be provided in the pre-built packet, so we don't need to compute it.
21018 	 * Also, other application set flags, like DF, should not be altered.
21019 	 * Other transport MUST pass down zero.
21020 	 */
21021 	ip_hdr_included = ipha->ipha_ident;
21022 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21023 
21024 	if (CLASSD(dst)) {
21025 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21026 		    ntohl(dst),
21027 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21028 		    ntohl(ire->ire_addr)));
21029 	}
21030 
21031 /* Macros to extract header fields from data already in registers */
21032 #ifdef	_BIG_ENDIAN
21033 #define	V_HLEN	(v_hlen_tos_len >> 24)
21034 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21035 #define	PROTO	(ttl_protocol & 0xFF)
21036 #else
21037 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21038 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21039 #define	PROTO	(ttl_protocol >> 8)
21040 #endif
21041 
21042 
21043 	orig_src = src = ipha->ipha_src;
21044 	/* (The loop back to "another" is explained down below.) */
21045 another:;
21046 	/*
21047 	 * Assign an ident value for this packet.  We assign idents on
21048 	 * a per destination basis out of the IRE.  There could be
21049 	 * other threads targeting the same destination, so we have to
21050 	 * arrange for a atomic increment.  Note that we use a 32-bit
21051 	 * atomic add because it has better performance than its
21052 	 * 16-bit sibling.
21053 	 *
21054 	 * If running in cluster mode and if the source address
21055 	 * belongs to a replicated service then vector through
21056 	 * cl_inet_ipident vector to allocate ip identifier
21057 	 * NOTE: This is a contract private interface with the
21058 	 * clustering group.
21059 	 */
21060 	clusterwide = 0;
21061 	if (cl_inet_ipident) {
21062 		ASSERT(cl_inet_isclusterwide);
21063 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21064 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21065 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21066 			    AF_INET, (uint8_t *)(uintptr_t)src,
21067 			    (uint8_t *)(uintptr_t)dst);
21068 			clusterwide = 1;
21069 		}
21070 	}
21071 	if (!clusterwide) {
21072 		ipha->ipha_ident =
21073 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21074 	}
21075 
21076 #ifndef _BIG_ENDIAN
21077 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21078 #endif
21079 
21080 	/*
21081 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21082 	 * This is needed to obey conn_unspec_src when packets go through
21083 	 * ip_newroute + arp.
21084 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21085 	 */
21086 	if (src == INADDR_ANY && !unspec_src) {
21087 		/*
21088 		 * Assign the appropriate source address from the IRE if none
21089 		 * was specified.
21090 		 */
21091 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21092 
21093 		/*
21094 		 * With IP multipathing, broadcast packets are sent on the ire
21095 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21096 		 * the group. However, this ire might not be in the same zone so
21097 		 * we can't always use its source address. We look for a
21098 		 * broadcast ire in the same group and in the right zone.
21099 		 */
21100 		if (ire->ire_type == IRE_BROADCAST &&
21101 		    ire->ire_zoneid != zoneid) {
21102 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21103 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21104 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21105 			if (src_ire != NULL) {
21106 				src = src_ire->ire_src_addr;
21107 				ire_refrele(src_ire);
21108 			} else {
21109 				ire_refrele(ire);
21110 				if (conn_outgoing_ill != NULL)
21111 					ill_refrele(conn_outgoing_ill);
21112 				freemsg(first_mp);
21113 				BUMP_MIB(&ip_mib, ipOutDiscards);
21114 				return;
21115 			}
21116 		} else {
21117 			src = ire->ire_src_addr;
21118 		}
21119 
21120 		if (connp == NULL) {
21121 			ip1dbg(("ip_wput_ire: no connp and no src "
21122 			    "address for dst 0x%x, using src 0x%x\n",
21123 			    ntohl(dst),
21124 			    ntohl(src)));
21125 		}
21126 		ipha->ipha_src = src;
21127 	}
21128 	stq = ire->ire_stq;
21129 
21130 	/*
21131 	 * We only allow ire chains for broadcasts since there will
21132 	 * be multiple IRE_CACHE entries for the same multicast
21133 	 * address (one per ipif).
21134 	 */
21135 	next_mp = NULL;
21136 
21137 	/* broadcast packet */
21138 	if (ire->ire_type == IRE_BROADCAST)
21139 		goto broadcast;
21140 
21141 	/* loopback ? */
21142 	if (stq == NULL)
21143 		goto nullstq;
21144 
21145 	/* The ill_index for outbound ILL */
21146 	ill_index = Q_TO_INDEX(stq);
21147 
21148 	BUMP_MIB(&ip_mib, ipOutRequests);
21149 	ttl_protocol = ((uint16_t *)ipha)[4];
21150 
21151 	/* pseudo checksum (do it in parts for IP header checksum) */
21152 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21153 
21154 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21155 		queue_t *dev_q = stq->q_next;
21156 
21157 		/* flow controlled */
21158 		if ((dev_q->q_next || dev_q->q_first) &&
21159 		    !canput(dev_q))
21160 			goto blocked;
21161 		if ((PROTO == IPPROTO_UDP) &&
21162 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21163 			hlen = (V_HLEN & 0xF) << 2;
21164 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21165 			if (*up != 0) {
21166 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21167 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21168 				/* Software checksum? */
21169 				if (DB_CKSUMFLAGS(mp) == 0) {
21170 					IP_STAT(ip_out_sw_cksum);
21171 					IP_STAT_UPDATE(
21172 					    ip_udp_out_sw_cksum_bytes,
21173 					    LENGTH - hlen);
21174 				}
21175 			}
21176 		}
21177 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21178 		hlen = (V_HLEN & 0xF) << 2;
21179 		if (PROTO == IPPROTO_TCP) {
21180 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21181 			/*
21182 			 * The packet header is processed once and for all, even
21183 			 * in the multirouting case. We disable hardware
21184 			 * checksum if the packet is multirouted, as it will be
21185 			 * replicated via several interfaces, and not all of
21186 			 * them may have this capability.
21187 			 */
21188 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21189 			    LENGTH, max_frag, ipsec_len, cksum);
21190 			/* Software checksum? */
21191 			if (DB_CKSUMFLAGS(mp) == 0) {
21192 				IP_STAT(ip_out_sw_cksum);
21193 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21194 				    LENGTH - hlen);
21195 			}
21196 		} else {
21197 			sctp_hdr_t	*sctph;
21198 
21199 			ASSERT(PROTO == IPPROTO_SCTP);
21200 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21201 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21202 			/*
21203 			 * Zero out the checksum field to ensure proper
21204 			 * checksum calculation.
21205 			 */
21206 			sctph->sh_chksum = 0;
21207 #ifdef	DEBUG
21208 			if (!skip_sctp_cksum)
21209 #endif
21210 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21211 		}
21212 	}
21213 
21214 	/*
21215 	 * If this is a multicast packet and originated from ip_wput
21216 	 * we need to do loopback and forwarding checks. If it comes
21217 	 * from ip_wput_multicast, we SHOULD not do this.
21218 	 */
21219 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21220 
21221 	/* checksum */
21222 	cksum += ttl_protocol;
21223 
21224 	/* fragment the packet */
21225 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21226 		goto fragmentit;
21227 	/*
21228 	 * Don't use frag_flag if packet is pre-built or source
21229 	 * routed or if multicast (since multicast packets do
21230 	 * not solicit ICMP "packet too big" messages).
21231 	 */
21232 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21233 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21234 	    !ip_source_route_included(ipha)) &&
21235 	    !CLASSD(ipha->ipha_dst))
21236 		ipha->ipha_fragment_offset_and_flags |=
21237 		    htons(ire->ire_frag_flag);
21238 
21239 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21240 		/* calculate IP header checksum */
21241 		cksum += ipha->ipha_ident;
21242 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21243 		cksum += ipha->ipha_fragment_offset_and_flags;
21244 
21245 		/* IP options present */
21246 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21247 		if (hlen)
21248 			goto checksumoptions;
21249 
21250 		/* calculate hdr checksum */
21251 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21252 		cksum = ~(cksum + (cksum >> 16));
21253 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21254 	}
21255 	if (ipsec_len != 0) {
21256 		/*
21257 		 * We will do the rest of the processing after
21258 		 * we come back from IPSEC in ip_wput_ipsec_out().
21259 		 */
21260 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21261 
21262 		io = (ipsec_out_t *)first_mp->b_rptr;
21263 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21264 				ill_phyint->phyint_ifindex;
21265 
21266 		ipsec_out_process(q, first_mp, ire, ill_index);
21267 		ire_refrele(ire);
21268 		if (conn_outgoing_ill != NULL)
21269 			ill_refrele(conn_outgoing_ill);
21270 		return;
21271 	}
21272 
21273 	/*
21274 	 * In most cases, the emission loop below is entered only
21275 	 * once. Only in the case where the ire holds the
21276 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21277 	 * flagged ires in the bucket, and send the packet
21278 	 * through all crossed RTF_MULTIRT routes.
21279 	 */
21280 	if (ire->ire_flags & RTF_MULTIRT) {
21281 		multirt_send = B_TRUE;
21282 	}
21283 	do {
21284 		if (multirt_send) {
21285 			irb_t *irb;
21286 			/*
21287 			 * We are in a multiple send case, need to get
21288 			 * the next ire and make a duplicate of the packet.
21289 			 * ire1 holds here the next ire to process in the
21290 			 * bucket. If multirouting is expected,
21291 			 * any non-RTF_MULTIRT ire that has the
21292 			 * right destination address is ignored.
21293 			 */
21294 			irb = ire->ire_bucket;
21295 			ASSERT(irb != NULL);
21296 
21297 			IRB_REFHOLD(irb);
21298 			for (ire1 = ire->ire_next;
21299 			    ire1 != NULL;
21300 			    ire1 = ire1->ire_next) {
21301 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21302 					continue;
21303 				if (ire1->ire_addr != ire->ire_addr)
21304 					continue;
21305 				if (ire1->ire_marks &
21306 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21307 					continue;
21308 
21309 				/* Got one */
21310 				IRE_REFHOLD(ire1);
21311 				break;
21312 			}
21313 			IRB_REFRELE(irb);
21314 
21315 			if (ire1 != NULL) {
21316 				next_mp = copyb(mp);
21317 				if ((next_mp == NULL) ||
21318 				    ((mp->b_cont != NULL) &&
21319 				    ((next_mp->b_cont =
21320 				    dupmsg(mp->b_cont)) == NULL))) {
21321 					freemsg(next_mp);
21322 					next_mp = NULL;
21323 					ire_refrele(ire1);
21324 					ire1 = NULL;
21325 				}
21326 			}
21327 
21328 			/* Last multiroute ire; don't loop anymore. */
21329 			if (ire1 == NULL) {
21330 				multirt_send = B_FALSE;
21331 			}
21332 		}
21333 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21334 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21335 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21336 		if ((pktxmit_state == SEND_FAILED) ||
21337 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21338 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21339 			    "- packet dropped\n"));
21340 			ire_refrele(ire);
21341 			if (next_mp != NULL) {
21342 				freemsg(next_mp);
21343 				ire_refrele(ire1);
21344 			}
21345 			if (conn_outgoing_ill != NULL)
21346 				ill_refrele(conn_outgoing_ill);
21347 			return;
21348 		}
21349 
21350 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21351 		    "ip_wput_ire_end: q %p (%S)",
21352 		    q, "last copy out");
21353 		IRE_REFRELE(ire);
21354 
21355 		if (multirt_send) {
21356 			ASSERT(ire1);
21357 			/*
21358 			 * Proceed with the next RTF_MULTIRT ire,
21359 			 * Also set up the send-to queue accordingly.
21360 			 */
21361 			ire = ire1;
21362 			ire1 = NULL;
21363 			stq = ire->ire_stq;
21364 			mp = next_mp;
21365 			next_mp = NULL;
21366 			ipha = (ipha_t *)mp->b_rptr;
21367 			ill_index = Q_TO_INDEX(stq);
21368 		}
21369 	} while (multirt_send);
21370 	if (conn_outgoing_ill != NULL)
21371 		ill_refrele(conn_outgoing_ill);
21372 	return;
21373 
21374 	/*
21375 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21376 	 */
21377 broadcast:
21378 	{
21379 		/*
21380 		 * Avoid broadcast storms by setting the ttl to 1
21381 		 * for broadcasts. This parameter can be set
21382 		 * via ndd, so make sure that for the SO_DONTROUTE
21383 		 * case that ipha_ttl is always set to 1.
21384 		 * In the event that we are replying to incoming
21385 		 * ICMP packets, conn could be NULL.
21386 		 */
21387 		if ((connp != NULL) && connp->conn_dontroute)
21388 			ipha->ipha_ttl = 1;
21389 		else
21390 			ipha->ipha_ttl = ip_broadcast_ttl;
21391 
21392 		/*
21393 		 * Note that we are not doing a IRB_REFHOLD here.
21394 		 * Actually we don't care if the list changes i.e
21395 		 * if somebody deletes an IRE from the list while
21396 		 * we drop the lock, the next time we come around
21397 		 * ire_next will be NULL and hence we won't send
21398 		 * out multiple copies which is fine.
21399 		 */
21400 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21401 		ire1 = ire->ire_next;
21402 		if (conn_outgoing_ill != NULL) {
21403 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21404 				ASSERT(ire1 == ire->ire_next);
21405 				if (ire1 != NULL && ire1->ire_addr == dst) {
21406 					ire_refrele(ire);
21407 					ire = ire1;
21408 					IRE_REFHOLD(ire);
21409 					ire1 = ire->ire_next;
21410 					continue;
21411 				}
21412 				rw_exit(&ire->ire_bucket->irb_lock);
21413 				/* Did not find a matching ill */
21414 				ip1dbg(("ip_wput_ire: broadcast with no "
21415 				    "matching IP_BOUND_IF ill %s\n",
21416 				    conn_outgoing_ill->ill_name));
21417 				freemsg(first_mp);
21418 				if (ire != NULL)
21419 					ire_refrele(ire);
21420 				ill_refrele(conn_outgoing_ill);
21421 				return;
21422 			}
21423 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21424 			/*
21425 			 * If the next IRE has the same address and is not one
21426 			 * of the two copies that we need to send, try to see
21427 			 * whether this copy should be sent at all. This
21428 			 * assumes that we insert loopbacks first and then
21429 			 * non-loopbacks. This is acheived by inserting the
21430 			 * loopback always before non-loopback.
21431 			 * This is used to send a single copy of a broadcast
21432 			 * packet out all physical interfaces that have an
21433 			 * matching IRE_BROADCAST while also looping
21434 			 * back one copy (to ip_wput_local) for each
21435 			 * matching physical interface. However, we avoid
21436 			 * sending packets out different logical that match by
21437 			 * having ipif_up/ipif_down supress duplicate
21438 			 * IRE_BROADCASTS.
21439 			 *
21440 			 * This feature is currently used to get broadcasts
21441 			 * sent to multiple interfaces, when the broadcast
21442 			 * address being used applies to multiple interfaces.
21443 			 * For example, a whole net broadcast will be
21444 			 * replicated on every connected subnet of
21445 			 * the target net.
21446 			 *
21447 			 * Each zone has its own set of IRE_BROADCASTs, so that
21448 			 * we're able to distribute inbound packets to multiple
21449 			 * zones who share a broadcast address. We avoid looping
21450 			 * back outbound packets in different zones but on the
21451 			 * same ill, as the application would see duplicates.
21452 			 *
21453 			 * If the interfaces are part of the same group,
21454 			 * we would want to send only one copy out for
21455 			 * whole group.
21456 			 *
21457 			 * This logic assumes that ire_add_v4() groups the
21458 			 * IRE_BROADCAST entries so that those with the same
21459 			 * ire_addr and ill_group are kept together.
21460 			 */
21461 			ire_ill = ire->ire_ipif->ipif_ill;
21462 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21463 				if (ire_ill->ill_group != NULL &&
21464 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21465 					/*
21466 					 * If the current zone only has an ire
21467 					 * broadcast for this address marked
21468 					 * NORECV, the ire we want is ahead in
21469 					 * the bucket, so we look it up
21470 					 * deliberately ignoring the zoneid.
21471 					 */
21472 					for (ire1 = ire->ire_bucket->irb_ire;
21473 					    ire1 != NULL;
21474 					    ire1 = ire1->ire_next) {
21475 						ire1_ill =
21476 						    ire1->ire_ipif->ipif_ill;
21477 						if (ire1->ire_addr != dst)
21478 							continue;
21479 						/* skip over the current ire */
21480 						if (ire1 == ire)
21481 							continue;
21482 						/* skip over deleted ires */
21483 						if (ire1->ire_marks &
21484 						    IRE_MARK_CONDEMNED)
21485 							continue;
21486 						/*
21487 						 * non-loopback ire in our
21488 						 * group: use it for the next
21489 						 * pass in the loop
21490 						 */
21491 						if (ire1->ire_stq != NULL &&
21492 						    ire1_ill->ill_group ==
21493 						    ire_ill->ill_group)
21494 							break;
21495 					}
21496 				}
21497 			} else {
21498 				while (ire1 != NULL && ire1->ire_addr == dst) {
21499 					ire1_ill = ire1->ire_ipif->ipif_ill;
21500 					/*
21501 					 * We can have two broadcast ires on the
21502 					 * same ill in different zones; here
21503 					 * we'll send a copy of the packet on
21504 					 * each ill and the fanout code will
21505 					 * call conn_wantpacket() to check that
21506 					 * the zone has the broadcast address
21507 					 * configured on the ill. If the two
21508 					 * ires are in the same group we only
21509 					 * send one copy up.
21510 					 */
21511 					if (ire1_ill != ire_ill &&
21512 					    (ire1_ill->ill_group == NULL ||
21513 					    ire_ill->ill_group == NULL ||
21514 					    ire1_ill->ill_group !=
21515 					    ire_ill->ill_group)) {
21516 						break;
21517 					}
21518 					ire1 = ire1->ire_next;
21519 				}
21520 			}
21521 		}
21522 		ASSERT(multirt_send == B_FALSE);
21523 		if (ire1 != NULL && ire1->ire_addr == dst) {
21524 			if ((ire->ire_flags & RTF_MULTIRT) &&
21525 			    (ire1->ire_flags & RTF_MULTIRT)) {
21526 				/*
21527 				 * We are in the multirouting case.
21528 				 * The message must be sent at least
21529 				 * on both ires. These ires have been
21530 				 * inserted AFTER the standard ones
21531 				 * in ip_rt_add(). There are thus no
21532 				 * other ire entries for the destination
21533 				 * address in the rest of the bucket
21534 				 * that do not have the RTF_MULTIRT
21535 				 * flag. We don't process a copy
21536 				 * of the message here. This will be
21537 				 * done in the final sending loop.
21538 				 */
21539 				multirt_send = B_TRUE;
21540 			} else {
21541 				next_mp = ip_copymsg(first_mp);
21542 				if (next_mp != NULL)
21543 					IRE_REFHOLD(ire1);
21544 			}
21545 		}
21546 		rw_exit(&ire->ire_bucket->irb_lock);
21547 	}
21548 
21549 	if (stq) {
21550 		/*
21551 		 * A non-NULL send-to queue means this packet is going
21552 		 * out of this machine.
21553 		 */
21554 
21555 		BUMP_MIB(&ip_mib, ipOutRequests);
21556 		ttl_protocol = ((uint16_t *)ipha)[4];
21557 		/*
21558 		 * We accumulate the pseudo header checksum in cksum.
21559 		 * This is pretty hairy code, so watch close.  One
21560 		 * thing to keep in mind is that UDP and TCP have
21561 		 * stored their respective datagram lengths in their
21562 		 * checksum fields.  This lines things up real nice.
21563 		 */
21564 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21565 		    (src >> 16) + (src & 0xFFFF);
21566 		/*
21567 		 * We assume the udp checksum field contains the
21568 		 * length, so to compute the pseudo header checksum,
21569 		 * all we need is the protocol number and src/dst.
21570 		 */
21571 		/* Provide the checksums for UDP and TCP. */
21572 		if ((PROTO == IPPROTO_TCP) &&
21573 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21574 			/* hlen gets the number of uchar_ts in the IP header */
21575 			hlen = (V_HLEN & 0xF) << 2;
21576 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21577 			IP_STAT(ip_out_sw_cksum);
21578 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21579 			    LENGTH - hlen);
21580 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21581 			if (*up == 0)
21582 				*up = 0xFFFF;
21583 		} else if (PROTO == IPPROTO_SCTP &&
21584 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21585 			sctp_hdr_t	*sctph;
21586 
21587 			hlen = (V_HLEN & 0xF) << 2;
21588 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21589 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21590 			sctph->sh_chksum = 0;
21591 #ifdef	DEBUG
21592 			if (!skip_sctp_cksum)
21593 #endif
21594 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21595 		} else {
21596 			queue_t *dev_q = stq->q_next;
21597 
21598 			if ((dev_q->q_next || dev_q->q_first) &&
21599 			    !canput(dev_q)) {
21600 			    blocked:
21601 				ipha->ipha_ident = ip_hdr_included;
21602 				/*
21603 				 * If we don't have a conn to apply
21604 				 * backpressure, free the message.
21605 				 * In the ire_send path, we don't know
21606 				 * the position to requeue the packet. Rather
21607 				 * than reorder packets, we just drop this
21608 				 * packet.
21609 				 */
21610 				if (ip_output_queue && connp != NULL &&
21611 				    caller != IRE_SEND) {
21612 					if (caller == IP_WSRV) {
21613 						connp->conn_did_putbq = 1;
21614 						(void) putbq(connp->conn_wq,
21615 						    first_mp);
21616 						conn_drain_insert(connp);
21617 						/*
21618 						 * This is the service thread,
21619 						 * and the queue is already
21620 						 * noenabled. The check for
21621 						 * canput and the putbq is not
21622 						 * atomic. So we need to check
21623 						 * again.
21624 						 */
21625 						if (canput(stq->q_next))
21626 							connp->conn_did_putbq
21627 							    = 0;
21628 						IP_STAT(ip_conn_flputbq);
21629 					} else {
21630 						/*
21631 						 * We are not the service proc.
21632 						 * ip_wsrv will be scheduled or
21633 						 * is already running.
21634 						 */
21635 						(void) putq(connp->conn_wq,
21636 						    first_mp);
21637 					}
21638 				} else {
21639 					BUMP_MIB(&ip_mib, ipOutDiscards);
21640 					freemsg(first_mp);
21641 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21642 					    "ip_wput_ire_end: q %p (%S)",
21643 					    q, "discard");
21644 				}
21645 				ire_refrele(ire);
21646 				if (next_mp) {
21647 					ire_refrele(ire1);
21648 					freemsg(next_mp);
21649 				}
21650 				if (conn_outgoing_ill != NULL)
21651 					ill_refrele(conn_outgoing_ill);
21652 				return;
21653 			}
21654 			if ((PROTO == IPPROTO_UDP) &&
21655 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21656 				/*
21657 				 * hlen gets the number of uchar_ts in the
21658 				 * IP header
21659 				 */
21660 				hlen = (V_HLEN & 0xF) << 2;
21661 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21662 				max_frag = ire->ire_max_frag;
21663 				if (*up != 0) {
21664 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21665 					    up, PROTO, hlen, LENGTH, max_frag,
21666 					    ipsec_len, cksum);
21667 					/* Software checksum? */
21668 					if (DB_CKSUMFLAGS(mp) == 0) {
21669 						IP_STAT(ip_out_sw_cksum);
21670 						IP_STAT_UPDATE(
21671 						    ip_udp_out_sw_cksum_bytes,
21672 						    LENGTH - hlen);
21673 					}
21674 				}
21675 			}
21676 		}
21677 		/*
21678 		 * Need to do this even when fragmenting. The local
21679 		 * loopback can be done without computing checksums
21680 		 * but forwarding out other interface must be done
21681 		 * after the IP checksum (and ULP checksums) have been
21682 		 * computed.
21683 		 *
21684 		 * NOTE : multicast_forward is set only if this packet
21685 		 * originated from ip_wput. For packets originating from
21686 		 * ip_wput_multicast, it is not set.
21687 		 */
21688 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21689 		    multi_loopback:
21690 			ip2dbg(("ip_wput: multicast, loop %d\n",
21691 			    conn_multicast_loop));
21692 
21693 			/*  Forget header checksum offload */
21694 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21695 
21696 			/*
21697 			 * Local loopback of multicasts?  Check the
21698 			 * ill.
21699 			 *
21700 			 * Note that the loopback function will not come
21701 			 * in through ip_rput - it will only do the
21702 			 * client fanout thus we need to do an mforward
21703 			 * as well.  The is different from the BSD
21704 			 * logic.
21705 			 */
21706 			if (ill != NULL) {
21707 				ilm_t	*ilm;
21708 
21709 				ILM_WALKER_HOLD(ill);
21710 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21711 				    ALL_ZONES);
21712 				ILM_WALKER_RELE(ill);
21713 				if (ilm != NULL) {
21714 					/*
21715 					 * Pass along the virtual output q.
21716 					 * ip_wput_local() will distribute the
21717 					 * packet to all the matching zones,
21718 					 * except the sending zone when
21719 					 * IP_MULTICAST_LOOP is false.
21720 					 */
21721 					ip_multicast_loopback(q, ill, first_mp,
21722 					    conn_multicast_loop ? 0 :
21723 					    IP_FF_NO_MCAST_LOOP, zoneid);
21724 				}
21725 			}
21726 			if (ipha->ipha_ttl == 0) {
21727 				/*
21728 				 * 0 => only to this host i.e. we are
21729 				 * done. We are also done if this was the
21730 				 * loopback interface since it is sufficient
21731 				 * to loopback one copy of a multicast packet.
21732 				 */
21733 				freemsg(first_mp);
21734 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21735 				    "ip_wput_ire_end: q %p (%S)",
21736 				    q, "loopback");
21737 				ire_refrele(ire);
21738 				if (conn_outgoing_ill != NULL)
21739 					ill_refrele(conn_outgoing_ill);
21740 				return;
21741 			}
21742 			/*
21743 			 * ILLF_MULTICAST is checked in ip_newroute
21744 			 * i.e. we don't need to check it here since
21745 			 * all IRE_CACHEs come from ip_newroute.
21746 			 * For multicast traffic, SO_DONTROUTE is interpreted
21747 			 * to mean only send the packet out the interface
21748 			 * (optionally specified with IP_MULTICAST_IF)
21749 			 * and do not forward it out additional interfaces.
21750 			 * RSVP and the rsvp daemon is an example of a
21751 			 * protocol and user level process that
21752 			 * handles it's own routing. Hence, it uses the
21753 			 * SO_DONTROUTE option to accomplish this.
21754 			 */
21755 
21756 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21757 				/* Unconditionally redo the checksum */
21758 				ipha->ipha_hdr_checksum = 0;
21759 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21760 
21761 				/*
21762 				 * If this needs to go out secure, we need
21763 				 * to wait till we finish the IPSEC
21764 				 * processing.
21765 				 */
21766 				if (ipsec_len == 0 &&
21767 				    ip_mforward(ill, ipha, mp)) {
21768 					freemsg(first_mp);
21769 					ip1dbg(("ip_wput: mforward failed\n"));
21770 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21771 					    "ip_wput_ire_end: q %p (%S)",
21772 					    q, "mforward failed");
21773 					ire_refrele(ire);
21774 					if (conn_outgoing_ill != NULL)
21775 						ill_refrele(conn_outgoing_ill);
21776 					return;
21777 				}
21778 			}
21779 		}
21780 		max_frag = ire->ire_max_frag;
21781 		cksum += ttl_protocol;
21782 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21783 			/* No fragmentation required for this one. */
21784 			/*
21785 			 * Don't use frag_flag if packet is pre-built or source
21786 			 * routed or if multicast (since multicast packets do
21787 			 * not solicit ICMP "packet too big" messages).
21788 			 */
21789 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21790 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21791 			    !ip_source_route_included(ipha)) &&
21792 			    !CLASSD(ipha->ipha_dst))
21793 				ipha->ipha_fragment_offset_and_flags |=
21794 				    htons(ire->ire_frag_flag);
21795 
21796 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21797 				/* Complete the IP header checksum. */
21798 				cksum += ipha->ipha_ident;
21799 				cksum += (v_hlen_tos_len >> 16)+
21800 				    (v_hlen_tos_len & 0xFFFF);
21801 				cksum += ipha->ipha_fragment_offset_and_flags;
21802 				hlen = (V_HLEN & 0xF) -
21803 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21804 				if (hlen) {
21805 				    checksumoptions:
21806 					/*
21807 					 * Account for the IP Options in the IP
21808 					 * header checksum.
21809 					 */
21810 					up = (uint16_t *)(rptr+
21811 					    IP_SIMPLE_HDR_LENGTH);
21812 					do {
21813 						cksum += up[0];
21814 						cksum += up[1];
21815 						up += 2;
21816 					} while (--hlen);
21817 				}
21818 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21819 				cksum = ~(cksum + (cksum >> 16));
21820 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21821 			}
21822 			if (ipsec_len != 0) {
21823 				ipsec_out_process(q, first_mp, ire, ill_index);
21824 				if (!next_mp) {
21825 					ire_refrele(ire);
21826 					if (conn_outgoing_ill != NULL)
21827 						ill_refrele(conn_outgoing_ill);
21828 					return;
21829 				}
21830 				goto next;
21831 			}
21832 
21833 			/*
21834 			 * multirt_send has already been handled
21835 			 * for broadcast, but not yet for multicast
21836 			 * or IP options.
21837 			 */
21838 			if (next_mp == NULL) {
21839 				if (ire->ire_flags & RTF_MULTIRT) {
21840 					multirt_send = B_TRUE;
21841 				}
21842 			}
21843 
21844 			/*
21845 			 * In most cases, the emission loop below is
21846 			 * entered only once. Only in the case where
21847 			 * the ire holds the RTF_MULTIRT flag, do we loop
21848 			 * to process all RTF_MULTIRT ires in the bucket,
21849 			 * and send the packet through all crossed
21850 			 * RTF_MULTIRT routes.
21851 			 */
21852 			do {
21853 				if (multirt_send) {
21854 					irb_t *irb;
21855 
21856 					irb = ire->ire_bucket;
21857 					ASSERT(irb != NULL);
21858 					/*
21859 					 * We are in a multiple send case,
21860 					 * need to get the next IRE and make
21861 					 * a duplicate of the packet.
21862 					 */
21863 					IRB_REFHOLD(irb);
21864 					for (ire1 = ire->ire_next;
21865 					    ire1 != NULL;
21866 					    ire1 = ire1->ire_next) {
21867 						if (!(ire1->ire_flags &
21868 						    RTF_MULTIRT))
21869 							continue;
21870 						if (ire1->ire_addr !=
21871 						    ire->ire_addr)
21872 							continue;
21873 						if (ire1->ire_marks &
21874 						    (IRE_MARK_CONDEMNED|
21875 							IRE_MARK_HIDDEN))
21876 							continue;
21877 
21878 						/* Got one */
21879 						IRE_REFHOLD(ire1);
21880 						break;
21881 					}
21882 					IRB_REFRELE(irb);
21883 
21884 					if (ire1 != NULL) {
21885 						next_mp = copyb(mp);
21886 						if ((next_mp == NULL) ||
21887 						    ((mp->b_cont != NULL) &&
21888 						    ((next_mp->b_cont =
21889 						    dupmsg(mp->b_cont))
21890 						    == NULL))) {
21891 							freemsg(next_mp);
21892 							next_mp = NULL;
21893 							ire_refrele(ire1);
21894 							ire1 = NULL;
21895 						}
21896 					}
21897 
21898 					/*
21899 					 * Last multiroute ire; don't loop
21900 					 * anymore. The emission is over
21901 					 * and next_mp is NULL.
21902 					 */
21903 					if (ire1 == NULL) {
21904 						multirt_send = B_FALSE;
21905 					}
21906 				}
21907 
21908 				ASSERT(ipsec_len == 0);
21909 				mp->b_prev =
21910 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
21911 				DTRACE_PROBE2(ip__xmit__2,
21912 				    mblk_t *, mp, ire_t *, ire);
21913 				pktxmit_state = ip_xmit_v4(mp, ire,
21914 				    NULL, B_TRUE);
21915 				if ((pktxmit_state == SEND_FAILED) ||
21916 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21917 					if (next_mp) {
21918 						freemsg(next_mp);
21919 						ire_refrele(ire1);
21920 					}
21921 					ire_refrele(ire);
21922 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21923 					    "ip_wput_ire_end: q %p (%S)",
21924 					    q, "discard MDATA");
21925 					if (conn_outgoing_ill != NULL)
21926 						ill_refrele(conn_outgoing_ill);
21927 					return;
21928 				}
21929 
21930 				if (multirt_send) {
21931 					/*
21932 					 * We are in a multiple send case,
21933 					 * need to re-enter the sending loop
21934 					 * using the next ire.
21935 					 */
21936 					ire_refrele(ire);
21937 					ire = ire1;
21938 					stq = ire->ire_stq;
21939 					mp = next_mp;
21940 					next_mp = NULL;
21941 					ipha = (ipha_t *)mp->b_rptr;
21942 					ill_index = Q_TO_INDEX(stq);
21943 				}
21944 			} while (multirt_send);
21945 
21946 			if (!next_mp) {
21947 				/*
21948 				 * Last copy going out (the ultra-common
21949 				 * case).  Note that we intentionally replicate
21950 				 * the putnext rather than calling it before
21951 				 * the next_mp check in hopes of a little
21952 				 * tail-call action out of the compiler.
21953 				 */
21954 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21955 				    "ip_wput_ire_end: q %p (%S)",
21956 				    q, "last copy out(1)");
21957 				ire_refrele(ire);
21958 				if (conn_outgoing_ill != NULL)
21959 					ill_refrele(conn_outgoing_ill);
21960 				return;
21961 			}
21962 			/* More copies going out below. */
21963 		} else {
21964 			int offset;
21965 		    fragmentit:
21966 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21967 			/*
21968 			 * If this would generate a icmp_frag_needed message,
21969 			 * we need to handle it before we do the IPSEC
21970 			 * processing. Otherwise, we need to strip the IPSEC
21971 			 * headers before we send up the message to the ULPs
21972 			 * which becomes messy and difficult.
21973 			 */
21974 			if (ipsec_len != 0) {
21975 				if ((max_frag < (unsigned int)(LENGTH +
21976 				    ipsec_len)) && (offset & IPH_DF)) {
21977 
21978 					BUMP_MIB(&ip_mib, ipFragFails);
21979 					ipha->ipha_hdr_checksum = 0;
21980 					ipha->ipha_hdr_checksum =
21981 					    (uint16_t)ip_csum_hdr(ipha);
21982 					icmp_frag_needed(ire->ire_stq, first_mp,
21983 					    max_frag);
21984 					if (!next_mp) {
21985 						ire_refrele(ire);
21986 						if (conn_outgoing_ill != NULL) {
21987 							ill_refrele(
21988 							    conn_outgoing_ill);
21989 						}
21990 						return;
21991 					}
21992 				} else {
21993 					/*
21994 					 * This won't cause a icmp_frag_needed
21995 					 * message. to be gnerated. Send it on
21996 					 * the wire. Note that this could still
21997 					 * cause fragmentation and all we
21998 					 * do is the generation of the message
21999 					 * to the ULP if needed before IPSEC.
22000 					 */
22001 					if (!next_mp) {
22002 						ipsec_out_process(q, first_mp,
22003 						    ire, ill_index);
22004 						TRACE_2(TR_FAC_IP,
22005 						    TR_IP_WPUT_IRE_END,
22006 						    "ip_wput_ire_end: q %p "
22007 						    "(%S)", q,
22008 						    "last ipsec_out_process");
22009 						ire_refrele(ire);
22010 						if (conn_outgoing_ill != NULL) {
22011 							ill_refrele(
22012 							    conn_outgoing_ill);
22013 						}
22014 						return;
22015 					}
22016 					ipsec_out_process(q, first_mp,
22017 					    ire, ill_index);
22018 				}
22019 			} else {
22020 				/*
22021 				 * Initiate IPPF processing. For
22022 				 * fragmentable packets we finish
22023 				 * all QOS packet processing before
22024 				 * calling:
22025 				 * ip_wput_ire_fragmentit->ip_wput_frag
22026 				 */
22027 
22028 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22029 					ip_process(IPP_LOCAL_OUT, &mp,
22030 					    ill_index);
22031 					if (mp == NULL) {
22032 						BUMP_MIB(&ip_mib,
22033 						    ipOutDiscards);
22034 						if (next_mp != NULL) {
22035 							freemsg(next_mp);
22036 							ire_refrele(ire1);
22037 						}
22038 						ire_refrele(ire);
22039 						TRACE_2(TR_FAC_IP,
22040 						    TR_IP_WPUT_IRE_END,
22041 						    "ip_wput_ire: q %p (%S)",
22042 						    q, "discard MDATA");
22043 						if (conn_outgoing_ill != NULL) {
22044 							ill_refrele(
22045 							    conn_outgoing_ill);
22046 						}
22047 						return;
22048 					}
22049 				}
22050 				if (!next_mp) {
22051 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22052 					    "ip_wput_ire_end: q %p (%S)",
22053 					    q, "last fragmentation");
22054 					ip_wput_ire_fragmentit(mp, ire);
22055 					ire_refrele(ire);
22056 					if (conn_outgoing_ill != NULL)
22057 						ill_refrele(conn_outgoing_ill);
22058 					return;
22059 				}
22060 				ip_wput_ire_fragmentit(mp, ire);
22061 			}
22062 		}
22063 	} else {
22064 	    nullstq:
22065 		/* A NULL stq means the destination address is local. */
22066 		UPDATE_OB_PKT_COUNT(ire);
22067 		ire->ire_last_used_time = lbolt;
22068 		ASSERT(ire->ire_ipif != NULL);
22069 		if (!next_mp) {
22070 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22071 			    "ip_wput_ire_end: q %p (%S)",
22072 			    q, "local address");
22073 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22074 			    first_mp, ire, 0, ire->ire_zoneid);
22075 			ire_refrele(ire);
22076 			if (conn_outgoing_ill != NULL)
22077 				ill_refrele(conn_outgoing_ill);
22078 			return;
22079 		}
22080 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22081 		    ire, 0, ire->ire_zoneid);
22082 	}
22083 next:
22084 	/*
22085 	 * More copies going out to additional interfaces.
22086 	 * ire1 has already been held. We don't need the
22087 	 * "ire" anymore.
22088 	 */
22089 	ire_refrele(ire);
22090 	ire = ire1;
22091 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22092 	mp = next_mp;
22093 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22094 	ill = ire_to_ill(ire);
22095 	first_mp = mp;
22096 	if (ipsec_len != 0) {
22097 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22098 		mp = mp->b_cont;
22099 	}
22100 	dst = ire->ire_addr;
22101 	ipha = (ipha_t *)mp->b_rptr;
22102 	/*
22103 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22104 	 * Restore ipha_ident "no checksum" flag.
22105 	 */
22106 	src = orig_src;
22107 	ipha->ipha_ident = ip_hdr_included;
22108 	goto another;
22109 
22110 #undef	rptr
22111 #undef	Q_TO_INDEX
22112 }
22113 
22114 /*
22115  * Routine to allocate a message that is used to notify the ULP about MDT.
22116  * The caller may provide a pointer to the link-layer MDT capabilities,
22117  * or NULL if MDT is to be disabled on the stream.
22118  */
22119 mblk_t *
22120 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22121 {
22122 	mblk_t *mp;
22123 	ip_mdt_info_t *mdti;
22124 	ill_mdt_capab_t *idst;
22125 
22126 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22127 		DB_TYPE(mp) = M_CTL;
22128 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22129 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22130 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22131 		idst = &(mdti->mdt_capab);
22132 
22133 		/*
22134 		 * If the caller provides us with the capability, copy
22135 		 * it over into our notification message; otherwise
22136 		 * we zero out the capability portion.
22137 		 */
22138 		if (isrc != NULL)
22139 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22140 		else
22141 			bzero((caddr_t)idst, sizeof (*idst));
22142 	}
22143 	return (mp);
22144 }
22145 
22146 /*
22147  * Routine which determines whether MDT can be enabled on the destination
22148  * IRE and IPC combination, and if so, allocates and returns the MDT
22149  * notification mblk that may be used by ULP.  We also check if we need to
22150  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22151  * MDT usage in the past have been lifted.  This gets called during IP
22152  * and ULP binding.
22153  */
22154 mblk_t *
22155 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22156     ill_mdt_capab_t *mdt_cap)
22157 {
22158 	mblk_t *mp;
22159 	boolean_t rc = B_FALSE;
22160 
22161 	ASSERT(dst_ire != NULL);
22162 	ASSERT(connp != NULL);
22163 	ASSERT(mdt_cap != NULL);
22164 
22165 	/*
22166 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22167 	 * Multidata, which is handled in tcp_multisend().  This
22168 	 * is the reason why we do all these checks here, to ensure
22169 	 * that we don't enable Multidata for the cases which we
22170 	 * can't handle at the moment.
22171 	 */
22172 	do {
22173 		/* Only do TCP at the moment */
22174 		if (connp->conn_ulp != IPPROTO_TCP)
22175 			break;
22176 
22177 		/*
22178 		 * IPSEC outbound policy present?  Note that we get here
22179 		 * after calling ipsec_conn_cache_policy() where the global
22180 		 * policy checking is performed.  conn_latch will be
22181 		 * non-NULL as long as there's a policy defined,
22182 		 * i.e. conn_out_enforce_policy may be NULL in such case
22183 		 * when the connection is non-secure, and hence we check
22184 		 * further if the latch refers to an outbound policy.
22185 		 */
22186 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22187 			break;
22188 
22189 		/* CGTP (multiroute) is enabled? */
22190 		if (dst_ire->ire_flags & RTF_MULTIRT)
22191 			break;
22192 
22193 		/* Outbound IPQoS enabled? */
22194 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22195 			/*
22196 			 * In this case, we disable MDT for this and all
22197 			 * future connections going over the interface.
22198 			 */
22199 			mdt_cap->ill_mdt_on = 0;
22200 			break;
22201 		}
22202 
22203 		/* socket option(s) present? */
22204 		if (!CONN_IS_MD_FASTPATH(connp))
22205 			break;
22206 
22207 		rc = B_TRUE;
22208 	/* CONSTCOND */
22209 	} while (0);
22210 
22211 	/* Remember the result */
22212 	connp->conn_mdt_ok = rc;
22213 
22214 	if (!rc)
22215 		return (NULL);
22216 	else if (!mdt_cap->ill_mdt_on) {
22217 		/*
22218 		 * If MDT has been previously turned off in the past, and we
22219 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22220 		 * then enable it for this interface.
22221 		 */
22222 		mdt_cap->ill_mdt_on = 1;
22223 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22224 		    "interface %s\n", ill_name));
22225 	}
22226 
22227 	/* Allocate the MDT info mblk */
22228 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22229 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22230 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22231 		return (NULL);
22232 	}
22233 	return (mp);
22234 }
22235 
22236 /*
22237  * Create destination address attribute, and fill it with the physical
22238  * destination address and SAP taken from the template DL_UNITDATA_REQ
22239  * message block.
22240  */
22241 boolean_t
22242 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22243 {
22244 	dl_unitdata_req_t *dlurp;
22245 	pattr_t *pa;
22246 	pattrinfo_t pa_info;
22247 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22248 	uint_t das_len, das_off;
22249 
22250 	ASSERT(dlmp != NULL);
22251 
22252 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22253 	das_len = dlurp->dl_dest_addr_length;
22254 	das_off = dlurp->dl_dest_addr_offset;
22255 
22256 	pa_info.type = PATTR_DSTADDRSAP;
22257 	pa_info.len = sizeof (**das) + das_len - 1;
22258 
22259 	/* create and associate the attribute */
22260 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22261 	if (pa != NULL) {
22262 		ASSERT(*das != NULL);
22263 		(*das)->addr_is_group = 0;
22264 		(*das)->addr_len = (uint8_t)das_len;
22265 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22266 	}
22267 
22268 	return (pa != NULL);
22269 }
22270 
22271 /*
22272  * Create hardware checksum attribute and fill it with the values passed.
22273  */
22274 boolean_t
22275 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22276     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22277 {
22278 	pattr_t *pa;
22279 	pattrinfo_t pa_info;
22280 
22281 	ASSERT(mmd != NULL);
22282 
22283 	pa_info.type = PATTR_HCKSUM;
22284 	pa_info.len = sizeof (pattr_hcksum_t);
22285 
22286 	/* create and associate the attribute */
22287 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22288 	if (pa != NULL) {
22289 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22290 
22291 		hck->hcksum_start_offset = start_offset;
22292 		hck->hcksum_stuff_offset = stuff_offset;
22293 		hck->hcksum_end_offset = end_offset;
22294 		hck->hcksum_flags = flags;
22295 	}
22296 	return (pa != NULL);
22297 }
22298 
22299 /*
22300  * Create zerocopy attribute and fill it with the specified flags
22301  */
22302 boolean_t
22303 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22304 {
22305 	pattr_t *pa;
22306 	pattrinfo_t pa_info;
22307 
22308 	ASSERT(mmd != NULL);
22309 	pa_info.type = PATTR_ZCOPY;
22310 	pa_info.len = sizeof (pattr_zcopy_t);
22311 
22312 	/* create and associate the attribute */
22313 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22314 	if (pa != NULL) {
22315 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22316 
22317 		zcopy->zcopy_flags = flags;
22318 	}
22319 	return (pa != NULL);
22320 }
22321 
22322 /*
22323  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22324  * block chain. We could rewrite to handle arbitrary message block chains but
22325  * that would make the code complicated and slow. Right now there three
22326  * restrictions:
22327  *
22328  *   1. The first message block must contain the complete IP header and
22329  *	at least 1 byte of payload data.
22330  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22331  *	so that we can use a single Multidata message.
22332  *   3. No frag must be distributed over two or more message blocks so
22333  *	that we don't need more than two packet descriptors per frag.
22334  *
22335  * The above restrictions allow us to support userland applications (which
22336  * will send down a single message block) and NFS over UDP (which will
22337  * send down a chain of at most three message blocks).
22338  *
22339  * We also don't use MDT for payloads with less than or equal to
22340  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22341  */
22342 boolean_t
22343 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22344 {
22345 	int	blocks;
22346 	ssize_t	total, missing, size;
22347 
22348 	ASSERT(mp != NULL);
22349 	ASSERT(hdr_len > 0);
22350 
22351 	size = MBLKL(mp) - hdr_len;
22352 	if (size <= 0)
22353 		return (B_FALSE);
22354 
22355 	/* The first mblk contains the header and some payload. */
22356 	blocks = 1;
22357 	total = size;
22358 	size %= len;
22359 	missing = (size == 0) ? 0 : (len - size);
22360 	mp = mp->b_cont;
22361 
22362 	while (mp != NULL) {
22363 		/*
22364 		 * Give up if we encounter a zero length message block.
22365 		 * In practice, this should rarely happen and therefore
22366 		 * not worth the trouble of freeing and re-linking the
22367 		 * mblk from the chain to handle such case.
22368 		 */
22369 		if ((size = MBLKL(mp)) == 0)
22370 			return (B_FALSE);
22371 
22372 		/* Too many payload buffers for a single Multidata message? */
22373 		if (++blocks > MULTIDATA_MAX_PBUFS)
22374 			return (B_FALSE);
22375 
22376 		total += size;
22377 		/* Is a frag distributed over two or more message blocks? */
22378 		if (missing > size)
22379 			return (B_FALSE);
22380 		size -= missing;
22381 
22382 		size %= len;
22383 		missing = (size == 0) ? 0 : (len - size);
22384 
22385 		mp = mp->b_cont;
22386 	}
22387 
22388 	return (total > ip_wput_frag_mdt_min);
22389 }
22390 
22391 /*
22392  * Outbound IPv4 fragmentation routine using MDT.
22393  */
22394 static void
22395 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22396     uint32_t frag_flag, int offset)
22397 {
22398 	ipha_t		*ipha_orig;
22399 	int		i1, ip_data_end;
22400 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22401 	mblk_t		*hdr_mp, *md_mp = NULL;
22402 	unsigned char	*hdr_ptr, *pld_ptr;
22403 	multidata_t	*mmd;
22404 	ip_pdescinfo_t	pdi;
22405 
22406 	ASSERT(DB_TYPE(mp) == M_DATA);
22407 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22408 
22409 	ipha_orig = (ipha_t *)mp->b_rptr;
22410 	mp->b_rptr += sizeof (ipha_t);
22411 
22412 	/* Calculate how many packets we will send out */
22413 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22414 	pkts = (i1 + len - 1) / len;
22415 	ASSERT(pkts > 1);
22416 
22417 	/* Allocate a message block which will hold all the IP Headers. */
22418 	wroff = ip_wroff_extra;
22419 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22420 
22421 	i1 = pkts * hdr_chunk_len;
22422 	/*
22423 	 * Create the header buffer, Multidata and destination address
22424 	 * and SAP attribute that should be associated with it.
22425 	 */
22426 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22427 	    ((hdr_mp->b_wptr += i1),
22428 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22429 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22430 		freemsg(mp);
22431 		if (md_mp == NULL) {
22432 			freemsg(hdr_mp);
22433 		} else {
22434 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22435 			freemsg(md_mp);
22436 		}
22437 		IP_STAT(ip_frag_mdt_allocfail);
22438 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22439 		return;
22440 	}
22441 	IP_STAT(ip_frag_mdt_allocd);
22442 
22443 	/*
22444 	 * Add a payload buffer to the Multidata; this operation must not
22445 	 * fail, or otherwise our logic in this routine is broken.  There
22446 	 * is no memory allocation done by the routine, so any returned
22447 	 * failure simply tells us that we've done something wrong.
22448 	 *
22449 	 * A failure tells us that either we're adding the same payload
22450 	 * buffer more than once, or we're trying to add more buffers than
22451 	 * allowed.  None of the above cases should happen, and we panic
22452 	 * because either there's horrible heap corruption, and/or
22453 	 * programming mistake.
22454 	 */
22455 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22456 		goto pbuf_panic;
22457 
22458 	hdr_ptr = hdr_mp->b_rptr;
22459 	pld_ptr = mp->b_rptr;
22460 
22461 	/* Establish the ending byte offset, based on the starting offset. */
22462 	offset <<= 3;
22463 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22464 	    IP_SIMPLE_HDR_LENGTH;
22465 
22466 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22467 
22468 	while (pld_ptr < mp->b_wptr) {
22469 		ipha_t		*ipha;
22470 		uint16_t	offset_and_flags;
22471 		uint16_t	ip_len;
22472 		int		error;
22473 
22474 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22475 		ipha = (ipha_t *)(hdr_ptr + wroff);
22476 		ASSERT(OK_32PTR(ipha));
22477 		*ipha = *ipha_orig;
22478 
22479 		if (ip_data_end - offset > len) {
22480 			offset_and_flags = IPH_MF;
22481 		} else {
22482 			/*
22483 			 * Last frag. Set len to the length of this last piece.
22484 			 */
22485 			len = ip_data_end - offset;
22486 			/* A frag of a frag might have IPH_MF non-zero */
22487 			offset_and_flags =
22488 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22489 			    IPH_MF;
22490 		}
22491 		offset_and_flags |= (uint16_t)(offset >> 3);
22492 		offset_and_flags |= (uint16_t)frag_flag;
22493 		/* Store the offset and flags in the IP header. */
22494 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22495 
22496 		/* Store the length in the IP header. */
22497 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22498 		ipha->ipha_length = htons(ip_len);
22499 
22500 		/*
22501 		 * Set the IP header checksum.  Note that mp is just
22502 		 * the header, so this is easy to pass to ip_csum.
22503 		 */
22504 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22505 
22506 		/*
22507 		 * Record offset and size of header and data of the next packet
22508 		 * in the multidata message.
22509 		 */
22510 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22511 		PDESC_PLD_INIT(&pdi);
22512 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22513 		ASSERT(i1 > 0);
22514 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22515 		if (i1 == len) {
22516 			pld_ptr += len;
22517 		} else {
22518 			i1 = len - i1;
22519 			mp = mp->b_cont;
22520 			ASSERT(mp != NULL);
22521 			ASSERT(MBLKL(mp) >= i1);
22522 			/*
22523 			 * Attach the next payload message block to the
22524 			 * multidata message.
22525 			 */
22526 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22527 				goto pbuf_panic;
22528 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22529 			pld_ptr = mp->b_rptr + i1;
22530 		}
22531 
22532 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22533 		    KM_NOSLEEP)) == NULL) {
22534 			/*
22535 			 * Any failure other than ENOMEM indicates that we
22536 			 * have passed in invalid pdesc info or parameters
22537 			 * to mmd_addpdesc, which must not happen.
22538 			 *
22539 			 * EINVAL is a result of failure on boundary checks
22540 			 * against the pdesc info contents.  It should not
22541 			 * happen, and we panic because either there's
22542 			 * horrible heap corruption, and/or programming
22543 			 * mistake.
22544 			 */
22545 			if (error != ENOMEM) {
22546 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22547 				    "pdesc logic error detected for "
22548 				    "mmd %p pinfo %p (%d)\n",
22549 				    (void *)mmd, (void *)&pdi, error);
22550 				/* NOTREACHED */
22551 			}
22552 			IP_STAT(ip_frag_mdt_addpdescfail);
22553 			/* Free unattached payload message blocks as well */
22554 			md_mp->b_cont = mp->b_cont;
22555 			goto free_mmd;
22556 		}
22557 
22558 		/* Advance fragment offset. */
22559 		offset += len;
22560 
22561 		/* Advance to location for next header in the buffer. */
22562 		hdr_ptr += hdr_chunk_len;
22563 
22564 		/* Did we reach the next payload message block? */
22565 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22566 			mp = mp->b_cont;
22567 			/*
22568 			 * Attach the next message block with payload
22569 			 * data to the multidata message.
22570 			 */
22571 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22572 				goto pbuf_panic;
22573 			pld_ptr = mp->b_rptr;
22574 		}
22575 	}
22576 
22577 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22578 	ASSERT(mp->b_wptr == pld_ptr);
22579 
22580 	/* Update IP statistics */
22581 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22582 	BUMP_MIB(&ip_mib, ipFragOKs);
22583 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22584 
22585 	if (pkt_type == OB_PKT) {
22586 		ire->ire_ob_pkt_count += pkts;
22587 		if (ire->ire_ipif != NULL)
22588 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22589 	} else {
22590 		/*
22591 		 * The type is IB_PKT in the forwarding path and in
22592 		 * the mobile IP case when the packet is being reverse-
22593 		 * tunneled to the home agent.
22594 		 */
22595 		ire->ire_ib_pkt_count += pkts;
22596 		ASSERT(!IRE_IS_LOCAL(ire));
22597 		if (ire->ire_type & IRE_BROADCAST)
22598 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22599 		else
22600 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22601 	}
22602 	ire->ire_last_used_time = lbolt;
22603 	/* Send it down */
22604 	putnext(ire->ire_stq, md_mp);
22605 	return;
22606 
22607 pbuf_panic:
22608 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22609 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22610 	    pbuf_idx);
22611 	/* NOTREACHED */
22612 }
22613 
22614 /*
22615  * Outbound IP fragmentation routine.
22616  *
22617  * NOTE : This routine does not ire_refrele the ire that is passed in
22618  * as the argument.
22619  */
22620 static void
22621 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22622     uint32_t frag_flag)
22623 {
22624 	int		i1;
22625 	mblk_t		*ll_hdr_mp;
22626 	int 		ll_hdr_len;
22627 	int		hdr_len;
22628 	mblk_t		*hdr_mp;
22629 	ipha_t		*ipha;
22630 	int		ip_data_end;
22631 	int		len;
22632 	mblk_t		*mp = mp_orig;
22633 	int		offset;
22634 	queue_t		*q;
22635 	uint32_t	v_hlen_tos_len;
22636 	mblk_t		*first_mp;
22637 	boolean_t	mctl_present;
22638 	ill_t		*ill;
22639 	mblk_t		*xmit_mp;
22640 	mblk_t		*carve_mp;
22641 	ire_t		*ire1 = NULL;
22642 	ire_t		*save_ire = NULL;
22643 	mblk_t  	*next_mp = NULL;
22644 	boolean_t	last_frag = B_FALSE;
22645 	boolean_t	multirt_send = B_FALSE;
22646 	ire_t		*first_ire = NULL;
22647 	irb_t		*irb = NULL;
22648 
22649 	/*
22650 	 * IPSEC does not allow hw accelerated packets to be fragmented
22651 	 * This check is made in ip_wput_ipsec_out prior to coming here
22652 	 * via ip_wput_ire_fragmentit.
22653 	 *
22654 	 * If at this point we have an ire whose ARP request has not
22655 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
22656 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
22657 	 * This packet and all fragmentable packets for this ire will
22658 	 * continue to get dropped while ire_nce->nce_state remains in
22659 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
22660 	 * ND_REACHABLE, all subsquent large packets for this ire will
22661 	 * get fragemented and sent out by this function.
22662 	 */
22663 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
22664 		/* If nce_state is ND_INITIAL, trigger ARP query */
22665 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
22666 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
22667 		    " -  dropping packet\n"));
22668 		BUMP_MIB(&ip_mib, ipFragFails);
22669 		freemsg(mp);
22670 		return;
22671 	}
22672 
22673 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22674 	    "ip_wput_frag_start:");
22675 
22676 	if (mp->b_datap->db_type == M_CTL) {
22677 		first_mp = mp;
22678 		mp_orig = mp = mp->b_cont;
22679 		mctl_present = B_TRUE;
22680 	} else {
22681 		first_mp = mp;
22682 		mctl_present = B_FALSE;
22683 	}
22684 
22685 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22686 	ipha = (ipha_t *)mp->b_rptr;
22687 
22688 	/*
22689 	 * If the Don't Fragment flag is on, generate an ICMP destination
22690 	 * unreachable, fragmentation needed.
22691 	 */
22692 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22693 	if (offset & IPH_DF) {
22694 		BUMP_MIB(&ip_mib, ipFragFails);
22695 		/*
22696 		 * Need to compute hdr checksum if called from ip_wput_ire.
22697 		 * Note that ip_rput_forward verifies the checksum before
22698 		 * calling this routine so in that case this is a noop.
22699 		 */
22700 		ipha->ipha_hdr_checksum = 0;
22701 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22702 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22703 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22704 		    "ip_wput_frag_end:(%S)",
22705 		    "don't fragment");
22706 		return;
22707 	}
22708 	if (mctl_present)
22709 		freeb(first_mp);
22710 	/*
22711 	 * Establish the starting offset.  May not be zero if we are fragging
22712 	 * a fragment that is being forwarded.
22713 	 */
22714 	offset = offset & IPH_OFFSET;
22715 
22716 	/* TODO why is this test needed? */
22717 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22718 	if (((max_frag - LENGTH) & ~7) < 8) {
22719 		/* TODO: notify ulp somehow */
22720 		BUMP_MIB(&ip_mib, ipFragFails);
22721 		freemsg(mp);
22722 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22723 		    "ip_wput_frag_end:(%S)",
22724 		    "len < 8");
22725 		return;
22726 	}
22727 
22728 	hdr_len = (V_HLEN & 0xF) << 2;
22729 
22730 	ipha->ipha_hdr_checksum = 0;
22731 
22732 	/*
22733 	 * Establish the number of bytes maximum per frag, after putting
22734 	 * in the header.
22735 	 */
22736 	len = (max_frag - hdr_len) & ~7;
22737 
22738 	/* Check if we can use MDT to send out the frags. */
22739 	ASSERT(!IRE_IS_LOCAL(ire));
22740 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22741 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22742 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22743 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22744 		ASSERT(ill->ill_mdt_capab != NULL);
22745 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22746 			/*
22747 			 * If MDT has been previously turned off in the past,
22748 			 * and we currently can do MDT (due to IPQoS policy
22749 			 * removal, etc.) then enable it for this interface.
22750 			 */
22751 			ill->ill_mdt_capab->ill_mdt_on = 1;
22752 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22753 			    ill->ill_name));
22754 		}
22755 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22756 		    offset);
22757 		return;
22758 	}
22759 
22760 	/* Get a copy of the header for the trailing frags */
22761 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22762 	if (!hdr_mp) {
22763 		BUMP_MIB(&ip_mib, ipOutDiscards);
22764 		freemsg(mp);
22765 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22766 		    "ip_wput_frag_end:(%S)",
22767 		    "couldn't copy hdr");
22768 		return;
22769 	}
22770 	if (DB_CRED(mp) != NULL)
22771 		mblk_setcred(hdr_mp, DB_CRED(mp));
22772 
22773 	/* Store the starting offset, with the MoreFrags flag. */
22774 	i1 = offset | IPH_MF | frag_flag;
22775 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22776 
22777 	/* Establish the ending byte offset, based on the starting offset. */
22778 	offset <<= 3;
22779 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22780 
22781 	/* Store the length of the first fragment in the IP header. */
22782 	i1 = len + hdr_len;
22783 	ASSERT(i1 <= IP_MAXPACKET);
22784 	ipha->ipha_length = htons((uint16_t)i1);
22785 
22786 	/*
22787 	 * Compute the IP header checksum for the first frag.  We have to
22788 	 * watch out that we stop at the end of the header.
22789 	 */
22790 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22791 
22792 	/*
22793 	 * Now carve off the first frag.  Note that this will include the
22794 	 * original IP header.
22795 	 */
22796 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22797 		BUMP_MIB(&ip_mib, ipOutDiscards);
22798 		freeb(hdr_mp);
22799 		freemsg(mp_orig);
22800 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22801 		    "ip_wput_frag_end:(%S)",
22802 		    "couldn't carve first");
22803 		return;
22804 	}
22805 
22806 	/*
22807 	 * Multirouting case. Each fragment is replicated
22808 	 * via all non-condemned RTF_MULTIRT routes
22809 	 * currently resolved.
22810 	 * We ensure that first_ire is the first RTF_MULTIRT
22811 	 * ire in the bucket.
22812 	 */
22813 	if (ire->ire_flags & RTF_MULTIRT) {
22814 		irb = ire->ire_bucket;
22815 		ASSERT(irb != NULL);
22816 
22817 		multirt_send = B_TRUE;
22818 
22819 		/* Make sure we do not omit any multiroute ire. */
22820 		IRB_REFHOLD(irb);
22821 		for (first_ire = irb->irb_ire;
22822 		    first_ire != NULL;
22823 		    first_ire = first_ire->ire_next) {
22824 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22825 			    (first_ire->ire_addr == ire->ire_addr) &&
22826 			    !(first_ire->ire_marks &
22827 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22828 				break;
22829 		}
22830 
22831 		if (first_ire != NULL) {
22832 			if (first_ire != ire) {
22833 				IRE_REFHOLD(first_ire);
22834 				/*
22835 				 * Do not release the ire passed in
22836 				 * as the argument.
22837 				 */
22838 				ire = first_ire;
22839 			} else {
22840 				first_ire = NULL;
22841 			}
22842 		}
22843 		IRB_REFRELE(irb);
22844 
22845 		/*
22846 		 * Save the first ire; we will need to restore it
22847 		 * for the trailing frags.
22848 		 * We REFHOLD save_ire, as each iterated ire will be
22849 		 * REFRELEd.
22850 		 */
22851 		save_ire = ire;
22852 		IRE_REFHOLD(save_ire);
22853 	}
22854 
22855 	/*
22856 	 * First fragment emission loop.
22857 	 * In most cases, the emission loop below is entered only
22858 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22859 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22860 	 * bucket, and send the fragment through all crossed
22861 	 * RTF_MULTIRT routes.
22862 	 */
22863 	do {
22864 		if (ire->ire_flags & RTF_MULTIRT) {
22865 			/*
22866 			 * We are in a multiple send case, need to get
22867 			 * the next ire and make a copy of the packet.
22868 			 * ire1 holds here the next ire to process in the
22869 			 * bucket. If multirouting is expected,
22870 			 * any non-RTF_MULTIRT ire that has the
22871 			 * right destination address is ignored.
22872 			 *
22873 			 * We have to take into account the MTU of
22874 			 * each walked ire. max_frag is set by the
22875 			 * the caller and generally refers to
22876 			 * the primary ire entry. Here we ensure that
22877 			 * no route with a lower MTU will be used, as
22878 			 * fragments are carved once for all ires,
22879 			 * then replicated.
22880 			 */
22881 			ASSERT(irb != NULL);
22882 			IRB_REFHOLD(irb);
22883 			for (ire1 = ire->ire_next;
22884 			    ire1 != NULL;
22885 			    ire1 = ire1->ire_next) {
22886 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22887 					continue;
22888 				if (ire1->ire_addr != ire->ire_addr)
22889 					continue;
22890 				if (ire1->ire_marks &
22891 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22892 					continue;
22893 				/*
22894 				 * Ensure we do not exceed the MTU
22895 				 * of the next route.
22896 				 */
22897 				if (ire1->ire_max_frag < max_frag) {
22898 					ip_multirt_bad_mtu(ire1, max_frag);
22899 					continue;
22900 				}
22901 
22902 				/* Got one. */
22903 				IRE_REFHOLD(ire1);
22904 				break;
22905 			}
22906 			IRB_REFRELE(irb);
22907 
22908 			if (ire1 != NULL) {
22909 				next_mp = copyb(mp);
22910 				if ((next_mp == NULL) ||
22911 				    ((mp->b_cont != NULL) &&
22912 				    ((next_mp->b_cont =
22913 				    dupmsg(mp->b_cont)) == NULL))) {
22914 					freemsg(next_mp);
22915 					next_mp = NULL;
22916 					ire_refrele(ire1);
22917 					ire1 = NULL;
22918 				}
22919 			}
22920 
22921 			/* Last multiroute ire; don't loop anymore. */
22922 			if (ire1 == NULL) {
22923 				multirt_send = B_FALSE;
22924 			}
22925 		}
22926 
22927 		ll_hdr_len = 0;
22928 		LOCK_IRE_FP_MP(ire);
22929 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
22930 		if (ll_hdr_mp != NULL) {
22931 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22932 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22933 		} else {
22934 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
22935 		}
22936 
22937 		/* If there is a transmit header, get a copy for this frag. */
22938 		/*
22939 		 * TODO: should check db_ref before calling ip_carve_mp since
22940 		 * it might give us a dup.
22941 		 */
22942 		if (!ll_hdr_mp) {
22943 			/* No xmit header. */
22944 			xmit_mp = mp;
22945 
22946 		/* We have a link-layer header that can fit in our mblk. */
22947 		} else if (mp->b_datap->db_ref == 1 &&
22948 		    ll_hdr_len != 0 &&
22949 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22950 			/* M_DATA fastpath */
22951 			mp->b_rptr -= ll_hdr_len;
22952 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22953 			xmit_mp = mp;
22954 
22955 		/* Corner case if copyb has failed */
22956 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22957 			UNLOCK_IRE_FP_MP(ire);
22958 			BUMP_MIB(&ip_mib, ipOutDiscards);
22959 			freeb(hdr_mp);
22960 			freemsg(mp);
22961 			freemsg(mp_orig);
22962 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22963 			    "ip_wput_frag_end:(%S)",
22964 			    "discard");
22965 
22966 			if (multirt_send) {
22967 				ASSERT(ire1);
22968 				ASSERT(next_mp);
22969 
22970 				freemsg(next_mp);
22971 				ire_refrele(ire1);
22972 			}
22973 			if (save_ire != NULL)
22974 				IRE_REFRELE(save_ire);
22975 
22976 			if (first_ire != NULL)
22977 				ire_refrele(first_ire);
22978 			return;
22979 
22980 		/*
22981 		 * Case of res_mp OR the fastpath mp can't fit
22982 		 * in the mblk
22983 		 */
22984 		} else {
22985 			xmit_mp->b_cont = mp;
22986 			if (DB_CRED(mp) != NULL)
22987 				mblk_setcred(xmit_mp, DB_CRED(mp));
22988 			/*
22989 			 * Get priority marking, if any.
22990 			 * We propagate the CoS marking from the
22991 			 * original packet that went to QoS processing
22992 			 * in ip_wput_ire to the newly carved mp.
22993 			 */
22994 			if (DB_TYPE(xmit_mp) == M_DATA)
22995 				xmit_mp->b_band = mp->b_band;
22996 		}
22997 		UNLOCK_IRE_FP_MP(ire);
22998 		q = ire->ire_stq;
22999 		BUMP_MIB(&ip_mib, ipFragCreates);
23000 		putnext(q, xmit_mp);
23001 		if (pkt_type != OB_PKT) {
23002 			/*
23003 			 * Update the packet count of trailing
23004 			 * RTF_MULTIRT ires.
23005 			 */
23006 			UPDATE_OB_PKT_COUNT(ire);
23007 		}
23008 
23009 		if (multirt_send) {
23010 			/*
23011 			 * We are in a multiple send case; look for
23012 			 * the next ire and re-enter the loop.
23013 			 */
23014 			ASSERT(ire1);
23015 			ASSERT(next_mp);
23016 			/* REFRELE the current ire before looping */
23017 			ire_refrele(ire);
23018 			ire = ire1;
23019 			ire1 = NULL;
23020 			mp = next_mp;
23021 			next_mp = NULL;
23022 		}
23023 	} while (multirt_send);
23024 
23025 	ASSERT(ire1 == NULL);
23026 
23027 	/* Restore the original ire; we need it for the trailing frags */
23028 	if (save_ire != NULL) {
23029 		/* REFRELE the last iterated ire */
23030 		ire_refrele(ire);
23031 		/* save_ire has been REFHOLDed */
23032 		ire = save_ire;
23033 		save_ire = NULL;
23034 		q = ire->ire_stq;
23035 	}
23036 
23037 	if (pkt_type == OB_PKT) {
23038 		UPDATE_OB_PKT_COUNT(ire);
23039 	} else {
23040 		UPDATE_IB_PKT_COUNT(ire);
23041 	}
23042 
23043 	/* Advance the offset to the second frag starting point. */
23044 	offset += len;
23045 	/*
23046 	 * Update hdr_len from the copied header - there might be less options
23047 	 * in the later fragments.
23048 	 */
23049 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23050 	/* Loop until done. */
23051 	for (;;) {
23052 		uint16_t	offset_and_flags;
23053 		uint16_t	ip_len;
23054 
23055 		if (ip_data_end - offset > len) {
23056 			/*
23057 			 * Carve off the appropriate amount from the original
23058 			 * datagram.
23059 			 */
23060 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23061 				mp = NULL;
23062 				break;
23063 			}
23064 			/*
23065 			 * More frags after this one.  Get another copy
23066 			 * of the header.
23067 			 */
23068 			if (carve_mp->b_datap->db_ref == 1 &&
23069 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23070 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23071 				/* Inline IP header */
23072 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23073 				    hdr_mp->b_rptr;
23074 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23075 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23076 				mp = carve_mp;
23077 			} else {
23078 				if (!(mp = copyb(hdr_mp))) {
23079 					freemsg(carve_mp);
23080 					break;
23081 				}
23082 				/* Get priority marking, if any. */
23083 				mp->b_band = carve_mp->b_band;
23084 				mp->b_cont = carve_mp;
23085 			}
23086 			ipha = (ipha_t *)mp->b_rptr;
23087 			offset_and_flags = IPH_MF;
23088 		} else {
23089 			/*
23090 			 * Last frag.  Consume the header. Set len to
23091 			 * the length of this last piece.
23092 			 */
23093 			len = ip_data_end - offset;
23094 
23095 			/*
23096 			 * Carve off the appropriate amount from the original
23097 			 * datagram.
23098 			 */
23099 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23100 				mp = NULL;
23101 				break;
23102 			}
23103 			if (carve_mp->b_datap->db_ref == 1 &&
23104 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23105 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23106 				/* Inline IP header */
23107 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23108 				    hdr_mp->b_rptr;
23109 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23110 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23111 				mp = carve_mp;
23112 				freeb(hdr_mp);
23113 				hdr_mp = mp;
23114 			} else {
23115 				mp = hdr_mp;
23116 				/* Get priority marking, if any. */
23117 				mp->b_band = carve_mp->b_band;
23118 				mp->b_cont = carve_mp;
23119 			}
23120 			ipha = (ipha_t *)mp->b_rptr;
23121 			/* A frag of a frag might have IPH_MF non-zero */
23122 			offset_and_flags =
23123 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23124 			    IPH_MF;
23125 		}
23126 		offset_and_flags |= (uint16_t)(offset >> 3);
23127 		offset_and_flags |= (uint16_t)frag_flag;
23128 		/* Store the offset and flags in the IP header. */
23129 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23130 
23131 		/* Store the length in the IP header. */
23132 		ip_len = (uint16_t)(len + hdr_len);
23133 		ipha->ipha_length = htons(ip_len);
23134 
23135 		/*
23136 		 * Set the IP header checksum.	Note that mp is just
23137 		 * the header, so this is easy to pass to ip_csum.
23138 		 */
23139 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23140 
23141 		/* Attach a transmit header, if any, and ship it. */
23142 		if (pkt_type == OB_PKT) {
23143 			UPDATE_OB_PKT_COUNT(ire);
23144 		} else {
23145 			UPDATE_IB_PKT_COUNT(ire);
23146 		}
23147 
23148 		if (ire->ire_flags & RTF_MULTIRT) {
23149 			irb = ire->ire_bucket;
23150 			ASSERT(irb != NULL);
23151 
23152 			multirt_send = B_TRUE;
23153 
23154 			/*
23155 			 * Save the original ire; we will need to restore it
23156 			 * for the tailing frags.
23157 			 */
23158 			save_ire = ire;
23159 			IRE_REFHOLD(save_ire);
23160 		}
23161 		/*
23162 		 * Emission loop for this fragment, similar
23163 		 * to what is done for the first fragment.
23164 		 */
23165 		do {
23166 			if (multirt_send) {
23167 				/*
23168 				 * We are in a multiple send case, need to get
23169 				 * the next ire and make a copy of the packet.
23170 				 */
23171 				ASSERT(irb != NULL);
23172 				IRB_REFHOLD(irb);
23173 				for (ire1 = ire->ire_next;
23174 				    ire1 != NULL;
23175 				    ire1 = ire1->ire_next) {
23176 					if (!(ire1->ire_flags & RTF_MULTIRT))
23177 						continue;
23178 					if (ire1->ire_addr != ire->ire_addr)
23179 						continue;
23180 					if (ire1->ire_marks &
23181 					    (IRE_MARK_CONDEMNED|
23182 						IRE_MARK_HIDDEN))
23183 						continue;
23184 					/*
23185 					 * Ensure we do not exceed the MTU
23186 					 * of the next route.
23187 					 */
23188 					if (ire1->ire_max_frag < max_frag) {
23189 						ip_multirt_bad_mtu(ire1,
23190 						    max_frag);
23191 						continue;
23192 					}
23193 
23194 					/* Got one. */
23195 					IRE_REFHOLD(ire1);
23196 					break;
23197 				}
23198 				IRB_REFRELE(irb);
23199 
23200 				if (ire1 != NULL) {
23201 					next_mp = copyb(mp);
23202 					if ((next_mp == NULL) ||
23203 					    ((mp->b_cont != NULL) &&
23204 					    ((next_mp->b_cont =
23205 					    dupmsg(mp->b_cont)) == NULL))) {
23206 						freemsg(next_mp);
23207 						next_mp = NULL;
23208 						ire_refrele(ire1);
23209 						ire1 = NULL;
23210 					}
23211 				}
23212 
23213 				/* Last multiroute ire; don't loop anymore. */
23214 				if (ire1 == NULL) {
23215 					multirt_send = B_FALSE;
23216 				}
23217 			}
23218 
23219 			/* Update transmit header */
23220 			ll_hdr_len = 0;
23221 			LOCK_IRE_FP_MP(ire);
23222 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23223 			if (ll_hdr_mp != NULL) {
23224 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23225 				ll_hdr_len = MBLKL(ll_hdr_mp);
23226 			} else {
23227 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23228 			}
23229 
23230 			if (!ll_hdr_mp) {
23231 				xmit_mp = mp;
23232 
23233 			/*
23234 			 * We have link-layer header that can fit in
23235 			 * our mblk.
23236 			 */
23237 			} else if (mp->b_datap->db_ref == 1 &&
23238 			    ll_hdr_len != 0 &&
23239 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23240 				/* M_DATA fastpath */
23241 				mp->b_rptr -= ll_hdr_len;
23242 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23243 				    ll_hdr_len);
23244 				xmit_mp = mp;
23245 
23246 			/*
23247 			 * Case of res_mp OR the fastpath mp can't fit
23248 			 * in the mblk
23249 			 */
23250 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23251 				xmit_mp->b_cont = mp;
23252 				if (DB_CRED(mp) != NULL)
23253 					mblk_setcred(xmit_mp, DB_CRED(mp));
23254 				/* Get priority marking, if any. */
23255 				if (DB_TYPE(xmit_mp) == M_DATA)
23256 					xmit_mp->b_band = mp->b_band;
23257 
23258 			/* Corner case if copyb failed */
23259 			} else {
23260 				/*
23261 				 * Exit both the replication and
23262 				 * fragmentation loops.
23263 				 */
23264 				UNLOCK_IRE_FP_MP(ire);
23265 				goto drop_pkt;
23266 			}
23267 			UNLOCK_IRE_FP_MP(ire);
23268 			BUMP_MIB(&ip_mib, ipFragCreates);
23269 			putnext(q, xmit_mp);
23270 
23271 			if (pkt_type != OB_PKT) {
23272 				/*
23273 				 * Update the packet count of trailing
23274 				 * RTF_MULTIRT ires.
23275 				 */
23276 				UPDATE_OB_PKT_COUNT(ire);
23277 			}
23278 
23279 			/* All done if we just consumed the hdr_mp. */
23280 			if (mp == hdr_mp) {
23281 				last_frag = B_TRUE;
23282 			}
23283 
23284 			if (multirt_send) {
23285 				/*
23286 				 * We are in a multiple send case; look for
23287 				 * the next ire and re-enter the loop.
23288 				 */
23289 				ASSERT(ire1);
23290 				ASSERT(next_mp);
23291 				/* REFRELE the current ire before looping */
23292 				ire_refrele(ire);
23293 				ire = ire1;
23294 				ire1 = NULL;
23295 				q = ire->ire_stq;
23296 				mp = next_mp;
23297 				next_mp = NULL;
23298 			}
23299 		} while (multirt_send);
23300 		/*
23301 		 * Restore the original ire; we need it for the
23302 		 * trailing frags
23303 		 */
23304 		if (save_ire != NULL) {
23305 			ASSERT(ire1 == NULL);
23306 			/* REFRELE the last iterated ire */
23307 			ire_refrele(ire);
23308 			/* save_ire has been REFHOLDed */
23309 			ire = save_ire;
23310 			q = ire->ire_stq;
23311 			save_ire = NULL;
23312 		}
23313 
23314 		if (last_frag) {
23315 			BUMP_MIB(&ip_mib, ipFragOKs);
23316 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23317 			    "ip_wput_frag_end:(%S)",
23318 			    "consumed hdr_mp");
23319 
23320 			if (first_ire != NULL)
23321 				ire_refrele(first_ire);
23322 			return;
23323 		}
23324 		/* Otherwise, advance and loop. */
23325 		offset += len;
23326 	}
23327 
23328 drop_pkt:
23329 	/* Clean up following allocation failure. */
23330 	BUMP_MIB(&ip_mib, ipOutDiscards);
23331 	freemsg(mp);
23332 	if (mp != hdr_mp)
23333 		freeb(hdr_mp);
23334 	if (mp != mp_orig)
23335 		freemsg(mp_orig);
23336 
23337 	if (save_ire != NULL)
23338 		IRE_REFRELE(save_ire);
23339 	if (first_ire != NULL)
23340 		ire_refrele(first_ire);
23341 
23342 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23343 	    "ip_wput_frag_end:(%S)",
23344 	    "end--alloc failure");
23345 }
23346 
23347 /*
23348  * Copy the header plus those options which have the copy bit set
23349  */
23350 static mblk_t *
23351 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23352 {
23353 	mblk_t	*mp;
23354 	uchar_t	*up;
23355 
23356 	/*
23357 	 * Quick check if we need to look for options without the copy bit
23358 	 * set
23359 	 */
23360 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23361 	if (!mp)
23362 		return (mp);
23363 	mp->b_rptr += ip_wroff_extra;
23364 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23365 		bcopy(rptr, mp->b_rptr, hdr_len);
23366 		mp->b_wptr += hdr_len + ip_wroff_extra;
23367 		return (mp);
23368 	}
23369 	up  = mp->b_rptr;
23370 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23371 	up += IP_SIMPLE_HDR_LENGTH;
23372 	rptr += IP_SIMPLE_HDR_LENGTH;
23373 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23374 	while (hdr_len > 0) {
23375 		uint32_t optval;
23376 		uint32_t optlen;
23377 
23378 		optval = *rptr;
23379 		if (optval == IPOPT_EOL)
23380 			break;
23381 		if (optval == IPOPT_NOP)
23382 			optlen = 1;
23383 		else
23384 			optlen = rptr[1];
23385 		if (optval & IPOPT_COPY) {
23386 			bcopy(rptr, up, optlen);
23387 			up += optlen;
23388 		}
23389 		rptr += optlen;
23390 		hdr_len -= optlen;
23391 	}
23392 	/*
23393 	 * Make sure that we drop an even number of words by filling
23394 	 * with EOL to the next word boundary.
23395 	 */
23396 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23397 	    hdr_len & 0x3; hdr_len++)
23398 		*up++ = IPOPT_EOL;
23399 	mp->b_wptr = up;
23400 	/* Update header length */
23401 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23402 	return (mp);
23403 }
23404 
23405 /*
23406  * Delivery to local recipients including fanout to multiple recipients.
23407  * Does not do checksumming of UDP/TCP.
23408  * Note: q should be the read side queue for either the ill or conn.
23409  * Note: rq should be the read side q for the lower (ill) stream.
23410  * We don't send packets to IPPF processing, thus the last argument
23411  * to all the fanout calls are B_FALSE.
23412  */
23413 void
23414 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23415     int fanout_flags, zoneid_t zoneid)
23416 {
23417 	uint32_t	protocol;
23418 	mblk_t		*first_mp;
23419 	boolean_t	mctl_present;
23420 	int		ire_type;
23421 #define	rptr	((uchar_t *)ipha)
23422 
23423 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23424 	    "ip_wput_local_start: q %p", q);
23425 
23426 	if (ire != NULL) {
23427 		ire_type = ire->ire_type;
23428 	} else {
23429 		/*
23430 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23431 		 * packet is not multicast, we can't tell the ire type.
23432 		 */
23433 		ASSERT(CLASSD(ipha->ipha_dst));
23434 		ire_type = IRE_BROADCAST;
23435 	}
23436 
23437 	first_mp = mp;
23438 	if (first_mp->b_datap->db_type == M_CTL) {
23439 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23440 		if (!io->ipsec_out_secure) {
23441 			/*
23442 			 * This ipsec_out_t was allocated in ip_wput
23443 			 * for multicast packets to store the ill_index.
23444 			 * As this is being delivered locally, we don't
23445 			 * need this anymore.
23446 			 */
23447 			mp = first_mp->b_cont;
23448 			freeb(first_mp);
23449 			first_mp = mp;
23450 			mctl_present = B_FALSE;
23451 		} else {
23452 			mctl_present = B_TRUE;
23453 			mp = first_mp->b_cont;
23454 			ASSERT(mp != NULL);
23455 			ipsec_out_to_in(first_mp);
23456 		}
23457 	} else {
23458 		mctl_present = B_FALSE;
23459 	}
23460 
23461 	loopback_packets++;
23462 
23463 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23464 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23465 	if (!IS_SIMPLE_IPH(ipha)) {
23466 		ip_wput_local_options(ipha);
23467 	}
23468 
23469 	protocol = ipha->ipha_protocol;
23470 	switch (protocol) {
23471 	case IPPROTO_ICMP: {
23472 		ire_t		*ire_zone;
23473 		ilm_t		*ilm;
23474 		mblk_t		*mp1;
23475 		zoneid_t	last_zoneid;
23476 
23477 		if (CLASSD(ipha->ipha_dst) &&
23478 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23479 			ASSERT(ire_type == IRE_BROADCAST);
23480 			/*
23481 			 * In the multicast case, applications may have joined
23482 			 * the group from different zones, so we need to deliver
23483 			 * the packet to each of them. Loop through the
23484 			 * multicast memberships structures (ilm) on the receive
23485 			 * ill and send a copy of the packet up each matching
23486 			 * one. However, we don't do this for multicasts sent on
23487 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23488 			 * they must stay in the sender's zone.
23489 			 *
23490 			 * ilm_add_v6() ensures that ilms in the same zone are
23491 			 * contiguous in the ill_ilm list. We use this property
23492 			 * to avoid sending duplicates needed when two
23493 			 * applications in the same zone join the same group on
23494 			 * different logical interfaces: we ignore the ilm if
23495 			 * it's zoneid is the same as the last matching one.
23496 			 * In addition, the sending of the packet for
23497 			 * ire_zoneid is delayed until all of the other ilms
23498 			 * have been exhausted.
23499 			 */
23500 			last_zoneid = -1;
23501 			ILM_WALKER_HOLD(ill);
23502 			for (ilm = ill->ill_ilm; ilm != NULL;
23503 			    ilm = ilm->ilm_next) {
23504 				if ((ilm->ilm_flags & ILM_DELETED) ||
23505 				    ipha->ipha_dst != ilm->ilm_addr ||
23506 				    ilm->ilm_zoneid == last_zoneid ||
23507 				    ilm->ilm_zoneid == zoneid ||
23508 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23509 					continue;
23510 				mp1 = ip_copymsg(first_mp);
23511 				if (mp1 == NULL)
23512 					continue;
23513 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23514 				    mctl_present, B_FALSE, ill,
23515 				    ilm->ilm_zoneid);
23516 				last_zoneid = ilm->ilm_zoneid;
23517 			}
23518 			ILM_WALKER_RELE(ill);
23519 			/*
23520 			 * Loopback case: the sending endpoint has
23521 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23522 			 * dispatch the multicast packet to the sending zone.
23523 			 */
23524 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23525 				freemsg(first_mp);
23526 				return;
23527 			}
23528 		} else if (ire_type == IRE_BROADCAST) {
23529 			/*
23530 			 * In the broadcast case, there may be many zones
23531 			 * which need a copy of the packet delivered to them.
23532 			 * There is one IRE_BROADCAST per broadcast address
23533 			 * and per zone; we walk those using a helper function.
23534 			 * In addition, the sending of the packet for zoneid is
23535 			 * delayed until all of the other ires have been
23536 			 * processed.
23537 			 */
23538 			IRB_REFHOLD(ire->ire_bucket);
23539 			ire_zone = NULL;
23540 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23541 			    ire)) != NULL) {
23542 				mp1 = ip_copymsg(first_mp);
23543 				if (mp1 == NULL)
23544 					continue;
23545 
23546 				UPDATE_IB_PKT_COUNT(ire_zone);
23547 				ire_zone->ire_last_used_time = lbolt;
23548 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23549 				    mctl_present, B_FALSE, ill,
23550 				    ire_zone->ire_zoneid);
23551 			}
23552 			IRB_REFRELE(ire->ire_bucket);
23553 		}
23554 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23555 		    0, mctl_present, B_FALSE, ill, zoneid);
23556 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23557 		    "ip_wput_local_end: q %p (%S)",
23558 		    q, "icmp");
23559 		return;
23560 	}
23561 	case IPPROTO_IGMP:
23562 		if (igmp_input(q, mp, ill)) {
23563 			/* Bad packet - discarded by igmp_input */
23564 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23565 			    "ip_wput_local_end: q %p (%S)",
23566 			    q, "igmp_input--bad packet");
23567 			if (mctl_present)
23568 				freeb(first_mp);
23569 			return;
23570 		}
23571 		/*
23572 		 * igmp_input() may have pulled up the message so ipha needs to
23573 		 * be reinitialized.
23574 		 */
23575 		ipha = (ipha_t *)mp->b_rptr;
23576 		/* deliver to local raw users */
23577 		break;
23578 	case IPPROTO_ENCAP:
23579 		/*
23580 		 * This case is covered by either ip_fanout_proto, or by
23581 		 * the above security processing for self-tunneled packets.
23582 		 */
23583 		break;
23584 	case IPPROTO_UDP: {
23585 		uint16_t	*up;
23586 		uint32_t	ports;
23587 
23588 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23589 		    UDP_PORTS_OFFSET);
23590 		/* Force a 'valid' checksum. */
23591 		up[3] = 0;
23592 
23593 		ports = *(uint32_t *)up;
23594 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23595 		    (ire_type == IRE_BROADCAST),
23596 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23597 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23598 		    ill, zoneid);
23599 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23600 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23601 		return;
23602 	}
23603 	case IPPROTO_TCP: {
23604 
23605 		/*
23606 		 * For TCP, discard broadcast packets.
23607 		 */
23608 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23609 			freemsg(first_mp);
23610 			BUMP_MIB(&ip_mib, ipInDiscards);
23611 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23612 			return;
23613 		}
23614 
23615 		if (mp->b_datap->db_type == M_DATA) {
23616 			/*
23617 			 * M_DATA mblk, so init mblk (chain) for no struio().
23618 			 */
23619 			mblk_t	*mp1 = mp;
23620 
23621 			do
23622 				mp1->b_datap->db_struioflag = 0;
23623 			while ((mp1 = mp1->b_cont) != NULL);
23624 		}
23625 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23626 		    <= mp->b_wptr);
23627 		ip_fanout_tcp(q, first_mp, ill, ipha,
23628 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23629 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23630 		    mctl_present, B_FALSE, zoneid);
23631 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23632 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23633 		return;
23634 	}
23635 	case IPPROTO_SCTP:
23636 	{
23637 		uint32_t	ports;
23638 
23639 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23640 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23641 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23642 		    IP_FF_IP6INFO,
23643 		    mctl_present, B_FALSE, 0, zoneid);
23644 		return;
23645 	}
23646 
23647 	default:
23648 		break;
23649 	}
23650 	/*
23651 	 * Find a client for some other protocol.  We give
23652 	 * copies to multiple clients, if more than one is
23653 	 * bound.
23654 	 */
23655 	ip_fanout_proto(q, first_mp, ill, ipha,
23656 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23657 	    mctl_present, B_FALSE, ill, zoneid);
23658 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23659 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23660 #undef	rptr
23661 }
23662 
23663 /*
23664  * Update any source route, record route, or timestamp options.
23665  * Check that we are at end of strict source route.
23666  * The options have been sanity checked by ip_wput_options().
23667  */
23668 static void
23669 ip_wput_local_options(ipha_t *ipha)
23670 {
23671 	ipoptp_t	opts;
23672 	uchar_t		*opt;
23673 	uint8_t		optval;
23674 	uint8_t		optlen;
23675 	ipaddr_t	dst;
23676 	uint32_t	ts;
23677 	ire_t		*ire;
23678 	timestruc_t	now;
23679 
23680 	ip2dbg(("ip_wput_local_options\n"));
23681 	for (optval = ipoptp_first(&opts, ipha);
23682 	    optval != IPOPT_EOL;
23683 	    optval = ipoptp_next(&opts)) {
23684 		opt = opts.ipoptp_cur;
23685 		optlen = opts.ipoptp_len;
23686 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23687 		switch (optval) {
23688 			uint32_t off;
23689 		case IPOPT_SSRR:
23690 		case IPOPT_LSRR:
23691 			off = opt[IPOPT_OFFSET];
23692 			off--;
23693 			if (optlen < IP_ADDR_LEN ||
23694 			    off > optlen - IP_ADDR_LEN) {
23695 				/* End of source route */
23696 				break;
23697 			}
23698 			/*
23699 			 * This will only happen if two consecutive entries
23700 			 * in the source route contains our address or if
23701 			 * it is a packet with a loose source route which
23702 			 * reaches us before consuming the whole source route
23703 			 */
23704 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23705 			if (optval == IPOPT_SSRR) {
23706 				return;
23707 			}
23708 			/*
23709 			 * Hack: instead of dropping the packet truncate the
23710 			 * source route to what has been used by filling the
23711 			 * rest with IPOPT_NOP.
23712 			 */
23713 			opt[IPOPT_OLEN] = (uint8_t)off;
23714 			while (off < optlen) {
23715 				opt[off++] = IPOPT_NOP;
23716 			}
23717 			break;
23718 		case IPOPT_RR:
23719 			off = opt[IPOPT_OFFSET];
23720 			off--;
23721 			if (optlen < IP_ADDR_LEN ||
23722 			    off > optlen - IP_ADDR_LEN) {
23723 				/* No more room - ignore */
23724 				ip1dbg((
23725 				    "ip_wput_forward_options: end of RR\n"));
23726 				break;
23727 			}
23728 			dst = htonl(INADDR_LOOPBACK);
23729 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23730 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23731 			break;
23732 		case IPOPT_TS:
23733 			/* Insert timestamp if there is romm */
23734 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23735 			case IPOPT_TS_TSONLY:
23736 				off = IPOPT_TS_TIMELEN;
23737 				break;
23738 			case IPOPT_TS_PRESPEC:
23739 			case IPOPT_TS_PRESPEC_RFC791:
23740 				/* Verify that the address matched */
23741 				off = opt[IPOPT_OFFSET] - 1;
23742 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23743 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23744 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23745 				if (ire == NULL) {
23746 					/* Not for us */
23747 					break;
23748 				}
23749 				ire_refrele(ire);
23750 				/* FALLTHRU */
23751 			case IPOPT_TS_TSANDADDR:
23752 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23753 				break;
23754 			default:
23755 				/*
23756 				 * ip_*put_options should have already
23757 				 * dropped this packet.
23758 				 */
23759 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23760 				    "unknown IT - bug in ip_wput_options?\n");
23761 				return;	/* Keep "lint" happy */
23762 			}
23763 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23764 				/* Increase overflow counter */
23765 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23766 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23767 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23768 				    (off << 4);
23769 				break;
23770 			}
23771 			off = opt[IPOPT_OFFSET] - 1;
23772 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23773 			case IPOPT_TS_PRESPEC:
23774 			case IPOPT_TS_PRESPEC_RFC791:
23775 			case IPOPT_TS_TSANDADDR:
23776 				dst = htonl(INADDR_LOOPBACK);
23777 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23778 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23779 				/* FALLTHRU */
23780 			case IPOPT_TS_TSONLY:
23781 				off = opt[IPOPT_OFFSET] - 1;
23782 				/* Compute # of milliseconds since midnight */
23783 				gethrestime(&now);
23784 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23785 				    now.tv_nsec / (NANOSEC / MILLISEC);
23786 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23787 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23788 				break;
23789 			}
23790 			break;
23791 		}
23792 	}
23793 }
23794 
23795 /*
23796  * Send out a multicast packet on interface ipif.
23797  * The sender does not have an conn.
23798  * Caller verifies that this isn't a PHYI_LOOPBACK.
23799  */
23800 void
23801 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23802 {
23803 	ipha_t	*ipha;
23804 	ire_t	*ire;
23805 	ipaddr_t	dst;
23806 	mblk_t		*first_mp;
23807 
23808 	/* igmp_sendpkt always allocates a ipsec_out_t */
23809 	ASSERT(mp->b_datap->db_type == M_CTL);
23810 	ASSERT(!ipif->ipif_isv6);
23811 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23812 
23813 	first_mp = mp;
23814 	mp = first_mp->b_cont;
23815 	ASSERT(mp->b_datap->db_type == M_DATA);
23816 	ipha = (ipha_t *)mp->b_rptr;
23817 
23818 	/*
23819 	 * Find an IRE which matches the destination and the outgoing
23820 	 * queue (i.e. the outgoing interface.)
23821 	 */
23822 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23823 		dst = ipif->ipif_pp_dst_addr;
23824 	else
23825 		dst = ipha->ipha_dst;
23826 	/*
23827 	 * The source address has already been initialized by the
23828 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23829 	 * be sufficient rather than MATCH_IRE_IPIF.
23830 	 *
23831 	 * This function is used for sending IGMP packets. We need
23832 	 * to make sure that we send the packet out of the interface
23833 	 * (ipif->ipif_ill) where we joined the group. This is to
23834 	 * prevent from switches doing IGMP snooping to send us multicast
23835 	 * packets for a given group on the interface we have joined.
23836 	 * If we can't find an ire, igmp_sendpkt has already initialized
23837 	 * ipsec_out_attach_if so that this will not be load spread in
23838 	 * ip_newroute_ipif.
23839 	 */
23840 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23841 	    MATCH_IRE_ILL);
23842 	if (!ire) {
23843 		/*
23844 		 * Mark this packet to make it be delivered to
23845 		 * ip_wput_ire after the new ire has been
23846 		 * created.
23847 		 */
23848 		mp->b_prev = NULL;
23849 		mp->b_next = NULL;
23850 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23851 		return;
23852 	}
23853 
23854 	/*
23855 	 * Honor the RTF_SETSRC flag; this is the only case
23856 	 * where we force this addr whatever the current src addr is,
23857 	 * because this address is set by igmp_sendpkt(), and
23858 	 * cannot be specified by any user.
23859 	 */
23860 	if (ire->ire_flags & RTF_SETSRC) {
23861 		ipha->ipha_src = ire->ire_src_addr;
23862 	}
23863 
23864 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23865 }
23866 
23867 /*
23868  * NOTE : This function does not ire_refrele the ire argument passed in.
23869  *
23870  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23871  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
23872  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23873  * the ire_lock to access the nce_fp_mp in this case.
23874  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23875  * prepending a fastpath message IPQoS processing must precede it, we also set
23876  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23877  * (IPQoS might have set the b_band for CoS marking).
23878  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23879  * must follow it so that IPQoS can mark the dl_priority field for CoS
23880  * marking, if needed.
23881  */
23882 static mblk_t *
23883 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23884 {
23885 	uint_t	hlen;
23886 	ipha_t *ipha;
23887 	mblk_t *mp1;
23888 	boolean_t qos_done = B_FALSE;
23889 	uchar_t	*ll_hdr;
23890 
23891 #define	rptr	((uchar_t *)ipha)
23892 
23893 	ipha = (ipha_t *)mp->b_rptr;
23894 	hlen = 0;
23895 	LOCK_IRE_FP_MP(ire);
23896 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
23897 		ASSERT(DB_TYPE(mp1) == M_DATA);
23898 		/* Initiate IPPF processing */
23899 		if ((proc != 0) && IPP_ENABLED(proc)) {
23900 			UNLOCK_IRE_FP_MP(ire);
23901 			ip_process(proc, &mp, ill_index);
23902 			if (mp == NULL)
23903 				return (NULL);
23904 
23905 			ipha = (ipha_t *)mp->b_rptr;
23906 			LOCK_IRE_FP_MP(ire);
23907 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
23908 				qos_done = B_TRUE;
23909 				goto no_fp_mp;
23910 			}
23911 			ASSERT(DB_TYPE(mp1) == M_DATA);
23912 		}
23913 		hlen = MBLKL(mp1);
23914 		/*
23915 		 * Check if we have enough room to prepend fastpath
23916 		 * header
23917 		 */
23918 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23919 			ll_hdr = rptr - hlen;
23920 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23921 			/*
23922 			 * Set the b_rptr to the start of the link layer
23923 			 * header
23924 			 */
23925 			mp->b_rptr = ll_hdr;
23926 			mp1 = mp;
23927 		} else {
23928 			mp1 = copyb(mp1);
23929 			if (mp1 == NULL)
23930 				goto unlock_err;
23931 			mp1->b_band = mp->b_band;
23932 			mp1->b_cont = mp;
23933 			/*
23934 			 * certain system generated traffic may not
23935 			 * have cred/label in ip header block. This
23936 			 * is true even for a labeled system. But for
23937 			 * labeled traffic, inherit the label in the
23938 			 * new header.
23939 			 */
23940 			if (DB_CRED(mp) != NULL)
23941 				mblk_setcred(mp1, DB_CRED(mp));
23942 			/*
23943 			 * XXX disable ICK_VALID and compute checksum
23944 			 * here; can happen if nce_fp_mp changes and
23945 			 * it can't be copied now due to insufficient
23946 			 * space. (unlikely, fp mp can change, but it
23947 			 * does not increase in length)
23948 			 */
23949 		}
23950 		UNLOCK_IRE_FP_MP(ire);
23951 	} else {
23952 no_fp_mp:
23953 		mp1 = copyb(ire->ire_nce->nce_res_mp);
23954 		if (mp1 == NULL) {
23955 unlock_err:
23956 			UNLOCK_IRE_FP_MP(ire);
23957 			freemsg(mp);
23958 			return (NULL);
23959 		}
23960 		UNLOCK_IRE_FP_MP(ire);
23961 		mp1->b_cont = mp;
23962 		/*
23963 		 * certain system generated traffic may not
23964 		 * have cred/label in ip header block. This
23965 		 * is true even for a labeled system. But for
23966 		 * labeled traffic, inherit the label in the
23967 		 * new header.
23968 		 */
23969 		if (DB_CRED(mp) != NULL)
23970 			mblk_setcred(mp1, DB_CRED(mp));
23971 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23972 			ip_process(proc, &mp1, ill_index);
23973 			if (mp1 == NULL)
23974 				return (NULL);
23975 		}
23976 	}
23977 	return (mp1);
23978 #undef rptr
23979 }
23980 
23981 /*
23982  * Finish the outbound IPsec processing for an IPv6 packet. This function
23983  * is called from ipsec_out_process() if the IPsec packet was processed
23984  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23985  * asynchronously.
23986  */
23987 void
23988 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23989     ire_t *ire_arg)
23990 {
23991 	in6_addr_t *v6dstp;
23992 	ire_t *ire;
23993 	mblk_t *mp;
23994 	uint_t	ill_index;
23995 	ipsec_out_t *io;
23996 	boolean_t attach_if, hwaccel;
23997 	uint32_t flags = IP6_NO_IPPOLICY;
23998 	int match_flags;
23999 	zoneid_t zoneid;
24000 	boolean_t ill_need_rele = B_FALSE;
24001 	boolean_t ire_need_rele = B_FALSE;
24002 
24003 	mp = ipsec_mp->b_cont;
24004 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24005 	ill_index = io->ipsec_out_ill_index;
24006 	if (io->ipsec_out_reachable) {
24007 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24008 	}
24009 	attach_if = io->ipsec_out_attach_if;
24010 	hwaccel = io->ipsec_out_accelerated;
24011 	zoneid = io->ipsec_out_zoneid;
24012 	ASSERT(zoneid != ALL_ZONES);
24013 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24014 	/* Multicast addresses should have non-zero ill_index. */
24015 	v6dstp = &ip6h->ip6_dst;
24016 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24017 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24018 	ASSERT(!attach_if || ill_index != 0);
24019 	if (ill_index != 0) {
24020 		if (ill == NULL) {
24021 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24022 			    B_TRUE);
24023 
24024 			/* Failure case frees things for us. */
24025 			if (ill == NULL)
24026 				return;
24027 
24028 			ill_need_rele = B_TRUE;
24029 		}
24030 		/*
24031 		 * If this packet needs to go out on a particular interface
24032 		 * honor it.
24033 		 */
24034 		if (attach_if) {
24035 			match_flags = MATCH_IRE_ILL;
24036 
24037 			/*
24038 			 * Check if we need an ire that will not be
24039 			 * looked up by anybody else i.e. HIDDEN.
24040 			 */
24041 			if (ill_is_probeonly(ill)) {
24042 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24043 			}
24044 		}
24045 	}
24046 	ASSERT(mp != NULL);
24047 
24048 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24049 		boolean_t unspec_src;
24050 		ipif_t	*ipif;
24051 
24052 		/*
24053 		 * Use the ill_index to get the right ill.
24054 		 */
24055 		unspec_src = io->ipsec_out_unspec_src;
24056 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24057 		if (ipif == NULL) {
24058 			if (ill_need_rele)
24059 				ill_refrele(ill);
24060 			freemsg(ipsec_mp);
24061 			return;
24062 		}
24063 
24064 		if (ire_arg != NULL) {
24065 			ire = ire_arg;
24066 		} else {
24067 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24068 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24069 			ire_need_rele = B_TRUE;
24070 		}
24071 		if (ire != NULL) {
24072 			ipif_refrele(ipif);
24073 			/*
24074 			 * XXX Do the multicast forwarding now, as the IPSEC
24075 			 * processing has been done.
24076 			 */
24077 			goto send;
24078 		}
24079 
24080 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24081 		mp->b_prev = NULL;
24082 		mp->b_next = NULL;
24083 
24084 		/*
24085 		 * If the IPsec packet was processed asynchronously,
24086 		 * drop it now.
24087 		 */
24088 		if (q == NULL) {
24089 			if (ill_need_rele)
24090 				ill_refrele(ill);
24091 			freemsg(ipsec_mp);
24092 			return;
24093 		}
24094 
24095 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24096 		    unspec_src, zoneid);
24097 		ipif_refrele(ipif);
24098 	} else {
24099 		if (attach_if) {
24100 			ipif_t	*ipif;
24101 
24102 			ipif = ipif_get_next_ipif(NULL, ill);
24103 			if (ipif == NULL) {
24104 				if (ill_need_rele)
24105 					ill_refrele(ill);
24106 				freemsg(ipsec_mp);
24107 				return;
24108 			}
24109 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24110 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24111 			ire_need_rele = B_TRUE;
24112 			ipif_refrele(ipif);
24113 		} else {
24114 			if (ire_arg != NULL) {
24115 				ire = ire_arg;
24116 			} else {
24117 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24118 				ire_need_rele = B_TRUE;
24119 			}
24120 		}
24121 		if (ire != NULL)
24122 			goto send;
24123 		/*
24124 		 * ire disappeared underneath.
24125 		 *
24126 		 * What we need to do here is the ip_newroute
24127 		 * logic to get the ire without doing the IPSEC
24128 		 * processing. Follow the same old path. But this
24129 		 * time, ip_wput or ire_add_then_send will call us
24130 		 * directly as all the IPSEC operations are done.
24131 		 */
24132 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24133 		mp->b_prev = NULL;
24134 		mp->b_next = NULL;
24135 
24136 		/*
24137 		 * If the IPsec packet was processed asynchronously,
24138 		 * drop it now.
24139 		 */
24140 		if (q == NULL) {
24141 			if (ill_need_rele)
24142 				ill_refrele(ill);
24143 			freemsg(ipsec_mp);
24144 			return;
24145 		}
24146 
24147 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24148 		    zoneid);
24149 	}
24150 	if (ill != NULL && ill_need_rele)
24151 		ill_refrele(ill);
24152 	return;
24153 send:
24154 	if (ill != NULL && ill_need_rele)
24155 		ill_refrele(ill);
24156 
24157 	/* Local delivery */
24158 	if (ire->ire_stq == NULL) {
24159 		ASSERT(q != NULL);
24160 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24161 		    ire, 0);
24162 		if (ire_need_rele)
24163 			ire_refrele(ire);
24164 		return;
24165 	}
24166 	/*
24167 	 * Everything is done. Send it out on the wire.
24168 	 * We force the insertion of a fragment header using the
24169 	 * IPH_FRAG_HDR flag in two cases:
24170 	 * - after reception of an ICMPv6 "packet too big" message
24171 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24172 	 * - for multirouted IPv6 packets, so that the receiver can
24173 	 *   discard duplicates according to their fragment identifier
24174 	 */
24175 	/* XXX fix flow control problems. */
24176 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24177 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24178 		if (hwaccel) {
24179 			/*
24180 			 * hardware acceleration does not handle these
24181 			 * "slow path" cases.
24182 			 */
24183 			/* IPsec KSTATS: should bump bean counter here. */
24184 			if (ire_need_rele)
24185 				ire_refrele(ire);
24186 			freemsg(ipsec_mp);
24187 			return;
24188 		}
24189 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24190 		    (mp->b_cont ? msgdsize(mp) :
24191 		    mp->b_wptr - (uchar_t *)ip6h)) {
24192 			/* IPsec KSTATS: should bump bean counter here. */
24193 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24194 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24195 			    msgdsize(mp)));
24196 			if (ire_need_rele)
24197 				ire_refrele(ire);
24198 			freemsg(ipsec_mp);
24199 			return;
24200 		}
24201 		ASSERT(mp->b_prev == NULL);
24202 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24203 		    ntohs(ip6h->ip6_plen) +
24204 		    IPV6_HDR_LEN, ire->ire_max_frag));
24205 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24206 		    ire->ire_max_frag);
24207 	} else {
24208 		UPDATE_OB_PKT_COUNT(ire);
24209 		ire->ire_last_used_time = lbolt;
24210 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24211 	}
24212 	if (ire_need_rele)
24213 		ire_refrele(ire);
24214 	freeb(ipsec_mp);
24215 }
24216 
24217 void
24218 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24219 {
24220 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24221 	da_ipsec_t *hada;	/* data attributes */
24222 	ill_t *ill = (ill_t *)q->q_ptr;
24223 
24224 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24225 
24226 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24227 		/* IPsec KSTATS: Bump lose counter here! */
24228 		freemsg(mp);
24229 		return;
24230 	}
24231 
24232 	/*
24233 	 * It's an IPsec packet that must be
24234 	 * accelerated by the Provider, and the
24235 	 * outbound ill is IPsec acceleration capable.
24236 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24237 	 * to the ill.
24238 	 * IPsec KSTATS: should bump packet counter here.
24239 	 */
24240 
24241 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24242 	if (hada_mp == NULL) {
24243 		/* IPsec KSTATS: should bump packet counter here. */
24244 		freemsg(mp);
24245 		return;
24246 	}
24247 
24248 	hada_mp->b_datap->db_type = M_CTL;
24249 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24250 	hada_mp->b_cont = mp;
24251 
24252 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24253 	bzero(hada, sizeof (da_ipsec_t));
24254 	hada->da_type = IPHADA_M_CTL;
24255 
24256 	putnext(q, hada_mp);
24257 }
24258 
24259 /*
24260  * Finish the outbound IPsec processing. This function is called from
24261  * ipsec_out_process() if the IPsec packet was processed
24262  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24263  * asynchronously.
24264  */
24265 void
24266 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24267     ire_t *ire_arg)
24268 {
24269 	uint32_t v_hlen_tos_len;
24270 	ipaddr_t	dst;
24271 	ipif_t	*ipif = NULL;
24272 	ire_t *ire;
24273 	ire_t *ire1 = NULL;
24274 	mblk_t *next_mp = NULL;
24275 	uint32_t max_frag;
24276 	boolean_t multirt_send = B_FALSE;
24277 	mblk_t *mp;
24278 	mblk_t *mp1;
24279 	uint_t	ill_index;
24280 	ipsec_out_t *io;
24281 	boolean_t attach_if;
24282 	int match_flags, offset;
24283 	irb_t *irb = NULL;
24284 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24285 	zoneid_t zoneid;
24286 	uint32_t cksum;
24287 	uint16_t *up;
24288 	ipxmit_state_t	pktxmit_state;
24289 #ifdef	_BIG_ENDIAN
24290 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24291 #else
24292 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24293 #endif
24294 
24295 	mp = ipsec_mp->b_cont;
24296 	ASSERT(mp != NULL);
24297 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24298 	dst = ipha->ipha_dst;
24299 
24300 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24301 	ill_index = io->ipsec_out_ill_index;
24302 	attach_if = io->ipsec_out_attach_if;
24303 	zoneid = io->ipsec_out_zoneid;
24304 	ASSERT(zoneid != ALL_ZONES);
24305 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24306 	if (ill_index != 0) {
24307 		if (ill == NULL) {
24308 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24309 			    ill_index, B_FALSE);
24310 
24311 			/* Failure case frees things for us. */
24312 			if (ill == NULL)
24313 				return;
24314 
24315 			ill_need_rele = B_TRUE;
24316 		}
24317 		/*
24318 		 * If this packet needs to go out on a particular interface
24319 		 * honor it.
24320 		 */
24321 		if (attach_if) {
24322 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24323 
24324 			/*
24325 			 * Check if we need an ire that will not be
24326 			 * looked up by anybody else i.e. HIDDEN.
24327 			 */
24328 			if (ill_is_probeonly(ill)) {
24329 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24330 			}
24331 		}
24332 	}
24333 
24334 	if (CLASSD(dst)) {
24335 		boolean_t conn_dontroute;
24336 		/*
24337 		 * Use the ill_index to get the right ipif.
24338 		 */
24339 		conn_dontroute = io->ipsec_out_dontroute;
24340 		if (ill_index == 0)
24341 			ipif = ipif_lookup_group(dst, zoneid);
24342 		else
24343 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24344 		if (ipif == NULL) {
24345 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24346 			    " multicast\n"));
24347 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24348 			freemsg(ipsec_mp);
24349 			goto done;
24350 		}
24351 		/*
24352 		 * ipha_src has already been intialized with the
24353 		 * value of the ipif in ip_wput. All we need now is
24354 		 * an ire to send this downstream.
24355 		 */
24356 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24357 		    MBLK_GETLABEL(mp), match_flags);
24358 		if (ire != NULL) {
24359 			ill_t *ill1;
24360 			/*
24361 			 * Do the multicast forwarding now, as the IPSEC
24362 			 * processing has been done.
24363 			 */
24364 			if (ip_g_mrouter && !conn_dontroute &&
24365 			    (ill1 = ire_to_ill(ire))) {
24366 				if (ip_mforward(ill1, ipha, mp)) {
24367 					freemsg(ipsec_mp);
24368 					ip1dbg(("ip_wput_ipsec_out: mforward "
24369 					    "failed\n"));
24370 					ire_refrele(ire);
24371 					goto done;
24372 				}
24373 			}
24374 			goto send;
24375 		}
24376 
24377 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24378 		mp->b_prev = NULL;
24379 		mp->b_next = NULL;
24380 
24381 		/*
24382 		 * If the IPsec packet was processed asynchronously,
24383 		 * drop it now.
24384 		 */
24385 		if (q == NULL) {
24386 			freemsg(ipsec_mp);
24387 			goto done;
24388 		}
24389 
24390 		/*
24391 		 * We may be using a wrong ipif to create the ire.
24392 		 * But it is okay as the source address is assigned
24393 		 * for the packet already. Next outbound packet would
24394 		 * create the IRE with the right IPIF in ip_wput.
24395 		 *
24396 		 * Also handle RTF_MULTIRT routes.
24397 		 */
24398 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24399 	} else {
24400 		if (attach_if) {
24401 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24402 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24403 		} else {
24404 			if (ire_arg != NULL) {
24405 				ire = ire_arg;
24406 				ire_need_rele = B_FALSE;
24407 			} else {
24408 				ire = ire_cache_lookup(dst, zoneid,
24409 				    MBLK_GETLABEL(mp));
24410 			}
24411 		}
24412 		if (ire != NULL) {
24413 			goto send;
24414 		}
24415 
24416 		/*
24417 		 * ire disappeared underneath.
24418 		 *
24419 		 * What we need to do here is the ip_newroute
24420 		 * logic to get the ire without doing the IPSEC
24421 		 * processing. Follow the same old path. But this
24422 		 * time, ip_wput or ire_add_then_put will call us
24423 		 * directly as all the IPSEC operations are done.
24424 		 */
24425 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24426 		mp->b_prev = NULL;
24427 		mp->b_next = NULL;
24428 
24429 		/*
24430 		 * If the IPsec packet was processed asynchronously,
24431 		 * drop it now.
24432 		 */
24433 		if (q == NULL) {
24434 			freemsg(ipsec_mp);
24435 			goto done;
24436 		}
24437 
24438 		/*
24439 		 * Since we're going through ip_newroute() again, we
24440 		 * need to make sure we don't:
24441 		 *
24442 		 *	1.) Trigger the ASSERT() with the ipha_ident
24443 		 *	    overloading.
24444 		 *	2.) Redo transport-layer checksumming, since we've
24445 		 *	    already done all that to get this far.
24446 		 *
24447 		 * The easiest way not do either of the above is to set
24448 		 * the ipha_ident field to IP_HDR_INCLUDED.
24449 		 */
24450 		ipha->ipha_ident = IP_HDR_INCLUDED;
24451 		ip_newroute(q, ipsec_mp, dst, NULL,
24452 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24453 	}
24454 	goto done;
24455 send:
24456 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24457 		/*
24458 		 * ESP NAT-Traversal packet.
24459 		 *
24460 		 * Just do software checksum for now.
24461 		 */
24462 
24463 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24464 		IP_STAT(ip_out_sw_cksum);
24465 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24466 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24467 #define	iphs	((uint16_t *)ipha)
24468 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24469 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24470 		    IP_SIMPLE_HDR_LENGTH);
24471 #undef iphs
24472 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24473 			cksum = 0xFFFF;
24474 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24475 			if (mp1->b_wptr - mp1->b_rptr >=
24476 			    offset + sizeof (uint16_t)) {
24477 				up = (uint16_t *)(mp1->b_rptr + offset);
24478 				*up = cksum;
24479 				break;	/* out of for loop */
24480 			} else {
24481 				offset -= (mp->b_wptr - mp->b_rptr);
24482 			}
24483 	} /* Otherwise, just keep the all-zero checksum. */
24484 
24485 	if (ire->ire_stq == NULL) {
24486 		/*
24487 		 * Loopbacks go through ip_wput_local except for one case.
24488 		 * We come here if we generate a icmp_frag_needed message
24489 		 * after IPSEC processing is over. When this function calls
24490 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24491 		 * icmp_frag_needed. The message generated comes back here
24492 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24493 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24494 		 * source address as it is usually set in ip_wput_ire. As
24495 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24496 		 * and we end up here. We can't enter ip_wput_ire once the
24497 		 * IPSEC processing is over and hence we need to do it here.
24498 		 */
24499 		ASSERT(q != NULL);
24500 		UPDATE_OB_PKT_COUNT(ire);
24501 		ire->ire_last_used_time = lbolt;
24502 		if (ipha->ipha_src == 0)
24503 			ipha->ipha_src = ire->ire_src_addr;
24504 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24505 		    ire, 0, zoneid);
24506 		if (ire_need_rele)
24507 			ire_refrele(ire);
24508 		goto done;
24509 	}
24510 
24511 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24512 		/*
24513 		 * We are through with IPSEC processing.
24514 		 * Fragment this and send it on the wire.
24515 		 */
24516 		if (io->ipsec_out_accelerated) {
24517 			/*
24518 			 * The packet has been accelerated but must
24519 			 * be fragmented. This should not happen
24520 			 * since AH and ESP must not accelerate
24521 			 * packets that need fragmentation, however
24522 			 * the configuration could have changed
24523 			 * since the AH or ESP processing.
24524 			 * Drop packet.
24525 			 * IPsec KSTATS: bump bean counter here.
24526 			 */
24527 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24528 			    "fragmented accelerated packet!\n"));
24529 			freemsg(ipsec_mp);
24530 		} else {
24531 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24532 		}
24533 		if (ire_need_rele)
24534 			ire_refrele(ire);
24535 		goto done;
24536 	}
24537 
24538 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24539 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24540 	    (void *)ire->ire_ipif, (void *)ipif));
24541 
24542 	/*
24543 	 * Multiroute the secured packet, unless IPsec really
24544 	 * requires the packet to go out only through a particular
24545 	 * interface.
24546 	 */
24547 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24548 		ire_t *first_ire;
24549 		irb = ire->ire_bucket;
24550 		ASSERT(irb != NULL);
24551 		/*
24552 		 * This ire has been looked up as the one that
24553 		 * goes through the given ipif;
24554 		 * make sure we do not omit any other multiroute ire
24555 		 * that may be present in the bucket before this one.
24556 		 */
24557 		IRB_REFHOLD(irb);
24558 		for (first_ire = irb->irb_ire;
24559 		    first_ire != NULL;
24560 		    first_ire = first_ire->ire_next) {
24561 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24562 			    (first_ire->ire_addr == ire->ire_addr) &&
24563 			    !(first_ire->ire_marks &
24564 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24565 				break;
24566 		}
24567 
24568 		if ((first_ire != NULL) && (first_ire != ire)) {
24569 			/*
24570 			 * Don't change the ire if the packet must
24571 			 * be fragmented if sent via this new one.
24572 			 */
24573 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24574 				IRE_REFHOLD(first_ire);
24575 				if (ire_need_rele)
24576 					ire_refrele(ire);
24577 				else
24578 					ire_need_rele = B_TRUE;
24579 				ire = first_ire;
24580 			}
24581 		}
24582 		IRB_REFRELE(irb);
24583 
24584 		multirt_send = B_TRUE;
24585 		max_frag = ire->ire_max_frag;
24586 	} else {
24587 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24588 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24589 			    "flag, attach_if %d\n", attach_if));
24590 		}
24591 	}
24592 
24593 	/*
24594 	 * In most cases, the emission loop below is entered only once.
24595 	 * Only in the case where the ire holds the RTF_MULTIRT
24596 	 * flag, we loop to process all RTF_MULTIRT ires in the
24597 	 * bucket, and send the packet through all crossed
24598 	 * RTF_MULTIRT routes.
24599 	 */
24600 	do {
24601 		if (multirt_send) {
24602 			/*
24603 			 * ire1 holds here the next ire to process in the
24604 			 * bucket. If multirouting is expected,
24605 			 * any non-RTF_MULTIRT ire that has the
24606 			 * right destination address is ignored.
24607 			 */
24608 			ASSERT(irb != NULL);
24609 			IRB_REFHOLD(irb);
24610 			for (ire1 = ire->ire_next;
24611 			    ire1 != NULL;
24612 			    ire1 = ire1->ire_next) {
24613 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24614 					continue;
24615 				if (ire1->ire_addr != ire->ire_addr)
24616 					continue;
24617 				if (ire1->ire_marks &
24618 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24619 					continue;
24620 				/* No loopback here */
24621 				if (ire1->ire_stq == NULL)
24622 					continue;
24623 				/*
24624 				 * Ensure we do not exceed the MTU
24625 				 * of the next route.
24626 				 */
24627 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24628 					ip_multirt_bad_mtu(ire1, max_frag);
24629 					continue;
24630 				}
24631 
24632 				IRE_REFHOLD(ire1);
24633 				break;
24634 			}
24635 			IRB_REFRELE(irb);
24636 			if (ire1 != NULL) {
24637 				/*
24638 				 * We are in a multiple send case, need to
24639 				 * make a copy of the packet.
24640 				 */
24641 				next_mp = copymsg(ipsec_mp);
24642 				if (next_mp == NULL) {
24643 					ire_refrele(ire1);
24644 					ire1 = NULL;
24645 				}
24646 			}
24647 		}
24648 		/*
24649 		 * Everything is done. Send it out on the wire
24650 		 *
24651 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
24652 		 * either send it on the wire or, in the case of
24653 		 * HW acceleration, call ipsec_hw_putnext.
24654 		 */
24655 		if (ire->ire_nce &&
24656 		    ire->ire_nce->nce_state != ND_REACHABLE) {
24657 			DTRACE_PROBE2(ip__wput__ipsec__bail,
24658 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
24659 			/*
24660 			 * If ire's link-layer is unresolved (this
24661 			 * would only happen if the incomplete ire
24662 			 * was added to cachetable via forwarding path)
24663 			 * don't bother going to ip_xmit_v4. Just drop the
24664 			 * packet.
24665 			 * There is a slight risk here, in that, if we
24666 			 * have the forwarding path create an incomplete
24667 			 * IRE, then until the IRE is completed, any
24668 			 * transmitted IPSEC packets will be dropped
24669 			 * instead of being queued waiting for resolution.
24670 			 *
24671 			 * But the likelihood of a forwarding packet and a wput
24672 			 * packet sending to the same dst at the same time
24673 			 * and there not yet be an ARP entry for it is small.
24674 			 * Furthermore, if this actually happens, it might
24675 			 * be likely that wput would generate multiple
24676 			 * packets (and forwarding would also have a train
24677 			 * of packets) for that destination. If this is
24678 			 * the case, some of them would have been dropped
24679 			 * anyway, since ARP only queues a few packets while
24680 			 * waiting for resolution
24681 			 *
24682 			 * NOTE: We should really call ip_xmit_v4,
24683 			 * and let it queue the packet and send the
24684 			 * ARP query and have ARP come back thus:
24685 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
24686 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
24687 			 * hw accel work. But it's too complex to get
24688 			 * the IPsec hw  acceleration approach to fit
24689 			 * well with ip_xmit_v4 doing ARP without
24690 			 * doing IPSEC simplification. For now, we just
24691 			 * poke ip_xmit_v4 to trigger the arp resolve, so
24692 			 * that we can continue with the send on the next
24693 			 * attempt.
24694 			 *
24695 			 * XXX THis should be revisited, when
24696 			 * the IPsec/IP interaction is cleaned up
24697 			 */
24698 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
24699 			    " - dropping packet\n"));
24700 			freemsg(ipsec_mp);
24701 			/*
24702 			 * Call ip_xmit_v4() to trigger ARP query
24703 			 * in case the nce_state is ND_INITIAL
24704 			 */
24705 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24706 			goto drop_pkt;
24707 		}
24708 
24709 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
24710 		pktxmit_state = ip_xmit_v4(mp, ire,
24711 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
24712 
24713 		if ((pktxmit_state ==  SEND_FAILED) ||
24714 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
24715 
24716 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
24717 drop_pkt:
24718 			BUMP_MIB(&ip_mib, ipOutDiscards);
24719 			if (ire_need_rele)
24720 				ire_refrele(ire);
24721 			if (ire1 != NULL) {
24722 				ire_refrele(ire1);
24723 				freemsg(next_mp);
24724 			}
24725 			goto done;
24726 		}
24727 
24728 		freeb(ipsec_mp);
24729 		if (ire_need_rele)
24730 			ire_refrele(ire);
24731 
24732 		if (ire1 != NULL) {
24733 			ire = ire1;
24734 			ire_need_rele = B_TRUE;
24735 			ASSERT(next_mp);
24736 			ipsec_mp = next_mp;
24737 			mp = ipsec_mp->b_cont;
24738 			ire1 = NULL;
24739 			next_mp = NULL;
24740 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24741 		} else {
24742 			multirt_send = B_FALSE;
24743 		}
24744 	} while (multirt_send);
24745 done:
24746 	if (ill != NULL && ill_need_rele)
24747 		ill_refrele(ill);
24748 	if (ipif != NULL)
24749 		ipif_refrele(ipif);
24750 }
24751 
24752 /*
24753  * Get the ill corresponding to the specified ire, and compare its
24754  * capabilities with the protocol and algorithms specified by the
24755  * the SA obtained from ipsec_out. If they match, annotate the
24756  * ipsec_out structure to indicate that the packet needs acceleration.
24757  *
24758  *
24759  * A packet is eligible for outbound hardware acceleration if the
24760  * following conditions are satisfied:
24761  *
24762  * 1. the packet will not be fragmented
24763  * 2. the provider supports the algorithm
24764  * 3. there is no pending control message being exchanged
24765  * 4. snoop is not attached
24766  * 5. the destination address is not a broadcast or multicast address.
24767  *
24768  * Rationale:
24769  *	- Hardware drivers do not support fragmentation with
24770  *	  the current interface.
24771  *	- snoop, multicast, and broadcast may result in exposure of
24772  *	  a cleartext datagram.
24773  * We check all five of these conditions here.
24774  *
24775  * XXX would like to nuke "ire_t *" parameter here; problem is that
24776  * IRE is only way to figure out if a v4 address is a broadcast and
24777  * thus ineligible for acceleration...
24778  */
24779 static void
24780 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24781 {
24782 	ipsec_out_t *io;
24783 	mblk_t *data_mp;
24784 	uint_t plen, overhead;
24785 
24786 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24787 		return;
24788 
24789 	if (ill == NULL)
24790 		return;
24791 
24792 	/*
24793 	 * Destination address is a broadcast or multicast.  Punt.
24794 	 */
24795 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24796 	    IRE_LOCAL)))
24797 		return;
24798 
24799 	data_mp = ipsec_mp->b_cont;
24800 
24801 	if (ill->ill_isv6) {
24802 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24803 
24804 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24805 			return;
24806 
24807 		plen = ip6h->ip6_plen;
24808 	} else {
24809 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24810 
24811 		if (CLASSD(ipha->ipha_dst))
24812 			return;
24813 
24814 		plen = ipha->ipha_length;
24815 	}
24816 	/*
24817 	 * Is there a pending DLPI control message being exchanged
24818 	 * between IP/IPsec and the DLS Provider? If there is, it
24819 	 * could be a SADB update, and the state of the DLS Provider
24820 	 * SADB might not be in sync with the SADB maintained by
24821 	 * IPsec. To avoid dropping packets or using the wrong keying
24822 	 * material, we do not accelerate this packet.
24823 	 */
24824 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24825 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24826 		    "ill_dlpi_pending! don't accelerate packet\n"));
24827 		return;
24828 	}
24829 
24830 	/*
24831 	 * Is the Provider in promiscous mode? If it does, we don't
24832 	 * accelerate the packet since it will bounce back up to the
24833 	 * listeners in the clear.
24834 	 */
24835 	if (ill->ill_promisc_on_phys) {
24836 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24837 		    "ill in promiscous mode, don't accelerate packet\n"));
24838 		return;
24839 	}
24840 
24841 	/*
24842 	 * Will the packet require fragmentation?
24843 	 */
24844 
24845 	/*
24846 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24847 	 * as is used elsewhere.
24848 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24849 	 *	+ 2-byte trailer
24850 	 */
24851 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24852 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24853 
24854 	if ((plen + overhead) > ill->ill_max_mtu)
24855 		return;
24856 
24857 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24858 
24859 	/*
24860 	 * Can the ill accelerate this IPsec protocol and algorithm
24861 	 * specified by the SA?
24862 	 */
24863 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24864 	    ill->ill_isv6, sa)) {
24865 		return;
24866 	}
24867 
24868 	/*
24869 	 * Tell AH or ESP that the outbound ill is capable of
24870 	 * accelerating this packet.
24871 	 */
24872 	io->ipsec_out_is_capab_ill = B_TRUE;
24873 }
24874 
24875 /*
24876  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24877  *
24878  * If this function returns B_TRUE, the requested SA's have been filled
24879  * into the ipsec_out_*_sa pointers.
24880  *
24881  * If the function returns B_FALSE, the packet has been "consumed", most
24882  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24883  *
24884  * The SA references created by the protocol-specific "select"
24885  * function will be released when the ipsec_mp is freed, thanks to the
24886  * ipsec_out_free destructor -- see spd.c.
24887  */
24888 static boolean_t
24889 ipsec_out_select_sa(mblk_t *ipsec_mp)
24890 {
24891 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24892 	ipsec_out_t *io;
24893 	ipsec_policy_t *pp;
24894 	ipsec_action_t *ap;
24895 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24896 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24897 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24898 
24899 	if (!io->ipsec_out_secure) {
24900 		/*
24901 		 * We came here by mistake.
24902 		 * Don't bother with ipsec processing
24903 		 * We should "discourage" this path in the future.
24904 		 */
24905 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24906 		return (B_FALSE);
24907 	}
24908 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24909 	ASSERT((io->ipsec_out_policy != NULL) ||
24910 	    (io->ipsec_out_act != NULL));
24911 
24912 	ASSERT(io->ipsec_out_failed == B_FALSE);
24913 
24914 	/*
24915 	 * IPSEC processing has started.
24916 	 */
24917 	io->ipsec_out_proc_begin = B_TRUE;
24918 	ap = io->ipsec_out_act;
24919 	if (ap == NULL) {
24920 		pp = io->ipsec_out_policy;
24921 		ASSERT(pp != NULL);
24922 		ap = pp->ipsp_act;
24923 		ASSERT(ap != NULL);
24924 	}
24925 
24926 	/*
24927 	 * We have an action.  now, let's select SA's.
24928 	 * (In the future, we can cache this in the conn_t..)
24929 	 */
24930 	if (ap->ipa_want_esp) {
24931 		if (io->ipsec_out_esp_sa == NULL) {
24932 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24933 			    IPPROTO_ESP);
24934 		}
24935 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24936 	}
24937 
24938 	if (ap->ipa_want_ah) {
24939 		if (io->ipsec_out_ah_sa == NULL) {
24940 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24941 			    IPPROTO_AH);
24942 		}
24943 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24944 		/*
24945 		 * The ESP and AH processing order needs to be preserved
24946 		 * when both protocols are required (ESP should be applied
24947 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24948 		 * when both ESP and AH are required, and an AH ACQUIRE
24949 		 * is needed.
24950 		 */
24951 		if (ap->ipa_want_esp && need_ah_acquire)
24952 			need_esp_acquire = B_TRUE;
24953 	}
24954 
24955 	/*
24956 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24957 	 * Release SAs that got referenced, but will not be used until we
24958 	 * acquire _all_ of the SAs we need.
24959 	 */
24960 	if (need_ah_acquire || need_esp_acquire) {
24961 		if (io->ipsec_out_ah_sa != NULL) {
24962 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24963 			io->ipsec_out_ah_sa = NULL;
24964 		}
24965 		if (io->ipsec_out_esp_sa != NULL) {
24966 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24967 			io->ipsec_out_esp_sa = NULL;
24968 		}
24969 
24970 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24971 		return (B_FALSE);
24972 	}
24973 
24974 	return (B_TRUE);
24975 }
24976 
24977 /*
24978  * Process an IPSEC_OUT message and see what you can
24979  * do with it.
24980  * IPQoS Notes:
24981  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24982  * IPSec.
24983  * XXX would like to nuke ire_t.
24984  * XXX ill_index better be "real"
24985  */
24986 void
24987 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24988 {
24989 	ipsec_out_t *io;
24990 	ipsec_policy_t *pp;
24991 	ipsec_action_t *ap;
24992 	ipha_t *ipha;
24993 	ip6_t *ip6h;
24994 	mblk_t *mp;
24995 	ill_t *ill;
24996 	zoneid_t zoneid;
24997 	ipsec_status_t ipsec_rc;
24998 	boolean_t ill_need_rele = B_FALSE;
24999 
25000 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25001 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25002 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25003 	mp = ipsec_mp->b_cont;
25004 
25005 	/*
25006 	 * Initiate IPPF processing. We do it here to account for packets
25007 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25008 	 * We can check for ipsec_out_proc_begin even for such packets, as
25009 	 * they will always be false (asserted below).
25010 	 */
25011 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25012 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25013 		    io->ipsec_out_ill_index : ill_index);
25014 		if (mp == NULL) {
25015 			ip2dbg(("ipsec_out_process: packet dropped "\
25016 			    "during IPPF processing\n"));
25017 			freeb(ipsec_mp);
25018 			BUMP_MIB(&ip_mib, ipOutDiscards);
25019 			return;
25020 		}
25021 	}
25022 
25023 	if (!io->ipsec_out_secure) {
25024 		/*
25025 		 * We came here by mistake.
25026 		 * Don't bother with ipsec processing
25027 		 * Should "discourage" this path in the future.
25028 		 */
25029 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25030 		goto done;
25031 	}
25032 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25033 	ASSERT((io->ipsec_out_policy != NULL) ||
25034 	    (io->ipsec_out_act != NULL));
25035 	ASSERT(io->ipsec_out_failed == B_FALSE);
25036 
25037 	if (!ipsec_loaded()) {
25038 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25039 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25040 			BUMP_MIB(&ip_mib, ipOutDiscards);
25041 		} else {
25042 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25043 		}
25044 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25045 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25046 		return;
25047 	}
25048 
25049 	/*
25050 	 * IPSEC processing has started.
25051 	 */
25052 	io->ipsec_out_proc_begin = B_TRUE;
25053 	ap = io->ipsec_out_act;
25054 	if (ap == NULL) {
25055 		pp = io->ipsec_out_policy;
25056 		ASSERT(pp != NULL);
25057 		ap = pp->ipsp_act;
25058 		ASSERT(ap != NULL);
25059 	}
25060 
25061 	/*
25062 	 * Save the outbound ill index. When the packet comes back
25063 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25064 	 * before sending it the accelerated packet.
25065 	 */
25066 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25067 		int ifindex;
25068 		ill = ire_to_ill(ire);
25069 		ifindex = ill->ill_phyint->phyint_ifindex;
25070 		io->ipsec_out_capab_ill_index = ifindex;
25071 	}
25072 
25073 	/*
25074 	 * The order of processing is first insert a IP header if needed.
25075 	 * Then insert the ESP header and then the AH header.
25076 	 */
25077 	if ((io->ipsec_out_se_done == B_FALSE) &&
25078 	    (ap->ipa_want_se)) {
25079 		/*
25080 		 * First get the outer IP header before sending
25081 		 * it to ESP.
25082 		 */
25083 		ipha_t *oipha, *iipha;
25084 		mblk_t *outer_mp, *inner_mp;
25085 
25086 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25087 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25088 			    "ipsec_out_process: "
25089 			    "Self-Encapsulation failed: Out of memory\n");
25090 			freemsg(ipsec_mp);
25091 			BUMP_MIB(&ip_mib, ipOutDiscards);
25092 			return;
25093 		}
25094 		inner_mp = ipsec_mp->b_cont;
25095 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25096 		oipha = (ipha_t *)outer_mp->b_rptr;
25097 		iipha = (ipha_t *)inner_mp->b_rptr;
25098 		*oipha = *iipha;
25099 		outer_mp->b_wptr += sizeof (ipha_t);
25100 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25101 		    sizeof (ipha_t));
25102 		oipha->ipha_protocol = IPPROTO_ENCAP;
25103 		oipha->ipha_version_and_hdr_length =
25104 		    IP_SIMPLE_HDR_VERSION;
25105 		oipha->ipha_hdr_checksum = 0;
25106 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25107 		outer_mp->b_cont = inner_mp;
25108 		ipsec_mp->b_cont = outer_mp;
25109 
25110 		io->ipsec_out_se_done = B_TRUE;
25111 		io->ipsec_out_encaps = B_TRUE;
25112 	}
25113 
25114 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25115 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25116 	    !ipsec_out_select_sa(ipsec_mp))
25117 		return;
25118 
25119 	/*
25120 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25121 	 * to do the heavy lifting.
25122 	 */
25123 	zoneid = io->ipsec_out_zoneid;
25124 	ASSERT(zoneid != ALL_ZONES);
25125 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25126 		ASSERT(io->ipsec_out_esp_sa != NULL);
25127 		io->ipsec_out_esp_done = B_TRUE;
25128 		/*
25129 		 * Note that since hw accel can only apply one transform,
25130 		 * not two, we skip hw accel for ESP if we also have AH
25131 		 * This is an design limitation of the interface
25132 		 * which should be revisited.
25133 		 */
25134 		ASSERT(ire != NULL);
25135 		if (io->ipsec_out_ah_sa == NULL) {
25136 			ill = (ill_t *)ire->ire_stq->q_ptr;
25137 			ipsec_out_is_accelerated(ipsec_mp,
25138 			    io->ipsec_out_esp_sa, ill, ire);
25139 		}
25140 
25141 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25142 		switch (ipsec_rc) {
25143 		case IPSEC_STATUS_SUCCESS:
25144 			break;
25145 		case IPSEC_STATUS_FAILED:
25146 			BUMP_MIB(&ip_mib, ipOutDiscards);
25147 			/* FALLTHRU */
25148 		case IPSEC_STATUS_PENDING:
25149 			return;
25150 		}
25151 	}
25152 
25153 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25154 		ASSERT(io->ipsec_out_ah_sa != NULL);
25155 		io->ipsec_out_ah_done = B_TRUE;
25156 		if (ire == NULL) {
25157 			int idx = io->ipsec_out_capab_ill_index;
25158 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25159 			    NULL, NULL, NULL, NULL);
25160 			ill_need_rele = B_TRUE;
25161 		} else {
25162 			ill = (ill_t *)ire->ire_stq->q_ptr;
25163 		}
25164 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25165 		    ire);
25166 
25167 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25168 		switch (ipsec_rc) {
25169 		case IPSEC_STATUS_SUCCESS:
25170 			break;
25171 		case IPSEC_STATUS_FAILED:
25172 			BUMP_MIB(&ip_mib, ipOutDiscards);
25173 			/* FALLTHRU */
25174 		case IPSEC_STATUS_PENDING:
25175 			if (ill != NULL && ill_need_rele)
25176 				ill_refrele(ill);
25177 			return;
25178 		}
25179 	}
25180 	/*
25181 	 * We are done with IPSEC processing. Send it over
25182 	 * the wire.
25183 	 */
25184 done:
25185 	mp = ipsec_mp->b_cont;
25186 	ipha = (ipha_t *)mp->b_rptr;
25187 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25188 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25189 	} else {
25190 		ip6h = (ip6_t *)ipha;
25191 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25192 	}
25193 	if (ill != NULL && ill_need_rele)
25194 		ill_refrele(ill);
25195 }
25196 
25197 /* ARGSUSED */
25198 void
25199 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25200 {
25201 	opt_restart_t	*or;
25202 	int	err;
25203 	conn_t	*connp;
25204 
25205 	ASSERT(CONN_Q(q));
25206 	connp = Q_TO_CONN(q);
25207 
25208 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25209 	or = (opt_restart_t *)first_mp->b_rptr;
25210 	/*
25211 	 * We don't need to pass any credentials here since this is just
25212 	 * a restart. The credentials are passed in when svr4_optcom_req
25213 	 * is called the first time (from ip_wput_nondata).
25214 	 */
25215 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25216 		err = svr4_optcom_req(q, first_mp, NULL,
25217 		    &ip_opt_obj);
25218 	} else {
25219 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25220 		err = tpi_optcom_req(q, first_mp, NULL,
25221 		    &ip_opt_obj);
25222 	}
25223 	if (err != EINPROGRESS) {
25224 		/* operation is done */
25225 		CONN_OPER_PENDING_DONE(connp);
25226 	}
25227 }
25228 
25229 /*
25230  * ioctls that go through a down/up sequence may need to wait for the down
25231  * to complete. This involves waiting for the ire and ipif refcnts to go down
25232  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25233  */
25234 /* ARGSUSED */
25235 void
25236 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25237 {
25238 	struct iocblk *iocp;
25239 	mblk_t *mp1;
25240 	ipif_t	*ipif;
25241 	ip_ioctl_cmd_t *ipip;
25242 	int err;
25243 	sin_t	*sin;
25244 	struct lifreq *lifr;
25245 	struct ifreq *ifr;
25246 
25247 	iocp = (struct iocblk *)mp->b_rptr;
25248 	ASSERT(ipsq != NULL);
25249 	/* Existence of mp1 verified in ip_wput_nondata */
25250 	mp1 = mp->b_cont->b_cont;
25251 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25252 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25253 		ill_t *ill;
25254 		/*
25255 		 * Special case where ipsq_current_ipif may not be set.
25256 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25257 		 * ill could also have become part of a ipmp group in the
25258 		 * process, we are here as were not able to complete the
25259 		 * operation in ipif_set_values because we could not become
25260 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25261 		 * will not be set so we need to set it.
25262 		 */
25263 		ill = (ill_t *)q->q_ptr;
25264 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25265 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25266 	}
25267 
25268 	ipif = ipsq->ipsq_current_ipif;
25269 	ASSERT(ipif != NULL);
25270 	if (ipip->ipi_cmd_type == IF_CMD) {
25271 		/* This a old style SIOC[GS]IF* command */
25272 		ifr = (struct ifreq *)mp1->b_rptr;
25273 		sin = (sin_t *)&ifr->ifr_addr;
25274 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25275 		/* This a new style SIOC[GS]LIF* command */
25276 		lifr = (struct lifreq *)mp1->b_rptr;
25277 		sin = (sin_t *)&lifr->lifr_addr;
25278 	} else {
25279 		sin = NULL;
25280 	}
25281 
25282 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25283 	    (void *)mp1->b_rptr);
25284 
25285 	/* SIOCLIFREMOVEIF could have removed the ipif */
25286 	ip_ioctl_finish(q, mp, err,
25287 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25288 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25289 }
25290 
25291 /*
25292  * ioctl processing
25293  *
25294  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25295  * the ioctl command in the ioctl tables and determines the copyin data size
25296  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25297  * size.
25298  *
25299  * ioctl processing then continues when the M_IOCDATA makes its way down.
25300  * Now the ioctl is looked up again in the ioctl table, and its properties are
25301  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25302  * and the general ioctl processing function ip_process_ioctl is called.
25303  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25304  * so goes thru the serialization primitive ipsq_try_enter. Then the
25305  * appropriate function to handle the ioctl is called based on the entry in
25306  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25307  * which also refreleases the 'conn' that was refheld at the start of the
25308  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25309  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25310  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25311  *
25312  * Many exclusive ioctls go thru an internal down up sequence as part of
25313  * the operation. For example an attempt to change the IP address of an
25314  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25315  * does all the cleanup such as deleting all ires that use this address.
25316  * Then we need to wait till all references to the interface go away.
25317  */
25318 void
25319 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25320 {
25321 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25322 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25323 	cmd_info_t ci;
25324 	int err;
25325 	boolean_t entered_ipsq = B_FALSE;
25326 
25327 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25328 
25329 	if (ipip == NULL)
25330 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25331 
25332 	/*
25333 	 * SIOCLIFADDIF needs to go thru a special path since the
25334 	 * ill may not exist yet. This happens in the case of lo0
25335 	 * which is created using this ioctl.
25336 	 */
25337 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25338 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25339 		ip_ioctl_finish(q, mp, err,
25340 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25341 		    NULL, NULL);
25342 		return;
25343 	}
25344 
25345 	ci.ci_ipif = NULL;
25346 	switch (ipip->ipi_cmd_type) {
25347 	case IF_CMD:
25348 	case LIF_CMD:
25349 		/*
25350 		 * ioctls that pass in a [l]ifreq appear here.
25351 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25352 		 * ci.ci_ipif
25353 		 */
25354 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25355 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25356 		if (err != 0) {
25357 			ip_ioctl_finish(q, mp, err,
25358 			    ipip->ipi_flags & IPI_GET_CMD ?
25359 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25360 			return;
25361 		}
25362 		ASSERT(ci.ci_ipif != NULL);
25363 		break;
25364 
25365 	case TUN_CMD:
25366 		/*
25367 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25368 		 * a refheld ipif in ci.ci_ipif
25369 		 */
25370 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25371 		if (err != 0) {
25372 			ip_ioctl_finish(q, mp, err,
25373 			    ipip->ipi_flags & IPI_GET_CMD ?
25374 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25375 			return;
25376 		}
25377 		ASSERT(ci.ci_ipif != NULL);
25378 		break;
25379 
25380 	case MISC_CMD:
25381 		/*
25382 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25383 		 * For eg. SIOCGLIFCONF will appear here.
25384 		 */
25385 		switch (ipip->ipi_cmd) {
25386 		case IF_UNITSEL:
25387 			/* ioctl comes down the ill */
25388 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25389 			ipif_refhold(ci.ci_ipif);
25390 			break;
25391 		case SIOCGMSFILTER:
25392 		case SIOCSMSFILTER:
25393 		case SIOCGIPMSFILTER:
25394 		case SIOCSIPMSFILTER:
25395 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25396 			    ip_process_ioctl);
25397 			if (err != 0) {
25398 				ip_ioctl_finish(q, mp, err,
25399 				    ipip->ipi_flags & IPI_GET_CMD ?
25400 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25401 				return;
25402 			}
25403 			break;
25404 		}
25405 		err = 0;
25406 		ci.ci_sin = NULL;
25407 		ci.ci_sin6 = NULL;
25408 		ci.ci_lifr = NULL;
25409 		break;
25410 	}
25411 
25412 	/*
25413 	 * If ipsq is non-null, we are already being called exclusively
25414 	 */
25415 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25416 	if (!(ipip->ipi_flags & IPI_WR)) {
25417 		/*
25418 		 * A return value of EINPROGRESS means the ioctl is
25419 		 * either queued and waiting for some reason or has
25420 		 * already completed.
25421 		 */
25422 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25423 		    ci.ci_lifr);
25424 		if (ci.ci_ipif != NULL)
25425 			ipif_refrele(ci.ci_ipif);
25426 		ip_ioctl_finish(q, mp, err,
25427 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25428 		    NULL, NULL);
25429 		return;
25430 	}
25431 
25432 	ASSERT(ci.ci_ipif != NULL);
25433 
25434 	if (ipsq == NULL) {
25435 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25436 		    ip_process_ioctl, NEW_OP, B_TRUE);
25437 		entered_ipsq = B_TRUE;
25438 	}
25439 	/*
25440 	 * Release the ipif so that ipif_down and friends that wait for
25441 	 * references to go away are not misled about the current ipif_refcnt
25442 	 * values. We are writer so we can access the ipif even after releasing
25443 	 * the ipif.
25444 	 */
25445 	ipif_refrele(ci.ci_ipif);
25446 	if (ipsq == NULL)
25447 		return;
25448 
25449 	mutex_enter(&ipsq->ipsq_lock);
25450 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25451 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25452 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25453 	mutex_exit(&ipsq->ipsq_lock);
25454 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25455 	/*
25456 	 * For most set ioctls that come here, this serves as a single point
25457 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25458 	 * be any new references to the ipif. This helps functions that go
25459 	 * through this path and end up trying to wait for the refcnts
25460 	 * associated with the ipif to go down to zero. Some exceptions are
25461 	 * Failover, Failback, and Groupname commands that operate on more than
25462 	 * just the ci.ci_ipif. These commands internally determine the
25463 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25464 	 * flags on that set. Another exception is the Removeif command that
25465 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25466 	 * ipif to operate on.
25467 	 */
25468 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25469 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25470 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25471 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25472 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25473 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25474 
25475 	/*
25476 	 * A return value of EINPROGRESS means the ioctl is
25477 	 * either queued and waiting for some reason or has
25478 	 * already completed.
25479 	 */
25480 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25481 	    ci.ci_lifr);
25482 
25483 	/* SIOCLIFREMOVEIF could have removed the ipif */
25484 	ip_ioctl_finish(q, mp, err,
25485 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25486 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25487 
25488 	if (entered_ipsq)
25489 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25490 }
25491 
25492 /*
25493  * Complete the ioctl. Typically ioctls use the mi package and need to
25494  * do mi_copyout/mi_copy_done.
25495  */
25496 void
25497 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25498     ipif_t *ipif, ipsq_t *ipsq)
25499 {
25500 	conn_t	*connp = NULL;
25501 
25502 	if (err == EINPROGRESS)
25503 		return;
25504 
25505 	if (CONN_Q(q)) {
25506 		connp = Q_TO_CONN(q);
25507 		ASSERT(connp->conn_ref >= 2);
25508 	}
25509 
25510 	switch (mode) {
25511 	case COPYOUT:
25512 		if (err == 0)
25513 			mi_copyout(q, mp);
25514 		else
25515 			mi_copy_done(q, mp, err);
25516 		break;
25517 
25518 	case NO_COPYOUT:
25519 		mi_copy_done(q, mp, err);
25520 		break;
25521 
25522 	default:
25523 		/* An ioctl aborted through a conn close would take this path */
25524 		break;
25525 	}
25526 
25527 	/*
25528 	 * The refhold placed at the start of the ioctl is released here.
25529 	 */
25530 	if (connp != NULL)
25531 		CONN_OPER_PENDING_DONE(connp);
25532 
25533 	/*
25534 	 * If the ioctl were an exclusive ioctl it would have set
25535 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25536 	 */
25537 	if (ipif != NULL) {
25538 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25539 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25540 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25541 	}
25542 
25543 	/*
25544 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25545 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25546 	 * entering the ipsq
25547 	 */
25548 	if (ipsq != NULL) {
25549 		mutex_enter(&ipsq->ipsq_lock);
25550 		ipsq->ipsq_current_ipif = NULL;
25551 		mutex_exit(&ipsq->ipsq_lock);
25552 	}
25553 }
25554 
25555 /*
25556  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25557  */
25558 /* ARGSUSED */
25559 void
25560 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25561 {
25562 	conn_t *connp = arg;
25563 	tcp_t	*tcp;
25564 
25565 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25566 	tcp = connp->conn_tcp;
25567 
25568 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25569 		freemsg(mp);
25570 	else
25571 		tcp_rput_other(tcp, mp);
25572 	CONN_OPER_PENDING_DONE(connp);
25573 }
25574 
25575 /* Called from ip_wput for all non data messages */
25576 /* ARGSUSED */
25577 void
25578 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25579 {
25580 	mblk_t		*mp1;
25581 	ire_t		*ire, *fake_ire;
25582 	ill_t		*ill;
25583 	struct iocblk	*iocp;
25584 	ip_ioctl_cmd_t	*ipip;
25585 	cred_t		*cr;
25586 	conn_t		*connp = NULL;
25587 	int		cmd, err;
25588 	nce_t		*nce;
25589 	ipif_t		*ipif;
25590 
25591 	if (CONN_Q(q))
25592 		connp = Q_TO_CONN(q);
25593 
25594 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25595 
25596 	/* Check if it is a queue to /dev/sctp. */
25597 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25598 	    connp->conn_rq == NULL) {
25599 		sctp_wput(q, mp);
25600 		return;
25601 	}
25602 
25603 	switch (DB_TYPE(mp)) {
25604 	case M_IOCTL:
25605 		/*
25606 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25607 		 * will arrange to copy in associated control structures.
25608 		 */
25609 		ip_sioctl_copyin_setup(q, mp);
25610 		return;
25611 	case M_IOCDATA:
25612 		/*
25613 		 * Ensure that this is associated with one of our trans-
25614 		 * parent ioctls.  If it's not ours, discard it if we're
25615 		 * running as a driver, or pass it on if we're a module.
25616 		 */
25617 		iocp = (struct iocblk *)mp->b_rptr;
25618 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25619 		if (ipip == NULL) {
25620 			if (q->q_next == NULL) {
25621 				goto nak;
25622 			} else {
25623 				putnext(q, mp);
25624 			}
25625 			return;
25626 		} else if ((q->q_next != NULL) &&
25627 		    !(ipip->ipi_flags & IPI_MODOK)) {
25628 			/*
25629 			 * the ioctl is one we recognise, but is not
25630 			 * consumed by IP as a module, pass M_IOCDATA
25631 			 * for processing downstream, but only for
25632 			 * common Streams ioctls.
25633 			 */
25634 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25635 				putnext(q, mp);
25636 				return;
25637 			} else {
25638 				goto nak;
25639 			}
25640 		}
25641 
25642 		/* IOCTL continuation following copyin or copyout. */
25643 		if (mi_copy_state(q, mp, NULL) == -1) {
25644 			/*
25645 			 * The copy operation failed.  mi_copy_state already
25646 			 * cleaned up, so we're out of here.
25647 			 */
25648 			return;
25649 		}
25650 		/*
25651 		 * If we just completed a copy in, we become writer and
25652 		 * continue processing in ip_sioctl_copyin_done.  If it
25653 		 * was a copy out, we call mi_copyout again.  If there is
25654 		 * nothing more to copy out, it will complete the IOCTL.
25655 		 */
25656 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25657 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25658 				mi_copy_done(q, mp, EPROTO);
25659 				return;
25660 			}
25661 			/*
25662 			 * Check for cases that need more copying.  A return
25663 			 * value of 0 means a second copyin has been started,
25664 			 * so we return; a return value of 1 means no more
25665 			 * copying is needed, so we continue.
25666 			 */
25667 			cmd = iocp->ioc_cmd;
25668 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25669 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25670 			    MI_COPY_COUNT(mp) == 1) {
25671 				if (ip_copyin_msfilter(q, mp) == 0)
25672 					return;
25673 			}
25674 			/*
25675 			 * Refhold the conn, till the ioctl completes. This is
25676 			 * needed in case the ioctl ends up in the pending mp
25677 			 * list. Every mp in the ill_pending_mp list and
25678 			 * the ipsq_pending_mp must have a refhold on the conn
25679 			 * to resume processing. The refhold is released when
25680 			 * the ioctl completes. (normally or abnormally)
25681 			 * In all cases ip_ioctl_finish is called to finish
25682 			 * the ioctl.
25683 			 */
25684 			if (connp != NULL) {
25685 				/* This is not a reentry */
25686 				ASSERT(ipsq == NULL);
25687 				CONN_INC_REF(connp);
25688 			} else {
25689 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25690 					mi_copy_done(q, mp, EINVAL);
25691 					return;
25692 				}
25693 			}
25694 
25695 			ip_process_ioctl(ipsq, q, mp, ipip);
25696 
25697 		} else {
25698 			mi_copyout(q, mp);
25699 		}
25700 		return;
25701 nak:
25702 		iocp->ioc_error = EINVAL;
25703 		mp->b_datap->db_type = M_IOCNAK;
25704 		iocp->ioc_count = 0;
25705 		qreply(q, mp);
25706 		return;
25707 
25708 	case M_IOCNAK:
25709 		/*
25710 		 * The only way we could get here is if a resolver didn't like
25711 		 * an IOCTL we sent it.	 This shouldn't happen.
25712 		 */
25713 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25714 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25715 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25716 		freemsg(mp);
25717 		return;
25718 	case M_IOCACK:
25719 		/* Finish socket ioctls passed through to ARP. */
25720 		ip_sioctl_iocack(q, mp);
25721 		return;
25722 	case M_FLUSH:
25723 		if (*mp->b_rptr & FLUSHW)
25724 			flushq(q, FLUSHALL);
25725 		if (q->q_next) {
25726 			/*
25727 			 * M_FLUSH is sent up to IP by some drivers during
25728 			 * unbind. ip_rput has already replied to it. We are
25729 			 * here for the M_FLUSH that we originated in IP
25730 			 * before sending the unbind request to the driver.
25731 			 * Just free it as we don't queue packets in IP
25732 			 * on the write side of the device instance.
25733 			 */
25734 			freemsg(mp);
25735 			return;
25736 		}
25737 		if (*mp->b_rptr & FLUSHR) {
25738 			*mp->b_rptr &= ~FLUSHW;
25739 			qreply(q, mp);
25740 			return;
25741 		}
25742 		freemsg(mp);
25743 		return;
25744 	case IRE_DB_REQ_TYPE:
25745 		/* An Upper Level Protocol wants a copy of an IRE. */
25746 		ip_ire_req(q, mp);
25747 		return;
25748 	case M_CTL:
25749 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25750 			break;
25751 
25752 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25753 		    IP_ULP_OUT_LABELED) {
25754 			out_labeled_t *olp;
25755 
25756 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25757 				break;
25758 			olp = (out_labeled_t *)mp->b_rptr;
25759 			connp->conn_ulp_labeled = olp->out_qnext == q;
25760 			freemsg(mp);
25761 			return;
25762 		}
25763 
25764 		/* M_CTL messages are used by ARP to tell us things. */
25765 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25766 			break;
25767 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25768 		case AR_ENTRY_SQUERY:
25769 			ip_wput_ctl(q, mp);
25770 			return;
25771 		case AR_CLIENT_NOTIFY:
25772 			ip_arp_news(q, mp);
25773 			return;
25774 		case AR_DLPIOP_DONE:
25775 			ASSERT(q->q_next != NULL);
25776 			ill = (ill_t *)q->q_ptr;
25777 			/* qwriter_ip releases the refhold */
25778 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25779 			ill_refhold(ill);
25780 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25781 			    CUR_OP, B_FALSE);
25782 			return;
25783 		case AR_ARP_CLOSING:
25784 			/*
25785 			 * ARP (above us) is closing. If no ARP bringup is
25786 			 * currently pending, ack the message so that ARP
25787 			 * can complete its close. Also mark ill_arp_closing
25788 			 * so that new ARP bringups will fail. If any
25789 			 * ARP bringup is currently in progress, we will
25790 			 * ack this when the current ARP bringup completes.
25791 			 */
25792 			ASSERT(q->q_next != NULL);
25793 			ill = (ill_t *)q->q_ptr;
25794 			mutex_enter(&ill->ill_lock);
25795 			ill->ill_arp_closing = 1;
25796 			if (!ill->ill_arp_bringup_pending) {
25797 				mutex_exit(&ill->ill_lock);
25798 				qreply(q, mp);
25799 			} else {
25800 				mutex_exit(&ill->ill_lock);
25801 				freemsg(mp);
25802 			}
25803 			return;
25804 		default:
25805 			break;
25806 		}
25807 		break;
25808 	case M_PROTO:
25809 	case M_PCPROTO:
25810 		/*
25811 		 * The only PROTO messages we expect are ULP binds and
25812 		 * copies of option negotiation acknowledgements.
25813 		 */
25814 		switch (((union T_primitives *)mp->b_rptr)->type) {
25815 		case O_T_BIND_REQ:
25816 		case T_BIND_REQ: {
25817 			/* Request can get queued in bind */
25818 			ASSERT(connp != NULL);
25819 			/*
25820 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25821 			 * instead of going through this path.  We only get
25822 			 * here in the following cases:
25823 			 *
25824 			 * a. Bind retries, where ipsq is non-NULL.
25825 			 * b. T_BIND_REQ is issued from non TCP/UDP
25826 			 *    transport, e.g. icmp for raw socket,
25827 			 *    in which case ipsq will be NULL.
25828 			 */
25829 			ASSERT(ipsq != NULL ||
25830 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25831 
25832 			/* Don't increment refcnt if this is a re-entry */
25833 			if (ipsq == NULL)
25834 				CONN_INC_REF(connp);
25835 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25836 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25837 			if (mp == NULL)
25838 				return;
25839 			if (IPCL_IS_TCP(connp)) {
25840 				/*
25841 				 * In the case of TCP endpoint we
25842 				 * come here only for bind retries
25843 				 */
25844 				ASSERT(ipsq != NULL);
25845 				CONN_INC_REF(connp);
25846 				squeue_fill(connp->conn_sqp, mp,
25847 				    ip_resume_tcp_bind, connp,
25848 				    SQTAG_BIND_RETRY);
25849 				return;
25850 			} else if (IPCL_IS_UDP(connp)) {
25851 				/*
25852 				 * In the case of UDP endpoint we
25853 				 * come here only for bind retries
25854 				 */
25855 				ASSERT(ipsq != NULL);
25856 				udp_resume_bind(connp, mp);
25857 				return;
25858 			}
25859 			qreply(q, mp);
25860 			CONN_OPER_PENDING_DONE(connp);
25861 			return;
25862 		}
25863 		case T_SVR4_OPTMGMT_REQ:
25864 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25865 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25866 
25867 			ASSERT(connp != NULL);
25868 			if (!snmpcom_req(q, mp, ip_snmp_set,
25869 			    ip_snmp_get, cr)) {
25870 				/*
25871 				 * Call svr4_optcom_req so that it can
25872 				 * generate the ack. We don't come here
25873 				 * if this operation is being restarted.
25874 				 * ip_restart_optmgmt will drop the conn ref.
25875 				 * In the case of ipsec option after the ipsec
25876 				 * load is complete conn_restart_ipsec_waiter
25877 				 * drops the conn ref.
25878 				 */
25879 				ASSERT(ipsq == NULL);
25880 				CONN_INC_REF(connp);
25881 				if (ip_check_for_ipsec_opt(q, mp))
25882 					return;
25883 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25884 				if (err != EINPROGRESS) {
25885 					/* Operation is done */
25886 					CONN_OPER_PENDING_DONE(connp);
25887 				}
25888 			}
25889 			return;
25890 		case T_OPTMGMT_REQ:
25891 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25892 			/*
25893 			 * Note: No snmpcom_req support through new
25894 			 * T_OPTMGMT_REQ.
25895 			 * Call tpi_optcom_req so that it can
25896 			 * generate the ack.
25897 			 */
25898 			ASSERT(connp != NULL);
25899 			ASSERT(ipsq == NULL);
25900 			/*
25901 			 * We don't come here for restart. ip_restart_optmgmt
25902 			 * will drop the conn ref. In the case of ipsec option
25903 			 * after the ipsec load is complete
25904 			 * conn_restart_ipsec_waiter drops the conn ref.
25905 			 */
25906 			CONN_INC_REF(connp);
25907 			if (ip_check_for_ipsec_opt(q, mp))
25908 				return;
25909 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25910 			if (err != EINPROGRESS) {
25911 				/* Operation is done */
25912 				CONN_OPER_PENDING_DONE(connp);
25913 			}
25914 			return;
25915 		case T_UNBIND_REQ:
25916 			mp = ip_unbind(q, mp);
25917 			qreply(q, mp);
25918 			return;
25919 		default:
25920 			/*
25921 			 * Have to drop any DLPI messages coming down from
25922 			 * arp (such as an info_req which would cause ip
25923 			 * to receive an extra info_ack if it was passed
25924 			 * through.
25925 			 */
25926 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25927 			    (int)*(uint_t *)mp->b_rptr));
25928 			freemsg(mp);
25929 			return;
25930 		}
25931 		/* NOTREACHED */
25932 	case IRE_DB_TYPE: {
25933 		nce_t		*nce;
25934 		ill_t		*ill;
25935 		in6_addr_t	gw_addr_v6;
25936 
25937 
25938 		/*
25939 		 * This is a response back from a resolver.  It
25940 		 * consists of a message chain containing:
25941 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25942 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25943 		 * The LL_HDR_MBLK is the DLPI header to use to get
25944 		 * the attached packet, and subsequent ones for the
25945 		 * same destination, transmitted.
25946 		 */
25947 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25948 			break;
25949 		/*
25950 		 * First, check to make sure the resolution succeeded.
25951 		 * If it failed, the second mblk will be empty.
25952 		 * If it is, free the chain, dropping the packet.
25953 		 * (We must ire_delete the ire; that frees the ire mblk)
25954 		 * We're doing this now to support PVCs for ATM; it's
25955 		 * a partial xresolv implementation. When we fully implement
25956 		 * xresolv interfaces, instead of freeing everything here
25957 		 * we'll initiate neighbor discovery.
25958 		 *
25959 		 * For v4 (ARP and other external resolvers) the resolver
25960 		 * frees the message, so no check is needed. This check
25961 		 * is required, though, for a full xresolve implementation.
25962 		 * Including this code here now both shows how external
25963 		 * resolvers can NACK a resolution request using an
25964 		 * existing design that has no specific provisions for NACKs,
25965 		 * and also takes into account that the current non-ARP
25966 		 * external resolver has been coded to use this method of
25967 		 * NACKing for all IPv6 (xresolv) cases,
25968 		 * whether our xresolv implementation is complete or not.
25969 		 *
25970 		 */
25971 		ire = (ire_t *)mp->b_rptr;
25972 		ill = ire_to_ill(ire);
25973 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25974 		if (mp1->b_rptr == mp1->b_wptr) {
25975 			if (ire->ire_ipversion == IPV6_VERSION) {
25976 				/*
25977 				 * XRESOLV interface.
25978 				 */
25979 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25980 				mutex_enter(&ire->ire_lock);
25981 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25982 				mutex_exit(&ire->ire_lock);
25983 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25984 					nce = ndp_lookup_v6(ill,
25985 					    &ire->ire_addr_v6, B_FALSE);
25986 				} else {
25987 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
25988 					    B_FALSE);
25989 				}
25990 				if (nce != NULL) {
25991 					nce_resolv_failed(nce);
25992 					ndp_delete(nce);
25993 					NCE_REFRELE(nce);
25994 				}
25995 			}
25996 			mp->b_cont = NULL;
25997 			freemsg(mp1);		/* frees the pkt as well */
25998 			ASSERT(ire->ire_nce == NULL);
25999 			ire_delete((ire_t *)mp->b_rptr);
26000 			return;
26001 		}
26002 
26003 		/*
26004 		 * Split them into IRE_MBLK and pkt and feed it into
26005 		 * ire_add_then_send. Then in ire_add_then_send
26006 		 * the IRE will be added, and then the packet will be
26007 		 * run back through ip_wput. This time it will make
26008 		 * it to the wire.
26009 		 */
26010 		mp->b_cont = NULL;
26011 		mp = mp1->b_cont;		/* now, mp points to pkt */
26012 		mp1->b_cont = NULL;
26013 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26014 		if (ire->ire_ipversion == IPV6_VERSION) {
26015 			/*
26016 			 * XRESOLV interface. Find the nce and put a copy
26017 			 * of the dl_unitdata_req in nce_res_mp
26018 			 */
26019 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26020 			mutex_enter(&ire->ire_lock);
26021 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26022 			mutex_exit(&ire->ire_lock);
26023 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26024 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26025 				    B_FALSE);
26026 			} else {
26027 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26028 			}
26029 			if (nce != NULL) {
26030 				/*
26031 				 * We have to protect nce_res_mp here
26032 				 * from being accessed by other threads
26033 				 * while we change the mblk pointer.
26034 				 * Other functions will also lock the nce when
26035 				 * accessing nce_res_mp.
26036 				 *
26037 				 * The reason we change the mblk pointer
26038 				 * here rather than copying the resolved address
26039 				 * into the template is that, unlike with
26040 				 * ethernet, we have no guarantee that the
26041 				 * resolved address length will be
26042 				 * smaller than or equal to the lla length
26043 				 * with which the template was allocated,
26044 				 * (for ethernet, they're equal)
26045 				 * so we have to use the actual resolved
26046 				 * address mblk - which holds the real
26047 				 * dl_unitdata_req with the resolved address.
26048 				 *
26049 				 * Doing this is the same behavior as was
26050 				 * previously used in the v4 ARP case.
26051 				 */
26052 				mutex_enter(&nce->nce_lock);
26053 				if (nce->nce_res_mp != NULL)
26054 					freemsg(nce->nce_res_mp);
26055 				nce->nce_res_mp = mp1;
26056 				mutex_exit(&nce->nce_lock);
26057 				/*
26058 				 * We do a fastpath probe here because
26059 				 * we have resolved the address without
26060 				 * using Neighbor Discovery.
26061 				 * In the non-XRESOLV v6 case, the fastpath
26062 				 * probe is done right after neighbor
26063 				 * discovery completes.
26064 				 */
26065 				if (nce->nce_res_mp != NULL) {
26066 					int res;
26067 					nce_fastpath_list_add(nce);
26068 					res = ill_fastpath_probe(ill,
26069 					    nce->nce_res_mp);
26070 					if (res != 0 && res != EAGAIN)
26071 						nce_fastpath_list_delete(nce);
26072 				}
26073 
26074 				ire_add_then_send(q, ire, mp);
26075 				/*
26076 				 * Now we have to clean out any packets
26077 				 * that may have been queued on the nce
26078 				 * while it was waiting for address resolution
26079 				 * to complete.
26080 				 */
26081 				mutex_enter(&nce->nce_lock);
26082 				mp1 = nce->nce_qd_mp;
26083 				nce->nce_qd_mp = NULL;
26084 				mutex_exit(&nce->nce_lock);
26085 				while (mp1 != NULL) {
26086 					mblk_t *nxt_mp;
26087 					queue_t *fwdq = NULL;
26088 					ill_t   *inbound_ill;
26089 					uint_t ifindex;
26090 
26091 					nxt_mp = mp1->b_next;
26092 					mp1->b_next = NULL;
26093 					/*
26094 					 * Retrieve ifindex stored in
26095 					 * ip_rput_data_v6()
26096 					 */
26097 					ifindex =
26098 					    (uint_t)(uintptr_t)mp1->b_prev;
26099 					inbound_ill =
26100 						ill_lookup_on_ifindex(ifindex,
26101 						    B_TRUE, NULL, NULL, NULL,
26102 						    NULL);
26103 					mp1->b_prev = NULL;
26104 					if (inbound_ill != NULL)
26105 						fwdq = inbound_ill->ill_rq;
26106 
26107 					if (fwdq != NULL) {
26108 						put(fwdq, mp1);
26109 						ill_refrele(inbound_ill);
26110 					} else
26111 						put(WR(ill->ill_rq), mp1);
26112 					mp1 = nxt_mp;
26113 				}
26114 				NCE_REFRELE(nce);
26115 			} else {	/* nce is NULL; clean up */
26116 				ire_delete(ire);
26117 				freemsg(mp);
26118 				freemsg(mp1);
26119 				return;
26120 			}
26121 		} else {
26122 			nce_t *arpce;
26123 			/*
26124 			 * Link layer resolution succeeded. Recompute the
26125 			 * ire_nce.
26126 			 */
26127 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26128 			if ((arpce = ndp_lookup_v4(ill,
26129 			    (ire->ire_gateway_addr != INADDR_ANY ?
26130 			    &ire->ire_gateway_addr : &ire->ire_addr),
26131 			    B_FALSE)) == NULL) {
26132 				freeb(ire->ire_mp);
26133 				freeb(mp1);
26134 				freemsg(mp);
26135 				return;
26136 			}
26137 			mutex_enter(&arpce->nce_lock);
26138 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26139 			if (arpce->nce_state == ND_REACHABLE) {
26140 				/*
26141 				 * Someone resolved this before us;
26142 				 * cleanup the res_mp. Since ire has
26143 				 * not been added yet, the call to ire_add_v4
26144 				 * from ire_add_then_send (when a dup is
26145 				 * detected) will clean up the ire.
26146 				 */
26147 				freeb(mp1);
26148 			} else {
26149 				if (arpce->nce_res_mp != NULL)
26150 					freemsg(arpce->nce_res_mp);
26151 				arpce->nce_res_mp = mp1;
26152 				arpce->nce_state = ND_REACHABLE;
26153 			}
26154 			mutex_exit(&arpce->nce_lock);
26155 			if (ire->ire_marks & IRE_MARK_NOADD) {
26156 				/*
26157 				 * this ire will not be added to the ire
26158 				 * cache table, so we can set the ire_nce
26159 				 * here, as there are no atomicity constraints.
26160 				 */
26161 				ire->ire_nce = arpce;
26162 				/*
26163 				 * We are associating this nce with the ire
26164 				 * so change the nce ref taken in
26165 				 * ndp_lookup_v4() from
26166 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26167 				 */
26168 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26169 			} else {
26170 				NCE_REFRELE(arpce);
26171 			}
26172 			ire_add_then_send(q, ire, mp);
26173 		}
26174 		return;	/* All is well, the packet has been sent. */
26175 	}
26176 	case IRE_ARPRESOLVE_TYPE: {
26177 
26178 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26179 			break;
26180 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26181 		mp->b_cont = NULL;
26182 		/*
26183 		 * First, check to make sure the resolution succeeded.
26184 		 * If it failed, the second mblk will be empty.
26185 		 */
26186 		if (mp1->b_rptr == mp1->b_wptr) {
26187 			/* cleanup  the incomplete ire, free queued packets */
26188 			freemsg(mp); /* fake ire */
26189 			freeb(mp1);  /* dl_unitdata response */
26190 			return;
26191 		}
26192 
26193 		/*
26194 		 * update any incomplete nce_t found. we lookup the ctable
26195 		 * and find the nce from the ire->ire_nce because we need
26196 		 * to pass the ire to ip_xmit_v4 later, and can find both
26197 		 * ire and nce in one lookup from the ctable.
26198 		 */
26199 		fake_ire = (ire_t *)mp->b_rptr;
26200 		/*
26201 		 * By the time we come back here from ARP
26202 		 * the logical outgoing interface  of the incomplete ire
26203 		 * we added in ire_forward could have disappeared,
26204 		 * causing the incomplete ire to also have
26205 		 * dissapeared. So we need to retreive the
26206 		 * proper ipif for the ire  before looking
26207 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26208 		 */
26209 		ill = q->q_ptr;
26210 
26211 		/* Get the outgoing ipif */
26212 		mutex_enter(&ill->ill_lock);
26213 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26214 			mutex_exit(&ill->ill_lock);
26215 			freemsg(mp); /* fake ire */
26216 			freeb(mp1);  /* dl_unitdata response */
26217 			return;
26218 		}
26219 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26220 
26221 		if (ipif == NULL) {
26222 			mutex_exit(&ill->ill_lock);
26223 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26224 			freemsg(mp);
26225 			freeb(mp1);
26226 			return;
26227 		}
26228 		ipif_refhold_locked(ipif);
26229 		mutex_exit(&ill->ill_lock);
26230 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26231 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26232 		    ipif, fake_ire->ire_zoneid, NULL,
26233 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26234 		ipif_refrele(ipif);
26235 		if (ire == NULL) {
26236 			/*
26237 			 * no ire was found; check if there is an nce
26238 			 * for this lookup; if it has no ire's pointing at it
26239 			 * cleanup.
26240 			 */
26241 			if ((nce = ndp_lookup_v4(ill,
26242 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26243 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26244 			    B_FALSE)) != NULL) {
26245 				/*
26246 				 * cleanup: just reset nce.
26247 				 * We check for refcnt 2 (one for the nce
26248 				 * hash list + 1 for the ref taken by
26249 				 * ndp_lookup_v4) to ensure that there are
26250 				 * no ire's pointing at the nce.
26251 				 */
26252 				if (nce->nce_refcnt == 2) {
26253 					nce = nce_reinit(nce);
26254 				}
26255 				if (nce != NULL)
26256 					NCE_REFRELE(nce);
26257 			}
26258 			freeb(mp1);  /* dl_unitdata response */
26259 			freemsg(mp); /* fake ire */
26260 			return;
26261 		}
26262 		nce = ire->ire_nce;
26263 		DTRACE_PROBE2(ire__arpresolve__type,
26264 		    ire_t *, ire, nce_t *, nce);
26265 		ASSERT(nce->nce_state != ND_INITIAL);
26266 		mutex_enter(&nce->nce_lock);
26267 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26268 		if (nce->nce_state == ND_REACHABLE) {
26269 			/*
26270 			 * Someone resolved this before us;
26271 			 * our response is not needed any more.
26272 			 */
26273 			mutex_exit(&nce->nce_lock);
26274 			freeb(mp1);  /* dl_unitdata response */
26275 		} else {
26276 			if (nce->nce_res_mp != NULL) {
26277 				freemsg(nce->nce_res_mp);
26278 				/* existing dl_unitdata template */
26279 			}
26280 			nce->nce_res_mp = mp1;
26281 			nce->nce_state = ND_REACHABLE;
26282 			mutex_exit(&nce->nce_lock);
26283 			ire_fastpath(ire);
26284 		}
26285 		/*
26286 		 * The cached nce_t has been updated to be reachable;
26287 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26288 		 */
26289 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26290 		freemsg(mp);
26291 		/*
26292 		 * send out queued packets.
26293 		 */
26294 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26295 
26296 		IRE_REFRELE(ire);
26297 		return;
26298 	}
26299 	default:
26300 		break;
26301 	}
26302 	if (q->q_next) {
26303 		putnext(q, mp);
26304 	} else
26305 		freemsg(mp);
26306 }
26307 
26308 /*
26309  * Process IP options in an outbound packet.  Modify the destination if there
26310  * is a source route option.
26311  * Returns non-zero if something fails in which case an ICMP error has been
26312  * sent and mp freed.
26313  */
26314 static int
26315 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26316     boolean_t mctl_present, zoneid_t zoneid)
26317 {
26318 	ipoptp_t	opts;
26319 	uchar_t		*opt;
26320 	uint8_t		optval;
26321 	uint8_t		optlen;
26322 	ipaddr_t	dst;
26323 	intptr_t	code = 0;
26324 	mblk_t		*mp;
26325 	ire_t		*ire = NULL;
26326 
26327 	ip2dbg(("ip_wput_options\n"));
26328 	mp = ipsec_mp;
26329 	if (mctl_present) {
26330 		mp = ipsec_mp->b_cont;
26331 	}
26332 
26333 	dst = ipha->ipha_dst;
26334 	for (optval = ipoptp_first(&opts, ipha);
26335 	    optval != IPOPT_EOL;
26336 	    optval = ipoptp_next(&opts)) {
26337 		opt = opts.ipoptp_cur;
26338 		optlen = opts.ipoptp_len;
26339 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26340 		    optval, optlen));
26341 		switch (optval) {
26342 			uint32_t off;
26343 		case IPOPT_SSRR:
26344 		case IPOPT_LSRR:
26345 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26346 				ip1dbg((
26347 				    "ip_wput_options: bad option offset\n"));
26348 				code = (char *)&opt[IPOPT_OLEN] -
26349 				    (char *)ipha;
26350 				goto param_prob;
26351 			}
26352 			off = opt[IPOPT_OFFSET];
26353 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26354 			    ntohl(dst)));
26355 			/*
26356 			 * For strict: verify that dst is directly
26357 			 * reachable.
26358 			 */
26359 			if (optval == IPOPT_SSRR) {
26360 				ire = ire_ftable_lookup(dst, 0, 0,
26361 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26362 				    MBLK_GETLABEL(mp),
26363 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26364 				if (ire == NULL) {
26365 					ip1dbg(("ip_wput_options: SSRR not"
26366 					    " directly reachable: 0x%x\n",
26367 					    ntohl(dst)));
26368 					goto bad_src_route;
26369 				}
26370 				ire_refrele(ire);
26371 			}
26372 			break;
26373 		case IPOPT_RR:
26374 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26375 				ip1dbg((
26376 				    "ip_wput_options: bad option offset\n"));
26377 				code = (char *)&opt[IPOPT_OLEN] -
26378 				    (char *)ipha;
26379 				goto param_prob;
26380 			}
26381 			break;
26382 		case IPOPT_TS:
26383 			/*
26384 			 * Verify that length >=5 and that there is either
26385 			 * room for another timestamp or that the overflow
26386 			 * counter is not maxed out.
26387 			 */
26388 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26389 			if (optlen < IPOPT_MINLEN_IT) {
26390 				goto param_prob;
26391 			}
26392 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26393 				ip1dbg((
26394 				    "ip_wput_options: bad option offset\n"));
26395 				code = (char *)&opt[IPOPT_OFFSET] -
26396 				    (char *)ipha;
26397 				goto param_prob;
26398 			}
26399 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26400 			case IPOPT_TS_TSONLY:
26401 				off = IPOPT_TS_TIMELEN;
26402 				break;
26403 			case IPOPT_TS_TSANDADDR:
26404 			case IPOPT_TS_PRESPEC:
26405 			case IPOPT_TS_PRESPEC_RFC791:
26406 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26407 				break;
26408 			default:
26409 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26410 				    (char *)ipha;
26411 				goto param_prob;
26412 			}
26413 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26414 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26415 				/*
26416 				 * No room and the overflow counter is 15
26417 				 * already.
26418 				 */
26419 				goto param_prob;
26420 			}
26421 			break;
26422 		}
26423 	}
26424 
26425 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26426 		return (0);
26427 
26428 	ip1dbg(("ip_wput_options: error processing IP options."));
26429 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26430 
26431 param_prob:
26432 	/*
26433 	 * Since ip_wput() isn't close to finished, we fill
26434 	 * in enough of the header for credible error reporting.
26435 	 */
26436 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26437 		/* Failed */
26438 		freemsg(ipsec_mp);
26439 		return (-1);
26440 	}
26441 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
26442 	return (-1);
26443 
26444 bad_src_route:
26445 	/*
26446 	 * Since ip_wput() isn't close to finished, we fill
26447 	 * in enough of the header for credible error reporting.
26448 	 */
26449 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26450 		/* Failed */
26451 		freemsg(ipsec_mp);
26452 		return (-1);
26453 	}
26454 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
26455 	return (-1);
26456 }
26457 
26458 /*
26459  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26460  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26461  * thru /etc/system.
26462  */
26463 #define	CONN_MAXDRAINCNT	64
26464 
26465 static void
26466 conn_drain_init(void)
26467 {
26468 	int i;
26469 
26470 	conn_drain_list_cnt = conn_drain_nthreads;
26471 
26472 	if ((conn_drain_list_cnt == 0) ||
26473 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26474 		/*
26475 		 * Default value of the number of drainers is the
26476 		 * number of cpus, subject to maximum of 8 drainers.
26477 		 */
26478 		if (boot_max_ncpus != -1)
26479 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26480 		else
26481 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26482 	}
26483 
26484 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26485 	    KM_SLEEP);
26486 
26487 	for (i = 0; i < conn_drain_list_cnt; i++) {
26488 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26489 		    MUTEX_DEFAULT, NULL);
26490 	}
26491 }
26492 
26493 static void
26494 conn_drain_fini(void)
26495 {
26496 	int i;
26497 
26498 	for (i = 0; i < conn_drain_list_cnt; i++)
26499 		mutex_destroy(&conn_drain_list[i].idl_lock);
26500 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26501 	conn_drain_list = NULL;
26502 }
26503 
26504 /*
26505  * Note: For an overview of how flowcontrol is handled in IP please see the
26506  * IP Flowcontrol notes at the top of this file.
26507  *
26508  * Flow control has blocked us from proceeding. Insert the given conn in one
26509  * of the conn drain lists. These conn wq's will be qenabled later on when
26510  * STREAMS flow control does a backenable. conn_walk_drain will enable
26511  * the first conn in each of these drain lists. Each of these qenabled conns
26512  * in turn enables the next in the list, after it runs, or when it closes,
26513  * thus sustaining the drain process.
26514  *
26515  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26516  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26517  * running at any time, on a given conn, since there can be only 1 service proc
26518  * running on a queue at any time.
26519  */
26520 void
26521 conn_drain_insert(conn_t *connp)
26522 {
26523 	idl_t	*idl;
26524 	uint_t	index;
26525 
26526 	mutex_enter(&connp->conn_lock);
26527 	if (connp->conn_state_flags & CONN_CLOSING) {
26528 		/*
26529 		 * The conn is closing as a result of which CONN_CLOSING
26530 		 * is set. Return.
26531 		 */
26532 		mutex_exit(&connp->conn_lock);
26533 		return;
26534 	} else if (connp->conn_idl == NULL) {
26535 		/*
26536 		 * Assign the next drain list round robin. We dont' use
26537 		 * a lock, and thus it may not be strictly round robin.
26538 		 * Atomicity of load/stores is enough to make sure that
26539 		 * conn_drain_list_index is always within bounds.
26540 		 */
26541 		index = conn_drain_list_index;
26542 		ASSERT(index < conn_drain_list_cnt);
26543 		connp->conn_idl = &conn_drain_list[index];
26544 		index++;
26545 		if (index == conn_drain_list_cnt)
26546 			index = 0;
26547 		conn_drain_list_index = index;
26548 	}
26549 	mutex_exit(&connp->conn_lock);
26550 
26551 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26552 	if ((connp->conn_drain_prev != NULL) ||
26553 	    (connp->conn_state_flags & CONN_CLOSING)) {
26554 		/*
26555 		 * The conn is already in the drain list, OR
26556 		 * the conn is closing. We need to check again for
26557 		 * the closing case again since close can happen
26558 		 * after we drop the conn_lock, and before we
26559 		 * acquire the CONN_DRAIN_LIST_LOCK.
26560 		 */
26561 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26562 		return;
26563 	} else {
26564 		idl = connp->conn_idl;
26565 	}
26566 
26567 	/*
26568 	 * The conn is not in the drain list. Insert it at the
26569 	 * tail of the drain list. The drain list is circular
26570 	 * and doubly linked. idl_conn points to the 1st element
26571 	 * in the list.
26572 	 */
26573 	if (idl->idl_conn == NULL) {
26574 		idl->idl_conn = connp;
26575 		connp->conn_drain_next = connp;
26576 		connp->conn_drain_prev = connp;
26577 	} else {
26578 		conn_t *head = idl->idl_conn;
26579 
26580 		connp->conn_drain_next = head;
26581 		connp->conn_drain_prev = head->conn_drain_prev;
26582 		head->conn_drain_prev->conn_drain_next = connp;
26583 		head->conn_drain_prev = connp;
26584 	}
26585 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26586 }
26587 
26588 /*
26589  * This conn is closing, and we are called from ip_close. OR
26590  * This conn has been serviced by ip_wsrv, and we need to do the tail
26591  * processing.
26592  * If this conn is part of the drain list, we may need to sustain the drain
26593  * process by qenabling the next conn in the drain list. We may also need to
26594  * remove this conn from the list, if it is done.
26595  */
26596 static void
26597 conn_drain_tail(conn_t *connp, boolean_t closing)
26598 {
26599 	idl_t *idl;
26600 
26601 	/*
26602 	 * connp->conn_idl is stable at this point, and no lock is needed
26603 	 * to check it. If we are called from ip_close, close has already
26604 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26605 	 * called us only because conn_idl is non-null. If we are called thru
26606 	 * service, conn_idl could be null, but it cannot change because
26607 	 * service is single-threaded per queue, and there cannot be another
26608 	 * instance of service trying to call conn_drain_insert on this conn
26609 	 * now.
26610 	 */
26611 	ASSERT(!closing || (connp->conn_idl != NULL));
26612 
26613 	/*
26614 	 * If connp->conn_idl is null, the conn has not been inserted into any
26615 	 * drain list even once since creation of the conn. Just return.
26616 	 */
26617 	if (connp->conn_idl == NULL)
26618 		return;
26619 
26620 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26621 
26622 	if (connp->conn_drain_prev == NULL) {
26623 		/* This conn is currently not in the drain list.  */
26624 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26625 		return;
26626 	}
26627 	idl = connp->conn_idl;
26628 	if (idl->idl_conn_draining == connp) {
26629 		/*
26630 		 * This conn is the current drainer. If this is the last conn
26631 		 * in the drain list, we need to do more checks, in the 'if'
26632 		 * below. Otherwwise we need to just qenable the next conn,
26633 		 * to sustain the draining, and is handled in the 'else'
26634 		 * below.
26635 		 */
26636 		if (connp->conn_drain_next == idl->idl_conn) {
26637 			/*
26638 			 * This conn is the last in this list. This round
26639 			 * of draining is complete. If idl_repeat is set,
26640 			 * it means another flow enabling has happened from
26641 			 * the driver/streams and we need to another round
26642 			 * of draining.
26643 			 * If there are more than 2 conns in the drain list,
26644 			 * do a left rotate by 1, so that all conns except the
26645 			 * conn at the head move towards the head by 1, and the
26646 			 * the conn at the head goes to the tail. This attempts
26647 			 * a more even share for all queues that are being
26648 			 * drained.
26649 			 */
26650 			if ((connp->conn_drain_next != connp) &&
26651 			    (idl->idl_conn->conn_drain_next != connp)) {
26652 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26653 			}
26654 			if (idl->idl_repeat) {
26655 				qenable(idl->idl_conn->conn_wq);
26656 				idl->idl_conn_draining = idl->idl_conn;
26657 				idl->idl_repeat = 0;
26658 			} else {
26659 				idl->idl_conn_draining = NULL;
26660 			}
26661 		} else {
26662 			/*
26663 			 * If the next queue that we are now qenable'ing,
26664 			 * is closing, it will remove itself from this list
26665 			 * and qenable the subsequent queue in ip_close().
26666 			 * Serialization is acheived thru idl_lock.
26667 			 */
26668 			qenable(connp->conn_drain_next->conn_wq);
26669 			idl->idl_conn_draining = connp->conn_drain_next;
26670 		}
26671 	}
26672 	if (!connp->conn_did_putbq || closing) {
26673 		/*
26674 		 * Remove ourself from the drain list, if we did not do
26675 		 * a putbq, or if the conn is closing.
26676 		 * Note: It is possible that q->q_first is non-null. It means
26677 		 * that these messages landed after we did a enableok() in
26678 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26679 		 * service them.
26680 		 */
26681 		if (connp->conn_drain_next == connp) {
26682 			/* Singleton in the list */
26683 			ASSERT(connp->conn_drain_prev == connp);
26684 			idl->idl_conn = NULL;
26685 			idl->idl_conn_draining = NULL;
26686 		} else {
26687 			connp->conn_drain_prev->conn_drain_next =
26688 			    connp->conn_drain_next;
26689 			connp->conn_drain_next->conn_drain_prev =
26690 			    connp->conn_drain_prev;
26691 			if (idl->idl_conn == connp)
26692 				idl->idl_conn = connp->conn_drain_next;
26693 			ASSERT(idl->idl_conn_draining != connp);
26694 
26695 		}
26696 		connp->conn_drain_next = NULL;
26697 		connp->conn_drain_prev = NULL;
26698 	}
26699 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26700 }
26701 
26702 /*
26703  * Write service routine. Shared perimeter entry point.
26704  * ip_wsrv can be called in any of the following ways.
26705  * 1. The device queue's messages has fallen below the low water mark
26706  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26707  *    the drain lists and backenable the first conn in each list.
26708  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26709  *    qenabled non-tcp upper layers. We start dequeing messages and call
26710  *    ip_wput for each message.
26711  */
26712 
26713 void
26714 ip_wsrv(queue_t *q)
26715 {
26716 	conn_t	*connp;
26717 	ill_t	*ill;
26718 	mblk_t	*mp;
26719 
26720 	if (q->q_next) {
26721 		ill = (ill_t *)q->q_ptr;
26722 		if (ill->ill_state_flags == 0) {
26723 			/*
26724 			 * The device flow control has opened up.
26725 			 * Walk through conn drain lists and qenable the
26726 			 * first conn in each list. This makes sense only
26727 			 * if the stream is fully plumbed and setup.
26728 			 * Hence the if check above.
26729 			 */
26730 			ip1dbg(("ip_wsrv: walking\n"));
26731 			conn_walk_drain();
26732 		}
26733 		return;
26734 	}
26735 
26736 	connp = Q_TO_CONN(q);
26737 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26738 
26739 	/*
26740 	 * 1. Set conn_draining flag to signal that service is active.
26741 	 *
26742 	 * 2. ip_output determines whether it has been called from service,
26743 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26744 	 *    has been called from service.
26745 	 *
26746 	 * 3. Message ordering is preserved by the following logic.
26747 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26748 	 *    the message at the tail, if conn_draining is set (i.e. service
26749 	 *    is running) or if q->q_first is non-null.
26750 	 *
26751 	 *    ii. If ip_output is called from service, and if ip_output cannot
26752 	 *    putnext due to flow control, it does a putbq.
26753 	 *
26754 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26755 	 *    (causing an infinite loop).
26756 	 */
26757 	ASSERT(!connp->conn_did_putbq);
26758 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26759 		connp->conn_draining = 1;
26760 		noenable(q);
26761 		while ((mp = getq(q)) != NULL) {
26762 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26763 			if (connp->conn_did_putbq) {
26764 				/* ip_wput did a putbq */
26765 				break;
26766 			}
26767 		}
26768 		/*
26769 		 * At this point, a thread coming down from top, calling
26770 		 * ip_wput, may end up queueing the message. We have not yet
26771 		 * enabled the queue, so ip_wsrv won't be called again.
26772 		 * To avoid this race, check q->q_first again (in the loop)
26773 		 * If the other thread queued the message before we call
26774 		 * enableok(), we will catch it in the q->q_first check.
26775 		 * If the other thread queues the message after we call
26776 		 * enableok(), ip_wsrv will be called again by STREAMS.
26777 		 */
26778 		connp->conn_draining = 0;
26779 		enableok(q);
26780 	}
26781 
26782 	/* Enable the next conn for draining */
26783 	conn_drain_tail(connp, B_FALSE);
26784 
26785 	connp->conn_did_putbq = 0;
26786 }
26787 
26788 /*
26789  * Walk the list of all conn's calling the function provided with the
26790  * specified argument for each.	 Note that this only walks conn's that
26791  * have been bound.
26792  * Applies to both IPv4 and IPv6.
26793  */
26794 static void
26795 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26796 {
26797 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26798 	    func, arg, zoneid);
26799 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26800 	    func, arg, zoneid);
26801 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26802 	    func, arg, zoneid);
26803 	conn_walk_fanout_table(ipcl_proto_fanout,
26804 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26805 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26806 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26807 }
26808 
26809 /*
26810  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26811  * of conns that need to be drained, check if drain is already in progress.
26812  * If so set the idl_repeat bit, indicating that the last conn in the list
26813  * needs to reinitiate the drain once again, for the list. If drain is not
26814  * in progress for the list, initiate the draining, by qenabling the 1st
26815  * conn in the list. The drain is self-sustaining, each qenabled conn will
26816  * in turn qenable the next conn, when it is done/blocked/closing.
26817  */
26818 static void
26819 conn_walk_drain(void)
26820 {
26821 	int i;
26822 	idl_t *idl;
26823 
26824 	IP_STAT(ip_conn_walk_drain);
26825 
26826 	for (i = 0; i < conn_drain_list_cnt; i++) {
26827 		idl = &conn_drain_list[i];
26828 		mutex_enter(&idl->idl_lock);
26829 		if (idl->idl_conn == NULL) {
26830 			mutex_exit(&idl->idl_lock);
26831 			continue;
26832 		}
26833 		/*
26834 		 * If this list is not being drained currently by
26835 		 * an ip_wsrv thread, start the process.
26836 		 */
26837 		if (idl->idl_conn_draining == NULL) {
26838 			ASSERT(idl->idl_repeat == 0);
26839 			qenable(idl->idl_conn->conn_wq);
26840 			idl->idl_conn_draining = idl->idl_conn;
26841 		} else {
26842 			idl->idl_repeat = 1;
26843 		}
26844 		mutex_exit(&idl->idl_lock);
26845 	}
26846 }
26847 
26848 /*
26849  * Walk an conn hash table of `count' buckets, calling func for each entry.
26850  */
26851 static void
26852 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26853     zoneid_t zoneid)
26854 {
26855 	conn_t	*connp;
26856 
26857 	while (count-- > 0) {
26858 		mutex_enter(&connfp->connf_lock);
26859 		for (connp = connfp->connf_head; connp != NULL;
26860 		    connp = connp->conn_next) {
26861 			if (zoneid == GLOBAL_ZONEID ||
26862 			    zoneid == connp->conn_zoneid) {
26863 				CONN_INC_REF(connp);
26864 				mutex_exit(&connfp->connf_lock);
26865 				(*func)(connp, arg);
26866 				mutex_enter(&connfp->connf_lock);
26867 				CONN_DEC_REF(connp);
26868 			}
26869 		}
26870 		mutex_exit(&connfp->connf_lock);
26871 		connfp++;
26872 	}
26873 }
26874 
26875 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26876 static void
26877 conn_report1(conn_t *connp, void *mp)
26878 {
26879 	char	buf1[INET6_ADDRSTRLEN];
26880 	char	buf2[INET6_ADDRSTRLEN];
26881 	uint_t	print_len, buf_len;
26882 
26883 	ASSERT(connp != NULL);
26884 
26885 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26886 	if (buf_len <= 0)
26887 		return;
26888 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26889 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26890 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26891 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26892 	    "%5d %s/%05d %s/%05d\n",
26893 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26894 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26895 	    buf1, connp->conn_lport,
26896 	    buf2, connp->conn_fport);
26897 	if (print_len < buf_len) {
26898 		((mblk_t *)mp)->b_wptr += print_len;
26899 	} else {
26900 		((mblk_t *)mp)->b_wptr += buf_len;
26901 	}
26902 }
26903 
26904 /*
26905  * Named Dispatch routine to produce a formatted report on all conns
26906  * that are listed in one of the fanout tables.
26907  * This report is accessed by using the ndd utility to "get" ND variable
26908  * "ip_conn_status".
26909  */
26910 /* ARGSUSED */
26911 static int
26912 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26913 {
26914 	(void) mi_mpprintf(mp,
26915 	    "CONN      " MI_COL_HDRPAD_STR
26916 	    "rfq      " MI_COL_HDRPAD_STR
26917 	    "stq      " MI_COL_HDRPAD_STR
26918 	    " zone local                 remote");
26919 
26920 	/*
26921 	 * Because of the ndd constraint, at most we can have 64K buffer
26922 	 * to put in all conn info.  So to be more efficient, just
26923 	 * allocate a 64K buffer here, assuming we need that large buffer.
26924 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26925 	 */
26926 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26927 		/* The following may work even if we cannot get a large buf. */
26928 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26929 		return (0);
26930 	}
26931 
26932 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26933 	return (0);
26934 }
26935 
26936 /*
26937  * Determine if the ill and multicast aspects of that packets
26938  * "matches" the conn.
26939  */
26940 boolean_t
26941 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26942     zoneid_t zoneid)
26943 {
26944 	ill_t *in_ill;
26945 	boolean_t found;
26946 	ipif_t *ipif;
26947 	ire_t *ire;
26948 	ipaddr_t dst, src;
26949 
26950 	dst = ipha->ipha_dst;
26951 	src = ipha->ipha_src;
26952 
26953 	/*
26954 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26955 	 * unicast, broadcast and multicast reception to
26956 	 * conn_incoming_ill. conn_wantpacket itself is called
26957 	 * only for BROADCAST and multicast.
26958 	 *
26959 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26960 	 *    is part of a group. Hence, we should be receiving
26961 	 *    just one copy of broadcast for the whole group.
26962 	 *    Thus, if it is part of the group the packet could
26963 	 *    come on any ill of the group and hence we need a
26964 	 *    match on the group. Otherwise, match on ill should
26965 	 *    be sufficient.
26966 	 *
26967 	 * 2) ip_rput does not suppress duplicate multicast packets.
26968 	 *    If there are two interfaces in a ill group and we have
26969 	 *    2 applications (conns) joined a multicast group G on
26970 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26971 	 *    will give us two packets because we join G on both the
26972 	 *    interfaces rather than nominating just one interface
26973 	 *    for receiving multicast like broadcast above. So,
26974 	 *    we have to call ilg_lookup_ill to filter out duplicate
26975 	 *    copies, if ill is part of a group.
26976 	 */
26977 	in_ill = connp->conn_incoming_ill;
26978 	if (in_ill != NULL) {
26979 		if (in_ill->ill_group == NULL) {
26980 			if (in_ill != ill)
26981 				return (B_FALSE);
26982 		} else if (in_ill->ill_group != ill->ill_group) {
26983 			return (B_FALSE);
26984 		}
26985 	}
26986 
26987 	if (!CLASSD(dst)) {
26988 		if (IPCL_ZONE_MATCH(connp, zoneid))
26989 			return (B_TRUE);
26990 		/*
26991 		 * The conn is in a different zone; we need to check that this
26992 		 * broadcast address is configured in the application's zone and
26993 		 * on one ill in the group.
26994 		 */
26995 		ipif = ipif_get_next_ipif(NULL, ill);
26996 		if (ipif == NULL)
26997 			return (B_FALSE);
26998 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26999 		    connp->conn_zoneid, NULL,
27000 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27001 		ipif_refrele(ipif);
27002 		if (ire != NULL) {
27003 			ire_refrele(ire);
27004 			return (B_TRUE);
27005 		} else {
27006 			return (B_FALSE);
27007 		}
27008 	}
27009 
27010 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27011 	    connp->conn_zoneid == zoneid) {
27012 		/*
27013 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27014 		 * disabled, therefore we don't dispatch the multicast packet to
27015 		 * the sending zone.
27016 		 */
27017 		return (B_FALSE);
27018 	}
27019 
27020 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27021 	    connp->conn_zoneid != zoneid) {
27022 		/*
27023 		 * Multicast packet on the loopback interface: we only match
27024 		 * conns who joined the group in the specified zone.
27025 		 */
27026 		return (B_FALSE);
27027 	}
27028 
27029 	if (connp->conn_multi_router) {
27030 		/* multicast packet and multicast router socket: send up */
27031 		return (B_TRUE);
27032 	}
27033 
27034 	mutex_enter(&connp->conn_lock);
27035 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27036 	mutex_exit(&connp->conn_lock);
27037 	return (found);
27038 }
27039 
27040 /*
27041  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27042  */
27043 /* ARGSUSED */
27044 static void
27045 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27046 {
27047 	ill_t *ill = (ill_t *)q->q_ptr;
27048 	mblk_t	*mp1, *mp2;
27049 	ipif_t  *ipif;
27050 	int err = 0;
27051 	conn_t *connp = NULL;
27052 	ipsq_t	*ipsq;
27053 	arc_t	*arc;
27054 
27055 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27056 
27057 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27058 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27059 
27060 	ASSERT(IAM_WRITER_ILL(ill));
27061 	mp2 = mp->b_cont;
27062 	mp->b_cont = NULL;
27063 
27064 	/*
27065 	 * We have now received the arp bringup completion message
27066 	 * from ARP. Mark the arp bringup as done. Also if the arp
27067 	 * stream has already started closing, send up the AR_ARP_CLOSING
27068 	 * ack now since ARP is waiting in close for this ack.
27069 	 */
27070 	mutex_enter(&ill->ill_lock);
27071 	ill->ill_arp_bringup_pending = 0;
27072 	if (ill->ill_arp_closing) {
27073 		mutex_exit(&ill->ill_lock);
27074 		/* Let's reuse the mp for sending the ack */
27075 		arc = (arc_t *)mp->b_rptr;
27076 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27077 		arc->arc_cmd = AR_ARP_CLOSING;
27078 		qreply(q, mp);
27079 	} else {
27080 		mutex_exit(&ill->ill_lock);
27081 		freeb(mp);
27082 	}
27083 
27084 	/* We should have an IOCTL waiting on this. */
27085 	ipsq = ill->ill_phyint->phyint_ipsq;
27086 	ipif = ipsq->ipsq_pending_ipif;
27087 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27088 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27089 	if (mp1 == NULL) {
27090 		/* bringup was aborted by the user */
27091 		freemsg(mp2);
27092 		return;
27093 	}
27094 	ASSERT(connp != NULL);
27095 	q = CONNP_TO_WQ(connp);
27096 	/*
27097 	 * If the DL_BIND_REQ fails, it is noted
27098 	 * in arc_name_offset.
27099 	 */
27100 	err = *((int *)mp2->b_rptr);
27101 	if (err == 0) {
27102 		if (ipif->ipif_isv6) {
27103 			if ((err = ipif_up_done_v6(ipif)) != 0)
27104 				ip0dbg(("ip_arp_done: init failed\n"));
27105 		} else {
27106 			if ((err = ipif_up_done(ipif)) != 0)
27107 				ip0dbg(("ip_arp_done: init failed\n"));
27108 		}
27109 	} else {
27110 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27111 	}
27112 
27113 	freemsg(mp2);
27114 
27115 	if ((err == 0) && (ill->ill_up_ipifs)) {
27116 		err = ill_up_ipifs(ill, q, mp1);
27117 		if (err == EINPROGRESS)
27118 			return;
27119 	}
27120 
27121 	if (ill->ill_up_ipifs) {
27122 		ill_group_cleanup(ill);
27123 	}
27124 
27125 	/*
27126 	 * The ioctl must complete now without EINPROGRESS
27127 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27128 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27129 	 * stuck for ever in the ipsq.
27130 	 */
27131 	ASSERT(err != EINPROGRESS);
27132 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27133 }
27134 
27135 /* Allocate the private structure */
27136 static int
27137 ip_priv_alloc(void **bufp)
27138 {
27139 	void	*buf;
27140 
27141 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27142 		return (ENOMEM);
27143 
27144 	*bufp = buf;
27145 	return (0);
27146 }
27147 
27148 /* Function to delete the private structure */
27149 void
27150 ip_priv_free(void *buf)
27151 {
27152 	ASSERT(buf != NULL);
27153 	kmem_free(buf, sizeof (ip_priv_t));
27154 }
27155 
27156 /*
27157  * The entry point for IPPF processing.
27158  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27159  * routine just returns.
27160  *
27161  * When called, ip_process generates an ipp_packet_t structure
27162  * which holds the state information for this packet and invokes the
27163  * the classifier (via ipp_packet_process). The classification, depending on
27164  * configured filters, results in a list of actions for this packet. Invoking
27165  * an action may cause the packet to be dropped, in which case the resulting
27166  * mblk (*mpp) is NULL. proc indicates the callout position for
27167  * this packet and ill_index is the interface this packet on or will leave
27168  * on (inbound and outbound resp.).
27169  */
27170 void
27171 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27172 {
27173 	mblk_t		*mp;
27174 	ip_priv_t	*priv;
27175 	ipp_action_id_t	aid;
27176 	int		rc = 0;
27177 	ipp_packet_t	*pp;
27178 #define	IP_CLASS	"ip"
27179 
27180 	/* If the classifier is not loaded, return  */
27181 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27182 		return;
27183 	}
27184 
27185 	mp = *mpp;
27186 	ASSERT(mp != NULL);
27187 
27188 	/* Allocate the packet structure */
27189 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27190 	if (rc != 0) {
27191 		*mpp = NULL;
27192 		freemsg(mp);
27193 		return;
27194 	}
27195 
27196 	/* Allocate the private structure */
27197 	rc = ip_priv_alloc((void **)&priv);
27198 	if (rc != 0) {
27199 		*mpp = NULL;
27200 		freemsg(mp);
27201 		ipp_packet_free(pp);
27202 		return;
27203 	}
27204 	priv->proc = proc;
27205 	priv->ill_index = ill_index;
27206 	ipp_packet_set_private(pp, priv, ip_priv_free);
27207 	ipp_packet_set_data(pp, mp);
27208 
27209 	/* Invoke the classifier */
27210 	rc = ipp_packet_process(&pp);
27211 	if (pp != NULL) {
27212 		mp = ipp_packet_get_data(pp);
27213 		ipp_packet_free(pp);
27214 		if (rc != 0) {
27215 			freemsg(mp);
27216 			*mpp = NULL;
27217 		}
27218 	} else {
27219 		*mpp = NULL;
27220 	}
27221 #undef	IP_CLASS
27222 }
27223 
27224 /*
27225  * Propagate a multicast group membership operation (add/drop) on
27226  * all the interfaces crossed by the related multirt routes.
27227  * The call is considered successful if the operation succeeds
27228  * on at least one interface.
27229  */
27230 static int
27231 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27232     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27233     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27234     mblk_t *first_mp)
27235 {
27236 	ire_t		*ire_gw;
27237 	irb_t		*irb;
27238 	int		error = 0;
27239 	opt_restart_t	*or;
27240 
27241 	irb = ire->ire_bucket;
27242 	ASSERT(irb != NULL);
27243 
27244 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27245 
27246 	or = (opt_restart_t *)first_mp->b_rptr;
27247 	IRB_REFHOLD(irb);
27248 	for (; ire != NULL; ire = ire->ire_next) {
27249 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27250 			continue;
27251 		if (ire->ire_addr != group)
27252 			continue;
27253 
27254 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27255 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27256 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27257 		/* No resolver exists for the gateway; skip this ire. */
27258 		if (ire_gw == NULL)
27259 			continue;
27260 
27261 		/*
27262 		 * This function can return EINPROGRESS. If so the operation
27263 		 * will be restarted from ip_restart_optmgmt which will
27264 		 * call ip_opt_set and option processing will restart for
27265 		 * this option. So we may end up calling 'fn' more than once.
27266 		 * This requires that 'fn' is idempotent except for the
27267 		 * return value. The operation is considered a success if
27268 		 * it succeeds at least once on any one interface.
27269 		 */
27270 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27271 		    NULL, fmode, src, first_mp);
27272 		if (error == 0)
27273 			or->or_private = CGTP_MCAST_SUCCESS;
27274 
27275 		if (ip_debug > 0) {
27276 			ulong_t	off;
27277 			char	*ksym;
27278 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27279 			ip2dbg(("ip_multirt_apply_membership: "
27280 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27281 			    "error %d [success %u]\n",
27282 			    ksym ? ksym : "?",
27283 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27284 			    error, or->or_private));
27285 		}
27286 
27287 		ire_refrele(ire_gw);
27288 		if (error == EINPROGRESS) {
27289 			IRB_REFRELE(irb);
27290 			return (error);
27291 		}
27292 	}
27293 	IRB_REFRELE(irb);
27294 	/*
27295 	 * Consider the call as successful if we succeeded on at least
27296 	 * one interface. Otherwise, return the last encountered error.
27297 	 */
27298 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27299 }
27300 
27301 
27302 /*
27303  * Issue a warning regarding a route crossing an interface with an
27304  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27305  * amount of time is logged.
27306  */
27307 static void
27308 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27309 {
27310 	hrtime_t	current = gethrtime();
27311 	char		buf[16];
27312 
27313 	/* Convert interval in ms to hrtime in ns */
27314 	if (multirt_bad_mtu_last_time +
27315 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27316 	    current) {
27317 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27318 		    "to %s, incorrect MTU %u (expected %u)\n",
27319 		    ip_dot_addr(ire->ire_addr, buf),
27320 		    ire->ire_max_frag, max_frag);
27321 
27322 		multirt_bad_mtu_last_time = current;
27323 	}
27324 }
27325 
27326 
27327 /*
27328  * Get the CGTP (multirouting) filtering status.
27329  * If 0, the CGTP hooks are transparent.
27330  */
27331 /* ARGSUSED */
27332 static int
27333 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27334 {
27335 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27336 
27337 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27338 	return (0);
27339 }
27340 
27341 
27342 /*
27343  * Set the CGTP (multirouting) filtering status.
27344  * If the status is changed from active to transparent
27345  * or from transparent to active, forward the new status
27346  * to the filtering module (if loaded).
27347  */
27348 /* ARGSUSED */
27349 static int
27350 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27351     cred_t *ioc_cr)
27352 {
27353 	long		new_value;
27354 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27355 
27356 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27357 	    new_value < 0 || new_value > 1) {
27358 		return (EINVAL);
27359 	}
27360 
27361 	/*
27362 	 * Do not enable CGTP filtering - thus preventing the hooks
27363 	 * from being invoked - if the version number of the
27364 	 * filtering module hooks does not match.
27365 	 */
27366 	if ((ip_cgtp_filter_ops != NULL) &&
27367 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27368 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27369 		    "(module hooks version %d, expecting %d)\n",
27370 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27371 		return (ENOTSUP);
27372 	}
27373 
27374 	if ((!*ip_cgtp_filter_value) && new_value) {
27375 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27376 		    ip_cgtp_filter_ops == NULL ?
27377 		    " (module not loaded)" : "");
27378 	}
27379 	if (*ip_cgtp_filter_value && (!new_value)) {
27380 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27381 		    ip_cgtp_filter_ops == NULL ?
27382 		    " (module not loaded)" : "");
27383 	}
27384 
27385 	if (ip_cgtp_filter_ops != NULL) {
27386 		int	res;
27387 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27388 			return (res);
27389 		}
27390 	}
27391 
27392 	*ip_cgtp_filter_value = (boolean_t)new_value;
27393 
27394 	return (0);
27395 }
27396 
27397 
27398 /*
27399  * Return the expected CGTP hooks version number.
27400  */
27401 int
27402 ip_cgtp_filter_supported(void)
27403 {
27404 	return (ip_cgtp_filter_rev);
27405 }
27406 
27407 
27408 /*
27409  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27410  * or by invoking this function. In the first case, the version number
27411  * of the registered structure is checked at hooks activation time
27412  * in ip_cgtp_filter_set().
27413  */
27414 int
27415 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27416 {
27417 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27418 		return (ENOTSUP);
27419 
27420 	ip_cgtp_filter_ops = ops;
27421 	return (0);
27422 }
27423 
27424 static squeue_func_t
27425 ip_squeue_switch(int val)
27426 {
27427 	squeue_func_t rval = squeue_fill;
27428 
27429 	switch (val) {
27430 	case IP_SQUEUE_ENTER_NODRAIN:
27431 		rval = squeue_enter_nodrain;
27432 		break;
27433 	case IP_SQUEUE_ENTER:
27434 		rval = squeue_enter;
27435 		break;
27436 	default:
27437 		break;
27438 	}
27439 	return (rval);
27440 }
27441 
27442 /* ARGSUSED */
27443 static int
27444 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27445     caddr_t addr, cred_t *cr)
27446 {
27447 	int *v = (int *)addr;
27448 	long new_value;
27449 
27450 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27451 		return (EINVAL);
27452 
27453 	ip_input_proc = ip_squeue_switch(new_value);
27454 	*v = new_value;
27455 	return (0);
27456 }
27457 
27458 /* ARGSUSED */
27459 static int
27460 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27461     caddr_t addr, cred_t *cr)
27462 {
27463 	int *v = (int *)addr;
27464 	long new_value;
27465 
27466 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27467 		return (EINVAL);
27468 
27469 	*v = new_value;
27470 	return (0);
27471 }
27472 
27473 static void
27474 ip_kstat_init(void)
27475 {
27476 	ip_named_kstat_t template = {
27477 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27478 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27479 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27480 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27481 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27482 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27483 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27484 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27485 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27486 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27487 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27488 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27489 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27490 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27491 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27492 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27493 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27494 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27495 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27496 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27497 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27498 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27499 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27500 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27501 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27502 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27503 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27504 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27505 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27506 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27507 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27508 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27509 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27510 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27511 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27512 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27513 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27514 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27515 	};
27516 
27517 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27518 					NUM_OF_FIELDS(ip_named_kstat_t),
27519 					0);
27520 	if (!ip_mibkp)
27521 		return;
27522 
27523 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27524 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27525 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27526 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27527 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27528 
27529 	template.netToMediaEntrySize.value.i32 =
27530 		sizeof (mib2_ipNetToMediaEntry_t);
27531 
27532 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27533 
27534 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27535 
27536 	ip_mibkp->ks_update = ip_kstat_update;
27537 
27538 	kstat_install(ip_mibkp);
27539 }
27540 
27541 static void
27542 ip_kstat_fini(void)
27543 {
27544 
27545 	if (ip_mibkp != NULL) {
27546 		kstat_delete(ip_mibkp);
27547 		ip_mibkp = NULL;
27548 	}
27549 }
27550 
27551 static int
27552 ip_kstat_update(kstat_t *kp, int rw)
27553 {
27554 	ip_named_kstat_t *ipkp;
27555 
27556 	if (!kp || !kp->ks_data)
27557 		return (EIO);
27558 
27559 	if (rw == KSTAT_WRITE)
27560 		return (EACCES);
27561 
27562 	ipkp = (ip_named_kstat_t *)kp->ks_data;
27563 
27564 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
27565 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
27566 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
27567 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
27568 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
27569 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
27570 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
27571 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
27572 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
27573 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
27574 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
27575 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
27576 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
27577 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
27578 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
27579 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
27580 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
27581 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
27582 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
27583 
27584 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
27585 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
27586 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
27587 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
27588 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
27589 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
27590 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
27591 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
27592 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
27593 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27594 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27595 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27596 
27597 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27598 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27599 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27600 
27601 	return (0);
27602 }
27603 
27604 static void
27605 icmp_kstat_init(void)
27606 {
27607 	icmp_named_kstat_t template = {
27608 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27609 		{ "inErrors",		KSTAT_DATA_UINT32 },
27610 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27611 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27612 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27613 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27614 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27615 		{ "inEchos",		KSTAT_DATA_UINT32 },
27616 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27617 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27618 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27619 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27620 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27621 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27622 		{ "outErrors",		KSTAT_DATA_UINT32 },
27623 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27624 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27625 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27626 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27627 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27628 		{ "outEchos",		KSTAT_DATA_UINT32 },
27629 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27630 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27631 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27632 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27633 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27634 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27635 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27636 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27637 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27638 		{ "outDrops",		KSTAT_DATA_UINT32 },
27639 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27640 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27641 	};
27642 
27643 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27644 					NUM_OF_FIELDS(icmp_named_kstat_t),
27645 					0);
27646 	if (icmp_mibkp == NULL)
27647 		return;
27648 
27649 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27650 
27651 	icmp_mibkp->ks_update = icmp_kstat_update;
27652 
27653 	kstat_install(icmp_mibkp);
27654 }
27655 
27656 static void
27657 icmp_kstat_fini(void)
27658 {
27659 
27660 	if (icmp_mibkp != NULL) {
27661 		kstat_delete(icmp_mibkp);
27662 		icmp_mibkp = NULL;
27663 	}
27664 }
27665 
27666 static int
27667 icmp_kstat_update(kstat_t *kp, int rw)
27668 {
27669 	icmp_named_kstat_t *icmpkp;
27670 
27671 	if ((kp == NULL) || (kp->ks_data == NULL))
27672 		return (EIO);
27673 
27674 	if (rw == KSTAT_WRITE)
27675 		return (EACCES);
27676 
27677 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27678 
27679 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27680 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27681 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27682 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27683 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27684 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27685 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27686 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27687 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27688 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27689 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27690 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27691 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27692 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27693 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27694 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27695 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27696 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27697 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27698 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27699 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27700 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27701 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27702 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27703 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27704 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27705 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27706 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27707 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27708 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27709 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27710 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27711 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27712 
27713 	return (0);
27714 }
27715 
27716 /*
27717  * This is the fanout function for raw socket opened for SCTP.  Note
27718  * that it is called after SCTP checks that there is no socket which
27719  * wants a packet.  Then before SCTP handles this out of the blue packet,
27720  * this function is called to see if there is any raw socket for SCTP.
27721  * If there is and it is bound to the correct address, the packet will
27722  * be sent to that socket.  Note that only one raw socket can be bound to
27723  * a port.  This is assured in ipcl_sctp_hash_insert();
27724  */
27725 void
27726 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27727     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27728     uint_t ipif_seqid, zoneid_t zoneid)
27729 {
27730 	conn_t		*connp;
27731 	queue_t		*rq;
27732 	mblk_t		*first_mp;
27733 	boolean_t	secure;
27734 	ip6_t		*ip6h;
27735 
27736 	first_mp = mp;
27737 	if (mctl_present) {
27738 		mp = first_mp->b_cont;
27739 		secure = ipsec_in_is_secure(first_mp);
27740 		ASSERT(mp != NULL);
27741 	} else {
27742 		secure = B_FALSE;
27743 	}
27744 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27745 
27746 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27747 	if (connp == NULL) {
27748 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27749 		    mctl_present);
27750 		return;
27751 	}
27752 	rq = connp->conn_rq;
27753 	if (!canputnext(rq)) {
27754 		CONN_DEC_REF(connp);
27755 		BUMP_MIB(&ip_mib, rawipInOverflows);
27756 		freemsg(first_mp);
27757 		return;
27758 	}
27759 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27760 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27761 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27762 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27763 		if (first_mp == NULL) {
27764 			CONN_DEC_REF(connp);
27765 			return;
27766 		}
27767 	}
27768 	/*
27769 	 * We probably should not send M_CTL message up to
27770 	 * raw socket.
27771 	 */
27772 	if (mctl_present)
27773 		freeb(first_mp);
27774 
27775 	/* Initiate IPPF processing here if needed. */
27776 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27777 	    (!isv4 && IP6_IN_IPP(flags))) {
27778 		ip_process(IPP_LOCAL_IN, &mp,
27779 		    recv_ill->ill_phyint->phyint_ifindex);
27780 		if (mp == NULL) {
27781 			CONN_DEC_REF(connp);
27782 			return;
27783 		}
27784 	}
27785 
27786 	if (connp->conn_recvif || connp->conn_recvslla ||
27787 	    ((connp->conn_ipv6_recvpktinfo ||
27788 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27789 	    (flags & IP_FF_IP6INFO))) {
27790 		int in_flags = 0;
27791 
27792 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27793 			in_flags = IPF_RECVIF;
27794 		}
27795 		if (connp->conn_recvslla) {
27796 			in_flags |= IPF_RECVSLLA;
27797 		}
27798 		if (isv4) {
27799 			mp = ip_add_info(mp, recv_ill, in_flags);
27800 		} else {
27801 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27802 			if (mp == NULL) {
27803 				CONN_DEC_REF(connp);
27804 				return;
27805 			}
27806 		}
27807 	}
27808 
27809 	BUMP_MIB(&ip_mib, ipInDelivers);
27810 	/*
27811 	 * We are sending the IPSEC_IN message also up. Refer
27812 	 * to comments above this function.
27813 	 */
27814 	putnext(rq, mp);
27815 	CONN_DEC_REF(connp);
27816 }
27817 
27818 /*
27819  * This function should be called only if all packet processing
27820  * including fragmentation is complete. Callers of this function
27821  * must set mp->b_prev to one of these values:
27822  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
27823  * prior to handing over the mp as first argument to this function.
27824  *
27825  * If the ire passed by caller is incomplete, this function
27826  * queues the packet and if necessary, sends ARP request and bails.
27827  * If the ire passed is fully resolved, we simply prepend
27828  * the link-layer header to the packet, do ipsec hw acceleration
27829  * work if necessary, and send the packet out on the wire.
27830  *
27831  * NOTE: IPSEC will only call this function with fully resolved
27832  * ires if hw acceleration is involved.
27833  * TODO list :
27834  * 	a Handle M_MULTIDATA so that
27835  *	  tcp_multisend->tcp_multisend_data can
27836  *	  call ip_xmit_v4 directly
27837  *	b Handle post-ARP work for fragments so that
27838  *	  ip_wput_frag can call this function.
27839  */
27840 ipxmit_state_t
27841 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
27842 {
27843 	nce_t		*arpce;
27844 	queue_t		*q;
27845 	int		ill_index;
27846 	mblk_t		*nxt_mp;
27847 	boolean_t	xmit_drop = B_FALSE;
27848 	ip_proc_t	proc;
27849 
27850 	arpce = ire->ire_nce;
27851 	ASSERT(arpce != NULL);
27852 
27853 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
27854 
27855 	mutex_enter(&arpce->nce_lock);
27856 	switch (arpce->nce_state) {
27857 	case ND_REACHABLE:
27858 		/* If there are other queued packets, queue this packet */
27859 		if (arpce->nce_qd_mp != NULL) {
27860 			if (mp != NULL)
27861 				nce_queue_mp_common(arpce, mp, B_FALSE);
27862 			mp = arpce->nce_qd_mp;
27863 		}
27864 		arpce->nce_qd_mp = NULL;
27865 		mutex_exit(&arpce->nce_lock);
27866 
27867 		/*
27868 		 * Flush the queue.  In the common case, where the
27869 		 * ARP is already resolved,  it will go through the
27870 		 * while loop only once.
27871 		 */
27872 		while (mp != NULL) {
27873 
27874 			nxt_mp = mp->b_next;
27875 			mp->b_next = NULL;
27876 			/*
27877 			 * This info is needed for IPQOS to do COS marking
27878 			 * in ip_wput_attach_llhdr->ip_process.
27879 			 */
27880 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
27881 			mp->b_prev = NULL;
27882 
27883 			/* set up ill index for outbound qos processing */
27884 			ill_index =
27885 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
27886 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
27887 			if (mp == NULL) {
27888 				xmit_drop = B_TRUE;
27889 				if (proc == IPP_FWD_OUT) {
27890 					BUMP_MIB(&ip_mib, ipInDiscards);
27891 				} else {
27892 					BUMP_MIB(&ip_mib, ipOutDiscards);
27893 				}
27894 				goto next_mp;
27895 			}
27896 			/* non-ipsec hw accel case */
27897 			if (io == NULL || !io->ipsec_out_accelerated) {
27898 				/* send it */
27899 				q = ire->ire_stq;
27900 				if (proc == IPP_FWD_OUT) {
27901 					UPDATE_IB_PKT_COUNT(ire);
27902 				} else {
27903 					UPDATE_OB_PKT_COUNT(ire);
27904 				}
27905 				ire->ire_last_used_time = lbolt;
27906 
27907 				if (flow_ctl_enabled) {
27908 					/*
27909 					 * We are here from ip_wout_ire
27910 					 * which has already done canput
27911 					 * check and has enabled flow
27912 					 * control, so skip the canputnext
27913 					 * check.
27914 					 */
27915 					putnext(q, mp);
27916 					goto next_mp;
27917 				}
27918 				if (canputnext(q))  {
27919 					if (proc == IPP_FWD_OUT) {
27920 						BUMP_MIB(&ip_mib,
27921 						    ipForwDatagrams);
27922 					}
27923 					putnext(q, mp);
27924 				} else {
27925 					BUMP_MIB(&ip_mib,
27926 					    ipOutDiscards);
27927 					xmit_drop = B_TRUE;
27928 					freemsg(mp);
27929 				}
27930 			} else {
27931 				/*
27932 				 * Safety Pup says: make sure this
27933 				 *  is going to the right interface!
27934 				 */
27935 				ill_t *ill1 =
27936 				    (ill_t *)ire->ire_stq->q_ptr;
27937 				int ifindex =
27938 				    ill1->ill_phyint->phyint_ifindex;
27939 				if (ifindex !=
27940 				    io->ipsec_out_capab_ill_index) {
27941 					xmit_drop = B_TRUE;
27942 					freemsg(mp);
27943 				} else {
27944 					ipsec_hw_putnext(ire->ire_stq,
27945 					    mp);
27946 				}
27947 			}
27948 next_mp:
27949 			mp = nxt_mp;
27950 		} /* while (mp != NULL) */
27951 		if (xmit_drop)
27952 			return (SEND_FAILED);
27953 		else
27954 			return (SEND_PASSED);
27955 
27956 	case ND_INITIAL:
27957 	case ND_INCOMPLETE:
27958 
27959 		/*
27960 		 * While we do send off packets to dests that
27961 		 * use fully-resolved CGTP routes, we do not
27962 		 * handle unresolved CGTP routes.
27963 		 */
27964 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
27965 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
27966 
27967 		if (mp != NULL) {
27968 			/* queue the packet */
27969 			nce_queue_mp_common(arpce, mp, B_FALSE);
27970 		}
27971 
27972 		if (arpce->nce_state == ND_INCOMPLETE) {
27973 			mutex_exit(&arpce->nce_lock);
27974 			DTRACE_PROBE3(ip__xmit__incomplete,
27975 			    (ire_t *), ire, (mblk_t *), mp,
27976 			    (ipsec_out_t *), io);
27977 			return (LOOKUP_IN_PROGRESS);
27978 		}
27979 
27980 		arpce->nce_state = ND_INCOMPLETE;
27981 		mutex_exit(&arpce->nce_lock);
27982 		/*
27983 		 * Note that ire_add() (called from ire_forward())
27984 		 * holds a ref on the ire until ARP is completed.
27985 		 */
27986 
27987 		ire_arpresolve(ire, ire->ire_ipif->ipif_ill);
27988 		return (LOOKUP_IN_PROGRESS);
27989 	default:
27990 		ASSERT(0);
27991 		mutex_exit(&arpce->nce_lock);
27992 		return (LLHDR_RESLV_FAILED);
27993 	}
27994 }
27995 
27996 /*
27997  * Return B_TRUE if the buffers differ in length or content.
27998  * This is used for comparing extension header buffers.
27999  * Note that an extension header would be declared different
28000  * even if all that changed was the next header value in that header i.e.
28001  * what really changed is the next extension header.
28002  */
28003 boolean_t
28004 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28005     uint_t blen)
28006 {
28007 	if (!b_valid)
28008 		blen = 0;
28009 
28010 	if (alen != blen)
28011 		return (B_TRUE);
28012 	if (alen == 0)
28013 		return (B_FALSE);	/* Both zero length */
28014 	return (bcmp(abuf, bbuf, alen));
28015 }
28016 
28017 /*
28018  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28019  * Return B_FALSE if memory allocation fails - don't change any state!
28020  */
28021 boolean_t
28022 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28023     const void *src, uint_t srclen)
28024 {
28025 	void *dst;
28026 
28027 	if (!src_valid)
28028 		srclen = 0;
28029 
28030 	ASSERT(*dstlenp == 0);
28031 	if (src != NULL && srclen != 0) {
28032 		dst = mi_alloc(srclen, BPRI_MED);
28033 		if (dst == NULL)
28034 			return (B_FALSE);
28035 	} else {
28036 		dst = NULL;
28037 	}
28038 	if (*dstp != NULL)
28039 		mi_free(*dstp);
28040 	*dstp = dst;
28041 	*dstlenp = dst == NULL ? 0 : srclen;
28042 	return (B_TRUE);
28043 }
28044 
28045 /*
28046  * Replace what is in *dst, *dstlen with the source.
28047  * Assumes ip_allocbuf has already been called.
28048  */
28049 void
28050 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28051     const void *src, uint_t srclen)
28052 {
28053 	if (!src_valid)
28054 		srclen = 0;
28055 
28056 	ASSERT(*dstlenp == srclen);
28057 	if (src != NULL && srclen != 0)
28058 		bcopy(src, *dstp, srclen);
28059 }
28060 
28061 /*
28062  * Free the storage pointed to by the members of an ip6_pkt_t.
28063  */
28064 void
28065 ip6_pkt_free(ip6_pkt_t *ipp)
28066 {
28067 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28068 
28069 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28070 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28071 		ipp->ipp_hopopts = NULL;
28072 		ipp->ipp_hopoptslen = 0;
28073 	}
28074 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28075 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28076 		ipp->ipp_rtdstopts = NULL;
28077 		ipp->ipp_rtdstoptslen = 0;
28078 	}
28079 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28080 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28081 		ipp->ipp_dstopts = NULL;
28082 		ipp->ipp_dstoptslen = 0;
28083 	}
28084 	if (ipp->ipp_fields & IPPF_RTHDR) {
28085 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28086 		ipp->ipp_rthdr = NULL;
28087 		ipp->ipp_rthdrlen = 0;
28088 	}
28089 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28090 	    IPPF_RTHDR);
28091 }
28092