xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 46ae6f1e3494358cbcad951902b491d6826ebd75)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 int ip_modclose_ackwait_ms = 3000;
255 
256 /*
257  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
258  */
259 
260 struct listptr_s {
261 	mblk_t	*lp_head;	/* pointer to the head of the list */
262 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
263 };
264 
265 typedef struct listptr_s listptr_t;
266 
267 /*
268  * This is used by ip_snmp_get_mib2_ip_route_media and
269  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
270  */
271 typedef struct iproutedata_s {
272 	uint_t		ird_idx;
273 	listptr_t	ird_route;	/* ipRouteEntryTable */
274 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
275 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
276 } iproutedata_t;
277 
278 /*
279  * Cluster specific hooks. These should be NULL when booted as a non-cluster
280  */
281 
282 /*
283  * Hook functions to enable cluster networking
284  * On non-clustered systems these vectors must always be NULL.
285  *
286  * Hook function to Check ip specified ip address is a shared ip address
287  * in the cluster
288  *
289  */
290 int (*cl_inet_isclusterwide)(uint8_t protocol,
291     sa_family_t addr_family, uint8_t *laddrp) = NULL;
292 
293 /*
294  * Hook function to generate cluster wide ip fragment identifier
295  */
296 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
297     uint8_t *laddrp, uint8_t *faddrp) = NULL;
298 
299 /*
300  * Synchronization notes:
301  *
302  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
303  * MT level protection given by STREAMS. IP uses a combination of its own
304  * internal serialization mechanism and standard Solaris locking techniques.
305  * The internal serialization is per phyint (no IPMP) or per IPMP group.
306  * This is used to serialize plumbing operations, IPMP operations, certain
307  * multicast operations, most set ioctls, igmp/mld timers etc.
308  *
309  * Plumbing is a long sequence of operations involving message
310  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
311  * involved in plumbing operations. A natural model is to serialize these
312  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
313  * parallel without any interference. But various set ioctls on hme0 are best
314  * serialized. However if the system uses IPMP, the operations are easier if
315  * they are serialized on a per IPMP group basis since IPMP operations
316  * happen across ill's of a group. Thus the lowest common denominator is to
317  * serialize most set ioctls, multicast join/leave operations, IPMP operations
318  * igmp/mld timer operations, and processing of DLPI control messages received
319  * from drivers on a per IPMP group basis. If the system does not employ
320  * IPMP the serialization is on a per phyint basis. This serialization is
321  * provided by the ipsq_t and primitives operating on this. Details can
322  * be found in ip_if.c above the core primitives operating on ipsq_t.
323  *
324  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
325  * Simiarly lookup of an ire by a thread also returns a refheld ire.
326  * In addition ipif's and ill's referenced by the ire are also indirectly
327  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
328  * the ipif's address or netmask change as long as an ipif is refheld
329  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
330  * address of an ipif has to go through the ipsq_t. This ensures that only
331  * 1 such exclusive operation proceeds at any time on the ipif. It then
332  * deletes all ires associated with this ipif, and waits for all refcnts
333  * associated with this ipif to come down to zero. The address is changed
334  * only after the ipif has been quiesced. Then the ipif is brought up again.
335  * More details are described above the comment in ip_sioctl_flags.
336  *
337  * Packet processing is based mostly on IREs and are fully multi-threaded
338  * using standard Solaris MT techniques.
339  *
340  * There are explicit locks in IP to handle:
341  * - The ip_g_head list maintained by mi_open_link() and friends.
342  *
343  * - The reassembly data structures (one lock per hash bucket)
344  *
345  * - conn_lock is meant to protect conn_t fields. The fields actually
346  *   protected by conn_lock are documented in the conn_t definition.
347  *
348  * - ire_lock to protect some of the fields of the ire, IRE tables
349  *   (one lock per hash bucket). Refer to ip_ire.c for details.
350  *
351  * - ndp_g_lock and nce_lock for protecting NCEs.
352  *
353  * - ill_lock protects fields of the ill and ipif. Details in ip.h
354  *
355  * - ill_g_lock: This is a global reader/writer lock. Protects the following
356  *	* The AVL tree based global multi list of all ills.
357  *	* The linked list of all ipifs of an ill
358  *	* The <ill-ipsq> mapping
359  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
360  *	* The illgroup list threaded by ill_group_next.
361  *	* <ill-phyint> association
362  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
363  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
364  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
365  *   will all have to hold the ill_g_lock as writer for the actual duration
366  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
367  *   may be found in the IPMP section.
368  *
369  * - ill_lock:  This is a per ill mutex.
370  *   It protects some members of the ill and is documented below.
371  *   It also protects the <ill-ipsq> mapping
372  *   It also protects the illgroup list threaded by ill_group_next.
373  *   It also protects the <ill-phyint> assoc.
374  *   It also protects the list of ipifs hanging off the ill.
375  *
376  * - ipsq_lock: This is a per ipsq_t mutex lock.
377  *   This protects all the other members of the ipsq struct except
378  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
379  *
380  * - illgrp_lock: This is a per ill_group mutex lock.
381  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
382  *   which dictates which is the next ill in an ill_group that is to be chosen
383  *   for sending outgoing packets, through creation of an IRE_CACHE that
384  *   references this ill.
385  *
386  * - phyint_lock: This is a per phyint mutex lock. Protects just the
387  *   phyint_flags
388  *
389  * - ip_g_nd_lock: This is a global reader/writer lock.
390  *   Any call to nd_load to load a new parameter to the ND table must hold the
391  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
392  *   as reader.
393  *
394  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
395  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
396  *   uniqueness check also done atomically.
397  *
398  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
399  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
400  *   as a writer when adding or deleting elements from these lists, and
401  *   as a reader when walking these lists to send a SADB update to the
402  *   IPsec capable ills.
403  *
404  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
405  *   group list linked by ill_usesrc_grp_next. It also protects the
406  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
407  *   group is being added or deleted.  This lock is taken as a reader when
408  *   walking the list/group(eg: to get the number of members in a usesrc group).
409  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
410  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
411  *   example, it is not necessary to take this lock in the initial portion
412  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
413  *   ip_sioctl_flags since the these operations are executed exclusively and
414  *   that ensures that the "usesrc group state" cannot change. The "usesrc
415  *   group state" change can happen only in the latter part of
416  *   ip_sioctl_slifusesrc and in ill_delete.
417  *
418  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
419  *
420  * To change the <ill-phyint> association, the ill_g_lock must be held
421  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
422  * must be held.
423  *
424  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
425  * and the ill_lock of the ill in question must be held.
426  *
427  * To change the <ill-illgroup> association the ill_g_lock must be held as
428  * writer and the ill_lock of the ill in question must be held.
429  *
430  * To add or delete an ipif from the list of ipifs hanging off the ill,
431  * ill_g_lock (writer) and ill_lock must be held and the thread must be
432  * a writer on the associated ipsq,.
433  *
434  * To add or delete an ill to the system, the ill_g_lock must be held as
435  * writer and the thread must be a writer on the associated ipsq.
436  *
437  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
438  * must be a writer on the associated ipsq.
439  *
440  * Lock hierarchy
441  *
442  * Some lock hierarchy scenarios are listed below.
443  *
444  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
445  * ill_g_lock -> illgrp_lock -> ill_lock
446  * ill_g_lock -> ill_lock(s) -> phyint_lock
447  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
448  * ill_g_lock -> ip_addr_avail_lock
449  * conn_lock -> irb_lock -> ill_lock -> ire_lock
450  * ill_g_lock -> ip_g_nd_lock
451  *
452  * When more than 1 ill lock is needed to be held, all ill lock addresses
453  * are sorted on address and locked starting from highest addressed lock
454  * downward.
455  *
456  * Mobile-IP scenarios
457  *
458  * irb_lock -> ill_lock -> ire_mrtun_lock
459  * irb_lock -> ill_lock -> ire_srcif_table_lock
460  *
461  * IPsec scenarios
462  *
463  * ipsa_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
465  * ipsec_capab_ills_lock -> ipsa_lock
466  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
467  *
468  * Trusted Solaris scenarios
469  *
470  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
471  * igsa_lock -> gcdb_lock
472  * gcgrp_rwlock -> ire_lock
473  * gcgrp_rwlock -> gcdb_lock
474  *
475  *
476  * Routing/forwarding table locking notes:
477  *
478  * Lock acquisition order: Radix tree lock, irb_lock.
479  * Requirements:
480  * i.  Walker must not hold any locks during the walker callback.
481  * ii  Walker must not see a truncated tree during the walk because of any node
482  *     deletion.
483  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
484  *     in many places in the code to walk the irb list. Thus even if all the
485  *     ires in a bucket have been deleted, we still can't free the radix node
486  *     until the ires have actually been inactive'd (freed).
487  *
488  * Tree traversal - Need to hold the global tree lock in read mode.
489  * Before dropping the global tree lock, need to either increment the ire_refcnt
490  * to ensure that the radix node can't be deleted.
491  *
492  * Tree add - Need to hold the global tree lock in write mode to add a
493  * radix node. To prevent the node from being deleted, increment the
494  * irb_refcnt, after the node is added to the tree. The ire itself is
495  * added later while holding the irb_lock, but not the tree lock.
496  *
497  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
498  * All associated ires must be inactive (i.e. freed), and irb_refcnt
499  * must be zero.
500  *
501  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
502  * global tree lock (read mode) for traversal.
503  *
504  * IPSEC notes :
505  *
506  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
507  * in front of the actual packet. For outbound datagrams, the M_CTL
508  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
509  * information used by the IPSEC code for applying the right level of
510  * protection. The information initialized by IP in the ipsec_out_t
511  * is determined by the per-socket policy or global policy in the system.
512  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
513  * ipsec_info.h) which starts out with nothing in it. It gets filled
514  * with the right information if it goes through the AH/ESP code, which
515  * happens if the incoming packet is secure. The information initialized
516  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
517  * the policy requirements needed by per-socket policy or global policy
518  * is met or not.
519  *
520  * If there is both per-socket policy (set using setsockopt) and there
521  * is also global policy match for the 5 tuples of the socket,
522  * ipsec_override_policy() makes the decision of which one to use.
523  *
524  * For fully connected sockets i.e dst, src [addr, port] is known,
525  * conn_policy_cached is set indicating that policy has been cached.
526  * conn_in_enforce_policy may or may not be set depending on whether
527  * there is a global policy match or per-socket policy match.
528  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
529  * Once the right policy is set on the conn_t, policy cannot change for
530  * this socket. This makes life simpler for TCP (UDP ?) where
531  * re-transmissions go out with the same policy. For symmetry, policy
532  * is cached for fully connected UDP sockets also. Thus if policy is cached,
533  * it also implies that policy is latched i.e policy cannot change
534  * on these sockets. As we have the right policy on the conn, we don't
535  * have to lookup global policy for every outbound and inbound datagram
536  * and thus serving as an optimization. Note that a global policy change
537  * does not affect fully connected sockets if they have policy. If fully
538  * connected sockets did not have any policy associated with it, global
539  * policy change may affect them.
540  *
541  * IP Flow control notes:
542  *
543  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
544  * cannot be sent down to the driver by IP, because of a canput failure, IP
545  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
546  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
547  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
548  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
549  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
550  * the queued messages, and removes the conn from the drain list, if all
551  * messages were drained. It also qenables the next conn in the drain list to
552  * continue the drain process.
553  *
554  * In reality the drain list is not a single list, but a configurable number
555  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
556  * list. If the ip_wsrv of the next qenabled conn does not run, because the
557  * stream closes, ip_close takes responsibility to qenable the next conn in
558  * the drain list. The directly called ip_wput path always does a putq, if
559  * it cannot putnext. Thus synchronization problems are handled between
560  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
561  * functions that manipulate this drain list. Furthermore conn_drain_insert
562  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
563  * running on a queue at any time. conn_drain_tail can be simultaneously called
564  * from both ip_wsrv and ip_close.
565  *
566  * IPQOS notes:
567  *
568  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
569  * and IPQoS modules. IPPF includes hooks in IP at different control points
570  * (callout positions) which direct packets to IPQoS modules for policy
571  * processing. Policies, if present, are global.
572  *
573  * The callout positions are located in the following paths:
574  *		o local_in (packets destined for this host)
575  *		o local_out (packets orginating from this host )
576  *		o fwd_in  (packets forwarded by this m/c - inbound)
577  *		o fwd_out (packets forwarded by this m/c - outbound)
578  * Hooks at these callout points can be enabled/disabled using the ndd variable
579  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
580  * By default all the callout positions are enabled.
581  *
582  * Outbound (local_out)
583  * Hooks are placed in ip_wput_ire and ipsec_out_process.
584  *
585  * Inbound (local_in)
586  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
587  * TCP and UDP fanout routines.
588  *
589  * Forwarding (in and out)
590  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
591  *
592  * IP Policy Framework processing (IPPF processing)
593  * Policy processing for a packet is initiated by ip_process, which ascertains
594  * that the classifier (ipgpc) is loaded and configured, failing which the
595  * packet resumes normal processing in IP. If the clasifier is present, the
596  * packet is acted upon by one or more IPQoS modules (action instances), per
597  * filters configured in ipgpc and resumes normal IP processing thereafter.
598  * An action instance can drop a packet in course of its processing.
599  *
600  * A boolean variable, ip_policy, is used in all the fanout routines that can
601  * invoke ip_process for a packet. This variable indicates if the packet should
602  * to be sent for policy processing. The variable is set to B_TRUE by default,
603  * i.e. when the routines are invoked in the normal ip procesing path for a
604  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
605  * ip_policy is set to B_FALSE for all the routines called in these two
606  * functions because, in the former case,  we don't process loopback traffic
607  * currently while in the latter, the packets have already been processed in
608  * icmp_inbound.
609  *
610  * Zones notes:
611  *
612  * The partitioning rules for networking are as follows:
613  * 1) Packets coming from a zone must have a source address belonging to that
614  * zone.
615  * 2) Packets coming from a zone can only be sent on a physical interface on
616  * which the zone has an IP address.
617  * 3) Between two zones on the same machine, packet delivery is only allowed if
618  * there's a matching route for the destination and zone in the forwarding
619  * table.
620  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
621  * different zones can bind to the same port with the wildcard address
622  * (INADDR_ANY).
623  *
624  * The granularity of interface partitioning is at the logical interface level.
625  * Therefore, every zone has its own IP addresses, and incoming packets can be
626  * attributed to a zone unambiguously. A logical interface is placed into a zone
627  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
628  * structure. Rule (1) is implemented by modifying the source address selection
629  * algorithm so that the list of eligible addresses is filtered based on the
630  * sending process zone.
631  *
632  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
633  * across all zones, depending on their type. Here is the break-up:
634  *
635  * IRE type				Shared/exclusive
636  * --------				----------------
637  * IRE_BROADCAST			Exclusive
638  * IRE_DEFAULT (default routes)		Shared (*)
639  * IRE_LOCAL				Exclusive (x)
640  * IRE_LOOPBACK				Exclusive
641  * IRE_PREFIX (net routes)		Shared (*)
642  * IRE_CACHE				Exclusive
643  * IRE_IF_NORESOLVER (interface routes)	Exclusive
644  * IRE_IF_RESOLVER (interface routes)	Exclusive
645  * IRE_HOST (host routes)		Shared (*)
646  *
647  * (*) A zone can only use a default or off-subnet route if the gateway is
648  * directly reachable from the zone, that is, if the gateway's address matches
649  * one of the zone's logical interfaces.
650  *
651  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
652  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
653  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
654  * address of the zone itself (the destination). Since IRE_LOCAL is used
655  * for communication between zones, ip_wput_ire has special logic to set
656  * the right source address when sending using an IRE_LOCAL.
657  *
658  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
659  * ire_cache_lookup restricts loopback using an IRE_LOCAL
660  * between zone to the case when L2 would have conceptually looped the packet
661  * back, i.e. the loopback which is required since neither Ethernet drivers
662  * nor Ethernet hardware loops them back. This is the case when the normal
663  * routes (ignoring IREs with different zoneids) would send out the packet on
664  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
665  * associated.
666  *
667  * Multiple zones can share a common broadcast address; typically all zones
668  * share the 255.255.255.255 address. Incoming as well as locally originated
669  * broadcast packets must be dispatched to all the zones on the broadcast
670  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
671  * since some zones may not be on the 10.16.72/24 network. To handle this, each
672  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
673  * sent to every zone that has an IRE_BROADCAST entry for the destination
674  * address on the input ill, see conn_wantpacket().
675  *
676  * Applications in different zones can join the same multicast group address.
677  * For IPv4, group memberships are per-logical interface, so they're already
678  * inherently part of a zone. For IPv6, group memberships are per-physical
679  * interface, so we distinguish IPv6 group memberships based on group address,
680  * interface and zoneid. In both cases, received multicast packets are sent to
681  * every zone for which a group membership entry exists. On IPv6 we need to
682  * check that the target zone still has an address on the receiving physical
683  * interface; it could have been removed since the application issued the
684  * IPV6_JOIN_GROUP.
685  */
686 
687 /*
688  * Squeue Fanout flags:
689  *	0: No fanout.
690  *	1: Fanout across all squeues
691  */
692 boolean_t	ip_squeue_fanout = 0;
693 
694 /*
695  * Maximum dups allowed per packet.
696  */
697 uint_t ip_max_frag_dups = 10;
698 
699 #define	IS_SIMPLE_IPH(ipha)						\
700 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
701 
702 /* RFC1122 Conformance */
703 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
704 
705 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
706 
707 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
708 
709 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
710 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
711 
712 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
723 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
724 		    zoneid_t zoneid);
725 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
726 static void	icmp_redirect(mblk_t *);
727 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
728 
729 static void	ip_arp_news(queue_t *, mblk_t *);
730 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
731 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
732 char		*ip_dot_addr(ipaddr_t, char *);
733 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
734 int		ip_close(queue_t *, int);
735 static char	*ip_dot_saddr(uchar_t *, char *);
736 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
737 		    boolean_t, boolean_t, ill_t *, zoneid_t);
738 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, zoneid_t);
740 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
741 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
742 static void	ip_lrput(queue_t *, mblk_t *);
743 ipaddr_t	ip_massage_options(ipha_t *);
744 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
747 		    zoneid_t);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
755 			    size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
762 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
763 			    ire_t *);
764 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
765 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
766 		    uint16_t *);
767 int		ip_snmp_get(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
783 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
784 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
785 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
786 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
787 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
788 static boolean_t	ip_source_routed(ipha_t *);
789 static boolean_t	ip_source_route_included(ipha_t *);
790 
791 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
792 		    zoneid_t);
793 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
794 static void	ip_wput_local_options(ipha_t *);
795 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
796 		    zoneid_t);
797 
798 static void	conn_drain_init(void);
799 static void	conn_drain_fini(void);
800 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
801 
802 static void	conn_walk_drain(void);
803 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
804     zoneid_t);
805 
806 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
807     zoneid_t);
808 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
809     void *dummy_arg);
810 
811 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
812 
813 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
814     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
815     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
816 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
817 
818 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
819 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
820     caddr_t, cred_t *);
821 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
822     caddr_t cp, cred_t *cr);
823 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
824     cred_t *);
825 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
826     caddr_t cp, cred_t *cr);
827 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
828     cred_t *);
829 static squeue_func_t ip_squeue_switch(int);
830 
831 static void	ip_kstat_init(void);
832 static void	ip_kstat_fini(void);
833 static int	ip_kstat_update(kstat_t *kp, int rw);
834 static void	icmp_kstat_init(void);
835 static void	icmp_kstat_fini(void);
836 static int	icmp_kstat_update(kstat_t *kp, int rw);
837 
838 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
839 
840 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
841     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
842 
843 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
844     ipha_t *, ill_t *, boolean_t);
845 
846 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
847 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
848 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
849 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
850 
851 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
852 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
853 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
854 
855 /* How long, in seconds, we allow frags to hang around. */
856 #define	IP_FRAG_TIMEOUT	60
857 
858 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
859 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
860 
861 /*
862  * Threshold which determines whether MDT should be used when
863  * generating IP fragments; payload size must be greater than
864  * this threshold for MDT to take place.
865  */
866 #define	IP_WPUT_FRAG_MDT_MIN	32768
867 
868 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
869 
870 /* Protected by ip_mi_lock */
871 static void	*ip_g_head;		/* Instance Data List Head */
872 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
873 
874 /* Only modified during _init and _fini thus no locking is needed. */
875 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
876 
877 
878 static long ip_rput_pullups;
879 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
880 
881 vmem_t *ip_minor_arena;
882 
883 /*
884  * MIB-2 stuff for SNMP (both IP and ICMP)
885  */
886 mib2_ip_t	ip_mib;
887 mib2_icmp_t	icmp_mib;
888 
889 #ifdef DEBUG
890 uint32_t ipsechw_debug = 0;
891 #endif
892 
893 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
894 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
895 
896 uint_t	loopback_packets = 0;
897 
898 /*
899  * Multirouting/CGTP stuff
900  */
901 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
902 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
903 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
904 /* Interval (in ms) between consecutive 'bad MTU' warnings */
905 hrtime_t ip_multirt_log_interval = 1000;
906 /* Time since last warning issued. */
907 static hrtime_t	multirt_bad_mtu_last_time = 0;
908 
909 kmutex_t ip_trash_timer_lock;
910 krwlock_t ip_g_nd_lock;
911 
912 /*
913  * XXX following really should only be in a header. Would need more
914  * header and .c clean up first.
915  */
916 extern optdb_obj_t	ip_opt_obj;
917 
918 ulong_t ip_squeue_enter_unbound = 0;
919 
920 /*
921  * Named Dispatch Parameter Table.
922  * All of these are alterable, within the min/max values given, at run time.
923  */
924 static ipparam_t	lcl_param_arr[] = {
925 	/* min	max	value	name */
926 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
928 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp"},
930 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
931 	{  0,	1,	1,	"ip_send_redirects"},
932 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
933 	{  0,	10,	0,	"ip_debug"},
934 	{  0,	10,	0,	"ip_mrtdebug"},
935 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
936 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
937 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
938 	{  1,	255,	255,	"ip_def_ttl" },
939 	{  0,	1,	0,	"ip_forward_src_routed"},
940 	{  0,	256,	32,	"ip_wroff_extra" },
941 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
942 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
943 	{  0,	1,	1,	"ip_path_mtu_discovery" },
944 	{  0,	240,	30,	"ip_ignore_delete_time" },
945 	{  0,	1,	0,	"ip_ignore_redirect" },
946 	{  0,	1,	1,	"ip_output_queue" },
947 	{  1,	254,	1,	"ip_broadcast_ttl" },
948 	{  0,	99999,	100,	"ip_icmp_err_interval" },
949 	{  1,	99999,	10,	"ip_icmp_err_burst" },
950 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
951 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
952 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
953 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
954 	{  0,	1,	1,	"icmp_accept_clear_messages" },
955 	{  0,	1,	1,	"igmp_accept_clear_messages" },
956 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
957 				"ip_ndp_delay_first_probe_time"},
958 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
959 				"ip_ndp_max_unicast_solicit"},
960 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
961 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
962 	{  0,	1,	0,	"ip6_forward_src_routed"},
963 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
964 	{  0,	1,	1,	"ip6_send_redirects"},
965 	{  0,	1,	0,	"ip6_ignore_redirect" },
966 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
967 
968 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
969 
970 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
971 
972 	{  0,	1,	1,	"pim_accept_clear_messages" },
973 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
974 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
975 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
976 	{  0,	15,	0,	"ip_policy_mask" },
977 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
978 	{  0,	255,	1,	"ip_multirt_ttl" },
979 	{  0,	1,	1,	"ip_multidata_outbound" },
980 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
981 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
982 	{  0,	1000,	1,	"ip_max_temp_defend" },
983 	{  0,	1000,	3,	"ip_max_defend" },
984 	{  0,	999999,	30,	"ip_defend_interval" },
985 	{  0,	3600000, 300000, "ip_dup_recovery" },
986 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
987 	{  0,	1,	1,	"ip_lso_outbound" },
988 #ifdef DEBUG
989 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
990 #endif
991 };
992 
993 ipparam_t	*ip_param_arr = lcl_param_arr;
994 
995 /* Extended NDP table */
996 static ipndp_t	lcl_ndp_arr[] = {
997 	/* getf			setf		data			name */
998 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
999 	    "ip_forwarding" },
1000 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
1001 	    "ip6_forwarding" },
1002 	{  ip_ill_report,	NULL,		NULL,
1003 	    "ip_ill_status" },
1004 	{  ip_ipif_report,	NULL,		NULL,
1005 	    "ip_ipif_status" },
1006 	{  ip_ire_report,	NULL,		NULL,
1007 	    "ipv4_ire_status" },
1008 	{  ip_ire_report_mrtun,	NULL,		NULL,
1009 	    "ipv4_mrtun_ire_status" },
1010 	{  ip_ire_report_srcif,	NULL,		NULL,
1011 	    "ipv4_srcif_ire_status" },
1012 	{  ip_ire_report_v6,	NULL,		NULL,
1013 	    "ipv6_ire_status" },
1014 	{  ip_conn_report,	NULL,		NULL,
1015 	    "ip_conn_status" },
1016 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1017 	    "ip_rput_pullups" },
1018 	{  ndp_report,		NULL,		NULL,
1019 	    "ip_ndp_cache_report" },
1020 	{  ip_srcid_report,	NULL,		NULL,
1021 	    "ip_srcid_status" },
1022 	{ ip_param_generic_get, ip_squeue_profile_set,
1023 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1024 	{ ip_param_generic_get, ip_squeue_bind_set,
1025 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1026 	{ ip_param_generic_get, ip_input_proc_set,
1027 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1028 	{ ip_param_generic_get, ip_int_set,
1029 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1030 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1031 	    "ip_cgtp_filter" },
1032 	{ ip_param_generic_get, ip_int_set,
1033 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1034 };
1035 
1036 /*
1037  * ip_g_forward controls IP forwarding.  It takes two values:
1038  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1039  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1040  *
1041  * RFC1122 says there must be a configuration switch to control forwarding,
1042  * but that the default MUST be to not forward packets ever.  Implicit
1043  * control based on configuration of multiple interfaces MUST NOT be
1044  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1045  * and, in fact, it was the default.  That capability is now provided in the
1046  * /etc/rc2.d/S69inet script.
1047  */
1048 int ip_g_forward = IP_FORWARD_DEFAULT;
1049 
1050 /* It also has an IPv6 counterpart. */
1051 
1052 int ipv6_forward = IP_FORWARD_DEFAULT;
1053 
1054 /*
1055  * Table of IP ioctls encoding the various properties of the ioctl and
1056  * indexed based on the last byte of the ioctl command. Occasionally there
1057  * is a clash, and there is more than 1 ioctl with the same last byte.
1058  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1059  * ioctls are encoded in the misc table. An entry in the ndx table is
1060  * retrieved by indexing on the last byte of the ioctl command and comparing
1061  * the ioctl command with the value in the ndx table. In the event of a
1062  * mismatch the misc table is then searched sequentially for the desired
1063  * ioctl command.
1064  *
1065  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1066  */
1067 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1068 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1080 			MISC_CMD, ip_siocaddrt, NULL },
1081 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1082 			MISC_CMD, ip_siocdelrt, NULL },
1083 
1084 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1086 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1087 			IF_CMD, ip_sioctl_get_addr, NULL },
1088 
1089 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1090 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1091 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1092 			IPI_GET_CMD | IPI_REPL,
1093 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1094 
1095 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1096 			IPI_PRIV | IPI_WR | IPI_REPL,
1097 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1098 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1099 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1100 			IF_CMD, ip_sioctl_get_flags, NULL },
1101 
1102 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 
1105 	/* copyin size cannot be coded for SIOCGIFCONF */
1106 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1107 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1108 
1109 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1110 			IF_CMD, ip_sioctl_mtu, NULL },
1111 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1112 			IF_CMD, ip_sioctl_get_mtu, NULL },
1113 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1114 			IPI_GET_CMD | IPI_REPL,
1115 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1116 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1117 			IF_CMD, ip_sioctl_brdaddr, NULL },
1118 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1119 			IPI_GET_CMD | IPI_REPL,
1120 			IF_CMD, ip_sioctl_get_netmask, NULL },
1121 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1122 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1123 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1124 			IPI_GET_CMD | IPI_REPL,
1125 			IF_CMD, ip_sioctl_get_metric, NULL },
1126 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1127 			IF_CMD, ip_sioctl_metric, NULL },
1128 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 
1130 	/* See 166-168 below for extended SIOC*XARP ioctls */
1131 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1132 			MISC_CMD, ip_sioctl_arp, NULL },
1133 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1134 			MISC_CMD, ip_sioctl_arp, NULL },
1135 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1136 			MISC_CMD, ip_sioctl_arp, NULL },
1137 
1138 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 
1160 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1161 			MISC_CMD, if_unitsel, if_unitsel_restart },
1162 
1163 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 
1182 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1183 			IPI_PRIV | IPI_WR | IPI_MODOK,
1184 			IF_CMD, ip_sioctl_sifname, NULL },
1185 
1186 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 
1200 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1201 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1202 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1203 			IF_CMD, ip_sioctl_get_muxid, NULL },
1204 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1205 			IPI_PRIV | IPI_WR | IPI_REPL,
1206 			IF_CMD, ip_sioctl_muxid, NULL },
1207 
1208 	/* Both if and lif variants share same func */
1209 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1210 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1211 	/* Both if and lif variants share same func */
1212 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1213 			IPI_PRIV | IPI_WR | IPI_REPL,
1214 			IF_CMD, ip_sioctl_slifindex, NULL },
1215 
1216 	/* copyin size cannot be coded for SIOCGIFCONF */
1217 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1218 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1219 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 
1237 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1238 			IPI_PRIV | IPI_WR | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_removeif,
1240 			ip_sioctl_removeif_restart },
1241 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1242 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_addif, NULL },
1244 #define	SIOCLIFADDR_NDX 112
1245 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1247 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1248 			IPI_GET_CMD | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_get_addr, NULL },
1250 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1252 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1253 			IPI_GET_CMD | IPI_REPL,
1254 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1255 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1256 			IPI_PRIV | IPI_WR | IPI_REPL,
1257 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1258 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1259 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1260 			LIF_CMD, ip_sioctl_get_flags, NULL },
1261 
1262 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1264 
1265 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1266 			ip_sioctl_get_lifconf, NULL },
1267 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1268 			LIF_CMD, ip_sioctl_mtu, NULL },
1269 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1271 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1272 			IPI_GET_CMD | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1274 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1275 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1276 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1279 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1280 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1281 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1282 			IPI_GET_CMD | IPI_REPL,
1283 			LIF_CMD, ip_sioctl_get_metric, NULL },
1284 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_metric, NULL },
1286 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1287 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1288 			LIF_CMD, ip_sioctl_slifname,
1289 			ip_sioctl_slifname_restart },
1290 
1291 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1292 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1293 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1294 			IPI_GET_CMD | IPI_REPL,
1295 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1296 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1297 			IPI_PRIV | IPI_WR | IPI_REPL,
1298 			LIF_CMD, ip_sioctl_muxid, NULL },
1299 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1300 			IPI_GET_CMD | IPI_REPL,
1301 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1302 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1303 			IPI_PRIV | IPI_WR | IPI_REPL,
1304 			LIF_CMD, ip_sioctl_slifindex, 0 },
1305 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1306 			LIF_CMD, ip_sioctl_token, NULL },
1307 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1308 			IPI_GET_CMD | IPI_REPL,
1309 			LIF_CMD, ip_sioctl_get_token, NULL },
1310 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1311 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1312 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1313 			IPI_GET_CMD | IPI_REPL,
1314 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1315 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1316 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1317 
1318 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1319 			IPI_GET_CMD | IPI_REPL,
1320 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1321 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1322 			LIF_CMD, ip_siocdelndp_v6, NULL },
1323 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1324 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1325 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1326 			LIF_CMD, ip_siocsetndp_v6, NULL },
1327 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1328 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1329 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1330 			MISC_CMD, ip_sioctl_tonlink, NULL },
1331 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1332 			MISC_CMD, ip_sioctl_tmysite, NULL },
1333 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1334 			TUN_CMD, ip_sioctl_tunparam, NULL },
1335 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1336 			IPI_PRIV | IPI_WR,
1337 			TUN_CMD, ip_sioctl_tunparam, NULL },
1338 
1339 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1340 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1343 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1344 
1345 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1346 			IPI_PRIV | IPI_WR | IPI_REPL,
1347 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1348 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1349 			IPI_PRIV | IPI_WR | IPI_REPL,
1350 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1351 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1352 			IPI_PRIV | IPI_WR,
1353 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1354 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1355 			IPI_GET_CMD | IPI_REPL,
1356 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1357 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1358 			IPI_GET_CMD | IPI_REPL,
1359 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1360 
1361 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1362 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1364 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1365 
1366 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1367 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1368 
1369 	/* These are handled in ip_sioctl_copyin_setup itself */
1370 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1371 			MISC_CMD, NULL, NULL },
1372 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1373 			MISC_CMD, NULL, NULL },
1374 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1375 
1376 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1377 			ip_sioctl_get_lifconf, NULL },
1378 
1379 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1380 			MISC_CMD, ip_sioctl_xarp, NULL },
1381 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1382 			MISC_CMD, ip_sioctl_xarp, NULL },
1383 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1384 			MISC_CMD, ip_sioctl_xarp, NULL },
1385 
1386 	/* SIOCPOPSOCKFS is not handled by IP */
1387 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1388 
1389 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1390 			IPI_GET_CMD | IPI_REPL,
1391 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1392 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1393 			IPI_PRIV | IPI_WR | IPI_REPL,
1394 			LIF_CMD, ip_sioctl_slifzone,
1395 			ip_sioctl_slifzone_restart },
1396 	/* 172-174 are SCTP ioctls and not handled by IP */
1397 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1399 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1400 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1401 			IPI_GET_CMD, LIF_CMD,
1402 			ip_sioctl_get_lifusesrc, 0 },
1403 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1404 			IPI_PRIV | IPI_WR,
1405 			LIF_CMD, ip_sioctl_slifusesrc,
1406 			NULL },
1407 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1408 			ip_sioctl_get_lifsrcof, NULL },
1409 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1410 			MISC_CMD, ip_sioctl_msfilter, NULL },
1411 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1412 			MISC_CMD, ip_sioctl_msfilter, NULL },
1413 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1416 			MISC_CMD, ip_sioctl_msfilter, NULL },
1417 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1418 			ip_sioctl_set_ipmpfailback, NULL }
1419 };
1420 
1421 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1422 
1423 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1424 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1425 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1426 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1427 		TUN_CMD, ip_sioctl_tunparam, NULL },
1428 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1433 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1434 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1435 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1436 		MISC_CMD, mrt_ioctl},
1437 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1438 		MISC_CMD, mrt_ioctl},
1439 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1440 		MISC_CMD, mrt_ioctl}
1441 };
1442 
1443 int ip_misc_ioctl_count =
1444     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1445 
1446 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1447 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1448 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1449 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1450 					/* Settable in /etc/system */
1451 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1452 
1453 /* Defined in ip_ire.c */
1454 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1455 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1456 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1457 
1458 static nv_t	ire_nv_arr[] = {
1459 	{ IRE_BROADCAST, "BROADCAST" },
1460 	{ IRE_LOCAL, "LOCAL" },
1461 	{ IRE_LOOPBACK, "LOOPBACK" },
1462 	{ IRE_CACHE, "CACHE" },
1463 	{ IRE_DEFAULT, "DEFAULT" },
1464 	{ IRE_PREFIX, "PREFIX" },
1465 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1466 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1467 	{ IRE_HOST, "HOST" },
1468 	{ 0 }
1469 };
1470 
1471 nv_t	*ire_nv_tbl = ire_nv_arr;
1472 
1473 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1474 extern krwlock_t ipsec_capab_ills_lock;
1475 
1476 /* Defined in ip_netinfo.c */
1477 extern ddi_taskq_t	*eventq_queue_nic;
1478 
1479 /* Packet dropper for IP IPsec processing failures */
1480 ipdropper_t ip_dropper;
1481 
1482 /* Simple ICMP IP Header Template */
1483 static ipha_t icmp_ipha = {
1484 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1485 };
1486 
1487 struct module_info ip_mod_info = {
1488 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1489 };
1490 
1491 /*
1492  * Duplicate static symbols within a module confuses mdb; so we avoid the
1493  * problem by making the symbols here distinct from those in udp.c.
1494  */
1495 
1496 static struct qinit iprinit = {
1497 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1498 	&ip_mod_info
1499 };
1500 
1501 static struct qinit ipwinit = {
1502 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1503 	&ip_mod_info
1504 };
1505 
1506 static struct qinit iplrinit = {
1507 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1508 	&ip_mod_info
1509 };
1510 
1511 static struct qinit iplwinit = {
1512 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1513 	&ip_mod_info
1514 };
1515 
1516 struct streamtab ipinfo = {
1517 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1518 };
1519 
1520 #ifdef	DEBUG
1521 static boolean_t skip_sctp_cksum = B_FALSE;
1522 #endif
1523 
1524 /*
1525  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1526  * ip_rput_v6(), ip_output(), etc.  If the message
1527  * block already has a M_CTL at the front of it, then simply set the zoneid
1528  * appropriately.
1529  */
1530 mblk_t *
1531 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1532 {
1533 	mblk_t		*first_mp;
1534 	ipsec_out_t	*io;
1535 
1536 	ASSERT(zoneid != ALL_ZONES);
1537 	if (mp->b_datap->db_type == M_CTL) {
1538 		io = (ipsec_out_t *)mp->b_rptr;
1539 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1540 		io->ipsec_out_zoneid = zoneid;
1541 		return (mp);
1542 	}
1543 
1544 	first_mp = ipsec_alloc_ipsec_out();
1545 	if (first_mp == NULL)
1546 		return (NULL);
1547 	io = (ipsec_out_t *)first_mp->b_rptr;
1548 	/* This is not a secure packet */
1549 	io->ipsec_out_secure = B_FALSE;
1550 	io->ipsec_out_zoneid = zoneid;
1551 	first_mp->b_cont = mp;
1552 	return (first_mp);
1553 }
1554 
1555 /*
1556  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1557  */
1558 mblk_t *
1559 ip_copymsg(mblk_t *mp)
1560 {
1561 	mblk_t *nmp;
1562 	ipsec_info_t *in;
1563 
1564 	if (mp->b_datap->db_type != M_CTL)
1565 		return (copymsg(mp));
1566 
1567 	in = (ipsec_info_t *)mp->b_rptr;
1568 
1569 	/*
1570 	 * Note that M_CTL is also used for delivering ICMP error messages
1571 	 * upstream to transport layers.
1572 	 */
1573 	if (in->ipsec_info_type != IPSEC_OUT &&
1574 	    in->ipsec_info_type != IPSEC_IN)
1575 		return (copymsg(mp));
1576 
1577 	nmp = copymsg(mp->b_cont);
1578 
1579 	if (in->ipsec_info_type == IPSEC_OUT)
1580 		return (ipsec_out_tag(mp, nmp));
1581 	else
1582 		return (ipsec_in_tag(mp, nmp));
1583 }
1584 
1585 /* Generate an ICMP fragmentation needed message. */
1586 static void
1587 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1588 {
1589 	icmph_t	icmph;
1590 	mblk_t *first_mp;
1591 	boolean_t mctl_present;
1592 
1593 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1594 
1595 	if (!(mp = icmp_pkt_err_ok(mp))) {
1596 		if (mctl_present)
1597 			freeb(first_mp);
1598 		return;
1599 	}
1600 
1601 	bzero(&icmph, sizeof (icmph_t));
1602 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1603 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1604 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1605 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1606 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1607 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1608 }
1609 
1610 /*
1611  * icmp_inbound deals with ICMP messages in the following ways.
1612  *
1613  * 1) It needs to send a reply back and possibly delivering it
1614  *    to the "interested" upper clients.
1615  * 2) It needs to send it to the upper clients only.
1616  * 3) It needs to change some values in IP only.
1617  * 4) It needs to change some values in IP and upper layers e.g TCP.
1618  *
1619  * We need to accomodate icmp messages coming in clear until we get
1620  * everything secure from the wire. If icmp_accept_clear_messages
1621  * is zero we check with the global policy and act accordingly. If
1622  * it is non-zero, we accept the message without any checks. But
1623  * *this does not mean* that this will be delivered to the upper
1624  * clients. By accepting we might send replies back, change our MTU
1625  * value etc. but delivery to the ULP/clients depends on their policy
1626  * dispositions.
1627  *
1628  * We handle the above 4 cases in the context of IPSEC in the
1629  * following way :
1630  *
1631  * 1) Send the reply back in the same way as the request came in.
1632  *    If it came in encrypted, it goes out encrypted. If it came in
1633  *    clear, it goes out in clear. Thus, this will prevent chosen
1634  *    plain text attack.
1635  * 2) The client may or may not expect things to come in secure.
1636  *    If it comes in secure, the policy constraints are checked
1637  *    before delivering it to the upper layers. If it comes in
1638  *    clear, ipsec_inbound_accept_clear will decide whether to
1639  *    accept this in clear or not. In both the cases, if the returned
1640  *    message (IP header + 8 bytes) that caused the icmp message has
1641  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1642  *    sending up. If there are only 8 bytes of returned message, then
1643  *    upper client will not be notified.
1644  * 3) Check with global policy to see whether it matches the constaints.
1645  *    But this will be done only if icmp_accept_messages_in_clear is
1646  *    zero.
1647  * 4) If we need to change both in IP and ULP, then the decision taken
1648  *    while affecting the values in IP and while delivering up to TCP
1649  *    should be the same.
1650  *
1651  * 	There are two cases.
1652  *
1653  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1654  *	   failed), we will not deliver it to the ULP, even though they
1655  *	   are *willing* to accept in *clear*. This is fine as our global
1656  *	   disposition to icmp messages asks us reject the datagram.
1657  *
1658  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1659  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1660  *	   to deliver it to ULP (policy failed), it can lead to
1661  *	   consistency problems. The cases known at this time are
1662  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1663  *	   values :
1664  *
1665  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1666  *	     and Upper layer rejects. Then the communication will
1667  *	     come to a stop. This is solved by making similar decisions
1668  *	     at both levels. Currently, when we are unable to deliver
1669  *	     to the Upper Layer (due to policy failures) while IP has
1670  *	     adjusted ire_max_frag, the next outbound datagram would
1671  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1672  *	     will be with the right level of protection. Thus the right
1673  *	     value will be communicated even if we are not able to
1674  *	     communicate when we get from the wire initially. But this
1675  *	     assumes there would be at least one outbound datagram after
1676  *	     IP has adjusted its ire_max_frag value. To make things
1677  *	     simpler, we accept in clear after the validation of
1678  *	     AH/ESP headers.
1679  *
1680  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1681  *	     upper layer depending on the level of protection the upper
1682  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1683  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1684  *	     should be accepted in clear when the Upper layer expects secure.
1685  *	     Thus the communication may get aborted by some bad ICMP
1686  *	     packets.
1687  *
1688  * IPQoS Notes:
1689  * The only instance when a packet is sent for processing is when there
1690  * isn't an ICMP client and if we are interested in it.
1691  * If there is a client, IPPF processing will take place in the
1692  * ip_fanout_proto routine.
1693  *
1694  * Zones notes:
1695  * The packet is only processed in the context of the specified zone: typically
1696  * only this zone will reply to an echo request, and only interested clients in
1697  * this zone will receive a copy of the packet. This means that the caller must
1698  * call icmp_inbound() for each relevant zone.
1699  */
1700 static void
1701 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1702     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1703     ill_t *recv_ill, zoneid_t zoneid)
1704 {
1705 	icmph_t	*icmph;
1706 	ipha_t	*ipha;
1707 	int	iph_hdr_length;
1708 	int	hdr_length;
1709 	boolean_t	interested;
1710 	uint32_t	ts;
1711 	uchar_t	*wptr;
1712 	ipif_t	*ipif;
1713 	mblk_t *first_mp;
1714 	ipsec_in_t *ii;
1715 	ire_t *src_ire;
1716 	boolean_t onlink;
1717 	timestruc_t now;
1718 	uint32_t ill_index;
1719 
1720 	ASSERT(ill != NULL);
1721 
1722 	first_mp = mp;
1723 	if (mctl_present) {
1724 		mp = first_mp->b_cont;
1725 		ASSERT(mp != NULL);
1726 	}
1727 
1728 	ipha = (ipha_t *)mp->b_rptr;
1729 	if (icmp_accept_clear_messages == 0) {
1730 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1731 		    ipha, NULL, mctl_present);
1732 		if (first_mp == NULL)
1733 			return;
1734 	}
1735 
1736 	/*
1737 	 * On a labeled system, we have to check whether the zone itself is
1738 	 * permitted to receive raw traffic.
1739 	 */
1740 	if (is_system_labeled()) {
1741 		if (zoneid == ALL_ZONES)
1742 			zoneid = tsol_packet_to_zoneid(mp);
1743 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1744 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1745 			    zoneid));
1746 			BUMP_MIB(&icmp_mib, icmpInErrors);
1747 			freemsg(first_mp);
1748 			return;
1749 		}
1750 	}
1751 
1752 	/*
1753 	 * We have accepted the ICMP message. It means that we will
1754 	 * respond to the packet if needed. It may not be delivered
1755 	 * to the upper client depending on the policy constraints
1756 	 * and the disposition in ipsec_inbound_accept_clear.
1757 	 */
1758 
1759 	ASSERT(ill != NULL);
1760 
1761 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1762 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1763 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1764 		/* Last chance to get real. */
1765 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1766 			BUMP_MIB(&icmp_mib, icmpInErrors);
1767 			freemsg(first_mp);
1768 			return;
1769 		}
1770 		/* Refresh iph following the pullup. */
1771 		ipha = (ipha_t *)mp->b_rptr;
1772 	}
1773 	/* ICMP header checksum, including checksum field, should be zero. */
1774 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1775 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1776 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1777 		freemsg(first_mp);
1778 		return;
1779 	}
1780 	/* The IP header will always be a multiple of four bytes */
1781 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1782 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1783 	    icmph->icmph_code));
1784 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1785 	/* We will set "interested" to "true" if we want a copy */
1786 	interested = B_FALSE;
1787 	switch (icmph->icmph_type) {
1788 	case ICMP_ECHO_REPLY:
1789 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1790 		break;
1791 	case ICMP_DEST_UNREACHABLE:
1792 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1793 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1794 		interested = B_TRUE;	/* Pass up to transport */
1795 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1796 		break;
1797 	case ICMP_SOURCE_QUENCH:
1798 		interested = B_TRUE;	/* Pass up to transport */
1799 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1800 		break;
1801 	case ICMP_REDIRECT:
1802 		if (!ip_ignore_redirect)
1803 			interested = B_TRUE;
1804 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1805 		break;
1806 	case ICMP_ECHO_REQUEST:
1807 		/*
1808 		 * Whether to respond to echo requests that come in as IP
1809 		 * broadcasts or as IP multicast is subject to debate
1810 		 * (what isn't?).  We aim to please, you pick it.
1811 		 * Default is do it.
1812 		 */
1813 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1814 			/* unicast: always respond */
1815 			interested = B_TRUE;
1816 		} else if (CLASSD(ipha->ipha_dst)) {
1817 			/* multicast: respond based on tunable */
1818 			interested = ip_g_resp_to_echo_mcast;
1819 		} else if (broadcast) {
1820 			/* broadcast: respond based on tunable */
1821 			interested = ip_g_resp_to_echo_bcast;
1822 		}
1823 		BUMP_MIB(&icmp_mib, icmpInEchos);
1824 		break;
1825 	case ICMP_ROUTER_ADVERTISEMENT:
1826 	case ICMP_ROUTER_SOLICITATION:
1827 		break;
1828 	case ICMP_TIME_EXCEEDED:
1829 		interested = B_TRUE;	/* Pass up to transport */
1830 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1831 		break;
1832 	case ICMP_PARAM_PROBLEM:
1833 		interested = B_TRUE;	/* Pass up to transport */
1834 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1835 		break;
1836 	case ICMP_TIME_STAMP_REQUEST:
1837 		/* Response to Time Stamp Requests is local policy. */
1838 		if (ip_g_resp_to_timestamp &&
1839 		    /* So is whether to respond if it was an IP broadcast. */
1840 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1841 			int tstamp_len = 3 * sizeof (uint32_t);
1842 
1843 			if (wptr +  tstamp_len > mp->b_wptr) {
1844 				if (!pullupmsg(mp, wptr + tstamp_len -
1845 				    mp->b_rptr)) {
1846 					BUMP_MIB(&ip_mib, ipInDiscards);
1847 					freemsg(first_mp);
1848 					return;
1849 				}
1850 				/* Refresh ipha following the pullup. */
1851 				ipha = (ipha_t *)mp->b_rptr;
1852 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1853 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1854 			}
1855 			interested = B_TRUE;
1856 		}
1857 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1858 		break;
1859 	case ICMP_TIME_STAMP_REPLY:
1860 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1861 		break;
1862 	case ICMP_INFO_REQUEST:
1863 		/* Per RFC 1122 3.2.2.7, ignore this. */
1864 	case ICMP_INFO_REPLY:
1865 		break;
1866 	case ICMP_ADDRESS_MASK_REQUEST:
1867 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1868 		    /* TODO m_pullup of complete header? */
1869 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1870 			interested = B_TRUE;
1871 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1872 		break;
1873 	case ICMP_ADDRESS_MASK_REPLY:
1874 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1875 		break;
1876 	default:
1877 		interested = B_TRUE;	/* Pass up to transport */
1878 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1879 		break;
1880 	}
1881 	/* See if there is an ICMP client. */
1882 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1883 		/* If there is an ICMP client and we want one too, copy it. */
1884 		mblk_t *first_mp1;
1885 
1886 		if (!interested) {
1887 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1888 			    ip_policy, recv_ill, zoneid);
1889 			return;
1890 		}
1891 		first_mp1 = ip_copymsg(first_mp);
1892 		if (first_mp1 != NULL) {
1893 			ip_fanout_proto(q, first_mp1, ill, ipha,
1894 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1895 		}
1896 	} else if (!interested) {
1897 		freemsg(first_mp);
1898 		return;
1899 	} else {
1900 		/*
1901 		 * Initiate policy processing for this packet if ip_policy
1902 		 * is true.
1903 		 */
1904 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1905 			ill_index = ill->ill_phyint->phyint_ifindex;
1906 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1907 			if (mp == NULL) {
1908 				if (mctl_present) {
1909 					freeb(first_mp);
1910 				}
1911 				BUMP_MIB(&icmp_mib, icmpInErrors);
1912 				return;
1913 			}
1914 		}
1915 	}
1916 	/* We want to do something with it. */
1917 	/* Check db_ref to make sure we can modify the packet. */
1918 	if (mp->b_datap->db_ref > 1) {
1919 		mblk_t	*first_mp1;
1920 
1921 		first_mp1 = ip_copymsg(first_mp);
1922 		freemsg(first_mp);
1923 		if (!first_mp1) {
1924 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1925 			return;
1926 		}
1927 		first_mp = first_mp1;
1928 		if (mctl_present) {
1929 			mp = first_mp->b_cont;
1930 			ASSERT(mp != NULL);
1931 		} else {
1932 			mp = first_mp;
1933 		}
1934 		ipha = (ipha_t *)mp->b_rptr;
1935 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1936 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1937 	}
1938 	switch (icmph->icmph_type) {
1939 	case ICMP_ADDRESS_MASK_REQUEST:
1940 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1941 		if (ipif == NULL) {
1942 			freemsg(first_mp);
1943 			return;
1944 		}
1945 		/*
1946 		 * outging interface must be IPv4
1947 		 */
1948 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1949 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1950 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1951 		ipif_refrele(ipif);
1952 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1953 		break;
1954 	case ICMP_ECHO_REQUEST:
1955 		icmph->icmph_type = ICMP_ECHO_REPLY;
1956 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1957 		break;
1958 	case ICMP_TIME_STAMP_REQUEST: {
1959 		uint32_t *tsp;
1960 
1961 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1962 		tsp = (uint32_t *)wptr;
1963 		tsp++;		/* Skip past 'originate time' */
1964 		/* Compute # of milliseconds since midnight */
1965 		gethrestime(&now);
1966 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1967 		    now.tv_nsec / (NANOSEC / MILLISEC);
1968 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1969 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1970 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1971 		break;
1972 	}
1973 	default:
1974 		ipha = (ipha_t *)&icmph[1];
1975 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1976 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1977 				BUMP_MIB(&ip_mib, ipInDiscards);
1978 				freemsg(first_mp);
1979 				return;
1980 			}
1981 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1982 			ipha = (ipha_t *)&icmph[1];
1983 		}
1984 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1985 			BUMP_MIB(&ip_mib, ipInDiscards);
1986 			freemsg(first_mp);
1987 			return;
1988 		}
1989 		hdr_length = IPH_HDR_LENGTH(ipha);
1990 		if (hdr_length < sizeof (ipha_t)) {
1991 			BUMP_MIB(&ip_mib, ipInDiscards);
1992 			freemsg(first_mp);
1993 			return;
1994 		}
1995 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1996 			if (!pullupmsg(mp,
1997 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1998 				BUMP_MIB(&ip_mib, ipInDiscards);
1999 				freemsg(first_mp);
2000 				return;
2001 			}
2002 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2003 			ipha = (ipha_t *)&icmph[1];
2004 		}
2005 		switch (icmph->icmph_type) {
2006 		case ICMP_REDIRECT:
2007 			/*
2008 			 * As there is no upper client to deliver, we don't
2009 			 * need the first_mp any more.
2010 			 */
2011 			if (mctl_present) {
2012 				freeb(first_mp);
2013 			}
2014 			icmp_redirect(mp);
2015 			return;
2016 		case ICMP_DEST_UNREACHABLE:
2017 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2018 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2019 				    zoneid, mp, iph_hdr_length)) {
2020 					freemsg(first_mp);
2021 					return;
2022 				}
2023 				/*
2024 				 * icmp_inbound_too_big() may alter mp.
2025 				 * Resynch ipha and icmph accordingly.
2026 				 */
2027 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2028 				ipha = (ipha_t *)&icmph[1];
2029 			}
2030 			/* FALLTHRU */
2031 		default :
2032 			/*
2033 			 * IPQoS notes: Since we have already done IPQoS
2034 			 * processing we don't want to do it again in
2035 			 * the fanout routines called by
2036 			 * icmp_inbound_error_fanout, hence the last
2037 			 * argument, ip_policy, is B_FALSE.
2038 			 */
2039 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2040 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2041 			    B_FALSE, recv_ill, zoneid);
2042 		}
2043 		return;
2044 	}
2045 	/* Send out an ICMP packet */
2046 	icmph->icmph_checksum = 0;
2047 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2048 	if (icmph->icmph_checksum == 0)
2049 		icmph->icmph_checksum = 0xFFFF;
2050 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2051 		ipif_t	*ipif_chosen;
2052 		/*
2053 		 * Make it look like it was directed to us, so we don't look
2054 		 * like a fool with a broadcast or multicast source address.
2055 		 */
2056 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2057 		/*
2058 		 * Make sure that we haven't grabbed an interface that's DOWN.
2059 		 */
2060 		if (ipif != NULL) {
2061 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2062 			    ipha->ipha_src, zoneid);
2063 			if (ipif_chosen != NULL) {
2064 				ipif_refrele(ipif);
2065 				ipif = ipif_chosen;
2066 			}
2067 		}
2068 		if (ipif == NULL) {
2069 			ip0dbg(("icmp_inbound: "
2070 			    "No source for broadcast/multicast:\n"
2071 			    "\tsrc 0x%x dst 0x%x ill %p "
2072 			    "ipif_lcl_addr 0x%x\n",
2073 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2074 			    (void *)ill,
2075 			    ill->ill_ipif->ipif_lcl_addr));
2076 			freemsg(first_mp);
2077 			return;
2078 		}
2079 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2080 		ipha->ipha_dst = ipif->ipif_src_addr;
2081 		ipif_refrele(ipif);
2082 	}
2083 	/* Reset time to live. */
2084 	ipha->ipha_ttl = ip_def_ttl;
2085 	{
2086 		/* Swap source and destination addresses */
2087 		ipaddr_t tmp;
2088 
2089 		tmp = ipha->ipha_src;
2090 		ipha->ipha_src = ipha->ipha_dst;
2091 		ipha->ipha_dst = tmp;
2092 	}
2093 	ipha->ipha_ident = 0;
2094 	if (!IS_SIMPLE_IPH(ipha))
2095 		icmp_options_update(ipha);
2096 
2097 	/*
2098 	 * ICMP echo replies should go out on the same interface
2099 	 * the request came on as probes used by in.mpathd for detecting
2100 	 * NIC failures are ECHO packets. We turn-off load spreading
2101 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2102 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2103 	 * function. This is in turn handled by ip_wput and ip_newroute
2104 	 * to make sure that the packet goes out on the interface it came
2105 	 * in on. If we don't turnoff load spreading, the packets might get
2106 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2107 	 * to go out and in.mpathd would wrongly detect a failure or
2108 	 * mis-detect a NIC failure for link failure. As load spreading
2109 	 * can happen only if ill_group is not NULL, we do only for
2110 	 * that case and this does not affect the normal case.
2111 	 *
2112 	 * We turn off load spreading only on echo packets that came from
2113 	 * on-link hosts. If the interface route has been deleted, this will
2114 	 * not be enforced as we can't do much. For off-link hosts, as the
2115 	 * default routes in IPv4 does not typically have an ire_ipif
2116 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2117 	 * Moreover, expecting a default route through this interface may
2118 	 * not be correct. We use ipha_dst because of the swap above.
2119 	 */
2120 	onlink = B_FALSE;
2121 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2122 		/*
2123 		 * First, we need to make sure that it is not one of our
2124 		 * local addresses. If we set onlink when it is one of
2125 		 * our local addresses, we will end up creating IRE_CACHES
2126 		 * for one of our local addresses. Then, we will never
2127 		 * accept packets for them afterwards.
2128 		 */
2129 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2130 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2131 		if (src_ire == NULL) {
2132 			ipif = ipif_get_next_ipif(NULL, ill);
2133 			if (ipif == NULL) {
2134 				BUMP_MIB(&ip_mib, ipInDiscards);
2135 				freemsg(mp);
2136 				return;
2137 			}
2138 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2139 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2140 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2141 			ipif_refrele(ipif);
2142 			if (src_ire != NULL) {
2143 				onlink = B_TRUE;
2144 				ire_refrele(src_ire);
2145 			}
2146 		} else {
2147 			ire_refrele(src_ire);
2148 		}
2149 	}
2150 	if (!mctl_present) {
2151 		/*
2152 		 * This packet should go out the same way as it
2153 		 * came in i.e in clear. To make sure that global
2154 		 * policy will not be applied to this in ip_wput_ire,
2155 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2156 		 */
2157 		ASSERT(first_mp == mp);
2158 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2159 			BUMP_MIB(&ip_mib, ipInDiscards);
2160 			freemsg(mp);
2161 			return;
2162 		}
2163 		ii = (ipsec_in_t *)first_mp->b_rptr;
2164 
2165 		/* This is not a secure packet */
2166 		ii->ipsec_in_secure = B_FALSE;
2167 		if (onlink) {
2168 			ii->ipsec_in_attach_if = B_TRUE;
2169 			ii->ipsec_in_ill_index =
2170 			    ill->ill_phyint->phyint_ifindex;
2171 			ii->ipsec_in_rill_index =
2172 			    recv_ill->ill_phyint->phyint_ifindex;
2173 		}
2174 		first_mp->b_cont = mp;
2175 	} else if (onlink) {
2176 		ii = (ipsec_in_t *)first_mp->b_rptr;
2177 		ii->ipsec_in_attach_if = B_TRUE;
2178 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2179 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2180 	} else {
2181 		ii = (ipsec_in_t *)first_mp->b_rptr;
2182 	}
2183 	ii->ipsec_in_zoneid = zoneid;
2184 	ASSERT(zoneid != ALL_ZONES);
2185 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2186 		BUMP_MIB(&ip_mib, ipInDiscards);
2187 		return;
2188 	}
2189 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2190 	put(WR(q), first_mp);
2191 }
2192 
2193 static ipaddr_t
2194 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2195 {
2196 	conn_t *connp;
2197 	connf_t *connfp;
2198 	ipaddr_t nexthop_addr = INADDR_ANY;
2199 	int hdr_length = IPH_HDR_LENGTH(ipha);
2200 	uint16_t *up;
2201 	uint32_t ports;
2202 
2203 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2204 	switch (ipha->ipha_protocol) {
2205 		case IPPROTO_TCP:
2206 		{
2207 			tcph_t *tcph;
2208 
2209 			/* do a reverse lookup */
2210 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2211 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2212 			    TCPS_LISTEN);
2213 			break;
2214 		}
2215 		case IPPROTO_UDP:
2216 		{
2217 			uint32_t dstport, srcport;
2218 
2219 			((uint16_t *)&ports)[0] = up[1];
2220 			((uint16_t *)&ports)[1] = up[0];
2221 
2222 			/* Extract ports in net byte order */
2223 			dstport = htons(ntohl(ports) & 0xFFFF);
2224 			srcport = htons(ntohl(ports) >> 16);
2225 
2226 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2227 			mutex_enter(&connfp->connf_lock);
2228 			connp = connfp->connf_head;
2229 
2230 			/* do a reverse lookup */
2231 			while ((connp != NULL) &&
2232 			    (!IPCL_UDP_MATCH(connp, dstport,
2233 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2234 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2235 				connp = connp->conn_next;
2236 			}
2237 			if (connp != NULL)
2238 				CONN_INC_REF(connp);
2239 			mutex_exit(&connfp->connf_lock);
2240 			break;
2241 		}
2242 		case IPPROTO_SCTP:
2243 		{
2244 			in6_addr_t map_src, map_dst;
2245 
2246 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2247 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2248 			((uint16_t *)&ports)[0] = up[1];
2249 			((uint16_t *)&ports)[1] = up[0];
2250 
2251 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2252 			    0, zoneid)) == NULL) {
2253 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2254 				    zoneid, ports, ipha);
2255 			} else {
2256 				CONN_INC_REF(connp);
2257 				SCTP_REFRELE(CONN2SCTP(connp));
2258 			}
2259 			break;
2260 		}
2261 		default:
2262 		{
2263 			ipha_t ripha;
2264 
2265 			ripha.ipha_src = ipha->ipha_dst;
2266 			ripha.ipha_dst = ipha->ipha_src;
2267 			ripha.ipha_protocol = ipha->ipha_protocol;
2268 
2269 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2270 			mutex_enter(&connfp->connf_lock);
2271 			connp = connfp->connf_head;
2272 			for (connp = connfp->connf_head; connp != NULL;
2273 			    connp = connp->conn_next) {
2274 				if (IPCL_PROTO_MATCH(connp,
2275 				    ipha->ipha_protocol, &ripha, ill,
2276 				    0, zoneid)) {
2277 					CONN_INC_REF(connp);
2278 					break;
2279 				}
2280 			}
2281 			mutex_exit(&connfp->connf_lock);
2282 		}
2283 	}
2284 	if (connp != NULL) {
2285 		if (connp->conn_nexthop_set)
2286 			nexthop_addr = connp->conn_nexthop_v4;
2287 		CONN_DEC_REF(connp);
2288 	}
2289 	return (nexthop_addr);
2290 }
2291 
2292 /* Table from RFC 1191 */
2293 static int icmp_frag_size_table[] =
2294 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2295 
2296 /*
2297  * Process received ICMP Packet too big.
2298  * After updating any IRE it does the fanout to any matching transport streams.
2299  * Assumes the message has been pulled up till the IP header that caused
2300  * the error.
2301  *
2302  * Returns B_FALSE on failure and B_TRUE on success.
2303  */
2304 static boolean_t
2305 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2306     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2307 {
2308 	ire_t	*ire, *first_ire;
2309 	int	mtu;
2310 	int	hdr_length;
2311 	ipaddr_t nexthop_addr;
2312 
2313 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2314 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2315 
2316 	hdr_length = IPH_HDR_LENGTH(ipha);
2317 
2318 	/* Drop if the original packet contained a source route */
2319 	if (ip_source_route_included(ipha)) {
2320 		return (B_FALSE);
2321 	}
2322 	/*
2323 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2324 	 * header.
2325 	 */
2326 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2327 	    mp->b_wptr) {
2328 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2329 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2330 			BUMP_MIB(&ip_mib, ipInDiscards);
2331 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2332 			return (B_FALSE);
2333 		}
2334 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2335 		ipha = (ipha_t *)&icmph[1];
2336 	}
2337 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2338 	if (nexthop_addr != INADDR_ANY) {
2339 		/* nexthop set */
2340 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2341 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2342 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2343 	} else {
2344 		/* nexthop not set */
2345 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2346 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2347 	}
2348 
2349 	if (!first_ire) {
2350 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2351 		    ntohl(ipha->ipha_dst)));
2352 		return (B_FALSE);
2353 	}
2354 	/* Check for MTU discovery advice as described in RFC 1191 */
2355 	mtu = ntohs(icmph->icmph_du_mtu);
2356 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2357 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2358 	    ire = ire->ire_next) {
2359 		/*
2360 		 * Look for the connection to which this ICMP message is
2361 		 * directed. If it has the IP_NEXTHOP option set, then the
2362 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2363 		 * option. Else the search is limited to regular IREs.
2364 		 */
2365 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2366 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2367 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2368 		    (nexthop_addr != INADDR_ANY)))
2369 			continue;
2370 
2371 		mutex_enter(&ire->ire_lock);
2372 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2373 			/* Reduce the IRE max frag value as advised. */
2374 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2375 			    mtu, ire->ire_max_frag));
2376 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2377 		} else {
2378 			uint32_t length;
2379 			int	i;
2380 
2381 			/*
2382 			 * Use the table from RFC 1191 to figure out
2383 			 * the next "plateau" based on the length in
2384 			 * the original IP packet.
2385 			 */
2386 			length = ntohs(ipha->ipha_length);
2387 			if (ire->ire_max_frag <= length &&
2388 			    ire->ire_max_frag >= length - hdr_length) {
2389 				/*
2390 				 * Handle broken BSD 4.2 systems that
2391 				 * return the wrong iph_length in ICMP
2392 				 * errors.
2393 				 */
2394 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2395 				    length, ire->ire_max_frag));
2396 				length -= hdr_length;
2397 			}
2398 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2399 				if (length > icmp_frag_size_table[i])
2400 					break;
2401 			}
2402 			if (i == A_CNT(icmp_frag_size_table)) {
2403 				/* Smaller than 68! */
2404 				ip1dbg(("Too big for packet size %d\n",
2405 				    length));
2406 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2407 				ire->ire_frag_flag = 0;
2408 			} else {
2409 				mtu = icmp_frag_size_table[i];
2410 				ip1dbg(("Calculated mtu %d, packet size %d, "
2411 				    "before %d", mtu, length,
2412 				    ire->ire_max_frag));
2413 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2414 				ip1dbg((", after %d\n", ire->ire_max_frag));
2415 			}
2416 			/* Record the new max frag size for the ULP. */
2417 			icmph->icmph_du_zero = 0;
2418 			icmph->icmph_du_mtu =
2419 			    htons((uint16_t)ire->ire_max_frag);
2420 		}
2421 		mutex_exit(&ire->ire_lock);
2422 	}
2423 	rw_exit(&first_ire->ire_bucket->irb_lock);
2424 	ire_refrele(first_ire);
2425 	return (B_TRUE);
2426 }
2427 
2428 /*
2429  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2430  * calls this function.
2431  */
2432 static mblk_t *
2433 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2434 {
2435 	ipha_t *ipha;
2436 	icmph_t *icmph;
2437 	ipha_t *in_ipha;
2438 	int length;
2439 
2440 	ASSERT(mp->b_datap->db_type == M_DATA);
2441 
2442 	/*
2443 	 * For Self-encapsulated packets, we added an extra IP header
2444 	 * without the options. Inner IP header is the one from which
2445 	 * the outer IP header was formed. Thus, we need to remove the
2446 	 * outer IP header. To do this, we pullup the whole message
2447 	 * and overlay whatever follows the outer IP header over the
2448 	 * outer IP header.
2449 	 */
2450 
2451 	if (!pullupmsg(mp, -1)) {
2452 		BUMP_MIB(&ip_mib, ipInDiscards);
2453 		return (NULL);
2454 	}
2455 
2456 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2457 	ipha = (ipha_t *)&icmph[1];
2458 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2459 
2460 	/*
2461 	 * The length that we want to overlay is following the inner
2462 	 * IP header. Subtracting the IP header + icmp header + outer
2463 	 * IP header's length should give us the length that we want to
2464 	 * overlay.
2465 	 */
2466 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2467 	    hdr_length;
2468 	/*
2469 	 * Overlay whatever follows the inner header over the
2470 	 * outer header.
2471 	 */
2472 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2473 
2474 	/* Set the wptr to account for the outer header */
2475 	mp->b_wptr -= hdr_length;
2476 	return (mp);
2477 }
2478 
2479 /*
2480  * Try to pass the ICMP message upstream in case the ULP cares.
2481  *
2482  * If the packet that caused the ICMP error is secure, we send
2483  * it to AH/ESP to make sure that the attached packet has a
2484  * valid association. ipha in the code below points to the
2485  * IP header of the packet that caused the error.
2486  *
2487  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2488  * in the context of IPSEC. Normally we tell the upper layer
2489  * whenever we send the ire (including ip_bind), the IPSEC header
2490  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2491  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2492  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2493  * same thing. As TCP has the IPSEC options size that needs to be
2494  * adjusted, we just pass the MTU unchanged.
2495  *
2496  * IFN could have been generated locally or by some router.
2497  *
2498  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2499  *	    This happens because IP adjusted its value of MTU on an
2500  *	    earlier IFN message and could not tell the upper layer,
2501  *	    the new adjusted value of MTU e.g. Packet was encrypted
2502  *	    or there was not enough information to fanout to upper
2503  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2504  *	    generates the IFN, where IPSEC processing has *not* been
2505  *	    done.
2506  *
2507  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2508  *	    could have generated this. This happens because ire_max_frag
2509  *	    value in IP was set to a new value, while the IPSEC processing
2510  *	    was being done and after we made the fragmentation check in
2511  *	    ip_wput_ire. Thus on return from IPSEC processing,
2512  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2513  *	    and generates the IFN. As IPSEC processing is over, we fanout
2514  *	    to AH/ESP to remove the header.
2515  *
2516  *	    In both these cases, ipsec_in_loopback will be set indicating
2517  *	    that IFN was generated locally.
2518  *
2519  * ROUTER : IFN could be secure or non-secure.
2520  *
2521  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2522  *	      packet in error has AH/ESP headers to validate the AH/ESP
2523  *	      headers. AH/ESP will verify whether there is a valid SA or
2524  *	      not and send it back. We will fanout again if we have more
2525  *	      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  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2531  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2532  *	      for validation. AH/ESP will verify whether there is a
2533  *	      valid SA or not and send it back. We will fanout again if
2534  *	      we have more data in the packet.
2535  *
2536  *	      If the packet in error does not have AH/ESP, we handle it
2537  *	      like any other case.
2538  */
2539 static void
2540 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2541     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2542     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2543     zoneid_t zoneid)
2544 {
2545 	uint16_t *up;	/* Pointer to ports in ULP header */
2546 	uint32_t ports;	/* reversed ports for fanout */
2547 	ipha_t ripha;	/* With reversed addresses */
2548 	mblk_t *first_mp;
2549 	ipsec_in_t *ii;
2550 	tcph_t	*tcph;
2551 	conn_t	*connp;
2552 
2553 	first_mp = mp;
2554 	if (mctl_present) {
2555 		mp = first_mp->b_cont;
2556 		ASSERT(mp != NULL);
2557 
2558 		ii = (ipsec_in_t *)first_mp->b_rptr;
2559 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2560 	} else {
2561 		ii = NULL;
2562 	}
2563 
2564 	switch (ipha->ipha_protocol) {
2565 	case IPPROTO_UDP:
2566 		/*
2567 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2568 		 * transport header.
2569 		 */
2570 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2571 		    mp->b_wptr) {
2572 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2573 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2574 				BUMP_MIB(&ip_mib, ipInDiscards);
2575 				goto drop_pkt;
2576 			}
2577 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2578 			ipha = (ipha_t *)&icmph[1];
2579 		}
2580 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2581 
2582 		/*
2583 		 * Attempt to find a client stream based on port.
2584 		 * Note that we do a reverse lookup since the header is
2585 		 * in the form we sent it out.
2586 		 * The ripha header is only used for the IP_UDP_MATCH and we
2587 		 * only set the src and dst addresses and protocol.
2588 		 */
2589 		ripha.ipha_src = ipha->ipha_dst;
2590 		ripha.ipha_dst = ipha->ipha_src;
2591 		ripha.ipha_protocol = ipha->ipha_protocol;
2592 		((uint16_t *)&ports)[0] = up[1];
2593 		((uint16_t *)&ports)[1] = up[0];
2594 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2595 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2596 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2597 		    icmph->icmph_type, icmph->icmph_code));
2598 
2599 		/* Have to change db_type after any pullupmsg */
2600 		DB_TYPE(mp) = M_CTL;
2601 
2602 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2603 		    mctl_present, ip_policy, recv_ill, zoneid);
2604 		return;
2605 
2606 	case IPPROTO_TCP:
2607 		/*
2608 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2609 		 * transport header.
2610 		 */
2611 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2612 		    mp->b_wptr) {
2613 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2614 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2615 				BUMP_MIB(&ip_mib, ipInDiscards);
2616 				goto drop_pkt;
2617 			}
2618 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2619 			ipha = (ipha_t *)&icmph[1];
2620 		}
2621 		/*
2622 		 * Find a TCP client stream for this packet.
2623 		 * Note that we do a reverse lookup since the header is
2624 		 * in the form we sent it out.
2625 		 */
2626 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2627 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2628 		if (connp == NULL) {
2629 			BUMP_MIB(&ip_mib, ipInDiscards);
2630 			goto drop_pkt;
2631 		}
2632 
2633 		/* Have to change db_type after any pullupmsg */
2634 		DB_TYPE(mp) = M_CTL;
2635 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2636 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2637 		return;
2638 
2639 	case IPPROTO_SCTP:
2640 		/*
2641 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2642 		 * transport header.
2643 		 */
2644 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2645 		    mp->b_wptr) {
2646 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2647 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2648 				BUMP_MIB(&ip_mib, ipInDiscards);
2649 				goto drop_pkt;
2650 			}
2651 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2652 			ipha = (ipha_t *)&icmph[1];
2653 		}
2654 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2655 		/*
2656 		 * Find a SCTP client stream for this packet.
2657 		 * Note that we do a reverse lookup since the header is
2658 		 * in the form we sent it out.
2659 		 * The ripha header is only used for the matching and we
2660 		 * only set the src and dst addresses, protocol, and version.
2661 		 */
2662 		ripha.ipha_src = ipha->ipha_dst;
2663 		ripha.ipha_dst = ipha->ipha_src;
2664 		ripha.ipha_protocol = ipha->ipha_protocol;
2665 		ripha.ipha_version_and_hdr_length =
2666 		    ipha->ipha_version_and_hdr_length;
2667 		((uint16_t *)&ports)[0] = up[1];
2668 		((uint16_t *)&ports)[1] = up[0];
2669 
2670 		/* Have to change db_type after any pullupmsg */
2671 		DB_TYPE(mp) = M_CTL;
2672 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2673 		    mctl_present, ip_policy, 0, zoneid);
2674 		return;
2675 
2676 	case IPPROTO_ESP:
2677 	case IPPROTO_AH: {
2678 		int ipsec_rc;
2679 
2680 		/*
2681 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2682 		 * We will re-use the IPSEC_IN if it is already present as
2683 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2684 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2685 		 * one and attach it in the front.
2686 		 */
2687 		if (ii != NULL) {
2688 			/*
2689 			 * ip_fanout_proto_again converts the ICMP errors
2690 			 * that come back from AH/ESP to M_DATA so that
2691 			 * if it is non-AH/ESP and we do a pullupmsg in
2692 			 * this function, it would work. Convert it back
2693 			 * to M_CTL before we send up as this is a ICMP
2694 			 * error. This could have been generated locally or
2695 			 * by some router. Validate the inner IPSEC
2696 			 * headers.
2697 			 *
2698 			 * NOTE : ill_index is used by ip_fanout_proto_again
2699 			 * to locate the ill.
2700 			 */
2701 			ASSERT(ill != NULL);
2702 			ii->ipsec_in_ill_index =
2703 			    ill->ill_phyint->phyint_ifindex;
2704 			ii->ipsec_in_rill_index =
2705 			    recv_ill->ill_phyint->phyint_ifindex;
2706 			DB_TYPE(first_mp->b_cont) = M_CTL;
2707 		} else {
2708 			/*
2709 			 * IPSEC_IN is not present. We attach a ipsec_in
2710 			 * message and send up to IPSEC for validating
2711 			 * and removing the IPSEC headers. Clear
2712 			 * ipsec_in_secure so that when we return
2713 			 * from IPSEC, we don't mistakenly think that this
2714 			 * is a secure packet came from the network.
2715 			 *
2716 			 * NOTE : ill_index is used by ip_fanout_proto_again
2717 			 * to locate the ill.
2718 			 */
2719 			ASSERT(first_mp == mp);
2720 			first_mp = ipsec_in_alloc(B_TRUE);
2721 			if (first_mp == NULL) {
2722 				freemsg(mp);
2723 				BUMP_MIB(&ip_mib, ipInDiscards);
2724 				return;
2725 			}
2726 			ii = (ipsec_in_t *)first_mp->b_rptr;
2727 
2728 			/* This is not a secure packet */
2729 			ii->ipsec_in_secure = B_FALSE;
2730 			first_mp->b_cont = mp;
2731 			DB_TYPE(mp) = M_CTL;
2732 			ASSERT(ill != NULL);
2733 			ii->ipsec_in_ill_index =
2734 			    ill->ill_phyint->phyint_ifindex;
2735 			ii->ipsec_in_rill_index =
2736 			    recv_ill->ill_phyint->phyint_ifindex;
2737 		}
2738 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2739 
2740 		if (!ipsec_loaded()) {
2741 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2742 			return;
2743 		}
2744 
2745 		if (ipha->ipha_protocol == IPPROTO_ESP)
2746 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2747 		else
2748 			ipsec_rc = ipsecah_icmp_error(first_mp);
2749 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2750 			return;
2751 
2752 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2753 		return;
2754 	}
2755 	default:
2756 		/*
2757 		 * The ripha header is only used for the lookup and we
2758 		 * only set the src and dst addresses and protocol.
2759 		 */
2760 		ripha.ipha_src = ipha->ipha_dst;
2761 		ripha.ipha_dst = ipha->ipha_src;
2762 		ripha.ipha_protocol = ipha->ipha_protocol;
2763 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2764 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2765 		    ntohl(ipha->ipha_dst),
2766 		    icmph->icmph_type, icmph->icmph_code));
2767 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2768 			ipha_t *in_ipha;
2769 
2770 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2771 			    mp->b_wptr) {
2772 				if (!pullupmsg(mp, (uchar_t *)ipha +
2773 				    hdr_length + sizeof (ipha_t) -
2774 				    mp->b_rptr)) {
2775 
2776 					BUMP_MIB(&ip_mib, ipInDiscards);
2777 					goto drop_pkt;
2778 				}
2779 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2780 				ipha = (ipha_t *)&icmph[1];
2781 			}
2782 			/*
2783 			 * Caller has verified that length has to be
2784 			 * at least the size of IP header.
2785 			 */
2786 			ASSERT(hdr_length >= sizeof (ipha_t));
2787 			/*
2788 			 * Check the sanity of the inner IP header like
2789 			 * we did for the outer header.
2790 			 */
2791 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2792 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2793 				BUMP_MIB(&ip_mib, ipInDiscards);
2794 				goto drop_pkt;
2795 			}
2796 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2797 				BUMP_MIB(&ip_mib, ipInDiscards);
2798 				goto drop_pkt;
2799 			}
2800 			/* Check for Self-encapsulated tunnels */
2801 			if (in_ipha->ipha_src == ipha->ipha_src &&
2802 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2803 
2804 				mp = icmp_inbound_self_encap_error(mp,
2805 				    iph_hdr_length, hdr_length);
2806 				if (mp == NULL)
2807 					goto drop_pkt;
2808 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2809 				ipha = (ipha_t *)&icmph[1];
2810 				hdr_length = IPH_HDR_LENGTH(ipha);
2811 				/*
2812 				 * The packet in error is self-encapsualted.
2813 				 * And we are finding it further encapsulated
2814 				 * which we could not have possibly generated.
2815 				 */
2816 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2817 					BUMP_MIB(&ip_mib, ipInDiscards);
2818 					goto drop_pkt;
2819 				}
2820 				icmp_inbound_error_fanout(q, ill, first_mp,
2821 				    icmph, ipha, iph_hdr_length, hdr_length,
2822 				    mctl_present, ip_policy, recv_ill, zoneid);
2823 				return;
2824 			}
2825 		}
2826 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2827 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2828 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2829 		    ii != NULL &&
2830 		    ii->ipsec_in_loopback &&
2831 		    ii->ipsec_in_secure) {
2832 			/*
2833 			 * For IP tunnels that get a looped-back
2834 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2835 			 * reported new MTU to take into account the IPsec
2836 			 * headers protecting this configured tunnel.
2837 			 *
2838 			 * This allows the tunnel module (tun.c) to blindly
2839 			 * accept the MTU reported in an ICMP "too big"
2840 			 * message.
2841 			 *
2842 			 * Non-looped back ICMP messages will just be
2843 			 * handled by the security protocols (if needed),
2844 			 * and the first subsequent packet will hit this
2845 			 * path.
2846 			 */
2847 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2848 			    ipsec_in_extra_length(first_mp));
2849 		}
2850 		/* Have to change db_type after any pullupmsg */
2851 		DB_TYPE(mp) = M_CTL;
2852 
2853 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2854 		    ip_policy, recv_ill, zoneid);
2855 		return;
2856 	}
2857 	/* NOTREACHED */
2858 drop_pkt:;
2859 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2860 	freemsg(first_mp);
2861 }
2862 
2863 /*
2864  * Common IP options parser.
2865  *
2866  * Setup routine: fill in *optp with options-parsing state, then
2867  * tail-call ipoptp_next to return the first option.
2868  */
2869 uint8_t
2870 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2871 {
2872 	uint32_t totallen; /* total length of all options */
2873 
2874 	totallen = ipha->ipha_version_and_hdr_length -
2875 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2876 	totallen <<= 2;
2877 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2878 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2879 	optp->ipoptp_flags = 0;
2880 	return (ipoptp_next(optp));
2881 }
2882 
2883 /*
2884  * Common IP options parser: extract next option.
2885  */
2886 uint8_t
2887 ipoptp_next(ipoptp_t *optp)
2888 {
2889 	uint8_t *end = optp->ipoptp_end;
2890 	uint8_t *cur = optp->ipoptp_next;
2891 	uint8_t opt, len, pointer;
2892 
2893 	/*
2894 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2895 	 * has been corrupted.
2896 	 */
2897 	ASSERT(cur <= end);
2898 
2899 	if (cur == end)
2900 		return (IPOPT_EOL);
2901 
2902 	opt = cur[IPOPT_OPTVAL];
2903 
2904 	/*
2905 	 * Skip any NOP options.
2906 	 */
2907 	while (opt == IPOPT_NOP) {
2908 		cur++;
2909 		if (cur == end)
2910 			return (IPOPT_EOL);
2911 		opt = cur[IPOPT_OPTVAL];
2912 	}
2913 
2914 	if (opt == IPOPT_EOL)
2915 		return (IPOPT_EOL);
2916 
2917 	/*
2918 	 * Option requiring a length.
2919 	 */
2920 	if ((cur + 1) >= end) {
2921 		optp->ipoptp_flags |= IPOPTP_ERROR;
2922 		return (IPOPT_EOL);
2923 	}
2924 	len = cur[IPOPT_OLEN];
2925 	if (len < 2) {
2926 		optp->ipoptp_flags |= IPOPTP_ERROR;
2927 		return (IPOPT_EOL);
2928 	}
2929 	optp->ipoptp_cur = cur;
2930 	optp->ipoptp_len = len;
2931 	optp->ipoptp_next = cur + len;
2932 	if (cur + len > end) {
2933 		optp->ipoptp_flags |= IPOPTP_ERROR;
2934 		return (IPOPT_EOL);
2935 	}
2936 
2937 	/*
2938 	 * For the options which require a pointer field, make sure
2939 	 * its there, and make sure it points to either something
2940 	 * inside this option, or the end of the option.
2941 	 */
2942 	switch (opt) {
2943 	case IPOPT_RR:
2944 	case IPOPT_TS:
2945 	case IPOPT_LSRR:
2946 	case IPOPT_SSRR:
2947 		if (len <= IPOPT_OFFSET) {
2948 			optp->ipoptp_flags |= IPOPTP_ERROR;
2949 			return (opt);
2950 		}
2951 		pointer = cur[IPOPT_OFFSET];
2952 		if (pointer - 1 > len) {
2953 			optp->ipoptp_flags |= IPOPTP_ERROR;
2954 			return (opt);
2955 		}
2956 		break;
2957 	}
2958 
2959 	/*
2960 	 * Sanity check the pointer field based on the type of the
2961 	 * option.
2962 	 */
2963 	switch (opt) {
2964 	case IPOPT_RR:
2965 	case IPOPT_SSRR:
2966 	case IPOPT_LSRR:
2967 		if (pointer < IPOPT_MINOFF_SR)
2968 			optp->ipoptp_flags |= IPOPTP_ERROR;
2969 		break;
2970 	case IPOPT_TS:
2971 		if (pointer < IPOPT_MINOFF_IT)
2972 			optp->ipoptp_flags |= IPOPTP_ERROR;
2973 		/*
2974 		 * Note that the Internet Timestamp option also
2975 		 * contains two four bit fields (the Overflow field,
2976 		 * and the Flag field), which follow the pointer
2977 		 * field.  We don't need to check that these fields
2978 		 * fall within the length of the option because this
2979 		 * was implicitely done above.  We've checked that the
2980 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2981 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2982 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2983 		 */
2984 		ASSERT(len > IPOPT_POS_OV_FLG);
2985 		break;
2986 	}
2987 
2988 	return (opt);
2989 }
2990 
2991 /*
2992  * Use the outgoing IP header to create an IP_OPTIONS option the way
2993  * it was passed down from the application.
2994  */
2995 int
2996 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2997 {
2998 	ipoptp_t	opts;
2999 	const uchar_t	*opt;
3000 	uint8_t		optval;
3001 	uint8_t		optlen;
3002 	uint32_t	len = 0;
3003 	uchar_t	*buf1 = buf;
3004 
3005 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3006 	len += IP_ADDR_LEN;
3007 	bzero(buf1, IP_ADDR_LEN);
3008 
3009 	/*
3010 	 * OK to cast away const here, as we don't store through the returned
3011 	 * opts.ipoptp_cur pointer.
3012 	 */
3013 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3014 	    optval != IPOPT_EOL;
3015 	    optval = ipoptp_next(&opts)) {
3016 		int	off;
3017 
3018 		opt = opts.ipoptp_cur;
3019 		optlen = opts.ipoptp_len;
3020 		switch (optval) {
3021 		case IPOPT_SSRR:
3022 		case IPOPT_LSRR:
3023 
3024 			/*
3025 			 * Insert ipha_dst as the first entry in the source
3026 			 * route and move down the entries on step.
3027 			 * The last entry gets placed at buf1.
3028 			 */
3029 			buf[IPOPT_OPTVAL] = optval;
3030 			buf[IPOPT_OLEN] = optlen;
3031 			buf[IPOPT_OFFSET] = optlen;
3032 
3033 			off = optlen - IP_ADDR_LEN;
3034 			if (off < 0) {
3035 				/* No entries in source route */
3036 				break;
3037 			}
3038 			/* Last entry in source route */
3039 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3040 			off -= IP_ADDR_LEN;
3041 
3042 			while (off > 0) {
3043 				bcopy(opt + off,
3044 				    buf + off + IP_ADDR_LEN,
3045 				    IP_ADDR_LEN);
3046 				off -= IP_ADDR_LEN;
3047 			}
3048 			/* ipha_dst into first slot */
3049 			bcopy(&ipha->ipha_dst,
3050 			    buf + off + IP_ADDR_LEN,
3051 			    IP_ADDR_LEN);
3052 			buf += optlen;
3053 			len += optlen;
3054 			break;
3055 
3056 		case IPOPT_COMSEC:
3057 		case IPOPT_SECURITY:
3058 			/* if passing up a label is not ok, then remove */
3059 			if (is_system_labeled())
3060 				break;
3061 			/* FALLTHROUGH */
3062 		default:
3063 			bcopy(opt, buf, optlen);
3064 			buf += optlen;
3065 			len += optlen;
3066 			break;
3067 		}
3068 	}
3069 done:
3070 	/* Pad the resulting options */
3071 	while (len & 0x3) {
3072 		*buf++ = IPOPT_EOL;
3073 		len++;
3074 	}
3075 	return (len);
3076 }
3077 
3078 /*
3079  * Update any record route or timestamp options to include this host.
3080  * Reverse any source route option.
3081  * This routine assumes that the options are well formed i.e. that they
3082  * have already been checked.
3083  */
3084 static void
3085 icmp_options_update(ipha_t *ipha)
3086 {
3087 	ipoptp_t	opts;
3088 	uchar_t		*opt;
3089 	uint8_t		optval;
3090 	ipaddr_t	src;		/* Our local address */
3091 	ipaddr_t	dst;
3092 
3093 	ip2dbg(("icmp_options_update\n"));
3094 	src = ipha->ipha_src;
3095 	dst = ipha->ipha_dst;
3096 
3097 	for (optval = ipoptp_first(&opts, ipha);
3098 	    optval != IPOPT_EOL;
3099 	    optval = ipoptp_next(&opts)) {
3100 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3101 		opt = opts.ipoptp_cur;
3102 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3103 		    optval, opts.ipoptp_len));
3104 		switch (optval) {
3105 			int off1, off2;
3106 		case IPOPT_SSRR:
3107 		case IPOPT_LSRR:
3108 			/*
3109 			 * Reverse the source route.  The first entry
3110 			 * should be the next to last one in the current
3111 			 * source route (the last entry is our address).
3112 			 * The last entry should be the final destination.
3113 			 */
3114 			off1 = IPOPT_MINOFF_SR - 1;
3115 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3116 			if (off2 < 0) {
3117 				/* No entries in source route */
3118 				ip1dbg((
3119 				    "icmp_options_update: bad src route\n"));
3120 				break;
3121 			}
3122 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3123 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3124 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3125 			off2 -= IP_ADDR_LEN;
3126 
3127 			while (off1 < off2) {
3128 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3129 				bcopy((char *)opt + off2, (char *)opt + off1,
3130 				    IP_ADDR_LEN);
3131 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3132 				off1 += IP_ADDR_LEN;
3133 				off2 -= IP_ADDR_LEN;
3134 			}
3135 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3136 			break;
3137 		}
3138 	}
3139 }
3140 
3141 /*
3142  * Process received ICMP Redirect messages.
3143  */
3144 /* ARGSUSED */
3145 static void
3146 icmp_redirect(mblk_t *mp)
3147 {
3148 	ipha_t	*ipha;
3149 	int	iph_hdr_length;
3150 	icmph_t	*icmph;
3151 	ipha_t	*ipha_err;
3152 	ire_t	*ire;
3153 	ire_t	*prev_ire;
3154 	ire_t	*save_ire;
3155 	ipaddr_t  src, dst, gateway;
3156 	iulp_t	ulp_info = { 0 };
3157 	int	error;
3158 
3159 	ipha = (ipha_t *)mp->b_rptr;
3160 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3161 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3162 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3163 		BUMP_MIB(&icmp_mib, icmpInErrors);
3164 		freemsg(mp);
3165 		return;
3166 	}
3167 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3168 	ipha_err = (ipha_t *)&icmph[1];
3169 	src = ipha->ipha_src;
3170 	dst = ipha_err->ipha_dst;
3171 	gateway = icmph->icmph_rd_gateway;
3172 	/* Make sure the new gateway is reachable somehow. */
3173 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3174 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3175 	/*
3176 	 * Make sure we had a route for the dest in question and that
3177 	 * that route was pointing to the old gateway (the source of the
3178 	 * redirect packet.)
3179 	 */
3180 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3181 	    NULL, MATCH_IRE_GW);
3182 	/*
3183 	 * Check that
3184 	 *	the redirect was not from ourselves
3185 	 *	the new gateway and the old gateway are directly reachable
3186 	 */
3187 	if (!prev_ire ||
3188 	    !ire ||
3189 	    ire->ire_type == IRE_LOCAL) {
3190 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3191 		freemsg(mp);
3192 		if (ire != NULL)
3193 			ire_refrele(ire);
3194 		if (prev_ire != NULL)
3195 			ire_refrele(prev_ire);
3196 		return;
3197 	}
3198 
3199 	/*
3200 	 * Should we use the old ULP info to create the new gateway?  From
3201 	 * a user's perspective, we should inherit the info so that it
3202 	 * is a "smooth" transition.  If we do not do that, then new
3203 	 * connections going thru the new gateway will have no route metrics,
3204 	 * which is counter-intuitive to user.  From a network point of
3205 	 * view, this may or may not make sense even though the new gateway
3206 	 * is still directly connected to us so the route metrics should not
3207 	 * change much.
3208 	 *
3209 	 * But if the old ire_uinfo is not initialized, we do another
3210 	 * recursive lookup on the dest using the new gateway.  There may
3211 	 * be a route to that.  If so, use it to initialize the redirect
3212 	 * route.
3213 	 */
3214 	if (prev_ire->ire_uinfo.iulp_set) {
3215 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3216 	} else {
3217 		ire_t *tmp_ire;
3218 		ire_t *sire;
3219 
3220 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3221 		    ALL_ZONES, 0, NULL,
3222 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3223 		if (sire != NULL) {
3224 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3225 			/*
3226 			 * If sire != NULL, ire_ftable_lookup() should not
3227 			 * return a NULL value.
3228 			 */
3229 			ASSERT(tmp_ire != NULL);
3230 			ire_refrele(tmp_ire);
3231 			ire_refrele(sire);
3232 		} else if (tmp_ire != NULL) {
3233 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3234 			    sizeof (iulp_t));
3235 			ire_refrele(tmp_ire);
3236 		}
3237 	}
3238 	if (prev_ire->ire_type == IRE_CACHE)
3239 		ire_delete(prev_ire);
3240 	ire_refrele(prev_ire);
3241 	/*
3242 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3243 	 * require TOS routing
3244 	 */
3245 	switch (icmph->icmph_code) {
3246 	case 0:
3247 	case 1:
3248 		/* TODO: TOS specificity for cases 2 and 3 */
3249 	case 2:
3250 	case 3:
3251 		break;
3252 	default:
3253 		freemsg(mp);
3254 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3255 		ire_refrele(ire);
3256 		return;
3257 	}
3258 	/*
3259 	 * Create a Route Association.  This will allow us to remember that
3260 	 * someone we believe told us to use the particular gateway.
3261 	 */
3262 	save_ire = ire;
3263 	ire = ire_create(
3264 		(uchar_t *)&dst,			/* dest addr */
3265 		(uchar_t *)&ip_g_all_ones,		/* mask */
3266 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3267 		(uchar_t *)&gateway,			/* gateway addr */
3268 		NULL,					/* no in_srcaddr */
3269 		&save_ire->ire_max_frag,		/* max frag */
3270 		NULL,					/* Fast Path header */
3271 		NULL,					/* no rfq */
3272 		NULL,					/* no stq */
3273 		IRE_HOST,
3274 		NULL,
3275 		NULL,
3276 		NULL,
3277 		0,
3278 		0,
3279 		0,
3280 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3281 		&ulp_info,
3282 		NULL,
3283 		NULL);
3284 
3285 	if (ire == NULL) {
3286 		freemsg(mp);
3287 		ire_refrele(save_ire);
3288 		return;
3289 	}
3290 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3291 	ire_refrele(save_ire);
3292 	atomic_inc_32(&ip_redirect_cnt);
3293 
3294 	if (error == 0) {
3295 		ire_refrele(ire);		/* Held in ire_add_v4 */
3296 		/* tell routing sockets that we received a redirect */
3297 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3298 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3299 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3300 	}
3301 
3302 	/*
3303 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3304 	 * This together with the added IRE has the effect of
3305 	 * modifying an existing redirect.
3306 	 */
3307 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3308 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3309 	if (prev_ire != NULL) {
3310 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3311 			ire_delete(prev_ire);
3312 		ire_refrele(prev_ire);
3313 	}
3314 
3315 	freemsg(mp);
3316 }
3317 
3318 /*
3319  * Generate an ICMP parameter problem message.
3320  */
3321 static void
3322 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3323 {
3324 	icmph_t	icmph;
3325 	boolean_t mctl_present;
3326 	mblk_t *first_mp;
3327 
3328 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3329 
3330 	if (!(mp = icmp_pkt_err_ok(mp))) {
3331 		if (mctl_present)
3332 			freeb(first_mp);
3333 		return;
3334 	}
3335 
3336 	bzero(&icmph, sizeof (icmph_t));
3337 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3338 	icmph.icmph_pp_ptr = ptr;
3339 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3340 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3341 }
3342 
3343 /*
3344  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3345  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3346  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3347  * an icmp error packet can be sent.
3348  * Assigns an appropriate source address to the packet. If ipha_dst is
3349  * one of our addresses use it for source. Otherwise pick a source based
3350  * on a route lookup back to ipha_src.
3351  * Note that ipha_src must be set here since the
3352  * packet is likely to arrive on an ill queue in ip_wput() which will
3353  * not set a source address.
3354  */
3355 static void
3356 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3357     boolean_t mctl_present, zoneid_t zoneid)
3358 {
3359 	ipaddr_t dst;
3360 	icmph_t	*icmph;
3361 	ipha_t	*ipha;
3362 	uint_t	len_needed;
3363 	size_t	msg_len;
3364 	mblk_t	*mp1;
3365 	ipaddr_t src;
3366 	ire_t	*ire;
3367 	mblk_t *ipsec_mp;
3368 	ipsec_out_t	*io = NULL;
3369 	boolean_t xmit_if_on = B_FALSE;
3370 
3371 	if (mctl_present) {
3372 		/*
3373 		 * If it is :
3374 		 *
3375 		 * 1) a IPSEC_OUT, then this is caused by outbound
3376 		 *    datagram originating on this host. IPSEC processing
3377 		 *    may or may not have been done. Refer to comments above
3378 		 *    icmp_inbound_error_fanout for details.
3379 		 *
3380 		 * 2) a IPSEC_IN if we are generating a icmp_message
3381 		 *    for an incoming datagram destined for us i.e called
3382 		 *    from ip_fanout_send_icmp.
3383 		 */
3384 		ipsec_info_t *in;
3385 		ipsec_mp = mp;
3386 		mp = ipsec_mp->b_cont;
3387 
3388 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3389 		ipha = (ipha_t *)mp->b_rptr;
3390 
3391 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3392 		    in->ipsec_info_type == IPSEC_IN);
3393 
3394 		if (in->ipsec_info_type == IPSEC_IN) {
3395 			/*
3396 			 * Convert the IPSEC_IN to IPSEC_OUT.
3397 			 */
3398 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3399 				BUMP_MIB(&ip_mib, ipOutDiscards);
3400 				return;
3401 			}
3402 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3403 		} else {
3404 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3405 			io = (ipsec_out_t *)in;
3406 			if (io->ipsec_out_xmit_if)
3407 				xmit_if_on = B_TRUE;
3408 			/*
3409 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3410 			 * ire lookup.
3411 			 */
3412 			io->ipsec_out_proc_begin = B_FALSE;
3413 		}
3414 		ASSERT(zoneid == io->ipsec_out_zoneid);
3415 		ASSERT(zoneid != ALL_ZONES);
3416 	} else {
3417 		/*
3418 		 * This is in clear. The icmp message we are building
3419 		 * here should go out in clear.
3420 		 *
3421 		 * Pardon the convolution of it all, but it's easier to
3422 		 * allocate a "use cleartext" IPSEC_IN message and convert
3423 		 * it than it is to allocate a new one.
3424 		 */
3425 		ipsec_in_t *ii;
3426 		ASSERT(DB_TYPE(mp) == M_DATA);
3427 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3428 			freemsg(mp);
3429 			BUMP_MIB(&ip_mib, ipOutDiscards);
3430 			return;
3431 		}
3432 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3433 
3434 		/* This is not a secure packet */
3435 		ii->ipsec_in_secure = B_FALSE;
3436 		/*
3437 		 * For trusted extensions using a shared IP address we can
3438 		 * send using any zoneid.
3439 		 */
3440 		if (zoneid == ALL_ZONES)
3441 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3442 		else
3443 			ii->ipsec_in_zoneid = zoneid;
3444 		ipsec_mp->b_cont = mp;
3445 		ipha = (ipha_t *)mp->b_rptr;
3446 		/*
3447 		 * Convert the IPSEC_IN to IPSEC_OUT.
3448 		 */
3449 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3450 			BUMP_MIB(&ip_mib, ipOutDiscards);
3451 			return;
3452 		}
3453 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3454 	}
3455 
3456 	/* Remember our eventual destination */
3457 	dst = ipha->ipha_src;
3458 
3459 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3460 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3461 	if (ire != NULL &&
3462 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3463 		src = ipha->ipha_dst;
3464 	} else if (!xmit_if_on) {
3465 		if (ire != NULL)
3466 			ire_refrele(ire);
3467 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3468 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3469 		if (ire == NULL) {
3470 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3471 			freemsg(ipsec_mp);
3472 			return;
3473 		}
3474 		src = ire->ire_src_addr;
3475 	} else {
3476 		ipif_t	*ipif = NULL;
3477 		ill_t	*ill;
3478 		/*
3479 		 * This must be an ICMP error coming from
3480 		 * ip_mrtun_forward(). The src addr should
3481 		 * be equal to the IP-addr of the outgoing
3482 		 * interface.
3483 		 */
3484 		if (io == NULL) {
3485 			/* This is not a IPSEC_OUT type control msg */
3486 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3487 			freemsg(ipsec_mp);
3488 			return;
3489 		}
3490 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3491 		    NULL, NULL, NULL, NULL);
3492 		if (ill != NULL) {
3493 			ipif = ipif_get_next_ipif(NULL, ill);
3494 			ill_refrele(ill);
3495 		}
3496 		if (ipif == NULL) {
3497 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3498 			freemsg(ipsec_mp);
3499 			return;
3500 		}
3501 		src = ipif->ipif_src_addr;
3502 		ipif_refrele(ipif);
3503 	}
3504 
3505 	if (ire != NULL)
3506 		ire_refrele(ire);
3507 
3508 	/*
3509 	 * Check if we can send back more then 8 bytes in addition
3510 	 * to the IP header. We will include as much as 64 bytes.
3511 	 */
3512 	len_needed = IPH_HDR_LENGTH(ipha);
3513 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3514 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3515 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3516 	}
3517 	len_needed += ip_icmp_return;
3518 	msg_len = msgdsize(mp);
3519 	if (msg_len > len_needed) {
3520 		(void) adjmsg(mp, len_needed - msg_len);
3521 		msg_len = len_needed;
3522 	}
3523 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3524 	if (mp1 == NULL) {
3525 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3526 		freemsg(ipsec_mp);
3527 		return;
3528 	}
3529 	/*
3530 	 * On an unlabeled system, dblks don't necessarily have creds.
3531 	 */
3532 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3533 	if (DB_CRED(mp) != NULL)
3534 		mblk_setcred(mp1, DB_CRED(mp));
3535 	mp1->b_cont = mp;
3536 	mp = mp1;
3537 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3538 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3539 	    io->ipsec_out_type == IPSEC_OUT);
3540 	ipsec_mp->b_cont = mp;
3541 
3542 	/*
3543 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3544 	 * node generates be accepted in peace by all on-host destinations.
3545 	 * If we do NOT assume that all on-host destinations trust
3546 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3547 	 * (Look for ipsec_out_icmp_loopback).
3548 	 */
3549 	io->ipsec_out_icmp_loopback = B_TRUE;
3550 
3551 	ipha = (ipha_t *)mp->b_rptr;
3552 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3553 	*ipha = icmp_ipha;
3554 	ipha->ipha_src = src;
3555 	ipha->ipha_dst = dst;
3556 	ipha->ipha_ttl = ip_def_ttl;
3557 	msg_len += sizeof (icmp_ipha) + len;
3558 	if (msg_len > IP_MAXPACKET) {
3559 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3560 		msg_len = IP_MAXPACKET;
3561 	}
3562 	ipha->ipha_length = htons((uint16_t)msg_len);
3563 	icmph = (icmph_t *)&ipha[1];
3564 	bcopy(stuff, icmph, len);
3565 	icmph->icmph_checksum = 0;
3566 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3567 	if (icmph->icmph_checksum == 0)
3568 		icmph->icmph_checksum = 0xFFFF;
3569 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3570 	put(q, ipsec_mp);
3571 }
3572 
3573 /*
3574  * Determine if an ICMP error packet can be sent given the rate limit.
3575  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3576  * in milliseconds) and a burst size. Burst size number of packets can
3577  * be sent arbitrarely closely spaced.
3578  * The state is tracked using two variables to implement an approximate
3579  * token bucket filter:
3580  *	icmp_pkt_err_last - lbolt value when the last burst started
3581  *	icmp_pkt_err_sent - number of packets sent in current burst
3582  */
3583 boolean_t
3584 icmp_err_rate_limit(void)
3585 {
3586 	clock_t now = TICK_TO_MSEC(lbolt);
3587 	uint_t refilled; /* Number of packets refilled in tbf since last */
3588 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3589 
3590 	if (err_interval == 0)
3591 		return (B_FALSE);
3592 
3593 	if (icmp_pkt_err_last > now) {
3594 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3595 		icmp_pkt_err_last = 0;
3596 		icmp_pkt_err_sent = 0;
3597 	}
3598 	/*
3599 	 * If we are in a burst update the token bucket filter.
3600 	 * Update the "last" time to be close to "now" but make sure
3601 	 * we don't loose precision.
3602 	 */
3603 	if (icmp_pkt_err_sent != 0) {
3604 		refilled = (now - icmp_pkt_err_last)/err_interval;
3605 		if (refilled > icmp_pkt_err_sent) {
3606 			icmp_pkt_err_sent = 0;
3607 		} else {
3608 			icmp_pkt_err_sent -= refilled;
3609 			icmp_pkt_err_last += refilled * err_interval;
3610 		}
3611 	}
3612 	if (icmp_pkt_err_sent == 0) {
3613 		/* Start of new burst */
3614 		icmp_pkt_err_last = now;
3615 	}
3616 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3617 		icmp_pkt_err_sent++;
3618 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3619 		    icmp_pkt_err_sent));
3620 		return (B_FALSE);
3621 	}
3622 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3623 	return (B_TRUE);
3624 }
3625 
3626 /*
3627  * Check if it is ok to send an IPv4 ICMP error packet in
3628  * response to the IPv4 packet in mp.
3629  * Free the message and return null if no
3630  * ICMP error packet should be sent.
3631  */
3632 static mblk_t *
3633 icmp_pkt_err_ok(mblk_t *mp)
3634 {
3635 	icmph_t	*icmph;
3636 	ipha_t	*ipha;
3637 	uint_t	len_needed;
3638 	ire_t	*src_ire;
3639 	ire_t	*dst_ire;
3640 
3641 	if (!mp)
3642 		return (NULL);
3643 	ipha = (ipha_t *)mp->b_rptr;
3644 	if (ip_csum_hdr(ipha)) {
3645 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3646 		freemsg(mp);
3647 		return (NULL);
3648 	}
3649 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3652 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3653 	if (src_ire != NULL || dst_ire != NULL ||
3654 	    CLASSD(ipha->ipha_dst) ||
3655 	    CLASSD(ipha->ipha_src) ||
3656 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3657 		/* Note: only errors to the fragment with offset 0 */
3658 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3659 		freemsg(mp);
3660 		if (src_ire != NULL)
3661 			ire_refrele(src_ire);
3662 		if (dst_ire != NULL)
3663 			ire_refrele(dst_ire);
3664 		return (NULL);
3665 	}
3666 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3667 		/*
3668 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3669 		 * errors in response to any ICMP errors.
3670 		 */
3671 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3672 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3673 			if (!pullupmsg(mp, len_needed)) {
3674 				BUMP_MIB(&icmp_mib, icmpInErrors);
3675 				freemsg(mp);
3676 				return (NULL);
3677 			}
3678 			ipha = (ipha_t *)mp->b_rptr;
3679 		}
3680 		icmph = (icmph_t *)
3681 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3682 		switch (icmph->icmph_type) {
3683 		case ICMP_DEST_UNREACHABLE:
3684 		case ICMP_SOURCE_QUENCH:
3685 		case ICMP_TIME_EXCEEDED:
3686 		case ICMP_PARAM_PROBLEM:
3687 		case ICMP_REDIRECT:
3688 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3689 			freemsg(mp);
3690 			return (NULL);
3691 		default:
3692 			break;
3693 		}
3694 	}
3695 	/*
3696 	 * If this is a labeled system, then check to see if we're allowed to
3697 	 * send a response to this particular sender.  If not, then just drop.
3698 	 */
3699 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3700 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3701 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3702 		freemsg(mp);
3703 		return (NULL);
3704 	}
3705 	if (icmp_err_rate_limit()) {
3706 		/*
3707 		 * Only send ICMP error packets every so often.
3708 		 * This should be done on a per port/source basis,
3709 		 * but for now this will suffice.
3710 		 */
3711 		freemsg(mp);
3712 		return (NULL);
3713 	}
3714 	return (mp);
3715 }
3716 
3717 /*
3718  * Generate an ICMP redirect message.
3719  */
3720 static void
3721 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3722 {
3723 	icmph_t	icmph;
3724 
3725 	/*
3726 	 * We are called from ip_rput where we could
3727 	 * not have attached an IPSEC_IN.
3728 	 */
3729 	ASSERT(mp->b_datap->db_type == M_DATA);
3730 
3731 	if (!(mp = icmp_pkt_err_ok(mp))) {
3732 		return;
3733 	}
3734 
3735 	bzero(&icmph, sizeof (icmph_t));
3736 	icmph.icmph_type = ICMP_REDIRECT;
3737 	icmph.icmph_code = 1;
3738 	icmph.icmph_rd_gateway = gateway;
3739 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3740 	/* Redirects sent by router, and router is global zone */
3741 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3742 }
3743 
3744 /*
3745  * Generate an ICMP time exceeded message.
3746  */
3747 void
3748 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3749 {
3750 	icmph_t	icmph;
3751 	boolean_t mctl_present;
3752 	mblk_t *first_mp;
3753 
3754 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3755 
3756 	if (!(mp = icmp_pkt_err_ok(mp))) {
3757 		if (mctl_present)
3758 			freeb(first_mp);
3759 		return;
3760 	}
3761 
3762 	bzero(&icmph, sizeof (icmph_t));
3763 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3764 	icmph.icmph_code = code;
3765 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3766 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3767 }
3768 
3769 /*
3770  * Generate an ICMP unreachable message.
3771  */
3772 void
3773 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3774 {
3775 	icmph_t	icmph;
3776 	mblk_t *first_mp;
3777 	boolean_t mctl_present;
3778 
3779 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3780 
3781 	if (!(mp = icmp_pkt_err_ok(mp))) {
3782 		if (mctl_present)
3783 			freeb(first_mp);
3784 		return;
3785 	}
3786 
3787 	bzero(&icmph, sizeof (icmph_t));
3788 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3789 	icmph.icmph_code = code;
3790 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3791 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3792 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3793 	    zoneid);
3794 }
3795 
3796 /*
3797  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3798  * duplicate.  As long as someone else holds the address, the interface will
3799  * stay down.  When that conflict goes away, the interface is brought back up.
3800  * This is done so that accidental shutdowns of addresses aren't made
3801  * permanent.  Your server will recover from a failure.
3802  *
3803  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3804  * user space process (dhcpagent).
3805  *
3806  * Recovery completes if ARP reports that the address is now ours (via
3807  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3808  *
3809  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3810  */
3811 static void
3812 ipif_dup_recovery(void *arg)
3813 {
3814 	ipif_t *ipif = arg;
3815 	ill_t *ill = ipif->ipif_ill;
3816 	mblk_t *arp_add_mp;
3817 	mblk_t *arp_del_mp;
3818 	area_t *area;
3819 
3820 	ipif->ipif_recovery_id = 0;
3821 
3822 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3823 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3824 		/* No reason to try to bring this address back. */
3825 		return;
3826 	}
3827 
3828 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3829 		goto alloc_fail;
3830 
3831 	if (ipif->ipif_arp_del_mp == NULL) {
3832 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3833 			goto alloc_fail;
3834 		ipif->ipif_arp_del_mp = arp_del_mp;
3835 	}
3836 
3837 	/* Setting the 'unverified' flag restarts DAD */
3838 	area = (area_t *)arp_add_mp->b_rptr;
3839 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3840 	    ACE_F_UNVERIFIED;
3841 	putnext(ill->ill_rq, arp_add_mp);
3842 	return;
3843 
3844 alloc_fail:
3845 	/* On allocation failure, just restart the timer */
3846 	freemsg(arp_add_mp);
3847 	if (ip_dup_recovery > 0) {
3848 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3849 		    MSEC_TO_TICK(ip_dup_recovery));
3850 	}
3851 }
3852 
3853 /*
3854  * This is for exclusive changes due to ARP.  Either tear down an interface due
3855  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3856  */
3857 /* ARGSUSED */
3858 static void
3859 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3860 {
3861 	ill_t	*ill = rq->q_ptr;
3862 	arh_t *arh;
3863 	ipaddr_t src;
3864 	ipif_t	*ipif;
3865 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3866 	char hbuf[MAC_STR_LEN];
3867 	char sbuf[INET_ADDRSTRLEN];
3868 	const char *failtype;
3869 	boolean_t bring_up;
3870 
3871 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3872 	case AR_CN_READY:
3873 		failtype = NULL;
3874 		bring_up = B_TRUE;
3875 		break;
3876 	case AR_CN_FAILED:
3877 		failtype = "in use";
3878 		bring_up = B_FALSE;
3879 		break;
3880 	default:
3881 		failtype = "claimed";
3882 		bring_up = B_FALSE;
3883 		break;
3884 	}
3885 
3886 	arh = (arh_t *)mp->b_cont->b_rptr;
3887 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3888 
3889 	/* Handle failures due to probes */
3890 	if (src == 0) {
3891 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3892 		    IP_ADDR_LEN);
3893 	}
3894 
3895 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3896 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3897 	    sizeof (hbuf));
3898 	(void) ip_dot_addr(src, sbuf);
3899 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3900 
3901 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3902 		    ipif->ipif_lcl_addr != src) {
3903 			continue;
3904 		}
3905 
3906 		/*
3907 		 * If we failed on a recovery probe, then restart the timer to
3908 		 * try again later.
3909 		 */
3910 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3911 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3912 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3913 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3914 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3915 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3916 			continue;
3917 		}
3918 
3919 		/*
3920 		 * If what we're trying to do has already been done, then do
3921 		 * nothing.
3922 		 */
3923 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3924 			continue;
3925 
3926 		if (ipif->ipif_id != 0) {
3927 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3928 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3929 			    ipif->ipif_id);
3930 		}
3931 		if (failtype == NULL) {
3932 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3933 			    ibuf);
3934 		} else {
3935 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3936 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3937 		}
3938 
3939 		if (bring_up) {
3940 			ASSERT(ill->ill_dl_up);
3941 			/*
3942 			 * Free up the ARP delete message so we can allocate
3943 			 * a fresh one through the normal path.
3944 			 */
3945 			freemsg(ipif->ipif_arp_del_mp);
3946 			ipif->ipif_arp_del_mp = NULL;
3947 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3948 			    EINPROGRESS) {
3949 				ipif->ipif_addr_ready = 1;
3950 				(void) ipif_up_done(ipif);
3951 			}
3952 			continue;
3953 		}
3954 
3955 		mutex_enter(&ill->ill_lock);
3956 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3957 		ipif->ipif_flags |= IPIF_DUPLICATE;
3958 		ill->ill_ipif_dup_count++;
3959 		mutex_exit(&ill->ill_lock);
3960 		/*
3961 		 * Already exclusive on the ill; no need to handle deferred
3962 		 * processing here.
3963 		 */
3964 		(void) ipif_down(ipif, NULL, NULL);
3965 		ipif_down_tail(ipif);
3966 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3967 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3968 		    ip_dup_recovery > 0) {
3969 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3970 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3971 		}
3972 	}
3973 	freemsg(mp);
3974 }
3975 
3976 /* ARGSUSED */
3977 static void
3978 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3979 {
3980 	ill_t	*ill = rq->q_ptr;
3981 	arh_t *arh;
3982 	ipaddr_t src;
3983 	ipif_t	*ipif;
3984 
3985 	arh = (arh_t *)mp->b_cont->b_rptr;
3986 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3987 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3988 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3989 			(void) ipif_resolver_up(ipif, Res_act_defend);
3990 	}
3991 	freemsg(mp);
3992 }
3993 
3994 /*
3995  * News from ARP.  ARP sends notification of interesting events down
3996  * to its clients using M_CTL messages with the interesting ARP packet
3997  * attached via b_cont.
3998  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3999  * queue as opposed to ARP sending the message to all the clients, i.e. all
4000  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
4001  * table if a cache IRE is found to delete all the entries for the address in
4002  * the packet.
4003  */
4004 static void
4005 ip_arp_news(queue_t *q, mblk_t *mp)
4006 {
4007 	arcn_t		*arcn;
4008 	arh_t		*arh;
4009 	ire_t		*ire = NULL;
4010 	char		hbuf[MAC_STR_LEN];
4011 	char		sbuf[INET_ADDRSTRLEN];
4012 	ipaddr_t	src;
4013 	in6_addr_t	v6src;
4014 	boolean_t	isv6 = B_FALSE;
4015 	ipif_t		*ipif;
4016 	ill_t		*ill;
4017 
4018 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4019 		if (q->q_next) {
4020 			putnext(q, mp);
4021 		} else
4022 			freemsg(mp);
4023 		return;
4024 	}
4025 	arh = (arh_t *)mp->b_cont->b_rptr;
4026 	/* Is it one we are interested in? */
4027 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4028 		isv6 = B_TRUE;
4029 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4030 		    IPV6_ADDR_LEN);
4031 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4032 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4033 		    IP_ADDR_LEN);
4034 	} else {
4035 		freemsg(mp);
4036 		return;
4037 	}
4038 
4039 	ill = q->q_ptr;
4040 
4041 	arcn = (arcn_t *)mp->b_rptr;
4042 	switch (arcn->arcn_code) {
4043 	case AR_CN_BOGON:
4044 		/*
4045 		 * Someone is sending ARP packets with a source protocol
4046 		 * address that we have published and for which we believe our
4047 		 * entry is authoritative and (when ill_arp_extend is set)
4048 		 * verified to be unique on the network.
4049 		 *
4050 		 * The ARP module internally handles the cases where the sender
4051 		 * is just probing (for DAD) and where the hardware address of
4052 		 * a non-authoritative entry has changed.  Thus, these are the
4053 		 * real conflicts, and we have to do resolution.
4054 		 *
4055 		 * We back away quickly from the address if it's from DHCP or
4056 		 * otherwise temporary and hasn't been used recently (or at
4057 		 * all).  We'd like to include "deprecated" addresses here as
4058 		 * well (as there's no real reason to defend something we're
4059 		 * discarding), but IPMP "reuses" this flag to mean something
4060 		 * other than the standard meaning.
4061 		 *
4062 		 * If the ARP module above is not extended (meaning that it
4063 		 * doesn't know how to defend the address), then we just log
4064 		 * the problem as we always did and continue on.  It's not
4065 		 * right, but there's little else we can do, and those old ATM
4066 		 * users are going away anyway.
4067 		 */
4068 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4069 		    hbuf, sizeof (hbuf));
4070 		(void) ip_dot_addr(src, sbuf);
4071 		if (isv6)
4072 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4073 		else
4074 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4075 
4076 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4077 			uint32_t now;
4078 			uint32_t maxage;
4079 			clock_t lused;
4080 			uint_t maxdefense;
4081 			uint_t defs;
4082 
4083 			/*
4084 			 * First, figure out if this address hasn't been used
4085 			 * in a while.  If it hasn't, then it's a better
4086 			 * candidate for abandoning.
4087 			 */
4088 			ipif = ire->ire_ipif;
4089 			ASSERT(ipif != NULL);
4090 			now = gethrestime_sec();
4091 			maxage = now - ire->ire_create_time;
4092 			if (maxage > ip_max_temp_idle)
4093 				maxage = ip_max_temp_idle;
4094 			lused = drv_hztousec(ddi_get_lbolt() -
4095 			    ire->ire_last_used_time) / MICROSEC + 1;
4096 			if (lused >= maxage && (ipif->ipif_flags &
4097 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4098 				maxdefense = ip_max_temp_defend;
4099 			else
4100 				maxdefense = ip_max_defend;
4101 
4102 			/*
4103 			 * Now figure out how many times we've defended
4104 			 * ourselves.  Ignore defenses that happened long in
4105 			 * the past.
4106 			 */
4107 			mutex_enter(&ire->ire_lock);
4108 			if ((defs = ire->ire_defense_count) > 0 &&
4109 			    now - ire->ire_defense_time > ip_defend_interval) {
4110 				ire->ire_defense_count = defs = 0;
4111 			}
4112 			ire->ire_defense_count++;
4113 			ire->ire_defense_time = now;
4114 			mutex_exit(&ire->ire_lock);
4115 			ill_refhold(ill);
4116 			ire_refrele(ire);
4117 
4118 			/*
4119 			 * If we've defended ourselves too many times already,
4120 			 * then give up and tear down the interface(s) using
4121 			 * this address.  Otherwise, defend by sending out a
4122 			 * gratuitous ARP.
4123 			 */
4124 			if (defs >= maxdefense && ill->ill_arp_extend) {
4125 				(void) qwriter_ip(NULL, ill, q, mp,
4126 				    ip_arp_excl, CUR_OP, B_FALSE);
4127 			} else {
4128 				cmn_err(CE_WARN,
4129 				    "node %s is using our IP address %s on %s",
4130 				    hbuf, sbuf, ill->ill_name);
4131 				/*
4132 				 * If this is an old (ATM) ARP module, then
4133 				 * don't try to defend the address.  Remain
4134 				 * compatible with the old behavior.  Defend
4135 				 * only with new ARP.
4136 				 */
4137 				if (ill->ill_arp_extend) {
4138 					(void) qwriter_ip(NULL, ill, q, mp,
4139 					    ip_arp_defend, CUR_OP, B_FALSE);
4140 				} else {
4141 					ill_refrele(ill);
4142 				}
4143 			}
4144 			return;
4145 		}
4146 		cmn_err(CE_WARN,
4147 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4148 		    hbuf, sbuf, ill->ill_name);
4149 		if (ire != NULL)
4150 			ire_refrele(ire);
4151 		break;
4152 	case AR_CN_ANNOUNCE:
4153 		if (isv6) {
4154 			/*
4155 			 * For XRESOLV interfaces.
4156 			 * Delete the IRE cache entry and NCE for this
4157 			 * v6 address
4158 			 */
4159 			ip_ire_clookup_and_delete_v6(&v6src);
4160 			/*
4161 			 * If v6src is a non-zero, it's a router address
4162 			 * as below. Do the same sort of thing to clean
4163 			 * out off-net IRE_CACHE entries that go through
4164 			 * the router.
4165 			 */
4166 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4167 				ire_walk_v6(ire_delete_cache_gw_v6,
4168 				    (char *)&v6src, ALL_ZONES);
4169 			}
4170 		} else {
4171 			nce_hw_map_t hwm;
4172 
4173 			/*
4174 			 * ARP gives us a copy of any packet where it thinks
4175 			 * the address has changed, so that we can update our
4176 			 * caches.  We're responsible for caching known answers
4177 			 * in the current design.  We check whether the
4178 			 * hardware address really has changed in all of our
4179 			 * entries that have cached this mapping, and if so, we
4180 			 * blow them away.  This way we will immediately pick
4181 			 * up the rare case of a host changing hardware
4182 			 * address.
4183 			 */
4184 			if (src == 0)
4185 				break;
4186 			hwm.hwm_addr = src;
4187 			hwm.hwm_hwlen = arh->arh_hlen;
4188 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4189 			ndp_walk_common(&ndp4, NULL,
4190 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4191 		}
4192 		break;
4193 	case AR_CN_READY:
4194 		/* No external v6 resolver has a contract to use this */
4195 		if (isv6)
4196 			break;
4197 		/* If the link is down, we'll retry this later */
4198 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4199 			break;
4200 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4201 		    NULL, NULL);
4202 		if (ipif != NULL) {
4203 			/*
4204 			 * If this is a duplicate recovery, then we now need to
4205 			 * go exclusive to bring this thing back up.
4206 			 */
4207 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4208 			    IPIF_DUPLICATE) {
4209 				ipif_refrele(ipif);
4210 				ill_refhold(ill);
4211 				(void) qwriter_ip(NULL, ill, q, mp,
4212 				    ip_arp_excl, CUR_OP, B_FALSE);
4213 				return;
4214 			}
4215 			/*
4216 			 * If this is the first notice that this address is
4217 			 * ready, then let the user know now.
4218 			 */
4219 			if ((ipif->ipif_flags & IPIF_UP) &&
4220 			    !ipif->ipif_addr_ready) {
4221 				ipif_mask_reply(ipif);
4222 				ip_rts_ifmsg(ipif);
4223 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4224 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4225 			}
4226 			ipif->ipif_addr_ready = 1;
4227 			ipif_refrele(ipif);
4228 		}
4229 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4230 		if (ire != NULL) {
4231 			ire->ire_defense_count = 0;
4232 			ire_refrele(ire);
4233 		}
4234 		break;
4235 	case AR_CN_FAILED:
4236 		/* No external v6 resolver has a contract to use this */
4237 		if (isv6)
4238 			break;
4239 		ill_refhold(ill);
4240 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4241 		    B_FALSE);
4242 		return;
4243 	}
4244 	freemsg(mp);
4245 }
4246 
4247 /*
4248  * Create a mblk suitable for carrying the interface index and/or source link
4249  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4250  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4251  * application.
4252  */
4253 mblk_t *
4254 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4255 {
4256 	mblk_t		*mp;
4257 	in_pktinfo_t	*pinfo;
4258 	ipha_t *ipha;
4259 	struct ether_header *pether;
4260 
4261 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4262 	if (mp == NULL) {
4263 		ip1dbg(("ip_add_info: allocation failure.\n"));
4264 		return (data_mp);
4265 	}
4266 
4267 	ipha	= (ipha_t *)data_mp->b_rptr;
4268 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4269 	bzero(pinfo, sizeof (in_pktinfo_t));
4270 	pinfo->in_pkt_flags = (uchar_t)flags;
4271 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4272 
4273 	if (flags & IPF_RECVIF)
4274 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4275 
4276 	pether = (struct ether_header *)((char *)ipha
4277 	    - sizeof (struct ether_header));
4278 	/*
4279 	 * Make sure the interface is an ethernet type, since this option
4280 	 * is currently supported only on this type of interface. Also make
4281 	 * sure we are pointing correctly above db_base.
4282 	 */
4283 
4284 	if ((flags & IPF_RECVSLLA) &&
4285 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4286 	    (ill->ill_type == IFT_ETHER) &&
4287 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4288 
4289 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4290 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4291 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4292 	} else {
4293 		/*
4294 		 * Clear the bit. Indicate to upper layer that IP is not
4295 		 * sending this ancillary info.
4296 		 */
4297 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4298 	}
4299 
4300 	mp->b_datap->db_type = M_CTL;
4301 	mp->b_wptr += sizeof (in_pktinfo_t);
4302 	mp->b_cont = data_mp;
4303 
4304 	return (mp);
4305 }
4306 
4307 /*
4308  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4309  * part of the bind request.
4310  */
4311 
4312 boolean_t
4313 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4314 {
4315 	ipsec_in_t *ii;
4316 
4317 	ASSERT(policy_mp != NULL);
4318 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4319 
4320 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4321 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4322 
4323 	connp->conn_policy = ii->ipsec_in_policy;
4324 	ii->ipsec_in_policy = NULL;
4325 
4326 	if (ii->ipsec_in_action != NULL) {
4327 		if (connp->conn_latch == NULL) {
4328 			connp->conn_latch = iplatch_create();
4329 			if (connp->conn_latch == NULL)
4330 				return (B_FALSE);
4331 		}
4332 		ipsec_latch_inbound(connp->conn_latch, ii);
4333 	}
4334 	return (B_TRUE);
4335 }
4336 
4337 /*
4338  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4339  * and to arrange for power-fanout assist.  The ULP is identified by
4340  * adding a single byte at the end of the original bind message.
4341  * A ULP other than UDP or TCP that wishes to be recognized passes
4342  * down a bind with a zero length address.
4343  *
4344  * The binding works as follows:
4345  * - A zero byte address means just bind to the protocol.
4346  * - A four byte address is treated as a request to validate
4347  *   that the address is a valid local address, appropriate for
4348  *   an application to bind to. This does not affect any fanout
4349  *   information in IP.
4350  * - A sizeof sin_t byte address is used to bind to only the local address
4351  *   and port.
4352  * - A sizeof ipa_conn_t byte address contains complete fanout information
4353  *   consisting of local and remote addresses and ports.  In
4354  *   this case, the addresses are both validated as appropriate
4355  *   for this operation, and, if so, the information is retained
4356  *   for use in the inbound fanout.
4357  *
4358  * The ULP (except in the zero-length bind) can append an
4359  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4360  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4361  * a copy of the source or destination IRE (source for local bind;
4362  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4363  * policy information contained should be copied on to the conn.
4364  *
4365  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4366  */
4367 mblk_t *
4368 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4369 {
4370 	ssize_t		len;
4371 	struct T_bind_req	*tbr;
4372 	sin_t		*sin;
4373 	ipa_conn_t	*ac;
4374 	uchar_t		*ucp;
4375 	mblk_t		*mp1;
4376 	boolean_t	ire_requested;
4377 	boolean_t	ipsec_policy_set = B_FALSE;
4378 	int		error = 0;
4379 	int		protocol;
4380 	ipa_conn_x_t	*acx;
4381 
4382 	ASSERT(!connp->conn_af_isv6);
4383 	connp->conn_pkt_isv6 = B_FALSE;
4384 
4385 	len = MBLKL(mp);
4386 	if (len < (sizeof (*tbr) + 1)) {
4387 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4388 		    "ip_bind: bogus msg, len %ld", len);
4389 		/* XXX: Need to return something better */
4390 		goto bad_addr;
4391 	}
4392 	/* Back up and extract the protocol identifier. */
4393 	mp->b_wptr--;
4394 	protocol = *mp->b_wptr & 0xFF;
4395 	tbr = (struct T_bind_req *)mp->b_rptr;
4396 	/* Reset the message type in preparation for shipping it back. */
4397 	DB_TYPE(mp) = M_PCPROTO;
4398 
4399 	connp->conn_ulp = (uint8_t)protocol;
4400 
4401 	/*
4402 	 * Check for a zero length address.  This is from a protocol that
4403 	 * wants to register to receive all packets of its type.
4404 	 */
4405 	if (tbr->ADDR_length == 0) {
4406 		/*
4407 		 * These protocols are now intercepted in ip_bind_v6().
4408 		 * Reject protocol-level binds here for now.
4409 		 *
4410 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4411 		 * so that the protocol type cannot be SCTP.
4412 		 */
4413 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4414 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4415 			goto bad_addr;
4416 		}
4417 
4418 		/*
4419 		 *
4420 		 * The udp module never sends down a zero-length address,
4421 		 * and allowing this on a labeled system will break MLP
4422 		 * functionality.
4423 		 */
4424 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4425 			goto bad_addr;
4426 
4427 		if (connp->conn_mac_exempt)
4428 			goto bad_addr;
4429 
4430 		/* No hash here really.  The table is big enough. */
4431 		connp->conn_srcv6 = ipv6_all_zeros;
4432 
4433 		ipcl_proto_insert(connp, protocol);
4434 
4435 		tbr->PRIM_type = T_BIND_ACK;
4436 		return (mp);
4437 	}
4438 
4439 	/* Extract the address pointer from the message. */
4440 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4441 	    tbr->ADDR_length);
4442 	if (ucp == NULL) {
4443 		ip1dbg(("ip_bind: no address\n"));
4444 		goto bad_addr;
4445 	}
4446 	if (!OK_32PTR(ucp)) {
4447 		ip1dbg(("ip_bind: unaligned address\n"));
4448 		goto bad_addr;
4449 	}
4450 	/*
4451 	 * Check for trailing mps.
4452 	 */
4453 
4454 	mp1 = mp->b_cont;
4455 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4456 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4457 
4458 	switch (tbr->ADDR_length) {
4459 	default:
4460 		ip1dbg(("ip_bind: bad address length %d\n",
4461 		    (int)tbr->ADDR_length));
4462 		goto bad_addr;
4463 
4464 	case IP_ADDR_LEN:
4465 		/* Verification of local address only */
4466 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4467 		    ire_requested, ipsec_policy_set, B_FALSE);
4468 		break;
4469 
4470 	case sizeof (sin_t):
4471 		sin = (sin_t *)ucp;
4472 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4473 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		break;
4486 
4487 	case sizeof (ipa_conn_x_t):
4488 		acx = (ipa_conn_x_t *)ucp;
4489 		/*
4490 		 * Whether or not to verify destination reachability depends
4491 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4492 		 */
4493 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4494 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4495 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4496 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4497 		break;
4498 	}
4499 	if (error == EINPROGRESS)
4500 		return (NULL);
4501 	else if (error != 0)
4502 		goto bad_addr;
4503 	/*
4504 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4505 	 * We can't do this in ip_bind_insert_ire because the policy
4506 	 * may not have been inherited at that point in time and hence
4507 	 * conn_out_enforce_policy may not be set.
4508 	 */
4509 	mp1 = mp->b_cont;
4510 	if (ire_requested && connp->conn_out_enforce_policy &&
4511 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4512 		ire_t *ire = (ire_t *)mp1->b_rptr;
4513 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4514 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4515 	}
4516 
4517 	/* Send it home. */
4518 	mp->b_datap->db_type = M_PCPROTO;
4519 	tbr->PRIM_type = T_BIND_ACK;
4520 	return (mp);
4521 
4522 bad_addr:
4523 	/*
4524 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4525 	 * a unix errno.
4526 	 */
4527 	if (error > 0)
4528 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4529 	else
4530 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4531 	return (mp);
4532 }
4533 
4534 /*
4535  * Here address is verified to be a valid local address.
4536  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4537  * address is also considered a valid local address.
4538  * In the case of a broadcast/multicast address, however, the
4539  * upper protocol is expected to reset the src address
4540  * to 0 if it sees a IRE_BROADCAST type returned so that
4541  * no packets are emitted with broadcast/multicast address as
4542  * source address (that violates hosts requirements RFC1122)
4543  * The addresses valid for bind are:
4544  *	(1) - INADDR_ANY (0)
4545  *	(2) - IP address of an UP interface
4546  *	(3) - IP address of a DOWN interface
4547  *	(4) - valid local IP broadcast addresses. In this case
4548  *	the conn will only receive packets destined to
4549  *	the specified broadcast address.
4550  *	(5) - a multicast address. In this case
4551  *	the conn will only receive packets destined to
4552  *	the specified multicast address. Note: the
4553  *	application still has to issue an
4554  *	IP_ADD_MEMBERSHIP socket option.
4555  *
4556  * On error, return -1 for TBADADDR otherwise pass the
4557  * errno with TSYSERR reply.
4558  *
4559  * In all the above cases, the bound address must be valid in the current zone.
4560  * When the address is loopback, multicast or broadcast, there might be many
4561  * matching IREs so bind has to look up based on the zone.
4562  *
4563  * Note: lport is in network byte order.
4564  */
4565 int
4566 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4567     boolean_t ire_requested, boolean_t ipsec_policy_set,
4568     boolean_t fanout_insert)
4569 {
4570 	int		error = 0;
4571 	ire_t		*src_ire;
4572 	mblk_t		*policy_mp;
4573 	ipif_t		*ipif;
4574 	zoneid_t	zoneid;
4575 
4576 	if (ipsec_policy_set) {
4577 		policy_mp = mp->b_cont;
4578 	}
4579 
4580 	/*
4581 	 * If it was previously connected, conn_fully_bound would have
4582 	 * been set.
4583 	 */
4584 	connp->conn_fully_bound = B_FALSE;
4585 
4586 	src_ire = NULL;
4587 	ipif = NULL;
4588 
4589 	zoneid = IPCL_ZONEID(connp);
4590 
4591 	if (src_addr) {
4592 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4593 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4594 		/*
4595 		 * If an address other than 0.0.0.0 is requested,
4596 		 * we verify that it is a valid address for bind
4597 		 * Note: Following code is in if-else-if form for
4598 		 * readability compared to a condition check.
4599 		 */
4600 		/* LINTED - statement has no consequent */
4601 		if (IRE_IS_LOCAL(src_ire)) {
4602 			/*
4603 			 * (2) Bind to address of local UP interface
4604 			 */
4605 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4606 			/*
4607 			 * (4) Bind to broadcast address
4608 			 * Note: permitted only from transports that
4609 			 * request IRE
4610 			 */
4611 			if (!ire_requested)
4612 				error = EADDRNOTAVAIL;
4613 		} else {
4614 			/*
4615 			 * (3) Bind to address of local DOWN interface
4616 			 * (ipif_lookup_addr() looks up all interfaces
4617 			 * but we do not get here for UP interfaces
4618 			 * - case (2) above)
4619 			 * We put the protocol byte back into the mblk
4620 			 * since we may come back via ip_wput_nondata()
4621 			 * later with this mblk if ipif_lookup_addr chooses
4622 			 * to defer processing.
4623 			 */
4624 			*mp->b_wptr++ = (char)connp->conn_ulp;
4625 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4626 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4627 			    &error)) != NULL) {
4628 				ipif_refrele(ipif);
4629 			} else if (error == EINPROGRESS) {
4630 				if (src_ire != NULL)
4631 					ire_refrele(src_ire);
4632 				return (EINPROGRESS);
4633 			} else if (CLASSD(src_addr)) {
4634 				error = 0;
4635 				if (src_ire != NULL)
4636 					ire_refrele(src_ire);
4637 				/*
4638 				 * (5) bind to multicast address.
4639 				 * Fake out the IRE returned to upper
4640 				 * layer to be a broadcast IRE.
4641 				 */
4642 				src_ire = ire_ctable_lookup(
4643 				    INADDR_BROADCAST, INADDR_ANY,
4644 				    IRE_BROADCAST, NULL, zoneid, NULL,
4645 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4646 				if (src_ire == NULL || !ire_requested)
4647 					error = EADDRNOTAVAIL;
4648 			} else {
4649 				/*
4650 				 * Not a valid address for bind
4651 				 */
4652 				error = EADDRNOTAVAIL;
4653 			}
4654 			/*
4655 			 * Just to keep it consistent with the processing in
4656 			 * ip_bind_v4()
4657 			 */
4658 			mp->b_wptr--;
4659 		}
4660 		if (error) {
4661 			/* Red Alert!  Attempting to be a bogon! */
4662 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4663 			    ntohl(src_addr)));
4664 			goto bad_addr;
4665 		}
4666 	}
4667 
4668 	/*
4669 	 * Allow setting new policies. For example, disconnects come
4670 	 * down as ipa_t bind. As we would have set conn_policy_cached
4671 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4672 	 * can change after the disconnect.
4673 	 */
4674 	connp->conn_policy_cached = B_FALSE;
4675 
4676 	/*
4677 	 * If not fanout_insert this was just an address verification
4678 	 */
4679 	if (fanout_insert) {
4680 		/*
4681 		 * The addresses have been verified. Time to insert in
4682 		 * the correct fanout list.
4683 		 */
4684 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4685 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4686 		connp->conn_lport = lport;
4687 		connp->conn_fport = 0;
4688 		/*
4689 		 * Do we need to add a check to reject Multicast packets
4690 		 *
4691 		 * We need to make sure that the conn_recv is set to a non-null
4692 		 * value before we insert the conn into the classifier table.
4693 		 * This is to avoid a race with an incoming packet which does an
4694 		 * ipcl_classify().
4695 		 */
4696 		if (*mp->b_wptr == IPPROTO_TCP)
4697 			connp->conn_recv = tcp_conn_request;
4698 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4699 	}
4700 
4701 	if (error == 0) {
4702 		if (ire_requested) {
4703 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4704 				error = -1;
4705 				/* Falls through to bad_addr */
4706 			}
4707 		} else if (ipsec_policy_set) {
4708 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4709 				error = -1;
4710 				/* Falls through to bad_addr */
4711 			}
4712 		}
4713 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4714 		connp->conn_recv = tcp_input;
4715 	}
4716 bad_addr:
4717 	if (error != 0) {
4718 		if (connp->conn_anon_port) {
4719 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4720 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4721 			    B_FALSE);
4722 		}
4723 		connp->conn_mlp_type = mlptSingle;
4724 	}
4725 	if (src_ire != NULL)
4726 		IRE_REFRELE(src_ire);
4727 	if (ipsec_policy_set) {
4728 		ASSERT(policy_mp == mp->b_cont);
4729 		ASSERT(policy_mp != NULL);
4730 		freeb(policy_mp);
4731 		/*
4732 		 * As of now assume that nothing else accompanies
4733 		 * IPSEC_POLICY_SET.
4734 		 */
4735 		mp->b_cont = NULL;
4736 	}
4737 	return (error);
4738 }
4739 
4740 /*
4741  * Verify that both the source and destination addresses
4742  * are valid.  If verify_dst is false, then the destination address may be
4743  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4744  * destination reachability, while tunnels do not.
4745  * Note that we allow connect to broadcast and multicast
4746  * addresses when ire_requested is set. Thus the ULP
4747  * has to check for IRE_BROADCAST and multicast.
4748  *
4749  * Returns zero if ok.
4750  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4751  * (for use with TSYSERR reply).
4752  *
4753  * Note: lport and fport are in network byte order.
4754  */
4755 int
4756 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4757     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4758     boolean_t ire_requested, boolean_t ipsec_policy_set,
4759     boolean_t fanout_insert, boolean_t verify_dst)
4760 {
4761 	ire_t		*src_ire;
4762 	ire_t		*dst_ire;
4763 	int		error = 0;
4764 	int 		protocol;
4765 	mblk_t		*policy_mp;
4766 	ire_t		*sire = NULL;
4767 	ire_t		*md_dst_ire = NULL;
4768 	ire_t		*lso_dst_ire = NULL;
4769 	ill_t		*ill = NULL;
4770 	zoneid_t	zoneid;
4771 	ipaddr_t	src_addr = *src_addrp;
4772 
4773 	src_ire = dst_ire = NULL;
4774 	protocol = *mp->b_wptr & 0xFF;
4775 
4776 	/*
4777 	 * If we never got a disconnect before, clear it now.
4778 	 */
4779 	connp->conn_fully_bound = B_FALSE;
4780 
4781 	if (ipsec_policy_set) {
4782 		policy_mp = mp->b_cont;
4783 	}
4784 
4785 	zoneid = IPCL_ZONEID(connp);
4786 
4787 	if (CLASSD(dst_addr)) {
4788 		/* Pick up an IRE_BROADCAST */
4789 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4790 		    NULL, zoneid, MBLK_GETLABEL(mp),
4791 		    (MATCH_IRE_RECURSIVE |
4792 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4793 		    MATCH_IRE_SECATTR));
4794 	} else {
4795 		/*
4796 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4797 		 * and onlink ipif is not found set ENETUNREACH error.
4798 		 */
4799 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4800 			ipif_t *ipif;
4801 
4802 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4803 			    dst_addr : connp->conn_nexthop_v4,
4804 			    connp->conn_zoneid);
4805 			if (ipif == NULL) {
4806 				error = ENETUNREACH;
4807 				goto bad_addr;
4808 			}
4809 			ipif_refrele(ipif);
4810 		}
4811 
4812 		if (connp->conn_nexthop_set) {
4813 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4814 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4815 			    MATCH_IRE_SECATTR);
4816 		} else {
4817 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4818 			    &sire, zoneid, MBLK_GETLABEL(mp),
4819 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4820 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4821 			    MATCH_IRE_SECATTR));
4822 		}
4823 	}
4824 	/*
4825 	 * dst_ire can't be a broadcast when not ire_requested.
4826 	 * We also prevent ire's with src address INADDR_ANY to
4827 	 * be used, which are created temporarily for
4828 	 * sending out packets from endpoints that have
4829 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4830 	 * reachable.  If verify_dst is false, the destination needn't be
4831 	 * reachable.
4832 	 *
4833 	 * If we match on a reject or black hole, then we've got a
4834 	 * local failure.  May as well fail out the connect() attempt,
4835 	 * since it's never going to succeed.
4836 	 */
4837 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4838 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4839 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4840 		/*
4841 		 * If we're verifying destination reachability, we always want
4842 		 * to complain here.
4843 		 *
4844 		 * If we're not verifying destination reachability but the
4845 		 * destination has a route, we still want to fail on the
4846 		 * temporary address and broadcast address tests.
4847 		 */
4848 		if (verify_dst || (dst_ire != NULL)) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg("ip_bind_connected: bad connected "
4851 				    "dst %s\n", AF_INET, &dst_addr);
4852 			}
4853 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4854 				error = ENETUNREACH;
4855 			else
4856 				error = EHOSTUNREACH;
4857 			goto bad_addr;
4858 		}
4859 	}
4860 
4861 	/*
4862 	 * We now know that routing will allow us to reach the destination.
4863 	 * Check whether Trusted Solaris policy allows communication with this
4864 	 * host, and pretend that the destination is unreachable if not.
4865 	 *
4866 	 * This is never a problem for TCP, since that transport is known to
4867 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4868 	 * handling.  If the remote is unreachable, it will be detected at that
4869 	 * point, so there's no reason to check it here.
4870 	 *
4871 	 * Note that for sendto (and other datagram-oriented friends), this
4872 	 * check is done as part of the data path label computation instead.
4873 	 * The check here is just to make non-TCP connect() report the right
4874 	 * error.
4875 	 */
4876 	if (dst_ire != NULL && is_system_labeled() &&
4877 	    !IPCL_IS_TCP(connp) &&
4878 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4879 	    connp->conn_mac_exempt) != 0) {
4880 		error = EHOSTUNREACH;
4881 		if (ip_debug > 2) {
4882 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4883 			    AF_INET, &dst_addr);
4884 		}
4885 		goto bad_addr;
4886 	}
4887 
4888 	/*
4889 	 * If the app does a connect(), it means that it will most likely
4890 	 * send more than 1 packet to the destination.  It makes sense
4891 	 * to clear the temporary flag.
4892 	 */
4893 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4894 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4895 		irb_t *irb = dst_ire->ire_bucket;
4896 
4897 		rw_enter(&irb->irb_lock, RW_WRITER);
4898 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4899 		irb->irb_tmp_ire_cnt--;
4900 		rw_exit(&irb->irb_lock);
4901 	}
4902 
4903 	/*
4904 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4905 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4906 	 * eligibility tests for passive connects are handled separately
4907 	 * through tcp_adapt_ire().  We do this before the source address
4908 	 * selection, because dst_ire may change after a call to
4909 	 * ipif_select_source().  This is a best-effort check, as the
4910 	 * packet for this connection may not actually go through
4911 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4912 	 * calling ip_newroute().  This is why we further check on the
4913 	 * IRE during LSO/Multidata packet transmission in
4914 	 * tcp_lsosend()/tcp_multisend().
4915 	 */
4916 	if (!ipsec_policy_set && dst_ire != NULL &&
4917 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4918 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4919 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4920 			lso_dst_ire = dst_ire;
4921 			IRE_REFHOLD(lso_dst_ire);
4922 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4923 			md_dst_ire = dst_ire;
4924 			IRE_REFHOLD(md_dst_ire);
4925 		}
4926 	}
4927 
4928 	if (dst_ire != NULL &&
4929 	    dst_ire->ire_type == IRE_LOCAL &&
4930 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4931 		/*
4932 		 * If the IRE belongs to a different zone, look for a matching
4933 		 * route in the forwarding table and use the source address from
4934 		 * that route.
4935 		 */
4936 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4937 		    zoneid, 0, NULL,
4938 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4939 		    MATCH_IRE_RJ_BHOLE);
4940 		if (src_ire == NULL) {
4941 			error = EHOSTUNREACH;
4942 			goto bad_addr;
4943 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4944 			if (!(src_ire->ire_type & IRE_HOST))
4945 				error = ENETUNREACH;
4946 			else
4947 				error = EHOSTUNREACH;
4948 			goto bad_addr;
4949 		}
4950 		if (src_addr == INADDR_ANY)
4951 			src_addr = src_ire->ire_src_addr;
4952 		ire_refrele(src_ire);
4953 		src_ire = NULL;
4954 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4955 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4956 			src_addr = sire->ire_src_addr;
4957 			ire_refrele(dst_ire);
4958 			dst_ire = sire;
4959 			sire = NULL;
4960 		} else {
4961 			/*
4962 			 * Pick a source address so that a proper inbound
4963 			 * load spreading would happen.
4964 			 */
4965 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4966 			ipif_t *src_ipif = NULL;
4967 			ire_t *ipif_ire;
4968 
4969 			/*
4970 			 * Supply a local source address such that inbound
4971 			 * load spreading happens.
4972 			 *
4973 			 * Determine the best source address on this ill for
4974 			 * the destination.
4975 			 *
4976 			 * 1) For broadcast, we should return a broadcast ire
4977 			 *    found above so that upper layers know that the
4978 			 *    destination address is a broadcast address.
4979 			 *
4980 			 * 2) If this is part of a group, select a better
4981 			 *    source address so that better inbound load
4982 			 *    balancing happens. Do the same if the ipif
4983 			 *    is DEPRECATED.
4984 			 *
4985 			 * 3) If the outgoing interface is part of a usesrc
4986 			 *    group, then try selecting a source address from
4987 			 *    the usesrc ILL.
4988 			 */
4989 			if ((dst_ire->ire_zoneid != zoneid &&
4990 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4991 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4992 			    ((dst_ill->ill_group != NULL) ||
4993 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4994 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4995 				/*
4996 				 * If the destination is reachable via a
4997 				 * given gateway, the selected source address
4998 				 * should be in the same subnet as the gateway.
4999 				 * Otherwise, the destination is not reachable.
5000 				 *
5001 				 * If there are no interfaces on the same subnet
5002 				 * as the destination, ipif_select_source gives
5003 				 * first non-deprecated interface which might be
5004 				 * on a different subnet than the gateway.
5005 				 * This is not desirable. Hence pass the dst_ire
5006 				 * source address to ipif_select_source.
5007 				 * It is sure that the destination is reachable
5008 				 * with the dst_ire source address subnet.
5009 				 * So passing dst_ire source address to
5010 				 * ipif_select_source will make sure that the
5011 				 * selected source will be on the same subnet
5012 				 * as dst_ire source address.
5013 				 */
5014 				ipaddr_t saddr =
5015 				    dst_ire->ire_ipif->ipif_src_addr;
5016 				src_ipif = ipif_select_source(dst_ill,
5017 				    saddr, zoneid);
5018 				if (src_ipif != NULL) {
5019 					if (IS_VNI(src_ipif->ipif_ill)) {
5020 						/*
5021 						 * For VNI there is no
5022 						 * interface route
5023 						 */
5024 						src_addr =
5025 						    src_ipif->ipif_src_addr;
5026 					} else {
5027 						ipif_ire =
5028 						    ipif_to_ire(src_ipif);
5029 						if (ipif_ire != NULL) {
5030 							IRE_REFRELE(dst_ire);
5031 							dst_ire = ipif_ire;
5032 						}
5033 						src_addr =
5034 						    dst_ire->ire_src_addr;
5035 					}
5036 					ipif_refrele(src_ipif);
5037 				} else {
5038 					src_addr = dst_ire->ire_src_addr;
5039 				}
5040 			} else {
5041 				src_addr = dst_ire->ire_src_addr;
5042 			}
5043 		}
5044 	}
5045 
5046 	/*
5047 	 * We do ire_route_lookup() here (and not
5048 	 * interface lookup as we assert that
5049 	 * src_addr should only come from an
5050 	 * UP interface for hard binding.
5051 	 */
5052 	ASSERT(src_ire == NULL);
5053 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5054 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5055 	/* src_ire must be a local|loopback */
5056 	if (!IRE_IS_LOCAL(src_ire)) {
5057 		if (ip_debug > 2) {
5058 			pr_addr_dbg("ip_bind_connected: bad connected "
5059 			    "src %s\n", AF_INET, &src_addr);
5060 		}
5061 		error = EADDRNOTAVAIL;
5062 		goto bad_addr;
5063 	}
5064 
5065 	/*
5066 	 * If the source address is a loopback address, the
5067 	 * destination had best be local or multicast.
5068 	 * The transports that can't handle multicast will reject
5069 	 * those addresses.
5070 	 */
5071 	if (src_ire->ire_type == IRE_LOOPBACK &&
5072 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5073 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5074 		error = -1;
5075 		goto bad_addr;
5076 	}
5077 
5078 	/*
5079 	 * Allow setting new policies. For example, disconnects come
5080 	 * down as ipa_t bind. As we would have set conn_policy_cached
5081 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5082 	 * can change after the disconnect.
5083 	 */
5084 	connp->conn_policy_cached = B_FALSE;
5085 
5086 	/*
5087 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5088 	 * can handle their passed-in conn's.
5089 	 */
5090 
5091 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5092 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5093 	connp->conn_lport = lport;
5094 	connp->conn_fport = fport;
5095 	*src_addrp = src_addr;
5096 
5097 	ASSERT(!(ipsec_policy_set && ire_requested));
5098 	if (ire_requested) {
5099 		iulp_t *ulp_info = NULL;
5100 
5101 		/*
5102 		 * Note that sire will not be NULL if this is an off-link
5103 		 * connection and there is not cache for that dest yet.
5104 		 *
5105 		 * XXX Because of an existing bug, if there are multiple
5106 		 * default routes, the IRE returned now may not be the actual
5107 		 * default route used (default routes are chosen in a
5108 		 * round robin fashion).  So if the metrics for different
5109 		 * default routes are different, we may return the wrong
5110 		 * metrics.  This will not be a problem if the existing
5111 		 * bug is fixed.
5112 		 */
5113 		if (sire != NULL) {
5114 			ulp_info = &(sire->ire_uinfo);
5115 		}
5116 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5117 			error = -1;
5118 			goto bad_addr;
5119 		}
5120 	} else if (ipsec_policy_set) {
5121 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5122 			error = -1;
5123 			goto bad_addr;
5124 		}
5125 	}
5126 
5127 	/*
5128 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5129 	 * we'll cache that.  If we don't, we'll inherit global policy.
5130 	 *
5131 	 * We can't insert until the conn reflects the policy. Note that
5132 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5133 	 * connections where we don't have a policy. This is to prevent
5134 	 * global policy lookups in the inbound path.
5135 	 *
5136 	 * If we insert before we set conn_policy_cached,
5137 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5138 	 * because global policy cound be non-empty. We normally call
5139 	 * ipsec_check_policy() for conn_policy_cached connections only if
5140 	 * ipc_in_enforce_policy is set. But in this case,
5141 	 * conn_policy_cached can get set anytime since we made the
5142 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5143 	 * called, which will make the above assumption false.  Thus, we
5144 	 * need to insert after we set conn_policy_cached.
5145 	 */
5146 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5147 		goto bad_addr;
5148 
5149 	if (fanout_insert) {
5150 		/*
5151 		 * The addresses have been verified. Time to insert in
5152 		 * the correct fanout list.
5153 		 * We need to make sure that the conn_recv is set to a non-null
5154 		 * value before we insert into the classifier table to avoid a
5155 		 * race with an incoming packet which does an ipcl_classify().
5156 		 */
5157 		if (protocol == IPPROTO_TCP)
5158 			connp->conn_recv = tcp_input;
5159 		error = ipcl_conn_insert(connp, protocol, src_addr,
5160 		    dst_addr, connp->conn_ports);
5161 	}
5162 
5163 	if (error == 0) {
5164 		connp->conn_fully_bound = B_TRUE;
5165 		/*
5166 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5167 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5168 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5169 		 * ip_xxinfo_return(), which performs further checks
5170 		 * against them and upon success, returns the LSO/MDT info
5171 		 * mblk which we will attach to the bind acknowledgment.
5172 		 */
5173 		if (lso_dst_ire != NULL) {
5174 			mblk_t *lsoinfo_mp;
5175 
5176 			ASSERT(ill->ill_lso_capab != NULL);
5177 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5178 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5179 				linkb(mp, lsoinfo_mp);
5180 		} else if (md_dst_ire != NULL) {
5181 			mblk_t *mdinfo_mp;
5182 
5183 			ASSERT(ill->ill_mdt_capab != NULL);
5184 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5185 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5186 				linkb(mp, mdinfo_mp);
5187 		}
5188 	}
5189 bad_addr:
5190 	if (ipsec_policy_set) {
5191 		ASSERT(policy_mp == mp->b_cont);
5192 		ASSERT(policy_mp != NULL);
5193 		freeb(policy_mp);
5194 		/*
5195 		 * As of now assume that nothing else accompanies
5196 		 * IPSEC_POLICY_SET.
5197 		 */
5198 		mp->b_cont = NULL;
5199 	}
5200 	if (src_ire != NULL)
5201 		IRE_REFRELE(src_ire);
5202 	if (dst_ire != NULL)
5203 		IRE_REFRELE(dst_ire);
5204 	if (sire != NULL)
5205 		IRE_REFRELE(sire);
5206 	if (md_dst_ire != NULL)
5207 		IRE_REFRELE(md_dst_ire);
5208 	if (lso_dst_ire != NULL)
5209 		IRE_REFRELE(lso_dst_ire);
5210 	return (error);
5211 }
5212 
5213 /*
5214  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5215  * Prefers dst_ire over src_ire.
5216  */
5217 static boolean_t
5218 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5219 {
5220 	mblk_t	*mp1;
5221 	ire_t *ret_ire = NULL;
5222 
5223 	mp1 = mp->b_cont;
5224 	ASSERT(mp1 != NULL);
5225 
5226 	if (ire != NULL) {
5227 		/*
5228 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5229 		 * appended mblk. Its <upper protocol>'s
5230 		 * job to make sure there is room.
5231 		 */
5232 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5233 			return (0);
5234 
5235 		mp1->b_datap->db_type = IRE_DB_TYPE;
5236 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5237 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5238 		ret_ire = (ire_t *)mp1->b_rptr;
5239 		/*
5240 		 * Pass the latest setting of the ip_path_mtu_discovery and
5241 		 * copy the ulp info if any.
5242 		 */
5243 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5244 		    IPH_DF : 0;
5245 		if (ulp_info != NULL) {
5246 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5247 			    sizeof (iulp_t));
5248 		}
5249 		ret_ire->ire_mp = mp1;
5250 	} else {
5251 		/*
5252 		 * No IRE was found. Remove IRE mblk.
5253 		 */
5254 		mp->b_cont = mp1->b_cont;
5255 		freeb(mp1);
5256 	}
5257 
5258 	return (1);
5259 }
5260 
5261 /*
5262  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5263  * the final piece where we don't.  Return a pointer to the first mblk in the
5264  * result, and update the pointer to the next mblk to chew on.  If anything
5265  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5266  * NULL pointer.
5267  */
5268 mblk_t *
5269 ip_carve_mp(mblk_t **mpp, ssize_t len)
5270 {
5271 	mblk_t	*mp0;
5272 	mblk_t	*mp1;
5273 	mblk_t	*mp2;
5274 
5275 	if (!len || !mpp || !(mp0 = *mpp))
5276 		return (NULL);
5277 	/* If we aren't going to consume the first mblk, we need a dup. */
5278 	if (mp0->b_wptr - mp0->b_rptr > len) {
5279 		mp1 = dupb(mp0);
5280 		if (mp1) {
5281 			/* Partition the data between the two mblks. */
5282 			mp1->b_wptr = mp1->b_rptr + len;
5283 			mp0->b_rptr = mp1->b_wptr;
5284 			/*
5285 			 * after adjustments if mblk not consumed is now
5286 			 * unaligned, try to align it. If this fails free
5287 			 * all messages and let upper layer recover.
5288 			 */
5289 			if (!OK_32PTR(mp0->b_rptr)) {
5290 				if (!pullupmsg(mp0, -1)) {
5291 					freemsg(mp0);
5292 					freemsg(mp1);
5293 					*mpp = NULL;
5294 					return (NULL);
5295 				}
5296 			}
5297 		}
5298 		return (mp1);
5299 	}
5300 	/* Eat through as many mblks as we need to get len bytes. */
5301 	len -= mp0->b_wptr - mp0->b_rptr;
5302 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5303 		if (mp2->b_wptr - mp2->b_rptr > len) {
5304 			/*
5305 			 * We won't consume the entire last mblk.  Like
5306 			 * above, dup and partition it.
5307 			 */
5308 			mp1->b_cont = dupb(mp2);
5309 			mp1 = mp1->b_cont;
5310 			if (!mp1) {
5311 				/*
5312 				 * Trouble.  Rather than go to a lot of
5313 				 * trouble to clean up, we free the messages.
5314 				 * This won't be any worse than losing it on
5315 				 * the wire.
5316 				 */
5317 				freemsg(mp0);
5318 				freemsg(mp2);
5319 				*mpp = NULL;
5320 				return (NULL);
5321 			}
5322 			mp1->b_wptr = mp1->b_rptr + len;
5323 			mp2->b_rptr = mp1->b_wptr;
5324 			/*
5325 			 * after adjustments if mblk not consumed is now
5326 			 * unaligned, try to align it. If this fails free
5327 			 * all messages and let upper layer recover.
5328 			 */
5329 			if (!OK_32PTR(mp2->b_rptr)) {
5330 				if (!pullupmsg(mp2, -1)) {
5331 					freemsg(mp0);
5332 					freemsg(mp2);
5333 					*mpp = NULL;
5334 					return (NULL);
5335 				}
5336 			}
5337 			*mpp = mp2;
5338 			return (mp0);
5339 		}
5340 		/* Decrement len by the amount we just got. */
5341 		len -= mp2->b_wptr - mp2->b_rptr;
5342 	}
5343 	/*
5344 	 * len should be reduced to zero now.  If not our caller has
5345 	 * screwed up.
5346 	 */
5347 	if (len) {
5348 		/* Shouldn't happen! */
5349 		freemsg(mp0);
5350 		*mpp = NULL;
5351 		return (NULL);
5352 	}
5353 	/*
5354 	 * We consumed up to exactly the end of an mblk.  Detach the part
5355 	 * we are returning from the rest of the chain.
5356 	 */
5357 	mp1->b_cont = NULL;
5358 	*mpp = mp2;
5359 	return (mp0);
5360 }
5361 
5362 /* The ill stream is being unplumbed. Called from ip_close */
5363 int
5364 ip_modclose(ill_t *ill)
5365 {
5366 
5367 	boolean_t success;
5368 	ipsq_t	*ipsq;
5369 	ipif_t	*ipif;
5370 	queue_t	*q = ill->ill_rq;
5371 	hook_nic_event_t *info;
5372 	clock_t timeout;
5373 
5374 	/*
5375 	 * Wait for the ACKs of all deferred control messages to be processed.
5376 	 * In particular, we wait for a potential capability reset initiated
5377 	 * in ip_sioctl_plink() to complete before proceeding.
5378 	 *
5379 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5380 	 * in case the driver never replies.
5381 	 */
5382 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5383 	mutex_enter(&ill->ill_lock);
5384 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5385 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5386 			/* Timeout */
5387 			break;
5388 		}
5389 	}
5390 	mutex_exit(&ill->ill_lock);
5391 
5392 	/*
5393 	 * Forcibly enter the ipsq after some delay. This is to take
5394 	 * care of the case when some ioctl does not complete because
5395 	 * we sent a control message to the driver and it did not
5396 	 * send us a reply. We want to be able to at least unplumb
5397 	 * and replumb rather than force the user to reboot the system.
5398 	 */
5399 	success = ipsq_enter(ill, B_FALSE);
5400 
5401 	/*
5402 	 * Open/close/push/pop is guaranteed to be single threaded
5403 	 * per stream by STREAMS. FS guarantees that all references
5404 	 * from top are gone before close is called. So there can't
5405 	 * be another close thread that has set CONDEMNED on this ill.
5406 	 * and cause ipsq_enter to return failure.
5407 	 */
5408 	ASSERT(success);
5409 	ipsq = ill->ill_phyint->phyint_ipsq;
5410 
5411 	/*
5412 	 * Mark it condemned. No new reference will be made to this ill.
5413 	 * Lookup functions will return an error. Threads that try to
5414 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5415 	 * that the refcnt will drop down to zero.
5416 	 */
5417 	mutex_enter(&ill->ill_lock);
5418 	ill->ill_state_flags |= ILL_CONDEMNED;
5419 	for (ipif = ill->ill_ipif; ipif != NULL;
5420 	    ipif = ipif->ipif_next) {
5421 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5422 	}
5423 	/*
5424 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5425 	 * returns  error if ILL_CONDEMNED is set
5426 	 */
5427 	cv_broadcast(&ill->ill_cv);
5428 	mutex_exit(&ill->ill_lock);
5429 
5430 	/*
5431 	 * Send all the deferred control messages downstream which came in
5432 	 * during the small window right before ipsq_enter(). We do this
5433 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5434 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5435 	 */
5436 	ill_send_all_deferred_mp(ill);
5437 
5438 	/*
5439 	 * Shut down fragmentation reassembly.
5440 	 * ill_frag_timer won't start a timer again.
5441 	 * Now cancel any existing timer
5442 	 */
5443 	(void) untimeout(ill->ill_frag_timer_id);
5444 	(void) ill_frag_timeout(ill, 0);
5445 
5446 	/*
5447 	 * If MOVE was in progress, clear the
5448 	 * move_in_progress fields also.
5449 	 */
5450 	if (ill->ill_move_in_progress) {
5451 		ILL_CLEAR_MOVE(ill);
5452 	}
5453 
5454 	/*
5455 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5456 	 * this ill. Then wait for the refcnts to drop to zero.
5457 	 * ill_is_quiescent checks whether the ill is really quiescent.
5458 	 * Then make sure that threads that are waiting to enter the
5459 	 * ipsq have seen the error returned by ipsq_enter and have
5460 	 * gone away. Then we call ill_delete_tail which does the
5461 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5462 	 */
5463 	ill_delete(ill);
5464 	mutex_enter(&ill->ill_lock);
5465 	while (!ill_is_quiescent(ill))
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 	while (ill->ill_waiters)
5468 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5469 
5470 	mutex_exit(&ill->ill_lock);
5471 
5472 	/* qprocsoff is called in ill_delete_tail */
5473 	ill_delete_tail(ill);
5474 
5475 	/*
5476 	 * Walk through all upper (conn) streams and qenable
5477 	 * those that have queued data.
5478 	 * close synchronization needs this to
5479 	 * be done to ensure that all upper layers blocked
5480 	 * due to flow control to the closing device
5481 	 * get unblocked.
5482 	 */
5483 	ip1dbg(("ip_wsrv: walking\n"));
5484 	conn_walk_drain();
5485 
5486 	mutex_enter(&ip_mi_lock);
5487 	mi_close_unlink(&ip_g_head, (IDP)ill);
5488 	mutex_exit(&ip_mi_lock);
5489 
5490 	/*
5491 	 * credp could be null if the open didn't succeed and ip_modopen
5492 	 * itself calls ip_close.
5493 	 */
5494 	if (ill->ill_credp != NULL)
5495 		crfree(ill->ill_credp);
5496 
5497 	/*
5498 	 * Unhook the nic event message from the ill and enqueue it into the nic
5499 	 * event taskq.
5500 	 */
5501 	if ((info = ill->ill_nic_event_info) != NULL) {
5502 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5503 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5504 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5505 			if (info->hne_data != NULL)
5506 				kmem_free(info->hne_data, info->hne_datalen);
5507 			kmem_free(info, sizeof (hook_nic_event_t));
5508 		}
5509 		ill->ill_nic_event_info = NULL;
5510 	}
5511 
5512 	mi_close_free((IDP)ill);
5513 	q->q_ptr = WR(q)->q_ptr = NULL;
5514 
5515 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5516 
5517 	return (0);
5518 }
5519 
5520 /*
5521  * This is called as part of close() for both IP and UDP
5522  * in order to quiesce the conn.
5523  */
5524 void
5525 ip_quiesce_conn(conn_t *connp)
5526 {
5527 	boolean_t	drain_cleanup_reqd = B_FALSE;
5528 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5529 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5530 
5531 	ASSERT(!IPCL_IS_TCP(connp));
5532 
5533 	/*
5534 	 * Mark the conn as closing, and this conn must not be
5535 	 * inserted in future into any list. Eg. conn_drain_insert(),
5536 	 * won't insert this conn into the conn_drain_list.
5537 	 * Similarly ill_pending_mp_add() will not add any mp to
5538 	 * the pending mp list, after this conn has started closing.
5539 	 *
5540 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5541 	 * cannot get set henceforth.
5542 	 */
5543 	mutex_enter(&connp->conn_lock);
5544 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5545 	connp->conn_state_flags |= CONN_CLOSING;
5546 	if (connp->conn_idl != NULL)
5547 		drain_cleanup_reqd = B_TRUE;
5548 	if (connp->conn_oper_pending_ill != NULL)
5549 		conn_ioctl_cleanup_reqd = B_TRUE;
5550 	if (connp->conn_ilg_inuse != 0)
5551 		ilg_cleanup_reqd = B_TRUE;
5552 	mutex_exit(&connp->conn_lock);
5553 
5554 	if (IPCL_IS_UDP(connp))
5555 		udp_quiesce_conn(connp);
5556 
5557 	if (conn_ioctl_cleanup_reqd)
5558 		conn_ioctl_cleanup(connp);
5559 
5560 	if (is_system_labeled() && connp->conn_anon_port) {
5561 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5562 		    connp->conn_mlp_type, connp->conn_ulp,
5563 		    ntohs(connp->conn_lport), B_FALSE);
5564 		connp->conn_anon_port = 0;
5565 	}
5566 	connp->conn_mlp_type = mlptSingle;
5567 
5568 	/*
5569 	 * Remove this conn from any fanout list it is on.
5570 	 * and then wait for any threads currently operating
5571 	 * on this endpoint to finish
5572 	 */
5573 	ipcl_hash_remove(connp);
5574 
5575 	/*
5576 	 * Remove this conn from the drain list, and do
5577 	 * any other cleanup that may be required.
5578 	 * (Only non-tcp streams may have a non-null conn_idl.
5579 	 * TCP streams are never flow controlled, and
5580 	 * conn_idl will be null)
5581 	 */
5582 	if (drain_cleanup_reqd)
5583 		conn_drain_tail(connp, B_TRUE);
5584 
5585 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5586 		(void) ip_mrouter_done(NULL);
5587 
5588 	if (ilg_cleanup_reqd)
5589 		ilg_delete_all(connp);
5590 
5591 	conn_delete_ire(connp, NULL);
5592 
5593 	/*
5594 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5595 	 * callers from write side can't be there now because close
5596 	 * is in progress. The only other caller is ipcl_walk
5597 	 * which checks for the condemned flag.
5598 	 */
5599 	mutex_enter(&connp->conn_lock);
5600 	connp->conn_state_flags |= CONN_CONDEMNED;
5601 	while (connp->conn_ref != 1)
5602 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5603 	connp->conn_state_flags |= CONN_QUIESCED;
5604 	mutex_exit(&connp->conn_lock);
5605 }
5606 
5607 /* ARGSUSED */
5608 int
5609 ip_close(queue_t *q, int flags)
5610 {
5611 	conn_t		*connp;
5612 
5613 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5614 
5615 	/*
5616 	 * Call the appropriate delete routine depending on whether this is
5617 	 * a module or device.
5618 	 */
5619 	if (WR(q)->q_next != NULL) {
5620 		/* This is a module close */
5621 		return (ip_modclose((ill_t *)q->q_ptr));
5622 	}
5623 
5624 	connp = q->q_ptr;
5625 	ip_quiesce_conn(connp);
5626 
5627 	qprocsoff(q);
5628 
5629 	/*
5630 	 * Now we are truly single threaded on this stream, and can
5631 	 * delete the things hanging off the connp, and finally the connp.
5632 	 * We removed this connp from the fanout list, it cannot be
5633 	 * accessed thru the fanouts, and we already waited for the
5634 	 * conn_ref to drop to 0. We are already in close, so
5635 	 * there cannot be any other thread from the top. qprocsoff
5636 	 * has completed, and service has completed or won't run in
5637 	 * future.
5638 	 */
5639 	ASSERT(connp->conn_ref == 1);
5640 
5641 	/*
5642 	 * A conn which was previously marked as IPCL_UDP cannot
5643 	 * retain the flag because it would have been cleared by
5644 	 * udp_close().
5645 	 */
5646 	ASSERT(!IPCL_IS_UDP(connp));
5647 
5648 	if (connp->conn_latch != NULL) {
5649 		IPLATCH_REFRELE(connp->conn_latch);
5650 		connp->conn_latch = NULL;
5651 	}
5652 	if (connp->conn_policy != NULL) {
5653 		IPPH_REFRELE(connp->conn_policy);
5654 		connp->conn_policy = NULL;
5655 	}
5656 	if (connp->conn_ipsec_opt_mp != NULL) {
5657 		freemsg(connp->conn_ipsec_opt_mp);
5658 		connp->conn_ipsec_opt_mp = NULL;
5659 	}
5660 
5661 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5662 
5663 	connp->conn_ref--;
5664 	ipcl_conn_destroy(connp);
5665 
5666 	q->q_ptr = WR(q)->q_ptr = NULL;
5667 	return (0);
5668 }
5669 
5670 int
5671 ip_snmpmod_close(queue_t *q)
5672 {
5673 	conn_t *connp = Q_TO_CONN(q);
5674 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5675 
5676 	qprocsoff(q);
5677 
5678 	if (connp->conn_flags & IPCL_UDPMOD)
5679 		udp_close_free(connp);
5680 
5681 	if (connp->conn_cred != NULL) {
5682 		crfree(connp->conn_cred);
5683 		connp->conn_cred = NULL;
5684 	}
5685 	CONN_DEC_REF(connp);
5686 	q->q_ptr = WR(q)->q_ptr = NULL;
5687 	return (0);
5688 }
5689 
5690 /*
5691  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5692  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5693  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5694  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5695  * queues as we never enqueue messages there and we don't handle any ioctls.
5696  * Everything else is freed.
5697  */
5698 void
5699 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5700 {
5701 	conn_t	*connp = q->q_ptr;
5702 	pfi_t	setfn;
5703 	pfi_t	getfn;
5704 
5705 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5706 
5707 	switch (DB_TYPE(mp)) {
5708 	case M_PROTO:
5709 	case M_PCPROTO:
5710 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5711 		    ((((union T_primitives *)mp->b_rptr)->type ==
5712 			T_SVR4_OPTMGMT_REQ) ||
5713 		    (((union T_primitives *)mp->b_rptr)->type ==
5714 			T_OPTMGMT_REQ))) {
5715 			/*
5716 			 * This is the only TPI primitive supported. Its
5717 			 * handling does not require tcp_t, but it does require
5718 			 * conn_t to check permissions.
5719 			 */
5720 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5721 
5722 			if (connp->conn_flags & IPCL_TCPMOD) {
5723 				setfn = tcp_snmp_set;
5724 				getfn = tcp_snmp_get;
5725 			} else {
5726 				setfn = udp_snmp_set;
5727 				getfn = udp_snmp_get;
5728 			}
5729 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5730 				freemsg(mp);
5731 				return;
5732 			}
5733 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5734 		    != NULL)
5735 			qreply(q, mp);
5736 		break;
5737 	case M_FLUSH:
5738 	case M_IOCTL:
5739 		putnext(q, mp);
5740 		break;
5741 	default:
5742 		freemsg(mp);
5743 		break;
5744 	}
5745 }
5746 
5747 /* Return the IP checksum for the IP header at "iph". */
5748 uint16_t
5749 ip_csum_hdr(ipha_t *ipha)
5750 {
5751 	uint16_t	*uph;
5752 	uint32_t	sum;
5753 	int		opt_len;
5754 
5755 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5756 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5757 	uph = (uint16_t *)ipha;
5758 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5759 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5760 	if (opt_len > 0) {
5761 		do {
5762 			sum += uph[10];
5763 			sum += uph[11];
5764 			uph += 2;
5765 		} while (--opt_len);
5766 	}
5767 	sum = (sum & 0xFFFF) + (sum >> 16);
5768 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5769 	if (sum == 0xffff)
5770 		sum = 0;
5771 	return ((uint16_t)sum);
5772 }
5773 
5774 void
5775 ip_ddi_destroy(void)
5776 {
5777 	ipv4_hook_destroy();
5778 	ipv6_hook_destroy();
5779 	ip_net_destroy();
5780 
5781 	tnet_fini();
5782 	tcp_ddi_destroy();
5783 	sctp_ddi_destroy();
5784 	ipsec_loader_destroy();
5785 	ipsec_policy_destroy();
5786 	ipsec_kstat_destroy();
5787 	nd_free(&ip_g_nd);
5788 	mutex_destroy(&igmp_timer_lock);
5789 	mutex_destroy(&mld_timer_lock);
5790 	mutex_destroy(&igmp_slowtimeout_lock);
5791 	mutex_destroy(&mld_slowtimeout_lock);
5792 	mutex_destroy(&ip_mi_lock);
5793 	mutex_destroy(&rts_clients.connf_lock);
5794 	ip_ire_fini();
5795 	ip6_asp_free();
5796 	conn_drain_fini();
5797 	ipcl_destroy();
5798 	inet_minor_destroy(ip_minor_arena);
5799 	icmp_kstat_fini();
5800 	ip_kstat_fini();
5801 	rw_destroy(&ipsec_capab_ills_lock);
5802 	rw_destroy(&ill_g_usesrc_lock);
5803 	ip_drop_unregister(&ip_dropper);
5804 }
5805 
5806 
5807 void
5808 ip_ddi_init(void)
5809 {
5810 	TCP6_MAJ = ddi_name_to_major(TCP6);
5811 	TCP_MAJ	= ddi_name_to_major(TCP);
5812 	SCTP_MAJ = ddi_name_to_major(SCTP);
5813 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5814 
5815 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5816 
5817 	/* IP's IPsec code calls the packet dropper */
5818 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5819 
5820 	if (!ip_g_nd) {
5821 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5822 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5823 			nd_free(&ip_g_nd);
5824 		}
5825 	}
5826 
5827 	ipsec_loader_init();
5828 	ipsec_policy_init();
5829 	ipsec_kstat_init();
5830 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5831 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5832 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5833 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5834 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5835 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5836 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5837 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5838 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5839 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5840 
5841 	/*
5842 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5843 	 * initial devices: ip, ip6, tcp, tcp6.
5844 	 */
5845 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5846 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5847 		cmn_err(CE_PANIC,
5848 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5849 	}
5850 
5851 	ipcl_init();
5852 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5853 	ip_ire_init();
5854 	ip6_asp_init();
5855 	ipif_init();
5856 	conn_drain_init();
5857 	tcp_ddi_init();
5858 	sctp_ddi_init();
5859 
5860 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5861 
5862 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5863 		"net", KSTAT_TYPE_NAMED,
5864 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5865 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5866 		ip_kstat->ks_data = &ip_statistics;
5867 		kstat_install(ip_kstat);
5868 	}
5869 	ip_kstat_init();
5870 	ip6_kstat_init();
5871 	icmp_kstat_init();
5872 	ipsec_loader_start();
5873 	tnet_init();
5874 
5875 	ip_net_init();
5876 	ipv4_hook_init();
5877 	ipv6_hook_init();
5878 }
5879 
5880 /*
5881  * Allocate and initialize a DLPI template of the specified length.  (May be
5882  * called as writer.)
5883  */
5884 mblk_t *
5885 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5886 {
5887 	mblk_t	*mp;
5888 
5889 	mp = allocb(len, BPRI_MED);
5890 	if (!mp)
5891 		return (NULL);
5892 
5893 	/*
5894 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5895 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5896 	 * that other DLPI are M_PROTO.
5897 	 */
5898 	if (prim == DL_INFO_REQ) {
5899 		mp->b_datap->db_type = M_PCPROTO;
5900 	} else {
5901 		mp->b_datap->db_type = M_PROTO;
5902 	}
5903 
5904 	mp->b_wptr = mp->b_rptr + len;
5905 	bzero(mp->b_rptr, len);
5906 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5907 	return (mp);
5908 }
5909 
5910 const char *
5911 dlpi_prim_str(int prim)
5912 {
5913 	switch (prim) {
5914 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5915 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5916 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5917 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5918 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5919 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5920 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5921 	case DL_OK_ACK:		return ("DL_OK_ACK");
5922 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5923 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5924 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5925 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5926 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5927 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5928 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5929 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5930 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5931 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5932 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5933 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5934 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5935 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5936 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5937 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5938 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5939 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5940 	default:		return ("<unknown primitive>");
5941 	}
5942 }
5943 
5944 const char *
5945 dlpi_err_str(int err)
5946 {
5947 	switch (err) {
5948 	case DL_ACCESS:		return ("DL_ACCESS");
5949 	case DL_BADADDR:	return ("DL_BADADDR");
5950 	case DL_BADCORR:	return ("DL_BADCORR");
5951 	case DL_BADDATA:	return ("DL_BADDATA");
5952 	case DL_BADPPA:		return ("DL_BADPPA");
5953 	case DL_BADPRIM:	return ("DL_BADPRIM");
5954 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5955 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5956 	case DL_BADSAP:		return ("DL_BADSAP");
5957 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5958 	case DL_BOUND:		return ("DL_BOUND");
5959 	case DL_INITFAILED:	return ("DL_INITFAILED");
5960 	case DL_NOADDR:		return ("DL_NOADDR");
5961 	case DL_NOTINIT:	return ("DL_NOTINIT");
5962 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5963 	case DL_SYSERR:		return ("DL_SYSERR");
5964 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5965 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5966 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5967 	case DL_TOOMANY:	return ("DL_TOOMANY");
5968 	case DL_NOTENAB:	return ("DL_NOTENAB");
5969 	case DL_BUSY:		return ("DL_BUSY");
5970 	case DL_NOAUTO:		return ("DL_NOAUTO");
5971 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5972 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5973 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5974 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5975 	case DL_PENDING:	return ("DL_PENDING");
5976 	default:		return ("<unknown error>");
5977 	}
5978 }
5979 
5980 /*
5981  * Debug formatting routine.  Returns a character string representation of the
5982  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5983  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5984  *
5985  * Once the ndd table-printing interfaces are removed, this can be changed to
5986  * standard dotted-decimal form.
5987  */
5988 char *
5989 ip_dot_addr(ipaddr_t addr, char *buf)
5990 {
5991 	uint8_t *ap = (uint8_t *)&addr;
5992 
5993 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5994 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5995 	return (buf);
5996 }
5997 
5998 /*
5999  * Write the given MAC address as a printable string in the usual colon-
6000  * separated format.
6001  */
6002 const char *
6003 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6004 {
6005 	char *bp;
6006 
6007 	if (alen == 0 || buflen < 4)
6008 		return ("?");
6009 	bp = buf;
6010 	for (;;) {
6011 		/*
6012 		 * If there are more MAC address bytes available, but we won't
6013 		 * have any room to print them, then add "..." to the string
6014 		 * instead.  See below for the 'magic number' explanation.
6015 		 */
6016 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6017 			(void) strcpy(bp, "...");
6018 			break;
6019 		}
6020 		(void) sprintf(bp, "%02x", *addr++);
6021 		bp += 2;
6022 		if (--alen == 0)
6023 			break;
6024 		*bp++ = ':';
6025 		buflen -= 3;
6026 		/*
6027 		 * At this point, based on the first 'if' statement above,
6028 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6029 		 * buflen >= 4.  The first case leaves room for the final "xx"
6030 		 * number and trailing NUL byte.  The second leaves room for at
6031 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6032 		 * that statement.
6033 		 */
6034 	}
6035 	return (buf);
6036 }
6037 
6038 /*
6039  * Send an ICMP error after patching up the packet appropriately.  Returns
6040  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6041  */
6042 static boolean_t
6043 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6044     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6045 {
6046 	ipha_t *ipha;
6047 	mblk_t *first_mp;
6048 	boolean_t secure;
6049 	unsigned char db_type;
6050 
6051 	first_mp = mp;
6052 	if (mctl_present) {
6053 		mp = mp->b_cont;
6054 		secure = ipsec_in_is_secure(first_mp);
6055 		ASSERT(mp != NULL);
6056 	} else {
6057 		/*
6058 		 * If this is an ICMP error being reported - which goes
6059 		 * up as M_CTLs, we need to convert them to M_DATA till
6060 		 * we finish checking with global policy because
6061 		 * ipsec_check_global_policy() assumes M_DATA as clear
6062 		 * and M_CTL as secure.
6063 		 */
6064 		db_type = DB_TYPE(mp);
6065 		DB_TYPE(mp) = M_DATA;
6066 		secure = B_FALSE;
6067 	}
6068 	/*
6069 	 * We are generating an icmp error for some inbound packet.
6070 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6071 	 * Before we generate an error, check with global policy
6072 	 * to see whether this is allowed to enter the system. As
6073 	 * there is no "conn", we are checking with global policy.
6074 	 */
6075 	ipha = (ipha_t *)mp->b_rptr;
6076 	if (secure || ipsec_inbound_v4_policy_present) {
6077 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6078 		    ipha, NULL, mctl_present);
6079 		if (first_mp == NULL)
6080 			return (B_FALSE);
6081 	}
6082 
6083 	if (!mctl_present)
6084 		DB_TYPE(mp) = db_type;
6085 
6086 	if (flags & IP_FF_SEND_ICMP) {
6087 		if (flags & IP_FF_HDR_COMPLETE) {
6088 			if (ip_hdr_complete(ipha, zoneid)) {
6089 				freemsg(first_mp);
6090 				return (B_TRUE);
6091 			}
6092 		}
6093 		if (flags & IP_FF_CKSUM) {
6094 			/*
6095 			 * Have to correct checksum since
6096 			 * the packet might have been
6097 			 * fragmented and the reassembly code in ip_rput
6098 			 * does not restore the IP checksum.
6099 			 */
6100 			ipha->ipha_hdr_checksum = 0;
6101 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6102 		}
6103 		switch (icmp_type) {
6104 		case ICMP_DEST_UNREACHABLE:
6105 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6106 			break;
6107 		default:
6108 			freemsg(first_mp);
6109 			break;
6110 		}
6111 	} else {
6112 		freemsg(first_mp);
6113 		return (B_FALSE);
6114 	}
6115 
6116 	return (B_TRUE);
6117 }
6118 
6119 /*
6120  * Used to send an ICMP error message when a packet is received for
6121  * a protocol that is not supported. The mblk passed as argument
6122  * is consumed by this function.
6123  */
6124 void
6125 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6126 {
6127 	mblk_t *mp;
6128 	ipha_t *ipha;
6129 	ill_t *ill;
6130 	ipsec_in_t *ii;
6131 
6132 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6133 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6134 
6135 	mp = ipsec_mp->b_cont;
6136 	ipsec_mp->b_cont = NULL;
6137 	ipha = (ipha_t *)mp->b_rptr;
6138 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6139 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6140 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6141 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6142 		}
6143 	} else {
6144 		/* Get ill from index in ipsec_in_t. */
6145 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6146 		    B_TRUE, NULL, NULL, NULL, NULL);
6147 		if (ill != NULL) {
6148 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6149 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6150 			    0, B_FALSE, zoneid)) {
6151 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6152 			}
6153 
6154 			ill_refrele(ill);
6155 		} else { /* re-link for the freemsg() below. */
6156 			ipsec_mp->b_cont = mp;
6157 		}
6158 	}
6159 
6160 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6161 	freemsg(ipsec_mp);
6162 }
6163 
6164 /*
6165  * See if the inbound datagram has had IPsec processing applied to it.
6166  */
6167 boolean_t
6168 ipsec_in_is_secure(mblk_t *ipsec_mp)
6169 {
6170 	ipsec_in_t *ii;
6171 
6172 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6173 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6174 
6175 	if (ii->ipsec_in_loopback) {
6176 		return (ii->ipsec_in_secure);
6177 	} else {
6178 		return (ii->ipsec_in_ah_sa != NULL ||
6179 		    ii->ipsec_in_esp_sa != NULL ||
6180 		    ii->ipsec_in_decaps);
6181 	}
6182 }
6183 
6184 /*
6185  * Handle protocols with which IP is less intimate.  There
6186  * can be more than one stream bound to a particular
6187  * protocol.  When this is the case, normally each one gets a copy
6188  * of any incoming packets.
6189  *
6190  * IPSEC NOTE :
6191  *
6192  * Don't allow a secure packet going up a non-secure connection.
6193  * We don't allow this because
6194  *
6195  * 1) Reply might go out in clear which will be dropped at
6196  *    the sending side.
6197  * 2) If the reply goes out in clear it will give the
6198  *    adversary enough information for getting the key in
6199  *    most of the cases.
6200  *
6201  * Moreover getting a secure packet when we expect clear
6202  * implies that SA's were added without checking for
6203  * policy on both ends. This should not happen once ISAKMP
6204  * is used to negotiate SAs as SAs will be added only after
6205  * verifying the policy.
6206  *
6207  * NOTE : If the packet was tunneled and not multicast we only send
6208  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6209  * back to delivering packets to AF_INET6 raw sockets.
6210  *
6211  * IPQoS Notes:
6212  * Once we have determined the client, invoke IPPF processing.
6213  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6214  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6215  * ip_policy will be false.
6216  *
6217  * Zones notes:
6218  * Currently only applications in the global zone can create raw sockets for
6219  * protocols other than ICMP. So unlike the broadcast / multicast case of
6220  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6221  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6222  */
6223 static void
6224 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6225     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6226     zoneid_t zoneid)
6227 {
6228 	queue_t	*rq;
6229 	mblk_t	*mp1, *first_mp1;
6230 	uint_t	protocol = ipha->ipha_protocol;
6231 	ipaddr_t dst;
6232 	boolean_t one_only;
6233 	mblk_t *first_mp = mp;
6234 	boolean_t secure;
6235 	uint32_t ill_index;
6236 	conn_t	*connp, *first_connp, *next_connp;
6237 	connf_t	*connfp;
6238 	boolean_t shared_addr;
6239 
6240 	if (mctl_present) {
6241 		mp = first_mp->b_cont;
6242 		secure = ipsec_in_is_secure(first_mp);
6243 		ASSERT(mp != NULL);
6244 	} else {
6245 		secure = B_FALSE;
6246 	}
6247 	dst = ipha->ipha_dst;
6248 	/*
6249 	 * If the packet was tunneled and not multicast we only send to it
6250 	 * the first match.
6251 	 */
6252 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6253 	    !CLASSD(dst));
6254 
6255 	shared_addr = (zoneid == ALL_ZONES);
6256 	if (shared_addr) {
6257 		/*
6258 		 * We don't allow multilevel ports for raw IP, so no need to
6259 		 * check for that here.
6260 		 */
6261 		zoneid = tsol_packet_to_zoneid(mp);
6262 	}
6263 
6264 	connfp = &ipcl_proto_fanout[protocol];
6265 	mutex_enter(&connfp->connf_lock);
6266 	connp = connfp->connf_head;
6267 	for (connp = connfp->connf_head; connp != NULL;
6268 		connp = connp->conn_next) {
6269 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6270 		    zoneid) &&
6271 		    (!is_system_labeled() ||
6272 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6273 		    connp)))
6274 			break;
6275 	}
6276 
6277 	if (connp == NULL || connp->conn_upq == NULL) {
6278 		/*
6279 		 * No one bound to these addresses.  Is
6280 		 * there a client that wants all
6281 		 * unclaimed datagrams?
6282 		 */
6283 		mutex_exit(&connfp->connf_lock);
6284 		/*
6285 		 * Check for IPPROTO_ENCAP...
6286 		 */
6287 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6288 			/*
6289 			 * If an IPsec mblk is here on a multicast
6290 			 * tunnel (using ip_mroute stuff), check policy here,
6291 			 * THEN ship off to ip_mroute_decap().
6292 			 *
6293 			 * BTW,  If I match a configured IP-in-IP
6294 			 * tunnel, this path will not be reached, and
6295 			 * ip_mroute_decap will never be called.
6296 			 */
6297 			first_mp = ipsec_check_global_policy(first_mp, connp,
6298 			    ipha, NULL, mctl_present);
6299 			if (first_mp != NULL) {
6300 				if (mctl_present)
6301 					freeb(first_mp);
6302 				ip_mroute_decap(q, mp);
6303 			} /* Else we already freed everything! */
6304 		} else {
6305 			/*
6306 			 * Otherwise send an ICMP protocol unreachable.
6307 			 */
6308 			if (ip_fanout_send_icmp(q, first_mp, flags,
6309 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6310 			    mctl_present, zoneid)) {
6311 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6312 			}
6313 		}
6314 		return;
6315 	}
6316 	CONN_INC_REF(connp);
6317 	first_connp = connp;
6318 
6319 	/*
6320 	 * Only send message to one tunnel driver by immediately
6321 	 * terminating the loop.
6322 	 */
6323 	connp = one_only ? NULL : connp->conn_next;
6324 
6325 	for (;;) {
6326 		while (connp != NULL) {
6327 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6328 			    flags, zoneid) &&
6329 			    (!is_system_labeled() ||
6330 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6331 			    shared_addr, connp)))
6332 				break;
6333 			connp = connp->conn_next;
6334 		}
6335 
6336 		/*
6337 		 * Copy the packet.
6338 		 */
6339 		if (connp == NULL || connp->conn_upq == NULL ||
6340 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6341 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6342 			/*
6343 			 * No more interested clients or memory
6344 			 * allocation failed
6345 			 */
6346 			connp = first_connp;
6347 			break;
6348 		}
6349 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6350 		CONN_INC_REF(connp);
6351 		mutex_exit(&connfp->connf_lock);
6352 		rq = connp->conn_rq;
6353 		if (!canputnext(rq)) {
6354 			if (flags & IP_FF_RAWIP) {
6355 				BUMP_MIB(&ip_mib, rawipInOverflows);
6356 			} else {
6357 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6358 			}
6359 
6360 			freemsg(first_mp1);
6361 		} else {
6362 			/*
6363 			 * Don't enforce here if we're an actual tunnel -
6364 			 * let "tun" do it instead.
6365 			 */
6366 			if (!IPCL_IS_IPTUN(connp) &&
6367 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6368 				first_mp1 = ipsec_check_inbound_policy
6369 				    (first_mp1, connp, ipha, NULL,
6370 				    mctl_present);
6371 			}
6372 			if (first_mp1 != NULL) {
6373 				/*
6374 				 * ip_fanout_proto also gets called from
6375 				 * icmp_inbound_error_fanout, in which case
6376 				 * the msg type is M_CTL.  Don't add info
6377 				 * in this case for the time being. In future
6378 				 * when there is a need for knowing the
6379 				 * inbound iface index for ICMP error msgs,
6380 				 * then this can be changed.
6381 				 */
6382 				if ((connp->conn_recvif != 0) &&
6383 				    (mp->b_datap->db_type != M_CTL)) {
6384 					/*
6385 					 * the actual data will be
6386 					 * contained in b_cont upon
6387 					 * successful return of the
6388 					 * following call else
6389 					 * original mblk is returned
6390 					 */
6391 					ASSERT(recv_ill != NULL);
6392 					mp1 = ip_add_info(mp1, recv_ill,
6393 						IPF_RECVIF);
6394 				}
6395 				BUMP_MIB(&ip_mib, ipInDelivers);
6396 				if (mctl_present)
6397 					freeb(first_mp1);
6398 				putnext(rq, mp1);
6399 			}
6400 		}
6401 		mutex_enter(&connfp->connf_lock);
6402 		/* Follow the next pointer before releasing the conn. */
6403 		next_connp = connp->conn_next;
6404 		CONN_DEC_REF(connp);
6405 		connp = next_connp;
6406 	}
6407 
6408 	/* Last one.  Send it upstream. */
6409 	mutex_exit(&connfp->connf_lock);
6410 
6411 	/*
6412 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6413 	 * will be set to false.
6414 	 */
6415 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6416 		ill_index = ill->ill_phyint->phyint_ifindex;
6417 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6418 		if (mp == NULL) {
6419 			CONN_DEC_REF(connp);
6420 			if (mctl_present) {
6421 				freeb(first_mp);
6422 			}
6423 			return;
6424 		}
6425 	}
6426 
6427 	rq = connp->conn_rq;
6428 	if (!canputnext(rq)) {
6429 		if (flags & IP_FF_RAWIP) {
6430 			BUMP_MIB(&ip_mib, rawipInOverflows);
6431 		} else {
6432 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6433 		}
6434 
6435 		freemsg(first_mp);
6436 	} else {
6437 		if (IPCL_IS_IPTUN(connp)) {
6438 			/*
6439 			 * Tunneled packet.  We enforce policy in the tunnel
6440 			 * module itself.
6441 			 *
6442 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6443 			 * a policy check.
6444 			 */
6445 			putnext(rq, first_mp);
6446 			CONN_DEC_REF(connp);
6447 			return;
6448 		}
6449 
6450 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6451 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6452 			    ipha, NULL, mctl_present);
6453 		}
6454 
6455 		if (first_mp != NULL) {
6456 			/*
6457 			 * ip_fanout_proto also gets called
6458 			 * from icmp_inbound_error_fanout, in
6459 			 * which case the msg type is M_CTL.
6460 			 * Don't add info in this case for time
6461 			 * being. In future when there is a
6462 			 * need for knowing the inbound iface
6463 			 * index for ICMP error msgs, then this
6464 			 * can be changed
6465 			 */
6466 			if ((connp->conn_recvif != 0) &&
6467 			    (mp->b_datap->db_type != M_CTL)) {
6468 				/*
6469 				 * the actual data will be contained in
6470 				 * b_cont upon successful return
6471 				 * of the following call else original
6472 				 * mblk is returned
6473 				 */
6474 				ASSERT(recv_ill != NULL);
6475 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6476 			}
6477 			BUMP_MIB(&ip_mib, ipInDelivers);
6478 			putnext(rq, mp);
6479 			if (mctl_present)
6480 				freeb(first_mp);
6481 		}
6482 	}
6483 	CONN_DEC_REF(connp);
6484 }
6485 
6486 /*
6487  * Fanout for TCP packets
6488  * The caller puts <fport, lport> in the ports parameter.
6489  *
6490  * IPQoS Notes
6491  * Before sending it to the client, invoke IPPF processing.
6492  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6493  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6494  * ip_policy is false.
6495  */
6496 static void
6497 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6498     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6499 {
6500 	mblk_t  *first_mp;
6501 	boolean_t secure;
6502 	uint32_t ill_index;
6503 	int	ip_hdr_len;
6504 	tcph_t	*tcph;
6505 	boolean_t syn_present = B_FALSE;
6506 	conn_t	*connp;
6507 
6508 	first_mp = mp;
6509 	if (mctl_present) {
6510 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6511 		mp = first_mp->b_cont;
6512 		secure = ipsec_in_is_secure(first_mp);
6513 		ASSERT(mp != NULL);
6514 	} else {
6515 		secure = B_FALSE;
6516 	}
6517 
6518 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6519 
6520 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6521 	    NULL) {
6522 		/*
6523 		 * No connected connection or listener. Send a
6524 		 * TH_RST via tcp_xmit_listeners_reset.
6525 		 */
6526 
6527 		/* Initiate IPPf processing, if needed. */
6528 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6529 			uint32_t ill_index;
6530 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6531 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6532 			if (first_mp == NULL)
6533 				return;
6534 		}
6535 		BUMP_MIB(&ip_mib, ipInDelivers);
6536 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6537 		    zoneid));
6538 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6539 		return;
6540 	}
6541 
6542 	/*
6543 	 * Allocate the SYN for the TCP connection here itself
6544 	 */
6545 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6546 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6547 		if (IPCL_IS_TCP(connp)) {
6548 			squeue_t *sqp;
6549 
6550 			/*
6551 			 * For fused tcp loopback, assign the eager's
6552 			 * squeue to be that of the active connect's.
6553 			 * Note that we don't check for IP_FF_LOOPBACK
6554 			 * here since this routine gets called only
6555 			 * for loopback (unlike the IPv6 counterpart).
6556 			 */
6557 			ASSERT(Q_TO_CONN(q) != NULL);
6558 			if (do_tcp_fusion &&
6559 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6560 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6561 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6562 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6563 				sqp = Q_TO_CONN(q)->conn_sqp;
6564 			} else {
6565 				sqp = IP_SQUEUE_GET(lbolt);
6566 			}
6567 
6568 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6569 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6570 			syn_present = B_TRUE;
6571 		}
6572 	}
6573 
6574 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6575 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6576 		if ((flags & TH_RST) || (flags & TH_URG)) {
6577 			CONN_DEC_REF(connp);
6578 			freemsg(first_mp);
6579 			return;
6580 		}
6581 		if (flags & TH_ACK) {
6582 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6583 			CONN_DEC_REF(connp);
6584 			return;
6585 		}
6586 
6587 		CONN_DEC_REF(connp);
6588 		freemsg(first_mp);
6589 		return;
6590 	}
6591 
6592 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6593 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6594 		    NULL, mctl_present);
6595 		if (first_mp == NULL) {
6596 			CONN_DEC_REF(connp);
6597 			return;
6598 		}
6599 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6600 			ASSERT(syn_present);
6601 			if (mctl_present) {
6602 				ASSERT(first_mp != mp);
6603 				first_mp->b_datap->db_struioflag |=
6604 				    STRUIO_POLICY;
6605 			} else {
6606 				ASSERT(first_mp == mp);
6607 				mp->b_datap->db_struioflag &=
6608 				    ~STRUIO_EAGER;
6609 				mp->b_datap->db_struioflag |=
6610 				    STRUIO_POLICY;
6611 			}
6612 		} else {
6613 			/*
6614 			 * Discard first_mp early since we're dealing with a
6615 			 * fully-connected conn_t and tcp doesn't do policy in
6616 			 * this case.
6617 			 */
6618 			if (mctl_present) {
6619 				freeb(first_mp);
6620 				mctl_present = B_FALSE;
6621 			}
6622 			first_mp = mp;
6623 		}
6624 	}
6625 
6626 	/*
6627 	 * Initiate policy processing here if needed. If we get here from
6628 	 * icmp_inbound_error_fanout, ip_policy is false.
6629 	 */
6630 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6631 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6632 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6633 		if (mp == NULL) {
6634 			CONN_DEC_REF(connp);
6635 			if (mctl_present)
6636 				freeb(first_mp);
6637 			return;
6638 		} else if (mctl_present) {
6639 			ASSERT(first_mp != mp);
6640 			first_mp->b_cont = mp;
6641 		} else {
6642 			first_mp = mp;
6643 		}
6644 	}
6645 
6646 
6647 
6648 	/* Handle IPv6 socket options. */
6649 	if (!syn_present &&
6650 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6651 		/* Add header */
6652 		ASSERT(recv_ill != NULL);
6653 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6654 		if (mp == NULL) {
6655 			CONN_DEC_REF(connp);
6656 			if (mctl_present)
6657 				freeb(first_mp);
6658 			return;
6659 		} else if (mctl_present) {
6660 			/*
6661 			 * ip_add_info might return a new mp.
6662 			 */
6663 			ASSERT(first_mp != mp);
6664 			first_mp->b_cont = mp;
6665 		} else {
6666 			first_mp = mp;
6667 		}
6668 	}
6669 
6670 	BUMP_MIB(&ip_mib, ipInDelivers);
6671 	if (IPCL_IS_TCP(connp)) {
6672 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6673 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6674 	} else {
6675 		putnext(connp->conn_rq, first_mp);
6676 		CONN_DEC_REF(connp);
6677 	}
6678 }
6679 
6680 /*
6681  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6682  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6683  * Caller is responsible for dropping references to the conn, and freeing
6684  * first_mp.
6685  *
6686  * IPQoS Notes
6687  * Before sending it to the client, invoke IPPF processing. Policy processing
6688  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6689  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6690  * ip_wput_local, ip_policy is false.
6691  */
6692 static void
6693 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6694     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6695     boolean_t ip_policy)
6696 {
6697 	boolean_t	mctl_present = (first_mp != NULL);
6698 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6699 	uint32_t	ill_index;
6700 
6701 	if (mctl_present)
6702 		first_mp->b_cont = mp;
6703 	else
6704 		first_mp = mp;
6705 
6706 	if (CONN_UDP_FLOWCTLD(connp)) {
6707 		BUMP_MIB(&ip_mib, udpInOverflows);
6708 		freemsg(first_mp);
6709 		return;
6710 	}
6711 
6712 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6713 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6714 		    NULL, mctl_present);
6715 		if (first_mp == NULL)
6716 			return;	/* Freed by ipsec_check_inbound_policy(). */
6717 	}
6718 	if (mctl_present)
6719 		freeb(first_mp);
6720 
6721 	if (connp->conn_recvif)
6722 		in_flags = IPF_RECVIF;
6723 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6724 		in_flags |= IPF_RECVSLLA;
6725 
6726 	/* Handle IPv6 options. */
6727 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6728 		in_flags |= IPF_RECVIF;
6729 
6730 	/*
6731 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6732 	 * freed if the packet is dropped. The caller will do so.
6733 	 */
6734 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6735 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6736 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6737 		if (mp == NULL) {
6738 			return;
6739 		}
6740 	}
6741 	if ((in_flags != 0) &&
6742 	    (mp->b_datap->db_type != M_CTL)) {
6743 		/*
6744 		 * The actual data will be contained in b_cont
6745 		 * upon successful return of the following call
6746 		 * else original mblk is returned
6747 		 */
6748 		ASSERT(recv_ill != NULL);
6749 		mp = ip_add_info(mp, recv_ill, in_flags);
6750 	}
6751 	BUMP_MIB(&ip_mib, ipInDelivers);
6752 
6753 	/* Send it upstream */
6754 	CONN_UDP_RECV(connp, mp);
6755 }
6756 
6757 /*
6758  * Fanout for UDP packets.
6759  * The caller puts <fport, lport> in the ports parameter.
6760  *
6761  * If SO_REUSEADDR is set all multicast and broadcast packets
6762  * will be delivered to all streams bound to the same port.
6763  *
6764  * Zones notes:
6765  * Multicast and broadcast packets will be distributed to streams in all zones.
6766  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6767  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6768  * packets. To maintain this behavior with multiple zones, the conns are grouped
6769  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6770  * each zone. If unset, all the following conns in the same zone are skipped.
6771  */
6772 static void
6773 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6774     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6775     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6776 {
6777 	uint32_t	dstport, srcport;
6778 	ipaddr_t	dst;
6779 	mblk_t		*first_mp;
6780 	boolean_t	secure;
6781 	in6_addr_t	v6src;
6782 	conn_t		*connp;
6783 	connf_t		*connfp;
6784 	conn_t		*first_connp;
6785 	conn_t		*next_connp;
6786 	mblk_t		*mp1, *first_mp1;
6787 	ipaddr_t	src;
6788 	zoneid_t	last_zoneid;
6789 	boolean_t	reuseaddr;
6790 	boolean_t	shared_addr;
6791 
6792 	first_mp = mp;
6793 	if (mctl_present) {
6794 		mp = first_mp->b_cont;
6795 		first_mp->b_cont = NULL;
6796 		secure = ipsec_in_is_secure(first_mp);
6797 		ASSERT(mp != NULL);
6798 	} else {
6799 		first_mp = NULL;
6800 		secure = B_FALSE;
6801 	}
6802 
6803 	/* Extract ports in net byte order */
6804 	dstport = htons(ntohl(ports) & 0xFFFF);
6805 	srcport = htons(ntohl(ports) >> 16);
6806 	dst = ipha->ipha_dst;
6807 	src = ipha->ipha_src;
6808 
6809 	shared_addr = (zoneid == ALL_ZONES);
6810 	if (shared_addr) {
6811 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6812 		if (zoneid == ALL_ZONES)
6813 			zoneid = tsol_packet_to_zoneid(mp);
6814 	}
6815 
6816 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6817 	mutex_enter(&connfp->connf_lock);
6818 	connp = connfp->connf_head;
6819 	if (!broadcast && !CLASSD(dst)) {
6820 		/*
6821 		 * Not broadcast or multicast. Send to the one (first)
6822 		 * client we find. No need to check conn_wantpacket()
6823 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6824 		 * IPv4 unicast packets.
6825 		 */
6826 		while ((connp != NULL) &&
6827 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6828 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6829 			connp = connp->conn_next;
6830 		}
6831 
6832 		if (connp == NULL || connp->conn_upq == NULL)
6833 			goto notfound;
6834 
6835 		if (is_system_labeled() &&
6836 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6837 		    connp))
6838 			goto notfound;
6839 
6840 		CONN_INC_REF(connp);
6841 		mutex_exit(&connfp->connf_lock);
6842 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6843 		    recv_ill, ip_policy);
6844 		IP_STAT(ip_udp_fannorm);
6845 		CONN_DEC_REF(connp);
6846 		return;
6847 	}
6848 
6849 	/*
6850 	 * Broadcast and multicast case
6851 	 *
6852 	 * Need to check conn_wantpacket().
6853 	 * If SO_REUSEADDR has been set on the first we send the
6854 	 * packet to all clients that have joined the group and
6855 	 * match the port.
6856 	 */
6857 
6858 	while (connp != NULL) {
6859 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6860 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6861 		    (!is_system_labeled() ||
6862 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6863 		    connp)))
6864 			break;
6865 		connp = connp->conn_next;
6866 	}
6867 
6868 	if (connp == NULL || connp->conn_upq == NULL)
6869 		goto notfound;
6870 
6871 	first_connp = connp;
6872 	/*
6873 	 * When SO_REUSEADDR is not set, send the packet only to the first
6874 	 * matching connection in its zone by keeping track of the zoneid.
6875 	 */
6876 	reuseaddr = first_connp->conn_reuseaddr;
6877 	last_zoneid = first_connp->conn_zoneid;
6878 
6879 	CONN_INC_REF(connp);
6880 	connp = connp->conn_next;
6881 	for (;;) {
6882 		while (connp != NULL) {
6883 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6884 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6885 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6886 			    (!is_system_labeled() ||
6887 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6888 			    shared_addr, connp)))
6889 				break;
6890 			connp = connp->conn_next;
6891 		}
6892 		/*
6893 		 * Just copy the data part alone. The mctl part is
6894 		 * needed just for verifying policy and it is never
6895 		 * sent up.
6896 		 */
6897 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6898 		    ((mp1 = copymsg(mp)) == NULL))) {
6899 			/*
6900 			 * No more interested clients or memory
6901 			 * allocation failed
6902 			 */
6903 			connp = first_connp;
6904 			break;
6905 		}
6906 		if (connp->conn_zoneid != last_zoneid) {
6907 			/*
6908 			 * Update the zoneid so that the packet isn't sent to
6909 			 * any more conns in the same zone unless SO_REUSEADDR
6910 			 * is set.
6911 			 */
6912 			reuseaddr = connp->conn_reuseaddr;
6913 			last_zoneid = connp->conn_zoneid;
6914 		}
6915 		if (first_mp != NULL) {
6916 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6917 			    ipsec_info_type == IPSEC_IN);
6918 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6919 			if (first_mp1 == NULL) {
6920 				freemsg(mp1);
6921 				connp = first_connp;
6922 				break;
6923 			}
6924 		} else {
6925 			first_mp1 = NULL;
6926 		}
6927 		CONN_INC_REF(connp);
6928 		mutex_exit(&connfp->connf_lock);
6929 		/*
6930 		 * IPQoS notes: We don't send the packet for policy
6931 		 * processing here, will do it for the last one (below).
6932 		 * i.e. we do it per-packet now, but if we do policy
6933 		 * processing per-conn, then we would need to do it
6934 		 * here too.
6935 		 */
6936 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6937 		    ipha, flags, recv_ill, B_FALSE);
6938 		mutex_enter(&connfp->connf_lock);
6939 		/* Follow the next pointer before releasing the conn. */
6940 		next_connp = connp->conn_next;
6941 		IP_STAT(ip_udp_fanmb);
6942 		CONN_DEC_REF(connp);
6943 		connp = next_connp;
6944 	}
6945 
6946 	/* Last one.  Send it upstream. */
6947 	mutex_exit(&connfp->connf_lock);
6948 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6949 	    ip_policy);
6950 	IP_STAT(ip_udp_fanmb);
6951 	CONN_DEC_REF(connp);
6952 	return;
6953 
6954 notfound:
6955 
6956 	mutex_exit(&connfp->connf_lock);
6957 	IP_STAT(ip_udp_fanothers);
6958 	/*
6959 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6960 	 * have already been matched above, since they live in the IPv4
6961 	 * fanout tables. This implies we only need to
6962 	 * check for IPv6 in6addr_any endpoints here.
6963 	 * Thus we compare using ipv6_all_zeros instead of the destination
6964 	 * address, except for the multicast group membership lookup which
6965 	 * uses the IPv4 destination.
6966 	 */
6967 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6968 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6969 	mutex_enter(&connfp->connf_lock);
6970 	connp = connfp->connf_head;
6971 	if (!broadcast && !CLASSD(dst)) {
6972 		while (connp != NULL) {
6973 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6974 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6975 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6976 			    !connp->conn_ipv6_v6only)
6977 				break;
6978 			connp = connp->conn_next;
6979 		}
6980 
6981 		if (connp != NULL && is_system_labeled() &&
6982 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6983 		    connp))
6984 			connp = NULL;
6985 
6986 		if (connp == NULL || connp->conn_upq == NULL) {
6987 			/*
6988 			 * No one bound to this port.  Is
6989 			 * there a client that wants all
6990 			 * unclaimed datagrams?
6991 			 */
6992 			mutex_exit(&connfp->connf_lock);
6993 
6994 			if (mctl_present)
6995 				first_mp->b_cont = mp;
6996 			else
6997 				first_mp = mp;
6998 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6999 				ip_fanout_proto(q, first_mp, ill, ipha,
7000 				    flags | IP_FF_RAWIP, mctl_present,
7001 				    ip_policy, recv_ill, zoneid);
7002 			} else {
7003 				if (ip_fanout_send_icmp(q, first_mp, flags,
7004 				    ICMP_DEST_UNREACHABLE,
7005 				    ICMP_PORT_UNREACHABLE,
7006 				    mctl_present, zoneid)) {
7007 					BUMP_MIB(&ip_mib, udpNoPorts);
7008 				}
7009 			}
7010 			return;
7011 		}
7012 
7013 		CONN_INC_REF(connp);
7014 		mutex_exit(&connfp->connf_lock);
7015 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
7016 		    recv_ill, ip_policy);
7017 		CONN_DEC_REF(connp);
7018 		return;
7019 	}
7020 	/*
7021 	 * IPv4 multicast packet being delivered to an AF_INET6
7022 	 * in6addr_any endpoint.
7023 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7024 	 * and not conn_wantpacket_v6() since any multicast membership is
7025 	 * for an IPv4-mapped multicast address.
7026 	 * The packet is sent to all clients in all zones that have joined the
7027 	 * group and match the port.
7028 	 */
7029 	while (connp != NULL) {
7030 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7031 		    srcport, v6src) &&
7032 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7033 		    (!is_system_labeled() ||
7034 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7035 		    connp)))
7036 			break;
7037 		connp = connp->conn_next;
7038 	}
7039 
7040 	if (connp == NULL || connp->conn_upq == NULL) {
7041 		/*
7042 		 * No one bound to this port.  Is
7043 		 * there a client that wants all
7044 		 * unclaimed datagrams?
7045 		 */
7046 		mutex_exit(&connfp->connf_lock);
7047 
7048 		if (mctl_present)
7049 			first_mp->b_cont = mp;
7050 		else
7051 			first_mp = mp;
7052 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7053 			ip_fanout_proto(q, first_mp, ill, ipha,
7054 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7055 			    recv_ill, zoneid);
7056 		} else {
7057 			/*
7058 			 * We used to attempt to send an icmp error here, but
7059 			 * since this is known to be a multicast packet
7060 			 * and we don't send icmp errors in response to
7061 			 * multicast, just drop the packet and give up sooner.
7062 			 */
7063 			BUMP_MIB(&ip_mib, udpNoPorts);
7064 			freemsg(first_mp);
7065 		}
7066 		return;
7067 	}
7068 
7069 	first_connp = connp;
7070 
7071 	CONN_INC_REF(connp);
7072 	connp = connp->conn_next;
7073 	for (;;) {
7074 		while (connp != NULL) {
7075 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7076 			    ipv6_all_zeros, srcport, v6src) &&
7077 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7078 			    (!is_system_labeled() ||
7079 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7080 			    shared_addr, connp)))
7081 				break;
7082 			connp = connp->conn_next;
7083 		}
7084 		/*
7085 		 * Just copy the data part alone. The mctl part is
7086 		 * needed just for verifying policy and it is never
7087 		 * sent up.
7088 		 */
7089 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7090 		    ((mp1 = copymsg(mp)) == NULL))) {
7091 			/*
7092 			 * No more intested clients or memory
7093 			 * allocation failed
7094 			 */
7095 			connp = first_connp;
7096 			break;
7097 		}
7098 		if (first_mp != NULL) {
7099 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7100 			    ipsec_info_type == IPSEC_IN);
7101 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7102 			if (first_mp1 == NULL) {
7103 				freemsg(mp1);
7104 				connp = first_connp;
7105 				break;
7106 			}
7107 		} else {
7108 			first_mp1 = NULL;
7109 		}
7110 		CONN_INC_REF(connp);
7111 		mutex_exit(&connfp->connf_lock);
7112 		/*
7113 		 * IPQoS notes: We don't send the packet for policy
7114 		 * processing here, will do it for the last one (below).
7115 		 * i.e. we do it per-packet now, but if we do policy
7116 		 * processing per-conn, then we would need to do it
7117 		 * here too.
7118 		 */
7119 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7120 		    ipha, flags, recv_ill, B_FALSE);
7121 		mutex_enter(&connfp->connf_lock);
7122 		/* Follow the next pointer before releasing the conn. */
7123 		next_connp = connp->conn_next;
7124 		CONN_DEC_REF(connp);
7125 		connp = next_connp;
7126 	}
7127 
7128 	/* Last one.  Send it upstream. */
7129 	mutex_exit(&connfp->connf_lock);
7130 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7131 	    ip_policy);
7132 	CONN_DEC_REF(connp);
7133 }
7134 
7135 /*
7136  * Complete the ip_wput header so that it
7137  * is possible to generate ICMP
7138  * errors.
7139  */
7140 int
7141 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7142 {
7143 	ire_t *ire;
7144 
7145 	if (ipha->ipha_src == INADDR_ANY) {
7146 		ire = ire_lookup_local(zoneid);
7147 		if (ire == NULL) {
7148 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7149 			return (1);
7150 		}
7151 		ipha->ipha_src = ire->ire_addr;
7152 		ire_refrele(ire);
7153 	}
7154 	ipha->ipha_ttl = ip_def_ttl;
7155 	ipha->ipha_hdr_checksum = 0;
7156 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7157 	return (0);
7158 }
7159 
7160 /*
7161  * Nobody should be sending
7162  * packets up this stream
7163  */
7164 static void
7165 ip_lrput(queue_t *q, mblk_t *mp)
7166 {
7167 	mblk_t *mp1;
7168 
7169 	switch (mp->b_datap->db_type) {
7170 	case M_FLUSH:
7171 		/* Turn around */
7172 		if (*mp->b_rptr & FLUSHW) {
7173 			*mp->b_rptr &= ~FLUSHR;
7174 			qreply(q, mp);
7175 			return;
7176 		}
7177 		break;
7178 	}
7179 	/* Could receive messages that passed through ar_rput */
7180 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7181 		mp1->b_prev = mp1->b_next = NULL;
7182 	freemsg(mp);
7183 }
7184 
7185 /* Nobody should be sending packets down this stream */
7186 /* ARGSUSED */
7187 void
7188 ip_lwput(queue_t *q, mblk_t *mp)
7189 {
7190 	freemsg(mp);
7191 }
7192 
7193 /*
7194  * Move the first hop in any source route to ipha_dst and remove that part of
7195  * the source route.  Called by other protocols.  Errors in option formatting
7196  * are ignored - will be handled by ip_wput_options Return the final
7197  * destination (either ipha_dst or the last entry in a source route.)
7198  */
7199 ipaddr_t
7200 ip_massage_options(ipha_t *ipha)
7201 {
7202 	ipoptp_t	opts;
7203 	uchar_t		*opt;
7204 	uint8_t		optval;
7205 	uint8_t		optlen;
7206 	ipaddr_t	dst;
7207 	int		i;
7208 	ire_t		*ire;
7209 
7210 	ip2dbg(("ip_massage_options\n"));
7211 	dst = ipha->ipha_dst;
7212 	for (optval = ipoptp_first(&opts, ipha);
7213 	    optval != IPOPT_EOL;
7214 	    optval = ipoptp_next(&opts)) {
7215 		opt = opts.ipoptp_cur;
7216 		switch (optval) {
7217 			uint8_t off;
7218 		case IPOPT_SSRR:
7219 		case IPOPT_LSRR:
7220 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7221 				ip1dbg(("ip_massage_options: bad src route\n"));
7222 				break;
7223 			}
7224 			optlen = opts.ipoptp_len;
7225 			off = opt[IPOPT_OFFSET];
7226 			off--;
7227 		redo_srr:
7228 			if (optlen < IP_ADDR_LEN ||
7229 			    off > optlen - IP_ADDR_LEN) {
7230 				/* End of source route */
7231 				ip1dbg(("ip_massage_options: end of SR\n"));
7232 				break;
7233 			}
7234 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7235 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7236 			    ntohl(dst)));
7237 			/*
7238 			 * Check if our address is present more than
7239 			 * once as consecutive hops in source route.
7240 			 * XXX verify per-interface ip_forwarding
7241 			 * for source route?
7242 			 */
7243 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7244 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7245 			if (ire != NULL) {
7246 				ire_refrele(ire);
7247 				off += IP_ADDR_LEN;
7248 				goto redo_srr;
7249 			}
7250 			if (dst == htonl(INADDR_LOOPBACK)) {
7251 				ip1dbg(("ip_massage_options: loopback addr in "
7252 				    "source route!\n"));
7253 				break;
7254 			}
7255 			/*
7256 			 * Update ipha_dst to be the first hop and remove the
7257 			 * first hop from the source route (by overwriting
7258 			 * part of the option with NOP options).
7259 			 */
7260 			ipha->ipha_dst = dst;
7261 			/* Put the last entry in dst */
7262 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7263 			    3;
7264 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7265 
7266 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7267 			    ntohl(dst)));
7268 			/* Move down and overwrite */
7269 			opt[IP_ADDR_LEN] = opt[0];
7270 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7271 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7272 			for (i = 0; i < IP_ADDR_LEN; i++)
7273 				opt[i] = IPOPT_NOP;
7274 			break;
7275 		}
7276 	}
7277 	return (dst);
7278 }
7279 
7280 /*
7281  * This function's job is to forward data to the reverse tunnel (FA->HA)
7282  * after doing a few checks. It is assumed that the incoming interface
7283  * of the packet is always different than the outgoing interface and the
7284  * ire_type of the found ire has to be a non-resolver type.
7285  *
7286  * IPQoS notes
7287  * IP policy is invoked twice for a forwarded packet, once on the read side
7288  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7289  * enabled.
7290  */
7291 static void
7292 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7293 {
7294 	ipha_t		*ipha;
7295 	queue_t		*q;
7296 	uint32_t 	pkt_len;
7297 #define	rptr    ((uchar_t *)ipha)
7298 	uint32_t 	sum;
7299 	uint32_t 	max_frag;
7300 	mblk_t		*first_mp;
7301 	uint32_t	ill_index;
7302 	ipxmit_state_t	pktxmit_state;
7303 	ill_t		*out_ill;
7304 
7305 	ASSERT(ire != NULL);
7306 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7307 	ASSERT(ire->ire_stq != NULL);
7308 
7309 	/* Initiate read side IPPF processing */
7310 	if (IPP_ENABLED(IPP_FWD_IN)) {
7311 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7312 		ip_process(IPP_FWD_IN, &mp, ill_index);
7313 		if (mp == NULL) {
7314 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7315 			    "dropped during IPPF processing\n"));
7316 			return;
7317 		}
7318 	}
7319 
7320 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7321 		ILLF_ROUTER) == 0) ||
7322 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7323 		BUMP_MIB(&ip_mib, ipForwProhibits);
7324 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7325 		    "forwarding is not turned on\n"));
7326 		goto drop_pkt;
7327 	}
7328 
7329 	/*
7330 	 * Don't forward if the interface is down
7331 	 */
7332 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7333 		BUMP_MIB(&ip_mib, ipInDiscards);
7334 		goto drop_pkt;
7335 	}
7336 
7337 	ipha = (ipha_t *)mp->b_rptr;
7338 	pkt_len = ntohs(ipha->ipha_length);
7339 	/* Adjust the checksum to reflect the ttl decrement. */
7340 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7341 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7342 	if (ipha->ipha_ttl-- <= 1) {
7343 		if (ip_csum_hdr(ipha)) {
7344 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7345 			goto drop_pkt;
7346 		}
7347 		q = ire->ire_stq;
7348 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7349 		    BPRI_HI)) == NULL) {
7350 			goto drop_pkt;
7351 		}
7352 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7353 		/* Sent by forwarding path, and router is global zone */
7354 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7355 		    GLOBAL_ZONEID);
7356 		return;
7357 	}
7358 
7359 	/* Get the ill_index of the ILL */
7360 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7361 
7362 	/*
7363 	 * This location is chosen for the placement of the forwarding hook
7364 	 * because at this point we know that we have a path out for the
7365 	 * packet but haven't yet applied any logic (such as fragmenting)
7366 	 * that happen as part of transmitting the packet out.
7367 	 */
7368 	out_ill = ire->ire_ipif->ipif_ill;
7369 
7370 	DTRACE_PROBE4(ip4__forwarding__start,
7371 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7372 
7373 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7374 	    in_ill, out_ill, ipha, mp, mp);
7375 
7376 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7377 
7378 	if (mp == NULL)
7379 		return;
7380 	pkt_len = ntohs(ipha->ipha_length);
7381 
7382 	/*
7383 	 * ip_mrtun_forward is only used by foreign agent to reverse
7384 	 * tunnel the incoming packet. So it does not do any option
7385 	 * processing for source routing.
7386 	 */
7387 	max_frag = ire->ire_max_frag;
7388 	if (pkt_len > max_frag) {
7389 		/*
7390 		 * It needs fragging on its way out.  We haven't
7391 		 * verified the header checksum yet.  Since we
7392 		 * are going to put a surely good checksum in the
7393 		 * outgoing header, we have to make sure that it
7394 		 * was good coming in.
7395 		 */
7396 		if (ip_csum_hdr(ipha)) {
7397 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7398 			goto drop_pkt;
7399 		}
7400 
7401 		/* Initiate write side IPPF processing */
7402 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7403 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7404 			if (mp == NULL) {
7405 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7406 				    "dropped/deferred during ip policy "\
7407 				    "processing\n"));
7408 				return;
7409 			}
7410 		}
7411 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7412 		    BPRI_HI)) == NULL) {
7413 			goto drop_pkt;
7414 		}
7415 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7416 		mp = first_mp;
7417 
7418 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7419 		return;
7420 	}
7421 
7422 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7423 
7424 	ASSERT(ire->ire_ipif != NULL);
7425 
7426 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7427 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7428 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7429 	    NULL, out_ill, ipha, mp, mp);
7430 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7431 	if (mp == NULL)
7432 		return;
7433 
7434 	/* Now send the packet to the tunnel interface */
7435 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7436 	q = ire->ire_stq;
7437 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7438 	if ((pktxmit_state == SEND_FAILED) ||
7439 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7440 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7441 		    q->q_ptr));
7442 	}
7443 
7444 	return;
7445 
7446 drop_pkt:;
7447 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7448 	freemsg(mp);
7449 #undef	rptr
7450 }
7451 
7452 /*
7453  * Fills the ipsec_out_t data structure with appropriate fields and
7454  * prepends it to mp which contains the IP hdr + data that was meant
7455  * to be forwarded. Please note that ipsec_out_info data structure
7456  * is used here to communicate the outgoing ill path at ip_wput()
7457  * for the ICMP error packet. This has nothing to do with ipsec IP
7458  * security. ipsec_out_t is really used to pass the info to the module
7459  * IP where this information cannot be extracted from conn.
7460  * This functions is called by ip_mrtun_forward().
7461  */
7462 void
7463 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7464 {
7465 	ipsec_out_t	*io;
7466 
7467 	ASSERT(xmit_ill != NULL);
7468 	first_mp->b_datap->db_type = M_CTL;
7469 	first_mp->b_wptr += sizeof (ipsec_info_t);
7470 	/*
7471 	 * This is to pass info to ip_wput in absence of conn.
7472 	 * ipsec_out_secure will be B_FALSE because of this.
7473 	 * Thus ipsec_out_secure being B_FALSE indicates that
7474 	 * this is not IPSEC security related information.
7475 	 */
7476 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7477 	io = (ipsec_out_t *)first_mp->b_rptr;
7478 	io->ipsec_out_type = IPSEC_OUT;
7479 	io->ipsec_out_len = sizeof (ipsec_out_t);
7480 	first_mp->b_cont = mp;
7481 	io->ipsec_out_ill_index =
7482 	    xmit_ill->ill_phyint->phyint_ifindex;
7483 	io->ipsec_out_xmit_if = B_TRUE;
7484 }
7485 
7486 /*
7487  * Return the network mask
7488  * associated with the specified address.
7489  */
7490 ipaddr_t
7491 ip_net_mask(ipaddr_t addr)
7492 {
7493 	uchar_t	*up = (uchar_t *)&addr;
7494 	ipaddr_t mask = 0;
7495 	uchar_t	*maskp = (uchar_t *)&mask;
7496 
7497 #if defined(__i386) || defined(__amd64)
7498 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7499 #endif
7500 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7501 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7502 #endif
7503 	if (CLASSD(addr)) {
7504 		maskp[0] = 0xF0;
7505 		return (mask);
7506 	}
7507 	if (addr == 0)
7508 		return (0);
7509 	maskp[0] = 0xFF;
7510 	if ((up[0] & 0x80) == 0)
7511 		return (mask);
7512 
7513 	maskp[1] = 0xFF;
7514 	if ((up[0] & 0xC0) == 0x80)
7515 		return (mask);
7516 
7517 	maskp[2] = 0xFF;
7518 	if ((up[0] & 0xE0) == 0xC0)
7519 		return (mask);
7520 
7521 	/* Must be experimental or multicast, indicate as much */
7522 	return ((ipaddr_t)0);
7523 }
7524 
7525 /*
7526  * Select an ill for the packet by considering load spreading across
7527  * a different ill in the group if dst_ill is part of some group.
7528  */
7529 ill_t *
7530 ip_newroute_get_dst_ill(ill_t *dst_ill)
7531 {
7532 	ill_t *ill;
7533 
7534 	/*
7535 	 * We schedule irrespective of whether the source address is
7536 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7537 	 */
7538 	ill = illgrp_scheduler(dst_ill);
7539 	if (ill == NULL)
7540 		return (NULL);
7541 
7542 	/*
7543 	 * For groups with names ip_sioctl_groupname ensures that all
7544 	 * ills are of same type. For groups without names, ifgrp_insert
7545 	 * ensures this.
7546 	 */
7547 	ASSERT(dst_ill->ill_type == ill->ill_type);
7548 
7549 	return (ill);
7550 }
7551 
7552 /*
7553  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7554  */
7555 ill_t *
7556 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7557 {
7558 	ill_t *ret_ill;
7559 
7560 	ASSERT(ifindex != 0);
7561 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7562 	if (ret_ill == NULL ||
7563 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7564 		if (isv6) {
7565 			if (ill != NULL) {
7566 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7567 			} else {
7568 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7569 			}
7570 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7571 			    "bad ifindex %d.\n", ifindex));
7572 		} else {
7573 			BUMP_MIB(&ip_mib, ipOutDiscards);
7574 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7575 			    "bad ifindex %d.\n", ifindex));
7576 		}
7577 		if (ret_ill != NULL)
7578 			ill_refrele(ret_ill);
7579 		freemsg(first_mp);
7580 		return (NULL);
7581 	}
7582 
7583 	return (ret_ill);
7584 }
7585 
7586 /*
7587  * IPv4 -
7588  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7589  * out a packet to a destination address for which we do not have specific
7590  * (or sufficient) routing information.
7591  *
7592  * NOTE : These are the scopes of some of the variables that point at IRE,
7593  *	  which needs to be followed while making any future modifications
7594  *	  to avoid memory leaks.
7595  *
7596  *	- ire and sire are the entries looked up initially by
7597  *	  ire_ftable_lookup.
7598  *	- ipif_ire is used to hold the interface ire associated with
7599  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7600  *	  it before branching out to error paths.
7601  *	- save_ire is initialized before ire_create, so that ire returned
7602  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7603  *	  before breaking out of the switch.
7604  *
7605  *	Thus on failures, we have to REFRELE only ire and sire, if they
7606  *	are not NULL.
7607  */
7608 void
7609 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7610     zoneid_t zoneid)
7611 {
7612 	areq_t	*areq;
7613 	ipaddr_t gw = 0;
7614 	ire_t	*ire = NULL;
7615 	mblk_t	*res_mp;
7616 	ipaddr_t *addrp;
7617 	ipaddr_t nexthop_addr;
7618 	ipif_t  *src_ipif = NULL;
7619 	ill_t	*dst_ill = NULL;
7620 	ipha_t  *ipha;
7621 	ire_t	*sire = NULL;
7622 	mblk_t	*first_mp;
7623 	ire_t	*save_ire;
7624 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7625 	ushort_t ire_marks = 0;
7626 	boolean_t mctl_present;
7627 	ipsec_out_t *io;
7628 	mblk_t	*saved_mp;
7629 	ire_t	*first_sire = NULL;
7630 	mblk_t	*copy_mp = NULL;
7631 	mblk_t	*xmit_mp = NULL;
7632 	ipaddr_t save_dst;
7633 	uint32_t multirt_flags =
7634 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7635 	boolean_t multirt_is_resolvable;
7636 	boolean_t multirt_resolve_next;
7637 	boolean_t do_attach_ill = B_FALSE;
7638 	boolean_t ip_nexthop = B_FALSE;
7639 	tsol_ire_gw_secattr_t *attrp = NULL;
7640 	tsol_gcgrp_t *gcgrp = NULL;
7641 	tsol_gcgrp_addr_t ga;
7642 
7643 	if (ip_debug > 2) {
7644 		/* ip1dbg */
7645 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7646 	}
7647 
7648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7649 	if (mctl_present) {
7650 		io = (ipsec_out_t *)first_mp->b_rptr;
7651 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7652 		ASSERT(zoneid == io->ipsec_out_zoneid);
7653 		ASSERT(zoneid != ALL_ZONES);
7654 	}
7655 
7656 	ipha = (ipha_t *)mp->b_rptr;
7657 
7658 	/* All multicast lookups come through ip_newroute_ipif() */
7659 	if (CLASSD(dst)) {
7660 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7661 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7662 		freemsg(first_mp);
7663 		return;
7664 	}
7665 
7666 	if (mctl_present && io->ipsec_out_attach_if) {
7667 		/* ip_grab_attach_ill returns a held ill */
7668 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7669 		    io->ipsec_out_ill_index, B_FALSE);
7670 
7671 		/* Failure case frees things for us. */
7672 		if (attach_ill == NULL)
7673 			return;
7674 
7675 		/*
7676 		 * Check if we need an ire that will not be
7677 		 * looked up by anybody else i.e. HIDDEN.
7678 		 */
7679 		if (ill_is_probeonly(attach_ill))
7680 			ire_marks = IRE_MARK_HIDDEN;
7681 	}
7682 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7683 		ip_nexthop = B_TRUE;
7684 		nexthop_addr = io->ipsec_out_nexthop_addr;
7685 	}
7686 	/*
7687 	 * If this IRE is created for forwarding or it is not for
7688 	 * traffic for congestion controlled protocols, mark it as temporary.
7689 	 */
7690 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7691 		ire_marks |= IRE_MARK_TEMPORARY;
7692 
7693 	/*
7694 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7695 	 * chain until it gets the most specific information available.
7696 	 * For example, we know that there is no IRE_CACHE for this dest,
7697 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7698 	 * ire_ftable_lookup will look up the gateway, etc.
7699 	 * Check if in_ill != NULL. If it is true, the packet must be
7700 	 * from an incoming interface where RTA_SRCIFP is set.
7701 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7702 	 * to the destination, of equal netmask length in the forward table,
7703 	 * will be recursively explored. If no information is available
7704 	 * for the final gateway of that route, we force the returned ire
7705 	 * to be equal to sire using MATCH_IRE_PARENT.
7706 	 * At least, in this case we have a starting point (in the buckets)
7707 	 * to look for other routes to the destination in the forward table.
7708 	 * This is actually used only for multirouting, where a list
7709 	 * of routes has to be processed in sequence.
7710 	 *
7711 	 * In the process of coming up with the most specific information,
7712 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7713 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7714 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7715 	 * Two caveats when handling incomplete ire's in ip_newroute:
7716 	 * - we should be careful when accessing its ire_nce (specifically
7717 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7718 	 * - not all legacy code path callers are prepared to handle
7719 	 *   incomplete ire's, so we should not create/add incomplete
7720 	 *   ire_cache entries here. (See discussion about temporary solution
7721 	 *   further below).
7722 	 *
7723 	 * In order to minimize packet dropping, and to preserve existing
7724 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7725 	 * gateway, and instead use the IF_RESOLVER ire to send out
7726 	 * another request to ARP (this is achieved by passing the
7727 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7728 	 * arp response comes back in ip_wput_nondata, we will create
7729 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7730 	 *
7731 	 * Note that this is a temporary solution; the correct solution is
7732 	 * to create an incomplete  per-dst ire_cache entry, and send the
7733 	 * packet out when the gw's nce is resolved. In order to achieve this,
7734 	 * all packet processing must have been completed prior to calling
7735 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7736 	 * to be modified to accomodate this solution.
7737 	 */
7738 	if (in_ill != NULL) {
7739 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7740 		    in_ill, MATCH_IRE_TYPE);
7741 	} else if (ip_nexthop) {
7742 		/*
7743 		 * The first time we come here, we look for an IRE_INTERFACE
7744 		 * entry for the specified nexthop, set the dst to be the
7745 		 * nexthop address and create an IRE_CACHE entry for the
7746 		 * nexthop. The next time around, we are able to find an
7747 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7748 		 * nexthop address and create an IRE_CACHE entry for the
7749 		 * destination address via the specified nexthop.
7750 		 */
7751 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7752 		    MBLK_GETLABEL(mp));
7753 		if (ire != NULL) {
7754 			gw = nexthop_addr;
7755 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7756 		} else {
7757 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7758 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7759 			    MBLK_GETLABEL(mp),
7760 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7761 			if (ire != NULL) {
7762 				dst = nexthop_addr;
7763 			}
7764 		}
7765 	} else if (attach_ill == NULL) {
7766 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7767 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7768 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7769 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7770 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7771 	} else {
7772 		/*
7773 		 * attach_ill is set only for communicating with
7774 		 * on-link hosts. So, don't look for DEFAULT.
7775 		 */
7776 		ipif_t	*attach_ipif;
7777 
7778 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7779 		if (attach_ipif == NULL) {
7780 			ill_refrele(attach_ill);
7781 			goto icmp_err_ret;
7782 		}
7783 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7784 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7785 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7786 		    MATCH_IRE_SECATTR);
7787 		ipif_refrele(attach_ipif);
7788 	}
7789 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7790 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7791 
7792 	/*
7793 	 * This loop is run only once in most cases.
7794 	 * We loop to resolve further routes only when the destination
7795 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7796 	 */
7797 	do {
7798 		/* Clear the previous iteration's values */
7799 		if (src_ipif != NULL) {
7800 			ipif_refrele(src_ipif);
7801 			src_ipif = NULL;
7802 		}
7803 		if (dst_ill != NULL) {
7804 			ill_refrele(dst_ill);
7805 			dst_ill = NULL;
7806 		}
7807 
7808 		multirt_resolve_next = B_FALSE;
7809 		/*
7810 		 * We check if packets have to be multirouted.
7811 		 * In this case, given the current <ire, sire> couple,
7812 		 * we look for the next suitable <ire, sire>.
7813 		 * This check is done in ire_multirt_lookup(),
7814 		 * which applies various criteria to find the next route
7815 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7816 		 * unchanged if it detects it has not been tried yet.
7817 		 */
7818 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7819 			ip3dbg(("ip_newroute: starting next_resolution "
7820 			    "with first_mp %p, tag %d\n",
7821 			    (void *)first_mp,
7822 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7823 
7824 			ASSERT(sire != NULL);
7825 			multirt_is_resolvable =
7826 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7827 				MBLK_GETLABEL(mp));
7828 
7829 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7830 			    "ire %p, sire %p\n",
7831 			    multirt_is_resolvable,
7832 			    (void *)ire, (void *)sire));
7833 
7834 			if (!multirt_is_resolvable) {
7835 				/*
7836 				 * No more multirt route to resolve; give up
7837 				 * (all routes resolved or no more
7838 				 * resolvable routes).
7839 				 */
7840 				if (ire != NULL) {
7841 					ire_refrele(ire);
7842 					ire = NULL;
7843 				}
7844 			} else {
7845 				ASSERT(sire != NULL);
7846 				ASSERT(ire != NULL);
7847 				/*
7848 				 * We simply use first_sire as a flag that
7849 				 * indicates if a resolvable multirt route
7850 				 * has already been found.
7851 				 * If it is not the case, we may have to send
7852 				 * an ICMP error to report that the
7853 				 * destination is unreachable.
7854 				 * We do not IRE_REFHOLD first_sire.
7855 				 */
7856 				if (first_sire == NULL) {
7857 					first_sire = sire;
7858 				}
7859 			}
7860 		}
7861 		if (ire == NULL) {
7862 			if (ip_debug > 3) {
7863 				/* ip2dbg */
7864 				pr_addr_dbg("ip_newroute: "
7865 				    "can't resolve %s\n", AF_INET, &dst);
7866 			}
7867 			ip3dbg(("ip_newroute: "
7868 			    "ire %p, sire %p, first_sire %p\n",
7869 			    (void *)ire, (void *)sire, (void *)first_sire));
7870 
7871 			if (sire != NULL) {
7872 				ire_refrele(sire);
7873 				sire = NULL;
7874 			}
7875 
7876 			if (first_sire != NULL) {
7877 				/*
7878 				 * At least one multirt route has been found
7879 				 * in the same call to ip_newroute();
7880 				 * there is no need to report an ICMP error.
7881 				 * first_sire was not IRE_REFHOLDed.
7882 				 */
7883 				MULTIRT_DEBUG_UNTAG(first_mp);
7884 				freemsg(first_mp);
7885 				return;
7886 			}
7887 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7888 			    RTA_DST);
7889 			if (attach_ill != NULL)
7890 				ill_refrele(attach_ill);
7891 			goto icmp_err_ret;
7892 		}
7893 
7894 		/*
7895 		 * When RTA_SRCIFP is used to add a route, then an interface
7896 		 * route is added in the source interface's routing table.
7897 		 * If the outgoing interface of this route is of type
7898 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7899 		 * ire_nce->nce_res_mp is set to NULL.
7900 		 * Later, when this route is first used for forwarding
7901 		 * a packet, ip_newroute() is called
7902 		 * to resolve the hardware address of the outgoing ipif.
7903 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7904 		 * source interface based table. We only come here if the
7905 		 * outgoing interface is a resolver interface and we don't
7906 		 * have the ire_nce->nce_res_mp information yet.
7907 		 * If in_ill is not null that means it is called from
7908 		 * ip_rput.
7909 		 */
7910 
7911 		ASSERT(ire->ire_in_ill == NULL ||
7912 		    (ire->ire_type == IRE_IF_RESOLVER &&
7913 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7914 
7915 		/*
7916 		 * Verify that the returned IRE does not have either
7917 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7918 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7919 		 */
7920 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7921 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7922 			if (attach_ill != NULL)
7923 				ill_refrele(attach_ill);
7924 			goto icmp_err_ret;
7925 		}
7926 		/*
7927 		 * Increment the ire_ob_pkt_count field for ire if it is an
7928 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7929 		 * increment the same for the parent IRE, sire, if it is some
7930 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7931 		 * and HOST_REDIRECT).
7932 		 */
7933 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7934 			UPDATE_OB_PKT_COUNT(ire);
7935 			ire->ire_last_used_time = lbolt;
7936 		}
7937 
7938 		if (sire != NULL) {
7939 			gw = sire->ire_gateway_addr;
7940 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7941 			    IRE_INTERFACE)) == 0);
7942 			UPDATE_OB_PKT_COUNT(sire);
7943 			sire->ire_last_used_time = lbolt;
7944 		}
7945 		/*
7946 		 * We have a route to reach the destination.
7947 		 *
7948 		 * 1) If the interface is part of ill group, try to get a new
7949 		 *    ill taking load spreading into account.
7950 		 *
7951 		 * 2) After selecting the ill, get a source address that
7952 		 *    might create good inbound load spreading.
7953 		 *    ipif_select_source does this for us.
7954 		 *
7955 		 * If the application specified the ill (ifindex), we still
7956 		 * load spread. Only if the packets needs to go out
7957 		 * specifically on a given ill e.g. binding to
7958 		 * IPIF_NOFAILOVER address, then we don't try to use a
7959 		 * different ill for load spreading.
7960 		 */
7961 		if (attach_ill == NULL) {
7962 			/*
7963 			 * Don't perform outbound load spreading in the
7964 			 * case of an RTF_MULTIRT route, as we actually
7965 			 * typically want to replicate outgoing packets
7966 			 * through particular interfaces.
7967 			 */
7968 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7969 				dst_ill = ire->ire_ipif->ipif_ill;
7970 				/* for uniformity */
7971 				ill_refhold(dst_ill);
7972 			} else {
7973 				/*
7974 				 * If we are here trying to create an IRE_CACHE
7975 				 * for an offlink destination and have the
7976 				 * IRE_CACHE for the next hop and the latter is
7977 				 * using virtual IP source address selection i.e
7978 				 * it's ire->ire_ipif is pointing to a virtual
7979 				 * network interface (vni) then
7980 				 * ip_newroute_get_dst_ll() will return the vni
7981 				 * interface as the dst_ill. Since the vni is
7982 				 * virtual i.e not associated with any physical
7983 				 * interface, it cannot be the dst_ill, hence
7984 				 * in such a case call ip_newroute_get_dst_ll()
7985 				 * with the stq_ill instead of the ire_ipif ILL.
7986 				 * The function returns a refheld ill.
7987 				 */
7988 				if ((ire->ire_type == IRE_CACHE) &&
7989 				    IS_VNI(ire->ire_ipif->ipif_ill))
7990 					dst_ill = ip_newroute_get_dst_ill(
7991 						ire->ire_stq->q_ptr);
7992 				else
7993 					dst_ill = ip_newroute_get_dst_ill(
7994 						ire->ire_ipif->ipif_ill);
7995 			}
7996 			if (dst_ill == NULL) {
7997 				if (ip_debug > 2) {
7998 					pr_addr_dbg("ip_newroute: "
7999 					    "no dst ill for dst"
8000 					    " %s\n", AF_INET, &dst);
8001 				}
8002 				goto icmp_err_ret;
8003 			}
8004 		} else {
8005 			dst_ill = ire->ire_ipif->ipif_ill;
8006 			/* for uniformity */
8007 			ill_refhold(dst_ill);
8008 			/*
8009 			 * We should have found a route matching ill as we
8010 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8011 			 * Rather than asserting, when there is a mismatch,
8012 			 * we just drop the packet.
8013 			 */
8014 			if (dst_ill != attach_ill) {
8015 				ip0dbg(("ip_newroute: Packet dropped as "
8016 				    "IPIF_NOFAILOVER ill is %s, "
8017 				    "ire->ire_ipif->ipif_ill is %s\n",
8018 				    attach_ill->ill_name,
8019 				    dst_ill->ill_name));
8020 				ill_refrele(attach_ill);
8021 				goto icmp_err_ret;
8022 			}
8023 		}
8024 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8025 		if (attach_ill != NULL) {
8026 			ill_refrele(attach_ill);
8027 			attach_ill = NULL;
8028 			do_attach_ill = B_TRUE;
8029 		}
8030 		ASSERT(dst_ill != NULL);
8031 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8032 
8033 		/*
8034 		 * Pick the best source address from dst_ill.
8035 		 *
8036 		 * 1) If it is part of a multipathing group, we would
8037 		 *    like to spread the inbound packets across different
8038 		 *    interfaces. ipif_select_source picks a random source
8039 		 *    across the different ills in the group.
8040 		 *
8041 		 * 2) If it is not part of a multipathing group, we try
8042 		 *    to pick the source address from the destination
8043 		 *    route. Clustering assumes that when we have multiple
8044 		 *    prefixes hosted on an interface, the prefix of the
8045 		 *    source address matches the prefix of the destination
8046 		 *    route. We do this only if the address is not
8047 		 *    DEPRECATED.
8048 		 *
8049 		 * 3) If the conn is in a different zone than the ire, we
8050 		 *    need to pick a source address from the right zone.
8051 		 *
8052 		 * NOTE : If we hit case (1) above, the prefix of the source
8053 		 *	  address picked may not match the prefix of the
8054 		 *	  destination routes prefix as ipif_select_source
8055 		 *	  does not look at "dst" while picking a source
8056 		 *	  address.
8057 		 *	  If we want the same behavior as (2), we will need
8058 		 *	  to change the behavior of ipif_select_source.
8059 		 */
8060 		ASSERT(src_ipif == NULL);
8061 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8062 			/*
8063 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8064 			 * Check that the ipif matching the requested source
8065 			 * address still exists.
8066 			 */
8067 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8068 			    zoneid, NULL, NULL, NULL, NULL);
8069 		}
8070 		if (src_ipif == NULL) {
8071 			ire_marks |= IRE_MARK_USESRC_CHECK;
8072 			if ((dst_ill->ill_group != NULL) ||
8073 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8074 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8075 			    ire->ire_zoneid != ALL_ZONES) ||
8076 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8077 				/*
8078 				 * If the destination is reachable via a
8079 				 * given gateway, the selected source address
8080 				 * should be in the same subnet as the gateway.
8081 				 * Otherwise, the destination is not reachable.
8082 				 *
8083 				 * If there are no interfaces on the same subnet
8084 				 * as the destination, ipif_select_source gives
8085 				 * first non-deprecated interface which might be
8086 				 * on a different subnet than the gateway.
8087 				 * This is not desirable. Hence pass the dst_ire
8088 				 * source address to ipif_select_source.
8089 				 * It is sure that the destination is reachable
8090 				 * with the dst_ire source address subnet.
8091 				 * So passing dst_ire source address to
8092 				 * ipif_select_source will make sure that the
8093 				 * selected source will be on the same subnet
8094 				 * as dst_ire source address.
8095 				 */
8096 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8097 				src_ipif = ipif_select_source(dst_ill, saddr,
8098 				    zoneid);
8099 				if (src_ipif == NULL) {
8100 					if (ip_debug > 2) {
8101 						pr_addr_dbg("ip_newroute: "
8102 						    "no src for dst %s ",
8103 						    AF_INET, &dst);
8104 						printf("through interface %s\n",
8105 						    dst_ill->ill_name);
8106 					}
8107 					goto icmp_err_ret;
8108 				}
8109 			} else {
8110 				src_ipif = ire->ire_ipif;
8111 				ASSERT(src_ipif != NULL);
8112 				/* hold src_ipif for uniformity */
8113 				ipif_refhold(src_ipif);
8114 			}
8115 		}
8116 
8117 		/*
8118 		 * Assign a source address while we have the conn.
8119 		 * We can't have ip_wput_ire pick a source address when the
8120 		 * packet returns from arp since we need to look at
8121 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8122 		 * going through arp.
8123 		 *
8124 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8125 		 *	  it uses ip6i to store this information.
8126 		 */
8127 		if (ipha->ipha_src == INADDR_ANY &&
8128 		    (connp == NULL || !connp->conn_unspec_src)) {
8129 			ipha->ipha_src = src_ipif->ipif_src_addr;
8130 		}
8131 		if (ip_debug > 3) {
8132 			/* ip2dbg */
8133 			pr_addr_dbg("ip_newroute: first hop %s\n",
8134 			    AF_INET, &gw);
8135 		}
8136 		ip2dbg(("\tire type %s (%d)\n",
8137 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8138 
8139 		/*
8140 		 * The TTL of multirouted packets is bounded by the
8141 		 * ip_multirt_ttl ndd variable.
8142 		 */
8143 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8144 			/* Force TTL of multirouted packets */
8145 			if ((ip_multirt_ttl > 0) &&
8146 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8147 				ip2dbg(("ip_newroute: forcing multirt TTL "
8148 				    "to %d (was %d), dst 0x%08x\n",
8149 				    ip_multirt_ttl, ipha->ipha_ttl,
8150 				    ntohl(sire->ire_addr)));
8151 				ipha->ipha_ttl = ip_multirt_ttl;
8152 			}
8153 		}
8154 		/*
8155 		 * At this point in ip_newroute(), ire is either the
8156 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8157 		 * destination or an IRE_INTERFACE type that should be used
8158 		 * to resolve an on-subnet destination or an on-subnet
8159 		 * next-hop gateway.
8160 		 *
8161 		 * In the IRE_CACHE case, we have the following :
8162 		 *
8163 		 * 1) src_ipif - used for getting a source address.
8164 		 *
8165 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8166 		 *    means packets using this IRE_CACHE will go out on
8167 		 *    dst_ill.
8168 		 *
8169 		 * 3) The IRE sire will point to the prefix that is the
8170 		 *    longest  matching route for the destination. These
8171 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8172 		 *
8173 		 *    The newly created IRE_CACHE entry for the off-subnet
8174 		 *    destination is tied to both the prefix route and the
8175 		 *    interface route used to resolve the next-hop gateway
8176 		 *    via the ire_phandle and ire_ihandle fields,
8177 		 *    respectively.
8178 		 *
8179 		 * In the IRE_INTERFACE case, we have the following :
8180 		 *
8181 		 * 1) src_ipif - used for getting a source address.
8182 		 *
8183 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8184 		 *    means packets using the IRE_CACHE that we will build
8185 		 *    here will go out on dst_ill.
8186 		 *
8187 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8188 		 *    to be created will only be tied to the IRE_INTERFACE
8189 		 *    that was derived from the ire_ihandle field.
8190 		 *
8191 		 *    If sire is non-NULL, it means the destination is
8192 		 *    off-link and we will first create the IRE_CACHE for the
8193 		 *    gateway. Next time through ip_newroute, we will create
8194 		 *    the IRE_CACHE for the final destination as described
8195 		 *    above.
8196 		 *
8197 		 * In both cases, after the current resolution has been
8198 		 * completed (or possibly initialised, in the IRE_INTERFACE
8199 		 * case), the loop may be re-entered to attempt the resolution
8200 		 * of another RTF_MULTIRT route.
8201 		 *
8202 		 * When an IRE_CACHE entry for the off-subnet destination is
8203 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8204 		 * for further processing in emission loops.
8205 		 */
8206 		save_ire = ire;
8207 		switch (ire->ire_type) {
8208 		case IRE_CACHE: {
8209 			ire_t	*ipif_ire;
8210 			mblk_t	*ire_fp_mp;
8211 
8212 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8213 			if (gw == 0)
8214 				gw = ire->ire_gateway_addr;
8215 			/*
8216 			 * We need 3 ire's to create a new cache ire for an
8217 			 * off-link destination from the cache ire of the
8218 			 * gateway.
8219 			 *
8220 			 *	1. The prefix ire 'sire' (Note that this does
8221 			 *	   not apply to the conn_nexthop_set case)
8222 			 *	2. The cache ire of the gateway 'ire'
8223 			 *	3. The interface ire 'ipif_ire'
8224 			 *
8225 			 * We have (1) and (2). We lookup (3) below.
8226 			 *
8227 			 * If there is no interface route to the gateway,
8228 			 * it is a race condition, where we found the cache
8229 			 * but the interface route has been deleted.
8230 			 */
8231 			if (ip_nexthop) {
8232 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8233 			} else {
8234 				ipif_ire =
8235 				    ire_ihandle_lookup_offlink(ire, sire);
8236 			}
8237 			if (ipif_ire == NULL) {
8238 				ip1dbg(("ip_newroute: "
8239 				    "ire_ihandle_lookup_offlink failed\n"));
8240 				goto icmp_err_ret;
8241 			}
8242 			/*
8243 			 * XXX We are using the same res_mp
8244 			 * (DL_UNITDATA_REQ) though the save_ire is not
8245 			 * pointing at the same ill.
8246 			 * This is incorrect. We need to send it up to the
8247 			 * resolver to get the right res_mp. For ethernets
8248 			 * this may be okay (ill_type == DL_ETHER).
8249 			 */
8250 			res_mp = save_ire->ire_nce->nce_res_mp;
8251 			ire_fp_mp = NULL;
8252 			/*
8253 			 * save_ire's nce_fp_mp can't change since it is
8254 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8255 			 * LOCK_IRE_FP_MP does not do any useful work in
8256 			 * the case of IRE_CACHE. So we don't use it below.
8257 			 */
8258 			if (save_ire->ire_stq == dst_ill->ill_wq)
8259 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8260 
8261 			/*
8262 			 * Check cached gateway IRE for any security
8263 			 * attributes; if found, associate the gateway
8264 			 * credentials group to the destination IRE.
8265 			 */
8266 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8267 				mutex_enter(&attrp->igsa_lock);
8268 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8269 					GCGRP_REFHOLD(gcgrp);
8270 				mutex_exit(&attrp->igsa_lock);
8271 			}
8272 
8273 			ire = ire_create(
8274 			    (uchar_t *)&dst,		/* dest address */
8275 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8276 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8277 			    (uchar_t *)&gw,		/* gateway address */
8278 			    NULL,
8279 			    &save_ire->ire_max_frag,
8280 			    ire_fp_mp,			/* Fast Path header */
8281 			    dst_ill->ill_rq,		/* recv-from queue */
8282 			    dst_ill->ill_wq,		/* send-to queue */
8283 			    IRE_CACHE,			/* IRE type */
8284 			    res_mp,
8285 			    src_ipif,
8286 			    in_ill,			/* incoming ill */
8287 			    (sire != NULL) ?
8288 				sire->ire_mask : 0, 	/* Parent mask */
8289 			    (sire != NULL) ?
8290 				sire->ire_phandle : 0,  /* Parent handle */
8291 			    ipif_ire->ire_ihandle,	/* Interface handle */
8292 			    (sire != NULL) ? (sire->ire_flags &
8293 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8294 			    (sire != NULL) ?
8295 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8296 			    NULL,
8297 			    gcgrp);
8298 
8299 			if (ire == NULL) {
8300 				if (gcgrp != NULL) {
8301 					GCGRP_REFRELE(gcgrp);
8302 					gcgrp = NULL;
8303 				}
8304 				ire_refrele(ipif_ire);
8305 				ire_refrele(save_ire);
8306 				break;
8307 			}
8308 
8309 			/* reference now held by IRE */
8310 			gcgrp = NULL;
8311 
8312 			ire->ire_marks |= ire_marks;
8313 
8314 			/*
8315 			 * Prevent sire and ipif_ire from getting deleted.
8316 			 * The newly created ire is tied to both of them via
8317 			 * the phandle and ihandle respectively.
8318 			 */
8319 			if (sire != NULL) {
8320 				IRB_REFHOLD(sire->ire_bucket);
8321 				/* Has it been removed already ? */
8322 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8323 					IRB_REFRELE(sire->ire_bucket);
8324 					ire_refrele(ipif_ire);
8325 					ire_refrele(save_ire);
8326 					break;
8327 				}
8328 			}
8329 
8330 			IRB_REFHOLD(ipif_ire->ire_bucket);
8331 			/* Has it been removed already ? */
8332 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8333 				IRB_REFRELE(ipif_ire->ire_bucket);
8334 				if (sire != NULL)
8335 					IRB_REFRELE(sire->ire_bucket);
8336 				ire_refrele(ipif_ire);
8337 				ire_refrele(save_ire);
8338 				break;
8339 			}
8340 
8341 			xmit_mp = first_mp;
8342 			/*
8343 			 * In the case of multirouting, a copy
8344 			 * of the packet is done before its sending.
8345 			 * The copy is used to attempt another
8346 			 * route resolution, in a next loop.
8347 			 */
8348 			if (ire->ire_flags & RTF_MULTIRT) {
8349 				copy_mp = copymsg(first_mp);
8350 				if (copy_mp != NULL) {
8351 					xmit_mp = copy_mp;
8352 					MULTIRT_DEBUG_TAG(first_mp);
8353 				}
8354 			}
8355 			ire_add_then_send(q, ire, xmit_mp);
8356 			ire_refrele(save_ire);
8357 
8358 			/* Assert that sire is not deleted yet. */
8359 			if (sire != NULL) {
8360 				ASSERT(sire->ire_ptpn != NULL);
8361 				IRB_REFRELE(sire->ire_bucket);
8362 			}
8363 
8364 			/* Assert that ipif_ire is not deleted yet. */
8365 			ASSERT(ipif_ire->ire_ptpn != NULL);
8366 			IRB_REFRELE(ipif_ire->ire_bucket);
8367 			ire_refrele(ipif_ire);
8368 
8369 			/*
8370 			 * If copy_mp is not NULL, multirouting was
8371 			 * requested. We loop to initiate a next
8372 			 * route resolution attempt, starting from sire.
8373 			 */
8374 			if (copy_mp != NULL) {
8375 				/*
8376 				 * Search for the next unresolved
8377 				 * multirt route.
8378 				 */
8379 				copy_mp = NULL;
8380 				ipif_ire = NULL;
8381 				ire = NULL;
8382 				multirt_resolve_next = B_TRUE;
8383 				continue;
8384 			}
8385 			if (sire != NULL)
8386 				ire_refrele(sire);
8387 			ipif_refrele(src_ipif);
8388 			ill_refrele(dst_ill);
8389 			return;
8390 		}
8391 		case IRE_IF_NORESOLVER: {
8392 			/*
8393 			 * We have what we need to build an IRE_CACHE.
8394 			 *
8395 			 * Create a new res_mp with the IP gateway address
8396 			 * in destination address in the DLPI hdr if the
8397 			 * physical length is exactly 4 bytes.
8398 			 */
8399 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8400 				uchar_t *addr;
8401 
8402 				if (gw)
8403 					addr = (uchar_t *)&gw;
8404 				else
8405 					addr = (uchar_t *)&dst;
8406 
8407 				res_mp = ill_dlur_gen(addr,
8408 				    dst_ill->ill_phys_addr_length,
8409 				    dst_ill->ill_sap,
8410 				    dst_ill->ill_sap_length);
8411 
8412 				if (res_mp == NULL) {
8413 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8414 					break;
8415 				}
8416 			} else if (dst_ill->ill_resolver_mp == NULL) {
8417 				ip1dbg(("ip_newroute: dst_ill %p "
8418 				    "for IF_NORESOLV ire %p has "
8419 				    "no ill_resolver_mp\n",
8420 				    (void *)dst_ill, (void *)ire));
8421 				break;
8422 			} else {
8423 				res_mp = NULL;
8424 			}
8425 
8426 			/*
8427 			 * TSol note: We are creating the ire cache for the
8428 			 * destination 'dst'. If 'dst' is offlink, going
8429 			 * through the first hop 'gw', the security attributes
8430 			 * of 'dst' must be set to point to the gateway
8431 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8432 			 * is possible that 'dst' is a potential gateway that is
8433 			 * referenced by some route that has some security
8434 			 * attributes. Thus in the former case, we need to do a
8435 			 * gcgrp_lookup of 'gw' while in the latter case we
8436 			 * need to do gcgrp_lookup of 'dst' itself.
8437 			 */
8438 			ga.ga_af = AF_INET;
8439 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8440 			    &ga.ga_addr);
8441 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8442 
8443 			ire = ire_create(
8444 			    (uchar_t *)&dst,		/* dest address */
8445 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8446 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8447 			    (uchar_t *)&gw,		/* gateway address */
8448 			    NULL,
8449 			    &save_ire->ire_max_frag,
8450 			    NULL,			/* Fast Path header */
8451 			    dst_ill->ill_rq,		/* recv-from queue */
8452 			    dst_ill->ill_wq,		/* send-to queue */
8453 			    IRE_CACHE,
8454 			    res_mp,
8455 			    src_ipif,
8456 			    in_ill,			/* Incoming ill */
8457 			    save_ire->ire_mask,		/* Parent mask */
8458 			    (sire != NULL) ?		/* Parent handle */
8459 				sire->ire_phandle : 0,
8460 			    save_ire->ire_ihandle,	/* Interface handle */
8461 			    (sire != NULL) ? sire->ire_flags &
8462 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8463 			    &(save_ire->ire_uinfo),
8464 			    NULL,
8465 			    gcgrp);
8466 
8467 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8468 				freeb(res_mp);
8469 
8470 			if (ire == NULL) {
8471 				if (gcgrp != NULL) {
8472 					GCGRP_REFRELE(gcgrp);
8473 					gcgrp = NULL;
8474 				}
8475 				ire_refrele(save_ire);
8476 				break;
8477 			}
8478 
8479 			/* reference now held by IRE */
8480 			gcgrp = NULL;
8481 
8482 			ire->ire_marks |= ire_marks;
8483 
8484 			/* Prevent save_ire from getting deleted */
8485 			IRB_REFHOLD(save_ire->ire_bucket);
8486 			/* Has it been removed already ? */
8487 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8488 				IRB_REFRELE(save_ire->ire_bucket);
8489 				ire_refrele(save_ire);
8490 				break;
8491 			}
8492 
8493 			/*
8494 			 * In the case of multirouting, a copy
8495 			 * of the packet is made before it is sent.
8496 			 * The copy is used in the next
8497 			 * loop to attempt another resolution.
8498 			 */
8499 			xmit_mp = first_mp;
8500 			if ((sire != NULL) &&
8501 			    (sire->ire_flags & RTF_MULTIRT)) {
8502 				copy_mp = copymsg(first_mp);
8503 				if (copy_mp != NULL) {
8504 					xmit_mp = copy_mp;
8505 					MULTIRT_DEBUG_TAG(first_mp);
8506 				}
8507 			}
8508 			ire_add_then_send(q, ire, xmit_mp);
8509 
8510 			/* Assert that it is not deleted yet. */
8511 			ASSERT(save_ire->ire_ptpn != NULL);
8512 			IRB_REFRELE(save_ire->ire_bucket);
8513 			ire_refrele(save_ire);
8514 
8515 			if (copy_mp != NULL) {
8516 				/*
8517 				 * If we found a (no)resolver, we ignore any
8518 				 * trailing top priority IRE_CACHE in further
8519 				 * loops. This ensures that we do not omit any
8520 				 * (no)resolver.
8521 				 * This IRE_CACHE, if any, will be processed
8522 				 * by another thread entering ip_newroute().
8523 				 * IRE_CACHE entries, if any, will be processed
8524 				 * by another thread entering ip_newroute(),
8525 				 * (upon resolver response, for instance).
8526 				 * This aims to force parallel multirt
8527 				 * resolutions as soon as a packet must be sent.
8528 				 * In the best case, after the tx of only one
8529 				 * packet, all reachable routes are resolved.
8530 				 * Otherwise, the resolution of all RTF_MULTIRT
8531 				 * routes would require several emissions.
8532 				 */
8533 				multirt_flags &= ~MULTIRT_CACHEGW;
8534 
8535 				/*
8536 				 * Search for the next unresolved multirt
8537 				 * route.
8538 				 */
8539 				copy_mp = NULL;
8540 				save_ire = NULL;
8541 				ire = NULL;
8542 				multirt_resolve_next = B_TRUE;
8543 				continue;
8544 			}
8545 
8546 			/*
8547 			 * Don't need sire anymore
8548 			 */
8549 			if (sire != NULL)
8550 				ire_refrele(sire);
8551 
8552 			ipif_refrele(src_ipif);
8553 			ill_refrele(dst_ill);
8554 			return;
8555 		}
8556 		case IRE_IF_RESOLVER:
8557 			/*
8558 			 * We can't build an IRE_CACHE yet, but at least we
8559 			 * found a resolver that can help.
8560 			 */
8561 			res_mp = dst_ill->ill_resolver_mp;
8562 			if (!OK_RESOLVER_MP(res_mp))
8563 				break;
8564 
8565 			/*
8566 			 * To be at this point in the code with a non-zero gw
8567 			 * means that dst is reachable through a gateway that
8568 			 * we have never resolved.  By changing dst to the gw
8569 			 * addr we resolve the gateway first.
8570 			 * When ire_add_then_send() tries to put the IP dg
8571 			 * to dst, it will reenter ip_newroute() at which
8572 			 * time we will find the IRE_CACHE for the gw and
8573 			 * create another IRE_CACHE in case IRE_CACHE above.
8574 			 */
8575 			if (gw != INADDR_ANY) {
8576 				/*
8577 				 * The source ipif that was determined above was
8578 				 * relative to the destination address, not the
8579 				 * gateway's. If src_ipif was not taken out of
8580 				 * the IRE_IF_RESOLVER entry, we'll need to call
8581 				 * ipif_select_source() again.
8582 				 */
8583 				if (src_ipif != ire->ire_ipif) {
8584 					ipif_refrele(src_ipif);
8585 					src_ipif = ipif_select_source(dst_ill,
8586 					    gw, zoneid);
8587 					if (src_ipif == NULL) {
8588 						if (ip_debug > 2) {
8589 							pr_addr_dbg(
8590 							    "ip_newroute: no "
8591 							    "src for gw %s ",
8592 							    AF_INET, &gw);
8593 							printf("through "
8594 							    "interface %s\n",
8595 							    dst_ill->ill_name);
8596 						}
8597 						goto icmp_err_ret;
8598 					}
8599 				}
8600 				save_dst = dst;
8601 				dst = gw;
8602 				gw = INADDR_ANY;
8603 			}
8604 
8605 			/*
8606 			 * We obtain a partial IRE_CACHE which we will pass
8607 			 * along with the resolver query.  When the response
8608 			 * comes back it will be there ready for us to add.
8609 			 * The ire_max_frag is atomically set under the
8610 			 * irebucket lock in ire_add_v[46].
8611 			 */
8612 
8613 			ire = ire_create_mp(
8614 			    (uchar_t *)&dst,		/* dest address */
8615 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8616 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8617 			    (uchar_t *)&gw,		/* gateway address */
8618 			    NULL,			/* no in_src_addr */
8619 			    NULL,			/* ire_max_frag */
8620 			    NULL,			/* Fast Path header */
8621 			    dst_ill->ill_rq,		/* recv-from queue */
8622 			    dst_ill->ill_wq,		/* send-to queue */
8623 			    IRE_CACHE,
8624 			    NULL,
8625 			    src_ipif,			/* Interface ipif */
8626 			    in_ill,			/* Incoming ILL */
8627 			    save_ire->ire_mask,		/* Parent mask */
8628 			    0,
8629 			    save_ire->ire_ihandle,	/* Interface handle */
8630 			    0,				/* flags if any */
8631 			    &(save_ire->ire_uinfo),
8632 			    NULL,
8633 			    NULL);
8634 
8635 			if (ire == NULL) {
8636 				ire_refrele(save_ire);
8637 				break;
8638 			}
8639 
8640 			if ((sire != NULL) &&
8641 			    (sire->ire_flags & RTF_MULTIRT)) {
8642 				copy_mp = copymsg(first_mp);
8643 				if (copy_mp != NULL)
8644 					MULTIRT_DEBUG_TAG(copy_mp);
8645 			}
8646 
8647 			ire->ire_marks |= ire_marks;
8648 
8649 			/*
8650 			 * Construct message chain for the resolver
8651 			 * of the form:
8652 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8653 			 * Packet could contain a IPSEC_OUT mp.
8654 			 *
8655 			 * NOTE : ire will be added later when the response
8656 			 * comes back from ARP. If the response does not
8657 			 * come back, ARP frees the packet. For this reason,
8658 			 * we can't REFHOLD the bucket of save_ire to prevent
8659 			 * deletions. We may not be able to REFRELE the bucket
8660 			 * if the response never comes back. Thus, before
8661 			 * adding the ire, ire_add_v4 will make sure that the
8662 			 * interface route does not get deleted. This is the
8663 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8664 			 * where we can always prevent deletions because of
8665 			 * the synchronous nature of adding IRES i.e
8666 			 * ire_add_then_send is called after creating the IRE.
8667 			 */
8668 			ASSERT(ire->ire_mp != NULL);
8669 			ire->ire_mp->b_cont = first_mp;
8670 			/* Have saved_mp handy, for cleanup if canput fails */
8671 			saved_mp = mp;
8672 			mp = copyb(res_mp);
8673 			if (mp == NULL) {
8674 				/* Prepare for cleanup */
8675 				mp = saved_mp; /* pkt */
8676 				ire_delete(ire); /* ire_mp */
8677 				ire = NULL;
8678 				ire_refrele(save_ire);
8679 				if (copy_mp != NULL) {
8680 					MULTIRT_DEBUG_UNTAG(copy_mp);
8681 					freemsg(copy_mp);
8682 					copy_mp = NULL;
8683 				}
8684 				break;
8685 			}
8686 			linkb(mp, ire->ire_mp);
8687 
8688 			/*
8689 			 * Fill in the source and dest addrs for the resolver.
8690 			 * NOTE: this depends on memory layouts imposed by
8691 			 * ill_init().
8692 			 */
8693 			areq = (areq_t *)mp->b_rptr;
8694 			addrp = (ipaddr_t *)((char *)areq +
8695 			    areq->areq_sender_addr_offset);
8696 			if (do_attach_ill) {
8697 				/*
8698 				 * This is bind to no failover case.
8699 				 * arp packet also must go out on attach_ill.
8700 				 */
8701 				ASSERT(ipha->ipha_src != NULL);
8702 				*addrp = ipha->ipha_src;
8703 			} else {
8704 				*addrp = save_ire->ire_src_addr;
8705 			}
8706 
8707 			ire_refrele(save_ire);
8708 			addrp = (ipaddr_t *)((char *)areq +
8709 			    areq->areq_target_addr_offset);
8710 			*addrp = dst;
8711 			/* Up to the resolver. */
8712 			if (canputnext(dst_ill->ill_rq) &&
8713 			    !(dst_ill->ill_arp_closing)) {
8714 				putnext(dst_ill->ill_rq, mp);
8715 				ire = NULL;
8716 				if (copy_mp != NULL) {
8717 					/*
8718 					 * If we found a resolver, we ignore
8719 					 * any trailing top priority IRE_CACHE
8720 					 * in the further loops. This ensures
8721 					 * that we do not omit any resolver.
8722 					 * IRE_CACHE entries, if any, will be
8723 					 * processed next time we enter
8724 					 * ip_newroute().
8725 					 */
8726 					multirt_flags &= ~MULTIRT_CACHEGW;
8727 					/*
8728 					 * Search for the next unresolved
8729 					 * multirt route.
8730 					 */
8731 					first_mp = copy_mp;
8732 					copy_mp = NULL;
8733 					/* Prepare the next resolution loop. */
8734 					mp = first_mp;
8735 					EXTRACT_PKT_MP(mp, first_mp,
8736 					    mctl_present);
8737 					if (mctl_present)
8738 						io = (ipsec_out_t *)
8739 						    first_mp->b_rptr;
8740 					ipha = (ipha_t *)mp->b_rptr;
8741 
8742 					ASSERT(sire != NULL);
8743 
8744 					dst = save_dst;
8745 					multirt_resolve_next = B_TRUE;
8746 					continue;
8747 				}
8748 
8749 				if (sire != NULL)
8750 					ire_refrele(sire);
8751 
8752 				/*
8753 				 * The response will come back in ip_wput
8754 				 * with db_type IRE_DB_TYPE.
8755 				 */
8756 				ipif_refrele(src_ipif);
8757 				ill_refrele(dst_ill);
8758 				return;
8759 			} else {
8760 				/* Prepare for cleanup */
8761 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8762 				    mp);
8763 				mp->b_cont = NULL;
8764 				freeb(mp); /* areq */
8765 				/*
8766 				 * this is an ire that is not added to the
8767 				 * cache. ire_freemblk will handle the release
8768 				 * of any resources associated with the ire.
8769 				 */
8770 				ire_delete(ire); /* ire_mp */
8771 				mp = saved_mp; /* pkt */
8772 				ire = NULL;
8773 				if (copy_mp != NULL) {
8774 					MULTIRT_DEBUG_UNTAG(copy_mp);
8775 					freemsg(copy_mp);
8776 					copy_mp = NULL;
8777 				}
8778 				break;
8779 			}
8780 		default:
8781 			break;
8782 		}
8783 	} while (multirt_resolve_next);
8784 
8785 	ip1dbg(("ip_newroute: dropped\n"));
8786 	/* Did this packet originate externally? */
8787 	if (mp->b_prev) {
8788 		mp->b_next = NULL;
8789 		mp->b_prev = NULL;
8790 		BUMP_MIB(&ip_mib, ipInDiscards);
8791 	} else {
8792 		BUMP_MIB(&ip_mib, ipOutDiscards);
8793 	}
8794 	ASSERT(copy_mp == NULL);
8795 	MULTIRT_DEBUG_UNTAG(first_mp);
8796 	freemsg(first_mp);
8797 	if (ire != NULL)
8798 		ire_refrele(ire);
8799 	if (sire != NULL)
8800 		ire_refrele(sire);
8801 	if (src_ipif != NULL)
8802 		ipif_refrele(src_ipif);
8803 	if (dst_ill != NULL)
8804 		ill_refrele(dst_ill);
8805 	return;
8806 
8807 icmp_err_ret:
8808 	ip1dbg(("ip_newroute: no route\n"));
8809 	if (src_ipif != NULL)
8810 		ipif_refrele(src_ipif);
8811 	if (dst_ill != NULL)
8812 		ill_refrele(dst_ill);
8813 	if (sire != NULL)
8814 		ire_refrele(sire);
8815 	/* Did this packet originate externally? */
8816 	if (mp->b_prev) {
8817 		mp->b_next = NULL;
8818 		mp->b_prev = NULL;
8819 		/* XXX ipInNoRoutes */
8820 		q = WR(q);
8821 	} else {
8822 		/*
8823 		 * Since ip_wput() isn't close to finished, we fill
8824 		 * in enough of the header for credible error reporting.
8825 		 */
8826 		if (ip_hdr_complete(ipha, zoneid)) {
8827 			/* Failed */
8828 			MULTIRT_DEBUG_UNTAG(first_mp);
8829 			freemsg(first_mp);
8830 			if (ire != NULL)
8831 				ire_refrele(ire);
8832 			return;
8833 		}
8834 	}
8835 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8836 
8837 	/*
8838 	 * At this point we will have ire only if RTF_BLACKHOLE
8839 	 * or RTF_REJECT flags are set on the IRE. It will not
8840 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8841 	 */
8842 	if (ire != NULL) {
8843 		if (ire->ire_flags & RTF_BLACKHOLE) {
8844 			ire_refrele(ire);
8845 			MULTIRT_DEBUG_UNTAG(first_mp);
8846 			freemsg(first_mp);
8847 			return;
8848 		}
8849 		ire_refrele(ire);
8850 	}
8851 	if (ip_source_routed(ipha)) {
8852 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8853 		    zoneid);
8854 		return;
8855 	}
8856 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8857 }
8858 
8859 /*
8860  * IPv4 -
8861  * ip_newroute_ipif is called by ip_wput_multicast and
8862  * ip_rput_forward_multicast whenever we need to send
8863  * out a packet to a destination address for which we do not have specific
8864  * routing information. It is used when the packet will be sent out
8865  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8866  * socket option is set or icmp error message wants to go out on a particular
8867  * interface for a unicast packet.
8868  *
8869  * In most cases, the destination address is resolved thanks to the ipif
8870  * intrinsic resolver. However, there are some cases where the call to
8871  * ip_newroute_ipif must take into account the potential presence of
8872  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8873  * that uses the interface. This is specified through flags,
8874  * which can be a combination of:
8875  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8876  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8877  *   and flags. Additionally, the packet source address has to be set to
8878  *   the specified address. The caller is thus expected to set this flag
8879  *   if the packet has no specific source address yet.
8880  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8881  *   flag, the resulting ire will inherit the flag. All unresolved routes
8882  *   to the destination must be explored in the same call to
8883  *   ip_newroute_ipif().
8884  */
8885 static void
8886 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8887     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8888 {
8889 	areq_t	*areq;
8890 	ire_t	*ire = NULL;
8891 	mblk_t	*res_mp;
8892 	ipaddr_t *addrp;
8893 	mblk_t *first_mp;
8894 	ire_t	*save_ire = NULL;
8895 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8896 	ipif_t	*src_ipif = NULL;
8897 	ushort_t ire_marks = 0;
8898 	ill_t	*dst_ill = NULL;
8899 	boolean_t mctl_present;
8900 	ipsec_out_t *io;
8901 	ipha_t *ipha;
8902 	int	ihandle = 0;
8903 	mblk_t	*saved_mp;
8904 	ire_t   *fire = NULL;
8905 	mblk_t  *copy_mp = NULL;
8906 	boolean_t multirt_resolve_next;
8907 	ipaddr_t ipha_dst;
8908 
8909 	/*
8910 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8911 	 * here for uniformity
8912 	 */
8913 	ipif_refhold(ipif);
8914 
8915 	/*
8916 	 * This loop is run only once in most cases.
8917 	 * We loop to resolve further routes only when the destination
8918 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8919 	 */
8920 	do {
8921 		if (dst_ill != NULL) {
8922 			ill_refrele(dst_ill);
8923 			dst_ill = NULL;
8924 		}
8925 		if (src_ipif != NULL) {
8926 			ipif_refrele(src_ipif);
8927 			src_ipif = NULL;
8928 		}
8929 		multirt_resolve_next = B_FALSE;
8930 
8931 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8932 		    ipif->ipif_ill->ill_name));
8933 
8934 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8935 		if (mctl_present)
8936 			io = (ipsec_out_t *)first_mp->b_rptr;
8937 
8938 		ipha = (ipha_t *)mp->b_rptr;
8939 
8940 		/*
8941 		 * Save the packet destination address, we may need it after
8942 		 * the packet has been consumed.
8943 		 */
8944 		ipha_dst = ipha->ipha_dst;
8945 
8946 		/*
8947 		 * If the interface is a pt-pt interface we look for an
8948 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8949 		 * local_address and the pt-pt destination address. Otherwise
8950 		 * we just match the local address.
8951 		 * NOTE: dst could be different than ipha->ipha_dst in case
8952 		 * of sending igmp multicast packets over a point-to-point
8953 		 * connection.
8954 		 * Thus we must be careful enough to check ipha_dst to be a
8955 		 * multicast address, otherwise it will take xmit_if path for
8956 		 * multicast packets resulting into kernel stack overflow by
8957 		 * repeated calls to ip_newroute_ipif from ire_send().
8958 		 */
8959 		if (CLASSD(ipha_dst) &&
8960 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8961 			goto err_ret;
8962 		}
8963 
8964 		/*
8965 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8966 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8967 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8968 		 * propagate its flags to the new ire.
8969 		 */
8970 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8971 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8972 			ip2dbg(("ip_newroute_ipif: "
8973 			    "ipif_lookup_multi_ire("
8974 			    "ipif %p, dst %08x) = fire %p\n",
8975 			    (void *)ipif, ntohl(dst), (void *)fire));
8976 		}
8977 
8978 		if (mctl_present && io->ipsec_out_attach_if) {
8979 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8980 			    io->ipsec_out_ill_index, B_FALSE);
8981 
8982 			/* Failure case frees things for us. */
8983 			if (attach_ill == NULL) {
8984 				ipif_refrele(ipif);
8985 				if (fire != NULL)
8986 					ire_refrele(fire);
8987 				return;
8988 			}
8989 
8990 			/*
8991 			 * Check if we need an ire that will not be
8992 			 * looked up by anybody else i.e. HIDDEN.
8993 			 */
8994 			if (ill_is_probeonly(attach_ill)) {
8995 				ire_marks = IRE_MARK_HIDDEN;
8996 			}
8997 			/*
8998 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8999 			 * case.
9000 			 */
9001 			dst_ill = ipif->ipif_ill;
9002 			/* attach_ill has been refheld by ip_grab_attach_ill */
9003 			ASSERT(dst_ill == attach_ill);
9004 		} else {
9005 			/*
9006 			 * If this is set by IP_XMIT_IF, then make sure that
9007 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9008 			 * specified ill.
9009 			 */
9010 			ASSERT((connp == NULL) ||
9011 			    (connp->conn_xmit_if_ill == NULL) ||
9012 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9013 			/*
9014 			 * If the interface belongs to an interface group,
9015 			 * make sure the next possible interface in the group
9016 			 * is used.  This encourages load spreading among
9017 			 * peers in an interface group.
9018 			 * Note: load spreading is disabled for RTF_MULTIRT
9019 			 * routes.
9020 			 */
9021 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9022 			    (fire->ire_flags & RTF_MULTIRT)) {
9023 				/*
9024 				 * Don't perform outbound load spreading
9025 				 * in the case of an RTF_MULTIRT issued route,
9026 				 * we actually typically want to replicate
9027 				 * outgoing packets through particular
9028 				 * interfaces.
9029 				 */
9030 				dst_ill = ipif->ipif_ill;
9031 				ill_refhold(dst_ill);
9032 			} else {
9033 				dst_ill = ip_newroute_get_dst_ill(
9034 				    ipif->ipif_ill);
9035 			}
9036 			if (dst_ill == NULL) {
9037 				if (ip_debug > 2) {
9038 					pr_addr_dbg("ip_newroute_ipif: "
9039 					    "no dst ill for dst %s\n",
9040 					    AF_INET, &dst);
9041 				}
9042 				goto err_ret;
9043 			}
9044 		}
9045 
9046 		/*
9047 		 * Pick a source address preferring non-deprecated ones.
9048 		 * Unlike ip_newroute, we don't do any source address
9049 		 * selection here since for multicast it really does not help
9050 		 * in inbound load spreading as in the unicast case.
9051 		 */
9052 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9053 		    (fire->ire_flags & RTF_SETSRC)) {
9054 			/*
9055 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9056 			 * on that interface. This ire has RTF_SETSRC flag, so
9057 			 * the source address of the packet must be changed.
9058 			 * Check that the ipif matching the requested source
9059 			 * address still exists.
9060 			 */
9061 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9062 			    zoneid, NULL, NULL, NULL, NULL);
9063 		}
9064 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9065 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9066 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9067 		    (src_ipif == NULL)) {
9068 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9069 			if (src_ipif == NULL) {
9070 				if (ip_debug > 2) {
9071 					/* ip1dbg */
9072 					pr_addr_dbg("ip_newroute_ipif: "
9073 					    "no src for dst %s",
9074 					    AF_INET, &dst);
9075 				}
9076 				ip1dbg((" through interface %s\n",
9077 				    dst_ill->ill_name));
9078 				goto err_ret;
9079 			}
9080 			ipif_refrele(ipif);
9081 			ipif = src_ipif;
9082 			ipif_refhold(ipif);
9083 		}
9084 		if (src_ipif == NULL) {
9085 			src_ipif = ipif;
9086 			ipif_refhold(src_ipif);
9087 		}
9088 
9089 		/*
9090 		 * Assign a source address while we have the conn.
9091 		 * We can't have ip_wput_ire pick a source address when the
9092 		 * packet returns from arp since conn_unspec_src might be set
9093 		 * and we loose the conn when going through arp.
9094 		 */
9095 		if (ipha->ipha_src == INADDR_ANY &&
9096 		    (connp == NULL || !connp->conn_unspec_src)) {
9097 			ipha->ipha_src = src_ipif->ipif_src_addr;
9098 		}
9099 
9100 		/*
9101 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9102 		 * interface does not have an interface ire.
9103 		 * Example: Thousands of mobileip PPP interfaces to mobile
9104 		 * nodes. We don't want to create interface ires because
9105 		 * packets from other mobile nodes must not take the route
9106 		 * via interface ires to the visiting mobile node without
9107 		 * going through the home agent, in absence of mobileip
9108 		 * route optimization.
9109 		 */
9110 		if (CLASSD(ipha_dst) && (connp == NULL ||
9111 		    connp->conn_xmit_if_ill == NULL)) {
9112 			/* ipif_to_ire returns an held ire */
9113 			ire = ipif_to_ire(ipif);
9114 			if (ire == NULL)
9115 				goto err_ret;
9116 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9117 				goto err_ret;
9118 			/*
9119 			 * ihandle is needed when the ire is added to
9120 			 * cache table.
9121 			 */
9122 			save_ire = ire;
9123 			ihandle = save_ire->ire_ihandle;
9124 
9125 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9126 			    "flags %04x\n",
9127 			    (void *)ire, (void *)ipif, flags));
9128 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9129 			    (fire->ire_flags & RTF_MULTIRT)) {
9130 				/*
9131 				 * As requested by flags, an IRE_OFFSUBNET was
9132 				 * looked up on that interface. This ire has
9133 				 * RTF_MULTIRT flag, so the resolution loop will
9134 				 * be re-entered to resolve additional routes on
9135 				 * other interfaces. For that purpose, a copy of
9136 				 * the packet is performed at this point.
9137 				 */
9138 				fire->ire_last_used_time = lbolt;
9139 				copy_mp = copymsg(first_mp);
9140 				if (copy_mp) {
9141 					MULTIRT_DEBUG_TAG(copy_mp);
9142 				}
9143 			}
9144 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9145 			    (fire->ire_flags & RTF_SETSRC)) {
9146 				/*
9147 				 * As requested by flags, an IRE_OFFSUBET was
9148 				 * looked up on that interface. This ire has
9149 				 * RTF_SETSRC flag, so the source address of the
9150 				 * packet must be changed.
9151 				 */
9152 				ipha->ipha_src = fire->ire_src_addr;
9153 			}
9154 		} else {
9155 			ASSERT((connp == NULL) ||
9156 			    (connp->conn_xmit_if_ill != NULL) ||
9157 			    (connp->conn_dontroute));
9158 			/*
9159 			 * The only ways we can come here are:
9160 			 * 1) IP_XMIT_IF socket option is set
9161 			 * 2) ICMP error message generated from
9162 			 *    ip_mrtun_forward() routine and it needs
9163 			 *    to go through the specified ill.
9164 			 * 3) SO_DONTROUTE socket option is set
9165 			 * In all cases, the new ire will not be added
9166 			 * into cache table.
9167 			 */
9168 			ire_marks |= IRE_MARK_NOADD;
9169 		}
9170 
9171 		switch (ipif->ipif_net_type) {
9172 		case IRE_IF_NORESOLVER: {
9173 			/* We have what we need to build an IRE_CACHE. */
9174 			mblk_t	*res_mp;
9175 
9176 			/*
9177 			 * Create a new res_mp with the
9178 			 * IP gateway address as destination address in the
9179 			 * DLPI hdr if the physical length is exactly 4 bytes.
9180 			 */
9181 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9182 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9183 				    dst_ill->ill_phys_addr_length,
9184 				    dst_ill->ill_sap,
9185 				    dst_ill->ill_sap_length);
9186 			} else if (dst_ill->ill_resolver_mp == NULL) {
9187 				ip1dbg(("ip_newroute: dst_ill %p "
9188 				    "for IF_NORESOLV ire %p has "
9189 				    "no ill_resolver_mp\n",
9190 				    (void *)dst_ill, (void *)ire));
9191 				break;
9192 			} else {
9193 				/* use the value set in ip_ll_subnet_defaults */
9194 				res_mp = ill_dlur_gen(NULL,
9195 				    dst_ill->ill_phys_addr_length,
9196 				    dst_ill->ill_sap,
9197 				    dst_ill->ill_sap_length);
9198 			}
9199 
9200 			if (res_mp == NULL)
9201 				break;
9202 			/*
9203 			 * The new ire inherits the IRE_OFFSUBNET flags
9204 			 * and source address, if this was requested.
9205 			 */
9206 			ire = ire_create(
9207 			    (uchar_t *)&dst,		/* dest address */
9208 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9209 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9210 			    NULL,			/* gateway address */
9211 			    NULL,
9212 			    &ipif->ipif_mtu,
9213 			    NULL,			/* Fast Path header */
9214 			    dst_ill->ill_rq,		/* recv-from queue */
9215 			    dst_ill->ill_wq,		/* send-to queue */
9216 			    IRE_CACHE,
9217 			    res_mp,
9218 			    src_ipif,
9219 			    NULL,
9220 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9221 			    (fire != NULL) ?		/* Parent handle */
9222 				fire->ire_phandle : 0,
9223 			    ihandle,			/* Interface handle */
9224 			    (fire != NULL) ?
9225 				(fire->ire_flags &
9226 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9227 			    (save_ire == NULL ? &ire_uinfo_null :
9228 				&save_ire->ire_uinfo),
9229 			    NULL,
9230 			    NULL);
9231 
9232 			freeb(res_mp);
9233 
9234 			if (ire == NULL) {
9235 				if (save_ire != NULL)
9236 					ire_refrele(save_ire);
9237 				break;
9238 			}
9239 
9240 			ire->ire_marks |= ire_marks;
9241 
9242 			/*
9243 			 * If IRE_MARK_NOADD is set then we need to convert
9244 			 * the max_fragp to a useable value now. This is
9245 			 * normally done in ire_add_v[46]. We also need to
9246 			 * associate the ire with an nce (normally would be
9247 			 * done in ip_wput_nondata()).
9248 			 *
9249 			 * Note that IRE_MARK_NOADD packets created here
9250 			 * do not have a non-null ire_mp pointer. The null
9251 			 * value of ire_bucket indicates that they were
9252 			 * never added.
9253 			 */
9254 			if (ire->ire_marks & IRE_MARK_NOADD) {
9255 				uint_t  max_frag;
9256 
9257 				max_frag = *ire->ire_max_fragp;
9258 				ire->ire_max_fragp = NULL;
9259 				ire->ire_max_frag = max_frag;
9260 
9261 				if ((ire->ire_nce = ndp_lookup_v4(
9262 				    ire_to_ill(ire),
9263 				    (ire->ire_gateway_addr != INADDR_ANY ?
9264 				    &ire->ire_gateway_addr : &ire->ire_addr),
9265 				    B_FALSE)) == NULL) {
9266 					if (save_ire != NULL)
9267 						ire_refrele(save_ire);
9268 					break;
9269 				}
9270 				ASSERT(ire->ire_nce->nce_state ==
9271 				    ND_REACHABLE);
9272 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9273 			}
9274 
9275 			/* Prevent save_ire from getting deleted */
9276 			if (save_ire != NULL) {
9277 				IRB_REFHOLD(save_ire->ire_bucket);
9278 				/* Has it been removed already ? */
9279 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9280 					IRB_REFRELE(save_ire->ire_bucket);
9281 					ire_refrele(save_ire);
9282 					break;
9283 				}
9284 			}
9285 
9286 			ire_add_then_send(q, ire, first_mp);
9287 
9288 			/* Assert that save_ire is not deleted yet. */
9289 			if (save_ire != NULL) {
9290 				ASSERT(save_ire->ire_ptpn != NULL);
9291 				IRB_REFRELE(save_ire->ire_bucket);
9292 				ire_refrele(save_ire);
9293 				save_ire = NULL;
9294 			}
9295 			if (fire != NULL) {
9296 				ire_refrele(fire);
9297 				fire = NULL;
9298 			}
9299 
9300 			/*
9301 			 * the resolution loop is re-entered if this
9302 			 * was requested through flags and if we
9303 			 * actually are in a multirouting case.
9304 			 */
9305 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9306 				boolean_t need_resolve =
9307 				    ire_multirt_need_resolve(ipha_dst,
9308 					MBLK_GETLABEL(copy_mp));
9309 				if (!need_resolve) {
9310 					MULTIRT_DEBUG_UNTAG(copy_mp);
9311 					freemsg(copy_mp);
9312 					copy_mp = NULL;
9313 				} else {
9314 					/*
9315 					 * ipif_lookup_group() calls
9316 					 * ire_lookup_multi() that uses
9317 					 * ire_ftable_lookup() to find
9318 					 * an IRE_INTERFACE for the group.
9319 					 * In the multirt case,
9320 					 * ire_lookup_multi() then invokes
9321 					 * ire_multirt_lookup() to find
9322 					 * the next resolvable ire.
9323 					 * As a result, we obtain an new
9324 					 * interface, derived from the
9325 					 * next ire.
9326 					 */
9327 					ipif_refrele(ipif);
9328 					ipif = ipif_lookup_group(ipha_dst,
9329 					    zoneid);
9330 					ip2dbg(("ip_newroute_ipif: "
9331 					    "multirt dst %08x, ipif %p\n",
9332 					    htonl(dst), (void *)ipif));
9333 					if (ipif != NULL) {
9334 						mp = copy_mp;
9335 						copy_mp = NULL;
9336 						multirt_resolve_next = B_TRUE;
9337 						continue;
9338 					} else {
9339 						freemsg(copy_mp);
9340 					}
9341 				}
9342 			}
9343 			if (ipif != NULL)
9344 				ipif_refrele(ipif);
9345 			ill_refrele(dst_ill);
9346 			ipif_refrele(src_ipif);
9347 			return;
9348 		}
9349 		case IRE_IF_RESOLVER:
9350 			/*
9351 			 * We can't build an IRE_CACHE yet, but at least
9352 			 * we found a resolver that can help.
9353 			 */
9354 			res_mp = dst_ill->ill_resolver_mp;
9355 			if (!OK_RESOLVER_MP(res_mp))
9356 				break;
9357 
9358 			/*
9359 			 * We obtain a partial IRE_CACHE which we will pass
9360 			 * along with the resolver query.  When the response
9361 			 * comes back it will be there ready for us to add.
9362 			 * The new ire inherits the IRE_OFFSUBNET flags
9363 			 * and source address, if this was requested.
9364 			 * The ire_max_frag is atomically set under the
9365 			 * irebucket lock in ire_add_v[46]. Only in the
9366 			 * case of IRE_MARK_NOADD, we set it here itself.
9367 			 */
9368 			ire = ire_create_mp(
9369 			    (uchar_t *)&dst,		/* dest address */
9370 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9371 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9372 			    NULL,			/* gateway address */
9373 			    NULL,			/* no in_src_addr */
9374 			    (ire_marks & IRE_MARK_NOADD) ?
9375 				ipif->ipif_mtu : 0,	/* max_frag */
9376 			    NULL,			/* Fast path header */
9377 			    dst_ill->ill_rq,		/* recv-from queue */
9378 			    dst_ill->ill_wq,		/* send-to queue */
9379 			    IRE_CACHE,
9380 			    NULL,	/* let ire_nce_init figure res_mp out */
9381 			    src_ipif,
9382 			    NULL,
9383 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9384 			    (fire != NULL) ?		/* Parent handle */
9385 				fire->ire_phandle : 0,
9386 			    ihandle,			/* Interface handle */
9387 			    (fire != NULL) ?		/* flags if any */
9388 				(fire->ire_flags &
9389 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9390 			    (save_ire == NULL ? &ire_uinfo_null :
9391 				&save_ire->ire_uinfo),
9392 			    NULL,
9393 			    NULL);
9394 
9395 			if (save_ire != NULL) {
9396 				ire_refrele(save_ire);
9397 				save_ire = NULL;
9398 			}
9399 			if (ire == NULL)
9400 				break;
9401 
9402 			ire->ire_marks |= ire_marks;
9403 			/*
9404 			 * Construct message chain for the resolver of the
9405 			 * form:
9406 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9407 			 *
9408 			 * NOTE : ire will be added later when the response
9409 			 * comes back from ARP. If the response does not
9410 			 * come back, ARP frees the packet. For this reason,
9411 			 * we can't REFHOLD the bucket of save_ire to prevent
9412 			 * deletions. We may not be able to REFRELE the
9413 			 * bucket if the response never comes back.
9414 			 * Thus, before adding the ire, ire_add_v4 will make
9415 			 * sure that the interface route does not get deleted.
9416 			 * This is the only case unlike ip_newroute_v6,
9417 			 * ip_newroute_ipif_v6 where we can always prevent
9418 			 * deletions because ire_add_then_send is called after
9419 			 * creating the IRE.
9420 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9421 			 * does not add this IRE into the IRE CACHE.
9422 			 */
9423 			ASSERT(ire->ire_mp != NULL);
9424 			ire->ire_mp->b_cont = first_mp;
9425 			/* Have saved_mp handy, for cleanup if canput fails */
9426 			saved_mp = mp;
9427 			mp = copyb(res_mp);
9428 			if (mp == NULL) {
9429 				/* Prepare for cleanup */
9430 				mp = saved_mp; /* pkt */
9431 				ire_delete(ire); /* ire_mp */
9432 				ire = NULL;
9433 				if (copy_mp != NULL) {
9434 					MULTIRT_DEBUG_UNTAG(copy_mp);
9435 					freemsg(copy_mp);
9436 					copy_mp = NULL;
9437 				}
9438 				break;
9439 			}
9440 			linkb(mp, ire->ire_mp);
9441 
9442 			/*
9443 			 * Fill in the source and dest addrs for the resolver.
9444 			 * NOTE: this depends on memory layouts imposed by
9445 			 * ill_init().
9446 			 */
9447 			areq = (areq_t *)mp->b_rptr;
9448 			addrp = (ipaddr_t *)((char *)areq +
9449 			    areq->areq_sender_addr_offset);
9450 			*addrp = ire->ire_src_addr;
9451 			addrp = (ipaddr_t *)((char *)areq +
9452 			    areq->areq_target_addr_offset);
9453 			*addrp = dst;
9454 			/* Up to the resolver. */
9455 			if (canputnext(dst_ill->ill_rq) &&
9456 			    !(dst_ill->ill_arp_closing)) {
9457 				putnext(dst_ill->ill_rq, mp);
9458 				/*
9459 				 * The response will come back in ip_wput
9460 				 * with db_type IRE_DB_TYPE.
9461 				 */
9462 			} else {
9463 				mp->b_cont = NULL;
9464 				freeb(mp); /* areq */
9465 				ire_delete(ire); /* ire_mp */
9466 				saved_mp->b_next = NULL;
9467 				saved_mp->b_prev = NULL;
9468 				freemsg(first_mp); /* pkt */
9469 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9470 			}
9471 
9472 			if (fire != NULL) {
9473 				ire_refrele(fire);
9474 				fire = NULL;
9475 			}
9476 
9477 
9478 			/*
9479 			 * The resolution loop is re-entered if this was
9480 			 * requested through flags and we actually are
9481 			 * in a multirouting case.
9482 			 */
9483 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9484 				boolean_t need_resolve =
9485 				    ire_multirt_need_resolve(ipha_dst,
9486 					MBLK_GETLABEL(copy_mp));
9487 				if (!need_resolve) {
9488 					MULTIRT_DEBUG_UNTAG(copy_mp);
9489 					freemsg(copy_mp);
9490 					copy_mp = NULL;
9491 				} else {
9492 					/*
9493 					 * ipif_lookup_group() calls
9494 					 * ire_lookup_multi() that uses
9495 					 * ire_ftable_lookup() to find
9496 					 * an IRE_INTERFACE for the group.
9497 					 * In the multirt case,
9498 					 * ire_lookup_multi() then invokes
9499 					 * ire_multirt_lookup() to find
9500 					 * the next resolvable ire.
9501 					 * As a result, we obtain an new
9502 					 * interface, derived from the
9503 					 * next ire.
9504 					 */
9505 					ipif_refrele(ipif);
9506 					ipif = ipif_lookup_group(ipha_dst,
9507 					    zoneid);
9508 					if (ipif != NULL) {
9509 						mp = copy_mp;
9510 						copy_mp = NULL;
9511 						multirt_resolve_next = B_TRUE;
9512 						continue;
9513 					} else {
9514 						freemsg(copy_mp);
9515 					}
9516 				}
9517 			}
9518 			if (ipif != NULL)
9519 				ipif_refrele(ipif);
9520 			ill_refrele(dst_ill);
9521 			ipif_refrele(src_ipif);
9522 			return;
9523 		default:
9524 			break;
9525 		}
9526 	} while (multirt_resolve_next);
9527 
9528 err_ret:
9529 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9530 	if (fire != NULL)
9531 		ire_refrele(fire);
9532 	ipif_refrele(ipif);
9533 	/* Did this packet originate externally? */
9534 	if (dst_ill != NULL)
9535 		ill_refrele(dst_ill);
9536 	if (src_ipif != NULL)
9537 		ipif_refrele(src_ipif);
9538 	if (mp->b_prev || mp->b_next) {
9539 		mp->b_next = NULL;
9540 		mp->b_prev = NULL;
9541 	} else {
9542 		/*
9543 		 * Since ip_wput() isn't close to finished, we fill
9544 		 * in enough of the header for credible error reporting.
9545 		 */
9546 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9547 			/* Failed */
9548 			freemsg(first_mp);
9549 			if (ire != NULL)
9550 				ire_refrele(ire);
9551 			return;
9552 		}
9553 	}
9554 	/*
9555 	 * At this point we will have ire only if RTF_BLACKHOLE
9556 	 * or RTF_REJECT flags are set on the IRE. It will not
9557 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9558 	 */
9559 	if (ire != NULL) {
9560 		if (ire->ire_flags & RTF_BLACKHOLE) {
9561 			ire_refrele(ire);
9562 			freemsg(first_mp);
9563 			return;
9564 		}
9565 		ire_refrele(ire);
9566 	}
9567 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9568 }
9569 
9570 /* Name/Value Table Lookup Routine */
9571 char *
9572 ip_nv_lookup(nv_t *nv, int value)
9573 {
9574 	if (!nv)
9575 		return (NULL);
9576 	for (; nv->nv_name; nv++) {
9577 		if (nv->nv_value == value)
9578 			return (nv->nv_name);
9579 	}
9580 	return ("unknown");
9581 }
9582 
9583 /*
9584  * one day it can be patched to 1 from /etc/system for machines that have few
9585  * fast network interfaces feeding multiple cpus.
9586  */
9587 int ill_stream_putlocks = 0;
9588 
9589 /*
9590  * This is a module open, i.e. this is a control stream for access
9591  * to a DLPI device.  We allocate an ill_t as the instance data in
9592  * this case.
9593  */
9594 int
9595 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9596 {
9597 	uint32_t mem_cnt;
9598 	uint32_t cpu_cnt;
9599 	uint32_t min_cnt;
9600 	pgcnt_t mem_avail;
9601 	ill_t	*ill;
9602 	int	err;
9603 
9604 	/*
9605 	 * Prevent unprivileged processes from pushing IP so that
9606 	 * they can't send raw IP.
9607 	 */
9608 	if (secpolicy_net_rawaccess(credp) != 0)
9609 		return (EPERM);
9610 
9611 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9612 	q->q_ptr = WR(q)->q_ptr = ill;
9613 
9614 	/*
9615 	 * ill_init initializes the ill fields and then sends down
9616 	 * down a DL_INFO_REQ after calling qprocson.
9617 	 */
9618 	err = ill_init(q, ill);
9619 	if (err != 0) {
9620 		mi_free(ill);
9621 		q->q_ptr = NULL;
9622 		WR(q)->q_ptr = NULL;
9623 		return (err);
9624 	}
9625 
9626 	/* ill_init initializes the ipsq marking this thread as writer */
9627 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9628 	/* Wait for the DL_INFO_ACK */
9629 	mutex_enter(&ill->ill_lock);
9630 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9631 		/*
9632 		 * Return value of 0 indicates a pending signal.
9633 		 */
9634 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9635 		if (err == 0) {
9636 			mutex_exit(&ill->ill_lock);
9637 			(void) ip_close(q, 0);
9638 			return (EINTR);
9639 		}
9640 	}
9641 	mutex_exit(&ill->ill_lock);
9642 
9643 	/*
9644 	 * ip_rput_other could have set an error  in ill_error on
9645 	 * receipt of M_ERROR.
9646 	 */
9647 
9648 	err = ill->ill_error;
9649 	if (err != 0) {
9650 		(void) ip_close(q, 0);
9651 		return (err);
9652 	}
9653 
9654 	/*
9655 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9656 	 * size and the cpu speed of the machine. This is upper
9657 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9658 	 * and is lower bounded by the compile time value of
9659 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9660 	 * ip6_ire_max_bucket_cnt.
9661 	 */
9662 	mem_avail = kmem_avail();
9663 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9664 	    ip_cache_table_size / sizeof (ire_t);
9665 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9666 
9667 	min_cnt = MIN(cpu_cnt, mem_cnt);
9668 	if (min_cnt < ip_ire_min_bucket_cnt)
9669 		min_cnt = ip_ire_min_bucket_cnt;
9670 	if (ip_ire_max_bucket_cnt > min_cnt) {
9671 		ip_ire_max_bucket_cnt = min_cnt;
9672 	}
9673 
9674 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9675 	    ip6_cache_table_size / sizeof (ire_t);
9676 	min_cnt = MIN(cpu_cnt, mem_cnt);
9677 	if (min_cnt < ip6_ire_min_bucket_cnt)
9678 		min_cnt = ip6_ire_min_bucket_cnt;
9679 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9680 		ip6_ire_max_bucket_cnt = min_cnt;
9681 	}
9682 
9683 	ill->ill_credp = credp;
9684 	crhold(credp);
9685 
9686 	mutex_enter(&ip_mi_lock);
9687 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9688 	mutex_exit(&ip_mi_lock);
9689 	if (err) {
9690 		(void) ip_close(q, 0);
9691 		return (err);
9692 	}
9693 	return (0);
9694 }
9695 
9696 /* IP open routine. */
9697 int
9698 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9699 {
9700 	conn_t 		*connp;
9701 	major_t		maj;
9702 
9703 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9704 
9705 	/* Allow reopen. */
9706 	if (q->q_ptr != NULL)
9707 		return (0);
9708 
9709 	if (sflag & MODOPEN) {
9710 		/* This is a module open */
9711 		return (ip_modopen(q, devp, flag, sflag, credp));
9712 	}
9713 
9714 	/*
9715 	 * We are opening as a device. This is an IP client stream, and we
9716 	 * allocate an conn_t as the instance data.
9717 	 */
9718 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9719 	connp->conn_upq = q;
9720 	q->q_ptr = WR(q)->q_ptr = connp;
9721 
9722 	if (flag & SO_SOCKSTR)
9723 		connp->conn_flags |= IPCL_SOCKET;
9724 
9725 	/* Minor tells us which /dev entry was opened */
9726 	if (geteminor(*devp) == IPV6_MINOR) {
9727 		connp->conn_flags |= IPCL_ISV6;
9728 		connp->conn_af_isv6 = B_TRUE;
9729 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9730 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9731 	} else {
9732 		connp->conn_af_isv6 = B_FALSE;
9733 		connp->conn_pkt_isv6 = B_FALSE;
9734 	}
9735 
9736 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9737 		q->q_ptr = WR(q)->q_ptr = NULL;
9738 		CONN_DEC_REF(connp);
9739 		return (EBUSY);
9740 	}
9741 
9742 	maj = getemajor(*devp);
9743 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9744 
9745 	/*
9746 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9747 	 */
9748 	connp->conn_cred = credp;
9749 	crhold(connp->conn_cred);
9750 
9751 	/*
9752 	 * If the caller has the process-wide flag set, then default to MAC
9753 	 * exempt mode.  This allows read-down to unlabeled hosts.
9754 	 */
9755 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9756 		connp->conn_mac_exempt = B_TRUE;
9757 
9758 	connp->conn_zoneid = getzoneid();
9759 
9760 	/*
9761 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9762 	 * administrative ops.  In these cases, we just need a normal conn_t
9763 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9764 	 * an error will be returned.
9765 	 */
9766 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9767 		connp->conn_rq = q;
9768 		connp->conn_wq = WR(q);
9769 	} else {
9770 		connp->conn_ulp = IPPROTO_SCTP;
9771 		connp->conn_rq = connp->conn_wq = NULL;
9772 	}
9773 	/* Non-zero default values */
9774 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9775 
9776 	/*
9777 	 * Make the conn globally visible to walkers
9778 	 */
9779 	mutex_enter(&connp->conn_lock);
9780 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9781 	mutex_exit(&connp->conn_lock);
9782 	ASSERT(connp->conn_ref == 1);
9783 
9784 	qprocson(q);
9785 
9786 	return (0);
9787 }
9788 
9789 /*
9790  * Change q_qinfo based on the value of isv6.
9791  * This can not called on an ill queue.
9792  * Note that there is no race since either q_qinfo works for conn queues - it
9793  * is just an optimization to enter the best wput routine directly.
9794  */
9795 void
9796 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9797 {
9798 	ASSERT(q->q_flag & QREADR);
9799 	ASSERT(WR(q)->q_next == NULL);
9800 	ASSERT(q->q_ptr != NULL);
9801 
9802 	if (minor == IPV6_MINOR)  {
9803 		if (bump_mib)
9804 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9805 		q->q_qinfo = &rinit_ipv6;
9806 		WR(q)->q_qinfo = &winit_ipv6;
9807 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9808 	} else {
9809 		if (bump_mib)
9810 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9811 		q->q_qinfo = &iprinit;
9812 		WR(q)->q_qinfo = &ipwinit;
9813 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9814 	}
9815 
9816 }
9817 
9818 /*
9819  * See if IPsec needs loading because of the options in mp.
9820  */
9821 static boolean_t
9822 ipsec_opt_present(mblk_t *mp)
9823 {
9824 	uint8_t *optcp, *next_optcp, *opt_endcp;
9825 	struct opthdr *opt;
9826 	struct T_opthdr *topt;
9827 	int opthdr_len;
9828 	t_uscalar_t optname, optlevel;
9829 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9830 	ipsec_req_t *ipsr;
9831 
9832 	/*
9833 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9834 	 * return TRUE.
9835 	 */
9836 
9837 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9838 	opt_endcp = optcp + tor->OPT_length;
9839 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9840 		opthdr_len = sizeof (struct T_opthdr);
9841 	} else {		/* O_OPTMGMT_REQ */
9842 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9843 		opthdr_len = sizeof (struct opthdr);
9844 	}
9845 	for (; optcp < opt_endcp; optcp = next_optcp) {
9846 		if (optcp + opthdr_len > opt_endcp)
9847 			return (B_FALSE);	/* Not enough option header. */
9848 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9849 			topt = (struct T_opthdr *)optcp;
9850 			optlevel = topt->level;
9851 			optname = topt->name;
9852 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9853 		} else {
9854 			opt = (struct opthdr *)optcp;
9855 			optlevel = opt->level;
9856 			optname = opt->name;
9857 			next_optcp = optcp + opthdr_len +
9858 			    _TPI_ALIGN_OPT(opt->len);
9859 		}
9860 		if ((next_optcp < optcp) || /* wraparound pointer space */
9861 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9862 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9863 			return (B_FALSE); /* bad option buffer */
9864 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9865 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9866 			/*
9867 			 * Check to see if it's an all-bypass or all-zeroes
9868 			 * IPsec request.  Don't bother loading IPsec if
9869 			 * the socket doesn't want to use it.  (A good example
9870 			 * is a bypass request.)
9871 			 *
9872 			 * Basically, if any of the non-NEVER bits are set,
9873 			 * load IPsec.
9874 			 */
9875 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9876 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9877 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9878 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9879 			    != 0)
9880 				return (B_TRUE);
9881 		}
9882 	}
9883 	return (B_FALSE);
9884 }
9885 
9886 /*
9887  * If conn is is waiting for ipsec to finish loading, kick it.
9888  */
9889 /* ARGSUSED */
9890 static void
9891 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9892 {
9893 	t_scalar_t	optreq_prim;
9894 	mblk_t		*mp;
9895 	cred_t		*cr;
9896 	int		err = 0;
9897 
9898 	/*
9899 	 * This function is called, after ipsec loading is complete.
9900 	 * Since IP checks exclusively and atomically (i.e it prevents
9901 	 * ipsec load from completing until ip_optcom_req completes)
9902 	 * whether ipsec load is complete, there cannot be a race with IP
9903 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9904 	 */
9905 	mutex_enter(&connp->conn_lock);
9906 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9907 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9908 		mp = connp->conn_ipsec_opt_mp;
9909 		connp->conn_ipsec_opt_mp = NULL;
9910 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9911 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9912 		mutex_exit(&connp->conn_lock);
9913 
9914 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9915 
9916 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9917 		if (optreq_prim == T_OPTMGMT_REQ) {
9918 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9919 			    &ip_opt_obj);
9920 		} else {
9921 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9922 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9923 			    &ip_opt_obj);
9924 		}
9925 		if (err != EINPROGRESS)
9926 			CONN_OPER_PENDING_DONE(connp);
9927 		return;
9928 	}
9929 	mutex_exit(&connp->conn_lock);
9930 }
9931 
9932 /*
9933  * Called from the ipsec_loader thread, outside any perimeter, to tell
9934  * ip qenable any of the queues waiting for the ipsec loader to
9935  * complete.
9936  *
9937  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9938  * are done with this lock held, so it's guaranteed that none of the
9939  * links will change along the way.
9940  */
9941 void
9942 ip_ipsec_load_complete()
9943 {
9944 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9945 }
9946 
9947 /*
9948  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9949  * determines the grp on which it has to become exclusive, queues the mp
9950  * and sq draining restarts the optmgmt
9951  */
9952 static boolean_t
9953 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9954 {
9955 	conn_t *connp;
9956 
9957 	/*
9958 	 * Take IPsec requests and treat them special.
9959 	 */
9960 	if (ipsec_opt_present(mp)) {
9961 		/* First check if IPsec is loaded. */
9962 		mutex_enter(&ipsec_loader_lock);
9963 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9964 			mutex_exit(&ipsec_loader_lock);
9965 			return (B_FALSE);
9966 		}
9967 		connp = Q_TO_CONN(q);
9968 		mutex_enter(&connp->conn_lock);
9969 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9970 
9971 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9972 		connp->conn_ipsec_opt_mp = mp;
9973 		mutex_exit(&connp->conn_lock);
9974 		mutex_exit(&ipsec_loader_lock);
9975 
9976 		ipsec_loader_loadnow();
9977 		return (B_TRUE);
9978 	}
9979 	return (B_FALSE);
9980 }
9981 
9982 /*
9983  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9984  * all of them are copied to the conn_t. If the req is "zero", the policy is
9985  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9986  * fields.
9987  * We keep only the latest setting of the policy and thus policy setting
9988  * is not incremental/cumulative.
9989  *
9990  * Requests to set policies with multiple alternative actions will
9991  * go through a different API.
9992  */
9993 int
9994 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9995 {
9996 	uint_t ah_req = 0;
9997 	uint_t esp_req = 0;
9998 	uint_t se_req = 0;
9999 	ipsec_selkey_t sel;
10000 	ipsec_act_t *actp = NULL;
10001 	uint_t nact;
10002 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10003 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10004 	ipsec_policy_root_t *pr;
10005 	ipsec_policy_head_t *ph;
10006 	int fam;
10007 	boolean_t is_pol_reset;
10008 	int error = 0;
10009 
10010 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10011 
10012 	/*
10013 	 * The IP_SEC_OPT option does not allow variable length parameters,
10014 	 * hence a request cannot be NULL.
10015 	 */
10016 	if (req == NULL)
10017 		return (EINVAL);
10018 
10019 	ah_req = req->ipsr_ah_req;
10020 	esp_req = req->ipsr_esp_req;
10021 	se_req = req->ipsr_self_encap_req;
10022 
10023 	/*
10024 	 * Are we dealing with a request to reset the policy (i.e.
10025 	 * zero requests).
10026 	 */
10027 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10028 	    (esp_req & REQ_MASK) == 0 &&
10029 	    (se_req & REQ_MASK) == 0);
10030 
10031 	if (!is_pol_reset) {
10032 		/*
10033 		 * If we couldn't load IPsec, fail with "protocol
10034 		 * not supported".
10035 		 * IPsec may not have been loaded for a request with zero
10036 		 * policies, so we don't fail in this case.
10037 		 */
10038 		mutex_enter(&ipsec_loader_lock);
10039 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10040 			mutex_exit(&ipsec_loader_lock);
10041 			return (EPROTONOSUPPORT);
10042 		}
10043 		mutex_exit(&ipsec_loader_lock);
10044 
10045 		/*
10046 		 * Test for valid requests. Invalid algorithms
10047 		 * need to be tested by IPSEC code because new
10048 		 * algorithms can be added dynamically.
10049 		 */
10050 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10051 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10052 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10053 			return (EINVAL);
10054 		}
10055 
10056 		/*
10057 		 * Only privileged users can issue these
10058 		 * requests.
10059 		 */
10060 		if (((ah_req & IPSEC_PREF_NEVER) ||
10061 		    (esp_req & IPSEC_PREF_NEVER) ||
10062 		    (se_req & IPSEC_PREF_NEVER)) &&
10063 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10064 			return (EPERM);
10065 		}
10066 
10067 		/*
10068 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10069 		 * are mutually exclusive.
10070 		 */
10071 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10072 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10073 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10074 			/* Both of them are set */
10075 			return (EINVAL);
10076 		}
10077 	}
10078 
10079 	mutex_enter(&connp->conn_lock);
10080 
10081 	/*
10082 	 * If we have already cached policies in ip_bind_connected*(), don't
10083 	 * let them change now. We cache policies for connections
10084 	 * whose src,dst [addr, port] is known.
10085 	 */
10086 	if (connp->conn_policy_cached) {
10087 		mutex_exit(&connp->conn_lock);
10088 		return (EINVAL);
10089 	}
10090 
10091 	/*
10092 	 * We have a zero policies, reset the connection policy if already
10093 	 * set. This will cause the connection to inherit the
10094 	 * global policy, if any.
10095 	 */
10096 	if (is_pol_reset) {
10097 		if (connp->conn_policy != NULL) {
10098 			IPPH_REFRELE(connp->conn_policy);
10099 			connp->conn_policy = NULL;
10100 		}
10101 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10102 		connp->conn_in_enforce_policy = B_FALSE;
10103 		connp->conn_out_enforce_policy = B_FALSE;
10104 		mutex_exit(&connp->conn_lock);
10105 		return (0);
10106 	}
10107 
10108 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10109 	if (ph == NULL)
10110 		goto enomem;
10111 
10112 	ipsec_actvec_from_req(req, &actp, &nact);
10113 	if (actp == NULL)
10114 		goto enomem;
10115 
10116 	/*
10117 	 * Always allocate IPv4 policy entries, since they can also
10118 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10119 	 */
10120 	bzero(&sel, sizeof (sel));
10121 	sel.ipsl_valid = IPSL_IPV4;
10122 
10123 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10124 	if (pin4 == NULL)
10125 		goto enomem;
10126 
10127 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10128 	if (pout4 == NULL)
10129 		goto enomem;
10130 
10131 	if (connp->conn_pkt_isv6) {
10132 		/*
10133 		 * We're looking at a v6 socket, also allocate the
10134 		 * v6-specific entries...
10135 		 */
10136 		sel.ipsl_valid = IPSL_IPV6;
10137 		pin6 = ipsec_policy_create(&sel, actp, nact,
10138 		    IPSEC_PRIO_SOCKET, NULL);
10139 		if (pin6 == NULL)
10140 			goto enomem;
10141 
10142 		pout6 = ipsec_policy_create(&sel, actp, nact,
10143 		    IPSEC_PRIO_SOCKET, NULL);
10144 		if (pout6 == NULL)
10145 			goto enomem;
10146 
10147 		/*
10148 		 * .. and file them away in the right place.
10149 		 */
10150 		fam = IPSEC_AF_V6;
10151 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10152 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10153 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10154 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10155 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10156 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10157 	}
10158 
10159 	ipsec_actvec_free(actp, nact);
10160 
10161 	/*
10162 	 * File the v4 policies.
10163 	 */
10164 	fam = IPSEC_AF_V4;
10165 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10166 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10167 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10168 
10169 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10170 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10171 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10172 
10173 	/*
10174 	 * If the requests need security, set enforce_policy.
10175 	 * If the requests are IPSEC_PREF_NEVER, one should
10176 	 * still set conn_out_enforce_policy so that an ipsec_out
10177 	 * gets attached in ip_wput. This is needed so that
10178 	 * for connections that we don't cache policy in ip_bind,
10179 	 * if global policy matches in ip_wput_attach_policy, we
10180 	 * don't wrongly inherit global policy. Similarly, we need
10181 	 * to set conn_in_enforce_policy also so that we don't verify
10182 	 * policy wrongly.
10183 	 */
10184 	if ((ah_req & REQ_MASK) != 0 ||
10185 	    (esp_req & REQ_MASK) != 0 ||
10186 	    (se_req & REQ_MASK) != 0) {
10187 		connp->conn_in_enforce_policy = B_TRUE;
10188 		connp->conn_out_enforce_policy = B_TRUE;
10189 		connp->conn_flags |= IPCL_CHECK_POLICY;
10190 	}
10191 
10192 	mutex_exit(&connp->conn_lock);
10193 	return (error);
10194 #undef REQ_MASK
10195 
10196 	/*
10197 	 * Common memory-allocation-failure exit path.
10198 	 */
10199 enomem:
10200 	mutex_exit(&connp->conn_lock);
10201 	if (actp != NULL)
10202 		ipsec_actvec_free(actp, nact);
10203 	if (pin4 != NULL)
10204 		IPPOL_REFRELE(pin4);
10205 	if (pout4 != NULL)
10206 		IPPOL_REFRELE(pout4);
10207 	if (pin6 != NULL)
10208 		IPPOL_REFRELE(pin6);
10209 	if (pout6 != NULL)
10210 		IPPOL_REFRELE(pout6);
10211 	return (ENOMEM);
10212 }
10213 
10214 /*
10215  * Only for options that pass in an IP addr. Currently only V4 options
10216  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10217  * So this function assumes level is IPPROTO_IP
10218  */
10219 int
10220 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10221     mblk_t *first_mp)
10222 {
10223 	ipif_t *ipif = NULL;
10224 	int error;
10225 	ill_t *ill;
10226 	int zoneid;
10227 
10228 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10229 
10230 	if (addr != INADDR_ANY || checkonly) {
10231 		ASSERT(connp != NULL);
10232 		zoneid = IPCL_ZONEID(connp);
10233 		if (option == IP_NEXTHOP) {
10234 			ipif = ipif_lookup_onlink_addr(addr,
10235 			    connp->conn_zoneid);
10236 		} else {
10237 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10238 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10239 			    &error);
10240 		}
10241 		if (ipif == NULL) {
10242 			if (error == EINPROGRESS)
10243 				return (error);
10244 			else if ((option == IP_MULTICAST_IF) ||
10245 			    (option == IP_NEXTHOP))
10246 				return (EHOSTUNREACH);
10247 			else
10248 				return (EINVAL);
10249 		} else if (checkonly) {
10250 			if (option == IP_MULTICAST_IF) {
10251 				ill = ipif->ipif_ill;
10252 				/* not supported by the virtual network iface */
10253 				if (IS_VNI(ill)) {
10254 					ipif_refrele(ipif);
10255 					return (EINVAL);
10256 				}
10257 			}
10258 			ipif_refrele(ipif);
10259 			return (0);
10260 		}
10261 		ill = ipif->ipif_ill;
10262 		mutex_enter(&connp->conn_lock);
10263 		mutex_enter(&ill->ill_lock);
10264 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10265 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10266 			mutex_exit(&ill->ill_lock);
10267 			mutex_exit(&connp->conn_lock);
10268 			ipif_refrele(ipif);
10269 			return (option == IP_MULTICAST_IF ?
10270 			    EHOSTUNREACH : EINVAL);
10271 		}
10272 	} else {
10273 		mutex_enter(&connp->conn_lock);
10274 	}
10275 
10276 	/* None of the options below are supported on the VNI */
10277 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10278 		mutex_exit(&ill->ill_lock);
10279 		mutex_exit(&connp->conn_lock);
10280 		ipif_refrele(ipif);
10281 		return (EINVAL);
10282 	}
10283 
10284 	switch (option) {
10285 	case IP_DONTFAILOVER_IF:
10286 		/*
10287 		 * This option is used by in.mpathd to ensure
10288 		 * that IPMP probe packets only go out on the
10289 		 * test interfaces. in.mpathd sets this option
10290 		 * on the non-failover interfaces.
10291 		 * For backward compatibility, this option
10292 		 * implicitly sets IP_MULTICAST_IF, as used
10293 		 * be done in bind(), so that ip_wput gets
10294 		 * this ipif to send mcast packets.
10295 		 */
10296 		if (ipif != NULL) {
10297 			ASSERT(addr != INADDR_ANY);
10298 			connp->conn_nofailover_ill = ipif->ipif_ill;
10299 			connp->conn_multicast_ipif = ipif;
10300 		} else {
10301 			ASSERT(addr == INADDR_ANY);
10302 			connp->conn_nofailover_ill = NULL;
10303 			connp->conn_multicast_ipif = NULL;
10304 		}
10305 		break;
10306 
10307 	case IP_MULTICAST_IF:
10308 		connp->conn_multicast_ipif = ipif;
10309 		break;
10310 	case IP_NEXTHOP:
10311 		connp->conn_nexthop_v4 = addr;
10312 		connp->conn_nexthop_set = B_TRUE;
10313 		break;
10314 	}
10315 
10316 	if (ipif != NULL) {
10317 		mutex_exit(&ill->ill_lock);
10318 		mutex_exit(&connp->conn_lock);
10319 		ipif_refrele(ipif);
10320 		return (0);
10321 	}
10322 	mutex_exit(&connp->conn_lock);
10323 	/* We succeded in cleared the option */
10324 	return (0);
10325 }
10326 
10327 /*
10328  * For options that pass in an ifindex specifying the ill. V6 options always
10329  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10330  */
10331 int
10332 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10333     int level, int option, mblk_t *first_mp)
10334 {
10335 	ill_t *ill = NULL;
10336 	int error = 0;
10337 
10338 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10339 	if (ifindex != 0) {
10340 		ASSERT(connp != NULL);
10341 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10342 		    first_mp, ip_restart_optmgmt, &error);
10343 		if (ill != NULL) {
10344 			if (checkonly) {
10345 				/* not supported by the virtual network iface */
10346 				if (IS_VNI(ill)) {
10347 					ill_refrele(ill);
10348 					return (EINVAL);
10349 				}
10350 				ill_refrele(ill);
10351 				return (0);
10352 			}
10353 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10354 			    0, NULL)) {
10355 				ill_refrele(ill);
10356 				ill = NULL;
10357 				mutex_enter(&connp->conn_lock);
10358 				goto setit;
10359 			}
10360 			mutex_enter(&connp->conn_lock);
10361 			mutex_enter(&ill->ill_lock);
10362 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10363 				mutex_exit(&ill->ill_lock);
10364 				mutex_exit(&connp->conn_lock);
10365 				ill_refrele(ill);
10366 				ill = NULL;
10367 				mutex_enter(&connp->conn_lock);
10368 			}
10369 			goto setit;
10370 		} else if (error == EINPROGRESS) {
10371 			return (error);
10372 		} else {
10373 			error = 0;
10374 		}
10375 	}
10376 	mutex_enter(&connp->conn_lock);
10377 setit:
10378 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10379 
10380 	/*
10381 	 * The options below assume that the ILL (if any) transmits and/or
10382 	 * receives traffic. Neither of which is true for the virtual network
10383 	 * interface, so fail setting these on a VNI.
10384 	 */
10385 	if (IS_VNI(ill)) {
10386 		ASSERT(ill != NULL);
10387 		mutex_exit(&ill->ill_lock);
10388 		mutex_exit(&connp->conn_lock);
10389 		ill_refrele(ill);
10390 		return (EINVAL);
10391 	}
10392 
10393 	if (level == IPPROTO_IP) {
10394 		switch (option) {
10395 		case IP_BOUND_IF:
10396 			connp->conn_incoming_ill = ill;
10397 			connp->conn_outgoing_ill = ill;
10398 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10399 			    0 : ifindex;
10400 			break;
10401 
10402 		case IP_XMIT_IF:
10403 			/*
10404 			 * Similar to IP_BOUND_IF, but this only
10405 			 * determines the outgoing interface for
10406 			 * unicast packets. Also no IRE_CACHE entry
10407 			 * is added for the destination of the
10408 			 * outgoing packets. This feature is needed
10409 			 * for mobile IP.
10410 			 */
10411 			connp->conn_xmit_if_ill = ill;
10412 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10413 			    0 : ifindex;
10414 			break;
10415 
10416 		case IP_MULTICAST_IF:
10417 			/*
10418 			 * This option is an internal special. The socket
10419 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10420 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10421 			 * specifies an ifindex and we try first on V6 ill's.
10422 			 * If we don't find one, we they try using on v4 ill's
10423 			 * intenally and we come here.
10424 			 */
10425 			if (!checkonly && ill != NULL) {
10426 				ipif_t	*ipif;
10427 				ipif = ill->ill_ipif;
10428 
10429 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10430 					mutex_exit(&ill->ill_lock);
10431 					mutex_exit(&connp->conn_lock);
10432 					ill_refrele(ill);
10433 					ill = NULL;
10434 					mutex_enter(&connp->conn_lock);
10435 				} else {
10436 					connp->conn_multicast_ipif = ipif;
10437 				}
10438 			}
10439 			break;
10440 		}
10441 	} else {
10442 		switch (option) {
10443 		case IPV6_BOUND_IF:
10444 			connp->conn_incoming_ill = ill;
10445 			connp->conn_outgoing_ill = ill;
10446 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10447 			    0 : ifindex;
10448 			break;
10449 
10450 		case IPV6_BOUND_PIF:
10451 			/*
10452 			 * Limit all transmit to this ill.
10453 			 * Unlike IPV6_BOUND_IF, using this option
10454 			 * prevents load spreading and failover from
10455 			 * happening when the interface is part of the
10456 			 * group. That's why we don't need to remember
10457 			 * the ifindex in orig_bound_ifindex as in
10458 			 * IPV6_BOUND_IF.
10459 			 */
10460 			connp->conn_outgoing_pill = ill;
10461 			break;
10462 
10463 		case IPV6_DONTFAILOVER_IF:
10464 			/*
10465 			 * This option is used by in.mpathd to ensure
10466 			 * that IPMP probe packets only go out on the
10467 			 * test interfaces. in.mpathd sets this option
10468 			 * on the non-failover interfaces.
10469 			 */
10470 			connp->conn_nofailover_ill = ill;
10471 			/*
10472 			 * For backward compatibility, this option
10473 			 * implicitly sets ip_multicast_ill as used in
10474 			 * IP_MULTICAST_IF so that ip_wput gets
10475 			 * this ipif to send mcast packets.
10476 			 */
10477 			connp->conn_multicast_ill = ill;
10478 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10479 			    0 : ifindex;
10480 			break;
10481 
10482 		case IPV6_MULTICAST_IF:
10483 			/*
10484 			 * Set conn_multicast_ill to be the IPv6 ill.
10485 			 * Set conn_multicast_ipif to be an IPv4 ipif
10486 			 * for ifindex to make IPv4 mapped addresses
10487 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10488 			 * Even if no IPv6 ill exists for the ifindex
10489 			 * we need to check for an IPv4 ifindex in order
10490 			 * for this to work with mapped addresses. In that
10491 			 * case only set conn_multicast_ipif.
10492 			 */
10493 			if (!checkonly) {
10494 				if (ifindex == 0) {
10495 					connp->conn_multicast_ill = NULL;
10496 					connp->conn_orig_multicast_ifindex = 0;
10497 					connp->conn_multicast_ipif = NULL;
10498 				} else if (ill != NULL) {
10499 					connp->conn_multicast_ill = ill;
10500 					connp->conn_orig_multicast_ifindex =
10501 					    ifindex;
10502 				}
10503 			}
10504 			break;
10505 		}
10506 	}
10507 
10508 	if (ill != NULL) {
10509 		mutex_exit(&ill->ill_lock);
10510 		mutex_exit(&connp->conn_lock);
10511 		ill_refrele(ill);
10512 		return (0);
10513 	}
10514 	mutex_exit(&connp->conn_lock);
10515 	/*
10516 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10517 	 * locate the ill and could not set the option (ifindex != 0)
10518 	 */
10519 	return (ifindex == 0 ? 0 : EINVAL);
10520 }
10521 
10522 /* This routine sets socket options. */
10523 /* ARGSUSED */
10524 int
10525 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10526     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10527     void *dummy, cred_t *cr, mblk_t *first_mp)
10528 {
10529 	int		*i1 = (int *)invalp;
10530 	conn_t		*connp = Q_TO_CONN(q);
10531 	int		error = 0;
10532 	boolean_t	checkonly;
10533 	ire_t		*ire;
10534 	boolean_t	found;
10535 
10536 	switch (optset_context) {
10537 
10538 	case SETFN_OPTCOM_CHECKONLY:
10539 		checkonly = B_TRUE;
10540 		/*
10541 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10542 		 * inlen != 0 implies value supplied and
10543 		 * 	we have to "pretend" to set it.
10544 		 * inlen == 0 implies that there is no
10545 		 * 	value part in T_CHECK request and just validation
10546 		 * done elsewhere should be enough, we just return here.
10547 		 */
10548 		if (inlen == 0) {
10549 			*outlenp = 0;
10550 			return (0);
10551 		}
10552 		break;
10553 	case SETFN_OPTCOM_NEGOTIATE:
10554 	case SETFN_UD_NEGOTIATE:
10555 	case SETFN_CONN_NEGOTIATE:
10556 		checkonly = B_FALSE;
10557 		break;
10558 	default:
10559 		/*
10560 		 * We should never get here
10561 		 */
10562 		*outlenp = 0;
10563 		return (EINVAL);
10564 	}
10565 
10566 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10567 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10568 
10569 	/*
10570 	 * For fixed length options, no sanity check
10571 	 * of passed in length is done. It is assumed *_optcom_req()
10572 	 * routines do the right thing.
10573 	 */
10574 
10575 	switch (level) {
10576 	case SOL_SOCKET:
10577 		/*
10578 		 * conn_lock protects the bitfields, and is used to
10579 		 * set the fields atomically.
10580 		 */
10581 		switch (name) {
10582 		case SO_BROADCAST:
10583 			if (!checkonly) {
10584 				/* TODO: use value someplace? */
10585 				mutex_enter(&connp->conn_lock);
10586 				connp->conn_broadcast = *i1 ? 1 : 0;
10587 				mutex_exit(&connp->conn_lock);
10588 			}
10589 			break;	/* goto sizeof (int) option return */
10590 		case SO_USELOOPBACK:
10591 			if (!checkonly) {
10592 				/* TODO: use value someplace? */
10593 				mutex_enter(&connp->conn_lock);
10594 				connp->conn_loopback = *i1 ? 1 : 0;
10595 				mutex_exit(&connp->conn_lock);
10596 			}
10597 			break;	/* goto sizeof (int) option return */
10598 		case SO_DONTROUTE:
10599 			if (!checkonly) {
10600 				mutex_enter(&connp->conn_lock);
10601 				connp->conn_dontroute = *i1 ? 1 : 0;
10602 				mutex_exit(&connp->conn_lock);
10603 			}
10604 			break;	/* goto sizeof (int) option return */
10605 		case SO_REUSEADDR:
10606 			if (!checkonly) {
10607 				mutex_enter(&connp->conn_lock);
10608 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10609 				mutex_exit(&connp->conn_lock);
10610 			}
10611 			break;	/* goto sizeof (int) option return */
10612 		case SO_PROTOTYPE:
10613 			if (!checkonly) {
10614 				mutex_enter(&connp->conn_lock);
10615 				connp->conn_proto = *i1;
10616 				mutex_exit(&connp->conn_lock);
10617 			}
10618 			break;	/* goto sizeof (int) option return */
10619 		case SO_ALLZONES:
10620 			if (!checkonly) {
10621 				mutex_enter(&connp->conn_lock);
10622 				if (IPCL_IS_BOUND(connp)) {
10623 					mutex_exit(&connp->conn_lock);
10624 					return (EINVAL);
10625 				}
10626 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10627 				mutex_exit(&connp->conn_lock);
10628 			}
10629 			break;	/* goto sizeof (int) option return */
10630 		case SO_ANON_MLP:
10631 			if (!checkonly) {
10632 				mutex_enter(&connp->conn_lock);
10633 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10634 				mutex_exit(&connp->conn_lock);
10635 			}
10636 			break;	/* goto sizeof (int) option return */
10637 		case SO_MAC_EXEMPT:
10638 			if (secpolicy_net_mac_aware(cr) != 0 ||
10639 			    IPCL_IS_BOUND(connp))
10640 				return (EACCES);
10641 			if (!checkonly) {
10642 				mutex_enter(&connp->conn_lock);
10643 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10644 				mutex_exit(&connp->conn_lock);
10645 			}
10646 			break;	/* goto sizeof (int) option return */
10647 		default:
10648 			/*
10649 			 * "soft" error (negative)
10650 			 * option not handled at this level
10651 			 * Note: Do not modify *outlenp
10652 			 */
10653 			return (-EINVAL);
10654 		}
10655 		break;
10656 	case IPPROTO_IP:
10657 		switch (name) {
10658 		case IP_NEXTHOP:
10659 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10660 				return (EPERM);
10661 			/* FALLTHRU */
10662 		case IP_MULTICAST_IF:
10663 		case IP_DONTFAILOVER_IF: {
10664 			ipaddr_t addr = *i1;
10665 
10666 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10667 			    first_mp);
10668 			if (error != 0)
10669 				return (error);
10670 			break;	/* goto sizeof (int) option return */
10671 		}
10672 
10673 		case IP_MULTICAST_TTL:
10674 			/* Recorded in transport above IP */
10675 			*outvalp = *invalp;
10676 			*outlenp = sizeof (uchar_t);
10677 			return (0);
10678 		case IP_MULTICAST_LOOP:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			*outvalp = *invalp;
10685 			*outlenp = sizeof (uchar_t);
10686 			return (0);
10687 		case IP_ADD_MEMBERSHIP:
10688 		case MCAST_JOIN_GROUP:
10689 		case IP_DROP_MEMBERSHIP:
10690 		case MCAST_LEAVE_GROUP: {
10691 			struct ip_mreq *mreqp;
10692 			struct group_req *greqp;
10693 			ire_t *ire;
10694 			boolean_t done = B_FALSE;
10695 			ipaddr_t group, ifaddr;
10696 			struct sockaddr_in *sin;
10697 			uint32_t *ifindexp;
10698 			boolean_t mcast_opt = B_TRUE;
10699 			mcast_record_t fmode;
10700 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10701 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10702 
10703 			switch (name) {
10704 			case IP_ADD_MEMBERSHIP:
10705 				mcast_opt = B_FALSE;
10706 				/* FALLTHRU */
10707 			case MCAST_JOIN_GROUP:
10708 				fmode = MODE_IS_EXCLUDE;
10709 				optfn = ip_opt_add_group;
10710 				break;
10711 
10712 			case IP_DROP_MEMBERSHIP:
10713 				mcast_opt = B_FALSE;
10714 				/* FALLTHRU */
10715 			case MCAST_LEAVE_GROUP:
10716 				fmode = MODE_IS_INCLUDE;
10717 				optfn = ip_opt_delete_group;
10718 				break;
10719 			}
10720 
10721 			if (mcast_opt) {
10722 				greqp = (struct group_req *)i1;
10723 				sin = (struct sockaddr_in *)&greqp->gr_group;
10724 				if (sin->sin_family != AF_INET) {
10725 					*outlenp = 0;
10726 					return (ENOPROTOOPT);
10727 				}
10728 				group = (ipaddr_t)sin->sin_addr.s_addr;
10729 				ifaddr = INADDR_ANY;
10730 				ifindexp = &greqp->gr_interface;
10731 			} else {
10732 				mreqp = (struct ip_mreq *)i1;
10733 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10734 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10735 				ifindexp = NULL;
10736 			}
10737 
10738 			/*
10739 			 * In the multirouting case, we need to replicate
10740 			 * the request on all interfaces that will take part
10741 			 * in replication.  We do so because multirouting is
10742 			 * reflective, thus we will probably receive multi-
10743 			 * casts on those interfaces.
10744 			 * The ip_multirt_apply_membership() succeeds if the
10745 			 * operation succeeds on at least one interface.
10746 			 */
10747 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10748 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10749 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10750 			if (ire != NULL) {
10751 				if (ire->ire_flags & RTF_MULTIRT) {
10752 					error = ip_multirt_apply_membership(
10753 					    optfn, ire, connp, checkonly, group,
10754 					    fmode, INADDR_ANY, first_mp);
10755 					done = B_TRUE;
10756 				}
10757 				ire_refrele(ire);
10758 			}
10759 			if (!done) {
10760 				error = optfn(connp, checkonly, group, ifaddr,
10761 				    ifindexp, fmode, INADDR_ANY, first_mp);
10762 			}
10763 			if (error) {
10764 				/*
10765 				 * EINPROGRESS is a soft error, needs retry
10766 				 * so don't make *outlenp zero.
10767 				 */
10768 				if (error != EINPROGRESS)
10769 					*outlenp = 0;
10770 				return (error);
10771 			}
10772 			/* OK return - copy input buffer into output buffer */
10773 			if (invalp != outvalp) {
10774 				/* don't trust bcopy for identical src/dst */
10775 				bcopy(invalp, outvalp, inlen);
10776 			}
10777 			*outlenp = inlen;
10778 			return (0);
10779 		}
10780 		case IP_BLOCK_SOURCE:
10781 		case IP_UNBLOCK_SOURCE:
10782 		case IP_ADD_SOURCE_MEMBERSHIP:
10783 		case IP_DROP_SOURCE_MEMBERSHIP:
10784 		case MCAST_BLOCK_SOURCE:
10785 		case MCAST_UNBLOCK_SOURCE:
10786 		case MCAST_JOIN_SOURCE_GROUP:
10787 		case MCAST_LEAVE_SOURCE_GROUP: {
10788 			struct ip_mreq_source *imreqp;
10789 			struct group_source_req *gsreqp;
10790 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10791 			uint32_t ifindex = 0;
10792 			mcast_record_t fmode;
10793 			struct sockaddr_in *sin;
10794 			ire_t *ire;
10795 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10796 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10797 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10798 
10799 			switch (name) {
10800 			case IP_BLOCK_SOURCE:
10801 				mcast_opt = B_FALSE;
10802 				/* FALLTHRU */
10803 			case MCAST_BLOCK_SOURCE:
10804 				fmode = MODE_IS_EXCLUDE;
10805 				optfn = ip_opt_add_group;
10806 				break;
10807 
10808 			case IP_UNBLOCK_SOURCE:
10809 				mcast_opt = B_FALSE;
10810 				/* FALLTHRU */
10811 			case MCAST_UNBLOCK_SOURCE:
10812 				fmode = MODE_IS_EXCLUDE;
10813 				optfn = ip_opt_delete_group;
10814 				break;
10815 
10816 			case IP_ADD_SOURCE_MEMBERSHIP:
10817 				mcast_opt = B_FALSE;
10818 				/* FALLTHRU */
10819 			case MCAST_JOIN_SOURCE_GROUP:
10820 				fmode = MODE_IS_INCLUDE;
10821 				optfn = ip_opt_add_group;
10822 				break;
10823 
10824 			case IP_DROP_SOURCE_MEMBERSHIP:
10825 				mcast_opt = B_FALSE;
10826 				/* FALLTHRU */
10827 			case MCAST_LEAVE_SOURCE_GROUP:
10828 				fmode = MODE_IS_INCLUDE;
10829 				optfn = ip_opt_delete_group;
10830 				break;
10831 			}
10832 
10833 			if (mcast_opt) {
10834 				gsreqp = (struct group_source_req *)i1;
10835 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10836 					*outlenp = 0;
10837 					return (ENOPROTOOPT);
10838 				}
10839 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10840 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10841 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10842 				src = (ipaddr_t)sin->sin_addr.s_addr;
10843 				ifindex = gsreqp->gsr_interface;
10844 			} else {
10845 				imreqp = (struct ip_mreq_source *)i1;
10846 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10847 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10848 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10849 			}
10850 
10851 			/*
10852 			 * In the multirouting case, we need to replicate
10853 			 * the request as noted in the mcast cases above.
10854 			 */
10855 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10856 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10857 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10858 			if (ire != NULL) {
10859 				if (ire->ire_flags & RTF_MULTIRT) {
10860 					error = ip_multirt_apply_membership(
10861 					    optfn, ire, connp, checkonly, grp,
10862 					    fmode, src, first_mp);
10863 					done = B_TRUE;
10864 				}
10865 				ire_refrele(ire);
10866 			}
10867 			if (!done) {
10868 				error = optfn(connp, checkonly, grp, ifaddr,
10869 				    &ifindex, fmode, src, first_mp);
10870 			}
10871 			if (error != 0) {
10872 				/*
10873 				 * EINPROGRESS is a soft error, needs retry
10874 				 * so don't make *outlenp zero.
10875 				 */
10876 				if (error != EINPROGRESS)
10877 					*outlenp = 0;
10878 				return (error);
10879 			}
10880 			/* OK return - copy input buffer into output buffer */
10881 			if (invalp != outvalp) {
10882 				bcopy(invalp, outvalp, inlen);
10883 			}
10884 			*outlenp = inlen;
10885 			return (0);
10886 		}
10887 		case IP_SEC_OPT:
10888 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10889 			if (error != 0) {
10890 				*outlenp = 0;
10891 				return (error);
10892 			}
10893 			break;
10894 		case IP_HDRINCL:
10895 		case IP_OPTIONS:
10896 		case T_IP_OPTIONS:
10897 		case IP_TOS:
10898 		case T_IP_TOS:
10899 		case IP_TTL:
10900 		case IP_RECVDSTADDR:
10901 		case IP_RECVOPTS:
10902 			/* OK return - copy input buffer into output buffer */
10903 			if (invalp != outvalp) {
10904 				/* don't trust bcopy for identical src/dst */
10905 				bcopy(invalp, outvalp, inlen);
10906 			}
10907 			*outlenp = inlen;
10908 			return (0);
10909 		case IP_RECVIF:
10910 			/* Retrieve the inbound interface index */
10911 			if (!checkonly) {
10912 				mutex_enter(&connp->conn_lock);
10913 				connp->conn_recvif = *i1 ? 1 : 0;
10914 				mutex_exit(&connp->conn_lock);
10915 			}
10916 			break;	/* goto sizeof (int) option return */
10917 		case IP_RECVSLLA:
10918 			/* Retrieve the source link layer address */
10919 			if (!checkonly) {
10920 				mutex_enter(&connp->conn_lock);
10921 				connp->conn_recvslla = *i1 ? 1 : 0;
10922 				mutex_exit(&connp->conn_lock);
10923 			}
10924 			break;	/* goto sizeof (int) option return */
10925 		case MRT_INIT:
10926 		case MRT_DONE:
10927 		case MRT_ADD_VIF:
10928 		case MRT_DEL_VIF:
10929 		case MRT_ADD_MFC:
10930 		case MRT_DEL_MFC:
10931 		case MRT_ASSERT:
10932 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10933 				*outlenp = 0;
10934 				return (error);
10935 			}
10936 			error = ip_mrouter_set((int)name, q, checkonly,
10937 			    (uchar_t *)invalp, inlen, first_mp);
10938 			if (error) {
10939 				*outlenp = 0;
10940 				return (error);
10941 			}
10942 			/* OK return - copy input buffer into output buffer */
10943 			if (invalp != outvalp) {
10944 				/* don't trust bcopy for identical src/dst */
10945 				bcopy(invalp, outvalp, inlen);
10946 			}
10947 			*outlenp = inlen;
10948 			return (0);
10949 		case IP_BOUND_IF:
10950 		case IP_XMIT_IF:
10951 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10952 			    level, name, first_mp);
10953 			if (error != 0)
10954 				return (error);
10955 			break; 		/* goto sizeof (int) option return */
10956 
10957 		case IP_UNSPEC_SRC:
10958 			/* Allow sending with a zero source address */
10959 			if (!checkonly) {
10960 				mutex_enter(&connp->conn_lock);
10961 				connp->conn_unspec_src = *i1 ? 1 : 0;
10962 				mutex_exit(&connp->conn_lock);
10963 			}
10964 			break;	/* goto sizeof (int) option return */
10965 		default:
10966 			/*
10967 			 * "soft" error (negative)
10968 			 * option not handled at this level
10969 			 * Note: Do not modify *outlenp
10970 			 */
10971 			return (-EINVAL);
10972 		}
10973 		break;
10974 	case IPPROTO_IPV6:
10975 		switch (name) {
10976 		case IPV6_BOUND_IF:
10977 		case IPV6_BOUND_PIF:
10978 		case IPV6_DONTFAILOVER_IF:
10979 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10980 			    level, name, first_mp);
10981 			if (error != 0)
10982 				return (error);
10983 			break; 		/* goto sizeof (int) option return */
10984 
10985 		case IPV6_MULTICAST_IF:
10986 			/*
10987 			 * The only possible errors are EINPROGRESS and
10988 			 * EINVAL. EINPROGRESS will be restarted and is not
10989 			 * a hard error. We call this option on both V4 and V6
10990 			 * If both return EINVAL, then this call returns
10991 			 * EINVAL. If at least one of them succeeds we
10992 			 * return success.
10993 			 */
10994 			found = B_FALSE;
10995 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10996 			    level, name, first_mp);
10997 			if (error == EINPROGRESS)
10998 				return (error);
10999 			if (error == 0)
11000 				found = B_TRUE;
11001 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11002 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11003 			if (error == 0)
11004 				found = B_TRUE;
11005 			if (!found)
11006 				return (error);
11007 			break; 		/* goto sizeof (int) option return */
11008 
11009 		case IPV6_MULTICAST_HOPS:
11010 			/* Recorded in transport above IP */
11011 			break;	/* goto sizeof (int) option return */
11012 		case IPV6_MULTICAST_LOOP:
11013 			if (!checkonly) {
11014 				mutex_enter(&connp->conn_lock);
11015 				connp->conn_multicast_loop = *i1;
11016 				mutex_exit(&connp->conn_lock);
11017 			}
11018 			break;	/* goto sizeof (int) option return */
11019 		case IPV6_JOIN_GROUP:
11020 		case MCAST_JOIN_GROUP:
11021 		case IPV6_LEAVE_GROUP:
11022 		case MCAST_LEAVE_GROUP: {
11023 			struct ipv6_mreq *ip_mreqp;
11024 			struct group_req *greqp;
11025 			ire_t *ire;
11026 			boolean_t done = B_FALSE;
11027 			in6_addr_t groupv6;
11028 			uint32_t ifindex;
11029 			boolean_t mcast_opt = B_TRUE;
11030 			mcast_record_t fmode;
11031 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11032 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11033 
11034 			switch (name) {
11035 			case IPV6_JOIN_GROUP:
11036 				mcast_opt = B_FALSE;
11037 				/* FALLTHRU */
11038 			case MCAST_JOIN_GROUP:
11039 				fmode = MODE_IS_EXCLUDE;
11040 				optfn = ip_opt_add_group_v6;
11041 				break;
11042 
11043 			case IPV6_LEAVE_GROUP:
11044 				mcast_opt = B_FALSE;
11045 				/* FALLTHRU */
11046 			case MCAST_LEAVE_GROUP:
11047 				fmode = MODE_IS_INCLUDE;
11048 				optfn = ip_opt_delete_group_v6;
11049 				break;
11050 			}
11051 
11052 			if (mcast_opt) {
11053 				struct sockaddr_in *sin;
11054 				struct sockaddr_in6 *sin6;
11055 				greqp = (struct group_req *)i1;
11056 				if (greqp->gr_group.ss_family == AF_INET) {
11057 					sin = (struct sockaddr_in *)
11058 					    &(greqp->gr_group);
11059 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11060 					    &groupv6);
11061 				} else {
11062 					sin6 = (struct sockaddr_in6 *)
11063 					    &(greqp->gr_group);
11064 					groupv6 = sin6->sin6_addr;
11065 				}
11066 				ifindex = greqp->gr_interface;
11067 			} else {
11068 				ip_mreqp = (struct ipv6_mreq *)i1;
11069 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11070 				ifindex = ip_mreqp->ipv6mr_interface;
11071 			}
11072 			/*
11073 			 * In the multirouting case, we need to replicate
11074 			 * the request on all interfaces that will take part
11075 			 * in replication.  We do so because multirouting is
11076 			 * reflective, thus we will probably receive multi-
11077 			 * casts on those interfaces.
11078 			 * The ip_multirt_apply_membership_v6() succeeds if
11079 			 * the operation succeeds on at least one interface.
11080 			 */
11081 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11082 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11083 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11084 			if (ire != NULL) {
11085 				if (ire->ire_flags & RTF_MULTIRT) {
11086 					error = ip_multirt_apply_membership_v6(
11087 					    optfn, ire, connp, checkonly,
11088 					    &groupv6, fmode, &ipv6_all_zeros,
11089 					    first_mp);
11090 					done = B_TRUE;
11091 				}
11092 				ire_refrele(ire);
11093 			}
11094 			if (!done) {
11095 				error = optfn(connp, checkonly, &groupv6,
11096 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11097 			}
11098 			if (error) {
11099 				/*
11100 				 * EINPROGRESS is a soft error, needs retry
11101 				 * so don't make *outlenp zero.
11102 				 */
11103 				if (error != EINPROGRESS)
11104 					*outlenp = 0;
11105 				return (error);
11106 			}
11107 			/* OK return - copy input buffer into output buffer */
11108 			if (invalp != outvalp) {
11109 				/* don't trust bcopy for identical src/dst */
11110 				bcopy(invalp, outvalp, inlen);
11111 			}
11112 			*outlenp = inlen;
11113 			return (0);
11114 		}
11115 		case MCAST_BLOCK_SOURCE:
11116 		case MCAST_UNBLOCK_SOURCE:
11117 		case MCAST_JOIN_SOURCE_GROUP:
11118 		case MCAST_LEAVE_SOURCE_GROUP: {
11119 			struct group_source_req *gsreqp;
11120 			in6_addr_t v6grp, v6src;
11121 			uint32_t ifindex;
11122 			mcast_record_t fmode;
11123 			ire_t *ire;
11124 			boolean_t done = B_FALSE;
11125 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11126 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11127 
11128 			switch (name) {
11129 			case MCAST_BLOCK_SOURCE:
11130 				fmode = MODE_IS_EXCLUDE;
11131 				optfn = ip_opt_add_group_v6;
11132 				break;
11133 			case MCAST_UNBLOCK_SOURCE:
11134 				fmode = MODE_IS_EXCLUDE;
11135 				optfn = ip_opt_delete_group_v6;
11136 				break;
11137 			case MCAST_JOIN_SOURCE_GROUP:
11138 				fmode = MODE_IS_INCLUDE;
11139 				optfn = ip_opt_add_group_v6;
11140 				break;
11141 			case MCAST_LEAVE_SOURCE_GROUP:
11142 				fmode = MODE_IS_INCLUDE;
11143 				optfn = ip_opt_delete_group_v6;
11144 				break;
11145 			}
11146 
11147 			gsreqp = (struct group_source_req *)i1;
11148 			ifindex = gsreqp->gsr_interface;
11149 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11150 				struct sockaddr_in *s;
11151 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11152 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11153 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11154 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11155 			} else {
11156 				struct sockaddr_in6 *s6;
11157 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11158 				v6grp = s6->sin6_addr;
11159 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11160 				v6src = s6->sin6_addr;
11161 			}
11162 
11163 			/*
11164 			 * In the multirouting case, we need to replicate
11165 			 * the request as noted in the mcast cases above.
11166 			 */
11167 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11168 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11169 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11170 			if (ire != NULL) {
11171 				if (ire->ire_flags & RTF_MULTIRT) {
11172 					error = ip_multirt_apply_membership_v6(
11173 					    optfn, ire, connp, checkonly,
11174 					    &v6grp, fmode, &v6src, first_mp);
11175 					done = B_TRUE;
11176 				}
11177 				ire_refrele(ire);
11178 			}
11179 			if (!done) {
11180 				error = optfn(connp, checkonly, &v6grp,
11181 				    ifindex, fmode, &v6src, first_mp);
11182 			}
11183 			if (error != 0) {
11184 				/*
11185 				 * EINPROGRESS is a soft error, needs retry
11186 				 * so don't make *outlenp zero.
11187 				 */
11188 				if (error != EINPROGRESS)
11189 					*outlenp = 0;
11190 				return (error);
11191 			}
11192 			/* OK return - copy input buffer into output buffer */
11193 			if (invalp != outvalp) {
11194 				bcopy(invalp, outvalp, inlen);
11195 			}
11196 			*outlenp = inlen;
11197 			return (0);
11198 		}
11199 		case IPV6_UNICAST_HOPS:
11200 			/* Recorded in transport above IP */
11201 			break;	/* goto sizeof (int) option return */
11202 		case IPV6_UNSPEC_SRC:
11203 			/* Allow sending with a zero source address */
11204 			if (!checkonly) {
11205 				mutex_enter(&connp->conn_lock);
11206 				connp->conn_unspec_src = *i1 ? 1 : 0;
11207 				mutex_exit(&connp->conn_lock);
11208 			}
11209 			break;	/* goto sizeof (int) option return */
11210 		case IPV6_RECVPKTINFO:
11211 			if (!checkonly) {
11212 				mutex_enter(&connp->conn_lock);
11213 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11214 				mutex_exit(&connp->conn_lock);
11215 			}
11216 			break;	/* goto sizeof (int) option return */
11217 		case IPV6_RECVTCLASS:
11218 			if (!checkonly) {
11219 				if (*i1 < 0 || *i1 > 1) {
11220 					return (EINVAL);
11221 				}
11222 				mutex_enter(&connp->conn_lock);
11223 				connp->conn_ipv6_recvtclass = *i1;
11224 				mutex_exit(&connp->conn_lock);
11225 			}
11226 			break;
11227 		case IPV6_RECVPATHMTU:
11228 			if (!checkonly) {
11229 				if (*i1 < 0 || *i1 > 1) {
11230 					return (EINVAL);
11231 				}
11232 				mutex_enter(&connp->conn_lock);
11233 				connp->conn_ipv6_recvpathmtu = *i1;
11234 				mutex_exit(&connp->conn_lock);
11235 			}
11236 			break;
11237 		case IPV6_RECVHOPLIMIT:
11238 			if (!checkonly) {
11239 				mutex_enter(&connp->conn_lock);
11240 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11241 				mutex_exit(&connp->conn_lock);
11242 			}
11243 			break;	/* goto sizeof (int) option return */
11244 		case IPV6_RECVHOPOPTS:
11245 			if (!checkonly) {
11246 				mutex_enter(&connp->conn_lock);
11247 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11248 				mutex_exit(&connp->conn_lock);
11249 			}
11250 			break;	/* goto sizeof (int) option return */
11251 		case IPV6_RECVDSTOPTS:
11252 			if (!checkonly) {
11253 				mutex_enter(&connp->conn_lock);
11254 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11255 				mutex_exit(&connp->conn_lock);
11256 			}
11257 			break;	/* goto sizeof (int) option return */
11258 		case IPV6_RECVRTHDR:
11259 			if (!checkonly) {
11260 				mutex_enter(&connp->conn_lock);
11261 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11262 				mutex_exit(&connp->conn_lock);
11263 			}
11264 			break;	/* goto sizeof (int) option return */
11265 		case IPV6_RECVRTHDRDSTOPTS:
11266 			if (!checkonly) {
11267 				mutex_enter(&connp->conn_lock);
11268 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11269 				mutex_exit(&connp->conn_lock);
11270 			}
11271 			break;	/* goto sizeof (int) option return */
11272 		case IPV6_PKTINFO:
11273 			if (inlen == 0)
11274 				return (-EINVAL);	/* clearing option */
11275 			error = ip6_set_pktinfo(cr, connp,
11276 			    (struct in6_pktinfo *)invalp, first_mp);
11277 			if (error != 0)
11278 				*outlenp = 0;
11279 			else
11280 				*outlenp = inlen;
11281 			return (error);
11282 		case IPV6_NEXTHOP: {
11283 			struct sockaddr_in6 *sin6;
11284 
11285 			/* Verify that the nexthop is reachable */
11286 			if (inlen == 0)
11287 				return (-EINVAL);	/* clearing option */
11288 
11289 			sin6 = (struct sockaddr_in6 *)invalp;
11290 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11291 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11292 			    NULL, MATCH_IRE_DEFAULT);
11293 
11294 			if (ire == NULL) {
11295 				*outlenp = 0;
11296 				return (EHOSTUNREACH);
11297 			}
11298 			ire_refrele(ire);
11299 			return (-EINVAL);
11300 		}
11301 		case IPV6_SEC_OPT:
11302 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11303 			if (error != 0) {
11304 				*outlenp = 0;
11305 				return (error);
11306 			}
11307 			break;
11308 		case IPV6_SRC_PREFERENCES: {
11309 			/*
11310 			 * This is implemented strictly in the ip module
11311 			 * (here and in tcp_opt_*() to accomodate tcp
11312 			 * sockets).  Modules above ip pass this option
11313 			 * down here since ip is the only one that needs to
11314 			 * be aware of source address preferences.
11315 			 *
11316 			 * This socket option only affects connected
11317 			 * sockets that haven't already bound to a specific
11318 			 * IPv6 address.  In other words, sockets that
11319 			 * don't call bind() with an address other than the
11320 			 * unspecified address and that call connect().
11321 			 * ip_bind_connected_v6() passes these preferences
11322 			 * to the ipif_select_source_v6() function.
11323 			 */
11324 			if (inlen != sizeof (uint32_t))
11325 				return (EINVAL);
11326 			error = ip6_set_src_preferences(connp,
11327 			    *(uint32_t *)invalp);
11328 			if (error != 0) {
11329 				*outlenp = 0;
11330 				return (error);
11331 			} else {
11332 				*outlenp = sizeof (uint32_t);
11333 			}
11334 			break;
11335 		}
11336 		case IPV6_V6ONLY:
11337 			if (*i1 < 0 || *i1 > 1) {
11338 				return (EINVAL);
11339 			}
11340 			mutex_enter(&connp->conn_lock);
11341 			connp->conn_ipv6_v6only = *i1;
11342 			mutex_exit(&connp->conn_lock);
11343 			break;
11344 		default:
11345 			return (-EINVAL);
11346 		}
11347 		break;
11348 	default:
11349 		/*
11350 		 * "soft" error (negative)
11351 		 * option not handled at this level
11352 		 * Note: Do not modify *outlenp
11353 		 */
11354 		return (-EINVAL);
11355 	}
11356 	/*
11357 	 * Common case of return from an option that is sizeof (int)
11358 	 */
11359 	*(int *)outvalp = *i1;
11360 	*outlenp = sizeof (int);
11361 	return (0);
11362 }
11363 
11364 /*
11365  * This routine gets default values of certain options whose default
11366  * values are maintained by protocol specific code
11367  */
11368 /* ARGSUSED */
11369 int
11370 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11371 {
11372 	int *i1 = (int *)ptr;
11373 
11374 	switch (level) {
11375 	case IPPROTO_IP:
11376 		switch (name) {
11377 		case IP_MULTICAST_TTL:
11378 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11379 			return (sizeof (uchar_t));
11380 		case IP_MULTICAST_LOOP:
11381 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11382 			return (sizeof (uchar_t));
11383 		default:
11384 			return (-1);
11385 		}
11386 	case IPPROTO_IPV6:
11387 		switch (name) {
11388 		case IPV6_UNICAST_HOPS:
11389 			*i1 = ipv6_def_hops;
11390 			return (sizeof (int));
11391 		case IPV6_MULTICAST_HOPS:
11392 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11393 			return (sizeof (int));
11394 		case IPV6_MULTICAST_LOOP:
11395 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11396 			return (sizeof (int));
11397 		case IPV6_V6ONLY:
11398 			*i1 = 1;
11399 			return (sizeof (int));
11400 		default:
11401 			return (-1);
11402 		}
11403 	default:
11404 		return (-1);
11405 	}
11406 	/* NOTREACHED */
11407 }
11408 
11409 /*
11410  * Given a destination address and a pointer to where to put the information
11411  * this routine fills in the mtuinfo.
11412  */
11413 int
11414 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11415     struct ip6_mtuinfo *mtuinfo)
11416 {
11417 	ire_t *ire;
11418 
11419 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11420 		return (-1);
11421 
11422 	bzero(mtuinfo, sizeof (*mtuinfo));
11423 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11424 	mtuinfo->ip6m_addr.sin6_port = port;
11425 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11426 
11427 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11428 	if (ire != NULL) {
11429 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11430 		ire_refrele(ire);
11431 	} else {
11432 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11433 	}
11434 	return (sizeof (struct ip6_mtuinfo));
11435 }
11436 
11437 /*
11438  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11439  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11440  * isn't.  This doesn't matter as the error checking is done properly for the
11441  * other MRT options coming in through ip_opt_set.
11442  */
11443 int
11444 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11445 {
11446 	conn_t		*connp = Q_TO_CONN(q);
11447 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11448 
11449 	switch (level) {
11450 	case IPPROTO_IP:
11451 		switch (name) {
11452 		case MRT_VERSION:
11453 		case MRT_ASSERT:
11454 			(void) ip_mrouter_get(name, q, ptr);
11455 			return (sizeof (int));
11456 		case IP_SEC_OPT:
11457 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11458 		case IP_NEXTHOP:
11459 			if (connp->conn_nexthop_set) {
11460 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11461 				return (sizeof (ipaddr_t));
11462 			} else
11463 				return (0);
11464 		default:
11465 			break;
11466 		}
11467 		break;
11468 	case IPPROTO_IPV6:
11469 		switch (name) {
11470 		case IPV6_SEC_OPT:
11471 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11472 		case IPV6_SRC_PREFERENCES: {
11473 			return (ip6_get_src_preferences(connp,
11474 			    (uint32_t *)ptr));
11475 		}
11476 		case IPV6_V6ONLY:
11477 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11478 			return (sizeof (int));
11479 		case IPV6_PATHMTU:
11480 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11481 				(struct ip6_mtuinfo *)ptr));
11482 		default:
11483 			break;
11484 		}
11485 		break;
11486 	default:
11487 		break;
11488 	}
11489 	return (-1);
11490 }
11491 
11492 /* Named Dispatch routine to get a current value out of our parameter table. */
11493 /* ARGSUSED */
11494 static int
11495 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11496 {
11497 	ipparam_t *ippa = (ipparam_t *)cp;
11498 
11499 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11500 	return (0);
11501 }
11502 
11503 /* ARGSUSED */
11504 static int
11505 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11506 {
11507 
11508 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11509 	return (0);
11510 }
11511 
11512 /*
11513  * Set ip{,6}_forwarding values.  This means walking through all of the
11514  * ill's and toggling their forwarding values.
11515  */
11516 /* ARGSUSED */
11517 static int
11518 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11519 {
11520 	long new_value;
11521 	int *forwarding_value = (int *)cp;
11522 	ill_t *walker;
11523 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11524 	ill_walk_context_t ctx;
11525 
11526 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11527 	    new_value < 0 || new_value > 1) {
11528 		return (EINVAL);
11529 	}
11530 
11531 	*forwarding_value = new_value;
11532 
11533 	/*
11534 	 * Regardless of the current value of ip_forwarding, set all per-ill
11535 	 * values of ip_forwarding to the value being set.
11536 	 *
11537 	 * Bring all the ill's up to date with the new global value.
11538 	 */
11539 	rw_enter(&ill_g_lock, RW_READER);
11540 
11541 	if (isv6)
11542 		walker = ILL_START_WALK_V6(&ctx);
11543 	else
11544 		walker = ILL_START_WALK_V4(&ctx);
11545 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11546 		(void) ill_forward_set(q, mp, (new_value != 0),
11547 		    (caddr_t)walker);
11548 	}
11549 	rw_exit(&ill_g_lock);
11550 
11551 	return (0);
11552 }
11553 
11554 /*
11555  * Walk through the param array specified registering each element with the
11556  * Named Dispatch handler. This is called only during init. So it is ok
11557  * not to acquire any locks
11558  */
11559 static boolean_t
11560 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11561     ipndp_t *ipnd, size_t ipnd_cnt)
11562 {
11563 	for (; ippa_cnt-- > 0; ippa++) {
11564 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11565 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11566 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11567 				nd_free(&ip_g_nd);
11568 				return (B_FALSE);
11569 			}
11570 		}
11571 	}
11572 
11573 	for (; ipnd_cnt-- > 0; ipnd++) {
11574 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11575 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11576 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11577 			    ipnd->ip_ndp_data)) {
11578 				nd_free(&ip_g_nd);
11579 				return (B_FALSE);
11580 			}
11581 		}
11582 	}
11583 
11584 	return (B_TRUE);
11585 }
11586 
11587 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11588 /* ARGSUSED */
11589 static int
11590 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11591 {
11592 	long		new_value;
11593 	ipparam_t	*ippa = (ipparam_t *)cp;
11594 
11595 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11596 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11597 		return (EINVAL);
11598 	}
11599 	ippa->ip_param_value = new_value;
11600 	return (0);
11601 }
11602 
11603 /*
11604  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11605  * When an ipf is passed here for the first time, if
11606  * we already have in-order fragments on the queue, we convert from the fast-
11607  * path reassembly scheme to the hard-case scheme.  From then on, additional
11608  * fragments are reassembled here.  We keep track of the start and end offsets
11609  * of each piece, and the number of holes in the chain.  When the hole count
11610  * goes to zero, we are done!
11611  *
11612  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11613  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11614  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11615  * after the call to ip_reassemble().
11616  */
11617 int
11618 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11619     size_t msg_len)
11620 {
11621 	uint_t	end;
11622 	mblk_t	*next_mp;
11623 	mblk_t	*mp1;
11624 	uint_t	offset;
11625 	boolean_t incr_dups = B_TRUE;
11626 	boolean_t offset_zero_seen = B_FALSE;
11627 	boolean_t pkt_boundary_checked = B_FALSE;
11628 
11629 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11630 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11631 
11632 	/* Add in byte count */
11633 	ipf->ipf_count += msg_len;
11634 	if (ipf->ipf_end) {
11635 		/*
11636 		 * We were part way through in-order reassembly, but now there
11637 		 * is a hole.  We walk through messages already queued, and
11638 		 * mark them for hard case reassembly.  We know that up till
11639 		 * now they were in order starting from offset zero.
11640 		 */
11641 		offset = 0;
11642 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11643 			IP_REASS_SET_START(mp1, offset);
11644 			if (offset == 0) {
11645 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11646 				offset = -ipf->ipf_nf_hdr_len;
11647 			}
11648 			offset += mp1->b_wptr - mp1->b_rptr;
11649 			IP_REASS_SET_END(mp1, offset);
11650 		}
11651 		/* One hole at the end. */
11652 		ipf->ipf_hole_cnt = 1;
11653 		/* Brand it as a hard case, forever. */
11654 		ipf->ipf_end = 0;
11655 	}
11656 	/* Walk through all the new pieces. */
11657 	do {
11658 		end = start + (mp->b_wptr - mp->b_rptr);
11659 		/*
11660 		 * If start is 0, decrease 'end' only for the first mblk of
11661 		 * the fragment. Otherwise 'end' can get wrong value in the
11662 		 * second pass of the loop if first mblk is exactly the
11663 		 * size of ipf_nf_hdr_len.
11664 		 */
11665 		if (start == 0 && !offset_zero_seen) {
11666 			/* First segment */
11667 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11668 			end -= ipf->ipf_nf_hdr_len;
11669 			offset_zero_seen = B_TRUE;
11670 		}
11671 		next_mp = mp->b_cont;
11672 		/*
11673 		 * We are checking to see if there is any interesing data
11674 		 * to process.  If there isn't and the mblk isn't the
11675 		 * one which carries the unfragmentable header then we
11676 		 * drop it.  It's possible to have just the unfragmentable
11677 		 * header come through without any data.  That needs to be
11678 		 * saved.
11679 		 *
11680 		 * If the assert at the top of this function holds then the
11681 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11682 		 * is infrequently traveled enough that the test is left in
11683 		 * to protect against future code changes which break that
11684 		 * invariant.
11685 		 */
11686 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11687 			/* Empty.  Blast it. */
11688 			IP_REASS_SET_START(mp, 0);
11689 			IP_REASS_SET_END(mp, 0);
11690 			/*
11691 			 * If the ipf points to the mblk we are about to free,
11692 			 * update ipf to point to the next mblk (or NULL
11693 			 * if none).
11694 			 */
11695 			if (ipf->ipf_mp->b_cont == mp)
11696 				ipf->ipf_mp->b_cont = next_mp;
11697 			freeb(mp);
11698 			continue;
11699 		}
11700 		mp->b_cont = NULL;
11701 		IP_REASS_SET_START(mp, start);
11702 		IP_REASS_SET_END(mp, end);
11703 		if (!ipf->ipf_tail_mp) {
11704 			ipf->ipf_tail_mp = mp;
11705 			ipf->ipf_mp->b_cont = mp;
11706 			if (start == 0 || !more) {
11707 				ipf->ipf_hole_cnt = 1;
11708 				/*
11709 				 * if the first fragment comes in more than one
11710 				 * mblk, this loop will be executed for each
11711 				 * mblk. Need to adjust hole count so exiting
11712 				 * this routine will leave hole count at 1.
11713 				 */
11714 				if (next_mp)
11715 					ipf->ipf_hole_cnt++;
11716 			} else
11717 				ipf->ipf_hole_cnt = 2;
11718 			continue;
11719 		} else if (ipf->ipf_last_frag_seen && !more &&
11720 			    !pkt_boundary_checked) {
11721 			/*
11722 			 * We check datagram boundary only if this fragment
11723 			 * claims to be the last fragment and we have seen a
11724 			 * last fragment in the past too. We do this only
11725 			 * once for a given fragment.
11726 			 *
11727 			 * start cannot be 0 here as fragments with start=0
11728 			 * and MF=0 gets handled as a complete packet. These
11729 			 * fragments should not reach here.
11730 			 */
11731 
11732 			if (start + msgdsize(mp) !=
11733 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11734 				/*
11735 				 * We have two fragments both of which claim
11736 				 * to be the last fragment but gives conflicting
11737 				 * information about the whole datagram size.
11738 				 * Something fishy is going on. Drop the
11739 				 * fragment and free up the reassembly list.
11740 				 */
11741 				return (IP_REASS_FAILED);
11742 			}
11743 
11744 			/*
11745 			 * We shouldn't come to this code block again for this
11746 			 * particular fragment.
11747 			 */
11748 			pkt_boundary_checked = B_TRUE;
11749 		}
11750 
11751 		/* New stuff at or beyond tail? */
11752 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11753 		if (start >= offset) {
11754 			if (ipf->ipf_last_frag_seen) {
11755 				/* current fragment is beyond last fragment */
11756 				return (IP_REASS_FAILED);
11757 			}
11758 			/* Link it on end. */
11759 			ipf->ipf_tail_mp->b_cont = mp;
11760 			ipf->ipf_tail_mp = mp;
11761 			if (more) {
11762 				if (start != offset)
11763 					ipf->ipf_hole_cnt++;
11764 			} else if (start == offset && next_mp == NULL)
11765 					ipf->ipf_hole_cnt--;
11766 			continue;
11767 		}
11768 		mp1 = ipf->ipf_mp->b_cont;
11769 		offset = IP_REASS_START(mp1);
11770 		/* New stuff at the front? */
11771 		if (start < offset) {
11772 			if (start == 0) {
11773 				if (end >= offset) {
11774 					/* Nailed the hole at the begining. */
11775 					ipf->ipf_hole_cnt--;
11776 				}
11777 			} else if (end < offset) {
11778 				/*
11779 				 * A hole, stuff, and a hole where there used
11780 				 * to be just a hole.
11781 				 */
11782 				ipf->ipf_hole_cnt++;
11783 			}
11784 			mp->b_cont = mp1;
11785 			/* Check for overlap. */
11786 			while (end > offset) {
11787 				if (end < IP_REASS_END(mp1)) {
11788 					mp->b_wptr -= end - offset;
11789 					IP_REASS_SET_END(mp, offset);
11790 					if (ill->ill_isv6) {
11791 						BUMP_MIB(ill->ill_ip6_mib,
11792 						    ipv6ReasmPartDups);
11793 					} else {
11794 						BUMP_MIB(&ip_mib,
11795 						    ipReasmPartDups);
11796 					}
11797 					break;
11798 				}
11799 				/* Did we cover another hole? */
11800 				if ((mp1->b_cont &&
11801 				    IP_REASS_END(mp1) !=
11802 				    IP_REASS_START(mp1->b_cont) &&
11803 				    end >= IP_REASS_START(mp1->b_cont)) ||
11804 				    (!ipf->ipf_last_frag_seen && !more)) {
11805 					ipf->ipf_hole_cnt--;
11806 				}
11807 				/* Clip out mp1. */
11808 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11809 					/*
11810 					 * After clipping out mp1, this guy
11811 					 * is now hanging off the end.
11812 					 */
11813 					ipf->ipf_tail_mp = mp;
11814 				}
11815 				IP_REASS_SET_START(mp1, 0);
11816 				IP_REASS_SET_END(mp1, 0);
11817 				/* Subtract byte count */
11818 				ipf->ipf_count -= mp1->b_datap->db_lim -
11819 				    mp1->b_datap->db_base;
11820 				freeb(mp1);
11821 				if (ill->ill_isv6) {
11822 					BUMP_MIB(ill->ill_ip6_mib,
11823 					    ipv6ReasmPartDups);
11824 				} else {
11825 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11826 				}
11827 				mp1 = mp->b_cont;
11828 				if (!mp1)
11829 					break;
11830 				offset = IP_REASS_START(mp1);
11831 			}
11832 			ipf->ipf_mp->b_cont = mp;
11833 			continue;
11834 		}
11835 		/*
11836 		 * The new piece starts somewhere between the start of the head
11837 		 * and before the end of the tail.
11838 		 */
11839 		for (; mp1; mp1 = mp1->b_cont) {
11840 			offset = IP_REASS_END(mp1);
11841 			if (start < offset) {
11842 				if (end <= offset) {
11843 					/* Nothing new. */
11844 					IP_REASS_SET_START(mp, 0);
11845 					IP_REASS_SET_END(mp, 0);
11846 					/* Subtract byte count */
11847 					ipf->ipf_count -= mp->b_datap->db_lim -
11848 					    mp->b_datap->db_base;
11849 					if (incr_dups) {
11850 						ipf->ipf_num_dups++;
11851 						incr_dups = B_FALSE;
11852 					}
11853 					freeb(mp);
11854 					if (ill->ill_isv6) {
11855 						BUMP_MIB(ill->ill_ip6_mib,
11856 						    ipv6ReasmDuplicates);
11857 					} else {
11858 						BUMP_MIB(&ip_mib,
11859 						    ipReasmDuplicates);
11860 					}
11861 					break;
11862 				}
11863 				/*
11864 				 * Trim redundant stuff off beginning of new
11865 				 * piece.
11866 				 */
11867 				IP_REASS_SET_START(mp, offset);
11868 				mp->b_rptr += offset - start;
11869 				if (ill->ill_isv6) {
11870 					BUMP_MIB(ill->ill_ip6_mib,
11871 					    ipv6ReasmPartDups);
11872 				} else {
11873 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11874 				}
11875 				start = offset;
11876 				if (!mp1->b_cont) {
11877 					/*
11878 					 * After trimming, this guy is now
11879 					 * hanging off the end.
11880 					 */
11881 					mp1->b_cont = mp;
11882 					ipf->ipf_tail_mp = mp;
11883 					if (!more) {
11884 						ipf->ipf_hole_cnt--;
11885 					}
11886 					break;
11887 				}
11888 			}
11889 			if (start >= IP_REASS_START(mp1->b_cont))
11890 				continue;
11891 			/* Fill a hole */
11892 			if (start > offset)
11893 				ipf->ipf_hole_cnt++;
11894 			mp->b_cont = mp1->b_cont;
11895 			mp1->b_cont = mp;
11896 			mp1 = mp->b_cont;
11897 			offset = IP_REASS_START(mp1);
11898 			if (end >= offset) {
11899 				ipf->ipf_hole_cnt--;
11900 				/* Check for overlap. */
11901 				while (end > offset) {
11902 					if (end < IP_REASS_END(mp1)) {
11903 						mp->b_wptr -= end - offset;
11904 						IP_REASS_SET_END(mp, offset);
11905 						/*
11906 						 * TODO we might bump
11907 						 * this up twice if there is
11908 						 * overlap at both ends.
11909 						 */
11910 						if (ill->ill_isv6) {
11911 							BUMP_MIB(
11912 							    ill->ill_ip6_mib,
11913 							    ipv6ReasmPartDups);
11914 						} else {
11915 							BUMP_MIB(&ip_mib,
11916 							    ipReasmPartDups);
11917 						}
11918 						break;
11919 					}
11920 					/* Did we cover another hole? */
11921 					if ((mp1->b_cont &&
11922 					    IP_REASS_END(mp1)
11923 					    != IP_REASS_START(mp1->b_cont) &&
11924 					    end >=
11925 					    IP_REASS_START(mp1->b_cont)) ||
11926 					    (!ipf->ipf_last_frag_seen &&
11927 					    !more)) {
11928 						ipf->ipf_hole_cnt--;
11929 					}
11930 					/* Clip out mp1. */
11931 					if ((mp->b_cont = mp1->b_cont) ==
11932 					    NULL) {
11933 						/*
11934 						 * After clipping out mp1,
11935 						 * this guy is now hanging
11936 						 * off the end.
11937 						 */
11938 						ipf->ipf_tail_mp = mp;
11939 					}
11940 					IP_REASS_SET_START(mp1, 0);
11941 					IP_REASS_SET_END(mp1, 0);
11942 					/* Subtract byte count */
11943 					ipf->ipf_count -=
11944 					    mp1->b_datap->db_lim -
11945 					    mp1->b_datap->db_base;
11946 					freeb(mp1);
11947 					if (ill->ill_isv6) {
11948 						BUMP_MIB(ill->ill_ip6_mib,
11949 						    ipv6ReasmPartDups);
11950 					} else {
11951 						BUMP_MIB(&ip_mib,
11952 						    ipReasmPartDups);
11953 					}
11954 					mp1 = mp->b_cont;
11955 					if (!mp1)
11956 						break;
11957 					offset = IP_REASS_START(mp1);
11958 				}
11959 			}
11960 			break;
11961 		}
11962 	} while (start = end, mp = next_mp);
11963 
11964 	/* Fragment just processed could be the last one. Remember this fact */
11965 	if (!more)
11966 		ipf->ipf_last_frag_seen = B_TRUE;
11967 
11968 	/* Still got holes? */
11969 	if (ipf->ipf_hole_cnt)
11970 		return (IP_REASS_PARTIAL);
11971 	/* Clean up overloaded fields to avoid upstream disasters. */
11972 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11973 		IP_REASS_SET_START(mp1, 0);
11974 		IP_REASS_SET_END(mp1, 0);
11975 	}
11976 	return (IP_REASS_COMPLETE);
11977 }
11978 
11979 /*
11980  * ipsec processing for the fast path, used for input UDP Packets
11981  */
11982 static boolean_t
11983 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11984     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11985 {
11986 	uint32_t	ill_index;
11987 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11988 
11989 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11990 	/* The ill_index of the incoming ILL */
11991 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11992 
11993 	/* pass packet up to the transport */
11994 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11995 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11996 		    NULL, mctl_present);
11997 		if (*first_mpp == NULL) {
11998 			return (B_FALSE);
11999 		}
12000 	}
12001 
12002 	/* Initiate IPPF processing for fastpath UDP */
12003 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12004 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12005 		if (*mpp == NULL) {
12006 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12007 			    "deferred/dropped during IPPF processing\n"));
12008 			return (B_FALSE);
12009 		}
12010 	}
12011 	/*
12012 	 * We make the checks as below since we are in the fast path
12013 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12014 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12015 	 */
12016 	if (connp->conn_recvif || connp->conn_recvslla ||
12017 	    connp->conn_ipv6_recvpktinfo) {
12018 		if (connp->conn_recvif ||
12019 		    connp->conn_ipv6_recvpktinfo) {
12020 			in_flags = IPF_RECVIF;
12021 		}
12022 		if (connp->conn_recvslla) {
12023 			in_flags |= IPF_RECVSLLA;
12024 		}
12025 		/*
12026 		 * since in_flags are being set ill will be
12027 		 * referenced in ip_add_info, so it better not
12028 		 * be NULL.
12029 		 */
12030 		/*
12031 		 * the actual data will be contained in b_cont
12032 		 * upon successful return of the following call.
12033 		 * If the call fails then the original mblk is
12034 		 * returned.
12035 		 */
12036 		*mpp = ip_add_info(*mpp, ill, in_flags);
12037 	}
12038 
12039 	return (B_TRUE);
12040 }
12041 
12042 /*
12043  * Fragmentation reassembly.  Each ILL has a hash table for
12044  * queuing packets undergoing reassembly for all IPIFs
12045  * associated with the ILL.  The hash is based on the packet
12046  * IP ident field.  The ILL frag hash table was allocated
12047  * as a timer block at the time the ILL was created.  Whenever
12048  * there is anything on the reassembly queue, the timer will
12049  * be running.  Returns B_TRUE if successful else B_FALSE;
12050  * frees mp on failure.
12051  */
12052 static boolean_t
12053 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12054     uint32_t *cksum_val, uint16_t *cksum_flags)
12055 {
12056 	uint32_t	frag_offset_flags;
12057 	ill_t		*ill = (ill_t *)q->q_ptr;
12058 	mblk_t		*mp = *mpp;
12059 	mblk_t		*t_mp;
12060 	ipaddr_t	dst;
12061 	uint8_t		proto = ipha->ipha_protocol;
12062 	uint32_t	sum_val;
12063 	uint16_t	sum_flags;
12064 	ipf_t		*ipf;
12065 	ipf_t		**ipfp;
12066 	ipfb_t		*ipfb;
12067 	uint16_t	ident;
12068 	uint32_t	offset;
12069 	ipaddr_t	src;
12070 	uint_t		hdr_length;
12071 	uint32_t	end;
12072 	mblk_t		*mp1;
12073 	mblk_t		*tail_mp;
12074 	size_t		count;
12075 	size_t		msg_len;
12076 	uint8_t		ecn_info = 0;
12077 	uint32_t	packet_size;
12078 	boolean_t	pruned = B_FALSE;
12079 
12080 	if (cksum_val != NULL)
12081 		*cksum_val = 0;
12082 	if (cksum_flags != NULL)
12083 		*cksum_flags = 0;
12084 
12085 	/*
12086 	 * Drop the fragmented as early as possible, if
12087 	 * we don't have resource(s) to re-assemble.
12088 	 */
12089 	if (ip_reass_queue_bytes == 0) {
12090 		freemsg(mp);
12091 		return (B_FALSE);
12092 	}
12093 
12094 	/* Check for fragmentation offset; return if there's none */
12095 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12096 	    (IPH_MF | IPH_OFFSET)) == 0)
12097 		return (B_TRUE);
12098 
12099 	/*
12100 	 * We utilize hardware computed checksum info only for UDP since
12101 	 * IP fragmentation is a normal occurence for the protocol.  In
12102 	 * addition, checksum offload support for IP fragments carrying
12103 	 * UDP payload is commonly implemented across network adapters.
12104 	 */
12105 	ASSERT(ill != NULL);
12106 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12107 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12108 		mblk_t *mp1 = mp->b_cont;
12109 		int32_t len;
12110 
12111 		/* Record checksum information from the packet */
12112 		sum_val = (uint32_t)DB_CKSUM16(mp);
12113 		sum_flags = DB_CKSUMFLAGS(mp);
12114 
12115 		/* IP payload offset from beginning of mblk */
12116 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12117 
12118 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12119 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12120 		    offset >= DB_CKSUMSTART(mp) &&
12121 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12122 			uint32_t adj;
12123 			/*
12124 			 * Partial checksum has been calculated by hardware
12125 			 * and attached to the packet; in addition, any
12126 			 * prepended extraneous data is even byte aligned.
12127 			 * If any such data exists, we adjust the checksum;
12128 			 * this would also handle any postpended data.
12129 			 */
12130 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12131 			    mp, mp1, len, adj);
12132 
12133 			/* One's complement subtract extraneous checksum */
12134 			if (adj >= sum_val)
12135 				sum_val = ~(adj - sum_val) & 0xFFFF;
12136 			else
12137 				sum_val -= adj;
12138 		}
12139 	} else {
12140 		sum_val = 0;
12141 		sum_flags = 0;
12142 	}
12143 
12144 	/* Clear hardware checksumming flag */
12145 	DB_CKSUMFLAGS(mp) = 0;
12146 
12147 	ident = ipha->ipha_ident;
12148 	offset = (frag_offset_flags << 3) & 0xFFFF;
12149 	src = ipha->ipha_src;
12150 	dst = ipha->ipha_dst;
12151 	hdr_length = IPH_HDR_LENGTH(ipha);
12152 	end = ntohs(ipha->ipha_length) - hdr_length;
12153 
12154 	/* If end == 0 then we have a packet with no data, so just free it */
12155 	if (end == 0) {
12156 		freemsg(mp);
12157 		return (B_FALSE);
12158 	}
12159 
12160 	/* Record the ECN field info. */
12161 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12162 	if (offset != 0) {
12163 		/*
12164 		 * If this isn't the first piece, strip the header, and
12165 		 * add the offset to the end value.
12166 		 */
12167 		mp->b_rptr += hdr_length;
12168 		end += offset;
12169 	}
12170 
12171 	msg_len = MBLKSIZE(mp);
12172 	tail_mp = mp;
12173 	while (tail_mp->b_cont != NULL) {
12174 		tail_mp = tail_mp->b_cont;
12175 		msg_len += MBLKSIZE(tail_mp);
12176 	}
12177 
12178 	/* If the reassembly list for this ILL will get too big, prune it */
12179 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12180 	    ip_reass_queue_bytes) {
12181 		ill_frag_prune(ill,
12182 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12183 		    (ip_reass_queue_bytes - msg_len));
12184 		pruned = B_TRUE;
12185 	}
12186 
12187 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12188 	mutex_enter(&ipfb->ipfb_lock);
12189 
12190 	ipfp = &ipfb->ipfb_ipf;
12191 	/* Try to find an existing fragment queue for this packet. */
12192 	for (;;) {
12193 		ipf = ipfp[0];
12194 		if (ipf != NULL) {
12195 			/*
12196 			 * It has to match on ident and src/dst address.
12197 			 */
12198 			if (ipf->ipf_ident == ident &&
12199 			    ipf->ipf_src == src &&
12200 			    ipf->ipf_dst == dst &&
12201 			    ipf->ipf_protocol == proto) {
12202 				/*
12203 				 * If we have received too many
12204 				 * duplicate fragments for this packet
12205 				 * free it.
12206 				 */
12207 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12208 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12209 					freemsg(mp);
12210 					mutex_exit(&ipfb->ipfb_lock);
12211 					return (B_FALSE);
12212 				}
12213 				/* Found it. */
12214 				break;
12215 			}
12216 			ipfp = &ipf->ipf_hash_next;
12217 			continue;
12218 		}
12219 
12220 		/*
12221 		 * If we pruned the list, do we want to store this new
12222 		 * fragment?. We apply an optimization here based on the
12223 		 * fact that most fragments will be received in order.
12224 		 * So if the offset of this incoming fragment is zero,
12225 		 * it is the first fragment of a new packet. We will
12226 		 * keep it.  Otherwise drop the fragment, as we have
12227 		 * probably pruned the packet already (since the
12228 		 * packet cannot be found).
12229 		 */
12230 		if (pruned && offset != 0) {
12231 			mutex_exit(&ipfb->ipfb_lock);
12232 			freemsg(mp);
12233 			return (B_FALSE);
12234 		}
12235 
12236 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12237 			/*
12238 			 * Too many fragmented packets in this hash
12239 			 * bucket. Free the oldest.
12240 			 */
12241 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12242 		}
12243 
12244 		/* New guy.  Allocate a frag message. */
12245 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12246 		if (mp1 == NULL) {
12247 			BUMP_MIB(&ip_mib, ipInDiscards);
12248 			freemsg(mp);
12249 reass_done:
12250 			mutex_exit(&ipfb->ipfb_lock);
12251 			return (B_FALSE);
12252 		}
12253 
12254 
12255 		BUMP_MIB(&ip_mib, ipReasmReqds);
12256 		mp1->b_cont = mp;
12257 
12258 		/* Initialize the fragment header. */
12259 		ipf = (ipf_t *)mp1->b_rptr;
12260 		ipf->ipf_mp = mp1;
12261 		ipf->ipf_ptphn = ipfp;
12262 		ipfp[0] = ipf;
12263 		ipf->ipf_hash_next = NULL;
12264 		ipf->ipf_ident = ident;
12265 		ipf->ipf_protocol = proto;
12266 		ipf->ipf_src = src;
12267 		ipf->ipf_dst = dst;
12268 		ipf->ipf_nf_hdr_len = 0;
12269 		/* Record reassembly start time. */
12270 		ipf->ipf_timestamp = gethrestime_sec();
12271 		/* Record ipf generation and account for frag header */
12272 		ipf->ipf_gen = ill->ill_ipf_gen++;
12273 		ipf->ipf_count = MBLKSIZE(mp1);
12274 		ipf->ipf_last_frag_seen = B_FALSE;
12275 		ipf->ipf_ecn = ecn_info;
12276 		ipf->ipf_num_dups = 0;
12277 		ipfb->ipfb_frag_pkts++;
12278 		ipf->ipf_checksum = 0;
12279 		ipf->ipf_checksum_flags = 0;
12280 
12281 		/* Store checksum value in fragment header */
12282 		if (sum_flags != 0) {
12283 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12284 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12285 			ipf->ipf_checksum = sum_val;
12286 			ipf->ipf_checksum_flags = sum_flags;
12287 		}
12288 
12289 		/*
12290 		 * We handle reassembly two ways.  In the easy case,
12291 		 * where all the fragments show up in order, we do
12292 		 * minimal bookkeeping, and just clip new pieces on
12293 		 * the end.  If we ever see a hole, then we go off
12294 		 * to ip_reassemble which has to mark the pieces and
12295 		 * keep track of the number of holes, etc.  Obviously,
12296 		 * the point of having both mechanisms is so we can
12297 		 * handle the easy case as efficiently as possible.
12298 		 */
12299 		if (offset == 0) {
12300 			/* Easy case, in-order reassembly so far. */
12301 			ipf->ipf_count += msg_len;
12302 			ipf->ipf_tail_mp = tail_mp;
12303 			/*
12304 			 * Keep track of next expected offset in
12305 			 * ipf_end.
12306 			 */
12307 			ipf->ipf_end = end;
12308 			ipf->ipf_nf_hdr_len = hdr_length;
12309 		} else {
12310 			/* Hard case, hole at the beginning. */
12311 			ipf->ipf_tail_mp = NULL;
12312 			/*
12313 			 * ipf_end == 0 means that we have given up
12314 			 * on easy reassembly.
12315 			 */
12316 			ipf->ipf_end = 0;
12317 
12318 			/* Forget checksum offload from now on */
12319 			ipf->ipf_checksum_flags = 0;
12320 
12321 			/*
12322 			 * ipf_hole_cnt is set by ip_reassemble.
12323 			 * ipf_count is updated by ip_reassemble.
12324 			 * No need to check for return value here
12325 			 * as we don't expect reassembly to complete
12326 			 * or fail for the first fragment itself.
12327 			 */
12328 			(void) ip_reassemble(mp, ipf,
12329 			    (frag_offset_flags & IPH_OFFSET) << 3,
12330 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12331 		}
12332 		/* Update per ipfb and ill byte counts */
12333 		ipfb->ipfb_count += ipf->ipf_count;
12334 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12335 		ill->ill_frag_count += ipf->ipf_count;
12336 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12337 		/* If the frag timer wasn't already going, start it. */
12338 		mutex_enter(&ill->ill_lock);
12339 		ill_frag_timer_start(ill);
12340 		mutex_exit(&ill->ill_lock);
12341 		goto reass_done;
12342 	}
12343 
12344 	/*
12345 	 * If the packet's flag has changed (it could be coming up
12346 	 * from an interface different than the previous, therefore
12347 	 * possibly different checksum capability), then forget about
12348 	 * any stored checksum states.  Otherwise add the value to
12349 	 * the existing one stored in the fragment header.
12350 	 */
12351 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12352 		sum_val += ipf->ipf_checksum;
12353 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12354 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12355 		ipf->ipf_checksum = sum_val;
12356 	} else if (ipf->ipf_checksum_flags != 0) {
12357 		/* Forget checksum offload from now on */
12358 		ipf->ipf_checksum_flags = 0;
12359 	}
12360 
12361 	/*
12362 	 * We have a new piece of a datagram which is already being
12363 	 * reassembled.  Update the ECN info if all IP fragments
12364 	 * are ECN capable.  If there is one which is not, clear
12365 	 * all the info.  If there is at least one which has CE
12366 	 * code point, IP needs to report that up to transport.
12367 	 */
12368 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12369 		if (ecn_info == IPH_ECN_CE)
12370 			ipf->ipf_ecn = IPH_ECN_CE;
12371 	} else {
12372 		ipf->ipf_ecn = IPH_ECN_NECT;
12373 	}
12374 	if (offset && ipf->ipf_end == offset) {
12375 		/* The new fragment fits at the end */
12376 		ipf->ipf_tail_mp->b_cont = mp;
12377 		/* Update the byte count */
12378 		ipf->ipf_count += msg_len;
12379 		/* Update per ipfb and ill byte counts */
12380 		ipfb->ipfb_count += msg_len;
12381 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12382 		ill->ill_frag_count += msg_len;
12383 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12384 		if (frag_offset_flags & IPH_MF) {
12385 			/* More to come. */
12386 			ipf->ipf_end = end;
12387 			ipf->ipf_tail_mp = tail_mp;
12388 			goto reass_done;
12389 		}
12390 	} else {
12391 		/* Go do the hard cases. */
12392 		int ret;
12393 
12394 		if (offset == 0)
12395 			ipf->ipf_nf_hdr_len = hdr_length;
12396 
12397 		/* Save current byte count */
12398 		count = ipf->ipf_count;
12399 		ret = ip_reassemble(mp, ipf,
12400 		    (frag_offset_flags & IPH_OFFSET) << 3,
12401 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12402 		/* Count of bytes added and subtracted (freeb()ed) */
12403 		count = ipf->ipf_count - count;
12404 		if (count) {
12405 			/* Update per ipfb and ill byte counts */
12406 			ipfb->ipfb_count += count;
12407 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12408 			ill->ill_frag_count += count;
12409 			ASSERT(ill->ill_frag_count > 0);
12410 		}
12411 		if (ret == IP_REASS_PARTIAL) {
12412 			goto reass_done;
12413 		} else if (ret == IP_REASS_FAILED) {
12414 			/* Reassembly failed. Free up all resources */
12415 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12416 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12417 				IP_REASS_SET_START(t_mp, 0);
12418 				IP_REASS_SET_END(t_mp, 0);
12419 			}
12420 			freemsg(mp);
12421 			goto reass_done;
12422 		}
12423 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12424 	}
12425 	/*
12426 	 * We have completed reassembly.  Unhook the frag header from
12427 	 * the reassembly list.
12428 	 *
12429 	 * Before we free the frag header, record the ECN info
12430 	 * to report back to the transport.
12431 	 */
12432 	ecn_info = ipf->ipf_ecn;
12433 	BUMP_MIB(&ip_mib, ipReasmOKs);
12434 	ipfp = ipf->ipf_ptphn;
12435 
12436 	/* We need to supply these to caller */
12437 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12438 		sum_val = ipf->ipf_checksum;
12439 	else
12440 		sum_val = 0;
12441 
12442 	mp1 = ipf->ipf_mp;
12443 	count = ipf->ipf_count;
12444 	ipf = ipf->ipf_hash_next;
12445 	if (ipf != NULL)
12446 		ipf->ipf_ptphn = ipfp;
12447 	ipfp[0] = ipf;
12448 	ill->ill_frag_count -= count;
12449 	ASSERT(ipfb->ipfb_count >= count);
12450 	ipfb->ipfb_count -= count;
12451 	ipfb->ipfb_frag_pkts--;
12452 	mutex_exit(&ipfb->ipfb_lock);
12453 	/* Ditch the frag header. */
12454 	mp = mp1->b_cont;
12455 
12456 	freeb(mp1);
12457 
12458 	/* Restore original IP length in header. */
12459 	packet_size = (uint32_t)msgdsize(mp);
12460 	if (packet_size > IP_MAXPACKET) {
12461 		freemsg(mp);
12462 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12463 		return (B_FALSE);
12464 	}
12465 
12466 	if (DB_REF(mp) > 1) {
12467 		mblk_t *mp2 = copymsg(mp);
12468 
12469 		freemsg(mp);
12470 		if (mp2 == NULL) {
12471 			BUMP_MIB(&ip_mib, ipInDiscards);
12472 			return (B_FALSE);
12473 		}
12474 		mp = mp2;
12475 	}
12476 	ipha = (ipha_t *)mp->b_rptr;
12477 
12478 	ipha->ipha_length = htons((uint16_t)packet_size);
12479 	/* We're now complete, zip the frag state */
12480 	ipha->ipha_fragment_offset_and_flags = 0;
12481 	/* Record the ECN info. */
12482 	ipha->ipha_type_of_service &= 0xFC;
12483 	ipha->ipha_type_of_service |= ecn_info;
12484 	*mpp = mp;
12485 
12486 	/* Reassembly is successful; return checksum information if needed */
12487 	if (cksum_val != NULL)
12488 		*cksum_val = sum_val;
12489 	if (cksum_flags != NULL)
12490 		*cksum_flags = sum_flags;
12491 
12492 	return (B_TRUE);
12493 }
12494 
12495 /*
12496  * Perform ip header check sum update local options.
12497  * return B_TRUE if all is well, else return B_FALSE and release
12498  * the mp. caller is responsible for decrementing ire ref cnt.
12499  */
12500 static boolean_t
12501 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12502 {
12503 	mblk_t		*first_mp;
12504 	boolean_t	mctl_present;
12505 	uint16_t	sum;
12506 
12507 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12508 	/*
12509 	 * Don't do the checksum if it has gone through AH/ESP
12510 	 * processing.
12511 	 */
12512 	if (!mctl_present) {
12513 		sum = ip_csum_hdr(ipha);
12514 		if (sum != 0) {
12515 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12516 			freemsg(first_mp);
12517 			return (B_FALSE);
12518 		}
12519 	}
12520 
12521 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12522 		if (mctl_present)
12523 			freeb(first_mp);
12524 		return (B_FALSE);
12525 	}
12526 
12527 	return (B_TRUE);
12528 }
12529 
12530 /*
12531  * All udp packet are delivered to the local host via this routine.
12532  */
12533 void
12534 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12535     ill_t *recv_ill)
12536 {
12537 	uint32_t	sum;
12538 	uint32_t	u1;
12539 	boolean_t	mctl_present;
12540 	conn_t		*connp;
12541 	mblk_t		*first_mp;
12542 	uint16_t	*up;
12543 	ill_t		*ill = (ill_t *)q->q_ptr;
12544 	uint16_t	reass_hck_flags = 0;
12545 
12546 #define	rptr    ((uchar_t *)ipha)
12547 
12548 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12549 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12550 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12551 
12552 	/*
12553 	 * FAST PATH for udp packets
12554 	 */
12555 
12556 	/* u1 is # words of IP options */
12557 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12558 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12559 
12560 	/* IP options present */
12561 	if (u1 != 0)
12562 		goto ipoptions;
12563 
12564 	/* Check the IP header checksum.  */
12565 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12566 		/* Clear the IP header h/w cksum flag */
12567 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12568 	} else {
12569 #define	uph	((uint16_t *)ipha)
12570 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12571 		    uph[6] + uph[7] + uph[8] + uph[9];
12572 #undef	uph
12573 		/* finish doing IP checksum */
12574 		sum = (sum & 0xFFFF) + (sum >> 16);
12575 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12576 		/*
12577 		 * Don't verify header checksum if this packet is coming
12578 		 * back from AH/ESP as we already did it.
12579 		 */
12580 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12581 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12582 			freemsg(first_mp);
12583 			return;
12584 		}
12585 	}
12586 
12587 	/*
12588 	 * Count for SNMP of inbound packets for ire.
12589 	 * if mctl is present this might be a secure packet and
12590 	 * has already been counted for in ip_proto_input().
12591 	 */
12592 	if (!mctl_present) {
12593 		UPDATE_IB_PKT_COUNT(ire);
12594 		ire->ire_last_used_time = lbolt;
12595 	}
12596 
12597 	/* packet part of fragmented IP packet? */
12598 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12599 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12600 		goto fragmented;
12601 	}
12602 
12603 	/* u1 = IP header length (20 bytes) */
12604 	u1 = IP_SIMPLE_HDR_LENGTH;
12605 
12606 	/* packet does not contain complete IP & UDP headers */
12607 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12608 		goto udppullup;
12609 
12610 	/* up points to UDP header */
12611 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12612 #define	iphs    ((uint16_t *)ipha)
12613 
12614 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12615 	if (up[3] != 0) {
12616 		mblk_t *mp1 = mp->b_cont;
12617 		boolean_t cksum_err;
12618 		uint16_t hck_flags = 0;
12619 
12620 		/* Pseudo-header checksum */
12621 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12622 		    iphs[9] + up[2];
12623 
12624 		/*
12625 		 * Revert to software checksum calculation if the interface
12626 		 * isn't capable of checksum offload or if IPsec is present.
12627 		 */
12628 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12629 			hck_flags = DB_CKSUMFLAGS(mp);
12630 
12631 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12632 			IP_STAT(ip_in_sw_cksum);
12633 
12634 		IP_CKSUM_RECV(hck_flags, u1,
12635 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12636 		    (int32_t)((uchar_t *)up - rptr),
12637 		    mp, mp1, cksum_err);
12638 
12639 		if (cksum_err) {
12640 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12641 
12642 			if (hck_flags & HCK_FULLCKSUM)
12643 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12644 			else if (hck_flags & HCK_PARTIALCKSUM)
12645 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12646 			else
12647 				IP_STAT(ip_udp_in_sw_cksum_err);
12648 
12649 			freemsg(first_mp);
12650 			return;
12651 		}
12652 	}
12653 
12654 	/* Non-fragmented broadcast or multicast packet? */
12655 	if (ire->ire_type == IRE_BROADCAST)
12656 		goto udpslowpath;
12657 
12658 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12659 	    ire->ire_zoneid)) != NULL) {
12660 		ASSERT(connp->conn_upq != NULL);
12661 		IP_STAT(ip_udp_fast_path);
12662 
12663 		if (CONN_UDP_FLOWCTLD(connp)) {
12664 			freemsg(mp);
12665 			BUMP_MIB(&ip_mib, udpInOverflows);
12666 		} else {
12667 			if (!mctl_present) {
12668 				BUMP_MIB(&ip_mib, ipInDelivers);
12669 			}
12670 			/*
12671 			 * mp and first_mp can change.
12672 			 */
12673 			if (ip_udp_check(q, connp, recv_ill,
12674 			    ipha, &mp, &first_mp, mctl_present)) {
12675 				/* Send it upstream */
12676 				CONN_UDP_RECV(connp, mp);
12677 			}
12678 		}
12679 		/*
12680 		 * freeb() cannot deal with null mblk being passed
12681 		 * in and first_mp can be set to null in the call
12682 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12683 		 */
12684 		if (mctl_present && first_mp != NULL) {
12685 			freeb(first_mp);
12686 		}
12687 		CONN_DEC_REF(connp);
12688 		return;
12689 	}
12690 
12691 	/*
12692 	 * if we got here we know the packet is not fragmented and
12693 	 * has no options. The classifier could not find a conn_t and
12694 	 * most likely its an icmp packet so send it through slow path.
12695 	 */
12696 
12697 	goto udpslowpath;
12698 
12699 ipoptions:
12700 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12701 		goto slow_done;
12702 	}
12703 
12704 	UPDATE_IB_PKT_COUNT(ire);
12705 	ire->ire_last_used_time = lbolt;
12706 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12707 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12708 fragmented:
12709 		/*
12710 		 * "sum" and "reass_hck_flags" are non-zero if the
12711 		 * reassembled packet has a valid hardware computed
12712 		 * checksum information associated with it.
12713 		 */
12714 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12715 			goto slow_done;
12716 		/*
12717 		 * Make sure that first_mp points back to mp as
12718 		 * the mp we came in with could have changed in
12719 		 * ip_rput_fragment().
12720 		 */
12721 		ASSERT(!mctl_present);
12722 		ipha = (ipha_t *)mp->b_rptr;
12723 		first_mp = mp;
12724 	}
12725 
12726 	/* Now we have a complete datagram, destined for this machine. */
12727 	u1 = IPH_HDR_LENGTH(ipha);
12728 	/* Pull up the UDP header, if necessary. */
12729 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12730 udppullup:
12731 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12732 			BUMP_MIB(&ip_mib, ipInDiscards);
12733 			freemsg(first_mp);
12734 			goto slow_done;
12735 		}
12736 		ipha = (ipha_t *)mp->b_rptr;
12737 	}
12738 
12739 	/*
12740 	 * Validate the checksum for the reassembled packet; for the
12741 	 * pullup case we calculate the payload checksum in software.
12742 	 */
12743 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12744 	if (up[3] != 0) {
12745 		boolean_t cksum_err;
12746 
12747 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12748 			IP_STAT(ip_in_sw_cksum);
12749 
12750 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12751 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12752 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12753 		    iphs[9] + up[2], sum, cksum_err);
12754 
12755 		if (cksum_err) {
12756 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12757 
12758 			if (reass_hck_flags & HCK_FULLCKSUM)
12759 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12760 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12761 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12762 			else
12763 				IP_STAT(ip_udp_in_sw_cksum_err);
12764 
12765 			freemsg(first_mp);
12766 			goto slow_done;
12767 		}
12768 	}
12769 udpslowpath:
12770 
12771 	/* Clear hardware checksum flag to be safe */
12772 	DB_CKSUMFLAGS(mp) = 0;
12773 
12774 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12775 	    (ire->ire_type == IRE_BROADCAST),
12776 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12777 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12778 
12779 slow_done:
12780 	IP_STAT(ip_udp_slow_path);
12781 	return;
12782 
12783 #undef  iphs
12784 #undef  rptr
12785 }
12786 
12787 /* ARGSUSED */
12788 static mblk_t *
12789 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12790     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12791     ill_rx_ring_t *ill_ring)
12792 {
12793 	conn_t		*connp;
12794 	uint32_t	sum;
12795 	uint32_t	u1;
12796 	uint16_t	*up;
12797 	int		offset;
12798 	ssize_t		len;
12799 	mblk_t		*mp1;
12800 	boolean_t	syn_present = B_FALSE;
12801 	tcph_t		*tcph;
12802 	uint_t		ip_hdr_len;
12803 	ill_t		*ill = (ill_t *)q->q_ptr;
12804 	zoneid_t	zoneid = ire->ire_zoneid;
12805 	boolean_t	cksum_err;
12806 	uint16_t	hck_flags = 0;
12807 
12808 #define	rptr	((uchar_t *)ipha)
12809 
12810 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12811 
12812 	/*
12813 	 * FAST PATH for tcp packets
12814 	 */
12815 
12816 	/* u1 is # words of IP options */
12817 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12818 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12819 
12820 	/* IP options present */
12821 	if (u1) {
12822 		goto ipoptions;
12823 	} else {
12824 		/* Check the IP header checksum.  */
12825 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12826 			/* Clear the IP header h/w cksum flag */
12827 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12828 		} else {
12829 #define	uph	((uint16_t *)ipha)
12830 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12831 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12832 #undef	uph
12833 			/* finish doing IP checksum */
12834 			sum = (sum & 0xFFFF) + (sum >> 16);
12835 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12836 			/*
12837 			 * Don't verify header checksum if this packet
12838 			 * is coming back from AH/ESP as we already did it.
12839 			 */
12840 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12841 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12842 				goto error;
12843 			}
12844 		}
12845 	}
12846 
12847 	if (!mctl_present) {
12848 		UPDATE_IB_PKT_COUNT(ire);
12849 		ire->ire_last_used_time = lbolt;
12850 	}
12851 
12852 	/* packet part of fragmented IP packet? */
12853 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12854 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12855 		goto fragmented;
12856 	}
12857 
12858 	/* u1 = IP header length (20 bytes) */
12859 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12860 
12861 	/* does packet contain IP+TCP headers? */
12862 	len = mp->b_wptr - rptr;
12863 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12864 		IP_STAT(ip_tcppullup);
12865 		goto tcppullup;
12866 	}
12867 
12868 	/* TCP options present? */
12869 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12870 
12871 	/*
12872 	 * If options need to be pulled up, then goto tcpoptions.
12873 	 * otherwise we are still in the fast path
12874 	 */
12875 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12876 		IP_STAT(ip_tcpoptions);
12877 		goto tcpoptions;
12878 	}
12879 
12880 	/* multiple mblks of tcp data? */
12881 	if ((mp1 = mp->b_cont) != NULL) {
12882 		/* more then two? */
12883 		if (mp1->b_cont != NULL) {
12884 			IP_STAT(ip_multipkttcp);
12885 			goto multipkttcp;
12886 		}
12887 		len += mp1->b_wptr - mp1->b_rptr;
12888 	}
12889 
12890 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12891 
12892 	/* part of pseudo checksum */
12893 
12894 	/* TCP datagram length */
12895 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12896 
12897 #define	iphs    ((uint16_t *)ipha)
12898 
12899 #ifdef	_BIG_ENDIAN
12900 	u1 += IPPROTO_TCP;
12901 #else
12902 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12903 #endif
12904 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12905 
12906 	/*
12907 	 * Revert to software checksum calculation if the interface
12908 	 * isn't capable of checksum offload or if IPsec is present.
12909 	 */
12910 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12911 		hck_flags = DB_CKSUMFLAGS(mp);
12912 
12913 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12914 		IP_STAT(ip_in_sw_cksum);
12915 
12916 	IP_CKSUM_RECV(hck_flags, u1,
12917 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12918 	    (int32_t)((uchar_t *)up - rptr),
12919 	    mp, mp1, cksum_err);
12920 
12921 	if (cksum_err) {
12922 		BUMP_MIB(&ip_mib, tcpInErrs);
12923 
12924 		if (hck_flags & HCK_FULLCKSUM)
12925 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12926 		else if (hck_flags & HCK_PARTIALCKSUM)
12927 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12928 		else
12929 			IP_STAT(ip_tcp_in_sw_cksum_err);
12930 
12931 		goto error;
12932 	}
12933 
12934 try_again:
12935 
12936 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12937 	    NULL) {
12938 		/* Send the TH_RST */
12939 		goto no_conn;
12940 	}
12941 
12942 	/*
12943 	 * TCP FAST PATH for AF_INET socket.
12944 	 *
12945 	 * TCP fast path to avoid extra work. An AF_INET socket type
12946 	 * does not have facility to receive extra information via
12947 	 * ip_process or ip_add_info. Also, when the connection was
12948 	 * established, we made a check if this connection is impacted
12949 	 * by any global IPSec policy or per connection policy (a
12950 	 * policy that comes in effect later will not apply to this
12951 	 * connection). Since all this can be determined at the
12952 	 * connection establishment time, a quick check of flags
12953 	 * can avoid extra work.
12954 	 */
12955 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12956 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12957 		ASSERT(first_mp == mp);
12958 		SET_SQUEUE(mp, tcp_rput_data, connp);
12959 		return (mp);
12960 	}
12961 
12962 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12963 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12964 		if (IPCL_IS_TCP(connp)) {
12965 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12966 			DB_CKSUMSTART(mp) =
12967 			    (intptr_t)ip_squeue_get(ill_ring);
12968 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12969 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12970 				SET_SQUEUE(mp, connp->conn_recv, connp);
12971 				return (mp);
12972 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12973 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12974 				ip_squeue_enter_unbound++;
12975 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12976 				    connp);
12977 				return (mp);
12978 			}
12979 			syn_present = B_TRUE;
12980 		}
12981 
12982 	}
12983 
12984 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12985 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12986 
12987 		/* No need to send this packet to TCP */
12988 		if ((flags & TH_RST) || (flags & TH_URG)) {
12989 			CONN_DEC_REF(connp);
12990 			freemsg(first_mp);
12991 			return (NULL);
12992 		}
12993 		if (flags & TH_ACK) {
12994 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12995 			CONN_DEC_REF(connp);
12996 			return (NULL);
12997 		}
12998 
12999 		CONN_DEC_REF(connp);
13000 		freemsg(first_mp);
13001 		return (NULL);
13002 	}
13003 
13004 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
13005 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13006 		    ipha, NULL, mctl_present);
13007 		if (first_mp == NULL) {
13008 			CONN_DEC_REF(connp);
13009 			return (NULL);
13010 		}
13011 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13012 			ASSERT(syn_present);
13013 			if (mctl_present) {
13014 				ASSERT(first_mp != mp);
13015 				first_mp->b_datap->db_struioflag |=
13016 				    STRUIO_POLICY;
13017 			} else {
13018 				ASSERT(first_mp == mp);
13019 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13020 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13021 			}
13022 		} else {
13023 			/*
13024 			 * Discard first_mp early since we're dealing with a
13025 			 * fully-connected conn_t and tcp doesn't do policy in
13026 			 * this case.
13027 			 */
13028 			if (mctl_present) {
13029 				freeb(first_mp);
13030 				mctl_present = B_FALSE;
13031 			}
13032 			first_mp = mp;
13033 		}
13034 	}
13035 
13036 	/* Initiate IPPF processing for fastpath */
13037 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13038 		uint32_t	ill_index;
13039 
13040 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13041 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13042 		if (mp == NULL) {
13043 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13044 			    "deferred/dropped during IPPF processing\n"));
13045 			CONN_DEC_REF(connp);
13046 			if (mctl_present)
13047 				freeb(first_mp);
13048 			return (NULL);
13049 		} else if (mctl_present) {
13050 			/*
13051 			 * ip_process might return a new mp.
13052 			 */
13053 			ASSERT(first_mp != mp);
13054 			first_mp->b_cont = mp;
13055 		} else {
13056 			first_mp = mp;
13057 		}
13058 
13059 	}
13060 
13061 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
13062 		mp = ip_add_info(mp, recv_ill, flags);
13063 		if (mp == NULL) {
13064 			CONN_DEC_REF(connp);
13065 			if (mctl_present)
13066 				freeb(first_mp);
13067 			return (NULL);
13068 		} else if (mctl_present) {
13069 			/*
13070 			 * ip_add_info might return a new mp.
13071 			 */
13072 			ASSERT(first_mp != mp);
13073 			first_mp->b_cont = mp;
13074 		} else {
13075 			first_mp = mp;
13076 		}
13077 	}
13078 
13079 	if (IPCL_IS_TCP(connp)) {
13080 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13081 		return (first_mp);
13082 	} else {
13083 		putnext(connp->conn_rq, first_mp);
13084 		CONN_DEC_REF(connp);
13085 		return (NULL);
13086 	}
13087 
13088 no_conn:
13089 	/* Initiate IPPf processing, if needed. */
13090 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13091 		uint32_t ill_index;
13092 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13093 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13094 		if (first_mp == NULL) {
13095 			return (NULL);
13096 		}
13097 	}
13098 	BUMP_MIB(&ip_mib, ipInDelivers);
13099 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13100 	return (NULL);
13101 ipoptions:
13102 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13103 		goto slow_done;
13104 	}
13105 
13106 	UPDATE_IB_PKT_COUNT(ire);
13107 	ire->ire_last_used_time = lbolt;
13108 
13109 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13110 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13111 fragmented:
13112 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13113 			if (mctl_present)
13114 				freeb(first_mp);
13115 			goto slow_done;
13116 		}
13117 		/*
13118 		 * Make sure that first_mp points back to mp as
13119 		 * the mp we came in with could have changed in
13120 		 * ip_rput_fragment().
13121 		 */
13122 		ASSERT(!mctl_present);
13123 		ipha = (ipha_t *)mp->b_rptr;
13124 		first_mp = mp;
13125 	}
13126 
13127 	/* Now we have a complete datagram, destined for this machine. */
13128 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13129 
13130 	len = mp->b_wptr - mp->b_rptr;
13131 	/* Pull up a minimal TCP header, if necessary. */
13132 	if (len < (u1 + 20)) {
13133 tcppullup:
13134 		if (!pullupmsg(mp, u1 + 20)) {
13135 			BUMP_MIB(&ip_mib, ipInDiscards);
13136 			goto error;
13137 		}
13138 		ipha = (ipha_t *)mp->b_rptr;
13139 		len = mp->b_wptr - mp->b_rptr;
13140 	}
13141 
13142 	/*
13143 	 * Extract the offset field from the TCP header.  As usual, we
13144 	 * try to help the compiler more than the reader.
13145 	 */
13146 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13147 	if (offset != 5) {
13148 tcpoptions:
13149 		if (offset < 5) {
13150 			BUMP_MIB(&ip_mib, ipInDiscards);
13151 			goto error;
13152 		}
13153 		/*
13154 		 * There must be TCP options.
13155 		 * Make sure we can grab them.
13156 		 */
13157 		offset <<= 2;
13158 		offset += u1;
13159 		if (len < offset) {
13160 			if (!pullupmsg(mp, offset)) {
13161 				BUMP_MIB(&ip_mib, ipInDiscards);
13162 				goto error;
13163 			}
13164 			ipha = (ipha_t *)mp->b_rptr;
13165 			len = mp->b_wptr - rptr;
13166 		}
13167 	}
13168 
13169 	/* Get the total packet length in len, including headers. */
13170 	if (mp->b_cont) {
13171 multipkttcp:
13172 		len = msgdsize(mp);
13173 	}
13174 
13175 	/*
13176 	 * Check the TCP checksum by pulling together the pseudo-
13177 	 * header checksum, and passing it to ip_csum to be added in
13178 	 * with the TCP datagram.
13179 	 *
13180 	 * Since we are not using the hwcksum if available we must
13181 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13182 	 * If either of these fails along the way the mblk is freed.
13183 	 * If this logic ever changes and mblk is reused to say send
13184 	 * ICMP's back, then this flag may need to be cleared in
13185 	 * other places as well.
13186 	 */
13187 	DB_CKSUMFLAGS(mp) = 0;
13188 
13189 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13190 
13191 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13192 #ifdef	_BIG_ENDIAN
13193 	u1 += IPPROTO_TCP;
13194 #else
13195 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13196 #endif
13197 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13198 	/*
13199 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13200 	 */
13201 	IP_STAT(ip_in_sw_cksum);
13202 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13203 		BUMP_MIB(&ip_mib, tcpInErrs);
13204 		goto error;
13205 	}
13206 
13207 	IP_STAT(ip_tcp_slow_path);
13208 	goto try_again;
13209 #undef  iphs
13210 #undef  rptr
13211 
13212 error:
13213 	freemsg(first_mp);
13214 slow_done:
13215 	return (NULL);
13216 }
13217 
13218 /* ARGSUSED */
13219 static void
13220 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13221     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13222 {
13223 	conn_t		*connp;
13224 	uint32_t	sum;
13225 	uint32_t	u1;
13226 	ssize_t		len;
13227 	sctp_hdr_t	*sctph;
13228 	zoneid_t	zoneid = ire->ire_zoneid;
13229 	uint32_t	pktsum;
13230 	uint32_t	calcsum;
13231 	uint32_t	ports;
13232 	uint_t		ipif_seqid;
13233 	in6_addr_t	map_src, map_dst;
13234 	ill_t		*ill = (ill_t *)q->q_ptr;
13235 
13236 #define	rptr	((uchar_t *)ipha)
13237 
13238 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13239 
13240 	/* u1 is # words of IP options */
13241 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13242 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13243 
13244 	/* IP options present */
13245 	if (u1 > 0) {
13246 		goto ipoptions;
13247 	} else {
13248 		/* Check the IP header checksum.  */
13249 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13250 #define	uph	((uint16_t *)ipha)
13251 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13252 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13253 #undef	uph
13254 			/* finish doing IP checksum */
13255 			sum = (sum & 0xFFFF) + (sum >> 16);
13256 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13257 			/*
13258 			 * Don't verify header checksum if this packet
13259 			 * is coming back from AH/ESP as we already did it.
13260 			 */
13261 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13262 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13263 				goto error;
13264 			}
13265 		}
13266 		/*
13267 		 * Since there is no SCTP h/w cksum support yet, just
13268 		 * clear the flag.
13269 		 */
13270 		DB_CKSUMFLAGS(mp) = 0;
13271 	}
13272 
13273 	/*
13274 	 * Don't verify header checksum if this packet is coming
13275 	 * back from AH/ESP as we already did it.
13276 	 */
13277 	if (!mctl_present) {
13278 		UPDATE_IB_PKT_COUNT(ire);
13279 		ire->ire_last_used_time = lbolt;
13280 	}
13281 
13282 	/* packet part of fragmented IP packet? */
13283 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13284 	if (u1 & (IPH_MF | IPH_OFFSET))
13285 		goto fragmented;
13286 
13287 	/* u1 = IP header length (20 bytes) */
13288 	u1 = IP_SIMPLE_HDR_LENGTH;
13289 
13290 find_sctp_client:
13291 	/* Pullup if we don't have the sctp common header. */
13292 	len = MBLKL(mp);
13293 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13294 		if (mp->b_cont == NULL ||
13295 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13296 			BUMP_MIB(&ip_mib, ipInDiscards);
13297 			goto error;
13298 		}
13299 		ipha = (ipha_t *)mp->b_rptr;
13300 		len = MBLKL(mp);
13301 	}
13302 
13303 	sctph = (sctp_hdr_t *)(rptr + u1);
13304 #ifdef	DEBUG
13305 	if (!skip_sctp_cksum) {
13306 #endif
13307 		pktsum = sctph->sh_chksum;
13308 		sctph->sh_chksum = 0;
13309 		calcsum = sctp_cksum(mp, u1);
13310 		if (calcsum != pktsum) {
13311 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13312 			goto error;
13313 		}
13314 		sctph->sh_chksum = pktsum;
13315 #ifdef	DEBUG	/* skip_sctp_cksum */
13316 	}
13317 #endif
13318 	/* get the ports */
13319 	ports = *(uint32_t *)&sctph->sh_sport;
13320 
13321 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13322 	IRE_REFRELE(ire);
13323 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13324 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13325 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13326 	    mp)) == NULL) {
13327 		/* Check for raw socket or OOTB handling */
13328 		goto no_conn;
13329 	}
13330 
13331 	/* Found a client; up it goes */
13332 	BUMP_MIB(&ip_mib, ipInDelivers);
13333 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13334 	return;
13335 
13336 no_conn:
13337 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13338 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13339 	return;
13340 
13341 ipoptions:
13342 	DB_CKSUMFLAGS(mp) = 0;
13343 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13344 		goto slow_done;
13345 
13346 	UPDATE_IB_PKT_COUNT(ire);
13347 	ire->ire_last_used_time = lbolt;
13348 
13349 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13350 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13351 fragmented:
13352 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13353 			goto slow_done;
13354 		/*
13355 		 * Make sure that first_mp points back to mp as
13356 		 * the mp we came in with could have changed in
13357 		 * ip_rput_fragment().
13358 		 */
13359 		ASSERT(!mctl_present);
13360 		ipha = (ipha_t *)mp->b_rptr;
13361 		first_mp = mp;
13362 	}
13363 
13364 	/* Now we have a complete datagram, destined for this machine. */
13365 	u1 = IPH_HDR_LENGTH(ipha);
13366 	goto find_sctp_client;
13367 #undef  iphs
13368 #undef  rptr
13369 
13370 error:
13371 	freemsg(first_mp);
13372 slow_done:
13373 	IRE_REFRELE(ire);
13374 }
13375 
13376 #define	VER_BITS	0xF0
13377 #define	VERSION_6	0x60
13378 
13379 static boolean_t
13380 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13381     ipaddr_t *dstp)
13382 {
13383 	uint_t	opt_len;
13384 	ipha_t *ipha;
13385 	ssize_t len;
13386 	uint_t	pkt_len;
13387 
13388 	IP_STAT(ip_ipoptions);
13389 	ipha = *iphapp;
13390 
13391 #define	rptr    ((uchar_t *)ipha)
13392 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13393 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13394 		BUMP_MIB(&ip_mib, ipInIPv6);
13395 		freemsg(mp);
13396 		return (B_FALSE);
13397 	}
13398 
13399 	/* multiple mblk or too short */
13400 	pkt_len = ntohs(ipha->ipha_length);
13401 
13402 	/* Get the number of words of IP options in the IP header. */
13403 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13404 	if (opt_len) {
13405 		/* IP Options present!  Validate and process. */
13406 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13407 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13408 			goto done;
13409 		}
13410 		/*
13411 		 * Recompute complete header length and make sure we
13412 		 * have access to all of it.
13413 		 */
13414 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13415 		if (len > (mp->b_wptr - rptr)) {
13416 			if (len > pkt_len) {
13417 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13418 				goto done;
13419 			}
13420 			if (!pullupmsg(mp, len)) {
13421 				BUMP_MIB(&ip_mib, ipInDiscards);
13422 				goto done;
13423 			}
13424 			ipha = (ipha_t *)mp->b_rptr;
13425 		}
13426 		/*
13427 		 * Go off to ip_rput_options which returns the next hop
13428 		 * destination address, which may have been affected
13429 		 * by source routing.
13430 		 */
13431 		IP_STAT(ip_opt);
13432 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13433 			return (B_FALSE);
13434 		}
13435 	}
13436 	*iphapp = ipha;
13437 	return (B_TRUE);
13438 done:
13439 	/* clear b_prev - used by ip_mroute_decap */
13440 	mp->b_prev = NULL;
13441 	freemsg(mp);
13442 	return (B_FALSE);
13443 #undef  rptr
13444 }
13445 
13446 /*
13447  * Deal with the fact that there is no ire for the destination.
13448  * The incoming ill (in_ill) is passed in to ip_newroute only
13449  * in the case of packets coming from mobile ip forward tunnel.
13450  * It must be null otherwise.
13451  */
13452 static ire_t *
13453 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13454     ipaddr_t dst)
13455 {
13456 	ipha_t	*ipha;
13457 	ill_t	*ill;
13458 	ire_t	*ire;
13459 	boolean_t	check_multirt = B_FALSE;
13460 
13461 	ipha = (ipha_t *)mp->b_rptr;
13462 	ill = (ill_t *)q->q_ptr;
13463 
13464 	ASSERT(ill != NULL);
13465 	/*
13466 	 * No IRE for this destination, so it can't be for us.
13467 	 * Unless we are forwarding, drop the packet.
13468 	 * We have to let source routed packets through
13469 	 * since we don't yet know if they are 'ping -l'
13470 	 * packets i.e. if they will go out over the
13471 	 * same interface as they came in on.
13472 	 */
13473 	if (ll_multicast) {
13474 		freemsg(mp);
13475 		return (NULL);
13476 	}
13477 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13478 		BUMP_MIB(&ip_mib, ipForwProhibits);
13479 		freemsg(mp);
13480 		return (NULL);
13481 	}
13482 
13483 	/*
13484 	 * Mark this packet as having originated externally.
13485 	 *
13486 	 * For non-forwarding code path, ire_send later double
13487 	 * checks this interface to see if it is still exists
13488 	 * post-ARP resolution.
13489 	 *
13490 	 * Also, IPQOS uses this to differentiate between
13491 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13492 	 * QOS packet processing in ip_wput_attach_llhdr().
13493 	 * The QoS module can mark the b_band for a fastpath message
13494 	 * or the dl_priority field in a unitdata_req header for
13495 	 * CoS marking. This info can only be found in
13496 	 * ip_wput_attach_llhdr().
13497 	 */
13498 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13499 	/*
13500 	 * Clear the indication that this may have a hardware checksum
13501 	 * as we are not using it
13502 	 */
13503 	DB_CKSUMFLAGS(mp) = 0;
13504 
13505 	if (in_ill != NULL) {
13506 		/*
13507 		 * Now hand the packet to ip_newroute.
13508 		 */
13509 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13510 		return (NULL);
13511 	}
13512 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13513 	    MBLK_GETLABEL(mp));
13514 
13515 	if (ire == NULL && check_multirt) {
13516 		/* Let ip_newroute handle CGTP  */
13517 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13518 		return (NULL);
13519 	}
13520 
13521 	if (ire != NULL)
13522 		return (ire);
13523 
13524 	mp->b_prev = mp->b_next = 0;
13525 	/* send icmp unreachable */
13526 	q = WR(q);
13527 	/* Sent by forwarding path, and router is global zone */
13528 	if (ip_source_routed(ipha)) {
13529 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13530 		    GLOBAL_ZONEID);
13531 	} else {
13532 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13533 	}
13534 
13535 	return (NULL);
13536 
13537 }
13538 
13539 /*
13540  * check ip header length and align it.
13541  */
13542 static boolean_t
13543 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13544 {
13545 	ssize_t len;
13546 	ill_t *ill;
13547 	ipha_t	*ipha;
13548 
13549 	len = MBLKL(mp);
13550 
13551 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13552 		if (!OK_32PTR(mp->b_rptr))
13553 			IP_STAT(ip_notaligned1);
13554 		else
13555 			IP_STAT(ip_notaligned2);
13556 		/* Guard against bogus device drivers */
13557 		if (len < 0) {
13558 			/* clear b_prev - used by ip_mroute_decap */
13559 			mp->b_prev = NULL;
13560 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13561 			freemsg(mp);
13562 			return (B_FALSE);
13563 		}
13564 
13565 		if (ip_rput_pullups++ == 0) {
13566 			ill = (ill_t *)q->q_ptr;
13567 			ipha = (ipha_t *)mp->b_rptr;
13568 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13569 			    "ip_check_and_align_header: %s forced us to "
13570 			    " pullup pkt, hdr len %ld, hdr addr %p",
13571 			    ill->ill_name, len, ipha);
13572 		}
13573 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13574 			/* clear b_prev - used by ip_mroute_decap */
13575 			mp->b_prev = NULL;
13576 			BUMP_MIB(&ip_mib, ipInDiscards);
13577 			freemsg(mp);
13578 			return (B_FALSE);
13579 		}
13580 	}
13581 	return (B_TRUE);
13582 }
13583 
13584 static boolean_t
13585 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13586 {
13587 	ill_group_t	*ill_group;
13588 	ill_group_t	*ire_group;
13589 	queue_t 	*q;
13590 	ill_t		*ire_ill;
13591 	uint_t		ill_ifindex;
13592 
13593 	q = *qp;
13594 	/*
13595 	 * We need to check to make sure the packet came in
13596 	 * on the queue associated with the destination IRE.
13597 	 * Note that for multicast packets and broadcast packets sent to
13598 	 * a broadcast address which is shared between multiple interfaces
13599 	 * we should not do this since we just got a random broadcast ire.
13600 	 */
13601 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13602 		boolean_t check_multi = B_TRUE;
13603 
13604 		/*
13605 		 * This packet came in on an interface other than the
13606 		 * one associated with the destination address.
13607 		 * "Gateway" it to the appropriate interface here.
13608 		 * As long as the ills belong to the same group,
13609 		 * we don't consider them to arriving on the wrong
13610 		 * interface. Thus, when the switch is doing inbound
13611 		 * load spreading, we won't drop packets when we
13612 		 * are doing strict multihoming checks. Note, the
13613 		 * same holds true for 'usesrc groups' where the
13614 		 * destination address may belong to another interface
13615 		 * to allow multipathing to happen
13616 		 */
13617 		ill_group = ill->ill_group;
13618 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13619 		ill_ifindex = ill->ill_usesrc_ifindex;
13620 		ire_group = ire_ill->ill_group;
13621 
13622 		/*
13623 		 * If it's part of the same IPMP group, or if it's a legal
13624 		 * address on the 'usesrc' interface, then bypass strict
13625 		 * checks.
13626 		 */
13627 		if (ill_group != NULL && ill_group == ire_group) {
13628 			check_multi = B_FALSE;
13629 		} else if (ill_ifindex != 0 &&
13630 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13631 			check_multi = B_FALSE;
13632 		}
13633 
13634 		if (check_multi &&
13635 		    ip_strict_dst_multihoming &&
13636 		    ((ill->ill_flags &
13637 		    ire->ire_ipif->ipif_ill->ill_flags &
13638 		    ILLF_ROUTER) == 0)) {
13639 			/* Drop packet */
13640 			BUMP_MIB(&ip_mib, ipForwProhibits);
13641 			freemsg(mp);
13642 			return (B_TRUE);
13643 		}
13644 
13645 		/*
13646 		 * Change the queue (for non-virtual destination network
13647 		 * interfaces) and ip_rput_local will be called with the right
13648 		 * queue
13649 		 */
13650 		q = ire->ire_rfq;
13651 	}
13652 	/* Must be broadcast.  We'll take it. */
13653 	*qp = q;
13654 	return (B_FALSE);
13655 }
13656 
13657 ire_t *
13658 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13659 {
13660 	ipha_t	*ipha;
13661 	ipaddr_t ip_dst, ip_src;
13662 	ire_t	*src_ire = NULL;
13663 	ill_t	*stq_ill;
13664 	uint_t	hlen;
13665 	uint32_t sum;
13666 	queue_t	*dev_q;
13667 	boolean_t check_multirt = B_FALSE;
13668 
13669 
13670 	ipha = (ipha_t *)mp->b_rptr;
13671 
13672 	/*
13673 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13674 	 * The loopback address check for both src and dst has already
13675 	 * been checked in ip_input
13676 	 */
13677 	ip_dst = ntohl(dst);
13678 	ip_src = ntohl(ipha->ipha_src);
13679 
13680 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13681 	    IN_CLASSD(ip_src)) {
13682 		BUMP_MIB(&ip_mib, ipForwProhibits);
13683 		goto drop;
13684 	}
13685 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13686 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13687 
13688 	if (src_ire != NULL) {
13689 		BUMP_MIB(&ip_mib, ipForwProhibits);
13690 		goto drop;
13691 	}
13692 
13693 	/* No ire cache of nexthop. So first create one  */
13694 	if (ire == NULL) {
13695 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13696 		/*
13697 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13698 		 * is not set. So upon return from ire_forward
13699 		 * check_multirt should remain as false.
13700 		 */
13701 		ASSERT(!check_multirt);
13702 		if (ire == NULL) {
13703 			BUMP_MIB(&ip_mib, ipInDiscards);
13704 			mp->b_prev = mp->b_next = 0;
13705 			/* send icmp unreachable */
13706 			/* Sent by forwarding path, and router is global zone */
13707 			if (ip_source_routed(ipha)) {
13708 				icmp_unreachable(ill->ill_wq, mp,
13709 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13710 			} else {
13711 				icmp_unreachable(ill->ill_wq, mp,
13712 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13713 			}
13714 			return (ire);
13715 		}
13716 	}
13717 
13718 	/*
13719 	 * Forwarding fastpath exception case:
13720 	 * If either of the follwoing case is true, we take
13721 	 * the slowpath
13722 	 *	o forwarding is not enabled
13723 	 *	o incoming and outgoing interface are the same, or the same
13724 	 *	  IPMP group
13725 	 *	o corresponding ire is in incomplete state
13726 	 *	o packet needs fragmentation
13727 	 *
13728 	 * The codeflow from here on is thus:
13729 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13730 	 */
13731 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13732 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13733 	    !(ill->ill_flags & ILLF_ROUTER) ||
13734 	    (ill == stq_ill) ||
13735 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13736 	    (ire->ire_nce == NULL) ||
13737 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13738 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13739 	    ipha->ipha_ttl <= 1) {
13740 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13741 		    ipha, ill, B_FALSE);
13742 		return (ire);
13743 	}
13744 
13745 	DTRACE_PROBE4(ip4__forwarding__start,
13746 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13747 
13748 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13749 	    ill, stq_ill, ipha, mp, mp);
13750 
13751 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13752 
13753 	if (mp == NULL)
13754 		goto drop;
13755 
13756 	mp->b_datap->db_struioun.cksum.flags = 0;
13757 	/* Adjust the checksum to reflect the ttl decrement. */
13758 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13759 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13760 	ipha->ipha_ttl--;
13761 
13762 	dev_q = ire->ire_stq->q_next;
13763 	if ((dev_q->q_next != NULL ||
13764 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13765 		goto indiscard;
13766 	}
13767 
13768 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13769 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13770 
13771 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13772 		mblk_t *mpip = mp;
13773 
13774 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13775 		if (mp != NULL) {
13776 			DTRACE_PROBE4(ip4__physical__out__start,
13777 			    ill_t *, NULL, ill_t *, stq_ill,
13778 			    ipha_t *, ipha, mblk_t *, mp);
13779 			FW_HOOKS(ip4_physical_out_event,
13780 			    ipv4firewall_physical_out,
13781 			    NULL, stq_ill, ipha, mp, mpip);
13782 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13783 			    mp);
13784 			if (mp == NULL)
13785 				goto drop;
13786 
13787 			UPDATE_IB_PKT_COUNT(ire);
13788 			ire->ire_last_used_time = lbolt;
13789 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13790 			putnext(ire->ire_stq, mp);
13791 			return (ire);
13792 		}
13793 	}
13794 
13795 indiscard:
13796 	BUMP_MIB(&ip_mib, ipInDiscards);
13797 drop:
13798 	if (mp != NULL)
13799 		freemsg(mp);
13800 	if (src_ire != NULL)
13801 		ire_refrele(src_ire);
13802 	return (ire);
13803 
13804 }
13805 
13806 /*
13807  * This function is called in the forwarding slowpath, when
13808  * either the ire lacks the link-layer address, or the packet needs
13809  * further processing(eg. fragmentation), before transmission.
13810  */
13811 
13812 static void
13813 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13814     ill_t *ill, boolean_t ll_multicast)
13815 {
13816 	ill_group_t	*ill_group;
13817 	ill_group_t	*ire_group;
13818 	queue_t		*dev_q;
13819 	ire_t		*src_ire;
13820 
13821 	ASSERT(ire->ire_stq != NULL);
13822 
13823 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13824 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13825 
13826 	if (ll_multicast != 0)
13827 		goto drop_pkt;
13828 
13829 	/*
13830 	 * check if ipha_src is a broadcast address. Note that this
13831 	 * check is redundant when we get here from ip_fast_forward()
13832 	 * which has already done this check. However, since we can
13833 	 * also get here from ip_rput_process_broadcast() or, for
13834 	 * for the slow path through ip_fast_forward(), we perform
13835 	 * the check again for code-reusability
13836 	 */
13837 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13838 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13839 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13840 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13841 		if (src_ire != NULL)
13842 			ire_refrele(src_ire);
13843 		BUMP_MIB(&ip_mib, ipForwProhibits);
13844 		ip2dbg(("ip_rput_process_forward: Received packet with"
13845 		    " bad src/dst address on %s\n", ill->ill_name));
13846 		goto drop_pkt;
13847 	}
13848 
13849 	ill_group = ill->ill_group;
13850 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13851 	/*
13852 	 * Check if we want to forward this one at this time.
13853 	 * We allow source routed packets on a host provided that
13854 	 * they go out the same interface or same interface group
13855 	 * as they came in on.
13856 	 *
13857 	 * XXX To be quicker, we may wish to not chase pointers to
13858 	 * get the ILLF_ROUTER flag and instead store the
13859 	 * forwarding policy in the ire.  An unfortunate
13860 	 * side-effect of that would be requiring an ire flush
13861 	 * whenever the ILLF_ROUTER flag changes.
13862 	 */
13863 	if (((ill->ill_flags &
13864 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13865 	    ILLF_ROUTER) == 0) &&
13866 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13867 	    (ill_group != NULL && ill_group == ire_group)))) {
13868 		BUMP_MIB(&ip_mib, ipForwProhibits);
13869 		if (ip_source_routed(ipha)) {
13870 			q = WR(q);
13871 			/*
13872 			 * Clear the indication that this may have
13873 			 * hardware checksum as we are not using it.
13874 			 */
13875 			DB_CKSUMFLAGS(mp) = 0;
13876 			/* Sent by forwarding path, and router is global zone */
13877 			icmp_unreachable(q, mp,
13878 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13879 			return;
13880 		}
13881 		goto drop_pkt;
13882 	}
13883 
13884 	/* Packet is being forwarded. Turning off hwcksum flag. */
13885 	DB_CKSUMFLAGS(mp) = 0;
13886 	if (ip_g_send_redirects) {
13887 		/*
13888 		 * Check whether the incoming interface and outgoing
13889 		 * interface is part of the same group. If so,
13890 		 * send redirects.
13891 		 *
13892 		 * Check the source address to see if it originated
13893 		 * on the same logical subnet it is going back out on.
13894 		 * If so, we should be able to send it a redirect.
13895 		 * Avoid sending a redirect if the destination
13896 		 * is directly connected (i.e., ipha_dst is the same
13897 		 * as ire_gateway_addr or the ire_addr of the
13898 		 * nexthop IRE_CACHE ), or if the packet was source
13899 		 * routed out this interface.
13900 		 */
13901 		ipaddr_t src, nhop;
13902 		mblk_t	*mp1;
13903 		ire_t	*nhop_ire = NULL;
13904 
13905 		/*
13906 		 * Check whether ire_rfq and q are from the same ill
13907 		 * or if they are not same, they at least belong
13908 		 * to the same group. If so, send redirects.
13909 		 */
13910 		if ((ire->ire_rfq == q ||
13911 		    (ill_group != NULL && ill_group == ire_group)) &&
13912 		    !ip_source_routed(ipha)) {
13913 
13914 			nhop = (ire->ire_gateway_addr != 0 ?
13915 			    ire->ire_gateway_addr : ire->ire_addr);
13916 
13917 			if (ipha->ipha_dst == nhop) {
13918 				/*
13919 				 * We avoid sending a redirect if the
13920 				 * destination is directly connected
13921 				 * because it is possible that multiple
13922 				 * IP subnets may have been configured on
13923 				 * the link, and the source may not
13924 				 * be on the same subnet as ip destination,
13925 				 * even though they are on the same
13926 				 * physical link.
13927 				 */
13928 				goto sendit;
13929 			}
13930 
13931 			src = ipha->ipha_src;
13932 
13933 			/*
13934 			 * We look up the interface ire for the nexthop,
13935 			 * to see if ipha_src is in the same subnet
13936 			 * as the nexthop.
13937 			 *
13938 			 * Note that, if, in the future, IRE_CACHE entries
13939 			 * are obsoleted,  this lookup will not be needed,
13940 			 * as the ire passed to this function will be the
13941 			 * same as the nhop_ire computed below.
13942 			 */
13943 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13944 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13945 			    0, NULL, MATCH_IRE_TYPE);
13946 
13947 			if (nhop_ire != NULL) {
13948 				if ((src & nhop_ire->ire_mask) ==
13949 				    (nhop & nhop_ire->ire_mask)) {
13950 					/*
13951 					 * The source is directly connected.
13952 					 * Just copy the ip header (which is
13953 					 * in the first mblk)
13954 					 */
13955 					mp1 = copyb(mp);
13956 					if (mp1 != NULL) {
13957 						icmp_send_redirect(WR(q), mp1,
13958 						    nhop);
13959 					}
13960 				}
13961 				ire_refrele(nhop_ire);
13962 			}
13963 		}
13964 	}
13965 sendit:
13966 	dev_q = ire->ire_stq->q_next;
13967 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13968 		BUMP_MIB(&ip_mib, ipInDiscards);
13969 		freemsg(mp);
13970 		return;
13971 	}
13972 
13973 	ip_rput_forward(ire, ipha, mp, ill);
13974 	return;
13975 
13976 drop_pkt:
13977 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13978 	freemsg(mp);
13979 }
13980 
13981 ire_t *
13982 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13983     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13984 {
13985 	queue_t		*q;
13986 	uint16_t	hcksumflags;
13987 
13988 	q = *qp;
13989 
13990 	/*
13991 	 * Clear the indication that this may have hardware
13992 	 * checksum as we are not using it for forwarding.
13993 	 */
13994 	hcksumflags = DB_CKSUMFLAGS(mp);
13995 	DB_CKSUMFLAGS(mp) = 0;
13996 
13997 	/*
13998 	 * Directed broadcast forwarding: if the packet came in over a
13999 	 * different interface then it is routed out over we can forward it.
14000 	 */
14001 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14002 		ire_refrele(ire);
14003 		freemsg(mp);
14004 		BUMP_MIB(&ip_mib, ipInDiscards);
14005 		return (NULL);
14006 	}
14007 	/*
14008 	 * For multicast we have set dst to be INADDR_BROADCAST
14009 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14010 	 * only for broadcast packets.
14011 	 */
14012 	if (!CLASSD(ipha->ipha_dst)) {
14013 		ire_t *new_ire;
14014 		ipif_t *ipif;
14015 		/*
14016 		 * For ill groups, as the switch duplicates broadcasts
14017 		 * across all the ports, we need to filter out and
14018 		 * send up only one copy. There is one copy for every
14019 		 * broadcast address on each ill. Thus, we look for a
14020 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14021 		 * later to see whether this ill is eligible to receive
14022 		 * them or not. ill_nominate_bcast_rcv() nominates only
14023 		 * one set of IREs for receiving.
14024 		 */
14025 
14026 		ipif = ipif_get_next_ipif(NULL, ill);
14027 		if (ipif == NULL) {
14028 			ire_refrele(ire);
14029 			freemsg(mp);
14030 			BUMP_MIB(&ip_mib, ipInDiscards);
14031 			return (NULL);
14032 		}
14033 		new_ire = ire_ctable_lookup(dst, 0, 0,
14034 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
14035 		ipif_refrele(ipif);
14036 
14037 		if (new_ire != NULL) {
14038 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14039 				ire_refrele(ire);
14040 				ire_refrele(new_ire);
14041 				freemsg(mp);
14042 				BUMP_MIB(&ip_mib, ipInDiscards);
14043 				return (NULL);
14044 			}
14045 			/*
14046 			 * In the special case of multirouted broadcast
14047 			 * packets, we unconditionally need to "gateway"
14048 			 * them to the appropriate interface here.
14049 			 * In the normal case, this cannot happen, because
14050 			 * there is no broadcast IRE tagged with the
14051 			 * RTF_MULTIRT flag.
14052 			 */
14053 			if (new_ire->ire_flags & RTF_MULTIRT) {
14054 				ire_refrele(new_ire);
14055 				if (ire->ire_rfq != NULL) {
14056 					q = ire->ire_rfq;
14057 					*qp = q;
14058 				}
14059 			} else {
14060 				ire_refrele(ire);
14061 				ire = new_ire;
14062 			}
14063 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14064 			if (!ip_g_forward_directed_bcast) {
14065 				/*
14066 				 * Free the message if
14067 				 * ip_g_forward_directed_bcast is turned
14068 				 * off for non-local broadcast.
14069 				 */
14070 				ire_refrele(ire);
14071 				freemsg(mp);
14072 				BUMP_MIB(&ip_mib, ipInDiscards);
14073 				return (NULL);
14074 			}
14075 		} else {
14076 			/*
14077 			 * This CGTP packet successfully passed the
14078 			 * CGTP filter, but the related CGTP
14079 			 * broadcast IRE has not been found,
14080 			 * meaning that the redundant ipif is
14081 			 * probably down. However, if we discarded
14082 			 * this packet, its duplicate would be
14083 			 * filtered out by the CGTP filter so none
14084 			 * of them would get through. So we keep
14085 			 * going with this one.
14086 			 */
14087 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14088 			if (ire->ire_rfq != NULL) {
14089 				q = ire->ire_rfq;
14090 				*qp = q;
14091 			}
14092 		}
14093 	}
14094 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14095 		/*
14096 		 * Verify that there are not more then one
14097 		 * IRE_BROADCAST with this broadcast address which
14098 		 * has ire_stq set.
14099 		 * TODO: simplify, loop over all IRE's
14100 		 */
14101 		ire_t	*ire1;
14102 		int	num_stq = 0;
14103 		mblk_t	*mp1;
14104 
14105 		/* Find the first one with ire_stq set */
14106 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14107 		for (ire1 = ire; ire1 &&
14108 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14109 		    ire1 = ire1->ire_next)
14110 			;
14111 		if (ire1) {
14112 			ire_refrele(ire);
14113 			ire = ire1;
14114 			IRE_REFHOLD(ire);
14115 		}
14116 
14117 		/* Check if there are additional ones with stq set */
14118 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14119 			if (ire->ire_addr != ire1->ire_addr)
14120 				break;
14121 			if (ire1->ire_stq) {
14122 				num_stq++;
14123 				break;
14124 			}
14125 		}
14126 		rw_exit(&ire->ire_bucket->irb_lock);
14127 		if (num_stq == 1 && ire->ire_stq != NULL) {
14128 			ip1dbg(("ip_rput_process_broadcast: directed "
14129 			    "broadcast to 0x%x\n",
14130 			    ntohl(ire->ire_addr)));
14131 			mp1 = copymsg(mp);
14132 			if (mp1) {
14133 				switch (ipha->ipha_protocol) {
14134 				case IPPROTO_UDP:
14135 					ip_udp_input(q, mp1, ipha, ire, ill);
14136 					break;
14137 				default:
14138 					ip_proto_input(q, mp1, ipha, ire, ill);
14139 					break;
14140 				}
14141 			}
14142 			/*
14143 			 * Adjust ttl to 2 (1+1 - the forward engine
14144 			 * will decrement it by one.
14145 			 */
14146 			if (ip_csum_hdr(ipha)) {
14147 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14148 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14149 				freemsg(mp);
14150 				ire_refrele(ire);
14151 				return (NULL);
14152 			}
14153 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14154 			ipha->ipha_hdr_checksum = 0;
14155 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14156 			ip_rput_process_forward(q, mp, ire, ipha,
14157 			    ill, ll_multicast);
14158 			ire_refrele(ire);
14159 			return (NULL);
14160 		}
14161 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14162 		    ntohl(ire->ire_addr)));
14163 	}
14164 
14165 
14166 	/* Restore any hardware checksum flags */
14167 	DB_CKSUMFLAGS(mp) = hcksumflags;
14168 	return (ire);
14169 }
14170 
14171 /* ARGSUSED */
14172 static boolean_t
14173 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14174     int *ll_multicast, ipaddr_t *dstp)
14175 {
14176 	/*
14177 	 * Forward packets only if we have joined the allmulti
14178 	 * group on this interface.
14179 	 */
14180 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14181 		int retval;
14182 
14183 		/*
14184 		 * Clear the indication that this may have hardware
14185 		 * checksum as we are not using it.
14186 		 */
14187 		DB_CKSUMFLAGS(mp) = 0;
14188 		retval = ip_mforward(ill, ipha, mp);
14189 		/* ip_mforward updates mib variables if needed */
14190 		/* clear b_prev - used by ip_mroute_decap */
14191 		mp->b_prev = NULL;
14192 
14193 		switch (retval) {
14194 		case 0:
14195 			/*
14196 			 * pkt is okay and arrived on phyint.
14197 			 *
14198 			 * If we are running as a multicast router
14199 			 * we need to see all IGMP and/or PIM packets.
14200 			 */
14201 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14202 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14203 				goto done;
14204 			}
14205 			break;
14206 		case -1:
14207 			/* pkt is mal-formed, toss it */
14208 			goto drop_pkt;
14209 		case 1:
14210 			/* pkt is okay and arrived on a tunnel */
14211 			/*
14212 			 * If we are running a multicast router
14213 			 *  we need to see all igmp packets.
14214 			 */
14215 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14216 				*dstp = INADDR_BROADCAST;
14217 				*ll_multicast = 1;
14218 				return (B_FALSE);
14219 			}
14220 
14221 			goto drop_pkt;
14222 		}
14223 	}
14224 
14225 	ILM_WALKER_HOLD(ill);
14226 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14227 		/*
14228 		 * This might just be caused by the fact that
14229 		 * multiple IP Multicast addresses map to the same
14230 		 * link layer multicast - no need to increment counter!
14231 		 */
14232 		ILM_WALKER_RELE(ill);
14233 		freemsg(mp);
14234 		return (B_TRUE);
14235 	}
14236 	ILM_WALKER_RELE(ill);
14237 done:
14238 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14239 	/*
14240 	 * This assumes the we deliver to all streams for multicast
14241 	 * and broadcast packets.
14242 	 */
14243 	*dstp = INADDR_BROADCAST;
14244 	*ll_multicast = 1;
14245 	return (B_FALSE);
14246 drop_pkt:
14247 	ip2dbg(("ip_rput: drop pkt\n"));
14248 	freemsg(mp);
14249 	return (B_TRUE);
14250 }
14251 
14252 static boolean_t
14253 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14254     int *ll_multicast, mblk_t **mpp)
14255 {
14256 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14257 	boolean_t must_copy = B_FALSE;
14258 	struct iocblk   *iocp;
14259 	ipha_t		*ipha;
14260 
14261 #define	rptr    ((uchar_t *)ipha)
14262 
14263 	first_mp = *first_mpp;
14264 	mp = *mpp;
14265 
14266 	ASSERT(first_mp == mp);
14267 
14268 	/*
14269 	 * if db_ref > 1 then copymsg and free original. Packet may be
14270 	 * changed and do not want other entity who has a reference to this
14271 	 * message to trip over the changes. This is a blind change because
14272 	 * trying to catch all places that might change packet is too
14273 	 * difficult (since it may be a module above this one)
14274 	 *
14275 	 * This corresponds to the non-fast path case. We walk down the full
14276 	 * chain in this case, and check the db_ref count of all the dblks,
14277 	 * and do a copymsg if required. It is possible that the db_ref counts
14278 	 * of the data blocks in the mblk chain can be different.
14279 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14280 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14281 	 * 'snoop' is running.
14282 	 */
14283 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14284 		if (mp1->b_datap->db_ref > 1) {
14285 			must_copy = B_TRUE;
14286 			break;
14287 		}
14288 	}
14289 
14290 	if (must_copy) {
14291 		mp1 = copymsg(mp);
14292 		if (mp1 == NULL) {
14293 			for (mp1 = mp; mp1 != NULL;
14294 			    mp1 = mp1->b_cont) {
14295 				mp1->b_next = NULL;
14296 				mp1->b_prev = NULL;
14297 			}
14298 			freemsg(mp);
14299 			BUMP_MIB(&ip_mib, ipInDiscards);
14300 			return (B_TRUE);
14301 		}
14302 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14303 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14304 			/* Copy b_prev - used by ip_mroute_decap */
14305 			to_mp->b_prev = from_mp->b_prev;
14306 			from_mp->b_prev = NULL;
14307 		}
14308 		*first_mpp = first_mp = mp1;
14309 		freemsg(mp);
14310 		mp = mp1;
14311 		*mpp = mp1;
14312 	}
14313 
14314 	ipha = (ipha_t *)mp->b_rptr;
14315 
14316 	/*
14317 	 * previous code has a case for M_DATA.
14318 	 * We want to check how that happens.
14319 	 */
14320 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14321 	switch (first_mp->b_datap->db_type) {
14322 	case M_PROTO:
14323 	case M_PCPROTO:
14324 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14325 		    DL_UNITDATA_IND) {
14326 			/* Go handle anything other than data elsewhere. */
14327 			ip_rput_dlpi(q, mp);
14328 			return (B_TRUE);
14329 		}
14330 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14331 		/* Ditch the DLPI header. */
14332 		mp1 = mp->b_cont;
14333 		ASSERT(first_mp == mp);
14334 		*first_mpp = mp1;
14335 		freeb(mp);
14336 		*mpp = mp1;
14337 		return (B_FALSE);
14338 	case M_IOCACK:
14339 		ip1dbg(("got iocack "));
14340 		iocp = (struct iocblk *)mp->b_rptr;
14341 		switch (iocp->ioc_cmd) {
14342 		case DL_IOC_HDR_INFO:
14343 			ill = (ill_t *)q->q_ptr;
14344 			ill_fastpath_ack(ill, mp);
14345 			return (B_TRUE);
14346 		case SIOCSTUNPARAM:
14347 		case OSIOCSTUNPARAM:
14348 			/* Go through qwriter_ip */
14349 			break;
14350 		case SIOCGTUNPARAM:
14351 		case OSIOCGTUNPARAM:
14352 			ip_rput_other(NULL, q, mp, NULL);
14353 			return (B_TRUE);
14354 		default:
14355 			putnext(q, mp);
14356 			return (B_TRUE);
14357 		}
14358 		/* FALLTHRU */
14359 	case M_ERROR:
14360 	case M_HANGUP:
14361 		/*
14362 		 * Since this is on the ill stream we unconditionally
14363 		 * bump up the refcount
14364 		 */
14365 		ill_refhold(ill);
14366 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14367 		    B_FALSE);
14368 		return (B_TRUE);
14369 	case M_CTL:
14370 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14371 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14372 			IPHADA_M_CTL)) {
14373 			/*
14374 			 * It's an IPsec accelerated packet.
14375 			 * Make sure that the ill from which we received the
14376 			 * packet has enabled IPsec hardware acceleration.
14377 			 */
14378 			if (!(ill->ill_capabilities &
14379 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14380 				/* IPsec kstats: bean counter */
14381 				freemsg(mp);
14382 				return (B_TRUE);
14383 			}
14384 
14385 			/*
14386 			 * Make mp point to the mblk following the M_CTL,
14387 			 * then process according to type of mp.
14388 			 * After this processing, first_mp will point to
14389 			 * the data-attributes and mp to the pkt following
14390 			 * the M_CTL.
14391 			 */
14392 			mp = first_mp->b_cont;
14393 			if (mp == NULL) {
14394 				freemsg(first_mp);
14395 				return (B_TRUE);
14396 			}
14397 			/*
14398 			 * A Hardware Accelerated packet can only be M_DATA
14399 			 * ESP or AH packet.
14400 			 */
14401 			if (mp->b_datap->db_type != M_DATA) {
14402 				/* non-M_DATA IPsec accelerated packet */
14403 				IPSECHW_DEBUG(IPSECHW_PKT,
14404 				    ("non-M_DATA IPsec accelerated pkt\n"));
14405 				freemsg(first_mp);
14406 				return (B_TRUE);
14407 			}
14408 			ipha = (ipha_t *)mp->b_rptr;
14409 			if (ipha->ipha_protocol != IPPROTO_AH &&
14410 			    ipha->ipha_protocol != IPPROTO_ESP) {
14411 				IPSECHW_DEBUG(IPSECHW_PKT,
14412 				    ("non-M_DATA IPsec accelerated pkt\n"));
14413 				freemsg(first_mp);
14414 				return (B_TRUE);
14415 			}
14416 			*mpp = mp;
14417 			return (B_FALSE);
14418 		}
14419 		putnext(q, mp);
14420 		return (B_TRUE);
14421 	case M_FLUSH:
14422 		if (*mp->b_rptr & FLUSHW) {
14423 			*mp->b_rptr &= ~FLUSHR;
14424 			qreply(q, mp);
14425 			return (B_TRUE);
14426 		}
14427 		freemsg(mp);
14428 		return (B_TRUE);
14429 	case M_IOCNAK:
14430 		ip1dbg(("got iocnak "));
14431 		iocp = (struct iocblk *)mp->b_rptr;
14432 		switch (iocp->ioc_cmd) {
14433 		case DL_IOC_HDR_INFO:
14434 		case SIOCSTUNPARAM:
14435 		case OSIOCSTUNPARAM:
14436 			/*
14437 			 * Since this is on the ill stream we unconditionally
14438 			 * bump up the refcount
14439 			 */
14440 			ill_refhold(ill);
14441 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14442 			    CUR_OP, B_FALSE);
14443 			return (B_TRUE);
14444 		case SIOCGTUNPARAM:
14445 		case OSIOCGTUNPARAM:
14446 			ip_rput_other(NULL, q, mp, NULL);
14447 			return (B_TRUE);
14448 		default:
14449 			break;
14450 		}
14451 		/* FALLTHRU */
14452 	default:
14453 		putnext(q, mp);
14454 		return (B_TRUE);
14455 	}
14456 }
14457 
14458 /* Read side put procedure.  Packets coming from the wire arrive here. */
14459 void
14460 ip_rput(queue_t *q, mblk_t *mp)
14461 {
14462 	ill_t	*ill;
14463 	mblk_t	 *dmp = NULL;
14464 
14465 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14466 
14467 	ill = (ill_t *)q->q_ptr;
14468 
14469 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14470 		union DL_primitives *dl;
14471 
14472 		/*
14473 		 * Things are opening or closing. Only accept DLPI control
14474 		 * messages. In the open case, the ill->ill_ipif has not yet
14475 		 * been created. In the close case, things hanging off the
14476 		 * ill could have been freed already. In either case it
14477 		 * may not be safe to proceed further.
14478 		 */
14479 
14480 		dl = (union DL_primitives *)mp->b_rptr;
14481 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14482 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14483 			/*
14484 			 * Also SIOC[GS]TUN* ioctls can come here.
14485 			 */
14486 			inet_freemsg(mp);
14487 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14488 			    "ip_input_end: q %p (%S)", q, "uninit");
14489 			return;
14490 		}
14491 	}
14492 
14493 	/*
14494 	 * if db_ref > 1 then copymsg and free original. Packet may be
14495 	 * changed and we do not want the other entity who has a reference to
14496 	 * this message to trip over the changes. This is a blind change because
14497 	 * trying to catch all places that might change the packet is too
14498 	 * difficult.
14499 	 *
14500 	 * This corresponds to the fast path case, where we have a chain of
14501 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14502 	 * in the mblk chain. There doesn't seem to be a reason why a device
14503 	 * driver would send up data with varying db_ref counts in the mblk
14504 	 * chain. In any case the Fast path is a private interface, and our
14505 	 * drivers don't do such a thing. Given the above assumption, there is
14506 	 * no need to walk down the entire mblk chain (which could have a
14507 	 * potential performance problem)
14508 	 */
14509 	if (mp->b_datap->db_ref > 1) {
14510 		mblk_t  *mp1;
14511 		boolean_t adjusted = B_FALSE;
14512 		IP_STAT(ip_db_ref);
14513 
14514 		/*
14515 		 * The IP_RECVSLLA option depends on having the link layer
14516 		 * header. First check that:
14517 		 * a> the underlying device is of type ether, since this
14518 		 * option is currently supported only over ethernet.
14519 		 * b> there is enough room to copy over the link layer header.
14520 		 *
14521 		 * Once the checks are done, adjust rptr so that the link layer
14522 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14523 		 * be returned by some non-ethernet drivers but in this case the
14524 		 * second check will fail.
14525 		 */
14526 		if (ill->ill_type == IFT_ETHER &&
14527 		    (mp->b_rptr - mp->b_datap->db_base) >=
14528 		    sizeof (struct ether_header)) {
14529 			mp->b_rptr -= sizeof (struct ether_header);
14530 			adjusted = B_TRUE;
14531 		}
14532 		mp1 = copymsg(mp);
14533 		if (mp1 == NULL) {
14534 			mp->b_next = NULL;
14535 			/* clear b_prev - used by ip_mroute_decap */
14536 			mp->b_prev = NULL;
14537 			freemsg(mp);
14538 			BUMP_MIB(&ip_mib, ipInDiscards);
14539 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14540 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14541 			return;
14542 		}
14543 		if (adjusted) {
14544 			/*
14545 			 * Copy is done. Restore the pointer in the _new_ mblk
14546 			 */
14547 			mp1->b_rptr += sizeof (struct ether_header);
14548 		}
14549 		/* Copy b_prev - used by ip_mroute_decap */
14550 		mp1->b_prev = mp->b_prev;
14551 		mp->b_prev = NULL;
14552 		freemsg(mp);
14553 		mp = mp1;
14554 	}
14555 	if (DB_TYPE(mp) == M_DATA) {
14556 		dmp = mp;
14557 	} else if (DB_TYPE(mp) == M_PROTO &&
14558 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14559 		dmp = mp->b_cont;
14560 	}
14561 	if (dmp != NULL) {
14562 		/*
14563 		 * IP header ptr not aligned?
14564 		 * OR IP header not complete in first mblk
14565 		 */
14566 		if (!OK_32PTR(dmp->b_rptr) ||
14567 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14568 			if (!ip_check_and_align_header(q, dmp))
14569 				return;
14570 		}
14571 	}
14572 
14573 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14574 	    "ip_rput_end: q %p (%S)", q, "end");
14575 
14576 	ip_input(ill, NULL, mp, NULL);
14577 }
14578 
14579 /*
14580  * Direct read side procedure capable of dealing with chains. GLDv3 based
14581  * drivers call this function directly with mblk chains while STREAMS
14582  * read side procedure ip_rput() calls this for single packet with ip_ring
14583  * set to NULL to process one packet at a time.
14584  *
14585  * The ill will always be valid if this function is called directly from
14586  * the driver.
14587  *
14588  * If ip_input() is called from GLDv3:
14589  *
14590  *   - This must be a non-VLAN IP stream.
14591  *   - 'mp' is either an untagged or a special priority-tagged packet.
14592  *   - Any VLAN tag that was in the MAC header has been stripped.
14593  *
14594  * Thus, there is no need to adjust b_rptr in this function.
14595  */
14596 /* ARGSUSED */
14597 void
14598 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14599     struct mac_header_info_s *mhip)
14600 {
14601 	ipaddr_t		dst = NULL;
14602 	ipaddr_t		prev_dst;
14603 	ire_t			*ire = NULL;
14604 	ipha_t			*ipha;
14605 	uint_t			pkt_len;
14606 	ssize_t			len;
14607 	uint_t			opt_len;
14608 	int			ll_multicast;
14609 	int			cgtp_flt_pkt;
14610 	queue_t			*q = ill->ill_rq;
14611 	squeue_t		*curr_sqp = NULL;
14612 	mblk_t 			*head = NULL;
14613 	mblk_t			*tail = NULL;
14614 	mblk_t			*first_mp;
14615 	mblk_t 			*mp;
14616 	int			cnt = 0;
14617 
14618 	ASSERT(mp_chain != NULL);
14619 	ASSERT(ill != NULL);
14620 
14621 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14622 
14623 #define	rptr	((uchar_t *)ipha)
14624 
14625 	while (mp_chain != NULL) {
14626 		first_mp = mp = mp_chain;
14627 		mp_chain = mp_chain->b_next;
14628 		mp->b_next = NULL;
14629 		ll_multicast = 0;
14630 
14631 		/*
14632 		 * We do ire caching from one iteration to
14633 		 * another. In the event the packet chain contains
14634 		 * all packets from the same dst, this caching saves
14635 		 * an ire_cache_lookup for each of the succeeding
14636 		 * packets in a packet chain.
14637 		 */
14638 		prev_dst = dst;
14639 
14640 		/*
14641 		 * ip_input fast path
14642 		 */
14643 
14644 		/* mblk type is not M_DATA */
14645 		if (mp->b_datap->db_type != M_DATA) {
14646 			if (ip_rput_process_notdata(q, &first_mp, ill,
14647 			    &ll_multicast, &mp))
14648 				continue;
14649 		}
14650 
14651 		/* Make sure its an M_DATA and that its aligned */
14652 		ASSERT(mp->b_datap->db_type == M_DATA);
14653 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14654 
14655 		ipha = (ipha_t *)mp->b_rptr;
14656 		len = mp->b_wptr - rptr;
14657 
14658 		BUMP_MIB(&ip_mib, ipInReceives);
14659 
14660 
14661 		/* multiple mblk or too short */
14662 		pkt_len = ntohs(ipha->ipha_length);
14663 		len -= pkt_len;
14664 		if (len != 0) {
14665 			/*
14666 			 * Make sure we have data length consistent
14667 			 * with the IP header.
14668 			 */
14669 			if (mp->b_cont == NULL) {
14670 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14671 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14672 					ip2dbg(("ip_input: drop pkt\n"));
14673 					freemsg(mp);
14674 					continue;
14675 				}
14676 				mp->b_wptr = rptr + pkt_len;
14677 			} else if (len += msgdsize(mp->b_cont)) {
14678 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14679 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14680 					ip2dbg(("ip_input: drop pkt\n"));
14681 					freemsg(mp);
14682 					continue;
14683 				}
14684 				(void) adjmsg(mp, -len);
14685 				IP_STAT(ip_multimblk3);
14686 			}
14687 		}
14688 
14689 		/* Obtain the dst of the current packet */
14690 		dst = ipha->ipha_dst;
14691 
14692 		if (IP_LOOPBACK_ADDR(dst) ||
14693 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14694 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14695 			cmn_err(CE_CONT, "dst %X src %X\n",
14696 			    dst, ipha->ipha_src);
14697 			freemsg(mp);
14698 			continue;
14699 		}
14700 
14701 		/*
14702 		 * The event for packets being received from a 'physical'
14703 		 * interface is placed after validation of the source and/or
14704 		 * destination address as being local so that packets can be
14705 		 * redirected to loopback addresses using ipnat.
14706 		 */
14707 		DTRACE_PROBE4(ip4__physical__in__start,
14708 		    ill_t *, ill, ill_t *, NULL,
14709 		    ipha_t *, ipha, mblk_t *, first_mp);
14710 
14711 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14712 		    ill, NULL, ipha, first_mp, mp);
14713 
14714 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14715 
14716 		if (first_mp == NULL) {
14717 			continue;
14718 		}
14719 		dst = ipha->ipha_dst;
14720 
14721 		/*
14722 		 * Attach any necessary label information to
14723 		 * this packet
14724 		 */
14725 		if (is_system_labeled() &&
14726 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14727 			BUMP_MIB(&ip_mib, ipInDiscards);
14728 			freemsg(mp);
14729 			continue;
14730 		}
14731 
14732 		/*
14733 		 * Reuse the cached ire only if the ipha_dst of the previous
14734 		 * packet is the same as the current packet AND it is not
14735 		 * INADDR_ANY.
14736 		 */
14737 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14738 		    (ire != NULL)) {
14739 			ire_refrele(ire);
14740 			ire = NULL;
14741 		}
14742 		opt_len = ipha->ipha_version_and_hdr_length -
14743 		    IP_SIMPLE_HDR_VERSION;
14744 
14745 		/*
14746 		 * Check to see if we can take the fastpath.
14747 		 * That is possible if the following conditions are met
14748 		 *	o Tsol disabled
14749 		 *	o CGTP disabled
14750 		 *	o ipp_action_count is 0
14751 		 *	o Mobile IP not running
14752 		 *	o no options in the packet
14753 		 *	o not a RSVP packet
14754 		 * 	o not a multicast packet
14755 		 */
14756 		if (!is_system_labeled() &&
14757 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14758 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14759 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14760 		    !ll_multicast && !CLASSD(dst)) {
14761 			if (ire == NULL)
14762 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14763 
14764 			/* incoming packet is for forwarding */
14765 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14766 				ire = ip_fast_forward(ire, dst, ill, mp);
14767 				continue;
14768 			}
14769 			/* incoming packet is for local consumption */
14770 			if (ire->ire_type & IRE_LOCAL)
14771 				goto local;
14772 		}
14773 
14774 		/*
14775 		 * Disable ire caching for anything more complex
14776 		 * than the simple fast path case we checked for above.
14777 		 */
14778 		if (ire != NULL) {
14779 			ire_refrele(ire);
14780 			ire = NULL;
14781 		}
14782 
14783 		/* Full-blown slow path */
14784 		if (opt_len != 0) {
14785 			if (len != 0)
14786 				IP_STAT(ip_multimblk4);
14787 			else
14788 				IP_STAT(ip_ipoptions);
14789 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14790 				continue;
14791 		}
14792 
14793 		/*
14794 		 * Invoke the CGTP (multirouting) filtering module to process
14795 		 * the incoming packet. Packets identified as duplicates
14796 		 * must be discarded. Filtering is active only if the
14797 		 * the ip_cgtp_filter ndd variable is non-zero.
14798 		 */
14799 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14800 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14801 			cgtp_flt_pkt =
14802 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14803 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14804 				freemsg(first_mp);
14805 				continue;
14806 			}
14807 		}
14808 
14809 		/*
14810 		 * If rsvpd is running, let RSVP daemon handle its processing
14811 		 * and forwarding of RSVP multicast/unicast packets.
14812 		 * If rsvpd is not running but mrouted is running, RSVP
14813 		 * multicast packets are forwarded as multicast traffic
14814 		 * and RSVP unicast packets are forwarded by unicast router.
14815 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14816 		 * packets are not forwarded, but the unicast packets are
14817 		 * forwarded like unicast traffic.
14818 		 */
14819 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14820 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14821 			/* RSVP packet and rsvpd running. Treat as ours */
14822 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14823 			/*
14824 			 * This assumes that we deliver to all streams for
14825 			 * multicast and broadcast packets.
14826 			 * We have to force ll_multicast to 1 to handle the
14827 			 * M_DATA messages passed in from ip_mroute_decap.
14828 			 */
14829 			dst = INADDR_BROADCAST;
14830 			ll_multicast = 1;
14831 		} else if (CLASSD(dst)) {
14832 			/* packet is multicast */
14833 			mp->b_next = NULL;
14834 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14835 			    &ll_multicast, &dst))
14836 				continue;
14837 		}
14838 
14839 
14840 		/*
14841 		 * Check if the packet is coming from the Mobile IP
14842 		 * forward tunnel interface
14843 		 */
14844 		if (ill->ill_srcif_refcnt > 0) {
14845 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14846 			    NULL, ill, MATCH_IRE_TYPE);
14847 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14848 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14849 
14850 				/* We need to resolve the link layer info */
14851 				ire_refrele(ire);
14852 				ire = NULL;
14853 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14854 				    ll_multicast, dst);
14855 				continue;
14856 			}
14857 		}
14858 
14859 		if (ire == NULL) {
14860 			ire = ire_cache_lookup(dst, ALL_ZONES,
14861 			    MBLK_GETLABEL(mp));
14862 		}
14863 
14864 		/*
14865 		 * If mipagent is running and reverse tunnel is created as per
14866 		 * mobile node request, then any packet coming through the
14867 		 * incoming interface from the mobile-node, should be reverse
14868 		 * tunneled to it's home agent except those that are destined
14869 		 * to foreign agent only.
14870 		 * This needs source address based ire lookup. The routing
14871 		 * entries for source address based lookup are only created by
14872 		 * mipagent program only when a reverse tunnel is created.
14873 		 * Reference : RFC2002, RFC2344
14874 		 */
14875 		if (ill->ill_mrtun_refcnt > 0) {
14876 			ipaddr_t	srcaddr;
14877 			ire_t		*tmp_ire;
14878 
14879 			tmp_ire = ire;	/* Save, we might need it later */
14880 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14881 			    ire->ire_type != IRE_BROADCAST)) {
14882 				srcaddr = ipha->ipha_src;
14883 				ire = ire_mrtun_lookup(srcaddr, ill);
14884 				if (ire != NULL) {
14885 					/*
14886 					 * Should not be getting iphada packet
14887 					 * here. we should only get those for
14888 					 * IRE_LOCAL traffic, excluded above.
14889 					 * Fail-safe (drop packet) in the event
14890 					 * hardware is misbehaving.
14891 					 */
14892 					if (first_mp != mp) {
14893 						/* IPsec KSTATS: beancount me */
14894 						freemsg(first_mp);
14895 					} else {
14896 						/*
14897 						 * This packet must be forwarded
14898 						 * to Reverse Tunnel
14899 						 */
14900 						ip_mrtun_forward(ire, ill, mp);
14901 					}
14902 					ire_refrele(ire);
14903 					ire = NULL;
14904 					if (tmp_ire != NULL) {
14905 						ire_refrele(tmp_ire);
14906 						tmp_ire = NULL;
14907 					}
14908 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14909 					    "ip_input_end: q %p (%S)",
14910 					    q, "uninit");
14911 					continue;
14912 				}
14913 			}
14914 			/*
14915 			 * If this packet is from a non-mobilenode  or a
14916 			 * mobile-node which does not request reverse
14917 			 * tunnel service
14918 			 */
14919 			ire = tmp_ire;
14920 		}
14921 
14922 
14923 		/*
14924 		 * If we reach here that means the incoming packet satisfies
14925 		 * one of the following conditions:
14926 		 *   - packet is from a mobile node which does not request
14927 		 *	reverse tunnel
14928 		 *   - packet is from a non-mobile node, which is the most
14929 		 *	common case
14930 		 *   - packet is from a reverse tunnel enabled mobile node
14931 		 *	and destined to foreign agent only
14932 		 */
14933 
14934 		if (ire == NULL) {
14935 			/*
14936 			 * No IRE for this destination, so it can't be for us.
14937 			 * Unless we are forwarding, drop the packet.
14938 			 * We have to let source routed packets through
14939 			 * since we don't yet know if they are 'ping -l'
14940 			 * packets i.e. if they will go out over the
14941 			 * same interface as they came in on.
14942 			 */
14943 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14944 			if (ire == NULL)
14945 				continue;
14946 		}
14947 
14948 		/*
14949 		 * Broadcast IRE may indicate either broadcast or
14950 		 * multicast packet
14951 		 */
14952 		if (ire->ire_type == IRE_BROADCAST) {
14953 			/*
14954 			 * Skip broadcast checks if packet is UDP multicast;
14955 			 * we'd rather not enter ip_rput_process_broadcast()
14956 			 * unless the packet is broadcast for real, since
14957 			 * that routine is a no-op for multicast.
14958 			 */
14959 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14960 			    !CLASSD(ipha->ipha_dst)) {
14961 				ire = ip_rput_process_broadcast(&q, mp,
14962 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14963 				    ll_multicast);
14964 				if (ire == NULL)
14965 					continue;
14966 			}
14967 		} else if (ire->ire_stq != NULL) {
14968 			/* fowarding? */
14969 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14970 			    ll_multicast);
14971 			/* ip_rput_process_forward consumed the packet */
14972 			continue;
14973 		}
14974 
14975 local:
14976 		/* packet not for us */
14977 		if (ire->ire_rfq != q) {
14978 			if (ip_rput_notforus(&q, mp, ire, ill))
14979 				continue;
14980 		}
14981 
14982 		switch (ipha->ipha_protocol) {
14983 		case IPPROTO_TCP:
14984 			ASSERT(first_mp == mp);
14985 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14986 				mp, 0, q, ip_ring)) != NULL) {
14987 				if (curr_sqp == NULL) {
14988 					curr_sqp = GET_SQUEUE(mp);
14989 					ASSERT(cnt == 0);
14990 					cnt++;
14991 					head = tail = mp;
14992 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14993 					ASSERT(tail != NULL);
14994 					cnt++;
14995 					tail->b_next = mp;
14996 					tail = mp;
14997 				} else {
14998 					/*
14999 					 * A different squeue. Send the
15000 					 * chain for the previous squeue on
15001 					 * its way. This shouldn't happen
15002 					 * often unless interrupt binding
15003 					 * changes.
15004 					 */
15005 					IP_STAT(ip_input_multi_squeue);
15006 					squeue_enter_chain(curr_sqp, head,
15007 					    tail, cnt, SQTAG_IP_INPUT);
15008 					curr_sqp = GET_SQUEUE(mp);
15009 					head = mp;
15010 					tail = mp;
15011 					cnt = 1;
15012 				}
15013 			}
15014 			continue;
15015 		case IPPROTO_UDP:
15016 			ASSERT(first_mp == mp);
15017 			ip_udp_input(q, mp, ipha, ire, ill);
15018 			continue;
15019 		case IPPROTO_SCTP:
15020 			ASSERT(first_mp == mp);
15021 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15022 			    q, dst);
15023 			/* ire has been released by ip_sctp_input */
15024 			ire = NULL;
15025 			continue;
15026 		default:
15027 			ip_proto_input(q, first_mp, ipha, ire, ill);
15028 			continue;
15029 		}
15030 	}
15031 
15032 	if (ire != NULL)
15033 		ire_refrele(ire);
15034 
15035 	if (head != NULL)
15036 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15037 
15038 	/*
15039 	 * This code is there just to make netperf/ttcp look good.
15040 	 *
15041 	 * Its possible that after being in polling mode (and having cleared
15042 	 * the backlog), squeues have turned the interrupt frequency higher
15043 	 * to improve latency at the expense of more CPU utilization (less
15044 	 * packets per interrupts or more number of interrupts). Workloads
15045 	 * like ttcp/netperf do manage to tickle polling once in a while
15046 	 * but for the remaining time, stay in higher interrupt mode since
15047 	 * their packet arrival rate is pretty uniform and this shows up
15048 	 * as higher CPU utilization. Since people care about CPU utilization
15049 	 * while running netperf/ttcp, turn the interrupt frequency back to
15050 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15051 	 */
15052 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15053 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15054 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15055 			ip_ring->rr_blank(ip_ring->rr_handle,
15056 			    ip_ring->rr_normal_blank_time,
15057 			    ip_ring->rr_normal_pkt_cnt);
15058 		}
15059 	}
15060 
15061 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15062 	    "ip_input_end: q %p (%S)", q, "end");
15063 #undef	rptr
15064 }
15065 
15066 static void
15067 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15068     t_uscalar_t err)
15069 {
15070 	if (dl_err == DL_SYSERR) {
15071 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15072 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15073 		    ill->ill_name, dlpi_prim_str(prim), err);
15074 		return;
15075 	}
15076 
15077 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15078 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15079 	    dlpi_err_str(dl_err));
15080 }
15081 
15082 /*
15083  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15084  * than DL_UNITDATA_IND messages. If we need to process this message
15085  * exclusively, we call qwriter_ip, in which case we also need to call
15086  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15087  */
15088 void
15089 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15090 {
15091 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15092 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15093 	ill_t		*ill;
15094 
15095 	ip1dbg(("ip_rput_dlpi"));
15096 	ill = (ill_t *)q->q_ptr;
15097 	switch (dloa->dl_primitive) {
15098 	case DL_ERROR_ACK:
15099 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15100 		    "%s (0x%x), unix %u\n", ill->ill_name,
15101 		    dlpi_prim_str(dlea->dl_error_primitive),
15102 		    dlea->dl_error_primitive,
15103 		    dlpi_err_str(dlea->dl_errno),
15104 		    dlea->dl_errno,
15105 		    dlea->dl_unix_errno));
15106 		switch (dlea->dl_error_primitive) {
15107 		case DL_UNBIND_REQ:
15108 			mutex_enter(&ill->ill_lock);
15109 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15110 			cv_signal(&ill->ill_cv);
15111 			mutex_exit(&ill->ill_lock);
15112 			/* FALLTHRU */
15113 		case DL_NOTIFY_REQ:
15114 		case DL_ATTACH_REQ:
15115 		case DL_DETACH_REQ:
15116 		case DL_INFO_REQ:
15117 		case DL_BIND_REQ:
15118 		case DL_ENABMULTI_REQ:
15119 		case DL_PHYS_ADDR_REQ:
15120 		case DL_CAPABILITY_REQ:
15121 		case DL_CONTROL_REQ:
15122 			/*
15123 			 * Refhold the ill to match qwriter_ip which does a
15124 			 * refrele. Since this is on the ill stream we
15125 			 * unconditionally bump up the refcount without
15126 			 * checking for ILL_CAN_LOOKUP
15127 			 */
15128 			ill_refhold(ill);
15129 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15130 			    CUR_OP, B_FALSE);
15131 			return;
15132 		case DL_DISABMULTI_REQ:
15133 			freemsg(mp);	/* Don't want to pass this up */
15134 			return;
15135 		default:
15136 			break;
15137 		}
15138 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15139 		    dlea->dl_errno, dlea->dl_unix_errno);
15140 		freemsg(mp);
15141 		return;
15142 	case DL_INFO_ACK:
15143 	case DL_BIND_ACK:
15144 	case DL_PHYS_ADDR_ACK:
15145 	case DL_NOTIFY_ACK:
15146 	case DL_CAPABILITY_ACK:
15147 	case DL_CONTROL_ACK:
15148 		/*
15149 		 * Refhold the ill to match qwriter_ip which does a refrele
15150 		 * Since this is on the ill stream we unconditionally
15151 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15152 		 */
15153 		ill_refhold(ill);
15154 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15155 		    CUR_OP, B_FALSE);
15156 		return;
15157 	case DL_NOTIFY_IND:
15158 		ill_refhold(ill);
15159 		/*
15160 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15161 		 * relation to the current ioctl in progress (if any). Hence we
15162 		 * pass in NEW_OP in this case.
15163 		 */
15164 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15165 		    NEW_OP, B_FALSE);
15166 		return;
15167 	case DL_OK_ACK:
15168 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15169 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15170 		switch (dloa->dl_correct_primitive) {
15171 		case DL_UNBIND_REQ:
15172 			mutex_enter(&ill->ill_lock);
15173 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15174 			cv_signal(&ill->ill_cv);
15175 			mutex_exit(&ill->ill_lock);
15176 			/* FALLTHRU */
15177 		case DL_ATTACH_REQ:
15178 		case DL_DETACH_REQ:
15179 			/*
15180 			 * Refhold the ill to match qwriter_ip which does a
15181 			 * refrele. Since this is on the ill stream we
15182 			 * unconditionally bump up the refcount
15183 			 */
15184 			ill_refhold(ill);
15185 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15186 			    CUR_OP, B_FALSE);
15187 			return;
15188 		case DL_ENABMULTI_REQ:
15189 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15190 				ill->ill_dlpi_multicast_state = IDS_OK;
15191 			break;
15192 
15193 		}
15194 		break;
15195 	default:
15196 		break;
15197 	}
15198 	freemsg(mp);
15199 }
15200 
15201 /*
15202  * Handling of DLPI messages that require exclusive access to the ipsq.
15203  *
15204  * Need to do ill_pending_mp_release on ioctl completion, which could
15205  * happen here. (along with mi_copy_done)
15206  */
15207 /* ARGSUSED */
15208 static void
15209 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15210 {
15211 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15212 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15213 	int		err = 0;
15214 	ill_t		*ill;
15215 	ipif_t		*ipif = NULL;
15216 	mblk_t		*mp1 = NULL;
15217 	conn_t		*connp = NULL;
15218 	t_uscalar_t	physaddr_req;
15219 	mblk_t		*mp_hw;
15220 	union DL_primitives *dlp;
15221 	boolean_t	success;
15222 	boolean_t	ioctl_aborted = B_FALSE;
15223 	boolean_t	log = B_TRUE;
15224 	hook_nic_event_t	*info;
15225 
15226 	ip1dbg(("ip_rput_dlpi_writer .."));
15227 	ill = (ill_t *)q->q_ptr;
15228 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15229 
15230 	ASSERT(IAM_WRITER_ILL(ill));
15231 
15232 	/*
15233 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15234 	 * both are null or non-null. However we can assert that only
15235 	 * after grabbing the ipsq_lock. So we don't make any assertion
15236 	 * here and in other places in the code.
15237 	 */
15238 	ipif = ipsq->ipsq_pending_ipif;
15239 	/*
15240 	 * The current ioctl could have been aborted by the user and a new
15241 	 * ioctl to bring up another ill could have started. We could still
15242 	 * get a response from the driver later.
15243 	 */
15244 	if (ipif != NULL && ipif->ipif_ill != ill)
15245 		ioctl_aborted = B_TRUE;
15246 
15247 	switch (dloa->dl_primitive) {
15248 	case DL_ERROR_ACK:
15249 		switch (dlea->dl_error_primitive) {
15250 		case DL_UNBIND_REQ:
15251 		case DL_ATTACH_REQ:
15252 		case DL_DETACH_REQ:
15253 		case DL_INFO_REQ:
15254 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15255 			break;
15256 		case DL_NOTIFY_REQ:
15257 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15258 			log = B_FALSE;
15259 			break;
15260 		case DL_PHYS_ADDR_REQ:
15261 			/*
15262 			 * For IPv6 only, there are two additional
15263 			 * phys_addr_req's sent to the driver to get the
15264 			 * IPv6 token and lla. This allows IP to acquire
15265 			 * the hardware address format for a given interface
15266 			 * without having built in knowledge of the hardware
15267 			 * address. ill_phys_addr_pend keeps track of the last
15268 			 * DL_PAR sent so we know which response we are
15269 			 * dealing with. ill_dlpi_done will update
15270 			 * ill_phys_addr_pend when it sends the next req.
15271 			 * We don't complete the IOCTL until all three DL_PARs
15272 			 * have been attempted, so set *_len to 0 and break.
15273 			 */
15274 			physaddr_req = ill->ill_phys_addr_pend;
15275 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15276 			if (physaddr_req == DL_IPV6_TOKEN) {
15277 				ill->ill_token_length = 0;
15278 				log = B_FALSE;
15279 				break;
15280 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15281 				ill->ill_nd_lla_len = 0;
15282 				log = B_FALSE;
15283 				break;
15284 			}
15285 			/*
15286 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15287 			 * We presumably have an IOCTL hanging out waiting
15288 			 * for completion. Find it and complete the IOCTL
15289 			 * with the error noted.
15290 			 * However, ill_dl_phys was called on an ill queue
15291 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15292 			 * set. But the ioctl is known to be pending on ill_wq.
15293 			 */
15294 			if (!ill->ill_ifname_pending)
15295 				break;
15296 			ill->ill_ifname_pending = 0;
15297 			if (!ioctl_aborted)
15298 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15299 			if (mp1 != NULL) {
15300 				/*
15301 				 * This operation (SIOCSLIFNAME) must have
15302 				 * happened on the ill. Assert there is no conn
15303 				 */
15304 				ASSERT(connp == NULL);
15305 				q = ill->ill_wq;
15306 			}
15307 			break;
15308 		case DL_BIND_REQ:
15309 			ill_dlpi_done(ill, DL_BIND_REQ);
15310 			if (ill->ill_ifname_pending)
15311 				break;
15312 			/*
15313 			 * Something went wrong with the bind.  We presumably
15314 			 * have an IOCTL hanging out waiting for completion.
15315 			 * Find it, take down the interface that was coming
15316 			 * up, and complete the IOCTL with the error noted.
15317 			 */
15318 			if (!ioctl_aborted)
15319 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15320 			if (mp1 != NULL) {
15321 				/*
15322 				 * This operation (SIOCSLIFFLAGS) must have
15323 				 * happened from a conn.
15324 				 */
15325 				ASSERT(connp != NULL);
15326 				q = CONNP_TO_WQ(connp);
15327 				if (ill->ill_move_in_progress) {
15328 					ILL_CLEAR_MOVE(ill);
15329 				}
15330 				(void) ipif_down(ipif, NULL, NULL);
15331 				/* error is set below the switch */
15332 			}
15333 			break;
15334 		case DL_ENABMULTI_REQ:
15335 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15336 
15337 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15338 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15339 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15340 				ipif_t *ipif;
15341 
15342 				log = B_FALSE;
15343 				printf("ip: joining multicasts failed (%d)"
15344 				    " on %s - will use link layer "
15345 				    "broadcasts for multicast\n",
15346 				    dlea->dl_errno, ill->ill_name);
15347 
15348 				/*
15349 				 * Set up the multicast mapping alone.
15350 				 * writer, so ok to access ill->ill_ipif
15351 				 * without any lock.
15352 				 */
15353 				ipif = ill->ill_ipif;
15354 				mutex_enter(&ill->ill_phyint->phyint_lock);
15355 				ill->ill_phyint->phyint_flags |=
15356 				    PHYI_MULTI_BCAST;
15357 				mutex_exit(&ill->ill_phyint->phyint_lock);
15358 
15359 				if (!ill->ill_isv6) {
15360 					(void) ipif_arp_setup_multicast(ipif,
15361 					    NULL);
15362 				} else {
15363 					(void) ipif_ndp_setup_multicast(ipif,
15364 					    NULL);
15365 				}
15366 			}
15367 			freemsg(mp);	/* Don't want to pass this up */
15368 			return;
15369 		case DL_CAPABILITY_REQ:
15370 		case DL_CONTROL_REQ:
15371 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15372 			    "DL_CAPABILITY/CONTROL REQ\n"));
15373 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15374 			ill->ill_dlpi_capab_state = IDS_FAILED;
15375 			freemsg(mp);
15376 			return;
15377 		}
15378 		/*
15379 		 * Note the error for IOCTL completion (mp1 is set when
15380 		 * ready to complete ioctl). If ill_ifname_pending_err is
15381 		 * set, an error occured during plumbing (ill_ifname_pending),
15382 		 * so we want to report that error.
15383 		 *
15384 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15385 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15386 		 * expected to get errack'd if the driver doesn't support
15387 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15388 		 * if these error conditions are encountered.
15389 		 */
15390 		if (mp1 != NULL) {
15391 			if (ill->ill_ifname_pending_err != 0)  {
15392 				err = ill->ill_ifname_pending_err;
15393 				ill->ill_ifname_pending_err = 0;
15394 			} else {
15395 				err = dlea->dl_unix_errno ?
15396 				    dlea->dl_unix_errno : ENXIO;
15397 			}
15398 		/*
15399 		 * If we're plumbing an interface and an error hasn't already
15400 		 * been saved, set ill_ifname_pending_err to the error passed
15401 		 * up. Ignore the error if log is B_FALSE (see comment above).
15402 		 */
15403 		} else if (log && ill->ill_ifname_pending &&
15404 		    ill->ill_ifname_pending_err == 0) {
15405 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15406 			dlea->dl_unix_errno : ENXIO;
15407 		}
15408 
15409 		if (log)
15410 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15411 			    dlea->dl_errno, dlea->dl_unix_errno);
15412 		break;
15413 	case DL_CAPABILITY_ACK: {
15414 		boolean_t reneg_flag = B_FALSE;
15415 		/* Call a routine to handle this one. */
15416 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15417 		/*
15418 		 * Check if the ACK is due to renegotiation case since we
15419 		 * will need to send a new CAPABILITY_REQ later.
15420 		 */
15421 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15422 			/* This is the ack for a renogiation case */
15423 			reneg_flag = B_TRUE;
15424 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15425 		}
15426 		ill_capability_ack(ill, mp);
15427 		if (reneg_flag)
15428 			ill_capability_probe(ill);
15429 		break;
15430 	}
15431 	case DL_CONTROL_ACK:
15432 		/* We treat all of these as "fire and forget" */
15433 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15434 		break;
15435 	case DL_INFO_ACK:
15436 		/* Call a routine to handle this one. */
15437 		ill_dlpi_done(ill, DL_INFO_REQ);
15438 		ip_ll_subnet_defaults(ill, mp);
15439 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15440 		return;
15441 	case DL_BIND_ACK:
15442 		/*
15443 		 * We should have an IOCTL waiting on this unless
15444 		 * sent by ill_dl_phys, in which case just return
15445 		 */
15446 		ill_dlpi_done(ill, DL_BIND_REQ);
15447 		if (ill->ill_ifname_pending)
15448 			break;
15449 
15450 		if (!ioctl_aborted)
15451 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15452 		if (mp1 == NULL)
15453 			break;
15454 		ASSERT(connp != NULL);
15455 		q = CONNP_TO_WQ(connp);
15456 
15457 		/*
15458 		 * We are exclusive. So nothing can change even after
15459 		 * we get the pending mp. If need be we can put it back
15460 		 * and restart, as in calling ipif_arp_up()  below.
15461 		 */
15462 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15463 
15464 		mutex_enter(&ill->ill_lock);
15465 
15466 		ill->ill_dl_up = 1;
15467 
15468 		if ((info = ill->ill_nic_event_info) != NULL) {
15469 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15470 			    "attached for %s\n", info->hne_event,
15471 			    ill->ill_name));
15472 			if (info->hne_data != NULL)
15473 				kmem_free(info->hne_data, info->hne_datalen);
15474 			kmem_free(info, sizeof (hook_nic_event_t));
15475 		}
15476 
15477 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15478 		if (info != NULL) {
15479 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15480 			info->hne_lif = 0;
15481 			info->hne_event = NE_UP;
15482 			info->hne_data = NULL;
15483 			info->hne_datalen = 0;
15484 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15485 		} else
15486 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15487 			    "event information for %s (ENOMEM)\n",
15488 			    ill->ill_name));
15489 
15490 		ill->ill_nic_event_info = info;
15491 
15492 		mutex_exit(&ill->ill_lock);
15493 
15494 		/*
15495 		 * Now bring up the resolver; when that is complete, we'll
15496 		 * create IREs.  Note that we intentionally mirror what
15497 		 * ipif_up() would have done, because we got here by way of
15498 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15499 		 */
15500 		if (ill->ill_isv6) {
15501 			/*
15502 			 * v6 interfaces.
15503 			 * Unlike ARP which has to do another bind
15504 			 * and attach, once we get here we are
15505 			 * done with NDP. Except in the case of
15506 			 * ILLF_XRESOLV, in which case we send an
15507 			 * AR_INTERFACE_UP to the external resolver.
15508 			 * If all goes well, the ioctl will complete
15509 			 * in ip_rput(). If there's an error, we
15510 			 * complete it here.
15511 			 */
15512 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15513 			    B_FALSE);
15514 			if (err == 0) {
15515 				if (ill->ill_flags & ILLF_XRESOLV) {
15516 					mutex_enter(&connp->conn_lock);
15517 					mutex_enter(&ill->ill_lock);
15518 					success = ipsq_pending_mp_add(
15519 					    connp, ipif, q, mp1, 0);
15520 					mutex_exit(&ill->ill_lock);
15521 					mutex_exit(&connp->conn_lock);
15522 					if (success) {
15523 						err = ipif_resolver_up(ipif,
15524 						    Res_act_initial);
15525 						if (err == EINPROGRESS) {
15526 							freemsg(mp);
15527 							return;
15528 						}
15529 						ASSERT(err != 0);
15530 						mp1 = ipsq_pending_mp_get(ipsq,
15531 						    &connp);
15532 						ASSERT(mp1 != NULL);
15533 					} else {
15534 						/* conn has started closing */
15535 						err = EINTR;
15536 					}
15537 				} else { /* Non XRESOLV interface */
15538 					(void) ipif_resolver_up(ipif,
15539 					    Res_act_initial);
15540 					err = ipif_up_done_v6(ipif);
15541 				}
15542 			}
15543 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15544 			/*
15545 			 * ARP and other v4 external resolvers.
15546 			 * Leave the pending mblk intact so that
15547 			 * the ioctl completes in ip_rput().
15548 			 */
15549 			mutex_enter(&connp->conn_lock);
15550 			mutex_enter(&ill->ill_lock);
15551 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15552 			mutex_exit(&ill->ill_lock);
15553 			mutex_exit(&connp->conn_lock);
15554 			if (success) {
15555 				err = ipif_resolver_up(ipif, Res_act_initial);
15556 				if (err == EINPROGRESS) {
15557 					freemsg(mp);
15558 					return;
15559 				}
15560 				ASSERT(err != 0);
15561 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15562 			} else {
15563 				/* The conn has started closing */
15564 				err = EINTR;
15565 			}
15566 		} else {
15567 			/*
15568 			 * This one is complete. Reply to pending ioctl.
15569 			 */
15570 			(void) ipif_resolver_up(ipif, Res_act_initial);
15571 			err = ipif_up_done(ipif);
15572 		}
15573 
15574 		if ((err == 0) && (ill->ill_up_ipifs)) {
15575 			err = ill_up_ipifs(ill, q, mp1);
15576 			if (err == EINPROGRESS) {
15577 				freemsg(mp);
15578 				return;
15579 			}
15580 		}
15581 
15582 		if (ill->ill_up_ipifs) {
15583 			ill_group_cleanup(ill);
15584 		}
15585 
15586 		break;
15587 	case DL_NOTIFY_IND: {
15588 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15589 		ire_t *ire;
15590 		boolean_t need_ire_walk_v4 = B_FALSE;
15591 		boolean_t need_ire_walk_v6 = B_FALSE;
15592 
15593 		/*
15594 		 * Change the address everywhere we need to.
15595 		 * What we're getting here is a link-level addr or phys addr.
15596 		 * The new addr is at notify + notify->dl_addr_offset
15597 		 * The address length is notify->dl_addr_length;
15598 		 */
15599 		switch (notify->dl_notification) {
15600 		case DL_NOTE_PHYS_ADDR:
15601 			mp_hw = copyb(mp);
15602 			if (mp_hw == NULL) {
15603 				err = ENOMEM;
15604 				break;
15605 			}
15606 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15607 			/*
15608 			 * We currently don't support changing
15609 			 * the token via DL_NOTIFY_IND.
15610 			 * When we do support it, we have to consider
15611 			 * what the implications are with respect to
15612 			 * the token and the link local address.
15613 			 */
15614 			mutex_enter(&ill->ill_lock);
15615 			if (dlp->notify_ind.dl_data ==
15616 			    DL_IPV6_LINK_LAYER_ADDR) {
15617 				if (ill->ill_nd_lla_mp != NULL)
15618 					freemsg(ill->ill_nd_lla_mp);
15619 				ill->ill_nd_lla_mp = mp_hw;
15620 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15621 				    dlp->notify_ind.dl_addr_offset;
15622 				ill->ill_nd_lla_len =
15623 				    dlp->notify_ind.dl_addr_length -
15624 				    ABS(ill->ill_sap_length);
15625 				mutex_exit(&ill->ill_lock);
15626 				break;
15627 			} else if (dlp->notify_ind.dl_data ==
15628 			    DL_CURR_PHYS_ADDR) {
15629 				if (ill->ill_phys_addr_mp != NULL)
15630 					freemsg(ill->ill_phys_addr_mp);
15631 				ill->ill_phys_addr_mp = mp_hw;
15632 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15633 				    dlp->notify_ind.dl_addr_offset;
15634 				ill->ill_phys_addr_length =
15635 				    dlp->notify_ind.dl_addr_length -
15636 				    ABS(ill->ill_sap_length);
15637 				if (ill->ill_isv6 &&
15638 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15639 					if (ill->ill_nd_lla_mp != NULL)
15640 						freemsg(ill->ill_nd_lla_mp);
15641 					ill->ill_nd_lla_mp = copyb(mp_hw);
15642 					ill->ill_nd_lla = (uchar_t *)
15643 					    ill->ill_nd_lla_mp->b_rptr +
15644 					    dlp->notify_ind.dl_addr_offset;
15645 					ill->ill_nd_lla_len =
15646 					    ill->ill_phys_addr_length;
15647 				}
15648 			}
15649 			mutex_exit(&ill->ill_lock);
15650 			/*
15651 			 * Send out gratuitous arp request for our new
15652 			 * hardware address.
15653 			 */
15654 			for (ipif = ill->ill_ipif; ipif != NULL;
15655 			    ipif = ipif->ipif_next) {
15656 				if (!(ipif->ipif_flags & IPIF_UP))
15657 					continue;
15658 				if (ill->ill_isv6) {
15659 					ipif_ndp_down(ipif);
15660 					/*
15661 					 * Set B_TRUE to enable
15662 					 * ipif_ndp_up() to send out
15663 					 * unsolicited advertisements.
15664 					 */
15665 					err = ipif_ndp_up(ipif,
15666 					    &ipif->ipif_v6lcl_addr,
15667 					    B_TRUE);
15668 					if (err) {
15669 						ip1dbg((
15670 						    "ip_rput_dlpi_writer: "
15671 						    "Failed to update ndp "
15672 						    "err %d\n", err));
15673 					}
15674 				} else {
15675 					/*
15676 					 * IPv4 ARP case
15677 					 *
15678 					 * Set Res_act_move, as we only want
15679 					 * ipif_resolver_up to send an
15680 					 * AR_ENTRY_ADD request up to
15681 					 * ARP.
15682 					 */
15683 					err = ipif_resolver_up(ipif,
15684 					    Res_act_move);
15685 					if (err) {
15686 						ip1dbg((
15687 						    "ip_rput_dlpi_writer: "
15688 						    "Failed to update arp "
15689 						    "err %d\n", err));
15690 					}
15691 				}
15692 			}
15693 			/*
15694 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15695 			 * case so that all old fastpath information can be
15696 			 * purged from IRE caches.
15697 			 */
15698 		/* FALLTHRU */
15699 		case DL_NOTE_FASTPATH_FLUSH:
15700 			/*
15701 			 * Any fastpath probe sent henceforth will get the
15702 			 * new fp mp. So we first delete any ires that are
15703 			 * waiting for the fastpath. Then walk all ires and
15704 			 * delete the ire or delete the fp mp. In the case of
15705 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15706 			 * recreate the ire's without going through a complex
15707 			 * ipif up/down dance. So we don't delete the ire
15708 			 * itself, but just the nce_fp_mp for these 2 ire's
15709 			 * In the case of the other ire's we delete the ire's
15710 			 * themselves. Access to nce_fp_mp is completely
15711 			 * protected by ire_lock for IRE_MIPRTUN and
15712 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15713 			 * other cases for performance.
15714 			 */
15715 			if (ill->ill_isv6) {
15716 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15717 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15718 				    NULL);
15719 			} else {
15720 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15721 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15722 				    IRE_CACHE | IRE_BROADCAST,
15723 				    ire_fastpath_flush, NULL, ill);
15724 				mutex_enter(&ire_mrtun_lock);
15725 				if (ire_mrtun_count != 0) {
15726 					mutex_exit(&ire_mrtun_lock);
15727 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15728 					    IRE_MIPRTUN, ire_fastpath_flush,
15729 					    NULL, ill);
15730 				} else {
15731 					mutex_exit(&ire_mrtun_lock);
15732 				}
15733 			}
15734 			break;
15735 		case DL_NOTE_SDU_SIZE:
15736 			/*
15737 			 * Change the MTU size of the interface, of all
15738 			 * attached ipif's, and of all relevant ire's.  The
15739 			 * new value's a uint32_t at notify->dl_data.
15740 			 * Mtu change Vs. new ire creation - protocol below.
15741 			 *
15742 			 * a Mark the ipif as IPIF_CHANGING.
15743 			 * b Set the new mtu in the ipif.
15744 			 * c Change the ire_max_frag on all affected ires
15745 			 * d Unmark the IPIF_CHANGING
15746 			 *
15747 			 * To see how the protocol works, assume an interface
15748 			 * route is also being added simultaneously by
15749 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15750 			 * the ire. If the ire is created before step a,
15751 			 * it will be cleaned up by step c. If the ire is
15752 			 * created after step d, it will see the new value of
15753 			 * ipif_mtu. Any attempt to create the ire between
15754 			 * steps a to d will fail because of the IPIF_CHANGING
15755 			 * flag. Note that ire_create() is passed a pointer to
15756 			 * the ipif_mtu, and not the value. During ire_add
15757 			 * under the bucket lock, the ire_max_frag of the
15758 			 * new ire being created is set from the ipif/ire from
15759 			 * which it is being derived.
15760 			 */
15761 			mutex_enter(&ill->ill_lock);
15762 			ill->ill_max_frag = (uint_t)notify->dl_data;
15763 
15764 			/*
15765 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15766 			 * leave it alone
15767 			 */
15768 			if (ill->ill_mtu_userspecified) {
15769 				mutex_exit(&ill->ill_lock);
15770 				break;
15771 			}
15772 			ill->ill_max_mtu = ill->ill_max_frag;
15773 			if (ill->ill_isv6) {
15774 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15775 					ill->ill_max_mtu = IPV6_MIN_MTU;
15776 			} else {
15777 				if (ill->ill_max_mtu < IP_MIN_MTU)
15778 					ill->ill_max_mtu = IP_MIN_MTU;
15779 			}
15780 			for (ipif = ill->ill_ipif; ipif != NULL;
15781 			    ipif = ipif->ipif_next) {
15782 				/*
15783 				 * Don't override the mtu if the user
15784 				 * has explicitly set it.
15785 				 */
15786 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15787 					continue;
15788 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15789 				if (ipif->ipif_isv6)
15790 					ire = ipif_to_ire_v6(ipif);
15791 				else
15792 					ire = ipif_to_ire(ipif);
15793 				if (ire != NULL) {
15794 					ire->ire_max_frag = ipif->ipif_mtu;
15795 					ire_refrele(ire);
15796 				}
15797 				if (ipif->ipif_flags & IPIF_UP) {
15798 					if (ill->ill_isv6)
15799 						need_ire_walk_v6 = B_TRUE;
15800 					else
15801 						need_ire_walk_v4 = B_TRUE;
15802 				}
15803 			}
15804 			mutex_exit(&ill->ill_lock);
15805 			if (need_ire_walk_v4)
15806 				ire_walk_v4(ill_mtu_change, (char *)ill,
15807 				    ALL_ZONES);
15808 			if (need_ire_walk_v6)
15809 				ire_walk_v6(ill_mtu_change, (char *)ill,
15810 				    ALL_ZONES);
15811 			break;
15812 		case DL_NOTE_LINK_UP:
15813 		case DL_NOTE_LINK_DOWN: {
15814 			/*
15815 			 * We are writer. ill / phyint / ipsq assocs stable.
15816 			 * The RUNNING flag reflects the state of the link.
15817 			 */
15818 			phyint_t *phyint = ill->ill_phyint;
15819 			uint64_t new_phyint_flags;
15820 			boolean_t changed = B_FALSE;
15821 			boolean_t went_up;
15822 
15823 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15824 			mutex_enter(&phyint->phyint_lock);
15825 			new_phyint_flags = went_up ?
15826 			    phyint->phyint_flags | PHYI_RUNNING :
15827 			    phyint->phyint_flags & ~PHYI_RUNNING;
15828 			if (new_phyint_flags != phyint->phyint_flags) {
15829 				phyint->phyint_flags = new_phyint_flags;
15830 				changed = B_TRUE;
15831 			}
15832 			mutex_exit(&phyint->phyint_lock);
15833 			/*
15834 			 * ill_restart_dad handles the DAD restart and routing
15835 			 * socket notification logic.
15836 			 */
15837 			if (changed) {
15838 				ill_restart_dad(phyint->phyint_illv4, went_up);
15839 				ill_restart_dad(phyint->phyint_illv6, went_up);
15840 			}
15841 			break;
15842 		}
15843 		case DL_NOTE_PROMISC_ON_PHYS:
15844 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15845 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15846 			mutex_enter(&ill->ill_lock);
15847 			ill->ill_promisc_on_phys = B_TRUE;
15848 			mutex_exit(&ill->ill_lock);
15849 			break;
15850 		case DL_NOTE_PROMISC_OFF_PHYS:
15851 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15852 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15853 			mutex_enter(&ill->ill_lock);
15854 			ill->ill_promisc_on_phys = B_FALSE;
15855 			mutex_exit(&ill->ill_lock);
15856 			break;
15857 		case DL_NOTE_CAPAB_RENEG:
15858 			/*
15859 			 * Something changed on the driver side.
15860 			 * It wants us to renegotiate the capabilities
15861 			 * on this ill. The most likely cause is the
15862 			 * aggregation interface under us where a
15863 			 * port got added or went away.
15864 			 *
15865 			 * We reset the capabilities and set the
15866 			 * state to IDS_RENG so that when the ack
15867 			 * comes back, we can start the
15868 			 * renegotiation process.
15869 			 */
15870 			ill_capability_reset(ill);
15871 			ill->ill_dlpi_capab_state = IDS_RENEG;
15872 			break;
15873 		default:
15874 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15875 			    "type 0x%x for DL_NOTIFY_IND\n",
15876 			    notify->dl_notification));
15877 			break;
15878 		}
15879 
15880 		/*
15881 		 * As this is an asynchronous operation, we
15882 		 * should not call ill_dlpi_done
15883 		 */
15884 		break;
15885 	}
15886 	case DL_NOTIFY_ACK: {
15887 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15888 
15889 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15890 			ill->ill_note_link = 1;
15891 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15892 		break;
15893 	}
15894 	case DL_PHYS_ADDR_ACK: {
15895 		/*
15896 		 * We should have an IOCTL waiting on this when request
15897 		 * sent by ill_dl_phys.
15898 		 * However, ill_dl_phys was called on an ill queue (from
15899 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15900 		 * ioctl is known to be pending on ill_wq.
15901 		 * There are two additional phys_addr_req's sent to the
15902 		 * driver to get the token and lla. ill_phys_addr_pend
15903 		 * keeps track of the last one sent so we know which
15904 		 * response we are dealing with. ill_dlpi_done will
15905 		 * update ill_phys_addr_pend when it sends the next req.
15906 		 * We don't complete the IOCTL until all three DL_PARs
15907 		 * have been attempted.
15908 		 *
15909 		 * We don't need any lock to update ill_nd_lla* fields,
15910 		 * since the ill is not yet up, We grab the lock just
15911 		 * for uniformity with other code that accesses ill_nd_lla.
15912 		 */
15913 		physaddr_req = ill->ill_phys_addr_pend;
15914 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15915 		if (physaddr_req == DL_IPV6_TOKEN ||
15916 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15917 			if (physaddr_req == DL_IPV6_TOKEN) {
15918 				/*
15919 				 * bcopy to low-order bits of ill_token
15920 				 *
15921 				 * XXX Temporary hack - currently,
15922 				 * all known tokens are 64 bits,
15923 				 * so I'll cheat for the moment.
15924 				 */
15925 				dlp = (union DL_primitives *)mp->b_rptr;
15926 
15927 				mutex_enter(&ill->ill_lock);
15928 				bcopy((uchar_t *)(mp->b_rptr +
15929 				dlp->physaddr_ack.dl_addr_offset),
15930 				(void *)&ill->ill_token.s6_addr32[2],
15931 				dlp->physaddr_ack.dl_addr_length);
15932 				ill->ill_token_length =
15933 					dlp->physaddr_ack.dl_addr_length;
15934 				mutex_exit(&ill->ill_lock);
15935 			} else {
15936 				ASSERT(ill->ill_nd_lla_mp == NULL);
15937 				mp_hw = copyb(mp);
15938 				if (mp_hw == NULL) {
15939 					err = ENOMEM;
15940 					break;
15941 				}
15942 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15943 				mutex_enter(&ill->ill_lock);
15944 				ill->ill_nd_lla_mp = mp_hw;
15945 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15946 				dlp->physaddr_ack.dl_addr_offset;
15947 				ill->ill_nd_lla_len =
15948 					dlp->physaddr_ack.dl_addr_length;
15949 				mutex_exit(&ill->ill_lock);
15950 			}
15951 			break;
15952 		}
15953 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15954 		ASSERT(ill->ill_phys_addr_mp == NULL);
15955 		if (!ill->ill_ifname_pending)
15956 			break;
15957 		ill->ill_ifname_pending = 0;
15958 		if (!ioctl_aborted)
15959 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15960 		if (mp1 != NULL) {
15961 			ASSERT(connp == NULL);
15962 			q = ill->ill_wq;
15963 		}
15964 		/*
15965 		 * If any error acks received during the plumbing sequence,
15966 		 * ill_ifname_pending_err will be set. Break out and send up
15967 		 * the error to the pending ioctl.
15968 		 */
15969 		if (ill->ill_ifname_pending_err != 0) {
15970 			err = ill->ill_ifname_pending_err;
15971 			ill->ill_ifname_pending_err = 0;
15972 			break;
15973 		}
15974 		/*
15975 		 * Get the interface token.  If the zeroth interface
15976 		 * address is zero then set the address to the link local
15977 		 * address
15978 		 */
15979 		mp_hw = copyb(mp);
15980 		if (mp_hw == NULL) {
15981 			err = ENOMEM;
15982 			break;
15983 		}
15984 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15985 		ill->ill_phys_addr_mp = mp_hw;
15986 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15987 				dlp->physaddr_ack.dl_addr_offset;
15988 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15989 		    ill->ill_phys_addr_length == 0 ||
15990 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15991 			/*
15992 			 * Compatibility: atun driver returns a length of 0.
15993 			 * ipdptp has an ill_phys_addr_length of zero(from
15994 			 * DL_BIND_ACK) but a non-zero length here.
15995 			 * ipd has an ill_phys_addr_length of 4(from
15996 			 * DL_BIND_ACK) but a non-zero length here.
15997 			 */
15998 			ill->ill_phys_addr = NULL;
15999 		} else if (dlp->physaddr_ack.dl_addr_length !=
16000 		    ill->ill_phys_addr_length) {
16001 			ip0dbg(("DL_PHYS_ADDR_ACK: "
16002 			    "Address length mismatch %d %d\n",
16003 			    dlp->physaddr_ack.dl_addr_length,
16004 			    ill->ill_phys_addr_length));
16005 			err = EINVAL;
16006 			break;
16007 		}
16008 		mutex_enter(&ill->ill_lock);
16009 		if (ill->ill_nd_lla_mp == NULL) {
16010 			ill->ill_nd_lla_mp = copyb(mp_hw);
16011 			if (ill->ill_nd_lla_mp == NULL) {
16012 				err = ENOMEM;
16013 				mutex_exit(&ill->ill_lock);
16014 				break;
16015 			}
16016 			ill->ill_nd_lla =
16017 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
16018 			    dlp->physaddr_ack.dl_addr_offset;
16019 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
16020 		}
16021 		mutex_exit(&ill->ill_lock);
16022 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16023 			(void) ill_setdefaulttoken(ill);
16024 
16025 		/*
16026 		 * If the ill zero interface has a zero address assign
16027 		 * it the proper link local address.
16028 		 */
16029 		ASSERT(ill->ill_ipif->ipif_id == 0);
16030 		if (ipif != NULL &&
16031 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
16032 			(void) ipif_setlinklocal(ipif);
16033 		break;
16034 	}
16035 	case DL_OK_ACK:
16036 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16037 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16038 		    dloa->dl_correct_primitive));
16039 		switch (dloa->dl_correct_primitive) {
16040 		case DL_UNBIND_REQ:
16041 		case DL_ATTACH_REQ:
16042 		case DL_DETACH_REQ:
16043 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16044 			break;
16045 		}
16046 		break;
16047 	default:
16048 		break;
16049 	}
16050 
16051 	freemsg(mp);
16052 	if (mp1) {
16053 		struct iocblk *iocp;
16054 		int mode;
16055 
16056 		/*
16057 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
16058 		 * SIOCSLIFNAME do a copyout.
16059 		 */
16060 		iocp = (struct iocblk *)mp1->b_rptr;
16061 
16062 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16063 		    iocp->ioc_cmd == SIOCSLIFNAME)
16064 			mode = COPYOUT;
16065 		else
16066 			mode = NO_COPYOUT;
16067 		/*
16068 		 * The ioctl must complete now without EINPROGRESS
16069 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16070 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16071 		 * stuck for ever in the ipsq.
16072 		 */
16073 		ASSERT(err != EINPROGRESS);
16074 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16075 
16076 	}
16077 }
16078 
16079 /*
16080  * ip_rput_other is called by ip_rput to handle messages modifying the global
16081  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16082  */
16083 /* ARGSUSED */
16084 void
16085 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16086 {
16087 	ill_t		*ill;
16088 	struct iocblk	*iocp;
16089 	mblk_t		*mp1;
16090 	conn_t		*connp = NULL;
16091 
16092 	ip1dbg(("ip_rput_other "));
16093 	ill = (ill_t *)q->q_ptr;
16094 	/*
16095 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16096 	 * in which case ipsq is NULL.
16097 	 */
16098 	if (ipsq != NULL) {
16099 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16100 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16101 	}
16102 
16103 	switch (mp->b_datap->db_type) {
16104 	case M_ERROR:
16105 	case M_HANGUP:
16106 		/*
16107 		 * The device has a problem.  We force the ILL down.  It can
16108 		 * be brought up again manually using SIOCSIFFLAGS (via
16109 		 * ifconfig or equivalent).
16110 		 */
16111 		ASSERT(ipsq != NULL);
16112 		if (mp->b_rptr < mp->b_wptr)
16113 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16114 		if (ill->ill_error == 0)
16115 			ill->ill_error = ENXIO;
16116 		if (!ill_down_start(q, mp))
16117 			return;
16118 		ipif_all_down_tail(ipsq, q, mp, NULL);
16119 		break;
16120 	case M_IOCACK:
16121 		iocp = (struct iocblk *)mp->b_rptr;
16122 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16123 		switch (iocp->ioc_cmd) {
16124 		case SIOCSTUNPARAM:
16125 		case OSIOCSTUNPARAM:
16126 			ASSERT(ipsq != NULL);
16127 			/*
16128 			 * Finish socket ioctl passed through to tun.
16129 			 * We should have an IOCTL waiting on this.
16130 			 */
16131 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16132 			if (ill->ill_isv6) {
16133 				struct iftun_req *ta;
16134 
16135 				/*
16136 				 * if a source or destination is
16137 				 * being set, try and set the link
16138 				 * local address for the tunnel
16139 				 */
16140 				ta = (struct iftun_req *)mp->b_cont->
16141 				    b_cont->b_rptr;
16142 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16143 					ipif_set_tun_llink(ill, ta);
16144 				}
16145 
16146 			}
16147 			if (mp1 != NULL) {
16148 				/*
16149 				 * Now copy back the b_next/b_prev used by
16150 				 * mi code for the mi_copy* functions.
16151 				 * See ip_sioctl_tunparam() for the reason.
16152 				 * Also protect against missing b_cont.
16153 				 */
16154 				if (mp->b_cont != NULL) {
16155 					mp->b_cont->b_next =
16156 					    mp1->b_cont->b_next;
16157 					mp->b_cont->b_prev =
16158 					    mp1->b_cont->b_prev;
16159 				}
16160 				inet_freemsg(mp1);
16161 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16162 				ASSERT(connp != NULL);
16163 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16164 				    iocp->ioc_error, NO_COPYOUT,
16165 				    ipsq->ipsq_current_ipif, ipsq);
16166 			} else {
16167 				ASSERT(connp == NULL);
16168 				putnext(q, mp);
16169 			}
16170 			break;
16171 		case SIOCGTUNPARAM:
16172 		case OSIOCGTUNPARAM:
16173 			/*
16174 			 * This is really M_IOCDATA from the tunnel driver.
16175 			 * convert back and complete the ioctl.
16176 			 * We should have an IOCTL waiting on this.
16177 			 */
16178 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16179 			if (mp1) {
16180 				/*
16181 				 * Now copy back the b_next/b_prev used by
16182 				 * mi code for the mi_copy* functions.
16183 				 * See ip_sioctl_tunparam() for the reason.
16184 				 * Also protect against missing b_cont.
16185 				 */
16186 				if (mp->b_cont != NULL) {
16187 					mp->b_cont->b_next =
16188 					    mp1->b_cont->b_next;
16189 					mp->b_cont->b_prev =
16190 					    mp1->b_cont->b_prev;
16191 				}
16192 				inet_freemsg(mp1);
16193 				if (iocp->ioc_error == 0)
16194 					mp->b_datap->db_type = M_IOCDATA;
16195 				ASSERT(connp != NULL);
16196 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16197 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16198 			} else {
16199 				ASSERT(connp == NULL);
16200 				putnext(q, mp);
16201 			}
16202 			break;
16203 		default:
16204 			break;
16205 		}
16206 		break;
16207 	case M_IOCNAK:
16208 		iocp = (struct iocblk *)mp->b_rptr;
16209 
16210 		switch (iocp->ioc_cmd) {
16211 		int mode;
16212 		ipif_t	*ipif;
16213 
16214 		case DL_IOC_HDR_INFO:
16215 			/*
16216 			 * If this was the first attempt turn of the
16217 			 * fastpath probing.
16218 			 */
16219 			mutex_enter(&ill->ill_lock);
16220 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16221 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16222 				mutex_exit(&ill->ill_lock);
16223 				ill_fastpath_nack(ill);
16224 				ip1dbg(("ip_rput: DLPI fastpath off on "
16225 				    "interface %s\n",
16226 				    ill->ill_name));
16227 			} else {
16228 				mutex_exit(&ill->ill_lock);
16229 			}
16230 			freemsg(mp);
16231 			break;
16232 		case SIOCSTUNPARAM:
16233 		case OSIOCSTUNPARAM:
16234 			ASSERT(ipsq != NULL);
16235 			/*
16236 			 * Finish socket ioctl passed through to tun
16237 			 * We should have an IOCTL waiting on this.
16238 			 */
16239 			/* FALLTHRU */
16240 		case SIOCGTUNPARAM:
16241 		case OSIOCGTUNPARAM:
16242 			/*
16243 			 * This is really M_IOCDATA from the tunnel driver.
16244 			 * convert back and complete the ioctl.
16245 			 * We should have an IOCTL waiting on this.
16246 			 */
16247 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16248 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16249 				mp1 = ill_pending_mp_get(ill, &connp,
16250 				    iocp->ioc_id);
16251 				mode = COPYOUT;
16252 				ipsq = NULL;
16253 				ipif = NULL;
16254 			} else {
16255 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16256 				mode = NO_COPYOUT;
16257 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16258 				ipif = ipsq->ipsq_current_ipif;
16259 			}
16260 			if (mp1 != NULL) {
16261 				/*
16262 				 * Now copy back the b_next/b_prev used by
16263 				 * mi code for the mi_copy* functions.
16264 				 * See ip_sioctl_tunparam() for the reason.
16265 				 * Also protect against missing b_cont.
16266 				 */
16267 				if (mp->b_cont != NULL) {
16268 					mp->b_cont->b_next =
16269 					    mp1->b_cont->b_next;
16270 					mp->b_cont->b_prev =
16271 					    mp1->b_cont->b_prev;
16272 				}
16273 				inet_freemsg(mp1);
16274 				if (iocp->ioc_error == 0)
16275 					iocp->ioc_error = EINVAL;
16276 				ASSERT(connp != NULL);
16277 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16278 				    iocp->ioc_error, mode, ipif, ipsq);
16279 			} else {
16280 				ASSERT(connp == NULL);
16281 				putnext(q, mp);
16282 			}
16283 			break;
16284 		default:
16285 			break;
16286 		}
16287 	default:
16288 		break;
16289 	}
16290 }
16291 
16292 /*
16293  * NOTE : This function does not ire_refrele the ire argument passed in.
16294  *
16295  * IPQoS notes
16296  * IP policy is invoked twice for a forwarded packet, once on the read side
16297  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16298  * enabled. An additional parameter, in_ill, has been added for this purpose.
16299  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16300  * because ip_mroute drops this information.
16301  *
16302  */
16303 void
16304 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16305 {
16306 	uint32_t	pkt_len;
16307 	queue_t	*q;
16308 	uint32_t	sum;
16309 #define	rptr	((uchar_t *)ipha)
16310 	uint32_t	max_frag;
16311 	uint32_t	ill_index;
16312 	ill_t		*out_ill;
16313 
16314 	/* Get the ill_index of the incoming ILL */
16315 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16316 
16317 	/* Initiate Read side IPPF processing */
16318 	if (IPP_ENABLED(IPP_FWD_IN)) {
16319 		ip_process(IPP_FWD_IN, &mp, ill_index);
16320 		if (mp == NULL) {
16321 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16322 			    "during IPPF processing\n"));
16323 			return;
16324 		}
16325 	}
16326 
16327 	pkt_len = ntohs(ipha->ipha_length);
16328 
16329 	/* Adjust the checksum to reflect the ttl decrement. */
16330 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16331 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16332 
16333 	if (ipha->ipha_ttl-- <= 1) {
16334 		if (ip_csum_hdr(ipha)) {
16335 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16336 			goto drop_pkt;
16337 		}
16338 		/*
16339 		 * Note: ire_stq this will be NULL for multicast
16340 		 * datagrams using the long path through arp (the IRE
16341 		 * is not an IRE_CACHE). This should not cause
16342 		 * problems since we don't generate ICMP errors for
16343 		 * multicast packets.
16344 		 */
16345 		q = ire->ire_stq;
16346 		if (q != NULL) {
16347 			/* Sent by forwarding path, and router is global zone */
16348 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16349 			    GLOBAL_ZONEID);
16350 		} else
16351 			freemsg(mp);
16352 		return;
16353 	}
16354 
16355 	/*
16356 	 * Don't forward if the interface is down
16357 	 */
16358 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16359 		BUMP_MIB(&ip_mib, ipInDiscards);
16360 		ip2dbg(("ip_rput_forward:interface is down\n"));
16361 		goto drop_pkt;
16362 	}
16363 
16364 	/* Get the ill_index of the outgoing ILL */
16365 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16366 
16367 	out_ill = ire->ire_ipif->ipif_ill;
16368 
16369 	DTRACE_PROBE4(ip4__forwarding__start,
16370 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16371 
16372 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16373 	    in_ill, out_ill, ipha, mp, mp);
16374 
16375 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16376 
16377 	if (mp == NULL)
16378 		return;
16379 	pkt_len = ntohs(ipha->ipha_length);
16380 
16381 	if (is_system_labeled()) {
16382 		mblk_t *mp1;
16383 
16384 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16385 			BUMP_MIB(&ip_mib, ipForwProhibits);
16386 			goto drop_pkt;
16387 		}
16388 		/* Size may have changed */
16389 		mp = mp1;
16390 		ipha = (ipha_t *)mp->b_rptr;
16391 		pkt_len = ntohs(ipha->ipha_length);
16392 	}
16393 
16394 	/* Check if there are options to update */
16395 	if (!IS_SIMPLE_IPH(ipha)) {
16396 		if (ip_csum_hdr(ipha)) {
16397 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16398 			goto drop_pkt;
16399 		}
16400 		if (ip_rput_forward_options(mp, ipha, ire)) {
16401 			return;
16402 		}
16403 
16404 		ipha->ipha_hdr_checksum = 0;
16405 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16406 	}
16407 	max_frag = ire->ire_max_frag;
16408 	if (pkt_len > max_frag) {
16409 		/*
16410 		 * It needs fragging on its way out.  We haven't
16411 		 * verified the header checksum yet.  Since we
16412 		 * are going to put a surely good checksum in the
16413 		 * outgoing header, we have to make sure that it
16414 		 * was good coming in.
16415 		 */
16416 		if (ip_csum_hdr(ipha)) {
16417 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16418 			goto drop_pkt;
16419 		}
16420 		/* Initiate Write side IPPF processing */
16421 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16422 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16423 			if (mp == NULL) {
16424 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16425 				    " during IPPF processing\n"));
16426 				return;
16427 			}
16428 		}
16429 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16430 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16431 		return;
16432 	}
16433 
16434 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16435 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16436 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16437 	    NULL, out_ill, ipha, mp, mp);
16438 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16439 	if (mp == NULL)
16440 		return;
16441 
16442 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16443 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16444 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16445 	/* ip_xmit_v4 always consumes the packet */
16446 	return;
16447 
16448 drop_pkt:;
16449 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16450 	freemsg(mp);
16451 #undef	rptr
16452 }
16453 
16454 void
16455 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16456 {
16457 	ire_t	*ire;
16458 
16459 	ASSERT(!ipif->ipif_isv6);
16460 	/*
16461 	 * Find an IRE which matches the destination and the outgoing
16462 	 * queue in the cache table. All we need is an IRE_CACHE which
16463 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16464 	 * then it is enough to have some IRE_CACHE in the group.
16465 	 */
16466 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16467 		dst = ipif->ipif_pp_dst_addr;
16468 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16469 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16470 	if (ire == NULL) {
16471 		/*
16472 		 * Mark this packet to make it be delivered to
16473 		 * ip_rput_forward after the new ire has been
16474 		 * created.
16475 		 */
16476 		mp->b_prev = NULL;
16477 		mp->b_next = mp;
16478 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16479 		    NULL, 0, GLOBAL_ZONEID);
16480 	} else {
16481 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16482 		IRE_REFRELE(ire);
16483 	}
16484 }
16485 
16486 /* Update any source route, record route or timestamp options */
16487 static int
16488 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16489 {
16490 	ipoptp_t	opts;
16491 	uchar_t		*opt;
16492 	uint8_t		optval;
16493 	uint8_t		optlen;
16494 	ipaddr_t	dst;
16495 	uint32_t	ts;
16496 	ire_t		*dst_ire = NULL;
16497 	ire_t		*tmp_ire = NULL;
16498 	timestruc_t	now;
16499 
16500 	ip2dbg(("ip_rput_forward_options\n"));
16501 	dst = ipha->ipha_dst;
16502 	for (optval = ipoptp_first(&opts, ipha);
16503 	    optval != IPOPT_EOL;
16504 	    optval = ipoptp_next(&opts)) {
16505 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16506 		opt = opts.ipoptp_cur;
16507 		optlen = opts.ipoptp_len;
16508 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16509 		    optval, opts.ipoptp_len));
16510 		switch (optval) {
16511 			uint32_t off;
16512 		case IPOPT_SSRR:
16513 		case IPOPT_LSRR:
16514 			/* Check if adminstratively disabled */
16515 			if (!ip_forward_src_routed) {
16516 				BUMP_MIB(&ip_mib, ipForwProhibits);
16517 				if (ire->ire_stq != NULL) {
16518 					/*
16519 					 * Sent by forwarding path, and router
16520 					 * is global zone
16521 					 */
16522 					icmp_unreachable(ire->ire_stq, mp,
16523 					    ICMP_SOURCE_ROUTE_FAILED,
16524 					    GLOBAL_ZONEID);
16525 				} else {
16526 					ip0dbg(("ip_rput_forward_options: "
16527 					    "unable to send unreach\n"));
16528 					freemsg(mp);
16529 				}
16530 				return (-1);
16531 			}
16532 
16533 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16534 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16535 			if (dst_ire == NULL) {
16536 				/*
16537 				 * Must be partial since ip_rput_options
16538 				 * checked for strict.
16539 				 */
16540 				break;
16541 			}
16542 			off = opt[IPOPT_OFFSET];
16543 			off--;
16544 		redo_srr:
16545 			if (optlen < IP_ADDR_LEN ||
16546 			    off > optlen - IP_ADDR_LEN) {
16547 				/* End of source route */
16548 				ip1dbg((
16549 				    "ip_rput_forward_options: end of SR\n"));
16550 				ire_refrele(dst_ire);
16551 				break;
16552 			}
16553 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16554 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16555 			    IP_ADDR_LEN);
16556 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16557 			    ntohl(dst)));
16558 
16559 			/*
16560 			 * Check if our address is present more than
16561 			 * once as consecutive hops in source route.
16562 			 */
16563 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16564 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16565 			if (tmp_ire != NULL) {
16566 				ire_refrele(tmp_ire);
16567 				off += IP_ADDR_LEN;
16568 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16569 				goto redo_srr;
16570 			}
16571 			ipha->ipha_dst = dst;
16572 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16573 			ire_refrele(dst_ire);
16574 			break;
16575 		case IPOPT_RR:
16576 			off = opt[IPOPT_OFFSET];
16577 			off--;
16578 			if (optlen < IP_ADDR_LEN ||
16579 			    off > optlen - IP_ADDR_LEN) {
16580 				/* No more room - ignore */
16581 				ip1dbg((
16582 				    "ip_rput_forward_options: end of RR\n"));
16583 				break;
16584 			}
16585 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16586 			    IP_ADDR_LEN);
16587 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16588 			break;
16589 		case IPOPT_TS:
16590 			/* Insert timestamp if there is room */
16591 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16592 			case IPOPT_TS_TSONLY:
16593 				off = IPOPT_TS_TIMELEN;
16594 				break;
16595 			case IPOPT_TS_PRESPEC:
16596 			case IPOPT_TS_PRESPEC_RFC791:
16597 				/* Verify that the address matched */
16598 				off = opt[IPOPT_OFFSET] - 1;
16599 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16600 				dst_ire = ire_ctable_lookup(dst, 0,
16601 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16602 				    MATCH_IRE_TYPE);
16603 
16604 				if (dst_ire == NULL) {
16605 					/* Not for us */
16606 					break;
16607 				}
16608 				ire_refrele(dst_ire);
16609 				/* FALLTHRU */
16610 			case IPOPT_TS_TSANDADDR:
16611 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16612 				break;
16613 			default:
16614 				/*
16615 				 * ip_*put_options should have already
16616 				 * dropped this packet.
16617 				 */
16618 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16619 				    "unknown IT - bug in ip_rput_options?\n");
16620 				return (0);	/* Keep "lint" happy */
16621 			}
16622 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16623 				/* Increase overflow counter */
16624 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16625 				opt[IPOPT_POS_OV_FLG] =
16626 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16627 				    (off << 4));
16628 				break;
16629 			}
16630 			off = opt[IPOPT_OFFSET] - 1;
16631 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16632 			case IPOPT_TS_PRESPEC:
16633 			case IPOPT_TS_PRESPEC_RFC791:
16634 			case IPOPT_TS_TSANDADDR:
16635 				bcopy(&ire->ire_src_addr,
16636 				    (char *)opt + off, IP_ADDR_LEN);
16637 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16638 				/* FALLTHRU */
16639 			case IPOPT_TS_TSONLY:
16640 				off = opt[IPOPT_OFFSET] - 1;
16641 				/* Compute # of milliseconds since midnight */
16642 				gethrestime(&now);
16643 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16644 				    now.tv_nsec / (NANOSEC / MILLISEC);
16645 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16646 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16647 				break;
16648 			}
16649 			break;
16650 		}
16651 	}
16652 	return (0);
16653 }
16654 
16655 /*
16656  * This is called after processing at least one of AH/ESP headers.
16657  *
16658  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16659  * the actual, physical interface on which the packet was received,
16660  * but, when ip_strict_dst_multihoming is set to 1, could be the
16661  * interface which had the ipha_dst configured when the packet went
16662  * through ip_rput. The ill_index corresponding to the recv_ill
16663  * is saved in ipsec_in_rill_index
16664  */
16665 void
16666 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16667 {
16668 	mblk_t *mp;
16669 	ipaddr_t dst;
16670 	in6_addr_t *v6dstp;
16671 	ipha_t *ipha;
16672 	ip6_t *ip6h;
16673 	ipsec_in_t *ii;
16674 	boolean_t ill_need_rele = B_FALSE;
16675 	boolean_t rill_need_rele = B_FALSE;
16676 	boolean_t ire_need_rele = B_FALSE;
16677 
16678 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16679 	ASSERT(ii->ipsec_in_ill_index != 0);
16680 
16681 	mp = ipsec_mp->b_cont;
16682 	ASSERT(mp != NULL);
16683 
16684 
16685 	if (ill == NULL) {
16686 		ASSERT(recv_ill == NULL);
16687 		/*
16688 		 * We need to get the original queue on which ip_rput_local
16689 		 * or ip_rput_data_v6 was called.
16690 		 */
16691 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16692 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16693 		ill_need_rele = B_TRUE;
16694 
16695 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16696 			recv_ill = ill_lookup_on_ifindex(
16697 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16698 			    NULL, NULL, NULL, NULL);
16699 			rill_need_rele = B_TRUE;
16700 		} else {
16701 			recv_ill = ill;
16702 		}
16703 
16704 		if ((ill == NULL) || (recv_ill == NULL)) {
16705 			ip0dbg(("ip_fanout_proto_again: interface "
16706 			    "disappeared\n"));
16707 			if (ill != NULL)
16708 				ill_refrele(ill);
16709 			if (recv_ill != NULL)
16710 				ill_refrele(recv_ill);
16711 			freemsg(ipsec_mp);
16712 			return;
16713 		}
16714 	}
16715 
16716 	ASSERT(ill != NULL && recv_ill != NULL);
16717 
16718 	if (mp->b_datap->db_type == M_CTL) {
16719 		/*
16720 		 * AH/ESP is returning the ICMP message after
16721 		 * removing their headers. Fanout again till
16722 		 * it gets to the right protocol.
16723 		 */
16724 		if (ii->ipsec_in_v4) {
16725 			icmph_t *icmph;
16726 			int iph_hdr_length;
16727 			int hdr_length;
16728 
16729 			ipha = (ipha_t *)mp->b_rptr;
16730 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16731 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16732 			ipha = (ipha_t *)&icmph[1];
16733 			hdr_length = IPH_HDR_LENGTH(ipha);
16734 			/*
16735 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16736 			 * Reset the type to M_DATA.
16737 			 */
16738 			mp->b_datap->db_type = M_DATA;
16739 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16740 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16741 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16742 		} else {
16743 			icmp6_t *icmp6;
16744 			int hdr_length;
16745 
16746 			ip6h = (ip6_t *)mp->b_rptr;
16747 			/* Don't call hdr_length_v6() unless you have to. */
16748 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16749 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16750 			else
16751 				hdr_length = IPV6_HDR_LEN;
16752 
16753 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16754 			/*
16755 			 * icmp_inbound_error_fanout_v6 may need to do
16756 			 * pullupmsg.  Reset the type to M_DATA.
16757 			 */
16758 			mp->b_datap->db_type = M_DATA;
16759 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16760 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16761 		}
16762 		if (ill_need_rele)
16763 			ill_refrele(ill);
16764 		if (rill_need_rele)
16765 			ill_refrele(recv_ill);
16766 		return;
16767 	}
16768 
16769 	if (ii->ipsec_in_v4) {
16770 		ipha = (ipha_t *)mp->b_rptr;
16771 		dst = ipha->ipha_dst;
16772 		if (CLASSD(dst)) {
16773 			/*
16774 			 * Multicast has to be delivered to all streams.
16775 			 */
16776 			dst = INADDR_BROADCAST;
16777 		}
16778 
16779 		if (ire == NULL) {
16780 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16781 			    MBLK_GETLABEL(mp));
16782 			if (ire == NULL) {
16783 				if (ill_need_rele)
16784 					ill_refrele(ill);
16785 				if (rill_need_rele)
16786 					ill_refrele(recv_ill);
16787 				ip1dbg(("ip_fanout_proto_again: "
16788 				    "IRE not found"));
16789 				freemsg(ipsec_mp);
16790 				return;
16791 			}
16792 			ire_need_rele = B_TRUE;
16793 		}
16794 
16795 		switch (ipha->ipha_protocol) {
16796 			case IPPROTO_UDP:
16797 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16798 				    recv_ill);
16799 				if (ire_need_rele)
16800 					ire_refrele(ire);
16801 				break;
16802 			case IPPROTO_TCP:
16803 				if (!ire_need_rele)
16804 					IRE_REFHOLD(ire);
16805 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16806 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16807 				IRE_REFRELE(ire);
16808 				if (mp != NULL)
16809 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16810 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16811 				break;
16812 			case IPPROTO_SCTP:
16813 				if (!ire_need_rele)
16814 					IRE_REFHOLD(ire);
16815 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16816 				    ipsec_mp, 0, ill->ill_rq, dst);
16817 				break;
16818 			default:
16819 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16820 				    recv_ill);
16821 				if (ire_need_rele)
16822 					ire_refrele(ire);
16823 				break;
16824 		}
16825 	} else {
16826 		uint32_t rput_flags = 0;
16827 
16828 		ip6h = (ip6_t *)mp->b_rptr;
16829 		v6dstp = &ip6h->ip6_dst;
16830 		/*
16831 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16832 		 * address.
16833 		 *
16834 		 * Currently, we don't store that state in the IPSEC_IN
16835 		 * message, and we may need to.
16836 		 */
16837 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16838 		    IP6_IN_LLMCAST : 0);
16839 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16840 		    NULL, NULL);
16841 	}
16842 	if (ill_need_rele)
16843 		ill_refrele(ill);
16844 	if (rill_need_rele)
16845 		ill_refrele(recv_ill);
16846 }
16847 
16848 /*
16849  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16850  * returns 'true' if there are still fragments left on the queue, in
16851  * which case we restart the timer.
16852  */
16853 void
16854 ill_frag_timer(void *arg)
16855 {
16856 	ill_t	*ill = (ill_t *)arg;
16857 	boolean_t frag_pending;
16858 
16859 	mutex_enter(&ill->ill_lock);
16860 	ASSERT(!ill->ill_fragtimer_executing);
16861 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16862 		ill->ill_frag_timer_id = 0;
16863 		mutex_exit(&ill->ill_lock);
16864 		return;
16865 	}
16866 	ill->ill_fragtimer_executing = 1;
16867 	mutex_exit(&ill->ill_lock);
16868 
16869 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16870 
16871 	/*
16872 	 * Restart the timer, if we have fragments pending or if someone
16873 	 * wanted us to be scheduled again.
16874 	 */
16875 	mutex_enter(&ill->ill_lock);
16876 	ill->ill_fragtimer_executing = 0;
16877 	ill->ill_frag_timer_id = 0;
16878 	if (frag_pending || ill->ill_fragtimer_needrestart)
16879 		ill_frag_timer_start(ill);
16880 	mutex_exit(&ill->ill_lock);
16881 }
16882 
16883 void
16884 ill_frag_timer_start(ill_t *ill)
16885 {
16886 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16887 
16888 	/* If the ill is closing or opening don't proceed */
16889 	if (ill->ill_state_flags & ILL_CONDEMNED)
16890 		return;
16891 
16892 	if (ill->ill_fragtimer_executing) {
16893 		/*
16894 		 * ill_frag_timer is currently executing. Just record the
16895 		 * the fact that we want the timer to be restarted.
16896 		 * ill_frag_timer will post a timeout before it returns,
16897 		 * ensuring it will be called again.
16898 		 */
16899 		ill->ill_fragtimer_needrestart = 1;
16900 		return;
16901 	}
16902 
16903 	if (ill->ill_frag_timer_id == 0) {
16904 		/*
16905 		 * The timer is neither running nor is the timeout handler
16906 		 * executing. Post a timeout so that ill_frag_timer will be
16907 		 * called
16908 		 */
16909 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16910 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16911 		ill->ill_fragtimer_needrestart = 0;
16912 	}
16913 }
16914 
16915 /*
16916  * This routine is needed for loopback when forwarding multicasts.
16917  *
16918  * IPQoS Notes:
16919  * IPPF processing is done in fanout routines.
16920  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16921  * processing for IPSec packets is done when it comes back in clear.
16922  * NOTE : The callers of this function need to do the ire_refrele for the
16923  *	  ire that is being passed in.
16924  */
16925 void
16926 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16927     ill_t *recv_ill)
16928 {
16929 	ill_t	*ill = (ill_t *)q->q_ptr;
16930 	uint32_t	sum;
16931 	uint32_t	u1;
16932 	uint32_t	u2;
16933 	int		hdr_length;
16934 	boolean_t	mctl_present;
16935 	mblk_t		*first_mp = mp;
16936 	mblk_t		*hada_mp = NULL;
16937 	ipha_t		*inner_ipha;
16938 
16939 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16940 	    "ip_rput_locl_start: q %p", q);
16941 
16942 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16943 
16944 
16945 #define	rptr	((uchar_t *)ipha)
16946 #define	iphs	((uint16_t *)ipha)
16947 
16948 	/*
16949 	 * no UDP or TCP packet should come here anymore.
16950 	 */
16951 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16952 	    (ipha->ipha_protocol != IPPROTO_UDP));
16953 
16954 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16955 	if (mctl_present &&
16956 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16957 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16958 
16959 		/*
16960 		 * It's an IPsec accelerated packet.
16961 		 * Keep a pointer to the data attributes around until
16962 		 * we allocate the ipsec_info_t.
16963 		 */
16964 		IPSECHW_DEBUG(IPSECHW_PKT,
16965 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16966 		hada_mp = first_mp;
16967 		hada_mp->b_cont = NULL;
16968 		/*
16969 		 * Since it is accelerated, it comes directly from
16970 		 * the ill and the data attributes is followed by
16971 		 * the packet data.
16972 		 */
16973 		ASSERT(mp->b_datap->db_type != M_CTL);
16974 		first_mp = mp;
16975 		mctl_present = B_FALSE;
16976 	}
16977 
16978 	/*
16979 	 * IF M_CTL is not present, then ipsec_in_is_secure
16980 	 * should return B_TRUE. There is a case where loopback
16981 	 * packets has an M_CTL in the front with all the
16982 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16983 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16984 	 * packets never comes here, it is safe to ASSERT the
16985 	 * following.
16986 	 */
16987 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16988 
16989 
16990 	/* u1 is # words of IP options */
16991 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16992 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16993 
16994 	if (u1) {
16995 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16996 			if (hada_mp != NULL)
16997 				freemsg(hada_mp);
16998 			return;
16999 		}
17000 	} else {
17001 		/* Check the IP header checksum.  */
17002 #define	uph	((uint16_t *)ipha)
17003 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17004 		    uph[6] + uph[7] + uph[8] + uph[9];
17005 #undef  uph
17006 		/* finish doing IP checksum */
17007 		sum = (sum & 0xFFFF) + (sum >> 16);
17008 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17009 		/*
17010 		 * Don't verify header checksum if this packet is coming
17011 		 * back from AH/ESP as we already did it.
17012 		 */
17013 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17014 			BUMP_MIB(&ip_mib, ipInCksumErrs);
17015 			goto drop_pkt;
17016 		}
17017 	}
17018 
17019 	/*
17020 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17021 	 * might be called more than once for secure packets, count only
17022 	 * the first time.
17023 	 */
17024 	if (!mctl_present) {
17025 		UPDATE_IB_PKT_COUNT(ire);
17026 		ire->ire_last_used_time = lbolt;
17027 	}
17028 
17029 	/* Check for fragmentation offset. */
17030 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17031 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17032 	if (u1) {
17033 		/*
17034 		 * We re-assemble fragments before we do the AH/ESP
17035 		 * processing. Thus, M_CTL should not be present
17036 		 * while we are re-assembling.
17037 		 */
17038 		ASSERT(!mctl_present);
17039 		ASSERT(first_mp == mp);
17040 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17041 			return;
17042 		}
17043 		/*
17044 		 * Make sure that first_mp points back to mp as
17045 		 * the mp we came in with could have changed in
17046 		 * ip_rput_fragment().
17047 		 */
17048 		ipha = (ipha_t *)mp->b_rptr;
17049 		first_mp = mp;
17050 	}
17051 
17052 	/*
17053 	 * Clear hardware checksumming flag as it is currently only
17054 	 * used by TCP and UDP.
17055 	 */
17056 	DB_CKSUMFLAGS(mp) = 0;
17057 
17058 	/* Now we have a complete datagram, destined for this machine. */
17059 	u1 = IPH_HDR_LENGTH(ipha);
17060 	switch (ipha->ipha_protocol) {
17061 	case IPPROTO_ICMP: {
17062 		ire_t		*ire_zone;
17063 		ilm_t		*ilm;
17064 		mblk_t		*mp1;
17065 		zoneid_t	last_zoneid;
17066 
17067 		if (CLASSD(ipha->ipha_dst) &&
17068 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17069 			ASSERT(ire->ire_type == IRE_BROADCAST);
17070 			/*
17071 			 * In the multicast case, applications may have joined
17072 			 * the group from different zones, so we need to deliver
17073 			 * the packet to each of them. Loop through the
17074 			 * multicast memberships structures (ilm) on the receive
17075 			 * ill and send a copy of the packet up each matching
17076 			 * one. However, we don't do this for multicasts sent on
17077 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17078 			 * they must stay in the sender's zone.
17079 			 *
17080 			 * ilm_add_v6() ensures that ilms in the same zone are
17081 			 * contiguous in the ill_ilm list. We use this property
17082 			 * to avoid sending duplicates needed when two
17083 			 * applications in the same zone join the same group on
17084 			 * different logical interfaces: we ignore the ilm if
17085 			 * its zoneid is the same as the last matching one.
17086 			 * In addition, the sending of the packet for
17087 			 * ire_zoneid is delayed until all of the other ilms
17088 			 * have been exhausted.
17089 			 */
17090 			last_zoneid = -1;
17091 			ILM_WALKER_HOLD(recv_ill);
17092 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17093 			    ilm = ilm->ilm_next) {
17094 				if ((ilm->ilm_flags & ILM_DELETED) ||
17095 				    ipha->ipha_dst != ilm->ilm_addr ||
17096 				    ilm->ilm_zoneid == last_zoneid ||
17097 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17098 				    ilm->ilm_zoneid == ALL_ZONES ||
17099 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17100 					continue;
17101 				mp1 = ip_copymsg(first_mp);
17102 				if (mp1 == NULL)
17103 					continue;
17104 				icmp_inbound(q, mp1, B_TRUE, ill,
17105 				    0, sum, mctl_present, B_TRUE,
17106 				    recv_ill, ilm->ilm_zoneid);
17107 				last_zoneid = ilm->ilm_zoneid;
17108 			}
17109 			ILM_WALKER_RELE(recv_ill);
17110 		} else if (ire->ire_type == IRE_BROADCAST) {
17111 			/*
17112 			 * In the broadcast case, there may be many zones
17113 			 * which need a copy of the packet delivered to them.
17114 			 * There is one IRE_BROADCAST per broadcast address
17115 			 * and per zone; we walk those using a helper function.
17116 			 * In addition, the sending of the packet for ire is
17117 			 * delayed until all of the other ires have been
17118 			 * processed.
17119 			 */
17120 			IRB_REFHOLD(ire->ire_bucket);
17121 			ire_zone = NULL;
17122 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17123 			    ire)) != NULL) {
17124 				mp1 = ip_copymsg(first_mp);
17125 				if (mp1 == NULL)
17126 					continue;
17127 
17128 				UPDATE_IB_PKT_COUNT(ire_zone);
17129 				ire_zone->ire_last_used_time = lbolt;
17130 				icmp_inbound(q, mp1, B_TRUE, ill,
17131 				    0, sum, mctl_present, B_TRUE,
17132 				    recv_ill, ire_zone->ire_zoneid);
17133 			}
17134 			IRB_REFRELE(ire->ire_bucket);
17135 		}
17136 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17137 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17138 		    ire->ire_zoneid);
17139 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17140 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17141 		return;
17142 	}
17143 	case IPPROTO_IGMP:
17144 		/*
17145 		 * If we are not willing to accept IGMP packets in clear,
17146 		 * then check with global policy.
17147 		 */
17148 		if (igmp_accept_clear_messages == 0) {
17149 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17150 			    ipha, NULL, mctl_present);
17151 			if (first_mp == NULL)
17152 				return;
17153 		}
17154 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17155 			freemsg(first_mp);
17156 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17157 			BUMP_MIB(&ip_mib, ipInDiscards);
17158 			return;
17159 		}
17160 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17161 			/* Bad packet - discarded by igmp_input */
17162 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17163 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17164 			if (mctl_present)
17165 				freeb(first_mp);
17166 			return;
17167 		}
17168 		/*
17169 		 * igmp_input() may have returned the pulled up message.
17170 		 * So first_mp and ipha need to be reinitialized.
17171 		 */
17172 		ipha = (ipha_t *)mp->b_rptr;
17173 		if (mctl_present)
17174 			first_mp->b_cont = mp;
17175 		else
17176 			first_mp = mp;
17177 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17178 			/* No user-level listener for IGMP packets */
17179 			goto drop_pkt;
17180 		}
17181 		/* deliver to local raw users */
17182 		break;
17183 	case IPPROTO_PIM:
17184 		/*
17185 		 * If we are not willing to accept PIM packets in clear,
17186 		 * then check with global policy.
17187 		 */
17188 		if (pim_accept_clear_messages == 0) {
17189 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17190 			    ipha, NULL, mctl_present);
17191 			if (first_mp == NULL)
17192 				return;
17193 		}
17194 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17195 			freemsg(first_mp);
17196 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17197 			BUMP_MIB(&ip_mib, ipInDiscards);
17198 			return;
17199 		}
17200 		if (pim_input(q, mp) != 0) {
17201 			/* Bad packet - discarded by pim_input */
17202 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17203 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17204 			if (mctl_present)
17205 				freeb(first_mp);
17206 			return;
17207 		}
17208 
17209 		/*
17210 		 * pim_input() may have pulled up the message so ipha needs to
17211 		 * be reinitialized.
17212 		 */
17213 		ipha = (ipha_t *)mp->b_rptr;
17214 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17215 			/* No user-level listener for PIM packets */
17216 			goto drop_pkt;
17217 		}
17218 		/* deliver to local raw users */
17219 		break;
17220 	case IPPROTO_ENCAP:
17221 		/*
17222 		 * Handle self-encapsulated packets (IP-in-IP where
17223 		 * the inner addresses == the outer addresses).
17224 		 */
17225 		hdr_length = IPH_HDR_LENGTH(ipha);
17226 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17227 		    mp->b_wptr) {
17228 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17229 			    sizeof (ipha_t) - mp->b_rptr)) {
17230 				BUMP_MIB(&ip_mib, ipInDiscards);
17231 				freemsg(first_mp);
17232 				return;
17233 			}
17234 			ipha = (ipha_t *)mp->b_rptr;
17235 		}
17236 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17237 		/*
17238 		 * Check the sanity of the inner IP header.
17239 		 */
17240 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17241 			BUMP_MIB(&ip_mib, ipInDiscards);
17242 			freemsg(first_mp);
17243 			return;
17244 		}
17245 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17246 			BUMP_MIB(&ip_mib, ipInDiscards);
17247 			freemsg(first_mp);
17248 			return;
17249 		}
17250 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17251 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17252 			ipsec_in_t *ii;
17253 
17254 			/*
17255 			 * Self-encapsulated tunnel packet. Remove
17256 			 * the outer IP header and fanout again.
17257 			 * We also need to make sure that the inner
17258 			 * header is pulled up until options.
17259 			 */
17260 			mp->b_rptr = (uchar_t *)inner_ipha;
17261 			ipha = inner_ipha;
17262 			hdr_length = IPH_HDR_LENGTH(ipha);
17263 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17264 				if (!pullupmsg(mp, (uchar_t *)ipha +
17265 				    + hdr_length - mp->b_rptr)) {
17266 					freemsg(first_mp);
17267 					return;
17268 				}
17269 				ipha = (ipha_t *)mp->b_rptr;
17270 			}
17271 			if (!mctl_present) {
17272 				ASSERT(first_mp == mp);
17273 				/*
17274 				 * This means that somebody is sending
17275 				 * Self-encapsualted packets without AH/ESP.
17276 				 * If AH/ESP was present, we would have already
17277 				 * allocated the first_mp.
17278 				 */
17279 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17280 				    NULL) {
17281 					ip1dbg(("ip_proto_input: IPSEC_IN "
17282 					    "allocation failure.\n"));
17283 					BUMP_MIB(&ip_mib, ipInDiscards);
17284 					freemsg(mp);
17285 					return;
17286 				}
17287 				first_mp->b_cont = mp;
17288 			}
17289 			/*
17290 			 * We generally store the ill_index if we need to
17291 			 * do IPSEC processing as we lose the ill queue when
17292 			 * we come back. But in this case, we never should
17293 			 * have to store the ill_index here as it should have
17294 			 * been stored previously when we processed the
17295 			 * AH/ESP header in this routine or for non-ipsec
17296 			 * cases, we still have the queue. But for some bad
17297 			 * packets from the wire, we can get to IPSEC after
17298 			 * this and we better store the index for that case.
17299 			 */
17300 			ill = (ill_t *)q->q_ptr;
17301 			ii = (ipsec_in_t *)first_mp->b_rptr;
17302 			ii->ipsec_in_ill_index =
17303 			    ill->ill_phyint->phyint_ifindex;
17304 			ii->ipsec_in_rill_index =
17305 			    recv_ill->ill_phyint->phyint_ifindex;
17306 			if (ii->ipsec_in_decaps) {
17307 				/*
17308 				 * This packet is self-encapsulated multiple
17309 				 * times. We don't want to recurse infinitely.
17310 				 * To keep it simple, drop the packet.
17311 				 */
17312 				BUMP_MIB(&ip_mib, ipInDiscards);
17313 				freemsg(first_mp);
17314 				return;
17315 			}
17316 			ii->ipsec_in_decaps = B_TRUE;
17317 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17318 			    ire);
17319 			return;
17320 		}
17321 		break;
17322 	case IPPROTO_AH:
17323 	case IPPROTO_ESP: {
17324 		/*
17325 		 * Fast path for AH/ESP. If this is the first time
17326 		 * we are sending a datagram to AH/ESP, allocate
17327 		 * a IPSEC_IN message and prepend it. Otherwise,
17328 		 * just fanout.
17329 		 */
17330 
17331 		int ipsec_rc;
17332 		ipsec_in_t *ii;
17333 
17334 		IP_STAT(ipsec_proto_ahesp);
17335 		if (!mctl_present) {
17336 			ASSERT(first_mp == mp);
17337 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17338 				ip1dbg(("ip_proto_input: IPSEC_IN "
17339 				    "allocation failure.\n"));
17340 				freemsg(hada_mp); /* okay ifnull */
17341 				BUMP_MIB(&ip_mib, ipInDiscards);
17342 				freemsg(mp);
17343 				return;
17344 			}
17345 			/*
17346 			 * Store the ill_index so that when we come back
17347 			 * from IPSEC we ride on the same queue.
17348 			 */
17349 			ill = (ill_t *)q->q_ptr;
17350 			ii = (ipsec_in_t *)first_mp->b_rptr;
17351 			ii->ipsec_in_ill_index =
17352 			    ill->ill_phyint->phyint_ifindex;
17353 			ii->ipsec_in_rill_index =
17354 			    recv_ill->ill_phyint->phyint_ifindex;
17355 			first_mp->b_cont = mp;
17356 			/*
17357 			 * Cache hardware acceleration info.
17358 			 */
17359 			if (hada_mp != NULL) {
17360 				IPSECHW_DEBUG(IPSECHW_PKT,
17361 				    ("ip_rput_local: caching data attr.\n"));
17362 				ii->ipsec_in_accelerated = B_TRUE;
17363 				ii->ipsec_in_da = hada_mp;
17364 				hada_mp = NULL;
17365 			}
17366 		} else {
17367 			ii = (ipsec_in_t *)first_mp->b_rptr;
17368 		}
17369 
17370 		if (!ipsec_loaded()) {
17371 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17372 			    ire->ire_zoneid);
17373 			return;
17374 		}
17375 
17376 		/* select inbound SA and have IPsec process the pkt */
17377 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17378 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17379 			if (esph == NULL)
17380 				return;
17381 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17382 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17383 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17384 			    first_mp, esph);
17385 		} else {
17386 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17387 			if (ah == NULL)
17388 				return;
17389 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17390 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17391 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17392 			    first_mp, ah);
17393 		}
17394 
17395 		switch (ipsec_rc) {
17396 		case IPSEC_STATUS_SUCCESS:
17397 			break;
17398 		case IPSEC_STATUS_FAILED:
17399 			BUMP_MIB(&ip_mib, ipInDiscards);
17400 			/* FALLTHRU */
17401 		case IPSEC_STATUS_PENDING:
17402 			return;
17403 		}
17404 		/* we're done with IPsec processing, send it up */
17405 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17406 		return;
17407 	}
17408 	default:
17409 		break;
17410 	}
17411 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17412 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17413 		    ire->ire_zoneid));
17414 		goto drop_pkt;
17415 	}
17416 	/*
17417 	 * Handle protocols with which IP is less intimate.  There
17418 	 * can be more than one stream bound to a particular
17419 	 * protocol.  When this is the case, each one gets a copy
17420 	 * of any incoming packets.
17421 	 */
17422 	ip_fanout_proto(q, first_mp, ill, ipha,
17423 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17424 	    B_TRUE, recv_ill, ire->ire_zoneid);
17425 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17426 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17427 	return;
17428 
17429 drop_pkt:
17430 	freemsg(first_mp);
17431 	if (hada_mp != NULL)
17432 		freeb(hada_mp);
17433 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17434 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17435 #undef	rptr
17436 #undef  iphs
17437 
17438 }
17439 
17440 /*
17441  * Update any source route, record route or timestamp options.
17442  * Check that we are at end of strict source route.
17443  * The options have already been checked for sanity in ip_rput_options().
17444  */
17445 static boolean_t
17446 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17447 {
17448 	ipoptp_t	opts;
17449 	uchar_t		*opt;
17450 	uint8_t		optval;
17451 	uint8_t		optlen;
17452 	ipaddr_t	dst;
17453 	uint32_t	ts;
17454 	ire_t		*dst_ire;
17455 	timestruc_t	now;
17456 	zoneid_t	zoneid;
17457 	ill_t		*ill;
17458 
17459 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17460 
17461 	ip2dbg(("ip_rput_local_options\n"));
17462 
17463 	for (optval = ipoptp_first(&opts, ipha);
17464 	    optval != IPOPT_EOL;
17465 	    optval = ipoptp_next(&opts)) {
17466 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17467 		opt = opts.ipoptp_cur;
17468 		optlen = opts.ipoptp_len;
17469 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17470 		    optval, optlen));
17471 		switch (optval) {
17472 			uint32_t off;
17473 		case IPOPT_SSRR:
17474 		case IPOPT_LSRR:
17475 			off = opt[IPOPT_OFFSET];
17476 			off--;
17477 			if (optlen < IP_ADDR_LEN ||
17478 			    off > optlen - IP_ADDR_LEN) {
17479 				/* End of source route */
17480 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17481 				break;
17482 			}
17483 			/*
17484 			 * This will only happen if two consecutive entries
17485 			 * in the source route contains our address or if
17486 			 * it is a packet with a loose source route which
17487 			 * reaches us before consuming the whole source route
17488 			 */
17489 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17490 			if (optval == IPOPT_SSRR) {
17491 				goto bad_src_route;
17492 			}
17493 			/*
17494 			 * Hack: instead of dropping the packet truncate the
17495 			 * source route to what has been used by filling the
17496 			 * rest with IPOPT_NOP.
17497 			 */
17498 			opt[IPOPT_OLEN] = (uint8_t)off;
17499 			while (off < optlen) {
17500 				opt[off++] = IPOPT_NOP;
17501 			}
17502 			break;
17503 		case IPOPT_RR:
17504 			off = opt[IPOPT_OFFSET];
17505 			off--;
17506 			if (optlen < IP_ADDR_LEN ||
17507 			    off > optlen - IP_ADDR_LEN) {
17508 				/* No more room - ignore */
17509 				ip1dbg((
17510 				    "ip_rput_local_options: end of RR\n"));
17511 				break;
17512 			}
17513 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17514 			    IP_ADDR_LEN);
17515 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17516 			break;
17517 		case IPOPT_TS:
17518 			/* Insert timestamp if there is romm */
17519 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17520 			case IPOPT_TS_TSONLY:
17521 				off = IPOPT_TS_TIMELEN;
17522 				break;
17523 			case IPOPT_TS_PRESPEC:
17524 			case IPOPT_TS_PRESPEC_RFC791:
17525 				/* Verify that the address matched */
17526 				off = opt[IPOPT_OFFSET] - 1;
17527 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17528 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17529 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17530 				if (dst_ire == NULL) {
17531 					/* Not for us */
17532 					break;
17533 				}
17534 				ire_refrele(dst_ire);
17535 				/* FALLTHRU */
17536 			case IPOPT_TS_TSANDADDR:
17537 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17538 				break;
17539 			default:
17540 				/*
17541 				 * ip_*put_options should have already
17542 				 * dropped this packet.
17543 				 */
17544 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17545 				    "unknown IT - bug in ip_rput_options?\n");
17546 				return (B_TRUE);	/* Keep "lint" happy */
17547 			}
17548 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17549 				/* Increase overflow counter */
17550 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17551 				opt[IPOPT_POS_OV_FLG] =
17552 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17553 				    (off << 4));
17554 				break;
17555 			}
17556 			off = opt[IPOPT_OFFSET] - 1;
17557 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17558 			case IPOPT_TS_PRESPEC:
17559 			case IPOPT_TS_PRESPEC_RFC791:
17560 			case IPOPT_TS_TSANDADDR:
17561 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17562 				    IP_ADDR_LEN);
17563 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17564 				/* FALLTHRU */
17565 			case IPOPT_TS_TSONLY:
17566 				off = opt[IPOPT_OFFSET] - 1;
17567 				/* Compute # of milliseconds since midnight */
17568 				gethrestime(&now);
17569 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17570 				    now.tv_nsec / (NANOSEC / MILLISEC);
17571 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17572 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17573 				break;
17574 			}
17575 			break;
17576 		}
17577 	}
17578 	return (B_TRUE);
17579 
17580 bad_src_route:
17581 	q = WR(q);
17582 	if (q->q_next != NULL)
17583 		ill = q->q_ptr;
17584 	else
17585 		ill = NULL;
17586 
17587 	/* make sure we clear any indication of a hardware checksum */
17588 	DB_CKSUMFLAGS(mp) = 0;
17589 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17590 	if (zoneid == ALL_ZONES)
17591 		freemsg(mp);
17592 	else
17593 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17594 	return (B_FALSE);
17595 
17596 }
17597 
17598 /*
17599  * Process IP options in an inbound packet.  If an option affects the
17600  * effective destination address, return the next hop address via dstp.
17601  * Returns -1 if something fails in which case an ICMP error has been sent
17602  * and mp freed.
17603  */
17604 static int
17605 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17606 {
17607 	ipoptp_t	opts;
17608 	uchar_t		*opt;
17609 	uint8_t		optval;
17610 	uint8_t		optlen;
17611 	ipaddr_t	dst;
17612 	intptr_t	code = 0;
17613 	ire_t		*ire = NULL;
17614 	zoneid_t	zoneid;
17615 	ill_t		*ill;
17616 
17617 	ip2dbg(("ip_rput_options\n"));
17618 	dst = ipha->ipha_dst;
17619 	for (optval = ipoptp_first(&opts, ipha);
17620 	    optval != IPOPT_EOL;
17621 	    optval = ipoptp_next(&opts)) {
17622 		opt = opts.ipoptp_cur;
17623 		optlen = opts.ipoptp_len;
17624 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17625 		    optval, optlen));
17626 		/*
17627 		 * Note: we need to verify the checksum before we
17628 		 * modify anything thus this routine only extracts the next
17629 		 * hop dst from any source route.
17630 		 */
17631 		switch (optval) {
17632 			uint32_t off;
17633 		case IPOPT_SSRR:
17634 		case IPOPT_LSRR:
17635 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17636 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17637 			if (ire == NULL) {
17638 				if (optval == IPOPT_SSRR) {
17639 					ip1dbg(("ip_rput_options: not next"
17640 					    " strict source route 0x%x\n",
17641 					    ntohl(dst)));
17642 					code = (char *)&ipha->ipha_dst -
17643 					    (char *)ipha;
17644 					goto param_prob; /* RouterReq's */
17645 				}
17646 				ip2dbg(("ip_rput_options: "
17647 				    "not next source route 0x%x\n",
17648 				    ntohl(dst)));
17649 				break;
17650 			}
17651 			ire_refrele(ire);
17652 
17653 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17654 				ip1dbg((
17655 				    "ip_rput_options: bad option offset\n"));
17656 				code = (char *)&opt[IPOPT_OLEN] -
17657 				    (char *)ipha;
17658 				goto param_prob;
17659 			}
17660 			off = opt[IPOPT_OFFSET];
17661 			off--;
17662 		redo_srr:
17663 			if (optlen < IP_ADDR_LEN ||
17664 			    off > optlen - IP_ADDR_LEN) {
17665 				/* End of source route */
17666 				ip1dbg(("ip_rput_options: end of SR\n"));
17667 				break;
17668 			}
17669 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17670 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17671 			    ntohl(dst)));
17672 
17673 			/*
17674 			 * Check if our address is present more than
17675 			 * once as consecutive hops in source route.
17676 			 * XXX verify per-interface ip_forwarding
17677 			 * for source route?
17678 			 */
17679 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17680 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17681 
17682 			if (ire != NULL) {
17683 				ire_refrele(ire);
17684 				off += IP_ADDR_LEN;
17685 				goto redo_srr;
17686 			}
17687 
17688 			if (dst == htonl(INADDR_LOOPBACK)) {
17689 				ip1dbg(("ip_rput_options: loopback addr in "
17690 				    "source route!\n"));
17691 				goto bad_src_route;
17692 			}
17693 			/*
17694 			 * For strict: verify that dst is directly
17695 			 * reachable.
17696 			 */
17697 			if (optval == IPOPT_SSRR) {
17698 				ire = ire_ftable_lookup(dst, 0, 0,
17699 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17700 				    MBLK_GETLABEL(mp),
17701 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17702 				if (ire == NULL) {
17703 					ip1dbg(("ip_rput_options: SSRR not "
17704 					    "directly reachable: 0x%x\n",
17705 					    ntohl(dst)));
17706 					goto bad_src_route;
17707 				}
17708 				ire_refrele(ire);
17709 			}
17710 			/*
17711 			 * Defer update of the offset and the record route
17712 			 * until the packet is forwarded.
17713 			 */
17714 			break;
17715 		case IPOPT_RR:
17716 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17717 				ip1dbg((
17718 				    "ip_rput_options: bad option offset\n"));
17719 				code = (char *)&opt[IPOPT_OLEN] -
17720 				    (char *)ipha;
17721 				goto param_prob;
17722 			}
17723 			break;
17724 		case IPOPT_TS:
17725 			/*
17726 			 * Verify that length >= 5 and that there is either
17727 			 * room for another timestamp or that the overflow
17728 			 * counter is not maxed out.
17729 			 */
17730 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17731 			if (optlen < IPOPT_MINLEN_IT) {
17732 				goto param_prob;
17733 			}
17734 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17735 				ip1dbg((
17736 				    "ip_rput_options: bad option offset\n"));
17737 				code = (char *)&opt[IPOPT_OFFSET] -
17738 				    (char *)ipha;
17739 				goto param_prob;
17740 			}
17741 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17742 			case IPOPT_TS_TSONLY:
17743 				off = IPOPT_TS_TIMELEN;
17744 				break;
17745 			case IPOPT_TS_TSANDADDR:
17746 			case IPOPT_TS_PRESPEC:
17747 			case IPOPT_TS_PRESPEC_RFC791:
17748 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17749 				break;
17750 			default:
17751 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17752 				    (char *)ipha;
17753 				goto param_prob;
17754 			}
17755 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17756 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17757 				/*
17758 				 * No room and the overflow counter is 15
17759 				 * already.
17760 				 */
17761 				goto param_prob;
17762 			}
17763 			break;
17764 		}
17765 	}
17766 
17767 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17768 		*dstp = dst;
17769 		return (0);
17770 	}
17771 
17772 	ip1dbg(("ip_rput_options: error processing IP options."));
17773 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17774 
17775 param_prob:
17776 	q = WR(q);
17777 	if (q->q_next != NULL)
17778 		ill = q->q_ptr;
17779 	else
17780 		ill = NULL;
17781 
17782 	/* make sure we clear any indication of a hardware checksum */
17783 	DB_CKSUMFLAGS(mp) = 0;
17784 	/* Don't know whether this is for non-global or global/forwarding */
17785 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17786 	if (zoneid == ALL_ZONES)
17787 		freemsg(mp);
17788 	else
17789 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17790 	return (-1);
17791 
17792 bad_src_route:
17793 	q = WR(q);
17794 	if (q->q_next != NULL)
17795 		ill = q->q_ptr;
17796 	else
17797 		ill = NULL;
17798 
17799 	/* make sure we clear any indication of a hardware checksum */
17800 	DB_CKSUMFLAGS(mp) = 0;
17801 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17802 	if (zoneid == ALL_ZONES)
17803 		freemsg(mp);
17804 	else
17805 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17806 	return (-1);
17807 }
17808 
17809 /*
17810  * IP & ICMP info in >=14 msg's ...
17811  *  - ip fixed part (mib2_ip_t)
17812  *  - icmp fixed part (mib2_icmp_t)
17813  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17814  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17815  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17816  *  - ipRouteAttributeTable (ip 102)	labeled routes
17817  *  - ip multicast membership (ip_member_t)
17818  *  - ip multicast source filtering (ip_grpsrc_t)
17819  *  - igmp fixed part (struct igmpstat)
17820  *  - multicast routing stats (struct mrtstat)
17821  *  - multicast routing vifs (array of struct vifctl)
17822  *  - multicast routing routes (array of struct mfcctl)
17823  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17824  *					One per ill plus one generic
17825  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17826  *					One per ill plus one generic
17827  *  - ipv6RouteEntry			all IPv6 IREs
17828  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17829  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17830  *  - ipv6AddrEntry			all IPv6 ipifs
17831  *  - ipv6 multicast membership (ipv6_member_t)
17832  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17833  *
17834  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17835  *
17836  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17837  * already filled in by the caller.
17838  * Return value of 0 indicates that no messages were sent and caller
17839  * should free mpctl.
17840  */
17841 int
17842 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17843 {
17844 
17845 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17846 		return (0);
17847 	}
17848 
17849 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17850 		return (1);
17851 	}
17852 
17853 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17854 		return (1);
17855 	}
17856 
17857 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17858 		return (1);
17859 	}
17860 
17861 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17862 		return (1);
17863 	}
17864 
17865 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17866 		return (1);
17867 	}
17868 
17869 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17870 		return (1);
17871 	}
17872 
17873 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17874 		return (1);
17875 	}
17876 
17877 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17878 		return (1);
17879 	}
17880 
17881 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17882 		return (1);
17883 	}
17884 
17885 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17886 		return (1);
17887 	}
17888 
17889 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17890 		return (1);
17891 	}
17892 
17893 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17894 		return (1);
17895 	}
17896 
17897 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17898 		return (1);
17899 	}
17900 
17901 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17902 		return (1);
17903 	}
17904 
17905 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17906 		return (1);
17907 	}
17908 
17909 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17910 		return (1);
17911 	}
17912 
17913 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17914 		return (1);
17915 	}
17916 	freemsg(mpctl);
17917 	return (1);
17918 }
17919 
17920 
17921 /* Get global IPv4 statistics */
17922 static mblk_t *
17923 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17924 {
17925 	struct opthdr		*optp;
17926 	mblk_t			*mp2ctl;
17927 
17928 	/*
17929 	 * make a copy of the original message
17930 	 */
17931 	mp2ctl = copymsg(mpctl);
17932 
17933 	/* fixed length IP structure... */
17934 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17935 	optp->level = MIB2_IP;
17936 	optp->name = 0;
17937 	SET_MIB(ip_mib.ipForwarding,
17938 	    (WE_ARE_FORWARDING ? 1 : 2));
17939 	SET_MIB(ip_mib.ipDefaultTTL,
17940 	    (uint32_t)ip_def_ttl);
17941 	SET_MIB(ip_mib.ipReasmTimeout,
17942 	    ip_g_frag_timeout);
17943 	SET_MIB(ip_mib.ipAddrEntrySize,
17944 	    sizeof (mib2_ipAddrEntry_t));
17945 	SET_MIB(ip_mib.ipRouteEntrySize,
17946 	    sizeof (mib2_ipRouteEntry_t));
17947 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17948 	    sizeof (mib2_ipNetToMediaEntry_t));
17949 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17950 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17951 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17952 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17953 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17954 	    (int)sizeof (ip_mib))) {
17955 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17956 		    (uint_t)sizeof (ip_mib)));
17957 	}
17958 
17959 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17960 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17961 	    (int)optp->level, (int)optp->name, (int)optp->len));
17962 	qreply(q, mpctl);
17963 	return (mp2ctl);
17964 }
17965 
17966 /* Global IPv4 ICMP statistics */
17967 static mblk_t *
17968 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17969 {
17970 	struct opthdr		*optp;
17971 	mblk_t			*mp2ctl;
17972 
17973 	/*
17974 	 * Make a copy of the original message
17975 	 */
17976 	mp2ctl = copymsg(mpctl);
17977 
17978 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17979 	optp->level = MIB2_ICMP;
17980 	optp->name = 0;
17981 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17982 	    (int)sizeof (icmp_mib))) {
17983 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17984 		    (uint_t)sizeof (icmp_mib)));
17985 	}
17986 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17987 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17988 	    (int)optp->level, (int)optp->name, (int)optp->len));
17989 	qreply(q, mpctl);
17990 	return (mp2ctl);
17991 }
17992 
17993 /* Global IPv4 IGMP statistics */
17994 static mblk_t *
17995 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17996 {
17997 	struct opthdr		*optp;
17998 	mblk_t			*mp2ctl;
17999 
18000 	/*
18001 	 * make a copy of the original message
18002 	 */
18003 	mp2ctl = copymsg(mpctl);
18004 
18005 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18006 	optp->level = EXPER_IGMP;
18007 	optp->name = 0;
18008 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
18009 	    (int)sizeof (igmpstat))) {
18010 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18011 		    (uint_t)sizeof (igmpstat)));
18012 	}
18013 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18014 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18015 	    (int)optp->level, (int)optp->name, (int)optp->len));
18016 	qreply(q, mpctl);
18017 	return (mp2ctl);
18018 }
18019 
18020 /* Global IPv4 Multicast Routing statistics */
18021 static mblk_t *
18022 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
18023 {
18024 	struct opthdr		*optp;
18025 	mblk_t			*mp2ctl;
18026 
18027 	/*
18028 	 * make a copy of the original message
18029 	 */
18030 	mp2ctl = copymsg(mpctl);
18031 
18032 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18033 	optp->level = EXPER_DVMRP;
18034 	optp->name = 0;
18035 	if (!ip_mroute_stats(mpctl->b_cont)) {
18036 		ip0dbg(("ip_mroute_stats: failed\n"));
18037 	}
18038 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18039 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18040 	    (int)optp->level, (int)optp->name, (int)optp->len));
18041 	qreply(q, mpctl);
18042 	return (mp2ctl);
18043 }
18044 
18045 /* IPv4 address information */
18046 static mblk_t *
18047 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18048 {
18049 	struct opthdr		*optp;
18050 	mblk_t			*mp2ctl;
18051 	mblk_t			*mp_tail = NULL;
18052 	ill_t			*ill;
18053 	ipif_t			*ipif;
18054 	uint_t			bitval;
18055 	mib2_ipAddrEntry_t	mae;
18056 	zoneid_t		zoneid;
18057 	ill_walk_context_t ctx;
18058 
18059 	/*
18060 	 * make a copy of the original message
18061 	 */
18062 	mp2ctl = copymsg(mpctl);
18063 
18064 	/* ipAddrEntryTable */
18065 
18066 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18067 	optp->level = MIB2_IP;
18068 	optp->name = MIB2_IP_ADDR;
18069 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18070 
18071 	rw_enter(&ill_g_lock, RW_READER);
18072 	ill = ILL_START_WALK_V4(&ctx);
18073 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18074 		for (ipif = ill->ill_ipif; ipif != NULL;
18075 		    ipif = ipif->ipif_next) {
18076 			if (ipif->ipif_zoneid != zoneid &&
18077 			    ipif->ipif_zoneid != ALL_ZONES)
18078 				continue;
18079 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18080 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18081 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18082 
18083 			(void) ipif_get_name(ipif,
18084 			    mae.ipAdEntIfIndex.o_bytes,
18085 			    OCTET_LENGTH);
18086 			mae.ipAdEntIfIndex.o_length =
18087 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18088 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18089 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18090 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18091 			mae.ipAdEntInfo.ae_subnet_len =
18092 			    ip_mask_to_plen(ipif->ipif_net_mask);
18093 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18094 			for (bitval = 1;
18095 			    bitval &&
18096 			    !(bitval & ipif->ipif_brd_addr);
18097 			    bitval <<= 1)
18098 				noop;
18099 			mae.ipAdEntBcastAddr = bitval;
18100 			mae.ipAdEntReasmMaxSize = 65535;
18101 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18102 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18103 			mae.ipAdEntInfo.ae_broadcast_addr =
18104 			    ipif->ipif_brd_addr;
18105 			mae.ipAdEntInfo.ae_pp_dst_addr =
18106 			    ipif->ipif_pp_dst_addr;
18107 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18108 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18109 
18110 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18111 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18112 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18113 				    "allocate %u bytes\n",
18114 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18115 			}
18116 		}
18117 	}
18118 	rw_exit(&ill_g_lock);
18119 
18120 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18121 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18122 	    (int)optp->level, (int)optp->name, (int)optp->len));
18123 	qreply(q, mpctl);
18124 	return (mp2ctl);
18125 }
18126 
18127 /* IPv6 address information */
18128 static mblk_t *
18129 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18130 {
18131 	struct opthdr		*optp;
18132 	mblk_t			*mp2ctl;
18133 	mblk_t			*mp_tail = NULL;
18134 	ill_t			*ill;
18135 	ipif_t			*ipif;
18136 	mib2_ipv6AddrEntry_t	mae6;
18137 	zoneid_t		zoneid;
18138 	ill_walk_context_t	ctx;
18139 
18140 	/*
18141 	 * make a copy of the original message
18142 	 */
18143 	mp2ctl = copymsg(mpctl);
18144 
18145 	/* ipv6AddrEntryTable */
18146 
18147 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18148 	optp->level = MIB2_IP6;
18149 	optp->name = MIB2_IP6_ADDR;
18150 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18151 
18152 	rw_enter(&ill_g_lock, RW_READER);
18153 	ill = ILL_START_WALK_V6(&ctx);
18154 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18155 		for (ipif = ill->ill_ipif; ipif != NULL;
18156 		    ipif = ipif->ipif_next) {
18157 			if (ipif->ipif_zoneid != zoneid &&
18158 			    ipif->ipif_zoneid != ALL_ZONES)
18159 				continue;
18160 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18161 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18162 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18163 
18164 			(void) ipif_get_name(ipif,
18165 			    mae6.ipv6AddrIfIndex.o_bytes,
18166 			    OCTET_LENGTH);
18167 			mae6.ipv6AddrIfIndex.o_length =
18168 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18169 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18170 			mae6.ipv6AddrPfxLength =
18171 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18172 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18173 			mae6.ipv6AddrInfo.ae_subnet_len =
18174 			    mae6.ipv6AddrPfxLength;
18175 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18176 
18177 			/* Type: stateless(1), stateful(2), unknown(3) */
18178 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18179 				mae6.ipv6AddrType = 1;
18180 			else
18181 				mae6.ipv6AddrType = 2;
18182 			/* Anycast: true(1), false(2) */
18183 			if (ipif->ipif_flags & IPIF_ANYCAST)
18184 				mae6.ipv6AddrAnycastFlag = 1;
18185 			else
18186 				mae6.ipv6AddrAnycastFlag = 2;
18187 
18188 			/*
18189 			 * Address status: preferred(1), deprecated(2),
18190 			 * invalid(3), inaccessible(4), unknown(5)
18191 			 */
18192 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18193 				mae6.ipv6AddrStatus = 3;
18194 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18195 				mae6.ipv6AddrStatus = 2;
18196 			else
18197 				mae6.ipv6AddrStatus = 1;
18198 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18199 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18200 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18201 						ipif->ipif_v6pp_dst_addr;
18202 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18203 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18204 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18205 				(char *)&mae6,
18206 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18207 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18208 				    "allocate %u bytes\n",
18209 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18210 			}
18211 		}
18212 	}
18213 	rw_exit(&ill_g_lock);
18214 
18215 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18216 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18217 	    (int)optp->level, (int)optp->name, (int)optp->len));
18218 	qreply(q, mpctl);
18219 	return (mp2ctl);
18220 }
18221 
18222 /* IPv4 multicast group membership. */
18223 static mblk_t *
18224 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18225 {
18226 	struct opthdr		*optp;
18227 	mblk_t			*mp2ctl;
18228 	ill_t			*ill;
18229 	ipif_t			*ipif;
18230 	ilm_t			*ilm;
18231 	ip_member_t		ipm;
18232 	mblk_t			*mp_tail = NULL;
18233 	ill_walk_context_t	ctx;
18234 	zoneid_t		zoneid;
18235 
18236 	/*
18237 	 * make a copy of the original message
18238 	 */
18239 	mp2ctl = copymsg(mpctl);
18240 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18241 
18242 	/* ipGroupMember table */
18243 	optp = (struct opthdr *)&mpctl->b_rptr[
18244 	    sizeof (struct T_optmgmt_ack)];
18245 	optp->level = MIB2_IP;
18246 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18247 
18248 	rw_enter(&ill_g_lock, RW_READER);
18249 	ill = ILL_START_WALK_V4(&ctx);
18250 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18251 		ILM_WALKER_HOLD(ill);
18252 		for (ipif = ill->ill_ipif; ipif != NULL;
18253 		    ipif = ipif->ipif_next) {
18254 			if (ipif->ipif_zoneid != zoneid &&
18255 			    ipif->ipif_zoneid != ALL_ZONES)
18256 				continue;	/* not this zone */
18257 			(void) ipif_get_name(ipif,
18258 			    ipm.ipGroupMemberIfIndex.o_bytes,
18259 			    OCTET_LENGTH);
18260 			ipm.ipGroupMemberIfIndex.o_length =
18261 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18262 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18263 				ASSERT(ilm->ilm_ipif != NULL);
18264 				ASSERT(ilm->ilm_ill == NULL);
18265 				if (ilm->ilm_ipif != ipif)
18266 					continue;
18267 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18268 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18269 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18270 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18271 				    (char *)&ipm, (int)sizeof (ipm))) {
18272 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18273 					    "failed to allocate %u bytes\n",
18274 						(uint_t)sizeof (ipm)));
18275 				}
18276 			}
18277 		}
18278 		ILM_WALKER_RELE(ill);
18279 	}
18280 	rw_exit(&ill_g_lock);
18281 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18282 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18283 	    (int)optp->level, (int)optp->name, (int)optp->len));
18284 	qreply(q, mpctl);
18285 	return (mp2ctl);
18286 }
18287 
18288 /* IPv6 multicast group membership. */
18289 static mblk_t *
18290 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18291 {
18292 	struct opthdr		*optp;
18293 	mblk_t			*mp2ctl;
18294 	ill_t			*ill;
18295 	ilm_t			*ilm;
18296 	ipv6_member_t		ipm6;
18297 	mblk_t			*mp_tail = NULL;
18298 	ill_walk_context_t	ctx;
18299 	zoneid_t		zoneid;
18300 
18301 	/*
18302 	 * make a copy of the original message
18303 	 */
18304 	mp2ctl = copymsg(mpctl);
18305 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18306 
18307 	/* ip6GroupMember table */
18308 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18309 	optp->level = MIB2_IP6;
18310 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18311 
18312 	rw_enter(&ill_g_lock, RW_READER);
18313 	ill = ILL_START_WALK_V6(&ctx);
18314 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18315 		ILM_WALKER_HOLD(ill);
18316 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18317 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18318 			ASSERT(ilm->ilm_ipif == NULL);
18319 			ASSERT(ilm->ilm_ill != NULL);
18320 			if (ilm->ilm_zoneid != zoneid)
18321 				continue;	/* not this zone */
18322 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18323 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18324 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18325 			if (!snmp_append_data2(mpctl->b_cont,
18326 			    &mp_tail,
18327 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18328 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18329 				    "failed to allocate %u bytes\n",
18330 				    (uint_t)sizeof (ipm6)));
18331 			}
18332 		}
18333 		ILM_WALKER_RELE(ill);
18334 	}
18335 	rw_exit(&ill_g_lock);
18336 
18337 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18338 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18339 	    (int)optp->level, (int)optp->name, (int)optp->len));
18340 	qreply(q, mpctl);
18341 	return (mp2ctl);
18342 }
18343 
18344 /* IP multicast filtered sources */
18345 static mblk_t *
18346 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18347 {
18348 	struct opthdr		*optp;
18349 	mblk_t			*mp2ctl;
18350 	ill_t			*ill;
18351 	ipif_t			*ipif;
18352 	ilm_t			*ilm;
18353 	ip_grpsrc_t		ips;
18354 	mblk_t			*mp_tail = NULL;
18355 	ill_walk_context_t	ctx;
18356 	zoneid_t		zoneid;
18357 	int			i;
18358 	slist_t			*sl;
18359 
18360 	/*
18361 	 * make a copy of the original message
18362 	 */
18363 	mp2ctl = copymsg(mpctl);
18364 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18365 
18366 	/* ipGroupSource table */
18367 	optp = (struct opthdr *)&mpctl->b_rptr[
18368 	    sizeof (struct T_optmgmt_ack)];
18369 	optp->level = MIB2_IP;
18370 	optp->name = EXPER_IP_GROUP_SOURCES;
18371 
18372 	rw_enter(&ill_g_lock, RW_READER);
18373 	ill = ILL_START_WALK_V4(&ctx);
18374 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18375 		ILM_WALKER_HOLD(ill);
18376 		for (ipif = ill->ill_ipif; ipif != NULL;
18377 		    ipif = ipif->ipif_next) {
18378 			if (ipif->ipif_zoneid != zoneid)
18379 				continue;	/* not this zone */
18380 			(void) ipif_get_name(ipif,
18381 			    ips.ipGroupSourceIfIndex.o_bytes,
18382 			    OCTET_LENGTH);
18383 			ips.ipGroupSourceIfIndex.o_length =
18384 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18385 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18386 				ASSERT(ilm->ilm_ipif != NULL);
18387 				ASSERT(ilm->ilm_ill == NULL);
18388 				sl = ilm->ilm_filter;
18389 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18390 					continue;
18391 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18392 				for (i = 0; i < sl->sl_numsrc; i++) {
18393 					if (!IN6_IS_ADDR_V4MAPPED(
18394 					    &sl->sl_addr[i]))
18395 						continue;
18396 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18397 					    ips.ipGroupSourceAddress);
18398 					if (snmp_append_data2(mpctl->b_cont,
18399 					    &mp_tail, (char *)&ips,
18400 					    (int)sizeof (ips)) == 0) {
18401 						ip1dbg(("ip_snmp_get_mib2_"
18402 						    "ip_group_src: failed to "
18403 						    "allocate %u bytes\n",
18404 						    (uint_t)sizeof (ips)));
18405 					}
18406 				}
18407 			}
18408 		}
18409 		ILM_WALKER_RELE(ill);
18410 	}
18411 	rw_exit(&ill_g_lock);
18412 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18413 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18414 	    (int)optp->level, (int)optp->name, (int)optp->len));
18415 	qreply(q, mpctl);
18416 	return (mp2ctl);
18417 }
18418 
18419 /* IPv6 multicast filtered sources. */
18420 static mblk_t *
18421 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18422 {
18423 	struct opthdr		*optp;
18424 	mblk_t			*mp2ctl;
18425 	ill_t			*ill;
18426 	ilm_t			*ilm;
18427 	ipv6_grpsrc_t		ips6;
18428 	mblk_t			*mp_tail = NULL;
18429 	ill_walk_context_t	ctx;
18430 	zoneid_t		zoneid;
18431 	int			i;
18432 	slist_t			*sl;
18433 
18434 	/*
18435 	 * make a copy of the original message
18436 	 */
18437 	mp2ctl = copymsg(mpctl);
18438 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18439 
18440 	/* ip6GroupMember table */
18441 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18442 	optp->level = MIB2_IP6;
18443 	optp->name = EXPER_IP6_GROUP_SOURCES;
18444 
18445 	rw_enter(&ill_g_lock, RW_READER);
18446 	ill = ILL_START_WALK_V6(&ctx);
18447 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18448 		ILM_WALKER_HOLD(ill);
18449 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18450 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18451 			ASSERT(ilm->ilm_ipif == NULL);
18452 			ASSERT(ilm->ilm_ill != NULL);
18453 			sl = ilm->ilm_filter;
18454 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18455 				continue;
18456 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18457 			for (i = 0; i < sl->sl_numsrc; i++) {
18458 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18459 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18460 				    (char *)&ips6, (int)sizeof (ips6))) {
18461 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18462 					    "group_src: failed to allocate "
18463 					    "%u bytes\n",
18464 					    (uint_t)sizeof (ips6)));
18465 				}
18466 			}
18467 		}
18468 		ILM_WALKER_RELE(ill);
18469 	}
18470 	rw_exit(&ill_g_lock);
18471 
18472 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18473 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18474 	    (int)optp->level, (int)optp->name, (int)optp->len));
18475 	qreply(q, mpctl);
18476 	return (mp2ctl);
18477 }
18478 
18479 /* Multicast routing virtual interface table. */
18480 static mblk_t *
18481 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18482 {
18483 	struct opthdr		*optp;
18484 	mblk_t			*mp2ctl;
18485 
18486 	/*
18487 	 * make a copy of the original message
18488 	 */
18489 	mp2ctl = copymsg(mpctl);
18490 
18491 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18492 	optp->level = EXPER_DVMRP;
18493 	optp->name = EXPER_DVMRP_VIF;
18494 	if (!ip_mroute_vif(mpctl->b_cont)) {
18495 		ip0dbg(("ip_mroute_vif: failed\n"));
18496 	}
18497 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18498 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18499 	    (int)optp->level, (int)optp->name, (int)optp->len));
18500 	qreply(q, mpctl);
18501 	return (mp2ctl);
18502 }
18503 
18504 /* Multicast routing table. */
18505 static mblk_t *
18506 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18507 {
18508 	struct opthdr		*optp;
18509 	mblk_t			*mp2ctl;
18510 
18511 	/*
18512 	 * make a copy of the original message
18513 	 */
18514 	mp2ctl = copymsg(mpctl);
18515 
18516 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18517 	optp->level = EXPER_DVMRP;
18518 	optp->name = EXPER_DVMRP_MRT;
18519 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18520 		ip0dbg(("ip_mroute_mrt: failed\n"));
18521 	}
18522 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18523 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18524 	    (int)optp->level, (int)optp->name, (int)optp->len));
18525 	qreply(q, mpctl);
18526 	return (mp2ctl);
18527 }
18528 
18529 /*
18530  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18531  * in one IRE walk.
18532  */
18533 static mblk_t *
18534 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18535 {
18536 	struct opthdr	*optp;
18537 	mblk_t		*mp2ctl;	/* Returned */
18538 	mblk_t		*mp3ctl;	/* nettomedia */
18539 	mblk_t		*mp4ctl;	/* routeattrs */
18540 	iproutedata_t	ird;
18541 	zoneid_t	zoneid;
18542 
18543 	/*
18544 	 * make copies of the original message
18545 	 *	- mp2ctl is returned unchanged to the caller for his use
18546 	 *	- mpctl is sent upstream as ipRouteEntryTable
18547 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18548 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18549 	 */
18550 	mp2ctl = copymsg(mpctl);
18551 	mp3ctl = copymsg(mpctl);
18552 	mp4ctl = copymsg(mpctl);
18553 	if (mp3ctl == NULL || mp4ctl == NULL) {
18554 		freemsg(mp4ctl);
18555 		freemsg(mp3ctl);
18556 		freemsg(mp2ctl);
18557 		freemsg(mpctl);
18558 		return (NULL);
18559 	}
18560 
18561 	bzero(&ird, sizeof (ird));
18562 
18563 	ird.ird_route.lp_head = mpctl->b_cont;
18564 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18565 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18566 
18567 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18568 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18569 	if (zoneid == GLOBAL_ZONEID) {
18570 		/*
18571 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18572 		 * the sys_net_config privilege, it can only run in the global
18573 		 * zone, so we don't display these IREs in the other zones.
18574 		 */
18575 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18576 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18577 	}
18578 
18579 	/* ipRouteEntryTable in mpctl */
18580 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18581 	optp->level = MIB2_IP;
18582 	optp->name = MIB2_IP_ROUTE;
18583 	optp->len = msgdsize(ird.ird_route.lp_head);
18584 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18585 	    (int)optp->level, (int)optp->name, (int)optp->len));
18586 	qreply(q, mpctl);
18587 
18588 	/* ipNetToMediaEntryTable in mp3ctl */
18589 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18590 	optp->level = MIB2_IP;
18591 	optp->name = MIB2_IP_MEDIA;
18592 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18593 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18594 	    (int)optp->level, (int)optp->name, (int)optp->len));
18595 	qreply(q, mp3ctl);
18596 
18597 	/* ipRouteAttributeTable in mp4ctl */
18598 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18599 	optp->level = MIB2_IP;
18600 	optp->name = EXPER_IP_RTATTR;
18601 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18602 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18603 	    (int)optp->level, (int)optp->name, (int)optp->len));
18604 	if (optp->len == 0)
18605 		freemsg(mp4ctl);
18606 	else
18607 		qreply(q, mp4ctl);
18608 
18609 	return (mp2ctl);
18610 }
18611 
18612 /*
18613  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18614  * ipv6NetToMediaEntryTable in an NDP walk.
18615  */
18616 static mblk_t *
18617 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18618 {
18619 	struct opthdr	*optp;
18620 	mblk_t		*mp2ctl;	/* Returned */
18621 	mblk_t		*mp3ctl;	/* nettomedia */
18622 	mblk_t		*mp4ctl;	/* routeattrs */
18623 	iproutedata_t	ird;
18624 	zoneid_t	zoneid;
18625 
18626 	/*
18627 	 * make copies of the original message
18628 	 *	- mp2ctl is returned unchanged to the caller for his use
18629 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18630 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18631 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18632 	 */
18633 	mp2ctl = copymsg(mpctl);
18634 	mp3ctl = copymsg(mpctl);
18635 	mp4ctl = copymsg(mpctl);
18636 	if (mp3ctl == NULL || mp4ctl == NULL) {
18637 		freemsg(mp4ctl);
18638 		freemsg(mp3ctl);
18639 		freemsg(mp2ctl);
18640 		freemsg(mpctl);
18641 		return (NULL);
18642 	}
18643 
18644 	bzero(&ird, sizeof (ird));
18645 
18646 	ird.ird_route.lp_head = mpctl->b_cont;
18647 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18648 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18649 
18650 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18651 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18652 
18653 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18654 	optp->level = MIB2_IP6;
18655 	optp->name = MIB2_IP6_ROUTE;
18656 	optp->len = msgdsize(ird.ird_route.lp_head);
18657 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18658 	    (int)optp->level, (int)optp->name, (int)optp->len));
18659 	qreply(q, mpctl);
18660 
18661 	/* ipv6NetToMediaEntryTable in mp3ctl */
18662 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18663 
18664 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18665 	optp->level = MIB2_IP6;
18666 	optp->name = MIB2_IP6_MEDIA;
18667 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18668 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18669 	    (int)optp->level, (int)optp->name, (int)optp->len));
18670 	qreply(q, mp3ctl);
18671 
18672 	/* ipv6RouteAttributeTable in mp4ctl */
18673 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18674 	optp->level = MIB2_IP6;
18675 	optp->name = EXPER_IP_RTATTR;
18676 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18677 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18678 	    (int)optp->level, (int)optp->name, (int)optp->len));
18679 	if (optp->len == 0)
18680 		freemsg(mp4ctl);
18681 	else
18682 		qreply(q, mp4ctl);
18683 
18684 	return (mp2ctl);
18685 }
18686 
18687 /*
18688  * ICMPv6 mib: One per ill
18689  */
18690 static mblk_t *
18691 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18692 {
18693 	struct opthdr		*optp;
18694 	mblk_t			*mp2ctl;
18695 	ill_t			*ill;
18696 	ill_walk_context_t	ctx;
18697 	mblk_t			*mp_tail = NULL;
18698 
18699 	/*
18700 	 * Make a copy of the original message
18701 	 */
18702 	mp2ctl = copymsg(mpctl);
18703 
18704 	/* fixed length IPv6 structure ... */
18705 
18706 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18707 	optp->level = MIB2_IP6;
18708 	optp->name = 0;
18709 	/* Include "unknown interface" ip6_mib */
18710 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18711 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18712 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18713 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18714 	    sizeof (mib2_ipv6IfStatsEntry_t));
18715 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18716 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18717 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18718 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18719 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18720 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18721 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18722 	    (int)sizeof (ip6_mib))) {
18723 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18724 		    (uint_t)sizeof (ip6_mib)));
18725 	}
18726 
18727 	rw_enter(&ill_g_lock, RW_READER);
18728 	ill = ILL_START_WALK_V6(&ctx);
18729 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18730 		ill->ill_ip6_mib->ipv6IfIndex =
18731 		    ill->ill_phyint->phyint_ifindex;
18732 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18733 		    ipv6_forward ? 1 : 2);
18734 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18735 		    ill->ill_max_hops);
18736 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18737 		    sizeof (mib2_ipv6IfStatsEntry_t));
18738 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18739 		    sizeof (mib2_ipv6AddrEntry_t));
18740 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18741 		    sizeof (mib2_ipv6RouteEntry_t));
18742 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18743 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18744 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18745 		    sizeof (ipv6_member_t));
18746 
18747 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18748 		    (char *)ill->ill_ip6_mib,
18749 		    (int)sizeof (*ill->ill_ip6_mib))) {
18750 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18751 				"%u bytes\n",
18752 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18753 		}
18754 	}
18755 	rw_exit(&ill_g_lock);
18756 
18757 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18758 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18759 	    (int)optp->level, (int)optp->name, (int)optp->len));
18760 	qreply(q, mpctl);
18761 	return (mp2ctl);
18762 }
18763 
18764 /*
18765  * ICMPv6 mib: One per ill
18766  */
18767 static mblk_t *
18768 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18769 {
18770 	struct opthdr		*optp;
18771 	mblk_t			*mp2ctl;
18772 	ill_t			*ill;
18773 	ill_walk_context_t	ctx;
18774 	mblk_t			*mp_tail = NULL;
18775 	/*
18776 	 * Make a copy of the original message
18777 	 */
18778 	mp2ctl = copymsg(mpctl);
18779 
18780 	/* fixed length ICMPv6 structure ... */
18781 
18782 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18783 	optp->level = MIB2_ICMP6;
18784 	optp->name = 0;
18785 	/* Include "unknown interface" icmp6_mib */
18786 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18787 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18788 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18789 	    (int)sizeof (icmp6_mib))) {
18790 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18791 		    (uint_t)sizeof (icmp6_mib)));
18792 	}
18793 
18794 	rw_enter(&ill_g_lock, RW_READER);
18795 	ill = ILL_START_WALK_V6(&ctx);
18796 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18797 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18798 		    ill->ill_phyint->phyint_ifindex;
18799 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18800 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18801 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18802 		    (char *)ill->ill_icmp6_mib,
18803 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18804 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18805 			    "%u bytes\n",
18806 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18807 		}
18808 	}
18809 	rw_exit(&ill_g_lock);
18810 
18811 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18812 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18813 	    (int)optp->level, (int)optp->name, (int)optp->len));
18814 	qreply(q, mpctl);
18815 	return (mp2ctl);
18816 }
18817 
18818 /*
18819  * ire_walk routine to create both ipRouteEntryTable and
18820  * ipRouteAttributeTable in one IRE walk
18821  */
18822 static void
18823 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18824 {
18825 	ill_t				*ill;
18826 	ipif_t				*ipif;
18827 	mib2_ipRouteEntry_t		*re;
18828 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18829 	ipaddr_t			gw_addr;
18830 	tsol_ire_gw_secattr_t		*attrp;
18831 	tsol_gc_t			*gc = NULL;
18832 	tsol_gcgrp_t			*gcgrp = NULL;
18833 	uint_t				sacnt = 0;
18834 	int				i;
18835 
18836 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18837 
18838 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18839 		return;
18840 
18841 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18842 		mutex_enter(&attrp->igsa_lock);
18843 		if ((gc = attrp->igsa_gc) != NULL) {
18844 			gcgrp = gc->gc_grp;
18845 			ASSERT(gcgrp != NULL);
18846 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18847 			sacnt = 1;
18848 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18849 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18850 			gc = gcgrp->gcgrp_head;
18851 			sacnt = gcgrp->gcgrp_count;
18852 		}
18853 		mutex_exit(&attrp->igsa_lock);
18854 
18855 		/* do nothing if there's no gc to report */
18856 		if (gc == NULL) {
18857 			ASSERT(sacnt == 0);
18858 			if (gcgrp != NULL) {
18859 				/* we might as well drop the lock now */
18860 				rw_exit(&gcgrp->gcgrp_rwlock);
18861 				gcgrp = NULL;
18862 			}
18863 			attrp = NULL;
18864 		}
18865 
18866 		ASSERT(gc == NULL || (gcgrp != NULL &&
18867 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18868 	}
18869 	ASSERT(sacnt == 0 || gc != NULL);
18870 
18871 	if (sacnt != 0 &&
18872 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18873 		kmem_free(re, sizeof (*re));
18874 		rw_exit(&gcgrp->gcgrp_rwlock);
18875 		return;
18876 	}
18877 
18878 	/*
18879 	 * Return all IRE types for route table... let caller pick and choose
18880 	 */
18881 	re->ipRouteDest = ire->ire_addr;
18882 	ipif = ire->ire_ipif;
18883 	re->ipRouteIfIndex.o_length = 0;
18884 	if (ire->ire_type == IRE_CACHE) {
18885 		ill = (ill_t *)ire->ire_stq->q_ptr;
18886 		re->ipRouteIfIndex.o_length =
18887 		    ill->ill_name_length == 0 ? 0 :
18888 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18889 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18890 		    re->ipRouteIfIndex.o_length);
18891 	} else if (ipif != NULL) {
18892 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18893 		    OCTET_LENGTH);
18894 		re->ipRouteIfIndex.o_length =
18895 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18896 	}
18897 	re->ipRouteMetric1 = -1;
18898 	re->ipRouteMetric2 = -1;
18899 	re->ipRouteMetric3 = -1;
18900 	re->ipRouteMetric4 = -1;
18901 
18902 	gw_addr = ire->ire_gateway_addr;
18903 
18904 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18905 		re->ipRouteNextHop = ire->ire_src_addr;
18906 	else
18907 		re->ipRouteNextHop = gw_addr;
18908 	/* indirect(4), direct(3), or invalid(2) */
18909 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18910 		re->ipRouteType = 2;
18911 	else
18912 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18913 	re->ipRouteProto = -1;
18914 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18915 	re->ipRouteMask = ire->ire_mask;
18916 	re->ipRouteMetric5 = -1;
18917 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18918 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18919 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18920 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18921 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18922 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18923 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18924 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18925 	re->ipRouteInfo.re_in_ill.o_length = 0;
18926 
18927 	if (ire->ire_flags & RTF_DYNAMIC) {
18928 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18929 	} else {
18930 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18931 	}
18932 
18933 	if (ire->ire_in_ill != NULL) {
18934 		re->ipRouteInfo.re_in_ill.o_length =
18935 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18936 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18937 		bcopy(ire->ire_in_ill->ill_name,
18938 		    re->ipRouteInfo.re_in_ill.o_bytes,
18939 		    re->ipRouteInfo.re_in_ill.o_length);
18940 	}
18941 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18942 
18943 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18944 	    (char *)re, (int)sizeof (*re))) {
18945 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18946 		    (uint_t)sizeof (*re)));
18947 	}
18948 
18949 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18950 		iaeptr->iae_routeidx = ird->ird_idx;
18951 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18952 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18953 	}
18954 
18955 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18956 	    (char *)iae, sacnt * sizeof (*iae))) {
18957 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18958 		    (unsigned)(sacnt * sizeof (*iae))));
18959 	}
18960 
18961 	/* bump route index for next pass */
18962 	ird->ird_idx++;
18963 
18964 	kmem_free(re, sizeof (*re));
18965 	if (sacnt != 0)
18966 		kmem_free(iae, sacnt * sizeof (*iae));
18967 
18968 	if (gcgrp != NULL)
18969 		rw_exit(&gcgrp->gcgrp_rwlock);
18970 }
18971 
18972 /*
18973  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18974  */
18975 static void
18976 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18977 {
18978 	ill_t				*ill;
18979 	ipif_t				*ipif;
18980 	mib2_ipv6RouteEntry_t		*re;
18981 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18982 	in6_addr_t			gw_addr_v6;
18983 	tsol_ire_gw_secattr_t		*attrp;
18984 	tsol_gc_t			*gc = NULL;
18985 	tsol_gcgrp_t			*gcgrp = NULL;
18986 	uint_t				sacnt = 0;
18987 	int				i;
18988 
18989 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18990 
18991 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18992 		return;
18993 
18994 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18995 		mutex_enter(&attrp->igsa_lock);
18996 		if ((gc = attrp->igsa_gc) != NULL) {
18997 			gcgrp = gc->gc_grp;
18998 			ASSERT(gcgrp != NULL);
18999 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19000 			sacnt = 1;
19001 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19002 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19003 			gc = gcgrp->gcgrp_head;
19004 			sacnt = gcgrp->gcgrp_count;
19005 		}
19006 		mutex_exit(&attrp->igsa_lock);
19007 
19008 		/* do nothing if there's no gc to report */
19009 		if (gc == NULL) {
19010 			ASSERT(sacnt == 0);
19011 			if (gcgrp != NULL) {
19012 				/* we might as well drop the lock now */
19013 				rw_exit(&gcgrp->gcgrp_rwlock);
19014 				gcgrp = NULL;
19015 			}
19016 			attrp = NULL;
19017 		}
19018 
19019 		ASSERT(gc == NULL || (gcgrp != NULL &&
19020 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19021 	}
19022 	ASSERT(sacnt == 0 || gc != NULL);
19023 
19024 	if (sacnt != 0 &&
19025 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19026 		kmem_free(re, sizeof (*re));
19027 		rw_exit(&gcgrp->gcgrp_rwlock);
19028 		return;
19029 	}
19030 
19031 	/*
19032 	 * Return all IRE types for route table... let caller pick and choose
19033 	 */
19034 	re->ipv6RouteDest = ire->ire_addr_v6;
19035 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19036 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19037 	re->ipv6RouteIfIndex.o_length = 0;
19038 	ipif = ire->ire_ipif;
19039 	if (ire->ire_type == IRE_CACHE) {
19040 		ill = (ill_t *)ire->ire_stq->q_ptr;
19041 		re->ipv6RouteIfIndex.o_length =
19042 		    ill->ill_name_length == 0 ? 0 :
19043 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19044 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19045 		    re->ipv6RouteIfIndex.o_length);
19046 	} else if (ipif != NULL) {
19047 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19048 		    OCTET_LENGTH);
19049 		re->ipv6RouteIfIndex.o_length =
19050 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19051 	}
19052 
19053 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19054 
19055 	mutex_enter(&ire->ire_lock);
19056 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19057 	mutex_exit(&ire->ire_lock);
19058 
19059 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19060 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19061 	else
19062 		re->ipv6RouteNextHop = gw_addr_v6;
19063 
19064 	/* remote(4), local(3), or discard(2) */
19065 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19066 		re->ipv6RouteType = 2;
19067 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19068 		re->ipv6RouteType = 3;
19069 	else
19070 		re->ipv6RouteType = 4;
19071 
19072 	re->ipv6RouteProtocol	= -1;
19073 	re->ipv6RoutePolicy	= 0;
19074 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19075 	re->ipv6RouteNextHopRDI	= 0;
19076 	re->ipv6RouteWeight	= 0;
19077 	re->ipv6RouteMetric	= 0;
19078 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19079 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19080 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19081 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19082 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19083 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19084 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19085 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19086 
19087 	if (ire->ire_flags & RTF_DYNAMIC) {
19088 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19089 	} else {
19090 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19091 	}
19092 
19093 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19094 	    (char *)re, (int)sizeof (*re))) {
19095 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19096 		    (uint_t)sizeof (*re)));
19097 	}
19098 
19099 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19100 		iaeptr->iae_routeidx = ird->ird_idx;
19101 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19102 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19103 	}
19104 
19105 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19106 	    (char *)iae, sacnt * sizeof (*iae))) {
19107 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19108 		    (unsigned)(sacnt * sizeof (*iae))));
19109 	}
19110 
19111 	/* bump route index for next pass */
19112 	ird->ird_idx++;
19113 
19114 	kmem_free(re, sizeof (*re));
19115 	if (sacnt != 0)
19116 		kmem_free(iae, sacnt * sizeof (*iae));
19117 
19118 	if (gcgrp != NULL)
19119 		rw_exit(&gcgrp->gcgrp_rwlock);
19120 }
19121 
19122 /*
19123  * ndp_walk routine to create ipv6NetToMediaEntryTable
19124  */
19125 static int
19126 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19127 {
19128 	ill_t				*ill;
19129 	mib2_ipv6NetToMediaEntry_t	ntme;
19130 	dl_unitdata_req_t		*dl;
19131 
19132 	ill = nce->nce_ill;
19133 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19134 		return (0);
19135 
19136 	/*
19137 	 * Neighbor cache entry attached to IRE with on-link
19138 	 * destination.
19139 	 */
19140 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19141 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19142 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19143 	    (nce->nce_res_mp != NULL)) {
19144 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19145 		ntme.ipv6NetToMediaPhysAddress.o_length =
19146 		    dl->dl_dest_addr_length;
19147 	} else {
19148 		ntme.ipv6NetToMediaPhysAddress.o_length =
19149 		    ill->ill_phys_addr_length;
19150 	}
19151 	if (nce->nce_res_mp != NULL) {
19152 		bcopy((char *)nce->nce_res_mp->b_rptr +
19153 		    NCE_LL_ADDR_OFFSET(ill),
19154 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19155 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19156 	} else {
19157 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19158 		    ill->ill_phys_addr_length);
19159 	}
19160 	/*
19161 	 * Note: Returns ND_* states. Should be:
19162 	 * reachable(1), stale(2), delay(3), probe(4),
19163 	 * invalid(5), unknown(6)
19164 	 */
19165 	ntme.ipv6NetToMediaState = nce->nce_state;
19166 	ntme.ipv6NetToMediaLastUpdated = 0;
19167 
19168 	/* other(1), dynamic(2), static(3), local(4) */
19169 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19170 		ntme.ipv6NetToMediaType = 4;
19171 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19172 		ntme.ipv6NetToMediaType = 1;
19173 	} else {
19174 		ntme.ipv6NetToMediaType = 2;
19175 	}
19176 
19177 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19178 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19179 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19180 		    (uint_t)sizeof (ntme)));
19181 	}
19182 	return (0);
19183 }
19184 
19185 /*
19186  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19187  */
19188 /* ARGSUSED */
19189 int
19190 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19191 {
19192 	switch (level) {
19193 	case MIB2_IP:
19194 	case MIB2_ICMP:
19195 		switch (name) {
19196 		default:
19197 			break;
19198 		}
19199 		return (1);
19200 	default:
19201 		return (1);
19202 	}
19203 }
19204 
19205 /*
19206  * Called before the options are updated to check if this packet will
19207  * be source routed from here.
19208  * This routine assumes that the options are well formed i.e. that they
19209  * have already been checked.
19210  */
19211 static boolean_t
19212 ip_source_routed(ipha_t *ipha)
19213 {
19214 	ipoptp_t	opts;
19215 	uchar_t		*opt;
19216 	uint8_t		optval;
19217 	uint8_t		optlen;
19218 	ipaddr_t	dst;
19219 	ire_t		*ire;
19220 
19221 	if (IS_SIMPLE_IPH(ipha)) {
19222 		ip2dbg(("not source routed\n"));
19223 		return (B_FALSE);
19224 	}
19225 	dst = ipha->ipha_dst;
19226 	for (optval = ipoptp_first(&opts, ipha);
19227 	    optval != IPOPT_EOL;
19228 	    optval = ipoptp_next(&opts)) {
19229 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19230 		opt = opts.ipoptp_cur;
19231 		optlen = opts.ipoptp_len;
19232 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19233 		    optval, optlen));
19234 		switch (optval) {
19235 			uint32_t off;
19236 		case IPOPT_SSRR:
19237 		case IPOPT_LSRR:
19238 			/*
19239 			 * If dst is one of our addresses and there are some
19240 			 * entries left in the source route return (true).
19241 			 */
19242 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19243 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19244 			if (ire == NULL) {
19245 				ip2dbg(("ip_source_routed: not next"
19246 				    " source route 0x%x\n",
19247 				    ntohl(dst)));
19248 				return (B_FALSE);
19249 			}
19250 			ire_refrele(ire);
19251 			off = opt[IPOPT_OFFSET];
19252 			off--;
19253 			if (optlen < IP_ADDR_LEN ||
19254 			    off > optlen - IP_ADDR_LEN) {
19255 				/* End of source route */
19256 				ip1dbg(("ip_source_routed: end of SR\n"));
19257 				return (B_FALSE);
19258 			}
19259 			return (B_TRUE);
19260 		}
19261 	}
19262 	ip2dbg(("not source routed\n"));
19263 	return (B_FALSE);
19264 }
19265 
19266 /*
19267  * Check if the packet contains any source route.
19268  */
19269 static boolean_t
19270 ip_source_route_included(ipha_t *ipha)
19271 {
19272 	ipoptp_t	opts;
19273 	uint8_t		optval;
19274 
19275 	if (IS_SIMPLE_IPH(ipha))
19276 		return (B_FALSE);
19277 	for (optval = ipoptp_first(&opts, ipha);
19278 	    optval != IPOPT_EOL;
19279 	    optval = ipoptp_next(&opts)) {
19280 		switch (optval) {
19281 		case IPOPT_SSRR:
19282 		case IPOPT_LSRR:
19283 			return (B_TRUE);
19284 		}
19285 	}
19286 	return (B_FALSE);
19287 }
19288 
19289 /*
19290  * Called when the IRE expiration timer fires.
19291  */
19292 /* ARGSUSED */
19293 void
19294 ip_trash_timer_expire(void *args)
19295 {
19296 	int	flush_flag = 0;
19297 
19298 	/*
19299 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19300 	 * This lock makes sure that a new invocation of this function
19301 	 * that occurs due to an almost immediate timer firing will not
19302 	 * progress beyond this point until the current invocation is done
19303 	 */
19304 	mutex_enter(&ip_trash_timer_lock);
19305 	ip_ire_expire_id = 0;
19306 	mutex_exit(&ip_trash_timer_lock);
19307 
19308 	/* Periodic timer */
19309 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19310 		/*
19311 		 * Remove all IRE_CACHE entries since they might
19312 		 * contain arp information.
19313 		 */
19314 		flush_flag |= FLUSH_ARP_TIME;
19315 		ip_ire_arp_time_elapsed = 0;
19316 		IP_STAT(ip_ire_arp_timer_expired);
19317 	}
19318 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19319 		/* Remove all redirects */
19320 		flush_flag |= FLUSH_REDIRECT_TIME;
19321 		ip_ire_rd_time_elapsed = 0;
19322 		IP_STAT(ip_ire_redirect_timer_expired);
19323 	}
19324 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19325 		/* Increase path mtu */
19326 		flush_flag |= FLUSH_MTU_TIME;
19327 		ip_ire_pmtu_time_elapsed = 0;
19328 		IP_STAT(ip_ire_pmtu_timer_expired);
19329 	}
19330 
19331 	/*
19332 	 * Optimize for the case when there are no redirects in the
19333 	 * ftable, that is, no need to walk the ftable in that case.
19334 	 */
19335 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19336 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19337 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19338 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19339 	}
19340 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19341 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19342 		    ire_expire, (char *)(uintptr_t)flush_flag,
19343 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19344 	}
19345 	if (flush_flag & FLUSH_MTU_TIME) {
19346 		/*
19347 		 * Walk all IPv6 IRE's and update them
19348 		 * Note that ARP and redirect timers are not
19349 		 * needed since NUD handles stale entries.
19350 		 */
19351 		flush_flag = FLUSH_MTU_TIME;
19352 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19353 		    ALL_ZONES);
19354 	}
19355 
19356 	ip_ire_arp_time_elapsed += ip_timer_interval;
19357 	ip_ire_rd_time_elapsed += ip_timer_interval;
19358 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19359 
19360 	/*
19361 	 * Hold the lock to serialize timeout calls and prevent
19362 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19363 	 * for the timer to fire and a new invocation of this function
19364 	 * to start before the return value of timeout has been stored
19365 	 * in ip_ire_expire_id by the current invocation.
19366 	 */
19367 	mutex_enter(&ip_trash_timer_lock);
19368 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19369 	    MSEC_TO_TICK(ip_timer_interval));
19370 	mutex_exit(&ip_trash_timer_lock);
19371 }
19372 
19373 /*
19374  * Called by the memory allocator subsystem directly, when the system
19375  * is running low on memory.
19376  */
19377 /* ARGSUSED */
19378 void
19379 ip_trash_ire_reclaim(void *args)
19380 {
19381 	ire_cache_count_t icc;
19382 	ire_cache_reclaim_t icr;
19383 	ncc_cache_count_t ncc;
19384 	nce_cache_reclaim_t ncr;
19385 	uint_t delete_cnt;
19386 	/*
19387 	 * Memory reclaim call back.
19388 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19389 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19390 	 * entries, determine what fraction to free for
19391 	 * each category of IRE_CACHE entries giving absolute priority
19392 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19393 	 * entry will be freed unless all offlink entries are freed).
19394 	 */
19395 	icc.icc_total = 0;
19396 	icc.icc_unused = 0;
19397 	icc.icc_offlink = 0;
19398 	icc.icc_pmtu = 0;
19399 	icc.icc_onlink = 0;
19400 	ire_walk(ire_cache_count, (char *)&icc);
19401 
19402 	/*
19403 	 * Free NCEs for IPv6 like the onlink ires.
19404 	 */
19405 	ncc.ncc_total = 0;
19406 	ncc.ncc_host = 0;
19407 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19408 
19409 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19410 	    icc.icc_pmtu + icc.icc_onlink);
19411 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19412 	IP_STAT(ip_trash_ire_reclaim_calls);
19413 	if (delete_cnt == 0)
19414 		return;
19415 	IP_STAT(ip_trash_ire_reclaim_success);
19416 	/* Always delete all unused offlink entries */
19417 	icr.icr_unused = 1;
19418 	if (delete_cnt <= icc.icc_unused) {
19419 		/*
19420 		 * Only need to free unused entries.  In other words,
19421 		 * there are enough unused entries to free to meet our
19422 		 * target number of freed ire cache entries.
19423 		 */
19424 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19425 		ncr.ncr_host = 0;
19426 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19427 		/*
19428 		 * Only need to free unused entries, plus a fraction of offlink
19429 		 * entries.  It follows from the first if statement that
19430 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19431 		 */
19432 		delete_cnt -= icc.icc_unused;
19433 		/* Round up # deleted by truncating fraction */
19434 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19435 		icr.icr_pmtu = icr.icr_onlink = 0;
19436 		ncr.ncr_host = 0;
19437 	} else if (delete_cnt <=
19438 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19439 		/*
19440 		 * Free all unused and offlink entries, plus a fraction of
19441 		 * pmtu entries.  It follows from the previous if statement
19442 		 * that icc_pmtu is non-zero, and that
19443 		 * delete_cnt != icc_unused + icc_offlink.
19444 		 */
19445 		icr.icr_offlink = 1;
19446 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19447 		/* Round up # deleted by truncating fraction */
19448 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19449 		icr.icr_onlink = 0;
19450 		ncr.ncr_host = 0;
19451 	} else {
19452 		/*
19453 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19454 		 * of onlink entries.  If we're here, then we know that
19455 		 * icc_onlink is non-zero, and that
19456 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19457 		 */
19458 		icr.icr_offlink = icr.icr_pmtu = 1;
19459 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19460 		    icc.icc_pmtu;
19461 		/* Round up # deleted by truncating fraction */
19462 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19463 		/* Using the same delete fraction as for onlink IREs */
19464 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19465 	}
19466 #ifdef DEBUG
19467 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19468 	    "fractions %d/%d/%d/%d\n",
19469 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19470 	    icc.icc_unused, icc.icc_offlink,
19471 	    icc.icc_pmtu, icc.icc_onlink,
19472 	    icr.icr_unused, icr.icr_offlink,
19473 	    icr.icr_pmtu, icr.icr_onlink));
19474 #endif
19475 	ire_walk(ire_cache_reclaim, (char *)&icr);
19476 	if (ncr.ncr_host != 0)
19477 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19478 		    (uchar_t *)&ncr);
19479 #ifdef DEBUG
19480 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19481 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19482 	ire_walk(ire_cache_count, (char *)&icc);
19483 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19484 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19485 	    icc.icc_pmtu, icc.icc_onlink));
19486 #endif
19487 }
19488 
19489 /*
19490  * ip_unbind is called when a copy of an unbind request is received from the
19491  * upper level protocol.  We remove this conn from any fanout hash list it is
19492  * on, and zero out the bind information.  No reply is expected up above.
19493  */
19494 mblk_t *
19495 ip_unbind(queue_t *q, mblk_t *mp)
19496 {
19497 	conn_t	*connp = Q_TO_CONN(q);
19498 
19499 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19500 
19501 	if (is_system_labeled() && connp->conn_anon_port) {
19502 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19503 		    connp->conn_mlp_type, connp->conn_ulp,
19504 		    ntohs(connp->conn_lport), B_FALSE);
19505 		connp->conn_anon_port = 0;
19506 	}
19507 	connp->conn_mlp_type = mlptSingle;
19508 
19509 	ipcl_hash_remove(connp);
19510 
19511 	ASSERT(mp->b_cont == NULL);
19512 	/*
19513 	 * Convert mp into a T_OK_ACK
19514 	 */
19515 	mp = mi_tpi_ok_ack_alloc(mp);
19516 
19517 	/*
19518 	 * should not happen in practice... T_OK_ACK is smaller than the
19519 	 * original message.
19520 	 */
19521 	if (mp == NULL)
19522 		return (NULL);
19523 
19524 	/*
19525 	 * Don't bzero the ports if its TCP since TCP still needs the
19526 	 * lport to remove it from its own bind hash. TCP will do the
19527 	 * cleanup.
19528 	 */
19529 	if (!IPCL_IS_TCP(connp))
19530 		bzero(&connp->u_port, sizeof (connp->u_port));
19531 
19532 	return (mp);
19533 }
19534 
19535 /*
19536  * Write side put procedure.  Outbound data, IOCTLs, responses from
19537  * resolvers, etc, come down through here.
19538  *
19539  * arg2 is always a queue_t *.
19540  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19541  * the zoneid.
19542  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19543  */
19544 void
19545 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19546 {
19547 	conn_t		*connp = NULL;
19548 	queue_t		*q = (queue_t *)arg2;
19549 	ipha_t		*ipha;
19550 #define	rptr	((uchar_t *)ipha)
19551 	ire_t		*ire = NULL;
19552 	ire_t		*sctp_ire = NULL;
19553 	uint32_t	v_hlen_tos_len;
19554 	ipaddr_t	dst;
19555 	mblk_t		*first_mp = NULL;
19556 	boolean_t	mctl_present;
19557 	ipsec_out_t	*io;
19558 	int		match_flags;
19559 	ill_t		*attach_ill = NULL;
19560 					/* Bind to IPIF_NOFAILOVER ill etc. */
19561 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19562 	ipif_t		*dst_ipif;
19563 	boolean_t	multirt_need_resolve = B_FALSE;
19564 	mblk_t		*copy_mp = NULL;
19565 	int		err;
19566 	zoneid_t	zoneid;
19567 	int	adjust;
19568 	uint16_t iplen;
19569 	boolean_t	need_decref = B_FALSE;
19570 	boolean_t	ignore_dontroute = B_FALSE;
19571 	boolean_t	ignore_nexthop = B_FALSE;
19572 	boolean_t	ip_nexthop = B_FALSE;
19573 	ipaddr_t	nexthop_addr;
19574 
19575 #ifdef	_BIG_ENDIAN
19576 #define	V_HLEN	(v_hlen_tos_len >> 24)
19577 #else
19578 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19579 #endif
19580 
19581 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19582 	    "ip_wput_start: q %p", q);
19583 
19584 	/*
19585 	 * ip_wput fast path
19586 	 */
19587 
19588 	/* is packet from ARP ? */
19589 	if (q->q_next != NULL) {
19590 		zoneid = (zoneid_t)(uintptr_t)arg;
19591 		goto qnext;
19592 	}
19593 
19594 	connp = (conn_t *)arg;
19595 	ASSERT(connp != NULL);
19596 	zoneid = connp->conn_zoneid;
19597 
19598 	/* is queue flow controlled? */
19599 	if ((q->q_first != NULL || connp->conn_draining) &&
19600 	    (caller == IP_WPUT)) {
19601 		ASSERT(!need_decref);
19602 		(void) putq(q, mp);
19603 		return;
19604 	}
19605 
19606 	/* Multidata transmit? */
19607 	if (DB_TYPE(mp) == M_MULTIDATA) {
19608 		/*
19609 		 * We should never get here, since all Multidata messages
19610 		 * originating from tcp should have been directed over to
19611 		 * tcp_multisend() in the first place.
19612 		 */
19613 		BUMP_MIB(&ip_mib, ipOutDiscards);
19614 		freemsg(mp);
19615 		return;
19616 	} else if (DB_TYPE(mp) != M_DATA)
19617 		goto notdata;
19618 
19619 	if (mp->b_flag & MSGHASREF) {
19620 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19621 		mp->b_flag &= ~MSGHASREF;
19622 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19623 		need_decref = B_TRUE;
19624 	}
19625 	ipha = (ipha_t *)mp->b_rptr;
19626 
19627 	/* is IP header non-aligned or mblk smaller than basic IP header */
19628 #ifndef SAFETY_BEFORE_SPEED
19629 	if (!OK_32PTR(rptr) ||
19630 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19631 		goto hdrtoosmall;
19632 #endif
19633 
19634 	ASSERT(OK_32PTR(ipha));
19635 
19636 	/*
19637 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19638 	 * wrong version, we'll catch it again in ip_output_v6.
19639 	 *
19640 	 * Note that this is *only* locally-generated output here, and never
19641 	 * forwarded data, and that we need to deal only with transports that
19642 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19643 	 * label.)
19644 	 */
19645 	if (is_system_labeled() &&
19646 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19647 	    !connp->conn_ulp_labeled) {
19648 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19649 		    connp->conn_mac_exempt);
19650 		ipha = (ipha_t *)mp->b_rptr;
19651 		if (err != 0) {
19652 			first_mp = mp;
19653 			if (err == EINVAL)
19654 				goto icmp_parameter_problem;
19655 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19656 			goto drop_pkt;
19657 		}
19658 		iplen = ntohs(ipha->ipha_length) + adjust;
19659 		ipha->ipha_length = htons(iplen);
19660 	}
19661 
19662 	/*
19663 	 * If there is a policy, try to attach an ipsec_out in
19664 	 * the front. At the end, first_mp either points to a
19665 	 * M_DATA message or IPSEC_OUT message linked to a
19666 	 * M_DATA message. We have to do it now as we might
19667 	 * lose the "conn" if we go through ip_newroute.
19668 	 */
19669 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19670 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19671 		    ipha->ipha_protocol)) == NULL)) {
19672 			if (need_decref)
19673 				CONN_DEC_REF(connp);
19674 			return;
19675 		} else {
19676 			ASSERT(mp->b_datap->db_type == M_CTL);
19677 			first_mp = mp;
19678 			mp = mp->b_cont;
19679 			mctl_present = B_TRUE;
19680 		}
19681 	} else {
19682 		first_mp = mp;
19683 		mctl_present = B_FALSE;
19684 	}
19685 
19686 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19687 
19688 	/* is wrong version or IP options present */
19689 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19690 		goto version_hdrlen_check;
19691 	dst = ipha->ipha_dst;
19692 
19693 	if (connp->conn_nofailover_ill != NULL) {
19694 		attach_ill = conn_get_held_ill(connp,
19695 		    &connp->conn_nofailover_ill, &err);
19696 		if (err == ILL_LOOKUP_FAILED) {
19697 			if (need_decref)
19698 				CONN_DEC_REF(connp);
19699 			freemsg(first_mp);
19700 			return;
19701 		}
19702 	}
19703 
19704 	/* is packet multicast? */
19705 	if (CLASSD(dst))
19706 		goto multicast;
19707 
19708 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19709 	    (connp->conn_nexthop_set)) {
19710 		/*
19711 		 * If the destination is a broadcast or a loopback
19712 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19713 		 * through the standard path. But in the case of local
19714 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19715 		 * the standard path not IP_XMIT_IF.
19716 		 */
19717 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19718 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19719 		    (ire->ire_type != IRE_LOOPBACK))) {
19720 			if ((connp->conn_dontroute ||
19721 			    connp->conn_nexthop_set) && (ire != NULL) &&
19722 			    (ire->ire_type == IRE_LOCAL))
19723 				goto standard_path;
19724 
19725 			if (ire != NULL) {
19726 				ire_refrele(ire);
19727 				/* No more access to ire */
19728 				ire = NULL;
19729 			}
19730 			/*
19731 			 * bypass routing checks and go directly to
19732 			 * interface.
19733 			 */
19734 			if (connp->conn_dontroute) {
19735 				goto dontroute;
19736 			} else if (connp->conn_nexthop_set) {
19737 				ip_nexthop = B_TRUE;
19738 				nexthop_addr = connp->conn_nexthop_v4;
19739 				goto send_from_ill;
19740 			}
19741 
19742 			/*
19743 			 * If IP_XMIT_IF socket option is set,
19744 			 * then we allow unicast and multicast
19745 			 * packets to go through the ill. It is
19746 			 * quite possible that the destination
19747 			 * is not in the ire cache table and we
19748 			 * do not want to go to ip_newroute()
19749 			 * instead we call ip_newroute_ipif.
19750 			 */
19751 			xmit_ill = conn_get_held_ill(connp,
19752 			    &connp->conn_xmit_if_ill, &err);
19753 			if (err == ILL_LOOKUP_FAILED) {
19754 				if (attach_ill != NULL)
19755 					ill_refrele(attach_ill);
19756 				if (need_decref)
19757 					CONN_DEC_REF(connp);
19758 				freemsg(first_mp);
19759 				return;
19760 			}
19761 			goto send_from_ill;
19762 		}
19763 standard_path:
19764 		/* Must be a broadcast, a loopback or a local ire */
19765 		if (ire != NULL) {
19766 			ire_refrele(ire);
19767 			/* No more access to ire */
19768 			ire = NULL;
19769 		}
19770 	}
19771 
19772 	if (attach_ill != NULL)
19773 		goto send_from_ill;
19774 
19775 	/*
19776 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19777 	 * this for the tcp global queue and listen end point
19778 	 * as it does not really have a real destination to
19779 	 * talk to.  This is also true for SCTP.
19780 	 */
19781 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19782 	    !connp->conn_fully_bound) {
19783 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19784 		if (ire == NULL)
19785 			goto noirefound;
19786 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19787 		    "ip_wput_end: q %p (%S)", q, "end");
19788 
19789 		/*
19790 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19791 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19792 		 */
19793 		if (ire->ire_flags & RTF_MULTIRT) {
19794 
19795 			/*
19796 			 * Force the TTL of multirouted packets if required.
19797 			 * The TTL of such packets is bounded by the
19798 			 * ip_multirt_ttl ndd variable.
19799 			 */
19800 			if ((ip_multirt_ttl > 0) &&
19801 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19802 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19803 				    "(was %d), dst 0x%08x\n",
19804 				    ip_multirt_ttl, ipha->ipha_ttl,
19805 				    ntohl(ire->ire_addr)));
19806 				ipha->ipha_ttl = ip_multirt_ttl;
19807 			}
19808 			/*
19809 			 * We look at this point if there are pending
19810 			 * unresolved routes. ire_multirt_resolvable()
19811 			 * checks in O(n) that all IRE_OFFSUBNET ire
19812 			 * entries for the packet's destination and
19813 			 * flagged RTF_MULTIRT are currently resolved.
19814 			 * If some remain unresolved, we make a copy
19815 			 * of the current message. It will be used
19816 			 * to initiate additional route resolutions.
19817 			 */
19818 			multirt_need_resolve =
19819 			    ire_multirt_need_resolve(ire->ire_addr,
19820 			    MBLK_GETLABEL(first_mp));
19821 			ip2dbg(("ip_wput[TCP]: ire %p, "
19822 			    "multirt_need_resolve %d, first_mp %p\n",
19823 			    (void *)ire, multirt_need_resolve,
19824 			    (void *)first_mp));
19825 			if (multirt_need_resolve) {
19826 				copy_mp = copymsg(first_mp);
19827 				if (copy_mp != NULL) {
19828 					MULTIRT_DEBUG_TAG(copy_mp);
19829 				}
19830 			}
19831 		}
19832 
19833 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19834 
19835 		/*
19836 		 * Try to resolve another multiroute if
19837 		 * ire_multirt_need_resolve() deemed it necessary.
19838 		 */
19839 		if (copy_mp != NULL) {
19840 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19841 		}
19842 		if (need_decref)
19843 			CONN_DEC_REF(connp);
19844 		return;
19845 	}
19846 
19847 	/*
19848 	 * Access to conn_ire_cache. (protected by conn_lock)
19849 	 *
19850 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19851 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19852 	 * send a packet or two with the IRE_CACHE that is going away.
19853 	 * Access to the ire requires an ire refhold on the ire prior to
19854 	 * its use since an interface unplumb thread may delete the cached
19855 	 * ire and release the refhold at any time.
19856 	 *
19857 	 * Caching an ire in the conn_ire_cache
19858 	 *
19859 	 * o Caching an ire pointer in the conn requires a strict check for
19860 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19861 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19862 	 * in the conn is done after making sure under the bucket lock that the
19863 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19864 	 * caching an ire after the unplumb thread has cleaned up the conn.
19865 	 * If the conn does not send a packet subsequently the unplumb thread
19866 	 * will be hanging waiting for the ire count to drop to zero.
19867 	 *
19868 	 * o We also need to atomically test for a null conn_ire_cache and
19869 	 * set the conn_ire_cache under the the protection of the conn_lock
19870 	 * to avoid races among concurrent threads trying to simultaneously
19871 	 * cache an ire in the conn_ire_cache.
19872 	 */
19873 	mutex_enter(&connp->conn_lock);
19874 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19875 
19876 	if (ire != NULL && ire->ire_addr == dst &&
19877 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19878 
19879 		IRE_REFHOLD(ire);
19880 		mutex_exit(&connp->conn_lock);
19881 
19882 	} else {
19883 		boolean_t cached = B_FALSE;
19884 		connp->conn_ire_cache = NULL;
19885 		mutex_exit(&connp->conn_lock);
19886 		/* Release the old ire */
19887 		if (ire != NULL && sctp_ire == NULL)
19888 			IRE_REFRELE_NOTR(ire);
19889 
19890 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19891 		if (ire == NULL)
19892 			goto noirefound;
19893 		IRE_REFHOLD_NOTR(ire);
19894 
19895 		mutex_enter(&connp->conn_lock);
19896 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19897 		    connp->conn_ire_cache == NULL) {
19898 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19899 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19900 				connp->conn_ire_cache = ire;
19901 				cached = B_TRUE;
19902 			}
19903 			rw_exit(&ire->ire_bucket->irb_lock);
19904 		}
19905 		mutex_exit(&connp->conn_lock);
19906 
19907 		/*
19908 		 * We can continue to use the ire but since it was
19909 		 * not cached, we should drop the extra reference.
19910 		 */
19911 		if (!cached)
19912 			IRE_REFRELE_NOTR(ire);
19913 	}
19914 
19915 
19916 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19917 	    "ip_wput_end: q %p (%S)", q, "end");
19918 
19919 	/*
19920 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19921 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19922 	 */
19923 	if (ire->ire_flags & RTF_MULTIRT) {
19924 
19925 		/*
19926 		 * Force the TTL of multirouted packets if required.
19927 		 * The TTL of such packets is bounded by the
19928 		 * ip_multirt_ttl ndd variable.
19929 		 */
19930 		if ((ip_multirt_ttl > 0) &&
19931 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19932 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19933 			    "(was %d), dst 0x%08x\n",
19934 			    ip_multirt_ttl, ipha->ipha_ttl,
19935 			    ntohl(ire->ire_addr)));
19936 			ipha->ipha_ttl = ip_multirt_ttl;
19937 		}
19938 
19939 		/*
19940 		 * At this point, we check to see if there are any pending
19941 		 * unresolved routes. ire_multirt_resolvable()
19942 		 * checks in O(n) that all IRE_OFFSUBNET ire
19943 		 * entries for the packet's destination and
19944 		 * flagged RTF_MULTIRT are currently resolved.
19945 		 * If some remain unresolved, we make a copy
19946 		 * of the current message. It will be used
19947 		 * to initiate additional route resolutions.
19948 		 */
19949 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19950 		    MBLK_GETLABEL(first_mp));
19951 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19952 		    "multirt_need_resolve %d, first_mp %p\n",
19953 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19954 		if (multirt_need_resolve) {
19955 			copy_mp = copymsg(first_mp);
19956 			if (copy_mp != NULL) {
19957 				MULTIRT_DEBUG_TAG(copy_mp);
19958 			}
19959 		}
19960 	}
19961 
19962 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19963 
19964 	/*
19965 	 * Try to resolve another multiroute if
19966 	 * ire_multirt_resolvable() deemed it necessary
19967 	 */
19968 	if (copy_mp != NULL) {
19969 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19970 	}
19971 	if (need_decref)
19972 		CONN_DEC_REF(connp);
19973 	return;
19974 
19975 qnext:
19976 	/*
19977 	 * Upper Level Protocols pass down complete IP datagrams
19978 	 * as M_DATA messages.	Everything else is a sideshow.
19979 	 *
19980 	 * 1) We could be re-entering ip_wput because of ip_neworute
19981 	 *    in which case we could have a IPSEC_OUT message. We
19982 	 *    need to pass through ip_wput like other datagrams and
19983 	 *    hence cannot branch to ip_wput_nondata.
19984 	 *
19985 	 * 2) ARP, AH, ESP, and other clients who are on the module
19986 	 *    instance of IP stream, give us something to deal with.
19987 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19988 	 *
19989 	 * 3) ICMP replies also could come here.
19990 	 */
19991 	if (DB_TYPE(mp) != M_DATA) {
19992 	    notdata:
19993 		if (DB_TYPE(mp) == M_CTL) {
19994 			/*
19995 			 * M_CTL messages are used by ARP, AH and ESP to
19996 			 * communicate with IP. We deal with IPSEC_IN and
19997 			 * IPSEC_OUT here. ip_wput_nondata handles other
19998 			 * cases.
19999 			 */
20000 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20001 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20002 				first_mp = mp->b_cont;
20003 				first_mp->b_flag &= ~MSGHASREF;
20004 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20005 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20006 				CONN_DEC_REF(connp);
20007 				connp = NULL;
20008 			}
20009 			if (ii->ipsec_info_type == IPSEC_IN) {
20010 				/*
20011 				 * Either this message goes back to
20012 				 * IPSEC for further processing or to
20013 				 * ULP after policy checks.
20014 				 */
20015 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20016 				return;
20017 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20018 				io = (ipsec_out_t *)ii;
20019 				if (io->ipsec_out_proc_begin) {
20020 					/*
20021 					 * IPSEC processing has already started.
20022 					 * Complete it.
20023 					 * IPQoS notes: We don't care what is
20024 					 * in ipsec_out_ill_index since this
20025 					 * won't be processed for IPQoS policies
20026 					 * in ipsec_out_process.
20027 					 */
20028 					ipsec_out_process(q, mp, NULL,
20029 					    io->ipsec_out_ill_index);
20030 					return;
20031 				} else {
20032 					connp = (q->q_next != NULL) ?
20033 					    NULL : Q_TO_CONN(q);
20034 					first_mp = mp;
20035 					mp = mp->b_cont;
20036 					mctl_present = B_TRUE;
20037 				}
20038 				zoneid = io->ipsec_out_zoneid;
20039 				ASSERT(zoneid != ALL_ZONES);
20040 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20041 				/*
20042 				 * It's an IPsec control message requesting
20043 				 * an SADB update to be sent to the IPsec
20044 				 * hardware acceleration capable ills.
20045 				 */
20046 				ipsec_ctl_t *ipsec_ctl =
20047 				    (ipsec_ctl_t *)mp->b_rptr;
20048 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20049 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20050 				mblk_t *cmp = mp->b_cont;
20051 
20052 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20053 				ASSERT(cmp != NULL);
20054 
20055 				freeb(mp);
20056 				ill_ipsec_capab_send_all(satype, cmp, sa);
20057 				return;
20058 			} else {
20059 				/*
20060 				 * This must be ARP or special TSOL signaling.
20061 				 */
20062 				ip_wput_nondata(NULL, q, mp, NULL);
20063 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20064 				    "ip_wput_end: q %p (%S)", q, "nondata");
20065 				return;
20066 			}
20067 		} else {
20068 			/*
20069 			 * This must be non-(ARP/AH/ESP) messages.
20070 			 */
20071 			ASSERT(!need_decref);
20072 			ip_wput_nondata(NULL, q, mp, NULL);
20073 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20074 			    "ip_wput_end: q %p (%S)", q, "nondata");
20075 			return;
20076 		}
20077 	} else {
20078 		first_mp = mp;
20079 		mctl_present = B_FALSE;
20080 	}
20081 
20082 	ASSERT(first_mp != NULL);
20083 	/*
20084 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20085 	 * to make sure that this packet goes out on the same interface it
20086 	 * came in. We handle that here.
20087 	 */
20088 	if (mctl_present) {
20089 		uint_t ifindex;
20090 
20091 		io = (ipsec_out_t *)first_mp->b_rptr;
20092 		if (io->ipsec_out_attach_if ||
20093 		    io->ipsec_out_xmit_if ||
20094 		    io->ipsec_out_ip_nexthop) {
20095 			ill_t	*ill;
20096 
20097 			/*
20098 			 * We may have lost the conn context if we are
20099 			 * coming here from ip_newroute(). Copy the
20100 			 * nexthop information.
20101 			 */
20102 			if (io->ipsec_out_ip_nexthop) {
20103 				ip_nexthop = B_TRUE;
20104 				nexthop_addr = io->ipsec_out_nexthop_addr;
20105 
20106 				ipha = (ipha_t *)mp->b_rptr;
20107 				dst = ipha->ipha_dst;
20108 				goto send_from_ill;
20109 			} else {
20110 				ASSERT(io->ipsec_out_ill_index != 0);
20111 				ifindex = io->ipsec_out_ill_index;
20112 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20113 				    NULL, NULL, NULL, NULL);
20114 				/*
20115 				 * ipsec_out_xmit_if bit is used to tell
20116 				 * ip_wput to use the ill to send outgoing data
20117 				 * as we have no conn when data comes from ICMP
20118 				 * error msg routines. Currently this feature is
20119 				 * only used by ip_mrtun_forward routine.
20120 				 */
20121 				if (io->ipsec_out_xmit_if) {
20122 					xmit_ill = ill;
20123 					if (xmit_ill == NULL) {
20124 						ip1dbg(("ip_output:bad ifindex "
20125 						    "for xmit_ill %d\n",
20126 						    ifindex));
20127 						freemsg(first_mp);
20128 						BUMP_MIB(&ip_mib,
20129 						    ipOutDiscards);
20130 						ASSERT(!need_decref);
20131 						return;
20132 					}
20133 					/* Free up the ipsec_out_t mblk */
20134 					ASSERT(first_mp->b_cont == mp);
20135 					first_mp->b_cont = NULL;
20136 					freeb(first_mp);
20137 					/* Just send the IP header+ICMP+data */
20138 					first_mp = mp;
20139 					ipha = (ipha_t *)mp->b_rptr;
20140 					dst = ipha->ipha_dst;
20141 					goto send_from_ill;
20142 				} else {
20143 					attach_ill = ill;
20144 				}
20145 
20146 				if (attach_ill == NULL) {
20147 					ASSERT(xmit_ill == NULL);
20148 					ip1dbg(("ip_output: bad ifindex for "
20149 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20150 					    ifindex));
20151 					freemsg(first_mp);
20152 					BUMP_MIB(&ip_mib, ipOutDiscards);
20153 					ASSERT(!need_decref);
20154 					return;
20155 				}
20156 			}
20157 		}
20158 	}
20159 
20160 	ASSERT(xmit_ill == NULL);
20161 
20162 	/* We have a complete IP datagram heading outbound. */
20163 	ipha = (ipha_t *)mp->b_rptr;
20164 
20165 #ifndef SPEED_BEFORE_SAFETY
20166 	/*
20167 	 * Make sure we have a full-word aligned message and that at least
20168 	 * a simple IP header is accessible in the first message.  If not,
20169 	 * try a pullup.
20170 	 */
20171 	if (!OK_32PTR(rptr) ||
20172 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20173 	    hdrtoosmall:
20174 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20175 			BUMP_MIB(&ip_mib, ipOutDiscards);
20176 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20177 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20178 			if (first_mp == NULL)
20179 				first_mp = mp;
20180 			goto drop_pkt;
20181 		}
20182 
20183 		/* This function assumes that mp points to an IPv4 packet. */
20184 		if (is_system_labeled() && q->q_next == NULL &&
20185 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20186 		    !connp->conn_ulp_labeled) {
20187 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20188 			    &adjust, connp->conn_mac_exempt);
20189 			ipha = (ipha_t *)mp->b_rptr;
20190 			if (first_mp != NULL)
20191 				first_mp->b_cont = mp;
20192 			if (err != 0) {
20193 				if (first_mp == NULL)
20194 					first_mp = mp;
20195 				if (err == EINVAL)
20196 					goto icmp_parameter_problem;
20197 				ip2dbg(("ip_wput: label check failed (%d)\n",
20198 				    err));
20199 				goto drop_pkt;
20200 			}
20201 			iplen = ntohs(ipha->ipha_length) + adjust;
20202 			ipha->ipha_length = htons(iplen);
20203 		}
20204 
20205 		ipha = (ipha_t *)mp->b_rptr;
20206 		if (first_mp == NULL) {
20207 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20208 			/*
20209 			 * If we got here because of "goto hdrtoosmall"
20210 			 * We need to attach a IPSEC_OUT.
20211 			 */
20212 			if (connp->conn_out_enforce_policy) {
20213 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20214 				    NULL, ipha->ipha_protocol)) == NULL)) {
20215 					if (need_decref)
20216 						CONN_DEC_REF(connp);
20217 					return;
20218 				} else {
20219 					ASSERT(mp->b_datap->db_type == M_CTL);
20220 					first_mp = mp;
20221 					mp = mp->b_cont;
20222 					mctl_present = B_TRUE;
20223 				}
20224 			} else {
20225 				first_mp = mp;
20226 				mctl_present = B_FALSE;
20227 			}
20228 		}
20229 	}
20230 #endif
20231 
20232 	/* Most of the code below is written for speed, not readability */
20233 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20234 
20235 	/*
20236 	 * If ip_newroute() fails, we're going to need a full
20237 	 * header for the icmp wraparound.
20238 	 */
20239 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20240 		uint_t	v_hlen;
20241 	    version_hdrlen_check:
20242 		ASSERT(first_mp != NULL);
20243 		v_hlen = V_HLEN;
20244 		/*
20245 		 * siphon off IPv6 packets coming down from transport
20246 		 * layer modules here.
20247 		 * Note: high-order bit carries NUD reachability confirmation
20248 		 */
20249 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20250 			/*
20251 			 * XXX implement a IPv4 and IPv6 packet counter per
20252 			 * conn and switch when ratio exceeds e.g. 10:1
20253 			 */
20254 #ifdef notyet
20255 			if (q->q_next == NULL) /* Avoid ill queue */
20256 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20257 #endif
20258 			BUMP_MIB(&ip_mib, ipOutIPv6);
20259 			ASSERT(xmit_ill == NULL);
20260 			if (attach_ill != NULL)
20261 				ill_refrele(attach_ill);
20262 			if (need_decref)
20263 				mp->b_flag |= MSGHASREF;
20264 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20265 			return;
20266 		}
20267 
20268 		if ((v_hlen >> 4) != IP_VERSION) {
20269 			BUMP_MIB(&ip_mib, ipOutDiscards);
20270 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20271 			    "ip_wput_end: q %p (%S)", q, "badvers");
20272 			goto drop_pkt;
20273 		}
20274 		/*
20275 		 * Is the header length at least 20 bytes?
20276 		 *
20277 		 * Are there enough bytes accessible in the header?  If
20278 		 * not, try a pullup.
20279 		 */
20280 		v_hlen &= 0xF;
20281 		v_hlen <<= 2;
20282 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20283 			BUMP_MIB(&ip_mib, ipOutDiscards);
20284 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20285 			    "ip_wput_end: q %p (%S)", q, "badlen");
20286 			goto drop_pkt;
20287 		}
20288 		if (v_hlen > (mp->b_wptr - rptr)) {
20289 			if (!pullupmsg(mp, v_hlen)) {
20290 				BUMP_MIB(&ip_mib, ipOutDiscards);
20291 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20292 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20293 				goto drop_pkt;
20294 			}
20295 			ipha = (ipha_t *)mp->b_rptr;
20296 		}
20297 		/*
20298 		 * Move first entry from any source route into ipha_dst and
20299 		 * verify the options
20300 		 */
20301 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20302 			ASSERT(xmit_ill == NULL);
20303 			if (attach_ill != NULL)
20304 				ill_refrele(attach_ill);
20305 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20306 			    "ip_wput_end: q %p (%S)", q, "badopts");
20307 			if (need_decref)
20308 				CONN_DEC_REF(connp);
20309 			return;
20310 		}
20311 	}
20312 	dst = ipha->ipha_dst;
20313 
20314 	/*
20315 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20316 	 * we have to run the packet through ip_newroute which will take
20317 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20318 	 * a resolver, or assigning a default gateway, etc.
20319 	 */
20320 	if (CLASSD(dst)) {
20321 		ipif_t	*ipif;
20322 		uint32_t setsrc = 0;
20323 
20324 	    multicast:
20325 		ASSERT(first_mp != NULL);
20326 		ASSERT(xmit_ill == NULL);
20327 		ip2dbg(("ip_wput: CLASSD\n"));
20328 		if (connp == NULL) {
20329 			/*
20330 			 * Use the first good ipif on the ill.
20331 			 * XXX Should this ever happen? (Appears
20332 			 * to show up with just ppp and no ethernet due
20333 			 * to in.rdisc.)
20334 			 * However, ire_send should be able to
20335 			 * call ip_wput_ire directly.
20336 			 *
20337 			 * XXX Also, this can happen for ICMP and other packets
20338 			 * with multicast source addresses.  Perhaps we should
20339 			 * fix things so that we drop the packet in question,
20340 			 * but for now, just run with it.
20341 			 */
20342 			ill_t *ill = (ill_t *)q->q_ptr;
20343 
20344 			/*
20345 			 * Don't honor attach_if for this case. If ill
20346 			 * is part of the group, ipif could belong to
20347 			 * any ill and we cannot maintain attach_ill
20348 			 * and ipif_ill same anymore and the assert
20349 			 * below would fail.
20350 			 */
20351 			if (mctl_present && io->ipsec_out_attach_if) {
20352 				io->ipsec_out_ill_index = 0;
20353 				io->ipsec_out_attach_if = B_FALSE;
20354 				ASSERT(attach_ill != NULL);
20355 				ill_refrele(attach_ill);
20356 				attach_ill = NULL;
20357 			}
20358 
20359 			ASSERT(attach_ill == NULL);
20360 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20361 			if (ipif == NULL) {
20362 				if (need_decref)
20363 					CONN_DEC_REF(connp);
20364 				freemsg(first_mp);
20365 				return;
20366 			}
20367 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20368 			    ntohl(dst), ill->ill_name));
20369 		} else {
20370 			/*
20371 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20372 			 * IP_XMIT_IF is honoured.
20373 			 * Block comment above this function explains the
20374 			 * locking mechanism used here
20375 			 */
20376 			xmit_ill = conn_get_held_ill(connp,
20377 			    &connp->conn_xmit_if_ill, &err);
20378 			if (err == ILL_LOOKUP_FAILED) {
20379 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20380 				goto drop_pkt;
20381 			}
20382 			if (xmit_ill == NULL) {
20383 				ipif = conn_get_held_ipif(connp,
20384 				    &connp->conn_multicast_ipif, &err);
20385 				if (err == IPIF_LOOKUP_FAILED) {
20386 					ip1dbg(("ip_wput: No ipif for "
20387 					    "multicast\n"));
20388 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20389 					goto drop_pkt;
20390 				}
20391 			}
20392 			if (xmit_ill != NULL) {
20393 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20394 				if (ipif == NULL) {
20395 					ip1dbg(("ip_wput: No ipif for "
20396 					    "IP_XMIT_IF\n"));
20397 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20398 					goto drop_pkt;
20399 				}
20400 			} else if (ipif == NULL || ipif->ipif_isv6) {
20401 				/*
20402 				 * We must do this ipif determination here
20403 				 * else we could pass through ip_newroute
20404 				 * and come back here without the conn context.
20405 				 *
20406 				 * Note: we do late binding i.e. we bind to
20407 				 * the interface when the first packet is sent.
20408 				 * For performance reasons we do not rebind on
20409 				 * each packet but keep the binding until the
20410 				 * next IP_MULTICAST_IF option.
20411 				 *
20412 				 * conn_multicast_{ipif,ill} are shared between
20413 				 * IPv4 and IPv6 and AF_INET6 sockets can
20414 				 * send both IPv4 and IPv6 packets. Hence
20415 				 * we have to check that "isv6" matches above.
20416 				 */
20417 				if (ipif != NULL)
20418 					ipif_refrele(ipif);
20419 				ipif = ipif_lookup_group(dst, zoneid);
20420 				if (ipif == NULL) {
20421 					ip1dbg(("ip_wput: No ipif for "
20422 					    "multicast\n"));
20423 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20424 					goto drop_pkt;
20425 				}
20426 				err = conn_set_held_ipif(connp,
20427 				    &connp->conn_multicast_ipif, ipif);
20428 				if (err == IPIF_LOOKUP_FAILED) {
20429 					ipif_refrele(ipif);
20430 					ip1dbg(("ip_wput: No ipif for "
20431 					    "multicast\n"));
20432 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20433 					goto drop_pkt;
20434 				}
20435 			}
20436 		}
20437 		ASSERT(!ipif->ipif_isv6);
20438 		/*
20439 		 * As we may lose the conn by the time we reach ip_wput_ire,
20440 		 * we copy conn_multicast_loop and conn_dontroute on to an
20441 		 * ipsec_out. In case if this datagram goes out secure,
20442 		 * we need the ill_index also. Copy that also into the
20443 		 * ipsec_out.
20444 		 */
20445 		if (mctl_present) {
20446 			io = (ipsec_out_t *)first_mp->b_rptr;
20447 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20448 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20449 		} else {
20450 			ASSERT(mp == first_mp);
20451 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20452 			    BPRI_HI)) == NULL) {
20453 				ipif_refrele(ipif);
20454 				first_mp = mp;
20455 				goto drop_pkt;
20456 			}
20457 			first_mp->b_datap->db_type = M_CTL;
20458 			first_mp->b_wptr += sizeof (ipsec_info_t);
20459 			/* ipsec_out_secure is B_FALSE now */
20460 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20461 			io = (ipsec_out_t *)first_mp->b_rptr;
20462 			io->ipsec_out_type = IPSEC_OUT;
20463 			io->ipsec_out_len = sizeof (ipsec_out_t);
20464 			io->ipsec_out_use_global_policy = B_TRUE;
20465 			first_mp->b_cont = mp;
20466 			mctl_present = B_TRUE;
20467 		}
20468 		if (attach_ill != NULL) {
20469 			ASSERT(attach_ill == ipif->ipif_ill);
20470 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20471 
20472 			/*
20473 			 * Check if we need an ire that will not be
20474 			 * looked up by anybody else i.e. HIDDEN.
20475 			 */
20476 			if (ill_is_probeonly(attach_ill)) {
20477 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20478 			}
20479 			io->ipsec_out_ill_index =
20480 			    attach_ill->ill_phyint->phyint_ifindex;
20481 			io->ipsec_out_attach_if = B_TRUE;
20482 		} else {
20483 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20484 			io->ipsec_out_ill_index =
20485 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20486 		}
20487 		if (connp != NULL) {
20488 			io->ipsec_out_multicast_loop =
20489 			    connp->conn_multicast_loop;
20490 			io->ipsec_out_dontroute = connp->conn_dontroute;
20491 			io->ipsec_out_zoneid = connp->conn_zoneid;
20492 		}
20493 		/*
20494 		 * If the application uses IP_MULTICAST_IF with
20495 		 * different logical addresses of the same ILL, we
20496 		 * need to make sure that the soruce address of
20497 		 * the packet matches the logical IP address used
20498 		 * in the option. We do it by initializing ipha_src
20499 		 * here. This should keep IPSEC also happy as
20500 		 * when we return from IPSEC processing, we don't
20501 		 * have to worry about getting the right address on
20502 		 * the packet. Thus it is sufficient to look for
20503 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20504 		 * MATCH_IRE_IPIF.
20505 		 *
20506 		 * NOTE : We need to do it for non-secure case also as
20507 		 * this might go out secure if there is a global policy
20508 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20509 		 * address, the source should be initialized already and
20510 		 * hence we won't be initializing here.
20511 		 *
20512 		 * As we do not have the ire yet, it is possible that
20513 		 * we set the source address here and then later discover
20514 		 * that the ire implies the source address to be assigned
20515 		 * through the RTF_SETSRC flag.
20516 		 * In that case, the setsrc variable will remind us
20517 		 * that overwritting the source address by the one
20518 		 * of the RTF_SETSRC-flagged ire is allowed.
20519 		 */
20520 		if (ipha->ipha_src == INADDR_ANY &&
20521 		    (connp == NULL || !connp->conn_unspec_src)) {
20522 			ipha->ipha_src = ipif->ipif_src_addr;
20523 			setsrc = RTF_SETSRC;
20524 		}
20525 		/*
20526 		 * Find an IRE which matches the destination and the outgoing
20527 		 * queue (i.e. the outgoing interface.)
20528 		 * For loopback use a unicast IP address for
20529 		 * the ire lookup.
20530 		 */
20531 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20532 		    PHYI_LOOPBACK) {
20533 			dst = ipif->ipif_lcl_addr;
20534 		}
20535 		/*
20536 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20537 		 * We don't need to lookup ire in ctable as the packet
20538 		 * needs to be sent to the destination through the specified
20539 		 * ill irrespective of ires in the cache table.
20540 		 */
20541 		ire = NULL;
20542 		if (xmit_ill == NULL) {
20543 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20544 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20545 		}
20546 
20547 		/*
20548 		 * refrele attach_ill as its not needed anymore.
20549 		 */
20550 		if (attach_ill != NULL) {
20551 			ill_refrele(attach_ill);
20552 			attach_ill = NULL;
20553 		}
20554 
20555 		if (ire == NULL) {
20556 			/*
20557 			 * Multicast loopback and multicast forwarding is
20558 			 * done in ip_wput_ire.
20559 			 *
20560 			 * Mark this packet to make it be delivered to
20561 			 * ip_wput_ire after the new ire has been
20562 			 * created.
20563 			 *
20564 			 * The call to ip_newroute_ipif takes into account
20565 			 * the setsrc reminder. In any case, we take care
20566 			 * of the RTF_MULTIRT flag.
20567 			 */
20568 			mp->b_prev = mp->b_next = NULL;
20569 			if (xmit_ill == NULL ||
20570 			    xmit_ill->ill_ipif_up_count > 0) {
20571 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20572 				    setsrc | RTF_MULTIRT, zoneid);
20573 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20574 				    "ip_wput_end: q %p (%S)", q, "noire");
20575 			} else {
20576 				freemsg(first_mp);
20577 			}
20578 			ipif_refrele(ipif);
20579 			if (xmit_ill != NULL)
20580 				ill_refrele(xmit_ill);
20581 			if (need_decref)
20582 				CONN_DEC_REF(connp);
20583 			return;
20584 		}
20585 
20586 		ipif_refrele(ipif);
20587 		ipif = NULL;
20588 		ASSERT(xmit_ill == NULL);
20589 
20590 		/*
20591 		 * Honor the RTF_SETSRC flag for multicast packets,
20592 		 * if allowed by the setsrc reminder.
20593 		 */
20594 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20595 			ipha->ipha_src = ire->ire_src_addr;
20596 		}
20597 
20598 		/*
20599 		 * Unconditionally force the TTL to 1 for
20600 		 * multirouted multicast packets:
20601 		 * multirouted multicast should not cross
20602 		 * multicast routers.
20603 		 */
20604 		if (ire->ire_flags & RTF_MULTIRT) {
20605 			if (ipha->ipha_ttl > 1) {
20606 				ip2dbg(("ip_wput: forcing multicast "
20607 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20608 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20609 				ipha->ipha_ttl = 1;
20610 			}
20611 		}
20612 	} else {
20613 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20614 		if ((ire != NULL) && (ire->ire_type &
20615 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20616 			ignore_dontroute = B_TRUE;
20617 			ignore_nexthop = B_TRUE;
20618 		}
20619 		if (ire != NULL) {
20620 			ire_refrele(ire);
20621 			ire = NULL;
20622 		}
20623 		/*
20624 		 * Guard against coming in from arp in which case conn is NULL.
20625 		 * Also guard against non M_DATA with dontroute set but
20626 		 * destined to local, loopback or broadcast addresses.
20627 		 */
20628 		if (connp != NULL && connp->conn_dontroute &&
20629 		    !ignore_dontroute) {
20630 dontroute:
20631 			/*
20632 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20633 			 * routing protocols from seeing false direct
20634 			 * connectivity.
20635 			 */
20636 			ipha->ipha_ttl = 1;
20637 			/*
20638 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20639 			 * along with SO_DONTROUTE, higher precedence is
20640 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20641 			 */
20642 			if (connp->conn_xmit_if_ill == NULL) {
20643 				/* If suitable ipif not found, drop packet */
20644 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20645 				if (dst_ipif == NULL) {
20646 					ip1dbg(("ip_wput: no route for "
20647 					    "dst using SO_DONTROUTE\n"));
20648 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20649 					mp->b_prev = mp->b_next = NULL;
20650 					if (first_mp == NULL)
20651 						first_mp = mp;
20652 					goto drop_pkt;
20653 				} else {
20654 					/*
20655 					 * If suitable ipif has been found, set
20656 					 * xmit_ill to the corresponding
20657 					 * ipif_ill because we'll be following
20658 					 * the IP_XMIT_IF logic.
20659 					 */
20660 					ASSERT(xmit_ill == NULL);
20661 					xmit_ill = dst_ipif->ipif_ill;
20662 					mutex_enter(&xmit_ill->ill_lock);
20663 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20664 						mutex_exit(&xmit_ill->ill_lock);
20665 						xmit_ill = NULL;
20666 						ipif_refrele(dst_ipif);
20667 						ip1dbg(("ip_wput: no route for"
20668 						    " dst using"
20669 						    " SO_DONTROUTE\n"));
20670 						BUMP_MIB(&ip_mib,
20671 						    ipOutNoRoutes);
20672 						mp->b_prev = mp->b_next = NULL;
20673 						if (first_mp == NULL)
20674 							first_mp = mp;
20675 						goto drop_pkt;
20676 					}
20677 					ill_refhold_locked(xmit_ill);
20678 					mutex_exit(&xmit_ill->ill_lock);
20679 					ipif_refrele(dst_ipif);
20680 				}
20681 			}
20682 
20683 		}
20684 		/*
20685 		 * If we are bound to IPIF_NOFAILOVER address, look for
20686 		 * an IRE_CACHE matching the ill.
20687 		 */
20688 send_from_ill:
20689 		if (attach_ill != NULL) {
20690 			ipif_t	*attach_ipif;
20691 
20692 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20693 
20694 			/*
20695 			 * Check if we need an ire that will not be
20696 			 * looked up by anybody else i.e. HIDDEN.
20697 			 */
20698 			if (ill_is_probeonly(attach_ill)) {
20699 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20700 			}
20701 
20702 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20703 			if (attach_ipif == NULL) {
20704 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20705 				goto drop_pkt;
20706 			}
20707 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20708 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20709 			ipif_refrele(attach_ipif);
20710 		} else if (xmit_ill != NULL || (connp != NULL &&
20711 			    connp->conn_xmit_if_ill != NULL)) {
20712 			/*
20713 			 * Mark this packet as originated locally
20714 			 */
20715 			mp->b_prev = mp->b_next = NULL;
20716 			/*
20717 			 * xmit_ill could be NULL if SO_DONTROUTE
20718 			 * is also set.
20719 			 */
20720 			if (xmit_ill == NULL) {
20721 				xmit_ill = conn_get_held_ill(connp,
20722 				    &connp->conn_xmit_if_ill, &err);
20723 				if (err == ILL_LOOKUP_FAILED) {
20724 					if (need_decref)
20725 						CONN_DEC_REF(connp);
20726 					freemsg(first_mp);
20727 					return;
20728 				}
20729 				if (xmit_ill == NULL) {
20730 					if (connp->conn_dontroute)
20731 						goto dontroute;
20732 					goto send_from_ill;
20733 				}
20734 			}
20735 			/*
20736 			 * could be SO_DONTROUTE case also.
20737 			 * check at least one interface is UP as
20738 			 * spcified by this ILL, and then call
20739 			 * ip_newroute_ipif()
20740 			 */
20741 			if (xmit_ill->ill_ipif_up_count > 0) {
20742 				ipif_t *ipif;
20743 
20744 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20745 				if (ipif != NULL) {
20746 					ip_newroute_ipif(q, first_mp, ipif,
20747 					    dst, connp, 0, zoneid);
20748 					ipif_refrele(ipif);
20749 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20750 				}
20751 			} else {
20752 				freemsg(first_mp);
20753 			}
20754 			ill_refrele(xmit_ill);
20755 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20756 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20757 			if (need_decref)
20758 				CONN_DEC_REF(connp);
20759 			return;
20760 		} else if (ip_nexthop || (connp != NULL &&
20761 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20762 			if (!ip_nexthop) {
20763 				ip_nexthop = B_TRUE;
20764 				nexthop_addr = connp->conn_nexthop_v4;
20765 			}
20766 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20767 			    MATCH_IRE_GW;
20768 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20769 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20770 		} else {
20771 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20772 		}
20773 		if (!ire) {
20774 			/*
20775 			 * Make sure we don't load spread if this
20776 			 * is IPIF_NOFAILOVER case.
20777 			 */
20778 			if ((attach_ill != NULL) ||
20779 			    (ip_nexthop && !ignore_nexthop)) {
20780 				if (mctl_present) {
20781 					io = (ipsec_out_t *)first_mp->b_rptr;
20782 					ASSERT(first_mp->b_datap->db_type ==
20783 					    M_CTL);
20784 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20785 				} else {
20786 					ASSERT(mp == first_mp);
20787 					first_mp = allocb(
20788 					    sizeof (ipsec_info_t), BPRI_HI);
20789 					if (first_mp == NULL) {
20790 						first_mp = mp;
20791 						goto drop_pkt;
20792 					}
20793 					first_mp->b_datap->db_type = M_CTL;
20794 					first_mp->b_wptr +=
20795 					    sizeof (ipsec_info_t);
20796 					/* ipsec_out_secure is B_FALSE now */
20797 					bzero(first_mp->b_rptr,
20798 					    sizeof (ipsec_info_t));
20799 					io = (ipsec_out_t *)first_mp->b_rptr;
20800 					io->ipsec_out_type = IPSEC_OUT;
20801 					io->ipsec_out_len =
20802 					    sizeof (ipsec_out_t);
20803 					io->ipsec_out_use_global_policy =
20804 					    B_TRUE;
20805 					first_mp->b_cont = mp;
20806 					mctl_present = B_TRUE;
20807 				}
20808 				if (attach_ill != NULL) {
20809 					io->ipsec_out_ill_index = attach_ill->
20810 					    ill_phyint->phyint_ifindex;
20811 					io->ipsec_out_attach_if = B_TRUE;
20812 				} else {
20813 					io->ipsec_out_ip_nexthop = ip_nexthop;
20814 					io->ipsec_out_nexthop_addr =
20815 					    nexthop_addr;
20816 				}
20817 			}
20818 noirefound:
20819 			/*
20820 			 * Mark this packet as having originated on
20821 			 * this machine.  This will be noted in
20822 			 * ire_add_then_send, which needs to know
20823 			 * whether to run it back through ip_wput or
20824 			 * ip_rput following successful resolution.
20825 			 */
20826 			mp->b_prev = NULL;
20827 			mp->b_next = NULL;
20828 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20829 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20830 			    "ip_wput_end: q %p (%S)", q, "newroute");
20831 			if (attach_ill != NULL)
20832 				ill_refrele(attach_ill);
20833 			if (xmit_ill != NULL)
20834 				ill_refrele(xmit_ill);
20835 			if (need_decref)
20836 				CONN_DEC_REF(connp);
20837 			return;
20838 		}
20839 	}
20840 
20841 	/* We now know where we are going with it. */
20842 
20843 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20844 	    "ip_wput_end: q %p (%S)", q, "end");
20845 
20846 	/*
20847 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20848 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20849 	 */
20850 	if (ire->ire_flags & RTF_MULTIRT) {
20851 		/*
20852 		 * Force the TTL of multirouted packets if required.
20853 		 * The TTL of such packets is bounded by the
20854 		 * ip_multirt_ttl ndd variable.
20855 		 */
20856 		if ((ip_multirt_ttl > 0) &&
20857 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20858 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20859 			    "(was %d), dst 0x%08x\n",
20860 			    ip_multirt_ttl, ipha->ipha_ttl,
20861 			    ntohl(ire->ire_addr)));
20862 			ipha->ipha_ttl = ip_multirt_ttl;
20863 		}
20864 		/*
20865 		 * At this point, we check to see if there are any pending
20866 		 * unresolved routes. ire_multirt_resolvable()
20867 		 * checks in O(n) that all IRE_OFFSUBNET ire
20868 		 * entries for the packet's destination and
20869 		 * flagged RTF_MULTIRT are currently resolved.
20870 		 * If some remain unresolved, we make a copy
20871 		 * of the current message. It will be used
20872 		 * to initiate additional route resolutions.
20873 		 */
20874 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20875 		    MBLK_GETLABEL(first_mp));
20876 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20877 		    "multirt_need_resolve %d, first_mp %p\n",
20878 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20879 		if (multirt_need_resolve) {
20880 			copy_mp = copymsg(first_mp);
20881 			if (copy_mp != NULL) {
20882 				MULTIRT_DEBUG_TAG(copy_mp);
20883 			}
20884 		}
20885 	}
20886 
20887 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20888 	/*
20889 	 * Try to resolve another multiroute if
20890 	 * ire_multirt_resolvable() deemed it necessary.
20891 	 * At this point, we need to distinguish
20892 	 * multicasts from other packets. For multicasts,
20893 	 * we call ip_newroute_ipif() and request that both
20894 	 * multirouting and setsrc flags are checked.
20895 	 */
20896 	if (copy_mp != NULL) {
20897 		if (CLASSD(dst)) {
20898 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20899 			if (ipif) {
20900 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20901 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20902 				ipif_refrele(ipif);
20903 			} else {
20904 				MULTIRT_DEBUG_UNTAG(copy_mp);
20905 				freemsg(copy_mp);
20906 				copy_mp = NULL;
20907 			}
20908 		} else {
20909 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20910 		}
20911 	}
20912 	if (attach_ill != NULL)
20913 		ill_refrele(attach_ill);
20914 	if (xmit_ill != NULL)
20915 		ill_refrele(xmit_ill);
20916 	if (need_decref)
20917 		CONN_DEC_REF(connp);
20918 	return;
20919 
20920 icmp_parameter_problem:
20921 	/* could not have originated externally */
20922 	ASSERT(mp->b_prev == NULL);
20923 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20924 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20925 		/* it's the IP header length that's in trouble */
20926 		icmp_param_problem(q, first_mp, 0, zoneid);
20927 		first_mp = NULL;
20928 	}
20929 
20930 drop_pkt:
20931 	ip1dbg(("ip_wput: dropped packet\n"));
20932 	if (ire != NULL)
20933 		ire_refrele(ire);
20934 	if (need_decref)
20935 		CONN_DEC_REF(connp);
20936 	freemsg(first_mp);
20937 	if (attach_ill != NULL)
20938 		ill_refrele(attach_ill);
20939 	if (xmit_ill != NULL)
20940 		ill_refrele(xmit_ill);
20941 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20942 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20943 }
20944 
20945 /*
20946  * If this is a conn_t queue, then we pass in the conn. This includes the
20947  * zoneid.
20948  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20949  * in which case we use the global zoneid since those are all part of
20950  * the global zone.
20951  */
20952 void
20953 ip_wput(queue_t *q, mblk_t *mp)
20954 {
20955 	if (CONN_Q(q))
20956 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20957 	else
20958 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20959 }
20960 
20961 /*
20962  *
20963  * The following rules must be observed when accessing any ipif or ill
20964  * that has been cached in the conn. Typically conn_nofailover_ill,
20965  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20966  *
20967  * Access: The ipif or ill pointed to from the conn can be accessed under
20968  * the protection of the conn_lock or after it has been refheld under the
20969  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20970  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20971  * The reason for this is that a concurrent unplumb could actually be
20972  * cleaning up these cached pointers by walking the conns and might have
20973  * finished cleaning up the conn in question. The macros check that an
20974  * unplumb has not yet started on the ipif or ill.
20975  *
20976  * Caching: An ipif or ill pointer may be cached in the conn only after
20977  * making sure that an unplumb has not started. So the caching is done
20978  * while holding both the conn_lock and the ill_lock and after using the
20979  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20980  * flag before starting the cleanup of conns.
20981  *
20982  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20983  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20984  * or a reference to the ipif or a reference to an ire that references the
20985  * ipif. An ipif does not change its ill except for failover/failback. Since
20986  * failover/failback happens only after bringing down the ipif and making sure
20987  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20988  * the above holds.
20989  */
20990 ipif_t *
20991 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20992 {
20993 	ipif_t	*ipif;
20994 	ill_t	*ill;
20995 
20996 	*err = 0;
20997 	rw_enter(&ill_g_lock, RW_READER);
20998 	mutex_enter(&connp->conn_lock);
20999 	ipif = *ipifp;
21000 	if (ipif != NULL) {
21001 		ill = ipif->ipif_ill;
21002 		mutex_enter(&ill->ill_lock);
21003 		if (IPIF_CAN_LOOKUP(ipif)) {
21004 			ipif_refhold_locked(ipif);
21005 			mutex_exit(&ill->ill_lock);
21006 			mutex_exit(&connp->conn_lock);
21007 			rw_exit(&ill_g_lock);
21008 			return (ipif);
21009 		} else {
21010 			*err = IPIF_LOOKUP_FAILED;
21011 		}
21012 		mutex_exit(&ill->ill_lock);
21013 	}
21014 	mutex_exit(&connp->conn_lock);
21015 	rw_exit(&ill_g_lock);
21016 	return (NULL);
21017 }
21018 
21019 ill_t *
21020 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21021 {
21022 	ill_t	*ill;
21023 
21024 	*err = 0;
21025 	mutex_enter(&connp->conn_lock);
21026 	ill = *illp;
21027 	if (ill != NULL) {
21028 		mutex_enter(&ill->ill_lock);
21029 		if (ILL_CAN_LOOKUP(ill)) {
21030 			ill_refhold_locked(ill);
21031 			mutex_exit(&ill->ill_lock);
21032 			mutex_exit(&connp->conn_lock);
21033 			return (ill);
21034 		} else {
21035 			*err = ILL_LOOKUP_FAILED;
21036 		}
21037 		mutex_exit(&ill->ill_lock);
21038 	}
21039 	mutex_exit(&connp->conn_lock);
21040 	return (NULL);
21041 }
21042 
21043 static int
21044 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21045 {
21046 	ill_t	*ill;
21047 
21048 	ill = ipif->ipif_ill;
21049 	mutex_enter(&connp->conn_lock);
21050 	mutex_enter(&ill->ill_lock);
21051 	if (IPIF_CAN_LOOKUP(ipif)) {
21052 		*ipifp = ipif;
21053 		mutex_exit(&ill->ill_lock);
21054 		mutex_exit(&connp->conn_lock);
21055 		return (0);
21056 	}
21057 	mutex_exit(&ill->ill_lock);
21058 	mutex_exit(&connp->conn_lock);
21059 	return (IPIF_LOOKUP_FAILED);
21060 }
21061 
21062 /*
21063  * This is called if the outbound datagram needs fragmentation.
21064  *
21065  * NOTE : This function does not ire_refrele the ire argument passed in.
21066  */
21067 static void
21068 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21069 {
21070 	ipha_t		*ipha;
21071 	mblk_t		*mp;
21072 	uint32_t	v_hlen_tos_len;
21073 	uint32_t	max_frag;
21074 	uint32_t	frag_flag;
21075 	boolean_t	dont_use;
21076 
21077 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21078 		mp = ipsec_mp->b_cont;
21079 	} else {
21080 		mp = ipsec_mp;
21081 	}
21082 
21083 	ipha = (ipha_t *)mp->b_rptr;
21084 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21085 
21086 #ifdef	_BIG_ENDIAN
21087 #define	V_HLEN	(v_hlen_tos_len >> 24)
21088 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21089 #else
21090 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21091 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21092 #endif
21093 
21094 #ifndef SPEED_BEFORE_SAFETY
21095 	/*
21096 	 * Check that ipha_length is consistent with
21097 	 * the mblk length
21098 	 */
21099 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21100 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21101 		    LENGTH, msgdsize(mp)));
21102 		freemsg(ipsec_mp);
21103 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21104 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21105 		    "packet length mismatch");
21106 		return;
21107 	}
21108 #endif
21109 	/*
21110 	 * Don't use frag_flag if pre-built packet or source
21111 	 * routed or if multicast (since multicast packets do not solicit
21112 	 * ICMP "packet too big" messages). Get the values of
21113 	 * max_frag and frag_flag atomically by acquiring the
21114 	 * ire_lock.
21115 	 */
21116 	mutex_enter(&ire->ire_lock);
21117 	max_frag = ire->ire_max_frag;
21118 	frag_flag = ire->ire_frag_flag;
21119 	mutex_exit(&ire->ire_lock);
21120 
21121 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21122 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21123 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21124 
21125 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21126 	    (dont_use ? 0 : frag_flag), zoneid);
21127 }
21128 
21129 /*
21130  * Used for deciding the MSS size for the upper layer. Thus
21131  * we need to check the outbound policy values in the conn.
21132  */
21133 int
21134 conn_ipsec_length(conn_t *connp)
21135 {
21136 	ipsec_latch_t *ipl;
21137 
21138 	ipl = connp->conn_latch;
21139 	if (ipl == NULL)
21140 		return (0);
21141 
21142 	if (ipl->ipl_out_policy == NULL)
21143 		return (0);
21144 
21145 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21146 }
21147 
21148 /*
21149  * Returns an estimate of the IPSEC headers size. This is used if
21150  * we don't want to call into IPSEC to get the exact size.
21151  */
21152 int
21153 ipsec_out_extra_length(mblk_t *ipsec_mp)
21154 {
21155 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21156 	ipsec_action_t *a;
21157 
21158 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21159 	if (!io->ipsec_out_secure)
21160 		return (0);
21161 
21162 	a = io->ipsec_out_act;
21163 
21164 	if (a == NULL) {
21165 		ASSERT(io->ipsec_out_policy != NULL);
21166 		a = io->ipsec_out_policy->ipsp_act;
21167 	}
21168 	ASSERT(a != NULL);
21169 
21170 	return (a->ipa_ovhd);
21171 }
21172 
21173 /*
21174  * Returns an estimate of the IPSEC headers size. This is used if
21175  * we don't want to call into IPSEC to get the exact size.
21176  */
21177 int
21178 ipsec_in_extra_length(mblk_t *ipsec_mp)
21179 {
21180 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21181 	ipsec_action_t *a;
21182 
21183 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21184 
21185 	a = ii->ipsec_in_action;
21186 	return (a == NULL ? 0 : a->ipa_ovhd);
21187 }
21188 
21189 /*
21190  * If there are any source route options, return the true final
21191  * destination. Otherwise, return the destination.
21192  */
21193 ipaddr_t
21194 ip_get_dst(ipha_t *ipha)
21195 {
21196 	ipoptp_t	opts;
21197 	uchar_t		*opt;
21198 	uint8_t		optval;
21199 	uint8_t		optlen;
21200 	ipaddr_t	dst;
21201 	uint32_t off;
21202 
21203 	dst = ipha->ipha_dst;
21204 
21205 	if (IS_SIMPLE_IPH(ipha))
21206 		return (dst);
21207 
21208 	for (optval = ipoptp_first(&opts, ipha);
21209 	    optval != IPOPT_EOL;
21210 	    optval = ipoptp_next(&opts)) {
21211 		opt = opts.ipoptp_cur;
21212 		optlen = opts.ipoptp_len;
21213 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21214 		switch (optval) {
21215 		case IPOPT_SSRR:
21216 		case IPOPT_LSRR:
21217 			off = opt[IPOPT_OFFSET];
21218 			/*
21219 			 * If one of the conditions is true, it means
21220 			 * end of options and dst already has the right
21221 			 * value.
21222 			 */
21223 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21224 				off = optlen - IP_ADDR_LEN;
21225 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21226 			}
21227 			return (dst);
21228 		default:
21229 			break;
21230 		}
21231 	}
21232 
21233 	return (dst);
21234 }
21235 
21236 mblk_t *
21237 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21238     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21239 {
21240 	ipsec_out_t	*io;
21241 	mblk_t		*first_mp;
21242 	boolean_t policy_present;
21243 
21244 	first_mp = mp;
21245 	if (mp->b_datap->db_type == M_CTL) {
21246 		io = (ipsec_out_t *)first_mp->b_rptr;
21247 		/*
21248 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21249 		 *
21250 		 * 1) There is per-socket policy (including cached global
21251 		 *    policy) or a policy on the IP-in-IP tunnel.
21252 		 * 2) There is no per-socket policy, but it is
21253 		 *    a multicast packet that needs to go out
21254 		 *    on a specific interface. This is the case
21255 		 *    where (ip_wput and ip_wput_multicast) attaches
21256 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21257 		 *
21258 		 * In case (2) we check with global policy to
21259 		 * see if there is a match and set the ill_index
21260 		 * appropriately so that we can lookup the ire
21261 		 * properly in ip_wput_ipsec_out.
21262 		 */
21263 
21264 		/*
21265 		 * ipsec_out_use_global_policy is set to B_FALSE
21266 		 * in ipsec_in_to_out(). Refer to that function for
21267 		 * details.
21268 		 */
21269 		if ((io->ipsec_out_latch == NULL) &&
21270 		    (io->ipsec_out_use_global_policy)) {
21271 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21272 				    ire, connp, unspec_src, zoneid));
21273 		}
21274 		if (!io->ipsec_out_secure) {
21275 			/*
21276 			 * If this is not a secure packet, drop
21277 			 * the IPSEC_OUT mp and treat it as a clear
21278 			 * packet. This happens when we are sending
21279 			 * a ICMP reply back to a clear packet. See
21280 			 * ipsec_in_to_out() for details.
21281 			 */
21282 			mp = first_mp->b_cont;
21283 			freeb(first_mp);
21284 		}
21285 		return (mp);
21286 	}
21287 	/*
21288 	 * See whether we need to attach a global policy here. We
21289 	 * don't depend on the conn (as it could be null) for deciding
21290 	 * what policy this datagram should go through because it
21291 	 * should have happened in ip_wput if there was some
21292 	 * policy. This normally happens for connections which are not
21293 	 * fully bound preventing us from caching policies in
21294 	 * ip_bind. Packets coming from the TCP listener/global queue
21295 	 * - which are non-hard_bound - could also be affected by
21296 	 * applying policy here.
21297 	 *
21298 	 * If this packet is coming from tcp global queue or listener,
21299 	 * we will be applying policy here.  This may not be *right*
21300 	 * if these packets are coming from the detached connection as
21301 	 * it could have gone in clear before. This happens only if a
21302 	 * TCP connection started when there is no policy and somebody
21303 	 * added policy before it became detached. Thus packets of the
21304 	 * detached connection could go out secure and the other end
21305 	 * would drop it because it will be expecting in clear. The
21306 	 * converse is not true i.e if somebody starts a TCP
21307 	 * connection and deletes the policy, all the packets will
21308 	 * still go out with the policy that existed before deleting
21309 	 * because ip_unbind sends up policy information which is used
21310 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21311 	 * TCP to attach a dummy IPSEC_OUT and set
21312 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21313 	 * affect performance for normal cases, we are not doing it.
21314 	 * Thus, set policy before starting any TCP connections.
21315 	 *
21316 	 * NOTE - We might apply policy even for a hard bound connection
21317 	 * - for which we cached policy in ip_bind - if somebody added
21318 	 * global policy after we inherited the policy in ip_bind.
21319 	 * This means that the packets that were going out in clear
21320 	 * previously would start going secure and hence get dropped
21321 	 * on the other side. To fix this, TCP attaches a dummy
21322 	 * ipsec_out and make sure that we don't apply global policy.
21323 	 */
21324 	if (ipha != NULL)
21325 		policy_present = ipsec_outbound_v4_policy_present;
21326 	else
21327 		policy_present = ipsec_outbound_v6_policy_present;
21328 	if (!policy_present)
21329 		return (mp);
21330 
21331 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21332 		    zoneid));
21333 }
21334 
21335 ire_t *
21336 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21337 {
21338 	ipaddr_t addr;
21339 	ire_t *save_ire;
21340 	irb_t *irb;
21341 	ill_group_t *illgrp;
21342 	int	err;
21343 
21344 	save_ire = ire;
21345 	addr = ire->ire_addr;
21346 
21347 	ASSERT(ire->ire_type == IRE_BROADCAST);
21348 
21349 	illgrp = connp->conn_outgoing_ill->ill_group;
21350 	if (illgrp == NULL) {
21351 		*conn_outgoing_ill = conn_get_held_ill(connp,
21352 		    &connp->conn_outgoing_ill, &err);
21353 		if (err == ILL_LOOKUP_FAILED) {
21354 			ire_refrele(save_ire);
21355 			return (NULL);
21356 		}
21357 		return (save_ire);
21358 	}
21359 	/*
21360 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21361 	 * If it is part of the group, we need to send on the ire
21362 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21363 	 * to this group. This is okay as IP_BOUND_IF really means
21364 	 * any ill in the group. We depend on the fact that the
21365 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21366 	 * if such an ire exists. This is possible only if you have
21367 	 * at least one ill in the group that has not failed.
21368 	 *
21369 	 * First get to the ire that matches the address and group.
21370 	 *
21371 	 * We don't look for an ire with a matching zoneid because a given zone
21372 	 * won't always have broadcast ires on all ills in the group.
21373 	 */
21374 	irb = ire->ire_bucket;
21375 	rw_enter(&irb->irb_lock, RW_READER);
21376 	if (ire->ire_marks & IRE_MARK_NORECV) {
21377 		/*
21378 		 * If the current zone only has an ire broadcast for this
21379 		 * address marked NORECV, the ire we want is ahead in the
21380 		 * bucket, so we look it up deliberately ignoring the zoneid.
21381 		 */
21382 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21383 			if (ire->ire_addr != addr)
21384 				continue;
21385 			/* skip over deleted ires */
21386 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21387 				continue;
21388 		}
21389 	}
21390 	while (ire != NULL) {
21391 		/*
21392 		 * If a new interface is coming up, we could end up
21393 		 * seeing the loopback ire and the non-loopback ire
21394 		 * may not have been added yet. So check for ire_stq
21395 		 */
21396 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21397 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21398 			break;
21399 		}
21400 		ire = ire->ire_next;
21401 	}
21402 	if (ire != NULL && ire->ire_addr == addr &&
21403 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21404 		IRE_REFHOLD(ire);
21405 		rw_exit(&irb->irb_lock);
21406 		ire_refrele(save_ire);
21407 		*conn_outgoing_ill = ire_to_ill(ire);
21408 		/*
21409 		 * Refhold the ill to make the conn_outgoing_ill
21410 		 * independent of the ire. ip_wput_ire goes in a loop
21411 		 * and may refrele the ire. Since we have an ire at this
21412 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21413 		 */
21414 		ill_refhold(*conn_outgoing_ill);
21415 		return (ire);
21416 	}
21417 	rw_exit(&irb->irb_lock);
21418 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21419 	/*
21420 	 * If we can't find a suitable ire, return the original ire.
21421 	 */
21422 	return (save_ire);
21423 }
21424 
21425 /*
21426  * This function does the ire_refrele of the ire passed in as the
21427  * argument. As this function looks up more ires i.e broadcast ires,
21428  * it needs to REFRELE them. Currently, for simplicity we don't
21429  * differentiate the one passed in and looked up here. We always
21430  * REFRELE.
21431  * IPQoS Notes:
21432  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21433  * IPSec packets are done in ipsec_out_process.
21434  *
21435  */
21436 void
21437 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21438     zoneid_t zoneid)
21439 {
21440 	ipha_t		*ipha;
21441 #define	rptr	((uchar_t *)ipha)
21442 	queue_t		*stq;
21443 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21444 	uint32_t	v_hlen_tos_len;
21445 	uint32_t	ttl_protocol;
21446 	ipaddr_t	src;
21447 	ipaddr_t	dst;
21448 	uint32_t	cksum;
21449 	ipaddr_t	orig_src;
21450 	ire_t		*ire1;
21451 	mblk_t		*next_mp;
21452 	uint_t		hlen;
21453 	uint16_t	*up;
21454 	uint32_t	max_frag = ire->ire_max_frag;
21455 	ill_t		*ill = ire_to_ill(ire);
21456 	int		clusterwide;
21457 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21458 	int		ipsec_len;
21459 	mblk_t		*first_mp;
21460 	ipsec_out_t	*io;
21461 	boolean_t	conn_dontroute;		/* conn value for multicast */
21462 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21463 	boolean_t	multicast_forward;	/* Should we forward ? */
21464 	boolean_t	unspec_src;
21465 	ill_t		*conn_outgoing_ill = NULL;
21466 	ill_t		*ire_ill;
21467 	ill_t		*ire1_ill;
21468 	ill_t		*out_ill;
21469 	uint32_t 	ill_index = 0;
21470 	boolean_t	multirt_send = B_FALSE;
21471 	int		err;
21472 	ipxmit_state_t	pktxmit_state;
21473 
21474 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21475 	    "ip_wput_ire_start: q %p", q);
21476 
21477 	multicast_forward = B_FALSE;
21478 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21479 
21480 	if (ire->ire_flags & RTF_MULTIRT) {
21481 		/*
21482 		 * Multirouting case. The bucket where ire is stored
21483 		 * probably holds other RTF_MULTIRT flagged ire
21484 		 * to the destination. In this call to ip_wput_ire,
21485 		 * we attempt to send the packet through all
21486 		 * those ires. Thus, we first ensure that ire is the
21487 		 * first RTF_MULTIRT ire in the bucket,
21488 		 * before walking the ire list.
21489 		 */
21490 		ire_t *first_ire;
21491 		irb_t *irb = ire->ire_bucket;
21492 		ASSERT(irb != NULL);
21493 
21494 		/* Make sure we do not omit any multiroute ire. */
21495 		IRB_REFHOLD(irb);
21496 		for (first_ire = irb->irb_ire;
21497 		    first_ire != NULL;
21498 		    first_ire = first_ire->ire_next) {
21499 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21500 			    (first_ire->ire_addr == ire->ire_addr) &&
21501 			    !(first_ire->ire_marks &
21502 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21503 				break;
21504 		}
21505 
21506 		if ((first_ire != NULL) && (first_ire != ire)) {
21507 			IRE_REFHOLD(first_ire);
21508 			ire_refrele(ire);
21509 			ire = first_ire;
21510 			ill = ire_to_ill(ire);
21511 		}
21512 		IRB_REFRELE(irb);
21513 	}
21514 
21515 	/*
21516 	 * conn_outgoing_ill is used only in the broadcast loop.
21517 	 * for performance we don't grab the mutexs in the fastpath
21518 	 */
21519 	if ((connp != NULL) &&
21520 	    (connp->conn_xmit_if_ill == NULL) &&
21521 	    (ire->ire_type == IRE_BROADCAST) &&
21522 	    ((connp->conn_nofailover_ill != NULL) ||
21523 	    (connp->conn_outgoing_ill != NULL))) {
21524 		/*
21525 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21526 		 * option. So, see if this endpoint is bound to a
21527 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21528 		 * that if the interface is failed, we will still send
21529 		 * the packet on the same ill which is what we want.
21530 		 */
21531 		conn_outgoing_ill = conn_get_held_ill(connp,
21532 		    &connp->conn_nofailover_ill, &err);
21533 		if (err == ILL_LOOKUP_FAILED) {
21534 			ire_refrele(ire);
21535 			freemsg(mp);
21536 			return;
21537 		}
21538 		if (conn_outgoing_ill == NULL) {
21539 			/*
21540 			 * Choose a good ill in the group to send the
21541 			 * packets on.
21542 			 */
21543 			ire = conn_set_outgoing_ill(connp, ire,
21544 			    &conn_outgoing_ill);
21545 			if (ire == NULL) {
21546 				freemsg(mp);
21547 				return;
21548 			}
21549 		}
21550 	}
21551 
21552 	if (mp->b_datap->db_type != M_CTL) {
21553 		ipha = (ipha_t *)mp->b_rptr;
21554 	} else {
21555 		io = (ipsec_out_t *)mp->b_rptr;
21556 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21557 		ASSERT(zoneid == io->ipsec_out_zoneid);
21558 		ASSERT(zoneid != ALL_ZONES);
21559 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21560 		dst = ipha->ipha_dst;
21561 		/*
21562 		 * For the multicast case, ipsec_out carries conn_dontroute and
21563 		 * conn_multicast_loop as conn may not be available here. We
21564 		 * need this for multicast loopback and forwarding which is done
21565 		 * later in the code.
21566 		 */
21567 		if (CLASSD(dst)) {
21568 			conn_dontroute = io->ipsec_out_dontroute;
21569 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21570 			/*
21571 			 * If conn_dontroute is not set or conn_multicast_loop
21572 			 * is set, we need to do forwarding/loopback. For
21573 			 * datagrams from ip_wput_multicast, conn_dontroute is
21574 			 * set to B_TRUE and conn_multicast_loop is set to
21575 			 * B_FALSE so that we neither do forwarding nor
21576 			 * loopback.
21577 			 */
21578 			if (!conn_dontroute || conn_multicast_loop)
21579 				multicast_forward = B_TRUE;
21580 		}
21581 	}
21582 
21583 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21584 	    ire->ire_zoneid != ALL_ZONES) {
21585 		/*
21586 		 * When a zone sends a packet to another zone, we try to deliver
21587 		 * the packet under the same conditions as if the destination
21588 		 * was a real node on the network. To do so, we look for a
21589 		 * matching route in the forwarding table.
21590 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21591 		 * ip_newroute() does.
21592 		 * Note that IRE_LOCAL are special, since they are used
21593 		 * when the zoneid doesn't match in some cases. This means that
21594 		 * we need to handle ipha_src differently since ire_src_addr
21595 		 * belongs to the receiving zone instead of the sending zone.
21596 		 * When ip_restrict_interzone_loopback is set, then
21597 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21598 		 * for loopback between zones when the logical "Ethernet" would
21599 		 * have looped them back.
21600 		 */
21601 		ire_t *src_ire;
21602 
21603 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21604 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21605 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21606 		if (src_ire != NULL &&
21607 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21608 		    (!ip_restrict_interzone_loopback ||
21609 		    ire_local_same_ill_group(ire, src_ire))) {
21610 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21611 				ipha->ipha_src = src_ire->ire_src_addr;
21612 			ire_refrele(src_ire);
21613 		} else {
21614 			ire_refrele(ire);
21615 			if (conn_outgoing_ill != NULL)
21616 				ill_refrele(conn_outgoing_ill);
21617 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21618 			if (src_ire != NULL) {
21619 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21620 					ire_refrele(src_ire);
21621 					freemsg(mp);
21622 					return;
21623 				}
21624 				ire_refrele(src_ire);
21625 			}
21626 			if (ip_hdr_complete(ipha, zoneid)) {
21627 				/* Failed */
21628 				freemsg(mp);
21629 				return;
21630 			}
21631 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21632 			return;
21633 		}
21634 	}
21635 
21636 	if (mp->b_datap->db_type == M_CTL ||
21637 	    ipsec_outbound_v4_policy_present) {
21638 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21639 		    unspec_src, zoneid);
21640 		if (mp == NULL) {
21641 			ire_refrele(ire);
21642 			if (conn_outgoing_ill != NULL)
21643 				ill_refrele(conn_outgoing_ill);
21644 			return;
21645 		}
21646 	}
21647 
21648 	first_mp = mp;
21649 	ipsec_len = 0;
21650 
21651 	if (first_mp->b_datap->db_type == M_CTL) {
21652 		io = (ipsec_out_t *)first_mp->b_rptr;
21653 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21654 		mp = first_mp->b_cont;
21655 		ipsec_len = ipsec_out_extra_length(first_mp);
21656 		ASSERT(ipsec_len >= 0);
21657 		/* We already picked up the zoneid from the M_CTL above */
21658 		ASSERT(zoneid == io->ipsec_out_zoneid);
21659 		ASSERT(zoneid != ALL_ZONES);
21660 
21661 		/*
21662 		 * Drop M_CTL here if IPsec processing is not needed.
21663 		 * (Non-IPsec use of M_CTL extracted any information it
21664 		 * needed above).
21665 		 */
21666 		if (ipsec_len == 0) {
21667 			freeb(first_mp);
21668 			first_mp = mp;
21669 		}
21670 	}
21671 
21672 	/*
21673 	 * Fast path for ip_wput_ire
21674 	 */
21675 
21676 	ipha = (ipha_t *)mp->b_rptr;
21677 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21678 	dst = ipha->ipha_dst;
21679 
21680 	/*
21681 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21682 	 * if the socket is a SOCK_RAW type. The transport checksum should
21683 	 * be provided in the pre-built packet, so we don't need to compute it.
21684 	 * Also, other application set flags, like DF, should not be altered.
21685 	 * Other transport MUST pass down zero.
21686 	 */
21687 	ip_hdr_included = ipha->ipha_ident;
21688 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21689 
21690 	if (CLASSD(dst)) {
21691 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21692 		    ntohl(dst),
21693 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21694 		    ntohl(ire->ire_addr)));
21695 	}
21696 
21697 /* Macros to extract header fields from data already in registers */
21698 #ifdef	_BIG_ENDIAN
21699 #define	V_HLEN	(v_hlen_tos_len >> 24)
21700 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21701 #define	PROTO	(ttl_protocol & 0xFF)
21702 #else
21703 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21704 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21705 #define	PROTO	(ttl_protocol >> 8)
21706 #endif
21707 
21708 
21709 	orig_src = src = ipha->ipha_src;
21710 	/* (The loop back to "another" is explained down below.) */
21711 another:;
21712 	/*
21713 	 * Assign an ident value for this packet.  We assign idents on
21714 	 * a per destination basis out of the IRE.  There could be
21715 	 * other threads targeting the same destination, so we have to
21716 	 * arrange for a atomic increment.  Note that we use a 32-bit
21717 	 * atomic add because it has better performance than its
21718 	 * 16-bit sibling.
21719 	 *
21720 	 * If running in cluster mode and if the source address
21721 	 * belongs to a replicated service then vector through
21722 	 * cl_inet_ipident vector to allocate ip identifier
21723 	 * NOTE: This is a contract private interface with the
21724 	 * clustering group.
21725 	 */
21726 	clusterwide = 0;
21727 	if (cl_inet_ipident) {
21728 		ASSERT(cl_inet_isclusterwide);
21729 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21730 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21731 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21732 			    AF_INET, (uint8_t *)(uintptr_t)src,
21733 			    (uint8_t *)(uintptr_t)dst);
21734 			clusterwide = 1;
21735 		}
21736 	}
21737 	if (!clusterwide) {
21738 		ipha->ipha_ident =
21739 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21740 	}
21741 
21742 #ifndef _BIG_ENDIAN
21743 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21744 #endif
21745 
21746 	/*
21747 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21748 	 * This is needed to obey conn_unspec_src when packets go through
21749 	 * ip_newroute + arp.
21750 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21751 	 */
21752 	if (src == INADDR_ANY && !unspec_src) {
21753 		/*
21754 		 * Assign the appropriate source address from the IRE if none
21755 		 * was specified.
21756 		 */
21757 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21758 
21759 		/*
21760 		 * With IP multipathing, broadcast packets are sent on the ire
21761 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21762 		 * the group. However, this ire might not be in the same zone so
21763 		 * we can't always use its source address. We look for a
21764 		 * broadcast ire in the same group and in the right zone.
21765 		 */
21766 		if (ire->ire_type == IRE_BROADCAST &&
21767 		    ire->ire_zoneid != zoneid) {
21768 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21769 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21770 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21771 			if (src_ire != NULL) {
21772 				src = src_ire->ire_src_addr;
21773 				ire_refrele(src_ire);
21774 			} else {
21775 				ire_refrele(ire);
21776 				if (conn_outgoing_ill != NULL)
21777 					ill_refrele(conn_outgoing_ill);
21778 				freemsg(first_mp);
21779 				BUMP_MIB(&ip_mib, ipOutDiscards);
21780 				return;
21781 			}
21782 		} else {
21783 			src = ire->ire_src_addr;
21784 		}
21785 
21786 		if (connp == NULL) {
21787 			ip1dbg(("ip_wput_ire: no connp and no src "
21788 			    "address for dst 0x%x, using src 0x%x\n",
21789 			    ntohl(dst),
21790 			    ntohl(src)));
21791 		}
21792 		ipha->ipha_src = src;
21793 	}
21794 	stq = ire->ire_stq;
21795 
21796 	/*
21797 	 * We only allow ire chains for broadcasts since there will
21798 	 * be multiple IRE_CACHE entries for the same multicast
21799 	 * address (one per ipif).
21800 	 */
21801 	next_mp = NULL;
21802 
21803 	/* broadcast packet */
21804 	if (ire->ire_type == IRE_BROADCAST)
21805 		goto broadcast;
21806 
21807 	/* loopback ? */
21808 	if (stq == NULL)
21809 		goto nullstq;
21810 
21811 	/* The ill_index for outbound ILL */
21812 	ill_index = Q_TO_INDEX(stq);
21813 
21814 	BUMP_MIB(&ip_mib, ipOutRequests);
21815 	ttl_protocol = ((uint16_t *)ipha)[4];
21816 
21817 	/* pseudo checksum (do it in parts for IP header checksum) */
21818 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21819 
21820 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21821 		queue_t *dev_q = stq->q_next;
21822 
21823 		/* flow controlled */
21824 		if ((dev_q->q_next || dev_q->q_first) &&
21825 		    !canput(dev_q))
21826 			goto blocked;
21827 		if ((PROTO == IPPROTO_UDP) &&
21828 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21829 			hlen = (V_HLEN & 0xF) << 2;
21830 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21831 			if (*up != 0) {
21832 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21833 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21834 				/* Software checksum? */
21835 				if (DB_CKSUMFLAGS(mp) == 0) {
21836 					IP_STAT(ip_out_sw_cksum);
21837 					IP_STAT_UPDATE(
21838 					    ip_udp_out_sw_cksum_bytes,
21839 					    LENGTH - hlen);
21840 				}
21841 			}
21842 		}
21843 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21844 		hlen = (V_HLEN & 0xF) << 2;
21845 		if (PROTO == IPPROTO_TCP) {
21846 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21847 			/*
21848 			 * The packet header is processed once and for all, even
21849 			 * in the multirouting case. We disable hardware
21850 			 * checksum if the packet is multirouted, as it will be
21851 			 * replicated via several interfaces, and not all of
21852 			 * them may have this capability.
21853 			 */
21854 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21855 			    LENGTH, max_frag, ipsec_len, cksum);
21856 			/* Software checksum? */
21857 			if (DB_CKSUMFLAGS(mp) == 0) {
21858 				IP_STAT(ip_out_sw_cksum);
21859 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21860 				    LENGTH - hlen);
21861 			}
21862 		} else {
21863 			sctp_hdr_t	*sctph;
21864 
21865 			ASSERT(PROTO == IPPROTO_SCTP);
21866 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21867 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21868 			/*
21869 			 * Zero out the checksum field to ensure proper
21870 			 * checksum calculation.
21871 			 */
21872 			sctph->sh_chksum = 0;
21873 #ifdef	DEBUG
21874 			if (!skip_sctp_cksum)
21875 #endif
21876 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21877 		}
21878 	}
21879 
21880 	/*
21881 	 * If this is a multicast packet and originated from ip_wput
21882 	 * we need to do loopback and forwarding checks. If it comes
21883 	 * from ip_wput_multicast, we SHOULD not do this.
21884 	 */
21885 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21886 
21887 	/* checksum */
21888 	cksum += ttl_protocol;
21889 
21890 	/* fragment the packet */
21891 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21892 		goto fragmentit;
21893 	/*
21894 	 * Don't use frag_flag if packet is pre-built or source
21895 	 * routed or if multicast (since multicast packets do
21896 	 * not solicit ICMP "packet too big" messages).
21897 	 */
21898 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21899 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21900 	    !ip_source_route_included(ipha)) &&
21901 	    !CLASSD(ipha->ipha_dst))
21902 		ipha->ipha_fragment_offset_and_flags |=
21903 		    htons(ire->ire_frag_flag);
21904 
21905 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21906 		/* calculate IP header checksum */
21907 		cksum += ipha->ipha_ident;
21908 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21909 		cksum += ipha->ipha_fragment_offset_and_flags;
21910 
21911 		/* IP options present */
21912 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21913 		if (hlen)
21914 			goto checksumoptions;
21915 
21916 		/* calculate hdr checksum */
21917 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21918 		cksum = ~(cksum + (cksum >> 16));
21919 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21920 	}
21921 	if (ipsec_len != 0) {
21922 		/*
21923 		 * We will do the rest of the processing after
21924 		 * we come back from IPSEC in ip_wput_ipsec_out().
21925 		 */
21926 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21927 
21928 		io = (ipsec_out_t *)first_mp->b_rptr;
21929 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21930 				ill_phyint->phyint_ifindex;
21931 
21932 		ipsec_out_process(q, first_mp, ire, ill_index);
21933 		ire_refrele(ire);
21934 		if (conn_outgoing_ill != NULL)
21935 			ill_refrele(conn_outgoing_ill);
21936 		return;
21937 	}
21938 
21939 	/*
21940 	 * In most cases, the emission loop below is entered only
21941 	 * once. Only in the case where the ire holds the
21942 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21943 	 * flagged ires in the bucket, and send the packet
21944 	 * through all crossed RTF_MULTIRT routes.
21945 	 */
21946 	if (ire->ire_flags & RTF_MULTIRT) {
21947 		multirt_send = B_TRUE;
21948 	}
21949 	do {
21950 		if (multirt_send) {
21951 			irb_t *irb;
21952 			/*
21953 			 * We are in a multiple send case, need to get
21954 			 * the next ire and make a duplicate of the packet.
21955 			 * ire1 holds here the next ire to process in the
21956 			 * bucket. If multirouting is expected,
21957 			 * any non-RTF_MULTIRT ire that has the
21958 			 * right destination address is ignored.
21959 			 */
21960 			irb = ire->ire_bucket;
21961 			ASSERT(irb != NULL);
21962 
21963 			IRB_REFHOLD(irb);
21964 			for (ire1 = ire->ire_next;
21965 			    ire1 != NULL;
21966 			    ire1 = ire1->ire_next) {
21967 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21968 					continue;
21969 				if (ire1->ire_addr != ire->ire_addr)
21970 					continue;
21971 				if (ire1->ire_marks &
21972 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21973 					continue;
21974 
21975 				/* Got one */
21976 				IRE_REFHOLD(ire1);
21977 				break;
21978 			}
21979 			IRB_REFRELE(irb);
21980 
21981 			if (ire1 != NULL) {
21982 				next_mp = copyb(mp);
21983 				if ((next_mp == NULL) ||
21984 				    ((mp->b_cont != NULL) &&
21985 				    ((next_mp->b_cont =
21986 				    dupmsg(mp->b_cont)) == NULL))) {
21987 					freemsg(next_mp);
21988 					next_mp = NULL;
21989 					ire_refrele(ire1);
21990 					ire1 = NULL;
21991 				}
21992 			}
21993 
21994 			/* Last multiroute ire; don't loop anymore. */
21995 			if (ire1 == NULL) {
21996 				multirt_send = B_FALSE;
21997 			}
21998 		}
21999 
22000 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22001 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22002 		    mblk_t *, mp);
22003 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
22004 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
22005 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22006 		if (mp == NULL)
22007 			goto release_ire_and_ill;
22008 
22009 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22010 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22011 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22012 		if ((pktxmit_state == SEND_FAILED) ||
22013 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22014 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22015 			    "- packet dropped\n"));
22016 release_ire_and_ill:
22017 			ire_refrele(ire);
22018 			if (next_mp != NULL) {
22019 				freemsg(next_mp);
22020 				ire_refrele(ire1);
22021 			}
22022 			if (conn_outgoing_ill != NULL)
22023 				ill_refrele(conn_outgoing_ill);
22024 			return;
22025 		}
22026 
22027 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22028 		    "ip_wput_ire_end: q %p (%S)",
22029 		    q, "last copy out");
22030 		IRE_REFRELE(ire);
22031 
22032 		if (multirt_send) {
22033 			ASSERT(ire1);
22034 			/*
22035 			 * Proceed with the next RTF_MULTIRT ire,
22036 			 * Also set up the send-to queue accordingly.
22037 			 */
22038 			ire = ire1;
22039 			ire1 = NULL;
22040 			stq = ire->ire_stq;
22041 			mp = next_mp;
22042 			next_mp = NULL;
22043 			ipha = (ipha_t *)mp->b_rptr;
22044 			ill_index = Q_TO_INDEX(stq);
22045 		}
22046 	} while (multirt_send);
22047 	if (conn_outgoing_ill != NULL)
22048 		ill_refrele(conn_outgoing_ill);
22049 	return;
22050 
22051 	/*
22052 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22053 	 */
22054 broadcast:
22055 	{
22056 		/*
22057 		 * Avoid broadcast storms by setting the ttl to 1
22058 		 * for broadcasts. This parameter can be set
22059 		 * via ndd, so make sure that for the SO_DONTROUTE
22060 		 * case that ipha_ttl is always set to 1.
22061 		 * In the event that we are replying to incoming
22062 		 * ICMP packets, conn could be NULL.
22063 		 */
22064 		if ((connp != NULL) && connp->conn_dontroute)
22065 			ipha->ipha_ttl = 1;
22066 		else
22067 			ipha->ipha_ttl = ip_broadcast_ttl;
22068 
22069 		/*
22070 		 * Note that we are not doing a IRB_REFHOLD here.
22071 		 * Actually we don't care if the list changes i.e
22072 		 * if somebody deletes an IRE from the list while
22073 		 * we drop the lock, the next time we come around
22074 		 * ire_next will be NULL and hence we won't send
22075 		 * out multiple copies which is fine.
22076 		 */
22077 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22078 		ire1 = ire->ire_next;
22079 		if (conn_outgoing_ill != NULL) {
22080 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22081 				ASSERT(ire1 == ire->ire_next);
22082 				if (ire1 != NULL && ire1->ire_addr == dst) {
22083 					ire_refrele(ire);
22084 					ire = ire1;
22085 					IRE_REFHOLD(ire);
22086 					ire1 = ire->ire_next;
22087 					continue;
22088 				}
22089 				rw_exit(&ire->ire_bucket->irb_lock);
22090 				/* Did not find a matching ill */
22091 				ip1dbg(("ip_wput_ire: broadcast with no "
22092 				    "matching IP_BOUND_IF ill %s\n",
22093 				    conn_outgoing_ill->ill_name));
22094 				freemsg(first_mp);
22095 				if (ire != NULL)
22096 					ire_refrele(ire);
22097 				ill_refrele(conn_outgoing_ill);
22098 				return;
22099 			}
22100 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22101 			/*
22102 			 * If the next IRE has the same address and is not one
22103 			 * of the two copies that we need to send, try to see
22104 			 * whether this copy should be sent at all. This
22105 			 * assumes that we insert loopbacks first and then
22106 			 * non-loopbacks. This is acheived by inserting the
22107 			 * loopback always before non-loopback.
22108 			 * This is used to send a single copy of a broadcast
22109 			 * packet out all physical interfaces that have an
22110 			 * matching IRE_BROADCAST while also looping
22111 			 * back one copy (to ip_wput_local) for each
22112 			 * matching physical interface. However, we avoid
22113 			 * sending packets out different logical that match by
22114 			 * having ipif_up/ipif_down supress duplicate
22115 			 * IRE_BROADCASTS.
22116 			 *
22117 			 * This feature is currently used to get broadcasts
22118 			 * sent to multiple interfaces, when the broadcast
22119 			 * address being used applies to multiple interfaces.
22120 			 * For example, a whole net broadcast will be
22121 			 * replicated on every connected subnet of
22122 			 * the target net.
22123 			 *
22124 			 * Each zone has its own set of IRE_BROADCASTs, so that
22125 			 * we're able to distribute inbound packets to multiple
22126 			 * zones who share a broadcast address. We avoid looping
22127 			 * back outbound packets in different zones but on the
22128 			 * same ill, as the application would see duplicates.
22129 			 *
22130 			 * If the interfaces are part of the same group,
22131 			 * we would want to send only one copy out for
22132 			 * whole group.
22133 			 *
22134 			 * This logic assumes that ire_add_v4() groups the
22135 			 * IRE_BROADCAST entries so that those with the same
22136 			 * ire_addr and ill_group are kept together.
22137 			 */
22138 			ire_ill = ire->ire_ipif->ipif_ill;
22139 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22140 				if (ire_ill->ill_group != NULL &&
22141 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22142 					/*
22143 					 * If the current zone only has an ire
22144 					 * broadcast for this address marked
22145 					 * NORECV, the ire we want is ahead in
22146 					 * the bucket, so we look it up
22147 					 * deliberately ignoring the zoneid.
22148 					 */
22149 					for (ire1 = ire->ire_bucket->irb_ire;
22150 					    ire1 != NULL;
22151 					    ire1 = ire1->ire_next) {
22152 						ire1_ill =
22153 						    ire1->ire_ipif->ipif_ill;
22154 						if (ire1->ire_addr != dst)
22155 							continue;
22156 						/* skip over the current ire */
22157 						if (ire1 == ire)
22158 							continue;
22159 						/* skip over deleted ires */
22160 						if (ire1->ire_marks &
22161 						    IRE_MARK_CONDEMNED)
22162 							continue;
22163 						/*
22164 						 * non-loopback ire in our
22165 						 * group: use it for the next
22166 						 * pass in the loop
22167 						 */
22168 						if (ire1->ire_stq != NULL &&
22169 						    ire1_ill->ill_group ==
22170 						    ire_ill->ill_group)
22171 							break;
22172 					}
22173 				}
22174 			} else {
22175 				while (ire1 != NULL && ire1->ire_addr == dst) {
22176 					ire1_ill = ire1->ire_ipif->ipif_ill;
22177 					/*
22178 					 * We can have two broadcast ires on the
22179 					 * same ill in different zones; here
22180 					 * we'll send a copy of the packet on
22181 					 * each ill and the fanout code will
22182 					 * call conn_wantpacket() to check that
22183 					 * the zone has the broadcast address
22184 					 * configured on the ill. If the two
22185 					 * ires are in the same group we only
22186 					 * send one copy up.
22187 					 */
22188 					if (ire1_ill != ire_ill &&
22189 					    (ire1_ill->ill_group == NULL ||
22190 					    ire_ill->ill_group == NULL ||
22191 					    ire1_ill->ill_group !=
22192 					    ire_ill->ill_group)) {
22193 						break;
22194 					}
22195 					ire1 = ire1->ire_next;
22196 				}
22197 			}
22198 		}
22199 		ASSERT(multirt_send == B_FALSE);
22200 		if (ire1 != NULL && ire1->ire_addr == dst) {
22201 			if ((ire->ire_flags & RTF_MULTIRT) &&
22202 			    (ire1->ire_flags & RTF_MULTIRT)) {
22203 				/*
22204 				 * We are in the multirouting case.
22205 				 * The message must be sent at least
22206 				 * on both ires. These ires have been
22207 				 * inserted AFTER the standard ones
22208 				 * in ip_rt_add(). There are thus no
22209 				 * other ire entries for the destination
22210 				 * address in the rest of the bucket
22211 				 * that do not have the RTF_MULTIRT
22212 				 * flag. We don't process a copy
22213 				 * of the message here. This will be
22214 				 * done in the final sending loop.
22215 				 */
22216 				multirt_send = B_TRUE;
22217 			} else {
22218 				next_mp = ip_copymsg(first_mp);
22219 				if (next_mp != NULL)
22220 					IRE_REFHOLD(ire1);
22221 			}
22222 		}
22223 		rw_exit(&ire->ire_bucket->irb_lock);
22224 	}
22225 
22226 	if (stq) {
22227 		/*
22228 		 * A non-NULL send-to queue means this packet is going
22229 		 * out of this machine.
22230 		 */
22231 
22232 		BUMP_MIB(&ip_mib, ipOutRequests);
22233 		ttl_protocol = ((uint16_t *)ipha)[4];
22234 		/*
22235 		 * We accumulate the pseudo header checksum in cksum.
22236 		 * This is pretty hairy code, so watch close.  One
22237 		 * thing to keep in mind is that UDP and TCP have
22238 		 * stored their respective datagram lengths in their
22239 		 * checksum fields.  This lines things up real nice.
22240 		 */
22241 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22242 		    (src >> 16) + (src & 0xFFFF);
22243 		/*
22244 		 * We assume the udp checksum field contains the
22245 		 * length, so to compute the pseudo header checksum,
22246 		 * all we need is the protocol number and src/dst.
22247 		 */
22248 		/* Provide the checksums for UDP and TCP. */
22249 		if ((PROTO == IPPROTO_TCP) &&
22250 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22251 			/* hlen gets the number of uchar_ts in the IP header */
22252 			hlen = (V_HLEN & 0xF) << 2;
22253 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22254 			IP_STAT(ip_out_sw_cksum);
22255 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22256 			    LENGTH - hlen);
22257 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22258 			if (*up == 0)
22259 				*up = 0xFFFF;
22260 		} else if (PROTO == IPPROTO_SCTP &&
22261 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22262 			sctp_hdr_t	*sctph;
22263 
22264 			hlen = (V_HLEN & 0xF) << 2;
22265 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22266 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22267 			sctph->sh_chksum = 0;
22268 #ifdef	DEBUG
22269 			if (!skip_sctp_cksum)
22270 #endif
22271 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22272 		} else {
22273 			queue_t *dev_q = stq->q_next;
22274 
22275 			if ((dev_q->q_next || dev_q->q_first) &&
22276 			    !canput(dev_q)) {
22277 			    blocked:
22278 				ipha->ipha_ident = ip_hdr_included;
22279 				/*
22280 				 * If we don't have a conn to apply
22281 				 * backpressure, free the message.
22282 				 * In the ire_send path, we don't know
22283 				 * the position to requeue the packet. Rather
22284 				 * than reorder packets, we just drop this
22285 				 * packet.
22286 				 */
22287 				if (ip_output_queue && connp != NULL &&
22288 				    caller != IRE_SEND) {
22289 					if (caller == IP_WSRV) {
22290 						connp->conn_did_putbq = 1;
22291 						(void) putbq(connp->conn_wq,
22292 						    first_mp);
22293 						conn_drain_insert(connp);
22294 						/*
22295 						 * This is the service thread,
22296 						 * and the queue is already
22297 						 * noenabled. The check for
22298 						 * canput and the putbq is not
22299 						 * atomic. So we need to check
22300 						 * again.
22301 						 */
22302 						if (canput(stq->q_next))
22303 							connp->conn_did_putbq
22304 							    = 0;
22305 						IP_STAT(ip_conn_flputbq);
22306 					} else {
22307 						/*
22308 						 * We are not the service proc.
22309 						 * ip_wsrv will be scheduled or
22310 						 * is already running.
22311 						 */
22312 						(void) putq(connp->conn_wq,
22313 						    first_mp);
22314 					}
22315 				} else {
22316 					BUMP_MIB(&ip_mib, ipOutDiscards);
22317 					freemsg(first_mp);
22318 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22319 					    "ip_wput_ire_end: q %p (%S)",
22320 					    q, "discard");
22321 				}
22322 				ire_refrele(ire);
22323 				if (next_mp) {
22324 					ire_refrele(ire1);
22325 					freemsg(next_mp);
22326 				}
22327 				if (conn_outgoing_ill != NULL)
22328 					ill_refrele(conn_outgoing_ill);
22329 				return;
22330 			}
22331 			if ((PROTO == IPPROTO_UDP) &&
22332 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22333 				/*
22334 				 * hlen gets the number of uchar_ts in the
22335 				 * IP header
22336 				 */
22337 				hlen = (V_HLEN & 0xF) << 2;
22338 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22339 				max_frag = ire->ire_max_frag;
22340 				if (*up != 0) {
22341 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22342 					    up, PROTO, hlen, LENGTH, max_frag,
22343 					    ipsec_len, cksum);
22344 					/* Software checksum? */
22345 					if (DB_CKSUMFLAGS(mp) == 0) {
22346 						IP_STAT(ip_out_sw_cksum);
22347 						IP_STAT_UPDATE(
22348 						    ip_udp_out_sw_cksum_bytes,
22349 						    LENGTH - hlen);
22350 					}
22351 				}
22352 			}
22353 		}
22354 		/*
22355 		 * Need to do this even when fragmenting. The local
22356 		 * loopback can be done without computing checksums
22357 		 * but forwarding out other interface must be done
22358 		 * after the IP checksum (and ULP checksums) have been
22359 		 * computed.
22360 		 *
22361 		 * NOTE : multicast_forward is set only if this packet
22362 		 * originated from ip_wput. For packets originating from
22363 		 * ip_wput_multicast, it is not set.
22364 		 */
22365 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22366 		    multi_loopback:
22367 			ip2dbg(("ip_wput: multicast, loop %d\n",
22368 			    conn_multicast_loop));
22369 
22370 			/*  Forget header checksum offload */
22371 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22372 
22373 			/*
22374 			 * Local loopback of multicasts?  Check the
22375 			 * ill.
22376 			 *
22377 			 * Note that the loopback function will not come
22378 			 * in through ip_rput - it will only do the
22379 			 * client fanout thus we need to do an mforward
22380 			 * as well.  The is different from the BSD
22381 			 * logic.
22382 			 */
22383 			if (ill != NULL) {
22384 				ilm_t	*ilm;
22385 
22386 				ILM_WALKER_HOLD(ill);
22387 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22388 				    ALL_ZONES);
22389 				ILM_WALKER_RELE(ill);
22390 				if (ilm != NULL) {
22391 					/*
22392 					 * Pass along the virtual output q.
22393 					 * ip_wput_local() will distribute the
22394 					 * packet to all the matching zones,
22395 					 * except the sending zone when
22396 					 * IP_MULTICAST_LOOP is false.
22397 					 */
22398 					ip_multicast_loopback(q, ill, first_mp,
22399 					    conn_multicast_loop ? 0 :
22400 					    IP_FF_NO_MCAST_LOOP, zoneid);
22401 				}
22402 			}
22403 			if (ipha->ipha_ttl == 0) {
22404 				/*
22405 				 * 0 => only to this host i.e. we are
22406 				 * done. We are also done if this was the
22407 				 * loopback interface since it is sufficient
22408 				 * to loopback one copy of a multicast packet.
22409 				 */
22410 				freemsg(first_mp);
22411 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22412 				    "ip_wput_ire_end: q %p (%S)",
22413 				    q, "loopback");
22414 				ire_refrele(ire);
22415 				if (conn_outgoing_ill != NULL)
22416 					ill_refrele(conn_outgoing_ill);
22417 				return;
22418 			}
22419 			/*
22420 			 * ILLF_MULTICAST is checked in ip_newroute
22421 			 * i.e. we don't need to check it here since
22422 			 * all IRE_CACHEs come from ip_newroute.
22423 			 * For multicast traffic, SO_DONTROUTE is interpreted
22424 			 * to mean only send the packet out the interface
22425 			 * (optionally specified with IP_MULTICAST_IF)
22426 			 * and do not forward it out additional interfaces.
22427 			 * RSVP and the rsvp daemon is an example of a
22428 			 * protocol and user level process that
22429 			 * handles it's own routing. Hence, it uses the
22430 			 * SO_DONTROUTE option to accomplish this.
22431 			 */
22432 
22433 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22434 				/* Unconditionally redo the checksum */
22435 				ipha->ipha_hdr_checksum = 0;
22436 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22437 
22438 				/*
22439 				 * If this needs to go out secure, we need
22440 				 * to wait till we finish the IPSEC
22441 				 * processing.
22442 				 */
22443 				if (ipsec_len == 0 &&
22444 				    ip_mforward(ill, ipha, mp)) {
22445 					freemsg(first_mp);
22446 					ip1dbg(("ip_wput: mforward failed\n"));
22447 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22448 					    "ip_wput_ire_end: q %p (%S)",
22449 					    q, "mforward failed");
22450 					ire_refrele(ire);
22451 					if (conn_outgoing_ill != NULL)
22452 						ill_refrele(conn_outgoing_ill);
22453 					return;
22454 				}
22455 			}
22456 		}
22457 		max_frag = ire->ire_max_frag;
22458 		cksum += ttl_protocol;
22459 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22460 			/* No fragmentation required for this one. */
22461 			/*
22462 			 * Don't use frag_flag if packet is pre-built or source
22463 			 * routed or if multicast (since multicast packets do
22464 			 * not solicit ICMP "packet too big" messages).
22465 			 */
22466 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22467 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22468 			    !ip_source_route_included(ipha)) &&
22469 			    !CLASSD(ipha->ipha_dst))
22470 				ipha->ipha_fragment_offset_and_flags |=
22471 				    htons(ire->ire_frag_flag);
22472 
22473 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22474 				/* Complete the IP header checksum. */
22475 				cksum += ipha->ipha_ident;
22476 				cksum += (v_hlen_tos_len >> 16)+
22477 				    (v_hlen_tos_len & 0xFFFF);
22478 				cksum += ipha->ipha_fragment_offset_and_flags;
22479 				hlen = (V_HLEN & 0xF) -
22480 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22481 				if (hlen) {
22482 				    checksumoptions:
22483 					/*
22484 					 * Account for the IP Options in the IP
22485 					 * header checksum.
22486 					 */
22487 					up = (uint16_t *)(rptr+
22488 					    IP_SIMPLE_HDR_LENGTH);
22489 					do {
22490 						cksum += up[0];
22491 						cksum += up[1];
22492 						up += 2;
22493 					} while (--hlen);
22494 				}
22495 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22496 				cksum = ~(cksum + (cksum >> 16));
22497 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22498 			}
22499 			if (ipsec_len != 0) {
22500 				ipsec_out_process(q, first_mp, ire, ill_index);
22501 				if (!next_mp) {
22502 					ire_refrele(ire);
22503 					if (conn_outgoing_ill != NULL)
22504 						ill_refrele(conn_outgoing_ill);
22505 					return;
22506 				}
22507 				goto next;
22508 			}
22509 
22510 			/*
22511 			 * multirt_send has already been handled
22512 			 * for broadcast, but not yet for multicast
22513 			 * or IP options.
22514 			 */
22515 			if (next_mp == NULL) {
22516 				if (ire->ire_flags & RTF_MULTIRT) {
22517 					multirt_send = B_TRUE;
22518 				}
22519 			}
22520 
22521 			/*
22522 			 * In most cases, the emission loop below is
22523 			 * entered only once. Only in the case where
22524 			 * the ire holds the RTF_MULTIRT flag, do we loop
22525 			 * to process all RTF_MULTIRT ires in the bucket,
22526 			 * and send the packet through all crossed
22527 			 * RTF_MULTIRT routes.
22528 			 */
22529 			do {
22530 				if (multirt_send) {
22531 					irb_t *irb;
22532 
22533 					irb = ire->ire_bucket;
22534 					ASSERT(irb != NULL);
22535 					/*
22536 					 * We are in a multiple send case,
22537 					 * need to get the next IRE and make
22538 					 * a duplicate of the packet.
22539 					 */
22540 					IRB_REFHOLD(irb);
22541 					for (ire1 = ire->ire_next;
22542 					    ire1 != NULL;
22543 					    ire1 = ire1->ire_next) {
22544 						if (!(ire1->ire_flags &
22545 						    RTF_MULTIRT))
22546 							continue;
22547 						if (ire1->ire_addr !=
22548 						    ire->ire_addr)
22549 							continue;
22550 						if (ire1->ire_marks &
22551 						    (IRE_MARK_CONDEMNED|
22552 							IRE_MARK_HIDDEN))
22553 							continue;
22554 
22555 						/* Got one */
22556 						IRE_REFHOLD(ire1);
22557 						break;
22558 					}
22559 					IRB_REFRELE(irb);
22560 
22561 					if (ire1 != NULL) {
22562 						next_mp = copyb(mp);
22563 						if ((next_mp == NULL) ||
22564 						    ((mp->b_cont != NULL) &&
22565 						    ((next_mp->b_cont =
22566 						    dupmsg(mp->b_cont))
22567 						    == NULL))) {
22568 							freemsg(next_mp);
22569 							next_mp = NULL;
22570 							ire_refrele(ire1);
22571 							ire1 = NULL;
22572 						}
22573 					}
22574 
22575 					/*
22576 					 * Last multiroute ire; don't loop
22577 					 * anymore. The emission is over
22578 					 * and next_mp is NULL.
22579 					 */
22580 					if (ire1 == NULL) {
22581 						multirt_send = B_FALSE;
22582 					}
22583 				}
22584 
22585 				out_ill = ire->ire_ipif->ipif_ill;
22586 				DTRACE_PROBE4(ip4__physical__out__start,
22587 				    ill_t *, NULL,
22588 				    ill_t *, out_ill,
22589 				    ipha_t *, ipha, mblk_t *, mp);
22590 				FW_HOOKS(ip4_physical_out_event,
22591 				    ipv4firewall_physical_out,
22592 				    NULL, out_ill, ipha, mp, mp);
22593 				DTRACE_PROBE1(ip4__physical__out__end,
22594 				    mblk_t *, mp);
22595 				if (mp == NULL)
22596 					goto release_ire_and_ill_2;
22597 
22598 				ASSERT(ipsec_len == 0);
22599 				mp->b_prev =
22600 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22601 				DTRACE_PROBE2(ip__xmit__2,
22602 				    mblk_t *, mp, ire_t *, ire);
22603 				pktxmit_state = ip_xmit_v4(mp, ire,
22604 				    NULL, B_TRUE);
22605 				if ((pktxmit_state == SEND_FAILED) ||
22606 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22607 release_ire_and_ill_2:
22608 					if (next_mp) {
22609 						freemsg(next_mp);
22610 						ire_refrele(ire1);
22611 					}
22612 					ire_refrele(ire);
22613 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22614 					    "ip_wput_ire_end: q %p (%S)",
22615 					    q, "discard MDATA");
22616 					if (conn_outgoing_ill != NULL)
22617 						ill_refrele(conn_outgoing_ill);
22618 					return;
22619 				}
22620 
22621 				if (multirt_send) {
22622 					/*
22623 					 * We are in a multiple send case,
22624 					 * need to re-enter the sending loop
22625 					 * using the next ire.
22626 					 */
22627 					ire_refrele(ire);
22628 					ire = ire1;
22629 					stq = ire->ire_stq;
22630 					mp = next_mp;
22631 					next_mp = NULL;
22632 					ipha = (ipha_t *)mp->b_rptr;
22633 					ill_index = Q_TO_INDEX(stq);
22634 				}
22635 			} while (multirt_send);
22636 
22637 			if (!next_mp) {
22638 				/*
22639 				 * Last copy going out (the ultra-common
22640 				 * case).  Note that we intentionally replicate
22641 				 * the putnext rather than calling it before
22642 				 * the next_mp check in hopes of a little
22643 				 * tail-call action out of the compiler.
22644 				 */
22645 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22646 				    "ip_wput_ire_end: q %p (%S)",
22647 				    q, "last copy out(1)");
22648 				ire_refrele(ire);
22649 				if (conn_outgoing_ill != NULL)
22650 					ill_refrele(conn_outgoing_ill);
22651 				return;
22652 			}
22653 			/* More copies going out below. */
22654 		} else {
22655 			int offset;
22656 		    fragmentit:
22657 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22658 			/*
22659 			 * If this would generate a icmp_frag_needed message,
22660 			 * we need to handle it before we do the IPSEC
22661 			 * processing. Otherwise, we need to strip the IPSEC
22662 			 * headers before we send up the message to the ULPs
22663 			 * which becomes messy and difficult.
22664 			 */
22665 			if (ipsec_len != 0) {
22666 				if ((max_frag < (unsigned int)(LENGTH +
22667 				    ipsec_len)) && (offset & IPH_DF)) {
22668 
22669 					BUMP_MIB(&ip_mib, ipFragFails);
22670 					ipha->ipha_hdr_checksum = 0;
22671 					ipha->ipha_hdr_checksum =
22672 					    (uint16_t)ip_csum_hdr(ipha);
22673 					icmp_frag_needed(ire->ire_stq, first_mp,
22674 					    max_frag, zoneid);
22675 					if (!next_mp) {
22676 						ire_refrele(ire);
22677 						if (conn_outgoing_ill != NULL) {
22678 							ill_refrele(
22679 							    conn_outgoing_ill);
22680 						}
22681 						return;
22682 					}
22683 				} else {
22684 					/*
22685 					 * This won't cause a icmp_frag_needed
22686 					 * message. to be gnerated. Send it on
22687 					 * the wire. Note that this could still
22688 					 * cause fragmentation and all we
22689 					 * do is the generation of the message
22690 					 * to the ULP if needed before IPSEC.
22691 					 */
22692 					if (!next_mp) {
22693 						ipsec_out_process(q, first_mp,
22694 						    ire, ill_index);
22695 						TRACE_2(TR_FAC_IP,
22696 						    TR_IP_WPUT_IRE_END,
22697 						    "ip_wput_ire_end: q %p "
22698 						    "(%S)", q,
22699 						    "last ipsec_out_process");
22700 						ire_refrele(ire);
22701 						if (conn_outgoing_ill != NULL) {
22702 							ill_refrele(
22703 							    conn_outgoing_ill);
22704 						}
22705 						return;
22706 					}
22707 					ipsec_out_process(q, first_mp,
22708 					    ire, ill_index);
22709 				}
22710 			} else {
22711 				/*
22712 				 * Initiate IPPF processing. For
22713 				 * fragmentable packets we finish
22714 				 * all QOS packet processing before
22715 				 * calling:
22716 				 * ip_wput_ire_fragmentit->ip_wput_frag
22717 				 */
22718 
22719 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22720 					ip_process(IPP_LOCAL_OUT, &mp,
22721 					    ill_index);
22722 					if (mp == NULL) {
22723 						BUMP_MIB(&ip_mib,
22724 						    ipOutDiscards);
22725 						if (next_mp != NULL) {
22726 							freemsg(next_mp);
22727 							ire_refrele(ire1);
22728 						}
22729 						ire_refrele(ire);
22730 						TRACE_2(TR_FAC_IP,
22731 						    TR_IP_WPUT_IRE_END,
22732 						    "ip_wput_ire: q %p (%S)",
22733 						    q, "discard MDATA");
22734 						if (conn_outgoing_ill != NULL) {
22735 							ill_refrele(
22736 							    conn_outgoing_ill);
22737 						}
22738 						return;
22739 					}
22740 				}
22741 				if (!next_mp) {
22742 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22743 					    "ip_wput_ire_end: q %p (%S)",
22744 					    q, "last fragmentation");
22745 					ip_wput_ire_fragmentit(mp, ire,
22746 					    zoneid);
22747 					ire_refrele(ire);
22748 					if (conn_outgoing_ill != NULL)
22749 						ill_refrele(conn_outgoing_ill);
22750 					return;
22751 				}
22752 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22753 			}
22754 		}
22755 	} else {
22756 	    nullstq:
22757 		/* A NULL stq means the destination address is local. */
22758 		UPDATE_OB_PKT_COUNT(ire);
22759 		ire->ire_last_used_time = lbolt;
22760 		ASSERT(ire->ire_ipif != NULL);
22761 		if (!next_mp) {
22762 			/*
22763 			 * Is there an "in" and "out" for traffic local
22764 			 * to a host (loopback)?  The code in Solaris doesn't
22765 			 * explicitly draw a line in its code for in vs out,
22766 			 * so we've had to draw a line in the sand: ip_wput_ire
22767 			 * is considered to be the "output" side and
22768 			 * ip_wput_local to be the "input" side.
22769 			 */
22770 			out_ill = ire->ire_ipif->ipif_ill;
22771 
22772 			DTRACE_PROBE4(ip4__loopback__out__start,
22773 			    ill_t *, NULL, ill_t *, out_ill,
22774 			    ipha_t *, ipha, mblk_t *, first_mp);
22775 
22776 			FW_HOOKS(ip4_loopback_out_event,
22777 			    ipv4firewall_loopback_out,
22778 			    NULL, out_ill, ipha, first_mp, mp);
22779 
22780 			DTRACE_PROBE1(ip4__loopback__out_end,
22781 			    mblk_t *, first_mp);
22782 
22783 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22784 			    "ip_wput_ire_end: q %p (%S)",
22785 			    q, "local address");
22786 
22787 			if (first_mp != NULL)
22788 				ip_wput_local(q, out_ill, ipha,
22789 				    first_mp, ire, 0, ire->ire_zoneid);
22790 			ire_refrele(ire);
22791 			if (conn_outgoing_ill != NULL)
22792 				ill_refrele(conn_outgoing_ill);
22793 			return;
22794 		}
22795 
22796 		out_ill = ire->ire_ipif->ipif_ill;
22797 
22798 		DTRACE_PROBE4(ip4__loopback__out__start,
22799 		    ill_t *, NULL, ill_t *, out_ill,
22800 		    ipha_t *, ipha, mblk_t *, first_mp);
22801 
22802 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22803 		    NULL, out_ill, ipha, first_mp, mp);
22804 
22805 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22806 
22807 		if (first_mp != NULL)
22808 			ip_wput_local(q, out_ill, ipha,
22809 			    first_mp, ire, 0, ire->ire_zoneid);
22810 	}
22811 next:
22812 	/*
22813 	 * More copies going out to additional interfaces.
22814 	 * ire1 has already been held. We don't need the
22815 	 * "ire" anymore.
22816 	 */
22817 	ire_refrele(ire);
22818 	ire = ire1;
22819 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22820 	mp = next_mp;
22821 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22822 	ill = ire_to_ill(ire);
22823 	first_mp = mp;
22824 	if (ipsec_len != 0) {
22825 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22826 		mp = mp->b_cont;
22827 	}
22828 	dst = ire->ire_addr;
22829 	ipha = (ipha_t *)mp->b_rptr;
22830 	/*
22831 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22832 	 * Restore ipha_ident "no checksum" flag.
22833 	 */
22834 	src = orig_src;
22835 	ipha->ipha_ident = ip_hdr_included;
22836 	goto another;
22837 
22838 #undef	rptr
22839 #undef	Q_TO_INDEX
22840 }
22841 
22842 /*
22843  * Routine to allocate a message that is used to notify the ULP about MDT.
22844  * The caller may provide a pointer to the link-layer MDT capabilities,
22845  * or NULL if MDT is to be disabled on the stream.
22846  */
22847 mblk_t *
22848 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22849 {
22850 	mblk_t *mp;
22851 	ip_mdt_info_t *mdti;
22852 	ill_mdt_capab_t *idst;
22853 
22854 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22855 		DB_TYPE(mp) = M_CTL;
22856 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22857 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22858 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22859 		idst = &(mdti->mdt_capab);
22860 
22861 		/*
22862 		 * If the caller provides us with the capability, copy
22863 		 * it over into our notification message; otherwise
22864 		 * we zero out the capability portion.
22865 		 */
22866 		if (isrc != NULL)
22867 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22868 		else
22869 			bzero((caddr_t)idst, sizeof (*idst));
22870 	}
22871 	return (mp);
22872 }
22873 
22874 /*
22875  * Routine which determines whether MDT can be enabled on the destination
22876  * IRE and IPC combination, and if so, allocates and returns the MDT
22877  * notification mblk that may be used by ULP.  We also check if we need to
22878  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22879  * MDT usage in the past have been lifted.  This gets called during IP
22880  * and ULP binding.
22881  */
22882 mblk_t *
22883 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22884     ill_mdt_capab_t *mdt_cap)
22885 {
22886 	mblk_t *mp;
22887 	boolean_t rc = B_FALSE;
22888 
22889 	ASSERT(dst_ire != NULL);
22890 	ASSERT(connp != NULL);
22891 	ASSERT(mdt_cap != NULL);
22892 
22893 	/*
22894 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22895 	 * Multidata, which is handled in tcp_multisend().  This
22896 	 * is the reason why we do all these checks here, to ensure
22897 	 * that we don't enable Multidata for the cases which we
22898 	 * can't handle at the moment.
22899 	 */
22900 	do {
22901 		/* Only do TCP at the moment */
22902 		if (connp->conn_ulp != IPPROTO_TCP)
22903 			break;
22904 
22905 		/*
22906 		 * IPSEC outbound policy present?  Note that we get here
22907 		 * after calling ipsec_conn_cache_policy() where the global
22908 		 * policy checking is performed.  conn_latch will be
22909 		 * non-NULL as long as there's a policy defined,
22910 		 * i.e. conn_out_enforce_policy may be NULL in such case
22911 		 * when the connection is non-secure, and hence we check
22912 		 * further if the latch refers to an outbound policy.
22913 		 */
22914 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22915 			break;
22916 
22917 		/* CGTP (multiroute) is enabled? */
22918 		if (dst_ire->ire_flags & RTF_MULTIRT)
22919 			break;
22920 
22921 		/* Outbound IPQoS enabled? */
22922 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22923 			/*
22924 			 * In this case, we disable MDT for this and all
22925 			 * future connections going over the interface.
22926 			 */
22927 			mdt_cap->ill_mdt_on = 0;
22928 			break;
22929 		}
22930 
22931 		/* socket option(s) present? */
22932 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
22933 			break;
22934 
22935 		rc = B_TRUE;
22936 	/* CONSTCOND */
22937 	} while (0);
22938 
22939 	/* Remember the result */
22940 	connp->conn_mdt_ok = rc;
22941 
22942 	if (!rc)
22943 		return (NULL);
22944 	else if (!mdt_cap->ill_mdt_on) {
22945 		/*
22946 		 * If MDT has been previously turned off in the past, and we
22947 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22948 		 * then enable it for this interface.
22949 		 */
22950 		mdt_cap->ill_mdt_on = 1;
22951 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22952 		    "interface %s\n", ill_name));
22953 	}
22954 
22955 	/* Allocate the MDT info mblk */
22956 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22957 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22958 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22959 		return (NULL);
22960 	}
22961 	return (mp);
22962 }
22963 
22964 /*
22965  * Routine to allocate a message that is used to notify the ULP about LSO.
22966  * The caller may provide a pointer to the link-layer LSO capabilities,
22967  * or NULL if LSO is to be disabled on the stream.
22968  */
22969 mblk_t *
22970 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
22971 {
22972 	mblk_t *mp;
22973 	ip_lso_info_t *lsoi;
22974 	ill_lso_capab_t *idst;
22975 
22976 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
22977 		DB_TYPE(mp) = M_CTL;
22978 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
22979 		lsoi = (ip_lso_info_t *)mp->b_rptr;
22980 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
22981 		idst = &(lsoi->lso_capab);
22982 
22983 		/*
22984 		 * If the caller provides us with the capability, copy
22985 		 * it over into our notification message; otherwise
22986 		 * we zero out the capability portion.
22987 		 */
22988 		if (isrc != NULL)
22989 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22990 		else
22991 			bzero((caddr_t)idst, sizeof (*idst));
22992 	}
22993 	return (mp);
22994 }
22995 
22996 /*
22997  * Routine which determines whether LSO can be enabled on the destination
22998  * IRE and IPC combination, and if so, allocates and returns the LSO
22999  * notification mblk that may be used by ULP.  We also check if we need to
23000  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23001  * LSO usage in the past have been lifted.  This gets called during IP
23002  * and ULP binding.
23003  */
23004 mblk_t *
23005 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23006     ill_lso_capab_t *lso_cap)
23007 {
23008 	mblk_t *mp;
23009 
23010 	ASSERT(dst_ire != NULL);
23011 	ASSERT(connp != NULL);
23012 	ASSERT(lso_cap != NULL);
23013 
23014 	connp->conn_lso_ok = B_TRUE;
23015 
23016 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23017 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23018 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23019 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23020 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
23021 		connp->conn_lso_ok = B_FALSE;
23022 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23023 			/*
23024 			 * Disable LSO for this and all future connections going
23025 			 * over the interface.
23026 			 */
23027 			lso_cap->ill_lso_on = 0;
23028 		}
23029 	}
23030 
23031 	if (!connp->conn_lso_ok)
23032 		return (NULL);
23033 	else if (!lso_cap->ill_lso_on) {
23034 		/*
23035 		 * If LSO has been previously turned off in the past, and we
23036 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23037 		 * then enable it for this interface.
23038 		 */
23039 		lso_cap->ill_lso_on = 1;
23040 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23041 		    ill_name));
23042 	}
23043 
23044 	/* Allocate the LSO info mblk */
23045 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23046 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23047 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23048 
23049 	return (mp);
23050 }
23051 
23052 /*
23053  * Create destination address attribute, and fill it with the physical
23054  * destination address and SAP taken from the template DL_UNITDATA_REQ
23055  * message block.
23056  */
23057 boolean_t
23058 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23059 {
23060 	dl_unitdata_req_t *dlurp;
23061 	pattr_t *pa;
23062 	pattrinfo_t pa_info;
23063 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23064 	uint_t das_len, das_off;
23065 
23066 	ASSERT(dlmp != NULL);
23067 
23068 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23069 	das_len = dlurp->dl_dest_addr_length;
23070 	das_off = dlurp->dl_dest_addr_offset;
23071 
23072 	pa_info.type = PATTR_DSTADDRSAP;
23073 	pa_info.len = sizeof (**das) + das_len - 1;
23074 
23075 	/* create and associate the attribute */
23076 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23077 	if (pa != NULL) {
23078 		ASSERT(*das != NULL);
23079 		(*das)->addr_is_group = 0;
23080 		(*das)->addr_len = (uint8_t)das_len;
23081 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23082 	}
23083 
23084 	return (pa != NULL);
23085 }
23086 
23087 /*
23088  * Create hardware checksum attribute and fill it with the values passed.
23089  */
23090 boolean_t
23091 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23092     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23093 {
23094 	pattr_t *pa;
23095 	pattrinfo_t pa_info;
23096 
23097 	ASSERT(mmd != NULL);
23098 
23099 	pa_info.type = PATTR_HCKSUM;
23100 	pa_info.len = sizeof (pattr_hcksum_t);
23101 
23102 	/* create and associate the attribute */
23103 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23104 	if (pa != NULL) {
23105 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23106 
23107 		hck->hcksum_start_offset = start_offset;
23108 		hck->hcksum_stuff_offset = stuff_offset;
23109 		hck->hcksum_end_offset = end_offset;
23110 		hck->hcksum_flags = flags;
23111 	}
23112 	return (pa != NULL);
23113 }
23114 
23115 /*
23116  * Create zerocopy attribute and fill it with the specified flags
23117  */
23118 boolean_t
23119 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23120 {
23121 	pattr_t *pa;
23122 	pattrinfo_t pa_info;
23123 
23124 	ASSERT(mmd != NULL);
23125 	pa_info.type = PATTR_ZCOPY;
23126 	pa_info.len = sizeof (pattr_zcopy_t);
23127 
23128 	/* create and associate the attribute */
23129 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23130 	if (pa != NULL) {
23131 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23132 
23133 		zcopy->zcopy_flags = flags;
23134 	}
23135 	return (pa != NULL);
23136 }
23137 
23138 /*
23139  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23140  * block chain. We could rewrite to handle arbitrary message block chains but
23141  * that would make the code complicated and slow. Right now there three
23142  * restrictions:
23143  *
23144  *   1. The first message block must contain the complete IP header and
23145  *	at least 1 byte of payload data.
23146  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23147  *	so that we can use a single Multidata message.
23148  *   3. No frag must be distributed over two or more message blocks so
23149  *	that we don't need more than two packet descriptors per frag.
23150  *
23151  * The above restrictions allow us to support userland applications (which
23152  * will send down a single message block) and NFS over UDP (which will
23153  * send down a chain of at most three message blocks).
23154  *
23155  * We also don't use MDT for payloads with less than or equal to
23156  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23157  */
23158 boolean_t
23159 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23160 {
23161 	int	blocks;
23162 	ssize_t	total, missing, size;
23163 
23164 	ASSERT(mp != NULL);
23165 	ASSERT(hdr_len > 0);
23166 
23167 	size = MBLKL(mp) - hdr_len;
23168 	if (size <= 0)
23169 		return (B_FALSE);
23170 
23171 	/* The first mblk contains the header and some payload. */
23172 	blocks = 1;
23173 	total = size;
23174 	size %= len;
23175 	missing = (size == 0) ? 0 : (len - size);
23176 	mp = mp->b_cont;
23177 
23178 	while (mp != NULL) {
23179 		/*
23180 		 * Give up if we encounter a zero length message block.
23181 		 * In practice, this should rarely happen and therefore
23182 		 * not worth the trouble of freeing and re-linking the
23183 		 * mblk from the chain to handle such case.
23184 		 */
23185 		if ((size = MBLKL(mp)) == 0)
23186 			return (B_FALSE);
23187 
23188 		/* Too many payload buffers for a single Multidata message? */
23189 		if (++blocks > MULTIDATA_MAX_PBUFS)
23190 			return (B_FALSE);
23191 
23192 		total += size;
23193 		/* Is a frag distributed over two or more message blocks? */
23194 		if (missing > size)
23195 			return (B_FALSE);
23196 		size -= missing;
23197 
23198 		size %= len;
23199 		missing = (size == 0) ? 0 : (len - size);
23200 
23201 		mp = mp->b_cont;
23202 	}
23203 
23204 	return (total > ip_wput_frag_mdt_min);
23205 }
23206 
23207 /*
23208  * Outbound IPv4 fragmentation routine using MDT.
23209  */
23210 static void
23211 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23212     uint32_t frag_flag, int offset)
23213 {
23214 	ipha_t		*ipha_orig;
23215 	int		i1, ip_data_end;
23216 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23217 	mblk_t		*hdr_mp, *md_mp = NULL;
23218 	unsigned char	*hdr_ptr, *pld_ptr;
23219 	multidata_t	*mmd;
23220 	ip_pdescinfo_t	pdi;
23221 
23222 	ASSERT(DB_TYPE(mp) == M_DATA);
23223 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23224 
23225 	ipha_orig = (ipha_t *)mp->b_rptr;
23226 	mp->b_rptr += sizeof (ipha_t);
23227 
23228 	/* Calculate how many packets we will send out */
23229 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23230 	pkts = (i1 + len - 1) / len;
23231 	ASSERT(pkts > 1);
23232 
23233 	/* Allocate a message block which will hold all the IP Headers. */
23234 	wroff = ip_wroff_extra;
23235 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23236 
23237 	i1 = pkts * hdr_chunk_len;
23238 	/*
23239 	 * Create the header buffer, Multidata and destination address
23240 	 * and SAP attribute that should be associated with it.
23241 	 */
23242 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23243 	    ((hdr_mp->b_wptr += i1),
23244 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23245 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23246 		freemsg(mp);
23247 		if (md_mp == NULL) {
23248 			freemsg(hdr_mp);
23249 		} else {
23250 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23251 			freemsg(md_mp);
23252 		}
23253 		IP_STAT(ip_frag_mdt_allocfail);
23254 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23255 		return;
23256 	}
23257 	IP_STAT(ip_frag_mdt_allocd);
23258 
23259 	/*
23260 	 * Add a payload buffer to the Multidata; this operation must not
23261 	 * fail, or otherwise our logic in this routine is broken.  There
23262 	 * is no memory allocation done by the routine, so any returned
23263 	 * failure simply tells us that we've done something wrong.
23264 	 *
23265 	 * A failure tells us that either we're adding the same payload
23266 	 * buffer more than once, or we're trying to add more buffers than
23267 	 * allowed.  None of the above cases should happen, and we panic
23268 	 * because either there's horrible heap corruption, and/or
23269 	 * programming mistake.
23270 	 */
23271 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23272 		goto pbuf_panic;
23273 
23274 	hdr_ptr = hdr_mp->b_rptr;
23275 	pld_ptr = mp->b_rptr;
23276 
23277 	/* Establish the ending byte offset, based on the starting offset. */
23278 	offset <<= 3;
23279 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23280 	    IP_SIMPLE_HDR_LENGTH;
23281 
23282 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23283 
23284 	while (pld_ptr < mp->b_wptr) {
23285 		ipha_t		*ipha;
23286 		uint16_t	offset_and_flags;
23287 		uint16_t	ip_len;
23288 		int		error;
23289 
23290 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23291 		ipha = (ipha_t *)(hdr_ptr + wroff);
23292 		ASSERT(OK_32PTR(ipha));
23293 		*ipha = *ipha_orig;
23294 
23295 		if (ip_data_end - offset > len) {
23296 			offset_and_flags = IPH_MF;
23297 		} else {
23298 			/*
23299 			 * Last frag. Set len to the length of this last piece.
23300 			 */
23301 			len = ip_data_end - offset;
23302 			/* A frag of a frag might have IPH_MF non-zero */
23303 			offset_and_flags =
23304 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23305 			    IPH_MF;
23306 		}
23307 		offset_and_flags |= (uint16_t)(offset >> 3);
23308 		offset_and_flags |= (uint16_t)frag_flag;
23309 		/* Store the offset and flags in the IP header. */
23310 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23311 
23312 		/* Store the length in the IP header. */
23313 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23314 		ipha->ipha_length = htons(ip_len);
23315 
23316 		/*
23317 		 * Set the IP header checksum.  Note that mp is just
23318 		 * the header, so this is easy to pass to ip_csum.
23319 		 */
23320 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23321 
23322 		/*
23323 		 * Record offset and size of header and data of the next packet
23324 		 * in the multidata message.
23325 		 */
23326 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23327 		PDESC_PLD_INIT(&pdi);
23328 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23329 		ASSERT(i1 > 0);
23330 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23331 		if (i1 == len) {
23332 			pld_ptr += len;
23333 		} else {
23334 			i1 = len - i1;
23335 			mp = mp->b_cont;
23336 			ASSERT(mp != NULL);
23337 			ASSERT(MBLKL(mp) >= i1);
23338 			/*
23339 			 * Attach the next payload message block to the
23340 			 * multidata message.
23341 			 */
23342 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23343 				goto pbuf_panic;
23344 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23345 			pld_ptr = mp->b_rptr + i1;
23346 		}
23347 
23348 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23349 		    KM_NOSLEEP)) == NULL) {
23350 			/*
23351 			 * Any failure other than ENOMEM indicates that we
23352 			 * have passed in invalid pdesc info or parameters
23353 			 * to mmd_addpdesc, which must not happen.
23354 			 *
23355 			 * EINVAL is a result of failure on boundary checks
23356 			 * against the pdesc info contents.  It should not
23357 			 * happen, and we panic because either there's
23358 			 * horrible heap corruption, and/or programming
23359 			 * mistake.
23360 			 */
23361 			if (error != ENOMEM) {
23362 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23363 				    "pdesc logic error detected for "
23364 				    "mmd %p pinfo %p (%d)\n",
23365 				    (void *)mmd, (void *)&pdi, error);
23366 				/* NOTREACHED */
23367 			}
23368 			IP_STAT(ip_frag_mdt_addpdescfail);
23369 			/* Free unattached payload message blocks as well */
23370 			md_mp->b_cont = mp->b_cont;
23371 			goto free_mmd;
23372 		}
23373 
23374 		/* Advance fragment offset. */
23375 		offset += len;
23376 
23377 		/* Advance to location for next header in the buffer. */
23378 		hdr_ptr += hdr_chunk_len;
23379 
23380 		/* Did we reach the next payload message block? */
23381 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23382 			mp = mp->b_cont;
23383 			/*
23384 			 * Attach the next message block with payload
23385 			 * data to the multidata message.
23386 			 */
23387 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23388 				goto pbuf_panic;
23389 			pld_ptr = mp->b_rptr;
23390 		}
23391 	}
23392 
23393 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23394 	ASSERT(mp->b_wptr == pld_ptr);
23395 
23396 	/* Update IP statistics */
23397 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23398 	BUMP_MIB(&ip_mib, ipFragOKs);
23399 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23400 
23401 	if (pkt_type == OB_PKT) {
23402 		ire->ire_ob_pkt_count += pkts;
23403 		if (ire->ire_ipif != NULL)
23404 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23405 	} else {
23406 		/*
23407 		 * The type is IB_PKT in the forwarding path and in
23408 		 * the mobile IP case when the packet is being reverse-
23409 		 * tunneled to the home agent.
23410 		 */
23411 		ire->ire_ib_pkt_count += pkts;
23412 		ASSERT(!IRE_IS_LOCAL(ire));
23413 		if (ire->ire_type & IRE_BROADCAST)
23414 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23415 		else
23416 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23417 	}
23418 	ire->ire_last_used_time = lbolt;
23419 	/* Send it down */
23420 	putnext(ire->ire_stq, md_mp);
23421 	return;
23422 
23423 pbuf_panic:
23424 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23425 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23426 	    pbuf_idx);
23427 	/* NOTREACHED */
23428 }
23429 
23430 /*
23431  * Outbound IP fragmentation routine.
23432  *
23433  * NOTE : This routine does not ire_refrele the ire that is passed in
23434  * as the argument.
23435  */
23436 static void
23437 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23438     uint32_t frag_flag, zoneid_t zoneid)
23439 {
23440 	int		i1;
23441 	mblk_t		*ll_hdr_mp;
23442 	int 		ll_hdr_len;
23443 	int		hdr_len;
23444 	mblk_t		*hdr_mp;
23445 	ipha_t		*ipha;
23446 	int		ip_data_end;
23447 	int		len;
23448 	mblk_t		*mp = mp_orig, *mp1;
23449 	int		offset;
23450 	queue_t		*q;
23451 	uint32_t	v_hlen_tos_len;
23452 	mblk_t		*first_mp;
23453 	boolean_t	mctl_present;
23454 	ill_t		*ill;
23455 	ill_t		*out_ill;
23456 	mblk_t		*xmit_mp;
23457 	mblk_t		*carve_mp;
23458 	ire_t		*ire1 = NULL;
23459 	ire_t		*save_ire = NULL;
23460 	mblk_t  	*next_mp = NULL;
23461 	boolean_t	last_frag = B_FALSE;
23462 	boolean_t	multirt_send = B_FALSE;
23463 	ire_t		*first_ire = NULL;
23464 	irb_t		*irb = NULL;
23465 
23466 	/*
23467 	 * IPSEC does not allow hw accelerated packets to be fragmented
23468 	 * This check is made in ip_wput_ipsec_out prior to coming here
23469 	 * via ip_wput_ire_fragmentit.
23470 	 *
23471 	 * If at this point we have an ire whose ARP request has not
23472 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23473 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23474 	 * This packet and all fragmentable packets for this ire will
23475 	 * continue to get dropped while ire_nce->nce_state remains in
23476 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23477 	 * ND_REACHABLE, all subsquent large packets for this ire will
23478 	 * get fragemented and sent out by this function.
23479 	 */
23480 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23481 		/* If nce_state is ND_INITIAL, trigger ARP query */
23482 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23483 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23484 		    " -  dropping packet\n"));
23485 		BUMP_MIB(&ip_mib, ipFragFails);
23486 		freemsg(mp);
23487 		return;
23488 	}
23489 
23490 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23491 	    "ip_wput_frag_start:");
23492 
23493 	if (mp->b_datap->db_type == M_CTL) {
23494 		first_mp = mp;
23495 		mp_orig = mp = mp->b_cont;
23496 		mctl_present = B_TRUE;
23497 	} else {
23498 		first_mp = mp;
23499 		mctl_present = B_FALSE;
23500 	}
23501 
23502 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23503 	ipha = (ipha_t *)mp->b_rptr;
23504 
23505 	/*
23506 	 * If the Don't Fragment flag is on, generate an ICMP destination
23507 	 * unreachable, fragmentation needed.
23508 	 */
23509 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23510 	if (offset & IPH_DF) {
23511 		BUMP_MIB(&ip_mib, ipFragFails);
23512 		/*
23513 		 * Need to compute hdr checksum if called from ip_wput_ire.
23514 		 * Note that ip_rput_forward verifies the checksum before
23515 		 * calling this routine so in that case this is a noop.
23516 		 */
23517 		ipha->ipha_hdr_checksum = 0;
23518 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23519 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23520 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23521 		    "ip_wput_frag_end:(%S)",
23522 		    "don't fragment");
23523 		return;
23524 	}
23525 	if (mctl_present)
23526 		freeb(first_mp);
23527 	/*
23528 	 * Establish the starting offset.  May not be zero if we are fragging
23529 	 * a fragment that is being forwarded.
23530 	 */
23531 	offset = offset & IPH_OFFSET;
23532 
23533 	/* TODO why is this test needed? */
23534 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23535 	if (((max_frag - LENGTH) & ~7) < 8) {
23536 		/* TODO: notify ulp somehow */
23537 		BUMP_MIB(&ip_mib, ipFragFails);
23538 		freemsg(mp);
23539 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23540 		    "ip_wput_frag_end:(%S)",
23541 		    "len < 8");
23542 		return;
23543 	}
23544 
23545 	hdr_len = (V_HLEN & 0xF) << 2;
23546 
23547 	ipha->ipha_hdr_checksum = 0;
23548 
23549 	/*
23550 	 * Establish the number of bytes maximum per frag, after putting
23551 	 * in the header.
23552 	 */
23553 	len = (max_frag - hdr_len) & ~7;
23554 
23555 	/* Check if we can use MDT to send out the frags. */
23556 	ASSERT(!IRE_IS_LOCAL(ire));
23557 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23558 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23559 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23560 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23561 		ASSERT(ill->ill_mdt_capab != NULL);
23562 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23563 			/*
23564 			 * If MDT has been previously turned off in the past,
23565 			 * and we currently can do MDT (due to IPQoS policy
23566 			 * removal, etc.) then enable it for this interface.
23567 			 */
23568 			ill->ill_mdt_capab->ill_mdt_on = 1;
23569 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23570 			    ill->ill_name));
23571 		}
23572 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23573 		    offset);
23574 		return;
23575 	}
23576 
23577 	/* Get a copy of the header for the trailing frags */
23578 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23579 	if (!hdr_mp) {
23580 		BUMP_MIB(&ip_mib, ipOutDiscards);
23581 		freemsg(mp);
23582 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23583 		    "ip_wput_frag_end:(%S)",
23584 		    "couldn't copy hdr");
23585 		return;
23586 	}
23587 	if (DB_CRED(mp) != NULL)
23588 		mblk_setcred(hdr_mp, DB_CRED(mp));
23589 
23590 	/* Store the starting offset, with the MoreFrags flag. */
23591 	i1 = offset | IPH_MF | frag_flag;
23592 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23593 
23594 	/* Establish the ending byte offset, based on the starting offset. */
23595 	offset <<= 3;
23596 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23597 
23598 	/* Store the length of the first fragment in the IP header. */
23599 	i1 = len + hdr_len;
23600 	ASSERT(i1 <= IP_MAXPACKET);
23601 	ipha->ipha_length = htons((uint16_t)i1);
23602 
23603 	/*
23604 	 * Compute the IP header checksum for the first frag.  We have to
23605 	 * watch out that we stop at the end of the header.
23606 	 */
23607 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23608 
23609 	/*
23610 	 * Now carve off the first frag.  Note that this will include the
23611 	 * original IP header.
23612 	 */
23613 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23614 		BUMP_MIB(&ip_mib, ipOutDiscards);
23615 		freeb(hdr_mp);
23616 		freemsg(mp_orig);
23617 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23618 		    "ip_wput_frag_end:(%S)",
23619 		    "couldn't carve first");
23620 		return;
23621 	}
23622 
23623 	/*
23624 	 * Multirouting case. Each fragment is replicated
23625 	 * via all non-condemned RTF_MULTIRT routes
23626 	 * currently resolved.
23627 	 * We ensure that first_ire is the first RTF_MULTIRT
23628 	 * ire in the bucket.
23629 	 */
23630 	if (ire->ire_flags & RTF_MULTIRT) {
23631 		irb = ire->ire_bucket;
23632 		ASSERT(irb != NULL);
23633 
23634 		multirt_send = B_TRUE;
23635 
23636 		/* Make sure we do not omit any multiroute ire. */
23637 		IRB_REFHOLD(irb);
23638 		for (first_ire = irb->irb_ire;
23639 		    first_ire != NULL;
23640 		    first_ire = first_ire->ire_next) {
23641 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23642 			    (first_ire->ire_addr == ire->ire_addr) &&
23643 			    !(first_ire->ire_marks &
23644 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23645 				break;
23646 		}
23647 
23648 		if (first_ire != NULL) {
23649 			if (first_ire != ire) {
23650 				IRE_REFHOLD(first_ire);
23651 				/*
23652 				 * Do not release the ire passed in
23653 				 * as the argument.
23654 				 */
23655 				ire = first_ire;
23656 			} else {
23657 				first_ire = NULL;
23658 			}
23659 		}
23660 		IRB_REFRELE(irb);
23661 
23662 		/*
23663 		 * Save the first ire; we will need to restore it
23664 		 * for the trailing frags.
23665 		 * We REFHOLD save_ire, as each iterated ire will be
23666 		 * REFRELEd.
23667 		 */
23668 		save_ire = ire;
23669 		IRE_REFHOLD(save_ire);
23670 	}
23671 
23672 	/*
23673 	 * First fragment emission loop.
23674 	 * In most cases, the emission loop below is entered only
23675 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23676 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23677 	 * bucket, and send the fragment through all crossed
23678 	 * RTF_MULTIRT routes.
23679 	 */
23680 	do {
23681 		if (ire->ire_flags & RTF_MULTIRT) {
23682 			/*
23683 			 * We are in a multiple send case, need to get
23684 			 * the next ire and make a copy of the packet.
23685 			 * ire1 holds here the next ire to process in the
23686 			 * bucket. If multirouting is expected,
23687 			 * any non-RTF_MULTIRT ire that has the
23688 			 * right destination address is ignored.
23689 			 *
23690 			 * We have to take into account the MTU of
23691 			 * each walked ire. max_frag is set by the
23692 			 * the caller and generally refers to
23693 			 * the primary ire entry. Here we ensure that
23694 			 * no route with a lower MTU will be used, as
23695 			 * fragments are carved once for all ires,
23696 			 * then replicated.
23697 			 */
23698 			ASSERT(irb != NULL);
23699 			IRB_REFHOLD(irb);
23700 			for (ire1 = ire->ire_next;
23701 			    ire1 != NULL;
23702 			    ire1 = ire1->ire_next) {
23703 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23704 					continue;
23705 				if (ire1->ire_addr != ire->ire_addr)
23706 					continue;
23707 				if (ire1->ire_marks &
23708 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23709 					continue;
23710 				/*
23711 				 * Ensure we do not exceed the MTU
23712 				 * of the next route.
23713 				 */
23714 				if (ire1->ire_max_frag < max_frag) {
23715 					ip_multirt_bad_mtu(ire1, max_frag);
23716 					continue;
23717 				}
23718 
23719 				/* Got one. */
23720 				IRE_REFHOLD(ire1);
23721 				break;
23722 			}
23723 			IRB_REFRELE(irb);
23724 
23725 			if (ire1 != NULL) {
23726 				next_mp = copyb(mp);
23727 				if ((next_mp == NULL) ||
23728 				    ((mp->b_cont != NULL) &&
23729 				    ((next_mp->b_cont =
23730 				    dupmsg(mp->b_cont)) == NULL))) {
23731 					freemsg(next_mp);
23732 					next_mp = NULL;
23733 					ire_refrele(ire1);
23734 					ire1 = NULL;
23735 				}
23736 			}
23737 
23738 			/* Last multiroute ire; don't loop anymore. */
23739 			if (ire1 == NULL) {
23740 				multirt_send = B_FALSE;
23741 			}
23742 		}
23743 
23744 		ll_hdr_len = 0;
23745 		LOCK_IRE_FP_MP(ire);
23746 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23747 		if (ll_hdr_mp != NULL) {
23748 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23749 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23750 		} else {
23751 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23752 		}
23753 
23754 		/* If there is a transmit header, get a copy for this frag. */
23755 		/*
23756 		 * TODO: should check db_ref before calling ip_carve_mp since
23757 		 * it might give us a dup.
23758 		 */
23759 		if (!ll_hdr_mp) {
23760 			/* No xmit header. */
23761 			xmit_mp = mp;
23762 
23763 		/* We have a link-layer header that can fit in our mblk. */
23764 		} else if (mp->b_datap->db_ref == 1 &&
23765 		    ll_hdr_len != 0 &&
23766 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23767 			/* M_DATA fastpath */
23768 			mp->b_rptr -= ll_hdr_len;
23769 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23770 			xmit_mp = mp;
23771 
23772 		/* Corner case if copyb has failed */
23773 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23774 			UNLOCK_IRE_FP_MP(ire);
23775 			BUMP_MIB(&ip_mib, ipOutDiscards);
23776 			freeb(hdr_mp);
23777 			freemsg(mp);
23778 			freemsg(mp_orig);
23779 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23780 			    "ip_wput_frag_end:(%S)",
23781 			    "discard");
23782 
23783 			if (multirt_send) {
23784 				ASSERT(ire1);
23785 				ASSERT(next_mp);
23786 
23787 				freemsg(next_mp);
23788 				ire_refrele(ire1);
23789 			}
23790 			if (save_ire != NULL)
23791 				IRE_REFRELE(save_ire);
23792 
23793 			if (first_ire != NULL)
23794 				ire_refrele(first_ire);
23795 			return;
23796 
23797 		/*
23798 		 * Case of res_mp OR the fastpath mp can't fit
23799 		 * in the mblk
23800 		 */
23801 		} else {
23802 			xmit_mp->b_cont = mp;
23803 			if (DB_CRED(mp) != NULL)
23804 				mblk_setcred(xmit_mp, DB_CRED(mp));
23805 			/*
23806 			 * Get priority marking, if any.
23807 			 * We propagate the CoS marking from the
23808 			 * original packet that went to QoS processing
23809 			 * in ip_wput_ire to the newly carved mp.
23810 			 */
23811 			if (DB_TYPE(xmit_mp) == M_DATA)
23812 				xmit_mp->b_band = mp->b_band;
23813 		}
23814 		UNLOCK_IRE_FP_MP(ire);
23815 		q = ire->ire_stq;
23816 		BUMP_MIB(&ip_mib, ipFragCreates);
23817 
23818 		out_ill = (ill_t *)q->q_ptr;
23819 
23820 		DTRACE_PROBE4(ip4__physical__out__start,
23821 		    ill_t *, NULL, ill_t *, out_ill,
23822 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23823 
23824 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23825 		    NULL, out_ill, ipha, xmit_mp, mp);
23826 
23827 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23828 
23829 		if (xmit_mp != NULL) {
23830 			putnext(q, xmit_mp);
23831 			if (pkt_type != OB_PKT) {
23832 				/*
23833 				 * Update the packet count of trailing
23834 				 * RTF_MULTIRT ires.
23835 				 */
23836 				UPDATE_OB_PKT_COUNT(ire);
23837 			}
23838 		}
23839 
23840 		if (multirt_send) {
23841 			/*
23842 			 * We are in a multiple send case; look for
23843 			 * the next ire and re-enter the loop.
23844 			 */
23845 			ASSERT(ire1);
23846 			ASSERT(next_mp);
23847 			/* REFRELE the current ire before looping */
23848 			ire_refrele(ire);
23849 			ire = ire1;
23850 			ire1 = NULL;
23851 			mp = next_mp;
23852 			next_mp = NULL;
23853 		}
23854 	} while (multirt_send);
23855 
23856 	ASSERT(ire1 == NULL);
23857 
23858 	/* Restore the original ire; we need it for the trailing frags */
23859 	if (save_ire != NULL) {
23860 		/* REFRELE the last iterated ire */
23861 		ire_refrele(ire);
23862 		/* save_ire has been REFHOLDed */
23863 		ire = save_ire;
23864 		save_ire = NULL;
23865 		q = ire->ire_stq;
23866 	}
23867 
23868 	if (pkt_type == OB_PKT) {
23869 		UPDATE_OB_PKT_COUNT(ire);
23870 	} else {
23871 		UPDATE_IB_PKT_COUNT(ire);
23872 	}
23873 
23874 	/* Advance the offset to the second frag starting point. */
23875 	offset += len;
23876 	/*
23877 	 * Update hdr_len from the copied header - there might be less options
23878 	 * in the later fragments.
23879 	 */
23880 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23881 	/* Loop until done. */
23882 	for (;;) {
23883 		uint16_t	offset_and_flags;
23884 		uint16_t	ip_len;
23885 
23886 		if (ip_data_end - offset > len) {
23887 			/*
23888 			 * Carve off the appropriate amount from the original
23889 			 * datagram.
23890 			 */
23891 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23892 				mp = NULL;
23893 				break;
23894 			}
23895 			/*
23896 			 * More frags after this one.  Get another copy
23897 			 * of the header.
23898 			 */
23899 			if (carve_mp->b_datap->db_ref == 1 &&
23900 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23901 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23902 				/* Inline IP header */
23903 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23904 				    hdr_mp->b_rptr;
23905 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23906 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23907 				mp = carve_mp;
23908 			} else {
23909 				if (!(mp = copyb(hdr_mp))) {
23910 					freemsg(carve_mp);
23911 					break;
23912 				}
23913 				/* Get priority marking, if any. */
23914 				mp->b_band = carve_mp->b_band;
23915 				mp->b_cont = carve_mp;
23916 			}
23917 			ipha = (ipha_t *)mp->b_rptr;
23918 			offset_and_flags = IPH_MF;
23919 		} else {
23920 			/*
23921 			 * Last frag.  Consume the header. Set len to
23922 			 * the length of this last piece.
23923 			 */
23924 			len = ip_data_end - offset;
23925 
23926 			/*
23927 			 * Carve off the appropriate amount from the original
23928 			 * datagram.
23929 			 */
23930 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23931 				mp = NULL;
23932 				break;
23933 			}
23934 			if (carve_mp->b_datap->db_ref == 1 &&
23935 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23936 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23937 				/* Inline IP header */
23938 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23939 				    hdr_mp->b_rptr;
23940 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23941 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23942 				mp = carve_mp;
23943 				freeb(hdr_mp);
23944 				hdr_mp = mp;
23945 			} else {
23946 				mp = hdr_mp;
23947 				/* Get priority marking, if any. */
23948 				mp->b_band = carve_mp->b_band;
23949 				mp->b_cont = carve_mp;
23950 			}
23951 			ipha = (ipha_t *)mp->b_rptr;
23952 			/* A frag of a frag might have IPH_MF non-zero */
23953 			offset_and_flags =
23954 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23955 			    IPH_MF;
23956 		}
23957 		offset_and_flags |= (uint16_t)(offset >> 3);
23958 		offset_and_flags |= (uint16_t)frag_flag;
23959 		/* Store the offset and flags in the IP header. */
23960 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23961 
23962 		/* Store the length in the IP header. */
23963 		ip_len = (uint16_t)(len + hdr_len);
23964 		ipha->ipha_length = htons(ip_len);
23965 
23966 		/*
23967 		 * Set the IP header checksum.	Note that mp is just
23968 		 * the header, so this is easy to pass to ip_csum.
23969 		 */
23970 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23971 
23972 		/* Attach a transmit header, if any, and ship it. */
23973 		if (pkt_type == OB_PKT) {
23974 			UPDATE_OB_PKT_COUNT(ire);
23975 		} else {
23976 			UPDATE_IB_PKT_COUNT(ire);
23977 		}
23978 
23979 		if (ire->ire_flags & RTF_MULTIRT) {
23980 			irb = ire->ire_bucket;
23981 			ASSERT(irb != NULL);
23982 
23983 			multirt_send = B_TRUE;
23984 
23985 			/*
23986 			 * Save the original ire; we will need to restore it
23987 			 * for the tailing frags.
23988 			 */
23989 			save_ire = ire;
23990 			IRE_REFHOLD(save_ire);
23991 		}
23992 		/*
23993 		 * Emission loop for this fragment, similar
23994 		 * to what is done for the first fragment.
23995 		 */
23996 		do {
23997 			if (multirt_send) {
23998 				/*
23999 				 * We are in a multiple send case, need to get
24000 				 * the next ire and make a copy of the packet.
24001 				 */
24002 				ASSERT(irb != NULL);
24003 				IRB_REFHOLD(irb);
24004 				for (ire1 = ire->ire_next;
24005 				    ire1 != NULL;
24006 				    ire1 = ire1->ire_next) {
24007 					if (!(ire1->ire_flags & RTF_MULTIRT))
24008 						continue;
24009 					if (ire1->ire_addr != ire->ire_addr)
24010 						continue;
24011 					if (ire1->ire_marks &
24012 					    (IRE_MARK_CONDEMNED|
24013 						IRE_MARK_HIDDEN))
24014 						continue;
24015 					/*
24016 					 * Ensure we do not exceed the MTU
24017 					 * of the next route.
24018 					 */
24019 					if (ire1->ire_max_frag < max_frag) {
24020 						ip_multirt_bad_mtu(ire1,
24021 						    max_frag);
24022 						continue;
24023 					}
24024 
24025 					/* Got one. */
24026 					IRE_REFHOLD(ire1);
24027 					break;
24028 				}
24029 				IRB_REFRELE(irb);
24030 
24031 				if (ire1 != NULL) {
24032 					next_mp = copyb(mp);
24033 					if ((next_mp == NULL) ||
24034 					    ((mp->b_cont != NULL) &&
24035 					    ((next_mp->b_cont =
24036 					    dupmsg(mp->b_cont)) == NULL))) {
24037 						freemsg(next_mp);
24038 						next_mp = NULL;
24039 						ire_refrele(ire1);
24040 						ire1 = NULL;
24041 					}
24042 				}
24043 
24044 				/* Last multiroute ire; don't loop anymore. */
24045 				if (ire1 == NULL) {
24046 					multirt_send = B_FALSE;
24047 				}
24048 			}
24049 
24050 			/* Update transmit header */
24051 			ll_hdr_len = 0;
24052 			LOCK_IRE_FP_MP(ire);
24053 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24054 			if (ll_hdr_mp != NULL) {
24055 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24056 				ll_hdr_len = MBLKL(ll_hdr_mp);
24057 			} else {
24058 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24059 			}
24060 
24061 			if (!ll_hdr_mp) {
24062 				xmit_mp = mp;
24063 
24064 			/*
24065 			 * We have link-layer header that can fit in
24066 			 * our mblk.
24067 			 */
24068 			} else if (mp->b_datap->db_ref == 1 &&
24069 			    ll_hdr_len != 0 &&
24070 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24071 				/* M_DATA fastpath */
24072 				mp->b_rptr -= ll_hdr_len;
24073 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24074 				    ll_hdr_len);
24075 				xmit_mp = mp;
24076 
24077 			/*
24078 			 * Case of res_mp OR the fastpath mp can't fit
24079 			 * in the mblk
24080 			 */
24081 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24082 				xmit_mp->b_cont = mp;
24083 				if (DB_CRED(mp) != NULL)
24084 					mblk_setcred(xmit_mp, DB_CRED(mp));
24085 				/* Get priority marking, if any. */
24086 				if (DB_TYPE(xmit_mp) == M_DATA)
24087 					xmit_mp->b_band = mp->b_band;
24088 
24089 			/* Corner case if copyb failed */
24090 			} else {
24091 				/*
24092 				 * Exit both the replication and
24093 				 * fragmentation loops.
24094 				 */
24095 				UNLOCK_IRE_FP_MP(ire);
24096 				goto drop_pkt;
24097 			}
24098 			UNLOCK_IRE_FP_MP(ire);
24099 			BUMP_MIB(&ip_mib, ipFragCreates);
24100 
24101 			mp1 = mp;
24102 			out_ill = (ill_t *)q->q_ptr;
24103 
24104 			DTRACE_PROBE4(ip4__physical__out__start,
24105 			    ill_t *, NULL, ill_t *, out_ill,
24106 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24107 
24108 			FW_HOOKS(ip4_physical_out_event,
24109 			    ipv4firewall_physical_out,
24110 			    NULL, out_ill, ipha, xmit_mp, mp);
24111 
24112 			DTRACE_PROBE1(ip4__physical__out__end,
24113 			    mblk_t *, xmit_mp);
24114 
24115 			if (mp != mp1 && hdr_mp == mp1)
24116 				hdr_mp = mp;
24117 			if (mp != mp1 && mp_orig == mp1)
24118 				mp_orig = mp;
24119 
24120 			if (xmit_mp != NULL) {
24121 				putnext(q, xmit_mp);
24122 
24123 				if (pkt_type != OB_PKT) {
24124 					/*
24125 					 * Update the packet count of trailing
24126 					 * RTF_MULTIRT ires.
24127 					 */
24128 					UPDATE_OB_PKT_COUNT(ire);
24129 				}
24130 			}
24131 
24132 			/* All done if we just consumed the hdr_mp. */
24133 			if (mp == hdr_mp) {
24134 				last_frag = B_TRUE;
24135 			}
24136 
24137 			if (multirt_send) {
24138 				/*
24139 				 * We are in a multiple send case; look for
24140 				 * the next ire and re-enter the loop.
24141 				 */
24142 				ASSERT(ire1);
24143 				ASSERT(next_mp);
24144 				/* REFRELE the current ire before looping */
24145 				ire_refrele(ire);
24146 				ire = ire1;
24147 				ire1 = NULL;
24148 				q = ire->ire_stq;
24149 				mp = next_mp;
24150 				next_mp = NULL;
24151 			}
24152 		} while (multirt_send);
24153 		/*
24154 		 * Restore the original ire; we need it for the
24155 		 * trailing frags
24156 		 */
24157 		if (save_ire != NULL) {
24158 			ASSERT(ire1 == NULL);
24159 			/* REFRELE the last iterated ire */
24160 			ire_refrele(ire);
24161 			/* save_ire has been REFHOLDed */
24162 			ire = save_ire;
24163 			q = ire->ire_stq;
24164 			save_ire = NULL;
24165 		}
24166 
24167 		if (last_frag) {
24168 			BUMP_MIB(&ip_mib, ipFragOKs);
24169 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24170 			    "ip_wput_frag_end:(%S)",
24171 			    "consumed hdr_mp");
24172 
24173 			if (first_ire != NULL)
24174 				ire_refrele(first_ire);
24175 			return;
24176 		}
24177 		/* Otherwise, advance and loop. */
24178 		offset += len;
24179 	}
24180 
24181 drop_pkt:
24182 	/* Clean up following allocation failure. */
24183 	BUMP_MIB(&ip_mib, ipOutDiscards);
24184 	freemsg(mp);
24185 	if (mp != hdr_mp)
24186 		freeb(hdr_mp);
24187 	if (mp != mp_orig)
24188 		freemsg(mp_orig);
24189 
24190 	if (save_ire != NULL)
24191 		IRE_REFRELE(save_ire);
24192 	if (first_ire != NULL)
24193 		ire_refrele(first_ire);
24194 
24195 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24196 	    "ip_wput_frag_end:(%S)",
24197 	    "end--alloc failure");
24198 }
24199 
24200 /*
24201  * Copy the header plus those options which have the copy bit set
24202  */
24203 static mblk_t *
24204 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24205 {
24206 	mblk_t	*mp;
24207 	uchar_t	*up;
24208 
24209 	/*
24210 	 * Quick check if we need to look for options without the copy bit
24211 	 * set
24212 	 */
24213 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24214 	if (!mp)
24215 		return (mp);
24216 	mp->b_rptr += ip_wroff_extra;
24217 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24218 		bcopy(rptr, mp->b_rptr, hdr_len);
24219 		mp->b_wptr += hdr_len + ip_wroff_extra;
24220 		return (mp);
24221 	}
24222 	up  = mp->b_rptr;
24223 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24224 	up += IP_SIMPLE_HDR_LENGTH;
24225 	rptr += IP_SIMPLE_HDR_LENGTH;
24226 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24227 	while (hdr_len > 0) {
24228 		uint32_t optval;
24229 		uint32_t optlen;
24230 
24231 		optval = *rptr;
24232 		if (optval == IPOPT_EOL)
24233 			break;
24234 		if (optval == IPOPT_NOP)
24235 			optlen = 1;
24236 		else
24237 			optlen = rptr[1];
24238 		if (optval & IPOPT_COPY) {
24239 			bcopy(rptr, up, optlen);
24240 			up += optlen;
24241 		}
24242 		rptr += optlen;
24243 		hdr_len -= optlen;
24244 	}
24245 	/*
24246 	 * Make sure that we drop an even number of words by filling
24247 	 * with EOL to the next word boundary.
24248 	 */
24249 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24250 	    hdr_len & 0x3; hdr_len++)
24251 		*up++ = IPOPT_EOL;
24252 	mp->b_wptr = up;
24253 	/* Update header length */
24254 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24255 	return (mp);
24256 }
24257 
24258 /*
24259  * Delivery to local recipients including fanout to multiple recipients.
24260  * Does not do checksumming of UDP/TCP.
24261  * Note: q should be the read side queue for either the ill or conn.
24262  * Note: rq should be the read side q for the lower (ill) stream.
24263  * We don't send packets to IPPF processing, thus the last argument
24264  * to all the fanout calls are B_FALSE.
24265  */
24266 void
24267 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24268     int fanout_flags, zoneid_t zoneid)
24269 {
24270 	uint32_t	protocol;
24271 	mblk_t		*first_mp;
24272 	boolean_t	mctl_present;
24273 	int		ire_type;
24274 #define	rptr	((uchar_t *)ipha)
24275 
24276 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24277 	    "ip_wput_local_start: q %p", q);
24278 
24279 	if (ire != NULL) {
24280 		ire_type = ire->ire_type;
24281 	} else {
24282 		/*
24283 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24284 		 * packet is not multicast, we can't tell the ire type.
24285 		 */
24286 		ASSERT(CLASSD(ipha->ipha_dst));
24287 		ire_type = IRE_BROADCAST;
24288 	}
24289 
24290 	first_mp = mp;
24291 	if (first_mp->b_datap->db_type == M_CTL) {
24292 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24293 		if (!io->ipsec_out_secure) {
24294 			/*
24295 			 * This ipsec_out_t was allocated in ip_wput
24296 			 * for multicast packets to store the ill_index.
24297 			 * As this is being delivered locally, we don't
24298 			 * need this anymore.
24299 			 */
24300 			mp = first_mp->b_cont;
24301 			freeb(first_mp);
24302 			first_mp = mp;
24303 			mctl_present = B_FALSE;
24304 		} else {
24305 			/*
24306 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24307 			 * security properties for the looped-back packet.
24308 			 */
24309 			mctl_present = B_TRUE;
24310 			mp = first_mp->b_cont;
24311 			ASSERT(mp != NULL);
24312 			ipsec_out_to_in(first_mp);
24313 		}
24314 	} else {
24315 		mctl_present = B_FALSE;
24316 	}
24317 
24318 	DTRACE_PROBE4(ip4__loopback__in__start,
24319 	    ill_t *, ill, ill_t *, NULL,
24320 	    ipha_t *, ipha, mblk_t *, first_mp);
24321 
24322 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24323 	    ill, NULL, ipha, first_mp, mp);
24324 
24325 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24326 
24327 	if (first_mp == NULL)
24328 		return;
24329 
24330 	loopback_packets++;
24331 
24332 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24333 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24334 	if (!IS_SIMPLE_IPH(ipha)) {
24335 		ip_wput_local_options(ipha);
24336 	}
24337 
24338 	protocol = ipha->ipha_protocol;
24339 	switch (protocol) {
24340 	case IPPROTO_ICMP: {
24341 		ire_t		*ire_zone;
24342 		ilm_t		*ilm;
24343 		mblk_t		*mp1;
24344 		zoneid_t	last_zoneid;
24345 
24346 		if (CLASSD(ipha->ipha_dst) &&
24347 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24348 			ASSERT(ire_type == IRE_BROADCAST);
24349 			/*
24350 			 * In the multicast case, applications may have joined
24351 			 * the group from different zones, so we need to deliver
24352 			 * the packet to each of them. Loop through the
24353 			 * multicast memberships structures (ilm) on the receive
24354 			 * ill and send a copy of the packet up each matching
24355 			 * one. However, we don't do this for multicasts sent on
24356 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24357 			 * they must stay in the sender's zone.
24358 			 *
24359 			 * ilm_add_v6() ensures that ilms in the same zone are
24360 			 * contiguous in the ill_ilm list. We use this property
24361 			 * to avoid sending duplicates needed when two
24362 			 * applications in the same zone join the same group on
24363 			 * different logical interfaces: we ignore the ilm if
24364 			 * it's zoneid is the same as the last matching one.
24365 			 * In addition, the sending of the packet for
24366 			 * ire_zoneid is delayed until all of the other ilms
24367 			 * have been exhausted.
24368 			 */
24369 			last_zoneid = -1;
24370 			ILM_WALKER_HOLD(ill);
24371 			for (ilm = ill->ill_ilm; ilm != NULL;
24372 			    ilm = ilm->ilm_next) {
24373 				if ((ilm->ilm_flags & ILM_DELETED) ||
24374 				    ipha->ipha_dst != ilm->ilm_addr ||
24375 				    ilm->ilm_zoneid == last_zoneid ||
24376 				    ilm->ilm_zoneid == zoneid ||
24377 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24378 					continue;
24379 				mp1 = ip_copymsg(first_mp);
24380 				if (mp1 == NULL)
24381 					continue;
24382 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24383 				    mctl_present, B_FALSE, ill,
24384 				    ilm->ilm_zoneid);
24385 				last_zoneid = ilm->ilm_zoneid;
24386 			}
24387 			ILM_WALKER_RELE(ill);
24388 			/*
24389 			 * Loopback case: the sending endpoint has
24390 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24391 			 * dispatch the multicast packet to the sending zone.
24392 			 */
24393 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24394 				freemsg(first_mp);
24395 				return;
24396 			}
24397 		} else if (ire_type == IRE_BROADCAST) {
24398 			/*
24399 			 * In the broadcast case, there may be many zones
24400 			 * which need a copy of the packet delivered to them.
24401 			 * There is one IRE_BROADCAST per broadcast address
24402 			 * and per zone; we walk those using a helper function.
24403 			 * In addition, the sending of the packet for zoneid is
24404 			 * delayed until all of the other ires have been
24405 			 * processed.
24406 			 */
24407 			IRB_REFHOLD(ire->ire_bucket);
24408 			ire_zone = NULL;
24409 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24410 			    ire)) != NULL) {
24411 				mp1 = ip_copymsg(first_mp);
24412 				if (mp1 == NULL)
24413 					continue;
24414 
24415 				UPDATE_IB_PKT_COUNT(ire_zone);
24416 				ire_zone->ire_last_used_time = lbolt;
24417 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24418 				    mctl_present, B_FALSE, ill,
24419 				    ire_zone->ire_zoneid);
24420 			}
24421 			IRB_REFRELE(ire->ire_bucket);
24422 		}
24423 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24424 		    0, mctl_present, B_FALSE, ill, zoneid);
24425 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24426 		    "ip_wput_local_end: q %p (%S)",
24427 		    q, "icmp");
24428 		return;
24429 	}
24430 	case IPPROTO_IGMP:
24431 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24432 			/* Bad packet - discarded by igmp_input */
24433 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24434 			    "ip_wput_local_end: q %p (%S)",
24435 			    q, "igmp_input--bad packet");
24436 			if (mctl_present)
24437 				freeb(first_mp);
24438 			return;
24439 		}
24440 		/*
24441 		 * igmp_input() may have returned the pulled up message.
24442 		 * So first_mp and ipha need to be reinitialized.
24443 		 */
24444 		ipha = (ipha_t *)mp->b_rptr;
24445 		if (mctl_present)
24446 			first_mp->b_cont = mp;
24447 		else
24448 			first_mp = mp;
24449 		/* deliver to local raw users */
24450 		break;
24451 	case IPPROTO_ENCAP:
24452 		/*
24453 		 * This case is covered by either ip_fanout_proto, or by
24454 		 * the above security processing for self-tunneled packets.
24455 		 */
24456 		break;
24457 	case IPPROTO_UDP: {
24458 		uint16_t	*up;
24459 		uint32_t	ports;
24460 
24461 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24462 		    UDP_PORTS_OFFSET);
24463 		/* Force a 'valid' checksum. */
24464 		up[3] = 0;
24465 
24466 		ports = *(uint32_t *)up;
24467 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24468 		    (ire_type == IRE_BROADCAST),
24469 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24470 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24471 		    ill, zoneid);
24472 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24473 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24474 		return;
24475 	}
24476 	case IPPROTO_TCP: {
24477 
24478 		/*
24479 		 * For TCP, discard broadcast packets.
24480 		 */
24481 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24482 			freemsg(first_mp);
24483 			BUMP_MIB(&ip_mib, ipInDiscards);
24484 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24485 			return;
24486 		}
24487 
24488 		if (mp->b_datap->db_type == M_DATA) {
24489 			/*
24490 			 * M_DATA mblk, so init mblk (chain) for no struio().
24491 			 */
24492 			mblk_t	*mp1 = mp;
24493 
24494 			do
24495 				mp1->b_datap->db_struioflag = 0;
24496 			while ((mp1 = mp1->b_cont) != NULL);
24497 		}
24498 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24499 		    <= mp->b_wptr);
24500 		ip_fanout_tcp(q, first_mp, ill, ipha,
24501 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24502 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24503 		    mctl_present, B_FALSE, zoneid);
24504 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24505 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24506 		return;
24507 	}
24508 	case IPPROTO_SCTP:
24509 	{
24510 		uint32_t	ports;
24511 
24512 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24513 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24514 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24515 		    IP_FF_IP6INFO,
24516 		    mctl_present, B_FALSE, 0, zoneid);
24517 		return;
24518 	}
24519 
24520 	default:
24521 		break;
24522 	}
24523 	/*
24524 	 * Find a client for some other protocol.  We give
24525 	 * copies to multiple clients, if more than one is
24526 	 * bound.
24527 	 */
24528 	ip_fanout_proto(q, first_mp, ill, ipha,
24529 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24530 	    mctl_present, B_FALSE, ill, zoneid);
24531 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24532 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24533 #undef	rptr
24534 }
24535 
24536 /*
24537  * Update any source route, record route, or timestamp options.
24538  * Check that we are at end of strict source route.
24539  * The options have been sanity checked by ip_wput_options().
24540  */
24541 static void
24542 ip_wput_local_options(ipha_t *ipha)
24543 {
24544 	ipoptp_t	opts;
24545 	uchar_t		*opt;
24546 	uint8_t		optval;
24547 	uint8_t		optlen;
24548 	ipaddr_t	dst;
24549 	uint32_t	ts;
24550 	ire_t		*ire;
24551 	timestruc_t	now;
24552 
24553 	ip2dbg(("ip_wput_local_options\n"));
24554 	for (optval = ipoptp_first(&opts, ipha);
24555 	    optval != IPOPT_EOL;
24556 	    optval = ipoptp_next(&opts)) {
24557 		opt = opts.ipoptp_cur;
24558 		optlen = opts.ipoptp_len;
24559 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24560 		switch (optval) {
24561 			uint32_t off;
24562 		case IPOPT_SSRR:
24563 		case IPOPT_LSRR:
24564 			off = opt[IPOPT_OFFSET];
24565 			off--;
24566 			if (optlen < IP_ADDR_LEN ||
24567 			    off > optlen - IP_ADDR_LEN) {
24568 				/* End of source route */
24569 				break;
24570 			}
24571 			/*
24572 			 * This will only happen if two consecutive entries
24573 			 * in the source route contains our address or if
24574 			 * it is a packet with a loose source route which
24575 			 * reaches us before consuming the whole source route
24576 			 */
24577 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24578 			if (optval == IPOPT_SSRR) {
24579 				return;
24580 			}
24581 			/*
24582 			 * Hack: instead of dropping the packet truncate the
24583 			 * source route to what has been used by filling the
24584 			 * rest with IPOPT_NOP.
24585 			 */
24586 			opt[IPOPT_OLEN] = (uint8_t)off;
24587 			while (off < optlen) {
24588 				opt[off++] = IPOPT_NOP;
24589 			}
24590 			break;
24591 		case IPOPT_RR:
24592 			off = opt[IPOPT_OFFSET];
24593 			off--;
24594 			if (optlen < IP_ADDR_LEN ||
24595 			    off > optlen - IP_ADDR_LEN) {
24596 				/* No more room - ignore */
24597 				ip1dbg((
24598 				    "ip_wput_forward_options: end of RR\n"));
24599 				break;
24600 			}
24601 			dst = htonl(INADDR_LOOPBACK);
24602 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24603 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24604 			break;
24605 		case IPOPT_TS:
24606 			/* Insert timestamp if there is romm */
24607 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24608 			case IPOPT_TS_TSONLY:
24609 				off = IPOPT_TS_TIMELEN;
24610 				break;
24611 			case IPOPT_TS_PRESPEC:
24612 			case IPOPT_TS_PRESPEC_RFC791:
24613 				/* Verify that the address matched */
24614 				off = opt[IPOPT_OFFSET] - 1;
24615 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24616 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24617 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24618 				if (ire == NULL) {
24619 					/* Not for us */
24620 					break;
24621 				}
24622 				ire_refrele(ire);
24623 				/* FALLTHRU */
24624 			case IPOPT_TS_TSANDADDR:
24625 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24626 				break;
24627 			default:
24628 				/*
24629 				 * ip_*put_options should have already
24630 				 * dropped this packet.
24631 				 */
24632 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24633 				    "unknown IT - bug in ip_wput_options?\n");
24634 				return;	/* Keep "lint" happy */
24635 			}
24636 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24637 				/* Increase overflow counter */
24638 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24639 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24640 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24641 				    (off << 4);
24642 				break;
24643 			}
24644 			off = opt[IPOPT_OFFSET] - 1;
24645 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24646 			case IPOPT_TS_PRESPEC:
24647 			case IPOPT_TS_PRESPEC_RFC791:
24648 			case IPOPT_TS_TSANDADDR:
24649 				dst = htonl(INADDR_LOOPBACK);
24650 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24651 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24652 				/* FALLTHRU */
24653 			case IPOPT_TS_TSONLY:
24654 				off = opt[IPOPT_OFFSET] - 1;
24655 				/* Compute # of milliseconds since midnight */
24656 				gethrestime(&now);
24657 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24658 				    now.tv_nsec / (NANOSEC / MILLISEC);
24659 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24660 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24661 				break;
24662 			}
24663 			break;
24664 		}
24665 	}
24666 }
24667 
24668 /*
24669  * Send out a multicast packet on interface ipif.
24670  * The sender does not have an conn.
24671  * Caller verifies that this isn't a PHYI_LOOPBACK.
24672  */
24673 void
24674 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24675 {
24676 	ipha_t	*ipha;
24677 	ire_t	*ire;
24678 	ipaddr_t	dst;
24679 	mblk_t		*first_mp;
24680 
24681 	/* igmp_sendpkt always allocates a ipsec_out_t */
24682 	ASSERT(mp->b_datap->db_type == M_CTL);
24683 	ASSERT(!ipif->ipif_isv6);
24684 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24685 
24686 	first_mp = mp;
24687 	mp = first_mp->b_cont;
24688 	ASSERT(mp->b_datap->db_type == M_DATA);
24689 	ipha = (ipha_t *)mp->b_rptr;
24690 
24691 	/*
24692 	 * Find an IRE which matches the destination and the outgoing
24693 	 * queue (i.e. the outgoing interface.)
24694 	 */
24695 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24696 		dst = ipif->ipif_pp_dst_addr;
24697 	else
24698 		dst = ipha->ipha_dst;
24699 	/*
24700 	 * The source address has already been initialized by the
24701 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24702 	 * be sufficient rather than MATCH_IRE_IPIF.
24703 	 *
24704 	 * This function is used for sending IGMP packets. We need
24705 	 * to make sure that we send the packet out of the interface
24706 	 * (ipif->ipif_ill) where we joined the group. This is to
24707 	 * prevent from switches doing IGMP snooping to send us multicast
24708 	 * packets for a given group on the interface we have joined.
24709 	 * If we can't find an ire, igmp_sendpkt has already initialized
24710 	 * ipsec_out_attach_if so that this will not be load spread in
24711 	 * ip_newroute_ipif.
24712 	 */
24713 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24714 	    MATCH_IRE_ILL);
24715 	if (!ire) {
24716 		/*
24717 		 * Mark this packet to make it be delivered to
24718 		 * ip_wput_ire after the new ire has been
24719 		 * created.
24720 		 */
24721 		mp->b_prev = NULL;
24722 		mp->b_next = NULL;
24723 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24724 		    zoneid);
24725 		return;
24726 	}
24727 
24728 	/*
24729 	 * Honor the RTF_SETSRC flag; this is the only case
24730 	 * where we force this addr whatever the current src addr is,
24731 	 * because this address is set by igmp_sendpkt(), and
24732 	 * cannot be specified by any user.
24733 	 */
24734 	if (ire->ire_flags & RTF_SETSRC) {
24735 		ipha->ipha_src = ire->ire_src_addr;
24736 	}
24737 
24738 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24739 }
24740 
24741 /*
24742  * NOTE : This function does not ire_refrele the ire argument passed in.
24743  *
24744  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24745  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24746  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24747  * the ire_lock to access the nce_fp_mp in this case.
24748  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24749  * prepending a fastpath message IPQoS processing must precede it, we also set
24750  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24751  * (IPQoS might have set the b_band for CoS marking).
24752  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24753  * must follow it so that IPQoS can mark the dl_priority field for CoS
24754  * marking, if needed.
24755  */
24756 static mblk_t *
24757 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24758 {
24759 	uint_t	hlen;
24760 	ipha_t *ipha;
24761 	mblk_t *mp1;
24762 	boolean_t qos_done = B_FALSE;
24763 	uchar_t	*ll_hdr;
24764 
24765 #define	rptr	((uchar_t *)ipha)
24766 
24767 	ipha = (ipha_t *)mp->b_rptr;
24768 	hlen = 0;
24769 	LOCK_IRE_FP_MP(ire);
24770 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24771 		ASSERT(DB_TYPE(mp1) == M_DATA);
24772 		/* Initiate IPPF processing */
24773 		if ((proc != 0) && IPP_ENABLED(proc)) {
24774 			UNLOCK_IRE_FP_MP(ire);
24775 			ip_process(proc, &mp, ill_index);
24776 			if (mp == NULL)
24777 				return (NULL);
24778 
24779 			ipha = (ipha_t *)mp->b_rptr;
24780 			LOCK_IRE_FP_MP(ire);
24781 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24782 				qos_done = B_TRUE;
24783 				goto no_fp_mp;
24784 			}
24785 			ASSERT(DB_TYPE(mp1) == M_DATA);
24786 		}
24787 		hlen = MBLKL(mp1);
24788 		/*
24789 		 * Check if we have enough room to prepend fastpath
24790 		 * header
24791 		 */
24792 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24793 			ll_hdr = rptr - hlen;
24794 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24795 			/*
24796 			 * Set the b_rptr to the start of the link layer
24797 			 * header
24798 			 */
24799 			mp->b_rptr = ll_hdr;
24800 			mp1 = mp;
24801 		} else {
24802 			mp1 = copyb(mp1);
24803 			if (mp1 == NULL)
24804 				goto unlock_err;
24805 			mp1->b_band = mp->b_band;
24806 			mp1->b_cont = mp;
24807 			/*
24808 			 * certain system generated traffic may not
24809 			 * have cred/label in ip header block. This
24810 			 * is true even for a labeled system. But for
24811 			 * labeled traffic, inherit the label in the
24812 			 * new header.
24813 			 */
24814 			if (DB_CRED(mp) != NULL)
24815 				mblk_setcred(mp1, DB_CRED(mp));
24816 			/*
24817 			 * XXX disable ICK_VALID and compute checksum
24818 			 * here; can happen if nce_fp_mp changes and
24819 			 * it can't be copied now due to insufficient
24820 			 * space. (unlikely, fp mp can change, but it
24821 			 * does not increase in length)
24822 			 */
24823 		}
24824 		UNLOCK_IRE_FP_MP(ire);
24825 	} else {
24826 no_fp_mp:
24827 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24828 		if (mp1 == NULL) {
24829 unlock_err:
24830 			UNLOCK_IRE_FP_MP(ire);
24831 			freemsg(mp);
24832 			return (NULL);
24833 		}
24834 		UNLOCK_IRE_FP_MP(ire);
24835 		mp1->b_cont = mp;
24836 		/*
24837 		 * certain system generated traffic may not
24838 		 * have cred/label in ip header block. This
24839 		 * is true even for a labeled system. But for
24840 		 * labeled traffic, inherit the label in the
24841 		 * new header.
24842 		 */
24843 		if (DB_CRED(mp) != NULL)
24844 			mblk_setcred(mp1, DB_CRED(mp));
24845 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24846 			ip_process(proc, &mp1, ill_index);
24847 			if (mp1 == NULL)
24848 				return (NULL);
24849 		}
24850 	}
24851 	return (mp1);
24852 #undef rptr
24853 }
24854 
24855 /*
24856  * Finish the outbound IPsec processing for an IPv6 packet. This function
24857  * is called from ipsec_out_process() if the IPsec packet was processed
24858  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24859  * asynchronously.
24860  */
24861 void
24862 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24863     ire_t *ire_arg)
24864 {
24865 	in6_addr_t *v6dstp;
24866 	ire_t *ire;
24867 	mblk_t *mp;
24868 	ip6_t *ip6h1;
24869 	uint_t	ill_index;
24870 	ipsec_out_t *io;
24871 	boolean_t attach_if, hwaccel;
24872 	uint32_t flags = IP6_NO_IPPOLICY;
24873 	int match_flags;
24874 	zoneid_t zoneid;
24875 	boolean_t ill_need_rele = B_FALSE;
24876 	boolean_t ire_need_rele = B_FALSE;
24877 
24878 	mp = ipsec_mp->b_cont;
24879 	ip6h1 = (ip6_t *)mp->b_rptr;
24880 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24881 	ill_index = io->ipsec_out_ill_index;
24882 	if (io->ipsec_out_reachable) {
24883 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24884 	}
24885 	attach_if = io->ipsec_out_attach_if;
24886 	hwaccel = io->ipsec_out_accelerated;
24887 	zoneid = io->ipsec_out_zoneid;
24888 	ASSERT(zoneid != ALL_ZONES);
24889 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24890 	/* Multicast addresses should have non-zero ill_index. */
24891 	v6dstp = &ip6h->ip6_dst;
24892 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24893 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24894 	ASSERT(!attach_if || ill_index != 0);
24895 	if (ill_index != 0) {
24896 		if (ill == NULL) {
24897 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24898 			    B_TRUE);
24899 
24900 			/* Failure case frees things for us. */
24901 			if (ill == NULL)
24902 				return;
24903 
24904 			ill_need_rele = B_TRUE;
24905 		}
24906 		/*
24907 		 * If this packet needs to go out on a particular interface
24908 		 * honor it.
24909 		 */
24910 		if (attach_if) {
24911 			match_flags = MATCH_IRE_ILL;
24912 
24913 			/*
24914 			 * Check if we need an ire that will not be
24915 			 * looked up by anybody else i.e. HIDDEN.
24916 			 */
24917 			if (ill_is_probeonly(ill)) {
24918 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24919 			}
24920 		}
24921 	}
24922 	ASSERT(mp != NULL);
24923 
24924 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24925 		boolean_t unspec_src;
24926 		ipif_t	*ipif;
24927 
24928 		/*
24929 		 * Use the ill_index to get the right ill.
24930 		 */
24931 		unspec_src = io->ipsec_out_unspec_src;
24932 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24933 		if (ipif == NULL) {
24934 			if (ill_need_rele)
24935 				ill_refrele(ill);
24936 			freemsg(ipsec_mp);
24937 			return;
24938 		}
24939 
24940 		if (ire_arg != NULL) {
24941 			ire = ire_arg;
24942 		} else {
24943 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24944 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24945 			ire_need_rele = B_TRUE;
24946 		}
24947 		if (ire != NULL) {
24948 			ipif_refrele(ipif);
24949 			/*
24950 			 * XXX Do the multicast forwarding now, as the IPSEC
24951 			 * processing has been done.
24952 			 */
24953 			goto send;
24954 		}
24955 
24956 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24957 		mp->b_prev = NULL;
24958 		mp->b_next = NULL;
24959 
24960 		/*
24961 		 * If the IPsec packet was processed asynchronously,
24962 		 * drop it now.
24963 		 */
24964 		if (q == NULL) {
24965 			if (ill_need_rele)
24966 				ill_refrele(ill);
24967 			freemsg(ipsec_mp);
24968 			return;
24969 		}
24970 
24971 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24972 		    unspec_src, zoneid);
24973 		ipif_refrele(ipif);
24974 	} else {
24975 		if (attach_if) {
24976 			ipif_t	*ipif;
24977 
24978 			ipif = ipif_get_next_ipif(NULL, ill);
24979 			if (ipif == NULL) {
24980 				if (ill_need_rele)
24981 					ill_refrele(ill);
24982 				freemsg(ipsec_mp);
24983 				return;
24984 			}
24985 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24986 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24987 			ire_need_rele = B_TRUE;
24988 			ipif_refrele(ipif);
24989 		} else {
24990 			if (ire_arg != NULL) {
24991 				ire = ire_arg;
24992 			} else {
24993 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24994 				ire_need_rele = B_TRUE;
24995 			}
24996 		}
24997 		if (ire != NULL)
24998 			goto send;
24999 		/*
25000 		 * ire disappeared underneath.
25001 		 *
25002 		 * What we need to do here is the ip_newroute
25003 		 * logic to get the ire without doing the IPSEC
25004 		 * processing. Follow the same old path. But this
25005 		 * time, ip_wput or ire_add_then_send will call us
25006 		 * directly as all the IPSEC operations are done.
25007 		 */
25008 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25009 		mp->b_prev = NULL;
25010 		mp->b_next = NULL;
25011 
25012 		/*
25013 		 * If the IPsec packet was processed asynchronously,
25014 		 * drop it now.
25015 		 */
25016 		if (q == NULL) {
25017 			if (ill_need_rele)
25018 				ill_refrele(ill);
25019 			freemsg(ipsec_mp);
25020 			return;
25021 		}
25022 
25023 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25024 		    zoneid);
25025 	}
25026 	if (ill != NULL && ill_need_rele)
25027 		ill_refrele(ill);
25028 	return;
25029 send:
25030 	if (ill != NULL && ill_need_rele)
25031 		ill_refrele(ill);
25032 
25033 	/* Local delivery */
25034 	if (ire->ire_stq == NULL) {
25035 		ill_t	*out_ill;
25036 		ASSERT(q != NULL);
25037 
25038 		/* PFHooks: LOOPBACK_OUT */
25039 		out_ill = ire->ire_ipif->ipif_ill;
25040 
25041 		DTRACE_PROBE4(ip6__loopback__out__start,
25042 		    ill_t *, NULL, ill_t *, out_ill,
25043 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25044 
25045 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25046 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25047 
25048 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25049 
25050 		if (ipsec_mp != NULL)
25051 			ip_wput_local_v6(RD(q), out_ill,
25052 			    ip6h, ipsec_mp, ire, 0);
25053 		if (ire_need_rele)
25054 			ire_refrele(ire);
25055 		return;
25056 	}
25057 	/*
25058 	 * Everything is done. Send it out on the wire.
25059 	 * We force the insertion of a fragment header using the
25060 	 * IPH_FRAG_HDR flag in two cases:
25061 	 * - after reception of an ICMPv6 "packet too big" message
25062 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25063 	 * - for multirouted IPv6 packets, so that the receiver can
25064 	 *   discard duplicates according to their fragment identifier
25065 	 */
25066 	/* XXX fix flow control problems. */
25067 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25068 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25069 		if (hwaccel) {
25070 			/*
25071 			 * hardware acceleration does not handle these
25072 			 * "slow path" cases.
25073 			 */
25074 			/* IPsec KSTATS: should bump bean counter here. */
25075 			if (ire_need_rele)
25076 				ire_refrele(ire);
25077 			freemsg(ipsec_mp);
25078 			return;
25079 		}
25080 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25081 		    (mp->b_cont ? msgdsize(mp) :
25082 		    mp->b_wptr - (uchar_t *)ip6h)) {
25083 			/* IPsec KSTATS: should bump bean counter here. */
25084 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25085 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25086 			    msgdsize(mp)));
25087 			if (ire_need_rele)
25088 				ire_refrele(ire);
25089 			freemsg(ipsec_mp);
25090 			return;
25091 		}
25092 		ASSERT(mp->b_prev == NULL);
25093 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25094 		    ntohs(ip6h->ip6_plen) +
25095 		    IPV6_HDR_LEN, ire->ire_max_frag));
25096 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25097 		    ire->ire_max_frag);
25098 	} else {
25099 		UPDATE_OB_PKT_COUNT(ire);
25100 		ire->ire_last_used_time = lbolt;
25101 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25102 	}
25103 	if (ire_need_rele)
25104 		ire_refrele(ire);
25105 	freeb(ipsec_mp);
25106 }
25107 
25108 void
25109 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25110 {
25111 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25112 	da_ipsec_t *hada;	/* data attributes */
25113 	ill_t *ill = (ill_t *)q->q_ptr;
25114 
25115 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25116 
25117 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25118 		/* IPsec KSTATS: Bump lose counter here! */
25119 		freemsg(mp);
25120 		return;
25121 	}
25122 
25123 	/*
25124 	 * It's an IPsec packet that must be
25125 	 * accelerated by the Provider, and the
25126 	 * outbound ill is IPsec acceleration capable.
25127 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25128 	 * to the ill.
25129 	 * IPsec KSTATS: should bump packet counter here.
25130 	 */
25131 
25132 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25133 	if (hada_mp == NULL) {
25134 		/* IPsec KSTATS: should bump packet counter here. */
25135 		freemsg(mp);
25136 		return;
25137 	}
25138 
25139 	hada_mp->b_datap->db_type = M_CTL;
25140 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25141 	hada_mp->b_cont = mp;
25142 
25143 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25144 	bzero(hada, sizeof (da_ipsec_t));
25145 	hada->da_type = IPHADA_M_CTL;
25146 
25147 	putnext(q, hada_mp);
25148 }
25149 
25150 /*
25151  * Finish the outbound IPsec processing. This function is called from
25152  * ipsec_out_process() if the IPsec packet was processed
25153  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25154  * asynchronously.
25155  */
25156 void
25157 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25158     ire_t *ire_arg)
25159 {
25160 	uint32_t v_hlen_tos_len;
25161 	ipaddr_t	dst;
25162 	ipif_t	*ipif = NULL;
25163 	ire_t *ire;
25164 	ire_t *ire1 = NULL;
25165 	mblk_t *next_mp = NULL;
25166 	uint32_t max_frag;
25167 	boolean_t multirt_send = B_FALSE;
25168 	mblk_t *mp;
25169 	mblk_t *mp1;
25170 	ipha_t *ipha1;
25171 	uint_t	ill_index;
25172 	ipsec_out_t *io;
25173 	boolean_t attach_if;
25174 	int match_flags, offset;
25175 	irb_t *irb = NULL;
25176 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25177 	zoneid_t zoneid;
25178 	uint32_t cksum;
25179 	uint16_t *up;
25180 	ipxmit_state_t	pktxmit_state;
25181 #ifdef	_BIG_ENDIAN
25182 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25183 #else
25184 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25185 #endif
25186 
25187 	mp = ipsec_mp->b_cont;
25188 	ipha1 = (ipha_t *)mp->b_rptr;
25189 	ASSERT(mp != NULL);
25190 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25191 	dst = ipha->ipha_dst;
25192 
25193 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25194 	ill_index = io->ipsec_out_ill_index;
25195 	attach_if = io->ipsec_out_attach_if;
25196 	zoneid = io->ipsec_out_zoneid;
25197 	ASSERT(zoneid != ALL_ZONES);
25198 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25199 	if (ill_index != 0) {
25200 		if (ill == NULL) {
25201 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25202 			    ill_index, B_FALSE);
25203 
25204 			/* Failure case frees things for us. */
25205 			if (ill == NULL)
25206 				return;
25207 
25208 			ill_need_rele = B_TRUE;
25209 		}
25210 		/*
25211 		 * If this packet needs to go out on a particular interface
25212 		 * honor it.
25213 		 */
25214 		if (attach_if) {
25215 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25216 
25217 			/*
25218 			 * Check if we need an ire that will not be
25219 			 * looked up by anybody else i.e. HIDDEN.
25220 			 */
25221 			if (ill_is_probeonly(ill)) {
25222 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25223 			}
25224 		}
25225 	}
25226 
25227 	if (CLASSD(dst)) {
25228 		boolean_t conn_dontroute;
25229 		/*
25230 		 * Use the ill_index to get the right ipif.
25231 		 */
25232 		conn_dontroute = io->ipsec_out_dontroute;
25233 		if (ill_index == 0)
25234 			ipif = ipif_lookup_group(dst, zoneid);
25235 		else
25236 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25237 		if (ipif == NULL) {
25238 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25239 			    " multicast\n"));
25240 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25241 			freemsg(ipsec_mp);
25242 			goto done;
25243 		}
25244 		/*
25245 		 * ipha_src has already been intialized with the
25246 		 * value of the ipif in ip_wput. All we need now is
25247 		 * an ire to send this downstream.
25248 		 */
25249 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25250 		    MBLK_GETLABEL(mp), match_flags);
25251 		if (ire != NULL) {
25252 			ill_t *ill1;
25253 			/*
25254 			 * Do the multicast forwarding now, as the IPSEC
25255 			 * processing has been done.
25256 			 */
25257 			if (ip_g_mrouter && !conn_dontroute &&
25258 			    (ill1 = ire_to_ill(ire))) {
25259 				if (ip_mforward(ill1, ipha, mp)) {
25260 					freemsg(ipsec_mp);
25261 					ip1dbg(("ip_wput_ipsec_out: mforward "
25262 					    "failed\n"));
25263 					ire_refrele(ire);
25264 					goto done;
25265 				}
25266 			}
25267 			goto send;
25268 		}
25269 
25270 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25271 		mp->b_prev = NULL;
25272 		mp->b_next = NULL;
25273 
25274 		/*
25275 		 * If the IPsec packet was processed asynchronously,
25276 		 * drop it now.
25277 		 */
25278 		if (q == NULL) {
25279 			freemsg(ipsec_mp);
25280 			goto done;
25281 		}
25282 
25283 		/*
25284 		 * We may be using a wrong ipif to create the ire.
25285 		 * But it is okay as the source address is assigned
25286 		 * for the packet already. Next outbound packet would
25287 		 * create the IRE with the right IPIF in ip_wput.
25288 		 *
25289 		 * Also handle RTF_MULTIRT routes.
25290 		 */
25291 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25292 		    zoneid);
25293 	} else {
25294 		if (attach_if) {
25295 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25296 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25297 		} else {
25298 			if (ire_arg != NULL) {
25299 				ire = ire_arg;
25300 				ire_need_rele = B_FALSE;
25301 			} else {
25302 				ire = ire_cache_lookup(dst, zoneid,
25303 				    MBLK_GETLABEL(mp));
25304 			}
25305 		}
25306 		if (ire != NULL) {
25307 			goto send;
25308 		}
25309 
25310 		/*
25311 		 * ire disappeared underneath.
25312 		 *
25313 		 * What we need to do here is the ip_newroute
25314 		 * logic to get the ire without doing the IPSEC
25315 		 * processing. Follow the same old path. But this
25316 		 * time, ip_wput or ire_add_then_put will call us
25317 		 * directly as all the IPSEC operations are done.
25318 		 */
25319 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25320 		mp->b_prev = NULL;
25321 		mp->b_next = NULL;
25322 
25323 		/*
25324 		 * If the IPsec packet was processed asynchronously,
25325 		 * drop it now.
25326 		 */
25327 		if (q == NULL) {
25328 			freemsg(ipsec_mp);
25329 			goto done;
25330 		}
25331 
25332 		/*
25333 		 * Since we're going through ip_newroute() again, we
25334 		 * need to make sure we don't:
25335 		 *
25336 		 *	1.) Trigger the ASSERT() with the ipha_ident
25337 		 *	    overloading.
25338 		 *	2.) Redo transport-layer checksumming, since we've
25339 		 *	    already done all that to get this far.
25340 		 *
25341 		 * The easiest way not do either of the above is to set
25342 		 * the ipha_ident field to IP_HDR_INCLUDED.
25343 		 */
25344 		ipha->ipha_ident = IP_HDR_INCLUDED;
25345 		ip_newroute(q, ipsec_mp, dst, NULL,
25346 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25347 	}
25348 	goto done;
25349 send:
25350 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25351 		/*
25352 		 * ESP NAT-Traversal packet.
25353 		 *
25354 		 * Just do software checksum for now.
25355 		 */
25356 
25357 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25358 		IP_STAT(ip_out_sw_cksum);
25359 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25360 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25361 #define	iphs	((uint16_t *)ipha)
25362 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25363 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25364 		    IP_SIMPLE_HDR_LENGTH);
25365 #undef iphs
25366 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25367 			cksum = 0xFFFF;
25368 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25369 			if (mp1->b_wptr - mp1->b_rptr >=
25370 			    offset + sizeof (uint16_t)) {
25371 				up = (uint16_t *)(mp1->b_rptr + offset);
25372 				*up = cksum;
25373 				break;	/* out of for loop */
25374 			} else {
25375 				offset -= (mp->b_wptr - mp->b_rptr);
25376 			}
25377 	} /* Otherwise, just keep the all-zero checksum. */
25378 
25379 	if (ire->ire_stq == NULL) {
25380 		ill_t	*out_ill;
25381 		/*
25382 		 * Loopbacks go through ip_wput_local except for one case.
25383 		 * We come here if we generate a icmp_frag_needed message
25384 		 * after IPSEC processing is over. When this function calls
25385 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25386 		 * icmp_frag_needed. The message generated comes back here
25387 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25388 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25389 		 * source address as it is usually set in ip_wput_ire. As
25390 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25391 		 * and we end up here. We can't enter ip_wput_ire once the
25392 		 * IPSEC processing is over and hence we need to do it here.
25393 		 */
25394 		ASSERT(q != NULL);
25395 		UPDATE_OB_PKT_COUNT(ire);
25396 		ire->ire_last_used_time = lbolt;
25397 		if (ipha->ipha_src == 0)
25398 			ipha->ipha_src = ire->ire_src_addr;
25399 
25400 		/* PFHooks: LOOPBACK_OUT */
25401 		out_ill = ire->ire_ipif->ipif_ill;
25402 
25403 		DTRACE_PROBE4(ip4__loopback__out__start,
25404 		    ill_t *, NULL, ill_t *, out_ill,
25405 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25406 
25407 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25408 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25409 
25410 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25411 
25412 		if (ipsec_mp != NULL)
25413 			ip_wput_local(RD(q), out_ill,
25414 			    ipha, ipsec_mp, ire, 0, zoneid);
25415 		if (ire_need_rele)
25416 			ire_refrele(ire);
25417 		goto done;
25418 	}
25419 
25420 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25421 		/*
25422 		 * We are through with IPSEC processing.
25423 		 * Fragment this and send it on the wire.
25424 		 */
25425 		if (io->ipsec_out_accelerated) {
25426 			/*
25427 			 * The packet has been accelerated but must
25428 			 * be fragmented. This should not happen
25429 			 * since AH and ESP must not accelerate
25430 			 * packets that need fragmentation, however
25431 			 * the configuration could have changed
25432 			 * since the AH or ESP processing.
25433 			 * Drop packet.
25434 			 * IPsec KSTATS: bump bean counter here.
25435 			 */
25436 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25437 			    "fragmented accelerated packet!\n"));
25438 			freemsg(ipsec_mp);
25439 		} else {
25440 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25441 		}
25442 		if (ire_need_rele)
25443 			ire_refrele(ire);
25444 		goto done;
25445 	}
25446 
25447 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25448 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25449 	    (void *)ire->ire_ipif, (void *)ipif));
25450 
25451 	/*
25452 	 * Multiroute the secured packet, unless IPsec really
25453 	 * requires the packet to go out only through a particular
25454 	 * interface.
25455 	 */
25456 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25457 		ire_t *first_ire;
25458 		irb = ire->ire_bucket;
25459 		ASSERT(irb != NULL);
25460 		/*
25461 		 * This ire has been looked up as the one that
25462 		 * goes through the given ipif;
25463 		 * make sure we do not omit any other multiroute ire
25464 		 * that may be present in the bucket before this one.
25465 		 */
25466 		IRB_REFHOLD(irb);
25467 		for (first_ire = irb->irb_ire;
25468 		    first_ire != NULL;
25469 		    first_ire = first_ire->ire_next) {
25470 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25471 			    (first_ire->ire_addr == ire->ire_addr) &&
25472 			    !(first_ire->ire_marks &
25473 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25474 				break;
25475 		}
25476 
25477 		if ((first_ire != NULL) && (first_ire != ire)) {
25478 			/*
25479 			 * Don't change the ire if the packet must
25480 			 * be fragmented if sent via this new one.
25481 			 */
25482 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25483 				IRE_REFHOLD(first_ire);
25484 				if (ire_need_rele)
25485 					ire_refrele(ire);
25486 				else
25487 					ire_need_rele = B_TRUE;
25488 				ire = first_ire;
25489 			}
25490 		}
25491 		IRB_REFRELE(irb);
25492 
25493 		multirt_send = B_TRUE;
25494 		max_frag = ire->ire_max_frag;
25495 	} else {
25496 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25497 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25498 			    "flag, attach_if %d\n", attach_if));
25499 		}
25500 	}
25501 
25502 	/*
25503 	 * In most cases, the emission loop below is entered only once.
25504 	 * Only in the case where the ire holds the RTF_MULTIRT
25505 	 * flag, we loop to process all RTF_MULTIRT ires in the
25506 	 * bucket, and send the packet through all crossed
25507 	 * RTF_MULTIRT routes.
25508 	 */
25509 	do {
25510 		if (multirt_send) {
25511 			/*
25512 			 * ire1 holds here the next ire to process in the
25513 			 * bucket. If multirouting is expected,
25514 			 * any non-RTF_MULTIRT ire that has the
25515 			 * right destination address is ignored.
25516 			 */
25517 			ASSERT(irb != NULL);
25518 			IRB_REFHOLD(irb);
25519 			for (ire1 = ire->ire_next;
25520 			    ire1 != NULL;
25521 			    ire1 = ire1->ire_next) {
25522 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25523 					continue;
25524 				if (ire1->ire_addr != ire->ire_addr)
25525 					continue;
25526 				if (ire1->ire_marks &
25527 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25528 					continue;
25529 				/* No loopback here */
25530 				if (ire1->ire_stq == NULL)
25531 					continue;
25532 				/*
25533 				 * Ensure we do not exceed the MTU
25534 				 * of the next route.
25535 				 */
25536 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25537 					ip_multirt_bad_mtu(ire1, max_frag);
25538 					continue;
25539 				}
25540 
25541 				IRE_REFHOLD(ire1);
25542 				break;
25543 			}
25544 			IRB_REFRELE(irb);
25545 			if (ire1 != NULL) {
25546 				/*
25547 				 * We are in a multiple send case, need to
25548 				 * make a copy of the packet.
25549 				 */
25550 				next_mp = copymsg(ipsec_mp);
25551 				if (next_mp == NULL) {
25552 					ire_refrele(ire1);
25553 					ire1 = NULL;
25554 				}
25555 			}
25556 		}
25557 		/*
25558 		 * Everything is done. Send it out on the wire
25559 		 *
25560 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25561 		 * either send it on the wire or, in the case of
25562 		 * HW acceleration, call ipsec_hw_putnext.
25563 		 */
25564 		if (ire->ire_nce &&
25565 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25566 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25567 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25568 			/*
25569 			 * If ire's link-layer is unresolved (this
25570 			 * would only happen if the incomplete ire
25571 			 * was added to cachetable via forwarding path)
25572 			 * don't bother going to ip_xmit_v4. Just drop the
25573 			 * packet.
25574 			 * There is a slight risk here, in that, if we
25575 			 * have the forwarding path create an incomplete
25576 			 * IRE, then until the IRE is completed, any
25577 			 * transmitted IPSEC packets will be dropped
25578 			 * instead of being queued waiting for resolution.
25579 			 *
25580 			 * But the likelihood of a forwarding packet and a wput
25581 			 * packet sending to the same dst at the same time
25582 			 * and there not yet be an ARP entry for it is small.
25583 			 * Furthermore, if this actually happens, it might
25584 			 * be likely that wput would generate multiple
25585 			 * packets (and forwarding would also have a train
25586 			 * of packets) for that destination. If this is
25587 			 * the case, some of them would have been dropped
25588 			 * anyway, since ARP only queues a few packets while
25589 			 * waiting for resolution
25590 			 *
25591 			 * NOTE: We should really call ip_xmit_v4,
25592 			 * and let it queue the packet and send the
25593 			 * ARP query and have ARP come back thus:
25594 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25595 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25596 			 * hw accel work. But it's too complex to get
25597 			 * the IPsec hw  acceleration approach to fit
25598 			 * well with ip_xmit_v4 doing ARP without
25599 			 * doing IPSEC simplification. For now, we just
25600 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25601 			 * that we can continue with the send on the next
25602 			 * attempt.
25603 			 *
25604 			 * XXX THis should be revisited, when
25605 			 * the IPsec/IP interaction is cleaned up
25606 			 */
25607 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25608 			    " - dropping packet\n"));
25609 			freemsg(ipsec_mp);
25610 			/*
25611 			 * Call ip_xmit_v4() to trigger ARP query
25612 			 * in case the nce_state is ND_INITIAL
25613 			 */
25614 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25615 			goto drop_pkt;
25616 		}
25617 
25618 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25619 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25620 		    mblk_t *, mp);
25621 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25622 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25623 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25624 		if (mp == NULL)
25625 			goto drop_pkt;
25626 
25627 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25628 		pktxmit_state = ip_xmit_v4(mp, ire,
25629 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25630 
25631 		if ((pktxmit_state ==  SEND_FAILED) ||
25632 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25633 
25634 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25635 drop_pkt:
25636 			BUMP_MIB(&ip_mib, ipOutDiscards);
25637 			if (ire_need_rele)
25638 				ire_refrele(ire);
25639 			if (ire1 != NULL) {
25640 				ire_refrele(ire1);
25641 				freemsg(next_mp);
25642 			}
25643 			goto done;
25644 		}
25645 
25646 		freeb(ipsec_mp);
25647 		if (ire_need_rele)
25648 			ire_refrele(ire);
25649 
25650 		if (ire1 != NULL) {
25651 			ire = ire1;
25652 			ire_need_rele = B_TRUE;
25653 			ASSERT(next_mp);
25654 			ipsec_mp = next_mp;
25655 			mp = ipsec_mp->b_cont;
25656 			ire1 = NULL;
25657 			next_mp = NULL;
25658 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25659 		} else {
25660 			multirt_send = B_FALSE;
25661 		}
25662 	} while (multirt_send);
25663 done:
25664 	if (ill != NULL && ill_need_rele)
25665 		ill_refrele(ill);
25666 	if (ipif != NULL)
25667 		ipif_refrele(ipif);
25668 }
25669 
25670 /*
25671  * Get the ill corresponding to the specified ire, and compare its
25672  * capabilities with the protocol and algorithms specified by the
25673  * the SA obtained from ipsec_out. If they match, annotate the
25674  * ipsec_out structure to indicate that the packet needs acceleration.
25675  *
25676  *
25677  * A packet is eligible for outbound hardware acceleration if the
25678  * following conditions are satisfied:
25679  *
25680  * 1. the packet will not be fragmented
25681  * 2. the provider supports the algorithm
25682  * 3. there is no pending control message being exchanged
25683  * 4. snoop is not attached
25684  * 5. the destination address is not a broadcast or multicast address.
25685  *
25686  * Rationale:
25687  *	- Hardware drivers do not support fragmentation with
25688  *	  the current interface.
25689  *	- snoop, multicast, and broadcast may result in exposure of
25690  *	  a cleartext datagram.
25691  * We check all five of these conditions here.
25692  *
25693  * XXX would like to nuke "ire_t *" parameter here; problem is that
25694  * IRE is only way to figure out if a v4 address is a broadcast and
25695  * thus ineligible for acceleration...
25696  */
25697 static void
25698 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25699 {
25700 	ipsec_out_t *io;
25701 	mblk_t *data_mp;
25702 	uint_t plen, overhead;
25703 
25704 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25705 		return;
25706 
25707 	if (ill == NULL)
25708 		return;
25709 
25710 	/*
25711 	 * Destination address is a broadcast or multicast.  Punt.
25712 	 */
25713 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25714 	    IRE_LOCAL)))
25715 		return;
25716 
25717 	data_mp = ipsec_mp->b_cont;
25718 
25719 	if (ill->ill_isv6) {
25720 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25721 
25722 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25723 			return;
25724 
25725 		plen = ip6h->ip6_plen;
25726 	} else {
25727 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25728 
25729 		if (CLASSD(ipha->ipha_dst))
25730 			return;
25731 
25732 		plen = ipha->ipha_length;
25733 	}
25734 	/*
25735 	 * Is there a pending DLPI control message being exchanged
25736 	 * between IP/IPsec and the DLS Provider? If there is, it
25737 	 * could be a SADB update, and the state of the DLS Provider
25738 	 * SADB might not be in sync with the SADB maintained by
25739 	 * IPsec. To avoid dropping packets or using the wrong keying
25740 	 * material, we do not accelerate this packet.
25741 	 */
25742 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25743 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25744 		    "ill_dlpi_pending! don't accelerate packet\n"));
25745 		return;
25746 	}
25747 
25748 	/*
25749 	 * Is the Provider in promiscous mode? If it does, we don't
25750 	 * accelerate the packet since it will bounce back up to the
25751 	 * listeners in the clear.
25752 	 */
25753 	if (ill->ill_promisc_on_phys) {
25754 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25755 		    "ill in promiscous mode, don't accelerate packet\n"));
25756 		return;
25757 	}
25758 
25759 	/*
25760 	 * Will the packet require fragmentation?
25761 	 */
25762 
25763 	/*
25764 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25765 	 * as is used elsewhere.
25766 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25767 	 *	+ 2-byte trailer
25768 	 */
25769 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25770 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25771 
25772 	if ((plen + overhead) > ill->ill_max_mtu)
25773 		return;
25774 
25775 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25776 
25777 	/*
25778 	 * Can the ill accelerate this IPsec protocol and algorithm
25779 	 * specified by the SA?
25780 	 */
25781 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25782 	    ill->ill_isv6, sa)) {
25783 		return;
25784 	}
25785 
25786 	/*
25787 	 * Tell AH or ESP that the outbound ill is capable of
25788 	 * accelerating this packet.
25789 	 */
25790 	io->ipsec_out_is_capab_ill = B_TRUE;
25791 }
25792 
25793 /*
25794  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25795  *
25796  * If this function returns B_TRUE, the requested SA's have been filled
25797  * into the ipsec_out_*_sa pointers.
25798  *
25799  * If the function returns B_FALSE, the packet has been "consumed", most
25800  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25801  *
25802  * The SA references created by the protocol-specific "select"
25803  * function will be released when the ipsec_mp is freed, thanks to the
25804  * ipsec_out_free destructor -- see spd.c.
25805  */
25806 static boolean_t
25807 ipsec_out_select_sa(mblk_t *ipsec_mp)
25808 {
25809 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25810 	ipsec_out_t *io;
25811 	ipsec_policy_t *pp;
25812 	ipsec_action_t *ap;
25813 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25814 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25815 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25816 
25817 	if (!io->ipsec_out_secure) {
25818 		/*
25819 		 * We came here by mistake.
25820 		 * Don't bother with ipsec processing
25821 		 * We should "discourage" this path in the future.
25822 		 */
25823 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25824 		return (B_FALSE);
25825 	}
25826 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25827 	ASSERT((io->ipsec_out_policy != NULL) ||
25828 	    (io->ipsec_out_act != NULL));
25829 
25830 	ASSERT(io->ipsec_out_failed == B_FALSE);
25831 
25832 	/*
25833 	 * IPSEC processing has started.
25834 	 */
25835 	io->ipsec_out_proc_begin = B_TRUE;
25836 	ap = io->ipsec_out_act;
25837 	if (ap == NULL) {
25838 		pp = io->ipsec_out_policy;
25839 		ASSERT(pp != NULL);
25840 		ap = pp->ipsp_act;
25841 		ASSERT(ap != NULL);
25842 	}
25843 
25844 	/*
25845 	 * We have an action.  now, let's select SA's.
25846 	 * (In the future, we can cache this in the conn_t..)
25847 	 */
25848 	if (ap->ipa_want_esp) {
25849 		if (io->ipsec_out_esp_sa == NULL) {
25850 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25851 			    IPPROTO_ESP);
25852 		}
25853 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25854 	}
25855 
25856 	if (ap->ipa_want_ah) {
25857 		if (io->ipsec_out_ah_sa == NULL) {
25858 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25859 			    IPPROTO_AH);
25860 		}
25861 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25862 		/*
25863 		 * The ESP and AH processing order needs to be preserved
25864 		 * when both protocols are required (ESP should be applied
25865 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25866 		 * when both ESP and AH are required, and an AH ACQUIRE
25867 		 * is needed.
25868 		 */
25869 		if (ap->ipa_want_esp && need_ah_acquire)
25870 			need_esp_acquire = B_TRUE;
25871 	}
25872 
25873 	/*
25874 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25875 	 * Release SAs that got referenced, but will not be used until we
25876 	 * acquire _all_ of the SAs we need.
25877 	 */
25878 	if (need_ah_acquire || need_esp_acquire) {
25879 		if (io->ipsec_out_ah_sa != NULL) {
25880 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25881 			io->ipsec_out_ah_sa = NULL;
25882 		}
25883 		if (io->ipsec_out_esp_sa != NULL) {
25884 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25885 			io->ipsec_out_esp_sa = NULL;
25886 		}
25887 
25888 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25889 		return (B_FALSE);
25890 	}
25891 
25892 	return (B_TRUE);
25893 }
25894 
25895 /*
25896  * Process an IPSEC_OUT message and see what you can
25897  * do with it.
25898  * IPQoS Notes:
25899  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25900  * IPSec.
25901  * XXX would like to nuke ire_t.
25902  * XXX ill_index better be "real"
25903  */
25904 void
25905 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25906 {
25907 	ipsec_out_t *io;
25908 	ipsec_policy_t *pp;
25909 	ipsec_action_t *ap;
25910 	ipha_t *ipha;
25911 	ip6_t *ip6h;
25912 	mblk_t *mp;
25913 	ill_t *ill;
25914 	zoneid_t zoneid;
25915 	ipsec_status_t ipsec_rc;
25916 	boolean_t ill_need_rele = B_FALSE;
25917 
25918 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25919 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25920 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25921 	mp = ipsec_mp->b_cont;
25922 
25923 	/*
25924 	 * Initiate IPPF processing. We do it here to account for packets
25925 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25926 	 * We can check for ipsec_out_proc_begin even for such packets, as
25927 	 * they will always be false (asserted below).
25928 	 */
25929 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25930 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25931 		    io->ipsec_out_ill_index : ill_index);
25932 		if (mp == NULL) {
25933 			ip2dbg(("ipsec_out_process: packet dropped "\
25934 			    "during IPPF processing\n"));
25935 			freeb(ipsec_mp);
25936 			BUMP_MIB(&ip_mib, ipOutDiscards);
25937 			return;
25938 		}
25939 	}
25940 
25941 	if (!io->ipsec_out_secure) {
25942 		/*
25943 		 * We came here by mistake.
25944 		 * Don't bother with ipsec processing
25945 		 * Should "discourage" this path in the future.
25946 		 */
25947 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25948 		goto done;
25949 	}
25950 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25951 	ASSERT((io->ipsec_out_policy != NULL) ||
25952 	    (io->ipsec_out_act != NULL));
25953 	ASSERT(io->ipsec_out_failed == B_FALSE);
25954 
25955 	if (!ipsec_loaded()) {
25956 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25957 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25958 			BUMP_MIB(&ip_mib, ipOutDiscards);
25959 		} else {
25960 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25961 		}
25962 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25963 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25964 		return;
25965 	}
25966 
25967 	/*
25968 	 * IPSEC processing has started.
25969 	 */
25970 	io->ipsec_out_proc_begin = B_TRUE;
25971 	ap = io->ipsec_out_act;
25972 	if (ap == NULL) {
25973 		pp = io->ipsec_out_policy;
25974 		ASSERT(pp != NULL);
25975 		ap = pp->ipsp_act;
25976 		ASSERT(ap != NULL);
25977 	}
25978 
25979 	/*
25980 	 * Save the outbound ill index. When the packet comes back
25981 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25982 	 * before sending it the accelerated packet.
25983 	 */
25984 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25985 		int ifindex;
25986 		ill = ire_to_ill(ire);
25987 		ifindex = ill->ill_phyint->phyint_ifindex;
25988 		io->ipsec_out_capab_ill_index = ifindex;
25989 	}
25990 
25991 	/*
25992 	 * The order of processing is first insert a IP header if needed.
25993 	 * Then insert the ESP header and then the AH header.
25994 	 */
25995 	if ((io->ipsec_out_se_done == B_FALSE) &&
25996 	    (ap->ipa_want_se)) {
25997 		/*
25998 		 * First get the outer IP header before sending
25999 		 * it to ESP.
26000 		 */
26001 		ipha_t *oipha, *iipha;
26002 		mblk_t *outer_mp, *inner_mp;
26003 
26004 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26005 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26006 			    "ipsec_out_process: "
26007 			    "Self-Encapsulation failed: Out of memory\n");
26008 			freemsg(ipsec_mp);
26009 			BUMP_MIB(&ip_mib, ipOutDiscards);
26010 			return;
26011 		}
26012 		inner_mp = ipsec_mp->b_cont;
26013 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26014 		oipha = (ipha_t *)outer_mp->b_rptr;
26015 		iipha = (ipha_t *)inner_mp->b_rptr;
26016 		*oipha = *iipha;
26017 		outer_mp->b_wptr += sizeof (ipha_t);
26018 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26019 		    sizeof (ipha_t));
26020 		oipha->ipha_protocol = IPPROTO_ENCAP;
26021 		oipha->ipha_version_and_hdr_length =
26022 		    IP_SIMPLE_HDR_VERSION;
26023 		oipha->ipha_hdr_checksum = 0;
26024 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26025 		outer_mp->b_cont = inner_mp;
26026 		ipsec_mp->b_cont = outer_mp;
26027 
26028 		io->ipsec_out_se_done = B_TRUE;
26029 		io->ipsec_out_tunnel = B_TRUE;
26030 	}
26031 
26032 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26033 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26034 	    !ipsec_out_select_sa(ipsec_mp))
26035 		return;
26036 
26037 	/*
26038 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26039 	 * to do the heavy lifting.
26040 	 */
26041 	zoneid = io->ipsec_out_zoneid;
26042 	ASSERT(zoneid != ALL_ZONES);
26043 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26044 		ASSERT(io->ipsec_out_esp_sa != NULL);
26045 		io->ipsec_out_esp_done = B_TRUE;
26046 		/*
26047 		 * Note that since hw accel can only apply one transform,
26048 		 * not two, we skip hw accel for ESP if we also have AH
26049 		 * This is an design limitation of the interface
26050 		 * which should be revisited.
26051 		 */
26052 		ASSERT(ire != NULL);
26053 		if (io->ipsec_out_ah_sa == NULL) {
26054 			ill = (ill_t *)ire->ire_stq->q_ptr;
26055 			ipsec_out_is_accelerated(ipsec_mp,
26056 			    io->ipsec_out_esp_sa, ill, ire);
26057 		}
26058 
26059 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26060 		switch (ipsec_rc) {
26061 		case IPSEC_STATUS_SUCCESS:
26062 			break;
26063 		case IPSEC_STATUS_FAILED:
26064 			BUMP_MIB(&ip_mib, ipOutDiscards);
26065 			/* FALLTHRU */
26066 		case IPSEC_STATUS_PENDING:
26067 			return;
26068 		}
26069 	}
26070 
26071 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26072 		ASSERT(io->ipsec_out_ah_sa != NULL);
26073 		io->ipsec_out_ah_done = B_TRUE;
26074 		if (ire == NULL) {
26075 			int idx = io->ipsec_out_capab_ill_index;
26076 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26077 			    NULL, NULL, NULL, NULL);
26078 			ill_need_rele = B_TRUE;
26079 		} else {
26080 			ill = (ill_t *)ire->ire_stq->q_ptr;
26081 		}
26082 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26083 		    ire);
26084 
26085 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26086 		switch (ipsec_rc) {
26087 		case IPSEC_STATUS_SUCCESS:
26088 			break;
26089 		case IPSEC_STATUS_FAILED:
26090 			BUMP_MIB(&ip_mib, ipOutDiscards);
26091 			/* FALLTHRU */
26092 		case IPSEC_STATUS_PENDING:
26093 			if (ill != NULL && ill_need_rele)
26094 				ill_refrele(ill);
26095 			return;
26096 		}
26097 	}
26098 	/*
26099 	 * We are done with IPSEC processing. Send it over
26100 	 * the wire.
26101 	 */
26102 done:
26103 	mp = ipsec_mp->b_cont;
26104 	ipha = (ipha_t *)mp->b_rptr;
26105 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26106 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26107 	} else {
26108 		ip6h = (ip6_t *)ipha;
26109 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26110 	}
26111 	if (ill != NULL && ill_need_rele)
26112 		ill_refrele(ill);
26113 }
26114 
26115 /* ARGSUSED */
26116 void
26117 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26118 {
26119 	opt_restart_t	*or;
26120 	int	err;
26121 	conn_t	*connp;
26122 
26123 	ASSERT(CONN_Q(q));
26124 	connp = Q_TO_CONN(q);
26125 
26126 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26127 	or = (opt_restart_t *)first_mp->b_rptr;
26128 	/*
26129 	 * We don't need to pass any credentials here since this is just
26130 	 * a restart. The credentials are passed in when svr4_optcom_req
26131 	 * is called the first time (from ip_wput_nondata).
26132 	 */
26133 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26134 		err = svr4_optcom_req(q, first_mp, NULL,
26135 		    &ip_opt_obj);
26136 	} else {
26137 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26138 		err = tpi_optcom_req(q, first_mp, NULL,
26139 		    &ip_opt_obj);
26140 	}
26141 	if (err != EINPROGRESS) {
26142 		/* operation is done */
26143 		CONN_OPER_PENDING_DONE(connp);
26144 	}
26145 }
26146 
26147 /*
26148  * ioctls that go through a down/up sequence may need to wait for the down
26149  * to complete. This involves waiting for the ire and ipif refcnts to go down
26150  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26151  */
26152 /* ARGSUSED */
26153 void
26154 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26155 {
26156 	struct iocblk *iocp;
26157 	mblk_t *mp1;
26158 	ipif_t	*ipif;
26159 	ip_ioctl_cmd_t *ipip;
26160 	int err;
26161 	sin_t	*sin;
26162 	struct lifreq *lifr;
26163 	struct ifreq *ifr;
26164 
26165 	iocp = (struct iocblk *)mp->b_rptr;
26166 	ASSERT(ipsq != NULL);
26167 	/* Existence of mp1 verified in ip_wput_nondata */
26168 	mp1 = mp->b_cont->b_cont;
26169 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26170 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26171 		ill_t *ill;
26172 		/*
26173 		 * Special case where ipsq_current_ipif may not be set.
26174 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26175 		 * ill could also have become part of a ipmp group in the
26176 		 * process, we are here as were not able to complete the
26177 		 * operation in ipif_set_values because we could not become
26178 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26179 		 * will not be set so we need to set it.
26180 		 */
26181 		ill = (ill_t *)q->q_ptr;
26182 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26183 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26184 	}
26185 
26186 	ipif = ipsq->ipsq_current_ipif;
26187 	ASSERT(ipif != NULL);
26188 	if (ipip->ipi_cmd_type == IF_CMD) {
26189 		/* This a old style SIOC[GS]IF* command */
26190 		ifr = (struct ifreq *)mp1->b_rptr;
26191 		sin = (sin_t *)&ifr->ifr_addr;
26192 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26193 		/* This a new style SIOC[GS]LIF* command */
26194 		lifr = (struct lifreq *)mp1->b_rptr;
26195 		sin = (sin_t *)&lifr->lifr_addr;
26196 	} else {
26197 		sin = NULL;
26198 	}
26199 
26200 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26201 	    (void *)mp1->b_rptr);
26202 
26203 	/* SIOCLIFREMOVEIF could have removed the ipif */
26204 	ip_ioctl_finish(q, mp, err,
26205 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26206 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26207 }
26208 
26209 /*
26210  * ioctl processing
26211  *
26212  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26213  * the ioctl command in the ioctl tables and determines the copyin data size
26214  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26215  * size.
26216  *
26217  * ioctl processing then continues when the M_IOCDATA makes its way down.
26218  * Now the ioctl is looked up again in the ioctl table, and its properties are
26219  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26220  * and the general ioctl processing function ip_process_ioctl is called.
26221  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26222  * so goes thru the serialization primitive ipsq_try_enter. Then the
26223  * appropriate function to handle the ioctl is called based on the entry in
26224  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26225  * which also refreleases the 'conn' that was refheld at the start of the
26226  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26227  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26228  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26229  *
26230  * Many exclusive ioctls go thru an internal down up sequence as part of
26231  * the operation. For example an attempt to change the IP address of an
26232  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26233  * does all the cleanup such as deleting all ires that use this address.
26234  * Then we need to wait till all references to the interface go away.
26235  */
26236 void
26237 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26238 {
26239 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26240 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26241 	cmd_info_t ci;
26242 	int err;
26243 	boolean_t entered_ipsq = B_FALSE;
26244 
26245 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26246 
26247 	if (ipip == NULL)
26248 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26249 
26250 	/*
26251 	 * SIOCLIFADDIF needs to go thru a special path since the
26252 	 * ill may not exist yet. This happens in the case of lo0
26253 	 * which is created using this ioctl.
26254 	 */
26255 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26256 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26257 		ip_ioctl_finish(q, mp, err,
26258 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26259 		    NULL, NULL);
26260 		return;
26261 	}
26262 
26263 	ci.ci_ipif = NULL;
26264 	switch (ipip->ipi_cmd_type) {
26265 	case IF_CMD:
26266 	case LIF_CMD:
26267 		/*
26268 		 * ioctls that pass in a [l]ifreq appear here.
26269 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26270 		 * ci.ci_ipif
26271 		 */
26272 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26273 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26274 		if (err != 0) {
26275 			ip_ioctl_finish(q, mp, err,
26276 			    ipip->ipi_flags & IPI_GET_CMD ?
26277 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26278 			return;
26279 		}
26280 		ASSERT(ci.ci_ipif != NULL);
26281 		break;
26282 
26283 	case TUN_CMD:
26284 		/*
26285 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26286 		 * a refheld ipif in ci.ci_ipif
26287 		 */
26288 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26289 		if (err != 0) {
26290 			ip_ioctl_finish(q, mp, err,
26291 			    ipip->ipi_flags & IPI_GET_CMD ?
26292 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26293 			return;
26294 		}
26295 		ASSERT(ci.ci_ipif != NULL);
26296 		break;
26297 
26298 	case MISC_CMD:
26299 		/*
26300 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26301 		 * For eg. SIOCGLIFCONF will appear here.
26302 		 */
26303 		switch (ipip->ipi_cmd) {
26304 		case IF_UNITSEL:
26305 			/* ioctl comes down the ill */
26306 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26307 			ipif_refhold(ci.ci_ipif);
26308 			break;
26309 		case SIOCGMSFILTER:
26310 		case SIOCSMSFILTER:
26311 		case SIOCGIPMSFILTER:
26312 		case SIOCSIPMSFILTER:
26313 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26314 			    ip_process_ioctl);
26315 			if (err != 0) {
26316 				ip_ioctl_finish(q, mp, err,
26317 				    ipip->ipi_flags & IPI_GET_CMD ?
26318 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26319 				return;
26320 			}
26321 			break;
26322 		}
26323 		err = 0;
26324 		ci.ci_sin = NULL;
26325 		ci.ci_sin6 = NULL;
26326 		ci.ci_lifr = NULL;
26327 		break;
26328 	}
26329 
26330 	/*
26331 	 * If ipsq is non-null, we are already being called exclusively
26332 	 */
26333 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26334 	if (!(ipip->ipi_flags & IPI_WR)) {
26335 		/*
26336 		 * A return value of EINPROGRESS means the ioctl is
26337 		 * either queued and waiting for some reason or has
26338 		 * already completed.
26339 		 */
26340 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26341 		    ci.ci_lifr);
26342 		if (ci.ci_ipif != NULL)
26343 			ipif_refrele(ci.ci_ipif);
26344 		ip_ioctl_finish(q, mp, err,
26345 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26346 		    NULL, NULL);
26347 		return;
26348 	}
26349 
26350 	ASSERT(ci.ci_ipif != NULL);
26351 
26352 	if (ipsq == NULL) {
26353 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26354 		    ip_process_ioctl, NEW_OP, B_TRUE);
26355 		entered_ipsq = B_TRUE;
26356 	}
26357 	/*
26358 	 * Release the ipif so that ipif_down and friends that wait for
26359 	 * references to go away are not misled about the current ipif_refcnt
26360 	 * values. We are writer so we can access the ipif even after releasing
26361 	 * the ipif.
26362 	 */
26363 	ipif_refrele(ci.ci_ipif);
26364 	if (ipsq == NULL)
26365 		return;
26366 
26367 	mutex_enter(&ipsq->ipsq_lock);
26368 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26369 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26370 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26371 	mutex_exit(&ipsq->ipsq_lock);
26372 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26373 	/*
26374 	 * For most set ioctls that come here, this serves as a single point
26375 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26376 	 * be any new references to the ipif. This helps functions that go
26377 	 * through this path and end up trying to wait for the refcnts
26378 	 * associated with the ipif to go down to zero. Some exceptions are
26379 	 * Failover, Failback, and Groupname commands that operate on more than
26380 	 * just the ci.ci_ipif. These commands internally determine the
26381 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26382 	 * flags on that set. Another exception is the Removeif command that
26383 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26384 	 * ipif to operate on.
26385 	 */
26386 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26387 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26388 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26389 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26390 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26391 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26392 
26393 	/*
26394 	 * A return value of EINPROGRESS means the ioctl is
26395 	 * either queued and waiting for some reason or has
26396 	 * already completed.
26397 	 */
26398 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26399 	    ci.ci_lifr);
26400 
26401 	/* SIOCLIFREMOVEIF could have removed the ipif */
26402 	ip_ioctl_finish(q, mp, err,
26403 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26404 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26405 
26406 	if (entered_ipsq)
26407 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26408 }
26409 
26410 /*
26411  * Complete the ioctl. Typically ioctls use the mi package and need to
26412  * do mi_copyout/mi_copy_done.
26413  */
26414 void
26415 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26416     ipif_t *ipif, ipsq_t *ipsq)
26417 {
26418 	conn_t	*connp = NULL;
26419 	hook_nic_event_t *info;
26420 
26421 	if (err == EINPROGRESS)
26422 		return;
26423 
26424 	if (CONN_Q(q)) {
26425 		connp = Q_TO_CONN(q);
26426 		ASSERT(connp->conn_ref >= 2);
26427 	}
26428 
26429 	switch (mode) {
26430 	case COPYOUT:
26431 		if (err == 0)
26432 			mi_copyout(q, mp);
26433 		else
26434 			mi_copy_done(q, mp, err);
26435 		break;
26436 
26437 	case NO_COPYOUT:
26438 		mi_copy_done(q, mp, err);
26439 		break;
26440 
26441 	default:
26442 		/* An ioctl aborted through a conn close would take this path */
26443 		break;
26444 	}
26445 
26446 	/*
26447 	 * The refhold placed at the start of the ioctl is released here.
26448 	 */
26449 	if (connp != NULL)
26450 		CONN_OPER_PENDING_DONE(connp);
26451 
26452 	/*
26453 	 * If the ioctl were an exclusive ioctl it would have set
26454 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26455 	 */
26456 	if (ipif != NULL) {
26457 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26458 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26459 
26460 		/*
26461 		 * Unhook the nic event message from the ill and enqueue it into
26462 		 * the nic event taskq.
26463 		 */
26464 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26465 			if (ddi_taskq_dispatch(eventq_queue_nic,
26466 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26467 			    == DDI_FAILURE) {
26468 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26469 				    "failed\n"));
26470 				if (info->hne_data != NULL)
26471 					kmem_free(info->hne_data,
26472 					    info->hne_datalen);
26473 				kmem_free(info, sizeof (hook_nic_event_t));
26474 			}
26475 
26476 			ipif->ipif_ill->ill_nic_event_info = NULL;
26477 		}
26478 
26479 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26480 	}
26481 
26482 	/*
26483 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26484 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26485 	 * entering the ipsq
26486 	 */
26487 	if (ipsq != NULL) {
26488 		mutex_enter(&ipsq->ipsq_lock);
26489 		ipsq->ipsq_current_ipif = NULL;
26490 		mutex_exit(&ipsq->ipsq_lock);
26491 	}
26492 }
26493 
26494 /*
26495  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26496  */
26497 /* ARGSUSED */
26498 void
26499 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26500 {
26501 	conn_t *connp = arg;
26502 	tcp_t	*tcp;
26503 
26504 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26505 	tcp = connp->conn_tcp;
26506 
26507 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26508 		freemsg(mp);
26509 	else
26510 		tcp_rput_other(tcp, mp);
26511 	CONN_OPER_PENDING_DONE(connp);
26512 }
26513 
26514 /* Called from ip_wput for all non data messages */
26515 /* ARGSUSED */
26516 void
26517 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26518 {
26519 	mblk_t		*mp1;
26520 	ire_t		*ire, *fake_ire;
26521 	ill_t		*ill;
26522 	struct iocblk	*iocp;
26523 	ip_ioctl_cmd_t	*ipip;
26524 	cred_t		*cr;
26525 	conn_t		*connp = NULL;
26526 	int		cmd, err;
26527 	nce_t		*nce;
26528 	ipif_t		*ipif;
26529 
26530 	if (CONN_Q(q))
26531 		connp = Q_TO_CONN(q);
26532 
26533 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26534 
26535 	/* Check if it is a queue to /dev/sctp. */
26536 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26537 	    connp->conn_rq == NULL) {
26538 		sctp_wput(q, mp);
26539 		return;
26540 	}
26541 
26542 	switch (DB_TYPE(mp)) {
26543 	case M_IOCTL:
26544 		/*
26545 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26546 		 * will arrange to copy in associated control structures.
26547 		 */
26548 		ip_sioctl_copyin_setup(q, mp);
26549 		return;
26550 	case M_IOCDATA:
26551 		/*
26552 		 * Ensure that this is associated with one of our trans-
26553 		 * parent ioctls.  If it's not ours, discard it if we're
26554 		 * running as a driver, or pass it on if we're a module.
26555 		 */
26556 		iocp = (struct iocblk *)mp->b_rptr;
26557 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26558 		if (ipip == NULL) {
26559 			if (q->q_next == NULL) {
26560 				goto nak;
26561 			} else {
26562 				putnext(q, mp);
26563 			}
26564 			return;
26565 		} else if ((q->q_next != NULL) &&
26566 		    !(ipip->ipi_flags & IPI_MODOK)) {
26567 			/*
26568 			 * the ioctl is one we recognise, but is not
26569 			 * consumed by IP as a module, pass M_IOCDATA
26570 			 * for processing downstream, but only for
26571 			 * common Streams ioctls.
26572 			 */
26573 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26574 				putnext(q, mp);
26575 				return;
26576 			} else {
26577 				goto nak;
26578 			}
26579 		}
26580 
26581 		/* IOCTL continuation following copyin or copyout. */
26582 		if (mi_copy_state(q, mp, NULL) == -1) {
26583 			/*
26584 			 * The copy operation failed.  mi_copy_state already
26585 			 * cleaned up, so we're out of here.
26586 			 */
26587 			return;
26588 		}
26589 		/*
26590 		 * If we just completed a copy in, we become writer and
26591 		 * continue processing in ip_sioctl_copyin_done.  If it
26592 		 * was a copy out, we call mi_copyout again.  If there is
26593 		 * nothing more to copy out, it will complete the IOCTL.
26594 		 */
26595 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26596 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26597 				mi_copy_done(q, mp, EPROTO);
26598 				return;
26599 			}
26600 			/*
26601 			 * Check for cases that need more copying.  A return
26602 			 * value of 0 means a second copyin has been started,
26603 			 * so we return; a return value of 1 means no more
26604 			 * copying is needed, so we continue.
26605 			 */
26606 			cmd = iocp->ioc_cmd;
26607 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26608 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26609 			    MI_COPY_COUNT(mp) == 1) {
26610 				if (ip_copyin_msfilter(q, mp) == 0)
26611 					return;
26612 			}
26613 			/*
26614 			 * Refhold the conn, till the ioctl completes. This is
26615 			 * needed in case the ioctl ends up in the pending mp
26616 			 * list. Every mp in the ill_pending_mp list and
26617 			 * the ipsq_pending_mp must have a refhold on the conn
26618 			 * to resume processing. The refhold is released when
26619 			 * the ioctl completes. (normally or abnormally)
26620 			 * In all cases ip_ioctl_finish is called to finish
26621 			 * the ioctl.
26622 			 */
26623 			if (connp != NULL) {
26624 				/* This is not a reentry */
26625 				ASSERT(ipsq == NULL);
26626 				CONN_INC_REF(connp);
26627 			} else {
26628 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26629 					mi_copy_done(q, mp, EINVAL);
26630 					return;
26631 				}
26632 			}
26633 
26634 			ip_process_ioctl(ipsq, q, mp, ipip);
26635 
26636 		} else {
26637 			mi_copyout(q, mp);
26638 		}
26639 		return;
26640 nak:
26641 		iocp->ioc_error = EINVAL;
26642 		mp->b_datap->db_type = M_IOCNAK;
26643 		iocp->ioc_count = 0;
26644 		qreply(q, mp);
26645 		return;
26646 
26647 	case M_IOCNAK:
26648 		/*
26649 		 * The only way we could get here is if a resolver didn't like
26650 		 * an IOCTL we sent it.	 This shouldn't happen.
26651 		 */
26652 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26653 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26654 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26655 		freemsg(mp);
26656 		return;
26657 	case M_IOCACK:
26658 		/* Finish socket ioctls passed through to ARP. */
26659 		ip_sioctl_iocack(q, mp);
26660 		return;
26661 	case M_FLUSH:
26662 		if (*mp->b_rptr & FLUSHW)
26663 			flushq(q, FLUSHALL);
26664 		if (q->q_next) {
26665 			/*
26666 			 * M_FLUSH is sent up to IP by some drivers during
26667 			 * unbind. ip_rput has already replied to it. We are
26668 			 * here for the M_FLUSH that we originated in IP
26669 			 * before sending the unbind request to the driver.
26670 			 * Just free it as we don't queue packets in IP
26671 			 * on the write side of the device instance.
26672 			 */
26673 			freemsg(mp);
26674 			return;
26675 		}
26676 		if (*mp->b_rptr & FLUSHR) {
26677 			*mp->b_rptr &= ~FLUSHW;
26678 			qreply(q, mp);
26679 			return;
26680 		}
26681 		freemsg(mp);
26682 		return;
26683 	case IRE_DB_REQ_TYPE:
26684 		/* An Upper Level Protocol wants a copy of an IRE. */
26685 		ip_ire_req(q, mp);
26686 		return;
26687 	case M_CTL:
26688 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26689 			break;
26690 
26691 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
26692 		    TUN_HELLO) {
26693 			ASSERT(connp != NULL);
26694 			connp->conn_flags |= IPCL_IPTUN;
26695 			freeb(mp);
26696 			return;
26697 		}
26698 
26699 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26700 		    IP_ULP_OUT_LABELED) {
26701 			out_labeled_t *olp;
26702 
26703 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26704 				break;
26705 			olp = (out_labeled_t *)mp->b_rptr;
26706 			connp->conn_ulp_labeled = olp->out_qnext == q;
26707 			freemsg(mp);
26708 			return;
26709 		}
26710 
26711 		/* M_CTL messages are used by ARP to tell us things. */
26712 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26713 			break;
26714 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26715 		case AR_ENTRY_SQUERY:
26716 			ip_wput_ctl(q, mp);
26717 			return;
26718 		case AR_CLIENT_NOTIFY:
26719 			ip_arp_news(q, mp);
26720 			return;
26721 		case AR_DLPIOP_DONE:
26722 			ASSERT(q->q_next != NULL);
26723 			ill = (ill_t *)q->q_ptr;
26724 			/* qwriter_ip releases the refhold */
26725 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26726 			ill_refhold(ill);
26727 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26728 			    CUR_OP, B_FALSE);
26729 			return;
26730 		case AR_ARP_CLOSING:
26731 			/*
26732 			 * ARP (above us) is closing. If no ARP bringup is
26733 			 * currently pending, ack the message so that ARP
26734 			 * can complete its close. Also mark ill_arp_closing
26735 			 * so that new ARP bringups will fail. If any
26736 			 * ARP bringup is currently in progress, we will
26737 			 * ack this when the current ARP bringup completes.
26738 			 */
26739 			ASSERT(q->q_next != NULL);
26740 			ill = (ill_t *)q->q_ptr;
26741 			mutex_enter(&ill->ill_lock);
26742 			ill->ill_arp_closing = 1;
26743 			if (!ill->ill_arp_bringup_pending) {
26744 				mutex_exit(&ill->ill_lock);
26745 				qreply(q, mp);
26746 			} else {
26747 				mutex_exit(&ill->ill_lock);
26748 				freemsg(mp);
26749 			}
26750 			return;
26751 		case AR_ARP_EXTEND:
26752 			/*
26753 			 * The ARP module above us is capable of duplicate
26754 			 * address detection.  Old ATM drivers will not send
26755 			 * this message.
26756 			 */
26757 			ASSERT(q->q_next != NULL);
26758 			ill = (ill_t *)q->q_ptr;
26759 			ill->ill_arp_extend = B_TRUE;
26760 			freemsg(mp);
26761 			return;
26762 		default:
26763 			break;
26764 		}
26765 		break;
26766 	case M_PROTO:
26767 	case M_PCPROTO:
26768 		/*
26769 		 * The only PROTO messages we expect are ULP binds and
26770 		 * copies of option negotiation acknowledgements.
26771 		 */
26772 		switch (((union T_primitives *)mp->b_rptr)->type) {
26773 		case O_T_BIND_REQ:
26774 		case T_BIND_REQ: {
26775 			/* Request can get queued in bind */
26776 			ASSERT(connp != NULL);
26777 			/*
26778 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26779 			 * instead of going through this path.  We only get
26780 			 * here in the following cases:
26781 			 *
26782 			 * a. Bind retries, where ipsq is non-NULL.
26783 			 * b. T_BIND_REQ is issued from non TCP/UDP
26784 			 *    transport, e.g. icmp for raw socket,
26785 			 *    in which case ipsq will be NULL.
26786 			 */
26787 			ASSERT(ipsq != NULL ||
26788 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26789 
26790 			/* Don't increment refcnt if this is a re-entry */
26791 			if (ipsq == NULL)
26792 				CONN_INC_REF(connp);
26793 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26794 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26795 			if (mp == NULL)
26796 				return;
26797 			if (IPCL_IS_TCP(connp)) {
26798 				/*
26799 				 * In the case of TCP endpoint we
26800 				 * come here only for bind retries
26801 				 */
26802 				ASSERT(ipsq != NULL);
26803 				CONN_INC_REF(connp);
26804 				squeue_fill(connp->conn_sqp, mp,
26805 				    ip_resume_tcp_bind, connp,
26806 				    SQTAG_BIND_RETRY);
26807 				return;
26808 			} else if (IPCL_IS_UDP(connp)) {
26809 				/*
26810 				 * In the case of UDP endpoint we
26811 				 * come here only for bind retries
26812 				 */
26813 				ASSERT(ipsq != NULL);
26814 				udp_resume_bind(connp, mp);
26815 				return;
26816 			}
26817 			qreply(q, mp);
26818 			CONN_OPER_PENDING_DONE(connp);
26819 			return;
26820 		}
26821 		case T_SVR4_OPTMGMT_REQ:
26822 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26823 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26824 
26825 			ASSERT(connp != NULL);
26826 			if (!snmpcom_req(q, mp, ip_snmp_set,
26827 			    ip_snmp_get, cr)) {
26828 				/*
26829 				 * Call svr4_optcom_req so that it can
26830 				 * generate the ack. We don't come here
26831 				 * if this operation is being restarted.
26832 				 * ip_restart_optmgmt will drop the conn ref.
26833 				 * In the case of ipsec option after the ipsec
26834 				 * load is complete conn_restart_ipsec_waiter
26835 				 * drops the conn ref.
26836 				 */
26837 				ASSERT(ipsq == NULL);
26838 				CONN_INC_REF(connp);
26839 				if (ip_check_for_ipsec_opt(q, mp))
26840 					return;
26841 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26842 				if (err != EINPROGRESS) {
26843 					/* Operation is done */
26844 					CONN_OPER_PENDING_DONE(connp);
26845 				}
26846 			}
26847 			return;
26848 		case T_OPTMGMT_REQ:
26849 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26850 			/*
26851 			 * Note: No snmpcom_req support through new
26852 			 * T_OPTMGMT_REQ.
26853 			 * Call tpi_optcom_req so that it can
26854 			 * generate the ack.
26855 			 */
26856 			ASSERT(connp != NULL);
26857 			ASSERT(ipsq == NULL);
26858 			/*
26859 			 * We don't come here for restart. ip_restart_optmgmt
26860 			 * will drop the conn ref. In the case of ipsec option
26861 			 * after the ipsec load is complete
26862 			 * conn_restart_ipsec_waiter drops the conn ref.
26863 			 */
26864 			CONN_INC_REF(connp);
26865 			if (ip_check_for_ipsec_opt(q, mp))
26866 				return;
26867 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26868 			if (err != EINPROGRESS) {
26869 				/* Operation is done */
26870 				CONN_OPER_PENDING_DONE(connp);
26871 			}
26872 			return;
26873 		case T_UNBIND_REQ:
26874 			mp = ip_unbind(q, mp);
26875 			qreply(q, mp);
26876 			return;
26877 		default:
26878 			/*
26879 			 * Have to drop any DLPI messages coming down from
26880 			 * arp (such as an info_req which would cause ip
26881 			 * to receive an extra info_ack if it was passed
26882 			 * through.
26883 			 */
26884 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26885 			    (int)*(uint_t *)mp->b_rptr));
26886 			freemsg(mp);
26887 			return;
26888 		}
26889 		/* NOTREACHED */
26890 	case IRE_DB_TYPE: {
26891 		nce_t		*nce;
26892 		ill_t		*ill;
26893 		in6_addr_t	gw_addr_v6;
26894 
26895 
26896 		/*
26897 		 * This is a response back from a resolver.  It
26898 		 * consists of a message chain containing:
26899 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26900 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26901 		 * The LL_HDR_MBLK is the DLPI header to use to get
26902 		 * the attached packet, and subsequent ones for the
26903 		 * same destination, transmitted.
26904 		 */
26905 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26906 			break;
26907 		/*
26908 		 * First, check to make sure the resolution succeeded.
26909 		 * If it failed, the second mblk will be empty.
26910 		 * If it is, free the chain, dropping the packet.
26911 		 * (We must ire_delete the ire; that frees the ire mblk)
26912 		 * We're doing this now to support PVCs for ATM; it's
26913 		 * a partial xresolv implementation. When we fully implement
26914 		 * xresolv interfaces, instead of freeing everything here
26915 		 * we'll initiate neighbor discovery.
26916 		 *
26917 		 * For v4 (ARP and other external resolvers) the resolver
26918 		 * frees the message, so no check is needed. This check
26919 		 * is required, though, for a full xresolve implementation.
26920 		 * Including this code here now both shows how external
26921 		 * resolvers can NACK a resolution request using an
26922 		 * existing design that has no specific provisions for NACKs,
26923 		 * and also takes into account that the current non-ARP
26924 		 * external resolver has been coded to use this method of
26925 		 * NACKing for all IPv6 (xresolv) cases,
26926 		 * whether our xresolv implementation is complete or not.
26927 		 *
26928 		 */
26929 		ire = (ire_t *)mp->b_rptr;
26930 		ill = ire_to_ill(ire);
26931 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26932 		if (mp1->b_rptr == mp1->b_wptr) {
26933 			if (ire->ire_ipversion == IPV6_VERSION) {
26934 				/*
26935 				 * XRESOLV interface.
26936 				 */
26937 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26938 				mutex_enter(&ire->ire_lock);
26939 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26940 				mutex_exit(&ire->ire_lock);
26941 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26942 					nce = ndp_lookup_v6(ill,
26943 					    &ire->ire_addr_v6, B_FALSE);
26944 				} else {
26945 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26946 					    B_FALSE);
26947 				}
26948 				if (nce != NULL) {
26949 					nce_resolv_failed(nce);
26950 					ndp_delete(nce);
26951 					NCE_REFRELE(nce);
26952 				}
26953 			}
26954 			mp->b_cont = NULL;
26955 			freemsg(mp1);		/* frees the pkt as well */
26956 			ASSERT(ire->ire_nce == NULL);
26957 			ire_delete((ire_t *)mp->b_rptr);
26958 			return;
26959 		}
26960 
26961 		/*
26962 		 * Split them into IRE_MBLK and pkt and feed it into
26963 		 * ire_add_then_send. Then in ire_add_then_send
26964 		 * the IRE will be added, and then the packet will be
26965 		 * run back through ip_wput. This time it will make
26966 		 * it to the wire.
26967 		 */
26968 		mp->b_cont = NULL;
26969 		mp = mp1->b_cont;		/* now, mp points to pkt */
26970 		mp1->b_cont = NULL;
26971 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26972 		if (ire->ire_ipversion == IPV6_VERSION) {
26973 			/*
26974 			 * XRESOLV interface. Find the nce and put a copy
26975 			 * of the dl_unitdata_req in nce_res_mp
26976 			 */
26977 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26978 			mutex_enter(&ire->ire_lock);
26979 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26980 			mutex_exit(&ire->ire_lock);
26981 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26982 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26983 				    B_FALSE);
26984 			} else {
26985 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26986 			}
26987 			if (nce != NULL) {
26988 				/*
26989 				 * We have to protect nce_res_mp here
26990 				 * from being accessed by other threads
26991 				 * while we change the mblk pointer.
26992 				 * Other functions will also lock the nce when
26993 				 * accessing nce_res_mp.
26994 				 *
26995 				 * The reason we change the mblk pointer
26996 				 * here rather than copying the resolved address
26997 				 * into the template is that, unlike with
26998 				 * ethernet, we have no guarantee that the
26999 				 * resolved address length will be
27000 				 * smaller than or equal to the lla length
27001 				 * with which the template was allocated,
27002 				 * (for ethernet, they're equal)
27003 				 * so we have to use the actual resolved
27004 				 * address mblk - which holds the real
27005 				 * dl_unitdata_req with the resolved address.
27006 				 *
27007 				 * Doing this is the same behavior as was
27008 				 * previously used in the v4 ARP case.
27009 				 */
27010 				mutex_enter(&nce->nce_lock);
27011 				if (nce->nce_res_mp != NULL)
27012 					freemsg(nce->nce_res_mp);
27013 				nce->nce_res_mp = mp1;
27014 				mutex_exit(&nce->nce_lock);
27015 				/*
27016 				 * We do a fastpath probe here because
27017 				 * we have resolved the address without
27018 				 * using Neighbor Discovery.
27019 				 * In the non-XRESOLV v6 case, the fastpath
27020 				 * probe is done right after neighbor
27021 				 * discovery completes.
27022 				 */
27023 				if (nce->nce_res_mp != NULL) {
27024 					int res;
27025 					nce_fastpath_list_add(nce);
27026 					res = ill_fastpath_probe(ill,
27027 					    nce->nce_res_mp);
27028 					if (res != 0 && res != EAGAIN)
27029 						nce_fastpath_list_delete(nce);
27030 				}
27031 
27032 				ire_add_then_send(q, ire, mp);
27033 				/*
27034 				 * Now we have to clean out any packets
27035 				 * that may have been queued on the nce
27036 				 * while it was waiting for address resolution
27037 				 * to complete.
27038 				 */
27039 				mutex_enter(&nce->nce_lock);
27040 				mp1 = nce->nce_qd_mp;
27041 				nce->nce_qd_mp = NULL;
27042 				mutex_exit(&nce->nce_lock);
27043 				while (mp1 != NULL) {
27044 					mblk_t *nxt_mp;
27045 					queue_t *fwdq = NULL;
27046 					ill_t   *inbound_ill;
27047 					uint_t ifindex;
27048 
27049 					nxt_mp = mp1->b_next;
27050 					mp1->b_next = NULL;
27051 					/*
27052 					 * Retrieve ifindex stored in
27053 					 * ip_rput_data_v6()
27054 					 */
27055 					ifindex =
27056 					    (uint_t)(uintptr_t)mp1->b_prev;
27057 					inbound_ill =
27058 						ill_lookup_on_ifindex(ifindex,
27059 						    B_TRUE, NULL, NULL, NULL,
27060 						    NULL);
27061 					mp1->b_prev = NULL;
27062 					if (inbound_ill != NULL)
27063 						fwdq = inbound_ill->ill_rq;
27064 
27065 					if (fwdq != NULL) {
27066 						put(fwdq, mp1);
27067 						ill_refrele(inbound_ill);
27068 					} else
27069 						put(WR(ill->ill_rq), mp1);
27070 					mp1 = nxt_mp;
27071 				}
27072 				NCE_REFRELE(nce);
27073 			} else {	/* nce is NULL; clean up */
27074 				ire_delete(ire);
27075 				freemsg(mp);
27076 				freemsg(mp1);
27077 				return;
27078 			}
27079 		} else {
27080 			nce_t *arpce;
27081 			/*
27082 			 * Link layer resolution succeeded. Recompute the
27083 			 * ire_nce.
27084 			 */
27085 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27086 			if ((arpce = ndp_lookup_v4(ill,
27087 			    (ire->ire_gateway_addr != INADDR_ANY ?
27088 			    &ire->ire_gateway_addr : &ire->ire_addr),
27089 			    B_FALSE)) == NULL) {
27090 				freeb(ire->ire_mp);
27091 				freeb(mp1);
27092 				freemsg(mp);
27093 				return;
27094 			}
27095 			mutex_enter(&arpce->nce_lock);
27096 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27097 			if (arpce->nce_state == ND_REACHABLE) {
27098 				/*
27099 				 * Someone resolved this before us;
27100 				 * cleanup the res_mp. Since ire has
27101 				 * not been added yet, the call to ire_add_v4
27102 				 * from ire_add_then_send (when a dup is
27103 				 * detected) will clean up the ire.
27104 				 */
27105 				freeb(mp1);
27106 			} else {
27107 				if (arpce->nce_res_mp != NULL)
27108 					freemsg(arpce->nce_res_mp);
27109 				arpce->nce_res_mp = mp1;
27110 				arpce->nce_state = ND_REACHABLE;
27111 			}
27112 			mutex_exit(&arpce->nce_lock);
27113 			if (ire->ire_marks & IRE_MARK_NOADD) {
27114 				/*
27115 				 * this ire will not be added to the ire
27116 				 * cache table, so we can set the ire_nce
27117 				 * here, as there are no atomicity constraints.
27118 				 */
27119 				ire->ire_nce = arpce;
27120 				/*
27121 				 * We are associating this nce with the ire
27122 				 * so change the nce ref taken in
27123 				 * ndp_lookup_v4() from
27124 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27125 				 */
27126 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27127 			} else {
27128 				NCE_REFRELE(arpce);
27129 			}
27130 			ire_add_then_send(q, ire, mp);
27131 		}
27132 		return;	/* All is well, the packet has been sent. */
27133 	}
27134 	case IRE_ARPRESOLVE_TYPE: {
27135 
27136 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27137 			break;
27138 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27139 		mp->b_cont = NULL;
27140 		/*
27141 		 * First, check to make sure the resolution succeeded.
27142 		 * If it failed, the second mblk will be empty.
27143 		 */
27144 		if (mp1->b_rptr == mp1->b_wptr) {
27145 			/* cleanup  the incomplete ire, free queued packets */
27146 			freemsg(mp); /* fake ire */
27147 			freeb(mp1);  /* dl_unitdata response */
27148 			return;
27149 		}
27150 
27151 		/*
27152 		 * update any incomplete nce_t found. we lookup the ctable
27153 		 * and find the nce from the ire->ire_nce because we need
27154 		 * to pass the ire to ip_xmit_v4 later, and can find both
27155 		 * ire and nce in one lookup from the ctable.
27156 		 */
27157 		fake_ire = (ire_t *)mp->b_rptr;
27158 		/*
27159 		 * By the time we come back here from ARP
27160 		 * the logical outgoing interface  of the incomplete ire
27161 		 * we added in ire_forward could have disappeared,
27162 		 * causing the incomplete ire to also have
27163 		 * dissapeared. So we need to retreive the
27164 		 * proper ipif for the ire  before looking
27165 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27166 		 */
27167 		ill = q->q_ptr;
27168 
27169 		/* Get the outgoing ipif */
27170 		mutex_enter(&ill->ill_lock);
27171 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27172 			mutex_exit(&ill->ill_lock);
27173 			freemsg(mp); /* fake ire */
27174 			freeb(mp1);  /* dl_unitdata response */
27175 			return;
27176 		}
27177 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27178 
27179 		if (ipif == NULL) {
27180 			mutex_exit(&ill->ill_lock);
27181 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27182 			freemsg(mp);
27183 			freeb(mp1);
27184 			return;
27185 		}
27186 		ipif_refhold_locked(ipif);
27187 		mutex_exit(&ill->ill_lock);
27188 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27189 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27190 		    ipif, fake_ire->ire_zoneid, NULL,
27191 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27192 		ipif_refrele(ipif);
27193 		if (ire == NULL) {
27194 			/*
27195 			 * no ire was found; check if there is an nce
27196 			 * for this lookup; if it has no ire's pointing at it
27197 			 * cleanup.
27198 			 */
27199 			if ((nce = ndp_lookup_v4(ill,
27200 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27201 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27202 			    B_FALSE)) != NULL) {
27203 				/*
27204 				 * cleanup: just reset nce.
27205 				 * We check for refcnt 2 (one for the nce
27206 				 * hash list + 1 for the ref taken by
27207 				 * ndp_lookup_v4) to ensure that there are
27208 				 * no ire's pointing at the nce.
27209 				 */
27210 				if (nce->nce_refcnt == 2) {
27211 					nce = nce_reinit(nce);
27212 				}
27213 				if (nce != NULL)
27214 					NCE_REFRELE(nce);
27215 			}
27216 			freeb(mp1);  /* dl_unitdata response */
27217 			freemsg(mp); /* fake ire */
27218 			return;
27219 		}
27220 		nce = ire->ire_nce;
27221 		DTRACE_PROBE2(ire__arpresolve__type,
27222 		    ire_t *, ire, nce_t *, nce);
27223 		ASSERT(nce->nce_state != ND_INITIAL);
27224 		mutex_enter(&nce->nce_lock);
27225 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27226 		if (nce->nce_state == ND_REACHABLE) {
27227 			/*
27228 			 * Someone resolved this before us;
27229 			 * our response is not needed any more.
27230 			 */
27231 			mutex_exit(&nce->nce_lock);
27232 			freeb(mp1);  /* dl_unitdata response */
27233 		} else {
27234 			if (nce->nce_res_mp != NULL) {
27235 				freemsg(nce->nce_res_mp);
27236 				/* existing dl_unitdata template */
27237 			}
27238 			nce->nce_res_mp = mp1;
27239 			nce->nce_state = ND_REACHABLE;
27240 			mutex_exit(&nce->nce_lock);
27241 			ire_fastpath(ire);
27242 		}
27243 		/*
27244 		 * The cached nce_t has been updated to be reachable;
27245 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27246 		 */
27247 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27248 		freemsg(mp);
27249 		/*
27250 		 * send out queued packets.
27251 		 */
27252 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27253 
27254 		IRE_REFRELE(ire);
27255 		return;
27256 	}
27257 	default:
27258 		break;
27259 	}
27260 	if (q->q_next) {
27261 		putnext(q, mp);
27262 	} else
27263 		freemsg(mp);
27264 }
27265 
27266 /*
27267  * Process IP options in an outbound packet.  Modify the destination if there
27268  * is a source route option.
27269  * Returns non-zero if something fails in which case an ICMP error has been
27270  * sent and mp freed.
27271  */
27272 static int
27273 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27274     boolean_t mctl_present, zoneid_t zoneid)
27275 {
27276 	ipoptp_t	opts;
27277 	uchar_t		*opt;
27278 	uint8_t		optval;
27279 	uint8_t		optlen;
27280 	ipaddr_t	dst;
27281 	intptr_t	code = 0;
27282 	mblk_t		*mp;
27283 	ire_t		*ire = NULL;
27284 
27285 	ip2dbg(("ip_wput_options\n"));
27286 	mp = ipsec_mp;
27287 	if (mctl_present) {
27288 		mp = ipsec_mp->b_cont;
27289 	}
27290 
27291 	dst = ipha->ipha_dst;
27292 	for (optval = ipoptp_first(&opts, ipha);
27293 	    optval != IPOPT_EOL;
27294 	    optval = ipoptp_next(&opts)) {
27295 		opt = opts.ipoptp_cur;
27296 		optlen = opts.ipoptp_len;
27297 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27298 		    optval, optlen));
27299 		switch (optval) {
27300 			uint32_t off;
27301 		case IPOPT_SSRR:
27302 		case IPOPT_LSRR:
27303 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27304 				ip1dbg((
27305 				    "ip_wput_options: bad option offset\n"));
27306 				code = (char *)&opt[IPOPT_OLEN] -
27307 				    (char *)ipha;
27308 				goto param_prob;
27309 			}
27310 			off = opt[IPOPT_OFFSET];
27311 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27312 			    ntohl(dst)));
27313 			/*
27314 			 * For strict: verify that dst is directly
27315 			 * reachable.
27316 			 */
27317 			if (optval == IPOPT_SSRR) {
27318 				ire = ire_ftable_lookup(dst, 0, 0,
27319 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27320 				    MBLK_GETLABEL(mp),
27321 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27322 				if (ire == NULL) {
27323 					ip1dbg(("ip_wput_options: SSRR not"
27324 					    " directly reachable: 0x%x\n",
27325 					    ntohl(dst)));
27326 					goto bad_src_route;
27327 				}
27328 				ire_refrele(ire);
27329 			}
27330 			break;
27331 		case IPOPT_RR:
27332 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27333 				ip1dbg((
27334 				    "ip_wput_options: bad option offset\n"));
27335 				code = (char *)&opt[IPOPT_OLEN] -
27336 				    (char *)ipha;
27337 				goto param_prob;
27338 			}
27339 			break;
27340 		case IPOPT_TS:
27341 			/*
27342 			 * Verify that length >=5 and that there is either
27343 			 * room for another timestamp or that the overflow
27344 			 * counter is not maxed out.
27345 			 */
27346 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27347 			if (optlen < IPOPT_MINLEN_IT) {
27348 				goto param_prob;
27349 			}
27350 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27351 				ip1dbg((
27352 				    "ip_wput_options: bad option offset\n"));
27353 				code = (char *)&opt[IPOPT_OFFSET] -
27354 				    (char *)ipha;
27355 				goto param_prob;
27356 			}
27357 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27358 			case IPOPT_TS_TSONLY:
27359 				off = IPOPT_TS_TIMELEN;
27360 				break;
27361 			case IPOPT_TS_TSANDADDR:
27362 			case IPOPT_TS_PRESPEC:
27363 			case IPOPT_TS_PRESPEC_RFC791:
27364 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27365 				break;
27366 			default:
27367 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27368 				    (char *)ipha;
27369 				goto param_prob;
27370 			}
27371 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27372 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27373 				/*
27374 				 * No room and the overflow counter is 15
27375 				 * already.
27376 				 */
27377 				goto param_prob;
27378 			}
27379 			break;
27380 		}
27381 	}
27382 
27383 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27384 		return (0);
27385 
27386 	ip1dbg(("ip_wput_options: error processing IP options."));
27387 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27388 
27389 param_prob:
27390 	/*
27391 	 * Since ip_wput() isn't close to finished, we fill
27392 	 * in enough of the header for credible error reporting.
27393 	 */
27394 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27395 		/* Failed */
27396 		freemsg(ipsec_mp);
27397 		return (-1);
27398 	}
27399 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27400 	return (-1);
27401 
27402 bad_src_route:
27403 	/*
27404 	 * Since ip_wput() isn't close to finished, we fill
27405 	 * in enough of the header for credible error reporting.
27406 	 */
27407 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27408 		/* Failed */
27409 		freemsg(ipsec_mp);
27410 		return (-1);
27411 	}
27412 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27413 	return (-1);
27414 }
27415 
27416 /*
27417  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27418  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27419  * thru /etc/system.
27420  */
27421 #define	CONN_MAXDRAINCNT	64
27422 
27423 static void
27424 conn_drain_init(void)
27425 {
27426 	int i;
27427 
27428 	conn_drain_list_cnt = conn_drain_nthreads;
27429 
27430 	if ((conn_drain_list_cnt == 0) ||
27431 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27432 		/*
27433 		 * Default value of the number of drainers is the
27434 		 * number of cpus, subject to maximum of 8 drainers.
27435 		 */
27436 		if (boot_max_ncpus != -1)
27437 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27438 		else
27439 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27440 	}
27441 
27442 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27443 	    KM_SLEEP);
27444 
27445 	for (i = 0; i < conn_drain_list_cnt; i++) {
27446 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27447 		    MUTEX_DEFAULT, NULL);
27448 	}
27449 }
27450 
27451 static void
27452 conn_drain_fini(void)
27453 {
27454 	int i;
27455 
27456 	for (i = 0; i < conn_drain_list_cnt; i++)
27457 		mutex_destroy(&conn_drain_list[i].idl_lock);
27458 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27459 	conn_drain_list = NULL;
27460 }
27461 
27462 /*
27463  * Note: For an overview of how flowcontrol is handled in IP please see the
27464  * IP Flowcontrol notes at the top of this file.
27465  *
27466  * Flow control has blocked us from proceeding. Insert the given conn in one
27467  * of the conn drain lists. These conn wq's will be qenabled later on when
27468  * STREAMS flow control does a backenable. conn_walk_drain will enable
27469  * the first conn in each of these drain lists. Each of these qenabled conns
27470  * in turn enables the next in the list, after it runs, or when it closes,
27471  * thus sustaining the drain process.
27472  *
27473  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27474  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27475  * running at any time, on a given conn, since there can be only 1 service proc
27476  * running on a queue at any time.
27477  */
27478 void
27479 conn_drain_insert(conn_t *connp)
27480 {
27481 	idl_t	*idl;
27482 	uint_t	index;
27483 
27484 	mutex_enter(&connp->conn_lock);
27485 	if (connp->conn_state_flags & CONN_CLOSING) {
27486 		/*
27487 		 * The conn is closing as a result of which CONN_CLOSING
27488 		 * is set. Return.
27489 		 */
27490 		mutex_exit(&connp->conn_lock);
27491 		return;
27492 	} else if (connp->conn_idl == NULL) {
27493 		/*
27494 		 * Assign the next drain list round robin. We dont' use
27495 		 * a lock, and thus it may not be strictly round robin.
27496 		 * Atomicity of load/stores is enough to make sure that
27497 		 * conn_drain_list_index is always within bounds.
27498 		 */
27499 		index = conn_drain_list_index;
27500 		ASSERT(index < conn_drain_list_cnt);
27501 		connp->conn_idl = &conn_drain_list[index];
27502 		index++;
27503 		if (index == conn_drain_list_cnt)
27504 			index = 0;
27505 		conn_drain_list_index = index;
27506 	}
27507 	mutex_exit(&connp->conn_lock);
27508 
27509 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27510 	if ((connp->conn_drain_prev != NULL) ||
27511 	    (connp->conn_state_flags & CONN_CLOSING)) {
27512 		/*
27513 		 * The conn is already in the drain list, OR
27514 		 * the conn is closing. We need to check again for
27515 		 * the closing case again since close can happen
27516 		 * after we drop the conn_lock, and before we
27517 		 * acquire the CONN_DRAIN_LIST_LOCK.
27518 		 */
27519 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27520 		return;
27521 	} else {
27522 		idl = connp->conn_idl;
27523 	}
27524 
27525 	/*
27526 	 * The conn is not in the drain list. Insert it at the
27527 	 * tail of the drain list. The drain list is circular
27528 	 * and doubly linked. idl_conn points to the 1st element
27529 	 * in the list.
27530 	 */
27531 	if (idl->idl_conn == NULL) {
27532 		idl->idl_conn = connp;
27533 		connp->conn_drain_next = connp;
27534 		connp->conn_drain_prev = connp;
27535 	} else {
27536 		conn_t *head = idl->idl_conn;
27537 
27538 		connp->conn_drain_next = head;
27539 		connp->conn_drain_prev = head->conn_drain_prev;
27540 		head->conn_drain_prev->conn_drain_next = connp;
27541 		head->conn_drain_prev = connp;
27542 	}
27543 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27544 }
27545 
27546 /*
27547  * This conn is closing, and we are called from ip_close. OR
27548  * This conn has been serviced by ip_wsrv, and we need to do the tail
27549  * processing.
27550  * If this conn is part of the drain list, we may need to sustain the drain
27551  * process by qenabling the next conn in the drain list. We may also need to
27552  * remove this conn from the list, if it is done.
27553  */
27554 static void
27555 conn_drain_tail(conn_t *connp, boolean_t closing)
27556 {
27557 	idl_t *idl;
27558 
27559 	/*
27560 	 * connp->conn_idl is stable at this point, and no lock is needed
27561 	 * to check it. If we are called from ip_close, close has already
27562 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27563 	 * called us only because conn_idl is non-null. If we are called thru
27564 	 * service, conn_idl could be null, but it cannot change because
27565 	 * service is single-threaded per queue, and there cannot be another
27566 	 * instance of service trying to call conn_drain_insert on this conn
27567 	 * now.
27568 	 */
27569 	ASSERT(!closing || (connp->conn_idl != NULL));
27570 
27571 	/*
27572 	 * If connp->conn_idl is null, the conn has not been inserted into any
27573 	 * drain list even once since creation of the conn. Just return.
27574 	 */
27575 	if (connp->conn_idl == NULL)
27576 		return;
27577 
27578 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27579 
27580 	if (connp->conn_drain_prev == NULL) {
27581 		/* This conn is currently not in the drain list.  */
27582 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27583 		return;
27584 	}
27585 	idl = connp->conn_idl;
27586 	if (idl->idl_conn_draining == connp) {
27587 		/*
27588 		 * This conn is the current drainer. If this is the last conn
27589 		 * in the drain list, we need to do more checks, in the 'if'
27590 		 * below. Otherwwise we need to just qenable the next conn,
27591 		 * to sustain the draining, and is handled in the 'else'
27592 		 * below.
27593 		 */
27594 		if (connp->conn_drain_next == idl->idl_conn) {
27595 			/*
27596 			 * This conn is the last in this list. This round
27597 			 * of draining is complete. If idl_repeat is set,
27598 			 * it means another flow enabling has happened from
27599 			 * the driver/streams and we need to another round
27600 			 * of draining.
27601 			 * If there are more than 2 conns in the drain list,
27602 			 * do a left rotate by 1, so that all conns except the
27603 			 * conn at the head move towards the head by 1, and the
27604 			 * the conn at the head goes to the tail. This attempts
27605 			 * a more even share for all queues that are being
27606 			 * drained.
27607 			 */
27608 			if ((connp->conn_drain_next != connp) &&
27609 			    (idl->idl_conn->conn_drain_next != connp)) {
27610 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27611 			}
27612 			if (idl->idl_repeat) {
27613 				qenable(idl->idl_conn->conn_wq);
27614 				idl->idl_conn_draining = idl->idl_conn;
27615 				idl->idl_repeat = 0;
27616 			} else {
27617 				idl->idl_conn_draining = NULL;
27618 			}
27619 		} else {
27620 			/*
27621 			 * If the next queue that we are now qenable'ing,
27622 			 * is closing, it will remove itself from this list
27623 			 * and qenable the subsequent queue in ip_close().
27624 			 * Serialization is acheived thru idl_lock.
27625 			 */
27626 			qenable(connp->conn_drain_next->conn_wq);
27627 			idl->idl_conn_draining = connp->conn_drain_next;
27628 		}
27629 	}
27630 	if (!connp->conn_did_putbq || closing) {
27631 		/*
27632 		 * Remove ourself from the drain list, if we did not do
27633 		 * a putbq, or if the conn is closing.
27634 		 * Note: It is possible that q->q_first is non-null. It means
27635 		 * that these messages landed after we did a enableok() in
27636 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27637 		 * service them.
27638 		 */
27639 		if (connp->conn_drain_next == connp) {
27640 			/* Singleton in the list */
27641 			ASSERT(connp->conn_drain_prev == connp);
27642 			idl->idl_conn = NULL;
27643 			idl->idl_conn_draining = NULL;
27644 		} else {
27645 			connp->conn_drain_prev->conn_drain_next =
27646 			    connp->conn_drain_next;
27647 			connp->conn_drain_next->conn_drain_prev =
27648 			    connp->conn_drain_prev;
27649 			if (idl->idl_conn == connp)
27650 				idl->idl_conn = connp->conn_drain_next;
27651 			ASSERT(idl->idl_conn_draining != connp);
27652 
27653 		}
27654 		connp->conn_drain_next = NULL;
27655 		connp->conn_drain_prev = NULL;
27656 	}
27657 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27658 }
27659 
27660 /*
27661  * Write service routine. Shared perimeter entry point.
27662  * ip_wsrv can be called in any of the following ways.
27663  * 1. The device queue's messages has fallen below the low water mark
27664  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27665  *    the drain lists and backenable the first conn in each list.
27666  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27667  *    qenabled non-tcp upper layers. We start dequeing messages and call
27668  *    ip_wput for each message.
27669  */
27670 
27671 void
27672 ip_wsrv(queue_t *q)
27673 {
27674 	conn_t	*connp;
27675 	ill_t	*ill;
27676 	mblk_t	*mp;
27677 
27678 	if (q->q_next) {
27679 		ill = (ill_t *)q->q_ptr;
27680 		if (ill->ill_state_flags == 0) {
27681 			/*
27682 			 * The device flow control has opened up.
27683 			 * Walk through conn drain lists and qenable the
27684 			 * first conn in each list. This makes sense only
27685 			 * if the stream is fully plumbed and setup.
27686 			 * Hence the if check above.
27687 			 */
27688 			ip1dbg(("ip_wsrv: walking\n"));
27689 			conn_walk_drain();
27690 		}
27691 		return;
27692 	}
27693 
27694 	connp = Q_TO_CONN(q);
27695 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27696 
27697 	/*
27698 	 * 1. Set conn_draining flag to signal that service is active.
27699 	 *
27700 	 * 2. ip_output determines whether it has been called from service,
27701 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27702 	 *    has been called from service.
27703 	 *
27704 	 * 3. Message ordering is preserved by the following logic.
27705 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27706 	 *    the message at the tail, if conn_draining is set (i.e. service
27707 	 *    is running) or if q->q_first is non-null.
27708 	 *
27709 	 *    ii. If ip_output is called from service, and if ip_output cannot
27710 	 *    putnext due to flow control, it does a putbq.
27711 	 *
27712 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27713 	 *    (causing an infinite loop).
27714 	 */
27715 	ASSERT(!connp->conn_did_putbq);
27716 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27717 		connp->conn_draining = 1;
27718 		noenable(q);
27719 		while ((mp = getq(q)) != NULL) {
27720 			ASSERT(CONN_Q(q));
27721 
27722 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27723 			if (connp->conn_did_putbq) {
27724 				/* ip_wput did a putbq */
27725 				break;
27726 			}
27727 		}
27728 		/*
27729 		 * At this point, a thread coming down from top, calling
27730 		 * ip_wput, may end up queueing the message. We have not yet
27731 		 * enabled the queue, so ip_wsrv won't be called again.
27732 		 * To avoid this race, check q->q_first again (in the loop)
27733 		 * If the other thread queued the message before we call
27734 		 * enableok(), we will catch it in the q->q_first check.
27735 		 * If the other thread queues the message after we call
27736 		 * enableok(), ip_wsrv will be called again by STREAMS.
27737 		 */
27738 		connp->conn_draining = 0;
27739 		enableok(q);
27740 	}
27741 
27742 	/* Enable the next conn for draining */
27743 	conn_drain_tail(connp, B_FALSE);
27744 
27745 	connp->conn_did_putbq = 0;
27746 }
27747 
27748 /*
27749  * Walk the list of all conn's calling the function provided with the
27750  * specified argument for each.	 Note that this only walks conn's that
27751  * have been bound.
27752  * Applies to both IPv4 and IPv6.
27753  */
27754 static void
27755 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27756 {
27757 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27758 	    func, arg, zoneid);
27759 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27760 	    func, arg, zoneid);
27761 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27762 	    func, arg, zoneid);
27763 	conn_walk_fanout_table(ipcl_proto_fanout,
27764 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27765 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27766 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27767 }
27768 
27769 /*
27770  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27771  * of conns that need to be drained, check if drain is already in progress.
27772  * If so set the idl_repeat bit, indicating that the last conn in the list
27773  * needs to reinitiate the drain once again, for the list. If drain is not
27774  * in progress for the list, initiate the draining, by qenabling the 1st
27775  * conn in the list. The drain is self-sustaining, each qenabled conn will
27776  * in turn qenable the next conn, when it is done/blocked/closing.
27777  */
27778 static void
27779 conn_walk_drain(void)
27780 {
27781 	int i;
27782 	idl_t *idl;
27783 
27784 	IP_STAT(ip_conn_walk_drain);
27785 
27786 	for (i = 0; i < conn_drain_list_cnt; i++) {
27787 		idl = &conn_drain_list[i];
27788 		mutex_enter(&idl->idl_lock);
27789 		if (idl->idl_conn == NULL) {
27790 			mutex_exit(&idl->idl_lock);
27791 			continue;
27792 		}
27793 		/*
27794 		 * If this list is not being drained currently by
27795 		 * an ip_wsrv thread, start the process.
27796 		 */
27797 		if (idl->idl_conn_draining == NULL) {
27798 			ASSERT(idl->idl_repeat == 0);
27799 			qenable(idl->idl_conn->conn_wq);
27800 			idl->idl_conn_draining = idl->idl_conn;
27801 		} else {
27802 			idl->idl_repeat = 1;
27803 		}
27804 		mutex_exit(&idl->idl_lock);
27805 	}
27806 }
27807 
27808 /*
27809  * Walk an conn hash table of `count' buckets, calling func for each entry.
27810  */
27811 static void
27812 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27813     zoneid_t zoneid)
27814 {
27815 	conn_t	*connp;
27816 
27817 	while (count-- > 0) {
27818 		mutex_enter(&connfp->connf_lock);
27819 		for (connp = connfp->connf_head; connp != NULL;
27820 		    connp = connp->conn_next) {
27821 			if (zoneid == GLOBAL_ZONEID ||
27822 			    zoneid == connp->conn_zoneid) {
27823 				CONN_INC_REF(connp);
27824 				mutex_exit(&connfp->connf_lock);
27825 				(*func)(connp, arg);
27826 				mutex_enter(&connfp->connf_lock);
27827 				CONN_DEC_REF(connp);
27828 			}
27829 		}
27830 		mutex_exit(&connfp->connf_lock);
27831 		connfp++;
27832 	}
27833 }
27834 
27835 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27836 static void
27837 conn_report1(conn_t *connp, void *mp)
27838 {
27839 	char	buf1[INET6_ADDRSTRLEN];
27840 	char	buf2[INET6_ADDRSTRLEN];
27841 	uint_t	print_len, buf_len;
27842 
27843 	ASSERT(connp != NULL);
27844 
27845 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27846 	if (buf_len <= 0)
27847 		return;
27848 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27849 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27850 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27851 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27852 	    "%5d %s/%05d %s/%05d\n",
27853 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27854 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27855 	    buf1, connp->conn_lport,
27856 	    buf2, connp->conn_fport);
27857 	if (print_len < buf_len) {
27858 		((mblk_t *)mp)->b_wptr += print_len;
27859 	} else {
27860 		((mblk_t *)mp)->b_wptr += buf_len;
27861 	}
27862 }
27863 
27864 /*
27865  * Named Dispatch routine to produce a formatted report on all conns
27866  * that are listed in one of the fanout tables.
27867  * This report is accessed by using the ndd utility to "get" ND variable
27868  * "ip_conn_status".
27869  */
27870 /* ARGSUSED */
27871 static int
27872 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27873 {
27874 	(void) mi_mpprintf(mp,
27875 	    "CONN      " MI_COL_HDRPAD_STR
27876 	    "rfq      " MI_COL_HDRPAD_STR
27877 	    "stq      " MI_COL_HDRPAD_STR
27878 	    " zone local                 remote");
27879 
27880 	/*
27881 	 * Because of the ndd constraint, at most we can have 64K buffer
27882 	 * to put in all conn info.  So to be more efficient, just
27883 	 * allocate a 64K buffer here, assuming we need that large buffer.
27884 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27885 	 */
27886 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27887 		/* The following may work even if we cannot get a large buf. */
27888 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27889 		return (0);
27890 	}
27891 
27892 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27893 	return (0);
27894 }
27895 
27896 /*
27897  * Determine if the ill and multicast aspects of that packets
27898  * "matches" the conn.
27899  */
27900 boolean_t
27901 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27902     zoneid_t zoneid)
27903 {
27904 	ill_t *in_ill;
27905 	boolean_t found;
27906 	ipif_t *ipif;
27907 	ire_t *ire;
27908 	ipaddr_t dst, src;
27909 
27910 	dst = ipha->ipha_dst;
27911 	src = ipha->ipha_src;
27912 
27913 	/*
27914 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27915 	 * unicast, broadcast and multicast reception to
27916 	 * conn_incoming_ill. conn_wantpacket itself is called
27917 	 * only for BROADCAST and multicast.
27918 	 *
27919 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27920 	 *    is part of a group. Hence, we should be receiving
27921 	 *    just one copy of broadcast for the whole group.
27922 	 *    Thus, if it is part of the group the packet could
27923 	 *    come on any ill of the group and hence we need a
27924 	 *    match on the group. Otherwise, match on ill should
27925 	 *    be sufficient.
27926 	 *
27927 	 * 2) ip_rput does not suppress duplicate multicast packets.
27928 	 *    If there are two interfaces in a ill group and we have
27929 	 *    2 applications (conns) joined a multicast group G on
27930 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27931 	 *    will give us two packets because we join G on both the
27932 	 *    interfaces rather than nominating just one interface
27933 	 *    for receiving multicast like broadcast above. So,
27934 	 *    we have to call ilg_lookup_ill to filter out duplicate
27935 	 *    copies, if ill is part of a group.
27936 	 */
27937 	in_ill = connp->conn_incoming_ill;
27938 	if (in_ill != NULL) {
27939 		if (in_ill->ill_group == NULL) {
27940 			if (in_ill != ill)
27941 				return (B_FALSE);
27942 		} else if (in_ill->ill_group != ill->ill_group) {
27943 			return (B_FALSE);
27944 		}
27945 	}
27946 
27947 	if (!CLASSD(dst)) {
27948 		if (IPCL_ZONE_MATCH(connp, zoneid))
27949 			return (B_TRUE);
27950 		/*
27951 		 * The conn is in a different zone; we need to check that this
27952 		 * broadcast address is configured in the application's zone and
27953 		 * on one ill in the group.
27954 		 */
27955 		ipif = ipif_get_next_ipif(NULL, ill);
27956 		if (ipif == NULL)
27957 			return (B_FALSE);
27958 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27959 		    connp->conn_zoneid, NULL,
27960 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27961 		ipif_refrele(ipif);
27962 		if (ire != NULL) {
27963 			ire_refrele(ire);
27964 			return (B_TRUE);
27965 		} else {
27966 			return (B_FALSE);
27967 		}
27968 	}
27969 
27970 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27971 	    connp->conn_zoneid == zoneid) {
27972 		/*
27973 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27974 		 * disabled, therefore we don't dispatch the multicast packet to
27975 		 * the sending zone.
27976 		 */
27977 		return (B_FALSE);
27978 	}
27979 
27980 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27981 	    connp->conn_zoneid != zoneid) {
27982 		/*
27983 		 * Multicast packet on the loopback interface: we only match
27984 		 * conns who joined the group in the specified zone.
27985 		 */
27986 		return (B_FALSE);
27987 	}
27988 
27989 	if (connp->conn_multi_router) {
27990 		/* multicast packet and multicast router socket: send up */
27991 		return (B_TRUE);
27992 	}
27993 
27994 	mutex_enter(&connp->conn_lock);
27995 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27996 	mutex_exit(&connp->conn_lock);
27997 	return (found);
27998 }
27999 
28000 /*
28001  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28002  */
28003 /* ARGSUSED */
28004 static void
28005 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28006 {
28007 	ill_t *ill = (ill_t *)q->q_ptr;
28008 	mblk_t	*mp1, *mp2;
28009 	ipif_t  *ipif;
28010 	int err = 0;
28011 	conn_t *connp = NULL;
28012 	ipsq_t	*ipsq;
28013 	arc_t	*arc;
28014 
28015 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28016 
28017 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28018 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28019 
28020 	ASSERT(IAM_WRITER_ILL(ill));
28021 	mp2 = mp->b_cont;
28022 	mp->b_cont = NULL;
28023 
28024 	/*
28025 	 * We have now received the arp bringup completion message
28026 	 * from ARP. Mark the arp bringup as done. Also if the arp
28027 	 * stream has already started closing, send up the AR_ARP_CLOSING
28028 	 * ack now since ARP is waiting in close for this ack.
28029 	 */
28030 	mutex_enter(&ill->ill_lock);
28031 	ill->ill_arp_bringup_pending = 0;
28032 	if (ill->ill_arp_closing) {
28033 		mutex_exit(&ill->ill_lock);
28034 		/* Let's reuse the mp for sending the ack */
28035 		arc = (arc_t *)mp->b_rptr;
28036 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28037 		arc->arc_cmd = AR_ARP_CLOSING;
28038 		qreply(q, mp);
28039 	} else {
28040 		mutex_exit(&ill->ill_lock);
28041 		freeb(mp);
28042 	}
28043 
28044 	/* We should have an IOCTL waiting on this. */
28045 	ipsq = ill->ill_phyint->phyint_ipsq;
28046 	ipif = ipsq->ipsq_pending_ipif;
28047 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28048 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
28049 	if (mp1 == NULL) {
28050 		/* bringup was aborted by the user */
28051 		freemsg(mp2);
28052 		return;
28053 	}
28054 	ASSERT(connp != NULL);
28055 	q = CONNP_TO_WQ(connp);
28056 	/*
28057 	 * If the DL_BIND_REQ fails, it is noted
28058 	 * in arc_name_offset.
28059 	 */
28060 	err = *((int *)mp2->b_rptr);
28061 	if (err == 0) {
28062 		if (ipif->ipif_isv6) {
28063 			if ((err = ipif_up_done_v6(ipif)) != 0)
28064 				ip0dbg(("ip_arp_done: init failed\n"));
28065 		} else {
28066 			if ((err = ipif_up_done(ipif)) != 0)
28067 				ip0dbg(("ip_arp_done: init failed\n"));
28068 		}
28069 	} else {
28070 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28071 	}
28072 
28073 	freemsg(mp2);
28074 
28075 	if ((err == 0) && (ill->ill_up_ipifs)) {
28076 		err = ill_up_ipifs(ill, q, mp1);
28077 		if (err == EINPROGRESS)
28078 			return;
28079 	}
28080 
28081 	if (ill->ill_up_ipifs) {
28082 		ill_group_cleanup(ill);
28083 	}
28084 
28085 	/*
28086 	 * The ioctl must complete now without EINPROGRESS
28087 	 * since ipsq_pending_mp_get has removed the ioctl mblk
28088 	 * from ipsq_pending_mp. Otherwise the ioctl will be
28089 	 * stuck for ever in the ipsq.
28090 	 */
28091 	ASSERT(err != EINPROGRESS);
28092 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
28093 }
28094 
28095 /* Allocate the private structure */
28096 static int
28097 ip_priv_alloc(void **bufp)
28098 {
28099 	void	*buf;
28100 
28101 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28102 		return (ENOMEM);
28103 
28104 	*bufp = buf;
28105 	return (0);
28106 }
28107 
28108 /* Function to delete the private structure */
28109 void
28110 ip_priv_free(void *buf)
28111 {
28112 	ASSERT(buf != NULL);
28113 	kmem_free(buf, sizeof (ip_priv_t));
28114 }
28115 
28116 /*
28117  * The entry point for IPPF processing.
28118  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28119  * routine just returns.
28120  *
28121  * When called, ip_process generates an ipp_packet_t structure
28122  * which holds the state information for this packet and invokes the
28123  * the classifier (via ipp_packet_process). The classification, depending on
28124  * configured filters, results in a list of actions for this packet. Invoking
28125  * an action may cause the packet to be dropped, in which case the resulting
28126  * mblk (*mpp) is NULL. proc indicates the callout position for
28127  * this packet and ill_index is the interface this packet on or will leave
28128  * on (inbound and outbound resp.).
28129  */
28130 void
28131 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28132 {
28133 	mblk_t		*mp;
28134 	ip_priv_t	*priv;
28135 	ipp_action_id_t	aid;
28136 	int		rc = 0;
28137 	ipp_packet_t	*pp;
28138 #define	IP_CLASS	"ip"
28139 
28140 	/* If the classifier is not loaded, return  */
28141 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28142 		return;
28143 	}
28144 
28145 	mp = *mpp;
28146 	ASSERT(mp != NULL);
28147 
28148 	/* Allocate the packet structure */
28149 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28150 	if (rc != 0) {
28151 		*mpp = NULL;
28152 		freemsg(mp);
28153 		return;
28154 	}
28155 
28156 	/* Allocate the private structure */
28157 	rc = ip_priv_alloc((void **)&priv);
28158 	if (rc != 0) {
28159 		*mpp = NULL;
28160 		freemsg(mp);
28161 		ipp_packet_free(pp);
28162 		return;
28163 	}
28164 	priv->proc = proc;
28165 	priv->ill_index = ill_index;
28166 	ipp_packet_set_private(pp, priv, ip_priv_free);
28167 	ipp_packet_set_data(pp, mp);
28168 
28169 	/* Invoke the classifier */
28170 	rc = ipp_packet_process(&pp);
28171 	if (pp != NULL) {
28172 		mp = ipp_packet_get_data(pp);
28173 		ipp_packet_free(pp);
28174 		if (rc != 0) {
28175 			freemsg(mp);
28176 			*mpp = NULL;
28177 		}
28178 	} else {
28179 		*mpp = NULL;
28180 	}
28181 #undef	IP_CLASS
28182 }
28183 
28184 /*
28185  * Propagate a multicast group membership operation (add/drop) on
28186  * all the interfaces crossed by the related multirt routes.
28187  * The call is considered successful if the operation succeeds
28188  * on at least one interface.
28189  */
28190 static int
28191 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28192     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28193     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28194     mblk_t *first_mp)
28195 {
28196 	ire_t		*ire_gw;
28197 	irb_t		*irb;
28198 	int		error = 0;
28199 	opt_restart_t	*or;
28200 
28201 	irb = ire->ire_bucket;
28202 	ASSERT(irb != NULL);
28203 
28204 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28205 
28206 	or = (opt_restart_t *)first_mp->b_rptr;
28207 	IRB_REFHOLD(irb);
28208 	for (; ire != NULL; ire = ire->ire_next) {
28209 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28210 			continue;
28211 		if (ire->ire_addr != group)
28212 			continue;
28213 
28214 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28215 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28216 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28217 		/* No resolver exists for the gateway; skip this ire. */
28218 		if (ire_gw == NULL)
28219 			continue;
28220 
28221 		/*
28222 		 * This function can return EINPROGRESS. If so the operation
28223 		 * will be restarted from ip_restart_optmgmt which will
28224 		 * call ip_opt_set and option processing will restart for
28225 		 * this option. So we may end up calling 'fn' more than once.
28226 		 * This requires that 'fn' is idempotent except for the
28227 		 * return value. The operation is considered a success if
28228 		 * it succeeds at least once on any one interface.
28229 		 */
28230 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28231 		    NULL, fmode, src, first_mp);
28232 		if (error == 0)
28233 			or->or_private = CGTP_MCAST_SUCCESS;
28234 
28235 		if (ip_debug > 0) {
28236 			ulong_t	off;
28237 			char	*ksym;
28238 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28239 			ip2dbg(("ip_multirt_apply_membership: "
28240 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28241 			    "error %d [success %u]\n",
28242 			    ksym ? ksym : "?",
28243 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28244 			    error, or->or_private));
28245 		}
28246 
28247 		ire_refrele(ire_gw);
28248 		if (error == EINPROGRESS) {
28249 			IRB_REFRELE(irb);
28250 			return (error);
28251 		}
28252 	}
28253 	IRB_REFRELE(irb);
28254 	/*
28255 	 * Consider the call as successful if we succeeded on at least
28256 	 * one interface. Otherwise, return the last encountered error.
28257 	 */
28258 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28259 }
28260 
28261 
28262 /*
28263  * Issue a warning regarding a route crossing an interface with an
28264  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28265  * amount of time is logged.
28266  */
28267 static void
28268 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28269 {
28270 	hrtime_t	current = gethrtime();
28271 	char		buf[INET_ADDRSTRLEN];
28272 
28273 	/* Convert interval in ms to hrtime in ns */
28274 	if (multirt_bad_mtu_last_time +
28275 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28276 	    current) {
28277 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28278 		    "to %s, incorrect MTU %u (expected %u)\n",
28279 		    ip_dot_addr(ire->ire_addr, buf),
28280 		    ire->ire_max_frag, max_frag);
28281 
28282 		multirt_bad_mtu_last_time = current;
28283 	}
28284 }
28285 
28286 
28287 /*
28288  * Get the CGTP (multirouting) filtering status.
28289  * If 0, the CGTP hooks are transparent.
28290  */
28291 /* ARGSUSED */
28292 static int
28293 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28294 {
28295 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28296 
28297 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28298 	return (0);
28299 }
28300 
28301 
28302 /*
28303  * Set the CGTP (multirouting) filtering status.
28304  * If the status is changed from active to transparent
28305  * or from transparent to active, forward the new status
28306  * to the filtering module (if loaded).
28307  */
28308 /* ARGSUSED */
28309 static int
28310 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28311     cred_t *ioc_cr)
28312 {
28313 	long		new_value;
28314 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28315 
28316 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28317 	    new_value < 0 || new_value > 1) {
28318 		return (EINVAL);
28319 	}
28320 
28321 	/*
28322 	 * Do not enable CGTP filtering - thus preventing the hooks
28323 	 * from being invoked - if the version number of the
28324 	 * filtering module hooks does not match.
28325 	 */
28326 	if ((ip_cgtp_filter_ops != NULL) &&
28327 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28328 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28329 		    "(module hooks version %d, expecting %d)\n",
28330 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28331 		return (ENOTSUP);
28332 	}
28333 
28334 	if ((!*ip_cgtp_filter_value) && new_value) {
28335 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28336 		    ip_cgtp_filter_ops == NULL ?
28337 		    " (module not loaded)" : "");
28338 	}
28339 	if (*ip_cgtp_filter_value && (!new_value)) {
28340 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28341 		    ip_cgtp_filter_ops == NULL ?
28342 		    " (module not loaded)" : "");
28343 	}
28344 
28345 	if (ip_cgtp_filter_ops != NULL) {
28346 		int	res;
28347 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28348 			return (res);
28349 		}
28350 	}
28351 
28352 	*ip_cgtp_filter_value = (boolean_t)new_value;
28353 
28354 	return (0);
28355 }
28356 
28357 
28358 /*
28359  * Return the expected CGTP hooks version number.
28360  */
28361 int
28362 ip_cgtp_filter_supported(void)
28363 {
28364 	return (ip_cgtp_filter_rev);
28365 }
28366 
28367 
28368 /*
28369  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28370  * or by invoking this function. In the first case, the version number
28371  * of the registered structure is checked at hooks activation time
28372  * in ip_cgtp_filter_set().
28373  */
28374 int
28375 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28376 {
28377 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28378 		return (ENOTSUP);
28379 
28380 	ip_cgtp_filter_ops = ops;
28381 	return (0);
28382 }
28383 
28384 static squeue_func_t
28385 ip_squeue_switch(int val)
28386 {
28387 	squeue_func_t rval = squeue_fill;
28388 
28389 	switch (val) {
28390 	case IP_SQUEUE_ENTER_NODRAIN:
28391 		rval = squeue_enter_nodrain;
28392 		break;
28393 	case IP_SQUEUE_ENTER:
28394 		rval = squeue_enter;
28395 		break;
28396 	default:
28397 		break;
28398 	}
28399 	return (rval);
28400 }
28401 
28402 /* ARGSUSED */
28403 static int
28404 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28405     caddr_t addr, cred_t *cr)
28406 {
28407 	int *v = (int *)addr;
28408 	long new_value;
28409 
28410 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28411 		return (EINVAL);
28412 
28413 	ip_input_proc = ip_squeue_switch(new_value);
28414 	*v = new_value;
28415 	return (0);
28416 }
28417 
28418 /* ARGSUSED */
28419 static int
28420 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28421     caddr_t addr, cred_t *cr)
28422 {
28423 	int *v = (int *)addr;
28424 	long new_value;
28425 
28426 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28427 		return (EINVAL);
28428 
28429 	*v = new_value;
28430 	return (0);
28431 }
28432 
28433 static void
28434 ip_kstat_init(void)
28435 {
28436 	ip_named_kstat_t template = {
28437 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28438 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28439 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28440 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28441 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28442 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28443 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28444 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28445 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28446 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28447 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28448 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28449 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28450 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28451 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28452 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28453 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28454 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28455 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28456 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28457 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28458 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28459 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28460 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28461 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28462 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28463 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28464 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28465 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28466 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28467 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28468 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28469 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28470 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28471 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28472 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28473 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28474 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28475 	};
28476 
28477 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28478 					NUM_OF_FIELDS(ip_named_kstat_t),
28479 					0);
28480 	if (!ip_mibkp)
28481 		return;
28482 
28483 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28484 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28485 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28486 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28487 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28488 
28489 	template.netToMediaEntrySize.value.i32 =
28490 		sizeof (mib2_ipNetToMediaEntry_t);
28491 
28492 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28493 
28494 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28495 
28496 	ip_mibkp->ks_update = ip_kstat_update;
28497 
28498 	kstat_install(ip_mibkp);
28499 }
28500 
28501 static void
28502 ip_kstat_fini(void)
28503 {
28504 
28505 	if (ip_mibkp != NULL) {
28506 		kstat_delete(ip_mibkp);
28507 		ip_mibkp = NULL;
28508 	}
28509 }
28510 
28511 static int
28512 ip_kstat_update(kstat_t *kp, int rw)
28513 {
28514 	ip_named_kstat_t *ipkp;
28515 
28516 	if (!kp || !kp->ks_data)
28517 		return (EIO);
28518 
28519 	if (rw == KSTAT_WRITE)
28520 		return (EACCES);
28521 
28522 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28523 
28524 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28525 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28526 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28527 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28528 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28529 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28530 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28531 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28532 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28533 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28534 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28535 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28536 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28537 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28538 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28539 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28540 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28541 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28542 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28543 
28544 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28545 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28546 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28547 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28548 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28549 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28550 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28551 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28552 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28553 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28554 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28555 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28556 
28557 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28558 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28559 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28560 
28561 	return (0);
28562 }
28563 
28564 static void
28565 icmp_kstat_init(void)
28566 {
28567 	icmp_named_kstat_t template = {
28568 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28569 		{ "inErrors",		KSTAT_DATA_UINT32 },
28570 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28571 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28572 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28573 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28574 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28575 		{ "inEchos",		KSTAT_DATA_UINT32 },
28576 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28577 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28578 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28579 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28580 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28581 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28582 		{ "outErrors",		KSTAT_DATA_UINT32 },
28583 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28584 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28585 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28586 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28587 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28588 		{ "outEchos",		KSTAT_DATA_UINT32 },
28589 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28590 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28591 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28592 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28593 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28594 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28595 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28596 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28597 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28598 		{ "outDrops",		KSTAT_DATA_UINT32 },
28599 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28600 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28601 	};
28602 
28603 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28604 					NUM_OF_FIELDS(icmp_named_kstat_t),
28605 					0);
28606 	if (icmp_mibkp == NULL)
28607 		return;
28608 
28609 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28610 
28611 	icmp_mibkp->ks_update = icmp_kstat_update;
28612 
28613 	kstat_install(icmp_mibkp);
28614 }
28615 
28616 static void
28617 icmp_kstat_fini(void)
28618 {
28619 
28620 	if (icmp_mibkp != NULL) {
28621 		kstat_delete(icmp_mibkp);
28622 		icmp_mibkp = NULL;
28623 	}
28624 }
28625 
28626 static int
28627 icmp_kstat_update(kstat_t *kp, int rw)
28628 {
28629 	icmp_named_kstat_t *icmpkp;
28630 
28631 	if ((kp == NULL) || (kp->ks_data == NULL))
28632 		return (EIO);
28633 
28634 	if (rw == KSTAT_WRITE)
28635 		return (EACCES);
28636 
28637 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28638 
28639 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28640 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28641 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28642 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28643 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28644 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28645 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28646 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28647 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28648 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28649 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28650 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28651 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28652 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28653 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28654 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28655 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28656 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28657 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28658 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28659 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28660 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28661 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28662 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28663 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28664 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28665 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28666 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28667 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28668 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28669 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28670 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28671 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28672 
28673 	return (0);
28674 }
28675 
28676 /*
28677  * This is the fanout function for raw socket opened for SCTP.  Note
28678  * that it is called after SCTP checks that there is no socket which
28679  * wants a packet.  Then before SCTP handles this out of the blue packet,
28680  * this function is called to see if there is any raw socket for SCTP.
28681  * If there is and it is bound to the correct address, the packet will
28682  * be sent to that socket.  Note that only one raw socket can be bound to
28683  * a port.  This is assured in ipcl_sctp_hash_insert();
28684  */
28685 void
28686 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28687     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28688     uint_t ipif_seqid, zoneid_t zoneid)
28689 {
28690 	conn_t		*connp;
28691 	queue_t		*rq;
28692 	mblk_t		*first_mp;
28693 	boolean_t	secure;
28694 	ip6_t		*ip6h;
28695 
28696 	first_mp = mp;
28697 	if (mctl_present) {
28698 		mp = first_mp->b_cont;
28699 		secure = ipsec_in_is_secure(first_mp);
28700 		ASSERT(mp != NULL);
28701 	} else {
28702 		secure = B_FALSE;
28703 	}
28704 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28705 
28706 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28707 	if (connp == NULL) {
28708 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28709 		    mctl_present);
28710 		return;
28711 	}
28712 	rq = connp->conn_rq;
28713 	if (!canputnext(rq)) {
28714 		CONN_DEC_REF(connp);
28715 		BUMP_MIB(&ip_mib, rawipInOverflows);
28716 		freemsg(first_mp);
28717 		return;
28718 	}
28719 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28720 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28721 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28722 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28723 		if (first_mp == NULL) {
28724 			CONN_DEC_REF(connp);
28725 			return;
28726 		}
28727 	}
28728 	/*
28729 	 * We probably should not send M_CTL message up to
28730 	 * raw socket.
28731 	 */
28732 	if (mctl_present)
28733 		freeb(first_mp);
28734 
28735 	/* Initiate IPPF processing here if needed. */
28736 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28737 	    (!isv4 && IP6_IN_IPP(flags))) {
28738 		ip_process(IPP_LOCAL_IN, &mp,
28739 		    recv_ill->ill_phyint->phyint_ifindex);
28740 		if (mp == NULL) {
28741 			CONN_DEC_REF(connp);
28742 			return;
28743 		}
28744 	}
28745 
28746 	if (connp->conn_recvif || connp->conn_recvslla ||
28747 	    ((connp->conn_ipv6_recvpktinfo ||
28748 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28749 	    (flags & IP_FF_IP6INFO))) {
28750 		int in_flags = 0;
28751 
28752 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28753 			in_flags = IPF_RECVIF;
28754 		}
28755 		if (connp->conn_recvslla) {
28756 			in_flags |= IPF_RECVSLLA;
28757 		}
28758 		if (isv4) {
28759 			mp = ip_add_info(mp, recv_ill, in_flags);
28760 		} else {
28761 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28762 			if (mp == NULL) {
28763 				CONN_DEC_REF(connp);
28764 				return;
28765 			}
28766 		}
28767 	}
28768 
28769 	BUMP_MIB(&ip_mib, ipInDelivers);
28770 	/*
28771 	 * We are sending the IPSEC_IN message also up. Refer
28772 	 * to comments above this function.
28773 	 */
28774 	putnext(rq, mp);
28775 	CONN_DEC_REF(connp);
28776 }
28777 
28778 /*
28779  * This function should be called only if all packet processing
28780  * including fragmentation is complete. Callers of this function
28781  * must set mp->b_prev to one of these values:
28782  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28783  * prior to handing over the mp as first argument to this function.
28784  *
28785  * If the ire passed by caller is incomplete, this function
28786  * queues the packet and if necessary, sends ARP request and bails.
28787  * If the ire passed is fully resolved, we simply prepend
28788  * the link-layer header to the packet, do ipsec hw acceleration
28789  * work if necessary, and send the packet out on the wire.
28790  *
28791  * NOTE: IPSEC will only call this function with fully resolved
28792  * ires if hw acceleration is involved.
28793  * TODO list :
28794  * 	a Handle M_MULTIDATA so that
28795  *	  tcp_multisend->tcp_multisend_data can
28796  *	  call ip_xmit_v4 directly
28797  *	b Handle post-ARP work for fragments so that
28798  *	  ip_wput_frag can call this function.
28799  */
28800 ipxmit_state_t
28801 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28802 {
28803 	nce_t		*arpce;
28804 	queue_t		*q;
28805 	int		ill_index;
28806 	mblk_t		*nxt_mp, *first_mp;
28807 	boolean_t	xmit_drop = B_FALSE;
28808 	ip_proc_t	proc;
28809 	ill_t		*out_ill;
28810 
28811 	arpce = ire->ire_nce;
28812 	ASSERT(arpce != NULL);
28813 
28814 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28815 
28816 	mutex_enter(&arpce->nce_lock);
28817 	switch (arpce->nce_state) {
28818 	case ND_REACHABLE:
28819 		/* If there are other queued packets, queue this packet */
28820 		if (arpce->nce_qd_mp != NULL) {
28821 			if (mp != NULL)
28822 				nce_queue_mp_common(arpce, mp, B_FALSE);
28823 			mp = arpce->nce_qd_mp;
28824 		}
28825 		arpce->nce_qd_mp = NULL;
28826 		mutex_exit(&arpce->nce_lock);
28827 
28828 		/*
28829 		 * Flush the queue.  In the common case, where the
28830 		 * ARP is already resolved,  it will go through the
28831 		 * while loop only once.
28832 		 */
28833 		while (mp != NULL) {
28834 
28835 			nxt_mp = mp->b_next;
28836 			mp->b_next = NULL;
28837 			/*
28838 			 * This info is needed for IPQOS to do COS marking
28839 			 * in ip_wput_attach_llhdr->ip_process.
28840 			 */
28841 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28842 			mp->b_prev = NULL;
28843 
28844 			/* set up ill index for outbound qos processing */
28845 			out_ill = ire->ire_ipif->ipif_ill;
28846 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28847 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28848 			    ill_index);
28849 			if (first_mp == NULL) {
28850 				xmit_drop = B_TRUE;
28851 				if (proc == IPP_FWD_OUT) {
28852 					BUMP_MIB(&ip_mib, ipInDiscards);
28853 				} else {
28854 					BUMP_MIB(&ip_mib, ipOutDiscards);
28855 				}
28856 				goto next_mp;
28857 			}
28858 			/* non-ipsec hw accel case */
28859 			if (io == NULL || !io->ipsec_out_accelerated) {
28860 				/* send it */
28861 				q = ire->ire_stq;
28862 				if (proc == IPP_FWD_OUT) {
28863 					UPDATE_IB_PKT_COUNT(ire);
28864 				} else {
28865 					UPDATE_OB_PKT_COUNT(ire);
28866 				}
28867 				ire->ire_last_used_time = lbolt;
28868 
28869 				if (flow_ctl_enabled || canputnext(q))  {
28870 					if (proc == IPP_FWD_OUT) {
28871 						BUMP_MIB(&ip_mib,
28872 						    ipForwDatagrams);
28873 					}
28874 
28875 					if (mp == NULL)
28876 						goto next_mp;
28877 					putnext(q, first_mp);
28878 				} else {
28879 					BUMP_MIB(&ip_mib,
28880 					    ipOutDiscards);
28881 					xmit_drop = B_TRUE;
28882 					freemsg(first_mp);
28883 				}
28884 			} else {
28885 				/*
28886 				 * Safety Pup says: make sure this
28887 				 *  is going to the right interface!
28888 				 */
28889 				ill_t *ill1 =
28890 				    (ill_t *)ire->ire_stq->q_ptr;
28891 				int ifindex =
28892 				    ill1->ill_phyint->phyint_ifindex;
28893 				if (ifindex !=
28894 				    io->ipsec_out_capab_ill_index) {
28895 					xmit_drop = B_TRUE;
28896 					freemsg(mp);
28897 				} else {
28898 					ipsec_hw_putnext(ire->ire_stq,
28899 					    mp);
28900 				}
28901 			}
28902 next_mp:
28903 			mp = nxt_mp;
28904 		} /* while (mp != NULL) */
28905 		if (xmit_drop)
28906 			return (SEND_FAILED);
28907 		else
28908 			return (SEND_PASSED);
28909 
28910 	case ND_INITIAL:
28911 	case ND_INCOMPLETE:
28912 
28913 		/*
28914 		 * While we do send off packets to dests that
28915 		 * use fully-resolved CGTP routes, we do not
28916 		 * handle unresolved CGTP routes.
28917 		 */
28918 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28919 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28920 
28921 		if (mp != NULL) {
28922 			/* queue the packet */
28923 			nce_queue_mp_common(arpce, mp, B_FALSE);
28924 		}
28925 
28926 		if (arpce->nce_state == ND_INCOMPLETE) {
28927 			mutex_exit(&arpce->nce_lock);
28928 			DTRACE_PROBE3(ip__xmit__incomplete,
28929 			    (ire_t *), ire, (mblk_t *), mp,
28930 			    (ipsec_out_t *), io);
28931 			return (LOOKUP_IN_PROGRESS);
28932 		}
28933 
28934 		arpce->nce_state = ND_INCOMPLETE;
28935 		mutex_exit(&arpce->nce_lock);
28936 		/*
28937 		 * Note that ire_add() (called from ire_forward())
28938 		 * holds a ref on the ire until ARP is completed.
28939 		 */
28940 
28941 		ire_arpresolve(ire, ire_to_ill(ire));
28942 		return (LOOKUP_IN_PROGRESS);
28943 	default:
28944 		ASSERT(0);
28945 		mutex_exit(&arpce->nce_lock);
28946 		return (LLHDR_RESLV_FAILED);
28947 	}
28948 }
28949 
28950 /*
28951  * Return B_TRUE if the buffers differ in length or content.
28952  * This is used for comparing extension header buffers.
28953  * Note that an extension header would be declared different
28954  * even if all that changed was the next header value in that header i.e.
28955  * what really changed is the next extension header.
28956  */
28957 boolean_t
28958 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28959     uint_t blen)
28960 {
28961 	if (!b_valid)
28962 		blen = 0;
28963 
28964 	if (alen != blen)
28965 		return (B_TRUE);
28966 	if (alen == 0)
28967 		return (B_FALSE);	/* Both zero length */
28968 	return (bcmp(abuf, bbuf, alen));
28969 }
28970 
28971 /*
28972  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28973  * Return B_FALSE if memory allocation fails - don't change any state!
28974  */
28975 boolean_t
28976 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28977     const void *src, uint_t srclen)
28978 {
28979 	void *dst;
28980 
28981 	if (!src_valid)
28982 		srclen = 0;
28983 
28984 	ASSERT(*dstlenp == 0);
28985 	if (src != NULL && srclen != 0) {
28986 		dst = mi_alloc(srclen, BPRI_MED);
28987 		if (dst == NULL)
28988 			return (B_FALSE);
28989 	} else {
28990 		dst = NULL;
28991 	}
28992 	if (*dstp != NULL)
28993 		mi_free(*dstp);
28994 	*dstp = dst;
28995 	*dstlenp = dst == NULL ? 0 : srclen;
28996 	return (B_TRUE);
28997 }
28998 
28999 /*
29000  * Replace what is in *dst, *dstlen with the source.
29001  * Assumes ip_allocbuf has already been called.
29002  */
29003 void
29004 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29005     const void *src, uint_t srclen)
29006 {
29007 	if (!src_valid)
29008 		srclen = 0;
29009 
29010 	ASSERT(*dstlenp == srclen);
29011 	if (src != NULL && srclen != 0)
29012 		bcopy(src, *dstp, srclen);
29013 }
29014 
29015 /*
29016  * Free the storage pointed to by the members of an ip6_pkt_t.
29017  */
29018 void
29019 ip6_pkt_free(ip6_pkt_t *ipp)
29020 {
29021 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29022 
29023 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29024 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29025 		ipp->ipp_hopopts = NULL;
29026 		ipp->ipp_hopoptslen = 0;
29027 	}
29028 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29029 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29030 		ipp->ipp_rtdstopts = NULL;
29031 		ipp->ipp_rtdstoptslen = 0;
29032 	}
29033 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29034 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29035 		ipp->ipp_dstopts = NULL;
29036 		ipp->ipp_dstoptslen = 0;
29037 	}
29038 	if (ipp->ipp_fields & IPPF_RTHDR) {
29039 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29040 		ipp->ipp_rthdr = NULL;
29041 		ipp->ipp_rthdrlen = 0;
29042 	}
29043 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29044 	    IPPF_RTHDR);
29045 }
29046