xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision e250f1e2aa9a1ecc5cbc4e6fea59fab258f0db4d)
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 
255 /*
256  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
257  */
258 
259 struct listptr_s {
260 	mblk_t	*lp_head;	/* pointer to the head of the list */
261 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
262 };
263 
264 typedef struct listptr_s listptr_t;
265 
266 /*
267  * This is used by ip_snmp_get_mib2_ip_route_media and
268  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
269  */
270 typedef struct iproutedata_s {
271 	uint_t		ird_idx;
272 	listptr_t	ird_route;	/* ipRouteEntryTable */
273 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
274 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
275 } iproutedata_t;
276 
277 /*
278  * Cluster specific hooks. These should be NULL when booted as a non-cluster
279  */
280 
281 /*
282  * Hook functions to enable cluster networking
283  * On non-clustered systems these vectors must always be NULL.
284  *
285  * Hook function to Check ip specified ip address is a shared ip address
286  * in the cluster
287  *
288  */
289 int (*cl_inet_isclusterwide)(uint8_t protocol,
290     sa_family_t addr_family, uint8_t *laddrp) = NULL;
291 
292 /*
293  * Hook function to generate cluster wide ip fragment identifier
294  */
295 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
296     uint8_t *laddrp, uint8_t *faddrp) = NULL;
297 
298 /*
299  * Synchronization notes:
300  *
301  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
302  * MT level protection given by STREAMS. IP uses a combination of its own
303  * internal serialization mechanism and standard Solaris locking techniques.
304  * The internal serialization is per phyint (no IPMP) or per IPMP group.
305  * This is used to serialize plumbing operations, IPMP operations, certain
306  * multicast operations, most set ioctls, igmp/mld timers etc.
307  *
308  * Plumbing is a long sequence of operations involving message
309  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
310  * involved in plumbing operations. A natural model is to serialize these
311  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
312  * parallel without any interference. But various set ioctls on hme0 are best
313  * serialized. However if the system uses IPMP, the operations are easier if
314  * they are serialized on a per IPMP group basis since IPMP operations
315  * happen across ill's of a group. Thus the lowest common denominator is to
316  * serialize most set ioctls, multicast join/leave operations, IPMP operations
317  * igmp/mld timer operations, and processing of DLPI control messages received
318  * from drivers on a per IPMP group basis. If the system does not employ
319  * IPMP the serialization is on a per phyint basis. This serialization is
320  * provided by the ipsq_t and primitives operating on this. Details can
321  * be found in ip_if.c above the core primitives operating on ipsq_t.
322  *
323  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
324  * Simiarly lookup of an ire by a thread also returns a refheld ire.
325  * In addition ipif's and ill's referenced by the ire are also indirectly
326  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
327  * the ipif's address or netmask change as long as an ipif is refheld
328  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
329  * address of an ipif has to go through the ipsq_t. This ensures that only
330  * 1 such exclusive operation proceeds at any time on the ipif. It then
331  * deletes all ires associated with this ipif, and waits for all refcnts
332  * associated with this ipif to come down to zero. The address is changed
333  * only after the ipif has been quiesced. Then the ipif is brought up again.
334  * More details are described above the comment in ip_sioctl_flags.
335  *
336  * Packet processing is based mostly on IREs and are fully multi-threaded
337  * using standard Solaris MT techniques.
338  *
339  * There are explicit locks in IP to handle:
340  * - The ip_g_head list maintained by mi_open_link() and friends.
341  *
342  * - The reassembly data structures (one lock per hash bucket)
343  *
344  * - conn_lock is meant to protect conn_t fields. The fields actually
345  *   protected by conn_lock are documented in the conn_t definition.
346  *
347  * - ire_lock to protect some of the fields of the ire, IRE tables
348  *   (one lock per hash bucket). Refer to ip_ire.c for details.
349  *
350  * - ndp_g_lock and nce_lock for protecting NCEs.
351  *
352  * - ill_lock protects fields of the ill and ipif. Details in ip.h
353  *
354  * - ill_g_lock: This is a global reader/writer lock. Protects the following
355  *	* The AVL tree based global multi list of all ills.
356  *	* The linked list of all ipifs of an ill
357  *	* The <ill-ipsq> mapping
358  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
359  *	* The illgroup list threaded by ill_group_next.
360  *	* <ill-phyint> association
361  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
362  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
363  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
364  *   will all have to hold the ill_g_lock as writer for the actual duration
365  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
366  *   may be found in the IPMP section.
367  *
368  * - ill_lock:  This is a per ill mutex.
369  *   It protects some members of the ill and is documented below.
370  *   It also protects the <ill-ipsq> mapping
371  *   It also protects the illgroup list threaded by ill_group_next.
372  *   It also protects the <ill-phyint> assoc.
373  *   It also protects the list of ipifs hanging off the ill.
374  *
375  * - ipsq_lock: This is a per ipsq_t mutex lock.
376  *   This protects all the other members of the ipsq struct except
377  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
378  *
379  * - illgrp_lock: This is a per ill_group mutex lock.
380  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
381  *   which dictates which is the next ill in an ill_group that is to be chosen
382  *   for sending outgoing packets, through creation of an IRE_CACHE that
383  *   references this ill.
384  *
385  * - phyint_lock: This is a per phyint mutex lock. Protects just the
386  *   phyint_flags
387  *
388  * - ip_g_nd_lock: This is a global reader/writer lock.
389  *   Any call to nd_load to load a new parameter to the ND table must hold the
390  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
391  *   as reader.
392  *
393  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
394  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
395  *   uniqueness check also done atomically.
396  *
397  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
398  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
399  *   as a writer when adding or deleting elements from these lists, and
400  *   as a reader when walking these lists to send a SADB update to the
401  *   IPsec capable ills.
402  *
403  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
404  *   group list linked by ill_usesrc_grp_next. It also protects the
405  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
406  *   group is being added or deleted.  This lock is taken as a reader when
407  *   walking the list/group(eg: to get the number of members in a usesrc group).
408  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
409  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
410  *   example, it is not necessary to take this lock in the initial portion
411  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
412  *   ip_sioctl_flags since the these operations are executed exclusively and
413  *   that ensures that the "usesrc group state" cannot change. The "usesrc
414  *   group state" change can happen only in the latter part of
415  *   ip_sioctl_slifusesrc and in ill_delete.
416  *
417  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
418  *
419  * To change the <ill-phyint> association, the ill_g_lock must be held
420  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
421  * must be held.
422  *
423  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
424  * and the ill_lock of the ill in question must be held.
425  *
426  * To change the <ill-illgroup> association the ill_g_lock must be held as
427  * writer and the ill_lock of the ill in question must be held.
428  *
429  * To add or delete an ipif from the list of ipifs hanging off the ill,
430  * ill_g_lock (writer) and ill_lock must be held and the thread must be
431  * a writer on the associated ipsq,.
432  *
433  * To add or delete an ill to the system, the ill_g_lock must be held as
434  * writer and the thread must be a writer on the associated ipsq.
435  *
436  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
437  * must be a writer on the associated ipsq.
438  *
439  * Lock hierarchy
440  *
441  * Some lock hierarchy scenarios are listed below.
442  *
443  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
444  * ill_g_lock -> illgrp_lock -> ill_lock
445  * ill_g_lock -> ill_lock(s) -> phyint_lock
446  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
447  * ill_g_lock -> ip_addr_avail_lock
448  * conn_lock -> irb_lock -> ill_lock -> ire_lock
449  * ill_g_lock -> ip_g_nd_lock
450  *
451  * When more than 1 ill lock is needed to be held, all ill lock addresses
452  * are sorted on address and locked starting from highest addressed lock
453  * downward.
454  *
455  * Mobile-IP scenarios
456  *
457  * irb_lock -> ill_lock -> ire_mrtun_lock
458  * irb_lock -> ill_lock -> ire_srcif_table_lock
459  *
460  * IPsec scenarios
461  *
462  * ipsa_lock -> ill_g_lock -> ill_lock
463  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ipsa_lock
465  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
466  *
467  * Trusted Solaris scenarios
468  *
469  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
470  * igsa_lock -> gcdb_lock
471  * gcgrp_rwlock -> ire_lock
472  * gcgrp_rwlock -> gcdb_lock
473  *
474  *
475  * Routing/forwarding table locking notes:
476  *
477  * Lock acquisition order: Radix tree lock, irb_lock.
478  * Requirements:
479  * i.  Walker must not hold any locks during the walker callback.
480  * ii  Walker must not see a truncated tree during the walk because of any node
481  *     deletion.
482  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
483  *     in many places in the code to walk the irb list. Thus even if all the
484  *     ires in a bucket have been deleted, we still can't free the radix node
485  *     until the ires have actually been inactive'd (freed).
486  *
487  * Tree traversal - Need to hold the global tree lock in read mode.
488  * Before dropping the global tree lock, need to either increment the ire_refcnt
489  * to ensure that the radix node can't be deleted.
490  *
491  * Tree add - Need to hold the global tree lock in write mode to add a
492  * radix node. To prevent the node from being deleted, increment the
493  * irb_refcnt, after the node is added to the tree. The ire itself is
494  * added later while holding the irb_lock, but not the tree lock.
495  *
496  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
497  * All associated ires must be inactive (i.e. freed), and irb_refcnt
498  * must be zero.
499  *
500  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
501  * global tree lock (read mode) for traversal.
502  *
503  * IPSEC notes :
504  *
505  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
506  * in front of the actual packet. For outbound datagrams, the M_CTL
507  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
508  * information used by the IPSEC code for applying the right level of
509  * protection. The information initialized by IP in the ipsec_out_t
510  * is determined by the per-socket policy or global policy in the system.
511  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
512  * ipsec_info.h) which starts out with nothing in it. It gets filled
513  * with the right information if it goes through the AH/ESP code, which
514  * happens if the incoming packet is secure. The information initialized
515  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
516  * the policy requirements needed by per-socket policy or global policy
517  * is met or not.
518  *
519  * If there is both per-socket policy (set using setsockopt) and there
520  * is also global policy match for the 5 tuples of the socket,
521  * ipsec_override_policy() makes the decision of which one to use.
522  *
523  * For fully connected sockets i.e dst, src [addr, port] is known,
524  * conn_policy_cached is set indicating that policy has been cached.
525  * conn_in_enforce_policy may or may not be set depending on whether
526  * there is a global policy match or per-socket policy match.
527  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
528  * Once the right policy is set on the conn_t, policy cannot change for
529  * this socket. This makes life simpler for TCP (UDP ?) where
530  * re-transmissions go out with the same policy. For symmetry, policy
531  * is cached for fully connected UDP sockets also. Thus if policy is cached,
532  * it also implies that policy is latched i.e policy cannot change
533  * on these sockets. As we have the right policy on the conn, we don't
534  * have to lookup global policy for every outbound and inbound datagram
535  * and thus serving as an optimization. Note that a global policy change
536  * does not affect fully connected sockets if they have policy. If fully
537  * connected sockets did not have any policy associated with it, global
538  * policy change may affect them.
539  *
540  * IP Flow control notes:
541  *
542  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
543  * cannot be sent down to the driver by IP, because of a canput failure, IP
544  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
545  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
546  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
547  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
548  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
549  * the queued messages, and removes the conn from the drain list, if all
550  * messages were drained. It also qenables the next conn in the drain list to
551  * continue the drain process.
552  *
553  * In reality the drain list is not a single list, but a configurable number
554  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
555  * list. If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
562  * running on a queue at any time. conn_drain_tail can be simultaneously called
563  * from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
664  * associated.
665  *
666  * Multiple zones can share a common broadcast address; typically all zones
667  * share the 255.255.255.255 address. Incoming as well as locally originated
668  * broadcast packets must be dispatched to all the zones on the broadcast
669  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
670  * since some zones may not be on the 10.16.72/24 network. To handle this, each
671  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
672  * sent to every zone that has an IRE_BROADCAST entry for the destination
673  * address on the input ill, see conn_wantpacket().
674  *
675  * Applications in different zones can join the same multicast group address.
676  * For IPv4, group memberships are per-logical interface, so they're already
677  * inherently part of a zone. For IPv6, group memberships are per-physical
678  * interface, so we distinguish IPv6 group memberships based on group address,
679  * interface and zoneid. In both cases, received multicast packets are sent to
680  * every zone for which a group membership entry exists. On IPv6 we need to
681  * check that the target zone still has an address on the receiving physical
682  * interface; it could have been removed since the application issued the
683  * IPV6_JOIN_GROUP.
684  */
685 
686 /*
687  * Squeue Fanout flags:
688  *	0: No fanout.
689  *	1: Fanout across all squeues
690  */
691 boolean_t	ip_squeue_fanout = 0;
692 
693 /*
694  * Maximum dups allowed per packet.
695  */
696 uint_t ip_max_frag_dups = 10;
697 
698 #define	IS_SIMPLE_IPH(ipha)						\
699 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
700 
701 /* RFC1122 Conformance */
702 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
703 
704 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
705 
706 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
707 
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
709 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
712 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
713     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
714 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
715 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
716 		    mblk_t *, int);
717 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
718 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
719 		    ill_t *, zoneid_t);
720 static void	icmp_options_update(ipha_t *);
721 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
722 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
723 		    zoneid_t zoneid);
724 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
725 static void	icmp_redirect(mblk_t *);
726 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
727 
728 static void	ip_arp_news(queue_t *, mblk_t *);
729 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
730 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
731 char		*ip_dot_addr(ipaddr_t, char *);
732 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
733 int		ip_close(queue_t *, int);
734 static char	*ip_dot_saddr(uchar_t *, char *);
735 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
736 		    boolean_t, boolean_t, ill_t *, zoneid_t);
737 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
738 		    boolean_t, boolean_t, zoneid_t);
739 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
740 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_lrput(queue_t *, mblk_t *);
742 ipaddr_t	ip_massage_options(ipha_t *);
743 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
744 ipaddr_t	ip_net_mask(ipaddr_t);
745 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
746 		    zoneid_t);
747 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
748 		    conn_t *, uint32_t, zoneid_t);
749 char		*ip_nv_lookup(nv_t *, int);
750 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
751 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
752 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
754 			    size_t);
755 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
756 void	ip_rput(queue_t *, mblk_t *);
757 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758 		    void *dummy_arg);
759 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
760 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
761 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
762 			    ire_t *);
763 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
764 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
765 		    uint16_t *);
766 int		ip_snmp_get(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
783 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
784 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
785 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
786 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
787 static boolean_t	ip_source_routed(ipha_t *);
788 static boolean_t	ip_source_route_included(ipha_t *);
789 
790 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
791 		    zoneid_t);
792 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
793 static void	ip_wput_local_options(ipha_t *);
794 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
795 		    zoneid_t);
796 
797 static void	conn_drain_init(void);
798 static void	conn_drain_fini(void);
799 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
800 
801 static void	conn_walk_drain(void);
802 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
803     zoneid_t);
804 
805 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
806     zoneid_t);
807 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
808     void *dummy_arg);
809 
810 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
811 
812 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
813     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
814     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
815 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
816 
817 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
818 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
819     caddr_t, cred_t *);
820 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
821     caddr_t cp, cred_t *cr);
822 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
823     cred_t *);
824 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
825     caddr_t cp, cred_t *cr);
826 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
827     cred_t *);
828 static squeue_func_t ip_squeue_switch(int);
829 
830 static void	ip_kstat_init(void);
831 static void	ip_kstat_fini(void);
832 static int	ip_kstat_update(kstat_t *kp, int rw);
833 static void	icmp_kstat_init(void);
834 static void	icmp_kstat_fini(void);
835 static int	icmp_kstat_update(kstat_t *kp, int rw);
836 
837 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
838 
839 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
840     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
841 
842 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
843     ipha_t *, ill_t *, boolean_t);
844 
845 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
846 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
847 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
848 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
849 
850 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
851 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
852 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
853 
854 /* How long, in seconds, we allow frags to hang around. */
855 #define	IP_FRAG_TIMEOUT	60
856 
857 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
858 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
859 
860 /*
861  * Threshold which determines whether MDT should be used when
862  * generating IP fragments; payload size must be greater than
863  * this threshold for MDT to take place.
864  */
865 #define	IP_WPUT_FRAG_MDT_MIN	32768
866 
867 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
868 
869 /* Protected by ip_mi_lock */
870 static void	*ip_g_head;		/* Instance Data List Head */
871 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
872 
873 /* Only modified during _init and _fini thus no locking is needed. */
874 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
875 
876 
877 static long ip_rput_pullups;
878 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
879 
880 vmem_t *ip_minor_arena;
881 
882 /*
883  * MIB-2 stuff for SNMP (both IP and ICMP)
884  */
885 mib2_ip_t	ip_mib;
886 mib2_icmp_t	icmp_mib;
887 
888 #ifdef DEBUG
889 uint32_t ipsechw_debug = 0;
890 #endif
891 
892 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
893 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
894 
895 uint_t	loopback_packets = 0;
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
903 /* Interval (in ms) between consecutive 'bad MTU' warnings */
904 hrtime_t ip_multirt_log_interval = 1000;
905 /* Time since last warning issued. */
906 static hrtime_t	multirt_bad_mtu_last_time = 0;
907 
908 kmutex_t ip_trash_timer_lock;
909 krwlock_t ip_g_nd_lock;
910 
911 /*
912  * XXX following really should only be in a header. Would need more
913  * header and .c clean up first.
914  */
915 extern optdb_obj_t	ip_opt_obj;
916 
917 ulong_t ip_squeue_enter_unbound = 0;
918 
919 /*
920  * Named Dispatch Parameter Table.
921  * All of these are alterable, within the min/max values given, at run time.
922  */
923 static ipparam_t	lcl_param_arr[] = {
924 	/* min	max	value	name */
925 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
930 	{  0,	1,	1,	"ip_send_redirects"},
931 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
932 	{  0,	10,	0,	"ip_debug"},
933 	{  0,	10,	0,	"ip_mrtdebug"},
934 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
935 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
936 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
937 	{  1,	255,	255,	"ip_def_ttl" },
938 	{  0,	1,	0,	"ip_forward_src_routed"},
939 	{  0,	256,	32,	"ip_wroff_extra" },
940 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
941 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
942 	{  0,	1,	1,	"ip_path_mtu_discovery" },
943 	{  0,	240,	30,	"ip_ignore_delete_time" },
944 	{  0,	1,	0,	"ip_ignore_redirect" },
945 	{  0,	1,	1,	"ip_output_queue" },
946 	{  1,	254,	1,	"ip_broadcast_ttl" },
947 	{  0,	99999,	100,	"ip_icmp_err_interval" },
948 	{  1,	99999,	10,	"ip_icmp_err_burst" },
949 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
950 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
951 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
952 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
953 	{  0,	1,	1,	"icmp_accept_clear_messages" },
954 	{  0,	1,	1,	"igmp_accept_clear_messages" },
955 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
956 				"ip_ndp_delay_first_probe_time"},
957 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
958 				"ip_ndp_max_unicast_solicit"},
959 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
960 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
961 	{  0,	1,	0,	"ip6_forward_src_routed"},
962 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
963 	{  0,	1,	1,	"ip6_send_redirects"},
964 	{  0,	1,	0,	"ip6_ignore_redirect" },
965 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
966 
967 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
968 
969 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
970 
971 	{  0,	1,	1,	"pim_accept_clear_messages" },
972 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
973 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
974 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
975 	{  0,	15,	0,	"ip_policy_mask" },
976 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
977 	{  0,	255,	1,	"ip_multirt_ttl" },
978 	{  0,	1,	1,	"ip_multidata_outbound" },
979 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
980 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
981 	{  0,	1000,	1,	"ip_max_temp_defend" },
982 	{  0,	1000,	3,	"ip_max_defend" },
983 	{  0,	999999,	30,	"ip_defend_interval" },
984 	{  0,	3600000, 300000, "ip_dup_recovery" },
985 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
986 	{  0,	1,	1,	"ip_lso_outbound" },
987 #ifdef DEBUG
988 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
989 #endif
990 };
991 
992 ipparam_t	*ip_param_arr = lcl_param_arr;
993 
994 /* Extended NDP table */
995 static ipndp_t	lcl_ndp_arr[] = {
996 	/* getf			setf		data			name */
997 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
998 	    "ip_forwarding" },
999 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
1000 	    "ip6_forwarding" },
1001 	{  ip_ill_report,	NULL,		NULL,
1002 	    "ip_ill_status" },
1003 	{  ip_ipif_report,	NULL,		NULL,
1004 	    "ip_ipif_status" },
1005 	{  ip_ire_report,	NULL,		NULL,
1006 	    "ipv4_ire_status" },
1007 	{  ip_ire_report_mrtun,	NULL,		NULL,
1008 	    "ipv4_mrtun_ire_status" },
1009 	{  ip_ire_report_srcif,	NULL,		NULL,
1010 	    "ipv4_srcif_ire_status" },
1011 	{  ip_ire_report_v6,	NULL,		NULL,
1012 	    "ipv6_ire_status" },
1013 	{  ip_conn_report,	NULL,		NULL,
1014 	    "ip_conn_status" },
1015 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1016 	    "ip_rput_pullups" },
1017 	{  ndp_report,		NULL,		NULL,
1018 	    "ip_ndp_cache_report" },
1019 	{  ip_srcid_report,	NULL,		NULL,
1020 	    "ip_srcid_status" },
1021 	{ ip_param_generic_get, ip_squeue_profile_set,
1022 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1023 	{ ip_param_generic_get, ip_squeue_bind_set,
1024 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1025 	{ ip_param_generic_get, ip_input_proc_set,
1026 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1027 	{ ip_param_generic_get, ip_int_set,
1028 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1029 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1030 	    "ip_cgtp_filter" },
1031 	{ ip_param_generic_get, ip_int_set,
1032 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1033 };
1034 
1035 /*
1036  * ip_g_forward controls IP forwarding.  It takes two values:
1037  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1038  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1039  *
1040  * RFC1122 says there must be a configuration switch to control forwarding,
1041  * but that the default MUST be to not forward packets ever.  Implicit
1042  * control based on configuration of multiple interfaces MUST NOT be
1043  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1044  * and, in fact, it was the default.  That capability is now provided in the
1045  * /etc/rc2.d/S69inet script.
1046  */
1047 int ip_g_forward = IP_FORWARD_DEFAULT;
1048 
1049 /* It also has an IPv6 counterpart. */
1050 
1051 int ipv6_forward = IP_FORWARD_DEFAULT;
1052 
1053 /*
1054  * Table of IP ioctls encoding the various properties of the ioctl and
1055  * indexed based on the last byte of the ioctl command. Occasionally there
1056  * is a clash, and there is more than 1 ioctl with the same last byte.
1057  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1058  * ioctls are encoded in the misc table. An entry in the ndx table is
1059  * retrieved by indexing on the last byte of the ioctl command and comparing
1060  * the ioctl command with the value in the ndx table. In the event of a
1061  * mismatch the misc table is then searched sequentially for the desired
1062  * ioctl command.
1063  *
1064  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1065  */
1066 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1067 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1079 			MISC_CMD, ip_siocaddrt, NULL },
1080 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1081 			MISC_CMD, ip_siocdelrt, NULL },
1082 
1083 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1084 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1085 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_addr, NULL },
1087 
1088 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1090 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1091 			IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1093 
1094 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1095 			IPI_PRIV | IPI_WR | IPI_REPL,
1096 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1097 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1098 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1099 			IF_CMD, ip_sioctl_get_flags, NULL },
1100 
1101 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 
1104 	/* copyin size cannot be coded for SIOCGIFCONF */
1105 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1106 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1107 
1108 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1109 			IF_CMD, ip_sioctl_mtu, NULL },
1110 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1111 			IF_CMD, ip_sioctl_get_mtu, NULL },
1112 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1113 			IPI_GET_CMD | IPI_REPL,
1114 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1115 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1116 			IF_CMD, ip_sioctl_brdaddr, NULL },
1117 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1118 			IPI_GET_CMD | IPI_REPL,
1119 			IF_CMD, ip_sioctl_get_netmask, NULL },
1120 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1121 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1122 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1123 			IPI_GET_CMD | IPI_REPL,
1124 			IF_CMD, ip_sioctl_get_metric, NULL },
1125 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1126 			IF_CMD, ip_sioctl_metric, NULL },
1127 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 
1129 	/* See 166-168 below for extended SIOC*XARP ioctls */
1130 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1131 			MISC_CMD, ip_sioctl_arp, NULL },
1132 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1133 			MISC_CMD, ip_sioctl_arp, NULL },
1134 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1135 			MISC_CMD, ip_sioctl_arp, NULL },
1136 
1137 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 
1159 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1160 			MISC_CMD, if_unitsel, if_unitsel_restart },
1161 
1162 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 
1181 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1182 			IPI_PRIV | IPI_WR | IPI_MODOK,
1183 			IF_CMD, ip_sioctl_sifname, NULL },
1184 
1185 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 
1199 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1200 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1201 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1202 			IF_CMD, ip_sioctl_get_muxid, NULL },
1203 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1204 			IPI_PRIV | IPI_WR | IPI_REPL,
1205 			IF_CMD, ip_sioctl_muxid, NULL },
1206 
1207 	/* Both if and lif variants share same func */
1208 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1209 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1210 	/* Both if and lif variants share same func */
1211 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1212 			IPI_PRIV | IPI_WR | IPI_REPL,
1213 			IF_CMD, ip_sioctl_slifindex, NULL },
1214 
1215 	/* copyin size cannot be coded for SIOCGIFCONF */
1216 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1217 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1218 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 
1236 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1237 			IPI_PRIV | IPI_WR | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_removeif,
1239 			ip_sioctl_removeif_restart },
1240 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1241 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1242 			LIF_CMD, ip_sioctl_addif, NULL },
1243 #define	SIOCLIFADDR_NDX 112
1244 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1245 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1246 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1247 			IPI_GET_CMD | IPI_REPL,
1248 			LIF_CMD, ip_sioctl_get_addr, NULL },
1249 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1251 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1252 			IPI_GET_CMD | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1254 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1255 			IPI_PRIV | IPI_WR | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1257 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1258 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1259 			LIF_CMD, ip_sioctl_get_flags, NULL },
1260 
1261 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 
1264 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1265 			ip_sioctl_get_lifconf, NULL },
1266 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1267 			LIF_CMD, ip_sioctl_mtu, NULL },
1268 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1270 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1271 			IPI_GET_CMD | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1273 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1274 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1275 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1276 			IPI_GET_CMD | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1278 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1280 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_metric, NULL },
1283 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_metric, NULL },
1285 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1286 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_slifname,
1288 			ip_sioctl_slifname_restart },
1289 
1290 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1291 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1292 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1293 			IPI_GET_CMD | IPI_REPL,
1294 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1295 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1296 			IPI_PRIV | IPI_WR | IPI_REPL,
1297 			LIF_CMD, ip_sioctl_muxid, NULL },
1298 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1299 			IPI_GET_CMD | IPI_REPL,
1300 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1301 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1302 			IPI_PRIV | IPI_WR | IPI_REPL,
1303 			LIF_CMD, ip_sioctl_slifindex, 0 },
1304 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1305 			LIF_CMD, ip_sioctl_token, NULL },
1306 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1307 			IPI_GET_CMD | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_get_token, NULL },
1309 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1310 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1311 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1312 			IPI_GET_CMD | IPI_REPL,
1313 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1314 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1315 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1316 
1317 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1318 			IPI_GET_CMD | IPI_REPL,
1319 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1320 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1321 			LIF_CMD, ip_siocdelndp_v6, NULL },
1322 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1323 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1324 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1325 			LIF_CMD, ip_siocsetndp_v6, NULL },
1326 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1327 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1328 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1329 			MISC_CMD, ip_sioctl_tonlink, NULL },
1330 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1331 			MISC_CMD, ip_sioctl_tmysite, NULL },
1332 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1333 			TUN_CMD, ip_sioctl_tunparam, NULL },
1334 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1335 			IPI_PRIV | IPI_WR,
1336 			TUN_CMD, ip_sioctl_tunparam, NULL },
1337 
1338 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1339 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1343 
1344 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1345 			IPI_PRIV | IPI_WR | IPI_REPL,
1346 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1347 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1348 			IPI_PRIV | IPI_WR | IPI_REPL,
1349 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1350 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1351 			IPI_PRIV | IPI_WR,
1352 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1353 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1354 			IPI_GET_CMD | IPI_REPL,
1355 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1356 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1357 			IPI_GET_CMD | IPI_REPL,
1358 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1359 
1360 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1361 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1364 
1365 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1366 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1367 
1368 	/* These are handled in ip_sioctl_copyin_setup itself */
1369 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1370 			MISC_CMD, NULL, NULL },
1371 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1372 			MISC_CMD, NULL, NULL },
1373 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1374 
1375 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1376 			ip_sioctl_get_lifconf, NULL },
1377 
1378 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1379 			MISC_CMD, ip_sioctl_xarp, NULL },
1380 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1381 			MISC_CMD, ip_sioctl_xarp, NULL },
1382 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1383 			MISC_CMD, ip_sioctl_xarp, NULL },
1384 
1385 	/* SIOCPOPSOCKFS is not handled by IP */
1386 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1387 
1388 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1389 			IPI_GET_CMD | IPI_REPL,
1390 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1391 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1392 			IPI_PRIV | IPI_WR | IPI_REPL,
1393 			LIF_CMD, ip_sioctl_slifzone,
1394 			ip_sioctl_slifzone_restart },
1395 	/* 172-174 are SCTP ioctls and not handled by IP */
1396 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1399 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1400 			IPI_GET_CMD, LIF_CMD,
1401 			ip_sioctl_get_lifusesrc, 0 },
1402 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1403 			IPI_PRIV | IPI_WR,
1404 			LIF_CMD, ip_sioctl_slifusesrc,
1405 			NULL },
1406 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1407 			ip_sioctl_get_lifsrcof, NULL },
1408 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1409 			MISC_CMD, ip_sioctl_msfilter, NULL },
1410 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1411 			MISC_CMD, ip_sioctl_msfilter, NULL },
1412 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1413 			MISC_CMD, ip_sioctl_msfilter, NULL },
1414 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1415 			MISC_CMD, ip_sioctl_msfilter, NULL },
1416 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1417 			ip_sioctl_set_ipmpfailback, NULL }
1418 };
1419 
1420 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1421 
1422 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1423 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1424 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1425 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1426 		TUN_CMD, ip_sioctl_tunparam, NULL },
1427 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1433 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1434 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1435 		MISC_CMD, mrt_ioctl},
1436 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1437 		MISC_CMD, mrt_ioctl},
1438 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1439 		MISC_CMD, mrt_ioctl}
1440 };
1441 
1442 int ip_misc_ioctl_count =
1443     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1444 
1445 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1446 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1447 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1448 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1449 					/* Settable in /etc/system */
1450 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1451 
1452 /* Defined in ip_ire.c */
1453 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1454 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1455 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1456 
1457 static nv_t	ire_nv_arr[] = {
1458 	{ IRE_BROADCAST, "BROADCAST" },
1459 	{ IRE_LOCAL, "LOCAL" },
1460 	{ IRE_LOOPBACK, "LOOPBACK" },
1461 	{ IRE_CACHE, "CACHE" },
1462 	{ IRE_DEFAULT, "DEFAULT" },
1463 	{ IRE_PREFIX, "PREFIX" },
1464 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1465 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1466 	{ IRE_HOST, "HOST" },
1467 	{ 0 }
1468 };
1469 
1470 nv_t	*ire_nv_tbl = ire_nv_arr;
1471 
1472 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1473 extern krwlock_t ipsec_capab_ills_lock;
1474 
1475 /* Defined in ip_netinfo.c */
1476 extern ddi_taskq_t	*eventq_queue_nic;
1477 
1478 /* Packet dropper for IP IPsec processing failures */
1479 ipdropper_t ip_dropper;
1480 
1481 /* Simple ICMP IP Header Template */
1482 static ipha_t icmp_ipha = {
1483 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1484 };
1485 
1486 struct module_info ip_mod_info = {
1487 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1488 };
1489 
1490 /*
1491  * Duplicate static symbols within a module confuses mdb; so we avoid the
1492  * problem by making the symbols here distinct from those in udp.c.
1493  */
1494 
1495 static struct qinit iprinit = {
1496 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1497 	&ip_mod_info
1498 };
1499 
1500 static struct qinit ipwinit = {
1501 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1502 	&ip_mod_info
1503 };
1504 
1505 static struct qinit iplrinit = {
1506 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1507 	&ip_mod_info
1508 };
1509 
1510 static struct qinit iplwinit = {
1511 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1512 	&ip_mod_info
1513 };
1514 
1515 struct streamtab ipinfo = {
1516 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1517 };
1518 
1519 #ifdef	DEBUG
1520 static boolean_t skip_sctp_cksum = B_FALSE;
1521 #endif
1522 
1523 /*
1524  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1525  * ip_rput_v6(), ip_output(), etc.  If the message
1526  * block already has a M_CTL at the front of it, then simply set the zoneid
1527  * appropriately.
1528  */
1529 mblk_t *
1530 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1531 {
1532 	mblk_t		*first_mp;
1533 	ipsec_out_t	*io;
1534 
1535 	ASSERT(zoneid != ALL_ZONES);
1536 	if (mp->b_datap->db_type == M_CTL) {
1537 		io = (ipsec_out_t *)mp->b_rptr;
1538 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1539 		io->ipsec_out_zoneid = zoneid;
1540 		return (mp);
1541 	}
1542 
1543 	first_mp = ipsec_alloc_ipsec_out();
1544 	if (first_mp == NULL)
1545 		return (NULL);
1546 	io = (ipsec_out_t *)first_mp->b_rptr;
1547 	/* This is not a secure packet */
1548 	io->ipsec_out_secure = B_FALSE;
1549 	io->ipsec_out_zoneid = zoneid;
1550 	first_mp->b_cont = mp;
1551 	return (first_mp);
1552 }
1553 
1554 /*
1555  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1556  */
1557 mblk_t *
1558 ip_copymsg(mblk_t *mp)
1559 {
1560 	mblk_t *nmp;
1561 	ipsec_info_t *in;
1562 
1563 	if (mp->b_datap->db_type != M_CTL)
1564 		return (copymsg(mp));
1565 
1566 	in = (ipsec_info_t *)mp->b_rptr;
1567 
1568 	/*
1569 	 * Note that M_CTL is also used for delivering ICMP error messages
1570 	 * upstream to transport layers.
1571 	 */
1572 	if (in->ipsec_info_type != IPSEC_OUT &&
1573 	    in->ipsec_info_type != IPSEC_IN)
1574 		return (copymsg(mp));
1575 
1576 	nmp = copymsg(mp->b_cont);
1577 
1578 	if (in->ipsec_info_type == IPSEC_OUT)
1579 		return (ipsec_out_tag(mp, nmp));
1580 	else
1581 		return (ipsec_in_tag(mp, nmp));
1582 }
1583 
1584 /* Generate an ICMP fragmentation needed message. */
1585 static void
1586 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1587 {
1588 	icmph_t	icmph;
1589 	mblk_t *first_mp;
1590 	boolean_t mctl_present;
1591 
1592 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1593 
1594 	if (!(mp = icmp_pkt_err_ok(mp))) {
1595 		if (mctl_present)
1596 			freeb(first_mp);
1597 		return;
1598 	}
1599 
1600 	bzero(&icmph, sizeof (icmph_t));
1601 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1602 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1603 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1604 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1605 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1606 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1607 }
1608 
1609 /*
1610  * icmp_inbound deals with ICMP messages in the following ways.
1611  *
1612  * 1) It needs to send a reply back and possibly delivering it
1613  *    to the "interested" upper clients.
1614  * 2) It needs to send it to the upper clients only.
1615  * 3) It needs to change some values in IP only.
1616  * 4) It needs to change some values in IP and upper layers e.g TCP.
1617  *
1618  * We need to accomodate icmp messages coming in clear until we get
1619  * everything secure from the wire. If icmp_accept_clear_messages
1620  * is zero we check with the global policy and act accordingly. If
1621  * it is non-zero, we accept the message without any checks. But
1622  * *this does not mean* that this will be delivered to the upper
1623  * clients. By accepting we might send replies back, change our MTU
1624  * value etc. but delivery to the ULP/clients depends on their policy
1625  * dispositions.
1626  *
1627  * We handle the above 4 cases in the context of IPSEC in the
1628  * following way :
1629  *
1630  * 1) Send the reply back in the same way as the request came in.
1631  *    If it came in encrypted, it goes out encrypted. If it came in
1632  *    clear, it goes out in clear. Thus, this will prevent chosen
1633  *    plain text attack.
1634  * 2) The client may or may not expect things to come in secure.
1635  *    If it comes in secure, the policy constraints are checked
1636  *    before delivering it to the upper layers. If it comes in
1637  *    clear, ipsec_inbound_accept_clear will decide whether to
1638  *    accept this in clear or not. In both the cases, if the returned
1639  *    message (IP header + 8 bytes) that caused the icmp message has
1640  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1641  *    sending up. If there are only 8 bytes of returned message, then
1642  *    upper client will not be notified.
1643  * 3) Check with global policy to see whether it matches the constaints.
1644  *    But this will be done only if icmp_accept_messages_in_clear is
1645  *    zero.
1646  * 4) If we need to change both in IP and ULP, then the decision taken
1647  *    while affecting the values in IP and while delivering up to TCP
1648  *    should be the same.
1649  *
1650  * 	There are two cases.
1651  *
1652  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1653  *	   failed), we will not deliver it to the ULP, even though they
1654  *	   are *willing* to accept in *clear*. This is fine as our global
1655  *	   disposition to icmp messages asks us reject the datagram.
1656  *
1657  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1658  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1659  *	   to deliver it to ULP (policy failed), it can lead to
1660  *	   consistency problems. The cases known at this time are
1661  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1662  *	   values :
1663  *
1664  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1665  *	     and Upper layer rejects. Then the communication will
1666  *	     come to a stop. This is solved by making similar decisions
1667  *	     at both levels. Currently, when we are unable to deliver
1668  *	     to the Upper Layer (due to policy failures) while IP has
1669  *	     adjusted ire_max_frag, the next outbound datagram would
1670  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1671  *	     will be with the right level of protection. Thus the right
1672  *	     value will be communicated even if we are not able to
1673  *	     communicate when we get from the wire initially. But this
1674  *	     assumes there would be at least one outbound datagram after
1675  *	     IP has adjusted its ire_max_frag value. To make things
1676  *	     simpler, we accept in clear after the validation of
1677  *	     AH/ESP headers.
1678  *
1679  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1680  *	     upper layer depending on the level of protection the upper
1681  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1682  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1683  *	     should be accepted in clear when the Upper layer expects secure.
1684  *	     Thus the communication may get aborted by some bad ICMP
1685  *	     packets.
1686  *
1687  * IPQoS Notes:
1688  * The only instance when a packet is sent for processing is when there
1689  * isn't an ICMP client and if we are interested in it.
1690  * If there is a client, IPPF processing will take place in the
1691  * ip_fanout_proto routine.
1692  *
1693  * Zones notes:
1694  * The packet is only processed in the context of the specified zone: typically
1695  * only this zone will reply to an echo request, and only interested clients in
1696  * this zone will receive a copy of the packet. This means that the caller must
1697  * call icmp_inbound() for each relevant zone.
1698  */
1699 static void
1700 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1701     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1702     ill_t *recv_ill, zoneid_t zoneid)
1703 {
1704 	icmph_t	*icmph;
1705 	ipha_t	*ipha;
1706 	int	iph_hdr_length;
1707 	int	hdr_length;
1708 	boolean_t	interested;
1709 	uint32_t	ts;
1710 	uchar_t	*wptr;
1711 	ipif_t	*ipif;
1712 	mblk_t *first_mp;
1713 	ipsec_in_t *ii;
1714 	ire_t *src_ire;
1715 	boolean_t onlink;
1716 	timestruc_t now;
1717 	uint32_t ill_index;
1718 
1719 	ASSERT(ill != NULL);
1720 
1721 	first_mp = mp;
1722 	if (mctl_present) {
1723 		mp = first_mp->b_cont;
1724 		ASSERT(mp != NULL);
1725 	}
1726 
1727 	ipha = (ipha_t *)mp->b_rptr;
1728 	if (icmp_accept_clear_messages == 0) {
1729 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1730 		    ipha, NULL, mctl_present);
1731 		if (first_mp == NULL)
1732 			return;
1733 	}
1734 
1735 	/*
1736 	 * On a labeled system, we have to check whether the zone itself is
1737 	 * permitted to receive raw traffic.
1738 	 */
1739 	if (is_system_labeled()) {
1740 		if (zoneid == ALL_ZONES)
1741 			zoneid = tsol_packet_to_zoneid(mp);
1742 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1743 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1744 			    zoneid));
1745 			BUMP_MIB(&icmp_mib, icmpInErrors);
1746 			freemsg(first_mp);
1747 			return;
1748 		}
1749 	}
1750 
1751 	/*
1752 	 * We have accepted the ICMP message. It means that we will
1753 	 * respond to the packet if needed. It may not be delivered
1754 	 * to the upper client depending on the policy constraints
1755 	 * and the disposition in ipsec_inbound_accept_clear.
1756 	 */
1757 
1758 	ASSERT(ill != NULL);
1759 
1760 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1761 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1762 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1763 		/* Last chance to get real. */
1764 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1765 			BUMP_MIB(&icmp_mib, icmpInErrors);
1766 			freemsg(first_mp);
1767 			return;
1768 		}
1769 		/* Refresh iph following the pullup. */
1770 		ipha = (ipha_t *)mp->b_rptr;
1771 	}
1772 	/* ICMP header checksum, including checksum field, should be zero. */
1773 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1774 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1775 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1776 		freemsg(first_mp);
1777 		return;
1778 	}
1779 	/* The IP header will always be a multiple of four bytes */
1780 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1781 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1782 	    icmph->icmph_code));
1783 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1784 	/* We will set "interested" to "true" if we want a copy */
1785 	interested = B_FALSE;
1786 	switch (icmph->icmph_type) {
1787 	case ICMP_ECHO_REPLY:
1788 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1789 		break;
1790 	case ICMP_DEST_UNREACHABLE:
1791 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1792 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1793 		interested = B_TRUE;	/* Pass up to transport */
1794 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1795 		break;
1796 	case ICMP_SOURCE_QUENCH:
1797 		interested = B_TRUE;	/* Pass up to transport */
1798 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1799 		break;
1800 	case ICMP_REDIRECT:
1801 		if (!ip_ignore_redirect)
1802 			interested = B_TRUE;
1803 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1804 		break;
1805 	case ICMP_ECHO_REQUEST:
1806 		/*
1807 		 * Whether to respond to echo requests that come in as IP
1808 		 * broadcasts or as IP multicast is subject to debate
1809 		 * (what isn't?).  We aim to please, you pick it.
1810 		 * Default is do it.
1811 		 */
1812 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1813 			/* unicast: always respond */
1814 			interested = B_TRUE;
1815 		} else if (CLASSD(ipha->ipha_dst)) {
1816 			/* multicast: respond based on tunable */
1817 			interested = ip_g_resp_to_echo_mcast;
1818 		} else if (broadcast) {
1819 			/* broadcast: respond based on tunable */
1820 			interested = ip_g_resp_to_echo_bcast;
1821 		}
1822 		BUMP_MIB(&icmp_mib, icmpInEchos);
1823 		break;
1824 	case ICMP_ROUTER_ADVERTISEMENT:
1825 	case ICMP_ROUTER_SOLICITATION:
1826 		break;
1827 	case ICMP_TIME_EXCEEDED:
1828 		interested = B_TRUE;	/* Pass up to transport */
1829 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1830 		break;
1831 	case ICMP_PARAM_PROBLEM:
1832 		interested = B_TRUE;	/* Pass up to transport */
1833 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1834 		break;
1835 	case ICMP_TIME_STAMP_REQUEST:
1836 		/* Response to Time Stamp Requests is local policy. */
1837 		if (ip_g_resp_to_timestamp &&
1838 		    /* So is whether to respond if it was an IP broadcast. */
1839 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1840 			int tstamp_len = 3 * sizeof (uint32_t);
1841 
1842 			if (wptr +  tstamp_len > mp->b_wptr) {
1843 				if (!pullupmsg(mp, wptr + tstamp_len -
1844 				    mp->b_rptr)) {
1845 					BUMP_MIB(&ip_mib, ipInDiscards);
1846 					freemsg(first_mp);
1847 					return;
1848 				}
1849 				/* Refresh ipha following the pullup. */
1850 				ipha = (ipha_t *)mp->b_rptr;
1851 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1852 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1853 			}
1854 			interested = B_TRUE;
1855 		}
1856 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1857 		break;
1858 	case ICMP_TIME_STAMP_REPLY:
1859 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1860 		break;
1861 	case ICMP_INFO_REQUEST:
1862 		/* Per RFC 1122 3.2.2.7, ignore this. */
1863 	case ICMP_INFO_REPLY:
1864 		break;
1865 	case ICMP_ADDRESS_MASK_REQUEST:
1866 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1867 		    /* TODO m_pullup of complete header? */
1868 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1869 			interested = B_TRUE;
1870 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1871 		break;
1872 	case ICMP_ADDRESS_MASK_REPLY:
1873 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1874 		break;
1875 	default:
1876 		interested = B_TRUE;	/* Pass up to transport */
1877 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1878 		break;
1879 	}
1880 	/* See if there is an ICMP client. */
1881 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1882 		/* If there is an ICMP client and we want one too, copy it. */
1883 		mblk_t *first_mp1;
1884 
1885 		if (!interested) {
1886 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1887 			    ip_policy, recv_ill, zoneid);
1888 			return;
1889 		}
1890 		first_mp1 = ip_copymsg(first_mp);
1891 		if (first_mp1 != NULL) {
1892 			ip_fanout_proto(q, first_mp1, ill, ipha,
1893 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1894 		}
1895 	} else if (!interested) {
1896 		freemsg(first_mp);
1897 		return;
1898 	} else {
1899 		/*
1900 		 * Initiate policy processing for this packet if ip_policy
1901 		 * is true.
1902 		 */
1903 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1904 			ill_index = ill->ill_phyint->phyint_ifindex;
1905 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1906 			if (mp == NULL) {
1907 				if (mctl_present) {
1908 					freeb(first_mp);
1909 				}
1910 				BUMP_MIB(&icmp_mib, icmpInErrors);
1911 				return;
1912 			}
1913 		}
1914 	}
1915 	/* We want to do something with it. */
1916 	/* Check db_ref to make sure we can modify the packet. */
1917 	if (mp->b_datap->db_ref > 1) {
1918 		mblk_t	*first_mp1;
1919 
1920 		first_mp1 = ip_copymsg(first_mp);
1921 		freemsg(first_mp);
1922 		if (!first_mp1) {
1923 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1924 			return;
1925 		}
1926 		first_mp = first_mp1;
1927 		if (mctl_present) {
1928 			mp = first_mp->b_cont;
1929 			ASSERT(mp != NULL);
1930 		} else {
1931 			mp = first_mp;
1932 		}
1933 		ipha = (ipha_t *)mp->b_rptr;
1934 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1935 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1936 	}
1937 	switch (icmph->icmph_type) {
1938 	case ICMP_ADDRESS_MASK_REQUEST:
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		if (ipif == NULL) {
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		/*
1945 		 * outging interface must be IPv4
1946 		 */
1947 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1948 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1949 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1950 		ipif_refrele(ipif);
1951 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1952 		break;
1953 	case ICMP_ECHO_REQUEST:
1954 		icmph->icmph_type = ICMP_ECHO_REPLY;
1955 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1956 		break;
1957 	case ICMP_TIME_STAMP_REQUEST: {
1958 		uint32_t *tsp;
1959 
1960 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1961 		tsp = (uint32_t *)wptr;
1962 		tsp++;		/* Skip past 'originate time' */
1963 		/* Compute # of milliseconds since midnight */
1964 		gethrestime(&now);
1965 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1966 		    now.tv_nsec / (NANOSEC / MILLISEC);
1967 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1968 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1969 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1970 		break;
1971 	}
1972 	default:
1973 		ipha = (ipha_t *)&icmph[1];
1974 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1975 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1976 				BUMP_MIB(&ip_mib, ipInDiscards);
1977 				freemsg(first_mp);
1978 				return;
1979 			}
1980 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1981 			ipha = (ipha_t *)&icmph[1];
1982 		}
1983 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1984 			BUMP_MIB(&ip_mib, ipInDiscards);
1985 			freemsg(first_mp);
1986 			return;
1987 		}
1988 		hdr_length = IPH_HDR_LENGTH(ipha);
1989 		if (hdr_length < sizeof (ipha_t)) {
1990 			BUMP_MIB(&ip_mib, ipInDiscards);
1991 			freemsg(first_mp);
1992 			return;
1993 		}
1994 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1995 			if (!pullupmsg(mp,
1996 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1997 				BUMP_MIB(&ip_mib, ipInDiscards);
1998 				freemsg(first_mp);
1999 				return;
2000 			}
2001 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2002 			ipha = (ipha_t *)&icmph[1];
2003 		}
2004 		switch (icmph->icmph_type) {
2005 		case ICMP_REDIRECT:
2006 			/*
2007 			 * As there is no upper client to deliver, we don't
2008 			 * need the first_mp any more.
2009 			 */
2010 			if (mctl_present) {
2011 				freeb(first_mp);
2012 			}
2013 			icmp_redirect(mp);
2014 			return;
2015 		case ICMP_DEST_UNREACHABLE:
2016 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2017 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2018 				    zoneid, mp, iph_hdr_length)) {
2019 					freemsg(first_mp);
2020 					return;
2021 				}
2022 				/*
2023 				 * icmp_inbound_too_big() may alter mp.
2024 				 * Resynch ipha and icmph accordingly.
2025 				 */
2026 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2027 				ipha = (ipha_t *)&icmph[1];
2028 			}
2029 			/* FALLTHRU */
2030 		default :
2031 			/*
2032 			 * IPQoS notes: Since we have already done IPQoS
2033 			 * processing we don't want to do it again in
2034 			 * the fanout routines called by
2035 			 * icmp_inbound_error_fanout, hence the last
2036 			 * argument, ip_policy, is B_FALSE.
2037 			 */
2038 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2039 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2040 			    B_FALSE, recv_ill, zoneid);
2041 		}
2042 		return;
2043 	}
2044 	/* Send out an ICMP packet */
2045 	icmph->icmph_checksum = 0;
2046 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2047 	if (icmph->icmph_checksum == 0)
2048 		icmph->icmph_checksum = 0xFFFF;
2049 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2050 		ipif_t	*ipif_chosen;
2051 		/*
2052 		 * Make it look like it was directed to us, so we don't look
2053 		 * like a fool with a broadcast or multicast source address.
2054 		 */
2055 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2056 		/*
2057 		 * Make sure that we haven't grabbed an interface that's DOWN.
2058 		 */
2059 		if (ipif != NULL) {
2060 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2061 			    ipha->ipha_src, zoneid);
2062 			if (ipif_chosen != NULL) {
2063 				ipif_refrele(ipif);
2064 				ipif = ipif_chosen;
2065 			}
2066 		}
2067 		if (ipif == NULL) {
2068 			ip0dbg(("icmp_inbound: "
2069 			    "No source for broadcast/multicast:\n"
2070 			    "\tsrc 0x%x dst 0x%x ill %p "
2071 			    "ipif_lcl_addr 0x%x\n",
2072 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2073 			    (void *)ill,
2074 			    ill->ill_ipif->ipif_lcl_addr));
2075 			freemsg(first_mp);
2076 			return;
2077 		}
2078 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2079 		ipha->ipha_dst = ipif->ipif_src_addr;
2080 		ipif_refrele(ipif);
2081 	}
2082 	/* Reset time to live. */
2083 	ipha->ipha_ttl = ip_def_ttl;
2084 	{
2085 		/* Swap source and destination addresses */
2086 		ipaddr_t tmp;
2087 
2088 		tmp = ipha->ipha_src;
2089 		ipha->ipha_src = ipha->ipha_dst;
2090 		ipha->ipha_dst = tmp;
2091 	}
2092 	ipha->ipha_ident = 0;
2093 	if (!IS_SIMPLE_IPH(ipha))
2094 		icmp_options_update(ipha);
2095 
2096 	/*
2097 	 * ICMP echo replies should go out on the same interface
2098 	 * the request came on as probes used by in.mpathd for detecting
2099 	 * NIC failures are ECHO packets. We turn-off load spreading
2100 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2101 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2102 	 * function. This is in turn handled by ip_wput and ip_newroute
2103 	 * to make sure that the packet goes out on the interface it came
2104 	 * in on. If we don't turnoff load spreading, the packets might get
2105 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2106 	 * to go out and in.mpathd would wrongly detect a failure or
2107 	 * mis-detect a NIC failure for link failure. As load spreading
2108 	 * can happen only if ill_group is not NULL, we do only for
2109 	 * that case and this does not affect the normal case.
2110 	 *
2111 	 * We turn off load spreading only on echo packets that came from
2112 	 * on-link hosts. If the interface route has been deleted, this will
2113 	 * not be enforced as we can't do much. For off-link hosts, as the
2114 	 * default routes in IPv4 does not typically have an ire_ipif
2115 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2116 	 * Moreover, expecting a default route through this interface may
2117 	 * not be correct. We use ipha_dst because of the swap above.
2118 	 */
2119 	onlink = B_FALSE;
2120 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2121 		/*
2122 		 * First, we need to make sure that it is not one of our
2123 		 * local addresses. If we set onlink when it is one of
2124 		 * our local addresses, we will end up creating IRE_CACHES
2125 		 * for one of our local addresses. Then, we will never
2126 		 * accept packets for them afterwards.
2127 		 */
2128 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2129 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2130 		if (src_ire == NULL) {
2131 			ipif = ipif_get_next_ipif(NULL, ill);
2132 			if (ipif == NULL) {
2133 				BUMP_MIB(&ip_mib, ipInDiscards);
2134 				freemsg(mp);
2135 				return;
2136 			}
2137 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2138 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2139 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2140 			ipif_refrele(ipif);
2141 			if (src_ire != NULL) {
2142 				onlink = B_TRUE;
2143 				ire_refrele(src_ire);
2144 			}
2145 		} else {
2146 			ire_refrele(src_ire);
2147 		}
2148 	}
2149 	if (!mctl_present) {
2150 		/*
2151 		 * This packet should go out the same way as it
2152 		 * came in i.e in clear. To make sure that global
2153 		 * policy will not be applied to this in ip_wput_ire,
2154 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2155 		 */
2156 		ASSERT(first_mp == mp);
2157 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2158 			BUMP_MIB(&ip_mib, ipInDiscards);
2159 			freemsg(mp);
2160 			return;
2161 		}
2162 		ii = (ipsec_in_t *)first_mp->b_rptr;
2163 
2164 		/* This is not a secure packet */
2165 		ii->ipsec_in_secure = B_FALSE;
2166 		if (onlink) {
2167 			ii->ipsec_in_attach_if = B_TRUE;
2168 			ii->ipsec_in_ill_index =
2169 			    ill->ill_phyint->phyint_ifindex;
2170 			ii->ipsec_in_rill_index =
2171 			    recv_ill->ill_phyint->phyint_ifindex;
2172 		}
2173 		first_mp->b_cont = mp;
2174 	} else if (onlink) {
2175 		ii = (ipsec_in_t *)first_mp->b_rptr;
2176 		ii->ipsec_in_attach_if = B_TRUE;
2177 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2178 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2179 	} else {
2180 		ii = (ipsec_in_t *)first_mp->b_rptr;
2181 	}
2182 	ii->ipsec_in_zoneid = zoneid;
2183 	ASSERT(zoneid != ALL_ZONES);
2184 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2185 		BUMP_MIB(&ip_mib, ipInDiscards);
2186 		return;
2187 	}
2188 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2189 	put(WR(q), first_mp);
2190 }
2191 
2192 static ipaddr_t
2193 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2194 {
2195 	conn_t *connp;
2196 	connf_t *connfp;
2197 	ipaddr_t nexthop_addr = INADDR_ANY;
2198 	int hdr_length = IPH_HDR_LENGTH(ipha);
2199 	uint16_t *up;
2200 	uint32_t ports;
2201 
2202 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2203 	switch (ipha->ipha_protocol) {
2204 		case IPPROTO_TCP:
2205 		{
2206 			tcph_t *tcph;
2207 
2208 			/* do a reverse lookup */
2209 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2210 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2211 			    TCPS_LISTEN);
2212 			break;
2213 		}
2214 		case IPPROTO_UDP:
2215 		{
2216 			uint32_t dstport, srcport;
2217 
2218 			((uint16_t *)&ports)[0] = up[1];
2219 			((uint16_t *)&ports)[1] = up[0];
2220 
2221 			/* Extract ports in net byte order */
2222 			dstport = htons(ntohl(ports) & 0xFFFF);
2223 			srcport = htons(ntohl(ports) >> 16);
2224 
2225 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2226 			mutex_enter(&connfp->connf_lock);
2227 			connp = connfp->connf_head;
2228 
2229 			/* do a reverse lookup */
2230 			while ((connp != NULL) &&
2231 			    (!IPCL_UDP_MATCH(connp, dstport,
2232 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2233 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2234 				connp = connp->conn_next;
2235 			}
2236 			if (connp != NULL)
2237 				CONN_INC_REF(connp);
2238 			mutex_exit(&connfp->connf_lock);
2239 			break;
2240 		}
2241 		case IPPROTO_SCTP:
2242 		{
2243 			in6_addr_t map_src, map_dst;
2244 
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2246 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2247 			((uint16_t *)&ports)[0] = up[1];
2248 			((uint16_t *)&ports)[1] = up[0];
2249 
2250 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2251 			    0, zoneid)) == NULL) {
2252 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2253 				    zoneid, ports, ipha);
2254 			} else {
2255 				CONN_INC_REF(connp);
2256 				SCTP_REFRELE(CONN2SCTP(connp));
2257 			}
2258 			break;
2259 		}
2260 		default:
2261 		{
2262 			ipha_t ripha;
2263 
2264 			ripha.ipha_src = ipha->ipha_dst;
2265 			ripha.ipha_dst = ipha->ipha_src;
2266 			ripha.ipha_protocol = ipha->ipha_protocol;
2267 
2268 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2269 			mutex_enter(&connfp->connf_lock);
2270 			connp = connfp->connf_head;
2271 			for (connp = connfp->connf_head; connp != NULL;
2272 			    connp = connp->conn_next) {
2273 				if (IPCL_PROTO_MATCH(connp,
2274 				    ipha->ipha_protocol, &ripha, ill,
2275 				    0, zoneid)) {
2276 					CONN_INC_REF(connp);
2277 					break;
2278 				}
2279 			}
2280 			mutex_exit(&connfp->connf_lock);
2281 		}
2282 	}
2283 	if (connp != NULL) {
2284 		if (connp->conn_nexthop_set)
2285 			nexthop_addr = connp->conn_nexthop_v4;
2286 		CONN_DEC_REF(connp);
2287 	}
2288 	return (nexthop_addr);
2289 }
2290 
2291 /* Table from RFC 1191 */
2292 static int icmp_frag_size_table[] =
2293 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2294 
2295 /*
2296  * Process received ICMP Packet too big.
2297  * After updating any IRE it does the fanout to any matching transport streams.
2298  * Assumes the message has been pulled up till the IP header that caused
2299  * the error.
2300  *
2301  * Returns B_FALSE on failure and B_TRUE on success.
2302  */
2303 static boolean_t
2304 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2305     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2306 {
2307 	ire_t	*ire, *first_ire;
2308 	int	mtu;
2309 	int	hdr_length;
2310 	ipaddr_t nexthop_addr;
2311 
2312 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2313 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2314 
2315 	hdr_length = IPH_HDR_LENGTH(ipha);
2316 
2317 	/* Drop if the original packet contained a source route */
2318 	if (ip_source_route_included(ipha)) {
2319 		return (B_FALSE);
2320 	}
2321 	/*
2322 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2323 	 * header.
2324 	 */
2325 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2326 	    mp->b_wptr) {
2327 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2328 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2329 			BUMP_MIB(&ip_mib, ipInDiscards);
2330 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2331 			return (B_FALSE);
2332 		}
2333 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2334 		ipha = (ipha_t *)&icmph[1];
2335 	}
2336 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2337 	if (nexthop_addr != INADDR_ANY) {
2338 		/* nexthop set */
2339 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2340 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2341 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2342 	} else {
2343 		/* nexthop not set */
2344 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2345 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2346 	}
2347 
2348 	if (!first_ire) {
2349 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2350 		    ntohl(ipha->ipha_dst)));
2351 		return (B_FALSE);
2352 	}
2353 	/* Check for MTU discovery advice as described in RFC 1191 */
2354 	mtu = ntohs(icmph->icmph_du_mtu);
2355 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2356 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2357 	    ire = ire->ire_next) {
2358 		/*
2359 		 * Look for the connection to which this ICMP message is
2360 		 * directed. If it has the IP_NEXTHOP option set, then the
2361 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2362 		 * option. Else the search is limited to regular IREs.
2363 		 */
2364 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2365 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2366 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2367 		    (nexthop_addr != INADDR_ANY)))
2368 			continue;
2369 
2370 		mutex_enter(&ire->ire_lock);
2371 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2372 			/* Reduce the IRE max frag value as advised. */
2373 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2374 			    mtu, ire->ire_max_frag));
2375 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2376 		} else {
2377 			uint32_t length;
2378 			int	i;
2379 
2380 			/*
2381 			 * Use the table from RFC 1191 to figure out
2382 			 * the next "plateau" based on the length in
2383 			 * the original IP packet.
2384 			 */
2385 			length = ntohs(ipha->ipha_length);
2386 			if (ire->ire_max_frag <= length &&
2387 			    ire->ire_max_frag >= length - hdr_length) {
2388 				/*
2389 				 * Handle broken BSD 4.2 systems that
2390 				 * return the wrong iph_length in ICMP
2391 				 * errors.
2392 				 */
2393 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2394 				    length, ire->ire_max_frag));
2395 				length -= hdr_length;
2396 			}
2397 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2398 				if (length > icmp_frag_size_table[i])
2399 					break;
2400 			}
2401 			if (i == A_CNT(icmp_frag_size_table)) {
2402 				/* Smaller than 68! */
2403 				ip1dbg(("Too big for packet size %d\n",
2404 				    length));
2405 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2406 				ire->ire_frag_flag = 0;
2407 			} else {
2408 				mtu = icmp_frag_size_table[i];
2409 				ip1dbg(("Calculated mtu %d, packet size %d, "
2410 				    "before %d", mtu, length,
2411 				    ire->ire_max_frag));
2412 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2413 				ip1dbg((", after %d\n", ire->ire_max_frag));
2414 			}
2415 			/* Record the new max frag size for the ULP. */
2416 			icmph->icmph_du_zero = 0;
2417 			icmph->icmph_du_mtu =
2418 			    htons((uint16_t)ire->ire_max_frag);
2419 		}
2420 		mutex_exit(&ire->ire_lock);
2421 	}
2422 	rw_exit(&first_ire->ire_bucket->irb_lock);
2423 	ire_refrele(first_ire);
2424 	return (B_TRUE);
2425 }
2426 
2427 /*
2428  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2429  * calls this function.
2430  */
2431 static mblk_t *
2432 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2433 {
2434 	ipha_t *ipha;
2435 	icmph_t *icmph;
2436 	ipha_t *in_ipha;
2437 	int length;
2438 
2439 	ASSERT(mp->b_datap->db_type == M_DATA);
2440 
2441 	/*
2442 	 * For Self-encapsulated packets, we added an extra IP header
2443 	 * without the options. Inner IP header is the one from which
2444 	 * the outer IP header was formed. Thus, we need to remove the
2445 	 * outer IP header. To do this, we pullup the whole message
2446 	 * and overlay whatever follows the outer IP header over the
2447 	 * outer IP header.
2448 	 */
2449 
2450 	if (!pullupmsg(mp, -1)) {
2451 		BUMP_MIB(&ip_mib, ipInDiscards);
2452 		return (NULL);
2453 	}
2454 
2455 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2456 	ipha = (ipha_t *)&icmph[1];
2457 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2458 
2459 	/*
2460 	 * The length that we want to overlay is following the inner
2461 	 * IP header. Subtracting the IP header + icmp header + outer
2462 	 * IP header's length should give us the length that we want to
2463 	 * overlay.
2464 	 */
2465 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2466 	    hdr_length;
2467 	/*
2468 	 * Overlay whatever follows the inner header over the
2469 	 * outer header.
2470 	 */
2471 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2472 
2473 	/* Set the wptr to account for the outer header */
2474 	mp->b_wptr -= hdr_length;
2475 	return (mp);
2476 }
2477 
2478 /*
2479  * Try to pass the ICMP message upstream in case the ULP cares.
2480  *
2481  * If the packet that caused the ICMP error is secure, we send
2482  * it to AH/ESP to make sure that the attached packet has a
2483  * valid association. ipha in the code below points to the
2484  * IP header of the packet that caused the error.
2485  *
2486  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2487  * in the context of IPSEC. Normally we tell the upper layer
2488  * whenever we send the ire (including ip_bind), the IPSEC header
2489  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2490  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2491  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2492  * same thing. As TCP has the IPSEC options size that needs to be
2493  * adjusted, we just pass the MTU unchanged.
2494  *
2495  * IFN could have been generated locally or by some router.
2496  *
2497  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2498  *	    This happens because IP adjusted its value of MTU on an
2499  *	    earlier IFN message and could not tell the upper layer,
2500  *	    the new adjusted value of MTU e.g. Packet was encrypted
2501  *	    or there was not enough information to fanout to upper
2502  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2503  *	    generates the IFN, where IPSEC processing has *not* been
2504  *	    done.
2505  *
2506  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2507  *	    could have generated this. This happens because ire_max_frag
2508  *	    value in IP was set to a new value, while the IPSEC processing
2509  *	    was being done and after we made the fragmentation check in
2510  *	    ip_wput_ire. Thus on return from IPSEC processing,
2511  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2512  *	    and generates the IFN. As IPSEC processing is over, we fanout
2513  *	    to AH/ESP to remove the header.
2514  *
2515  *	    In both these cases, ipsec_in_loopback will be set indicating
2516  *	    that IFN was generated locally.
2517  *
2518  * ROUTER : IFN could be secure or non-secure.
2519  *
2520  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2521  *	      packet in error has AH/ESP headers to validate the AH/ESP
2522  *	      headers. AH/ESP will verify whether there is a valid SA or
2523  *	      not and send it back. We will fanout again if we have more
2524  *	      data in the packet.
2525  *
2526  *	      If the packet in error does not have AH/ESP, we handle it
2527  *	      like any other case.
2528  *
2529  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2530  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2531  *	      for validation. AH/ESP will verify whether there is a
2532  *	      valid SA or not and send it back. We will fanout again if
2533  *	      we have more data in the packet.
2534  *
2535  *	      If the packet in error does not have AH/ESP, we handle it
2536  *	      like any other case.
2537  */
2538 static void
2539 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2540     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2541     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2542     zoneid_t zoneid)
2543 {
2544 	uint16_t *up;	/* Pointer to ports in ULP header */
2545 	uint32_t ports;	/* reversed ports for fanout */
2546 	ipha_t ripha;	/* With reversed addresses */
2547 	mblk_t *first_mp;
2548 	ipsec_in_t *ii;
2549 	tcph_t	*tcph;
2550 	conn_t	*connp;
2551 
2552 	first_mp = mp;
2553 	if (mctl_present) {
2554 		mp = first_mp->b_cont;
2555 		ASSERT(mp != NULL);
2556 
2557 		ii = (ipsec_in_t *)first_mp->b_rptr;
2558 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2559 	} else {
2560 		ii = NULL;
2561 	}
2562 
2563 	switch (ipha->ipha_protocol) {
2564 	case IPPROTO_UDP:
2565 		/*
2566 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2567 		 * transport header.
2568 		 */
2569 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2570 		    mp->b_wptr) {
2571 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2572 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2573 				BUMP_MIB(&ip_mib, ipInDiscards);
2574 				goto drop_pkt;
2575 			}
2576 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2577 			ipha = (ipha_t *)&icmph[1];
2578 		}
2579 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2580 
2581 		/*
2582 		 * Attempt to find a client stream based on port.
2583 		 * Note that we do a reverse lookup since the header is
2584 		 * in the form we sent it out.
2585 		 * The ripha header is only used for the IP_UDP_MATCH and we
2586 		 * only set the src and dst addresses and protocol.
2587 		 */
2588 		ripha.ipha_src = ipha->ipha_dst;
2589 		ripha.ipha_dst = ipha->ipha_src;
2590 		ripha.ipha_protocol = ipha->ipha_protocol;
2591 		((uint16_t *)&ports)[0] = up[1];
2592 		((uint16_t *)&ports)[1] = up[0];
2593 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2594 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2595 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2596 		    icmph->icmph_type, icmph->icmph_code));
2597 
2598 		/* Have to change db_type after any pullupmsg */
2599 		DB_TYPE(mp) = M_CTL;
2600 
2601 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2602 		    mctl_present, ip_policy, recv_ill, zoneid);
2603 		return;
2604 
2605 	case IPPROTO_TCP:
2606 		/*
2607 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2608 		 * transport header.
2609 		 */
2610 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2611 		    mp->b_wptr) {
2612 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2613 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2614 				BUMP_MIB(&ip_mib, ipInDiscards);
2615 				goto drop_pkt;
2616 			}
2617 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2618 			ipha = (ipha_t *)&icmph[1];
2619 		}
2620 		/*
2621 		 * Find a TCP client stream for this packet.
2622 		 * Note that we do a reverse lookup since the header is
2623 		 * in the form we sent it out.
2624 		 */
2625 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2626 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2627 		if (connp == NULL) {
2628 			BUMP_MIB(&ip_mib, ipInDiscards);
2629 			goto drop_pkt;
2630 		}
2631 
2632 		/* Have to change db_type after any pullupmsg */
2633 		DB_TYPE(mp) = M_CTL;
2634 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2635 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2636 		return;
2637 
2638 	case IPPROTO_SCTP:
2639 		/*
2640 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2641 		 * transport header.
2642 		 */
2643 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2644 		    mp->b_wptr) {
2645 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2646 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2647 				BUMP_MIB(&ip_mib, ipInDiscards);
2648 				goto drop_pkt;
2649 			}
2650 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2651 			ipha = (ipha_t *)&icmph[1];
2652 		}
2653 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2654 		/*
2655 		 * Find a SCTP client stream for this packet.
2656 		 * Note that we do a reverse lookup since the header is
2657 		 * in the form we sent it out.
2658 		 * The ripha header is only used for the matching and we
2659 		 * only set the src and dst addresses, protocol, and version.
2660 		 */
2661 		ripha.ipha_src = ipha->ipha_dst;
2662 		ripha.ipha_dst = ipha->ipha_src;
2663 		ripha.ipha_protocol = ipha->ipha_protocol;
2664 		ripha.ipha_version_and_hdr_length =
2665 		    ipha->ipha_version_and_hdr_length;
2666 		((uint16_t *)&ports)[0] = up[1];
2667 		((uint16_t *)&ports)[1] = up[0];
2668 
2669 		/* Have to change db_type after any pullupmsg */
2670 		DB_TYPE(mp) = M_CTL;
2671 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2672 		    mctl_present, ip_policy, 0, zoneid);
2673 		return;
2674 
2675 	case IPPROTO_ESP:
2676 	case IPPROTO_AH: {
2677 		int ipsec_rc;
2678 
2679 		/*
2680 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2681 		 * We will re-use the IPSEC_IN if it is already present as
2682 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2683 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2684 		 * one and attach it in the front.
2685 		 */
2686 		if (ii != NULL) {
2687 			/*
2688 			 * ip_fanout_proto_again converts the ICMP errors
2689 			 * that come back from AH/ESP to M_DATA so that
2690 			 * if it is non-AH/ESP and we do a pullupmsg in
2691 			 * this function, it would work. Convert it back
2692 			 * to M_CTL before we send up as this is a ICMP
2693 			 * error. This could have been generated locally or
2694 			 * by some router. Validate the inner IPSEC
2695 			 * headers.
2696 			 *
2697 			 * NOTE : ill_index is used by ip_fanout_proto_again
2698 			 * to locate the ill.
2699 			 */
2700 			ASSERT(ill != NULL);
2701 			ii->ipsec_in_ill_index =
2702 			    ill->ill_phyint->phyint_ifindex;
2703 			ii->ipsec_in_rill_index =
2704 			    recv_ill->ill_phyint->phyint_ifindex;
2705 			DB_TYPE(first_mp->b_cont) = M_CTL;
2706 		} else {
2707 			/*
2708 			 * IPSEC_IN is not present. We attach a ipsec_in
2709 			 * message and send up to IPSEC for validating
2710 			 * and removing the IPSEC headers. Clear
2711 			 * ipsec_in_secure so that when we return
2712 			 * from IPSEC, we don't mistakenly think that this
2713 			 * is a secure packet came from the network.
2714 			 *
2715 			 * NOTE : ill_index is used by ip_fanout_proto_again
2716 			 * to locate the ill.
2717 			 */
2718 			ASSERT(first_mp == mp);
2719 			first_mp = ipsec_in_alloc(B_TRUE);
2720 			if (first_mp == NULL) {
2721 				freemsg(mp);
2722 				BUMP_MIB(&ip_mib, ipInDiscards);
2723 				return;
2724 			}
2725 			ii = (ipsec_in_t *)first_mp->b_rptr;
2726 
2727 			/* This is not a secure packet */
2728 			ii->ipsec_in_secure = B_FALSE;
2729 			first_mp->b_cont = mp;
2730 			DB_TYPE(mp) = M_CTL;
2731 			ASSERT(ill != NULL);
2732 			ii->ipsec_in_ill_index =
2733 			    ill->ill_phyint->phyint_ifindex;
2734 			ii->ipsec_in_rill_index =
2735 			    recv_ill->ill_phyint->phyint_ifindex;
2736 		}
2737 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2738 
2739 		if (!ipsec_loaded()) {
2740 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2741 			return;
2742 		}
2743 
2744 		if (ipha->ipha_protocol == IPPROTO_ESP)
2745 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2746 		else
2747 			ipsec_rc = ipsecah_icmp_error(first_mp);
2748 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2749 			return;
2750 
2751 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2752 		return;
2753 	}
2754 	default:
2755 		/*
2756 		 * The ripha header is only used for the lookup and we
2757 		 * only set the src and dst addresses and protocol.
2758 		 */
2759 		ripha.ipha_src = ipha->ipha_dst;
2760 		ripha.ipha_dst = ipha->ipha_src;
2761 		ripha.ipha_protocol = ipha->ipha_protocol;
2762 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2763 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2764 		    ntohl(ipha->ipha_dst),
2765 		    icmph->icmph_type, icmph->icmph_code));
2766 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2767 			ipha_t *in_ipha;
2768 
2769 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2770 			    mp->b_wptr) {
2771 				if (!pullupmsg(mp, (uchar_t *)ipha +
2772 				    hdr_length + sizeof (ipha_t) -
2773 				    mp->b_rptr)) {
2774 
2775 					BUMP_MIB(&ip_mib, ipInDiscards);
2776 					goto drop_pkt;
2777 				}
2778 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2779 				ipha = (ipha_t *)&icmph[1];
2780 			}
2781 			/*
2782 			 * Caller has verified that length has to be
2783 			 * at least the size of IP header.
2784 			 */
2785 			ASSERT(hdr_length >= sizeof (ipha_t));
2786 			/*
2787 			 * Check the sanity of the inner IP header like
2788 			 * we did for the outer header.
2789 			 */
2790 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2791 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2792 				BUMP_MIB(&ip_mib, ipInDiscards);
2793 				goto drop_pkt;
2794 			}
2795 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2796 				BUMP_MIB(&ip_mib, ipInDiscards);
2797 				goto drop_pkt;
2798 			}
2799 			/* Check for Self-encapsulated tunnels */
2800 			if (in_ipha->ipha_src == ipha->ipha_src &&
2801 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2802 
2803 				mp = icmp_inbound_self_encap_error(mp,
2804 				    iph_hdr_length, hdr_length);
2805 				if (mp == NULL)
2806 					goto drop_pkt;
2807 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2808 				ipha = (ipha_t *)&icmph[1];
2809 				hdr_length = IPH_HDR_LENGTH(ipha);
2810 				/*
2811 				 * The packet in error is self-encapsualted.
2812 				 * And we are finding it further encapsulated
2813 				 * which we could not have possibly generated.
2814 				 */
2815 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2816 					BUMP_MIB(&ip_mib, ipInDiscards);
2817 					goto drop_pkt;
2818 				}
2819 				icmp_inbound_error_fanout(q, ill, first_mp,
2820 				    icmph, ipha, iph_hdr_length, hdr_length,
2821 				    mctl_present, ip_policy, recv_ill, zoneid);
2822 				return;
2823 			}
2824 		}
2825 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2826 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2827 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2828 		    ii != NULL &&
2829 		    ii->ipsec_in_loopback &&
2830 		    ii->ipsec_in_secure) {
2831 			/*
2832 			 * For IP tunnels that get a looped-back
2833 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2834 			 * reported new MTU to take into account the IPsec
2835 			 * headers protecting this configured tunnel.
2836 			 *
2837 			 * This allows the tunnel module (tun.c) to blindly
2838 			 * accept the MTU reported in an ICMP "too big"
2839 			 * message.
2840 			 *
2841 			 * Non-looped back ICMP messages will just be
2842 			 * handled by the security protocols (if needed),
2843 			 * and the first subsequent packet will hit this
2844 			 * path.
2845 			 */
2846 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2847 			    ipsec_in_extra_length(first_mp));
2848 		}
2849 		/* Have to change db_type after any pullupmsg */
2850 		DB_TYPE(mp) = M_CTL;
2851 
2852 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2853 		    ip_policy, recv_ill, zoneid);
2854 		return;
2855 	}
2856 	/* NOTREACHED */
2857 drop_pkt:;
2858 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2859 	freemsg(first_mp);
2860 }
2861 
2862 /*
2863  * Common IP options parser.
2864  *
2865  * Setup routine: fill in *optp with options-parsing state, then
2866  * tail-call ipoptp_next to return the first option.
2867  */
2868 uint8_t
2869 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2870 {
2871 	uint32_t totallen; /* total length of all options */
2872 
2873 	totallen = ipha->ipha_version_and_hdr_length -
2874 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2875 	totallen <<= 2;
2876 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2877 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2878 	optp->ipoptp_flags = 0;
2879 	return (ipoptp_next(optp));
2880 }
2881 
2882 /*
2883  * Common IP options parser: extract next option.
2884  */
2885 uint8_t
2886 ipoptp_next(ipoptp_t *optp)
2887 {
2888 	uint8_t *end = optp->ipoptp_end;
2889 	uint8_t *cur = optp->ipoptp_next;
2890 	uint8_t opt, len, pointer;
2891 
2892 	/*
2893 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2894 	 * has been corrupted.
2895 	 */
2896 	ASSERT(cur <= end);
2897 
2898 	if (cur == end)
2899 		return (IPOPT_EOL);
2900 
2901 	opt = cur[IPOPT_OPTVAL];
2902 
2903 	/*
2904 	 * Skip any NOP options.
2905 	 */
2906 	while (opt == IPOPT_NOP) {
2907 		cur++;
2908 		if (cur == end)
2909 			return (IPOPT_EOL);
2910 		opt = cur[IPOPT_OPTVAL];
2911 	}
2912 
2913 	if (opt == IPOPT_EOL)
2914 		return (IPOPT_EOL);
2915 
2916 	/*
2917 	 * Option requiring a length.
2918 	 */
2919 	if ((cur + 1) >= end) {
2920 		optp->ipoptp_flags |= IPOPTP_ERROR;
2921 		return (IPOPT_EOL);
2922 	}
2923 	len = cur[IPOPT_OLEN];
2924 	if (len < 2) {
2925 		optp->ipoptp_flags |= IPOPTP_ERROR;
2926 		return (IPOPT_EOL);
2927 	}
2928 	optp->ipoptp_cur = cur;
2929 	optp->ipoptp_len = len;
2930 	optp->ipoptp_next = cur + len;
2931 	if (cur + len > end) {
2932 		optp->ipoptp_flags |= IPOPTP_ERROR;
2933 		return (IPOPT_EOL);
2934 	}
2935 
2936 	/*
2937 	 * For the options which require a pointer field, make sure
2938 	 * its there, and make sure it points to either something
2939 	 * inside this option, or the end of the option.
2940 	 */
2941 	switch (opt) {
2942 	case IPOPT_RR:
2943 	case IPOPT_TS:
2944 	case IPOPT_LSRR:
2945 	case IPOPT_SSRR:
2946 		if (len <= IPOPT_OFFSET) {
2947 			optp->ipoptp_flags |= IPOPTP_ERROR;
2948 			return (opt);
2949 		}
2950 		pointer = cur[IPOPT_OFFSET];
2951 		if (pointer - 1 > len) {
2952 			optp->ipoptp_flags |= IPOPTP_ERROR;
2953 			return (opt);
2954 		}
2955 		break;
2956 	}
2957 
2958 	/*
2959 	 * Sanity check the pointer field based on the type of the
2960 	 * option.
2961 	 */
2962 	switch (opt) {
2963 	case IPOPT_RR:
2964 	case IPOPT_SSRR:
2965 	case IPOPT_LSRR:
2966 		if (pointer < IPOPT_MINOFF_SR)
2967 			optp->ipoptp_flags |= IPOPTP_ERROR;
2968 		break;
2969 	case IPOPT_TS:
2970 		if (pointer < IPOPT_MINOFF_IT)
2971 			optp->ipoptp_flags |= IPOPTP_ERROR;
2972 		/*
2973 		 * Note that the Internet Timestamp option also
2974 		 * contains two four bit fields (the Overflow field,
2975 		 * and the Flag field), which follow the pointer
2976 		 * field.  We don't need to check that these fields
2977 		 * fall within the length of the option because this
2978 		 * was implicitely done above.  We've checked that the
2979 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2980 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2981 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2982 		 */
2983 		ASSERT(len > IPOPT_POS_OV_FLG);
2984 		break;
2985 	}
2986 
2987 	return (opt);
2988 }
2989 
2990 /*
2991  * Use the outgoing IP header to create an IP_OPTIONS option the way
2992  * it was passed down from the application.
2993  */
2994 int
2995 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2996 {
2997 	ipoptp_t	opts;
2998 	const uchar_t	*opt;
2999 	uint8_t		optval;
3000 	uint8_t		optlen;
3001 	uint32_t	len = 0;
3002 	uchar_t	*buf1 = buf;
3003 
3004 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3005 	len += IP_ADDR_LEN;
3006 	bzero(buf1, IP_ADDR_LEN);
3007 
3008 	/*
3009 	 * OK to cast away const here, as we don't store through the returned
3010 	 * opts.ipoptp_cur pointer.
3011 	 */
3012 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3013 	    optval != IPOPT_EOL;
3014 	    optval = ipoptp_next(&opts)) {
3015 		int	off;
3016 
3017 		opt = opts.ipoptp_cur;
3018 		optlen = opts.ipoptp_len;
3019 		switch (optval) {
3020 		case IPOPT_SSRR:
3021 		case IPOPT_LSRR:
3022 
3023 			/*
3024 			 * Insert ipha_dst as the first entry in the source
3025 			 * route and move down the entries on step.
3026 			 * The last entry gets placed at buf1.
3027 			 */
3028 			buf[IPOPT_OPTVAL] = optval;
3029 			buf[IPOPT_OLEN] = optlen;
3030 			buf[IPOPT_OFFSET] = optlen;
3031 
3032 			off = optlen - IP_ADDR_LEN;
3033 			if (off < 0) {
3034 				/* No entries in source route */
3035 				break;
3036 			}
3037 			/* Last entry in source route */
3038 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3039 			off -= IP_ADDR_LEN;
3040 
3041 			while (off > 0) {
3042 				bcopy(opt + off,
3043 				    buf + off + IP_ADDR_LEN,
3044 				    IP_ADDR_LEN);
3045 				off -= IP_ADDR_LEN;
3046 			}
3047 			/* ipha_dst into first slot */
3048 			bcopy(&ipha->ipha_dst,
3049 			    buf + off + IP_ADDR_LEN,
3050 			    IP_ADDR_LEN);
3051 			buf += optlen;
3052 			len += optlen;
3053 			break;
3054 
3055 		case IPOPT_COMSEC:
3056 		case IPOPT_SECURITY:
3057 			/* if passing up a label is not ok, then remove */
3058 			if (is_system_labeled())
3059 				break;
3060 			/* FALLTHROUGH */
3061 		default:
3062 			bcopy(opt, buf, optlen);
3063 			buf += optlen;
3064 			len += optlen;
3065 			break;
3066 		}
3067 	}
3068 done:
3069 	/* Pad the resulting options */
3070 	while (len & 0x3) {
3071 		*buf++ = IPOPT_EOL;
3072 		len++;
3073 	}
3074 	return (len);
3075 }
3076 
3077 /*
3078  * Update any record route or timestamp options to include this host.
3079  * Reverse any source route option.
3080  * This routine assumes that the options are well formed i.e. that they
3081  * have already been checked.
3082  */
3083 static void
3084 icmp_options_update(ipha_t *ipha)
3085 {
3086 	ipoptp_t	opts;
3087 	uchar_t		*opt;
3088 	uint8_t		optval;
3089 	ipaddr_t	src;		/* Our local address */
3090 	ipaddr_t	dst;
3091 
3092 	ip2dbg(("icmp_options_update\n"));
3093 	src = ipha->ipha_src;
3094 	dst = ipha->ipha_dst;
3095 
3096 	for (optval = ipoptp_first(&opts, ipha);
3097 	    optval != IPOPT_EOL;
3098 	    optval = ipoptp_next(&opts)) {
3099 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3100 		opt = opts.ipoptp_cur;
3101 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3102 		    optval, opts.ipoptp_len));
3103 		switch (optval) {
3104 			int off1, off2;
3105 		case IPOPT_SSRR:
3106 		case IPOPT_LSRR:
3107 			/*
3108 			 * Reverse the source route.  The first entry
3109 			 * should be the next to last one in the current
3110 			 * source route (the last entry is our address).
3111 			 * The last entry should be the final destination.
3112 			 */
3113 			off1 = IPOPT_MINOFF_SR - 1;
3114 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3115 			if (off2 < 0) {
3116 				/* No entries in source route */
3117 				ip1dbg((
3118 				    "icmp_options_update: bad src route\n"));
3119 				break;
3120 			}
3121 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3122 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3123 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3124 			off2 -= IP_ADDR_LEN;
3125 
3126 			while (off1 < off2) {
3127 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3128 				bcopy((char *)opt + off2, (char *)opt + off1,
3129 				    IP_ADDR_LEN);
3130 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3131 				off1 += IP_ADDR_LEN;
3132 				off2 -= IP_ADDR_LEN;
3133 			}
3134 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3135 			break;
3136 		}
3137 	}
3138 }
3139 
3140 /*
3141  * Process received ICMP Redirect messages.
3142  */
3143 /* ARGSUSED */
3144 static void
3145 icmp_redirect(mblk_t *mp)
3146 {
3147 	ipha_t	*ipha;
3148 	int	iph_hdr_length;
3149 	icmph_t	*icmph;
3150 	ipha_t	*ipha_err;
3151 	ire_t	*ire;
3152 	ire_t	*prev_ire;
3153 	ire_t	*save_ire;
3154 	ipaddr_t  src, dst, gateway;
3155 	iulp_t	ulp_info = { 0 };
3156 	int	error;
3157 
3158 	ipha = (ipha_t *)mp->b_rptr;
3159 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3160 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3161 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3162 		BUMP_MIB(&icmp_mib, icmpInErrors);
3163 		freemsg(mp);
3164 		return;
3165 	}
3166 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3167 	ipha_err = (ipha_t *)&icmph[1];
3168 	src = ipha->ipha_src;
3169 	dst = ipha_err->ipha_dst;
3170 	gateway = icmph->icmph_rd_gateway;
3171 	/* Make sure the new gateway is reachable somehow. */
3172 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3173 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3174 	/*
3175 	 * Make sure we had a route for the dest in question and that
3176 	 * that route was pointing to the old gateway (the source of the
3177 	 * redirect packet.)
3178 	 */
3179 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3180 	    NULL, MATCH_IRE_GW);
3181 	/*
3182 	 * Check that
3183 	 *	the redirect was not from ourselves
3184 	 *	the new gateway and the old gateway are directly reachable
3185 	 */
3186 	if (!prev_ire ||
3187 	    !ire ||
3188 	    ire->ire_type == IRE_LOCAL) {
3189 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3190 		freemsg(mp);
3191 		if (ire != NULL)
3192 			ire_refrele(ire);
3193 		if (prev_ire != NULL)
3194 			ire_refrele(prev_ire);
3195 		return;
3196 	}
3197 
3198 	/*
3199 	 * Should we use the old ULP info to create the new gateway?  From
3200 	 * a user's perspective, we should inherit the info so that it
3201 	 * is a "smooth" transition.  If we do not do that, then new
3202 	 * connections going thru the new gateway will have no route metrics,
3203 	 * which is counter-intuitive to user.  From a network point of
3204 	 * view, this may or may not make sense even though the new gateway
3205 	 * is still directly connected to us so the route metrics should not
3206 	 * change much.
3207 	 *
3208 	 * But if the old ire_uinfo is not initialized, we do another
3209 	 * recursive lookup on the dest using the new gateway.  There may
3210 	 * be a route to that.  If so, use it to initialize the redirect
3211 	 * route.
3212 	 */
3213 	if (prev_ire->ire_uinfo.iulp_set) {
3214 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3215 	} else {
3216 		ire_t *tmp_ire;
3217 		ire_t *sire;
3218 
3219 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3220 		    ALL_ZONES, 0, NULL,
3221 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3222 		if (sire != NULL) {
3223 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3224 			/*
3225 			 * If sire != NULL, ire_ftable_lookup() should not
3226 			 * return a NULL value.
3227 			 */
3228 			ASSERT(tmp_ire != NULL);
3229 			ire_refrele(tmp_ire);
3230 			ire_refrele(sire);
3231 		} else if (tmp_ire != NULL) {
3232 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3233 			    sizeof (iulp_t));
3234 			ire_refrele(tmp_ire);
3235 		}
3236 	}
3237 	if (prev_ire->ire_type == IRE_CACHE)
3238 		ire_delete(prev_ire);
3239 	ire_refrele(prev_ire);
3240 	/*
3241 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3242 	 * require TOS routing
3243 	 */
3244 	switch (icmph->icmph_code) {
3245 	case 0:
3246 	case 1:
3247 		/* TODO: TOS specificity for cases 2 and 3 */
3248 	case 2:
3249 	case 3:
3250 		break;
3251 	default:
3252 		freemsg(mp);
3253 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3254 		ire_refrele(ire);
3255 		return;
3256 	}
3257 	/*
3258 	 * Create a Route Association.  This will allow us to remember that
3259 	 * someone we believe told us to use the particular gateway.
3260 	 */
3261 	save_ire = ire;
3262 	ire = ire_create(
3263 		(uchar_t *)&dst,			/* dest addr */
3264 		(uchar_t *)&ip_g_all_ones,		/* mask */
3265 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3266 		(uchar_t *)&gateway,			/* gateway addr */
3267 		NULL,					/* no in_srcaddr */
3268 		&save_ire->ire_max_frag,		/* max frag */
3269 		NULL,					/* Fast Path header */
3270 		NULL,					/* no rfq */
3271 		NULL,					/* no stq */
3272 		IRE_HOST,
3273 		NULL,
3274 		NULL,
3275 		NULL,
3276 		0,
3277 		0,
3278 		0,
3279 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3280 		&ulp_info,
3281 		NULL,
3282 		NULL);
3283 
3284 	if (ire == NULL) {
3285 		freemsg(mp);
3286 		ire_refrele(save_ire);
3287 		return;
3288 	}
3289 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3290 	ire_refrele(save_ire);
3291 	atomic_inc_32(&ip_redirect_cnt);
3292 
3293 	if (error == 0) {
3294 		ire_refrele(ire);		/* Held in ire_add_v4 */
3295 		/* tell routing sockets that we received a redirect */
3296 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3297 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3298 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3299 	}
3300 
3301 	/*
3302 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3303 	 * This together with the added IRE has the effect of
3304 	 * modifying an existing redirect.
3305 	 */
3306 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3307 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3308 	if (prev_ire != NULL) {
3309 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3310 			ire_delete(prev_ire);
3311 		ire_refrele(prev_ire);
3312 	}
3313 
3314 	freemsg(mp);
3315 }
3316 
3317 /*
3318  * Generate an ICMP parameter problem message.
3319  */
3320 static void
3321 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3322 {
3323 	icmph_t	icmph;
3324 	boolean_t mctl_present;
3325 	mblk_t *first_mp;
3326 
3327 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3328 
3329 	if (!(mp = icmp_pkt_err_ok(mp))) {
3330 		if (mctl_present)
3331 			freeb(first_mp);
3332 		return;
3333 	}
3334 
3335 	bzero(&icmph, sizeof (icmph_t));
3336 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3337 	icmph.icmph_pp_ptr = ptr;
3338 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3339 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3340 }
3341 
3342 /*
3343  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3344  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3345  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3346  * an icmp error packet can be sent.
3347  * Assigns an appropriate source address to the packet. If ipha_dst is
3348  * one of our addresses use it for source. Otherwise pick a source based
3349  * on a route lookup back to ipha_src.
3350  * Note that ipha_src must be set here since the
3351  * packet is likely to arrive on an ill queue in ip_wput() which will
3352  * not set a source address.
3353  */
3354 static void
3355 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3356     boolean_t mctl_present, zoneid_t zoneid)
3357 {
3358 	ipaddr_t dst;
3359 	icmph_t	*icmph;
3360 	ipha_t	*ipha;
3361 	uint_t	len_needed;
3362 	size_t	msg_len;
3363 	mblk_t	*mp1;
3364 	ipaddr_t src;
3365 	ire_t	*ire;
3366 	mblk_t *ipsec_mp;
3367 	ipsec_out_t	*io = NULL;
3368 	boolean_t xmit_if_on = B_FALSE;
3369 
3370 	if (mctl_present) {
3371 		/*
3372 		 * If it is :
3373 		 *
3374 		 * 1) a IPSEC_OUT, then this is caused by outbound
3375 		 *    datagram originating on this host. IPSEC processing
3376 		 *    may or may not have been done. Refer to comments above
3377 		 *    icmp_inbound_error_fanout for details.
3378 		 *
3379 		 * 2) a IPSEC_IN if we are generating a icmp_message
3380 		 *    for an incoming datagram destined for us i.e called
3381 		 *    from ip_fanout_send_icmp.
3382 		 */
3383 		ipsec_info_t *in;
3384 		ipsec_mp = mp;
3385 		mp = ipsec_mp->b_cont;
3386 
3387 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3388 		ipha = (ipha_t *)mp->b_rptr;
3389 
3390 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3391 		    in->ipsec_info_type == IPSEC_IN);
3392 
3393 		if (in->ipsec_info_type == IPSEC_IN) {
3394 			/*
3395 			 * Convert the IPSEC_IN to IPSEC_OUT.
3396 			 */
3397 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3398 				BUMP_MIB(&ip_mib, ipOutDiscards);
3399 				return;
3400 			}
3401 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3402 		} else {
3403 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3404 			io = (ipsec_out_t *)in;
3405 			if (io->ipsec_out_xmit_if)
3406 				xmit_if_on = B_TRUE;
3407 			/*
3408 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3409 			 * ire lookup.
3410 			 */
3411 			io->ipsec_out_proc_begin = B_FALSE;
3412 		}
3413 		ASSERT(zoneid == io->ipsec_out_zoneid);
3414 		ASSERT(zoneid != ALL_ZONES);
3415 	} else {
3416 		/*
3417 		 * This is in clear. The icmp message we are building
3418 		 * here should go out in clear.
3419 		 *
3420 		 * Pardon the convolution of it all, but it's easier to
3421 		 * allocate a "use cleartext" IPSEC_IN message and convert
3422 		 * it than it is to allocate a new one.
3423 		 */
3424 		ipsec_in_t *ii;
3425 		ASSERT(DB_TYPE(mp) == M_DATA);
3426 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3427 			freemsg(mp);
3428 			BUMP_MIB(&ip_mib, ipOutDiscards);
3429 			return;
3430 		}
3431 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3432 
3433 		/* This is not a secure packet */
3434 		ii->ipsec_in_secure = B_FALSE;
3435 		/*
3436 		 * For trusted extensions using a shared IP address we can
3437 		 * send using any zoneid.
3438 		 */
3439 		if (zoneid == ALL_ZONES)
3440 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3441 		else
3442 			ii->ipsec_in_zoneid = zoneid;
3443 		ipsec_mp->b_cont = mp;
3444 		ipha = (ipha_t *)mp->b_rptr;
3445 		/*
3446 		 * Convert the IPSEC_IN to IPSEC_OUT.
3447 		 */
3448 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3449 			BUMP_MIB(&ip_mib, ipOutDiscards);
3450 			return;
3451 		}
3452 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3453 	}
3454 
3455 	/* Remember our eventual destination */
3456 	dst = ipha->ipha_src;
3457 
3458 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3459 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3460 	if (ire != NULL &&
3461 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3462 		src = ipha->ipha_dst;
3463 	} else if (!xmit_if_on) {
3464 		if (ire != NULL)
3465 			ire_refrele(ire);
3466 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3467 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3468 		if (ire == NULL) {
3469 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3470 			freemsg(ipsec_mp);
3471 			return;
3472 		}
3473 		src = ire->ire_src_addr;
3474 	} else {
3475 		ipif_t	*ipif = NULL;
3476 		ill_t	*ill;
3477 		/*
3478 		 * This must be an ICMP error coming from
3479 		 * ip_mrtun_forward(). The src addr should
3480 		 * be equal to the IP-addr of the outgoing
3481 		 * interface.
3482 		 */
3483 		if (io == NULL) {
3484 			/* This is not a IPSEC_OUT type control msg */
3485 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3486 			freemsg(ipsec_mp);
3487 			return;
3488 		}
3489 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3490 		    NULL, NULL, NULL, NULL);
3491 		if (ill != NULL) {
3492 			ipif = ipif_get_next_ipif(NULL, ill);
3493 			ill_refrele(ill);
3494 		}
3495 		if (ipif == NULL) {
3496 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3497 			freemsg(ipsec_mp);
3498 			return;
3499 		}
3500 		src = ipif->ipif_src_addr;
3501 		ipif_refrele(ipif);
3502 	}
3503 
3504 	if (ire != NULL)
3505 		ire_refrele(ire);
3506 
3507 	/*
3508 	 * Check if we can send back more then 8 bytes in addition
3509 	 * to the IP header. We will include as much as 64 bytes.
3510 	 */
3511 	len_needed = IPH_HDR_LENGTH(ipha);
3512 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3513 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3514 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3515 	}
3516 	len_needed += ip_icmp_return;
3517 	msg_len = msgdsize(mp);
3518 	if (msg_len > len_needed) {
3519 		(void) adjmsg(mp, len_needed - msg_len);
3520 		msg_len = len_needed;
3521 	}
3522 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3523 	if (mp1 == NULL) {
3524 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3525 		freemsg(ipsec_mp);
3526 		return;
3527 	}
3528 	/*
3529 	 * On an unlabeled system, dblks don't necessarily have creds.
3530 	 */
3531 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3532 	if (DB_CRED(mp) != NULL)
3533 		mblk_setcred(mp1, DB_CRED(mp));
3534 	mp1->b_cont = mp;
3535 	mp = mp1;
3536 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3537 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3538 	    io->ipsec_out_type == IPSEC_OUT);
3539 	ipsec_mp->b_cont = mp;
3540 
3541 	/*
3542 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3543 	 * node generates be accepted in peace by all on-host destinations.
3544 	 * If we do NOT assume that all on-host destinations trust
3545 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3546 	 * (Look for ipsec_out_icmp_loopback).
3547 	 */
3548 	io->ipsec_out_icmp_loopback = B_TRUE;
3549 
3550 	ipha = (ipha_t *)mp->b_rptr;
3551 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3552 	*ipha = icmp_ipha;
3553 	ipha->ipha_src = src;
3554 	ipha->ipha_dst = dst;
3555 	ipha->ipha_ttl = ip_def_ttl;
3556 	msg_len += sizeof (icmp_ipha) + len;
3557 	if (msg_len > IP_MAXPACKET) {
3558 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3559 		msg_len = IP_MAXPACKET;
3560 	}
3561 	ipha->ipha_length = htons((uint16_t)msg_len);
3562 	icmph = (icmph_t *)&ipha[1];
3563 	bcopy(stuff, icmph, len);
3564 	icmph->icmph_checksum = 0;
3565 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3566 	if (icmph->icmph_checksum == 0)
3567 		icmph->icmph_checksum = 0xFFFF;
3568 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3569 	put(q, ipsec_mp);
3570 }
3571 
3572 /*
3573  * Determine if an ICMP error packet can be sent given the rate limit.
3574  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3575  * in milliseconds) and a burst size. Burst size number of packets can
3576  * be sent arbitrarely closely spaced.
3577  * The state is tracked using two variables to implement an approximate
3578  * token bucket filter:
3579  *	icmp_pkt_err_last - lbolt value when the last burst started
3580  *	icmp_pkt_err_sent - number of packets sent in current burst
3581  */
3582 boolean_t
3583 icmp_err_rate_limit(void)
3584 {
3585 	clock_t now = TICK_TO_MSEC(lbolt);
3586 	uint_t refilled; /* Number of packets refilled in tbf since last */
3587 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3588 
3589 	if (err_interval == 0)
3590 		return (B_FALSE);
3591 
3592 	if (icmp_pkt_err_last > now) {
3593 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3594 		icmp_pkt_err_last = 0;
3595 		icmp_pkt_err_sent = 0;
3596 	}
3597 	/*
3598 	 * If we are in a burst update the token bucket filter.
3599 	 * Update the "last" time to be close to "now" but make sure
3600 	 * we don't loose precision.
3601 	 */
3602 	if (icmp_pkt_err_sent != 0) {
3603 		refilled = (now - icmp_pkt_err_last)/err_interval;
3604 		if (refilled > icmp_pkt_err_sent) {
3605 			icmp_pkt_err_sent = 0;
3606 		} else {
3607 			icmp_pkt_err_sent -= refilled;
3608 			icmp_pkt_err_last += refilled * err_interval;
3609 		}
3610 	}
3611 	if (icmp_pkt_err_sent == 0) {
3612 		/* Start of new burst */
3613 		icmp_pkt_err_last = now;
3614 	}
3615 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3616 		icmp_pkt_err_sent++;
3617 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3618 		    icmp_pkt_err_sent));
3619 		return (B_FALSE);
3620 	}
3621 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3622 	return (B_TRUE);
3623 }
3624 
3625 /*
3626  * Check if it is ok to send an IPv4 ICMP error packet in
3627  * response to the IPv4 packet in mp.
3628  * Free the message and return null if no
3629  * ICMP error packet should be sent.
3630  */
3631 static mblk_t *
3632 icmp_pkt_err_ok(mblk_t *mp)
3633 {
3634 	icmph_t	*icmph;
3635 	ipha_t	*ipha;
3636 	uint_t	len_needed;
3637 	ire_t	*src_ire;
3638 	ire_t	*dst_ire;
3639 
3640 	if (!mp)
3641 		return (NULL);
3642 	ipha = (ipha_t *)mp->b_rptr;
3643 	if (ip_csum_hdr(ipha)) {
3644 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3645 		freemsg(mp);
3646 		return (NULL);
3647 	}
3648 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3649 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3650 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3651 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3652 	if (src_ire != NULL || dst_ire != NULL ||
3653 	    CLASSD(ipha->ipha_dst) ||
3654 	    CLASSD(ipha->ipha_src) ||
3655 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3656 		/* Note: only errors to the fragment with offset 0 */
3657 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3658 		freemsg(mp);
3659 		if (src_ire != NULL)
3660 			ire_refrele(src_ire);
3661 		if (dst_ire != NULL)
3662 			ire_refrele(dst_ire);
3663 		return (NULL);
3664 	}
3665 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3666 		/*
3667 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3668 		 * errors in response to any ICMP errors.
3669 		 */
3670 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3671 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3672 			if (!pullupmsg(mp, len_needed)) {
3673 				BUMP_MIB(&icmp_mib, icmpInErrors);
3674 				freemsg(mp);
3675 				return (NULL);
3676 			}
3677 			ipha = (ipha_t *)mp->b_rptr;
3678 		}
3679 		icmph = (icmph_t *)
3680 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3681 		switch (icmph->icmph_type) {
3682 		case ICMP_DEST_UNREACHABLE:
3683 		case ICMP_SOURCE_QUENCH:
3684 		case ICMP_TIME_EXCEEDED:
3685 		case ICMP_PARAM_PROBLEM:
3686 		case ICMP_REDIRECT:
3687 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3688 			freemsg(mp);
3689 			return (NULL);
3690 		default:
3691 			break;
3692 		}
3693 	}
3694 	/*
3695 	 * If this is a labeled system, then check to see if we're allowed to
3696 	 * send a response to this particular sender.  If not, then just drop.
3697 	 */
3698 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3699 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3700 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3701 		freemsg(mp);
3702 		return (NULL);
3703 	}
3704 	if (icmp_err_rate_limit()) {
3705 		/*
3706 		 * Only send ICMP error packets every so often.
3707 		 * This should be done on a per port/source basis,
3708 		 * but for now this will suffice.
3709 		 */
3710 		freemsg(mp);
3711 		return (NULL);
3712 	}
3713 	return (mp);
3714 }
3715 
3716 /*
3717  * Generate an ICMP redirect message.
3718  */
3719 static void
3720 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3721 {
3722 	icmph_t	icmph;
3723 
3724 	/*
3725 	 * We are called from ip_rput where we could
3726 	 * not have attached an IPSEC_IN.
3727 	 */
3728 	ASSERT(mp->b_datap->db_type == M_DATA);
3729 
3730 	if (!(mp = icmp_pkt_err_ok(mp))) {
3731 		return;
3732 	}
3733 
3734 	bzero(&icmph, sizeof (icmph_t));
3735 	icmph.icmph_type = ICMP_REDIRECT;
3736 	icmph.icmph_code = 1;
3737 	icmph.icmph_rd_gateway = gateway;
3738 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3739 	/* Redirects sent by router, and router is global zone */
3740 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3741 }
3742 
3743 /*
3744  * Generate an ICMP time exceeded message.
3745  */
3746 void
3747 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3748 {
3749 	icmph_t	icmph;
3750 	boolean_t mctl_present;
3751 	mblk_t *first_mp;
3752 
3753 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3754 
3755 	if (!(mp = icmp_pkt_err_ok(mp))) {
3756 		if (mctl_present)
3757 			freeb(first_mp);
3758 		return;
3759 	}
3760 
3761 	bzero(&icmph, sizeof (icmph_t));
3762 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3763 	icmph.icmph_code = code;
3764 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3765 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3766 }
3767 
3768 /*
3769  * Generate an ICMP unreachable message.
3770  */
3771 void
3772 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3773 {
3774 	icmph_t	icmph;
3775 	mblk_t *first_mp;
3776 	boolean_t mctl_present;
3777 
3778 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3779 
3780 	if (!(mp = icmp_pkt_err_ok(mp))) {
3781 		if (mctl_present)
3782 			freeb(first_mp);
3783 		return;
3784 	}
3785 
3786 	bzero(&icmph, sizeof (icmph_t));
3787 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3788 	icmph.icmph_code = code;
3789 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3790 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3791 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3792 	    zoneid);
3793 }
3794 
3795 /*
3796  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3797  * duplicate.  As long as someone else holds the address, the interface will
3798  * stay down.  When that conflict goes away, the interface is brought back up.
3799  * This is done so that accidental shutdowns of addresses aren't made
3800  * permanent.  Your server will recover from a failure.
3801  *
3802  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3803  * user space process (dhcpagent).
3804  *
3805  * Recovery completes if ARP reports that the address is now ours (via
3806  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3807  *
3808  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3809  */
3810 static void
3811 ipif_dup_recovery(void *arg)
3812 {
3813 	ipif_t *ipif = arg;
3814 	ill_t *ill = ipif->ipif_ill;
3815 	mblk_t *arp_add_mp;
3816 	mblk_t *arp_del_mp;
3817 	area_t *area;
3818 
3819 	ipif->ipif_recovery_id = 0;
3820 
3821 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3822 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3823 		/* No reason to try to bring this address back. */
3824 		return;
3825 	}
3826 
3827 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3828 		goto alloc_fail;
3829 
3830 	if (ipif->ipif_arp_del_mp == NULL) {
3831 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3832 			goto alloc_fail;
3833 		ipif->ipif_arp_del_mp = arp_del_mp;
3834 	}
3835 
3836 	/* Setting the 'unverified' flag restarts DAD */
3837 	area = (area_t *)arp_add_mp->b_rptr;
3838 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3839 	    ACE_F_UNVERIFIED;
3840 	putnext(ill->ill_rq, arp_add_mp);
3841 	return;
3842 
3843 alloc_fail:
3844 	/* On allocation failure, just restart the timer */
3845 	freemsg(arp_add_mp);
3846 	if (ip_dup_recovery > 0) {
3847 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3848 		    MSEC_TO_TICK(ip_dup_recovery));
3849 	}
3850 }
3851 
3852 /*
3853  * This is for exclusive changes due to ARP.  Either tear down an interface due
3854  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3855  */
3856 /* ARGSUSED */
3857 static void
3858 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3859 {
3860 	ill_t	*ill = rq->q_ptr;
3861 	arh_t *arh;
3862 	ipaddr_t src;
3863 	ipif_t	*ipif;
3864 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3865 	char hbuf[MAC_STR_LEN];
3866 	char sbuf[INET_ADDRSTRLEN];
3867 	const char *failtype;
3868 	boolean_t bring_up;
3869 
3870 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3871 	case AR_CN_READY:
3872 		failtype = NULL;
3873 		bring_up = B_TRUE;
3874 		break;
3875 	case AR_CN_FAILED:
3876 		failtype = "in use";
3877 		bring_up = B_FALSE;
3878 		break;
3879 	default:
3880 		failtype = "claimed";
3881 		bring_up = B_FALSE;
3882 		break;
3883 	}
3884 
3885 	arh = (arh_t *)mp->b_cont->b_rptr;
3886 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3887 
3888 	/* Handle failures due to probes */
3889 	if (src == 0) {
3890 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3891 		    IP_ADDR_LEN);
3892 	}
3893 
3894 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3895 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3896 	    sizeof (hbuf));
3897 	(void) ip_dot_addr(src, sbuf);
3898 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3899 
3900 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3901 		    ipif->ipif_lcl_addr != src) {
3902 			continue;
3903 		}
3904 
3905 		/*
3906 		 * If we failed on a recovery probe, then restart the timer to
3907 		 * try again later.
3908 		 */
3909 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3910 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3911 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3912 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3913 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3914 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3915 			continue;
3916 		}
3917 
3918 		/*
3919 		 * If what we're trying to do has already been done, then do
3920 		 * nothing.
3921 		 */
3922 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3923 			continue;
3924 
3925 		if (ipif->ipif_id != 0) {
3926 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3927 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3928 			    ipif->ipif_id);
3929 		}
3930 		if (failtype == NULL) {
3931 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3932 			    ibuf);
3933 		} else {
3934 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3935 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3936 		}
3937 
3938 		if (bring_up) {
3939 			ASSERT(ill->ill_dl_up);
3940 			/*
3941 			 * Free up the ARP delete message so we can allocate
3942 			 * a fresh one through the normal path.
3943 			 */
3944 			freemsg(ipif->ipif_arp_del_mp);
3945 			ipif->ipif_arp_del_mp = NULL;
3946 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3947 			    EINPROGRESS) {
3948 				ipif->ipif_addr_ready = 1;
3949 				(void) ipif_up_done(ipif);
3950 			}
3951 			continue;
3952 		}
3953 
3954 		mutex_enter(&ill->ill_lock);
3955 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3956 		ipif->ipif_flags |= IPIF_DUPLICATE;
3957 		ill->ill_ipif_dup_count++;
3958 		mutex_exit(&ill->ill_lock);
3959 		/*
3960 		 * Already exclusive on the ill; no need to handle deferred
3961 		 * processing here.
3962 		 */
3963 		(void) ipif_down(ipif, NULL, NULL);
3964 		ipif_down_tail(ipif);
3965 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3966 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3967 		    ip_dup_recovery > 0) {
3968 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3969 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3970 		}
3971 	}
3972 	freemsg(mp);
3973 }
3974 
3975 /* ARGSUSED */
3976 static void
3977 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3978 {
3979 	ill_t	*ill = rq->q_ptr;
3980 	arh_t *arh;
3981 	ipaddr_t src;
3982 	ipif_t	*ipif;
3983 
3984 	arh = (arh_t *)mp->b_cont->b_rptr;
3985 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3986 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3987 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3988 			(void) ipif_resolver_up(ipif, Res_act_defend);
3989 	}
3990 	freemsg(mp);
3991 }
3992 
3993 /*
3994  * News from ARP.  ARP sends notification of interesting events down
3995  * to its clients using M_CTL messages with the interesting ARP packet
3996  * attached via b_cont.
3997  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3998  * queue as opposed to ARP sending the message to all the clients, i.e. all
3999  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
4000  * table if a cache IRE is found to delete all the entries for the address in
4001  * the packet.
4002  */
4003 static void
4004 ip_arp_news(queue_t *q, mblk_t *mp)
4005 {
4006 	arcn_t		*arcn;
4007 	arh_t		*arh;
4008 	ire_t		*ire = NULL;
4009 	char		hbuf[MAC_STR_LEN];
4010 	char		sbuf[INET_ADDRSTRLEN];
4011 	ipaddr_t	src;
4012 	in6_addr_t	v6src;
4013 	boolean_t	isv6 = B_FALSE;
4014 	ipif_t		*ipif;
4015 	ill_t		*ill;
4016 
4017 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4018 		if (q->q_next) {
4019 			putnext(q, mp);
4020 		} else
4021 			freemsg(mp);
4022 		return;
4023 	}
4024 	arh = (arh_t *)mp->b_cont->b_rptr;
4025 	/* Is it one we are interested in? */
4026 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4027 		isv6 = B_TRUE;
4028 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4029 		    IPV6_ADDR_LEN);
4030 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4031 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4032 		    IP_ADDR_LEN);
4033 	} else {
4034 		freemsg(mp);
4035 		return;
4036 	}
4037 
4038 	ill = q->q_ptr;
4039 
4040 	arcn = (arcn_t *)mp->b_rptr;
4041 	switch (arcn->arcn_code) {
4042 	case AR_CN_BOGON:
4043 		/*
4044 		 * Someone is sending ARP packets with a source protocol
4045 		 * address that we have published and for which we believe our
4046 		 * entry is authoritative and (when ill_arp_extend is set)
4047 		 * verified to be unique on the network.
4048 		 *
4049 		 * The ARP module internally handles the cases where the sender
4050 		 * is just probing (for DAD) and where the hardware address of
4051 		 * a non-authoritative entry has changed.  Thus, these are the
4052 		 * real conflicts, and we have to do resolution.
4053 		 *
4054 		 * We back away quickly from the address if it's from DHCP or
4055 		 * otherwise temporary and hasn't been used recently (or at
4056 		 * all).  We'd like to include "deprecated" addresses here as
4057 		 * well (as there's no real reason to defend something we're
4058 		 * discarding), but IPMP "reuses" this flag to mean something
4059 		 * other than the standard meaning.
4060 		 *
4061 		 * If the ARP module above is not extended (meaning that it
4062 		 * doesn't know how to defend the address), then we just log
4063 		 * the problem as we always did and continue on.  It's not
4064 		 * right, but there's little else we can do, and those old ATM
4065 		 * users are going away anyway.
4066 		 */
4067 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4068 		    hbuf, sizeof (hbuf));
4069 		(void) ip_dot_addr(src, sbuf);
4070 		if (isv6)
4071 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4072 		else
4073 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4074 
4075 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4076 			uint32_t now;
4077 			uint32_t maxage;
4078 			clock_t lused;
4079 			uint_t maxdefense;
4080 			uint_t defs;
4081 
4082 			/*
4083 			 * First, figure out if this address hasn't been used
4084 			 * in a while.  If it hasn't, then it's a better
4085 			 * candidate for abandoning.
4086 			 */
4087 			ipif = ire->ire_ipif;
4088 			ASSERT(ipif != NULL);
4089 			now = gethrestime_sec();
4090 			maxage = now - ire->ire_create_time;
4091 			if (maxage > ip_max_temp_idle)
4092 				maxage = ip_max_temp_idle;
4093 			lused = drv_hztousec(ddi_get_lbolt() -
4094 			    ire->ire_last_used_time) / MICROSEC + 1;
4095 			if (lused >= maxage && (ipif->ipif_flags &
4096 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4097 				maxdefense = ip_max_temp_defend;
4098 			else
4099 				maxdefense = ip_max_defend;
4100 
4101 			/*
4102 			 * Now figure out how many times we've defended
4103 			 * ourselves.  Ignore defenses that happened long in
4104 			 * the past.
4105 			 */
4106 			mutex_enter(&ire->ire_lock);
4107 			if ((defs = ire->ire_defense_count) > 0 &&
4108 			    now - ire->ire_defense_time > ip_defend_interval) {
4109 				ire->ire_defense_count = defs = 0;
4110 			}
4111 			ire->ire_defense_count++;
4112 			ire->ire_defense_time = now;
4113 			mutex_exit(&ire->ire_lock);
4114 			ill_refhold(ill);
4115 			ire_refrele(ire);
4116 
4117 			/*
4118 			 * If we've defended ourselves too many times already,
4119 			 * then give up and tear down the interface(s) using
4120 			 * this address.  Otherwise, defend by sending out a
4121 			 * gratuitous ARP.
4122 			 */
4123 			if (defs >= maxdefense && ill->ill_arp_extend) {
4124 				(void) qwriter_ip(NULL, ill, q, mp,
4125 				    ip_arp_excl, CUR_OP, B_FALSE);
4126 			} else {
4127 				cmn_err(CE_WARN,
4128 				    "node %s is using our IP address %s on %s",
4129 				    hbuf, sbuf, ill->ill_name);
4130 				/*
4131 				 * If this is an old (ATM) ARP module, then
4132 				 * don't try to defend the address.  Remain
4133 				 * compatible with the old behavior.  Defend
4134 				 * only with new ARP.
4135 				 */
4136 				if (ill->ill_arp_extend) {
4137 					(void) qwriter_ip(NULL, ill, q, mp,
4138 					    ip_arp_defend, CUR_OP, B_FALSE);
4139 				} else {
4140 					ill_refrele(ill);
4141 				}
4142 			}
4143 			return;
4144 		}
4145 		cmn_err(CE_WARN,
4146 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4147 		    hbuf, sbuf, ill->ill_name);
4148 		if (ire != NULL)
4149 			ire_refrele(ire);
4150 		break;
4151 	case AR_CN_ANNOUNCE:
4152 		if (isv6) {
4153 			/*
4154 			 * For XRESOLV interfaces.
4155 			 * Delete the IRE cache entry and NCE for this
4156 			 * v6 address
4157 			 */
4158 			ip_ire_clookup_and_delete_v6(&v6src);
4159 			/*
4160 			 * If v6src is a non-zero, it's a router address
4161 			 * as below. Do the same sort of thing to clean
4162 			 * out off-net IRE_CACHE entries that go through
4163 			 * the router.
4164 			 */
4165 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4166 				ire_walk_v6(ire_delete_cache_gw_v6,
4167 				    (char *)&v6src, ALL_ZONES);
4168 			}
4169 		} else {
4170 			nce_hw_map_t hwm;
4171 
4172 			/*
4173 			 * ARP gives us a copy of any packet where it thinks
4174 			 * the address has changed, so that we can update our
4175 			 * caches.  We're responsible for caching known answers
4176 			 * in the current design.  We check whether the
4177 			 * hardware address really has changed in all of our
4178 			 * entries that have cached this mapping, and if so, we
4179 			 * blow them away.  This way we will immediately pick
4180 			 * up the rare case of a host changing hardware
4181 			 * address.
4182 			 */
4183 			if (src == 0)
4184 				break;
4185 			hwm.hwm_addr = src;
4186 			hwm.hwm_hwlen = arh->arh_hlen;
4187 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4188 			ndp_walk_common(&ndp4, NULL,
4189 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4190 		}
4191 		break;
4192 	case AR_CN_READY:
4193 		/* No external v6 resolver has a contract to use this */
4194 		if (isv6)
4195 			break;
4196 		/* If the link is down, we'll retry this later */
4197 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4198 			break;
4199 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4200 		    NULL, NULL);
4201 		if (ipif != NULL) {
4202 			/*
4203 			 * If this is a duplicate recovery, then we now need to
4204 			 * go exclusive to bring this thing back up.
4205 			 */
4206 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4207 			    IPIF_DUPLICATE) {
4208 				ipif_refrele(ipif);
4209 				ill_refhold(ill);
4210 				(void) qwriter_ip(NULL, ill, q, mp,
4211 				    ip_arp_excl, CUR_OP, B_FALSE);
4212 				return;
4213 			}
4214 			/*
4215 			 * If this is the first notice that this address is
4216 			 * ready, then let the user know now.
4217 			 */
4218 			if ((ipif->ipif_flags & IPIF_UP) &&
4219 			    !ipif->ipif_addr_ready) {
4220 				ipif_mask_reply(ipif);
4221 				ip_rts_ifmsg(ipif);
4222 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4223 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4224 			}
4225 			ipif->ipif_addr_ready = 1;
4226 			ipif_refrele(ipif);
4227 		}
4228 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4229 		if (ire != NULL) {
4230 			ire->ire_defense_count = 0;
4231 			ire_refrele(ire);
4232 		}
4233 		break;
4234 	case AR_CN_FAILED:
4235 		/* No external v6 resolver has a contract to use this */
4236 		if (isv6)
4237 			break;
4238 		ill_refhold(ill);
4239 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4240 		    B_FALSE);
4241 		return;
4242 	}
4243 	freemsg(mp);
4244 }
4245 
4246 /*
4247  * Create a mblk suitable for carrying the interface index and/or source link
4248  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4249  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4250  * application.
4251  */
4252 mblk_t *
4253 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4254 {
4255 	mblk_t		*mp;
4256 	in_pktinfo_t	*pinfo;
4257 	ipha_t *ipha;
4258 	struct ether_header *pether;
4259 
4260 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4261 	if (mp == NULL) {
4262 		ip1dbg(("ip_add_info: allocation failure.\n"));
4263 		return (data_mp);
4264 	}
4265 
4266 	ipha	= (ipha_t *)data_mp->b_rptr;
4267 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4268 	bzero(pinfo, sizeof (in_pktinfo_t));
4269 	pinfo->in_pkt_flags = (uchar_t)flags;
4270 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4271 
4272 	if (flags & IPF_RECVIF)
4273 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4274 
4275 	pether = (struct ether_header *)((char *)ipha
4276 	    - sizeof (struct ether_header));
4277 	/*
4278 	 * Make sure the interface is an ethernet type, since this option
4279 	 * is currently supported only on this type of interface. Also make
4280 	 * sure we are pointing correctly above db_base.
4281 	 */
4282 
4283 	if ((flags & IPF_RECVSLLA) &&
4284 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4285 	    (ill->ill_type == IFT_ETHER) &&
4286 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4287 
4288 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4289 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4290 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4291 	} else {
4292 		/*
4293 		 * Clear the bit. Indicate to upper layer that IP is not
4294 		 * sending this ancillary info.
4295 		 */
4296 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4297 	}
4298 
4299 	mp->b_datap->db_type = M_CTL;
4300 	mp->b_wptr += sizeof (in_pktinfo_t);
4301 	mp->b_cont = data_mp;
4302 
4303 	return (mp);
4304 }
4305 
4306 /*
4307  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4308  * part of the bind request.
4309  */
4310 
4311 boolean_t
4312 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4313 {
4314 	ipsec_in_t *ii;
4315 
4316 	ASSERT(policy_mp != NULL);
4317 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4318 
4319 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4320 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4321 
4322 	connp->conn_policy = ii->ipsec_in_policy;
4323 	ii->ipsec_in_policy = NULL;
4324 
4325 	if (ii->ipsec_in_action != NULL) {
4326 		if (connp->conn_latch == NULL) {
4327 			connp->conn_latch = iplatch_create();
4328 			if (connp->conn_latch == NULL)
4329 				return (B_FALSE);
4330 		}
4331 		ipsec_latch_inbound(connp->conn_latch, ii);
4332 	}
4333 	return (B_TRUE);
4334 }
4335 
4336 /*
4337  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4338  * and to arrange for power-fanout assist.  The ULP is identified by
4339  * adding a single byte at the end of the original bind message.
4340  * A ULP other than UDP or TCP that wishes to be recognized passes
4341  * down a bind with a zero length address.
4342  *
4343  * The binding works as follows:
4344  * - A zero byte address means just bind to the protocol.
4345  * - A four byte address is treated as a request to validate
4346  *   that the address is a valid local address, appropriate for
4347  *   an application to bind to. This does not affect any fanout
4348  *   information in IP.
4349  * - A sizeof sin_t byte address is used to bind to only the local address
4350  *   and port.
4351  * - A sizeof ipa_conn_t byte address contains complete fanout information
4352  *   consisting of local and remote addresses and ports.  In
4353  *   this case, the addresses are both validated as appropriate
4354  *   for this operation, and, if so, the information is retained
4355  *   for use in the inbound fanout.
4356  *
4357  * The ULP (except in the zero-length bind) can append an
4358  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4359  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4360  * a copy of the source or destination IRE (source for local bind;
4361  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4362  * policy information contained should be copied on to the conn.
4363  *
4364  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4365  */
4366 mblk_t *
4367 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4368 {
4369 	ssize_t		len;
4370 	struct T_bind_req	*tbr;
4371 	sin_t		*sin;
4372 	ipa_conn_t	*ac;
4373 	uchar_t		*ucp;
4374 	mblk_t		*mp1;
4375 	boolean_t	ire_requested;
4376 	boolean_t	ipsec_policy_set = B_FALSE;
4377 	int		error = 0;
4378 	int		protocol;
4379 	ipa_conn_x_t	*acx;
4380 
4381 	ASSERT(!connp->conn_af_isv6);
4382 	connp->conn_pkt_isv6 = B_FALSE;
4383 
4384 	len = MBLKL(mp);
4385 	if (len < (sizeof (*tbr) + 1)) {
4386 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4387 		    "ip_bind: bogus msg, len %ld", len);
4388 		/* XXX: Need to return something better */
4389 		goto bad_addr;
4390 	}
4391 	/* Back up and extract the protocol identifier. */
4392 	mp->b_wptr--;
4393 	protocol = *mp->b_wptr & 0xFF;
4394 	tbr = (struct T_bind_req *)mp->b_rptr;
4395 	/* Reset the message type in preparation for shipping it back. */
4396 	DB_TYPE(mp) = M_PCPROTO;
4397 
4398 	connp->conn_ulp = (uint8_t)protocol;
4399 
4400 	/*
4401 	 * Check for a zero length address.  This is from a protocol that
4402 	 * wants to register to receive all packets of its type.
4403 	 */
4404 	if (tbr->ADDR_length == 0) {
4405 		/*
4406 		 * These protocols are now intercepted in ip_bind_v6().
4407 		 * Reject protocol-level binds here for now.
4408 		 *
4409 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4410 		 * so that the protocol type cannot be SCTP.
4411 		 */
4412 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4413 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4414 			goto bad_addr;
4415 		}
4416 
4417 		/*
4418 		 *
4419 		 * The udp module never sends down a zero-length address,
4420 		 * and allowing this on a labeled system will break MLP
4421 		 * functionality.
4422 		 */
4423 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4424 			goto bad_addr;
4425 
4426 		if (connp->conn_mac_exempt)
4427 			goto bad_addr;
4428 
4429 		/* No hash here really.  The table is big enough. */
4430 		connp->conn_srcv6 = ipv6_all_zeros;
4431 
4432 		ipcl_proto_insert(connp, protocol);
4433 
4434 		tbr->PRIM_type = T_BIND_ACK;
4435 		return (mp);
4436 	}
4437 
4438 	/* Extract the address pointer from the message. */
4439 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4440 	    tbr->ADDR_length);
4441 	if (ucp == NULL) {
4442 		ip1dbg(("ip_bind: no address\n"));
4443 		goto bad_addr;
4444 	}
4445 	if (!OK_32PTR(ucp)) {
4446 		ip1dbg(("ip_bind: unaligned address\n"));
4447 		goto bad_addr;
4448 	}
4449 	/*
4450 	 * Check for trailing mps.
4451 	 */
4452 
4453 	mp1 = mp->b_cont;
4454 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4455 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4456 
4457 	switch (tbr->ADDR_length) {
4458 	default:
4459 		ip1dbg(("ip_bind: bad address length %d\n",
4460 		    (int)tbr->ADDR_length));
4461 		goto bad_addr;
4462 
4463 	case IP_ADDR_LEN:
4464 		/* Verification of local address only */
4465 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4466 		    ire_requested, ipsec_policy_set, B_FALSE);
4467 		break;
4468 
4469 	case sizeof (sin_t):
4470 		sin = (sin_t *)ucp;
4471 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4472 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4473 		break;
4474 
4475 	case sizeof (ipa_conn_t):
4476 		ac = (ipa_conn_t *)ucp;
4477 		/* For raw socket, the local port is not set. */
4478 		if (ac->ac_lport == 0)
4479 			ac->ac_lport = connp->conn_lport;
4480 		/* Always verify destination reachability. */
4481 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4482 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4483 		    ipsec_policy_set, B_TRUE, B_TRUE);
4484 		break;
4485 
4486 	case sizeof (ipa_conn_x_t):
4487 		acx = (ipa_conn_x_t *)ucp;
4488 		/*
4489 		 * Whether or not to verify destination reachability depends
4490 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4491 		 */
4492 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4493 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4494 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4495 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4496 		break;
4497 	}
4498 	if (error == EINPROGRESS)
4499 		return (NULL);
4500 	else if (error != 0)
4501 		goto bad_addr;
4502 	/*
4503 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4504 	 * We can't do this in ip_bind_insert_ire because the policy
4505 	 * may not have been inherited at that point in time and hence
4506 	 * conn_out_enforce_policy may not be set.
4507 	 */
4508 	mp1 = mp->b_cont;
4509 	if (ire_requested && connp->conn_out_enforce_policy &&
4510 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4511 		ire_t *ire = (ire_t *)mp1->b_rptr;
4512 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4513 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4514 	}
4515 
4516 	/* Send it home. */
4517 	mp->b_datap->db_type = M_PCPROTO;
4518 	tbr->PRIM_type = T_BIND_ACK;
4519 	return (mp);
4520 
4521 bad_addr:
4522 	/*
4523 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4524 	 * a unix errno.
4525 	 */
4526 	if (error > 0)
4527 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4528 	else
4529 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4530 	return (mp);
4531 }
4532 
4533 /*
4534  * Here address is verified to be a valid local address.
4535  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4536  * address is also considered a valid local address.
4537  * In the case of a broadcast/multicast address, however, the
4538  * upper protocol is expected to reset the src address
4539  * to 0 if it sees a IRE_BROADCAST type returned so that
4540  * no packets are emitted with broadcast/multicast address as
4541  * source address (that violates hosts requirements RFC1122)
4542  * The addresses valid for bind are:
4543  *	(1) - INADDR_ANY (0)
4544  *	(2) - IP address of an UP interface
4545  *	(3) - IP address of a DOWN interface
4546  *	(4) - valid local IP broadcast addresses. In this case
4547  *	the conn will only receive packets destined to
4548  *	the specified broadcast address.
4549  *	(5) - a multicast address. In this case
4550  *	the conn will only receive packets destined to
4551  *	the specified multicast address. Note: the
4552  *	application still has to issue an
4553  *	IP_ADD_MEMBERSHIP socket option.
4554  *
4555  * On error, return -1 for TBADADDR otherwise pass the
4556  * errno with TSYSERR reply.
4557  *
4558  * In all the above cases, the bound address must be valid in the current zone.
4559  * When the address is loopback, multicast or broadcast, there might be many
4560  * matching IREs so bind has to look up based on the zone.
4561  *
4562  * Note: lport is in network byte order.
4563  */
4564 int
4565 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4566     boolean_t ire_requested, boolean_t ipsec_policy_set,
4567     boolean_t fanout_insert)
4568 {
4569 	int		error = 0;
4570 	ire_t		*src_ire;
4571 	mblk_t		*policy_mp;
4572 	ipif_t		*ipif;
4573 	zoneid_t	zoneid;
4574 
4575 	if (ipsec_policy_set) {
4576 		policy_mp = mp->b_cont;
4577 	}
4578 
4579 	/*
4580 	 * If it was previously connected, conn_fully_bound would have
4581 	 * been set.
4582 	 */
4583 	connp->conn_fully_bound = B_FALSE;
4584 
4585 	src_ire = NULL;
4586 	ipif = NULL;
4587 
4588 	zoneid = IPCL_ZONEID(connp);
4589 
4590 	if (src_addr) {
4591 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4592 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4593 		/*
4594 		 * If an address other than 0.0.0.0 is requested,
4595 		 * we verify that it is a valid address for bind
4596 		 * Note: Following code is in if-else-if form for
4597 		 * readability compared to a condition check.
4598 		 */
4599 		/* LINTED - statement has no consequent */
4600 		if (IRE_IS_LOCAL(src_ire)) {
4601 			/*
4602 			 * (2) Bind to address of local UP interface
4603 			 */
4604 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4605 			/*
4606 			 * (4) Bind to broadcast address
4607 			 * Note: permitted only from transports that
4608 			 * request IRE
4609 			 */
4610 			if (!ire_requested)
4611 				error = EADDRNOTAVAIL;
4612 		} else {
4613 			/*
4614 			 * (3) Bind to address of local DOWN interface
4615 			 * (ipif_lookup_addr() looks up all interfaces
4616 			 * but we do not get here for UP interfaces
4617 			 * - case (2) above)
4618 			 * We put the protocol byte back into the mblk
4619 			 * since we may come back via ip_wput_nondata()
4620 			 * later with this mblk if ipif_lookup_addr chooses
4621 			 * to defer processing.
4622 			 */
4623 			*mp->b_wptr++ = (char)connp->conn_ulp;
4624 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4625 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4626 			    &error)) != NULL) {
4627 				ipif_refrele(ipif);
4628 			} else if (error == EINPROGRESS) {
4629 				if (src_ire != NULL)
4630 					ire_refrele(src_ire);
4631 				return (EINPROGRESS);
4632 			} else if (CLASSD(src_addr)) {
4633 				error = 0;
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				/*
4637 				 * (5) bind to multicast address.
4638 				 * Fake out the IRE returned to upper
4639 				 * layer to be a broadcast IRE.
4640 				 */
4641 				src_ire = ire_ctable_lookup(
4642 				    INADDR_BROADCAST, INADDR_ANY,
4643 				    IRE_BROADCAST, NULL, zoneid, NULL,
4644 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4645 				if (src_ire == NULL || !ire_requested)
4646 					error = EADDRNOTAVAIL;
4647 			} else {
4648 				/*
4649 				 * Not a valid address for bind
4650 				 */
4651 				error = EADDRNOTAVAIL;
4652 			}
4653 			/*
4654 			 * Just to keep it consistent with the processing in
4655 			 * ip_bind_v4()
4656 			 */
4657 			mp->b_wptr--;
4658 		}
4659 		if (error) {
4660 			/* Red Alert!  Attempting to be a bogon! */
4661 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4662 			    ntohl(src_addr)));
4663 			goto bad_addr;
4664 		}
4665 	}
4666 
4667 	/*
4668 	 * Allow setting new policies. For example, disconnects come
4669 	 * down as ipa_t bind. As we would have set conn_policy_cached
4670 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4671 	 * can change after the disconnect.
4672 	 */
4673 	connp->conn_policy_cached = B_FALSE;
4674 
4675 	/*
4676 	 * If not fanout_insert this was just an address verification
4677 	 */
4678 	if (fanout_insert) {
4679 		/*
4680 		 * The addresses have been verified. Time to insert in
4681 		 * the correct fanout list.
4682 		 */
4683 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4684 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4685 		connp->conn_lport = lport;
4686 		connp->conn_fport = 0;
4687 		/*
4688 		 * Do we need to add a check to reject Multicast packets
4689 		 *
4690 		 * We need to make sure that the conn_recv is set to a non-null
4691 		 * value before we insert the conn into the classifier table.
4692 		 * This is to avoid a race with an incoming packet which does an
4693 		 * ipcl_classify().
4694 		 */
4695 		if (*mp->b_wptr == IPPROTO_TCP)
4696 			connp->conn_recv = tcp_conn_request;
4697 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4698 	}
4699 
4700 	if (error == 0) {
4701 		if (ire_requested) {
4702 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4703 				error = -1;
4704 				/* Falls through to bad_addr */
4705 			}
4706 		} else if (ipsec_policy_set) {
4707 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4708 				error = -1;
4709 				/* Falls through to bad_addr */
4710 			}
4711 		}
4712 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4713 		connp->conn_recv = tcp_input;
4714 	}
4715 bad_addr:
4716 	if (error != 0) {
4717 		if (connp->conn_anon_port) {
4718 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4719 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4720 			    B_FALSE);
4721 		}
4722 		connp->conn_mlp_type = mlptSingle;
4723 	}
4724 	if (src_ire != NULL)
4725 		IRE_REFRELE(src_ire);
4726 	if (ipsec_policy_set) {
4727 		ASSERT(policy_mp == mp->b_cont);
4728 		ASSERT(policy_mp != NULL);
4729 		freeb(policy_mp);
4730 		/*
4731 		 * As of now assume that nothing else accompanies
4732 		 * IPSEC_POLICY_SET.
4733 		 */
4734 		mp->b_cont = NULL;
4735 	}
4736 	return (error);
4737 }
4738 
4739 /*
4740  * Verify that both the source and destination addresses
4741  * are valid.  If verify_dst is false, then the destination address may be
4742  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4743  * destination reachability, while tunnels do not.
4744  * Note that we allow connect to broadcast and multicast
4745  * addresses when ire_requested is set. Thus the ULP
4746  * has to check for IRE_BROADCAST and multicast.
4747  *
4748  * Returns zero if ok.
4749  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4750  * (for use with TSYSERR reply).
4751  *
4752  * Note: lport and fport are in network byte order.
4753  */
4754 int
4755 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4756     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4757     boolean_t ire_requested, boolean_t ipsec_policy_set,
4758     boolean_t fanout_insert, boolean_t verify_dst)
4759 {
4760 	ire_t		*src_ire;
4761 	ire_t		*dst_ire;
4762 	int		error = 0;
4763 	int 		protocol;
4764 	mblk_t		*policy_mp;
4765 	ire_t		*sire = NULL;
4766 	ire_t		*md_dst_ire = NULL;
4767 	ire_t		*lso_dst_ire = NULL;
4768 	ill_t		*ill = NULL;
4769 	zoneid_t	zoneid;
4770 	ipaddr_t	src_addr = *src_addrp;
4771 
4772 	src_ire = dst_ire = NULL;
4773 	protocol = *mp->b_wptr & 0xFF;
4774 
4775 	/*
4776 	 * If we never got a disconnect before, clear it now.
4777 	 */
4778 	connp->conn_fully_bound = B_FALSE;
4779 
4780 	if (ipsec_policy_set) {
4781 		policy_mp = mp->b_cont;
4782 	}
4783 
4784 	zoneid = IPCL_ZONEID(connp);
4785 
4786 	if (CLASSD(dst_addr)) {
4787 		/* Pick up an IRE_BROADCAST */
4788 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4789 		    NULL, zoneid, MBLK_GETLABEL(mp),
4790 		    (MATCH_IRE_RECURSIVE |
4791 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4792 		    MATCH_IRE_SECATTR));
4793 	} else {
4794 		/*
4795 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4796 		 * and onlink ipif is not found set ENETUNREACH error.
4797 		 */
4798 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4799 			ipif_t *ipif;
4800 
4801 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4802 			    dst_addr : connp->conn_nexthop_v4,
4803 			    connp->conn_zoneid);
4804 			if (ipif == NULL) {
4805 				error = ENETUNREACH;
4806 				goto bad_addr;
4807 			}
4808 			ipif_refrele(ipif);
4809 		}
4810 
4811 		if (connp->conn_nexthop_set) {
4812 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4813 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4814 			    MATCH_IRE_SECATTR);
4815 		} else {
4816 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4817 			    &sire, zoneid, MBLK_GETLABEL(mp),
4818 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4819 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4820 			    MATCH_IRE_SECATTR));
4821 		}
4822 	}
4823 	/*
4824 	 * dst_ire can't be a broadcast when not ire_requested.
4825 	 * We also prevent ire's with src address INADDR_ANY to
4826 	 * be used, which are created temporarily for
4827 	 * sending out packets from endpoints that have
4828 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4829 	 * reachable.  If verify_dst is false, the destination needn't be
4830 	 * reachable.
4831 	 *
4832 	 * If we match on a reject or black hole, then we've got a
4833 	 * local failure.  May as well fail out the connect() attempt,
4834 	 * since it's never going to succeed.
4835 	 */
4836 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4837 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4838 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4839 		/*
4840 		 * If we're verifying destination reachability, we always want
4841 		 * to complain here.
4842 		 *
4843 		 * If we're not verifying destination reachability but the
4844 		 * destination has a route, we still want to fail on the
4845 		 * temporary address and broadcast address tests.
4846 		 */
4847 		if (verify_dst || (dst_ire != NULL)) {
4848 			if (ip_debug > 2) {
4849 				pr_addr_dbg("ip_bind_connected: bad connected "
4850 				    "dst %s\n", AF_INET, &dst_addr);
4851 			}
4852 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4853 				error = ENETUNREACH;
4854 			else
4855 				error = EHOSTUNREACH;
4856 			goto bad_addr;
4857 		}
4858 	}
4859 
4860 	/*
4861 	 * We now know that routing will allow us to reach the destination.
4862 	 * Check whether Trusted Solaris policy allows communication with this
4863 	 * host, and pretend that the destination is unreachable if not.
4864 	 *
4865 	 * This is never a problem for TCP, since that transport is known to
4866 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4867 	 * handling.  If the remote is unreachable, it will be detected at that
4868 	 * point, so there's no reason to check it here.
4869 	 *
4870 	 * Note that for sendto (and other datagram-oriented friends), this
4871 	 * check is done as part of the data path label computation instead.
4872 	 * The check here is just to make non-TCP connect() report the right
4873 	 * error.
4874 	 */
4875 	if (dst_ire != NULL && is_system_labeled() &&
4876 	    !IPCL_IS_TCP(connp) &&
4877 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4878 	    connp->conn_mac_exempt) != 0) {
4879 		error = EHOSTUNREACH;
4880 		if (ip_debug > 2) {
4881 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4882 			    AF_INET, &dst_addr);
4883 		}
4884 		goto bad_addr;
4885 	}
4886 
4887 	/*
4888 	 * If the app does a connect(), it means that it will most likely
4889 	 * send more than 1 packet to the destination.  It makes sense
4890 	 * to clear the temporary flag.
4891 	 */
4892 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4893 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4894 		irb_t *irb = dst_ire->ire_bucket;
4895 
4896 		rw_enter(&irb->irb_lock, RW_WRITER);
4897 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4898 		irb->irb_tmp_ire_cnt--;
4899 		rw_exit(&irb->irb_lock);
4900 	}
4901 
4902 	/*
4903 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4904 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4905 	 * eligibility tests for passive connects are handled separately
4906 	 * through tcp_adapt_ire().  We do this before the source address
4907 	 * selection, because dst_ire may change after a call to
4908 	 * ipif_select_source().  This is a best-effort check, as the
4909 	 * packet for this connection may not actually go through
4910 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4911 	 * calling ip_newroute().  This is why we further check on the
4912 	 * IRE during LSO/Multidata packet transmission in
4913 	 * tcp_lsosend()/tcp_multisend().
4914 	 */
4915 	if (!ipsec_policy_set && dst_ire != NULL &&
4916 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4917 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4918 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4919 			lso_dst_ire = dst_ire;
4920 			IRE_REFHOLD(lso_dst_ire);
4921 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4922 			md_dst_ire = dst_ire;
4923 			IRE_REFHOLD(md_dst_ire);
4924 		}
4925 	}
4926 
4927 	if (dst_ire != NULL &&
4928 	    dst_ire->ire_type == IRE_LOCAL &&
4929 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4930 		/*
4931 		 * If the IRE belongs to a different zone, look for a matching
4932 		 * route in the forwarding table and use the source address from
4933 		 * that route.
4934 		 */
4935 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4936 		    zoneid, 0, NULL,
4937 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4938 		    MATCH_IRE_RJ_BHOLE);
4939 		if (src_ire == NULL) {
4940 			error = EHOSTUNREACH;
4941 			goto bad_addr;
4942 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4943 			if (!(src_ire->ire_type & IRE_HOST))
4944 				error = ENETUNREACH;
4945 			else
4946 				error = EHOSTUNREACH;
4947 			goto bad_addr;
4948 		}
4949 		if (src_addr == INADDR_ANY)
4950 			src_addr = src_ire->ire_src_addr;
4951 		ire_refrele(src_ire);
4952 		src_ire = NULL;
4953 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4954 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4955 			src_addr = sire->ire_src_addr;
4956 			ire_refrele(dst_ire);
4957 			dst_ire = sire;
4958 			sire = NULL;
4959 		} else {
4960 			/*
4961 			 * Pick a source address so that a proper inbound
4962 			 * load spreading would happen.
4963 			 */
4964 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4965 			ipif_t *src_ipif = NULL;
4966 			ire_t *ipif_ire;
4967 
4968 			/*
4969 			 * Supply a local source address such that inbound
4970 			 * load spreading happens.
4971 			 *
4972 			 * Determine the best source address on this ill for
4973 			 * the destination.
4974 			 *
4975 			 * 1) For broadcast, we should return a broadcast ire
4976 			 *    found above so that upper layers know that the
4977 			 *    destination address is a broadcast address.
4978 			 *
4979 			 * 2) If this is part of a group, select a better
4980 			 *    source address so that better inbound load
4981 			 *    balancing happens. Do the same if the ipif
4982 			 *    is DEPRECATED.
4983 			 *
4984 			 * 3) If the outgoing interface is part of a usesrc
4985 			 *    group, then try selecting a source address from
4986 			 *    the usesrc ILL.
4987 			 */
4988 			if ((dst_ire->ire_zoneid != zoneid &&
4989 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4990 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4991 			    ((dst_ill->ill_group != NULL) ||
4992 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4993 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4994 				/*
4995 				 * If the destination is reachable via a
4996 				 * given gateway, the selected source address
4997 				 * should be in the same subnet as the gateway.
4998 				 * Otherwise, the destination is not reachable.
4999 				 *
5000 				 * If there are no interfaces on the same subnet
5001 				 * as the destination, ipif_select_source gives
5002 				 * first non-deprecated interface which might be
5003 				 * on a different subnet than the gateway.
5004 				 * This is not desirable. Hence pass the dst_ire
5005 				 * source address to ipif_select_source.
5006 				 * It is sure that the destination is reachable
5007 				 * with the dst_ire source address subnet.
5008 				 * So passing dst_ire source address to
5009 				 * ipif_select_source will make sure that the
5010 				 * selected source will be on the same subnet
5011 				 * as dst_ire source address.
5012 				 */
5013 				ipaddr_t saddr =
5014 				    dst_ire->ire_ipif->ipif_src_addr;
5015 				src_ipif = ipif_select_source(dst_ill,
5016 				    saddr, zoneid);
5017 				if (src_ipif != NULL) {
5018 					if (IS_VNI(src_ipif->ipif_ill)) {
5019 						/*
5020 						 * For VNI there is no
5021 						 * interface route
5022 						 */
5023 						src_addr =
5024 						    src_ipif->ipif_src_addr;
5025 					} else {
5026 						ipif_ire =
5027 						    ipif_to_ire(src_ipif);
5028 						if (ipif_ire != NULL) {
5029 							IRE_REFRELE(dst_ire);
5030 							dst_ire = ipif_ire;
5031 						}
5032 						src_addr =
5033 						    dst_ire->ire_src_addr;
5034 					}
5035 					ipif_refrele(src_ipif);
5036 				} else {
5037 					src_addr = dst_ire->ire_src_addr;
5038 				}
5039 			} else {
5040 				src_addr = dst_ire->ire_src_addr;
5041 			}
5042 		}
5043 	}
5044 
5045 	/*
5046 	 * We do ire_route_lookup() here (and not
5047 	 * interface lookup as we assert that
5048 	 * src_addr should only come from an
5049 	 * UP interface for hard binding.
5050 	 */
5051 	ASSERT(src_ire == NULL);
5052 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5053 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5054 	/* src_ire must be a local|loopback */
5055 	if (!IRE_IS_LOCAL(src_ire)) {
5056 		if (ip_debug > 2) {
5057 			pr_addr_dbg("ip_bind_connected: bad connected "
5058 			    "src %s\n", AF_INET, &src_addr);
5059 		}
5060 		error = EADDRNOTAVAIL;
5061 		goto bad_addr;
5062 	}
5063 
5064 	/*
5065 	 * If the source address is a loopback address, the
5066 	 * destination had best be local or multicast.
5067 	 * The transports that can't handle multicast will reject
5068 	 * those addresses.
5069 	 */
5070 	if (src_ire->ire_type == IRE_LOOPBACK &&
5071 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5072 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5073 		error = -1;
5074 		goto bad_addr;
5075 	}
5076 
5077 	/*
5078 	 * Allow setting new policies. For example, disconnects come
5079 	 * down as ipa_t bind. As we would have set conn_policy_cached
5080 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5081 	 * can change after the disconnect.
5082 	 */
5083 	connp->conn_policy_cached = B_FALSE;
5084 
5085 	/*
5086 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5087 	 * can handle their passed-in conn's.
5088 	 */
5089 
5090 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5091 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5092 	connp->conn_lport = lport;
5093 	connp->conn_fport = fport;
5094 	*src_addrp = src_addr;
5095 
5096 	ASSERT(!(ipsec_policy_set && ire_requested));
5097 	if (ire_requested) {
5098 		iulp_t *ulp_info = NULL;
5099 
5100 		/*
5101 		 * Note that sire will not be NULL if this is an off-link
5102 		 * connection and there is not cache for that dest yet.
5103 		 *
5104 		 * XXX Because of an existing bug, if there are multiple
5105 		 * default routes, the IRE returned now may not be the actual
5106 		 * default route used (default routes are chosen in a
5107 		 * round robin fashion).  So if the metrics for different
5108 		 * default routes are different, we may return the wrong
5109 		 * metrics.  This will not be a problem if the existing
5110 		 * bug is fixed.
5111 		 */
5112 		if (sire != NULL) {
5113 			ulp_info = &(sire->ire_uinfo);
5114 		}
5115 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5116 			error = -1;
5117 			goto bad_addr;
5118 		}
5119 	} else if (ipsec_policy_set) {
5120 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5121 			error = -1;
5122 			goto bad_addr;
5123 		}
5124 	}
5125 
5126 	/*
5127 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5128 	 * we'll cache that.  If we don't, we'll inherit global policy.
5129 	 *
5130 	 * We can't insert until the conn reflects the policy. Note that
5131 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5132 	 * connections where we don't have a policy. This is to prevent
5133 	 * global policy lookups in the inbound path.
5134 	 *
5135 	 * If we insert before we set conn_policy_cached,
5136 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5137 	 * because global policy cound be non-empty. We normally call
5138 	 * ipsec_check_policy() for conn_policy_cached connections only if
5139 	 * ipc_in_enforce_policy is set. But in this case,
5140 	 * conn_policy_cached can get set anytime since we made the
5141 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5142 	 * called, which will make the above assumption false.  Thus, we
5143 	 * need to insert after we set conn_policy_cached.
5144 	 */
5145 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5146 		goto bad_addr;
5147 
5148 	if (fanout_insert) {
5149 		/*
5150 		 * The addresses have been verified. Time to insert in
5151 		 * the correct fanout list.
5152 		 * We need to make sure that the conn_recv is set to a non-null
5153 		 * value before we insert into the classifier table to avoid a
5154 		 * race with an incoming packet which does an ipcl_classify().
5155 		 */
5156 		if (protocol == IPPROTO_TCP)
5157 			connp->conn_recv = tcp_input;
5158 		error = ipcl_conn_insert(connp, protocol, src_addr,
5159 		    dst_addr, connp->conn_ports);
5160 	}
5161 
5162 	if (error == 0) {
5163 		connp->conn_fully_bound = B_TRUE;
5164 		/*
5165 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5166 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5167 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5168 		 * ip_xxinfo_return(), which performs further checks
5169 		 * against them and upon success, returns the LSO/MDT info
5170 		 * mblk which we will attach to the bind acknowledgment.
5171 		 */
5172 		if (lso_dst_ire != NULL) {
5173 			mblk_t *lsoinfo_mp;
5174 
5175 			ASSERT(ill->ill_lso_capab != NULL);
5176 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5177 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5178 				linkb(mp, lsoinfo_mp);
5179 		} else if (md_dst_ire != NULL) {
5180 			mblk_t *mdinfo_mp;
5181 
5182 			ASSERT(ill->ill_mdt_capab != NULL);
5183 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5184 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5185 				linkb(mp, mdinfo_mp);
5186 		}
5187 	}
5188 bad_addr:
5189 	if (ipsec_policy_set) {
5190 		ASSERT(policy_mp == mp->b_cont);
5191 		ASSERT(policy_mp != NULL);
5192 		freeb(policy_mp);
5193 		/*
5194 		 * As of now assume that nothing else accompanies
5195 		 * IPSEC_POLICY_SET.
5196 		 */
5197 		mp->b_cont = NULL;
5198 	}
5199 	if (src_ire != NULL)
5200 		IRE_REFRELE(src_ire);
5201 	if (dst_ire != NULL)
5202 		IRE_REFRELE(dst_ire);
5203 	if (sire != NULL)
5204 		IRE_REFRELE(sire);
5205 	if (md_dst_ire != NULL)
5206 		IRE_REFRELE(md_dst_ire);
5207 	if (lso_dst_ire != NULL)
5208 		IRE_REFRELE(lso_dst_ire);
5209 	return (error);
5210 }
5211 
5212 /*
5213  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5214  * Prefers dst_ire over src_ire.
5215  */
5216 static boolean_t
5217 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5218 {
5219 	mblk_t	*mp1;
5220 	ire_t *ret_ire = NULL;
5221 
5222 	mp1 = mp->b_cont;
5223 	ASSERT(mp1 != NULL);
5224 
5225 	if (ire != NULL) {
5226 		/*
5227 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5228 		 * appended mblk. Its <upper protocol>'s
5229 		 * job to make sure there is room.
5230 		 */
5231 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5232 			return (0);
5233 
5234 		mp1->b_datap->db_type = IRE_DB_TYPE;
5235 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5236 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5237 		ret_ire = (ire_t *)mp1->b_rptr;
5238 		/*
5239 		 * Pass the latest setting of the ip_path_mtu_discovery and
5240 		 * copy the ulp info if any.
5241 		 */
5242 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5243 		    IPH_DF : 0;
5244 		if (ulp_info != NULL) {
5245 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5246 			    sizeof (iulp_t));
5247 		}
5248 		ret_ire->ire_mp = mp1;
5249 	} else {
5250 		/*
5251 		 * No IRE was found. Remove IRE mblk.
5252 		 */
5253 		mp->b_cont = mp1->b_cont;
5254 		freeb(mp1);
5255 	}
5256 
5257 	return (1);
5258 }
5259 
5260 /*
5261  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5262  * the final piece where we don't.  Return a pointer to the first mblk in the
5263  * result, and update the pointer to the next mblk to chew on.  If anything
5264  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5265  * NULL pointer.
5266  */
5267 mblk_t *
5268 ip_carve_mp(mblk_t **mpp, ssize_t len)
5269 {
5270 	mblk_t	*mp0;
5271 	mblk_t	*mp1;
5272 	mblk_t	*mp2;
5273 
5274 	if (!len || !mpp || !(mp0 = *mpp))
5275 		return (NULL);
5276 	/* If we aren't going to consume the first mblk, we need a dup. */
5277 	if (mp0->b_wptr - mp0->b_rptr > len) {
5278 		mp1 = dupb(mp0);
5279 		if (mp1) {
5280 			/* Partition the data between the two mblks. */
5281 			mp1->b_wptr = mp1->b_rptr + len;
5282 			mp0->b_rptr = mp1->b_wptr;
5283 			/*
5284 			 * after adjustments if mblk not consumed is now
5285 			 * unaligned, try to align it. If this fails free
5286 			 * all messages and let upper layer recover.
5287 			 */
5288 			if (!OK_32PTR(mp0->b_rptr)) {
5289 				if (!pullupmsg(mp0, -1)) {
5290 					freemsg(mp0);
5291 					freemsg(mp1);
5292 					*mpp = NULL;
5293 					return (NULL);
5294 				}
5295 			}
5296 		}
5297 		return (mp1);
5298 	}
5299 	/* Eat through as many mblks as we need to get len bytes. */
5300 	len -= mp0->b_wptr - mp0->b_rptr;
5301 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5302 		if (mp2->b_wptr - mp2->b_rptr > len) {
5303 			/*
5304 			 * We won't consume the entire last mblk.  Like
5305 			 * above, dup and partition it.
5306 			 */
5307 			mp1->b_cont = dupb(mp2);
5308 			mp1 = mp1->b_cont;
5309 			if (!mp1) {
5310 				/*
5311 				 * Trouble.  Rather than go to a lot of
5312 				 * trouble to clean up, we free the messages.
5313 				 * This won't be any worse than losing it on
5314 				 * the wire.
5315 				 */
5316 				freemsg(mp0);
5317 				freemsg(mp2);
5318 				*mpp = NULL;
5319 				return (NULL);
5320 			}
5321 			mp1->b_wptr = mp1->b_rptr + len;
5322 			mp2->b_rptr = mp1->b_wptr;
5323 			/*
5324 			 * after adjustments if mblk not consumed is now
5325 			 * unaligned, try to align it. If this fails free
5326 			 * all messages and let upper layer recover.
5327 			 */
5328 			if (!OK_32PTR(mp2->b_rptr)) {
5329 				if (!pullupmsg(mp2, -1)) {
5330 					freemsg(mp0);
5331 					freemsg(mp2);
5332 					*mpp = NULL;
5333 					return (NULL);
5334 				}
5335 			}
5336 			*mpp = mp2;
5337 			return (mp0);
5338 		}
5339 		/* Decrement len by the amount we just got. */
5340 		len -= mp2->b_wptr - mp2->b_rptr;
5341 	}
5342 	/*
5343 	 * len should be reduced to zero now.  If not our caller has
5344 	 * screwed up.
5345 	 */
5346 	if (len) {
5347 		/* Shouldn't happen! */
5348 		freemsg(mp0);
5349 		*mpp = NULL;
5350 		return (NULL);
5351 	}
5352 	/*
5353 	 * We consumed up to exactly the end of an mblk.  Detach the part
5354 	 * we are returning from the rest of the chain.
5355 	 */
5356 	mp1->b_cont = NULL;
5357 	*mpp = mp2;
5358 	return (mp0);
5359 }
5360 
5361 /* The ill stream is being unplumbed. Called from ip_close */
5362 int
5363 ip_modclose(ill_t *ill)
5364 {
5365 
5366 	boolean_t success;
5367 	ipsq_t	*ipsq;
5368 	ipif_t	*ipif;
5369 	queue_t	*q = ill->ill_rq;
5370 	hook_nic_event_t *info;
5371 
5372 	/*
5373 	 * Forcibly enter the ipsq after some delay. This is to take
5374 	 * care of the case when some ioctl does not complete because
5375 	 * we sent a control message to the driver and it did not
5376 	 * send us a reply. We want to be able to at least unplumb
5377 	 * and replumb rather than force the user to reboot the system.
5378 	 */
5379 	success = ipsq_enter(ill, B_FALSE);
5380 
5381 	/*
5382 	 * Open/close/push/pop is guaranteed to be single threaded
5383 	 * per stream by STREAMS. FS guarantees that all references
5384 	 * from top are gone before close is called. So there can't
5385 	 * be another close thread that has set CONDEMNED on this ill.
5386 	 * and cause ipsq_enter to return failure.
5387 	 */
5388 	ASSERT(success);
5389 	ipsq = ill->ill_phyint->phyint_ipsq;
5390 
5391 	/*
5392 	 * Mark it condemned. No new reference will be made to this ill.
5393 	 * Lookup functions will return an error. Threads that try to
5394 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5395 	 * that the refcnt will drop down to zero.
5396 	 */
5397 	mutex_enter(&ill->ill_lock);
5398 	ill->ill_state_flags |= ILL_CONDEMNED;
5399 	for (ipif = ill->ill_ipif; ipif != NULL;
5400 	    ipif = ipif->ipif_next) {
5401 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5402 	}
5403 	/*
5404 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5405 	 * returns  error if ILL_CONDEMNED is set
5406 	 */
5407 	cv_broadcast(&ill->ill_cv);
5408 	mutex_exit(&ill->ill_lock);
5409 
5410 	/*
5411 	 * Shut down fragmentation reassembly.
5412 	 * ill_frag_timer won't start a timer again.
5413 	 * Now cancel any existing timer
5414 	 */
5415 	(void) untimeout(ill->ill_frag_timer_id);
5416 	(void) ill_frag_timeout(ill, 0);
5417 
5418 	/*
5419 	 * If MOVE was in progress, clear the
5420 	 * move_in_progress fields also.
5421 	 */
5422 	if (ill->ill_move_in_progress) {
5423 		ILL_CLEAR_MOVE(ill);
5424 	}
5425 
5426 	/*
5427 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5428 	 * this ill. Then wait for the refcnts to drop to zero.
5429 	 * ill_is_quiescent checks whether the ill is really quiescent.
5430 	 * Then make sure that threads that are waiting to enter the
5431 	 * ipsq have seen the error returned by ipsq_enter and have
5432 	 * gone away. Then we call ill_delete_tail which does the
5433 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5434 	 */
5435 	ill_delete(ill);
5436 	mutex_enter(&ill->ill_lock);
5437 	while (!ill_is_quiescent(ill))
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 	while (ill->ill_waiters)
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 
5442 	mutex_exit(&ill->ill_lock);
5443 
5444 	/* qprocsoff is called in ill_delete_tail */
5445 	ill_delete_tail(ill);
5446 
5447 	/*
5448 	 * Walk through all upper (conn) streams and qenable
5449 	 * those that have queued data.
5450 	 * close synchronization needs this to
5451 	 * be done to ensure that all upper layers blocked
5452 	 * due to flow control to the closing device
5453 	 * get unblocked.
5454 	 */
5455 	ip1dbg(("ip_wsrv: walking\n"));
5456 	conn_walk_drain();
5457 
5458 	mutex_enter(&ip_mi_lock);
5459 	mi_close_unlink(&ip_g_head, (IDP)ill);
5460 	mutex_exit(&ip_mi_lock);
5461 
5462 	/*
5463 	 * credp could be null if the open didn't succeed and ip_modopen
5464 	 * itself calls ip_close.
5465 	 */
5466 	if (ill->ill_credp != NULL)
5467 		crfree(ill->ill_credp);
5468 
5469 	/*
5470 	 * Unhook the nic event message from the ill and enqueue it into the nic
5471 	 * event taskq.
5472 	 */
5473 	if ((info = ill->ill_nic_event_info) != NULL) {
5474 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5475 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5476 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5477 			if (info->hne_data != NULL)
5478 				kmem_free(info->hne_data, info->hne_datalen);
5479 			kmem_free(info, sizeof (hook_nic_event_t));
5480 		}
5481 		ill->ill_nic_event_info = NULL;
5482 	}
5483 
5484 	mi_close_free((IDP)ill);
5485 	q->q_ptr = WR(q)->q_ptr = NULL;
5486 
5487 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5488 
5489 	return (0);
5490 }
5491 
5492 /*
5493  * This is called as part of close() for both IP and UDP
5494  * in order to quiesce the conn.
5495  */
5496 void
5497 ip_quiesce_conn(conn_t *connp)
5498 {
5499 	boolean_t	drain_cleanup_reqd = B_FALSE;
5500 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5501 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5502 
5503 	ASSERT(!IPCL_IS_TCP(connp));
5504 
5505 	/*
5506 	 * Mark the conn as closing, and this conn must not be
5507 	 * inserted in future into any list. Eg. conn_drain_insert(),
5508 	 * won't insert this conn into the conn_drain_list.
5509 	 * Similarly ill_pending_mp_add() will not add any mp to
5510 	 * the pending mp list, after this conn has started closing.
5511 	 *
5512 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5513 	 * cannot get set henceforth.
5514 	 */
5515 	mutex_enter(&connp->conn_lock);
5516 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5517 	connp->conn_state_flags |= CONN_CLOSING;
5518 	if (connp->conn_idl != NULL)
5519 		drain_cleanup_reqd = B_TRUE;
5520 	if (connp->conn_oper_pending_ill != NULL)
5521 		conn_ioctl_cleanup_reqd = B_TRUE;
5522 	if (connp->conn_ilg_inuse != 0)
5523 		ilg_cleanup_reqd = B_TRUE;
5524 	mutex_exit(&connp->conn_lock);
5525 
5526 	if (IPCL_IS_UDP(connp))
5527 		udp_quiesce_conn(connp);
5528 
5529 	if (conn_ioctl_cleanup_reqd)
5530 		conn_ioctl_cleanup(connp);
5531 
5532 	if (is_system_labeled() && connp->conn_anon_port) {
5533 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5534 		    connp->conn_mlp_type, connp->conn_ulp,
5535 		    ntohs(connp->conn_lport), B_FALSE);
5536 		connp->conn_anon_port = 0;
5537 	}
5538 	connp->conn_mlp_type = mlptSingle;
5539 
5540 	/*
5541 	 * Remove this conn from any fanout list it is on.
5542 	 * and then wait for any threads currently operating
5543 	 * on this endpoint to finish
5544 	 */
5545 	ipcl_hash_remove(connp);
5546 
5547 	/*
5548 	 * Remove this conn from the drain list, and do
5549 	 * any other cleanup that may be required.
5550 	 * (Only non-tcp streams may have a non-null conn_idl.
5551 	 * TCP streams are never flow controlled, and
5552 	 * conn_idl will be null)
5553 	 */
5554 	if (drain_cleanup_reqd)
5555 		conn_drain_tail(connp, B_TRUE);
5556 
5557 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5558 		(void) ip_mrouter_done(NULL);
5559 
5560 	if (ilg_cleanup_reqd)
5561 		ilg_delete_all(connp);
5562 
5563 	conn_delete_ire(connp, NULL);
5564 
5565 	/*
5566 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5567 	 * callers from write side can't be there now because close
5568 	 * is in progress. The only other caller is ipcl_walk
5569 	 * which checks for the condemned flag.
5570 	 */
5571 	mutex_enter(&connp->conn_lock);
5572 	connp->conn_state_flags |= CONN_CONDEMNED;
5573 	while (connp->conn_ref != 1)
5574 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5575 	connp->conn_state_flags |= CONN_QUIESCED;
5576 	mutex_exit(&connp->conn_lock);
5577 }
5578 
5579 /* ARGSUSED */
5580 int
5581 ip_close(queue_t *q, int flags)
5582 {
5583 	conn_t		*connp;
5584 
5585 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5586 
5587 	/*
5588 	 * Call the appropriate delete routine depending on whether this is
5589 	 * a module or device.
5590 	 */
5591 	if (WR(q)->q_next != NULL) {
5592 		/* This is a module close */
5593 		return (ip_modclose((ill_t *)q->q_ptr));
5594 	}
5595 
5596 	connp = q->q_ptr;
5597 	ip_quiesce_conn(connp);
5598 
5599 	qprocsoff(q);
5600 
5601 	/*
5602 	 * Now we are truly single threaded on this stream, and can
5603 	 * delete the things hanging off the connp, and finally the connp.
5604 	 * We removed this connp from the fanout list, it cannot be
5605 	 * accessed thru the fanouts, and we already waited for the
5606 	 * conn_ref to drop to 0. We are already in close, so
5607 	 * there cannot be any other thread from the top. qprocsoff
5608 	 * has completed, and service has completed or won't run in
5609 	 * future.
5610 	 */
5611 	ASSERT(connp->conn_ref == 1);
5612 
5613 	/*
5614 	 * A conn which was previously marked as IPCL_UDP cannot
5615 	 * retain the flag because it would have been cleared by
5616 	 * udp_close().
5617 	 */
5618 	ASSERT(!IPCL_IS_UDP(connp));
5619 
5620 	if (connp->conn_latch != NULL) {
5621 		IPLATCH_REFRELE(connp->conn_latch);
5622 		connp->conn_latch = NULL;
5623 	}
5624 	if (connp->conn_policy != NULL) {
5625 		IPPH_REFRELE(connp->conn_policy);
5626 		connp->conn_policy = NULL;
5627 	}
5628 	if (connp->conn_ipsec_opt_mp != NULL) {
5629 		freemsg(connp->conn_ipsec_opt_mp);
5630 		connp->conn_ipsec_opt_mp = NULL;
5631 	}
5632 
5633 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5634 
5635 	connp->conn_ref--;
5636 	ipcl_conn_destroy(connp);
5637 
5638 	q->q_ptr = WR(q)->q_ptr = NULL;
5639 	return (0);
5640 }
5641 
5642 int
5643 ip_snmpmod_close(queue_t *q)
5644 {
5645 	conn_t *connp = Q_TO_CONN(q);
5646 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5647 
5648 	qprocsoff(q);
5649 
5650 	if (connp->conn_flags & IPCL_UDPMOD)
5651 		udp_close_free(connp);
5652 
5653 	if (connp->conn_cred != NULL) {
5654 		crfree(connp->conn_cred);
5655 		connp->conn_cred = NULL;
5656 	}
5657 	CONN_DEC_REF(connp);
5658 	q->q_ptr = WR(q)->q_ptr = NULL;
5659 	return (0);
5660 }
5661 
5662 /*
5663  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5664  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5665  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5666  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5667  * queues as we never enqueue messages there and we don't handle any ioctls.
5668  * Everything else is freed.
5669  */
5670 void
5671 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5672 {
5673 	conn_t	*connp = q->q_ptr;
5674 	pfi_t	setfn;
5675 	pfi_t	getfn;
5676 
5677 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5678 
5679 	switch (DB_TYPE(mp)) {
5680 	case M_PROTO:
5681 	case M_PCPROTO:
5682 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5683 		    ((((union T_primitives *)mp->b_rptr)->type ==
5684 			T_SVR4_OPTMGMT_REQ) ||
5685 		    (((union T_primitives *)mp->b_rptr)->type ==
5686 			T_OPTMGMT_REQ))) {
5687 			/*
5688 			 * This is the only TPI primitive supported. Its
5689 			 * handling does not require tcp_t, but it does require
5690 			 * conn_t to check permissions.
5691 			 */
5692 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5693 
5694 			if (connp->conn_flags & IPCL_TCPMOD) {
5695 				setfn = tcp_snmp_set;
5696 				getfn = tcp_snmp_get;
5697 			} else {
5698 				setfn = udp_snmp_set;
5699 				getfn = udp_snmp_get;
5700 			}
5701 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5702 				freemsg(mp);
5703 				return;
5704 			}
5705 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5706 		    != NULL)
5707 			qreply(q, mp);
5708 		break;
5709 	case M_FLUSH:
5710 	case M_IOCTL:
5711 		putnext(q, mp);
5712 		break;
5713 	default:
5714 		freemsg(mp);
5715 		break;
5716 	}
5717 }
5718 
5719 /* Return the IP checksum for the IP header at "iph". */
5720 uint16_t
5721 ip_csum_hdr(ipha_t *ipha)
5722 {
5723 	uint16_t	*uph;
5724 	uint32_t	sum;
5725 	int		opt_len;
5726 
5727 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5728 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5729 	uph = (uint16_t *)ipha;
5730 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5731 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5732 	if (opt_len > 0) {
5733 		do {
5734 			sum += uph[10];
5735 			sum += uph[11];
5736 			uph += 2;
5737 		} while (--opt_len);
5738 	}
5739 	sum = (sum & 0xFFFF) + (sum >> 16);
5740 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5741 	if (sum == 0xffff)
5742 		sum = 0;
5743 	return ((uint16_t)sum);
5744 }
5745 
5746 void
5747 ip_ddi_destroy(void)
5748 {
5749 	ipv4_hook_destroy();
5750 	ipv6_hook_destroy();
5751 	ip_net_destroy();
5752 
5753 	tnet_fini();
5754 	tcp_ddi_destroy();
5755 	sctp_ddi_destroy();
5756 	ipsec_loader_destroy();
5757 	ipsec_policy_destroy();
5758 	ipsec_kstat_destroy();
5759 	nd_free(&ip_g_nd);
5760 	mutex_destroy(&igmp_timer_lock);
5761 	mutex_destroy(&mld_timer_lock);
5762 	mutex_destroy(&igmp_slowtimeout_lock);
5763 	mutex_destroy(&mld_slowtimeout_lock);
5764 	mutex_destroy(&ip_mi_lock);
5765 	mutex_destroy(&rts_clients.connf_lock);
5766 	ip_ire_fini();
5767 	ip6_asp_free();
5768 	conn_drain_fini();
5769 	ipcl_destroy();
5770 	inet_minor_destroy(ip_minor_arena);
5771 	icmp_kstat_fini();
5772 	ip_kstat_fini();
5773 	rw_destroy(&ipsec_capab_ills_lock);
5774 	rw_destroy(&ill_g_usesrc_lock);
5775 	ip_drop_unregister(&ip_dropper);
5776 }
5777 
5778 
5779 void
5780 ip_ddi_init(void)
5781 {
5782 	TCP6_MAJ = ddi_name_to_major(TCP6);
5783 	TCP_MAJ	= ddi_name_to_major(TCP);
5784 	SCTP_MAJ = ddi_name_to_major(SCTP);
5785 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5786 
5787 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5788 
5789 	/* IP's IPsec code calls the packet dropper */
5790 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5791 
5792 	if (!ip_g_nd) {
5793 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5794 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5795 			nd_free(&ip_g_nd);
5796 		}
5797 	}
5798 
5799 	ipsec_loader_init();
5800 	ipsec_policy_init();
5801 	ipsec_kstat_init();
5802 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5803 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5804 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5805 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5806 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5807 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5808 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5809 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5810 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5811 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5812 
5813 	/*
5814 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5815 	 * initial devices: ip, ip6, tcp, tcp6.
5816 	 */
5817 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5818 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5819 		cmn_err(CE_PANIC,
5820 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5821 	}
5822 
5823 	ipcl_init();
5824 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5825 	ip_ire_init();
5826 	ip6_asp_init();
5827 	ipif_init();
5828 	conn_drain_init();
5829 	tcp_ddi_init();
5830 	sctp_ddi_init();
5831 
5832 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5833 
5834 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5835 		"net", KSTAT_TYPE_NAMED,
5836 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5837 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5838 		ip_kstat->ks_data = &ip_statistics;
5839 		kstat_install(ip_kstat);
5840 	}
5841 	ip_kstat_init();
5842 	ip6_kstat_init();
5843 	icmp_kstat_init();
5844 	ipsec_loader_start();
5845 	tnet_init();
5846 
5847 	ip_net_init();
5848 	ipv4_hook_init();
5849 	ipv6_hook_init();
5850 }
5851 
5852 /*
5853  * Allocate and initialize a DLPI template of the specified length.  (May be
5854  * called as writer.)
5855  */
5856 mblk_t *
5857 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5858 {
5859 	mblk_t	*mp;
5860 
5861 	mp = allocb(len, BPRI_MED);
5862 	if (!mp)
5863 		return (NULL);
5864 
5865 	/*
5866 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5867 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5868 	 * that other DLPI are M_PROTO.
5869 	 */
5870 	if (prim == DL_INFO_REQ) {
5871 		mp->b_datap->db_type = M_PCPROTO;
5872 	} else {
5873 		mp->b_datap->db_type = M_PROTO;
5874 	}
5875 
5876 	mp->b_wptr = mp->b_rptr + len;
5877 	bzero(mp->b_rptr, len);
5878 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5879 	return (mp);
5880 }
5881 
5882 const char *
5883 dlpi_prim_str(int prim)
5884 {
5885 	switch (prim) {
5886 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5887 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5888 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5889 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5890 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5891 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5892 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5893 	case DL_OK_ACK:		return ("DL_OK_ACK");
5894 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5895 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5896 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5897 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5898 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5899 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5900 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5901 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5902 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5903 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5904 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5905 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5906 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5907 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5908 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5909 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5910 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5911 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5912 	default:		return ("<unknown primitive>");
5913 	}
5914 }
5915 
5916 const char *
5917 dlpi_err_str(int err)
5918 {
5919 	switch (err) {
5920 	case DL_ACCESS:		return ("DL_ACCESS");
5921 	case DL_BADADDR:	return ("DL_BADADDR");
5922 	case DL_BADCORR:	return ("DL_BADCORR");
5923 	case DL_BADDATA:	return ("DL_BADDATA");
5924 	case DL_BADPPA:		return ("DL_BADPPA");
5925 	case DL_BADPRIM:	return ("DL_BADPRIM");
5926 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5927 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5928 	case DL_BADSAP:		return ("DL_BADSAP");
5929 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5930 	case DL_BOUND:		return ("DL_BOUND");
5931 	case DL_INITFAILED:	return ("DL_INITFAILED");
5932 	case DL_NOADDR:		return ("DL_NOADDR");
5933 	case DL_NOTINIT:	return ("DL_NOTINIT");
5934 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5935 	case DL_SYSERR:		return ("DL_SYSERR");
5936 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5937 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5938 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5939 	case DL_TOOMANY:	return ("DL_TOOMANY");
5940 	case DL_NOTENAB:	return ("DL_NOTENAB");
5941 	case DL_BUSY:		return ("DL_BUSY");
5942 	case DL_NOAUTO:		return ("DL_NOAUTO");
5943 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5944 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5945 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5946 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5947 	case DL_PENDING:	return ("DL_PENDING");
5948 	default:		return ("<unknown error>");
5949 	}
5950 }
5951 
5952 /*
5953  * Debug formatting routine.  Returns a character string representation of the
5954  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5955  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5956  *
5957  * Once the ndd table-printing interfaces are removed, this can be changed to
5958  * standard dotted-decimal form.
5959  */
5960 char *
5961 ip_dot_addr(ipaddr_t addr, char *buf)
5962 {
5963 	uint8_t *ap = (uint8_t *)&addr;
5964 
5965 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5966 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5967 	return (buf);
5968 }
5969 
5970 /*
5971  * Write the given MAC address as a printable string in the usual colon-
5972  * separated format.
5973  */
5974 const char *
5975 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5976 {
5977 	char *bp;
5978 
5979 	if (alen == 0 || buflen < 4)
5980 		return ("?");
5981 	bp = buf;
5982 	for (;;) {
5983 		/*
5984 		 * If there are more MAC address bytes available, but we won't
5985 		 * have any room to print them, then add "..." to the string
5986 		 * instead.  See below for the 'magic number' explanation.
5987 		 */
5988 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5989 			(void) strcpy(bp, "...");
5990 			break;
5991 		}
5992 		(void) sprintf(bp, "%02x", *addr++);
5993 		bp += 2;
5994 		if (--alen == 0)
5995 			break;
5996 		*bp++ = ':';
5997 		buflen -= 3;
5998 		/*
5999 		 * At this point, based on the first 'if' statement above,
6000 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6001 		 * buflen >= 4.  The first case leaves room for the final "xx"
6002 		 * number and trailing NUL byte.  The second leaves room for at
6003 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6004 		 * that statement.
6005 		 */
6006 	}
6007 	return (buf);
6008 }
6009 
6010 /*
6011  * Send an ICMP error after patching up the packet appropriately.  Returns
6012  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6013  */
6014 static boolean_t
6015 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6016     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6017 {
6018 	ipha_t *ipha;
6019 	mblk_t *first_mp;
6020 	boolean_t secure;
6021 	unsigned char db_type;
6022 
6023 	first_mp = mp;
6024 	if (mctl_present) {
6025 		mp = mp->b_cont;
6026 		secure = ipsec_in_is_secure(first_mp);
6027 		ASSERT(mp != NULL);
6028 	} else {
6029 		/*
6030 		 * If this is an ICMP error being reported - which goes
6031 		 * up as M_CTLs, we need to convert them to M_DATA till
6032 		 * we finish checking with global policy because
6033 		 * ipsec_check_global_policy() assumes M_DATA as clear
6034 		 * and M_CTL as secure.
6035 		 */
6036 		db_type = DB_TYPE(mp);
6037 		DB_TYPE(mp) = M_DATA;
6038 		secure = B_FALSE;
6039 	}
6040 	/*
6041 	 * We are generating an icmp error for some inbound packet.
6042 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6043 	 * Before we generate an error, check with global policy
6044 	 * to see whether this is allowed to enter the system. As
6045 	 * there is no "conn", we are checking with global policy.
6046 	 */
6047 	ipha = (ipha_t *)mp->b_rptr;
6048 	if (secure || ipsec_inbound_v4_policy_present) {
6049 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6050 		    ipha, NULL, mctl_present);
6051 		if (first_mp == NULL)
6052 			return (B_FALSE);
6053 	}
6054 
6055 	if (!mctl_present)
6056 		DB_TYPE(mp) = db_type;
6057 
6058 	if (flags & IP_FF_SEND_ICMP) {
6059 		if (flags & IP_FF_HDR_COMPLETE) {
6060 			if (ip_hdr_complete(ipha, zoneid)) {
6061 				freemsg(first_mp);
6062 				return (B_TRUE);
6063 			}
6064 		}
6065 		if (flags & IP_FF_CKSUM) {
6066 			/*
6067 			 * Have to correct checksum since
6068 			 * the packet might have been
6069 			 * fragmented and the reassembly code in ip_rput
6070 			 * does not restore the IP checksum.
6071 			 */
6072 			ipha->ipha_hdr_checksum = 0;
6073 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6074 		}
6075 		switch (icmp_type) {
6076 		case ICMP_DEST_UNREACHABLE:
6077 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6078 			break;
6079 		default:
6080 			freemsg(first_mp);
6081 			break;
6082 		}
6083 	} else {
6084 		freemsg(first_mp);
6085 		return (B_FALSE);
6086 	}
6087 
6088 	return (B_TRUE);
6089 }
6090 
6091 /*
6092  * Used to send an ICMP error message when a packet is received for
6093  * a protocol that is not supported. The mblk passed as argument
6094  * is consumed by this function.
6095  */
6096 void
6097 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6098 {
6099 	mblk_t *mp;
6100 	ipha_t *ipha;
6101 	ill_t *ill;
6102 	ipsec_in_t *ii;
6103 
6104 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6105 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6106 
6107 	mp = ipsec_mp->b_cont;
6108 	ipsec_mp->b_cont = NULL;
6109 	ipha = (ipha_t *)mp->b_rptr;
6110 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6111 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6112 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6113 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6114 		}
6115 	} else {
6116 		/* Get ill from index in ipsec_in_t. */
6117 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6118 		    B_TRUE, NULL, NULL, NULL, NULL);
6119 		if (ill != NULL) {
6120 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6121 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6122 			    0, B_FALSE, zoneid)) {
6123 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6124 			}
6125 
6126 			ill_refrele(ill);
6127 		} else { /* re-link for the freemsg() below. */
6128 			ipsec_mp->b_cont = mp;
6129 		}
6130 	}
6131 
6132 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6133 	freemsg(ipsec_mp);
6134 }
6135 
6136 /*
6137  * See if the inbound datagram has had IPsec processing applied to it.
6138  */
6139 boolean_t
6140 ipsec_in_is_secure(mblk_t *ipsec_mp)
6141 {
6142 	ipsec_in_t *ii;
6143 
6144 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6145 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6146 
6147 	if (ii->ipsec_in_loopback) {
6148 		return (ii->ipsec_in_secure);
6149 	} else {
6150 		return (ii->ipsec_in_ah_sa != NULL ||
6151 		    ii->ipsec_in_esp_sa != NULL ||
6152 		    ii->ipsec_in_decaps);
6153 	}
6154 }
6155 
6156 /*
6157  * Handle protocols with which IP is less intimate.  There
6158  * can be more than one stream bound to a particular
6159  * protocol.  When this is the case, normally each one gets a copy
6160  * of any incoming packets.
6161  *
6162  * IPSEC NOTE :
6163  *
6164  * Don't allow a secure packet going up a non-secure connection.
6165  * We don't allow this because
6166  *
6167  * 1) Reply might go out in clear which will be dropped at
6168  *    the sending side.
6169  * 2) If the reply goes out in clear it will give the
6170  *    adversary enough information for getting the key in
6171  *    most of the cases.
6172  *
6173  * Moreover getting a secure packet when we expect clear
6174  * implies that SA's were added without checking for
6175  * policy on both ends. This should not happen once ISAKMP
6176  * is used to negotiate SAs as SAs will be added only after
6177  * verifying the policy.
6178  *
6179  * NOTE : If the packet was tunneled and not multicast we only send
6180  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6181  * back to delivering packets to AF_INET6 raw sockets.
6182  *
6183  * IPQoS Notes:
6184  * Once we have determined the client, invoke IPPF processing.
6185  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6186  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6187  * ip_policy will be false.
6188  *
6189  * Zones notes:
6190  * Currently only applications in the global zone can create raw sockets for
6191  * protocols other than ICMP. So unlike the broadcast / multicast case of
6192  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6193  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6194  */
6195 static void
6196 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6197     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6198     zoneid_t zoneid)
6199 {
6200 	queue_t	*rq;
6201 	mblk_t	*mp1, *first_mp1;
6202 	uint_t	protocol = ipha->ipha_protocol;
6203 	ipaddr_t dst;
6204 	boolean_t one_only;
6205 	mblk_t *first_mp = mp;
6206 	boolean_t secure;
6207 	uint32_t ill_index;
6208 	conn_t	*connp, *first_connp, *next_connp;
6209 	connf_t	*connfp;
6210 	boolean_t shared_addr;
6211 
6212 	if (mctl_present) {
6213 		mp = first_mp->b_cont;
6214 		secure = ipsec_in_is_secure(first_mp);
6215 		ASSERT(mp != NULL);
6216 	} else {
6217 		secure = B_FALSE;
6218 	}
6219 	dst = ipha->ipha_dst;
6220 	/*
6221 	 * If the packet was tunneled and not multicast we only send to it
6222 	 * the first match.
6223 	 */
6224 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6225 	    !CLASSD(dst));
6226 
6227 	shared_addr = (zoneid == ALL_ZONES);
6228 	if (shared_addr) {
6229 		/*
6230 		 * We don't allow multilevel ports for raw IP, so no need to
6231 		 * check for that here.
6232 		 */
6233 		zoneid = tsol_packet_to_zoneid(mp);
6234 	}
6235 
6236 	connfp = &ipcl_proto_fanout[protocol];
6237 	mutex_enter(&connfp->connf_lock);
6238 	connp = connfp->connf_head;
6239 	for (connp = connfp->connf_head; connp != NULL;
6240 		connp = connp->conn_next) {
6241 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6242 		    zoneid) &&
6243 		    (!is_system_labeled() ||
6244 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6245 		    connp)))
6246 			break;
6247 	}
6248 
6249 	if (connp == NULL || connp->conn_upq == NULL) {
6250 		/*
6251 		 * No one bound to these addresses.  Is
6252 		 * there a client that wants all
6253 		 * unclaimed datagrams?
6254 		 */
6255 		mutex_exit(&connfp->connf_lock);
6256 		/*
6257 		 * Check for IPPROTO_ENCAP...
6258 		 */
6259 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6260 			/*
6261 			 * If an IPsec mblk is here on a multicast
6262 			 * tunnel (using ip_mroute stuff), check policy here,
6263 			 * THEN ship off to ip_mroute_decap().
6264 			 *
6265 			 * BTW,  If I match a configured IP-in-IP
6266 			 * tunnel, this path will not be reached, and
6267 			 * ip_mroute_decap will never be called.
6268 			 */
6269 			first_mp = ipsec_check_global_policy(first_mp, connp,
6270 			    ipha, NULL, mctl_present);
6271 			if (first_mp != NULL) {
6272 				if (mctl_present)
6273 					freeb(first_mp);
6274 				ip_mroute_decap(q, mp);
6275 			} /* Else we already freed everything! */
6276 		} else {
6277 			/*
6278 			 * Otherwise send an ICMP protocol unreachable.
6279 			 */
6280 			if (ip_fanout_send_icmp(q, first_mp, flags,
6281 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6282 			    mctl_present, zoneid)) {
6283 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6284 			}
6285 		}
6286 		return;
6287 	}
6288 	CONN_INC_REF(connp);
6289 	first_connp = connp;
6290 
6291 	/*
6292 	 * Only send message to one tunnel driver by immediately
6293 	 * terminating the loop.
6294 	 */
6295 	connp = one_only ? NULL : connp->conn_next;
6296 
6297 	for (;;) {
6298 		while (connp != NULL) {
6299 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6300 			    flags, zoneid) &&
6301 			    (!is_system_labeled() ||
6302 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6303 			    shared_addr, connp)))
6304 				break;
6305 			connp = connp->conn_next;
6306 		}
6307 
6308 		/*
6309 		 * Copy the packet.
6310 		 */
6311 		if (connp == NULL || connp->conn_upq == NULL ||
6312 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6313 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6314 			/*
6315 			 * No more interested clients or memory
6316 			 * allocation failed
6317 			 */
6318 			connp = first_connp;
6319 			break;
6320 		}
6321 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6322 		CONN_INC_REF(connp);
6323 		mutex_exit(&connfp->connf_lock);
6324 		rq = connp->conn_rq;
6325 		if (!canputnext(rq)) {
6326 			if (flags & IP_FF_RAWIP) {
6327 				BUMP_MIB(&ip_mib, rawipInOverflows);
6328 			} else {
6329 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6330 			}
6331 
6332 			freemsg(first_mp1);
6333 		} else {
6334 			/*
6335 			 * Don't enforce here if we're an actual tunnel -
6336 			 * let "tun" do it instead.
6337 			 */
6338 			if (!IPCL_IS_IPTUN(connp) &&
6339 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6340 				first_mp1 = ipsec_check_inbound_policy
6341 				    (first_mp1, connp, ipha, NULL,
6342 				    mctl_present);
6343 			}
6344 			if (first_mp1 != NULL) {
6345 				/*
6346 				 * ip_fanout_proto also gets called from
6347 				 * icmp_inbound_error_fanout, in which case
6348 				 * the msg type is M_CTL.  Don't add info
6349 				 * in this case for the time being. In future
6350 				 * when there is a need for knowing the
6351 				 * inbound iface index for ICMP error msgs,
6352 				 * then this can be changed.
6353 				 */
6354 				if ((connp->conn_recvif != 0) &&
6355 				    (mp->b_datap->db_type != M_CTL)) {
6356 					/*
6357 					 * the actual data will be
6358 					 * contained in b_cont upon
6359 					 * successful return of the
6360 					 * following call else
6361 					 * original mblk is returned
6362 					 */
6363 					ASSERT(recv_ill != NULL);
6364 					mp1 = ip_add_info(mp1, recv_ill,
6365 						IPF_RECVIF);
6366 				}
6367 				BUMP_MIB(&ip_mib, ipInDelivers);
6368 				if (mctl_present)
6369 					freeb(first_mp1);
6370 				putnext(rq, mp1);
6371 			}
6372 		}
6373 		mutex_enter(&connfp->connf_lock);
6374 		/* Follow the next pointer before releasing the conn. */
6375 		next_connp = connp->conn_next;
6376 		CONN_DEC_REF(connp);
6377 		connp = next_connp;
6378 	}
6379 
6380 	/* Last one.  Send it upstream. */
6381 	mutex_exit(&connfp->connf_lock);
6382 
6383 	/*
6384 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6385 	 * will be set to false.
6386 	 */
6387 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6388 		ill_index = ill->ill_phyint->phyint_ifindex;
6389 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6390 		if (mp == NULL) {
6391 			CONN_DEC_REF(connp);
6392 			if (mctl_present) {
6393 				freeb(first_mp);
6394 			}
6395 			return;
6396 		}
6397 	}
6398 
6399 	rq = connp->conn_rq;
6400 	if (!canputnext(rq)) {
6401 		if (flags & IP_FF_RAWIP) {
6402 			BUMP_MIB(&ip_mib, rawipInOverflows);
6403 		} else {
6404 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6405 		}
6406 
6407 		freemsg(first_mp);
6408 	} else {
6409 		if (IPCL_IS_IPTUN(connp)) {
6410 			/*
6411 			 * Tunneled packet.  We enforce policy in the tunnel
6412 			 * module itself.
6413 			 *
6414 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6415 			 * a policy check.
6416 			 */
6417 			putnext(rq, first_mp);
6418 			CONN_DEC_REF(connp);
6419 			return;
6420 		}
6421 
6422 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6423 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6424 			    ipha, NULL, mctl_present);
6425 		}
6426 
6427 		if (first_mp != NULL) {
6428 			/*
6429 			 * ip_fanout_proto also gets called
6430 			 * from icmp_inbound_error_fanout, in
6431 			 * which case the msg type is M_CTL.
6432 			 * Don't add info in this case for time
6433 			 * being. In future when there is a
6434 			 * need for knowing the inbound iface
6435 			 * index for ICMP error msgs, then this
6436 			 * can be changed
6437 			 */
6438 			if ((connp->conn_recvif != 0) &&
6439 			    (mp->b_datap->db_type != M_CTL)) {
6440 				/*
6441 				 * the actual data will be contained in
6442 				 * b_cont upon successful return
6443 				 * of the following call else original
6444 				 * mblk is returned
6445 				 */
6446 				ASSERT(recv_ill != NULL);
6447 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6448 			}
6449 			BUMP_MIB(&ip_mib, ipInDelivers);
6450 			putnext(rq, mp);
6451 			if (mctl_present)
6452 				freeb(first_mp);
6453 		}
6454 	}
6455 	CONN_DEC_REF(connp);
6456 }
6457 
6458 /*
6459  * Fanout for TCP packets
6460  * The caller puts <fport, lport> in the ports parameter.
6461  *
6462  * IPQoS Notes
6463  * Before sending it to the client, invoke IPPF processing.
6464  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6465  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6466  * ip_policy is false.
6467  */
6468 static void
6469 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6470     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6471 {
6472 	mblk_t  *first_mp;
6473 	boolean_t secure;
6474 	uint32_t ill_index;
6475 	int	ip_hdr_len;
6476 	tcph_t	*tcph;
6477 	boolean_t syn_present = B_FALSE;
6478 	conn_t	*connp;
6479 
6480 	first_mp = mp;
6481 	if (mctl_present) {
6482 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6483 		mp = first_mp->b_cont;
6484 		secure = ipsec_in_is_secure(first_mp);
6485 		ASSERT(mp != NULL);
6486 	} else {
6487 		secure = B_FALSE;
6488 	}
6489 
6490 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6491 
6492 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6493 	    NULL) {
6494 		/*
6495 		 * No connected connection or listener. Send a
6496 		 * TH_RST via tcp_xmit_listeners_reset.
6497 		 */
6498 
6499 		/* Initiate IPPf processing, if needed. */
6500 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6501 			uint32_t ill_index;
6502 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6503 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6504 			if (first_mp == NULL)
6505 				return;
6506 		}
6507 		BUMP_MIB(&ip_mib, ipInDelivers);
6508 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6509 		    zoneid));
6510 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6511 		return;
6512 	}
6513 
6514 	/*
6515 	 * Allocate the SYN for the TCP connection here itself
6516 	 */
6517 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6518 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6519 		if (IPCL_IS_TCP(connp)) {
6520 			squeue_t *sqp;
6521 
6522 			/*
6523 			 * For fused tcp loopback, assign the eager's
6524 			 * squeue to be that of the active connect's.
6525 			 * Note that we don't check for IP_FF_LOOPBACK
6526 			 * here since this routine gets called only
6527 			 * for loopback (unlike the IPv6 counterpart).
6528 			 */
6529 			ASSERT(Q_TO_CONN(q) != NULL);
6530 			if (do_tcp_fusion &&
6531 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6532 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6533 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6534 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6535 				sqp = Q_TO_CONN(q)->conn_sqp;
6536 			} else {
6537 				sqp = IP_SQUEUE_GET(lbolt);
6538 			}
6539 
6540 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6541 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6542 			syn_present = B_TRUE;
6543 		}
6544 	}
6545 
6546 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6547 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6548 		if ((flags & TH_RST) || (flags & TH_URG)) {
6549 			CONN_DEC_REF(connp);
6550 			freemsg(first_mp);
6551 			return;
6552 		}
6553 		if (flags & TH_ACK) {
6554 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6555 			CONN_DEC_REF(connp);
6556 			return;
6557 		}
6558 
6559 		CONN_DEC_REF(connp);
6560 		freemsg(first_mp);
6561 		return;
6562 	}
6563 
6564 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6565 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6566 		    NULL, mctl_present);
6567 		if (first_mp == NULL) {
6568 			CONN_DEC_REF(connp);
6569 			return;
6570 		}
6571 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6572 			ASSERT(syn_present);
6573 			if (mctl_present) {
6574 				ASSERT(first_mp != mp);
6575 				first_mp->b_datap->db_struioflag |=
6576 				    STRUIO_POLICY;
6577 			} else {
6578 				ASSERT(first_mp == mp);
6579 				mp->b_datap->db_struioflag &=
6580 				    ~STRUIO_EAGER;
6581 				mp->b_datap->db_struioflag |=
6582 				    STRUIO_POLICY;
6583 			}
6584 		} else {
6585 			/*
6586 			 * Discard first_mp early since we're dealing with a
6587 			 * fully-connected conn_t and tcp doesn't do policy in
6588 			 * this case.
6589 			 */
6590 			if (mctl_present) {
6591 				freeb(first_mp);
6592 				mctl_present = B_FALSE;
6593 			}
6594 			first_mp = mp;
6595 		}
6596 	}
6597 
6598 	/*
6599 	 * Initiate policy processing here if needed. If we get here from
6600 	 * icmp_inbound_error_fanout, ip_policy is false.
6601 	 */
6602 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6603 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6604 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6605 		if (mp == NULL) {
6606 			CONN_DEC_REF(connp);
6607 			if (mctl_present)
6608 				freeb(first_mp);
6609 			return;
6610 		} else if (mctl_present) {
6611 			ASSERT(first_mp != mp);
6612 			first_mp->b_cont = mp;
6613 		} else {
6614 			first_mp = mp;
6615 		}
6616 	}
6617 
6618 
6619 
6620 	/* Handle IPv6 socket options. */
6621 	if (!syn_present &&
6622 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6623 		/* Add header */
6624 		ASSERT(recv_ill != NULL);
6625 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6626 		if (mp == NULL) {
6627 			CONN_DEC_REF(connp);
6628 			if (mctl_present)
6629 				freeb(first_mp);
6630 			return;
6631 		} else if (mctl_present) {
6632 			/*
6633 			 * ip_add_info might return a new mp.
6634 			 */
6635 			ASSERT(first_mp != mp);
6636 			first_mp->b_cont = mp;
6637 		} else {
6638 			first_mp = mp;
6639 		}
6640 	}
6641 
6642 	BUMP_MIB(&ip_mib, ipInDelivers);
6643 	if (IPCL_IS_TCP(connp)) {
6644 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6645 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6646 	} else {
6647 		putnext(connp->conn_rq, first_mp);
6648 		CONN_DEC_REF(connp);
6649 	}
6650 }
6651 
6652 /*
6653  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6654  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6655  * Caller is responsible for dropping references to the conn, and freeing
6656  * first_mp.
6657  *
6658  * IPQoS Notes
6659  * Before sending it to the client, invoke IPPF processing. Policy processing
6660  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6661  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6662  * ip_wput_local, ip_policy is false.
6663  */
6664 static void
6665 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6666     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6667     boolean_t ip_policy)
6668 {
6669 	boolean_t	mctl_present = (first_mp != NULL);
6670 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6671 	uint32_t	ill_index;
6672 
6673 	if (mctl_present)
6674 		first_mp->b_cont = mp;
6675 	else
6676 		first_mp = mp;
6677 
6678 	if (CONN_UDP_FLOWCTLD(connp)) {
6679 		BUMP_MIB(&ip_mib, udpInOverflows);
6680 		freemsg(first_mp);
6681 		return;
6682 	}
6683 
6684 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6685 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6686 		    NULL, mctl_present);
6687 		if (first_mp == NULL)
6688 			return;	/* Freed by ipsec_check_inbound_policy(). */
6689 	}
6690 	if (mctl_present)
6691 		freeb(first_mp);
6692 
6693 	if (connp->conn_recvif)
6694 		in_flags = IPF_RECVIF;
6695 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6696 		in_flags |= IPF_RECVSLLA;
6697 
6698 	/* Handle IPv6 options. */
6699 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6700 		in_flags |= IPF_RECVIF;
6701 
6702 	/*
6703 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6704 	 * freed if the packet is dropped. The caller will do so.
6705 	 */
6706 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6707 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6708 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6709 		if (mp == NULL) {
6710 			return;
6711 		}
6712 	}
6713 	if ((in_flags != 0) &&
6714 	    (mp->b_datap->db_type != M_CTL)) {
6715 		/*
6716 		 * The actual data will be contained in b_cont
6717 		 * upon successful return of the following call
6718 		 * else original mblk is returned
6719 		 */
6720 		ASSERT(recv_ill != NULL);
6721 		mp = ip_add_info(mp, recv_ill, in_flags);
6722 	}
6723 	BUMP_MIB(&ip_mib, ipInDelivers);
6724 
6725 	/* Send it upstream */
6726 	CONN_UDP_RECV(connp, mp);
6727 }
6728 
6729 /*
6730  * Fanout for UDP packets.
6731  * The caller puts <fport, lport> in the ports parameter.
6732  *
6733  * If SO_REUSEADDR is set all multicast and broadcast packets
6734  * will be delivered to all streams bound to the same port.
6735  *
6736  * Zones notes:
6737  * Multicast and broadcast packets will be distributed to streams in all zones.
6738  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6739  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6740  * packets. To maintain this behavior with multiple zones, the conns are grouped
6741  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6742  * each zone. If unset, all the following conns in the same zone are skipped.
6743  */
6744 static void
6745 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6746     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6747     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6748 {
6749 	uint32_t	dstport, srcport;
6750 	ipaddr_t	dst;
6751 	mblk_t		*first_mp;
6752 	boolean_t	secure;
6753 	in6_addr_t	v6src;
6754 	conn_t		*connp;
6755 	connf_t		*connfp;
6756 	conn_t		*first_connp;
6757 	conn_t		*next_connp;
6758 	mblk_t		*mp1, *first_mp1;
6759 	ipaddr_t	src;
6760 	zoneid_t	last_zoneid;
6761 	boolean_t	reuseaddr;
6762 	boolean_t	shared_addr;
6763 
6764 	first_mp = mp;
6765 	if (mctl_present) {
6766 		mp = first_mp->b_cont;
6767 		first_mp->b_cont = NULL;
6768 		secure = ipsec_in_is_secure(first_mp);
6769 		ASSERT(mp != NULL);
6770 	} else {
6771 		first_mp = NULL;
6772 		secure = B_FALSE;
6773 	}
6774 
6775 	/* Extract ports in net byte order */
6776 	dstport = htons(ntohl(ports) & 0xFFFF);
6777 	srcport = htons(ntohl(ports) >> 16);
6778 	dst = ipha->ipha_dst;
6779 	src = ipha->ipha_src;
6780 
6781 	shared_addr = (zoneid == ALL_ZONES);
6782 	if (shared_addr) {
6783 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6784 		if (zoneid == ALL_ZONES)
6785 			zoneid = tsol_packet_to_zoneid(mp);
6786 	}
6787 
6788 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6789 	mutex_enter(&connfp->connf_lock);
6790 	connp = connfp->connf_head;
6791 	if (!broadcast && !CLASSD(dst)) {
6792 		/*
6793 		 * Not broadcast or multicast. Send to the one (first)
6794 		 * client we find. No need to check conn_wantpacket()
6795 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6796 		 * IPv4 unicast packets.
6797 		 */
6798 		while ((connp != NULL) &&
6799 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6800 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6801 			connp = connp->conn_next;
6802 		}
6803 
6804 		if (connp == NULL || connp->conn_upq == NULL)
6805 			goto notfound;
6806 
6807 		if (is_system_labeled() &&
6808 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6809 		    connp))
6810 			goto notfound;
6811 
6812 		CONN_INC_REF(connp);
6813 		mutex_exit(&connfp->connf_lock);
6814 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6815 		    recv_ill, ip_policy);
6816 		IP_STAT(ip_udp_fannorm);
6817 		CONN_DEC_REF(connp);
6818 		return;
6819 	}
6820 
6821 	/*
6822 	 * Broadcast and multicast case
6823 	 *
6824 	 * Need to check conn_wantpacket().
6825 	 * If SO_REUSEADDR has been set on the first we send the
6826 	 * packet to all clients that have joined the group and
6827 	 * match the port.
6828 	 */
6829 
6830 	while (connp != NULL) {
6831 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6832 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6833 		    (!is_system_labeled() ||
6834 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6835 		    connp)))
6836 			break;
6837 		connp = connp->conn_next;
6838 	}
6839 
6840 	if (connp == NULL || connp->conn_upq == NULL)
6841 		goto notfound;
6842 
6843 	first_connp = connp;
6844 	/*
6845 	 * When SO_REUSEADDR is not set, send the packet only to the first
6846 	 * matching connection in its zone by keeping track of the zoneid.
6847 	 */
6848 	reuseaddr = first_connp->conn_reuseaddr;
6849 	last_zoneid = first_connp->conn_zoneid;
6850 
6851 	CONN_INC_REF(connp);
6852 	connp = connp->conn_next;
6853 	for (;;) {
6854 		while (connp != NULL) {
6855 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6856 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6857 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6858 			    (!is_system_labeled() ||
6859 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6860 			    shared_addr, connp)))
6861 				break;
6862 			connp = connp->conn_next;
6863 		}
6864 		/*
6865 		 * Just copy the data part alone. The mctl part is
6866 		 * needed just for verifying policy and it is never
6867 		 * sent up.
6868 		 */
6869 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6870 		    ((mp1 = copymsg(mp)) == NULL))) {
6871 			/*
6872 			 * No more interested clients or memory
6873 			 * allocation failed
6874 			 */
6875 			connp = first_connp;
6876 			break;
6877 		}
6878 		if (connp->conn_zoneid != last_zoneid) {
6879 			/*
6880 			 * Update the zoneid so that the packet isn't sent to
6881 			 * any more conns in the same zone unless SO_REUSEADDR
6882 			 * is set.
6883 			 */
6884 			reuseaddr = connp->conn_reuseaddr;
6885 			last_zoneid = connp->conn_zoneid;
6886 		}
6887 		if (first_mp != NULL) {
6888 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6889 			    ipsec_info_type == IPSEC_IN);
6890 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6891 			if (first_mp1 == NULL) {
6892 				freemsg(mp1);
6893 				connp = first_connp;
6894 				break;
6895 			}
6896 		} else {
6897 			first_mp1 = NULL;
6898 		}
6899 		CONN_INC_REF(connp);
6900 		mutex_exit(&connfp->connf_lock);
6901 		/*
6902 		 * IPQoS notes: We don't send the packet for policy
6903 		 * processing here, will do it for the last one (below).
6904 		 * i.e. we do it per-packet now, but if we do policy
6905 		 * processing per-conn, then we would need to do it
6906 		 * here too.
6907 		 */
6908 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6909 		    ipha, flags, recv_ill, B_FALSE);
6910 		mutex_enter(&connfp->connf_lock);
6911 		/* Follow the next pointer before releasing the conn. */
6912 		next_connp = connp->conn_next;
6913 		IP_STAT(ip_udp_fanmb);
6914 		CONN_DEC_REF(connp);
6915 		connp = next_connp;
6916 	}
6917 
6918 	/* Last one.  Send it upstream. */
6919 	mutex_exit(&connfp->connf_lock);
6920 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6921 	    ip_policy);
6922 	IP_STAT(ip_udp_fanmb);
6923 	CONN_DEC_REF(connp);
6924 	return;
6925 
6926 notfound:
6927 
6928 	mutex_exit(&connfp->connf_lock);
6929 	IP_STAT(ip_udp_fanothers);
6930 	/*
6931 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6932 	 * have already been matched above, since they live in the IPv4
6933 	 * fanout tables. This implies we only need to
6934 	 * check for IPv6 in6addr_any endpoints here.
6935 	 * Thus we compare using ipv6_all_zeros instead of the destination
6936 	 * address, except for the multicast group membership lookup which
6937 	 * uses the IPv4 destination.
6938 	 */
6939 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6940 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6941 	mutex_enter(&connfp->connf_lock);
6942 	connp = connfp->connf_head;
6943 	if (!broadcast && !CLASSD(dst)) {
6944 		while (connp != NULL) {
6945 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6946 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6947 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6948 			    !connp->conn_ipv6_v6only)
6949 				break;
6950 			connp = connp->conn_next;
6951 		}
6952 
6953 		if (connp != NULL && is_system_labeled() &&
6954 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6955 		    connp))
6956 			connp = NULL;
6957 
6958 		if (connp == NULL || connp->conn_upq == NULL) {
6959 			/*
6960 			 * No one bound to this port.  Is
6961 			 * there a client that wants all
6962 			 * unclaimed datagrams?
6963 			 */
6964 			mutex_exit(&connfp->connf_lock);
6965 
6966 			if (mctl_present)
6967 				first_mp->b_cont = mp;
6968 			else
6969 				first_mp = mp;
6970 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6971 				ip_fanout_proto(q, first_mp, ill, ipha,
6972 				    flags | IP_FF_RAWIP, mctl_present,
6973 				    ip_policy, recv_ill, zoneid);
6974 			} else {
6975 				if (ip_fanout_send_icmp(q, first_mp, flags,
6976 				    ICMP_DEST_UNREACHABLE,
6977 				    ICMP_PORT_UNREACHABLE,
6978 				    mctl_present, zoneid)) {
6979 					BUMP_MIB(&ip_mib, udpNoPorts);
6980 				}
6981 			}
6982 			return;
6983 		}
6984 
6985 		CONN_INC_REF(connp);
6986 		mutex_exit(&connfp->connf_lock);
6987 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6988 		    recv_ill, ip_policy);
6989 		CONN_DEC_REF(connp);
6990 		return;
6991 	}
6992 	/*
6993 	 * IPv4 multicast packet being delivered to an AF_INET6
6994 	 * in6addr_any endpoint.
6995 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6996 	 * and not conn_wantpacket_v6() since any multicast membership is
6997 	 * for an IPv4-mapped multicast address.
6998 	 * The packet is sent to all clients in all zones that have joined the
6999 	 * group and match the port.
7000 	 */
7001 	while (connp != NULL) {
7002 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7003 		    srcport, v6src) &&
7004 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7005 		    (!is_system_labeled() ||
7006 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7007 		    connp)))
7008 			break;
7009 		connp = connp->conn_next;
7010 	}
7011 
7012 	if (connp == NULL || connp->conn_upq == NULL) {
7013 		/*
7014 		 * No one bound to this port.  Is
7015 		 * there a client that wants all
7016 		 * unclaimed datagrams?
7017 		 */
7018 		mutex_exit(&connfp->connf_lock);
7019 
7020 		if (mctl_present)
7021 			first_mp->b_cont = mp;
7022 		else
7023 			first_mp = mp;
7024 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7025 			ip_fanout_proto(q, first_mp, ill, ipha,
7026 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7027 			    recv_ill, zoneid);
7028 		} else {
7029 			/*
7030 			 * We used to attempt to send an icmp error here, but
7031 			 * since this is known to be a multicast packet
7032 			 * and we don't send icmp errors in response to
7033 			 * multicast, just drop the packet and give up sooner.
7034 			 */
7035 			BUMP_MIB(&ip_mib, udpNoPorts);
7036 			freemsg(first_mp);
7037 		}
7038 		return;
7039 	}
7040 
7041 	first_connp = connp;
7042 
7043 	CONN_INC_REF(connp);
7044 	connp = connp->conn_next;
7045 	for (;;) {
7046 		while (connp != NULL) {
7047 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7048 			    ipv6_all_zeros, srcport, v6src) &&
7049 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7050 			    (!is_system_labeled() ||
7051 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7052 			    shared_addr, connp)))
7053 				break;
7054 			connp = connp->conn_next;
7055 		}
7056 		/*
7057 		 * Just copy the data part alone. The mctl part is
7058 		 * needed just for verifying policy and it is never
7059 		 * sent up.
7060 		 */
7061 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7062 		    ((mp1 = copymsg(mp)) == NULL))) {
7063 			/*
7064 			 * No more intested clients or memory
7065 			 * allocation failed
7066 			 */
7067 			connp = first_connp;
7068 			break;
7069 		}
7070 		if (first_mp != NULL) {
7071 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7072 			    ipsec_info_type == IPSEC_IN);
7073 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7074 			if (first_mp1 == NULL) {
7075 				freemsg(mp1);
7076 				connp = first_connp;
7077 				break;
7078 			}
7079 		} else {
7080 			first_mp1 = NULL;
7081 		}
7082 		CONN_INC_REF(connp);
7083 		mutex_exit(&connfp->connf_lock);
7084 		/*
7085 		 * IPQoS notes: We don't send the packet for policy
7086 		 * processing here, will do it for the last one (below).
7087 		 * i.e. we do it per-packet now, but if we do policy
7088 		 * processing per-conn, then we would need to do it
7089 		 * here too.
7090 		 */
7091 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7092 		    ipha, flags, recv_ill, B_FALSE);
7093 		mutex_enter(&connfp->connf_lock);
7094 		/* Follow the next pointer before releasing the conn. */
7095 		next_connp = connp->conn_next;
7096 		CONN_DEC_REF(connp);
7097 		connp = next_connp;
7098 	}
7099 
7100 	/* Last one.  Send it upstream. */
7101 	mutex_exit(&connfp->connf_lock);
7102 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7103 	    ip_policy);
7104 	CONN_DEC_REF(connp);
7105 }
7106 
7107 /*
7108  * Complete the ip_wput header so that it
7109  * is possible to generate ICMP
7110  * errors.
7111  */
7112 int
7113 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7114 {
7115 	ire_t *ire;
7116 
7117 	if (ipha->ipha_src == INADDR_ANY) {
7118 		ire = ire_lookup_local(zoneid);
7119 		if (ire == NULL) {
7120 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7121 			return (1);
7122 		}
7123 		ipha->ipha_src = ire->ire_addr;
7124 		ire_refrele(ire);
7125 	}
7126 	ipha->ipha_ttl = ip_def_ttl;
7127 	ipha->ipha_hdr_checksum = 0;
7128 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7129 	return (0);
7130 }
7131 
7132 /*
7133  * Nobody should be sending
7134  * packets up this stream
7135  */
7136 static void
7137 ip_lrput(queue_t *q, mblk_t *mp)
7138 {
7139 	mblk_t *mp1;
7140 
7141 	switch (mp->b_datap->db_type) {
7142 	case M_FLUSH:
7143 		/* Turn around */
7144 		if (*mp->b_rptr & FLUSHW) {
7145 			*mp->b_rptr &= ~FLUSHR;
7146 			qreply(q, mp);
7147 			return;
7148 		}
7149 		break;
7150 	}
7151 	/* Could receive messages that passed through ar_rput */
7152 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7153 		mp1->b_prev = mp1->b_next = NULL;
7154 	freemsg(mp);
7155 }
7156 
7157 /* Nobody should be sending packets down this stream */
7158 /* ARGSUSED */
7159 void
7160 ip_lwput(queue_t *q, mblk_t *mp)
7161 {
7162 	freemsg(mp);
7163 }
7164 
7165 /*
7166  * Move the first hop in any source route to ipha_dst and remove that part of
7167  * the source route.  Called by other protocols.  Errors in option formatting
7168  * are ignored - will be handled by ip_wput_options Return the final
7169  * destination (either ipha_dst or the last entry in a source route.)
7170  */
7171 ipaddr_t
7172 ip_massage_options(ipha_t *ipha)
7173 {
7174 	ipoptp_t	opts;
7175 	uchar_t		*opt;
7176 	uint8_t		optval;
7177 	uint8_t		optlen;
7178 	ipaddr_t	dst;
7179 	int		i;
7180 	ire_t		*ire;
7181 
7182 	ip2dbg(("ip_massage_options\n"));
7183 	dst = ipha->ipha_dst;
7184 	for (optval = ipoptp_first(&opts, ipha);
7185 	    optval != IPOPT_EOL;
7186 	    optval = ipoptp_next(&opts)) {
7187 		opt = opts.ipoptp_cur;
7188 		switch (optval) {
7189 			uint8_t off;
7190 		case IPOPT_SSRR:
7191 		case IPOPT_LSRR:
7192 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7193 				ip1dbg(("ip_massage_options: bad src route\n"));
7194 				break;
7195 			}
7196 			optlen = opts.ipoptp_len;
7197 			off = opt[IPOPT_OFFSET];
7198 			off--;
7199 		redo_srr:
7200 			if (optlen < IP_ADDR_LEN ||
7201 			    off > optlen - IP_ADDR_LEN) {
7202 				/* End of source route */
7203 				ip1dbg(("ip_massage_options: end of SR\n"));
7204 				break;
7205 			}
7206 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7207 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7208 			    ntohl(dst)));
7209 			/*
7210 			 * Check if our address is present more than
7211 			 * once as consecutive hops in source route.
7212 			 * XXX verify per-interface ip_forwarding
7213 			 * for source route?
7214 			 */
7215 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7216 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7217 			if (ire != NULL) {
7218 				ire_refrele(ire);
7219 				off += IP_ADDR_LEN;
7220 				goto redo_srr;
7221 			}
7222 			if (dst == htonl(INADDR_LOOPBACK)) {
7223 				ip1dbg(("ip_massage_options: loopback addr in "
7224 				    "source route!\n"));
7225 				break;
7226 			}
7227 			/*
7228 			 * Update ipha_dst to be the first hop and remove the
7229 			 * first hop from the source route (by overwriting
7230 			 * part of the option with NOP options).
7231 			 */
7232 			ipha->ipha_dst = dst;
7233 			/* Put the last entry in dst */
7234 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7235 			    3;
7236 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7237 
7238 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7239 			    ntohl(dst)));
7240 			/* Move down and overwrite */
7241 			opt[IP_ADDR_LEN] = opt[0];
7242 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7243 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7244 			for (i = 0; i < IP_ADDR_LEN; i++)
7245 				opt[i] = IPOPT_NOP;
7246 			break;
7247 		}
7248 	}
7249 	return (dst);
7250 }
7251 
7252 /*
7253  * This function's job is to forward data to the reverse tunnel (FA->HA)
7254  * after doing a few checks. It is assumed that the incoming interface
7255  * of the packet is always different than the outgoing interface and the
7256  * ire_type of the found ire has to be a non-resolver type.
7257  *
7258  * IPQoS notes
7259  * IP policy is invoked twice for a forwarded packet, once on the read side
7260  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7261  * enabled.
7262  */
7263 static void
7264 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7265 {
7266 	ipha_t		*ipha;
7267 	queue_t		*q;
7268 	uint32_t 	pkt_len;
7269 #define	rptr    ((uchar_t *)ipha)
7270 	uint32_t 	sum;
7271 	uint32_t 	max_frag;
7272 	mblk_t		*first_mp;
7273 	uint32_t	ill_index;
7274 	ipxmit_state_t	pktxmit_state;
7275 	ill_t		*out_ill;
7276 
7277 	ASSERT(ire != NULL);
7278 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7279 	ASSERT(ire->ire_stq != NULL);
7280 
7281 	/* Initiate read side IPPF processing */
7282 	if (IPP_ENABLED(IPP_FWD_IN)) {
7283 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7284 		ip_process(IPP_FWD_IN, &mp, ill_index);
7285 		if (mp == NULL) {
7286 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7287 			    "dropped during IPPF processing\n"));
7288 			return;
7289 		}
7290 	}
7291 
7292 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7293 		ILLF_ROUTER) == 0) ||
7294 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7295 		BUMP_MIB(&ip_mib, ipForwProhibits);
7296 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7297 		    "forwarding is not turned on\n"));
7298 		goto drop_pkt;
7299 	}
7300 
7301 	/*
7302 	 * Don't forward if the interface is down
7303 	 */
7304 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7305 		BUMP_MIB(&ip_mib, ipInDiscards);
7306 		goto drop_pkt;
7307 	}
7308 
7309 	ipha = (ipha_t *)mp->b_rptr;
7310 	pkt_len = ntohs(ipha->ipha_length);
7311 	/* Adjust the checksum to reflect the ttl decrement. */
7312 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7313 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7314 	if (ipha->ipha_ttl-- <= 1) {
7315 		if (ip_csum_hdr(ipha)) {
7316 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7317 			goto drop_pkt;
7318 		}
7319 		q = ire->ire_stq;
7320 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7321 		    BPRI_HI)) == NULL) {
7322 			goto drop_pkt;
7323 		}
7324 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7325 		/* Sent by forwarding path, and router is global zone */
7326 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7327 		    GLOBAL_ZONEID);
7328 		return;
7329 	}
7330 
7331 	/* Get the ill_index of the ILL */
7332 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7333 
7334 	/*
7335 	 * This location is chosen for the placement of the forwarding hook
7336 	 * because at this point we know that we have a path out for the
7337 	 * packet but haven't yet applied any logic (such as fragmenting)
7338 	 * that happen as part of transmitting the packet out.
7339 	 */
7340 	out_ill = ire->ire_ipif->ipif_ill;
7341 
7342 	DTRACE_PROBE4(ip4__forwarding__start,
7343 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7344 
7345 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7346 	    in_ill, out_ill, ipha, mp, mp);
7347 
7348 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7349 
7350 	if (mp == NULL)
7351 		return;
7352 	pkt_len = ntohs(ipha->ipha_length);
7353 
7354 	/*
7355 	 * ip_mrtun_forward is only used by foreign agent to reverse
7356 	 * tunnel the incoming packet. So it does not do any option
7357 	 * processing for source routing.
7358 	 */
7359 	max_frag = ire->ire_max_frag;
7360 	if (pkt_len > max_frag) {
7361 		/*
7362 		 * It needs fragging on its way out.  We haven't
7363 		 * verified the header checksum yet.  Since we
7364 		 * are going to put a surely good checksum in the
7365 		 * outgoing header, we have to make sure that it
7366 		 * was good coming in.
7367 		 */
7368 		if (ip_csum_hdr(ipha)) {
7369 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7370 			goto drop_pkt;
7371 		}
7372 
7373 		/* Initiate write side IPPF processing */
7374 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7375 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7376 			if (mp == NULL) {
7377 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7378 				    "dropped/deferred during ip policy "\
7379 				    "processing\n"));
7380 				return;
7381 			}
7382 		}
7383 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7384 		    BPRI_HI)) == NULL) {
7385 			goto drop_pkt;
7386 		}
7387 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7388 		mp = first_mp;
7389 
7390 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7391 		return;
7392 	}
7393 
7394 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7395 
7396 	ASSERT(ire->ire_ipif != NULL);
7397 
7398 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7399 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7400 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7401 	    NULL, out_ill, ipha, mp, mp);
7402 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7403 	if (mp == NULL)
7404 		return;
7405 
7406 	/* Now send the packet to the tunnel interface */
7407 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7408 	q = ire->ire_stq;
7409 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7410 	if ((pktxmit_state == SEND_FAILED) ||
7411 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7412 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7413 		    q->q_ptr));
7414 	}
7415 
7416 	return;
7417 
7418 drop_pkt:;
7419 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7420 	freemsg(mp);
7421 #undef	rptr
7422 }
7423 
7424 /*
7425  * Fills the ipsec_out_t data structure with appropriate fields and
7426  * prepends it to mp which contains the IP hdr + data that was meant
7427  * to be forwarded. Please note that ipsec_out_info data structure
7428  * is used here to communicate the outgoing ill path at ip_wput()
7429  * for the ICMP error packet. This has nothing to do with ipsec IP
7430  * security. ipsec_out_t is really used to pass the info to the module
7431  * IP where this information cannot be extracted from conn.
7432  * This functions is called by ip_mrtun_forward().
7433  */
7434 void
7435 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7436 {
7437 	ipsec_out_t	*io;
7438 
7439 	ASSERT(xmit_ill != NULL);
7440 	first_mp->b_datap->db_type = M_CTL;
7441 	first_mp->b_wptr += sizeof (ipsec_info_t);
7442 	/*
7443 	 * This is to pass info to ip_wput in absence of conn.
7444 	 * ipsec_out_secure will be B_FALSE because of this.
7445 	 * Thus ipsec_out_secure being B_FALSE indicates that
7446 	 * this is not IPSEC security related information.
7447 	 */
7448 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7449 	io = (ipsec_out_t *)first_mp->b_rptr;
7450 	io->ipsec_out_type = IPSEC_OUT;
7451 	io->ipsec_out_len = sizeof (ipsec_out_t);
7452 	first_mp->b_cont = mp;
7453 	io->ipsec_out_ill_index =
7454 	    xmit_ill->ill_phyint->phyint_ifindex;
7455 	io->ipsec_out_xmit_if = B_TRUE;
7456 }
7457 
7458 /*
7459  * Return the network mask
7460  * associated with the specified address.
7461  */
7462 ipaddr_t
7463 ip_net_mask(ipaddr_t addr)
7464 {
7465 	uchar_t	*up = (uchar_t *)&addr;
7466 	ipaddr_t mask = 0;
7467 	uchar_t	*maskp = (uchar_t *)&mask;
7468 
7469 #if defined(__i386) || defined(__amd64)
7470 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7471 #endif
7472 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7473 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7474 #endif
7475 	if (CLASSD(addr)) {
7476 		maskp[0] = 0xF0;
7477 		return (mask);
7478 	}
7479 	if (addr == 0)
7480 		return (0);
7481 	maskp[0] = 0xFF;
7482 	if ((up[0] & 0x80) == 0)
7483 		return (mask);
7484 
7485 	maskp[1] = 0xFF;
7486 	if ((up[0] & 0xC0) == 0x80)
7487 		return (mask);
7488 
7489 	maskp[2] = 0xFF;
7490 	if ((up[0] & 0xE0) == 0xC0)
7491 		return (mask);
7492 
7493 	/* Must be experimental or multicast, indicate as much */
7494 	return ((ipaddr_t)0);
7495 }
7496 
7497 /*
7498  * Select an ill for the packet by considering load spreading across
7499  * a different ill in the group if dst_ill is part of some group.
7500  */
7501 ill_t *
7502 ip_newroute_get_dst_ill(ill_t *dst_ill)
7503 {
7504 	ill_t *ill;
7505 
7506 	/*
7507 	 * We schedule irrespective of whether the source address is
7508 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7509 	 */
7510 	ill = illgrp_scheduler(dst_ill);
7511 	if (ill == NULL)
7512 		return (NULL);
7513 
7514 	/*
7515 	 * For groups with names ip_sioctl_groupname ensures that all
7516 	 * ills are of same type. For groups without names, ifgrp_insert
7517 	 * ensures this.
7518 	 */
7519 	ASSERT(dst_ill->ill_type == ill->ill_type);
7520 
7521 	return (ill);
7522 }
7523 
7524 /*
7525  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7526  */
7527 ill_t *
7528 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7529 {
7530 	ill_t *ret_ill;
7531 
7532 	ASSERT(ifindex != 0);
7533 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7534 	if (ret_ill == NULL ||
7535 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7536 		if (isv6) {
7537 			if (ill != NULL) {
7538 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7539 			} else {
7540 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7541 			}
7542 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7543 			    "bad ifindex %d.\n", ifindex));
7544 		} else {
7545 			BUMP_MIB(&ip_mib, ipOutDiscards);
7546 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7547 			    "bad ifindex %d.\n", ifindex));
7548 		}
7549 		if (ret_ill != NULL)
7550 			ill_refrele(ret_ill);
7551 		freemsg(first_mp);
7552 		return (NULL);
7553 	}
7554 
7555 	return (ret_ill);
7556 }
7557 
7558 /*
7559  * IPv4 -
7560  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7561  * out a packet to a destination address for which we do not have specific
7562  * (or sufficient) routing information.
7563  *
7564  * NOTE : These are the scopes of some of the variables that point at IRE,
7565  *	  which needs to be followed while making any future modifications
7566  *	  to avoid memory leaks.
7567  *
7568  *	- ire and sire are the entries looked up initially by
7569  *	  ire_ftable_lookup.
7570  *	- ipif_ire is used to hold the interface ire associated with
7571  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7572  *	  it before branching out to error paths.
7573  *	- save_ire is initialized before ire_create, so that ire returned
7574  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7575  *	  before breaking out of the switch.
7576  *
7577  *	Thus on failures, we have to REFRELE only ire and sire, if they
7578  *	are not NULL.
7579  */
7580 void
7581 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7582     zoneid_t zoneid)
7583 {
7584 	areq_t	*areq;
7585 	ipaddr_t gw = 0;
7586 	ire_t	*ire = NULL;
7587 	mblk_t	*res_mp;
7588 	ipaddr_t *addrp;
7589 	ipaddr_t nexthop_addr;
7590 	ipif_t  *src_ipif = NULL;
7591 	ill_t	*dst_ill = NULL;
7592 	ipha_t  *ipha;
7593 	ire_t	*sire = NULL;
7594 	mblk_t	*first_mp;
7595 	ire_t	*save_ire;
7596 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7597 	ushort_t ire_marks = 0;
7598 	boolean_t mctl_present;
7599 	ipsec_out_t *io;
7600 	mblk_t	*saved_mp;
7601 	ire_t	*first_sire = NULL;
7602 	mblk_t	*copy_mp = NULL;
7603 	mblk_t	*xmit_mp = NULL;
7604 	ipaddr_t save_dst;
7605 	uint32_t multirt_flags =
7606 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7607 	boolean_t multirt_is_resolvable;
7608 	boolean_t multirt_resolve_next;
7609 	boolean_t do_attach_ill = B_FALSE;
7610 	boolean_t ip_nexthop = B_FALSE;
7611 	tsol_ire_gw_secattr_t *attrp = NULL;
7612 	tsol_gcgrp_t *gcgrp = NULL;
7613 	tsol_gcgrp_addr_t ga;
7614 
7615 	if (ip_debug > 2) {
7616 		/* ip1dbg */
7617 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7618 	}
7619 
7620 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7621 	if (mctl_present) {
7622 		io = (ipsec_out_t *)first_mp->b_rptr;
7623 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7624 		ASSERT(zoneid == io->ipsec_out_zoneid);
7625 		ASSERT(zoneid != ALL_ZONES);
7626 	}
7627 
7628 	ipha = (ipha_t *)mp->b_rptr;
7629 
7630 	/* All multicast lookups come through ip_newroute_ipif() */
7631 	if (CLASSD(dst)) {
7632 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7633 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7634 		freemsg(first_mp);
7635 		return;
7636 	}
7637 
7638 	if (mctl_present && io->ipsec_out_attach_if) {
7639 		/* ip_grab_attach_ill returns a held ill */
7640 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7641 		    io->ipsec_out_ill_index, B_FALSE);
7642 
7643 		/* Failure case frees things for us. */
7644 		if (attach_ill == NULL)
7645 			return;
7646 
7647 		/*
7648 		 * Check if we need an ire that will not be
7649 		 * looked up by anybody else i.e. HIDDEN.
7650 		 */
7651 		if (ill_is_probeonly(attach_ill))
7652 			ire_marks = IRE_MARK_HIDDEN;
7653 	}
7654 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7655 		ip_nexthop = B_TRUE;
7656 		nexthop_addr = io->ipsec_out_nexthop_addr;
7657 	}
7658 	/*
7659 	 * If this IRE is created for forwarding or it is not for
7660 	 * traffic for congestion controlled protocols, mark it as temporary.
7661 	 */
7662 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7663 		ire_marks |= IRE_MARK_TEMPORARY;
7664 
7665 	/*
7666 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7667 	 * chain until it gets the most specific information available.
7668 	 * For example, we know that there is no IRE_CACHE for this dest,
7669 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7670 	 * ire_ftable_lookup will look up the gateway, etc.
7671 	 * Check if in_ill != NULL. If it is true, the packet must be
7672 	 * from an incoming interface where RTA_SRCIFP is set.
7673 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7674 	 * to the destination, of equal netmask length in the forward table,
7675 	 * will be recursively explored. If no information is available
7676 	 * for the final gateway of that route, we force the returned ire
7677 	 * to be equal to sire using MATCH_IRE_PARENT.
7678 	 * At least, in this case we have a starting point (in the buckets)
7679 	 * to look for other routes to the destination in the forward table.
7680 	 * This is actually used only for multirouting, where a list
7681 	 * of routes has to be processed in sequence.
7682 	 *
7683 	 * In the process of coming up with the most specific information,
7684 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7685 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7686 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7687 	 * Two caveats when handling incomplete ire's in ip_newroute:
7688 	 * - we should be careful when accessing its ire_nce (specifically
7689 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7690 	 * - not all legacy code path callers are prepared to handle
7691 	 *   incomplete ire's, so we should not create/add incomplete
7692 	 *   ire_cache entries here. (See discussion about temporary solution
7693 	 *   further below).
7694 	 *
7695 	 * In order to minimize packet dropping, and to preserve existing
7696 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7697 	 * gateway, and instead use the IF_RESOLVER ire to send out
7698 	 * another request to ARP (this is achieved by passing the
7699 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7700 	 * arp response comes back in ip_wput_nondata, we will create
7701 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7702 	 *
7703 	 * Note that this is a temporary solution; the correct solution is
7704 	 * to create an incomplete  per-dst ire_cache entry, and send the
7705 	 * packet out when the gw's nce is resolved. In order to achieve this,
7706 	 * all packet processing must have been completed prior to calling
7707 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7708 	 * to be modified to accomodate this solution.
7709 	 */
7710 	if (in_ill != NULL) {
7711 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7712 		    in_ill, MATCH_IRE_TYPE);
7713 	} else if (ip_nexthop) {
7714 		/*
7715 		 * The first time we come here, we look for an IRE_INTERFACE
7716 		 * entry for the specified nexthop, set the dst to be the
7717 		 * nexthop address and create an IRE_CACHE entry for the
7718 		 * nexthop. The next time around, we are able to find an
7719 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7720 		 * nexthop address and create an IRE_CACHE entry for the
7721 		 * destination address via the specified nexthop.
7722 		 */
7723 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7724 		    MBLK_GETLABEL(mp));
7725 		if (ire != NULL) {
7726 			gw = nexthop_addr;
7727 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7728 		} else {
7729 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7730 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7731 			    MBLK_GETLABEL(mp),
7732 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7733 			if (ire != NULL) {
7734 				dst = nexthop_addr;
7735 			}
7736 		}
7737 	} else if (attach_ill == NULL) {
7738 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7739 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7740 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7741 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7742 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7743 	} else {
7744 		/*
7745 		 * attach_ill is set only for communicating with
7746 		 * on-link hosts. So, don't look for DEFAULT.
7747 		 */
7748 		ipif_t	*attach_ipif;
7749 
7750 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7751 		if (attach_ipif == NULL) {
7752 			ill_refrele(attach_ill);
7753 			goto icmp_err_ret;
7754 		}
7755 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7756 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7757 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7758 		    MATCH_IRE_SECATTR);
7759 		ipif_refrele(attach_ipif);
7760 	}
7761 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7762 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7763 
7764 	/*
7765 	 * This loop is run only once in most cases.
7766 	 * We loop to resolve further routes only when the destination
7767 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7768 	 */
7769 	do {
7770 		/* Clear the previous iteration's values */
7771 		if (src_ipif != NULL) {
7772 			ipif_refrele(src_ipif);
7773 			src_ipif = NULL;
7774 		}
7775 		if (dst_ill != NULL) {
7776 			ill_refrele(dst_ill);
7777 			dst_ill = NULL;
7778 		}
7779 
7780 		multirt_resolve_next = B_FALSE;
7781 		/*
7782 		 * We check if packets have to be multirouted.
7783 		 * In this case, given the current <ire, sire> couple,
7784 		 * we look for the next suitable <ire, sire>.
7785 		 * This check is done in ire_multirt_lookup(),
7786 		 * which applies various criteria to find the next route
7787 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7788 		 * unchanged if it detects it has not been tried yet.
7789 		 */
7790 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7791 			ip3dbg(("ip_newroute: starting next_resolution "
7792 			    "with first_mp %p, tag %d\n",
7793 			    (void *)first_mp,
7794 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7795 
7796 			ASSERT(sire != NULL);
7797 			multirt_is_resolvable =
7798 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7799 				MBLK_GETLABEL(mp));
7800 
7801 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7802 			    "ire %p, sire %p\n",
7803 			    multirt_is_resolvable,
7804 			    (void *)ire, (void *)sire));
7805 
7806 			if (!multirt_is_resolvable) {
7807 				/*
7808 				 * No more multirt route to resolve; give up
7809 				 * (all routes resolved or no more
7810 				 * resolvable routes).
7811 				 */
7812 				if (ire != NULL) {
7813 					ire_refrele(ire);
7814 					ire = NULL;
7815 				}
7816 			} else {
7817 				ASSERT(sire != NULL);
7818 				ASSERT(ire != NULL);
7819 				/*
7820 				 * We simply use first_sire as a flag that
7821 				 * indicates if a resolvable multirt route
7822 				 * has already been found.
7823 				 * If it is not the case, we may have to send
7824 				 * an ICMP error to report that the
7825 				 * destination is unreachable.
7826 				 * We do not IRE_REFHOLD first_sire.
7827 				 */
7828 				if (first_sire == NULL) {
7829 					first_sire = sire;
7830 				}
7831 			}
7832 		}
7833 		if (ire == NULL) {
7834 			if (ip_debug > 3) {
7835 				/* ip2dbg */
7836 				pr_addr_dbg("ip_newroute: "
7837 				    "can't resolve %s\n", AF_INET, &dst);
7838 			}
7839 			ip3dbg(("ip_newroute: "
7840 			    "ire %p, sire %p, first_sire %p\n",
7841 			    (void *)ire, (void *)sire, (void *)first_sire));
7842 
7843 			if (sire != NULL) {
7844 				ire_refrele(sire);
7845 				sire = NULL;
7846 			}
7847 
7848 			if (first_sire != NULL) {
7849 				/*
7850 				 * At least one multirt route has been found
7851 				 * in the same call to ip_newroute();
7852 				 * there is no need to report an ICMP error.
7853 				 * first_sire was not IRE_REFHOLDed.
7854 				 */
7855 				MULTIRT_DEBUG_UNTAG(first_mp);
7856 				freemsg(first_mp);
7857 				return;
7858 			}
7859 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7860 			    RTA_DST);
7861 			if (attach_ill != NULL)
7862 				ill_refrele(attach_ill);
7863 			goto icmp_err_ret;
7864 		}
7865 
7866 		/*
7867 		 * When RTA_SRCIFP is used to add a route, then an interface
7868 		 * route is added in the source interface's routing table.
7869 		 * If the outgoing interface of this route is of type
7870 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7871 		 * ire_nce->nce_res_mp is set to NULL.
7872 		 * Later, when this route is first used for forwarding
7873 		 * a packet, ip_newroute() is called
7874 		 * to resolve the hardware address of the outgoing ipif.
7875 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7876 		 * source interface based table. We only come here if the
7877 		 * outgoing interface is a resolver interface and we don't
7878 		 * have the ire_nce->nce_res_mp information yet.
7879 		 * If in_ill is not null that means it is called from
7880 		 * ip_rput.
7881 		 */
7882 
7883 		ASSERT(ire->ire_in_ill == NULL ||
7884 		    (ire->ire_type == IRE_IF_RESOLVER &&
7885 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7886 
7887 		/*
7888 		 * Verify that the returned IRE does not have either
7889 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7890 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7891 		 */
7892 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7893 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7894 			if (attach_ill != NULL)
7895 				ill_refrele(attach_ill);
7896 			goto icmp_err_ret;
7897 		}
7898 		/*
7899 		 * Increment the ire_ob_pkt_count field for ire if it is an
7900 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7901 		 * increment the same for the parent IRE, sire, if it is some
7902 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7903 		 * and HOST_REDIRECT).
7904 		 */
7905 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7906 			UPDATE_OB_PKT_COUNT(ire);
7907 			ire->ire_last_used_time = lbolt;
7908 		}
7909 
7910 		if (sire != NULL) {
7911 			gw = sire->ire_gateway_addr;
7912 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7913 			    IRE_INTERFACE)) == 0);
7914 			UPDATE_OB_PKT_COUNT(sire);
7915 			sire->ire_last_used_time = lbolt;
7916 		}
7917 		/*
7918 		 * We have a route to reach the destination.
7919 		 *
7920 		 * 1) If the interface is part of ill group, try to get a new
7921 		 *    ill taking load spreading into account.
7922 		 *
7923 		 * 2) After selecting the ill, get a source address that
7924 		 *    might create good inbound load spreading.
7925 		 *    ipif_select_source does this for us.
7926 		 *
7927 		 * If the application specified the ill (ifindex), we still
7928 		 * load spread. Only if the packets needs to go out
7929 		 * specifically on a given ill e.g. binding to
7930 		 * IPIF_NOFAILOVER address, then we don't try to use a
7931 		 * different ill for load spreading.
7932 		 */
7933 		if (attach_ill == NULL) {
7934 			/*
7935 			 * Don't perform outbound load spreading in the
7936 			 * case of an RTF_MULTIRT route, as we actually
7937 			 * typically want to replicate outgoing packets
7938 			 * through particular interfaces.
7939 			 */
7940 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7941 				dst_ill = ire->ire_ipif->ipif_ill;
7942 				/* for uniformity */
7943 				ill_refhold(dst_ill);
7944 			} else {
7945 				/*
7946 				 * If we are here trying to create an IRE_CACHE
7947 				 * for an offlink destination and have the
7948 				 * IRE_CACHE for the next hop and the latter is
7949 				 * using virtual IP source address selection i.e
7950 				 * it's ire->ire_ipif is pointing to a virtual
7951 				 * network interface (vni) then
7952 				 * ip_newroute_get_dst_ll() will return the vni
7953 				 * interface as the dst_ill. Since the vni is
7954 				 * virtual i.e not associated with any physical
7955 				 * interface, it cannot be the dst_ill, hence
7956 				 * in such a case call ip_newroute_get_dst_ll()
7957 				 * with the stq_ill instead of the ire_ipif ILL.
7958 				 * The function returns a refheld ill.
7959 				 */
7960 				if ((ire->ire_type == IRE_CACHE) &&
7961 				    IS_VNI(ire->ire_ipif->ipif_ill))
7962 					dst_ill = ip_newroute_get_dst_ill(
7963 						ire->ire_stq->q_ptr);
7964 				else
7965 					dst_ill = ip_newroute_get_dst_ill(
7966 						ire->ire_ipif->ipif_ill);
7967 			}
7968 			if (dst_ill == NULL) {
7969 				if (ip_debug > 2) {
7970 					pr_addr_dbg("ip_newroute: "
7971 					    "no dst ill for dst"
7972 					    " %s\n", AF_INET, &dst);
7973 				}
7974 				goto icmp_err_ret;
7975 			}
7976 		} else {
7977 			dst_ill = ire->ire_ipif->ipif_ill;
7978 			/* for uniformity */
7979 			ill_refhold(dst_ill);
7980 			/*
7981 			 * We should have found a route matching ill as we
7982 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7983 			 * Rather than asserting, when there is a mismatch,
7984 			 * we just drop the packet.
7985 			 */
7986 			if (dst_ill != attach_ill) {
7987 				ip0dbg(("ip_newroute: Packet dropped as "
7988 				    "IPIF_NOFAILOVER ill is %s, "
7989 				    "ire->ire_ipif->ipif_ill is %s\n",
7990 				    attach_ill->ill_name,
7991 				    dst_ill->ill_name));
7992 				ill_refrele(attach_ill);
7993 				goto icmp_err_ret;
7994 			}
7995 		}
7996 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7997 		if (attach_ill != NULL) {
7998 			ill_refrele(attach_ill);
7999 			attach_ill = NULL;
8000 			do_attach_ill = B_TRUE;
8001 		}
8002 		ASSERT(dst_ill != NULL);
8003 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8004 
8005 		/*
8006 		 * Pick the best source address from dst_ill.
8007 		 *
8008 		 * 1) If it is part of a multipathing group, we would
8009 		 *    like to spread the inbound packets across different
8010 		 *    interfaces. ipif_select_source picks a random source
8011 		 *    across the different ills in the group.
8012 		 *
8013 		 * 2) If it is not part of a multipathing group, we try
8014 		 *    to pick the source address from the destination
8015 		 *    route. Clustering assumes that when we have multiple
8016 		 *    prefixes hosted on an interface, the prefix of the
8017 		 *    source address matches the prefix of the destination
8018 		 *    route. We do this only if the address is not
8019 		 *    DEPRECATED.
8020 		 *
8021 		 * 3) If the conn is in a different zone than the ire, we
8022 		 *    need to pick a source address from the right zone.
8023 		 *
8024 		 * NOTE : If we hit case (1) above, the prefix of the source
8025 		 *	  address picked may not match the prefix of the
8026 		 *	  destination routes prefix as ipif_select_source
8027 		 *	  does not look at "dst" while picking a source
8028 		 *	  address.
8029 		 *	  If we want the same behavior as (2), we will need
8030 		 *	  to change the behavior of ipif_select_source.
8031 		 */
8032 		ASSERT(src_ipif == NULL);
8033 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8034 			/*
8035 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8036 			 * Check that the ipif matching the requested source
8037 			 * address still exists.
8038 			 */
8039 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8040 			    zoneid, NULL, NULL, NULL, NULL);
8041 		}
8042 		if (src_ipif == NULL) {
8043 			ire_marks |= IRE_MARK_USESRC_CHECK;
8044 			if ((dst_ill->ill_group != NULL) ||
8045 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8046 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8047 			    ire->ire_zoneid != ALL_ZONES) ||
8048 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8049 				/*
8050 				 * If the destination is reachable via a
8051 				 * given gateway, the selected source address
8052 				 * should be in the same subnet as the gateway.
8053 				 * Otherwise, the destination is not reachable.
8054 				 *
8055 				 * If there are no interfaces on the same subnet
8056 				 * as the destination, ipif_select_source gives
8057 				 * first non-deprecated interface which might be
8058 				 * on a different subnet than the gateway.
8059 				 * This is not desirable. Hence pass the dst_ire
8060 				 * source address to ipif_select_source.
8061 				 * It is sure that the destination is reachable
8062 				 * with the dst_ire source address subnet.
8063 				 * So passing dst_ire source address to
8064 				 * ipif_select_source will make sure that the
8065 				 * selected source will be on the same subnet
8066 				 * as dst_ire source address.
8067 				 */
8068 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8069 				src_ipif = ipif_select_source(dst_ill, saddr,
8070 				    zoneid);
8071 				if (src_ipif == NULL) {
8072 					if (ip_debug > 2) {
8073 						pr_addr_dbg("ip_newroute: "
8074 						    "no src for dst %s ",
8075 						    AF_INET, &dst);
8076 						printf("through interface %s\n",
8077 						    dst_ill->ill_name);
8078 					}
8079 					goto icmp_err_ret;
8080 				}
8081 			} else {
8082 				src_ipif = ire->ire_ipif;
8083 				ASSERT(src_ipif != NULL);
8084 				/* hold src_ipif for uniformity */
8085 				ipif_refhold(src_ipif);
8086 			}
8087 		}
8088 
8089 		/*
8090 		 * Assign a source address while we have the conn.
8091 		 * We can't have ip_wput_ire pick a source address when the
8092 		 * packet returns from arp since we need to look at
8093 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8094 		 * going through arp.
8095 		 *
8096 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8097 		 *	  it uses ip6i to store this information.
8098 		 */
8099 		if (ipha->ipha_src == INADDR_ANY &&
8100 		    (connp == NULL || !connp->conn_unspec_src)) {
8101 			ipha->ipha_src = src_ipif->ipif_src_addr;
8102 		}
8103 		if (ip_debug > 3) {
8104 			/* ip2dbg */
8105 			pr_addr_dbg("ip_newroute: first hop %s\n",
8106 			    AF_INET, &gw);
8107 		}
8108 		ip2dbg(("\tire type %s (%d)\n",
8109 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8110 
8111 		/*
8112 		 * The TTL of multirouted packets is bounded by the
8113 		 * ip_multirt_ttl ndd variable.
8114 		 */
8115 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8116 			/* Force TTL of multirouted packets */
8117 			if ((ip_multirt_ttl > 0) &&
8118 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8119 				ip2dbg(("ip_newroute: forcing multirt TTL "
8120 				    "to %d (was %d), dst 0x%08x\n",
8121 				    ip_multirt_ttl, ipha->ipha_ttl,
8122 				    ntohl(sire->ire_addr)));
8123 				ipha->ipha_ttl = ip_multirt_ttl;
8124 			}
8125 		}
8126 		/*
8127 		 * At this point in ip_newroute(), ire is either the
8128 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8129 		 * destination or an IRE_INTERFACE type that should be used
8130 		 * to resolve an on-subnet destination or an on-subnet
8131 		 * next-hop gateway.
8132 		 *
8133 		 * In the IRE_CACHE case, we have the following :
8134 		 *
8135 		 * 1) src_ipif - used for getting a source address.
8136 		 *
8137 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8138 		 *    means packets using this IRE_CACHE will go out on
8139 		 *    dst_ill.
8140 		 *
8141 		 * 3) The IRE sire will point to the prefix that is the
8142 		 *    longest  matching route for the destination. These
8143 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8144 		 *
8145 		 *    The newly created IRE_CACHE entry for the off-subnet
8146 		 *    destination is tied to both the prefix route and the
8147 		 *    interface route used to resolve the next-hop gateway
8148 		 *    via the ire_phandle and ire_ihandle fields,
8149 		 *    respectively.
8150 		 *
8151 		 * In the IRE_INTERFACE case, we have the following :
8152 		 *
8153 		 * 1) src_ipif - used for getting a source address.
8154 		 *
8155 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8156 		 *    means packets using the IRE_CACHE that we will build
8157 		 *    here will go out on dst_ill.
8158 		 *
8159 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8160 		 *    to be created will only be tied to the IRE_INTERFACE
8161 		 *    that was derived from the ire_ihandle field.
8162 		 *
8163 		 *    If sire is non-NULL, it means the destination is
8164 		 *    off-link and we will first create the IRE_CACHE for the
8165 		 *    gateway. Next time through ip_newroute, we will create
8166 		 *    the IRE_CACHE for the final destination as described
8167 		 *    above.
8168 		 *
8169 		 * In both cases, after the current resolution has been
8170 		 * completed (or possibly initialised, in the IRE_INTERFACE
8171 		 * case), the loop may be re-entered to attempt the resolution
8172 		 * of another RTF_MULTIRT route.
8173 		 *
8174 		 * When an IRE_CACHE entry for the off-subnet destination is
8175 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8176 		 * for further processing in emission loops.
8177 		 */
8178 		save_ire = ire;
8179 		switch (ire->ire_type) {
8180 		case IRE_CACHE: {
8181 			ire_t	*ipif_ire;
8182 			mblk_t	*ire_fp_mp;
8183 
8184 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8185 			if (gw == 0)
8186 				gw = ire->ire_gateway_addr;
8187 			/*
8188 			 * We need 3 ire's to create a new cache ire for an
8189 			 * off-link destination from the cache ire of the
8190 			 * gateway.
8191 			 *
8192 			 *	1. The prefix ire 'sire' (Note that this does
8193 			 *	   not apply to the conn_nexthop_set case)
8194 			 *	2. The cache ire of the gateway 'ire'
8195 			 *	3. The interface ire 'ipif_ire'
8196 			 *
8197 			 * We have (1) and (2). We lookup (3) below.
8198 			 *
8199 			 * If there is no interface route to the gateway,
8200 			 * it is a race condition, where we found the cache
8201 			 * but the interface route has been deleted.
8202 			 */
8203 			if (ip_nexthop) {
8204 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8205 			} else {
8206 				ipif_ire =
8207 				    ire_ihandle_lookup_offlink(ire, sire);
8208 			}
8209 			if (ipif_ire == NULL) {
8210 				ip1dbg(("ip_newroute: "
8211 				    "ire_ihandle_lookup_offlink failed\n"));
8212 				goto icmp_err_ret;
8213 			}
8214 			/*
8215 			 * XXX We are using the same res_mp
8216 			 * (DL_UNITDATA_REQ) though the save_ire is not
8217 			 * pointing at the same ill.
8218 			 * This is incorrect. We need to send it up to the
8219 			 * resolver to get the right res_mp. For ethernets
8220 			 * this may be okay (ill_type == DL_ETHER).
8221 			 */
8222 			res_mp = save_ire->ire_nce->nce_res_mp;
8223 			ire_fp_mp = NULL;
8224 			/*
8225 			 * save_ire's nce_fp_mp can't change since it is
8226 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8227 			 * LOCK_IRE_FP_MP does not do any useful work in
8228 			 * the case of IRE_CACHE. So we don't use it below.
8229 			 */
8230 			if (save_ire->ire_stq == dst_ill->ill_wq)
8231 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8232 
8233 			/*
8234 			 * Check cached gateway IRE for any security
8235 			 * attributes; if found, associate the gateway
8236 			 * credentials group to the destination IRE.
8237 			 */
8238 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8239 				mutex_enter(&attrp->igsa_lock);
8240 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8241 					GCGRP_REFHOLD(gcgrp);
8242 				mutex_exit(&attrp->igsa_lock);
8243 			}
8244 
8245 			ire = ire_create(
8246 			    (uchar_t *)&dst,		/* dest address */
8247 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8248 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8249 			    (uchar_t *)&gw,		/* gateway address */
8250 			    NULL,
8251 			    &save_ire->ire_max_frag,
8252 			    ire_fp_mp,			/* Fast Path header */
8253 			    dst_ill->ill_rq,		/* recv-from queue */
8254 			    dst_ill->ill_wq,		/* send-to queue */
8255 			    IRE_CACHE,			/* IRE type */
8256 			    res_mp,
8257 			    src_ipif,
8258 			    in_ill,			/* incoming ill */
8259 			    (sire != NULL) ?
8260 				sire->ire_mask : 0, 	/* Parent mask */
8261 			    (sire != NULL) ?
8262 				sire->ire_phandle : 0,  /* Parent handle */
8263 			    ipif_ire->ire_ihandle,	/* Interface handle */
8264 			    (sire != NULL) ? (sire->ire_flags &
8265 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8266 			    (sire != NULL) ?
8267 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8268 			    NULL,
8269 			    gcgrp);
8270 
8271 			if (ire == NULL) {
8272 				if (gcgrp != NULL) {
8273 					GCGRP_REFRELE(gcgrp);
8274 					gcgrp = NULL;
8275 				}
8276 				ire_refrele(ipif_ire);
8277 				ire_refrele(save_ire);
8278 				break;
8279 			}
8280 
8281 			/* reference now held by IRE */
8282 			gcgrp = NULL;
8283 
8284 			ire->ire_marks |= ire_marks;
8285 
8286 			/*
8287 			 * Prevent sire and ipif_ire from getting deleted.
8288 			 * The newly created ire is tied to both of them via
8289 			 * the phandle and ihandle respectively.
8290 			 */
8291 			if (sire != NULL) {
8292 				IRB_REFHOLD(sire->ire_bucket);
8293 				/* Has it been removed already ? */
8294 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8295 					IRB_REFRELE(sire->ire_bucket);
8296 					ire_refrele(ipif_ire);
8297 					ire_refrele(save_ire);
8298 					break;
8299 				}
8300 			}
8301 
8302 			IRB_REFHOLD(ipif_ire->ire_bucket);
8303 			/* Has it been removed already ? */
8304 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8305 				IRB_REFRELE(ipif_ire->ire_bucket);
8306 				if (sire != NULL)
8307 					IRB_REFRELE(sire->ire_bucket);
8308 				ire_refrele(ipif_ire);
8309 				ire_refrele(save_ire);
8310 				break;
8311 			}
8312 
8313 			xmit_mp = first_mp;
8314 			/*
8315 			 * In the case of multirouting, a copy
8316 			 * of the packet is done before its sending.
8317 			 * The copy is used to attempt another
8318 			 * route resolution, in a next loop.
8319 			 */
8320 			if (ire->ire_flags & RTF_MULTIRT) {
8321 				copy_mp = copymsg(first_mp);
8322 				if (copy_mp != NULL) {
8323 					xmit_mp = copy_mp;
8324 					MULTIRT_DEBUG_TAG(first_mp);
8325 				}
8326 			}
8327 			ire_add_then_send(q, ire, xmit_mp);
8328 			ire_refrele(save_ire);
8329 
8330 			/* Assert that sire is not deleted yet. */
8331 			if (sire != NULL) {
8332 				ASSERT(sire->ire_ptpn != NULL);
8333 				IRB_REFRELE(sire->ire_bucket);
8334 			}
8335 
8336 			/* Assert that ipif_ire is not deleted yet. */
8337 			ASSERT(ipif_ire->ire_ptpn != NULL);
8338 			IRB_REFRELE(ipif_ire->ire_bucket);
8339 			ire_refrele(ipif_ire);
8340 
8341 			/*
8342 			 * If copy_mp is not NULL, multirouting was
8343 			 * requested. We loop to initiate a next
8344 			 * route resolution attempt, starting from sire.
8345 			 */
8346 			if (copy_mp != NULL) {
8347 				/*
8348 				 * Search for the next unresolved
8349 				 * multirt route.
8350 				 */
8351 				copy_mp = NULL;
8352 				ipif_ire = NULL;
8353 				ire = NULL;
8354 				multirt_resolve_next = B_TRUE;
8355 				continue;
8356 			}
8357 			if (sire != NULL)
8358 				ire_refrele(sire);
8359 			ipif_refrele(src_ipif);
8360 			ill_refrele(dst_ill);
8361 			return;
8362 		}
8363 		case IRE_IF_NORESOLVER: {
8364 			/*
8365 			 * We have what we need to build an IRE_CACHE.
8366 			 *
8367 			 * Create a new res_mp with the IP gateway address
8368 			 * in destination address in the DLPI hdr if the
8369 			 * physical length is exactly 4 bytes.
8370 			 */
8371 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8372 				uchar_t *addr;
8373 
8374 				if (gw)
8375 					addr = (uchar_t *)&gw;
8376 				else
8377 					addr = (uchar_t *)&dst;
8378 
8379 				res_mp = ill_dlur_gen(addr,
8380 				    dst_ill->ill_phys_addr_length,
8381 				    dst_ill->ill_sap,
8382 				    dst_ill->ill_sap_length);
8383 
8384 				if (res_mp == NULL) {
8385 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8386 					break;
8387 				}
8388 			} else {
8389 				res_mp = NULL;
8390 			}
8391 
8392 			/*
8393 			 * TSol note: We are creating the ire cache for the
8394 			 * destination 'dst'. If 'dst' is offlink, going
8395 			 * through the first hop 'gw', the security attributes
8396 			 * of 'dst' must be set to point to the gateway
8397 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8398 			 * is possible that 'dst' is a potential gateway that is
8399 			 * referenced by some route that has some security
8400 			 * attributes. Thus in the former case, we need to do a
8401 			 * gcgrp_lookup of 'gw' while in the latter case we
8402 			 * need to do gcgrp_lookup of 'dst' itself.
8403 			 */
8404 			ga.ga_af = AF_INET;
8405 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8406 			    &ga.ga_addr);
8407 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8408 
8409 			ire = ire_create(
8410 			    (uchar_t *)&dst,		/* dest address */
8411 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8412 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8413 			    (uchar_t *)&gw,		/* gateway address */
8414 			    NULL,
8415 			    &save_ire->ire_max_frag,
8416 			    NULL,			/* Fast Path header */
8417 			    dst_ill->ill_rq,		/* recv-from queue */
8418 			    dst_ill->ill_wq,		/* send-to queue */
8419 			    IRE_CACHE,
8420 			    res_mp,
8421 			    src_ipif,
8422 			    in_ill,			/* Incoming ill */
8423 			    save_ire->ire_mask,		/* Parent mask */
8424 			    (sire != NULL) ?		/* Parent handle */
8425 				sire->ire_phandle : 0,
8426 			    save_ire->ire_ihandle,	/* Interface handle */
8427 			    (sire != NULL) ? sire->ire_flags &
8428 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8429 			    &(save_ire->ire_uinfo),
8430 			    NULL,
8431 			    gcgrp);
8432 
8433 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8434 				freeb(res_mp);
8435 
8436 			if (ire == NULL) {
8437 				if (gcgrp != NULL) {
8438 					GCGRP_REFRELE(gcgrp);
8439 					gcgrp = NULL;
8440 				}
8441 				ire_refrele(save_ire);
8442 				break;
8443 			}
8444 
8445 			/* reference now held by IRE */
8446 			gcgrp = NULL;
8447 
8448 			ire->ire_marks |= ire_marks;
8449 
8450 			/* Prevent save_ire from getting deleted */
8451 			IRB_REFHOLD(save_ire->ire_bucket);
8452 			/* Has it been removed already ? */
8453 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8454 				IRB_REFRELE(save_ire->ire_bucket);
8455 				ire_refrele(save_ire);
8456 				break;
8457 			}
8458 
8459 			/*
8460 			 * In the case of multirouting, a copy
8461 			 * of the packet is made before it is sent.
8462 			 * The copy is used in the next
8463 			 * loop to attempt another resolution.
8464 			 */
8465 			xmit_mp = first_mp;
8466 			if ((sire != NULL) &&
8467 			    (sire->ire_flags & RTF_MULTIRT)) {
8468 				copy_mp = copymsg(first_mp);
8469 				if (copy_mp != NULL) {
8470 					xmit_mp = copy_mp;
8471 					MULTIRT_DEBUG_TAG(first_mp);
8472 				}
8473 			}
8474 			ire_add_then_send(q, ire, xmit_mp);
8475 
8476 			/* Assert that it is not deleted yet. */
8477 			ASSERT(save_ire->ire_ptpn != NULL);
8478 			IRB_REFRELE(save_ire->ire_bucket);
8479 			ire_refrele(save_ire);
8480 
8481 			if (copy_mp != NULL) {
8482 				/*
8483 				 * If we found a (no)resolver, we ignore any
8484 				 * trailing top priority IRE_CACHE in further
8485 				 * loops. This ensures that we do not omit any
8486 				 * (no)resolver.
8487 				 * This IRE_CACHE, if any, will be processed
8488 				 * by another thread entering ip_newroute().
8489 				 * IRE_CACHE entries, if any, will be processed
8490 				 * by another thread entering ip_newroute(),
8491 				 * (upon resolver response, for instance).
8492 				 * This aims to force parallel multirt
8493 				 * resolutions as soon as a packet must be sent.
8494 				 * In the best case, after the tx of only one
8495 				 * packet, all reachable routes are resolved.
8496 				 * Otherwise, the resolution of all RTF_MULTIRT
8497 				 * routes would require several emissions.
8498 				 */
8499 				multirt_flags &= ~MULTIRT_CACHEGW;
8500 
8501 				/*
8502 				 * Search for the next unresolved multirt
8503 				 * route.
8504 				 */
8505 				copy_mp = NULL;
8506 				save_ire = NULL;
8507 				ire = NULL;
8508 				multirt_resolve_next = B_TRUE;
8509 				continue;
8510 			}
8511 
8512 			/*
8513 			 * Don't need sire anymore
8514 			 */
8515 			if (sire != NULL)
8516 				ire_refrele(sire);
8517 
8518 			ipif_refrele(src_ipif);
8519 			ill_refrele(dst_ill);
8520 			return;
8521 		}
8522 		case IRE_IF_RESOLVER:
8523 			/*
8524 			 * We can't build an IRE_CACHE yet, but at least we
8525 			 * found a resolver that can help.
8526 			 */
8527 			res_mp = dst_ill->ill_resolver_mp;
8528 			if (!OK_RESOLVER_MP(res_mp))
8529 				break;
8530 
8531 			/*
8532 			 * To be at this point in the code with a non-zero gw
8533 			 * means that dst is reachable through a gateway that
8534 			 * we have never resolved.  By changing dst to the gw
8535 			 * addr we resolve the gateway first.
8536 			 * When ire_add_then_send() tries to put the IP dg
8537 			 * to dst, it will reenter ip_newroute() at which
8538 			 * time we will find the IRE_CACHE for the gw and
8539 			 * create another IRE_CACHE in case IRE_CACHE above.
8540 			 */
8541 			if (gw != INADDR_ANY) {
8542 				/*
8543 				 * The source ipif that was determined above was
8544 				 * relative to the destination address, not the
8545 				 * gateway's. If src_ipif was not taken out of
8546 				 * the IRE_IF_RESOLVER entry, we'll need to call
8547 				 * ipif_select_source() again.
8548 				 */
8549 				if (src_ipif != ire->ire_ipif) {
8550 					ipif_refrele(src_ipif);
8551 					src_ipif = ipif_select_source(dst_ill,
8552 					    gw, zoneid);
8553 					if (src_ipif == NULL) {
8554 						if (ip_debug > 2) {
8555 							pr_addr_dbg(
8556 							    "ip_newroute: no "
8557 							    "src for gw %s ",
8558 							    AF_INET, &gw);
8559 							printf("through "
8560 							    "interface %s\n",
8561 							    dst_ill->ill_name);
8562 						}
8563 						goto icmp_err_ret;
8564 					}
8565 				}
8566 				save_dst = dst;
8567 				dst = gw;
8568 				gw = INADDR_ANY;
8569 			}
8570 
8571 			/*
8572 			 * We obtain a partial IRE_CACHE which we will pass
8573 			 * along with the resolver query.  When the response
8574 			 * comes back it will be there ready for us to add.
8575 			 * The ire_max_frag is atomically set under the
8576 			 * irebucket lock in ire_add_v[46].
8577 			 */
8578 
8579 			ire = ire_create_mp(
8580 			    (uchar_t *)&dst,		/* dest address */
8581 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8582 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8583 			    (uchar_t *)&gw,		/* gateway address */
8584 			    NULL,			/* no in_src_addr */
8585 			    NULL,			/* ire_max_frag */
8586 			    NULL,			/* Fast Path header */
8587 			    dst_ill->ill_rq,		/* recv-from queue */
8588 			    dst_ill->ill_wq,		/* send-to queue */
8589 			    IRE_CACHE,
8590 			    NULL,
8591 			    src_ipif,			/* Interface ipif */
8592 			    in_ill,			/* Incoming ILL */
8593 			    save_ire->ire_mask,		/* Parent mask */
8594 			    0,
8595 			    save_ire->ire_ihandle,	/* Interface handle */
8596 			    0,				/* flags if any */
8597 			    &(save_ire->ire_uinfo),
8598 			    NULL,
8599 			    NULL);
8600 
8601 			if (ire == NULL) {
8602 				ire_refrele(save_ire);
8603 				break;
8604 			}
8605 
8606 			if ((sire != NULL) &&
8607 			    (sire->ire_flags & RTF_MULTIRT)) {
8608 				copy_mp = copymsg(first_mp);
8609 				if (copy_mp != NULL)
8610 					MULTIRT_DEBUG_TAG(copy_mp);
8611 			}
8612 
8613 			ire->ire_marks |= ire_marks;
8614 
8615 			/*
8616 			 * Construct message chain for the resolver
8617 			 * of the form:
8618 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8619 			 * Packet could contain a IPSEC_OUT mp.
8620 			 *
8621 			 * NOTE : ire will be added later when the response
8622 			 * comes back from ARP. If the response does not
8623 			 * come back, ARP frees the packet. For this reason,
8624 			 * we can't REFHOLD the bucket of save_ire to prevent
8625 			 * deletions. We may not be able to REFRELE the bucket
8626 			 * if the response never comes back. Thus, before
8627 			 * adding the ire, ire_add_v4 will make sure that the
8628 			 * interface route does not get deleted. This is the
8629 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8630 			 * where we can always prevent deletions because of
8631 			 * the synchronous nature of adding IRES i.e
8632 			 * ire_add_then_send is called after creating the IRE.
8633 			 */
8634 			ASSERT(ire->ire_mp != NULL);
8635 			ire->ire_mp->b_cont = first_mp;
8636 			/* Have saved_mp handy, for cleanup if canput fails */
8637 			saved_mp = mp;
8638 			mp = copyb(res_mp);
8639 			if (mp == NULL) {
8640 				/* Prepare for cleanup */
8641 				mp = saved_mp; /* pkt */
8642 				ire_delete(ire); /* ire_mp */
8643 				ire = NULL;
8644 				ire_refrele(save_ire);
8645 				if (copy_mp != NULL) {
8646 					MULTIRT_DEBUG_UNTAG(copy_mp);
8647 					freemsg(copy_mp);
8648 					copy_mp = NULL;
8649 				}
8650 				break;
8651 			}
8652 			linkb(mp, ire->ire_mp);
8653 
8654 			/*
8655 			 * Fill in the source and dest addrs for the resolver.
8656 			 * NOTE: this depends on memory layouts imposed by
8657 			 * ill_init().
8658 			 */
8659 			areq = (areq_t *)mp->b_rptr;
8660 			addrp = (ipaddr_t *)((char *)areq +
8661 			    areq->areq_sender_addr_offset);
8662 			if (do_attach_ill) {
8663 				/*
8664 				 * This is bind to no failover case.
8665 				 * arp packet also must go out on attach_ill.
8666 				 */
8667 				ASSERT(ipha->ipha_src != NULL);
8668 				*addrp = ipha->ipha_src;
8669 			} else {
8670 				*addrp = save_ire->ire_src_addr;
8671 			}
8672 
8673 			ire_refrele(save_ire);
8674 			addrp = (ipaddr_t *)((char *)areq +
8675 			    areq->areq_target_addr_offset);
8676 			*addrp = dst;
8677 			/* Up to the resolver. */
8678 			if (canputnext(dst_ill->ill_rq) &&
8679 			    !(dst_ill->ill_arp_closing)) {
8680 				putnext(dst_ill->ill_rq, mp);
8681 				ire = NULL;
8682 				if (copy_mp != NULL) {
8683 					/*
8684 					 * If we found a resolver, we ignore
8685 					 * any trailing top priority IRE_CACHE
8686 					 * in the further loops. This ensures
8687 					 * that we do not omit any resolver.
8688 					 * IRE_CACHE entries, if any, will be
8689 					 * processed next time we enter
8690 					 * ip_newroute().
8691 					 */
8692 					multirt_flags &= ~MULTIRT_CACHEGW;
8693 					/*
8694 					 * Search for the next unresolved
8695 					 * multirt route.
8696 					 */
8697 					first_mp = copy_mp;
8698 					copy_mp = NULL;
8699 					/* Prepare the next resolution loop. */
8700 					mp = first_mp;
8701 					EXTRACT_PKT_MP(mp, first_mp,
8702 					    mctl_present);
8703 					if (mctl_present)
8704 						io = (ipsec_out_t *)
8705 						    first_mp->b_rptr;
8706 					ipha = (ipha_t *)mp->b_rptr;
8707 
8708 					ASSERT(sire != NULL);
8709 
8710 					dst = save_dst;
8711 					multirt_resolve_next = B_TRUE;
8712 					continue;
8713 				}
8714 
8715 				if (sire != NULL)
8716 					ire_refrele(sire);
8717 
8718 				/*
8719 				 * The response will come back in ip_wput
8720 				 * with db_type IRE_DB_TYPE.
8721 				 */
8722 				ipif_refrele(src_ipif);
8723 				ill_refrele(dst_ill);
8724 				return;
8725 			} else {
8726 				/* Prepare for cleanup */
8727 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8728 				    mp);
8729 				mp->b_cont = NULL;
8730 				freeb(mp); /* areq */
8731 				/*
8732 				 * this is an ire that is not added to the
8733 				 * cache. ire_freemblk will handle the release
8734 				 * of any resources associated with the ire.
8735 				 */
8736 				ire_delete(ire); /* ire_mp */
8737 				mp = saved_mp; /* pkt */
8738 				ire = NULL;
8739 				if (copy_mp != NULL) {
8740 					MULTIRT_DEBUG_UNTAG(copy_mp);
8741 					freemsg(copy_mp);
8742 					copy_mp = NULL;
8743 				}
8744 				break;
8745 			}
8746 		default:
8747 			break;
8748 		}
8749 	} while (multirt_resolve_next);
8750 
8751 	ip1dbg(("ip_newroute: dropped\n"));
8752 	/* Did this packet originate externally? */
8753 	if (mp->b_prev) {
8754 		mp->b_next = NULL;
8755 		mp->b_prev = NULL;
8756 		BUMP_MIB(&ip_mib, ipInDiscards);
8757 	} else {
8758 		BUMP_MIB(&ip_mib, ipOutDiscards);
8759 	}
8760 	ASSERT(copy_mp == NULL);
8761 	MULTIRT_DEBUG_UNTAG(first_mp);
8762 	freemsg(first_mp);
8763 	if (ire != NULL)
8764 		ire_refrele(ire);
8765 	if (sire != NULL)
8766 		ire_refrele(sire);
8767 	if (src_ipif != NULL)
8768 		ipif_refrele(src_ipif);
8769 	if (dst_ill != NULL)
8770 		ill_refrele(dst_ill);
8771 	return;
8772 
8773 icmp_err_ret:
8774 	ip1dbg(("ip_newroute: no route\n"));
8775 	if (src_ipif != NULL)
8776 		ipif_refrele(src_ipif);
8777 	if (dst_ill != NULL)
8778 		ill_refrele(dst_ill);
8779 	if (sire != NULL)
8780 		ire_refrele(sire);
8781 	/* Did this packet originate externally? */
8782 	if (mp->b_prev) {
8783 		mp->b_next = NULL;
8784 		mp->b_prev = NULL;
8785 		/* XXX ipInNoRoutes */
8786 		q = WR(q);
8787 	} else {
8788 		/*
8789 		 * Since ip_wput() isn't close to finished, we fill
8790 		 * in enough of the header for credible error reporting.
8791 		 */
8792 		if (ip_hdr_complete(ipha, zoneid)) {
8793 			/* Failed */
8794 			MULTIRT_DEBUG_UNTAG(first_mp);
8795 			freemsg(first_mp);
8796 			if (ire != NULL)
8797 				ire_refrele(ire);
8798 			return;
8799 		}
8800 	}
8801 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8802 
8803 	/*
8804 	 * At this point we will have ire only if RTF_BLACKHOLE
8805 	 * or RTF_REJECT flags are set on the IRE. It will not
8806 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8807 	 */
8808 	if (ire != NULL) {
8809 		if (ire->ire_flags & RTF_BLACKHOLE) {
8810 			ire_refrele(ire);
8811 			MULTIRT_DEBUG_UNTAG(first_mp);
8812 			freemsg(first_mp);
8813 			return;
8814 		}
8815 		ire_refrele(ire);
8816 	}
8817 	if (ip_source_routed(ipha)) {
8818 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8819 		    zoneid);
8820 		return;
8821 	}
8822 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8823 }
8824 
8825 /*
8826  * IPv4 -
8827  * ip_newroute_ipif is called by ip_wput_multicast and
8828  * ip_rput_forward_multicast whenever we need to send
8829  * out a packet to a destination address for which we do not have specific
8830  * routing information. It is used when the packet will be sent out
8831  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8832  * socket option is set or icmp error message wants to go out on a particular
8833  * interface for a unicast packet.
8834  *
8835  * In most cases, the destination address is resolved thanks to the ipif
8836  * intrinsic resolver. However, there are some cases where the call to
8837  * ip_newroute_ipif must take into account the potential presence of
8838  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8839  * that uses the interface. This is specified through flags,
8840  * which can be a combination of:
8841  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8842  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8843  *   and flags. Additionally, the packet source address has to be set to
8844  *   the specified address. The caller is thus expected to set this flag
8845  *   if the packet has no specific source address yet.
8846  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8847  *   flag, the resulting ire will inherit the flag. All unresolved routes
8848  *   to the destination must be explored in the same call to
8849  *   ip_newroute_ipif().
8850  */
8851 static void
8852 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8853     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8854 {
8855 	areq_t	*areq;
8856 	ire_t	*ire = NULL;
8857 	mblk_t	*res_mp;
8858 	ipaddr_t *addrp;
8859 	mblk_t *first_mp;
8860 	ire_t	*save_ire = NULL;
8861 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8862 	ipif_t	*src_ipif = NULL;
8863 	ushort_t ire_marks = 0;
8864 	ill_t	*dst_ill = NULL;
8865 	boolean_t mctl_present;
8866 	ipsec_out_t *io;
8867 	ipha_t *ipha;
8868 	int	ihandle = 0;
8869 	mblk_t	*saved_mp;
8870 	ire_t   *fire = NULL;
8871 	mblk_t  *copy_mp = NULL;
8872 	boolean_t multirt_resolve_next;
8873 	ipaddr_t ipha_dst;
8874 
8875 	/*
8876 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8877 	 * here for uniformity
8878 	 */
8879 	ipif_refhold(ipif);
8880 
8881 	/*
8882 	 * This loop is run only once in most cases.
8883 	 * We loop to resolve further routes only when the destination
8884 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8885 	 */
8886 	do {
8887 		if (dst_ill != NULL) {
8888 			ill_refrele(dst_ill);
8889 			dst_ill = NULL;
8890 		}
8891 		if (src_ipif != NULL) {
8892 			ipif_refrele(src_ipif);
8893 			src_ipif = NULL;
8894 		}
8895 		multirt_resolve_next = B_FALSE;
8896 
8897 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8898 		    ipif->ipif_ill->ill_name));
8899 
8900 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8901 		if (mctl_present)
8902 			io = (ipsec_out_t *)first_mp->b_rptr;
8903 
8904 		ipha = (ipha_t *)mp->b_rptr;
8905 
8906 		/*
8907 		 * Save the packet destination address, we may need it after
8908 		 * the packet has been consumed.
8909 		 */
8910 		ipha_dst = ipha->ipha_dst;
8911 
8912 		/*
8913 		 * If the interface is a pt-pt interface we look for an
8914 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8915 		 * local_address and the pt-pt destination address. Otherwise
8916 		 * we just match the local address.
8917 		 * NOTE: dst could be different than ipha->ipha_dst in case
8918 		 * of sending igmp multicast packets over a point-to-point
8919 		 * connection.
8920 		 * Thus we must be careful enough to check ipha_dst to be a
8921 		 * multicast address, otherwise it will take xmit_if path for
8922 		 * multicast packets resulting into kernel stack overflow by
8923 		 * repeated calls to ip_newroute_ipif from ire_send().
8924 		 */
8925 		if (CLASSD(ipha_dst) &&
8926 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8927 			goto err_ret;
8928 		}
8929 
8930 		/*
8931 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8932 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8933 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8934 		 * propagate its flags to the new ire.
8935 		 */
8936 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8937 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8938 			ip2dbg(("ip_newroute_ipif: "
8939 			    "ipif_lookup_multi_ire("
8940 			    "ipif %p, dst %08x) = fire %p\n",
8941 			    (void *)ipif, ntohl(dst), (void *)fire));
8942 		}
8943 
8944 		if (mctl_present && io->ipsec_out_attach_if) {
8945 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8946 			    io->ipsec_out_ill_index, B_FALSE);
8947 
8948 			/* Failure case frees things for us. */
8949 			if (attach_ill == NULL) {
8950 				ipif_refrele(ipif);
8951 				if (fire != NULL)
8952 					ire_refrele(fire);
8953 				return;
8954 			}
8955 
8956 			/*
8957 			 * Check if we need an ire that will not be
8958 			 * looked up by anybody else i.e. HIDDEN.
8959 			 */
8960 			if (ill_is_probeonly(attach_ill)) {
8961 				ire_marks = IRE_MARK_HIDDEN;
8962 			}
8963 			/*
8964 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8965 			 * case.
8966 			 */
8967 			dst_ill = ipif->ipif_ill;
8968 			/* attach_ill has been refheld by ip_grab_attach_ill */
8969 			ASSERT(dst_ill == attach_ill);
8970 		} else {
8971 			/*
8972 			 * If this is set by IP_XMIT_IF, then make sure that
8973 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8974 			 * specified ill.
8975 			 */
8976 			ASSERT((connp == NULL) ||
8977 			    (connp->conn_xmit_if_ill == NULL) ||
8978 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8979 			/*
8980 			 * If the interface belongs to an interface group,
8981 			 * make sure the next possible interface in the group
8982 			 * is used.  This encourages load spreading among
8983 			 * peers in an interface group.
8984 			 * Note: load spreading is disabled for RTF_MULTIRT
8985 			 * routes.
8986 			 */
8987 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8988 			    (fire->ire_flags & RTF_MULTIRT)) {
8989 				/*
8990 				 * Don't perform outbound load spreading
8991 				 * in the case of an RTF_MULTIRT issued route,
8992 				 * we actually typically want to replicate
8993 				 * outgoing packets through particular
8994 				 * interfaces.
8995 				 */
8996 				dst_ill = ipif->ipif_ill;
8997 				ill_refhold(dst_ill);
8998 			} else {
8999 				dst_ill = ip_newroute_get_dst_ill(
9000 				    ipif->ipif_ill);
9001 			}
9002 			if (dst_ill == NULL) {
9003 				if (ip_debug > 2) {
9004 					pr_addr_dbg("ip_newroute_ipif: "
9005 					    "no dst ill for dst %s\n",
9006 					    AF_INET, &dst);
9007 				}
9008 				goto err_ret;
9009 			}
9010 		}
9011 
9012 		/*
9013 		 * Pick a source address preferring non-deprecated ones.
9014 		 * Unlike ip_newroute, we don't do any source address
9015 		 * selection here since for multicast it really does not help
9016 		 * in inbound load spreading as in the unicast case.
9017 		 */
9018 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9019 		    (fire->ire_flags & RTF_SETSRC)) {
9020 			/*
9021 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9022 			 * on that interface. This ire has RTF_SETSRC flag, so
9023 			 * the source address of the packet must be changed.
9024 			 * Check that the ipif matching the requested source
9025 			 * address still exists.
9026 			 */
9027 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9028 			    zoneid, NULL, NULL, NULL, NULL);
9029 		}
9030 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9031 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9032 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9033 		    (src_ipif == NULL)) {
9034 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9035 			if (src_ipif == NULL) {
9036 				if (ip_debug > 2) {
9037 					/* ip1dbg */
9038 					pr_addr_dbg("ip_newroute_ipif: "
9039 					    "no src for dst %s",
9040 					    AF_INET, &dst);
9041 				}
9042 				ip1dbg((" through interface %s\n",
9043 				    dst_ill->ill_name));
9044 				goto err_ret;
9045 			}
9046 			ipif_refrele(ipif);
9047 			ipif = src_ipif;
9048 			ipif_refhold(ipif);
9049 		}
9050 		if (src_ipif == NULL) {
9051 			src_ipif = ipif;
9052 			ipif_refhold(src_ipif);
9053 		}
9054 
9055 		/*
9056 		 * Assign a source address while we have the conn.
9057 		 * We can't have ip_wput_ire pick a source address when the
9058 		 * packet returns from arp since conn_unspec_src might be set
9059 		 * and we loose the conn when going through arp.
9060 		 */
9061 		if (ipha->ipha_src == INADDR_ANY &&
9062 		    (connp == NULL || !connp->conn_unspec_src)) {
9063 			ipha->ipha_src = src_ipif->ipif_src_addr;
9064 		}
9065 
9066 		/*
9067 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9068 		 * interface does not have an interface ire.
9069 		 * Example: Thousands of mobileip PPP interfaces to mobile
9070 		 * nodes. We don't want to create interface ires because
9071 		 * packets from other mobile nodes must not take the route
9072 		 * via interface ires to the visiting mobile node without
9073 		 * going through the home agent, in absence of mobileip
9074 		 * route optimization.
9075 		 */
9076 		if (CLASSD(ipha_dst) && (connp == NULL ||
9077 		    connp->conn_xmit_if_ill == NULL)) {
9078 			/* ipif_to_ire returns an held ire */
9079 			ire = ipif_to_ire(ipif);
9080 			if (ire == NULL)
9081 				goto err_ret;
9082 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9083 				goto err_ret;
9084 			/*
9085 			 * ihandle is needed when the ire is added to
9086 			 * cache table.
9087 			 */
9088 			save_ire = ire;
9089 			ihandle = save_ire->ire_ihandle;
9090 
9091 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9092 			    "flags %04x\n",
9093 			    (void *)ire, (void *)ipif, flags));
9094 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9095 			    (fire->ire_flags & RTF_MULTIRT)) {
9096 				/*
9097 				 * As requested by flags, an IRE_OFFSUBNET was
9098 				 * looked up on that interface. This ire has
9099 				 * RTF_MULTIRT flag, so the resolution loop will
9100 				 * be re-entered to resolve additional routes on
9101 				 * other interfaces. For that purpose, a copy of
9102 				 * the packet is performed at this point.
9103 				 */
9104 				fire->ire_last_used_time = lbolt;
9105 				copy_mp = copymsg(first_mp);
9106 				if (copy_mp) {
9107 					MULTIRT_DEBUG_TAG(copy_mp);
9108 				}
9109 			}
9110 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9111 			    (fire->ire_flags & RTF_SETSRC)) {
9112 				/*
9113 				 * As requested by flags, an IRE_OFFSUBET was
9114 				 * looked up on that interface. This ire has
9115 				 * RTF_SETSRC flag, so the source address of the
9116 				 * packet must be changed.
9117 				 */
9118 				ipha->ipha_src = fire->ire_src_addr;
9119 			}
9120 		} else {
9121 			ASSERT((connp == NULL) ||
9122 			    (connp->conn_xmit_if_ill != NULL) ||
9123 			    (connp->conn_dontroute));
9124 			/*
9125 			 * The only ways we can come here are:
9126 			 * 1) IP_XMIT_IF socket option is set
9127 			 * 2) ICMP error message generated from
9128 			 *    ip_mrtun_forward() routine and it needs
9129 			 *    to go through the specified ill.
9130 			 * 3) SO_DONTROUTE socket option is set
9131 			 * In all cases, the new ire will not be added
9132 			 * into cache table.
9133 			 */
9134 			ire_marks |= IRE_MARK_NOADD;
9135 		}
9136 
9137 		switch (ipif->ipif_net_type) {
9138 		case IRE_IF_NORESOLVER: {
9139 			/* We have what we need to build an IRE_CACHE. */
9140 			mblk_t	*res_mp;
9141 
9142 			/*
9143 			 * Create a new res_mp with the
9144 			 * IP gateway address as destination address in the
9145 			 * DLPI hdr if the physical length is exactly 4 bytes.
9146 			 */
9147 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9148 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9149 				    dst_ill->ill_phys_addr_length,
9150 				    dst_ill->ill_sap,
9151 				    dst_ill->ill_sap_length);
9152 			} else {
9153 				/* use the value set in ip_ll_subnet_defaults */
9154 				res_mp = ill_dlur_gen(NULL,
9155 				    dst_ill->ill_phys_addr_length,
9156 				    dst_ill->ill_sap,
9157 				    dst_ill->ill_sap_length);
9158 			}
9159 
9160 			if (res_mp == NULL)
9161 				break;
9162 			/*
9163 			 * The new ire inherits the IRE_OFFSUBNET flags
9164 			 * and source address, if this was requested.
9165 			 */
9166 			ire = ire_create(
9167 			    (uchar_t *)&dst,		/* dest address */
9168 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9169 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9170 			    NULL,			/* gateway address */
9171 			    NULL,
9172 			    &ipif->ipif_mtu,
9173 			    NULL,			/* Fast Path header */
9174 			    dst_ill->ill_rq,		/* recv-from queue */
9175 			    dst_ill->ill_wq,		/* send-to queue */
9176 			    IRE_CACHE,
9177 			    res_mp,
9178 			    src_ipif,
9179 			    NULL,
9180 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9181 			    (fire != NULL) ?		/* Parent handle */
9182 				fire->ire_phandle : 0,
9183 			    ihandle,			/* Interface handle */
9184 			    (fire != NULL) ?
9185 				(fire->ire_flags &
9186 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9187 			    (save_ire == NULL ? &ire_uinfo_null :
9188 				&save_ire->ire_uinfo),
9189 			    NULL,
9190 			    NULL);
9191 
9192 			freeb(res_mp);
9193 
9194 			if (ire == NULL) {
9195 				if (save_ire != NULL)
9196 					ire_refrele(save_ire);
9197 				break;
9198 			}
9199 
9200 			ire->ire_marks |= ire_marks;
9201 
9202 			/*
9203 			 * If IRE_MARK_NOADD is set then we need to convert
9204 			 * the max_fragp to a useable value now. This is
9205 			 * normally done in ire_add_v[46]. We also need to
9206 			 * associate the ire with an nce (normally would be
9207 			 * done in ip_wput_nondata()).
9208 			 *
9209 			 * Note that IRE_MARK_NOADD packets created here
9210 			 * do not have a non-null ire_mp pointer. The null
9211 			 * value of ire_bucket indicates that they were
9212 			 * never added.
9213 			 */
9214 			if (ire->ire_marks & IRE_MARK_NOADD) {
9215 				uint_t  max_frag;
9216 
9217 				max_frag = *ire->ire_max_fragp;
9218 				ire->ire_max_fragp = NULL;
9219 				ire->ire_max_frag = max_frag;
9220 
9221 				if ((ire->ire_nce = ndp_lookup_v4(
9222 				    ire_to_ill(ire),
9223 				    (ire->ire_gateway_addr != INADDR_ANY ?
9224 				    &ire->ire_gateway_addr : &ire->ire_addr),
9225 				    B_FALSE)) == NULL) {
9226 					if (save_ire != NULL)
9227 						ire_refrele(save_ire);
9228 					break;
9229 				}
9230 				ASSERT(ire->ire_nce->nce_state ==
9231 				    ND_REACHABLE);
9232 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9233 			}
9234 
9235 			/* Prevent save_ire from getting deleted */
9236 			if (save_ire != NULL) {
9237 				IRB_REFHOLD(save_ire->ire_bucket);
9238 				/* Has it been removed already ? */
9239 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9240 					IRB_REFRELE(save_ire->ire_bucket);
9241 					ire_refrele(save_ire);
9242 					break;
9243 				}
9244 			}
9245 
9246 			ire_add_then_send(q, ire, first_mp);
9247 
9248 			/* Assert that save_ire is not deleted yet. */
9249 			if (save_ire != NULL) {
9250 				ASSERT(save_ire->ire_ptpn != NULL);
9251 				IRB_REFRELE(save_ire->ire_bucket);
9252 				ire_refrele(save_ire);
9253 				save_ire = NULL;
9254 			}
9255 			if (fire != NULL) {
9256 				ire_refrele(fire);
9257 				fire = NULL;
9258 			}
9259 
9260 			/*
9261 			 * the resolution loop is re-entered if this
9262 			 * was requested through flags and if we
9263 			 * actually are in a multirouting case.
9264 			 */
9265 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9266 				boolean_t need_resolve =
9267 				    ire_multirt_need_resolve(ipha_dst,
9268 					MBLK_GETLABEL(copy_mp));
9269 				if (!need_resolve) {
9270 					MULTIRT_DEBUG_UNTAG(copy_mp);
9271 					freemsg(copy_mp);
9272 					copy_mp = NULL;
9273 				} else {
9274 					/*
9275 					 * ipif_lookup_group() calls
9276 					 * ire_lookup_multi() that uses
9277 					 * ire_ftable_lookup() to find
9278 					 * an IRE_INTERFACE for the group.
9279 					 * In the multirt case,
9280 					 * ire_lookup_multi() then invokes
9281 					 * ire_multirt_lookup() to find
9282 					 * the next resolvable ire.
9283 					 * As a result, we obtain an new
9284 					 * interface, derived from the
9285 					 * next ire.
9286 					 */
9287 					ipif_refrele(ipif);
9288 					ipif = ipif_lookup_group(ipha_dst,
9289 					    zoneid);
9290 					ip2dbg(("ip_newroute_ipif: "
9291 					    "multirt dst %08x, ipif %p\n",
9292 					    htonl(dst), (void *)ipif));
9293 					if (ipif != NULL) {
9294 						mp = copy_mp;
9295 						copy_mp = NULL;
9296 						multirt_resolve_next = B_TRUE;
9297 						continue;
9298 					} else {
9299 						freemsg(copy_mp);
9300 					}
9301 				}
9302 			}
9303 			if (ipif != NULL)
9304 				ipif_refrele(ipif);
9305 			ill_refrele(dst_ill);
9306 			ipif_refrele(src_ipif);
9307 			return;
9308 		}
9309 		case IRE_IF_RESOLVER:
9310 			/*
9311 			 * We can't build an IRE_CACHE yet, but at least
9312 			 * we found a resolver that can help.
9313 			 */
9314 			res_mp = dst_ill->ill_resolver_mp;
9315 			if (!OK_RESOLVER_MP(res_mp))
9316 				break;
9317 
9318 			/*
9319 			 * We obtain a partial IRE_CACHE which we will pass
9320 			 * along with the resolver query.  When the response
9321 			 * comes back it will be there ready for us to add.
9322 			 * The new ire inherits the IRE_OFFSUBNET flags
9323 			 * and source address, if this was requested.
9324 			 * The ire_max_frag is atomically set under the
9325 			 * irebucket lock in ire_add_v[46]. Only in the
9326 			 * case of IRE_MARK_NOADD, we set it here itself.
9327 			 */
9328 			ire = ire_create_mp(
9329 			    (uchar_t *)&dst,		/* dest address */
9330 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9331 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9332 			    NULL,			/* gateway address */
9333 			    NULL,			/* no in_src_addr */
9334 			    (ire_marks & IRE_MARK_NOADD) ?
9335 				ipif->ipif_mtu : 0,	/* max_frag */
9336 			    NULL,			/* Fast path header */
9337 			    dst_ill->ill_rq,		/* recv-from queue */
9338 			    dst_ill->ill_wq,		/* send-to queue */
9339 			    IRE_CACHE,
9340 			    NULL,	/* let ire_nce_init figure res_mp out */
9341 			    src_ipif,
9342 			    NULL,
9343 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9344 			    (fire != NULL) ?		/* Parent handle */
9345 				fire->ire_phandle : 0,
9346 			    ihandle,			/* Interface handle */
9347 			    (fire != NULL) ?		/* flags if any */
9348 				(fire->ire_flags &
9349 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9350 			    (save_ire == NULL ? &ire_uinfo_null :
9351 				&save_ire->ire_uinfo),
9352 			    NULL,
9353 			    NULL);
9354 
9355 			if (save_ire != NULL) {
9356 				ire_refrele(save_ire);
9357 				save_ire = NULL;
9358 			}
9359 			if (ire == NULL)
9360 				break;
9361 
9362 			ire->ire_marks |= ire_marks;
9363 			/*
9364 			 * Construct message chain for the resolver of the
9365 			 * form:
9366 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9367 			 *
9368 			 * NOTE : ire will be added later when the response
9369 			 * comes back from ARP. If the response does not
9370 			 * come back, ARP frees the packet. For this reason,
9371 			 * we can't REFHOLD the bucket of save_ire to prevent
9372 			 * deletions. We may not be able to REFRELE the
9373 			 * bucket if the response never comes back.
9374 			 * Thus, before adding the ire, ire_add_v4 will make
9375 			 * sure that the interface route does not get deleted.
9376 			 * This is the only case unlike ip_newroute_v6,
9377 			 * ip_newroute_ipif_v6 where we can always prevent
9378 			 * deletions because ire_add_then_send is called after
9379 			 * creating the IRE.
9380 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9381 			 * does not add this IRE into the IRE CACHE.
9382 			 */
9383 			ASSERT(ire->ire_mp != NULL);
9384 			ire->ire_mp->b_cont = first_mp;
9385 			/* Have saved_mp handy, for cleanup if canput fails */
9386 			saved_mp = mp;
9387 			mp = copyb(res_mp);
9388 			if (mp == NULL) {
9389 				/* Prepare for cleanup */
9390 				mp = saved_mp; /* pkt */
9391 				ire_delete(ire); /* ire_mp */
9392 				ire = NULL;
9393 				if (copy_mp != NULL) {
9394 					MULTIRT_DEBUG_UNTAG(copy_mp);
9395 					freemsg(copy_mp);
9396 					copy_mp = NULL;
9397 				}
9398 				break;
9399 			}
9400 			linkb(mp, ire->ire_mp);
9401 
9402 			/*
9403 			 * Fill in the source and dest addrs for the resolver.
9404 			 * NOTE: this depends on memory layouts imposed by
9405 			 * ill_init().
9406 			 */
9407 			areq = (areq_t *)mp->b_rptr;
9408 			addrp = (ipaddr_t *)((char *)areq +
9409 			    areq->areq_sender_addr_offset);
9410 			*addrp = ire->ire_src_addr;
9411 			addrp = (ipaddr_t *)((char *)areq +
9412 			    areq->areq_target_addr_offset);
9413 			*addrp = dst;
9414 			/* Up to the resolver. */
9415 			if (canputnext(dst_ill->ill_rq) &&
9416 			    !(dst_ill->ill_arp_closing)) {
9417 				putnext(dst_ill->ill_rq, mp);
9418 				/*
9419 				 * The response will come back in ip_wput
9420 				 * with db_type IRE_DB_TYPE.
9421 				 */
9422 			} else {
9423 				mp->b_cont = NULL;
9424 				freeb(mp); /* areq */
9425 				ire_delete(ire); /* ire_mp */
9426 				saved_mp->b_next = NULL;
9427 				saved_mp->b_prev = NULL;
9428 				freemsg(first_mp); /* pkt */
9429 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9430 			}
9431 
9432 			if (fire != NULL) {
9433 				ire_refrele(fire);
9434 				fire = NULL;
9435 			}
9436 
9437 
9438 			/*
9439 			 * The resolution loop is re-entered if this was
9440 			 * requested through flags and we actually are
9441 			 * in a multirouting case.
9442 			 */
9443 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9444 				boolean_t need_resolve =
9445 				    ire_multirt_need_resolve(ipha_dst,
9446 					MBLK_GETLABEL(copy_mp));
9447 				if (!need_resolve) {
9448 					MULTIRT_DEBUG_UNTAG(copy_mp);
9449 					freemsg(copy_mp);
9450 					copy_mp = NULL;
9451 				} else {
9452 					/*
9453 					 * ipif_lookup_group() calls
9454 					 * ire_lookup_multi() that uses
9455 					 * ire_ftable_lookup() to find
9456 					 * an IRE_INTERFACE for the group.
9457 					 * In the multirt case,
9458 					 * ire_lookup_multi() then invokes
9459 					 * ire_multirt_lookup() to find
9460 					 * the next resolvable ire.
9461 					 * As a result, we obtain an new
9462 					 * interface, derived from the
9463 					 * next ire.
9464 					 */
9465 					ipif_refrele(ipif);
9466 					ipif = ipif_lookup_group(ipha_dst,
9467 					    zoneid);
9468 					if (ipif != NULL) {
9469 						mp = copy_mp;
9470 						copy_mp = NULL;
9471 						multirt_resolve_next = B_TRUE;
9472 						continue;
9473 					} else {
9474 						freemsg(copy_mp);
9475 					}
9476 				}
9477 			}
9478 			if (ipif != NULL)
9479 				ipif_refrele(ipif);
9480 			ill_refrele(dst_ill);
9481 			ipif_refrele(src_ipif);
9482 			return;
9483 		default:
9484 			break;
9485 		}
9486 	} while (multirt_resolve_next);
9487 
9488 err_ret:
9489 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9490 	if (fire != NULL)
9491 		ire_refrele(fire);
9492 	ipif_refrele(ipif);
9493 	/* Did this packet originate externally? */
9494 	if (dst_ill != NULL)
9495 		ill_refrele(dst_ill);
9496 	if (src_ipif != NULL)
9497 		ipif_refrele(src_ipif);
9498 	if (mp->b_prev || mp->b_next) {
9499 		mp->b_next = NULL;
9500 		mp->b_prev = NULL;
9501 	} else {
9502 		/*
9503 		 * Since ip_wput() isn't close to finished, we fill
9504 		 * in enough of the header for credible error reporting.
9505 		 */
9506 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9507 			/* Failed */
9508 			freemsg(first_mp);
9509 			if (ire != NULL)
9510 				ire_refrele(ire);
9511 			return;
9512 		}
9513 	}
9514 	/*
9515 	 * At this point we will have ire only if RTF_BLACKHOLE
9516 	 * or RTF_REJECT flags are set on the IRE. It will not
9517 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9518 	 */
9519 	if (ire != NULL) {
9520 		if (ire->ire_flags & RTF_BLACKHOLE) {
9521 			ire_refrele(ire);
9522 			freemsg(first_mp);
9523 			return;
9524 		}
9525 		ire_refrele(ire);
9526 	}
9527 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9528 }
9529 
9530 /* Name/Value Table Lookup Routine */
9531 char *
9532 ip_nv_lookup(nv_t *nv, int value)
9533 {
9534 	if (!nv)
9535 		return (NULL);
9536 	for (; nv->nv_name; nv++) {
9537 		if (nv->nv_value == value)
9538 			return (nv->nv_name);
9539 	}
9540 	return ("unknown");
9541 }
9542 
9543 /*
9544  * one day it can be patched to 1 from /etc/system for machines that have few
9545  * fast network interfaces feeding multiple cpus.
9546  */
9547 int ill_stream_putlocks = 0;
9548 
9549 /*
9550  * This is a module open, i.e. this is a control stream for access
9551  * to a DLPI device.  We allocate an ill_t as the instance data in
9552  * this case.
9553  */
9554 int
9555 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9556 {
9557 	uint32_t mem_cnt;
9558 	uint32_t cpu_cnt;
9559 	uint32_t min_cnt;
9560 	pgcnt_t mem_avail;
9561 	ill_t	*ill;
9562 	int	err;
9563 
9564 	/*
9565 	 * Prevent unprivileged processes from pushing IP so that
9566 	 * they can't send raw IP.
9567 	 */
9568 	if (secpolicy_net_rawaccess(credp) != 0)
9569 		return (EPERM);
9570 
9571 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9572 	q->q_ptr = WR(q)->q_ptr = ill;
9573 
9574 	/*
9575 	 * ill_init initializes the ill fields and then sends down
9576 	 * down a DL_INFO_REQ after calling qprocson.
9577 	 */
9578 	err = ill_init(q, ill);
9579 	if (err != 0) {
9580 		mi_free(ill);
9581 		q->q_ptr = NULL;
9582 		WR(q)->q_ptr = NULL;
9583 		return (err);
9584 	}
9585 
9586 	/* ill_init initializes the ipsq marking this thread as writer */
9587 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9588 	/* Wait for the DL_INFO_ACK */
9589 	mutex_enter(&ill->ill_lock);
9590 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9591 		/*
9592 		 * Return value of 0 indicates a pending signal.
9593 		 */
9594 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9595 		if (err == 0) {
9596 			mutex_exit(&ill->ill_lock);
9597 			(void) ip_close(q, 0);
9598 			return (EINTR);
9599 		}
9600 	}
9601 	mutex_exit(&ill->ill_lock);
9602 
9603 	/*
9604 	 * ip_rput_other could have set an error  in ill_error on
9605 	 * receipt of M_ERROR.
9606 	 */
9607 
9608 	err = ill->ill_error;
9609 	if (err != 0) {
9610 		(void) ip_close(q, 0);
9611 		return (err);
9612 	}
9613 
9614 	/*
9615 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9616 	 * size and the cpu speed of the machine. This is upper
9617 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9618 	 * and is lower bounded by the compile time value of
9619 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9620 	 * ip6_ire_max_bucket_cnt.
9621 	 */
9622 	mem_avail = kmem_avail();
9623 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9624 	    ip_cache_table_size / sizeof (ire_t);
9625 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9626 
9627 	min_cnt = MIN(cpu_cnt, mem_cnt);
9628 	if (min_cnt < ip_ire_min_bucket_cnt)
9629 		min_cnt = ip_ire_min_bucket_cnt;
9630 	if (ip_ire_max_bucket_cnt > min_cnt) {
9631 		ip_ire_max_bucket_cnt = min_cnt;
9632 	}
9633 
9634 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9635 	    ip6_cache_table_size / sizeof (ire_t);
9636 	min_cnt = MIN(cpu_cnt, mem_cnt);
9637 	if (min_cnt < ip6_ire_min_bucket_cnt)
9638 		min_cnt = ip6_ire_min_bucket_cnt;
9639 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9640 		ip6_ire_max_bucket_cnt = min_cnt;
9641 	}
9642 
9643 	ill->ill_credp = credp;
9644 	crhold(credp);
9645 
9646 	mutex_enter(&ip_mi_lock);
9647 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9648 	mutex_exit(&ip_mi_lock);
9649 	if (err) {
9650 		(void) ip_close(q, 0);
9651 		return (err);
9652 	}
9653 	return (0);
9654 }
9655 
9656 /* IP open routine. */
9657 int
9658 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9659 {
9660 	conn_t 		*connp;
9661 	major_t		maj;
9662 
9663 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9664 
9665 	/* Allow reopen. */
9666 	if (q->q_ptr != NULL)
9667 		return (0);
9668 
9669 	if (sflag & MODOPEN) {
9670 		/* This is a module open */
9671 		return (ip_modopen(q, devp, flag, sflag, credp));
9672 	}
9673 
9674 	/*
9675 	 * We are opening as a device. This is an IP client stream, and we
9676 	 * allocate an conn_t as the instance data.
9677 	 */
9678 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9679 	connp->conn_upq = q;
9680 	q->q_ptr = WR(q)->q_ptr = connp;
9681 
9682 	if (flag & SO_SOCKSTR)
9683 		connp->conn_flags |= IPCL_SOCKET;
9684 
9685 	/* Minor tells us which /dev entry was opened */
9686 	if (geteminor(*devp) == IPV6_MINOR) {
9687 		connp->conn_flags |= IPCL_ISV6;
9688 		connp->conn_af_isv6 = B_TRUE;
9689 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9690 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9691 	} else {
9692 		connp->conn_af_isv6 = B_FALSE;
9693 		connp->conn_pkt_isv6 = B_FALSE;
9694 	}
9695 
9696 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9697 		q->q_ptr = WR(q)->q_ptr = NULL;
9698 		CONN_DEC_REF(connp);
9699 		return (EBUSY);
9700 	}
9701 
9702 	maj = getemajor(*devp);
9703 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9704 
9705 	/*
9706 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9707 	 */
9708 	connp->conn_cred = credp;
9709 	crhold(connp->conn_cred);
9710 
9711 	/*
9712 	 * If the caller has the process-wide flag set, then default to MAC
9713 	 * exempt mode.  This allows read-down to unlabeled hosts.
9714 	 */
9715 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9716 		connp->conn_mac_exempt = B_TRUE;
9717 
9718 	connp->conn_zoneid = getzoneid();
9719 
9720 	/*
9721 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9722 	 * administrative ops.  In these cases, we just need a normal conn_t
9723 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9724 	 * an error will be returned.
9725 	 */
9726 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9727 		connp->conn_rq = q;
9728 		connp->conn_wq = WR(q);
9729 	} else {
9730 		connp->conn_ulp = IPPROTO_SCTP;
9731 		connp->conn_rq = connp->conn_wq = NULL;
9732 	}
9733 	/* Non-zero default values */
9734 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9735 
9736 	/*
9737 	 * Make the conn globally visible to walkers
9738 	 */
9739 	mutex_enter(&connp->conn_lock);
9740 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9741 	mutex_exit(&connp->conn_lock);
9742 	ASSERT(connp->conn_ref == 1);
9743 
9744 	qprocson(q);
9745 
9746 	return (0);
9747 }
9748 
9749 /*
9750  * Change q_qinfo based on the value of isv6.
9751  * This can not called on an ill queue.
9752  * Note that there is no race since either q_qinfo works for conn queues - it
9753  * is just an optimization to enter the best wput routine directly.
9754  */
9755 void
9756 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9757 {
9758 	ASSERT(q->q_flag & QREADR);
9759 	ASSERT(WR(q)->q_next == NULL);
9760 	ASSERT(q->q_ptr != NULL);
9761 
9762 	if (minor == IPV6_MINOR)  {
9763 		if (bump_mib)
9764 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9765 		q->q_qinfo = &rinit_ipv6;
9766 		WR(q)->q_qinfo = &winit_ipv6;
9767 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9768 	} else {
9769 		if (bump_mib)
9770 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9771 		q->q_qinfo = &iprinit;
9772 		WR(q)->q_qinfo = &ipwinit;
9773 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9774 	}
9775 
9776 }
9777 
9778 /*
9779  * See if IPsec needs loading because of the options in mp.
9780  */
9781 static boolean_t
9782 ipsec_opt_present(mblk_t *mp)
9783 {
9784 	uint8_t *optcp, *next_optcp, *opt_endcp;
9785 	struct opthdr *opt;
9786 	struct T_opthdr *topt;
9787 	int opthdr_len;
9788 	t_uscalar_t optname, optlevel;
9789 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9790 	ipsec_req_t *ipsr;
9791 
9792 	/*
9793 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9794 	 * return TRUE.
9795 	 */
9796 
9797 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9798 	opt_endcp = optcp + tor->OPT_length;
9799 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9800 		opthdr_len = sizeof (struct T_opthdr);
9801 	} else {		/* O_OPTMGMT_REQ */
9802 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9803 		opthdr_len = sizeof (struct opthdr);
9804 	}
9805 	for (; optcp < opt_endcp; optcp = next_optcp) {
9806 		if (optcp + opthdr_len > opt_endcp)
9807 			return (B_FALSE);	/* Not enough option header. */
9808 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9809 			topt = (struct T_opthdr *)optcp;
9810 			optlevel = topt->level;
9811 			optname = topt->name;
9812 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9813 		} else {
9814 			opt = (struct opthdr *)optcp;
9815 			optlevel = opt->level;
9816 			optname = opt->name;
9817 			next_optcp = optcp + opthdr_len +
9818 			    _TPI_ALIGN_OPT(opt->len);
9819 		}
9820 		if ((next_optcp < optcp) || /* wraparound pointer space */
9821 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9822 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9823 			return (B_FALSE); /* bad option buffer */
9824 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9825 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9826 			/*
9827 			 * Check to see if it's an all-bypass or all-zeroes
9828 			 * IPsec request.  Don't bother loading IPsec if
9829 			 * the socket doesn't want to use it.  (A good example
9830 			 * is a bypass request.)
9831 			 *
9832 			 * Basically, if any of the non-NEVER bits are set,
9833 			 * load IPsec.
9834 			 */
9835 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9836 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9837 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9838 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9839 			    != 0)
9840 				return (B_TRUE);
9841 		}
9842 	}
9843 	return (B_FALSE);
9844 }
9845 
9846 /*
9847  * If conn is is waiting for ipsec to finish loading, kick it.
9848  */
9849 /* ARGSUSED */
9850 static void
9851 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9852 {
9853 	t_scalar_t	optreq_prim;
9854 	mblk_t		*mp;
9855 	cred_t		*cr;
9856 	int		err = 0;
9857 
9858 	/*
9859 	 * This function is called, after ipsec loading is complete.
9860 	 * Since IP checks exclusively and atomically (i.e it prevents
9861 	 * ipsec load from completing until ip_optcom_req completes)
9862 	 * whether ipsec load is complete, there cannot be a race with IP
9863 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9864 	 */
9865 	mutex_enter(&connp->conn_lock);
9866 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9867 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9868 		mp = connp->conn_ipsec_opt_mp;
9869 		connp->conn_ipsec_opt_mp = NULL;
9870 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9871 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9872 		mutex_exit(&connp->conn_lock);
9873 
9874 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9875 
9876 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9877 		if (optreq_prim == T_OPTMGMT_REQ) {
9878 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9879 			    &ip_opt_obj);
9880 		} else {
9881 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9882 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9883 			    &ip_opt_obj);
9884 		}
9885 		if (err != EINPROGRESS)
9886 			CONN_OPER_PENDING_DONE(connp);
9887 		return;
9888 	}
9889 	mutex_exit(&connp->conn_lock);
9890 }
9891 
9892 /*
9893  * Called from the ipsec_loader thread, outside any perimeter, to tell
9894  * ip qenable any of the queues waiting for the ipsec loader to
9895  * complete.
9896  *
9897  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9898  * are done with this lock held, so it's guaranteed that none of the
9899  * links will change along the way.
9900  */
9901 void
9902 ip_ipsec_load_complete()
9903 {
9904 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9905 }
9906 
9907 /*
9908  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9909  * determines the grp on which it has to become exclusive, queues the mp
9910  * and sq draining restarts the optmgmt
9911  */
9912 static boolean_t
9913 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9914 {
9915 	conn_t *connp;
9916 
9917 	/*
9918 	 * Take IPsec requests and treat them special.
9919 	 */
9920 	if (ipsec_opt_present(mp)) {
9921 		/* First check if IPsec is loaded. */
9922 		mutex_enter(&ipsec_loader_lock);
9923 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9924 			mutex_exit(&ipsec_loader_lock);
9925 			return (B_FALSE);
9926 		}
9927 		connp = Q_TO_CONN(q);
9928 		mutex_enter(&connp->conn_lock);
9929 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9930 
9931 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9932 		connp->conn_ipsec_opt_mp = mp;
9933 		mutex_exit(&connp->conn_lock);
9934 		mutex_exit(&ipsec_loader_lock);
9935 
9936 		ipsec_loader_loadnow();
9937 		return (B_TRUE);
9938 	}
9939 	return (B_FALSE);
9940 }
9941 
9942 /*
9943  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9944  * all of them are copied to the conn_t. If the req is "zero", the policy is
9945  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9946  * fields.
9947  * We keep only the latest setting of the policy and thus policy setting
9948  * is not incremental/cumulative.
9949  *
9950  * Requests to set policies with multiple alternative actions will
9951  * go through a different API.
9952  */
9953 int
9954 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9955 {
9956 	uint_t ah_req = 0;
9957 	uint_t esp_req = 0;
9958 	uint_t se_req = 0;
9959 	ipsec_selkey_t sel;
9960 	ipsec_act_t *actp = NULL;
9961 	uint_t nact;
9962 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9963 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9964 	ipsec_policy_root_t *pr;
9965 	ipsec_policy_head_t *ph;
9966 	int fam;
9967 	boolean_t is_pol_reset;
9968 	int error = 0;
9969 
9970 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9971 
9972 	/*
9973 	 * The IP_SEC_OPT option does not allow variable length parameters,
9974 	 * hence a request cannot be NULL.
9975 	 */
9976 	if (req == NULL)
9977 		return (EINVAL);
9978 
9979 	ah_req = req->ipsr_ah_req;
9980 	esp_req = req->ipsr_esp_req;
9981 	se_req = req->ipsr_self_encap_req;
9982 
9983 	/*
9984 	 * Are we dealing with a request to reset the policy (i.e.
9985 	 * zero requests).
9986 	 */
9987 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9988 	    (esp_req & REQ_MASK) == 0 &&
9989 	    (se_req & REQ_MASK) == 0);
9990 
9991 	if (!is_pol_reset) {
9992 		/*
9993 		 * If we couldn't load IPsec, fail with "protocol
9994 		 * not supported".
9995 		 * IPsec may not have been loaded for a request with zero
9996 		 * policies, so we don't fail in this case.
9997 		 */
9998 		mutex_enter(&ipsec_loader_lock);
9999 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10000 			mutex_exit(&ipsec_loader_lock);
10001 			return (EPROTONOSUPPORT);
10002 		}
10003 		mutex_exit(&ipsec_loader_lock);
10004 
10005 		/*
10006 		 * Test for valid requests. Invalid algorithms
10007 		 * need to be tested by IPSEC code because new
10008 		 * algorithms can be added dynamically.
10009 		 */
10010 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10011 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10012 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10013 			return (EINVAL);
10014 		}
10015 
10016 		/*
10017 		 * Only privileged users can issue these
10018 		 * requests.
10019 		 */
10020 		if (((ah_req & IPSEC_PREF_NEVER) ||
10021 		    (esp_req & IPSEC_PREF_NEVER) ||
10022 		    (se_req & IPSEC_PREF_NEVER)) &&
10023 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10024 			return (EPERM);
10025 		}
10026 
10027 		/*
10028 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10029 		 * are mutually exclusive.
10030 		 */
10031 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10032 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10033 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10034 			/* Both of them are set */
10035 			return (EINVAL);
10036 		}
10037 	}
10038 
10039 	mutex_enter(&connp->conn_lock);
10040 
10041 	/*
10042 	 * If we have already cached policies in ip_bind_connected*(), don't
10043 	 * let them change now. We cache policies for connections
10044 	 * whose src,dst [addr, port] is known.
10045 	 */
10046 	if (connp->conn_policy_cached) {
10047 		mutex_exit(&connp->conn_lock);
10048 		return (EINVAL);
10049 	}
10050 
10051 	/*
10052 	 * We have a zero policies, reset the connection policy if already
10053 	 * set. This will cause the connection to inherit the
10054 	 * global policy, if any.
10055 	 */
10056 	if (is_pol_reset) {
10057 		if (connp->conn_policy != NULL) {
10058 			IPPH_REFRELE(connp->conn_policy);
10059 			connp->conn_policy = NULL;
10060 		}
10061 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10062 		connp->conn_in_enforce_policy = B_FALSE;
10063 		connp->conn_out_enforce_policy = B_FALSE;
10064 		mutex_exit(&connp->conn_lock);
10065 		return (0);
10066 	}
10067 
10068 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10069 	if (ph == NULL)
10070 		goto enomem;
10071 
10072 	ipsec_actvec_from_req(req, &actp, &nact);
10073 	if (actp == NULL)
10074 		goto enomem;
10075 
10076 	/*
10077 	 * Always allocate IPv4 policy entries, since they can also
10078 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10079 	 */
10080 	bzero(&sel, sizeof (sel));
10081 	sel.ipsl_valid = IPSL_IPV4;
10082 
10083 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10084 	if (pin4 == NULL)
10085 		goto enomem;
10086 
10087 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10088 	if (pout4 == NULL)
10089 		goto enomem;
10090 
10091 	if (connp->conn_pkt_isv6) {
10092 		/*
10093 		 * We're looking at a v6 socket, also allocate the
10094 		 * v6-specific entries...
10095 		 */
10096 		sel.ipsl_valid = IPSL_IPV6;
10097 		pin6 = ipsec_policy_create(&sel, actp, nact,
10098 		    IPSEC_PRIO_SOCKET, NULL);
10099 		if (pin6 == NULL)
10100 			goto enomem;
10101 
10102 		pout6 = ipsec_policy_create(&sel, actp, nact,
10103 		    IPSEC_PRIO_SOCKET, NULL);
10104 		if (pout6 == NULL)
10105 			goto enomem;
10106 
10107 		/*
10108 		 * .. and file them away in the right place.
10109 		 */
10110 		fam = IPSEC_AF_V6;
10111 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10112 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10113 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10114 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10115 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10116 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10117 	}
10118 
10119 	ipsec_actvec_free(actp, nact);
10120 
10121 	/*
10122 	 * File the v4 policies.
10123 	 */
10124 	fam = IPSEC_AF_V4;
10125 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10126 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10127 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10128 
10129 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10130 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10131 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10132 
10133 	/*
10134 	 * If the requests need security, set enforce_policy.
10135 	 * If the requests are IPSEC_PREF_NEVER, one should
10136 	 * still set conn_out_enforce_policy so that an ipsec_out
10137 	 * gets attached in ip_wput. This is needed so that
10138 	 * for connections that we don't cache policy in ip_bind,
10139 	 * if global policy matches in ip_wput_attach_policy, we
10140 	 * don't wrongly inherit global policy. Similarly, we need
10141 	 * to set conn_in_enforce_policy also so that we don't verify
10142 	 * policy wrongly.
10143 	 */
10144 	if ((ah_req & REQ_MASK) != 0 ||
10145 	    (esp_req & REQ_MASK) != 0 ||
10146 	    (se_req & REQ_MASK) != 0) {
10147 		connp->conn_in_enforce_policy = B_TRUE;
10148 		connp->conn_out_enforce_policy = B_TRUE;
10149 		connp->conn_flags |= IPCL_CHECK_POLICY;
10150 	}
10151 
10152 	mutex_exit(&connp->conn_lock);
10153 	return (error);
10154 #undef REQ_MASK
10155 
10156 	/*
10157 	 * Common memory-allocation-failure exit path.
10158 	 */
10159 enomem:
10160 	mutex_exit(&connp->conn_lock);
10161 	if (actp != NULL)
10162 		ipsec_actvec_free(actp, nact);
10163 	if (pin4 != NULL)
10164 		IPPOL_REFRELE(pin4);
10165 	if (pout4 != NULL)
10166 		IPPOL_REFRELE(pout4);
10167 	if (pin6 != NULL)
10168 		IPPOL_REFRELE(pin6);
10169 	if (pout6 != NULL)
10170 		IPPOL_REFRELE(pout6);
10171 	return (ENOMEM);
10172 }
10173 
10174 /*
10175  * Only for options that pass in an IP addr. Currently only V4 options
10176  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10177  * So this function assumes level is IPPROTO_IP
10178  */
10179 int
10180 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10181     mblk_t *first_mp)
10182 {
10183 	ipif_t *ipif = NULL;
10184 	int error;
10185 	ill_t *ill;
10186 	int zoneid;
10187 
10188 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10189 
10190 	if (addr != INADDR_ANY || checkonly) {
10191 		ASSERT(connp != NULL);
10192 		zoneid = IPCL_ZONEID(connp);
10193 		if (option == IP_NEXTHOP) {
10194 			ipif = ipif_lookup_onlink_addr(addr,
10195 			    connp->conn_zoneid);
10196 		} else {
10197 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10198 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10199 			    &error);
10200 		}
10201 		if (ipif == NULL) {
10202 			if (error == EINPROGRESS)
10203 				return (error);
10204 			else if ((option == IP_MULTICAST_IF) ||
10205 			    (option == IP_NEXTHOP))
10206 				return (EHOSTUNREACH);
10207 			else
10208 				return (EINVAL);
10209 		} else if (checkonly) {
10210 			if (option == IP_MULTICAST_IF) {
10211 				ill = ipif->ipif_ill;
10212 				/* not supported by the virtual network iface */
10213 				if (IS_VNI(ill)) {
10214 					ipif_refrele(ipif);
10215 					return (EINVAL);
10216 				}
10217 			}
10218 			ipif_refrele(ipif);
10219 			return (0);
10220 		}
10221 		ill = ipif->ipif_ill;
10222 		mutex_enter(&connp->conn_lock);
10223 		mutex_enter(&ill->ill_lock);
10224 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10225 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10226 			mutex_exit(&ill->ill_lock);
10227 			mutex_exit(&connp->conn_lock);
10228 			ipif_refrele(ipif);
10229 			return (option == IP_MULTICAST_IF ?
10230 			    EHOSTUNREACH : EINVAL);
10231 		}
10232 	} else {
10233 		mutex_enter(&connp->conn_lock);
10234 	}
10235 
10236 	/* None of the options below are supported on the VNI */
10237 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10238 		mutex_exit(&ill->ill_lock);
10239 		mutex_exit(&connp->conn_lock);
10240 		ipif_refrele(ipif);
10241 		return (EINVAL);
10242 	}
10243 
10244 	switch (option) {
10245 	case IP_DONTFAILOVER_IF:
10246 		/*
10247 		 * This option is used by in.mpathd to ensure
10248 		 * that IPMP probe packets only go out on the
10249 		 * test interfaces. in.mpathd sets this option
10250 		 * on the non-failover interfaces.
10251 		 * For backward compatibility, this option
10252 		 * implicitly sets IP_MULTICAST_IF, as used
10253 		 * be done in bind(), so that ip_wput gets
10254 		 * this ipif to send mcast packets.
10255 		 */
10256 		if (ipif != NULL) {
10257 			ASSERT(addr != INADDR_ANY);
10258 			connp->conn_nofailover_ill = ipif->ipif_ill;
10259 			connp->conn_multicast_ipif = ipif;
10260 		} else {
10261 			ASSERT(addr == INADDR_ANY);
10262 			connp->conn_nofailover_ill = NULL;
10263 			connp->conn_multicast_ipif = NULL;
10264 		}
10265 		break;
10266 
10267 	case IP_MULTICAST_IF:
10268 		connp->conn_multicast_ipif = ipif;
10269 		break;
10270 	case IP_NEXTHOP:
10271 		connp->conn_nexthop_v4 = addr;
10272 		connp->conn_nexthop_set = B_TRUE;
10273 		break;
10274 	}
10275 
10276 	if (ipif != NULL) {
10277 		mutex_exit(&ill->ill_lock);
10278 		mutex_exit(&connp->conn_lock);
10279 		ipif_refrele(ipif);
10280 		return (0);
10281 	}
10282 	mutex_exit(&connp->conn_lock);
10283 	/* We succeded in cleared the option */
10284 	return (0);
10285 }
10286 
10287 /*
10288  * For options that pass in an ifindex specifying the ill. V6 options always
10289  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10290  */
10291 int
10292 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10293     int level, int option, mblk_t *first_mp)
10294 {
10295 	ill_t *ill = NULL;
10296 	int error = 0;
10297 
10298 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10299 	if (ifindex != 0) {
10300 		ASSERT(connp != NULL);
10301 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10302 		    first_mp, ip_restart_optmgmt, &error);
10303 		if (ill != NULL) {
10304 			if (checkonly) {
10305 				/* not supported by the virtual network iface */
10306 				if (IS_VNI(ill)) {
10307 					ill_refrele(ill);
10308 					return (EINVAL);
10309 				}
10310 				ill_refrele(ill);
10311 				return (0);
10312 			}
10313 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10314 			    0, NULL)) {
10315 				ill_refrele(ill);
10316 				ill = NULL;
10317 				mutex_enter(&connp->conn_lock);
10318 				goto setit;
10319 			}
10320 			mutex_enter(&connp->conn_lock);
10321 			mutex_enter(&ill->ill_lock);
10322 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10323 				mutex_exit(&ill->ill_lock);
10324 				mutex_exit(&connp->conn_lock);
10325 				ill_refrele(ill);
10326 				ill = NULL;
10327 				mutex_enter(&connp->conn_lock);
10328 			}
10329 			goto setit;
10330 		} else if (error == EINPROGRESS) {
10331 			return (error);
10332 		} else {
10333 			error = 0;
10334 		}
10335 	}
10336 	mutex_enter(&connp->conn_lock);
10337 setit:
10338 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10339 
10340 	/*
10341 	 * The options below assume that the ILL (if any) transmits and/or
10342 	 * receives traffic. Neither of which is true for the virtual network
10343 	 * interface, so fail setting these on a VNI.
10344 	 */
10345 	if (IS_VNI(ill)) {
10346 		ASSERT(ill != NULL);
10347 		mutex_exit(&ill->ill_lock);
10348 		mutex_exit(&connp->conn_lock);
10349 		ill_refrele(ill);
10350 		return (EINVAL);
10351 	}
10352 
10353 	if (level == IPPROTO_IP) {
10354 		switch (option) {
10355 		case IP_BOUND_IF:
10356 			connp->conn_incoming_ill = ill;
10357 			connp->conn_outgoing_ill = ill;
10358 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10359 			    0 : ifindex;
10360 			break;
10361 
10362 		case IP_XMIT_IF:
10363 			/*
10364 			 * Similar to IP_BOUND_IF, but this only
10365 			 * determines the outgoing interface for
10366 			 * unicast packets. Also no IRE_CACHE entry
10367 			 * is added for the destination of the
10368 			 * outgoing packets. This feature is needed
10369 			 * for mobile IP.
10370 			 */
10371 			connp->conn_xmit_if_ill = ill;
10372 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10373 			    0 : ifindex;
10374 			break;
10375 
10376 		case IP_MULTICAST_IF:
10377 			/*
10378 			 * This option is an internal special. The socket
10379 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10380 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10381 			 * specifies an ifindex and we try first on V6 ill's.
10382 			 * If we don't find one, we they try using on v4 ill's
10383 			 * intenally and we come here.
10384 			 */
10385 			if (!checkonly && ill != NULL) {
10386 				ipif_t	*ipif;
10387 				ipif = ill->ill_ipif;
10388 
10389 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10390 					mutex_exit(&ill->ill_lock);
10391 					mutex_exit(&connp->conn_lock);
10392 					ill_refrele(ill);
10393 					ill = NULL;
10394 					mutex_enter(&connp->conn_lock);
10395 				} else {
10396 					connp->conn_multicast_ipif = ipif;
10397 				}
10398 			}
10399 			break;
10400 		}
10401 	} else {
10402 		switch (option) {
10403 		case IPV6_BOUND_IF:
10404 			connp->conn_incoming_ill = ill;
10405 			connp->conn_outgoing_ill = ill;
10406 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10407 			    0 : ifindex;
10408 			break;
10409 
10410 		case IPV6_BOUND_PIF:
10411 			/*
10412 			 * Limit all transmit to this ill.
10413 			 * Unlike IPV6_BOUND_IF, using this option
10414 			 * prevents load spreading and failover from
10415 			 * happening when the interface is part of the
10416 			 * group. That's why we don't need to remember
10417 			 * the ifindex in orig_bound_ifindex as in
10418 			 * IPV6_BOUND_IF.
10419 			 */
10420 			connp->conn_outgoing_pill = ill;
10421 			break;
10422 
10423 		case IPV6_DONTFAILOVER_IF:
10424 			/*
10425 			 * This option is used by in.mpathd to ensure
10426 			 * that IPMP probe packets only go out on the
10427 			 * test interfaces. in.mpathd sets this option
10428 			 * on the non-failover interfaces.
10429 			 */
10430 			connp->conn_nofailover_ill = ill;
10431 			/*
10432 			 * For backward compatibility, this option
10433 			 * implicitly sets ip_multicast_ill as used in
10434 			 * IP_MULTICAST_IF so that ip_wput gets
10435 			 * this ipif to send mcast packets.
10436 			 */
10437 			connp->conn_multicast_ill = ill;
10438 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10439 			    0 : ifindex;
10440 			break;
10441 
10442 		case IPV6_MULTICAST_IF:
10443 			/*
10444 			 * Set conn_multicast_ill to be the IPv6 ill.
10445 			 * Set conn_multicast_ipif to be an IPv4 ipif
10446 			 * for ifindex to make IPv4 mapped addresses
10447 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10448 			 * Even if no IPv6 ill exists for the ifindex
10449 			 * we need to check for an IPv4 ifindex in order
10450 			 * for this to work with mapped addresses. In that
10451 			 * case only set conn_multicast_ipif.
10452 			 */
10453 			if (!checkonly) {
10454 				if (ifindex == 0) {
10455 					connp->conn_multicast_ill = NULL;
10456 					connp->conn_orig_multicast_ifindex = 0;
10457 					connp->conn_multicast_ipif = NULL;
10458 				} else if (ill != NULL) {
10459 					connp->conn_multicast_ill = ill;
10460 					connp->conn_orig_multicast_ifindex =
10461 					    ifindex;
10462 				}
10463 			}
10464 			break;
10465 		}
10466 	}
10467 
10468 	if (ill != NULL) {
10469 		mutex_exit(&ill->ill_lock);
10470 		mutex_exit(&connp->conn_lock);
10471 		ill_refrele(ill);
10472 		return (0);
10473 	}
10474 	mutex_exit(&connp->conn_lock);
10475 	/*
10476 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10477 	 * locate the ill and could not set the option (ifindex != 0)
10478 	 */
10479 	return (ifindex == 0 ? 0 : EINVAL);
10480 }
10481 
10482 /* This routine sets socket options. */
10483 /* ARGSUSED */
10484 int
10485 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10486     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10487     void *dummy, cred_t *cr, mblk_t *first_mp)
10488 {
10489 	int		*i1 = (int *)invalp;
10490 	conn_t		*connp = Q_TO_CONN(q);
10491 	int		error = 0;
10492 	boolean_t	checkonly;
10493 	ire_t		*ire;
10494 	boolean_t	found;
10495 
10496 	switch (optset_context) {
10497 
10498 	case SETFN_OPTCOM_CHECKONLY:
10499 		checkonly = B_TRUE;
10500 		/*
10501 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10502 		 * inlen != 0 implies value supplied and
10503 		 * 	we have to "pretend" to set it.
10504 		 * inlen == 0 implies that there is no
10505 		 * 	value part in T_CHECK request and just validation
10506 		 * done elsewhere should be enough, we just return here.
10507 		 */
10508 		if (inlen == 0) {
10509 			*outlenp = 0;
10510 			return (0);
10511 		}
10512 		break;
10513 	case SETFN_OPTCOM_NEGOTIATE:
10514 	case SETFN_UD_NEGOTIATE:
10515 	case SETFN_CONN_NEGOTIATE:
10516 		checkonly = B_FALSE;
10517 		break;
10518 	default:
10519 		/*
10520 		 * We should never get here
10521 		 */
10522 		*outlenp = 0;
10523 		return (EINVAL);
10524 	}
10525 
10526 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10527 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10528 
10529 	/*
10530 	 * For fixed length options, no sanity check
10531 	 * of passed in length is done. It is assumed *_optcom_req()
10532 	 * routines do the right thing.
10533 	 */
10534 
10535 	switch (level) {
10536 	case SOL_SOCKET:
10537 		/*
10538 		 * conn_lock protects the bitfields, and is used to
10539 		 * set the fields atomically.
10540 		 */
10541 		switch (name) {
10542 		case SO_BROADCAST:
10543 			if (!checkonly) {
10544 				/* TODO: use value someplace? */
10545 				mutex_enter(&connp->conn_lock);
10546 				connp->conn_broadcast = *i1 ? 1 : 0;
10547 				mutex_exit(&connp->conn_lock);
10548 			}
10549 			break;	/* goto sizeof (int) option return */
10550 		case SO_USELOOPBACK:
10551 			if (!checkonly) {
10552 				/* TODO: use value someplace? */
10553 				mutex_enter(&connp->conn_lock);
10554 				connp->conn_loopback = *i1 ? 1 : 0;
10555 				mutex_exit(&connp->conn_lock);
10556 			}
10557 			break;	/* goto sizeof (int) option return */
10558 		case SO_DONTROUTE:
10559 			if (!checkonly) {
10560 				mutex_enter(&connp->conn_lock);
10561 				connp->conn_dontroute = *i1 ? 1 : 0;
10562 				mutex_exit(&connp->conn_lock);
10563 			}
10564 			break;	/* goto sizeof (int) option return */
10565 		case SO_REUSEADDR:
10566 			if (!checkonly) {
10567 				mutex_enter(&connp->conn_lock);
10568 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10569 				mutex_exit(&connp->conn_lock);
10570 			}
10571 			break;	/* goto sizeof (int) option return */
10572 		case SO_PROTOTYPE:
10573 			if (!checkonly) {
10574 				mutex_enter(&connp->conn_lock);
10575 				connp->conn_proto = *i1;
10576 				mutex_exit(&connp->conn_lock);
10577 			}
10578 			break;	/* goto sizeof (int) option return */
10579 		case SO_ALLZONES:
10580 			if (!checkonly) {
10581 				mutex_enter(&connp->conn_lock);
10582 				if (IPCL_IS_BOUND(connp)) {
10583 					mutex_exit(&connp->conn_lock);
10584 					return (EINVAL);
10585 				}
10586 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10587 				mutex_exit(&connp->conn_lock);
10588 			}
10589 			break;	/* goto sizeof (int) option return */
10590 		case SO_ANON_MLP:
10591 			if (!checkonly) {
10592 				mutex_enter(&connp->conn_lock);
10593 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10594 				mutex_exit(&connp->conn_lock);
10595 			}
10596 			break;	/* goto sizeof (int) option return */
10597 		case SO_MAC_EXEMPT:
10598 			if (secpolicy_net_mac_aware(cr) != 0 ||
10599 			    IPCL_IS_BOUND(connp))
10600 				return (EACCES);
10601 			if (!checkonly) {
10602 				mutex_enter(&connp->conn_lock);
10603 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10604 				mutex_exit(&connp->conn_lock);
10605 			}
10606 			break;	/* goto sizeof (int) option return */
10607 		default:
10608 			/*
10609 			 * "soft" error (negative)
10610 			 * option not handled at this level
10611 			 * Note: Do not modify *outlenp
10612 			 */
10613 			return (-EINVAL);
10614 		}
10615 		break;
10616 	case IPPROTO_IP:
10617 		switch (name) {
10618 		case IP_NEXTHOP:
10619 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10620 				return (EPERM);
10621 			/* FALLTHRU */
10622 		case IP_MULTICAST_IF:
10623 		case IP_DONTFAILOVER_IF: {
10624 			ipaddr_t addr = *i1;
10625 
10626 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10627 			    first_mp);
10628 			if (error != 0)
10629 				return (error);
10630 			break;	/* goto sizeof (int) option return */
10631 		}
10632 
10633 		case IP_MULTICAST_TTL:
10634 			/* Recorded in transport above IP */
10635 			*outvalp = *invalp;
10636 			*outlenp = sizeof (uchar_t);
10637 			return (0);
10638 		case IP_MULTICAST_LOOP:
10639 			if (!checkonly) {
10640 				mutex_enter(&connp->conn_lock);
10641 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10642 				mutex_exit(&connp->conn_lock);
10643 			}
10644 			*outvalp = *invalp;
10645 			*outlenp = sizeof (uchar_t);
10646 			return (0);
10647 		case IP_ADD_MEMBERSHIP:
10648 		case MCAST_JOIN_GROUP:
10649 		case IP_DROP_MEMBERSHIP:
10650 		case MCAST_LEAVE_GROUP: {
10651 			struct ip_mreq *mreqp;
10652 			struct group_req *greqp;
10653 			ire_t *ire;
10654 			boolean_t done = B_FALSE;
10655 			ipaddr_t group, ifaddr;
10656 			struct sockaddr_in *sin;
10657 			uint32_t *ifindexp;
10658 			boolean_t mcast_opt = B_TRUE;
10659 			mcast_record_t fmode;
10660 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10661 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10662 
10663 			switch (name) {
10664 			case IP_ADD_MEMBERSHIP:
10665 				mcast_opt = B_FALSE;
10666 				/* FALLTHRU */
10667 			case MCAST_JOIN_GROUP:
10668 				fmode = MODE_IS_EXCLUDE;
10669 				optfn = ip_opt_add_group;
10670 				break;
10671 
10672 			case IP_DROP_MEMBERSHIP:
10673 				mcast_opt = B_FALSE;
10674 				/* FALLTHRU */
10675 			case MCAST_LEAVE_GROUP:
10676 				fmode = MODE_IS_INCLUDE;
10677 				optfn = ip_opt_delete_group;
10678 				break;
10679 			}
10680 
10681 			if (mcast_opt) {
10682 				greqp = (struct group_req *)i1;
10683 				sin = (struct sockaddr_in *)&greqp->gr_group;
10684 				if (sin->sin_family != AF_INET) {
10685 					*outlenp = 0;
10686 					return (ENOPROTOOPT);
10687 				}
10688 				group = (ipaddr_t)sin->sin_addr.s_addr;
10689 				ifaddr = INADDR_ANY;
10690 				ifindexp = &greqp->gr_interface;
10691 			} else {
10692 				mreqp = (struct ip_mreq *)i1;
10693 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10694 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10695 				ifindexp = NULL;
10696 			}
10697 
10698 			/*
10699 			 * In the multirouting case, we need to replicate
10700 			 * the request on all interfaces that will take part
10701 			 * in replication.  We do so because multirouting is
10702 			 * reflective, thus we will probably receive multi-
10703 			 * casts on those interfaces.
10704 			 * The ip_multirt_apply_membership() succeeds if the
10705 			 * operation succeeds on at least one interface.
10706 			 */
10707 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10708 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10709 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10710 			if (ire != NULL) {
10711 				if (ire->ire_flags & RTF_MULTIRT) {
10712 					error = ip_multirt_apply_membership(
10713 					    optfn, ire, connp, checkonly, group,
10714 					    fmode, INADDR_ANY, first_mp);
10715 					done = B_TRUE;
10716 				}
10717 				ire_refrele(ire);
10718 			}
10719 			if (!done) {
10720 				error = optfn(connp, checkonly, group, ifaddr,
10721 				    ifindexp, fmode, INADDR_ANY, first_mp);
10722 			}
10723 			if (error) {
10724 				/*
10725 				 * EINPROGRESS is a soft error, needs retry
10726 				 * so don't make *outlenp zero.
10727 				 */
10728 				if (error != EINPROGRESS)
10729 					*outlenp = 0;
10730 				return (error);
10731 			}
10732 			/* OK return - copy input buffer into output buffer */
10733 			if (invalp != outvalp) {
10734 				/* don't trust bcopy for identical src/dst */
10735 				bcopy(invalp, outvalp, inlen);
10736 			}
10737 			*outlenp = inlen;
10738 			return (0);
10739 		}
10740 		case IP_BLOCK_SOURCE:
10741 		case IP_UNBLOCK_SOURCE:
10742 		case IP_ADD_SOURCE_MEMBERSHIP:
10743 		case IP_DROP_SOURCE_MEMBERSHIP:
10744 		case MCAST_BLOCK_SOURCE:
10745 		case MCAST_UNBLOCK_SOURCE:
10746 		case MCAST_JOIN_SOURCE_GROUP:
10747 		case MCAST_LEAVE_SOURCE_GROUP: {
10748 			struct ip_mreq_source *imreqp;
10749 			struct group_source_req *gsreqp;
10750 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10751 			uint32_t ifindex = 0;
10752 			mcast_record_t fmode;
10753 			struct sockaddr_in *sin;
10754 			ire_t *ire;
10755 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10756 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10757 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10758 
10759 			switch (name) {
10760 			case IP_BLOCK_SOURCE:
10761 				mcast_opt = B_FALSE;
10762 				/* FALLTHRU */
10763 			case MCAST_BLOCK_SOURCE:
10764 				fmode = MODE_IS_EXCLUDE;
10765 				optfn = ip_opt_add_group;
10766 				break;
10767 
10768 			case IP_UNBLOCK_SOURCE:
10769 				mcast_opt = B_FALSE;
10770 				/* FALLTHRU */
10771 			case MCAST_UNBLOCK_SOURCE:
10772 				fmode = MODE_IS_EXCLUDE;
10773 				optfn = ip_opt_delete_group;
10774 				break;
10775 
10776 			case IP_ADD_SOURCE_MEMBERSHIP:
10777 				mcast_opt = B_FALSE;
10778 				/* FALLTHRU */
10779 			case MCAST_JOIN_SOURCE_GROUP:
10780 				fmode = MODE_IS_INCLUDE;
10781 				optfn = ip_opt_add_group;
10782 				break;
10783 
10784 			case IP_DROP_SOURCE_MEMBERSHIP:
10785 				mcast_opt = B_FALSE;
10786 				/* FALLTHRU */
10787 			case MCAST_LEAVE_SOURCE_GROUP:
10788 				fmode = MODE_IS_INCLUDE;
10789 				optfn = ip_opt_delete_group;
10790 				break;
10791 			}
10792 
10793 			if (mcast_opt) {
10794 				gsreqp = (struct group_source_req *)i1;
10795 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10796 					*outlenp = 0;
10797 					return (ENOPROTOOPT);
10798 				}
10799 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10800 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10801 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10802 				src = (ipaddr_t)sin->sin_addr.s_addr;
10803 				ifindex = gsreqp->gsr_interface;
10804 			} else {
10805 				imreqp = (struct ip_mreq_source *)i1;
10806 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10807 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10808 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10809 			}
10810 
10811 			/*
10812 			 * In the multirouting case, we need to replicate
10813 			 * the request as noted in the mcast cases above.
10814 			 */
10815 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10816 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10817 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10818 			if (ire != NULL) {
10819 				if (ire->ire_flags & RTF_MULTIRT) {
10820 					error = ip_multirt_apply_membership(
10821 					    optfn, ire, connp, checkonly, grp,
10822 					    fmode, src, first_mp);
10823 					done = B_TRUE;
10824 				}
10825 				ire_refrele(ire);
10826 			}
10827 			if (!done) {
10828 				error = optfn(connp, checkonly, grp, ifaddr,
10829 				    &ifindex, fmode, src, first_mp);
10830 			}
10831 			if (error != 0) {
10832 				/*
10833 				 * EINPROGRESS is a soft error, needs retry
10834 				 * so don't make *outlenp zero.
10835 				 */
10836 				if (error != EINPROGRESS)
10837 					*outlenp = 0;
10838 				return (error);
10839 			}
10840 			/* OK return - copy input buffer into output buffer */
10841 			if (invalp != outvalp) {
10842 				bcopy(invalp, outvalp, inlen);
10843 			}
10844 			*outlenp = inlen;
10845 			return (0);
10846 		}
10847 		case IP_SEC_OPT:
10848 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10849 			if (error != 0) {
10850 				*outlenp = 0;
10851 				return (error);
10852 			}
10853 			break;
10854 		case IP_HDRINCL:
10855 		case IP_OPTIONS:
10856 		case T_IP_OPTIONS:
10857 		case IP_TOS:
10858 		case T_IP_TOS:
10859 		case IP_TTL:
10860 		case IP_RECVDSTADDR:
10861 		case IP_RECVOPTS:
10862 			/* OK return - copy input buffer into output buffer */
10863 			if (invalp != outvalp) {
10864 				/* don't trust bcopy for identical src/dst */
10865 				bcopy(invalp, outvalp, inlen);
10866 			}
10867 			*outlenp = inlen;
10868 			return (0);
10869 		case IP_RECVIF:
10870 			/* Retrieve the inbound interface index */
10871 			if (!checkonly) {
10872 				mutex_enter(&connp->conn_lock);
10873 				connp->conn_recvif = *i1 ? 1 : 0;
10874 				mutex_exit(&connp->conn_lock);
10875 			}
10876 			break;	/* goto sizeof (int) option return */
10877 		case IP_RECVSLLA:
10878 			/* Retrieve the source link layer address */
10879 			if (!checkonly) {
10880 				mutex_enter(&connp->conn_lock);
10881 				connp->conn_recvslla = *i1 ? 1 : 0;
10882 				mutex_exit(&connp->conn_lock);
10883 			}
10884 			break;	/* goto sizeof (int) option return */
10885 		case MRT_INIT:
10886 		case MRT_DONE:
10887 		case MRT_ADD_VIF:
10888 		case MRT_DEL_VIF:
10889 		case MRT_ADD_MFC:
10890 		case MRT_DEL_MFC:
10891 		case MRT_ASSERT:
10892 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10893 				*outlenp = 0;
10894 				return (error);
10895 			}
10896 			error = ip_mrouter_set((int)name, q, checkonly,
10897 			    (uchar_t *)invalp, inlen, first_mp);
10898 			if (error) {
10899 				*outlenp = 0;
10900 				return (error);
10901 			}
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_BOUND_IF:
10910 		case IP_XMIT_IF:
10911 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10912 			    level, name, first_mp);
10913 			if (error != 0)
10914 				return (error);
10915 			break; 		/* goto sizeof (int) option return */
10916 
10917 		case IP_UNSPEC_SRC:
10918 			/* Allow sending with a zero source address */
10919 			if (!checkonly) {
10920 				mutex_enter(&connp->conn_lock);
10921 				connp->conn_unspec_src = *i1 ? 1 : 0;
10922 				mutex_exit(&connp->conn_lock);
10923 			}
10924 			break;	/* goto sizeof (int) option return */
10925 		default:
10926 			/*
10927 			 * "soft" error (negative)
10928 			 * option not handled at this level
10929 			 * Note: Do not modify *outlenp
10930 			 */
10931 			return (-EINVAL);
10932 		}
10933 		break;
10934 	case IPPROTO_IPV6:
10935 		switch (name) {
10936 		case IPV6_BOUND_IF:
10937 		case IPV6_BOUND_PIF:
10938 		case IPV6_DONTFAILOVER_IF:
10939 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10940 			    level, name, first_mp);
10941 			if (error != 0)
10942 				return (error);
10943 			break; 		/* goto sizeof (int) option return */
10944 
10945 		case IPV6_MULTICAST_IF:
10946 			/*
10947 			 * The only possible errors are EINPROGRESS and
10948 			 * EINVAL. EINPROGRESS will be restarted and is not
10949 			 * a hard error. We call this option on both V4 and V6
10950 			 * If both return EINVAL, then this call returns
10951 			 * EINVAL. If at least one of them succeeds we
10952 			 * return success.
10953 			 */
10954 			found = B_FALSE;
10955 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10956 			    level, name, first_mp);
10957 			if (error == EINPROGRESS)
10958 				return (error);
10959 			if (error == 0)
10960 				found = B_TRUE;
10961 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10962 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10963 			if (error == 0)
10964 				found = B_TRUE;
10965 			if (!found)
10966 				return (error);
10967 			break; 		/* goto sizeof (int) option return */
10968 
10969 		case IPV6_MULTICAST_HOPS:
10970 			/* Recorded in transport above IP */
10971 			break;	/* goto sizeof (int) option return */
10972 		case IPV6_MULTICAST_LOOP:
10973 			if (!checkonly) {
10974 				mutex_enter(&connp->conn_lock);
10975 				connp->conn_multicast_loop = *i1;
10976 				mutex_exit(&connp->conn_lock);
10977 			}
10978 			break;	/* goto sizeof (int) option return */
10979 		case IPV6_JOIN_GROUP:
10980 		case MCAST_JOIN_GROUP:
10981 		case IPV6_LEAVE_GROUP:
10982 		case MCAST_LEAVE_GROUP: {
10983 			struct ipv6_mreq *ip_mreqp;
10984 			struct group_req *greqp;
10985 			ire_t *ire;
10986 			boolean_t done = B_FALSE;
10987 			in6_addr_t groupv6;
10988 			uint32_t ifindex;
10989 			boolean_t mcast_opt = B_TRUE;
10990 			mcast_record_t fmode;
10991 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10992 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10993 
10994 			switch (name) {
10995 			case IPV6_JOIN_GROUP:
10996 				mcast_opt = B_FALSE;
10997 				/* FALLTHRU */
10998 			case MCAST_JOIN_GROUP:
10999 				fmode = MODE_IS_EXCLUDE;
11000 				optfn = ip_opt_add_group_v6;
11001 				break;
11002 
11003 			case IPV6_LEAVE_GROUP:
11004 				mcast_opt = B_FALSE;
11005 				/* FALLTHRU */
11006 			case MCAST_LEAVE_GROUP:
11007 				fmode = MODE_IS_INCLUDE;
11008 				optfn = ip_opt_delete_group_v6;
11009 				break;
11010 			}
11011 
11012 			if (mcast_opt) {
11013 				struct sockaddr_in *sin;
11014 				struct sockaddr_in6 *sin6;
11015 				greqp = (struct group_req *)i1;
11016 				if (greqp->gr_group.ss_family == AF_INET) {
11017 					sin = (struct sockaddr_in *)
11018 					    &(greqp->gr_group);
11019 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11020 					    &groupv6);
11021 				} else {
11022 					sin6 = (struct sockaddr_in6 *)
11023 					    &(greqp->gr_group);
11024 					groupv6 = sin6->sin6_addr;
11025 				}
11026 				ifindex = greqp->gr_interface;
11027 			} else {
11028 				ip_mreqp = (struct ipv6_mreq *)i1;
11029 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11030 				ifindex = ip_mreqp->ipv6mr_interface;
11031 			}
11032 			/*
11033 			 * In the multirouting case, we need to replicate
11034 			 * the request on all interfaces that will take part
11035 			 * in replication.  We do so because multirouting is
11036 			 * reflective, thus we will probably receive multi-
11037 			 * casts on those interfaces.
11038 			 * The ip_multirt_apply_membership_v6() succeeds if
11039 			 * the operation succeeds on at least one interface.
11040 			 */
11041 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11042 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11043 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11044 			if (ire != NULL) {
11045 				if (ire->ire_flags & RTF_MULTIRT) {
11046 					error = ip_multirt_apply_membership_v6(
11047 					    optfn, ire, connp, checkonly,
11048 					    &groupv6, fmode, &ipv6_all_zeros,
11049 					    first_mp);
11050 					done = B_TRUE;
11051 				}
11052 				ire_refrele(ire);
11053 			}
11054 			if (!done) {
11055 				error = optfn(connp, checkonly, &groupv6,
11056 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11057 			}
11058 			if (error) {
11059 				/*
11060 				 * EINPROGRESS is a soft error, needs retry
11061 				 * so don't make *outlenp zero.
11062 				 */
11063 				if (error != EINPROGRESS)
11064 					*outlenp = 0;
11065 				return (error);
11066 			}
11067 			/* OK return - copy input buffer into output buffer */
11068 			if (invalp != outvalp) {
11069 				/* don't trust bcopy for identical src/dst */
11070 				bcopy(invalp, outvalp, inlen);
11071 			}
11072 			*outlenp = inlen;
11073 			return (0);
11074 		}
11075 		case MCAST_BLOCK_SOURCE:
11076 		case MCAST_UNBLOCK_SOURCE:
11077 		case MCAST_JOIN_SOURCE_GROUP:
11078 		case MCAST_LEAVE_SOURCE_GROUP: {
11079 			struct group_source_req *gsreqp;
11080 			in6_addr_t v6grp, v6src;
11081 			uint32_t ifindex;
11082 			mcast_record_t fmode;
11083 			ire_t *ire;
11084 			boolean_t done = B_FALSE;
11085 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11086 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11087 
11088 			switch (name) {
11089 			case MCAST_BLOCK_SOURCE:
11090 				fmode = MODE_IS_EXCLUDE;
11091 				optfn = ip_opt_add_group_v6;
11092 				break;
11093 			case MCAST_UNBLOCK_SOURCE:
11094 				fmode = MODE_IS_EXCLUDE;
11095 				optfn = ip_opt_delete_group_v6;
11096 				break;
11097 			case MCAST_JOIN_SOURCE_GROUP:
11098 				fmode = MODE_IS_INCLUDE;
11099 				optfn = ip_opt_add_group_v6;
11100 				break;
11101 			case MCAST_LEAVE_SOURCE_GROUP:
11102 				fmode = MODE_IS_INCLUDE;
11103 				optfn = ip_opt_delete_group_v6;
11104 				break;
11105 			}
11106 
11107 			gsreqp = (struct group_source_req *)i1;
11108 			ifindex = gsreqp->gsr_interface;
11109 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11110 				struct sockaddr_in *s;
11111 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11112 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11113 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11114 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11115 			} else {
11116 				struct sockaddr_in6 *s6;
11117 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11118 				v6grp = s6->sin6_addr;
11119 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11120 				v6src = s6->sin6_addr;
11121 			}
11122 
11123 			/*
11124 			 * In the multirouting case, we need to replicate
11125 			 * the request as noted in the mcast cases above.
11126 			 */
11127 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11128 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11129 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11130 			if (ire != NULL) {
11131 				if (ire->ire_flags & RTF_MULTIRT) {
11132 					error = ip_multirt_apply_membership_v6(
11133 					    optfn, ire, connp, checkonly,
11134 					    &v6grp, fmode, &v6src, first_mp);
11135 					done = B_TRUE;
11136 				}
11137 				ire_refrele(ire);
11138 			}
11139 			if (!done) {
11140 				error = optfn(connp, checkonly, &v6grp,
11141 				    ifindex, fmode, &v6src, first_mp);
11142 			}
11143 			if (error != 0) {
11144 				/*
11145 				 * EINPROGRESS is a soft error, needs retry
11146 				 * so don't make *outlenp zero.
11147 				 */
11148 				if (error != EINPROGRESS)
11149 					*outlenp = 0;
11150 				return (error);
11151 			}
11152 			/* OK return - copy input buffer into output buffer */
11153 			if (invalp != outvalp) {
11154 				bcopy(invalp, outvalp, inlen);
11155 			}
11156 			*outlenp = inlen;
11157 			return (0);
11158 		}
11159 		case IPV6_UNICAST_HOPS:
11160 			/* Recorded in transport above IP */
11161 			break;	/* goto sizeof (int) option return */
11162 		case IPV6_UNSPEC_SRC:
11163 			/* Allow sending with a zero source address */
11164 			if (!checkonly) {
11165 				mutex_enter(&connp->conn_lock);
11166 				connp->conn_unspec_src = *i1 ? 1 : 0;
11167 				mutex_exit(&connp->conn_lock);
11168 			}
11169 			break;	/* goto sizeof (int) option return */
11170 		case IPV6_RECVPKTINFO:
11171 			if (!checkonly) {
11172 				mutex_enter(&connp->conn_lock);
11173 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11174 				mutex_exit(&connp->conn_lock);
11175 			}
11176 			break;	/* goto sizeof (int) option return */
11177 		case IPV6_RECVTCLASS:
11178 			if (!checkonly) {
11179 				if (*i1 < 0 || *i1 > 1) {
11180 					return (EINVAL);
11181 				}
11182 				mutex_enter(&connp->conn_lock);
11183 				connp->conn_ipv6_recvtclass = *i1;
11184 				mutex_exit(&connp->conn_lock);
11185 			}
11186 			break;
11187 		case IPV6_RECVPATHMTU:
11188 			if (!checkonly) {
11189 				if (*i1 < 0 || *i1 > 1) {
11190 					return (EINVAL);
11191 				}
11192 				mutex_enter(&connp->conn_lock);
11193 				connp->conn_ipv6_recvpathmtu = *i1;
11194 				mutex_exit(&connp->conn_lock);
11195 			}
11196 			break;
11197 		case IPV6_RECVHOPLIMIT:
11198 			if (!checkonly) {
11199 				mutex_enter(&connp->conn_lock);
11200 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11201 				mutex_exit(&connp->conn_lock);
11202 			}
11203 			break;	/* goto sizeof (int) option return */
11204 		case IPV6_RECVHOPOPTS:
11205 			if (!checkonly) {
11206 				mutex_enter(&connp->conn_lock);
11207 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11208 				mutex_exit(&connp->conn_lock);
11209 			}
11210 			break;	/* goto sizeof (int) option return */
11211 		case IPV6_RECVDSTOPTS:
11212 			if (!checkonly) {
11213 				mutex_enter(&connp->conn_lock);
11214 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11215 				mutex_exit(&connp->conn_lock);
11216 			}
11217 			break;	/* goto sizeof (int) option return */
11218 		case IPV6_RECVRTHDR:
11219 			if (!checkonly) {
11220 				mutex_enter(&connp->conn_lock);
11221 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11222 				mutex_exit(&connp->conn_lock);
11223 			}
11224 			break;	/* goto sizeof (int) option return */
11225 		case IPV6_RECVRTHDRDSTOPTS:
11226 			if (!checkonly) {
11227 				mutex_enter(&connp->conn_lock);
11228 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11229 				mutex_exit(&connp->conn_lock);
11230 			}
11231 			break;	/* goto sizeof (int) option return */
11232 		case IPV6_PKTINFO:
11233 			if (inlen == 0)
11234 				return (-EINVAL);	/* clearing option */
11235 			error = ip6_set_pktinfo(cr, connp,
11236 			    (struct in6_pktinfo *)invalp, first_mp);
11237 			if (error != 0)
11238 				*outlenp = 0;
11239 			else
11240 				*outlenp = inlen;
11241 			return (error);
11242 		case IPV6_NEXTHOP: {
11243 			struct sockaddr_in6 *sin6;
11244 
11245 			/* Verify that the nexthop is reachable */
11246 			if (inlen == 0)
11247 				return (-EINVAL);	/* clearing option */
11248 
11249 			sin6 = (struct sockaddr_in6 *)invalp;
11250 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11251 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11252 			    NULL, MATCH_IRE_DEFAULT);
11253 
11254 			if (ire == NULL) {
11255 				*outlenp = 0;
11256 				return (EHOSTUNREACH);
11257 			}
11258 			ire_refrele(ire);
11259 			return (-EINVAL);
11260 		}
11261 		case IPV6_SEC_OPT:
11262 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11263 			if (error != 0) {
11264 				*outlenp = 0;
11265 				return (error);
11266 			}
11267 			break;
11268 		case IPV6_SRC_PREFERENCES: {
11269 			/*
11270 			 * This is implemented strictly in the ip module
11271 			 * (here and in tcp_opt_*() to accomodate tcp
11272 			 * sockets).  Modules above ip pass this option
11273 			 * down here since ip is the only one that needs to
11274 			 * be aware of source address preferences.
11275 			 *
11276 			 * This socket option only affects connected
11277 			 * sockets that haven't already bound to a specific
11278 			 * IPv6 address.  In other words, sockets that
11279 			 * don't call bind() with an address other than the
11280 			 * unspecified address and that call connect().
11281 			 * ip_bind_connected_v6() passes these preferences
11282 			 * to the ipif_select_source_v6() function.
11283 			 */
11284 			if (inlen != sizeof (uint32_t))
11285 				return (EINVAL);
11286 			error = ip6_set_src_preferences(connp,
11287 			    *(uint32_t *)invalp);
11288 			if (error != 0) {
11289 				*outlenp = 0;
11290 				return (error);
11291 			} else {
11292 				*outlenp = sizeof (uint32_t);
11293 			}
11294 			break;
11295 		}
11296 		case IPV6_V6ONLY:
11297 			if (*i1 < 0 || *i1 > 1) {
11298 				return (EINVAL);
11299 			}
11300 			mutex_enter(&connp->conn_lock);
11301 			connp->conn_ipv6_v6only = *i1;
11302 			mutex_exit(&connp->conn_lock);
11303 			break;
11304 		default:
11305 			return (-EINVAL);
11306 		}
11307 		break;
11308 	default:
11309 		/*
11310 		 * "soft" error (negative)
11311 		 * option not handled at this level
11312 		 * Note: Do not modify *outlenp
11313 		 */
11314 		return (-EINVAL);
11315 	}
11316 	/*
11317 	 * Common case of return from an option that is sizeof (int)
11318 	 */
11319 	*(int *)outvalp = *i1;
11320 	*outlenp = sizeof (int);
11321 	return (0);
11322 }
11323 
11324 /*
11325  * This routine gets default values of certain options whose default
11326  * values are maintained by protocol specific code
11327  */
11328 /* ARGSUSED */
11329 int
11330 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11331 {
11332 	int *i1 = (int *)ptr;
11333 
11334 	switch (level) {
11335 	case IPPROTO_IP:
11336 		switch (name) {
11337 		case IP_MULTICAST_TTL:
11338 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11339 			return (sizeof (uchar_t));
11340 		case IP_MULTICAST_LOOP:
11341 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11342 			return (sizeof (uchar_t));
11343 		default:
11344 			return (-1);
11345 		}
11346 	case IPPROTO_IPV6:
11347 		switch (name) {
11348 		case IPV6_UNICAST_HOPS:
11349 			*i1 = ipv6_def_hops;
11350 			return (sizeof (int));
11351 		case IPV6_MULTICAST_HOPS:
11352 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11353 			return (sizeof (int));
11354 		case IPV6_MULTICAST_LOOP:
11355 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11356 			return (sizeof (int));
11357 		case IPV6_V6ONLY:
11358 			*i1 = 1;
11359 			return (sizeof (int));
11360 		default:
11361 			return (-1);
11362 		}
11363 	default:
11364 		return (-1);
11365 	}
11366 	/* NOTREACHED */
11367 }
11368 
11369 /*
11370  * Given a destination address and a pointer to where to put the information
11371  * this routine fills in the mtuinfo.
11372  */
11373 int
11374 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11375     struct ip6_mtuinfo *mtuinfo)
11376 {
11377 	ire_t *ire;
11378 
11379 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11380 		return (-1);
11381 
11382 	bzero(mtuinfo, sizeof (*mtuinfo));
11383 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11384 	mtuinfo->ip6m_addr.sin6_port = port;
11385 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11386 
11387 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11388 	if (ire != NULL) {
11389 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11390 		ire_refrele(ire);
11391 	} else {
11392 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11393 	}
11394 	return (sizeof (struct ip6_mtuinfo));
11395 }
11396 
11397 /*
11398  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11399  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11400  * isn't.  This doesn't matter as the error checking is done properly for the
11401  * other MRT options coming in through ip_opt_set.
11402  */
11403 int
11404 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11405 {
11406 	conn_t		*connp = Q_TO_CONN(q);
11407 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11408 
11409 	switch (level) {
11410 	case IPPROTO_IP:
11411 		switch (name) {
11412 		case MRT_VERSION:
11413 		case MRT_ASSERT:
11414 			(void) ip_mrouter_get(name, q, ptr);
11415 			return (sizeof (int));
11416 		case IP_SEC_OPT:
11417 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11418 		case IP_NEXTHOP:
11419 			if (connp->conn_nexthop_set) {
11420 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11421 				return (sizeof (ipaddr_t));
11422 			} else
11423 				return (0);
11424 		default:
11425 			break;
11426 		}
11427 		break;
11428 	case IPPROTO_IPV6:
11429 		switch (name) {
11430 		case IPV6_SEC_OPT:
11431 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11432 		case IPV6_SRC_PREFERENCES: {
11433 			return (ip6_get_src_preferences(connp,
11434 			    (uint32_t *)ptr));
11435 		}
11436 		case IPV6_V6ONLY:
11437 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11438 			return (sizeof (int));
11439 		case IPV6_PATHMTU:
11440 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11441 				(struct ip6_mtuinfo *)ptr));
11442 		default:
11443 			break;
11444 		}
11445 		break;
11446 	default:
11447 		break;
11448 	}
11449 	return (-1);
11450 }
11451 
11452 /* Named Dispatch routine to get a current value out of our parameter table. */
11453 /* ARGSUSED */
11454 static int
11455 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11456 {
11457 	ipparam_t *ippa = (ipparam_t *)cp;
11458 
11459 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11460 	return (0);
11461 }
11462 
11463 /* ARGSUSED */
11464 static int
11465 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11466 {
11467 
11468 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11469 	return (0);
11470 }
11471 
11472 /*
11473  * Set ip{,6}_forwarding values.  This means walking through all of the
11474  * ill's and toggling their forwarding values.
11475  */
11476 /* ARGSUSED */
11477 static int
11478 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11479 {
11480 	long new_value;
11481 	int *forwarding_value = (int *)cp;
11482 	ill_t *walker;
11483 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11484 	ill_walk_context_t ctx;
11485 
11486 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11487 	    new_value < 0 || new_value > 1) {
11488 		return (EINVAL);
11489 	}
11490 
11491 	*forwarding_value = new_value;
11492 
11493 	/*
11494 	 * Regardless of the current value of ip_forwarding, set all per-ill
11495 	 * values of ip_forwarding to the value being set.
11496 	 *
11497 	 * Bring all the ill's up to date with the new global value.
11498 	 */
11499 	rw_enter(&ill_g_lock, RW_READER);
11500 
11501 	if (isv6)
11502 		walker = ILL_START_WALK_V6(&ctx);
11503 	else
11504 		walker = ILL_START_WALK_V4(&ctx);
11505 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11506 		(void) ill_forward_set(q, mp, (new_value != 0),
11507 		    (caddr_t)walker);
11508 	}
11509 	rw_exit(&ill_g_lock);
11510 
11511 	return (0);
11512 }
11513 
11514 /*
11515  * Walk through the param array specified registering each element with the
11516  * Named Dispatch handler. This is called only during init. So it is ok
11517  * not to acquire any locks
11518  */
11519 static boolean_t
11520 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11521     ipndp_t *ipnd, size_t ipnd_cnt)
11522 {
11523 	for (; ippa_cnt-- > 0; ippa++) {
11524 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11525 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11526 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11527 				nd_free(&ip_g_nd);
11528 				return (B_FALSE);
11529 			}
11530 		}
11531 	}
11532 
11533 	for (; ipnd_cnt-- > 0; ipnd++) {
11534 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11535 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11536 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11537 			    ipnd->ip_ndp_data)) {
11538 				nd_free(&ip_g_nd);
11539 				return (B_FALSE);
11540 			}
11541 		}
11542 	}
11543 
11544 	return (B_TRUE);
11545 }
11546 
11547 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11548 /* ARGSUSED */
11549 static int
11550 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11551 {
11552 	long		new_value;
11553 	ipparam_t	*ippa = (ipparam_t *)cp;
11554 
11555 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11556 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11557 		return (EINVAL);
11558 	}
11559 	ippa->ip_param_value = new_value;
11560 	return (0);
11561 }
11562 
11563 /*
11564  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11565  * When an ipf is passed here for the first time, if
11566  * we already have in-order fragments on the queue, we convert from the fast-
11567  * path reassembly scheme to the hard-case scheme.  From then on, additional
11568  * fragments are reassembled here.  We keep track of the start and end offsets
11569  * of each piece, and the number of holes in the chain.  When the hole count
11570  * goes to zero, we are done!
11571  *
11572  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11573  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11574  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11575  * after the call to ip_reassemble().
11576  */
11577 int
11578 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11579     size_t msg_len)
11580 {
11581 	uint_t	end;
11582 	mblk_t	*next_mp;
11583 	mblk_t	*mp1;
11584 	uint_t	offset;
11585 	boolean_t incr_dups = B_TRUE;
11586 	boolean_t offset_zero_seen = B_FALSE;
11587 	boolean_t pkt_boundary_checked = B_FALSE;
11588 
11589 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11590 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11591 
11592 	/* Add in byte count */
11593 	ipf->ipf_count += msg_len;
11594 	if (ipf->ipf_end) {
11595 		/*
11596 		 * We were part way through in-order reassembly, but now there
11597 		 * is a hole.  We walk through messages already queued, and
11598 		 * mark them for hard case reassembly.  We know that up till
11599 		 * now they were in order starting from offset zero.
11600 		 */
11601 		offset = 0;
11602 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11603 			IP_REASS_SET_START(mp1, offset);
11604 			if (offset == 0) {
11605 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11606 				offset = -ipf->ipf_nf_hdr_len;
11607 			}
11608 			offset += mp1->b_wptr - mp1->b_rptr;
11609 			IP_REASS_SET_END(mp1, offset);
11610 		}
11611 		/* One hole at the end. */
11612 		ipf->ipf_hole_cnt = 1;
11613 		/* Brand it as a hard case, forever. */
11614 		ipf->ipf_end = 0;
11615 	}
11616 	/* Walk through all the new pieces. */
11617 	do {
11618 		end = start + (mp->b_wptr - mp->b_rptr);
11619 		/*
11620 		 * If start is 0, decrease 'end' only for the first mblk of
11621 		 * the fragment. Otherwise 'end' can get wrong value in the
11622 		 * second pass of the loop if first mblk is exactly the
11623 		 * size of ipf_nf_hdr_len.
11624 		 */
11625 		if (start == 0 && !offset_zero_seen) {
11626 			/* First segment */
11627 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11628 			end -= ipf->ipf_nf_hdr_len;
11629 			offset_zero_seen = B_TRUE;
11630 		}
11631 		next_mp = mp->b_cont;
11632 		/*
11633 		 * We are checking to see if there is any interesing data
11634 		 * to process.  If there isn't and the mblk isn't the
11635 		 * one which carries the unfragmentable header then we
11636 		 * drop it.  It's possible to have just the unfragmentable
11637 		 * header come through without any data.  That needs to be
11638 		 * saved.
11639 		 *
11640 		 * If the assert at the top of this function holds then the
11641 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11642 		 * is infrequently traveled enough that the test is left in
11643 		 * to protect against future code changes which break that
11644 		 * invariant.
11645 		 */
11646 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11647 			/* Empty.  Blast it. */
11648 			IP_REASS_SET_START(mp, 0);
11649 			IP_REASS_SET_END(mp, 0);
11650 			/*
11651 			 * If the ipf points to the mblk we are about to free,
11652 			 * update ipf to point to the next mblk (or NULL
11653 			 * if none).
11654 			 */
11655 			if (ipf->ipf_mp->b_cont == mp)
11656 				ipf->ipf_mp->b_cont = next_mp;
11657 			freeb(mp);
11658 			continue;
11659 		}
11660 		mp->b_cont = NULL;
11661 		IP_REASS_SET_START(mp, start);
11662 		IP_REASS_SET_END(mp, end);
11663 		if (!ipf->ipf_tail_mp) {
11664 			ipf->ipf_tail_mp = mp;
11665 			ipf->ipf_mp->b_cont = mp;
11666 			if (start == 0 || !more) {
11667 				ipf->ipf_hole_cnt = 1;
11668 				/*
11669 				 * if the first fragment comes in more than one
11670 				 * mblk, this loop will be executed for each
11671 				 * mblk. Need to adjust hole count so exiting
11672 				 * this routine will leave hole count at 1.
11673 				 */
11674 				if (next_mp)
11675 					ipf->ipf_hole_cnt++;
11676 			} else
11677 				ipf->ipf_hole_cnt = 2;
11678 			continue;
11679 		} else if (ipf->ipf_last_frag_seen && !more &&
11680 			    !pkt_boundary_checked) {
11681 			/*
11682 			 * We check datagram boundary only if this fragment
11683 			 * claims to be the last fragment and we have seen a
11684 			 * last fragment in the past too. We do this only
11685 			 * once for a given fragment.
11686 			 *
11687 			 * start cannot be 0 here as fragments with start=0
11688 			 * and MF=0 gets handled as a complete packet. These
11689 			 * fragments should not reach here.
11690 			 */
11691 
11692 			if (start + msgdsize(mp) !=
11693 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11694 				/*
11695 				 * We have two fragments both of which claim
11696 				 * to be the last fragment but gives conflicting
11697 				 * information about the whole datagram size.
11698 				 * Something fishy is going on. Drop the
11699 				 * fragment and free up the reassembly list.
11700 				 */
11701 				return (IP_REASS_FAILED);
11702 			}
11703 
11704 			/*
11705 			 * We shouldn't come to this code block again for this
11706 			 * particular fragment.
11707 			 */
11708 			pkt_boundary_checked = B_TRUE;
11709 		}
11710 
11711 		/* New stuff at or beyond tail? */
11712 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11713 		if (start >= offset) {
11714 			if (ipf->ipf_last_frag_seen) {
11715 				/* current fragment is beyond last fragment */
11716 				return (IP_REASS_FAILED);
11717 			}
11718 			/* Link it on end. */
11719 			ipf->ipf_tail_mp->b_cont = mp;
11720 			ipf->ipf_tail_mp = mp;
11721 			if (more) {
11722 				if (start != offset)
11723 					ipf->ipf_hole_cnt++;
11724 			} else if (start == offset && next_mp == NULL)
11725 					ipf->ipf_hole_cnt--;
11726 			continue;
11727 		}
11728 		mp1 = ipf->ipf_mp->b_cont;
11729 		offset = IP_REASS_START(mp1);
11730 		/* New stuff at the front? */
11731 		if (start < offset) {
11732 			if (start == 0) {
11733 				if (end >= offset) {
11734 					/* Nailed the hole at the begining. */
11735 					ipf->ipf_hole_cnt--;
11736 				}
11737 			} else if (end < offset) {
11738 				/*
11739 				 * A hole, stuff, and a hole where there used
11740 				 * to be just a hole.
11741 				 */
11742 				ipf->ipf_hole_cnt++;
11743 			}
11744 			mp->b_cont = mp1;
11745 			/* Check for overlap. */
11746 			while (end > offset) {
11747 				if (end < IP_REASS_END(mp1)) {
11748 					mp->b_wptr -= end - offset;
11749 					IP_REASS_SET_END(mp, offset);
11750 					if (ill->ill_isv6) {
11751 						BUMP_MIB(ill->ill_ip6_mib,
11752 						    ipv6ReasmPartDups);
11753 					} else {
11754 						BUMP_MIB(&ip_mib,
11755 						    ipReasmPartDups);
11756 					}
11757 					break;
11758 				}
11759 				/* Did we cover another hole? */
11760 				if ((mp1->b_cont &&
11761 				    IP_REASS_END(mp1) !=
11762 				    IP_REASS_START(mp1->b_cont) &&
11763 				    end >= IP_REASS_START(mp1->b_cont)) ||
11764 				    (!ipf->ipf_last_frag_seen && !more)) {
11765 					ipf->ipf_hole_cnt--;
11766 				}
11767 				/* Clip out mp1. */
11768 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11769 					/*
11770 					 * After clipping out mp1, this guy
11771 					 * is now hanging off the end.
11772 					 */
11773 					ipf->ipf_tail_mp = mp;
11774 				}
11775 				IP_REASS_SET_START(mp1, 0);
11776 				IP_REASS_SET_END(mp1, 0);
11777 				/* Subtract byte count */
11778 				ipf->ipf_count -= mp1->b_datap->db_lim -
11779 				    mp1->b_datap->db_base;
11780 				freeb(mp1);
11781 				if (ill->ill_isv6) {
11782 					BUMP_MIB(ill->ill_ip6_mib,
11783 					    ipv6ReasmPartDups);
11784 				} else {
11785 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11786 				}
11787 				mp1 = mp->b_cont;
11788 				if (!mp1)
11789 					break;
11790 				offset = IP_REASS_START(mp1);
11791 			}
11792 			ipf->ipf_mp->b_cont = mp;
11793 			continue;
11794 		}
11795 		/*
11796 		 * The new piece starts somewhere between the start of the head
11797 		 * and before the end of the tail.
11798 		 */
11799 		for (; mp1; mp1 = mp1->b_cont) {
11800 			offset = IP_REASS_END(mp1);
11801 			if (start < offset) {
11802 				if (end <= offset) {
11803 					/* Nothing new. */
11804 					IP_REASS_SET_START(mp, 0);
11805 					IP_REASS_SET_END(mp, 0);
11806 					/* Subtract byte count */
11807 					ipf->ipf_count -= mp->b_datap->db_lim -
11808 					    mp->b_datap->db_base;
11809 					if (incr_dups) {
11810 						ipf->ipf_num_dups++;
11811 						incr_dups = B_FALSE;
11812 					}
11813 					freeb(mp);
11814 					if (ill->ill_isv6) {
11815 						BUMP_MIB(ill->ill_ip6_mib,
11816 						    ipv6ReasmDuplicates);
11817 					} else {
11818 						BUMP_MIB(&ip_mib,
11819 						    ipReasmDuplicates);
11820 					}
11821 					break;
11822 				}
11823 				/*
11824 				 * Trim redundant stuff off beginning of new
11825 				 * piece.
11826 				 */
11827 				IP_REASS_SET_START(mp, offset);
11828 				mp->b_rptr += offset - start;
11829 				if (ill->ill_isv6) {
11830 					BUMP_MIB(ill->ill_ip6_mib,
11831 					    ipv6ReasmPartDups);
11832 				} else {
11833 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11834 				}
11835 				start = offset;
11836 				if (!mp1->b_cont) {
11837 					/*
11838 					 * After trimming, this guy is now
11839 					 * hanging off the end.
11840 					 */
11841 					mp1->b_cont = mp;
11842 					ipf->ipf_tail_mp = mp;
11843 					if (!more) {
11844 						ipf->ipf_hole_cnt--;
11845 					}
11846 					break;
11847 				}
11848 			}
11849 			if (start >= IP_REASS_START(mp1->b_cont))
11850 				continue;
11851 			/* Fill a hole */
11852 			if (start > offset)
11853 				ipf->ipf_hole_cnt++;
11854 			mp->b_cont = mp1->b_cont;
11855 			mp1->b_cont = mp;
11856 			mp1 = mp->b_cont;
11857 			offset = IP_REASS_START(mp1);
11858 			if (end >= offset) {
11859 				ipf->ipf_hole_cnt--;
11860 				/* Check for overlap. */
11861 				while (end > offset) {
11862 					if (end < IP_REASS_END(mp1)) {
11863 						mp->b_wptr -= end - offset;
11864 						IP_REASS_SET_END(mp, offset);
11865 						/*
11866 						 * TODO we might bump
11867 						 * this up twice if there is
11868 						 * overlap at both ends.
11869 						 */
11870 						if (ill->ill_isv6) {
11871 							BUMP_MIB(
11872 							    ill->ill_ip6_mib,
11873 							    ipv6ReasmPartDups);
11874 						} else {
11875 							BUMP_MIB(&ip_mib,
11876 							    ipReasmPartDups);
11877 						}
11878 						break;
11879 					}
11880 					/* Did we cover another hole? */
11881 					if ((mp1->b_cont &&
11882 					    IP_REASS_END(mp1)
11883 					    != IP_REASS_START(mp1->b_cont) &&
11884 					    end >=
11885 					    IP_REASS_START(mp1->b_cont)) ||
11886 					    (!ipf->ipf_last_frag_seen &&
11887 					    !more)) {
11888 						ipf->ipf_hole_cnt--;
11889 					}
11890 					/* Clip out mp1. */
11891 					if ((mp->b_cont = mp1->b_cont) ==
11892 					    NULL) {
11893 						/*
11894 						 * After clipping out mp1,
11895 						 * this guy is now hanging
11896 						 * off the end.
11897 						 */
11898 						ipf->ipf_tail_mp = mp;
11899 					}
11900 					IP_REASS_SET_START(mp1, 0);
11901 					IP_REASS_SET_END(mp1, 0);
11902 					/* Subtract byte count */
11903 					ipf->ipf_count -=
11904 					    mp1->b_datap->db_lim -
11905 					    mp1->b_datap->db_base;
11906 					freeb(mp1);
11907 					if (ill->ill_isv6) {
11908 						BUMP_MIB(ill->ill_ip6_mib,
11909 						    ipv6ReasmPartDups);
11910 					} else {
11911 						BUMP_MIB(&ip_mib,
11912 						    ipReasmPartDups);
11913 					}
11914 					mp1 = mp->b_cont;
11915 					if (!mp1)
11916 						break;
11917 					offset = IP_REASS_START(mp1);
11918 				}
11919 			}
11920 			break;
11921 		}
11922 	} while (start = end, mp = next_mp);
11923 
11924 	/* Fragment just processed could be the last one. Remember this fact */
11925 	if (!more)
11926 		ipf->ipf_last_frag_seen = B_TRUE;
11927 
11928 	/* Still got holes? */
11929 	if (ipf->ipf_hole_cnt)
11930 		return (IP_REASS_PARTIAL);
11931 	/* Clean up overloaded fields to avoid upstream disasters. */
11932 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11933 		IP_REASS_SET_START(mp1, 0);
11934 		IP_REASS_SET_END(mp1, 0);
11935 	}
11936 	return (IP_REASS_COMPLETE);
11937 }
11938 
11939 /*
11940  * ipsec processing for the fast path, used for input UDP Packets
11941  */
11942 static boolean_t
11943 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11944     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11945 {
11946 	uint32_t	ill_index;
11947 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11948 
11949 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11950 	/* The ill_index of the incoming ILL */
11951 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11952 
11953 	/* pass packet up to the transport */
11954 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11955 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11956 		    NULL, mctl_present);
11957 		if (*first_mpp == NULL) {
11958 			return (B_FALSE);
11959 		}
11960 	}
11961 
11962 	/* Initiate IPPF processing for fastpath UDP */
11963 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11964 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11965 		if (*mpp == NULL) {
11966 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11967 			    "deferred/dropped during IPPF processing\n"));
11968 			return (B_FALSE);
11969 		}
11970 	}
11971 	/*
11972 	 * We make the checks as below since we are in the fast path
11973 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11974 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11975 	 */
11976 	if (connp->conn_recvif || connp->conn_recvslla ||
11977 	    connp->conn_ipv6_recvpktinfo) {
11978 		if (connp->conn_recvif ||
11979 		    connp->conn_ipv6_recvpktinfo) {
11980 			in_flags = IPF_RECVIF;
11981 		}
11982 		if (connp->conn_recvslla) {
11983 			in_flags |= IPF_RECVSLLA;
11984 		}
11985 		/*
11986 		 * since in_flags are being set ill will be
11987 		 * referenced in ip_add_info, so it better not
11988 		 * be NULL.
11989 		 */
11990 		/*
11991 		 * the actual data will be contained in b_cont
11992 		 * upon successful return of the following call.
11993 		 * If the call fails then the original mblk is
11994 		 * returned.
11995 		 */
11996 		*mpp = ip_add_info(*mpp, ill, in_flags);
11997 	}
11998 
11999 	return (B_TRUE);
12000 }
12001 
12002 /*
12003  * Fragmentation reassembly.  Each ILL has a hash table for
12004  * queuing packets undergoing reassembly for all IPIFs
12005  * associated with the ILL.  The hash is based on the packet
12006  * IP ident field.  The ILL frag hash table was allocated
12007  * as a timer block at the time the ILL was created.  Whenever
12008  * there is anything on the reassembly queue, the timer will
12009  * be running.  Returns B_TRUE if successful else B_FALSE;
12010  * frees mp on failure.
12011  */
12012 static boolean_t
12013 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12014     uint32_t *cksum_val, uint16_t *cksum_flags)
12015 {
12016 	uint32_t	frag_offset_flags;
12017 	ill_t		*ill = (ill_t *)q->q_ptr;
12018 	mblk_t		*mp = *mpp;
12019 	mblk_t		*t_mp;
12020 	ipaddr_t	dst;
12021 	uint8_t		proto = ipha->ipha_protocol;
12022 	uint32_t	sum_val;
12023 	uint16_t	sum_flags;
12024 	ipf_t		*ipf;
12025 	ipf_t		**ipfp;
12026 	ipfb_t		*ipfb;
12027 	uint16_t	ident;
12028 	uint32_t	offset;
12029 	ipaddr_t	src;
12030 	uint_t		hdr_length;
12031 	uint32_t	end;
12032 	mblk_t		*mp1;
12033 	mblk_t		*tail_mp;
12034 	size_t		count;
12035 	size_t		msg_len;
12036 	uint8_t		ecn_info = 0;
12037 	uint32_t	packet_size;
12038 	boolean_t	pruned = B_FALSE;
12039 
12040 	if (cksum_val != NULL)
12041 		*cksum_val = 0;
12042 	if (cksum_flags != NULL)
12043 		*cksum_flags = 0;
12044 
12045 	/*
12046 	 * Drop the fragmented as early as possible, if
12047 	 * we don't have resource(s) to re-assemble.
12048 	 */
12049 	if (ip_reass_queue_bytes == 0) {
12050 		freemsg(mp);
12051 		return (B_FALSE);
12052 	}
12053 
12054 	/* Check for fragmentation offset; return if there's none */
12055 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12056 	    (IPH_MF | IPH_OFFSET)) == 0)
12057 		return (B_TRUE);
12058 
12059 	/*
12060 	 * We utilize hardware computed checksum info only for UDP since
12061 	 * IP fragmentation is a normal occurence for the protocol.  In
12062 	 * addition, checksum offload support for IP fragments carrying
12063 	 * UDP payload is commonly implemented across network adapters.
12064 	 */
12065 	ASSERT(ill != NULL);
12066 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12067 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12068 		mblk_t *mp1 = mp->b_cont;
12069 		int32_t len;
12070 
12071 		/* Record checksum information from the packet */
12072 		sum_val = (uint32_t)DB_CKSUM16(mp);
12073 		sum_flags = DB_CKSUMFLAGS(mp);
12074 
12075 		/* IP payload offset from beginning of mblk */
12076 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12077 
12078 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12079 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12080 		    offset >= DB_CKSUMSTART(mp) &&
12081 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12082 			uint32_t adj;
12083 			/*
12084 			 * Partial checksum has been calculated by hardware
12085 			 * and attached to the packet; in addition, any
12086 			 * prepended extraneous data is even byte aligned.
12087 			 * If any such data exists, we adjust the checksum;
12088 			 * this would also handle any postpended data.
12089 			 */
12090 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12091 			    mp, mp1, len, adj);
12092 
12093 			/* One's complement subtract extraneous checksum */
12094 			if (adj >= sum_val)
12095 				sum_val = ~(adj - sum_val) & 0xFFFF;
12096 			else
12097 				sum_val -= adj;
12098 		}
12099 	} else {
12100 		sum_val = 0;
12101 		sum_flags = 0;
12102 	}
12103 
12104 	/* Clear hardware checksumming flag */
12105 	DB_CKSUMFLAGS(mp) = 0;
12106 
12107 	ident = ipha->ipha_ident;
12108 	offset = (frag_offset_flags << 3) & 0xFFFF;
12109 	src = ipha->ipha_src;
12110 	dst = ipha->ipha_dst;
12111 	hdr_length = IPH_HDR_LENGTH(ipha);
12112 	end = ntohs(ipha->ipha_length) - hdr_length;
12113 
12114 	/* If end == 0 then we have a packet with no data, so just free it */
12115 	if (end == 0) {
12116 		freemsg(mp);
12117 		return (B_FALSE);
12118 	}
12119 
12120 	/* Record the ECN field info. */
12121 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12122 	if (offset != 0) {
12123 		/*
12124 		 * If this isn't the first piece, strip the header, and
12125 		 * add the offset to the end value.
12126 		 */
12127 		mp->b_rptr += hdr_length;
12128 		end += offset;
12129 	}
12130 
12131 	msg_len = MBLKSIZE(mp);
12132 	tail_mp = mp;
12133 	while (tail_mp->b_cont != NULL) {
12134 		tail_mp = tail_mp->b_cont;
12135 		msg_len += MBLKSIZE(tail_mp);
12136 	}
12137 
12138 	/* If the reassembly list for this ILL will get too big, prune it */
12139 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12140 	    ip_reass_queue_bytes) {
12141 		ill_frag_prune(ill,
12142 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12143 		    (ip_reass_queue_bytes - msg_len));
12144 		pruned = B_TRUE;
12145 	}
12146 
12147 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12148 	mutex_enter(&ipfb->ipfb_lock);
12149 
12150 	ipfp = &ipfb->ipfb_ipf;
12151 	/* Try to find an existing fragment queue for this packet. */
12152 	for (;;) {
12153 		ipf = ipfp[0];
12154 		if (ipf != NULL) {
12155 			/*
12156 			 * It has to match on ident and src/dst address.
12157 			 */
12158 			if (ipf->ipf_ident == ident &&
12159 			    ipf->ipf_src == src &&
12160 			    ipf->ipf_dst == dst &&
12161 			    ipf->ipf_protocol == proto) {
12162 				/*
12163 				 * If we have received too many
12164 				 * duplicate fragments for this packet
12165 				 * free it.
12166 				 */
12167 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12168 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12169 					freemsg(mp);
12170 					mutex_exit(&ipfb->ipfb_lock);
12171 					return (B_FALSE);
12172 				}
12173 				/* Found it. */
12174 				break;
12175 			}
12176 			ipfp = &ipf->ipf_hash_next;
12177 			continue;
12178 		}
12179 
12180 		/*
12181 		 * If we pruned the list, do we want to store this new
12182 		 * fragment?. We apply an optimization here based on the
12183 		 * fact that most fragments will be received in order.
12184 		 * So if the offset of this incoming fragment is zero,
12185 		 * it is the first fragment of a new packet. We will
12186 		 * keep it.  Otherwise drop the fragment, as we have
12187 		 * probably pruned the packet already (since the
12188 		 * packet cannot be found).
12189 		 */
12190 		if (pruned && offset != 0) {
12191 			mutex_exit(&ipfb->ipfb_lock);
12192 			freemsg(mp);
12193 			return (B_FALSE);
12194 		}
12195 
12196 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12197 			/*
12198 			 * Too many fragmented packets in this hash
12199 			 * bucket. Free the oldest.
12200 			 */
12201 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12202 		}
12203 
12204 		/* New guy.  Allocate a frag message. */
12205 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12206 		if (mp1 == NULL) {
12207 			BUMP_MIB(&ip_mib, ipInDiscards);
12208 			freemsg(mp);
12209 reass_done:
12210 			mutex_exit(&ipfb->ipfb_lock);
12211 			return (B_FALSE);
12212 		}
12213 
12214 
12215 		BUMP_MIB(&ip_mib, ipReasmReqds);
12216 		mp1->b_cont = mp;
12217 
12218 		/* Initialize the fragment header. */
12219 		ipf = (ipf_t *)mp1->b_rptr;
12220 		ipf->ipf_mp = mp1;
12221 		ipf->ipf_ptphn = ipfp;
12222 		ipfp[0] = ipf;
12223 		ipf->ipf_hash_next = NULL;
12224 		ipf->ipf_ident = ident;
12225 		ipf->ipf_protocol = proto;
12226 		ipf->ipf_src = src;
12227 		ipf->ipf_dst = dst;
12228 		ipf->ipf_nf_hdr_len = 0;
12229 		/* Record reassembly start time. */
12230 		ipf->ipf_timestamp = gethrestime_sec();
12231 		/* Record ipf generation and account for frag header */
12232 		ipf->ipf_gen = ill->ill_ipf_gen++;
12233 		ipf->ipf_count = MBLKSIZE(mp1);
12234 		ipf->ipf_last_frag_seen = B_FALSE;
12235 		ipf->ipf_ecn = ecn_info;
12236 		ipf->ipf_num_dups = 0;
12237 		ipfb->ipfb_frag_pkts++;
12238 		ipf->ipf_checksum = 0;
12239 		ipf->ipf_checksum_flags = 0;
12240 
12241 		/* Store checksum value in fragment header */
12242 		if (sum_flags != 0) {
12243 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12244 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12245 			ipf->ipf_checksum = sum_val;
12246 			ipf->ipf_checksum_flags = sum_flags;
12247 		}
12248 
12249 		/*
12250 		 * We handle reassembly two ways.  In the easy case,
12251 		 * where all the fragments show up in order, we do
12252 		 * minimal bookkeeping, and just clip new pieces on
12253 		 * the end.  If we ever see a hole, then we go off
12254 		 * to ip_reassemble which has to mark the pieces and
12255 		 * keep track of the number of holes, etc.  Obviously,
12256 		 * the point of having both mechanisms is so we can
12257 		 * handle the easy case as efficiently as possible.
12258 		 */
12259 		if (offset == 0) {
12260 			/* Easy case, in-order reassembly so far. */
12261 			ipf->ipf_count += msg_len;
12262 			ipf->ipf_tail_mp = tail_mp;
12263 			/*
12264 			 * Keep track of next expected offset in
12265 			 * ipf_end.
12266 			 */
12267 			ipf->ipf_end = end;
12268 			ipf->ipf_nf_hdr_len = hdr_length;
12269 		} else {
12270 			/* Hard case, hole at the beginning. */
12271 			ipf->ipf_tail_mp = NULL;
12272 			/*
12273 			 * ipf_end == 0 means that we have given up
12274 			 * on easy reassembly.
12275 			 */
12276 			ipf->ipf_end = 0;
12277 
12278 			/* Forget checksum offload from now on */
12279 			ipf->ipf_checksum_flags = 0;
12280 
12281 			/*
12282 			 * ipf_hole_cnt is set by ip_reassemble.
12283 			 * ipf_count is updated by ip_reassemble.
12284 			 * No need to check for return value here
12285 			 * as we don't expect reassembly to complete
12286 			 * or fail for the first fragment itself.
12287 			 */
12288 			(void) ip_reassemble(mp, ipf,
12289 			    (frag_offset_flags & IPH_OFFSET) << 3,
12290 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12291 		}
12292 		/* Update per ipfb and ill byte counts */
12293 		ipfb->ipfb_count += ipf->ipf_count;
12294 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12295 		ill->ill_frag_count += ipf->ipf_count;
12296 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12297 		/* If the frag timer wasn't already going, start it. */
12298 		mutex_enter(&ill->ill_lock);
12299 		ill_frag_timer_start(ill);
12300 		mutex_exit(&ill->ill_lock);
12301 		goto reass_done;
12302 	}
12303 
12304 	/*
12305 	 * If the packet's flag has changed (it could be coming up
12306 	 * from an interface different than the previous, therefore
12307 	 * possibly different checksum capability), then forget about
12308 	 * any stored checksum states.  Otherwise add the value to
12309 	 * the existing one stored in the fragment header.
12310 	 */
12311 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12312 		sum_val += ipf->ipf_checksum;
12313 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12314 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12315 		ipf->ipf_checksum = sum_val;
12316 	} else if (ipf->ipf_checksum_flags != 0) {
12317 		/* Forget checksum offload from now on */
12318 		ipf->ipf_checksum_flags = 0;
12319 	}
12320 
12321 	/*
12322 	 * We have a new piece of a datagram which is already being
12323 	 * reassembled.  Update the ECN info if all IP fragments
12324 	 * are ECN capable.  If there is one which is not, clear
12325 	 * all the info.  If there is at least one which has CE
12326 	 * code point, IP needs to report that up to transport.
12327 	 */
12328 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12329 		if (ecn_info == IPH_ECN_CE)
12330 			ipf->ipf_ecn = IPH_ECN_CE;
12331 	} else {
12332 		ipf->ipf_ecn = IPH_ECN_NECT;
12333 	}
12334 	if (offset && ipf->ipf_end == offset) {
12335 		/* The new fragment fits at the end */
12336 		ipf->ipf_tail_mp->b_cont = mp;
12337 		/* Update the byte count */
12338 		ipf->ipf_count += msg_len;
12339 		/* Update per ipfb and ill byte counts */
12340 		ipfb->ipfb_count += msg_len;
12341 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12342 		ill->ill_frag_count += msg_len;
12343 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12344 		if (frag_offset_flags & IPH_MF) {
12345 			/* More to come. */
12346 			ipf->ipf_end = end;
12347 			ipf->ipf_tail_mp = tail_mp;
12348 			goto reass_done;
12349 		}
12350 	} else {
12351 		/* Go do the hard cases. */
12352 		int ret;
12353 
12354 		if (offset == 0)
12355 			ipf->ipf_nf_hdr_len = hdr_length;
12356 
12357 		/* Save current byte count */
12358 		count = ipf->ipf_count;
12359 		ret = ip_reassemble(mp, ipf,
12360 		    (frag_offset_flags & IPH_OFFSET) << 3,
12361 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12362 		/* Count of bytes added and subtracted (freeb()ed) */
12363 		count = ipf->ipf_count - count;
12364 		if (count) {
12365 			/* Update per ipfb and ill byte counts */
12366 			ipfb->ipfb_count += count;
12367 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12368 			ill->ill_frag_count += count;
12369 			ASSERT(ill->ill_frag_count > 0);
12370 		}
12371 		if (ret == IP_REASS_PARTIAL) {
12372 			goto reass_done;
12373 		} else if (ret == IP_REASS_FAILED) {
12374 			/* Reassembly failed. Free up all resources */
12375 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12376 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12377 				IP_REASS_SET_START(t_mp, 0);
12378 				IP_REASS_SET_END(t_mp, 0);
12379 			}
12380 			freemsg(mp);
12381 			goto reass_done;
12382 		}
12383 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12384 	}
12385 	/*
12386 	 * We have completed reassembly.  Unhook the frag header from
12387 	 * the reassembly list.
12388 	 *
12389 	 * Before we free the frag header, record the ECN info
12390 	 * to report back to the transport.
12391 	 */
12392 	ecn_info = ipf->ipf_ecn;
12393 	BUMP_MIB(&ip_mib, ipReasmOKs);
12394 	ipfp = ipf->ipf_ptphn;
12395 
12396 	/* We need to supply these to caller */
12397 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12398 		sum_val = ipf->ipf_checksum;
12399 	else
12400 		sum_val = 0;
12401 
12402 	mp1 = ipf->ipf_mp;
12403 	count = ipf->ipf_count;
12404 	ipf = ipf->ipf_hash_next;
12405 	if (ipf != NULL)
12406 		ipf->ipf_ptphn = ipfp;
12407 	ipfp[0] = ipf;
12408 	ill->ill_frag_count -= count;
12409 	ASSERT(ipfb->ipfb_count >= count);
12410 	ipfb->ipfb_count -= count;
12411 	ipfb->ipfb_frag_pkts--;
12412 	mutex_exit(&ipfb->ipfb_lock);
12413 	/* Ditch the frag header. */
12414 	mp = mp1->b_cont;
12415 
12416 	freeb(mp1);
12417 
12418 	/* Restore original IP length in header. */
12419 	packet_size = (uint32_t)msgdsize(mp);
12420 	if (packet_size > IP_MAXPACKET) {
12421 		freemsg(mp);
12422 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12423 		return (B_FALSE);
12424 	}
12425 
12426 	if (DB_REF(mp) > 1) {
12427 		mblk_t *mp2 = copymsg(mp);
12428 
12429 		freemsg(mp);
12430 		if (mp2 == NULL) {
12431 			BUMP_MIB(&ip_mib, ipInDiscards);
12432 			return (B_FALSE);
12433 		}
12434 		mp = mp2;
12435 	}
12436 	ipha = (ipha_t *)mp->b_rptr;
12437 
12438 	ipha->ipha_length = htons((uint16_t)packet_size);
12439 	/* We're now complete, zip the frag state */
12440 	ipha->ipha_fragment_offset_and_flags = 0;
12441 	/* Record the ECN info. */
12442 	ipha->ipha_type_of_service &= 0xFC;
12443 	ipha->ipha_type_of_service |= ecn_info;
12444 	*mpp = mp;
12445 
12446 	/* Reassembly is successful; return checksum information if needed */
12447 	if (cksum_val != NULL)
12448 		*cksum_val = sum_val;
12449 	if (cksum_flags != NULL)
12450 		*cksum_flags = sum_flags;
12451 
12452 	return (B_TRUE);
12453 }
12454 
12455 /*
12456  * Perform ip header check sum update local options.
12457  * return B_TRUE if all is well, else return B_FALSE and release
12458  * the mp. caller is responsible for decrementing ire ref cnt.
12459  */
12460 static boolean_t
12461 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12462 {
12463 	mblk_t		*first_mp;
12464 	boolean_t	mctl_present;
12465 	uint16_t	sum;
12466 
12467 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12468 	/*
12469 	 * Don't do the checksum if it has gone through AH/ESP
12470 	 * processing.
12471 	 */
12472 	if (!mctl_present) {
12473 		sum = ip_csum_hdr(ipha);
12474 		if (sum != 0) {
12475 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12476 			freemsg(first_mp);
12477 			return (B_FALSE);
12478 		}
12479 	}
12480 
12481 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12482 		if (mctl_present)
12483 			freeb(first_mp);
12484 		return (B_FALSE);
12485 	}
12486 
12487 	return (B_TRUE);
12488 }
12489 
12490 /*
12491  * All udp packet are delivered to the local host via this routine.
12492  */
12493 void
12494 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12495     ill_t *recv_ill)
12496 {
12497 	uint32_t	sum;
12498 	uint32_t	u1;
12499 	boolean_t	mctl_present;
12500 	conn_t		*connp;
12501 	mblk_t		*first_mp;
12502 	uint16_t	*up;
12503 	ill_t		*ill = (ill_t *)q->q_ptr;
12504 	uint16_t	reass_hck_flags = 0;
12505 
12506 #define	rptr    ((uchar_t *)ipha)
12507 
12508 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12509 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12510 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12511 
12512 	/*
12513 	 * FAST PATH for udp packets
12514 	 */
12515 
12516 	/* u1 is # words of IP options */
12517 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12518 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12519 
12520 	/* IP options present */
12521 	if (u1 != 0)
12522 		goto ipoptions;
12523 
12524 	/* Check the IP header checksum.  */
12525 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12526 		/* Clear the IP header h/w cksum flag */
12527 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12528 	} else {
12529 #define	uph	((uint16_t *)ipha)
12530 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12531 		    uph[6] + uph[7] + uph[8] + uph[9];
12532 #undef	uph
12533 		/* finish doing IP checksum */
12534 		sum = (sum & 0xFFFF) + (sum >> 16);
12535 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12536 		/*
12537 		 * Don't verify header checksum if this packet is coming
12538 		 * back from AH/ESP as we already did it.
12539 		 */
12540 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12541 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12542 			freemsg(first_mp);
12543 			return;
12544 		}
12545 	}
12546 
12547 	/*
12548 	 * Count for SNMP of inbound packets for ire.
12549 	 * if mctl is present this might be a secure packet and
12550 	 * has already been counted for in ip_proto_input().
12551 	 */
12552 	if (!mctl_present) {
12553 		UPDATE_IB_PKT_COUNT(ire);
12554 		ire->ire_last_used_time = lbolt;
12555 	}
12556 
12557 	/* packet part of fragmented IP packet? */
12558 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12559 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12560 		goto fragmented;
12561 	}
12562 
12563 	/* u1 = IP header length (20 bytes) */
12564 	u1 = IP_SIMPLE_HDR_LENGTH;
12565 
12566 	/* packet does not contain complete IP & UDP headers */
12567 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12568 		goto udppullup;
12569 
12570 	/* up points to UDP header */
12571 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12572 #define	iphs    ((uint16_t *)ipha)
12573 
12574 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12575 	if (up[3] != 0) {
12576 		mblk_t *mp1 = mp->b_cont;
12577 		boolean_t cksum_err;
12578 		uint16_t hck_flags = 0;
12579 
12580 		/* Pseudo-header checksum */
12581 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12582 		    iphs[9] + up[2];
12583 
12584 		/*
12585 		 * Revert to software checksum calculation if the interface
12586 		 * isn't capable of checksum offload or if IPsec is present.
12587 		 */
12588 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12589 			hck_flags = DB_CKSUMFLAGS(mp);
12590 
12591 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12592 			IP_STAT(ip_in_sw_cksum);
12593 
12594 		IP_CKSUM_RECV(hck_flags, u1,
12595 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12596 		    (int32_t)((uchar_t *)up - rptr),
12597 		    mp, mp1, cksum_err);
12598 
12599 		if (cksum_err) {
12600 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12601 
12602 			if (hck_flags & HCK_FULLCKSUM)
12603 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12604 			else if (hck_flags & HCK_PARTIALCKSUM)
12605 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12606 			else
12607 				IP_STAT(ip_udp_in_sw_cksum_err);
12608 
12609 			freemsg(first_mp);
12610 			return;
12611 		}
12612 	}
12613 
12614 	/* Non-fragmented broadcast or multicast packet? */
12615 	if (ire->ire_type == IRE_BROADCAST)
12616 		goto udpslowpath;
12617 
12618 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12619 	    ire->ire_zoneid)) != NULL) {
12620 		ASSERT(connp->conn_upq != NULL);
12621 		IP_STAT(ip_udp_fast_path);
12622 
12623 		if (CONN_UDP_FLOWCTLD(connp)) {
12624 			freemsg(mp);
12625 			BUMP_MIB(&ip_mib, udpInOverflows);
12626 		} else {
12627 			if (!mctl_present) {
12628 				BUMP_MIB(&ip_mib, ipInDelivers);
12629 			}
12630 			/*
12631 			 * mp and first_mp can change.
12632 			 */
12633 			if (ip_udp_check(q, connp, recv_ill,
12634 			    ipha, &mp, &first_mp, mctl_present)) {
12635 				/* Send it upstream */
12636 				CONN_UDP_RECV(connp, mp);
12637 			}
12638 		}
12639 		/*
12640 		 * freeb() cannot deal with null mblk being passed
12641 		 * in and first_mp can be set to null in the call
12642 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12643 		 */
12644 		if (mctl_present && first_mp != NULL) {
12645 			freeb(first_mp);
12646 		}
12647 		CONN_DEC_REF(connp);
12648 		return;
12649 	}
12650 
12651 	/*
12652 	 * if we got here we know the packet is not fragmented and
12653 	 * has no options. The classifier could not find a conn_t and
12654 	 * most likely its an icmp packet so send it through slow path.
12655 	 */
12656 
12657 	goto udpslowpath;
12658 
12659 ipoptions:
12660 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12661 		goto slow_done;
12662 	}
12663 
12664 	UPDATE_IB_PKT_COUNT(ire);
12665 	ire->ire_last_used_time = lbolt;
12666 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12667 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12668 fragmented:
12669 		/*
12670 		 * "sum" and "reass_hck_flags" are non-zero if the
12671 		 * reassembled packet has a valid hardware computed
12672 		 * checksum information associated with it.
12673 		 */
12674 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12675 			goto slow_done;
12676 		/*
12677 		 * Make sure that first_mp points back to mp as
12678 		 * the mp we came in with could have changed in
12679 		 * ip_rput_fragment().
12680 		 */
12681 		ASSERT(!mctl_present);
12682 		ipha = (ipha_t *)mp->b_rptr;
12683 		first_mp = mp;
12684 	}
12685 
12686 	/* Now we have a complete datagram, destined for this machine. */
12687 	u1 = IPH_HDR_LENGTH(ipha);
12688 	/* Pull up the UDP header, if necessary. */
12689 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12690 udppullup:
12691 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12692 			BUMP_MIB(&ip_mib, ipInDiscards);
12693 			freemsg(first_mp);
12694 			goto slow_done;
12695 		}
12696 		ipha = (ipha_t *)mp->b_rptr;
12697 	}
12698 
12699 	/*
12700 	 * Validate the checksum for the reassembled packet; for the
12701 	 * pullup case we calculate the payload checksum in software.
12702 	 */
12703 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12704 	if (up[3] != 0) {
12705 		boolean_t cksum_err;
12706 
12707 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12708 			IP_STAT(ip_in_sw_cksum);
12709 
12710 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12711 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12712 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12713 		    iphs[9] + up[2], sum, cksum_err);
12714 
12715 		if (cksum_err) {
12716 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12717 
12718 			if (reass_hck_flags & HCK_FULLCKSUM)
12719 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12720 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12721 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12722 			else
12723 				IP_STAT(ip_udp_in_sw_cksum_err);
12724 
12725 			freemsg(first_mp);
12726 			goto slow_done;
12727 		}
12728 	}
12729 udpslowpath:
12730 
12731 	/* Clear hardware checksum flag to be safe */
12732 	DB_CKSUMFLAGS(mp) = 0;
12733 
12734 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12735 	    (ire->ire_type == IRE_BROADCAST),
12736 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12737 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12738 
12739 slow_done:
12740 	IP_STAT(ip_udp_slow_path);
12741 	return;
12742 
12743 #undef  iphs
12744 #undef  rptr
12745 }
12746 
12747 /* ARGSUSED */
12748 static mblk_t *
12749 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12750     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12751     ill_rx_ring_t *ill_ring)
12752 {
12753 	conn_t		*connp;
12754 	uint32_t	sum;
12755 	uint32_t	u1;
12756 	uint16_t	*up;
12757 	int		offset;
12758 	ssize_t		len;
12759 	mblk_t		*mp1;
12760 	boolean_t	syn_present = B_FALSE;
12761 	tcph_t		*tcph;
12762 	uint_t		ip_hdr_len;
12763 	ill_t		*ill = (ill_t *)q->q_ptr;
12764 	zoneid_t	zoneid = ire->ire_zoneid;
12765 	boolean_t	cksum_err;
12766 	uint16_t	hck_flags = 0;
12767 
12768 #define	rptr	((uchar_t *)ipha)
12769 
12770 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12771 
12772 	/*
12773 	 * FAST PATH for tcp packets
12774 	 */
12775 
12776 	/* u1 is # words of IP options */
12777 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12778 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12779 
12780 	/* IP options present */
12781 	if (u1) {
12782 		goto ipoptions;
12783 	} else {
12784 		/* Check the IP header checksum.  */
12785 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12786 			/* Clear the IP header h/w cksum flag */
12787 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12788 		} else {
12789 #define	uph	((uint16_t *)ipha)
12790 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12791 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12792 #undef	uph
12793 			/* finish doing IP checksum */
12794 			sum = (sum & 0xFFFF) + (sum >> 16);
12795 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12796 			/*
12797 			 * Don't verify header checksum if this packet
12798 			 * is coming back from AH/ESP as we already did it.
12799 			 */
12800 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12801 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12802 				goto error;
12803 			}
12804 		}
12805 	}
12806 
12807 	if (!mctl_present) {
12808 		UPDATE_IB_PKT_COUNT(ire);
12809 		ire->ire_last_used_time = lbolt;
12810 	}
12811 
12812 	/* packet part of fragmented IP packet? */
12813 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12814 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12815 		goto fragmented;
12816 	}
12817 
12818 	/* u1 = IP header length (20 bytes) */
12819 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12820 
12821 	/* does packet contain IP+TCP headers? */
12822 	len = mp->b_wptr - rptr;
12823 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12824 		IP_STAT(ip_tcppullup);
12825 		goto tcppullup;
12826 	}
12827 
12828 	/* TCP options present? */
12829 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12830 
12831 	/*
12832 	 * If options need to be pulled up, then goto tcpoptions.
12833 	 * otherwise we are still in the fast path
12834 	 */
12835 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12836 		IP_STAT(ip_tcpoptions);
12837 		goto tcpoptions;
12838 	}
12839 
12840 	/* multiple mblks of tcp data? */
12841 	if ((mp1 = mp->b_cont) != NULL) {
12842 		/* more then two? */
12843 		if (mp1->b_cont != NULL) {
12844 			IP_STAT(ip_multipkttcp);
12845 			goto multipkttcp;
12846 		}
12847 		len += mp1->b_wptr - mp1->b_rptr;
12848 	}
12849 
12850 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12851 
12852 	/* part of pseudo checksum */
12853 
12854 	/* TCP datagram length */
12855 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12856 
12857 #define	iphs    ((uint16_t *)ipha)
12858 
12859 #ifdef	_BIG_ENDIAN
12860 	u1 += IPPROTO_TCP;
12861 #else
12862 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12863 #endif
12864 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12865 
12866 	/*
12867 	 * Revert to software checksum calculation if the interface
12868 	 * isn't capable of checksum offload or if IPsec is present.
12869 	 */
12870 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12871 		hck_flags = DB_CKSUMFLAGS(mp);
12872 
12873 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12874 		IP_STAT(ip_in_sw_cksum);
12875 
12876 	IP_CKSUM_RECV(hck_flags, u1,
12877 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12878 	    (int32_t)((uchar_t *)up - rptr),
12879 	    mp, mp1, cksum_err);
12880 
12881 	if (cksum_err) {
12882 		BUMP_MIB(&ip_mib, tcpInErrs);
12883 
12884 		if (hck_flags & HCK_FULLCKSUM)
12885 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12886 		else if (hck_flags & HCK_PARTIALCKSUM)
12887 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12888 		else
12889 			IP_STAT(ip_tcp_in_sw_cksum_err);
12890 
12891 		goto error;
12892 	}
12893 
12894 try_again:
12895 
12896 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12897 	    NULL) {
12898 		/* Send the TH_RST */
12899 		goto no_conn;
12900 	}
12901 
12902 	/*
12903 	 * TCP FAST PATH for AF_INET socket.
12904 	 *
12905 	 * TCP fast path to avoid extra work. An AF_INET socket type
12906 	 * does not have facility to receive extra information via
12907 	 * ip_process or ip_add_info. Also, when the connection was
12908 	 * established, we made a check if this connection is impacted
12909 	 * by any global IPSec policy or per connection policy (a
12910 	 * policy that comes in effect later will not apply to this
12911 	 * connection). Since all this can be determined at the
12912 	 * connection establishment time, a quick check of flags
12913 	 * can avoid extra work.
12914 	 */
12915 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12916 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12917 		ASSERT(first_mp == mp);
12918 		SET_SQUEUE(mp, tcp_rput_data, connp);
12919 		return (mp);
12920 	}
12921 
12922 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12923 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12924 		if (IPCL_IS_TCP(connp)) {
12925 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12926 			DB_CKSUMSTART(mp) =
12927 			    (intptr_t)ip_squeue_get(ill_ring);
12928 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12929 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12930 				SET_SQUEUE(mp, connp->conn_recv, connp);
12931 				return (mp);
12932 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12933 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12934 				ip_squeue_enter_unbound++;
12935 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12936 				    connp);
12937 				return (mp);
12938 			}
12939 			syn_present = B_TRUE;
12940 		}
12941 
12942 	}
12943 
12944 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12945 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12946 
12947 		/* No need to send this packet to TCP */
12948 		if ((flags & TH_RST) || (flags & TH_URG)) {
12949 			CONN_DEC_REF(connp);
12950 			freemsg(first_mp);
12951 			return (NULL);
12952 		}
12953 		if (flags & TH_ACK) {
12954 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12955 			CONN_DEC_REF(connp);
12956 			return (NULL);
12957 		}
12958 
12959 		CONN_DEC_REF(connp);
12960 		freemsg(first_mp);
12961 		return (NULL);
12962 	}
12963 
12964 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12965 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12966 		    ipha, NULL, mctl_present);
12967 		if (first_mp == NULL) {
12968 			CONN_DEC_REF(connp);
12969 			return (NULL);
12970 		}
12971 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12972 			ASSERT(syn_present);
12973 			if (mctl_present) {
12974 				ASSERT(first_mp != mp);
12975 				first_mp->b_datap->db_struioflag |=
12976 				    STRUIO_POLICY;
12977 			} else {
12978 				ASSERT(first_mp == mp);
12979 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12980 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12981 			}
12982 		} else {
12983 			/*
12984 			 * Discard first_mp early since we're dealing with a
12985 			 * fully-connected conn_t and tcp doesn't do policy in
12986 			 * this case.
12987 			 */
12988 			if (mctl_present) {
12989 				freeb(first_mp);
12990 				mctl_present = B_FALSE;
12991 			}
12992 			first_mp = mp;
12993 		}
12994 	}
12995 
12996 	/* Initiate IPPF processing for fastpath */
12997 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12998 		uint32_t	ill_index;
12999 
13000 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13001 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13002 		if (mp == NULL) {
13003 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13004 			    "deferred/dropped during IPPF processing\n"));
13005 			CONN_DEC_REF(connp);
13006 			if (mctl_present)
13007 				freeb(first_mp);
13008 			return (NULL);
13009 		} else if (mctl_present) {
13010 			/*
13011 			 * ip_process might return a new mp.
13012 			 */
13013 			ASSERT(first_mp != mp);
13014 			first_mp->b_cont = mp;
13015 		} else {
13016 			first_mp = mp;
13017 		}
13018 
13019 	}
13020 
13021 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
13022 		mp = ip_add_info(mp, recv_ill, flags);
13023 		if (mp == NULL) {
13024 			CONN_DEC_REF(connp);
13025 			if (mctl_present)
13026 				freeb(first_mp);
13027 			return (NULL);
13028 		} else if (mctl_present) {
13029 			/*
13030 			 * ip_add_info might return a new mp.
13031 			 */
13032 			ASSERT(first_mp != mp);
13033 			first_mp->b_cont = mp;
13034 		} else {
13035 			first_mp = mp;
13036 		}
13037 	}
13038 
13039 	if (IPCL_IS_TCP(connp)) {
13040 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13041 		return (first_mp);
13042 	} else {
13043 		putnext(connp->conn_rq, first_mp);
13044 		CONN_DEC_REF(connp);
13045 		return (NULL);
13046 	}
13047 
13048 no_conn:
13049 	/* Initiate IPPf processing, if needed. */
13050 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13051 		uint32_t ill_index;
13052 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13053 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13054 		if (first_mp == NULL) {
13055 			return (NULL);
13056 		}
13057 	}
13058 	BUMP_MIB(&ip_mib, ipInDelivers);
13059 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13060 	return (NULL);
13061 ipoptions:
13062 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13063 		goto slow_done;
13064 	}
13065 
13066 	UPDATE_IB_PKT_COUNT(ire);
13067 	ire->ire_last_used_time = lbolt;
13068 
13069 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13070 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13071 fragmented:
13072 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13073 			if (mctl_present)
13074 				freeb(first_mp);
13075 			goto slow_done;
13076 		}
13077 		/*
13078 		 * Make sure that first_mp points back to mp as
13079 		 * the mp we came in with could have changed in
13080 		 * ip_rput_fragment().
13081 		 */
13082 		ASSERT(!mctl_present);
13083 		ipha = (ipha_t *)mp->b_rptr;
13084 		first_mp = mp;
13085 	}
13086 
13087 	/* Now we have a complete datagram, destined for this machine. */
13088 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13089 
13090 	len = mp->b_wptr - mp->b_rptr;
13091 	/* Pull up a minimal TCP header, if necessary. */
13092 	if (len < (u1 + 20)) {
13093 tcppullup:
13094 		if (!pullupmsg(mp, u1 + 20)) {
13095 			BUMP_MIB(&ip_mib, ipInDiscards);
13096 			goto error;
13097 		}
13098 		ipha = (ipha_t *)mp->b_rptr;
13099 		len = mp->b_wptr - mp->b_rptr;
13100 	}
13101 
13102 	/*
13103 	 * Extract the offset field from the TCP header.  As usual, we
13104 	 * try to help the compiler more than the reader.
13105 	 */
13106 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13107 	if (offset != 5) {
13108 tcpoptions:
13109 		if (offset < 5) {
13110 			BUMP_MIB(&ip_mib, ipInDiscards);
13111 			goto error;
13112 		}
13113 		/*
13114 		 * There must be TCP options.
13115 		 * Make sure we can grab them.
13116 		 */
13117 		offset <<= 2;
13118 		offset += u1;
13119 		if (len < offset) {
13120 			if (!pullupmsg(mp, offset)) {
13121 				BUMP_MIB(&ip_mib, ipInDiscards);
13122 				goto error;
13123 			}
13124 			ipha = (ipha_t *)mp->b_rptr;
13125 			len = mp->b_wptr - rptr;
13126 		}
13127 	}
13128 
13129 	/* Get the total packet length in len, including headers. */
13130 	if (mp->b_cont) {
13131 multipkttcp:
13132 		len = msgdsize(mp);
13133 	}
13134 
13135 	/*
13136 	 * Check the TCP checksum by pulling together the pseudo-
13137 	 * header checksum, and passing it to ip_csum to be added in
13138 	 * with the TCP datagram.
13139 	 *
13140 	 * Since we are not using the hwcksum if available we must
13141 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13142 	 * If either of these fails along the way the mblk is freed.
13143 	 * If this logic ever changes and mblk is reused to say send
13144 	 * ICMP's back, then this flag may need to be cleared in
13145 	 * other places as well.
13146 	 */
13147 	DB_CKSUMFLAGS(mp) = 0;
13148 
13149 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13150 
13151 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13152 #ifdef	_BIG_ENDIAN
13153 	u1 += IPPROTO_TCP;
13154 #else
13155 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13156 #endif
13157 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13158 	/*
13159 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13160 	 */
13161 	IP_STAT(ip_in_sw_cksum);
13162 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13163 		BUMP_MIB(&ip_mib, tcpInErrs);
13164 		goto error;
13165 	}
13166 
13167 	IP_STAT(ip_tcp_slow_path);
13168 	goto try_again;
13169 #undef  iphs
13170 #undef  rptr
13171 
13172 error:
13173 	freemsg(first_mp);
13174 slow_done:
13175 	return (NULL);
13176 }
13177 
13178 /* ARGSUSED */
13179 static void
13180 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13181     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13182 {
13183 	conn_t		*connp;
13184 	uint32_t	sum;
13185 	uint32_t	u1;
13186 	ssize_t		len;
13187 	sctp_hdr_t	*sctph;
13188 	zoneid_t	zoneid = ire->ire_zoneid;
13189 	uint32_t	pktsum;
13190 	uint32_t	calcsum;
13191 	uint32_t	ports;
13192 	uint_t		ipif_seqid;
13193 	in6_addr_t	map_src, map_dst;
13194 	ill_t		*ill = (ill_t *)q->q_ptr;
13195 
13196 #define	rptr	((uchar_t *)ipha)
13197 
13198 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13199 
13200 	/* u1 is # words of IP options */
13201 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13202 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13203 
13204 	/* IP options present */
13205 	if (u1 > 0) {
13206 		goto ipoptions;
13207 	} else {
13208 		/* Check the IP header checksum.  */
13209 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13210 #define	uph	((uint16_t *)ipha)
13211 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13212 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13213 #undef	uph
13214 			/* finish doing IP checksum */
13215 			sum = (sum & 0xFFFF) + (sum >> 16);
13216 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13217 			/*
13218 			 * Don't verify header checksum if this packet
13219 			 * is coming back from AH/ESP as we already did it.
13220 			 */
13221 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13222 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13223 				goto error;
13224 			}
13225 		}
13226 		/*
13227 		 * Since there is no SCTP h/w cksum support yet, just
13228 		 * clear the flag.
13229 		 */
13230 		DB_CKSUMFLAGS(mp) = 0;
13231 	}
13232 
13233 	/*
13234 	 * Don't verify header checksum if this packet is coming
13235 	 * back from AH/ESP as we already did it.
13236 	 */
13237 	if (!mctl_present) {
13238 		UPDATE_IB_PKT_COUNT(ire);
13239 		ire->ire_last_used_time = lbolt;
13240 	}
13241 
13242 	/* packet part of fragmented IP packet? */
13243 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13244 	if (u1 & (IPH_MF | IPH_OFFSET))
13245 		goto fragmented;
13246 
13247 	/* u1 = IP header length (20 bytes) */
13248 	u1 = IP_SIMPLE_HDR_LENGTH;
13249 
13250 find_sctp_client:
13251 	/* Pullup if we don't have the sctp common header. */
13252 	len = MBLKL(mp);
13253 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13254 		if (mp->b_cont == NULL ||
13255 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13256 			BUMP_MIB(&ip_mib, ipInDiscards);
13257 			goto error;
13258 		}
13259 		ipha = (ipha_t *)mp->b_rptr;
13260 		len = MBLKL(mp);
13261 	}
13262 
13263 	sctph = (sctp_hdr_t *)(rptr + u1);
13264 #ifdef	DEBUG
13265 	if (!skip_sctp_cksum) {
13266 #endif
13267 		pktsum = sctph->sh_chksum;
13268 		sctph->sh_chksum = 0;
13269 		calcsum = sctp_cksum(mp, u1);
13270 		if (calcsum != pktsum) {
13271 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13272 			goto error;
13273 		}
13274 		sctph->sh_chksum = pktsum;
13275 #ifdef	DEBUG	/* skip_sctp_cksum */
13276 	}
13277 #endif
13278 	/* get the ports */
13279 	ports = *(uint32_t *)&sctph->sh_sport;
13280 
13281 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13282 	IRE_REFRELE(ire);
13283 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13284 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13285 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13286 	    mp)) == NULL) {
13287 		/* Check for raw socket or OOTB handling */
13288 		goto no_conn;
13289 	}
13290 
13291 	/* Found a client; up it goes */
13292 	BUMP_MIB(&ip_mib, ipInDelivers);
13293 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13294 	return;
13295 
13296 no_conn:
13297 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13298 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13299 	return;
13300 
13301 ipoptions:
13302 	DB_CKSUMFLAGS(mp) = 0;
13303 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13304 		goto slow_done;
13305 
13306 	UPDATE_IB_PKT_COUNT(ire);
13307 	ire->ire_last_used_time = lbolt;
13308 
13309 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13310 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13311 fragmented:
13312 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13313 			goto slow_done;
13314 		/*
13315 		 * Make sure that first_mp points back to mp as
13316 		 * the mp we came in with could have changed in
13317 		 * ip_rput_fragment().
13318 		 */
13319 		ASSERT(!mctl_present);
13320 		ipha = (ipha_t *)mp->b_rptr;
13321 		first_mp = mp;
13322 	}
13323 
13324 	/* Now we have a complete datagram, destined for this machine. */
13325 	u1 = IPH_HDR_LENGTH(ipha);
13326 	goto find_sctp_client;
13327 #undef  iphs
13328 #undef  rptr
13329 
13330 error:
13331 	freemsg(first_mp);
13332 slow_done:
13333 	IRE_REFRELE(ire);
13334 }
13335 
13336 #define	VER_BITS	0xF0
13337 #define	VERSION_6	0x60
13338 
13339 static boolean_t
13340 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13341     ipaddr_t *dstp)
13342 {
13343 	uint_t	opt_len;
13344 	ipha_t *ipha;
13345 	ssize_t len;
13346 	uint_t	pkt_len;
13347 
13348 	IP_STAT(ip_ipoptions);
13349 	ipha = *iphapp;
13350 
13351 #define	rptr    ((uchar_t *)ipha)
13352 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13353 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13354 		BUMP_MIB(&ip_mib, ipInIPv6);
13355 		freemsg(mp);
13356 		return (B_FALSE);
13357 	}
13358 
13359 	/* multiple mblk or too short */
13360 	pkt_len = ntohs(ipha->ipha_length);
13361 
13362 	/* Get the number of words of IP options in the IP header. */
13363 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13364 	if (opt_len) {
13365 		/* IP Options present!  Validate and process. */
13366 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13367 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13368 			goto done;
13369 		}
13370 		/*
13371 		 * Recompute complete header length and make sure we
13372 		 * have access to all of it.
13373 		 */
13374 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13375 		if (len > (mp->b_wptr - rptr)) {
13376 			if (len > pkt_len) {
13377 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13378 				goto done;
13379 			}
13380 			if (!pullupmsg(mp, len)) {
13381 				BUMP_MIB(&ip_mib, ipInDiscards);
13382 				goto done;
13383 			}
13384 			ipha = (ipha_t *)mp->b_rptr;
13385 		}
13386 		/*
13387 		 * Go off to ip_rput_options which returns the next hop
13388 		 * destination address, which may have been affected
13389 		 * by source routing.
13390 		 */
13391 		IP_STAT(ip_opt);
13392 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13393 			return (B_FALSE);
13394 		}
13395 	}
13396 	*iphapp = ipha;
13397 	return (B_TRUE);
13398 done:
13399 	/* clear b_prev - used by ip_mroute_decap */
13400 	mp->b_prev = NULL;
13401 	freemsg(mp);
13402 	return (B_FALSE);
13403 #undef  rptr
13404 }
13405 
13406 /*
13407  * Deal with the fact that there is no ire for the destination.
13408  * The incoming ill (in_ill) is passed in to ip_newroute only
13409  * in the case of packets coming from mobile ip forward tunnel.
13410  * It must be null otherwise.
13411  */
13412 static ire_t *
13413 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13414     ipaddr_t dst)
13415 {
13416 	ipha_t	*ipha;
13417 	ill_t	*ill;
13418 	ire_t	*ire;
13419 	boolean_t	check_multirt = B_FALSE;
13420 
13421 	ipha = (ipha_t *)mp->b_rptr;
13422 	ill = (ill_t *)q->q_ptr;
13423 
13424 	ASSERT(ill != NULL);
13425 	/*
13426 	 * No IRE for this destination, so it can't be for us.
13427 	 * Unless we are forwarding, drop the packet.
13428 	 * We have to let source routed packets through
13429 	 * since we don't yet know if they are 'ping -l'
13430 	 * packets i.e. if they will go out over the
13431 	 * same interface as they came in on.
13432 	 */
13433 	if (ll_multicast) {
13434 		freemsg(mp);
13435 		return (NULL);
13436 	}
13437 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13438 		BUMP_MIB(&ip_mib, ipForwProhibits);
13439 		freemsg(mp);
13440 		return (NULL);
13441 	}
13442 
13443 	/*
13444 	 * Mark this packet as having originated externally.
13445 	 *
13446 	 * For non-forwarding code path, ire_send later double
13447 	 * checks this interface to see if it is still exists
13448 	 * post-ARP resolution.
13449 	 *
13450 	 * Also, IPQOS uses this to differentiate between
13451 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13452 	 * QOS packet processing in ip_wput_attach_llhdr().
13453 	 * The QoS module can mark the b_band for a fastpath message
13454 	 * or the dl_priority field in a unitdata_req header for
13455 	 * CoS marking. This info can only be found in
13456 	 * ip_wput_attach_llhdr().
13457 	 */
13458 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13459 	/*
13460 	 * Clear the indication that this may have a hardware checksum
13461 	 * as we are not using it
13462 	 */
13463 	DB_CKSUMFLAGS(mp) = 0;
13464 
13465 	if (in_ill != NULL) {
13466 		/*
13467 		 * Now hand the packet to ip_newroute.
13468 		 */
13469 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13470 		return (NULL);
13471 	}
13472 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13473 	    MBLK_GETLABEL(mp));
13474 
13475 	if (ire == NULL && check_multirt) {
13476 		/* Let ip_newroute handle CGTP  */
13477 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13478 		return (NULL);
13479 	}
13480 
13481 	if (ire != NULL)
13482 		return (ire);
13483 
13484 	mp->b_prev = mp->b_next = 0;
13485 	/* send icmp unreachable */
13486 	q = WR(q);
13487 	/* Sent by forwarding path, and router is global zone */
13488 	if (ip_source_routed(ipha)) {
13489 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13490 		    GLOBAL_ZONEID);
13491 	} else {
13492 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13493 	}
13494 
13495 	return (NULL);
13496 
13497 }
13498 
13499 /*
13500  * check ip header length and align it.
13501  */
13502 static boolean_t
13503 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13504 {
13505 	ssize_t len;
13506 	ill_t *ill;
13507 	ipha_t	*ipha;
13508 
13509 	len = MBLKL(mp);
13510 
13511 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13512 		if (!OK_32PTR(mp->b_rptr))
13513 			IP_STAT(ip_notaligned1);
13514 		else
13515 			IP_STAT(ip_notaligned2);
13516 		/* Guard against bogus device drivers */
13517 		if (len < 0) {
13518 			/* clear b_prev - used by ip_mroute_decap */
13519 			mp->b_prev = NULL;
13520 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13521 			freemsg(mp);
13522 			return (B_FALSE);
13523 		}
13524 
13525 		if (ip_rput_pullups++ == 0) {
13526 			ill = (ill_t *)q->q_ptr;
13527 			ipha = (ipha_t *)mp->b_rptr;
13528 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13529 			    "ip_check_and_align_header: %s forced us to "
13530 			    " pullup pkt, hdr len %ld, hdr addr %p",
13531 			    ill->ill_name, len, ipha);
13532 		}
13533 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13534 			/* clear b_prev - used by ip_mroute_decap */
13535 			mp->b_prev = NULL;
13536 			BUMP_MIB(&ip_mib, ipInDiscards);
13537 			freemsg(mp);
13538 			return (B_FALSE);
13539 		}
13540 	}
13541 	return (B_TRUE);
13542 }
13543 
13544 static boolean_t
13545 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13546 {
13547 	ill_group_t	*ill_group;
13548 	ill_group_t	*ire_group;
13549 	queue_t 	*q;
13550 	ill_t		*ire_ill;
13551 	uint_t		ill_ifindex;
13552 
13553 	q = *qp;
13554 	/*
13555 	 * We need to check to make sure the packet came in
13556 	 * on the queue associated with the destination IRE.
13557 	 * Note that for multicast packets and broadcast packets sent to
13558 	 * a broadcast address which is shared between multiple interfaces
13559 	 * we should not do this since we just got a random broadcast ire.
13560 	 */
13561 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13562 		boolean_t check_multi = B_TRUE;
13563 
13564 		/*
13565 		 * This packet came in on an interface other than the
13566 		 * one associated with the destination address.
13567 		 * "Gateway" it to the appropriate interface here.
13568 		 * As long as the ills belong to the same group,
13569 		 * we don't consider them to arriving on the wrong
13570 		 * interface. Thus, when the switch is doing inbound
13571 		 * load spreading, we won't drop packets when we
13572 		 * are doing strict multihoming checks. Note, the
13573 		 * same holds true for 'usesrc groups' where the
13574 		 * destination address may belong to another interface
13575 		 * to allow multipathing to happen
13576 		 */
13577 		ill_group = ill->ill_group;
13578 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13579 		ill_ifindex = ill->ill_usesrc_ifindex;
13580 		ire_group = ire_ill->ill_group;
13581 
13582 		/*
13583 		 * If it's part of the same IPMP group, or if it's a legal
13584 		 * address on the 'usesrc' interface, then bypass strict
13585 		 * checks.
13586 		 */
13587 		if (ill_group != NULL && ill_group == ire_group) {
13588 			check_multi = B_FALSE;
13589 		} else if (ill_ifindex != 0 &&
13590 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13591 			check_multi = B_FALSE;
13592 		}
13593 
13594 		if (check_multi &&
13595 		    ip_strict_dst_multihoming &&
13596 		    ((ill->ill_flags &
13597 		    ire->ire_ipif->ipif_ill->ill_flags &
13598 		    ILLF_ROUTER) == 0)) {
13599 			/* Drop packet */
13600 			BUMP_MIB(&ip_mib, ipForwProhibits);
13601 			freemsg(mp);
13602 			return (B_TRUE);
13603 		}
13604 
13605 		/*
13606 		 * Change the queue (for non-virtual destination network
13607 		 * interfaces) and ip_rput_local will be called with the right
13608 		 * queue
13609 		 */
13610 		q = ire->ire_rfq;
13611 	}
13612 	/* Must be broadcast.  We'll take it. */
13613 	*qp = q;
13614 	return (B_FALSE);
13615 }
13616 
13617 ire_t *
13618 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13619 {
13620 	ipha_t	*ipha;
13621 	ipaddr_t ip_dst, ip_src;
13622 	ire_t	*src_ire = NULL;
13623 	ill_t	*stq_ill;
13624 	uint_t	hlen;
13625 	uint32_t sum;
13626 	queue_t	*dev_q;
13627 	boolean_t check_multirt = B_FALSE;
13628 
13629 
13630 	ipha = (ipha_t *)mp->b_rptr;
13631 
13632 	/*
13633 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13634 	 * The loopback address check for both src and dst has already
13635 	 * been checked in ip_input
13636 	 */
13637 	ip_dst = ntohl(dst);
13638 	ip_src = ntohl(ipha->ipha_src);
13639 
13640 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13641 	    IN_CLASSD(ip_src)) {
13642 		BUMP_MIB(&ip_mib, ipForwProhibits);
13643 		goto drop;
13644 	}
13645 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13646 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13647 
13648 	if (src_ire != NULL) {
13649 		BUMP_MIB(&ip_mib, ipForwProhibits);
13650 		goto drop;
13651 	}
13652 
13653 	/* No ire cache of nexthop. So first create one  */
13654 	if (ire == NULL) {
13655 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13656 		/*
13657 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13658 		 * is not set. So upon return from ire_forward
13659 		 * check_multirt should remain as false.
13660 		 */
13661 		ASSERT(!check_multirt);
13662 		if (ire == NULL) {
13663 			BUMP_MIB(&ip_mib, ipInDiscards);
13664 			mp->b_prev = mp->b_next = 0;
13665 			/* send icmp unreachable */
13666 			/* Sent by forwarding path, and router is global zone */
13667 			if (ip_source_routed(ipha)) {
13668 				icmp_unreachable(ill->ill_wq, mp,
13669 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13670 			} else {
13671 				icmp_unreachable(ill->ill_wq, mp,
13672 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13673 			}
13674 			return (ire);
13675 		}
13676 	}
13677 
13678 	/*
13679 	 * Forwarding fastpath exception case:
13680 	 * If either of the follwoing case is true, we take
13681 	 * the slowpath
13682 	 *	o forwarding is not enabled
13683 	 *	o incoming and outgoing interface are the same, or the same
13684 	 *	  IPMP group
13685 	 *	o corresponding ire is in incomplete state
13686 	 *	o packet needs fragmentation
13687 	 *
13688 	 * The codeflow from here on is thus:
13689 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13690 	 */
13691 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13692 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13693 	    !(ill->ill_flags & ILLF_ROUTER) ||
13694 	    (ill == stq_ill) ||
13695 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13696 	    (ire->ire_nce == NULL) ||
13697 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13698 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13699 	    ipha->ipha_ttl <= 1) {
13700 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13701 		    ipha, ill, B_FALSE);
13702 		return (ire);
13703 	}
13704 
13705 	DTRACE_PROBE4(ip4__forwarding__start,
13706 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13707 
13708 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13709 	    ill, stq_ill, ipha, mp, mp);
13710 
13711 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13712 
13713 	if (mp == NULL)
13714 		goto drop;
13715 
13716 	mp->b_datap->db_struioun.cksum.flags = 0;
13717 	/* Adjust the checksum to reflect the ttl decrement. */
13718 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13719 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13720 	ipha->ipha_ttl--;
13721 
13722 	dev_q = ire->ire_stq->q_next;
13723 	if ((dev_q->q_next != NULL ||
13724 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13725 		goto indiscard;
13726 	}
13727 
13728 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13729 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13730 
13731 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13732 		mblk_t *mpip = mp;
13733 
13734 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13735 		if (mp != NULL) {
13736 			DTRACE_PROBE4(ip4__physical__out__start,
13737 			    ill_t *, NULL, ill_t *, stq_ill,
13738 			    ipha_t *, ipha, mblk_t *, mp);
13739 			FW_HOOKS(ip4_physical_out_event,
13740 			    ipv4firewall_physical_out,
13741 			    NULL, stq_ill, ipha, mp, mpip);
13742 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13743 			    mp);
13744 			if (mp == NULL)
13745 				goto drop;
13746 
13747 			UPDATE_IB_PKT_COUNT(ire);
13748 			ire->ire_last_used_time = lbolt;
13749 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13750 			putnext(ire->ire_stq, mp);
13751 			return (ire);
13752 		}
13753 	}
13754 
13755 indiscard:
13756 	BUMP_MIB(&ip_mib, ipInDiscards);
13757 drop:
13758 	if (mp != NULL)
13759 		freemsg(mp);
13760 	if (src_ire != NULL)
13761 		ire_refrele(src_ire);
13762 	return (ire);
13763 
13764 }
13765 
13766 /*
13767  * This function is called in the forwarding slowpath, when
13768  * either the ire lacks the link-layer address, or the packet needs
13769  * further processing(eg. fragmentation), before transmission.
13770  */
13771 
13772 static void
13773 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13774     ill_t *ill, boolean_t ll_multicast)
13775 {
13776 	ill_group_t	*ill_group;
13777 	ill_group_t	*ire_group;
13778 	queue_t		*dev_q;
13779 	ire_t		*src_ire;
13780 
13781 	ASSERT(ire->ire_stq != NULL);
13782 
13783 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13784 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13785 
13786 	if (ll_multicast != 0)
13787 		goto drop_pkt;
13788 
13789 	/*
13790 	 * check if ipha_src is a broadcast address. Note that this
13791 	 * check is redundant when we get here from ip_fast_forward()
13792 	 * which has already done this check. However, since we can
13793 	 * also get here from ip_rput_process_broadcast() or, for
13794 	 * for the slow path through ip_fast_forward(), we perform
13795 	 * the check again for code-reusability
13796 	 */
13797 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13798 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13799 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13800 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13801 		if (src_ire != NULL)
13802 			ire_refrele(src_ire);
13803 		BUMP_MIB(&ip_mib, ipForwProhibits);
13804 		ip2dbg(("ip_rput_process_forward: Received packet with"
13805 		    " bad src/dst address on %s\n", ill->ill_name));
13806 		goto drop_pkt;
13807 	}
13808 
13809 	ill_group = ill->ill_group;
13810 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13811 	/*
13812 	 * Check if we want to forward this one at this time.
13813 	 * We allow source routed packets on a host provided that
13814 	 * they go out the same interface or same interface group
13815 	 * as they came in on.
13816 	 *
13817 	 * XXX To be quicker, we may wish to not chase pointers to
13818 	 * get the ILLF_ROUTER flag and instead store the
13819 	 * forwarding policy in the ire.  An unfortunate
13820 	 * side-effect of that would be requiring an ire flush
13821 	 * whenever the ILLF_ROUTER flag changes.
13822 	 */
13823 	if (((ill->ill_flags &
13824 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13825 	    ILLF_ROUTER) == 0) &&
13826 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13827 	    (ill_group != NULL && ill_group == ire_group)))) {
13828 		BUMP_MIB(&ip_mib, ipForwProhibits);
13829 		if (ip_source_routed(ipha)) {
13830 			q = WR(q);
13831 			/*
13832 			 * Clear the indication that this may have
13833 			 * hardware checksum as we are not using it.
13834 			 */
13835 			DB_CKSUMFLAGS(mp) = 0;
13836 			/* Sent by forwarding path, and router is global zone */
13837 			icmp_unreachable(q, mp,
13838 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13839 			return;
13840 		}
13841 		goto drop_pkt;
13842 	}
13843 
13844 	/* Packet is being forwarded. Turning off hwcksum flag. */
13845 	DB_CKSUMFLAGS(mp) = 0;
13846 	if (ip_g_send_redirects) {
13847 		/*
13848 		 * Check whether the incoming interface and outgoing
13849 		 * interface is part of the same group. If so,
13850 		 * send redirects.
13851 		 *
13852 		 * Check the source address to see if it originated
13853 		 * on the same logical subnet it is going back out on.
13854 		 * If so, we should be able to send it a redirect.
13855 		 * Avoid sending a redirect if the destination
13856 		 * is directly connected (i.e., ipha_dst is the same
13857 		 * as ire_gateway_addr or the ire_addr of the
13858 		 * nexthop IRE_CACHE ), or if the packet was source
13859 		 * routed out this interface.
13860 		 */
13861 		ipaddr_t src, nhop;
13862 		mblk_t	*mp1;
13863 		ire_t	*nhop_ire = NULL;
13864 
13865 		/*
13866 		 * Check whether ire_rfq and q are from the same ill
13867 		 * or if they are not same, they at least belong
13868 		 * to the same group. If so, send redirects.
13869 		 */
13870 		if ((ire->ire_rfq == q ||
13871 		    (ill_group != NULL && ill_group == ire_group)) &&
13872 		    !ip_source_routed(ipha)) {
13873 
13874 			nhop = (ire->ire_gateway_addr != 0 ?
13875 			    ire->ire_gateway_addr : ire->ire_addr);
13876 
13877 			if (ipha->ipha_dst == nhop) {
13878 				/*
13879 				 * We avoid sending a redirect if the
13880 				 * destination is directly connected
13881 				 * because it is possible that multiple
13882 				 * IP subnets may have been configured on
13883 				 * the link, and the source may not
13884 				 * be on the same subnet as ip destination,
13885 				 * even though they are on the same
13886 				 * physical link.
13887 				 */
13888 				goto sendit;
13889 			}
13890 
13891 			src = ipha->ipha_src;
13892 
13893 			/*
13894 			 * We look up the interface ire for the nexthop,
13895 			 * to see if ipha_src is in the same subnet
13896 			 * as the nexthop.
13897 			 *
13898 			 * Note that, if, in the future, IRE_CACHE entries
13899 			 * are obsoleted,  this lookup will not be needed,
13900 			 * as the ire passed to this function will be the
13901 			 * same as the nhop_ire computed below.
13902 			 */
13903 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13904 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13905 			    0, NULL, MATCH_IRE_TYPE);
13906 
13907 			if (nhop_ire != NULL) {
13908 				if ((src & nhop_ire->ire_mask) ==
13909 				    (nhop & nhop_ire->ire_mask)) {
13910 					/*
13911 					 * The source is directly connected.
13912 					 * Just copy the ip header (which is
13913 					 * in the first mblk)
13914 					 */
13915 					mp1 = copyb(mp);
13916 					if (mp1 != NULL) {
13917 						icmp_send_redirect(WR(q), mp1,
13918 						    nhop);
13919 					}
13920 				}
13921 				ire_refrele(nhop_ire);
13922 			}
13923 		}
13924 	}
13925 sendit:
13926 	dev_q = ire->ire_stq->q_next;
13927 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13928 		BUMP_MIB(&ip_mib, ipInDiscards);
13929 		freemsg(mp);
13930 		return;
13931 	}
13932 
13933 	ip_rput_forward(ire, ipha, mp, ill);
13934 	return;
13935 
13936 drop_pkt:
13937 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13938 	freemsg(mp);
13939 }
13940 
13941 ire_t *
13942 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13943     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13944 {
13945 	queue_t		*q;
13946 	uint16_t	hcksumflags;
13947 
13948 	q = *qp;
13949 
13950 	/*
13951 	 * Clear the indication that this may have hardware
13952 	 * checksum as we are not using it for forwarding.
13953 	 */
13954 	hcksumflags = DB_CKSUMFLAGS(mp);
13955 	DB_CKSUMFLAGS(mp) = 0;
13956 
13957 	/*
13958 	 * Directed broadcast forwarding: if the packet came in over a
13959 	 * different interface then it is routed out over we can forward it.
13960 	 */
13961 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13962 		ire_refrele(ire);
13963 		freemsg(mp);
13964 		BUMP_MIB(&ip_mib, ipInDiscards);
13965 		return (NULL);
13966 	}
13967 	/*
13968 	 * For multicast we have set dst to be INADDR_BROADCAST
13969 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13970 	 * only for broadcast packets.
13971 	 */
13972 	if (!CLASSD(ipha->ipha_dst)) {
13973 		ire_t *new_ire;
13974 		ipif_t *ipif;
13975 		/*
13976 		 * For ill groups, as the switch duplicates broadcasts
13977 		 * across all the ports, we need to filter out and
13978 		 * send up only one copy. There is one copy for every
13979 		 * broadcast address on each ill. Thus, we look for a
13980 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13981 		 * later to see whether this ill is eligible to receive
13982 		 * them or not. ill_nominate_bcast_rcv() nominates only
13983 		 * one set of IREs for receiving.
13984 		 */
13985 
13986 		ipif = ipif_get_next_ipif(NULL, ill);
13987 		if (ipif == NULL) {
13988 			ire_refrele(ire);
13989 			freemsg(mp);
13990 			BUMP_MIB(&ip_mib, ipInDiscards);
13991 			return (NULL);
13992 		}
13993 		new_ire = ire_ctable_lookup(dst, 0, 0,
13994 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13995 		ipif_refrele(ipif);
13996 
13997 		if (new_ire != NULL) {
13998 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13999 				ire_refrele(ire);
14000 				ire_refrele(new_ire);
14001 				freemsg(mp);
14002 				BUMP_MIB(&ip_mib, ipInDiscards);
14003 				return (NULL);
14004 			}
14005 			/*
14006 			 * In the special case of multirouted broadcast
14007 			 * packets, we unconditionally need to "gateway"
14008 			 * them to the appropriate interface here.
14009 			 * In the normal case, this cannot happen, because
14010 			 * there is no broadcast IRE tagged with the
14011 			 * RTF_MULTIRT flag.
14012 			 */
14013 			if (new_ire->ire_flags & RTF_MULTIRT) {
14014 				ire_refrele(new_ire);
14015 				if (ire->ire_rfq != NULL) {
14016 					q = ire->ire_rfq;
14017 					*qp = q;
14018 				}
14019 			} else {
14020 				ire_refrele(ire);
14021 				ire = new_ire;
14022 			}
14023 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14024 			if (!ip_g_forward_directed_bcast) {
14025 				/*
14026 				 * Free the message if
14027 				 * ip_g_forward_directed_bcast is turned
14028 				 * off for non-local broadcast.
14029 				 */
14030 				ire_refrele(ire);
14031 				freemsg(mp);
14032 				BUMP_MIB(&ip_mib, ipInDiscards);
14033 				return (NULL);
14034 			}
14035 		} else {
14036 			/*
14037 			 * This CGTP packet successfully passed the
14038 			 * CGTP filter, but the related CGTP
14039 			 * broadcast IRE has not been found,
14040 			 * meaning that the redundant ipif is
14041 			 * probably down. However, if we discarded
14042 			 * this packet, its duplicate would be
14043 			 * filtered out by the CGTP filter so none
14044 			 * of them would get through. So we keep
14045 			 * going with this one.
14046 			 */
14047 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14048 			if (ire->ire_rfq != NULL) {
14049 				q = ire->ire_rfq;
14050 				*qp = q;
14051 			}
14052 		}
14053 	}
14054 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14055 		/*
14056 		 * Verify that there are not more then one
14057 		 * IRE_BROADCAST with this broadcast address which
14058 		 * has ire_stq set.
14059 		 * TODO: simplify, loop over all IRE's
14060 		 */
14061 		ire_t	*ire1;
14062 		int	num_stq = 0;
14063 		mblk_t	*mp1;
14064 
14065 		/* Find the first one with ire_stq set */
14066 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14067 		for (ire1 = ire; ire1 &&
14068 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14069 		    ire1 = ire1->ire_next)
14070 			;
14071 		if (ire1) {
14072 			ire_refrele(ire);
14073 			ire = ire1;
14074 			IRE_REFHOLD(ire);
14075 		}
14076 
14077 		/* Check if there are additional ones with stq set */
14078 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14079 			if (ire->ire_addr != ire1->ire_addr)
14080 				break;
14081 			if (ire1->ire_stq) {
14082 				num_stq++;
14083 				break;
14084 			}
14085 		}
14086 		rw_exit(&ire->ire_bucket->irb_lock);
14087 		if (num_stq == 1 && ire->ire_stq != NULL) {
14088 			ip1dbg(("ip_rput_process_broadcast: directed "
14089 			    "broadcast to 0x%x\n",
14090 			    ntohl(ire->ire_addr)));
14091 			mp1 = copymsg(mp);
14092 			if (mp1) {
14093 				switch (ipha->ipha_protocol) {
14094 				case IPPROTO_UDP:
14095 					ip_udp_input(q, mp1, ipha, ire, ill);
14096 					break;
14097 				default:
14098 					ip_proto_input(q, mp1, ipha, ire, ill);
14099 					break;
14100 				}
14101 			}
14102 			/*
14103 			 * Adjust ttl to 2 (1+1 - the forward engine
14104 			 * will decrement it by one.
14105 			 */
14106 			if (ip_csum_hdr(ipha)) {
14107 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14108 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14109 				freemsg(mp);
14110 				ire_refrele(ire);
14111 				return (NULL);
14112 			}
14113 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14114 			ipha->ipha_hdr_checksum = 0;
14115 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14116 			ip_rput_process_forward(q, mp, ire, ipha,
14117 			    ill, ll_multicast);
14118 			ire_refrele(ire);
14119 			return (NULL);
14120 		}
14121 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14122 		    ntohl(ire->ire_addr)));
14123 	}
14124 
14125 
14126 	/* Restore any hardware checksum flags */
14127 	DB_CKSUMFLAGS(mp) = hcksumflags;
14128 	return (ire);
14129 }
14130 
14131 /* ARGSUSED */
14132 static boolean_t
14133 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14134     int *ll_multicast, ipaddr_t *dstp)
14135 {
14136 	/*
14137 	 * Forward packets only if we have joined the allmulti
14138 	 * group on this interface.
14139 	 */
14140 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14141 		int retval;
14142 
14143 		/*
14144 		 * Clear the indication that this may have hardware
14145 		 * checksum as we are not using it.
14146 		 */
14147 		DB_CKSUMFLAGS(mp) = 0;
14148 		retval = ip_mforward(ill, ipha, mp);
14149 		/* ip_mforward updates mib variables if needed */
14150 		/* clear b_prev - used by ip_mroute_decap */
14151 		mp->b_prev = NULL;
14152 
14153 		switch (retval) {
14154 		case 0:
14155 			/*
14156 			 * pkt is okay and arrived on phyint.
14157 			 *
14158 			 * If we are running as a multicast router
14159 			 * we need to see all IGMP and/or PIM packets.
14160 			 */
14161 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14162 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14163 				goto done;
14164 			}
14165 			break;
14166 		case -1:
14167 			/* pkt is mal-formed, toss it */
14168 			goto drop_pkt;
14169 		case 1:
14170 			/* pkt is okay and arrived on a tunnel */
14171 			/*
14172 			 * If we are running a multicast router
14173 			 *  we need to see all igmp packets.
14174 			 */
14175 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14176 				*dstp = INADDR_BROADCAST;
14177 				*ll_multicast = 1;
14178 				return (B_FALSE);
14179 			}
14180 
14181 			goto drop_pkt;
14182 		}
14183 	}
14184 
14185 	ILM_WALKER_HOLD(ill);
14186 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14187 		/*
14188 		 * This might just be caused by the fact that
14189 		 * multiple IP Multicast addresses map to the same
14190 		 * link layer multicast - no need to increment counter!
14191 		 */
14192 		ILM_WALKER_RELE(ill);
14193 		freemsg(mp);
14194 		return (B_TRUE);
14195 	}
14196 	ILM_WALKER_RELE(ill);
14197 done:
14198 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14199 	/*
14200 	 * This assumes the we deliver to all streams for multicast
14201 	 * and broadcast packets.
14202 	 */
14203 	*dstp = INADDR_BROADCAST;
14204 	*ll_multicast = 1;
14205 	return (B_FALSE);
14206 drop_pkt:
14207 	ip2dbg(("ip_rput: drop pkt\n"));
14208 	freemsg(mp);
14209 	return (B_TRUE);
14210 }
14211 
14212 static boolean_t
14213 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14214     int *ll_multicast, mblk_t **mpp)
14215 {
14216 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14217 	boolean_t must_copy = B_FALSE;
14218 	struct iocblk   *iocp;
14219 	ipha_t		*ipha;
14220 
14221 #define	rptr    ((uchar_t *)ipha)
14222 
14223 	first_mp = *first_mpp;
14224 	mp = *mpp;
14225 
14226 	ASSERT(first_mp == mp);
14227 
14228 	/*
14229 	 * if db_ref > 1 then copymsg and free original. Packet may be
14230 	 * changed and do not want other entity who has a reference to this
14231 	 * message to trip over the changes. This is a blind change because
14232 	 * trying to catch all places that might change packet is too
14233 	 * difficult (since it may be a module above this one)
14234 	 *
14235 	 * This corresponds to the non-fast path case. We walk down the full
14236 	 * chain in this case, and check the db_ref count of all the dblks,
14237 	 * and do a copymsg if required. It is possible that the db_ref counts
14238 	 * of the data blocks in the mblk chain can be different.
14239 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14240 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14241 	 * 'snoop' is running.
14242 	 */
14243 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14244 		if (mp1->b_datap->db_ref > 1) {
14245 			must_copy = B_TRUE;
14246 			break;
14247 		}
14248 	}
14249 
14250 	if (must_copy) {
14251 		mp1 = copymsg(mp);
14252 		if (mp1 == NULL) {
14253 			for (mp1 = mp; mp1 != NULL;
14254 			    mp1 = mp1->b_cont) {
14255 				mp1->b_next = NULL;
14256 				mp1->b_prev = NULL;
14257 			}
14258 			freemsg(mp);
14259 			BUMP_MIB(&ip_mib, ipInDiscards);
14260 			return (B_TRUE);
14261 		}
14262 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14263 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14264 			/* Copy b_prev - used by ip_mroute_decap */
14265 			to_mp->b_prev = from_mp->b_prev;
14266 			from_mp->b_prev = NULL;
14267 		}
14268 		*first_mpp = first_mp = mp1;
14269 		freemsg(mp);
14270 		mp = mp1;
14271 		*mpp = mp1;
14272 	}
14273 
14274 	ipha = (ipha_t *)mp->b_rptr;
14275 
14276 	/*
14277 	 * previous code has a case for M_DATA.
14278 	 * We want to check how that happens.
14279 	 */
14280 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14281 	switch (first_mp->b_datap->db_type) {
14282 	case M_PROTO:
14283 	case M_PCPROTO:
14284 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14285 		    DL_UNITDATA_IND) {
14286 			/* Go handle anything other than data elsewhere. */
14287 			ip_rput_dlpi(q, mp);
14288 			return (B_TRUE);
14289 		}
14290 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14291 		/* Ditch the DLPI header. */
14292 		mp1 = mp->b_cont;
14293 		ASSERT(first_mp == mp);
14294 		*first_mpp = mp1;
14295 		freeb(mp);
14296 		*mpp = mp1;
14297 		return (B_FALSE);
14298 	case M_IOCACK:
14299 		ip1dbg(("got iocack "));
14300 		iocp = (struct iocblk *)mp->b_rptr;
14301 		switch (iocp->ioc_cmd) {
14302 		case DL_IOC_HDR_INFO:
14303 			ill = (ill_t *)q->q_ptr;
14304 			ill_fastpath_ack(ill, mp);
14305 			return (B_TRUE);
14306 		case SIOCSTUNPARAM:
14307 		case OSIOCSTUNPARAM:
14308 			/* Go through qwriter_ip */
14309 			break;
14310 		case SIOCGTUNPARAM:
14311 		case OSIOCGTUNPARAM:
14312 			ip_rput_other(NULL, q, mp, NULL);
14313 			return (B_TRUE);
14314 		default:
14315 			putnext(q, mp);
14316 			return (B_TRUE);
14317 		}
14318 		/* FALLTHRU */
14319 	case M_ERROR:
14320 	case M_HANGUP:
14321 		/*
14322 		 * Since this is on the ill stream we unconditionally
14323 		 * bump up the refcount
14324 		 */
14325 		ill_refhold(ill);
14326 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14327 		    B_FALSE);
14328 		return (B_TRUE);
14329 	case M_CTL:
14330 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14331 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14332 			IPHADA_M_CTL)) {
14333 			/*
14334 			 * It's an IPsec accelerated packet.
14335 			 * Make sure that the ill from which we received the
14336 			 * packet has enabled IPsec hardware acceleration.
14337 			 */
14338 			if (!(ill->ill_capabilities &
14339 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14340 				/* IPsec kstats: bean counter */
14341 				freemsg(mp);
14342 				return (B_TRUE);
14343 			}
14344 
14345 			/*
14346 			 * Make mp point to the mblk following the M_CTL,
14347 			 * then process according to type of mp.
14348 			 * After this processing, first_mp will point to
14349 			 * the data-attributes and mp to the pkt following
14350 			 * the M_CTL.
14351 			 */
14352 			mp = first_mp->b_cont;
14353 			if (mp == NULL) {
14354 				freemsg(first_mp);
14355 				return (B_TRUE);
14356 			}
14357 			/*
14358 			 * A Hardware Accelerated packet can only be M_DATA
14359 			 * ESP or AH packet.
14360 			 */
14361 			if (mp->b_datap->db_type != M_DATA) {
14362 				/* non-M_DATA IPsec accelerated packet */
14363 				IPSECHW_DEBUG(IPSECHW_PKT,
14364 				    ("non-M_DATA IPsec accelerated pkt\n"));
14365 				freemsg(first_mp);
14366 				return (B_TRUE);
14367 			}
14368 			ipha = (ipha_t *)mp->b_rptr;
14369 			if (ipha->ipha_protocol != IPPROTO_AH &&
14370 			    ipha->ipha_protocol != IPPROTO_ESP) {
14371 				IPSECHW_DEBUG(IPSECHW_PKT,
14372 				    ("non-M_DATA IPsec accelerated pkt\n"));
14373 				freemsg(first_mp);
14374 				return (B_TRUE);
14375 			}
14376 			*mpp = mp;
14377 			return (B_FALSE);
14378 		}
14379 		putnext(q, mp);
14380 		return (B_TRUE);
14381 	case M_FLUSH:
14382 		if (*mp->b_rptr & FLUSHW) {
14383 			*mp->b_rptr &= ~FLUSHR;
14384 			qreply(q, mp);
14385 			return (B_TRUE);
14386 		}
14387 		freemsg(mp);
14388 		return (B_TRUE);
14389 	case M_IOCNAK:
14390 		ip1dbg(("got iocnak "));
14391 		iocp = (struct iocblk *)mp->b_rptr;
14392 		switch (iocp->ioc_cmd) {
14393 		case DL_IOC_HDR_INFO:
14394 		case SIOCSTUNPARAM:
14395 		case OSIOCSTUNPARAM:
14396 			/*
14397 			 * Since this is on the ill stream we unconditionally
14398 			 * bump up the refcount
14399 			 */
14400 			ill_refhold(ill);
14401 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14402 			    CUR_OP, B_FALSE);
14403 			return (B_TRUE);
14404 		case SIOCGTUNPARAM:
14405 		case OSIOCGTUNPARAM:
14406 			ip_rput_other(NULL, q, mp, NULL);
14407 			return (B_TRUE);
14408 		default:
14409 			break;
14410 		}
14411 		/* FALLTHRU */
14412 	default:
14413 		putnext(q, mp);
14414 		return (B_TRUE);
14415 	}
14416 }
14417 
14418 /* Read side put procedure.  Packets coming from the wire arrive here. */
14419 void
14420 ip_rput(queue_t *q, mblk_t *mp)
14421 {
14422 	ill_t	*ill;
14423 	mblk_t	 *dmp = NULL;
14424 
14425 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14426 
14427 	ill = (ill_t *)q->q_ptr;
14428 
14429 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14430 		union DL_primitives *dl;
14431 
14432 		/*
14433 		 * Things are opening or closing. Only accept DLPI control
14434 		 * messages. In the open case, the ill->ill_ipif has not yet
14435 		 * been created. In the close case, things hanging off the
14436 		 * ill could have been freed already. In either case it
14437 		 * may not be safe to proceed further.
14438 		 */
14439 
14440 		dl = (union DL_primitives *)mp->b_rptr;
14441 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14442 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14443 			/*
14444 			 * Also SIOC[GS]TUN* ioctls can come here.
14445 			 */
14446 			inet_freemsg(mp);
14447 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14448 			    "ip_input_end: q %p (%S)", q, "uninit");
14449 			return;
14450 		}
14451 	}
14452 
14453 	/*
14454 	 * if db_ref > 1 then copymsg and free original. Packet may be
14455 	 * changed and we do not want the other entity who has a reference to
14456 	 * this message to trip over the changes. This is a blind change because
14457 	 * trying to catch all places that might change the packet is too
14458 	 * difficult.
14459 	 *
14460 	 * This corresponds to the fast path case, where we have a chain of
14461 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14462 	 * in the mblk chain. There doesn't seem to be a reason why a device
14463 	 * driver would send up data with varying db_ref counts in the mblk
14464 	 * chain. In any case the Fast path is a private interface, and our
14465 	 * drivers don't do such a thing. Given the above assumption, there is
14466 	 * no need to walk down the entire mblk chain (which could have a
14467 	 * potential performance problem)
14468 	 */
14469 	if (mp->b_datap->db_ref > 1) {
14470 		mblk_t  *mp1;
14471 		boolean_t adjusted = B_FALSE;
14472 		IP_STAT(ip_db_ref);
14473 
14474 		/*
14475 		 * The IP_RECVSLLA option depends on having the link layer
14476 		 * header. First check that:
14477 		 * a> the underlying device is of type ether, since this
14478 		 * option is currently supported only over ethernet.
14479 		 * b> there is enough room to copy over the link layer header.
14480 		 *
14481 		 * Once the checks are done, adjust rptr so that the link layer
14482 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14483 		 * be returned by some non-ethernet drivers but in this case the
14484 		 * second check will fail.
14485 		 */
14486 		if (ill->ill_type == IFT_ETHER &&
14487 		    (mp->b_rptr - mp->b_datap->db_base) >=
14488 		    sizeof (struct ether_header)) {
14489 			mp->b_rptr -= sizeof (struct ether_header);
14490 			adjusted = B_TRUE;
14491 		}
14492 		mp1 = copymsg(mp);
14493 		if (mp1 == NULL) {
14494 			mp->b_next = NULL;
14495 			/* clear b_prev - used by ip_mroute_decap */
14496 			mp->b_prev = NULL;
14497 			freemsg(mp);
14498 			BUMP_MIB(&ip_mib, ipInDiscards);
14499 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14500 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14501 			return;
14502 		}
14503 		if (adjusted) {
14504 			/*
14505 			 * Copy is done. Restore the pointer in the _new_ mblk
14506 			 */
14507 			mp1->b_rptr += sizeof (struct ether_header);
14508 		}
14509 		/* Copy b_prev - used by ip_mroute_decap */
14510 		mp1->b_prev = mp->b_prev;
14511 		mp->b_prev = NULL;
14512 		freemsg(mp);
14513 		mp = mp1;
14514 	}
14515 	if (DB_TYPE(mp) == M_DATA) {
14516 		dmp = mp;
14517 	} else if (DB_TYPE(mp) == M_PROTO &&
14518 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14519 		dmp = mp->b_cont;
14520 	}
14521 	if (dmp != NULL) {
14522 		/*
14523 		 * IP header ptr not aligned?
14524 		 * OR IP header not complete in first mblk
14525 		 */
14526 		if (!OK_32PTR(dmp->b_rptr) ||
14527 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14528 			if (!ip_check_and_align_header(q, dmp))
14529 				return;
14530 		}
14531 	}
14532 
14533 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14534 	    "ip_rput_end: q %p (%S)", q, "end");
14535 
14536 	ip_input(ill, NULL, mp, NULL);
14537 }
14538 
14539 /*
14540  * Direct read side procedure capable of dealing with chains. GLDv3 based
14541  * drivers call this function directly with mblk chains while STREAMS
14542  * read side procedure ip_rput() calls this for single packet with ip_ring
14543  * set to NULL to process one packet at a time.
14544  *
14545  * The ill will always be valid if this function is called directly from
14546  * the driver.
14547  *
14548  * If ip_input() is called from GLDv3:
14549  *
14550  *   - This must be a non-VLAN IP stream.
14551  *   - 'mp' is either an untagged or a special priority-tagged packet.
14552  *   - Any VLAN tag that was in the MAC header has been stripped.
14553  *
14554  * Thus, there is no need to adjust b_rptr in this function.
14555  */
14556 /* ARGSUSED */
14557 void
14558 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14559     struct mac_header_info_s *mhip)
14560 {
14561 	ipaddr_t		dst = NULL;
14562 	ipaddr_t		prev_dst;
14563 	ire_t			*ire = NULL;
14564 	ipha_t			*ipha;
14565 	uint_t			pkt_len;
14566 	ssize_t			len;
14567 	uint_t			opt_len;
14568 	int			ll_multicast;
14569 	int			cgtp_flt_pkt;
14570 	queue_t			*q = ill->ill_rq;
14571 	squeue_t		*curr_sqp = NULL;
14572 	mblk_t 			*head = NULL;
14573 	mblk_t			*tail = NULL;
14574 	mblk_t			*first_mp;
14575 	mblk_t 			*mp;
14576 	int			cnt = 0;
14577 
14578 	ASSERT(mp_chain != NULL);
14579 	ASSERT(ill != NULL);
14580 
14581 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14582 
14583 #define	rptr	((uchar_t *)ipha)
14584 
14585 	while (mp_chain != NULL) {
14586 		first_mp = mp = mp_chain;
14587 		mp_chain = mp_chain->b_next;
14588 		mp->b_next = NULL;
14589 		ll_multicast = 0;
14590 
14591 		/*
14592 		 * We do ire caching from one iteration to
14593 		 * another. In the event the packet chain contains
14594 		 * all packets from the same dst, this caching saves
14595 		 * an ire_cache_lookup for each of the succeeding
14596 		 * packets in a packet chain.
14597 		 */
14598 		prev_dst = dst;
14599 
14600 		/*
14601 		 * ip_input fast path
14602 		 */
14603 
14604 		/* mblk type is not M_DATA */
14605 		if (mp->b_datap->db_type != M_DATA) {
14606 			if (ip_rput_process_notdata(q, &first_mp, ill,
14607 			    &ll_multicast, &mp))
14608 				continue;
14609 		}
14610 
14611 		/* Make sure its an M_DATA and that its aligned */
14612 		ASSERT(mp->b_datap->db_type == M_DATA);
14613 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14614 
14615 		ipha = (ipha_t *)mp->b_rptr;
14616 		len = mp->b_wptr - rptr;
14617 
14618 		BUMP_MIB(&ip_mib, ipInReceives);
14619 
14620 
14621 		/* multiple mblk or too short */
14622 		pkt_len = ntohs(ipha->ipha_length);
14623 		len -= pkt_len;
14624 		if (len != 0) {
14625 			/*
14626 			 * Make sure we have data length consistent
14627 			 * with the IP header.
14628 			 */
14629 			if (mp->b_cont == NULL) {
14630 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14631 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14632 					ip2dbg(("ip_input: drop pkt\n"));
14633 					freemsg(mp);
14634 					continue;
14635 				}
14636 				mp->b_wptr = rptr + pkt_len;
14637 			} else if (len += msgdsize(mp->b_cont)) {
14638 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14639 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14640 					ip2dbg(("ip_input: drop pkt\n"));
14641 					freemsg(mp);
14642 					continue;
14643 				}
14644 				(void) adjmsg(mp, -len);
14645 				IP_STAT(ip_multimblk3);
14646 			}
14647 		}
14648 
14649 		/* Obtain the dst of the current packet */
14650 		dst = ipha->ipha_dst;
14651 
14652 		if (IP_LOOPBACK_ADDR(dst) ||
14653 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14654 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14655 			cmn_err(CE_CONT, "dst %X src %X\n",
14656 			    dst, ipha->ipha_src);
14657 			freemsg(mp);
14658 			continue;
14659 		}
14660 
14661 		/*
14662 		 * The event for packets being received from a 'physical'
14663 		 * interface is placed after validation of the source and/or
14664 		 * destination address as being local so that packets can be
14665 		 * redirected to loopback addresses using ipnat.
14666 		 */
14667 		DTRACE_PROBE4(ip4__physical__in__start,
14668 		    ill_t *, ill, ill_t *, NULL,
14669 		    ipha_t *, ipha, mblk_t *, first_mp);
14670 
14671 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14672 		    ill, NULL, ipha, first_mp, mp);
14673 
14674 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14675 
14676 		if (first_mp == NULL) {
14677 			continue;
14678 		}
14679 		dst = ipha->ipha_dst;
14680 
14681 		/*
14682 		 * Attach any necessary label information to
14683 		 * this packet
14684 		 */
14685 		if (is_system_labeled() &&
14686 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14687 			BUMP_MIB(&ip_mib, ipInDiscards);
14688 			freemsg(mp);
14689 			continue;
14690 		}
14691 
14692 		/*
14693 		 * Reuse the cached ire only if the ipha_dst of the previous
14694 		 * packet is the same as the current packet AND it is not
14695 		 * INADDR_ANY.
14696 		 */
14697 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14698 		    (ire != NULL)) {
14699 			ire_refrele(ire);
14700 			ire = NULL;
14701 		}
14702 		opt_len = ipha->ipha_version_and_hdr_length -
14703 		    IP_SIMPLE_HDR_VERSION;
14704 
14705 		/*
14706 		 * Check to see if we can take the fastpath.
14707 		 * That is possible if the following conditions are met
14708 		 *	o Tsol disabled
14709 		 *	o CGTP disabled
14710 		 *	o ipp_action_count is 0
14711 		 *	o Mobile IP not running
14712 		 *	o no options in the packet
14713 		 *	o not a RSVP packet
14714 		 * 	o not a multicast packet
14715 		 */
14716 		if (!is_system_labeled() &&
14717 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14718 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14719 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14720 		    !ll_multicast && !CLASSD(dst)) {
14721 			if (ire == NULL)
14722 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14723 
14724 			/* incoming packet is for forwarding */
14725 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14726 				ire = ip_fast_forward(ire, dst, ill, mp);
14727 				continue;
14728 			}
14729 			/* incoming packet is for local consumption */
14730 			if (ire->ire_type & IRE_LOCAL)
14731 				goto local;
14732 		}
14733 
14734 		/*
14735 		 * Disable ire caching for anything more complex
14736 		 * than the simple fast path case we checked for above.
14737 		 */
14738 		if (ire != NULL) {
14739 			ire_refrele(ire);
14740 			ire = NULL;
14741 		}
14742 
14743 		/* Full-blown slow path */
14744 		if (opt_len != 0) {
14745 			if (len != 0)
14746 				IP_STAT(ip_multimblk4);
14747 			else
14748 				IP_STAT(ip_ipoptions);
14749 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14750 				continue;
14751 		}
14752 
14753 		/*
14754 		 * Invoke the CGTP (multirouting) filtering module to process
14755 		 * the incoming packet. Packets identified as duplicates
14756 		 * must be discarded. Filtering is active only if the
14757 		 * the ip_cgtp_filter ndd variable is non-zero.
14758 		 */
14759 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14760 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14761 			cgtp_flt_pkt =
14762 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14763 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14764 				freemsg(first_mp);
14765 				continue;
14766 			}
14767 		}
14768 
14769 		/*
14770 		 * If rsvpd is running, let RSVP daemon handle its processing
14771 		 * and forwarding of RSVP multicast/unicast packets.
14772 		 * If rsvpd is not running but mrouted is running, RSVP
14773 		 * multicast packets are forwarded as multicast traffic
14774 		 * and RSVP unicast packets are forwarded by unicast router.
14775 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14776 		 * packets are not forwarded, but the unicast packets are
14777 		 * forwarded like unicast traffic.
14778 		 */
14779 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14780 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14781 			/* RSVP packet and rsvpd running. Treat as ours */
14782 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14783 			/*
14784 			 * This assumes that we deliver to all streams for
14785 			 * multicast and broadcast packets.
14786 			 * We have to force ll_multicast to 1 to handle the
14787 			 * M_DATA messages passed in from ip_mroute_decap.
14788 			 */
14789 			dst = INADDR_BROADCAST;
14790 			ll_multicast = 1;
14791 		} else if (CLASSD(dst)) {
14792 			/* packet is multicast */
14793 			mp->b_next = NULL;
14794 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14795 			    &ll_multicast, &dst))
14796 				continue;
14797 		}
14798 
14799 
14800 		/*
14801 		 * Check if the packet is coming from the Mobile IP
14802 		 * forward tunnel interface
14803 		 */
14804 		if (ill->ill_srcif_refcnt > 0) {
14805 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14806 			    NULL, ill, MATCH_IRE_TYPE);
14807 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14808 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14809 
14810 				/* We need to resolve the link layer info */
14811 				ire_refrele(ire);
14812 				ire = NULL;
14813 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14814 				    ll_multicast, dst);
14815 				continue;
14816 			}
14817 		}
14818 
14819 		if (ire == NULL) {
14820 			ire = ire_cache_lookup(dst, ALL_ZONES,
14821 			    MBLK_GETLABEL(mp));
14822 		}
14823 
14824 		/*
14825 		 * If mipagent is running and reverse tunnel is created as per
14826 		 * mobile node request, then any packet coming through the
14827 		 * incoming interface from the mobile-node, should be reverse
14828 		 * tunneled to it's home agent except those that are destined
14829 		 * to foreign agent only.
14830 		 * This needs source address based ire lookup. The routing
14831 		 * entries for source address based lookup are only created by
14832 		 * mipagent program only when a reverse tunnel is created.
14833 		 * Reference : RFC2002, RFC2344
14834 		 */
14835 		if (ill->ill_mrtun_refcnt > 0) {
14836 			ipaddr_t	srcaddr;
14837 			ire_t		*tmp_ire;
14838 
14839 			tmp_ire = ire;	/* Save, we might need it later */
14840 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14841 			    ire->ire_type != IRE_BROADCAST)) {
14842 				srcaddr = ipha->ipha_src;
14843 				ire = ire_mrtun_lookup(srcaddr, ill);
14844 				if (ire != NULL) {
14845 					/*
14846 					 * Should not be getting iphada packet
14847 					 * here. we should only get those for
14848 					 * IRE_LOCAL traffic, excluded above.
14849 					 * Fail-safe (drop packet) in the event
14850 					 * hardware is misbehaving.
14851 					 */
14852 					if (first_mp != mp) {
14853 						/* IPsec KSTATS: beancount me */
14854 						freemsg(first_mp);
14855 					} else {
14856 						/*
14857 						 * This packet must be forwarded
14858 						 * to Reverse Tunnel
14859 						 */
14860 						ip_mrtun_forward(ire, ill, mp);
14861 					}
14862 					ire_refrele(ire);
14863 					ire = NULL;
14864 					if (tmp_ire != NULL) {
14865 						ire_refrele(tmp_ire);
14866 						tmp_ire = NULL;
14867 					}
14868 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14869 					    "ip_input_end: q %p (%S)",
14870 					    q, "uninit");
14871 					continue;
14872 				}
14873 			}
14874 			/*
14875 			 * If this packet is from a non-mobilenode  or a
14876 			 * mobile-node which does not request reverse
14877 			 * tunnel service
14878 			 */
14879 			ire = tmp_ire;
14880 		}
14881 
14882 
14883 		/*
14884 		 * If we reach here that means the incoming packet satisfies
14885 		 * one of the following conditions:
14886 		 *   - packet is from a mobile node which does not request
14887 		 *	reverse tunnel
14888 		 *   - packet is from a non-mobile node, which is the most
14889 		 *	common case
14890 		 *   - packet is from a reverse tunnel enabled mobile node
14891 		 *	and destined to foreign agent only
14892 		 */
14893 
14894 		if (ire == NULL) {
14895 			/*
14896 			 * No IRE for this destination, so it can't be for us.
14897 			 * Unless we are forwarding, drop the packet.
14898 			 * We have to let source routed packets through
14899 			 * since we don't yet know if they are 'ping -l'
14900 			 * packets i.e. if they will go out over the
14901 			 * same interface as they came in on.
14902 			 */
14903 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14904 			if (ire == NULL)
14905 				continue;
14906 		}
14907 
14908 		/*
14909 		 * Broadcast IRE may indicate either broadcast or
14910 		 * multicast packet
14911 		 */
14912 		if (ire->ire_type == IRE_BROADCAST) {
14913 			/*
14914 			 * Skip broadcast checks if packet is UDP multicast;
14915 			 * we'd rather not enter ip_rput_process_broadcast()
14916 			 * unless the packet is broadcast for real, since
14917 			 * that routine is a no-op for multicast.
14918 			 */
14919 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14920 			    !CLASSD(ipha->ipha_dst)) {
14921 				ire = ip_rput_process_broadcast(&q, mp,
14922 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14923 				    ll_multicast);
14924 				if (ire == NULL)
14925 					continue;
14926 			}
14927 		} else if (ire->ire_stq != NULL) {
14928 			/* fowarding? */
14929 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14930 			    ll_multicast);
14931 			/* ip_rput_process_forward consumed the packet */
14932 			continue;
14933 		}
14934 
14935 local:
14936 		/* packet not for us */
14937 		if (ire->ire_rfq != q) {
14938 			if (ip_rput_notforus(&q, mp, ire, ill))
14939 				continue;
14940 		}
14941 
14942 		switch (ipha->ipha_protocol) {
14943 		case IPPROTO_TCP:
14944 			ASSERT(first_mp == mp);
14945 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14946 				mp, 0, q, ip_ring)) != NULL) {
14947 				if (curr_sqp == NULL) {
14948 					curr_sqp = GET_SQUEUE(mp);
14949 					ASSERT(cnt == 0);
14950 					cnt++;
14951 					head = tail = mp;
14952 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14953 					ASSERT(tail != NULL);
14954 					cnt++;
14955 					tail->b_next = mp;
14956 					tail = mp;
14957 				} else {
14958 					/*
14959 					 * A different squeue. Send the
14960 					 * chain for the previous squeue on
14961 					 * its way. This shouldn't happen
14962 					 * often unless interrupt binding
14963 					 * changes.
14964 					 */
14965 					IP_STAT(ip_input_multi_squeue);
14966 					squeue_enter_chain(curr_sqp, head,
14967 					    tail, cnt, SQTAG_IP_INPUT);
14968 					curr_sqp = GET_SQUEUE(mp);
14969 					head = mp;
14970 					tail = mp;
14971 					cnt = 1;
14972 				}
14973 			}
14974 			continue;
14975 		case IPPROTO_UDP:
14976 			ASSERT(first_mp == mp);
14977 			ip_udp_input(q, mp, ipha, ire, ill);
14978 			continue;
14979 		case IPPROTO_SCTP:
14980 			ASSERT(first_mp == mp);
14981 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14982 			    q, dst);
14983 			/* ire has been released by ip_sctp_input */
14984 			ire = NULL;
14985 			continue;
14986 		default:
14987 			ip_proto_input(q, first_mp, ipha, ire, ill);
14988 			continue;
14989 		}
14990 	}
14991 
14992 	if (ire != NULL)
14993 		ire_refrele(ire);
14994 
14995 	if (head != NULL)
14996 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14997 
14998 	/*
14999 	 * This code is there just to make netperf/ttcp look good.
15000 	 *
15001 	 * Its possible that after being in polling mode (and having cleared
15002 	 * the backlog), squeues have turned the interrupt frequency higher
15003 	 * to improve latency at the expense of more CPU utilization (less
15004 	 * packets per interrupts or more number of interrupts). Workloads
15005 	 * like ttcp/netperf do manage to tickle polling once in a while
15006 	 * but for the remaining time, stay in higher interrupt mode since
15007 	 * their packet arrival rate is pretty uniform and this shows up
15008 	 * as higher CPU utilization. Since people care about CPU utilization
15009 	 * while running netperf/ttcp, turn the interrupt frequency back to
15010 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15011 	 */
15012 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15013 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15014 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15015 			ip_ring->rr_blank(ip_ring->rr_handle,
15016 			    ip_ring->rr_normal_blank_time,
15017 			    ip_ring->rr_normal_pkt_cnt);
15018 		}
15019 	}
15020 
15021 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15022 	    "ip_input_end: q %p (%S)", q, "end");
15023 #undef	rptr
15024 }
15025 
15026 static void
15027 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15028     t_uscalar_t err)
15029 {
15030 	if (dl_err == DL_SYSERR) {
15031 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15032 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15033 		    ill->ill_name, dlpi_prim_str(prim), err);
15034 		return;
15035 	}
15036 
15037 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15038 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15039 	    dlpi_err_str(dl_err));
15040 }
15041 
15042 /*
15043  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15044  * than DL_UNITDATA_IND messages. If we need to process this message
15045  * exclusively, we call qwriter_ip, in which case we also need to call
15046  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15047  */
15048 void
15049 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15050 {
15051 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15052 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15053 	ill_t		*ill;
15054 
15055 	ip1dbg(("ip_rput_dlpi"));
15056 	ill = (ill_t *)q->q_ptr;
15057 	switch (dloa->dl_primitive) {
15058 	case DL_ERROR_ACK:
15059 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15060 		    "%s (0x%x), unix %u\n", ill->ill_name,
15061 		    dlpi_prim_str(dlea->dl_error_primitive),
15062 		    dlea->dl_error_primitive,
15063 		    dlpi_err_str(dlea->dl_errno),
15064 		    dlea->dl_errno,
15065 		    dlea->dl_unix_errno));
15066 		switch (dlea->dl_error_primitive) {
15067 		case DL_UNBIND_REQ:
15068 			mutex_enter(&ill->ill_lock);
15069 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15070 			cv_signal(&ill->ill_cv);
15071 			mutex_exit(&ill->ill_lock);
15072 			/* FALLTHRU */
15073 		case DL_NOTIFY_REQ:
15074 		case DL_ATTACH_REQ:
15075 		case DL_DETACH_REQ:
15076 		case DL_INFO_REQ:
15077 		case DL_BIND_REQ:
15078 		case DL_ENABMULTI_REQ:
15079 		case DL_PHYS_ADDR_REQ:
15080 		case DL_CAPABILITY_REQ:
15081 		case DL_CONTROL_REQ:
15082 			/*
15083 			 * Refhold the ill to match qwriter_ip which does a
15084 			 * refrele. Since this is on the ill stream we
15085 			 * unconditionally bump up the refcount without
15086 			 * checking for ILL_CAN_LOOKUP
15087 			 */
15088 			ill_refhold(ill);
15089 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15090 			    CUR_OP, B_FALSE);
15091 			return;
15092 		case DL_DISABMULTI_REQ:
15093 			freemsg(mp);	/* Don't want to pass this up */
15094 			return;
15095 		default:
15096 			break;
15097 		}
15098 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15099 		    dlea->dl_errno, dlea->dl_unix_errno);
15100 		freemsg(mp);
15101 		return;
15102 	case DL_INFO_ACK:
15103 	case DL_BIND_ACK:
15104 	case DL_PHYS_ADDR_ACK:
15105 	case DL_NOTIFY_ACK:
15106 	case DL_CAPABILITY_ACK:
15107 	case DL_CONTROL_ACK:
15108 		/*
15109 		 * Refhold the ill to match qwriter_ip which does a refrele
15110 		 * Since this is on the ill stream we unconditionally
15111 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15112 		 */
15113 		ill_refhold(ill);
15114 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15115 		    CUR_OP, B_FALSE);
15116 		return;
15117 	case DL_NOTIFY_IND:
15118 		ill_refhold(ill);
15119 		/*
15120 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15121 		 * relation to the current ioctl in progress (if any). Hence we
15122 		 * pass in NEW_OP in this case.
15123 		 */
15124 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15125 		    NEW_OP, B_FALSE);
15126 		return;
15127 	case DL_OK_ACK:
15128 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15129 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15130 		switch (dloa->dl_correct_primitive) {
15131 		case DL_UNBIND_REQ:
15132 			mutex_enter(&ill->ill_lock);
15133 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15134 			cv_signal(&ill->ill_cv);
15135 			mutex_exit(&ill->ill_lock);
15136 			/* FALLTHRU */
15137 		case DL_ATTACH_REQ:
15138 		case DL_DETACH_REQ:
15139 			/*
15140 			 * Refhold the ill to match qwriter_ip which does a
15141 			 * refrele. Since this is on the ill stream we
15142 			 * unconditionally bump up the refcount
15143 			 */
15144 			ill_refhold(ill);
15145 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15146 			    CUR_OP, B_FALSE);
15147 			return;
15148 		case DL_ENABMULTI_REQ:
15149 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15150 				ill->ill_dlpi_multicast_state = IDS_OK;
15151 			break;
15152 
15153 		}
15154 		break;
15155 	default:
15156 		break;
15157 	}
15158 	freemsg(mp);
15159 }
15160 
15161 /*
15162  * Handling of DLPI messages that require exclusive access to the ipsq.
15163  *
15164  * Need to do ill_pending_mp_release on ioctl completion, which could
15165  * happen here. (along with mi_copy_done)
15166  */
15167 /* ARGSUSED */
15168 static void
15169 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15170 {
15171 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15172 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15173 	int		err = 0;
15174 	ill_t		*ill;
15175 	ipif_t		*ipif = NULL;
15176 	mblk_t		*mp1 = NULL;
15177 	conn_t		*connp = NULL;
15178 	t_uscalar_t	physaddr_req;
15179 	mblk_t		*mp_hw;
15180 	union DL_primitives *dlp;
15181 	boolean_t	success;
15182 	boolean_t	ioctl_aborted = B_FALSE;
15183 	boolean_t	log = B_TRUE;
15184 	hook_nic_event_t	*info;
15185 
15186 	ip1dbg(("ip_rput_dlpi_writer .."));
15187 	ill = (ill_t *)q->q_ptr;
15188 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15189 
15190 	ASSERT(IAM_WRITER_ILL(ill));
15191 
15192 	/*
15193 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15194 	 * both are null or non-null. However we can assert that only
15195 	 * after grabbing the ipsq_lock. So we don't make any assertion
15196 	 * here and in other places in the code.
15197 	 */
15198 	ipif = ipsq->ipsq_pending_ipif;
15199 	/*
15200 	 * The current ioctl could have been aborted by the user and a new
15201 	 * ioctl to bring up another ill could have started. We could still
15202 	 * get a response from the driver later.
15203 	 */
15204 	if (ipif != NULL && ipif->ipif_ill != ill)
15205 		ioctl_aborted = B_TRUE;
15206 
15207 	switch (dloa->dl_primitive) {
15208 	case DL_ERROR_ACK:
15209 		switch (dlea->dl_error_primitive) {
15210 		case DL_UNBIND_REQ:
15211 		case DL_ATTACH_REQ:
15212 		case DL_DETACH_REQ:
15213 		case DL_INFO_REQ:
15214 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15215 			break;
15216 		case DL_NOTIFY_REQ:
15217 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15218 			log = B_FALSE;
15219 			break;
15220 		case DL_PHYS_ADDR_REQ:
15221 			/*
15222 			 * For IPv6 only, there are two additional
15223 			 * phys_addr_req's sent to the driver to get the
15224 			 * IPv6 token and lla. This allows IP to acquire
15225 			 * the hardware address format for a given interface
15226 			 * without having built in knowledge of the hardware
15227 			 * address. ill_phys_addr_pend keeps track of the last
15228 			 * DL_PAR sent so we know which response we are
15229 			 * dealing with. ill_dlpi_done will update
15230 			 * ill_phys_addr_pend when it sends the next req.
15231 			 * We don't complete the IOCTL until all three DL_PARs
15232 			 * have been attempted, so set *_len to 0 and break.
15233 			 */
15234 			physaddr_req = ill->ill_phys_addr_pend;
15235 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15236 			if (physaddr_req == DL_IPV6_TOKEN) {
15237 				ill->ill_token_length = 0;
15238 				log = B_FALSE;
15239 				break;
15240 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15241 				ill->ill_nd_lla_len = 0;
15242 				log = B_FALSE;
15243 				break;
15244 			}
15245 			/*
15246 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15247 			 * We presumably have an IOCTL hanging out waiting
15248 			 * for completion. Find it and complete the IOCTL
15249 			 * with the error noted.
15250 			 * However, ill_dl_phys was called on an ill queue
15251 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15252 			 * set. But the ioctl is known to be pending on ill_wq.
15253 			 */
15254 			if (!ill->ill_ifname_pending)
15255 				break;
15256 			ill->ill_ifname_pending = 0;
15257 			if (!ioctl_aborted)
15258 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15259 			if (mp1 != NULL) {
15260 				/*
15261 				 * This operation (SIOCSLIFNAME) must have
15262 				 * happened on the ill. Assert there is no conn
15263 				 */
15264 				ASSERT(connp == NULL);
15265 				q = ill->ill_wq;
15266 			}
15267 			break;
15268 		case DL_BIND_REQ:
15269 			ill_dlpi_done(ill, DL_BIND_REQ);
15270 			if (ill->ill_ifname_pending)
15271 				break;
15272 			/*
15273 			 * Something went wrong with the bind.  We presumably
15274 			 * have an IOCTL hanging out waiting for completion.
15275 			 * Find it, take down the interface that was coming
15276 			 * up, and complete the IOCTL with the error noted.
15277 			 */
15278 			if (!ioctl_aborted)
15279 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15280 			if (mp1 != NULL) {
15281 				/*
15282 				 * This operation (SIOCSLIFFLAGS) must have
15283 				 * happened from a conn.
15284 				 */
15285 				ASSERT(connp != NULL);
15286 				q = CONNP_TO_WQ(connp);
15287 				if (ill->ill_move_in_progress) {
15288 					ILL_CLEAR_MOVE(ill);
15289 				}
15290 				(void) ipif_down(ipif, NULL, NULL);
15291 				/* error is set below the switch */
15292 			}
15293 			break;
15294 		case DL_ENABMULTI_REQ:
15295 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15296 
15297 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15298 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15299 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15300 				ipif_t *ipif;
15301 
15302 				log = B_FALSE;
15303 				printf("ip: joining multicasts failed (%d)"
15304 				    " on %s - will use link layer "
15305 				    "broadcasts for multicast\n",
15306 				    dlea->dl_errno, ill->ill_name);
15307 
15308 				/*
15309 				 * Set up the multicast mapping alone.
15310 				 * writer, so ok to access ill->ill_ipif
15311 				 * without any lock.
15312 				 */
15313 				ipif = ill->ill_ipif;
15314 				mutex_enter(&ill->ill_phyint->phyint_lock);
15315 				ill->ill_phyint->phyint_flags |=
15316 				    PHYI_MULTI_BCAST;
15317 				mutex_exit(&ill->ill_phyint->phyint_lock);
15318 
15319 				if (!ill->ill_isv6) {
15320 					(void) ipif_arp_setup_multicast(ipif,
15321 					    NULL);
15322 				} else {
15323 					(void) ipif_ndp_setup_multicast(ipif,
15324 					    NULL);
15325 				}
15326 			}
15327 			freemsg(mp);	/* Don't want to pass this up */
15328 			return;
15329 		case DL_CAPABILITY_REQ:
15330 		case DL_CONTROL_REQ:
15331 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15332 			    "DL_CAPABILITY/CONTROL REQ\n"));
15333 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15334 			ill->ill_dlpi_capab_state = IDS_FAILED;
15335 			freemsg(mp);
15336 			return;
15337 		}
15338 		/*
15339 		 * Note the error for IOCTL completion (mp1 is set when
15340 		 * ready to complete ioctl). If ill_ifname_pending_err is
15341 		 * set, an error occured during plumbing (ill_ifname_pending),
15342 		 * so we want to report that error.
15343 		 *
15344 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15345 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15346 		 * expected to get errack'd if the driver doesn't support
15347 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15348 		 * if these error conditions are encountered.
15349 		 */
15350 		if (mp1 != NULL) {
15351 			if (ill->ill_ifname_pending_err != 0)  {
15352 				err = ill->ill_ifname_pending_err;
15353 				ill->ill_ifname_pending_err = 0;
15354 			} else {
15355 				err = dlea->dl_unix_errno ?
15356 				    dlea->dl_unix_errno : ENXIO;
15357 			}
15358 		/*
15359 		 * If we're plumbing an interface and an error hasn't already
15360 		 * been saved, set ill_ifname_pending_err to the error passed
15361 		 * up. Ignore the error if log is B_FALSE (see comment above).
15362 		 */
15363 		} else if (log && ill->ill_ifname_pending &&
15364 		    ill->ill_ifname_pending_err == 0) {
15365 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15366 			dlea->dl_unix_errno : ENXIO;
15367 		}
15368 
15369 		if (log)
15370 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15371 			    dlea->dl_errno, dlea->dl_unix_errno);
15372 		break;
15373 	case DL_CAPABILITY_ACK: {
15374 		boolean_t reneg_flag = B_FALSE;
15375 		/* Call a routine to handle this one. */
15376 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15377 		/*
15378 		 * Check if the ACK is due to renegotiation case since we
15379 		 * will need to send a new CAPABILITY_REQ later.
15380 		 */
15381 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15382 			/* This is the ack for a renogiation case */
15383 			reneg_flag = B_TRUE;
15384 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15385 		}
15386 		ill_capability_ack(ill, mp);
15387 		if (reneg_flag)
15388 			ill_capability_probe(ill);
15389 		break;
15390 	}
15391 	case DL_CONTROL_ACK:
15392 		/* We treat all of these as "fire and forget" */
15393 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15394 		break;
15395 	case DL_INFO_ACK:
15396 		/* Call a routine to handle this one. */
15397 		ill_dlpi_done(ill, DL_INFO_REQ);
15398 		ip_ll_subnet_defaults(ill, mp);
15399 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15400 		return;
15401 	case DL_BIND_ACK:
15402 		/*
15403 		 * We should have an IOCTL waiting on this unless
15404 		 * sent by ill_dl_phys, in which case just return
15405 		 */
15406 		ill_dlpi_done(ill, DL_BIND_REQ);
15407 		if (ill->ill_ifname_pending)
15408 			break;
15409 
15410 		if (!ioctl_aborted)
15411 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15412 		if (mp1 == NULL)
15413 			break;
15414 		ASSERT(connp != NULL);
15415 		q = CONNP_TO_WQ(connp);
15416 
15417 		/*
15418 		 * We are exclusive. So nothing can change even after
15419 		 * we get the pending mp. If need be we can put it back
15420 		 * and restart, as in calling ipif_arp_up()  below.
15421 		 */
15422 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15423 
15424 		mutex_enter(&ill->ill_lock);
15425 
15426 		ill->ill_dl_up = 1;
15427 
15428 		if ((info = ill->ill_nic_event_info) != NULL) {
15429 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15430 			    "attached for %s\n", info->hne_event,
15431 			    ill->ill_name));
15432 			if (info->hne_data != NULL)
15433 				kmem_free(info->hne_data, info->hne_datalen);
15434 			kmem_free(info, sizeof (hook_nic_event_t));
15435 		}
15436 
15437 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15438 		if (info != NULL) {
15439 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15440 			info->hne_lif = 0;
15441 			info->hne_event = NE_UP;
15442 			info->hne_data = NULL;
15443 			info->hne_datalen = 0;
15444 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15445 		} else
15446 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15447 			    "event information for %s (ENOMEM)\n",
15448 			    ill->ill_name));
15449 
15450 		ill->ill_nic_event_info = info;
15451 
15452 		mutex_exit(&ill->ill_lock);
15453 
15454 		/*
15455 		 * Now bring up the resolver; when that is complete, we'll
15456 		 * create IREs.  Note that we intentionally mirror what
15457 		 * ipif_up() would have done, because we got here by way of
15458 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15459 		 */
15460 		if (ill->ill_isv6) {
15461 			/*
15462 			 * v6 interfaces.
15463 			 * Unlike ARP which has to do another bind
15464 			 * and attach, once we get here we are
15465 			 * done with NDP. Except in the case of
15466 			 * ILLF_XRESOLV, in which case we send an
15467 			 * AR_INTERFACE_UP to the external resolver.
15468 			 * If all goes well, the ioctl will complete
15469 			 * in ip_rput(). If there's an error, we
15470 			 * complete it here.
15471 			 */
15472 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15473 			    B_FALSE);
15474 			if (err == 0) {
15475 				if (ill->ill_flags & ILLF_XRESOLV) {
15476 					mutex_enter(&connp->conn_lock);
15477 					mutex_enter(&ill->ill_lock);
15478 					success = ipsq_pending_mp_add(
15479 					    connp, ipif, q, mp1, 0);
15480 					mutex_exit(&ill->ill_lock);
15481 					mutex_exit(&connp->conn_lock);
15482 					if (success) {
15483 						err = ipif_resolver_up(ipif,
15484 						    Res_act_initial);
15485 						if (err == EINPROGRESS) {
15486 							freemsg(mp);
15487 							return;
15488 						}
15489 						ASSERT(err != 0);
15490 						mp1 = ipsq_pending_mp_get(ipsq,
15491 						    &connp);
15492 						ASSERT(mp1 != NULL);
15493 					} else {
15494 						/* conn has started closing */
15495 						err = EINTR;
15496 					}
15497 				} else { /* Non XRESOLV interface */
15498 					(void) ipif_resolver_up(ipif,
15499 					    Res_act_initial);
15500 					err = ipif_up_done_v6(ipif);
15501 				}
15502 			}
15503 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15504 			/*
15505 			 * ARP and other v4 external resolvers.
15506 			 * Leave the pending mblk intact so that
15507 			 * the ioctl completes in ip_rput().
15508 			 */
15509 			mutex_enter(&connp->conn_lock);
15510 			mutex_enter(&ill->ill_lock);
15511 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15512 			mutex_exit(&ill->ill_lock);
15513 			mutex_exit(&connp->conn_lock);
15514 			if (success) {
15515 				err = ipif_resolver_up(ipif, Res_act_initial);
15516 				if (err == EINPROGRESS) {
15517 					freemsg(mp);
15518 					return;
15519 				}
15520 				ASSERT(err != 0);
15521 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15522 			} else {
15523 				/* The conn has started closing */
15524 				err = EINTR;
15525 			}
15526 		} else {
15527 			/*
15528 			 * This one is complete. Reply to pending ioctl.
15529 			 */
15530 			(void) ipif_resolver_up(ipif, Res_act_initial);
15531 			err = ipif_up_done(ipif);
15532 		}
15533 
15534 		if ((err == 0) && (ill->ill_up_ipifs)) {
15535 			err = ill_up_ipifs(ill, q, mp1);
15536 			if (err == EINPROGRESS) {
15537 				freemsg(mp);
15538 				return;
15539 			}
15540 		}
15541 
15542 		if (ill->ill_up_ipifs) {
15543 			ill_group_cleanup(ill);
15544 		}
15545 
15546 		break;
15547 	case DL_NOTIFY_IND: {
15548 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15549 		ire_t *ire;
15550 		boolean_t need_ire_walk_v4 = B_FALSE;
15551 		boolean_t need_ire_walk_v6 = B_FALSE;
15552 
15553 		/*
15554 		 * Change the address everywhere we need to.
15555 		 * What we're getting here is a link-level addr or phys addr.
15556 		 * The new addr is at notify + notify->dl_addr_offset
15557 		 * The address length is notify->dl_addr_length;
15558 		 */
15559 		switch (notify->dl_notification) {
15560 		case DL_NOTE_PHYS_ADDR:
15561 			mp_hw = copyb(mp);
15562 			if (mp_hw == NULL) {
15563 				err = ENOMEM;
15564 				break;
15565 			}
15566 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15567 			/*
15568 			 * We currently don't support changing
15569 			 * the token via DL_NOTIFY_IND.
15570 			 * When we do support it, we have to consider
15571 			 * what the implications are with respect to
15572 			 * the token and the link local address.
15573 			 */
15574 			mutex_enter(&ill->ill_lock);
15575 			if (dlp->notify_ind.dl_data ==
15576 			    DL_IPV6_LINK_LAYER_ADDR) {
15577 				if (ill->ill_nd_lla_mp != NULL)
15578 					freemsg(ill->ill_nd_lla_mp);
15579 				ill->ill_nd_lla_mp = mp_hw;
15580 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15581 				    dlp->notify_ind.dl_addr_offset;
15582 				ill->ill_nd_lla_len =
15583 				    dlp->notify_ind.dl_addr_length -
15584 				    ABS(ill->ill_sap_length);
15585 				mutex_exit(&ill->ill_lock);
15586 				break;
15587 			} else if (dlp->notify_ind.dl_data ==
15588 			    DL_CURR_PHYS_ADDR) {
15589 				if (ill->ill_phys_addr_mp != NULL)
15590 					freemsg(ill->ill_phys_addr_mp);
15591 				ill->ill_phys_addr_mp = mp_hw;
15592 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15593 				    dlp->notify_ind.dl_addr_offset;
15594 				ill->ill_phys_addr_length =
15595 				    dlp->notify_ind.dl_addr_length -
15596 				    ABS(ill->ill_sap_length);
15597 				if (ill->ill_isv6 &&
15598 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15599 					if (ill->ill_nd_lla_mp != NULL)
15600 						freemsg(ill->ill_nd_lla_mp);
15601 					ill->ill_nd_lla_mp = copyb(mp_hw);
15602 					ill->ill_nd_lla = (uchar_t *)
15603 					    ill->ill_nd_lla_mp->b_rptr +
15604 					    dlp->notify_ind.dl_addr_offset;
15605 					ill->ill_nd_lla_len =
15606 					    ill->ill_phys_addr_length;
15607 				}
15608 			}
15609 			mutex_exit(&ill->ill_lock);
15610 			/*
15611 			 * Send out gratuitous arp request for our new
15612 			 * hardware address.
15613 			 */
15614 			for (ipif = ill->ill_ipif; ipif != NULL;
15615 			    ipif = ipif->ipif_next) {
15616 				if (!(ipif->ipif_flags & IPIF_UP))
15617 					continue;
15618 				if (ill->ill_isv6) {
15619 					ipif_ndp_down(ipif);
15620 					/*
15621 					 * Set B_TRUE to enable
15622 					 * ipif_ndp_up() to send out
15623 					 * unsolicited advertisements.
15624 					 */
15625 					err = ipif_ndp_up(ipif,
15626 					    &ipif->ipif_v6lcl_addr,
15627 					    B_TRUE);
15628 					if (err) {
15629 						ip1dbg((
15630 						    "ip_rput_dlpi_writer: "
15631 						    "Failed to update ndp "
15632 						    "err %d\n", err));
15633 					}
15634 				} else {
15635 					/*
15636 					 * IPv4 ARP case
15637 					 *
15638 					 * Set Res_act_move, as we only want
15639 					 * ipif_resolver_up to send an
15640 					 * AR_ENTRY_ADD request up to
15641 					 * ARP.
15642 					 */
15643 					err = ipif_resolver_up(ipif,
15644 					    Res_act_move);
15645 					if (err) {
15646 						ip1dbg((
15647 						    "ip_rput_dlpi_writer: "
15648 						    "Failed to update arp "
15649 						    "err %d\n", err));
15650 					}
15651 				}
15652 			}
15653 			/*
15654 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15655 			 * case so that all old fastpath information can be
15656 			 * purged from IRE caches.
15657 			 */
15658 		/* FALLTHRU */
15659 		case DL_NOTE_FASTPATH_FLUSH:
15660 			/*
15661 			 * Any fastpath probe sent henceforth will get the
15662 			 * new fp mp. So we first delete any ires that are
15663 			 * waiting for the fastpath. Then walk all ires and
15664 			 * delete the ire or delete the fp mp. In the case of
15665 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15666 			 * recreate the ire's without going through a complex
15667 			 * ipif up/down dance. So we don't delete the ire
15668 			 * itself, but just the nce_fp_mp for these 2 ire's
15669 			 * In the case of the other ire's we delete the ire's
15670 			 * themselves. Access to nce_fp_mp is completely
15671 			 * protected by ire_lock for IRE_MIPRTUN and
15672 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15673 			 * other cases for performance.
15674 			 */
15675 			if (ill->ill_isv6) {
15676 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15677 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15678 				    NULL);
15679 			} else {
15680 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15681 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15682 				    IRE_CACHE | IRE_BROADCAST,
15683 				    ire_fastpath_flush, NULL, ill);
15684 				mutex_enter(&ire_mrtun_lock);
15685 				if (ire_mrtun_count != 0) {
15686 					mutex_exit(&ire_mrtun_lock);
15687 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15688 					    IRE_MIPRTUN, ire_fastpath_flush,
15689 					    NULL, ill);
15690 				} else {
15691 					mutex_exit(&ire_mrtun_lock);
15692 				}
15693 			}
15694 			break;
15695 		case DL_NOTE_SDU_SIZE:
15696 			/*
15697 			 * Change the MTU size of the interface, of all
15698 			 * attached ipif's, and of all relevant ire's.  The
15699 			 * new value's a uint32_t at notify->dl_data.
15700 			 * Mtu change Vs. new ire creation - protocol below.
15701 			 *
15702 			 * a Mark the ipif as IPIF_CHANGING.
15703 			 * b Set the new mtu in the ipif.
15704 			 * c Change the ire_max_frag on all affected ires
15705 			 * d Unmark the IPIF_CHANGING
15706 			 *
15707 			 * To see how the protocol works, assume an interface
15708 			 * route is also being added simultaneously by
15709 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15710 			 * the ire. If the ire is created before step a,
15711 			 * it will be cleaned up by step c. If the ire is
15712 			 * created after step d, it will see the new value of
15713 			 * ipif_mtu. Any attempt to create the ire between
15714 			 * steps a to d will fail because of the IPIF_CHANGING
15715 			 * flag. Note that ire_create() is passed a pointer to
15716 			 * the ipif_mtu, and not the value. During ire_add
15717 			 * under the bucket lock, the ire_max_frag of the
15718 			 * new ire being created is set from the ipif/ire from
15719 			 * which it is being derived.
15720 			 */
15721 			mutex_enter(&ill->ill_lock);
15722 			ill->ill_max_frag = (uint_t)notify->dl_data;
15723 
15724 			/*
15725 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15726 			 * leave it alone
15727 			 */
15728 			if (ill->ill_mtu_userspecified) {
15729 				mutex_exit(&ill->ill_lock);
15730 				break;
15731 			}
15732 			ill->ill_max_mtu = ill->ill_max_frag;
15733 			if (ill->ill_isv6) {
15734 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15735 					ill->ill_max_mtu = IPV6_MIN_MTU;
15736 			} else {
15737 				if (ill->ill_max_mtu < IP_MIN_MTU)
15738 					ill->ill_max_mtu = IP_MIN_MTU;
15739 			}
15740 			for (ipif = ill->ill_ipif; ipif != NULL;
15741 			    ipif = ipif->ipif_next) {
15742 				/*
15743 				 * Don't override the mtu if the user
15744 				 * has explicitly set it.
15745 				 */
15746 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15747 					continue;
15748 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15749 				if (ipif->ipif_isv6)
15750 					ire = ipif_to_ire_v6(ipif);
15751 				else
15752 					ire = ipif_to_ire(ipif);
15753 				if (ire != NULL) {
15754 					ire->ire_max_frag = ipif->ipif_mtu;
15755 					ire_refrele(ire);
15756 				}
15757 				if (ipif->ipif_flags & IPIF_UP) {
15758 					if (ill->ill_isv6)
15759 						need_ire_walk_v6 = B_TRUE;
15760 					else
15761 						need_ire_walk_v4 = B_TRUE;
15762 				}
15763 			}
15764 			mutex_exit(&ill->ill_lock);
15765 			if (need_ire_walk_v4)
15766 				ire_walk_v4(ill_mtu_change, (char *)ill,
15767 				    ALL_ZONES);
15768 			if (need_ire_walk_v6)
15769 				ire_walk_v6(ill_mtu_change, (char *)ill,
15770 				    ALL_ZONES);
15771 			break;
15772 		case DL_NOTE_LINK_UP:
15773 		case DL_NOTE_LINK_DOWN: {
15774 			/*
15775 			 * We are writer. ill / phyint / ipsq assocs stable.
15776 			 * The RUNNING flag reflects the state of the link.
15777 			 */
15778 			phyint_t *phyint = ill->ill_phyint;
15779 			uint64_t new_phyint_flags;
15780 			boolean_t changed = B_FALSE;
15781 			boolean_t went_up;
15782 
15783 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15784 			mutex_enter(&phyint->phyint_lock);
15785 			new_phyint_flags = went_up ?
15786 			    phyint->phyint_flags | PHYI_RUNNING :
15787 			    phyint->phyint_flags & ~PHYI_RUNNING;
15788 			if (new_phyint_flags != phyint->phyint_flags) {
15789 				phyint->phyint_flags = new_phyint_flags;
15790 				changed = B_TRUE;
15791 			}
15792 			mutex_exit(&phyint->phyint_lock);
15793 			/*
15794 			 * ill_restart_dad handles the DAD restart and routing
15795 			 * socket notification logic.
15796 			 */
15797 			if (changed) {
15798 				ill_restart_dad(phyint->phyint_illv4, went_up);
15799 				ill_restart_dad(phyint->phyint_illv6, went_up);
15800 			}
15801 			break;
15802 		}
15803 		case DL_NOTE_PROMISC_ON_PHYS:
15804 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15805 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15806 			mutex_enter(&ill->ill_lock);
15807 			ill->ill_promisc_on_phys = B_TRUE;
15808 			mutex_exit(&ill->ill_lock);
15809 			break;
15810 		case DL_NOTE_PROMISC_OFF_PHYS:
15811 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15812 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15813 			mutex_enter(&ill->ill_lock);
15814 			ill->ill_promisc_on_phys = B_FALSE;
15815 			mutex_exit(&ill->ill_lock);
15816 			break;
15817 		case DL_NOTE_CAPAB_RENEG:
15818 			/*
15819 			 * Something changed on the driver side.
15820 			 * It wants us to renegotiate the capabilities
15821 			 * on this ill. The most likely cause is the
15822 			 * aggregation interface under us where a
15823 			 * port got added or went away.
15824 			 *
15825 			 * We reset the capabilities and set the
15826 			 * state to IDS_RENG so that when the ack
15827 			 * comes back, we can start the
15828 			 * renegotiation process.
15829 			 */
15830 			ill_capability_reset(ill);
15831 			ill->ill_dlpi_capab_state = IDS_RENEG;
15832 			break;
15833 		default:
15834 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15835 			    "type 0x%x for DL_NOTIFY_IND\n",
15836 			    notify->dl_notification));
15837 			break;
15838 		}
15839 
15840 		/*
15841 		 * As this is an asynchronous operation, we
15842 		 * should not call ill_dlpi_done
15843 		 */
15844 		break;
15845 	}
15846 	case DL_NOTIFY_ACK: {
15847 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15848 
15849 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15850 			ill->ill_note_link = 1;
15851 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15852 		break;
15853 	}
15854 	case DL_PHYS_ADDR_ACK: {
15855 		/*
15856 		 * We should have an IOCTL waiting on this when request
15857 		 * sent by ill_dl_phys.
15858 		 * However, ill_dl_phys was called on an ill queue (from
15859 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15860 		 * ioctl is known to be pending on ill_wq.
15861 		 * There are two additional phys_addr_req's sent to the
15862 		 * driver to get the token and lla. ill_phys_addr_pend
15863 		 * keeps track of the last one sent so we know which
15864 		 * response we are dealing with. ill_dlpi_done will
15865 		 * update ill_phys_addr_pend when it sends the next req.
15866 		 * We don't complete the IOCTL until all three DL_PARs
15867 		 * have been attempted.
15868 		 *
15869 		 * We don't need any lock to update ill_nd_lla* fields,
15870 		 * since the ill is not yet up, We grab the lock just
15871 		 * for uniformity with other code that accesses ill_nd_lla.
15872 		 */
15873 		physaddr_req = ill->ill_phys_addr_pend;
15874 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15875 		if (physaddr_req == DL_IPV6_TOKEN ||
15876 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15877 			if (physaddr_req == DL_IPV6_TOKEN) {
15878 				/*
15879 				 * bcopy to low-order bits of ill_token
15880 				 *
15881 				 * XXX Temporary hack - currently,
15882 				 * all known tokens are 64 bits,
15883 				 * so I'll cheat for the moment.
15884 				 */
15885 				dlp = (union DL_primitives *)mp->b_rptr;
15886 
15887 				mutex_enter(&ill->ill_lock);
15888 				bcopy((uchar_t *)(mp->b_rptr +
15889 				dlp->physaddr_ack.dl_addr_offset),
15890 				(void *)&ill->ill_token.s6_addr32[2],
15891 				dlp->physaddr_ack.dl_addr_length);
15892 				ill->ill_token_length =
15893 					dlp->physaddr_ack.dl_addr_length;
15894 				mutex_exit(&ill->ill_lock);
15895 			} else {
15896 				ASSERT(ill->ill_nd_lla_mp == NULL);
15897 				mp_hw = copyb(mp);
15898 				if (mp_hw == NULL) {
15899 					err = ENOMEM;
15900 					break;
15901 				}
15902 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15903 				mutex_enter(&ill->ill_lock);
15904 				ill->ill_nd_lla_mp = mp_hw;
15905 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15906 				dlp->physaddr_ack.dl_addr_offset;
15907 				ill->ill_nd_lla_len =
15908 					dlp->physaddr_ack.dl_addr_length;
15909 				mutex_exit(&ill->ill_lock);
15910 			}
15911 			break;
15912 		}
15913 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15914 		ASSERT(ill->ill_phys_addr_mp == NULL);
15915 		if (!ill->ill_ifname_pending)
15916 			break;
15917 		ill->ill_ifname_pending = 0;
15918 		if (!ioctl_aborted)
15919 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15920 		if (mp1 != NULL) {
15921 			ASSERT(connp == NULL);
15922 			q = ill->ill_wq;
15923 		}
15924 		/*
15925 		 * If any error acks received during the plumbing sequence,
15926 		 * ill_ifname_pending_err will be set. Break out and send up
15927 		 * the error to the pending ioctl.
15928 		 */
15929 		if (ill->ill_ifname_pending_err != 0) {
15930 			err = ill->ill_ifname_pending_err;
15931 			ill->ill_ifname_pending_err = 0;
15932 			break;
15933 		}
15934 		/*
15935 		 * Get the interface token.  If the zeroth interface
15936 		 * address is zero then set the address to the link local
15937 		 * address
15938 		 */
15939 		mp_hw = copyb(mp);
15940 		if (mp_hw == NULL) {
15941 			err = ENOMEM;
15942 			break;
15943 		}
15944 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15945 		ill->ill_phys_addr_mp = mp_hw;
15946 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15947 				dlp->physaddr_ack.dl_addr_offset;
15948 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15949 		    ill->ill_phys_addr_length == 0 ||
15950 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15951 			/*
15952 			 * Compatibility: atun driver returns a length of 0.
15953 			 * ipdptp has an ill_phys_addr_length of zero(from
15954 			 * DL_BIND_ACK) but a non-zero length here.
15955 			 * ipd has an ill_phys_addr_length of 4(from
15956 			 * DL_BIND_ACK) but a non-zero length here.
15957 			 */
15958 			ill->ill_phys_addr = NULL;
15959 		} else if (dlp->physaddr_ack.dl_addr_length !=
15960 		    ill->ill_phys_addr_length) {
15961 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15962 			    "Address length mismatch %d %d\n",
15963 			    dlp->physaddr_ack.dl_addr_length,
15964 			    ill->ill_phys_addr_length));
15965 			err = EINVAL;
15966 			break;
15967 		}
15968 		mutex_enter(&ill->ill_lock);
15969 		if (ill->ill_nd_lla_mp == NULL) {
15970 			ill->ill_nd_lla_mp = copyb(mp_hw);
15971 			if (ill->ill_nd_lla_mp == NULL) {
15972 				err = ENOMEM;
15973 				mutex_exit(&ill->ill_lock);
15974 				break;
15975 			}
15976 			ill->ill_nd_lla =
15977 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15978 			    dlp->physaddr_ack.dl_addr_offset;
15979 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15980 		}
15981 		mutex_exit(&ill->ill_lock);
15982 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15983 			(void) ill_setdefaulttoken(ill);
15984 
15985 		/*
15986 		 * If the ill zero interface has a zero address assign
15987 		 * it the proper link local address.
15988 		 */
15989 		ASSERT(ill->ill_ipif->ipif_id == 0);
15990 		if (ipif != NULL &&
15991 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15992 			(void) ipif_setlinklocal(ipif);
15993 		break;
15994 	}
15995 	case DL_OK_ACK:
15996 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15997 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15998 		    dloa->dl_correct_primitive));
15999 		switch (dloa->dl_correct_primitive) {
16000 		case DL_UNBIND_REQ:
16001 		case DL_ATTACH_REQ:
16002 		case DL_DETACH_REQ:
16003 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16004 			break;
16005 		}
16006 		break;
16007 	default:
16008 		break;
16009 	}
16010 
16011 	freemsg(mp);
16012 	if (mp1) {
16013 		struct iocblk *iocp;
16014 		int mode;
16015 
16016 		/*
16017 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
16018 		 * SIOCSLIFNAME do a copyout.
16019 		 */
16020 		iocp = (struct iocblk *)mp1->b_rptr;
16021 
16022 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16023 		    iocp->ioc_cmd == SIOCSLIFNAME)
16024 			mode = COPYOUT;
16025 		else
16026 			mode = NO_COPYOUT;
16027 		/*
16028 		 * The ioctl must complete now without EINPROGRESS
16029 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16030 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16031 		 * stuck for ever in the ipsq.
16032 		 */
16033 		ASSERT(err != EINPROGRESS);
16034 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16035 
16036 	}
16037 }
16038 
16039 /*
16040  * ip_rput_other is called by ip_rput to handle messages modifying the global
16041  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16042  */
16043 /* ARGSUSED */
16044 void
16045 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16046 {
16047 	ill_t		*ill;
16048 	struct iocblk	*iocp;
16049 	mblk_t		*mp1;
16050 	conn_t		*connp = NULL;
16051 
16052 	ip1dbg(("ip_rput_other "));
16053 	ill = (ill_t *)q->q_ptr;
16054 	/*
16055 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16056 	 * in which case ipsq is NULL.
16057 	 */
16058 	if (ipsq != NULL) {
16059 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16060 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16061 	}
16062 
16063 	switch (mp->b_datap->db_type) {
16064 	case M_ERROR:
16065 	case M_HANGUP:
16066 		/*
16067 		 * The device has a problem.  We force the ILL down.  It can
16068 		 * be brought up again manually using SIOCSIFFLAGS (via
16069 		 * ifconfig or equivalent).
16070 		 */
16071 		ASSERT(ipsq != NULL);
16072 		if (mp->b_rptr < mp->b_wptr)
16073 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16074 		if (ill->ill_error == 0)
16075 			ill->ill_error = ENXIO;
16076 		if (!ill_down_start(q, mp))
16077 			return;
16078 		ipif_all_down_tail(ipsq, q, mp, NULL);
16079 		break;
16080 	case M_IOCACK:
16081 		iocp = (struct iocblk *)mp->b_rptr;
16082 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16083 		switch (iocp->ioc_cmd) {
16084 		case SIOCSTUNPARAM:
16085 		case OSIOCSTUNPARAM:
16086 			ASSERT(ipsq != NULL);
16087 			/*
16088 			 * Finish socket ioctl passed through to tun.
16089 			 * We should have an IOCTL waiting on this.
16090 			 */
16091 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16092 			if (ill->ill_isv6) {
16093 				struct iftun_req *ta;
16094 
16095 				/*
16096 				 * if a source or destination is
16097 				 * being set, try and set the link
16098 				 * local address for the tunnel
16099 				 */
16100 				ta = (struct iftun_req *)mp->b_cont->
16101 				    b_cont->b_rptr;
16102 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16103 					ipif_set_tun_llink(ill, ta);
16104 				}
16105 
16106 			}
16107 			if (mp1 != NULL) {
16108 				/*
16109 				 * Now copy back the b_next/b_prev used by
16110 				 * mi code for the mi_copy* functions.
16111 				 * See ip_sioctl_tunparam() for the reason.
16112 				 * Also protect against missing b_cont.
16113 				 */
16114 				if (mp->b_cont != NULL) {
16115 					mp->b_cont->b_next =
16116 					    mp1->b_cont->b_next;
16117 					mp->b_cont->b_prev =
16118 					    mp1->b_cont->b_prev;
16119 				}
16120 				inet_freemsg(mp1);
16121 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16122 				ASSERT(connp != NULL);
16123 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16124 				    iocp->ioc_error, NO_COPYOUT,
16125 				    ipsq->ipsq_current_ipif, ipsq);
16126 			} else {
16127 				ASSERT(connp == NULL);
16128 				putnext(q, mp);
16129 			}
16130 			break;
16131 		case SIOCGTUNPARAM:
16132 		case OSIOCGTUNPARAM:
16133 			/*
16134 			 * This is really M_IOCDATA from the tunnel driver.
16135 			 * convert back and complete the ioctl.
16136 			 * We should have an IOCTL waiting on this.
16137 			 */
16138 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16139 			if (mp1) {
16140 				/*
16141 				 * Now copy back the b_next/b_prev used by
16142 				 * mi code for the mi_copy* functions.
16143 				 * See ip_sioctl_tunparam() for the reason.
16144 				 * Also protect against missing b_cont.
16145 				 */
16146 				if (mp->b_cont != NULL) {
16147 					mp->b_cont->b_next =
16148 					    mp1->b_cont->b_next;
16149 					mp->b_cont->b_prev =
16150 					    mp1->b_cont->b_prev;
16151 				}
16152 				inet_freemsg(mp1);
16153 				if (iocp->ioc_error == 0)
16154 					mp->b_datap->db_type = M_IOCDATA;
16155 				ASSERT(connp != NULL);
16156 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16157 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16158 			} else {
16159 				ASSERT(connp == NULL);
16160 				putnext(q, mp);
16161 			}
16162 			break;
16163 		default:
16164 			break;
16165 		}
16166 		break;
16167 	case M_IOCNAK:
16168 		iocp = (struct iocblk *)mp->b_rptr;
16169 
16170 		switch (iocp->ioc_cmd) {
16171 		int mode;
16172 		ipif_t	*ipif;
16173 
16174 		case DL_IOC_HDR_INFO:
16175 			/*
16176 			 * If this was the first attempt turn of the
16177 			 * fastpath probing.
16178 			 */
16179 			mutex_enter(&ill->ill_lock);
16180 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16181 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16182 				mutex_exit(&ill->ill_lock);
16183 				ill_fastpath_nack(ill);
16184 				ip1dbg(("ip_rput: DLPI fastpath off on "
16185 				    "interface %s\n",
16186 				    ill->ill_name));
16187 			} else {
16188 				mutex_exit(&ill->ill_lock);
16189 			}
16190 			freemsg(mp);
16191 			break;
16192 		case SIOCSTUNPARAM:
16193 		case OSIOCSTUNPARAM:
16194 			ASSERT(ipsq != NULL);
16195 			/*
16196 			 * Finish socket ioctl passed through to tun
16197 			 * We should have an IOCTL waiting on this.
16198 			 */
16199 			/* FALLTHRU */
16200 		case SIOCGTUNPARAM:
16201 		case OSIOCGTUNPARAM:
16202 			/*
16203 			 * This is really M_IOCDATA from the tunnel driver.
16204 			 * convert back and complete the ioctl.
16205 			 * We should have an IOCTL waiting on this.
16206 			 */
16207 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16208 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16209 				mp1 = ill_pending_mp_get(ill, &connp,
16210 				    iocp->ioc_id);
16211 				mode = COPYOUT;
16212 				ipsq = NULL;
16213 				ipif = NULL;
16214 			} else {
16215 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16216 				mode = NO_COPYOUT;
16217 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16218 				ipif = ipsq->ipsq_current_ipif;
16219 			}
16220 			if (mp1 != NULL) {
16221 				/*
16222 				 * Now copy back the b_next/b_prev used by
16223 				 * mi code for the mi_copy* functions.
16224 				 * See ip_sioctl_tunparam() for the reason.
16225 				 * Also protect against missing b_cont.
16226 				 */
16227 				if (mp->b_cont != NULL) {
16228 					mp->b_cont->b_next =
16229 					    mp1->b_cont->b_next;
16230 					mp->b_cont->b_prev =
16231 					    mp1->b_cont->b_prev;
16232 				}
16233 				inet_freemsg(mp1);
16234 				if (iocp->ioc_error == 0)
16235 					iocp->ioc_error = EINVAL;
16236 				ASSERT(connp != NULL);
16237 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16238 				    iocp->ioc_error, mode, ipif, ipsq);
16239 			} else {
16240 				ASSERT(connp == NULL);
16241 				putnext(q, mp);
16242 			}
16243 			break;
16244 		default:
16245 			break;
16246 		}
16247 	default:
16248 		break;
16249 	}
16250 }
16251 
16252 /*
16253  * NOTE : This function does not ire_refrele the ire argument passed in.
16254  *
16255  * IPQoS notes
16256  * IP policy is invoked twice for a forwarded packet, once on the read side
16257  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16258  * enabled. An additional parameter, in_ill, has been added for this purpose.
16259  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16260  * because ip_mroute drops this information.
16261  *
16262  */
16263 void
16264 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16265 {
16266 	uint32_t	pkt_len;
16267 	queue_t	*q;
16268 	uint32_t	sum;
16269 #define	rptr	((uchar_t *)ipha)
16270 	uint32_t	max_frag;
16271 	uint32_t	ill_index;
16272 	ill_t		*out_ill;
16273 
16274 	/* Get the ill_index of the incoming ILL */
16275 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16276 
16277 	/* Initiate Read side IPPF processing */
16278 	if (IPP_ENABLED(IPP_FWD_IN)) {
16279 		ip_process(IPP_FWD_IN, &mp, ill_index);
16280 		if (mp == NULL) {
16281 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16282 			    "during IPPF processing\n"));
16283 			return;
16284 		}
16285 	}
16286 
16287 	pkt_len = ntohs(ipha->ipha_length);
16288 
16289 	/* Adjust the checksum to reflect the ttl decrement. */
16290 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16291 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16292 
16293 	if (ipha->ipha_ttl-- <= 1) {
16294 		if (ip_csum_hdr(ipha)) {
16295 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16296 			goto drop_pkt;
16297 		}
16298 		/*
16299 		 * Note: ire_stq this will be NULL for multicast
16300 		 * datagrams using the long path through arp (the IRE
16301 		 * is not an IRE_CACHE). This should not cause
16302 		 * problems since we don't generate ICMP errors for
16303 		 * multicast packets.
16304 		 */
16305 		q = ire->ire_stq;
16306 		if (q != NULL) {
16307 			/* Sent by forwarding path, and router is global zone */
16308 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16309 			    GLOBAL_ZONEID);
16310 		} else
16311 			freemsg(mp);
16312 		return;
16313 	}
16314 
16315 	/*
16316 	 * Don't forward if the interface is down
16317 	 */
16318 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16319 		BUMP_MIB(&ip_mib, ipInDiscards);
16320 		ip2dbg(("ip_rput_forward:interface is down\n"));
16321 		goto drop_pkt;
16322 	}
16323 
16324 	/* Get the ill_index of the outgoing ILL */
16325 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16326 
16327 	out_ill = ire->ire_ipif->ipif_ill;
16328 
16329 	DTRACE_PROBE4(ip4__forwarding__start,
16330 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16331 
16332 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16333 	    in_ill, out_ill, ipha, mp, mp);
16334 
16335 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16336 
16337 	if (mp == NULL)
16338 		return;
16339 	pkt_len = ntohs(ipha->ipha_length);
16340 
16341 	if (is_system_labeled()) {
16342 		mblk_t *mp1;
16343 
16344 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16345 			BUMP_MIB(&ip_mib, ipForwProhibits);
16346 			goto drop_pkt;
16347 		}
16348 		/* Size may have changed */
16349 		mp = mp1;
16350 		ipha = (ipha_t *)mp->b_rptr;
16351 		pkt_len = ntohs(ipha->ipha_length);
16352 	}
16353 
16354 	/* Check if there are options to update */
16355 	if (!IS_SIMPLE_IPH(ipha)) {
16356 		if (ip_csum_hdr(ipha)) {
16357 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16358 			goto drop_pkt;
16359 		}
16360 		if (ip_rput_forward_options(mp, ipha, ire)) {
16361 			return;
16362 		}
16363 
16364 		ipha->ipha_hdr_checksum = 0;
16365 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16366 	}
16367 	max_frag = ire->ire_max_frag;
16368 	if (pkt_len > max_frag) {
16369 		/*
16370 		 * It needs fragging on its way out.  We haven't
16371 		 * verified the header checksum yet.  Since we
16372 		 * are going to put a surely good checksum in the
16373 		 * outgoing header, we have to make sure that it
16374 		 * was good coming in.
16375 		 */
16376 		if (ip_csum_hdr(ipha)) {
16377 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16378 			goto drop_pkt;
16379 		}
16380 		/* Initiate Write side IPPF processing */
16381 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16382 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16383 			if (mp == NULL) {
16384 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16385 				    " during IPPF processing\n"));
16386 				return;
16387 			}
16388 		}
16389 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16390 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16391 		return;
16392 	}
16393 
16394 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16395 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16396 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16397 	    NULL, out_ill, ipha, mp, mp);
16398 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16399 	if (mp == NULL)
16400 		return;
16401 
16402 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16403 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16404 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16405 	/* ip_xmit_v4 always consumes the packet */
16406 	return;
16407 
16408 drop_pkt:;
16409 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16410 	freemsg(mp);
16411 #undef	rptr
16412 }
16413 
16414 void
16415 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16416 {
16417 	ire_t	*ire;
16418 
16419 	ASSERT(!ipif->ipif_isv6);
16420 	/*
16421 	 * Find an IRE which matches the destination and the outgoing
16422 	 * queue in the cache table. All we need is an IRE_CACHE which
16423 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16424 	 * then it is enough to have some IRE_CACHE in the group.
16425 	 */
16426 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16427 		dst = ipif->ipif_pp_dst_addr;
16428 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16429 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16430 	if (ire == NULL) {
16431 		/*
16432 		 * Mark this packet to make it be delivered to
16433 		 * ip_rput_forward after the new ire has been
16434 		 * created.
16435 		 */
16436 		mp->b_prev = NULL;
16437 		mp->b_next = mp;
16438 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16439 		    NULL, 0, GLOBAL_ZONEID);
16440 	} else {
16441 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16442 		IRE_REFRELE(ire);
16443 	}
16444 }
16445 
16446 /* Update any source route, record route or timestamp options */
16447 static int
16448 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16449 {
16450 	ipoptp_t	opts;
16451 	uchar_t		*opt;
16452 	uint8_t		optval;
16453 	uint8_t		optlen;
16454 	ipaddr_t	dst;
16455 	uint32_t	ts;
16456 	ire_t		*dst_ire = NULL;
16457 	ire_t		*tmp_ire = NULL;
16458 	timestruc_t	now;
16459 
16460 	ip2dbg(("ip_rput_forward_options\n"));
16461 	dst = ipha->ipha_dst;
16462 	for (optval = ipoptp_first(&opts, ipha);
16463 	    optval != IPOPT_EOL;
16464 	    optval = ipoptp_next(&opts)) {
16465 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16466 		opt = opts.ipoptp_cur;
16467 		optlen = opts.ipoptp_len;
16468 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16469 		    optval, opts.ipoptp_len));
16470 		switch (optval) {
16471 			uint32_t off;
16472 		case IPOPT_SSRR:
16473 		case IPOPT_LSRR:
16474 			/* Check if adminstratively disabled */
16475 			if (!ip_forward_src_routed) {
16476 				BUMP_MIB(&ip_mib, ipForwProhibits);
16477 				if (ire->ire_stq != NULL) {
16478 					/*
16479 					 * Sent by forwarding path, and router
16480 					 * is global zone
16481 					 */
16482 					icmp_unreachable(ire->ire_stq, mp,
16483 					    ICMP_SOURCE_ROUTE_FAILED,
16484 					    GLOBAL_ZONEID);
16485 				} else {
16486 					ip0dbg(("ip_rput_forward_options: "
16487 					    "unable to send unreach\n"));
16488 					freemsg(mp);
16489 				}
16490 				return (-1);
16491 			}
16492 
16493 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16494 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16495 			if (dst_ire == NULL) {
16496 				/*
16497 				 * Must be partial since ip_rput_options
16498 				 * checked for strict.
16499 				 */
16500 				break;
16501 			}
16502 			off = opt[IPOPT_OFFSET];
16503 			off--;
16504 		redo_srr:
16505 			if (optlen < IP_ADDR_LEN ||
16506 			    off > optlen - IP_ADDR_LEN) {
16507 				/* End of source route */
16508 				ip1dbg((
16509 				    "ip_rput_forward_options: end of SR\n"));
16510 				ire_refrele(dst_ire);
16511 				break;
16512 			}
16513 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16514 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16515 			    IP_ADDR_LEN);
16516 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16517 			    ntohl(dst)));
16518 
16519 			/*
16520 			 * Check if our address is present more than
16521 			 * once as consecutive hops in source route.
16522 			 */
16523 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16524 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16525 			if (tmp_ire != NULL) {
16526 				ire_refrele(tmp_ire);
16527 				off += IP_ADDR_LEN;
16528 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16529 				goto redo_srr;
16530 			}
16531 			ipha->ipha_dst = dst;
16532 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16533 			ire_refrele(dst_ire);
16534 			break;
16535 		case IPOPT_RR:
16536 			off = opt[IPOPT_OFFSET];
16537 			off--;
16538 			if (optlen < IP_ADDR_LEN ||
16539 			    off > optlen - IP_ADDR_LEN) {
16540 				/* No more room - ignore */
16541 				ip1dbg((
16542 				    "ip_rput_forward_options: end of RR\n"));
16543 				break;
16544 			}
16545 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16546 			    IP_ADDR_LEN);
16547 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16548 			break;
16549 		case IPOPT_TS:
16550 			/* Insert timestamp if there is room */
16551 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16552 			case IPOPT_TS_TSONLY:
16553 				off = IPOPT_TS_TIMELEN;
16554 				break;
16555 			case IPOPT_TS_PRESPEC:
16556 			case IPOPT_TS_PRESPEC_RFC791:
16557 				/* Verify that the address matched */
16558 				off = opt[IPOPT_OFFSET] - 1;
16559 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16560 				dst_ire = ire_ctable_lookup(dst, 0,
16561 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16562 				    MATCH_IRE_TYPE);
16563 
16564 				if (dst_ire == NULL) {
16565 					/* Not for us */
16566 					break;
16567 				}
16568 				ire_refrele(dst_ire);
16569 				/* FALLTHRU */
16570 			case IPOPT_TS_TSANDADDR:
16571 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16572 				break;
16573 			default:
16574 				/*
16575 				 * ip_*put_options should have already
16576 				 * dropped this packet.
16577 				 */
16578 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16579 				    "unknown IT - bug in ip_rput_options?\n");
16580 				return (0);	/* Keep "lint" happy */
16581 			}
16582 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16583 				/* Increase overflow counter */
16584 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16585 				opt[IPOPT_POS_OV_FLG] =
16586 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16587 				    (off << 4));
16588 				break;
16589 			}
16590 			off = opt[IPOPT_OFFSET] - 1;
16591 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16592 			case IPOPT_TS_PRESPEC:
16593 			case IPOPT_TS_PRESPEC_RFC791:
16594 			case IPOPT_TS_TSANDADDR:
16595 				bcopy(&ire->ire_src_addr,
16596 				    (char *)opt + off, IP_ADDR_LEN);
16597 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16598 				/* FALLTHRU */
16599 			case IPOPT_TS_TSONLY:
16600 				off = opt[IPOPT_OFFSET] - 1;
16601 				/* Compute # of milliseconds since midnight */
16602 				gethrestime(&now);
16603 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16604 				    now.tv_nsec / (NANOSEC / MILLISEC);
16605 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16606 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16607 				break;
16608 			}
16609 			break;
16610 		}
16611 	}
16612 	return (0);
16613 }
16614 
16615 /*
16616  * This is called after processing at least one of AH/ESP headers.
16617  *
16618  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16619  * the actual, physical interface on which the packet was received,
16620  * but, when ip_strict_dst_multihoming is set to 1, could be the
16621  * interface which had the ipha_dst configured when the packet went
16622  * through ip_rput. The ill_index corresponding to the recv_ill
16623  * is saved in ipsec_in_rill_index
16624  */
16625 void
16626 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16627 {
16628 	mblk_t *mp;
16629 	ipaddr_t dst;
16630 	in6_addr_t *v6dstp;
16631 	ipha_t *ipha;
16632 	ip6_t *ip6h;
16633 	ipsec_in_t *ii;
16634 	boolean_t ill_need_rele = B_FALSE;
16635 	boolean_t rill_need_rele = B_FALSE;
16636 	boolean_t ire_need_rele = B_FALSE;
16637 
16638 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16639 	ASSERT(ii->ipsec_in_ill_index != 0);
16640 
16641 	mp = ipsec_mp->b_cont;
16642 	ASSERT(mp != NULL);
16643 
16644 
16645 	if (ill == NULL) {
16646 		ASSERT(recv_ill == NULL);
16647 		/*
16648 		 * We need to get the original queue on which ip_rput_local
16649 		 * or ip_rput_data_v6 was called.
16650 		 */
16651 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16652 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16653 		ill_need_rele = B_TRUE;
16654 
16655 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16656 			recv_ill = ill_lookup_on_ifindex(
16657 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16658 			    NULL, NULL, NULL, NULL);
16659 			rill_need_rele = B_TRUE;
16660 		} else {
16661 			recv_ill = ill;
16662 		}
16663 
16664 		if ((ill == NULL) || (recv_ill == NULL)) {
16665 			ip0dbg(("ip_fanout_proto_again: interface "
16666 			    "disappeared\n"));
16667 			if (ill != NULL)
16668 				ill_refrele(ill);
16669 			if (recv_ill != NULL)
16670 				ill_refrele(recv_ill);
16671 			freemsg(ipsec_mp);
16672 			return;
16673 		}
16674 	}
16675 
16676 	ASSERT(ill != NULL && recv_ill != NULL);
16677 
16678 	if (mp->b_datap->db_type == M_CTL) {
16679 		/*
16680 		 * AH/ESP is returning the ICMP message after
16681 		 * removing their headers. Fanout again till
16682 		 * it gets to the right protocol.
16683 		 */
16684 		if (ii->ipsec_in_v4) {
16685 			icmph_t *icmph;
16686 			int iph_hdr_length;
16687 			int hdr_length;
16688 
16689 			ipha = (ipha_t *)mp->b_rptr;
16690 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16691 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16692 			ipha = (ipha_t *)&icmph[1];
16693 			hdr_length = IPH_HDR_LENGTH(ipha);
16694 			/*
16695 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16696 			 * Reset the type to M_DATA.
16697 			 */
16698 			mp->b_datap->db_type = M_DATA;
16699 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16700 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16701 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16702 		} else {
16703 			icmp6_t *icmp6;
16704 			int hdr_length;
16705 
16706 			ip6h = (ip6_t *)mp->b_rptr;
16707 			/* Don't call hdr_length_v6() unless you have to. */
16708 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16709 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16710 			else
16711 				hdr_length = IPV6_HDR_LEN;
16712 
16713 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16714 			/*
16715 			 * icmp_inbound_error_fanout_v6 may need to do
16716 			 * pullupmsg.  Reset the type to M_DATA.
16717 			 */
16718 			mp->b_datap->db_type = M_DATA;
16719 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16720 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16721 		}
16722 		if (ill_need_rele)
16723 			ill_refrele(ill);
16724 		if (rill_need_rele)
16725 			ill_refrele(recv_ill);
16726 		return;
16727 	}
16728 
16729 	if (ii->ipsec_in_v4) {
16730 		ipha = (ipha_t *)mp->b_rptr;
16731 		dst = ipha->ipha_dst;
16732 		if (CLASSD(dst)) {
16733 			/*
16734 			 * Multicast has to be delivered to all streams.
16735 			 */
16736 			dst = INADDR_BROADCAST;
16737 		}
16738 
16739 		if (ire == NULL) {
16740 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16741 			    MBLK_GETLABEL(mp));
16742 			if (ire == NULL) {
16743 				if (ill_need_rele)
16744 					ill_refrele(ill);
16745 				if (rill_need_rele)
16746 					ill_refrele(recv_ill);
16747 				ip1dbg(("ip_fanout_proto_again: "
16748 				    "IRE not found"));
16749 				freemsg(ipsec_mp);
16750 				return;
16751 			}
16752 			ire_need_rele = B_TRUE;
16753 		}
16754 
16755 		switch (ipha->ipha_protocol) {
16756 			case IPPROTO_UDP:
16757 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16758 				    recv_ill);
16759 				if (ire_need_rele)
16760 					ire_refrele(ire);
16761 				break;
16762 			case IPPROTO_TCP:
16763 				if (!ire_need_rele)
16764 					IRE_REFHOLD(ire);
16765 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16766 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16767 				IRE_REFRELE(ire);
16768 				if (mp != NULL)
16769 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16770 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16771 				break;
16772 			case IPPROTO_SCTP:
16773 				if (!ire_need_rele)
16774 					IRE_REFHOLD(ire);
16775 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16776 				    ipsec_mp, 0, ill->ill_rq, dst);
16777 				break;
16778 			default:
16779 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16780 				    recv_ill);
16781 				if (ire_need_rele)
16782 					ire_refrele(ire);
16783 				break;
16784 		}
16785 	} else {
16786 		uint32_t rput_flags = 0;
16787 
16788 		ip6h = (ip6_t *)mp->b_rptr;
16789 		v6dstp = &ip6h->ip6_dst;
16790 		/*
16791 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16792 		 * address.
16793 		 *
16794 		 * Currently, we don't store that state in the IPSEC_IN
16795 		 * message, and we may need to.
16796 		 */
16797 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16798 		    IP6_IN_LLMCAST : 0);
16799 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16800 		    NULL, NULL);
16801 	}
16802 	if (ill_need_rele)
16803 		ill_refrele(ill);
16804 	if (rill_need_rele)
16805 		ill_refrele(recv_ill);
16806 }
16807 
16808 /*
16809  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16810  * returns 'true' if there are still fragments left on the queue, in
16811  * which case we restart the timer.
16812  */
16813 void
16814 ill_frag_timer(void *arg)
16815 {
16816 	ill_t	*ill = (ill_t *)arg;
16817 	boolean_t frag_pending;
16818 
16819 	mutex_enter(&ill->ill_lock);
16820 	ASSERT(!ill->ill_fragtimer_executing);
16821 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16822 		ill->ill_frag_timer_id = 0;
16823 		mutex_exit(&ill->ill_lock);
16824 		return;
16825 	}
16826 	ill->ill_fragtimer_executing = 1;
16827 	mutex_exit(&ill->ill_lock);
16828 
16829 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16830 
16831 	/*
16832 	 * Restart the timer, if we have fragments pending or if someone
16833 	 * wanted us to be scheduled again.
16834 	 */
16835 	mutex_enter(&ill->ill_lock);
16836 	ill->ill_fragtimer_executing = 0;
16837 	ill->ill_frag_timer_id = 0;
16838 	if (frag_pending || ill->ill_fragtimer_needrestart)
16839 		ill_frag_timer_start(ill);
16840 	mutex_exit(&ill->ill_lock);
16841 }
16842 
16843 void
16844 ill_frag_timer_start(ill_t *ill)
16845 {
16846 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16847 
16848 	/* If the ill is closing or opening don't proceed */
16849 	if (ill->ill_state_flags & ILL_CONDEMNED)
16850 		return;
16851 
16852 	if (ill->ill_fragtimer_executing) {
16853 		/*
16854 		 * ill_frag_timer is currently executing. Just record the
16855 		 * the fact that we want the timer to be restarted.
16856 		 * ill_frag_timer will post a timeout before it returns,
16857 		 * ensuring it will be called again.
16858 		 */
16859 		ill->ill_fragtimer_needrestart = 1;
16860 		return;
16861 	}
16862 
16863 	if (ill->ill_frag_timer_id == 0) {
16864 		/*
16865 		 * The timer is neither running nor is the timeout handler
16866 		 * executing. Post a timeout so that ill_frag_timer will be
16867 		 * called
16868 		 */
16869 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16870 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16871 		ill->ill_fragtimer_needrestart = 0;
16872 	}
16873 }
16874 
16875 /*
16876  * This routine is needed for loopback when forwarding multicasts.
16877  *
16878  * IPQoS Notes:
16879  * IPPF processing is done in fanout routines.
16880  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16881  * processing for IPSec packets is done when it comes back in clear.
16882  * NOTE : The callers of this function need to do the ire_refrele for the
16883  *	  ire that is being passed in.
16884  */
16885 void
16886 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16887     ill_t *recv_ill)
16888 {
16889 	ill_t	*ill = (ill_t *)q->q_ptr;
16890 	uint32_t	sum;
16891 	uint32_t	u1;
16892 	uint32_t	u2;
16893 	int		hdr_length;
16894 	boolean_t	mctl_present;
16895 	mblk_t		*first_mp = mp;
16896 	mblk_t		*hada_mp = NULL;
16897 	ipha_t		*inner_ipha;
16898 
16899 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16900 	    "ip_rput_locl_start: q %p", q);
16901 
16902 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16903 
16904 
16905 #define	rptr	((uchar_t *)ipha)
16906 #define	iphs	((uint16_t *)ipha)
16907 
16908 	/*
16909 	 * no UDP or TCP packet should come here anymore.
16910 	 */
16911 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16912 	    (ipha->ipha_protocol != IPPROTO_UDP));
16913 
16914 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16915 	if (mctl_present &&
16916 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16917 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16918 
16919 		/*
16920 		 * It's an IPsec accelerated packet.
16921 		 * Keep a pointer to the data attributes around until
16922 		 * we allocate the ipsec_info_t.
16923 		 */
16924 		IPSECHW_DEBUG(IPSECHW_PKT,
16925 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16926 		hada_mp = first_mp;
16927 		hada_mp->b_cont = NULL;
16928 		/*
16929 		 * Since it is accelerated, it comes directly from
16930 		 * the ill and the data attributes is followed by
16931 		 * the packet data.
16932 		 */
16933 		ASSERT(mp->b_datap->db_type != M_CTL);
16934 		first_mp = mp;
16935 		mctl_present = B_FALSE;
16936 	}
16937 
16938 	/*
16939 	 * IF M_CTL is not present, then ipsec_in_is_secure
16940 	 * should return B_TRUE. There is a case where loopback
16941 	 * packets has an M_CTL in the front with all the
16942 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16943 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16944 	 * packets never comes here, it is safe to ASSERT the
16945 	 * following.
16946 	 */
16947 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16948 
16949 
16950 	/* u1 is # words of IP options */
16951 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16952 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16953 
16954 	if (u1) {
16955 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16956 			if (hada_mp != NULL)
16957 				freemsg(hada_mp);
16958 			return;
16959 		}
16960 	} else {
16961 		/* Check the IP header checksum.  */
16962 #define	uph	((uint16_t *)ipha)
16963 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16964 		    uph[6] + uph[7] + uph[8] + uph[9];
16965 #undef  uph
16966 		/* finish doing IP checksum */
16967 		sum = (sum & 0xFFFF) + (sum >> 16);
16968 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16969 		/*
16970 		 * Don't verify header checksum if this packet is coming
16971 		 * back from AH/ESP as we already did it.
16972 		 */
16973 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16974 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16975 			goto drop_pkt;
16976 		}
16977 	}
16978 
16979 	/*
16980 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16981 	 * might be called more than once for secure packets, count only
16982 	 * the first time.
16983 	 */
16984 	if (!mctl_present) {
16985 		UPDATE_IB_PKT_COUNT(ire);
16986 		ire->ire_last_used_time = lbolt;
16987 	}
16988 
16989 	/* Check for fragmentation offset. */
16990 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16991 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16992 	if (u1) {
16993 		/*
16994 		 * We re-assemble fragments before we do the AH/ESP
16995 		 * processing. Thus, M_CTL should not be present
16996 		 * while we are re-assembling.
16997 		 */
16998 		ASSERT(!mctl_present);
16999 		ASSERT(first_mp == mp);
17000 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17001 			return;
17002 		}
17003 		/*
17004 		 * Make sure that first_mp points back to mp as
17005 		 * the mp we came in with could have changed in
17006 		 * ip_rput_fragment().
17007 		 */
17008 		ipha = (ipha_t *)mp->b_rptr;
17009 		first_mp = mp;
17010 	}
17011 
17012 	/*
17013 	 * Clear hardware checksumming flag as it is currently only
17014 	 * used by TCP and UDP.
17015 	 */
17016 	DB_CKSUMFLAGS(mp) = 0;
17017 
17018 	/* Now we have a complete datagram, destined for this machine. */
17019 	u1 = IPH_HDR_LENGTH(ipha);
17020 	switch (ipha->ipha_protocol) {
17021 	case IPPROTO_ICMP: {
17022 		ire_t		*ire_zone;
17023 		ilm_t		*ilm;
17024 		mblk_t		*mp1;
17025 		zoneid_t	last_zoneid;
17026 
17027 		if (CLASSD(ipha->ipha_dst) &&
17028 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17029 			ASSERT(ire->ire_type == IRE_BROADCAST);
17030 			/*
17031 			 * In the multicast case, applications may have joined
17032 			 * the group from different zones, so we need to deliver
17033 			 * the packet to each of them. Loop through the
17034 			 * multicast memberships structures (ilm) on the receive
17035 			 * ill and send a copy of the packet up each matching
17036 			 * one. However, we don't do this for multicasts sent on
17037 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17038 			 * they must stay in the sender's zone.
17039 			 *
17040 			 * ilm_add_v6() ensures that ilms in the same zone are
17041 			 * contiguous in the ill_ilm list. We use this property
17042 			 * to avoid sending duplicates needed when two
17043 			 * applications in the same zone join the same group on
17044 			 * different logical interfaces: we ignore the ilm if
17045 			 * its zoneid is the same as the last matching one.
17046 			 * In addition, the sending of the packet for
17047 			 * ire_zoneid is delayed until all of the other ilms
17048 			 * have been exhausted.
17049 			 */
17050 			last_zoneid = -1;
17051 			ILM_WALKER_HOLD(recv_ill);
17052 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17053 			    ilm = ilm->ilm_next) {
17054 				if ((ilm->ilm_flags & ILM_DELETED) ||
17055 				    ipha->ipha_dst != ilm->ilm_addr ||
17056 				    ilm->ilm_zoneid == last_zoneid ||
17057 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17058 				    ilm->ilm_zoneid == ALL_ZONES ||
17059 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17060 					continue;
17061 				mp1 = ip_copymsg(first_mp);
17062 				if (mp1 == NULL)
17063 					continue;
17064 				icmp_inbound(q, mp1, B_TRUE, ill,
17065 				    0, sum, mctl_present, B_TRUE,
17066 				    recv_ill, ilm->ilm_zoneid);
17067 				last_zoneid = ilm->ilm_zoneid;
17068 			}
17069 			ILM_WALKER_RELE(recv_ill);
17070 		} else if (ire->ire_type == IRE_BROADCAST) {
17071 			/*
17072 			 * In the broadcast case, there may be many zones
17073 			 * which need a copy of the packet delivered to them.
17074 			 * There is one IRE_BROADCAST per broadcast address
17075 			 * and per zone; we walk those using a helper function.
17076 			 * In addition, the sending of the packet for ire is
17077 			 * delayed until all of the other ires have been
17078 			 * processed.
17079 			 */
17080 			IRB_REFHOLD(ire->ire_bucket);
17081 			ire_zone = NULL;
17082 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17083 			    ire)) != NULL) {
17084 				mp1 = ip_copymsg(first_mp);
17085 				if (mp1 == NULL)
17086 					continue;
17087 
17088 				UPDATE_IB_PKT_COUNT(ire_zone);
17089 				ire_zone->ire_last_used_time = lbolt;
17090 				icmp_inbound(q, mp1, B_TRUE, ill,
17091 				    0, sum, mctl_present, B_TRUE,
17092 				    recv_ill, ire_zone->ire_zoneid);
17093 			}
17094 			IRB_REFRELE(ire->ire_bucket);
17095 		}
17096 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17097 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17098 		    ire->ire_zoneid);
17099 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17100 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17101 		return;
17102 	}
17103 	case IPPROTO_IGMP:
17104 		/*
17105 		 * If we are not willing to accept IGMP packets in clear,
17106 		 * then check with global policy.
17107 		 */
17108 		if (igmp_accept_clear_messages == 0) {
17109 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17110 			    ipha, NULL, mctl_present);
17111 			if (first_mp == NULL)
17112 				return;
17113 		}
17114 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17115 			freemsg(first_mp);
17116 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17117 			BUMP_MIB(&ip_mib, ipInDiscards);
17118 			return;
17119 		}
17120 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17121 			/* Bad packet - discarded by igmp_input */
17122 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17123 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17124 			if (mctl_present)
17125 				freeb(first_mp);
17126 			return;
17127 		}
17128 		/*
17129 		 * igmp_input() may have returned the pulled up message.
17130 		 * So first_mp and ipha need to be reinitialized.
17131 		 */
17132 		ipha = (ipha_t *)mp->b_rptr;
17133 		if (mctl_present)
17134 			first_mp->b_cont = mp;
17135 		else
17136 			first_mp = mp;
17137 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17138 			/* No user-level listener for IGMP packets */
17139 			goto drop_pkt;
17140 		}
17141 		/* deliver to local raw users */
17142 		break;
17143 	case IPPROTO_PIM:
17144 		/*
17145 		 * If we are not willing to accept PIM packets in clear,
17146 		 * then check with global policy.
17147 		 */
17148 		if (pim_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 PIM"));
17157 			BUMP_MIB(&ip_mib, ipInDiscards);
17158 			return;
17159 		}
17160 		if (pim_input(q, mp) != 0) {
17161 			/* Bad packet - discarded by pim_input */
17162 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17163 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17164 			if (mctl_present)
17165 				freeb(first_mp);
17166 			return;
17167 		}
17168 
17169 		/*
17170 		 * pim_input() may have pulled up the message so ipha needs to
17171 		 * be reinitialized.
17172 		 */
17173 		ipha = (ipha_t *)mp->b_rptr;
17174 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17175 			/* No user-level listener for PIM packets */
17176 			goto drop_pkt;
17177 		}
17178 		/* deliver to local raw users */
17179 		break;
17180 	case IPPROTO_ENCAP:
17181 		/*
17182 		 * Handle self-encapsulated packets (IP-in-IP where
17183 		 * the inner addresses == the outer addresses).
17184 		 */
17185 		hdr_length = IPH_HDR_LENGTH(ipha);
17186 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17187 		    mp->b_wptr) {
17188 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17189 			    sizeof (ipha_t) - mp->b_rptr)) {
17190 				BUMP_MIB(&ip_mib, ipInDiscards);
17191 				freemsg(first_mp);
17192 				return;
17193 			}
17194 			ipha = (ipha_t *)mp->b_rptr;
17195 		}
17196 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17197 		/*
17198 		 * Check the sanity of the inner IP header.
17199 		 */
17200 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17201 			BUMP_MIB(&ip_mib, ipInDiscards);
17202 			freemsg(first_mp);
17203 			return;
17204 		}
17205 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17206 			BUMP_MIB(&ip_mib, ipInDiscards);
17207 			freemsg(first_mp);
17208 			return;
17209 		}
17210 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17211 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17212 			ipsec_in_t *ii;
17213 
17214 			/*
17215 			 * Self-encapsulated tunnel packet. Remove
17216 			 * the outer IP header and fanout again.
17217 			 * We also need to make sure that the inner
17218 			 * header is pulled up until options.
17219 			 */
17220 			mp->b_rptr = (uchar_t *)inner_ipha;
17221 			ipha = inner_ipha;
17222 			hdr_length = IPH_HDR_LENGTH(ipha);
17223 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17224 				if (!pullupmsg(mp, (uchar_t *)ipha +
17225 				    + hdr_length - mp->b_rptr)) {
17226 					freemsg(first_mp);
17227 					return;
17228 				}
17229 				ipha = (ipha_t *)mp->b_rptr;
17230 			}
17231 			if (!mctl_present) {
17232 				ASSERT(first_mp == mp);
17233 				/*
17234 				 * This means that somebody is sending
17235 				 * Self-encapsualted packets without AH/ESP.
17236 				 * If AH/ESP was present, we would have already
17237 				 * allocated the first_mp.
17238 				 */
17239 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17240 				    NULL) {
17241 					ip1dbg(("ip_proto_input: IPSEC_IN "
17242 					    "allocation failure.\n"));
17243 					BUMP_MIB(&ip_mib, ipInDiscards);
17244 					freemsg(mp);
17245 					return;
17246 				}
17247 				first_mp->b_cont = mp;
17248 			}
17249 			/*
17250 			 * We generally store the ill_index if we need to
17251 			 * do IPSEC processing as we lose the ill queue when
17252 			 * we come back. But in this case, we never should
17253 			 * have to store the ill_index here as it should have
17254 			 * been stored previously when we processed the
17255 			 * AH/ESP header in this routine or for non-ipsec
17256 			 * cases, we still have the queue. But for some bad
17257 			 * packets from the wire, we can get to IPSEC after
17258 			 * this and we better store the index for that case.
17259 			 */
17260 			ill = (ill_t *)q->q_ptr;
17261 			ii = (ipsec_in_t *)first_mp->b_rptr;
17262 			ii->ipsec_in_ill_index =
17263 			    ill->ill_phyint->phyint_ifindex;
17264 			ii->ipsec_in_rill_index =
17265 			    recv_ill->ill_phyint->phyint_ifindex;
17266 			if (ii->ipsec_in_decaps) {
17267 				/*
17268 				 * This packet is self-encapsulated multiple
17269 				 * times. We don't want to recurse infinitely.
17270 				 * To keep it simple, drop the packet.
17271 				 */
17272 				BUMP_MIB(&ip_mib, ipInDiscards);
17273 				freemsg(first_mp);
17274 				return;
17275 			}
17276 			ii->ipsec_in_decaps = B_TRUE;
17277 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17278 			    ire);
17279 			return;
17280 		}
17281 		break;
17282 	case IPPROTO_AH:
17283 	case IPPROTO_ESP: {
17284 		/*
17285 		 * Fast path for AH/ESP. If this is the first time
17286 		 * we are sending a datagram to AH/ESP, allocate
17287 		 * a IPSEC_IN message and prepend it. Otherwise,
17288 		 * just fanout.
17289 		 */
17290 
17291 		int ipsec_rc;
17292 		ipsec_in_t *ii;
17293 
17294 		IP_STAT(ipsec_proto_ahesp);
17295 		if (!mctl_present) {
17296 			ASSERT(first_mp == mp);
17297 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17298 				ip1dbg(("ip_proto_input: IPSEC_IN "
17299 				    "allocation failure.\n"));
17300 				freemsg(hada_mp); /* okay ifnull */
17301 				BUMP_MIB(&ip_mib, ipInDiscards);
17302 				freemsg(mp);
17303 				return;
17304 			}
17305 			/*
17306 			 * Store the ill_index so that when we come back
17307 			 * from IPSEC we ride on the same queue.
17308 			 */
17309 			ill = (ill_t *)q->q_ptr;
17310 			ii = (ipsec_in_t *)first_mp->b_rptr;
17311 			ii->ipsec_in_ill_index =
17312 			    ill->ill_phyint->phyint_ifindex;
17313 			ii->ipsec_in_rill_index =
17314 			    recv_ill->ill_phyint->phyint_ifindex;
17315 			first_mp->b_cont = mp;
17316 			/*
17317 			 * Cache hardware acceleration info.
17318 			 */
17319 			if (hada_mp != NULL) {
17320 				IPSECHW_DEBUG(IPSECHW_PKT,
17321 				    ("ip_rput_local: caching data attr.\n"));
17322 				ii->ipsec_in_accelerated = B_TRUE;
17323 				ii->ipsec_in_da = hada_mp;
17324 				hada_mp = NULL;
17325 			}
17326 		} else {
17327 			ii = (ipsec_in_t *)first_mp->b_rptr;
17328 		}
17329 
17330 		if (!ipsec_loaded()) {
17331 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17332 			    ire->ire_zoneid);
17333 			return;
17334 		}
17335 
17336 		/* select inbound SA and have IPsec process the pkt */
17337 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17338 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17339 			if (esph == NULL)
17340 				return;
17341 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17342 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17343 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17344 			    first_mp, esph);
17345 		} else {
17346 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17347 			if (ah == NULL)
17348 				return;
17349 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17350 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17351 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17352 			    first_mp, ah);
17353 		}
17354 
17355 		switch (ipsec_rc) {
17356 		case IPSEC_STATUS_SUCCESS:
17357 			break;
17358 		case IPSEC_STATUS_FAILED:
17359 			BUMP_MIB(&ip_mib, ipInDiscards);
17360 			/* FALLTHRU */
17361 		case IPSEC_STATUS_PENDING:
17362 			return;
17363 		}
17364 		/* we're done with IPsec processing, send it up */
17365 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17366 		return;
17367 	}
17368 	default:
17369 		break;
17370 	}
17371 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17372 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17373 		    ire->ire_zoneid));
17374 		goto drop_pkt;
17375 	}
17376 	/*
17377 	 * Handle protocols with which IP is less intimate.  There
17378 	 * can be more than one stream bound to a particular
17379 	 * protocol.  When this is the case, each one gets a copy
17380 	 * of any incoming packets.
17381 	 */
17382 	ip_fanout_proto(q, first_mp, ill, ipha,
17383 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17384 	    B_TRUE, recv_ill, ire->ire_zoneid);
17385 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17386 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17387 	return;
17388 
17389 drop_pkt:
17390 	freemsg(first_mp);
17391 	if (hada_mp != NULL)
17392 		freeb(hada_mp);
17393 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17394 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17395 #undef	rptr
17396 #undef  iphs
17397 
17398 }
17399 
17400 /*
17401  * Update any source route, record route or timestamp options.
17402  * Check that we are at end of strict source route.
17403  * The options have already been checked for sanity in ip_rput_options().
17404  */
17405 static boolean_t
17406 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17407 {
17408 	ipoptp_t	opts;
17409 	uchar_t		*opt;
17410 	uint8_t		optval;
17411 	uint8_t		optlen;
17412 	ipaddr_t	dst;
17413 	uint32_t	ts;
17414 	ire_t		*dst_ire;
17415 	timestruc_t	now;
17416 	zoneid_t	zoneid;
17417 	ill_t		*ill;
17418 
17419 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17420 
17421 	ip2dbg(("ip_rput_local_options\n"));
17422 
17423 	for (optval = ipoptp_first(&opts, ipha);
17424 	    optval != IPOPT_EOL;
17425 	    optval = ipoptp_next(&opts)) {
17426 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17427 		opt = opts.ipoptp_cur;
17428 		optlen = opts.ipoptp_len;
17429 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17430 		    optval, optlen));
17431 		switch (optval) {
17432 			uint32_t off;
17433 		case IPOPT_SSRR:
17434 		case IPOPT_LSRR:
17435 			off = opt[IPOPT_OFFSET];
17436 			off--;
17437 			if (optlen < IP_ADDR_LEN ||
17438 			    off > optlen - IP_ADDR_LEN) {
17439 				/* End of source route */
17440 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17441 				break;
17442 			}
17443 			/*
17444 			 * This will only happen if two consecutive entries
17445 			 * in the source route contains our address or if
17446 			 * it is a packet with a loose source route which
17447 			 * reaches us before consuming the whole source route
17448 			 */
17449 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17450 			if (optval == IPOPT_SSRR) {
17451 				goto bad_src_route;
17452 			}
17453 			/*
17454 			 * Hack: instead of dropping the packet truncate the
17455 			 * source route to what has been used by filling the
17456 			 * rest with IPOPT_NOP.
17457 			 */
17458 			opt[IPOPT_OLEN] = (uint8_t)off;
17459 			while (off < optlen) {
17460 				opt[off++] = IPOPT_NOP;
17461 			}
17462 			break;
17463 		case IPOPT_RR:
17464 			off = opt[IPOPT_OFFSET];
17465 			off--;
17466 			if (optlen < IP_ADDR_LEN ||
17467 			    off > optlen - IP_ADDR_LEN) {
17468 				/* No more room - ignore */
17469 				ip1dbg((
17470 				    "ip_rput_local_options: end of RR\n"));
17471 				break;
17472 			}
17473 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17474 			    IP_ADDR_LEN);
17475 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17476 			break;
17477 		case IPOPT_TS:
17478 			/* Insert timestamp if there is romm */
17479 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17480 			case IPOPT_TS_TSONLY:
17481 				off = IPOPT_TS_TIMELEN;
17482 				break;
17483 			case IPOPT_TS_PRESPEC:
17484 			case IPOPT_TS_PRESPEC_RFC791:
17485 				/* Verify that the address matched */
17486 				off = opt[IPOPT_OFFSET] - 1;
17487 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17488 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17489 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17490 				if (dst_ire == NULL) {
17491 					/* Not for us */
17492 					break;
17493 				}
17494 				ire_refrele(dst_ire);
17495 				/* FALLTHRU */
17496 			case IPOPT_TS_TSANDADDR:
17497 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17498 				break;
17499 			default:
17500 				/*
17501 				 * ip_*put_options should have already
17502 				 * dropped this packet.
17503 				 */
17504 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17505 				    "unknown IT - bug in ip_rput_options?\n");
17506 				return (B_TRUE);	/* Keep "lint" happy */
17507 			}
17508 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17509 				/* Increase overflow counter */
17510 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17511 				opt[IPOPT_POS_OV_FLG] =
17512 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17513 				    (off << 4));
17514 				break;
17515 			}
17516 			off = opt[IPOPT_OFFSET] - 1;
17517 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17518 			case IPOPT_TS_PRESPEC:
17519 			case IPOPT_TS_PRESPEC_RFC791:
17520 			case IPOPT_TS_TSANDADDR:
17521 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17522 				    IP_ADDR_LEN);
17523 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17524 				/* FALLTHRU */
17525 			case IPOPT_TS_TSONLY:
17526 				off = opt[IPOPT_OFFSET] - 1;
17527 				/* Compute # of milliseconds since midnight */
17528 				gethrestime(&now);
17529 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17530 				    now.tv_nsec / (NANOSEC / MILLISEC);
17531 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17532 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17533 				break;
17534 			}
17535 			break;
17536 		}
17537 	}
17538 	return (B_TRUE);
17539 
17540 bad_src_route:
17541 	q = WR(q);
17542 	if (q->q_next != NULL)
17543 		ill = q->q_ptr;
17544 	else
17545 		ill = NULL;
17546 
17547 	/* make sure we clear any indication of a hardware checksum */
17548 	DB_CKSUMFLAGS(mp) = 0;
17549 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17550 	if (zoneid == ALL_ZONES)
17551 		freemsg(mp);
17552 	else
17553 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17554 	return (B_FALSE);
17555 
17556 }
17557 
17558 /*
17559  * Process IP options in an inbound packet.  If an option affects the
17560  * effective destination address, return the next hop address via dstp.
17561  * Returns -1 if something fails in which case an ICMP error has been sent
17562  * and mp freed.
17563  */
17564 static int
17565 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17566 {
17567 	ipoptp_t	opts;
17568 	uchar_t		*opt;
17569 	uint8_t		optval;
17570 	uint8_t		optlen;
17571 	ipaddr_t	dst;
17572 	intptr_t	code = 0;
17573 	ire_t		*ire = NULL;
17574 	zoneid_t	zoneid;
17575 	ill_t		*ill;
17576 
17577 	ip2dbg(("ip_rput_options\n"));
17578 	dst = ipha->ipha_dst;
17579 	for (optval = ipoptp_first(&opts, ipha);
17580 	    optval != IPOPT_EOL;
17581 	    optval = ipoptp_next(&opts)) {
17582 		opt = opts.ipoptp_cur;
17583 		optlen = opts.ipoptp_len;
17584 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17585 		    optval, optlen));
17586 		/*
17587 		 * Note: we need to verify the checksum before we
17588 		 * modify anything thus this routine only extracts the next
17589 		 * hop dst from any source route.
17590 		 */
17591 		switch (optval) {
17592 			uint32_t off;
17593 		case IPOPT_SSRR:
17594 		case IPOPT_LSRR:
17595 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17596 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17597 			if (ire == NULL) {
17598 				if (optval == IPOPT_SSRR) {
17599 					ip1dbg(("ip_rput_options: not next"
17600 					    " strict source route 0x%x\n",
17601 					    ntohl(dst)));
17602 					code = (char *)&ipha->ipha_dst -
17603 					    (char *)ipha;
17604 					goto param_prob; /* RouterReq's */
17605 				}
17606 				ip2dbg(("ip_rput_options: "
17607 				    "not next source route 0x%x\n",
17608 				    ntohl(dst)));
17609 				break;
17610 			}
17611 			ire_refrele(ire);
17612 
17613 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17614 				ip1dbg((
17615 				    "ip_rput_options: bad option offset\n"));
17616 				code = (char *)&opt[IPOPT_OLEN] -
17617 				    (char *)ipha;
17618 				goto param_prob;
17619 			}
17620 			off = opt[IPOPT_OFFSET];
17621 			off--;
17622 		redo_srr:
17623 			if (optlen < IP_ADDR_LEN ||
17624 			    off > optlen - IP_ADDR_LEN) {
17625 				/* End of source route */
17626 				ip1dbg(("ip_rput_options: end of SR\n"));
17627 				break;
17628 			}
17629 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17630 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17631 			    ntohl(dst)));
17632 
17633 			/*
17634 			 * Check if our address is present more than
17635 			 * once as consecutive hops in source route.
17636 			 * XXX verify per-interface ip_forwarding
17637 			 * for source route?
17638 			 */
17639 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17640 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17641 
17642 			if (ire != NULL) {
17643 				ire_refrele(ire);
17644 				off += IP_ADDR_LEN;
17645 				goto redo_srr;
17646 			}
17647 
17648 			if (dst == htonl(INADDR_LOOPBACK)) {
17649 				ip1dbg(("ip_rput_options: loopback addr in "
17650 				    "source route!\n"));
17651 				goto bad_src_route;
17652 			}
17653 			/*
17654 			 * For strict: verify that dst is directly
17655 			 * reachable.
17656 			 */
17657 			if (optval == IPOPT_SSRR) {
17658 				ire = ire_ftable_lookup(dst, 0, 0,
17659 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17660 				    MBLK_GETLABEL(mp),
17661 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17662 				if (ire == NULL) {
17663 					ip1dbg(("ip_rput_options: SSRR not "
17664 					    "directly reachable: 0x%x\n",
17665 					    ntohl(dst)));
17666 					goto bad_src_route;
17667 				}
17668 				ire_refrele(ire);
17669 			}
17670 			/*
17671 			 * Defer update of the offset and the record route
17672 			 * until the packet is forwarded.
17673 			 */
17674 			break;
17675 		case IPOPT_RR:
17676 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17677 				ip1dbg((
17678 				    "ip_rput_options: bad option offset\n"));
17679 				code = (char *)&opt[IPOPT_OLEN] -
17680 				    (char *)ipha;
17681 				goto param_prob;
17682 			}
17683 			break;
17684 		case IPOPT_TS:
17685 			/*
17686 			 * Verify that length >= 5 and that there is either
17687 			 * room for another timestamp or that the overflow
17688 			 * counter is not maxed out.
17689 			 */
17690 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17691 			if (optlen < IPOPT_MINLEN_IT) {
17692 				goto param_prob;
17693 			}
17694 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17695 				ip1dbg((
17696 				    "ip_rput_options: bad option offset\n"));
17697 				code = (char *)&opt[IPOPT_OFFSET] -
17698 				    (char *)ipha;
17699 				goto param_prob;
17700 			}
17701 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17702 			case IPOPT_TS_TSONLY:
17703 				off = IPOPT_TS_TIMELEN;
17704 				break;
17705 			case IPOPT_TS_TSANDADDR:
17706 			case IPOPT_TS_PRESPEC:
17707 			case IPOPT_TS_PRESPEC_RFC791:
17708 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17709 				break;
17710 			default:
17711 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17712 				    (char *)ipha;
17713 				goto param_prob;
17714 			}
17715 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17716 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17717 				/*
17718 				 * No room and the overflow counter is 15
17719 				 * already.
17720 				 */
17721 				goto param_prob;
17722 			}
17723 			break;
17724 		}
17725 	}
17726 
17727 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17728 		*dstp = dst;
17729 		return (0);
17730 	}
17731 
17732 	ip1dbg(("ip_rput_options: error processing IP options."));
17733 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17734 
17735 param_prob:
17736 	q = WR(q);
17737 	if (q->q_next != NULL)
17738 		ill = q->q_ptr;
17739 	else
17740 		ill = NULL;
17741 
17742 	/* make sure we clear any indication of a hardware checksum */
17743 	DB_CKSUMFLAGS(mp) = 0;
17744 	/* Don't know whether this is for non-global or global/forwarding */
17745 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17746 	if (zoneid == ALL_ZONES)
17747 		freemsg(mp);
17748 	else
17749 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17750 	return (-1);
17751 
17752 bad_src_route:
17753 	q = WR(q);
17754 	if (q->q_next != NULL)
17755 		ill = q->q_ptr;
17756 	else
17757 		ill = NULL;
17758 
17759 	/* make sure we clear any indication of a hardware checksum */
17760 	DB_CKSUMFLAGS(mp) = 0;
17761 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17762 	if (zoneid == ALL_ZONES)
17763 		freemsg(mp);
17764 	else
17765 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17766 	return (-1);
17767 }
17768 
17769 /*
17770  * IP & ICMP info in >=14 msg's ...
17771  *  - ip fixed part (mib2_ip_t)
17772  *  - icmp fixed part (mib2_icmp_t)
17773  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17774  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17775  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17776  *  - ipRouteAttributeTable (ip 102)	labeled routes
17777  *  - ip multicast membership (ip_member_t)
17778  *  - ip multicast source filtering (ip_grpsrc_t)
17779  *  - igmp fixed part (struct igmpstat)
17780  *  - multicast routing stats (struct mrtstat)
17781  *  - multicast routing vifs (array of struct vifctl)
17782  *  - multicast routing routes (array of struct mfcctl)
17783  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17784  *					One per ill plus one generic
17785  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17786  *					One per ill plus one generic
17787  *  - ipv6RouteEntry			all IPv6 IREs
17788  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17789  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17790  *  - ipv6AddrEntry			all IPv6 ipifs
17791  *  - ipv6 multicast membership (ipv6_member_t)
17792  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17793  *
17794  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17795  *
17796  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17797  * already filled in by the caller.
17798  * Return value of 0 indicates that no messages were sent and caller
17799  * should free mpctl.
17800  */
17801 int
17802 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17803 {
17804 
17805 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17806 		return (0);
17807 	}
17808 
17809 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17810 		return (1);
17811 	}
17812 
17813 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17814 		return (1);
17815 	}
17816 
17817 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17818 		return (1);
17819 	}
17820 
17821 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17822 		return (1);
17823 	}
17824 
17825 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17826 		return (1);
17827 	}
17828 
17829 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17830 		return (1);
17831 	}
17832 
17833 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17834 		return (1);
17835 	}
17836 
17837 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17838 		return (1);
17839 	}
17840 
17841 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17842 		return (1);
17843 	}
17844 
17845 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17846 		return (1);
17847 	}
17848 
17849 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17850 		return (1);
17851 	}
17852 
17853 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17854 		return (1);
17855 	}
17856 
17857 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17858 		return (1);
17859 	}
17860 
17861 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17862 		return (1);
17863 	}
17864 
17865 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17866 		return (1);
17867 	}
17868 
17869 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17870 		return (1);
17871 	}
17872 
17873 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17874 		return (1);
17875 	}
17876 	freemsg(mpctl);
17877 	return (1);
17878 }
17879 
17880 
17881 /* Get global IPv4 statistics */
17882 static mblk_t *
17883 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17884 {
17885 	struct opthdr		*optp;
17886 	mblk_t			*mp2ctl;
17887 
17888 	/*
17889 	 * make a copy of the original message
17890 	 */
17891 	mp2ctl = copymsg(mpctl);
17892 
17893 	/* fixed length IP structure... */
17894 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17895 	optp->level = MIB2_IP;
17896 	optp->name = 0;
17897 	SET_MIB(ip_mib.ipForwarding,
17898 	    (WE_ARE_FORWARDING ? 1 : 2));
17899 	SET_MIB(ip_mib.ipDefaultTTL,
17900 	    (uint32_t)ip_def_ttl);
17901 	SET_MIB(ip_mib.ipReasmTimeout,
17902 	    ip_g_frag_timeout);
17903 	SET_MIB(ip_mib.ipAddrEntrySize,
17904 	    sizeof (mib2_ipAddrEntry_t));
17905 	SET_MIB(ip_mib.ipRouteEntrySize,
17906 	    sizeof (mib2_ipRouteEntry_t));
17907 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17908 	    sizeof (mib2_ipNetToMediaEntry_t));
17909 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17910 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17911 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17912 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17913 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17914 	    (int)sizeof (ip_mib))) {
17915 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17916 		    (uint_t)sizeof (ip_mib)));
17917 	}
17918 
17919 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17920 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17921 	    (int)optp->level, (int)optp->name, (int)optp->len));
17922 	qreply(q, mpctl);
17923 	return (mp2ctl);
17924 }
17925 
17926 /* Global IPv4 ICMP statistics */
17927 static mblk_t *
17928 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17929 {
17930 	struct opthdr		*optp;
17931 	mblk_t			*mp2ctl;
17932 
17933 	/*
17934 	 * Make a copy of the original message
17935 	 */
17936 	mp2ctl = copymsg(mpctl);
17937 
17938 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17939 	optp->level = MIB2_ICMP;
17940 	optp->name = 0;
17941 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17942 	    (int)sizeof (icmp_mib))) {
17943 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17944 		    (uint_t)sizeof (icmp_mib)));
17945 	}
17946 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17947 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17948 	    (int)optp->level, (int)optp->name, (int)optp->len));
17949 	qreply(q, mpctl);
17950 	return (mp2ctl);
17951 }
17952 
17953 /* Global IPv4 IGMP statistics */
17954 static mblk_t *
17955 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17956 {
17957 	struct opthdr		*optp;
17958 	mblk_t			*mp2ctl;
17959 
17960 	/*
17961 	 * make a copy of the original message
17962 	 */
17963 	mp2ctl = copymsg(mpctl);
17964 
17965 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17966 	optp->level = EXPER_IGMP;
17967 	optp->name = 0;
17968 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17969 	    (int)sizeof (igmpstat))) {
17970 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17971 		    (uint_t)sizeof (igmpstat)));
17972 	}
17973 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17974 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17975 	    (int)optp->level, (int)optp->name, (int)optp->len));
17976 	qreply(q, mpctl);
17977 	return (mp2ctl);
17978 }
17979 
17980 /* Global IPv4 Multicast Routing statistics */
17981 static mblk_t *
17982 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17983 {
17984 	struct opthdr		*optp;
17985 	mblk_t			*mp2ctl;
17986 
17987 	/*
17988 	 * make a copy of the original message
17989 	 */
17990 	mp2ctl = copymsg(mpctl);
17991 
17992 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17993 	optp->level = EXPER_DVMRP;
17994 	optp->name = 0;
17995 	if (!ip_mroute_stats(mpctl->b_cont)) {
17996 		ip0dbg(("ip_mroute_stats: failed\n"));
17997 	}
17998 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17999 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18000 	    (int)optp->level, (int)optp->name, (int)optp->len));
18001 	qreply(q, mpctl);
18002 	return (mp2ctl);
18003 }
18004 
18005 /* IPv4 address information */
18006 static mblk_t *
18007 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18008 {
18009 	struct opthdr		*optp;
18010 	mblk_t			*mp2ctl;
18011 	mblk_t			*mp_tail = NULL;
18012 	ill_t			*ill;
18013 	ipif_t			*ipif;
18014 	uint_t			bitval;
18015 	mib2_ipAddrEntry_t	mae;
18016 	zoneid_t		zoneid;
18017 	ill_walk_context_t ctx;
18018 
18019 	/*
18020 	 * make a copy of the original message
18021 	 */
18022 	mp2ctl = copymsg(mpctl);
18023 
18024 	/* ipAddrEntryTable */
18025 
18026 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18027 	optp->level = MIB2_IP;
18028 	optp->name = MIB2_IP_ADDR;
18029 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18030 
18031 	rw_enter(&ill_g_lock, RW_READER);
18032 	ill = ILL_START_WALK_V4(&ctx);
18033 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18034 		for (ipif = ill->ill_ipif; ipif != NULL;
18035 		    ipif = ipif->ipif_next) {
18036 			if (ipif->ipif_zoneid != zoneid &&
18037 			    ipif->ipif_zoneid != ALL_ZONES)
18038 				continue;
18039 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18040 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18041 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18042 
18043 			(void) ipif_get_name(ipif,
18044 			    mae.ipAdEntIfIndex.o_bytes,
18045 			    OCTET_LENGTH);
18046 			mae.ipAdEntIfIndex.o_length =
18047 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18048 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18049 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18050 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18051 			mae.ipAdEntInfo.ae_subnet_len =
18052 			    ip_mask_to_plen(ipif->ipif_net_mask);
18053 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18054 			for (bitval = 1;
18055 			    bitval &&
18056 			    !(bitval & ipif->ipif_brd_addr);
18057 			    bitval <<= 1)
18058 				noop;
18059 			mae.ipAdEntBcastAddr = bitval;
18060 			mae.ipAdEntReasmMaxSize = 65535;
18061 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18062 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18063 			mae.ipAdEntInfo.ae_broadcast_addr =
18064 			    ipif->ipif_brd_addr;
18065 			mae.ipAdEntInfo.ae_pp_dst_addr =
18066 			    ipif->ipif_pp_dst_addr;
18067 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18068 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18069 
18070 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18071 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18072 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18073 				    "allocate %u bytes\n",
18074 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18075 			}
18076 		}
18077 	}
18078 	rw_exit(&ill_g_lock);
18079 
18080 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18081 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18082 	    (int)optp->level, (int)optp->name, (int)optp->len));
18083 	qreply(q, mpctl);
18084 	return (mp2ctl);
18085 }
18086 
18087 /* IPv6 address information */
18088 static mblk_t *
18089 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18090 {
18091 	struct opthdr		*optp;
18092 	mblk_t			*mp2ctl;
18093 	mblk_t			*mp_tail = NULL;
18094 	ill_t			*ill;
18095 	ipif_t			*ipif;
18096 	mib2_ipv6AddrEntry_t	mae6;
18097 	zoneid_t		zoneid;
18098 	ill_walk_context_t	ctx;
18099 
18100 	/*
18101 	 * make a copy of the original message
18102 	 */
18103 	mp2ctl = copymsg(mpctl);
18104 
18105 	/* ipv6AddrEntryTable */
18106 
18107 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18108 	optp->level = MIB2_IP6;
18109 	optp->name = MIB2_IP6_ADDR;
18110 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18111 
18112 	rw_enter(&ill_g_lock, RW_READER);
18113 	ill = ILL_START_WALK_V6(&ctx);
18114 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18115 		for (ipif = ill->ill_ipif; ipif != NULL;
18116 		    ipif = ipif->ipif_next) {
18117 			if (ipif->ipif_zoneid != zoneid &&
18118 			    ipif->ipif_zoneid != ALL_ZONES)
18119 				continue;
18120 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18121 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18122 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18123 
18124 			(void) ipif_get_name(ipif,
18125 			    mae6.ipv6AddrIfIndex.o_bytes,
18126 			    OCTET_LENGTH);
18127 			mae6.ipv6AddrIfIndex.o_length =
18128 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18129 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18130 			mae6.ipv6AddrPfxLength =
18131 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18132 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18133 			mae6.ipv6AddrInfo.ae_subnet_len =
18134 			    mae6.ipv6AddrPfxLength;
18135 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18136 
18137 			/* Type: stateless(1), stateful(2), unknown(3) */
18138 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18139 				mae6.ipv6AddrType = 1;
18140 			else
18141 				mae6.ipv6AddrType = 2;
18142 			/* Anycast: true(1), false(2) */
18143 			if (ipif->ipif_flags & IPIF_ANYCAST)
18144 				mae6.ipv6AddrAnycastFlag = 1;
18145 			else
18146 				mae6.ipv6AddrAnycastFlag = 2;
18147 
18148 			/*
18149 			 * Address status: preferred(1), deprecated(2),
18150 			 * invalid(3), inaccessible(4), unknown(5)
18151 			 */
18152 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18153 				mae6.ipv6AddrStatus = 3;
18154 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18155 				mae6.ipv6AddrStatus = 2;
18156 			else
18157 				mae6.ipv6AddrStatus = 1;
18158 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18159 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18160 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18161 						ipif->ipif_v6pp_dst_addr;
18162 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18163 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18164 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18165 				(char *)&mae6,
18166 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18167 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18168 				    "allocate %u bytes\n",
18169 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18170 			}
18171 		}
18172 	}
18173 	rw_exit(&ill_g_lock);
18174 
18175 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18176 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18177 	    (int)optp->level, (int)optp->name, (int)optp->len));
18178 	qreply(q, mpctl);
18179 	return (mp2ctl);
18180 }
18181 
18182 /* IPv4 multicast group membership. */
18183 static mblk_t *
18184 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18185 {
18186 	struct opthdr		*optp;
18187 	mblk_t			*mp2ctl;
18188 	ill_t			*ill;
18189 	ipif_t			*ipif;
18190 	ilm_t			*ilm;
18191 	ip_member_t		ipm;
18192 	mblk_t			*mp_tail = NULL;
18193 	ill_walk_context_t	ctx;
18194 	zoneid_t		zoneid;
18195 
18196 	/*
18197 	 * make a copy of the original message
18198 	 */
18199 	mp2ctl = copymsg(mpctl);
18200 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18201 
18202 	/* ipGroupMember table */
18203 	optp = (struct opthdr *)&mpctl->b_rptr[
18204 	    sizeof (struct T_optmgmt_ack)];
18205 	optp->level = MIB2_IP;
18206 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18207 
18208 	rw_enter(&ill_g_lock, RW_READER);
18209 	ill = ILL_START_WALK_V4(&ctx);
18210 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18211 		ILM_WALKER_HOLD(ill);
18212 		for (ipif = ill->ill_ipif; ipif != NULL;
18213 		    ipif = ipif->ipif_next) {
18214 			if (ipif->ipif_zoneid != zoneid &&
18215 			    ipif->ipif_zoneid != ALL_ZONES)
18216 				continue;	/* not this zone */
18217 			(void) ipif_get_name(ipif,
18218 			    ipm.ipGroupMemberIfIndex.o_bytes,
18219 			    OCTET_LENGTH);
18220 			ipm.ipGroupMemberIfIndex.o_length =
18221 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18222 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18223 				ASSERT(ilm->ilm_ipif != NULL);
18224 				ASSERT(ilm->ilm_ill == NULL);
18225 				if (ilm->ilm_ipif != ipif)
18226 					continue;
18227 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18228 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18229 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18230 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18231 				    (char *)&ipm, (int)sizeof (ipm))) {
18232 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18233 					    "failed to allocate %u bytes\n",
18234 						(uint_t)sizeof (ipm)));
18235 				}
18236 			}
18237 		}
18238 		ILM_WALKER_RELE(ill);
18239 	}
18240 	rw_exit(&ill_g_lock);
18241 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18242 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18243 	    (int)optp->level, (int)optp->name, (int)optp->len));
18244 	qreply(q, mpctl);
18245 	return (mp2ctl);
18246 }
18247 
18248 /* IPv6 multicast group membership. */
18249 static mblk_t *
18250 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18251 {
18252 	struct opthdr		*optp;
18253 	mblk_t			*mp2ctl;
18254 	ill_t			*ill;
18255 	ilm_t			*ilm;
18256 	ipv6_member_t		ipm6;
18257 	mblk_t			*mp_tail = NULL;
18258 	ill_walk_context_t	ctx;
18259 	zoneid_t		zoneid;
18260 
18261 	/*
18262 	 * make a copy of the original message
18263 	 */
18264 	mp2ctl = copymsg(mpctl);
18265 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18266 
18267 	/* ip6GroupMember table */
18268 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18269 	optp->level = MIB2_IP6;
18270 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18271 
18272 	rw_enter(&ill_g_lock, RW_READER);
18273 	ill = ILL_START_WALK_V6(&ctx);
18274 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18275 		ILM_WALKER_HOLD(ill);
18276 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18277 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18278 			ASSERT(ilm->ilm_ipif == NULL);
18279 			ASSERT(ilm->ilm_ill != NULL);
18280 			if (ilm->ilm_zoneid != zoneid)
18281 				continue;	/* not this zone */
18282 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18283 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18284 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18285 			if (!snmp_append_data2(mpctl->b_cont,
18286 			    &mp_tail,
18287 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18288 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18289 				    "failed to allocate %u bytes\n",
18290 				    (uint_t)sizeof (ipm6)));
18291 			}
18292 		}
18293 		ILM_WALKER_RELE(ill);
18294 	}
18295 	rw_exit(&ill_g_lock);
18296 
18297 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18298 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18299 	    (int)optp->level, (int)optp->name, (int)optp->len));
18300 	qreply(q, mpctl);
18301 	return (mp2ctl);
18302 }
18303 
18304 /* IP multicast filtered sources */
18305 static mblk_t *
18306 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18307 {
18308 	struct opthdr		*optp;
18309 	mblk_t			*mp2ctl;
18310 	ill_t			*ill;
18311 	ipif_t			*ipif;
18312 	ilm_t			*ilm;
18313 	ip_grpsrc_t		ips;
18314 	mblk_t			*mp_tail = NULL;
18315 	ill_walk_context_t	ctx;
18316 	zoneid_t		zoneid;
18317 	int			i;
18318 	slist_t			*sl;
18319 
18320 	/*
18321 	 * make a copy of the original message
18322 	 */
18323 	mp2ctl = copymsg(mpctl);
18324 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18325 
18326 	/* ipGroupSource table */
18327 	optp = (struct opthdr *)&mpctl->b_rptr[
18328 	    sizeof (struct T_optmgmt_ack)];
18329 	optp->level = MIB2_IP;
18330 	optp->name = EXPER_IP_GROUP_SOURCES;
18331 
18332 	rw_enter(&ill_g_lock, RW_READER);
18333 	ill = ILL_START_WALK_V4(&ctx);
18334 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18335 		ILM_WALKER_HOLD(ill);
18336 		for (ipif = ill->ill_ipif; ipif != NULL;
18337 		    ipif = ipif->ipif_next) {
18338 			if (ipif->ipif_zoneid != zoneid)
18339 				continue;	/* not this zone */
18340 			(void) ipif_get_name(ipif,
18341 			    ips.ipGroupSourceIfIndex.o_bytes,
18342 			    OCTET_LENGTH);
18343 			ips.ipGroupSourceIfIndex.o_length =
18344 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18345 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18346 				ASSERT(ilm->ilm_ipif != NULL);
18347 				ASSERT(ilm->ilm_ill == NULL);
18348 				sl = ilm->ilm_filter;
18349 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18350 					continue;
18351 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18352 				for (i = 0; i < sl->sl_numsrc; i++) {
18353 					if (!IN6_IS_ADDR_V4MAPPED(
18354 					    &sl->sl_addr[i]))
18355 						continue;
18356 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18357 					    ips.ipGroupSourceAddress);
18358 					if (snmp_append_data2(mpctl->b_cont,
18359 					    &mp_tail, (char *)&ips,
18360 					    (int)sizeof (ips)) == 0) {
18361 						ip1dbg(("ip_snmp_get_mib2_"
18362 						    "ip_group_src: failed to "
18363 						    "allocate %u bytes\n",
18364 						    (uint_t)sizeof (ips)));
18365 					}
18366 				}
18367 			}
18368 		}
18369 		ILM_WALKER_RELE(ill);
18370 	}
18371 	rw_exit(&ill_g_lock);
18372 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18373 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18374 	    (int)optp->level, (int)optp->name, (int)optp->len));
18375 	qreply(q, mpctl);
18376 	return (mp2ctl);
18377 }
18378 
18379 /* IPv6 multicast filtered sources. */
18380 static mblk_t *
18381 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18382 {
18383 	struct opthdr		*optp;
18384 	mblk_t			*mp2ctl;
18385 	ill_t			*ill;
18386 	ilm_t			*ilm;
18387 	ipv6_grpsrc_t		ips6;
18388 	mblk_t			*mp_tail = NULL;
18389 	ill_walk_context_t	ctx;
18390 	zoneid_t		zoneid;
18391 	int			i;
18392 	slist_t			*sl;
18393 
18394 	/*
18395 	 * make a copy of the original message
18396 	 */
18397 	mp2ctl = copymsg(mpctl);
18398 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18399 
18400 	/* ip6GroupMember table */
18401 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18402 	optp->level = MIB2_IP6;
18403 	optp->name = EXPER_IP6_GROUP_SOURCES;
18404 
18405 	rw_enter(&ill_g_lock, RW_READER);
18406 	ill = ILL_START_WALK_V6(&ctx);
18407 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18408 		ILM_WALKER_HOLD(ill);
18409 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18410 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18411 			ASSERT(ilm->ilm_ipif == NULL);
18412 			ASSERT(ilm->ilm_ill != NULL);
18413 			sl = ilm->ilm_filter;
18414 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18415 				continue;
18416 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18417 			for (i = 0; i < sl->sl_numsrc; i++) {
18418 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18419 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18420 				    (char *)&ips6, (int)sizeof (ips6))) {
18421 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18422 					    "group_src: failed to allocate "
18423 					    "%u bytes\n",
18424 					    (uint_t)sizeof (ips6)));
18425 				}
18426 			}
18427 		}
18428 		ILM_WALKER_RELE(ill);
18429 	}
18430 	rw_exit(&ill_g_lock);
18431 
18432 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18433 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18434 	    (int)optp->level, (int)optp->name, (int)optp->len));
18435 	qreply(q, mpctl);
18436 	return (mp2ctl);
18437 }
18438 
18439 /* Multicast routing virtual interface table. */
18440 static mblk_t *
18441 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18442 {
18443 	struct opthdr		*optp;
18444 	mblk_t			*mp2ctl;
18445 
18446 	/*
18447 	 * make a copy of the original message
18448 	 */
18449 	mp2ctl = copymsg(mpctl);
18450 
18451 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18452 	optp->level = EXPER_DVMRP;
18453 	optp->name = EXPER_DVMRP_VIF;
18454 	if (!ip_mroute_vif(mpctl->b_cont)) {
18455 		ip0dbg(("ip_mroute_vif: failed\n"));
18456 	}
18457 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18458 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18459 	    (int)optp->level, (int)optp->name, (int)optp->len));
18460 	qreply(q, mpctl);
18461 	return (mp2ctl);
18462 }
18463 
18464 /* Multicast routing table. */
18465 static mblk_t *
18466 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18467 {
18468 	struct opthdr		*optp;
18469 	mblk_t			*mp2ctl;
18470 
18471 	/*
18472 	 * make a copy of the original message
18473 	 */
18474 	mp2ctl = copymsg(mpctl);
18475 
18476 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18477 	optp->level = EXPER_DVMRP;
18478 	optp->name = EXPER_DVMRP_MRT;
18479 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18480 		ip0dbg(("ip_mroute_mrt: failed\n"));
18481 	}
18482 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18483 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18484 	    (int)optp->level, (int)optp->name, (int)optp->len));
18485 	qreply(q, mpctl);
18486 	return (mp2ctl);
18487 }
18488 
18489 /*
18490  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18491  * in one IRE walk.
18492  */
18493 static mblk_t *
18494 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18495 {
18496 	struct opthdr	*optp;
18497 	mblk_t		*mp2ctl;	/* Returned */
18498 	mblk_t		*mp3ctl;	/* nettomedia */
18499 	mblk_t		*mp4ctl;	/* routeattrs */
18500 	iproutedata_t	ird;
18501 	zoneid_t	zoneid;
18502 
18503 	/*
18504 	 * make copies of the original message
18505 	 *	- mp2ctl is returned unchanged to the caller for his use
18506 	 *	- mpctl is sent upstream as ipRouteEntryTable
18507 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18508 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18509 	 */
18510 	mp2ctl = copymsg(mpctl);
18511 	mp3ctl = copymsg(mpctl);
18512 	mp4ctl = copymsg(mpctl);
18513 	if (mp3ctl == NULL || mp4ctl == NULL) {
18514 		freemsg(mp4ctl);
18515 		freemsg(mp3ctl);
18516 		freemsg(mp2ctl);
18517 		freemsg(mpctl);
18518 		return (NULL);
18519 	}
18520 
18521 	bzero(&ird, sizeof (ird));
18522 
18523 	ird.ird_route.lp_head = mpctl->b_cont;
18524 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18525 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18526 
18527 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18528 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18529 	if (zoneid == GLOBAL_ZONEID) {
18530 		/*
18531 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18532 		 * the sys_net_config privilege, it can only run in the global
18533 		 * zone, so we don't display these IREs in the other zones.
18534 		 */
18535 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18536 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18537 	}
18538 
18539 	/* ipRouteEntryTable in mpctl */
18540 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18541 	optp->level = MIB2_IP;
18542 	optp->name = MIB2_IP_ROUTE;
18543 	optp->len = msgdsize(ird.ird_route.lp_head);
18544 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18545 	    (int)optp->level, (int)optp->name, (int)optp->len));
18546 	qreply(q, mpctl);
18547 
18548 	/* ipNetToMediaEntryTable in mp3ctl */
18549 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18550 	optp->level = MIB2_IP;
18551 	optp->name = MIB2_IP_MEDIA;
18552 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18553 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18554 	    (int)optp->level, (int)optp->name, (int)optp->len));
18555 	qreply(q, mp3ctl);
18556 
18557 	/* ipRouteAttributeTable in mp4ctl */
18558 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18559 	optp->level = MIB2_IP;
18560 	optp->name = EXPER_IP_RTATTR;
18561 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18562 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18563 	    (int)optp->level, (int)optp->name, (int)optp->len));
18564 	if (optp->len == 0)
18565 		freemsg(mp4ctl);
18566 	else
18567 		qreply(q, mp4ctl);
18568 
18569 	return (mp2ctl);
18570 }
18571 
18572 /*
18573  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18574  * ipv6NetToMediaEntryTable in an NDP walk.
18575  */
18576 static mblk_t *
18577 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18578 {
18579 	struct opthdr	*optp;
18580 	mblk_t		*mp2ctl;	/* Returned */
18581 	mblk_t		*mp3ctl;	/* nettomedia */
18582 	mblk_t		*mp4ctl;	/* routeattrs */
18583 	iproutedata_t	ird;
18584 	zoneid_t	zoneid;
18585 
18586 	/*
18587 	 * make copies of the original message
18588 	 *	- mp2ctl is returned unchanged to the caller for his use
18589 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18590 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18591 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18592 	 */
18593 	mp2ctl = copymsg(mpctl);
18594 	mp3ctl = copymsg(mpctl);
18595 	mp4ctl = copymsg(mpctl);
18596 	if (mp3ctl == NULL || mp4ctl == NULL) {
18597 		freemsg(mp4ctl);
18598 		freemsg(mp3ctl);
18599 		freemsg(mp2ctl);
18600 		freemsg(mpctl);
18601 		return (NULL);
18602 	}
18603 
18604 	bzero(&ird, sizeof (ird));
18605 
18606 	ird.ird_route.lp_head = mpctl->b_cont;
18607 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18608 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18609 
18610 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18611 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18612 
18613 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18614 	optp->level = MIB2_IP6;
18615 	optp->name = MIB2_IP6_ROUTE;
18616 	optp->len = msgdsize(ird.ird_route.lp_head);
18617 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18618 	    (int)optp->level, (int)optp->name, (int)optp->len));
18619 	qreply(q, mpctl);
18620 
18621 	/* ipv6NetToMediaEntryTable in mp3ctl */
18622 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18623 
18624 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18625 	optp->level = MIB2_IP6;
18626 	optp->name = MIB2_IP6_MEDIA;
18627 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18628 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18629 	    (int)optp->level, (int)optp->name, (int)optp->len));
18630 	qreply(q, mp3ctl);
18631 
18632 	/* ipv6RouteAttributeTable in mp4ctl */
18633 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18634 	optp->level = MIB2_IP6;
18635 	optp->name = EXPER_IP_RTATTR;
18636 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18637 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18638 	    (int)optp->level, (int)optp->name, (int)optp->len));
18639 	if (optp->len == 0)
18640 		freemsg(mp4ctl);
18641 	else
18642 		qreply(q, mp4ctl);
18643 
18644 	return (mp2ctl);
18645 }
18646 
18647 /*
18648  * ICMPv6 mib: One per ill
18649  */
18650 static mblk_t *
18651 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18652 {
18653 	struct opthdr		*optp;
18654 	mblk_t			*mp2ctl;
18655 	ill_t			*ill;
18656 	ill_walk_context_t	ctx;
18657 	mblk_t			*mp_tail = NULL;
18658 
18659 	/*
18660 	 * Make a copy of the original message
18661 	 */
18662 	mp2ctl = copymsg(mpctl);
18663 
18664 	/* fixed length IPv6 structure ... */
18665 
18666 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18667 	optp->level = MIB2_IP6;
18668 	optp->name = 0;
18669 	/* Include "unknown interface" ip6_mib */
18670 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18671 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18672 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18673 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18674 	    sizeof (mib2_ipv6IfStatsEntry_t));
18675 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18676 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18677 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18678 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18679 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18680 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18681 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18682 	    (int)sizeof (ip6_mib))) {
18683 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18684 		    (uint_t)sizeof (ip6_mib)));
18685 	}
18686 
18687 	rw_enter(&ill_g_lock, RW_READER);
18688 	ill = ILL_START_WALK_V6(&ctx);
18689 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18690 		ill->ill_ip6_mib->ipv6IfIndex =
18691 		    ill->ill_phyint->phyint_ifindex;
18692 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18693 		    ipv6_forward ? 1 : 2);
18694 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18695 		    ill->ill_max_hops);
18696 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18697 		    sizeof (mib2_ipv6IfStatsEntry_t));
18698 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18699 		    sizeof (mib2_ipv6AddrEntry_t));
18700 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18701 		    sizeof (mib2_ipv6RouteEntry_t));
18702 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18703 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18704 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18705 		    sizeof (ipv6_member_t));
18706 
18707 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18708 		    (char *)ill->ill_ip6_mib,
18709 		    (int)sizeof (*ill->ill_ip6_mib))) {
18710 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18711 				"%u bytes\n",
18712 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18713 		}
18714 	}
18715 	rw_exit(&ill_g_lock);
18716 
18717 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18718 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18719 	    (int)optp->level, (int)optp->name, (int)optp->len));
18720 	qreply(q, mpctl);
18721 	return (mp2ctl);
18722 }
18723 
18724 /*
18725  * ICMPv6 mib: One per ill
18726  */
18727 static mblk_t *
18728 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18729 {
18730 	struct opthdr		*optp;
18731 	mblk_t			*mp2ctl;
18732 	ill_t			*ill;
18733 	ill_walk_context_t	ctx;
18734 	mblk_t			*mp_tail = NULL;
18735 	/*
18736 	 * Make a copy of the original message
18737 	 */
18738 	mp2ctl = copymsg(mpctl);
18739 
18740 	/* fixed length ICMPv6 structure ... */
18741 
18742 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18743 	optp->level = MIB2_ICMP6;
18744 	optp->name = 0;
18745 	/* Include "unknown interface" icmp6_mib */
18746 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18747 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18748 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18749 	    (int)sizeof (icmp6_mib))) {
18750 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18751 		    (uint_t)sizeof (icmp6_mib)));
18752 	}
18753 
18754 	rw_enter(&ill_g_lock, RW_READER);
18755 	ill = ILL_START_WALK_V6(&ctx);
18756 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18757 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18758 		    ill->ill_phyint->phyint_ifindex;
18759 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18760 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18761 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18762 		    (char *)ill->ill_icmp6_mib,
18763 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18764 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18765 			    "%u bytes\n",
18766 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18767 		}
18768 	}
18769 	rw_exit(&ill_g_lock);
18770 
18771 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18772 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18773 	    (int)optp->level, (int)optp->name, (int)optp->len));
18774 	qreply(q, mpctl);
18775 	return (mp2ctl);
18776 }
18777 
18778 /*
18779  * ire_walk routine to create both ipRouteEntryTable and
18780  * ipRouteAttributeTable in one IRE walk
18781  */
18782 static void
18783 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18784 {
18785 	ill_t				*ill;
18786 	ipif_t				*ipif;
18787 	mib2_ipRouteEntry_t		*re;
18788 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18789 	ipaddr_t			gw_addr;
18790 	tsol_ire_gw_secattr_t		*attrp;
18791 	tsol_gc_t			*gc = NULL;
18792 	tsol_gcgrp_t			*gcgrp = NULL;
18793 	uint_t				sacnt = 0;
18794 	int				i;
18795 
18796 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18797 
18798 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18799 		return;
18800 
18801 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18802 		mutex_enter(&attrp->igsa_lock);
18803 		if ((gc = attrp->igsa_gc) != NULL) {
18804 			gcgrp = gc->gc_grp;
18805 			ASSERT(gcgrp != NULL);
18806 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18807 			sacnt = 1;
18808 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18809 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18810 			gc = gcgrp->gcgrp_head;
18811 			sacnt = gcgrp->gcgrp_count;
18812 		}
18813 		mutex_exit(&attrp->igsa_lock);
18814 
18815 		/* do nothing if there's no gc to report */
18816 		if (gc == NULL) {
18817 			ASSERT(sacnt == 0);
18818 			if (gcgrp != NULL) {
18819 				/* we might as well drop the lock now */
18820 				rw_exit(&gcgrp->gcgrp_rwlock);
18821 				gcgrp = NULL;
18822 			}
18823 			attrp = NULL;
18824 		}
18825 
18826 		ASSERT(gc == NULL || (gcgrp != NULL &&
18827 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18828 	}
18829 	ASSERT(sacnt == 0 || gc != NULL);
18830 
18831 	if (sacnt != 0 &&
18832 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18833 		kmem_free(re, sizeof (*re));
18834 		rw_exit(&gcgrp->gcgrp_rwlock);
18835 		return;
18836 	}
18837 
18838 	/*
18839 	 * Return all IRE types for route table... let caller pick and choose
18840 	 */
18841 	re->ipRouteDest = ire->ire_addr;
18842 	ipif = ire->ire_ipif;
18843 	re->ipRouteIfIndex.o_length = 0;
18844 	if (ire->ire_type == IRE_CACHE) {
18845 		ill = (ill_t *)ire->ire_stq->q_ptr;
18846 		re->ipRouteIfIndex.o_length =
18847 		    ill->ill_name_length == 0 ? 0 :
18848 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18849 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18850 		    re->ipRouteIfIndex.o_length);
18851 	} else if (ipif != NULL) {
18852 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18853 		    OCTET_LENGTH);
18854 		re->ipRouteIfIndex.o_length =
18855 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18856 	}
18857 	re->ipRouteMetric1 = -1;
18858 	re->ipRouteMetric2 = -1;
18859 	re->ipRouteMetric3 = -1;
18860 	re->ipRouteMetric4 = -1;
18861 
18862 	gw_addr = ire->ire_gateway_addr;
18863 
18864 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18865 		re->ipRouteNextHop = ire->ire_src_addr;
18866 	else
18867 		re->ipRouteNextHop = gw_addr;
18868 	/* indirect(4), direct(3), or invalid(2) */
18869 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18870 		re->ipRouteType = 2;
18871 	else
18872 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18873 	re->ipRouteProto = -1;
18874 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18875 	re->ipRouteMask = ire->ire_mask;
18876 	re->ipRouteMetric5 = -1;
18877 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18878 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18879 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18880 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18881 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18882 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18883 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18884 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18885 	re->ipRouteInfo.re_in_ill.o_length = 0;
18886 
18887 	if (ire->ire_flags & RTF_DYNAMIC) {
18888 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18889 	} else {
18890 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18891 	}
18892 
18893 	if (ire->ire_in_ill != NULL) {
18894 		re->ipRouteInfo.re_in_ill.o_length =
18895 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18896 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18897 		bcopy(ire->ire_in_ill->ill_name,
18898 		    re->ipRouteInfo.re_in_ill.o_bytes,
18899 		    re->ipRouteInfo.re_in_ill.o_length);
18900 	}
18901 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18902 
18903 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18904 	    (char *)re, (int)sizeof (*re))) {
18905 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18906 		    (uint_t)sizeof (*re)));
18907 	}
18908 
18909 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18910 		iaeptr->iae_routeidx = ird->ird_idx;
18911 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18912 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18913 	}
18914 
18915 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18916 	    (char *)iae, sacnt * sizeof (*iae))) {
18917 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18918 		    (unsigned)(sacnt * sizeof (*iae))));
18919 	}
18920 
18921 	/* bump route index for next pass */
18922 	ird->ird_idx++;
18923 
18924 	kmem_free(re, sizeof (*re));
18925 	if (sacnt != 0)
18926 		kmem_free(iae, sacnt * sizeof (*iae));
18927 
18928 	if (gcgrp != NULL)
18929 		rw_exit(&gcgrp->gcgrp_rwlock);
18930 }
18931 
18932 /*
18933  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18934  */
18935 static void
18936 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18937 {
18938 	ill_t				*ill;
18939 	ipif_t				*ipif;
18940 	mib2_ipv6RouteEntry_t		*re;
18941 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18942 	in6_addr_t			gw_addr_v6;
18943 	tsol_ire_gw_secattr_t		*attrp;
18944 	tsol_gc_t			*gc = NULL;
18945 	tsol_gcgrp_t			*gcgrp = NULL;
18946 	uint_t				sacnt = 0;
18947 	int				i;
18948 
18949 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18950 
18951 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18952 		return;
18953 
18954 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18955 		mutex_enter(&attrp->igsa_lock);
18956 		if ((gc = attrp->igsa_gc) != NULL) {
18957 			gcgrp = gc->gc_grp;
18958 			ASSERT(gcgrp != NULL);
18959 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18960 			sacnt = 1;
18961 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18962 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18963 			gc = gcgrp->gcgrp_head;
18964 			sacnt = gcgrp->gcgrp_count;
18965 		}
18966 		mutex_exit(&attrp->igsa_lock);
18967 
18968 		/* do nothing if there's no gc to report */
18969 		if (gc == NULL) {
18970 			ASSERT(sacnt == 0);
18971 			if (gcgrp != NULL) {
18972 				/* we might as well drop the lock now */
18973 				rw_exit(&gcgrp->gcgrp_rwlock);
18974 				gcgrp = NULL;
18975 			}
18976 			attrp = NULL;
18977 		}
18978 
18979 		ASSERT(gc == NULL || (gcgrp != NULL &&
18980 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18981 	}
18982 	ASSERT(sacnt == 0 || gc != NULL);
18983 
18984 	if (sacnt != 0 &&
18985 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18986 		kmem_free(re, sizeof (*re));
18987 		rw_exit(&gcgrp->gcgrp_rwlock);
18988 		return;
18989 	}
18990 
18991 	/*
18992 	 * Return all IRE types for route table... let caller pick and choose
18993 	 */
18994 	re->ipv6RouteDest = ire->ire_addr_v6;
18995 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18996 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18997 	re->ipv6RouteIfIndex.o_length = 0;
18998 	ipif = ire->ire_ipif;
18999 	if (ire->ire_type == IRE_CACHE) {
19000 		ill = (ill_t *)ire->ire_stq->q_ptr;
19001 		re->ipv6RouteIfIndex.o_length =
19002 		    ill->ill_name_length == 0 ? 0 :
19003 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19004 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19005 		    re->ipv6RouteIfIndex.o_length);
19006 	} else if (ipif != NULL) {
19007 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19008 		    OCTET_LENGTH);
19009 		re->ipv6RouteIfIndex.o_length =
19010 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19011 	}
19012 
19013 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19014 
19015 	mutex_enter(&ire->ire_lock);
19016 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19017 	mutex_exit(&ire->ire_lock);
19018 
19019 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19020 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19021 	else
19022 		re->ipv6RouteNextHop = gw_addr_v6;
19023 
19024 	/* remote(4), local(3), or discard(2) */
19025 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19026 		re->ipv6RouteType = 2;
19027 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19028 		re->ipv6RouteType = 3;
19029 	else
19030 		re->ipv6RouteType = 4;
19031 
19032 	re->ipv6RouteProtocol	= -1;
19033 	re->ipv6RoutePolicy	= 0;
19034 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19035 	re->ipv6RouteNextHopRDI	= 0;
19036 	re->ipv6RouteWeight	= 0;
19037 	re->ipv6RouteMetric	= 0;
19038 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19039 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19040 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19041 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19042 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19043 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19044 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19045 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19046 
19047 	if (ire->ire_flags & RTF_DYNAMIC) {
19048 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19049 	} else {
19050 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19051 	}
19052 
19053 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19054 	    (char *)re, (int)sizeof (*re))) {
19055 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19056 		    (uint_t)sizeof (*re)));
19057 	}
19058 
19059 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19060 		iaeptr->iae_routeidx = ird->ird_idx;
19061 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19062 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19063 	}
19064 
19065 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19066 	    (char *)iae, sacnt * sizeof (*iae))) {
19067 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19068 		    (unsigned)(sacnt * sizeof (*iae))));
19069 	}
19070 
19071 	/* bump route index for next pass */
19072 	ird->ird_idx++;
19073 
19074 	kmem_free(re, sizeof (*re));
19075 	if (sacnt != 0)
19076 		kmem_free(iae, sacnt * sizeof (*iae));
19077 
19078 	if (gcgrp != NULL)
19079 		rw_exit(&gcgrp->gcgrp_rwlock);
19080 }
19081 
19082 /*
19083  * ndp_walk routine to create ipv6NetToMediaEntryTable
19084  */
19085 static int
19086 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19087 {
19088 	ill_t				*ill;
19089 	mib2_ipv6NetToMediaEntry_t	ntme;
19090 	dl_unitdata_req_t		*dl;
19091 
19092 	ill = nce->nce_ill;
19093 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19094 		return (0);
19095 
19096 	/*
19097 	 * Neighbor cache entry attached to IRE with on-link
19098 	 * destination.
19099 	 */
19100 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19101 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19102 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19103 	    (nce->nce_res_mp != NULL)) {
19104 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19105 		ntme.ipv6NetToMediaPhysAddress.o_length =
19106 		    dl->dl_dest_addr_length;
19107 	} else {
19108 		ntme.ipv6NetToMediaPhysAddress.o_length =
19109 		    ill->ill_phys_addr_length;
19110 	}
19111 	if (nce->nce_res_mp != NULL) {
19112 		bcopy((char *)nce->nce_res_mp->b_rptr +
19113 		    NCE_LL_ADDR_OFFSET(ill),
19114 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19115 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19116 	} else {
19117 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19118 		    ill->ill_phys_addr_length);
19119 	}
19120 	/*
19121 	 * Note: Returns ND_* states. Should be:
19122 	 * reachable(1), stale(2), delay(3), probe(4),
19123 	 * invalid(5), unknown(6)
19124 	 */
19125 	ntme.ipv6NetToMediaState = nce->nce_state;
19126 	ntme.ipv6NetToMediaLastUpdated = 0;
19127 
19128 	/* other(1), dynamic(2), static(3), local(4) */
19129 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19130 		ntme.ipv6NetToMediaType = 4;
19131 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19132 		ntme.ipv6NetToMediaType = 1;
19133 	} else {
19134 		ntme.ipv6NetToMediaType = 2;
19135 	}
19136 
19137 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19138 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19139 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19140 		    (uint_t)sizeof (ntme)));
19141 	}
19142 	return (0);
19143 }
19144 
19145 /*
19146  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19147  */
19148 /* ARGSUSED */
19149 int
19150 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19151 {
19152 	switch (level) {
19153 	case MIB2_IP:
19154 	case MIB2_ICMP:
19155 		switch (name) {
19156 		default:
19157 			break;
19158 		}
19159 		return (1);
19160 	default:
19161 		return (1);
19162 	}
19163 }
19164 
19165 /*
19166  * Called before the options are updated to check if this packet will
19167  * be source routed from here.
19168  * This routine assumes that the options are well formed i.e. that they
19169  * have already been checked.
19170  */
19171 static boolean_t
19172 ip_source_routed(ipha_t *ipha)
19173 {
19174 	ipoptp_t	opts;
19175 	uchar_t		*opt;
19176 	uint8_t		optval;
19177 	uint8_t		optlen;
19178 	ipaddr_t	dst;
19179 	ire_t		*ire;
19180 
19181 	if (IS_SIMPLE_IPH(ipha)) {
19182 		ip2dbg(("not source routed\n"));
19183 		return (B_FALSE);
19184 	}
19185 	dst = ipha->ipha_dst;
19186 	for (optval = ipoptp_first(&opts, ipha);
19187 	    optval != IPOPT_EOL;
19188 	    optval = ipoptp_next(&opts)) {
19189 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19190 		opt = opts.ipoptp_cur;
19191 		optlen = opts.ipoptp_len;
19192 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19193 		    optval, optlen));
19194 		switch (optval) {
19195 			uint32_t off;
19196 		case IPOPT_SSRR:
19197 		case IPOPT_LSRR:
19198 			/*
19199 			 * If dst is one of our addresses and there are some
19200 			 * entries left in the source route return (true).
19201 			 */
19202 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19203 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19204 			if (ire == NULL) {
19205 				ip2dbg(("ip_source_routed: not next"
19206 				    " source route 0x%x\n",
19207 				    ntohl(dst)));
19208 				return (B_FALSE);
19209 			}
19210 			ire_refrele(ire);
19211 			off = opt[IPOPT_OFFSET];
19212 			off--;
19213 			if (optlen < IP_ADDR_LEN ||
19214 			    off > optlen - IP_ADDR_LEN) {
19215 				/* End of source route */
19216 				ip1dbg(("ip_source_routed: end of SR\n"));
19217 				return (B_FALSE);
19218 			}
19219 			return (B_TRUE);
19220 		}
19221 	}
19222 	ip2dbg(("not source routed\n"));
19223 	return (B_FALSE);
19224 }
19225 
19226 /*
19227  * Check if the packet contains any source route.
19228  */
19229 static boolean_t
19230 ip_source_route_included(ipha_t *ipha)
19231 {
19232 	ipoptp_t	opts;
19233 	uint8_t		optval;
19234 
19235 	if (IS_SIMPLE_IPH(ipha))
19236 		return (B_FALSE);
19237 	for (optval = ipoptp_first(&opts, ipha);
19238 	    optval != IPOPT_EOL;
19239 	    optval = ipoptp_next(&opts)) {
19240 		switch (optval) {
19241 		case IPOPT_SSRR:
19242 		case IPOPT_LSRR:
19243 			return (B_TRUE);
19244 		}
19245 	}
19246 	return (B_FALSE);
19247 }
19248 
19249 /*
19250  * Called when the IRE expiration timer fires.
19251  */
19252 /* ARGSUSED */
19253 void
19254 ip_trash_timer_expire(void *args)
19255 {
19256 	int	flush_flag = 0;
19257 
19258 	/*
19259 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19260 	 * This lock makes sure that a new invocation of this function
19261 	 * that occurs due to an almost immediate timer firing will not
19262 	 * progress beyond this point until the current invocation is done
19263 	 */
19264 	mutex_enter(&ip_trash_timer_lock);
19265 	ip_ire_expire_id = 0;
19266 	mutex_exit(&ip_trash_timer_lock);
19267 
19268 	/* Periodic timer */
19269 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19270 		/*
19271 		 * Remove all IRE_CACHE entries since they might
19272 		 * contain arp information.
19273 		 */
19274 		flush_flag |= FLUSH_ARP_TIME;
19275 		ip_ire_arp_time_elapsed = 0;
19276 		IP_STAT(ip_ire_arp_timer_expired);
19277 	}
19278 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19279 		/* Remove all redirects */
19280 		flush_flag |= FLUSH_REDIRECT_TIME;
19281 		ip_ire_rd_time_elapsed = 0;
19282 		IP_STAT(ip_ire_redirect_timer_expired);
19283 	}
19284 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19285 		/* Increase path mtu */
19286 		flush_flag |= FLUSH_MTU_TIME;
19287 		ip_ire_pmtu_time_elapsed = 0;
19288 		IP_STAT(ip_ire_pmtu_timer_expired);
19289 	}
19290 
19291 	/*
19292 	 * Optimize for the case when there are no redirects in the
19293 	 * ftable, that is, no need to walk the ftable in that case.
19294 	 */
19295 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19296 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19297 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19298 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19299 	}
19300 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19301 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19302 		    ire_expire, (char *)(uintptr_t)flush_flag,
19303 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19304 	}
19305 	if (flush_flag & FLUSH_MTU_TIME) {
19306 		/*
19307 		 * Walk all IPv6 IRE's and update them
19308 		 * Note that ARP and redirect timers are not
19309 		 * needed since NUD handles stale entries.
19310 		 */
19311 		flush_flag = FLUSH_MTU_TIME;
19312 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19313 		    ALL_ZONES);
19314 	}
19315 
19316 	ip_ire_arp_time_elapsed += ip_timer_interval;
19317 	ip_ire_rd_time_elapsed += ip_timer_interval;
19318 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19319 
19320 	/*
19321 	 * Hold the lock to serialize timeout calls and prevent
19322 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19323 	 * for the timer to fire and a new invocation of this function
19324 	 * to start before the return value of timeout has been stored
19325 	 * in ip_ire_expire_id by the current invocation.
19326 	 */
19327 	mutex_enter(&ip_trash_timer_lock);
19328 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19329 	    MSEC_TO_TICK(ip_timer_interval));
19330 	mutex_exit(&ip_trash_timer_lock);
19331 }
19332 
19333 /*
19334  * Called by the memory allocator subsystem directly, when the system
19335  * is running low on memory.
19336  */
19337 /* ARGSUSED */
19338 void
19339 ip_trash_ire_reclaim(void *args)
19340 {
19341 	ire_cache_count_t icc;
19342 	ire_cache_reclaim_t icr;
19343 	ncc_cache_count_t ncc;
19344 	nce_cache_reclaim_t ncr;
19345 	uint_t delete_cnt;
19346 	/*
19347 	 * Memory reclaim call back.
19348 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19349 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19350 	 * entries, determine what fraction to free for
19351 	 * each category of IRE_CACHE entries giving absolute priority
19352 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19353 	 * entry will be freed unless all offlink entries are freed).
19354 	 */
19355 	icc.icc_total = 0;
19356 	icc.icc_unused = 0;
19357 	icc.icc_offlink = 0;
19358 	icc.icc_pmtu = 0;
19359 	icc.icc_onlink = 0;
19360 	ire_walk(ire_cache_count, (char *)&icc);
19361 
19362 	/*
19363 	 * Free NCEs for IPv6 like the onlink ires.
19364 	 */
19365 	ncc.ncc_total = 0;
19366 	ncc.ncc_host = 0;
19367 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19368 
19369 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19370 	    icc.icc_pmtu + icc.icc_onlink);
19371 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19372 	IP_STAT(ip_trash_ire_reclaim_calls);
19373 	if (delete_cnt == 0)
19374 		return;
19375 	IP_STAT(ip_trash_ire_reclaim_success);
19376 	/* Always delete all unused offlink entries */
19377 	icr.icr_unused = 1;
19378 	if (delete_cnt <= icc.icc_unused) {
19379 		/*
19380 		 * Only need to free unused entries.  In other words,
19381 		 * there are enough unused entries to free to meet our
19382 		 * target number of freed ire cache entries.
19383 		 */
19384 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19385 		ncr.ncr_host = 0;
19386 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19387 		/*
19388 		 * Only need to free unused entries, plus a fraction of offlink
19389 		 * entries.  It follows from the first if statement that
19390 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19391 		 */
19392 		delete_cnt -= icc.icc_unused;
19393 		/* Round up # deleted by truncating fraction */
19394 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19395 		icr.icr_pmtu = icr.icr_onlink = 0;
19396 		ncr.ncr_host = 0;
19397 	} else if (delete_cnt <=
19398 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19399 		/*
19400 		 * Free all unused and offlink entries, plus a fraction of
19401 		 * pmtu entries.  It follows from the previous if statement
19402 		 * that icc_pmtu is non-zero, and that
19403 		 * delete_cnt != icc_unused + icc_offlink.
19404 		 */
19405 		icr.icr_offlink = 1;
19406 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19407 		/* Round up # deleted by truncating fraction */
19408 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19409 		icr.icr_onlink = 0;
19410 		ncr.ncr_host = 0;
19411 	} else {
19412 		/*
19413 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19414 		 * of onlink entries.  If we're here, then we know that
19415 		 * icc_onlink is non-zero, and that
19416 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19417 		 */
19418 		icr.icr_offlink = icr.icr_pmtu = 1;
19419 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19420 		    icc.icc_pmtu;
19421 		/* Round up # deleted by truncating fraction */
19422 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19423 		/* Using the same delete fraction as for onlink IREs */
19424 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19425 	}
19426 #ifdef DEBUG
19427 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19428 	    "fractions %d/%d/%d/%d\n",
19429 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19430 	    icc.icc_unused, icc.icc_offlink,
19431 	    icc.icc_pmtu, icc.icc_onlink,
19432 	    icr.icr_unused, icr.icr_offlink,
19433 	    icr.icr_pmtu, icr.icr_onlink));
19434 #endif
19435 	ire_walk(ire_cache_reclaim, (char *)&icr);
19436 	if (ncr.ncr_host != 0)
19437 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19438 		    (uchar_t *)&ncr);
19439 #ifdef DEBUG
19440 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19441 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19442 	ire_walk(ire_cache_count, (char *)&icc);
19443 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19444 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19445 	    icc.icc_pmtu, icc.icc_onlink));
19446 #endif
19447 }
19448 
19449 /*
19450  * ip_unbind is called when a copy of an unbind request is received from the
19451  * upper level protocol.  We remove this conn from any fanout hash list it is
19452  * on, and zero out the bind information.  No reply is expected up above.
19453  */
19454 mblk_t *
19455 ip_unbind(queue_t *q, mblk_t *mp)
19456 {
19457 	conn_t	*connp = Q_TO_CONN(q);
19458 
19459 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19460 
19461 	if (is_system_labeled() && connp->conn_anon_port) {
19462 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19463 		    connp->conn_mlp_type, connp->conn_ulp,
19464 		    ntohs(connp->conn_lport), B_FALSE);
19465 		connp->conn_anon_port = 0;
19466 	}
19467 	connp->conn_mlp_type = mlptSingle;
19468 
19469 	ipcl_hash_remove(connp);
19470 
19471 	ASSERT(mp->b_cont == NULL);
19472 	/*
19473 	 * Convert mp into a T_OK_ACK
19474 	 */
19475 	mp = mi_tpi_ok_ack_alloc(mp);
19476 
19477 	/*
19478 	 * should not happen in practice... T_OK_ACK is smaller than the
19479 	 * original message.
19480 	 */
19481 	if (mp == NULL)
19482 		return (NULL);
19483 
19484 	/*
19485 	 * Don't bzero the ports if its TCP since TCP still needs the
19486 	 * lport to remove it from its own bind hash. TCP will do the
19487 	 * cleanup.
19488 	 */
19489 	if (!IPCL_IS_TCP(connp))
19490 		bzero(&connp->u_port, sizeof (connp->u_port));
19491 
19492 	return (mp);
19493 }
19494 
19495 /*
19496  * Write side put procedure.  Outbound data, IOCTLs, responses from
19497  * resolvers, etc, come down through here.
19498  *
19499  * arg2 is always a queue_t *.
19500  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19501  * the zoneid.
19502  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19503  */
19504 void
19505 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19506 {
19507 	conn_t		*connp = NULL;
19508 	queue_t		*q = (queue_t *)arg2;
19509 	ipha_t		*ipha;
19510 #define	rptr	((uchar_t *)ipha)
19511 	ire_t		*ire = NULL;
19512 	ire_t		*sctp_ire = NULL;
19513 	uint32_t	v_hlen_tos_len;
19514 	ipaddr_t	dst;
19515 	mblk_t		*first_mp = NULL;
19516 	boolean_t	mctl_present;
19517 	ipsec_out_t	*io;
19518 	int		match_flags;
19519 	ill_t		*attach_ill = NULL;
19520 					/* Bind to IPIF_NOFAILOVER ill etc. */
19521 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19522 	ipif_t		*dst_ipif;
19523 	boolean_t	multirt_need_resolve = B_FALSE;
19524 	mblk_t		*copy_mp = NULL;
19525 	int		err;
19526 	zoneid_t	zoneid;
19527 	int	adjust;
19528 	uint16_t iplen;
19529 	boolean_t	need_decref = B_FALSE;
19530 	boolean_t	ignore_dontroute = B_FALSE;
19531 	boolean_t	ignore_nexthop = B_FALSE;
19532 	boolean_t	ip_nexthop = B_FALSE;
19533 	ipaddr_t	nexthop_addr;
19534 
19535 #ifdef	_BIG_ENDIAN
19536 #define	V_HLEN	(v_hlen_tos_len >> 24)
19537 #else
19538 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19539 #endif
19540 
19541 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19542 	    "ip_wput_start: q %p", q);
19543 
19544 	/*
19545 	 * ip_wput fast path
19546 	 */
19547 
19548 	/* is packet from ARP ? */
19549 	if (q->q_next != NULL) {
19550 		zoneid = (zoneid_t)(uintptr_t)arg;
19551 		goto qnext;
19552 	}
19553 
19554 	connp = (conn_t *)arg;
19555 	ASSERT(connp != NULL);
19556 	zoneid = connp->conn_zoneid;
19557 
19558 	/* is queue flow controlled? */
19559 	if ((q->q_first != NULL || connp->conn_draining) &&
19560 	    (caller == IP_WPUT)) {
19561 		ASSERT(!need_decref);
19562 		(void) putq(q, mp);
19563 		return;
19564 	}
19565 
19566 	/* Multidata transmit? */
19567 	if (DB_TYPE(mp) == M_MULTIDATA) {
19568 		/*
19569 		 * We should never get here, since all Multidata messages
19570 		 * originating from tcp should have been directed over to
19571 		 * tcp_multisend() in the first place.
19572 		 */
19573 		BUMP_MIB(&ip_mib, ipOutDiscards);
19574 		freemsg(mp);
19575 		return;
19576 	} else if (DB_TYPE(mp) != M_DATA)
19577 		goto notdata;
19578 
19579 	if (mp->b_flag & MSGHASREF) {
19580 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19581 		mp->b_flag &= ~MSGHASREF;
19582 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19583 		need_decref = B_TRUE;
19584 	}
19585 	ipha = (ipha_t *)mp->b_rptr;
19586 
19587 	/* is IP header non-aligned or mblk smaller than basic IP header */
19588 #ifndef SAFETY_BEFORE_SPEED
19589 	if (!OK_32PTR(rptr) ||
19590 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19591 		goto hdrtoosmall;
19592 #endif
19593 
19594 	ASSERT(OK_32PTR(ipha));
19595 
19596 	/*
19597 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19598 	 * wrong version, we'll catch it again in ip_output_v6.
19599 	 *
19600 	 * Note that this is *only* locally-generated output here, and never
19601 	 * forwarded data, and that we need to deal only with transports that
19602 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19603 	 * label.)
19604 	 */
19605 	if (is_system_labeled() &&
19606 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19607 	    !connp->conn_ulp_labeled) {
19608 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19609 		    connp->conn_mac_exempt);
19610 		ipha = (ipha_t *)mp->b_rptr;
19611 		if (err != 0) {
19612 			first_mp = mp;
19613 			if (err == EINVAL)
19614 				goto icmp_parameter_problem;
19615 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19616 			goto drop_pkt;
19617 		}
19618 		iplen = ntohs(ipha->ipha_length) + adjust;
19619 		ipha->ipha_length = htons(iplen);
19620 	}
19621 
19622 	/*
19623 	 * If there is a policy, try to attach an ipsec_out in
19624 	 * the front. At the end, first_mp either points to a
19625 	 * M_DATA message or IPSEC_OUT message linked to a
19626 	 * M_DATA message. We have to do it now as we might
19627 	 * lose the "conn" if we go through ip_newroute.
19628 	 */
19629 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19630 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19631 		    ipha->ipha_protocol)) == NULL)) {
19632 			if (need_decref)
19633 				CONN_DEC_REF(connp);
19634 			return;
19635 		} else {
19636 			ASSERT(mp->b_datap->db_type == M_CTL);
19637 			first_mp = mp;
19638 			mp = mp->b_cont;
19639 			mctl_present = B_TRUE;
19640 		}
19641 	} else {
19642 		first_mp = mp;
19643 		mctl_present = B_FALSE;
19644 	}
19645 
19646 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19647 
19648 	/* is wrong version or IP options present */
19649 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19650 		goto version_hdrlen_check;
19651 	dst = ipha->ipha_dst;
19652 
19653 	if (connp->conn_nofailover_ill != NULL) {
19654 		attach_ill = conn_get_held_ill(connp,
19655 		    &connp->conn_nofailover_ill, &err);
19656 		if (err == ILL_LOOKUP_FAILED) {
19657 			if (need_decref)
19658 				CONN_DEC_REF(connp);
19659 			freemsg(first_mp);
19660 			return;
19661 		}
19662 	}
19663 
19664 	/* is packet multicast? */
19665 	if (CLASSD(dst))
19666 		goto multicast;
19667 
19668 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19669 	    (connp->conn_nexthop_set)) {
19670 		/*
19671 		 * If the destination is a broadcast or a loopback
19672 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19673 		 * through the standard path. But in the case of local
19674 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19675 		 * the standard path not IP_XMIT_IF.
19676 		 */
19677 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19678 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19679 		    (ire->ire_type != IRE_LOOPBACK))) {
19680 			if ((connp->conn_dontroute ||
19681 			    connp->conn_nexthop_set) && (ire != NULL) &&
19682 			    (ire->ire_type == IRE_LOCAL))
19683 				goto standard_path;
19684 
19685 			if (ire != NULL) {
19686 				ire_refrele(ire);
19687 				/* No more access to ire */
19688 				ire = NULL;
19689 			}
19690 			/*
19691 			 * bypass routing checks and go directly to
19692 			 * interface.
19693 			 */
19694 			if (connp->conn_dontroute) {
19695 				goto dontroute;
19696 			} else if (connp->conn_nexthop_set) {
19697 				ip_nexthop = B_TRUE;
19698 				nexthop_addr = connp->conn_nexthop_v4;
19699 				goto send_from_ill;
19700 			}
19701 
19702 			/*
19703 			 * If IP_XMIT_IF socket option is set,
19704 			 * then we allow unicast and multicast
19705 			 * packets to go through the ill. It is
19706 			 * quite possible that the destination
19707 			 * is not in the ire cache table and we
19708 			 * do not want to go to ip_newroute()
19709 			 * instead we call ip_newroute_ipif.
19710 			 */
19711 			xmit_ill = conn_get_held_ill(connp,
19712 			    &connp->conn_xmit_if_ill, &err);
19713 			if (err == ILL_LOOKUP_FAILED) {
19714 				if (attach_ill != NULL)
19715 					ill_refrele(attach_ill);
19716 				if (need_decref)
19717 					CONN_DEC_REF(connp);
19718 				freemsg(first_mp);
19719 				return;
19720 			}
19721 			goto send_from_ill;
19722 		}
19723 standard_path:
19724 		/* Must be a broadcast, a loopback or a local ire */
19725 		if (ire != NULL) {
19726 			ire_refrele(ire);
19727 			/* No more access to ire */
19728 			ire = NULL;
19729 		}
19730 	}
19731 
19732 	if (attach_ill != NULL)
19733 		goto send_from_ill;
19734 
19735 	/*
19736 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19737 	 * this for the tcp global queue and listen end point
19738 	 * as it does not really have a real destination to
19739 	 * talk to.  This is also true for SCTP.
19740 	 */
19741 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19742 	    !connp->conn_fully_bound) {
19743 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19744 		if (ire == NULL)
19745 			goto noirefound;
19746 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19747 		    "ip_wput_end: q %p (%S)", q, "end");
19748 
19749 		/*
19750 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19751 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19752 		 */
19753 		if (ire->ire_flags & RTF_MULTIRT) {
19754 
19755 			/*
19756 			 * Force the TTL of multirouted packets if required.
19757 			 * The TTL of such packets is bounded by the
19758 			 * ip_multirt_ttl ndd variable.
19759 			 */
19760 			if ((ip_multirt_ttl > 0) &&
19761 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19762 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19763 				    "(was %d), dst 0x%08x\n",
19764 				    ip_multirt_ttl, ipha->ipha_ttl,
19765 				    ntohl(ire->ire_addr)));
19766 				ipha->ipha_ttl = ip_multirt_ttl;
19767 			}
19768 			/*
19769 			 * We look at this point if there are pending
19770 			 * unresolved routes. ire_multirt_resolvable()
19771 			 * checks in O(n) that all IRE_OFFSUBNET ire
19772 			 * entries for the packet's destination and
19773 			 * flagged RTF_MULTIRT are currently resolved.
19774 			 * If some remain unresolved, we make a copy
19775 			 * of the current message. It will be used
19776 			 * to initiate additional route resolutions.
19777 			 */
19778 			multirt_need_resolve =
19779 			    ire_multirt_need_resolve(ire->ire_addr,
19780 			    MBLK_GETLABEL(first_mp));
19781 			ip2dbg(("ip_wput[TCP]: ire %p, "
19782 			    "multirt_need_resolve %d, first_mp %p\n",
19783 			    (void *)ire, multirt_need_resolve,
19784 			    (void *)first_mp));
19785 			if (multirt_need_resolve) {
19786 				copy_mp = copymsg(first_mp);
19787 				if (copy_mp != NULL) {
19788 					MULTIRT_DEBUG_TAG(copy_mp);
19789 				}
19790 			}
19791 		}
19792 
19793 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19794 
19795 		/*
19796 		 * Try to resolve another multiroute if
19797 		 * ire_multirt_need_resolve() deemed it necessary.
19798 		 */
19799 		if (copy_mp != NULL) {
19800 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19801 		}
19802 		if (need_decref)
19803 			CONN_DEC_REF(connp);
19804 		return;
19805 	}
19806 
19807 	/*
19808 	 * Access to conn_ire_cache. (protected by conn_lock)
19809 	 *
19810 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19811 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19812 	 * send a packet or two with the IRE_CACHE that is going away.
19813 	 * Access to the ire requires an ire refhold on the ire prior to
19814 	 * its use since an interface unplumb thread may delete the cached
19815 	 * ire and release the refhold at any time.
19816 	 *
19817 	 * Caching an ire in the conn_ire_cache
19818 	 *
19819 	 * o Caching an ire pointer in the conn requires a strict check for
19820 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19821 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19822 	 * in the conn is done after making sure under the bucket lock that the
19823 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19824 	 * caching an ire after the unplumb thread has cleaned up the conn.
19825 	 * If the conn does not send a packet subsequently the unplumb thread
19826 	 * will be hanging waiting for the ire count to drop to zero.
19827 	 *
19828 	 * o We also need to atomically test for a null conn_ire_cache and
19829 	 * set the conn_ire_cache under the the protection of the conn_lock
19830 	 * to avoid races among concurrent threads trying to simultaneously
19831 	 * cache an ire in the conn_ire_cache.
19832 	 */
19833 	mutex_enter(&connp->conn_lock);
19834 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19835 
19836 	if (ire != NULL && ire->ire_addr == dst &&
19837 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19838 
19839 		IRE_REFHOLD(ire);
19840 		mutex_exit(&connp->conn_lock);
19841 
19842 	} else {
19843 		boolean_t cached = B_FALSE;
19844 		connp->conn_ire_cache = NULL;
19845 		mutex_exit(&connp->conn_lock);
19846 		/* Release the old ire */
19847 		if (ire != NULL && sctp_ire == NULL)
19848 			IRE_REFRELE_NOTR(ire);
19849 
19850 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19851 		if (ire == NULL)
19852 			goto noirefound;
19853 		IRE_REFHOLD_NOTR(ire);
19854 
19855 		mutex_enter(&connp->conn_lock);
19856 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19857 		    connp->conn_ire_cache == NULL) {
19858 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19859 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19860 				connp->conn_ire_cache = ire;
19861 				cached = B_TRUE;
19862 			}
19863 			rw_exit(&ire->ire_bucket->irb_lock);
19864 		}
19865 		mutex_exit(&connp->conn_lock);
19866 
19867 		/*
19868 		 * We can continue to use the ire but since it was
19869 		 * not cached, we should drop the extra reference.
19870 		 */
19871 		if (!cached)
19872 			IRE_REFRELE_NOTR(ire);
19873 	}
19874 
19875 
19876 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19877 	    "ip_wput_end: q %p (%S)", q, "end");
19878 
19879 	/*
19880 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19881 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19882 	 */
19883 	if (ire->ire_flags & RTF_MULTIRT) {
19884 
19885 		/*
19886 		 * Force the TTL of multirouted packets if required.
19887 		 * The TTL of such packets is bounded by the
19888 		 * ip_multirt_ttl ndd variable.
19889 		 */
19890 		if ((ip_multirt_ttl > 0) &&
19891 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19892 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19893 			    "(was %d), dst 0x%08x\n",
19894 			    ip_multirt_ttl, ipha->ipha_ttl,
19895 			    ntohl(ire->ire_addr)));
19896 			ipha->ipha_ttl = ip_multirt_ttl;
19897 		}
19898 
19899 		/*
19900 		 * At this point, we check to see if there are any pending
19901 		 * unresolved routes. ire_multirt_resolvable()
19902 		 * checks in O(n) that all IRE_OFFSUBNET ire
19903 		 * entries for the packet's destination and
19904 		 * flagged RTF_MULTIRT are currently resolved.
19905 		 * If some remain unresolved, we make a copy
19906 		 * of the current message. It will be used
19907 		 * to initiate additional route resolutions.
19908 		 */
19909 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19910 		    MBLK_GETLABEL(first_mp));
19911 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19912 		    "multirt_need_resolve %d, first_mp %p\n",
19913 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19914 		if (multirt_need_resolve) {
19915 			copy_mp = copymsg(first_mp);
19916 			if (copy_mp != NULL) {
19917 				MULTIRT_DEBUG_TAG(copy_mp);
19918 			}
19919 		}
19920 	}
19921 
19922 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19923 
19924 	/*
19925 	 * Try to resolve another multiroute if
19926 	 * ire_multirt_resolvable() deemed it necessary
19927 	 */
19928 	if (copy_mp != NULL) {
19929 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19930 	}
19931 	if (need_decref)
19932 		CONN_DEC_REF(connp);
19933 	return;
19934 
19935 qnext:
19936 	/*
19937 	 * Upper Level Protocols pass down complete IP datagrams
19938 	 * as M_DATA messages.	Everything else is a sideshow.
19939 	 *
19940 	 * 1) We could be re-entering ip_wput because of ip_neworute
19941 	 *    in which case we could have a IPSEC_OUT message. We
19942 	 *    need to pass through ip_wput like other datagrams and
19943 	 *    hence cannot branch to ip_wput_nondata.
19944 	 *
19945 	 * 2) ARP, AH, ESP, and other clients who are on the module
19946 	 *    instance of IP stream, give us something to deal with.
19947 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19948 	 *
19949 	 * 3) ICMP replies also could come here.
19950 	 */
19951 	if (DB_TYPE(mp) != M_DATA) {
19952 	    notdata:
19953 		if (DB_TYPE(mp) == M_CTL) {
19954 			/*
19955 			 * M_CTL messages are used by ARP, AH and ESP to
19956 			 * communicate with IP. We deal with IPSEC_IN and
19957 			 * IPSEC_OUT here. ip_wput_nondata handles other
19958 			 * cases.
19959 			 */
19960 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19961 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19962 				first_mp = mp->b_cont;
19963 				first_mp->b_flag &= ~MSGHASREF;
19964 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19965 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19966 				CONN_DEC_REF(connp);
19967 				connp = NULL;
19968 			}
19969 			if (ii->ipsec_info_type == IPSEC_IN) {
19970 				/*
19971 				 * Either this message goes back to
19972 				 * IPSEC for further processing or to
19973 				 * ULP after policy checks.
19974 				 */
19975 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19976 				return;
19977 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19978 				io = (ipsec_out_t *)ii;
19979 				if (io->ipsec_out_proc_begin) {
19980 					/*
19981 					 * IPSEC processing has already started.
19982 					 * Complete it.
19983 					 * IPQoS notes: We don't care what is
19984 					 * in ipsec_out_ill_index since this
19985 					 * won't be processed for IPQoS policies
19986 					 * in ipsec_out_process.
19987 					 */
19988 					ipsec_out_process(q, mp, NULL,
19989 					    io->ipsec_out_ill_index);
19990 					return;
19991 				} else {
19992 					connp = (q->q_next != NULL) ?
19993 					    NULL : Q_TO_CONN(q);
19994 					first_mp = mp;
19995 					mp = mp->b_cont;
19996 					mctl_present = B_TRUE;
19997 				}
19998 				zoneid = io->ipsec_out_zoneid;
19999 				ASSERT(zoneid != ALL_ZONES);
20000 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20001 				/*
20002 				 * It's an IPsec control message requesting
20003 				 * an SADB update to be sent to the IPsec
20004 				 * hardware acceleration capable ills.
20005 				 */
20006 				ipsec_ctl_t *ipsec_ctl =
20007 				    (ipsec_ctl_t *)mp->b_rptr;
20008 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20009 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20010 				mblk_t *cmp = mp->b_cont;
20011 
20012 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20013 				ASSERT(cmp != NULL);
20014 
20015 				freeb(mp);
20016 				ill_ipsec_capab_send_all(satype, cmp, sa);
20017 				return;
20018 			} else {
20019 				/*
20020 				 * This must be ARP or special TSOL signaling.
20021 				 */
20022 				ip_wput_nondata(NULL, q, mp, NULL);
20023 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20024 				    "ip_wput_end: q %p (%S)", q, "nondata");
20025 				return;
20026 			}
20027 		} else {
20028 			/*
20029 			 * This must be non-(ARP/AH/ESP) messages.
20030 			 */
20031 			ASSERT(!need_decref);
20032 			ip_wput_nondata(NULL, q, mp, NULL);
20033 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20034 			    "ip_wput_end: q %p (%S)", q, "nondata");
20035 			return;
20036 		}
20037 	} else {
20038 		first_mp = mp;
20039 		mctl_present = B_FALSE;
20040 	}
20041 
20042 	ASSERT(first_mp != NULL);
20043 	/*
20044 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20045 	 * to make sure that this packet goes out on the same interface it
20046 	 * came in. We handle that here.
20047 	 */
20048 	if (mctl_present) {
20049 		uint_t ifindex;
20050 
20051 		io = (ipsec_out_t *)first_mp->b_rptr;
20052 		if (io->ipsec_out_attach_if ||
20053 		    io->ipsec_out_xmit_if ||
20054 		    io->ipsec_out_ip_nexthop) {
20055 			ill_t	*ill;
20056 
20057 			/*
20058 			 * We may have lost the conn context if we are
20059 			 * coming here from ip_newroute(). Copy the
20060 			 * nexthop information.
20061 			 */
20062 			if (io->ipsec_out_ip_nexthop) {
20063 				ip_nexthop = B_TRUE;
20064 				nexthop_addr = io->ipsec_out_nexthop_addr;
20065 
20066 				ipha = (ipha_t *)mp->b_rptr;
20067 				dst = ipha->ipha_dst;
20068 				goto send_from_ill;
20069 			} else {
20070 				ASSERT(io->ipsec_out_ill_index != 0);
20071 				ifindex = io->ipsec_out_ill_index;
20072 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20073 				    NULL, NULL, NULL, NULL);
20074 				/*
20075 				 * ipsec_out_xmit_if bit is used to tell
20076 				 * ip_wput to use the ill to send outgoing data
20077 				 * as we have no conn when data comes from ICMP
20078 				 * error msg routines. Currently this feature is
20079 				 * only used by ip_mrtun_forward routine.
20080 				 */
20081 				if (io->ipsec_out_xmit_if) {
20082 					xmit_ill = ill;
20083 					if (xmit_ill == NULL) {
20084 						ip1dbg(("ip_output:bad ifindex "
20085 						    "for xmit_ill %d\n",
20086 						    ifindex));
20087 						freemsg(first_mp);
20088 						BUMP_MIB(&ip_mib,
20089 						    ipOutDiscards);
20090 						ASSERT(!need_decref);
20091 						return;
20092 					}
20093 					/* Free up the ipsec_out_t mblk */
20094 					ASSERT(first_mp->b_cont == mp);
20095 					first_mp->b_cont = NULL;
20096 					freeb(first_mp);
20097 					/* Just send the IP header+ICMP+data */
20098 					first_mp = mp;
20099 					ipha = (ipha_t *)mp->b_rptr;
20100 					dst = ipha->ipha_dst;
20101 					goto send_from_ill;
20102 				} else {
20103 					attach_ill = ill;
20104 				}
20105 
20106 				if (attach_ill == NULL) {
20107 					ASSERT(xmit_ill == NULL);
20108 					ip1dbg(("ip_output: bad ifindex for "
20109 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20110 					    ifindex));
20111 					freemsg(first_mp);
20112 					BUMP_MIB(&ip_mib, ipOutDiscards);
20113 					ASSERT(!need_decref);
20114 					return;
20115 				}
20116 			}
20117 		}
20118 	}
20119 
20120 	ASSERT(xmit_ill == NULL);
20121 
20122 	/* We have a complete IP datagram heading outbound. */
20123 	ipha = (ipha_t *)mp->b_rptr;
20124 
20125 #ifndef SPEED_BEFORE_SAFETY
20126 	/*
20127 	 * Make sure we have a full-word aligned message and that at least
20128 	 * a simple IP header is accessible in the first message.  If not,
20129 	 * try a pullup.
20130 	 */
20131 	if (!OK_32PTR(rptr) ||
20132 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20133 	    hdrtoosmall:
20134 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20135 			BUMP_MIB(&ip_mib, ipOutDiscards);
20136 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20137 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20138 			if (first_mp == NULL)
20139 				first_mp = mp;
20140 			goto drop_pkt;
20141 		}
20142 
20143 		/* This function assumes that mp points to an IPv4 packet. */
20144 		if (is_system_labeled() && q->q_next == NULL &&
20145 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20146 		    !connp->conn_ulp_labeled) {
20147 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20148 			    &adjust, connp->conn_mac_exempt);
20149 			ipha = (ipha_t *)mp->b_rptr;
20150 			if (first_mp != NULL)
20151 				first_mp->b_cont = mp;
20152 			if (err != 0) {
20153 				if (first_mp == NULL)
20154 					first_mp = mp;
20155 				if (err == EINVAL)
20156 					goto icmp_parameter_problem;
20157 				ip2dbg(("ip_wput: label check failed (%d)\n",
20158 				    err));
20159 				goto drop_pkt;
20160 			}
20161 			iplen = ntohs(ipha->ipha_length) + adjust;
20162 			ipha->ipha_length = htons(iplen);
20163 		}
20164 
20165 		ipha = (ipha_t *)mp->b_rptr;
20166 		if (first_mp == NULL) {
20167 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20168 			/*
20169 			 * If we got here because of "goto hdrtoosmall"
20170 			 * We need to attach a IPSEC_OUT.
20171 			 */
20172 			if (connp->conn_out_enforce_policy) {
20173 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20174 				    NULL, ipha->ipha_protocol)) == NULL)) {
20175 					if (need_decref)
20176 						CONN_DEC_REF(connp);
20177 					return;
20178 				} else {
20179 					ASSERT(mp->b_datap->db_type == M_CTL);
20180 					first_mp = mp;
20181 					mp = mp->b_cont;
20182 					mctl_present = B_TRUE;
20183 				}
20184 			} else {
20185 				first_mp = mp;
20186 				mctl_present = B_FALSE;
20187 			}
20188 		}
20189 	}
20190 #endif
20191 
20192 	/* Most of the code below is written for speed, not readability */
20193 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20194 
20195 	/*
20196 	 * If ip_newroute() fails, we're going to need a full
20197 	 * header for the icmp wraparound.
20198 	 */
20199 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20200 		uint_t	v_hlen;
20201 	    version_hdrlen_check:
20202 		ASSERT(first_mp != NULL);
20203 		v_hlen = V_HLEN;
20204 		/*
20205 		 * siphon off IPv6 packets coming down from transport
20206 		 * layer modules here.
20207 		 * Note: high-order bit carries NUD reachability confirmation
20208 		 */
20209 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20210 			/*
20211 			 * XXX implement a IPv4 and IPv6 packet counter per
20212 			 * conn and switch when ratio exceeds e.g. 10:1
20213 			 */
20214 #ifdef notyet
20215 			if (q->q_next == NULL) /* Avoid ill queue */
20216 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20217 #endif
20218 			BUMP_MIB(&ip_mib, ipOutIPv6);
20219 			ASSERT(xmit_ill == NULL);
20220 			if (attach_ill != NULL)
20221 				ill_refrele(attach_ill);
20222 			if (need_decref)
20223 				mp->b_flag |= MSGHASREF;
20224 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20225 			return;
20226 		}
20227 
20228 		if ((v_hlen >> 4) != IP_VERSION) {
20229 			BUMP_MIB(&ip_mib, ipOutDiscards);
20230 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20231 			    "ip_wput_end: q %p (%S)", q, "badvers");
20232 			goto drop_pkt;
20233 		}
20234 		/*
20235 		 * Is the header length at least 20 bytes?
20236 		 *
20237 		 * Are there enough bytes accessible in the header?  If
20238 		 * not, try a pullup.
20239 		 */
20240 		v_hlen &= 0xF;
20241 		v_hlen <<= 2;
20242 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20243 			BUMP_MIB(&ip_mib, ipOutDiscards);
20244 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20245 			    "ip_wput_end: q %p (%S)", q, "badlen");
20246 			goto drop_pkt;
20247 		}
20248 		if (v_hlen > (mp->b_wptr - rptr)) {
20249 			if (!pullupmsg(mp, v_hlen)) {
20250 				BUMP_MIB(&ip_mib, ipOutDiscards);
20251 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20252 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20253 				goto drop_pkt;
20254 			}
20255 			ipha = (ipha_t *)mp->b_rptr;
20256 		}
20257 		/*
20258 		 * Move first entry from any source route into ipha_dst and
20259 		 * verify the options
20260 		 */
20261 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20262 			ASSERT(xmit_ill == NULL);
20263 			if (attach_ill != NULL)
20264 				ill_refrele(attach_ill);
20265 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20266 			    "ip_wput_end: q %p (%S)", q, "badopts");
20267 			if (need_decref)
20268 				CONN_DEC_REF(connp);
20269 			return;
20270 		}
20271 	}
20272 	dst = ipha->ipha_dst;
20273 
20274 	/*
20275 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20276 	 * we have to run the packet through ip_newroute which will take
20277 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20278 	 * a resolver, or assigning a default gateway, etc.
20279 	 */
20280 	if (CLASSD(dst)) {
20281 		ipif_t	*ipif;
20282 		uint32_t setsrc = 0;
20283 
20284 	    multicast:
20285 		ASSERT(first_mp != NULL);
20286 		ASSERT(xmit_ill == NULL);
20287 		ip2dbg(("ip_wput: CLASSD\n"));
20288 		if (connp == NULL) {
20289 			/*
20290 			 * Use the first good ipif on the ill.
20291 			 * XXX Should this ever happen? (Appears
20292 			 * to show up with just ppp and no ethernet due
20293 			 * to in.rdisc.)
20294 			 * However, ire_send should be able to
20295 			 * call ip_wput_ire directly.
20296 			 *
20297 			 * XXX Also, this can happen for ICMP and other packets
20298 			 * with multicast source addresses.  Perhaps we should
20299 			 * fix things so that we drop the packet in question,
20300 			 * but for now, just run with it.
20301 			 */
20302 			ill_t *ill = (ill_t *)q->q_ptr;
20303 
20304 			/*
20305 			 * Don't honor attach_if for this case. If ill
20306 			 * is part of the group, ipif could belong to
20307 			 * any ill and we cannot maintain attach_ill
20308 			 * and ipif_ill same anymore and the assert
20309 			 * below would fail.
20310 			 */
20311 			if (mctl_present && io->ipsec_out_attach_if) {
20312 				io->ipsec_out_ill_index = 0;
20313 				io->ipsec_out_attach_if = B_FALSE;
20314 				ASSERT(attach_ill != NULL);
20315 				ill_refrele(attach_ill);
20316 				attach_ill = NULL;
20317 			}
20318 
20319 			ASSERT(attach_ill == NULL);
20320 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20321 			if (ipif == NULL) {
20322 				if (need_decref)
20323 					CONN_DEC_REF(connp);
20324 				freemsg(first_mp);
20325 				return;
20326 			}
20327 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20328 			    ntohl(dst), ill->ill_name));
20329 		} else {
20330 			/*
20331 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20332 			 * IP_XMIT_IF is honoured.
20333 			 * Block comment above this function explains the
20334 			 * locking mechanism used here
20335 			 */
20336 			xmit_ill = conn_get_held_ill(connp,
20337 			    &connp->conn_xmit_if_ill, &err);
20338 			if (err == ILL_LOOKUP_FAILED) {
20339 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20340 				goto drop_pkt;
20341 			}
20342 			if (xmit_ill == NULL) {
20343 				ipif = conn_get_held_ipif(connp,
20344 				    &connp->conn_multicast_ipif, &err);
20345 				if (err == IPIF_LOOKUP_FAILED) {
20346 					ip1dbg(("ip_wput: No ipif for "
20347 					    "multicast\n"));
20348 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20349 					goto drop_pkt;
20350 				}
20351 			}
20352 			if (xmit_ill != NULL) {
20353 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20354 				if (ipif == NULL) {
20355 					ip1dbg(("ip_wput: No ipif for "
20356 					    "IP_XMIT_IF\n"));
20357 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20358 					goto drop_pkt;
20359 				}
20360 			} else if (ipif == NULL || ipif->ipif_isv6) {
20361 				/*
20362 				 * We must do this ipif determination here
20363 				 * else we could pass through ip_newroute
20364 				 * and come back here without the conn context.
20365 				 *
20366 				 * Note: we do late binding i.e. we bind to
20367 				 * the interface when the first packet is sent.
20368 				 * For performance reasons we do not rebind on
20369 				 * each packet but keep the binding until the
20370 				 * next IP_MULTICAST_IF option.
20371 				 *
20372 				 * conn_multicast_{ipif,ill} are shared between
20373 				 * IPv4 and IPv6 and AF_INET6 sockets can
20374 				 * send both IPv4 and IPv6 packets. Hence
20375 				 * we have to check that "isv6" matches above.
20376 				 */
20377 				if (ipif != NULL)
20378 					ipif_refrele(ipif);
20379 				ipif = ipif_lookup_group(dst, zoneid);
20380 				if (ipif == NULL) {
20381 					ip1dbg(("ip_wput: No ipif for "
20382 					    "multicast\n"));
20383 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20384 					goto drop_pkt;
20385 				}
20386 				err = conn_set_held_ipif(connp,
20387 				    &connp->conn_multicast_ipif, ipif);
20388 				if (err == IPIF_LOOKUP_FAILED) {
20389 					ipif_refrele(ipif);
20390 					ip1dbg(("ip_wput: No ipif for "
20391 					    "multicast\n"));
20392 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20393 					goto drop_pkt;
20394 				}
20395 			}
20396 		}
20397 		ASSERT(!ipif->ipif_isv6);
20398 		/*
20399 		 * As we may lose the conn by the time we reach ip_wput_ire,
20400 		 * we copy conn_multicast_loop and conn_dontroute on to an
20401 		 * ipsec_out. In case if this datagram goes out secure,
20402 		 * we need the ill_index also. Copy that also into the
20403 		 * ipsec_out.
20404 		 */
20405 		if (mctl_present) {
20406 			io = (ipsec_out_t *)first_mp->b_rptr;
20407 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20408 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20409 		} else {
20410 			ASSERT(mp == first_mp);
20411 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20412 			    BPRI_HI)) == NULL) {
20413 				ipif_refrele(ipif);
20414 				first_mp = mp;
20415 				goto drop_pkt;
20416 			}
20417 			first_mp->b_datap->db_type = M_CTL;
20418 			first_mp->b_wptr += sizeof (ipsec_info_t);
20419 			/* ipsec_out_secure is B_FALSE now */
20420 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20421 			io = (ipsec_out_t *)first_mp->b_rptr;
20422 			io->ipsec_out_type = IPSEC_OUT;
20423 			io->ipsec_out_len = sizeof (ipsec_out_t);
20424 			io->ipsec_out_use_global_policy = B_TRUE;
20425 			first_mp->b_cont = mp;
20426 			mctl_present = B_TRUE;
20427 		}
20428 		if (attach_ill != NULL) {
20429 			ASSERT(attach_ill == ipif->ipif_ill);
20430 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20431 
20432 			/*
20433 			 * Check if we need an ire that will not be
20434 			 * looked up by anybody else i.e. HIDDEN.
20435 			 */
20436 			if (ill_is_probeonly(attach_ill)) {
20437 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20438 			}
20439 			io->ipsec_out_ill_index =
20440 			    attach_ill->ill_phyint->phyint_ifindex;
20441 			io->ipsec_out_attach_if = B_TRUE;
20442 		} else {
20443 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20444 			io->ipsec_out_ill_index =
20445 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20446 		}
20447 		if (connp != NULL) {
20448 			io->ipsec_out_multicast_loop =
20449 			    connp->conn_multicast_loop;
20450 			io->ipsec_out_dontroute = connp->conn_dontroute;
20451 			io->ipsec_out_zoneid = connp->conn_zoneid;
20452 		}
20453 		/*
20454 		 * If the application uses IP_MULTICAST_IF with
20455 		 * different logical addresses of the same ILL, we
20456 		 * need to make sure that the soruce address of
20457 		 * the packet matches the logical IP address used
20458 		 * in the option. We do it by initializing ipha_src
20459 		 * here. This should keep IPSEC also happy as
20460 		 * when we return from IPSEC processing, we don't
20461 		 * have to worry about getting the right address on
20462 		 * the packet. Thus it is sufficient to look for
20463 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20464 		 * MATCH_IRE_IPIF.
20465 		 *
20466 		 * NOTE : We need to do it for non-secure case also as
20467 		 * this might go out secure if there is a global policy
20468 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20469 		 * address, the source should be initialized already and
20470 		 * hence we won't be initializing here.
20471 		 *
20472 		 * As we do not have the ire yet, it is possible that
20473 		 * we set the source address here and then later discover
20474 		 * that the ire implies the source address to be assigned
20475 		 * through the RTF_SETSRC flag.
20476 		 * In that case, the setsrc variable will remind us
20477 		 * that overwritting the source address by the one
20478 		 * of the RTF_SETSRC-flagged ire is allowed.
20479 		 */
20480 		if (ipha->ipha_src == INADDR_ANY &&
20481 		    (connp == NULL || !connp->conn_unspec_src)) {
20482 			ipha->ipha_src = ipif->ipif_src_addr;
20483 			setsrc = RTF_SETSRC;
20484 		}
20485 		/*
20486 		 * Find an IRE which matches the destination and the outgoing
20487 		 * queue (i.e. the outgoing interface.)
20488 		 * For loopback use a unicast IP address for
20489 		 * the ire lookup.
20490 		 */
20491 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20492 		    PHYI_LOOPBACK) {
20493 			dst = ipif->ipif_lcl_addr;
20494 		}
20495 		/*
20496 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20497 		 * We don't need to lookup ire in ctable as the packet
20498 		 * needs to be sent to the destination through the specified
20499 		 * ill irrespective of ires in the cache table.
20500 		 */
20501 		ire = NULL;
20502 		if (xmit_ill == NULL) {
20503 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20504 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20505 		}
20506 
20507 		/*
20508 		 * refrele attach_ill as its not needed anymore.
20509 		 */
20510 		if (attach_ill != NULL) {
20511 			ill_refrele(attach_ill);
20512 			attach_ill = NULL;
20513 		}
20514 
20515 		if (ire == NULL) {
20516 			/*
20517 			 * Multicast loopback and multicast forwarding is
20518 			 * done in ip_wput_ire.
20519 			 *
20520 			 * Mark this packet to make it be delivered to
20521 			 * ip_wput_ire after the new ire has been
20522 			 * created.
20523 			 *
20524 			 * The call to ip_newroute_ipif takes into account
20525 			 * the setsrc reminder. In any case, we take care
20526 			 * of the RTF_MULTIRT flag.
20527 			 */
20528 			mp->b_prev = mp->b_next = NULL;
20529 			if (xmit_ill == NULL ||
20530 			    xmit_ill->ill_ipif_up_count > 0) {
20531 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20532 				    setsrc | RTF_MULTIRT, zoneid);
20533 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20534 				    "ip_wput_end: q %p (%S)", q, "noire");
20535 			} else {
20536 				freemsg(first_mp);
20537 			}
20538 			ipif_refrele(ipif);
20539 			if (xmit_ill != NULL)
20540 				ill_refrele(xmit_ill);
20541 			if (need_decref)
20542 				CONN_DEC_REF(connp);
20543 			return;
20544 		}
20545 
20546 		ipif_refrele(ipif);
20547 		ipif = NULL;
20548 		ASSERT(xmit_ill == NULL);
20549 
20550 		/*
20551 		 * Honor the RTF_SETSRC flag for multicast packets,
20552 		 * if allowed by the setsrc reminder.
20553 		 */
20554 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20555 			ipha->ipha_src = ire->ire_src_addr;
20556 		}
20557 
20558 		/*
20559 		 * Unconditionally force the TTL to 1 for
20560 		 * multirouted multicast packets:
20561 		 * multirouted multicast should not cross
20562 		 * multicast routers.
20563 		 */
20564 		if (ire->ire_flags & RTF_MULTIRT) {
20565 			if (ipha->ipha_ttl > 1) {
20566 				ip2dbg(("ip_wput: forcing multicast "
20567 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20568 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20569 				ipha->ipha_ttl = 1;
20570 			}
20571 		}
20572 	} else {
20573 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20574 		if ((ire != NULL) && (ire->ire_type &
20575 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20576 			ignore_dontroute = B_TRUE;
20577 			ignore_nexthop = B_TRUE;
20578 		}
20579 		if (ire != NULL) {
20580 			ire_refrele(ire);
20581 			ire = NULL;
20582 		}
20583 		/*
20584 		 * Guard against coming in from arp in which case conn is NULL.
20585 		 * Also guard against non M_DATA with dontroute set but
20586 		 * destined to local, loopback or broadcast addresses.
20587 		 */
20588 		if (connp != NULL && connp->conn_dontroute &&
20589 		    !ignore_dontroute) {
20590 dontroute:
20591 			/*
20592 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20593 			 * routing protocols from seeing false direct
20594 			 * connectivity.
20595 			 */
20596 			ipha->ipha_ttl = 1;
20597 			/*
20598 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20599 			 * along with SO_DONTROUTE, higher precedence is
20600 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20601 			 */
20602 			if (connp->conn_xmit_if_ill == NULL) {
20603 				/* If suitable ipif not found, drop packet */
20604 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20605 				if (dst_ipif == NULL) {
20606 					ip1dbg(("ip_wput: no route for "
20607 					    "dst using SO_DONTROUTE\n"));
20608 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20609 					mp->b_prev = mp->b_next = NULL;
20610 					if (first_mp == NULL)
20611 						first_mp = mp;
20612 					goto drop_pkt;
20613 				} else {
20614 					/*
20615 					 * If suitable ipif has been found, set
20616 					 * xmit_ill to the corresponding
20617 					 * ipif_ill because we'll be following
20618 					 * the IP_XMIT_IF logic.
20619 					 */
20620 					ASSERT(xmit_ill == NULL);
20621 					xmit_ill = dst_ipif->ipif_ill;
20622 					mutex_enter(&xmit_ill->ill_lock);
20623 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20624 						mutex_exit(&xmit_ill->ill_lock);
20625 						xmit_ill = NULL;
20626 						ipif_refrele(dst_ipif);
20627 						ip1dbg(("ip_wput: no route for"
20628 						    " dst using"
20629 						    " SO_DONTROUTE\n"));
20630 						BUMP_MIB(&ip_mib,
20631 						    ipOutNoRoutes);
20632 						mp->b_prev = mp->b_next = NULL;
20633 						if (first_mp == NULL)
20634 							first_mp = mp;
20635 						goto drop_pkt;
20636 					}
20637 					ill_refhold_locked(xmit_ill);
20638 					mutex_exit(&xmit_ill->ill_lock);
20639 					ipif_refrele(dst_ipif);
20640 				}
20641 			}
20642 
20643 		}
20644 		/*
20645 		 * If we are bound to IPIF_NOFAILOVER address, look for
20646 		 * an IRE_CACHE matching the ill.
20647 		 */
20648 send_from_ill:
20649 		if (attach_ill != NULL) {
20650 			ipif_t	*attach_ipif;
20651 
20652 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20653 
20654 			/*
20655 			 * Check if we need an ire that will not be
20656 			 * looked up by anybody else i.e. HIDDEN.
20657 			 */
20658 			if (ill_is_probeonly(attach_ill)) {
20659 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20660 			}
20661 
20662 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20663 			if (attach_ipif == NULL) {
20664 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20665 				goto drop_pkt;
20666 			}
20667 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20668 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20669 			ipif_refrele(attach_ipif);
20670 		} else if (xmit_ill != NULL || (connp != NULL &&
20671 			    connp->conn_xmit_if_ill != NULL)) {
20672 			/*
20673 			 * Mark this packet as originated locally
20674 			 */
20675 			mp->b_prev = mp->b_next = NULL;
20676 			/*
20677 			 * xmit_ill could be NULL if SO_DONTROUTE
20678 			 * is also set.
20679 			 */
20680 			if (xmit_ill == NULL) {
20681 				xmit_ill = conn_get_held_ill(connp,
20682 				    &connp->conn_xmit_if_ill, &err);
20683 				if (err == ILL_LOOKUP_FAILED) {
20684 					if (need_decref)
20685 						CONN_DEC_REF(connp);
20686 					freemsg(first_mp);
20687 					return;
20688 				}
20689 				if (xmit_ill == NULL) {
20690 					if (connp->conn_dontroute)
20691 						goto dontroute;
20692 					goto send_from_ill;
20693 				}
20694 			}
20695 			/*
20696 			 * could be SO_DONTROUTE case also.
20697 			 * check at least one interface is UP as
20698 			 * spcified by this ILL, and then call
20699 			 * ip_newroute_ipif()
20700 			 */
20701 			if (xmit_ill->ill_ipif_up_count > 0) {
20702 				ipif_t *ipif;
20703 
20704 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20705 				if (ipif != NULL) {
20706 					ip_newroute_ipif(q, first_mp, ipif,
20707 					    dst, connp, 0, zoneid);
20708 					ipif_refrele(ipif);
20709 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20710 				}
20711 			} else {
20712 				freemsg(first_mp);
20713 			}
20714 			ill_refrele(xmit_ill);
20715 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20716 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20717 			if (need_decref)
20718 				CONN_DEC_REF(connp);
20719 			return;
20720 		} else if (ip_nexthop || (connp != NULL &&
20721 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20722 			if (!ip_nexthop) {
20723 				ip_nexthop = B_TRUE;
20724 				nexthop_addr = connp->conn_nexthop_v4;
20725 			}
20726 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20727 			    MATCH_IRE_GW;
20728 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20729 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20730 		} else {
20731 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20732 		}
20733 		if (!ire) {
20734 			/*
20735 			 * Make sure we don't load spread if this
20736 			 * is IPIF_NOFAILOVER case.
20737 			 */
20738 			if ((attach_ill != NULL) ||
20739 			    (ip_nexthop && !ignore_nexthop)) {
20740 				if (mctl_present) {
20741 					io = (ipsec_out_t *)first_mp->b_rptr;
20742 					ASSERT(first_mp->b_datap->db_type ==
20743 					    M_CTL);
20744 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20745 				} else {
20746 					ASSERT(mp == first_mp);
20747 					first_mp = allocb(
20748 					    sizeof (ipsec_info_t), BPRI_HI);
20749 					if (first_mp == NULL) {
20750 						first_mp = mp;
20751 						goto drop_pkt;
20752 					}
20753 					first_mp->b_datap->db_type = M_CTL;
20754 					first_mp->b_wptr +=
20755 					    sizeof (ipsec_info_t);
20756 					/* ipsec_out_secure is B_FALSE now */
20757 					bzero(first_mp->b_rptr,
20758 					    sizeof (ipsec_info_t));
20759 					io = (ipsec_out_t *)first_mp->b_rptr;
20760 					io->ipsec_out_type = IPSEC_OUT;
20761 					io->ipsec_out_len =
20762 					    sizeof (ipsec_out_t);
20763 					io->ipsec_out_use_global_policy =
20764 					    B_TRUE;
20765 					first_mp->b_cont = mp;
20766 					mctl_present = B_TRUE;
20767 				}
20768 				if (attach_ill != NULL) {
20769 					io->ipsec_out_ill_index = attach_ill->
20770 					    ill_phyint->phyint_ifindex;
20771 					io->ipsec_out_attach_if = B_TRUE;
20772 				} else {
20773 					io->ipsec_out_ip_nexthop = ip_nexthop;
20774 					io->ipsec_out_nexthop_addr =
20775 					    nexthop_addr;
20776 				}
20777 			}
20778 noirefound:
20779 			/*
20780 			 * Mark this packet as having originated on
20781 			 * this machine.  This will be noted in
20782 			 * ire_add_then_send, which needs to know
20783 			 * whether to run it back through ip_wput or
20784 			 * ip_rput following successful resolution.
20785 			 */
20786 			mp->b_prev = NULL;
20787 			mp->b_next = NULL;
20788 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20789 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20790 			    "ip_wput_end: q %p (%S)", q, "newroute");
20791 			if (attach_ill != NULL)
20792 				ill_refrele(attach_ill);
20793 			if (xmit_ill != NULL)
20794 				ill_refrele(xmit_ill);
20795 			if (need_decref)
20796 				CONN_DEC_REF(connp);
20797 			return;
20798 		}
20799 	}
20800 
20801 	/* We now know where we are going with it. */
20802 
20803 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20804 	    "ip_wput_end: q %p (%S)", q, "end");
20805 
20806 	/*
20807 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20808 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20809 	 */
20810 	if (ire->ire_flags & RTF_MULTIRT) {
20811 		/*
20812 		 * Force the TTL of multirouted packets if required.
20813 		 * The TTL of such packets is bounded by the
20814 		 * ip_multirt_ttl ndd variable.
20815 		 */
20816 		if ((ip_multirt_ttl > 0) &&
20817 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20818 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20819 			    "(was %d), dst 0x%08x\n",
20820 			    ip_multirt_ttl, ipha->ipha_ttl,
20821 			    ntohl(ire->ire_addr)));
20822 			ipha->ipha_ttl = ip_multirt_ttl;
20823 		}
20824 		/*
20825 		 * At this point, we check to see if there are any pending
20826 		 * unresolved routes. ire_multirt_resolvable()
20827 		 * checks in O(n) that all IRE_OFFSUBNET ire
20828 		 * entries for the packet's destination and
20829 		 * flagged RTF_MULTIRT are currently resolved.
20830 		 * If some remain unresolved, we make a copy
20831 		 * of the current message. It will be used
20832 		 * to initiate additional route resolutions.
20833 		 */
20834 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20835 		    MBLK_GETLABEL(first_mp));
20836 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20837 		    "multirt_need_resolve %d, first_mp %p\n",
20838 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20839 		if (multirt_need_resolve) {
20840 			copy_mp = copymsg(first_mp);
20841 			if (copy_mp != NULL) {
20842 				MULTIRT_DEBUG_TAG(copy_mp);
20843 			}
20844 		}
20845 	}
20846 
20847 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20848 	/*
20849 	 * Try to resolve another multiroute if
20850 	 * ire_multirt_resolvable() deemed it necessary.
20851 	 * At this point, we need to distinguish
20852 	 * multicasts from other packets. For multicasts,
20853 	 * we call ip_newroute_ipif() and request that both
20854 	 * multirouting and setsrc flags are checked.
20855 	 */
20856 	if (copy_mp != NULL) {
20857 		if (CLASSD(dst)) {
20858 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20859 			if (ipif) {
20860 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20861 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20862 				ipif_refrele(ipif);
20863 			} else {
20864 				MULTIRT_DEBUG_UNTAG(copy_mp);
20865 				freemsg(copy_mp);
20866 				copy_mp = NULL;
20867 			}
20868 		} else {
20869 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20870 		}
20871 	}
20872 	if (attach_ill != NULL)
20873 		ill_refrele(attach_ill);
20874 	if (xmit_ill != NULL)
20875 		ill_refrele(xmit_ill);
20876 	if (need_decref)
20877 		CONN_DEC_REF(connp);
20878 	return;
20879 
20880 icmp_parameter_problem:
20881 	/* could not have originated externally */
20882 	ASSERT(mp->b_prev == NULL);
20883 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20884 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20885 		/* it's the IP header length that's in trouble */
20886 		icmp_param_problem(q, first_mp, 0, zoneid);
20887 		first_mp = NULL;
20888 	}
20889 
20890 drop_pkt:
20891 	ip1dbg(("ip_wput: dropped packet\n"));
20892 	if (ire != NULL)
20893 		ire_refrele(ire);
20894 	if (need_decref)
20895 		CONN_DEC_REF(connp);
20896 	freemsg(first_mp);
20897 	if (attach_ill != NULL)
20898 		ill_refrele(attach_ill);
20899 	if (xmit_ill != NULL)
20900 		ill_refrele(xmit_ill);
20901 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20902 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20903 }
20904 
20905 /*
20906  * If this is a conn_t queue, then we pass in the conn. This includes the
20907  * zoneid.
20908  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20909  * in which case we use the global zoneid since those are all part of
20910  * the global zone.
20911  */
20912 void
20913 ip_wput(queue_t *q, mblk_t *mp)
20914 {
20915 	if (CONN_Q(q))
20916 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20917 	else
20918 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20919 }
20920 
20921 /*
20922  *
20923  * The following rules must be observed when accessing any ipif or ill
20924  * that has been cached in the conn. Typically conn_nofailover_ill,
20925  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20926  *
20927  * Access: The ipif or ill pointed to from the conn can be accessed under
20928  * the protection of the conn_lock or after it has been refheld under the
20929  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20930  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20931  * The reason for this is that a concurrent unplumb could actually be
20932  * cleaning up these cached pointers by walking the conns and might have
20933  * finished cleaning up the conn in question. The macros check that an
20934  * unplumb has not yet started on the ipif or ill.
20935  *
20936  * Caching: An ipif or ill pointer may be cached in the conn only after
20937  * making sure that an unplumb has not started. So the caching is done
20938  * while holding both the conn_lock and the ill_lock and after using the
20939  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20940  * flag before starting the cleanup of conns.
20941  *
20942  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20943  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20944  * or a reference to the ipif or a reference to an ire that references the
20945  * ipif. An ipif does not change its ill except for failover/failback. Since
20946  * failover/failback happens only after bringing down the ipif and making sure
20947  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20948  * the above holds.
20949  */
20950 ipif_t *
20951 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20952 {
20953 	ipif_t	*ipif;
20954 	ill_t	*ill;
20955 
20956 	*err = 0;
20957 	rw_enter(&ill_g_lock, RW_READER);
20958 	mutex_enter(&connp->conn_lock);
20959 	ipif = *ipifp;
20960 	if (ipif != NULL) {
20961 		ill = ipif->ipif_ill;
20962 		mutex_enter(&ill->ill_lock);
20963 		if (IPIF_CAN_LOOKUP(ipif)) {
20964 			ipif_refhold_locked(ipif);
20965 			mutex_exit(&ill->ill_lock);
20966 			mutex_exit(&connp->conn_lock);
20967 			rw_exit(&ill_g_lock);
20968 			return (ipif);
20969 		} else {
20970 			*err = IPIF_LOOKUP_FAILED;
20971 		}
20972 		mutex_exit(&ill->ill_lock);
20973 	}
20974 	mutex_exit(&connp->conn_lock);
20975 	rw_exit(&ill_g_lock);
20976 	return (NULL);
20977 }
20978 
20979 ill_t *
20980 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20981 {
20982 	ill_t	*ill;
20983 
20984 	*err = 0;
20985 	mutex_enter(&connp->conn_lock);
20986 	ill = *illp;
20987 	if (ill != NULL) {
20988 		mutex_enter(&ill->ill_lock);
20989 		if (ILL_CAN_LOOKUP(ill)) {
20990 			ill_refhold_locked(ill);
20991 			mutex_exit(&ill->ill_lock);
20992 			mutex_exit(&connp->conn_lock);
20993 			return (ill);
20994 		} else {
20995 			*err = ILL_LOOKUP_FAILED;
20996 		}
20997 		mutex_exit(&ill->ill_lock);
20998 	}
20999 	mutex_exit(&connp->conn_lock);
21000 	return (NULL);
21001 }
21002 
21003 static int
21004 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21005 {
21006 	ill_t	*ill;
21007 
21008 	ill = ipif->ipif_ill;
21009 	mutex_enter(&connp->conn_lock);
21010 	mutex_enter(&ill->ill_lock);
21011 	if (IPIF_CAN_LOOKUP(ipif)) {
21012 		*ipifp = ipif;
21013 		mutex_exit(&ill->ill_lock);
21014 		mutex_exit(&connp->conn_lock);
21015 		return (0);
21016 	}
21017 	mutex_exit(&ill->ill_lock);
21018 	mutex_exit(&connp->conn_lock);
21019 	return (IPIF_LOOKUP_FAILED);
21020 }
21021 
21022 /*
21023  * This is called if the outbound datagram needs fragmentation.
21024  *
21025  * NOTE : This function does not ire_refrele the ire argument passed in.
21026  */
21027 static void
21028 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21029 {
21030 	ipha_t		*ipha;
21031 	mblk_t		*mp;
21032 	uint32_t	v_hlen_tos_len;
21033 	uint32_t	max_frag;
21034 	uint32_t	frag_flag;
21035 	boolean_t	dont_use;
21036 
21037 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21038 		mp = ipsec_mp->b_cont;
21039 	} else {
21040 		mp = ipsec_mp;
21041 	}
21042 
21043 	ipha = (ipha_t *)mp->b_rptr;
21044 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21045 
21046 #ifdef	_BIG_ENDIAN
21047 #define	V_HLEN	(v_hlen_tos_len >> 24)
21048 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21049 #else
21050 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21051 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21052 #endif
21053 
21054 #ifndef SPEED_BEFORE_SAFETY
21055 	/*
21056 	 * Check that ipha_length is consistent with
21057 	 * the mblk length
21058 	 */
21059 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21060 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21061 		    LENGTH, msgdsize(mp)));
21062 		freemsg(ipsec_mp);
21063 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21064 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21065 		    "packet length mismatch");
21066 		return;
21067 	}
21068 #endif
21069 	/*
21070 	 * Don't use frag_flag if pre-built packet or source
21071 	 * routed or if multicast (since multicast packets do not solicit
21072 	 * ICMP "packet too big" messages). Get the values of
21073 	 * max_frag and frag_flag atomically by acquiring the
21074 	 * ire_lock.
21075 	 */
21076 	mutex_enter(&ire->ire_lock);
21077 	max_frag = ire->ire_max_frag;
21078 	frag_flag = ire->ire_frag_flag;
21079 	mutex_exit(&ire->ire_lock);
21080 
21081 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21082 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21083 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21084 
21085 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21086 	    (dont_use ? 0 : frag_flag), zoneid);
21087 }
21088 
21089 /*
21090  * Used for deciding the MSS size for the upper layer. Thus
21091  * we need to check the outbound policy values in the conn.
21092  */
21093 int
21094 conn_ipsec_length(conn_t *connp)
21095 {
21096 	ipsec_latch_t *ipl;
21097 
21098 	ipl = connp->conn_latch;
21099 	if (ipl == NULL)
21100 		return (0);
21101 
21102 	if (ipl->ipl_out_policy == NULL)
21103 		return (0);
21104 
21105 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21106 }
21107 
21108 /*
21109  * Returns an estimate of the IPSEC headers size. This is used if
21110  * we don't want to call into IPSEC to get the exact size.
21111  */
21112 int
21113 ipsec_out_extra_length(mblk_t *ipsec_mp)
21114 {
21115 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21116 	ipsec_action_t *a;
21117 
21118 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21119 	if (!io->ipsec_out_secure)
21120 		return (0);
21121 
21122 	a = io->ipsec_out_act;
21123 
21124 	if (a == NULL) {
21125 		ASSERT(io->ipsec_out_policy != NULL);
21126 		a = io->ipsec_out_policy->ipsp_act;
21127 	}
21128 	ASSERT(a != NULL);
21129 
21130 	return (a->ipa_ovhd);
21131 }
21132 
21133 /*
21134  * Returns an estimate of the IPSEC headers size. This is used if
21135  * we don't want to call into IPSEC to get the exact size.
21136  */
21137 int
21138 ipsec_in_extra_length(mblk_t *ipsec_mp)
21139 {
21140 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21141 	ipsec_action_t *a;
21142 
21143 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21144 
21145 	a = ii->ipsec_in_action;
21146 	return (a == NULL ? 0 : a->ipa_ovhd);
21147 }
21148 
21149 /*
21150  * If there are any source route options, return the true final
21151  * destination. Otherwise, return the destination.
21152  */
21153 ipaddr_t
21154 ip_get_dst(ipha_t *ipha)
21155 {
21156 	ipoptp_t	opts;
21157 	uchar_t		*opt;
21158 	uint8_t		optval;
21159 	uint8_t		optlen;
21160 	ipaddr_t	dst;
21161 	uint32_t off;
21162 
21163 	dst = ipha->ipha_dst;
21164 
21165 	if (IS_SIMPLE_IPH(ipha))
21166 		return (dst);
21167 
21168 	for (optval = ipoptp_first(&opts, ipha);
21169 	    optval != IPOPT_EOL;
21170 	    optval = ipoptp_next(&opts)) {
21171 		opt = opts.ipoptp_cur;
21172 		optlen = opts.ipoptp_len;
21173 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21174 		switch (optval) {
21175 		case IPOPT_SSRR:
21176 		case IPOPT_LSRR:
21177 			off = opt[IPOPT_OFFSET];
21178 			/*
21179 			 * If one of the conditions is true, it means
21180 			 * end of options and dst already has the right
21181 			 * value.
21182 			 */
21183 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21184 				off = optlen - IP_ADDR_LEN;
21185 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21186 			}
21187 			return (dst);
21188 		default:
21189 			break;
21190 		}
21191 	}
21192 
21193 	return (dst);
21194 }
21195 
21196 mblk_t *
21197 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21198     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21199 {
21200 	ipsec_out_t	*io;
21201 	mblk_t		*first_mp;
21202 	boolean_t policy_present;
21203 
21204 	first_mp = mp;
21205 	if (mp->b_datap->db_type == M_CTL) {
21206 		io = (ipsec_out_t *)first_mp->b_rptr;
21207 		/*
21208 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21209 		 *
21210 		 * 1) There is per-socket policy (including cached global
21211 		 *    policy) or a policy on the IP-in-IP tunnel.
21212 		 * 2) There is no per-socket policy, but it is
21213 		 *    a multicast packet that needs to go out
21214 		 *    on a specific interface. This is the case
21215 		 *    where (ip_wput and ip_wput_multicast) attaches
21216 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21217 		 *
21218 		 * In case (2) we check with global policy to
21219 		 * see if there is a match and set the ill_index
21220 		 * appropriately so that we can lookup the ire
21221 		 * properly in ip_wput_ipsec_out.
21222 		 */
21223 
21224 		/*
21225 		 * ipsec_out_use_global_policy is set to B_FALSE
21226 		 * in ipsec_in_to_out(). Refer to that function for
21227 		 * details.
21228 		 */
21229 		if ((io->ipsec_out_latch == NULL) &&
21230 		    (io->ipsec_out_use_global_policy)) {
21231 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21232 				    ire, connp, unspec_src, zoneid));
21233 		}
21234 		if (!io->ipsec_out_secure) {
21235 			/*
21236 			 * If this is not a secure packet, drop
21237 			 * the IPSEC_OUT mp and treat it as a clear
21238 			 * packet. This happens when we are sending
21239 			 * a ICMP reply back to a clear packet. See
21240 			 * ipsec_in_to_out() for details.
21241 			 */
21242 			mp = first_mp->b_cont;
21243 			freeb(first_mp);
21244 		}
21245 		return (mp);
21246 	}
21247 	/*
21248 	 * See whether we need to attach a global policy here. We
21249 	 * don't depend on the conn (as it could be null) for deciding
21250 	 * what policy this datagram should go through because it
21251 	 * should have happened in ip_wput if there was some
21252 	 * policy. This normally happens for connections which are not
21253 	 * fully bound preventing us from caching policies in
21254 	 * ip_bind. Packets coming from the TCP listener/global queue
21255 	 * - which are non-hard_bound - could also be affected by
21256 	 * applying policy here.
21257 	 *
21258 	 * If this packet is coming from tcp global queue or listener,
21259 	 * we will be applying policy here.  This may not be *right*
21260 	 * if these packets are coming from the detached connection as
21261 	 * it could have gone in clear before. This happens only if a
21262 	 * TCP connection started when there is no policy and somebody
21263 	 * added policy before it became detached. Thus packets of the
21264 	 * detached connection could go out secure and the other end
21265 	 * would drop it because it will be expecting in clear. The
21266 	 * converse is not true i.e if somebody starts a TCP
21267 	 * connection and deletes the policy, all the packets will
21268 	 * still go out with the policy that existed before deleting
21269 	 * because ip_unbind sends up policy information which is used
21270 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21271 	 * TCP to attach a dummy IPSEC_OUT and set
21272 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21273 	 * affect performance for normal cases, we are not doing it.
21274 	 * Thus, set policy before starting any TCP connections.
21275 	 *
21276 	 * NOTE - We might apply policy even for a hard bound connection
21277 	 * - for which we cached policy in ip_bind - if somebody added
21278 	 * global policy after we inherited the policy in ip_bind.
21279 	 * This means that the packets that were going out in clear
21280 	 * previously would start going secure and hence get dropped
21281 	 * on the other side. To fix this, TCP attaches a dummy
21282 	 * ipsec_out and make sure that we don't apply global policy.
21283 	 */
21284 	if (ipha != NULL)
21285 		policy_present = ipsec_outbound_v4_policy_present;
21286 	else
21287 		policy_present = ipsec_outbound_v6_policy_present;
21288 	if (!policy_present)
21289 		return (mp);
21290 
21291 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21292 		    zoneid));
21293 }
21294 
21295 ire_t *
21296 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21297 {
21298 	ipaddr_t addr;
21299 	ire_t *save_ire;
21300 	irb_t *irb;
21301 	ill_group_t *illgrp;
21302 	int	err;
21303 
21304 	save_ire = ire;
21305 	addr = ire->ire_addr;
21306 
21307 	ASSERT(ire->ire_type == IRE_BROADCAST);
21308 
21309 	illgrp = connp->conn_outgoing_ill->ill_group;
21310 	if (illgrp == NULL) {
21311 		*conn_outgoing_ill = conn_get_held_ill(connp,
21312 		    &connp->conn_outgoing_ill, &err);
21313 		if (err == ILL_LOOKUP_FAILED) {
21314 			ire_refrele(save_ire);
21315 			return (NULL);
21316 		}
21317 		return (save_ire);
21318 	}
21319 	/*
21320 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21321 	 * If it is part of the group, we need to send on the ire
21322 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21323 	 * to this group. This is okay as IP_BOUND_IF really means
21324 	 * any ill in the group. We depend on the fact that the
21325 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21326 	 * if such an ire exists. This is possible only if you have
21327 	 * at least one ill in the group that has not failed.
21328 	 *
21329 	 * First get to the ire that matches the address and group.
21330 	 *
21331 	 * We don't look for an ire with a matching zoneid because a given zone
21332 	 * won't always have broadcast ires on all ills in the group.
21333 	 */
21334 	irb = ire->ire_bucket;
21335 	rw_enter(&irb->irb_lock, RW_READER);
21336 	if (ire->ire_marks & IRE_MARK_NORECV) {
21337 		/*
21338 		 * If the current zone only has an ire broadcast for this
21339 		 * address marked NORECV, the ire we want is ahead in the
21340 		 * bucket, so we look it up deliberately ignoring the zoneid.
21341 		 */
21342 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21343 			if (ire->ire_addr != addr)
21344 				continue;
21345 			/* skip over deleted ires */
21346 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21347 				continue;
21348 		}
21349 	}
21350 	while (ire != NULL) {
21351 		/*
21352 		 * If a new interface is coming up, we could end up
21353 		 * seeing the loopback ire and the non-loopback ire
21354 		 * may not have been added yet. So check for ire_stq
21355 		 */
21356 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21357 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21358 			break;
21359 		}
21360 		ire = ire->ire_next;
21361 	}
21362 	if (ire != NULL && ire->ire_addr == addr &&
21363 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21364 		IRE_REFHOLD(ire);
21365 		rw_exit(&irb->irb_lock);
21366 		ire_refrele(save_ire);
21367 		*conn_outgoing_ill = ire_to_ill(ire);
21368 		/*
21369 		 * Refhold the ill to make the conn_outgoing_ill
21370 		 * independent of the ire. ip_wput_ire goes in a loop
21371 		 * and may refrele the ire. Since we have an ire at this
21372 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21373 		 */
21374 		ill_refhold(*conn_outgoing_ill);
21375 		return (ire);
21376 	}
21377 	rw_exit(&irb->irb_lock);
21378 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21379 	/*
21380 	 * If we can't find a suitable ire, return the original ire.
21381 	 */
21382 	return (save_ire);
21383 }
21384 
21385 /*
21386  * This function does the ire_refrele of the ire passed in as the
21387  * argument. As this function looks up more ires i.e broadcast ires,
21388  * it needs to REFRELE them. Currently, for simplicity we don't
21389  * differentiate the one passed in and looked up here. We always
21390  * REFRELE.
21391  * IPQoS Notes:
21392  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21393  * IPSec packets are done in ipsec_out_process.
21394  *
21395  */
21396 void
21397 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21398     zoneid_t zoneid)
21399 {
21400 	ipha_t		*ipha;
21401 #define	rptr	((uchar_t *)ipha)
21402 	queue_t		*stq;
21403 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21404 	uint32_t	v_hlen_tos_len;
21405 	uint32_t	ttl_protocol;
21406 	ipaddr_t	src;
21407 	ipaddr_t	dst;
21408 	uint32_t	cksum;
21409 	ipaddr_t	orig_src;
21410 	ire_t		*ire1;
21411 	mblk_t		*next_mp;
21412 	uint_t		hlen;
21413 	uint16_t	*up;
21414 	uint32_t	max_frag = ire->ire_max_frag;
21415 	ill_t		*ill = ire_to_ill(ire);
21416 	int		clusterwide;
21417 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21418 	int		ipsec_len;
21419 	mblk_t		*first_mp;
21420 	ipsec_out_t	*io;
21421 	boolean_t	conn_dontroute;		/* conn value for multicast */
21422 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21423 	boolean_t	multicast_forward;	/* Should we forward ? */
21424 	boolean_t	unspec_src;
21425 	ill_t		*conn_outgoing_ill = NULL;
21426 	ill_t		*ire_ill;
21427 	ill_t		*ire1_ill;
21428 	ill_t		*out_ill;
21429 	uint32_t 	ill_index = 0;
21430 	boolean_t	multirt_send = B_FALSE;
21431 	int		err;
21432 	ipxmit_state_t	pktxmit_state;
21433 
21434 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21435 	    "ip_wput_ire_start: q %p", q);
21436 
21437 	multicast_forward = B_FALSE;
21438 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21439 
21440 	if (ire->ire_flags & RTF_MULTIRT) {
21441 		/*
21442 		 * Multirouting case. The bucket where ire is stored
21443 		 * probably holds other RTF_MULTIRT flagged ire
21444 		 * to the destination. In this call to ip_wput_ire,
21445 		 * we attempt to send the packet through all
21446 		 * those ires. Thus, we first ensure that ire is the
21447 		 * first RTF_MULTIRT ire in the bucket,
21448 		 * before walking the ire list.
21449 		 */
21450 		ire_t *first_ire;
21451 		irb_t *irb = ire->ire_bucket;
21452 		ASSERT(irb != NULL);
21453 
21454 		/* Make sure we do not omit any multiroute ire. */
21455 		IRB_REFHOLD(irb);
21456 		for (first_ire = irb->irb_ire;
21457 		    first_ire != NULL;
21458 		    first_ire = first_ire->ire_next) {
21459 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21460 			    (first_ire->ire_addr == ire->ire_addr) &&
21461 			    !(first_ire->ire_marks &
21462 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21463 				break;
21464 		}
21465 
21466 		if ((first_ire != NULL) && (first_ire != ire)) {
21467 			IRE_REFHOLD(first_ire);
21468 			ire_refrele(ire);
21469 			ire = first_ire;
21470 			ill = ire_to_ill(ire);
21471 		}
21472 		IRB_REFRELE(irb);
21473 	}
21474 
21475 	/*
21476 	 * conn_outgoing_ill is used only in the broadcast loop.
21477 	 * for performance we don't grab the mutexs in the fastpath
21478 	 */
21479 	if ((connp != NULL) &&
21480 	    (connp->conn_xmit_if_ill == NULL) &&
21481 	    (ire->ire_type == IRE_BROADCAST) &&
21482 	    ((connp->conn_nofailover_ill != NULL) ||
21483 	    (connp->conn_outgoing_ill != NULL))) {
21484 		/*
21485 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21486 		 * option. So, see if this endpoint is bound to a
21487 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21488 		 * that if the interface is failed, we will still send
21489 		 * the packet on the same ill which is what we want.
21490 		 */
21491 		conn_outgoing_ill = conn_get_held_ill(connp,
21492 		    &connp->conn_nofailover_ill, &err);
21493 		if (err == ILL_LOOKUP_FAILED) {
21494 			ire_refrele(ire);
21495 			freemsg(mp);
21496 			return;
21497 		}
21498 		if (conn_outgoing_ill == NULL) {
21499 			/*
21500 			 * Choose a good ill in the group to send the
21501 			 * packets on.
21502 			 */
21503 			ire = conn_set_outgoing_ill(connp, ire,
21504 			    &conn_outgoing_ill);
21505 			if (ire == NULL) {
21506 				freemsg(mp);
21507 				return;
21508 			}
21509 		}
21510 	}
21511 
21512 	if (mp->b_datap->db_type != M_CTL) {
21513 		ipha = (ipha_t *)mp->b_rptr;
21514 	} else {
21515 		io = (ipsec_out_t *)mp->b_rptr;
21516 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21517 		ASSERT(zoneid == io->ipsec_out_zoneid);
21518 		ASSERT(zoneid != ALL_ZONES);
21519 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21520 		dst = ipha->ipha_dst;
21521 		/*
21522 		 * For the multicast case, ipsec_out carries conn_dontroute and
21523 		 * conn_multicast_loop as conn may not be available here. We
21524 		 * need this for multicast loopback and forwarding which is done
21525 		 * later in the code.
21526 		 */
21527 		if (CLASSD(dst)) {
21528 			conn_dontroute = io->ipsec_out_dontroute;
21529 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21530 			/*
21531 			 * If conn_dontroute is not set or conn_multicast_loop
21532 			 * is set, we need to do forwarding/loopback. For
21533 			 * datagrams from ip_wput_multicast, conn_dontroute is
21534 			 * set to B_TRUE and conn_multicast_loop is set to
21535 			 * B_FALSE so that we neither do forwarding nor
21536 			 * loopback.
21537 			 */
21538 			if (!conn_dontroute || conn_multicast_loop)
21539 				multicast_forward = B_TRUE;
21540 		}
21541 	}
21542 
21543 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21544 	    ire->ire_zoneid != ALL_ZONES) {
21545 		/*
21546 		 * When a zone sends a packet to another zone, we try to deliver
21547 		 * the packet under the same conditions as if the destination
21548 		 * was a real node on the network. To do so, we look for a
21549 		 * matching route in the forwarding table.
21550 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21551 		 * ip_newroute() does.
21552 		 * Note that IRE_LOCAL are special, since they are used
21553 		 * when the zoneid doesn't match in some cases. This means that
21554 		 * we need to handle ipha_src differently since ire_src_addr
21555 		 * belongs to the receiving zone instead of the sending zone.
21556 		 * When ip_restrict_interzone_loopback is set, then
21557 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21558 		 * for loopback between zones when the logical "Ethernet" would
21559 		 * have looped them back.
21560 		 */
21561 		ire_t *src_ire;
21562 
21563 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21564 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21565 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21566 		if (src_ire != NULL &&
21567 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21568 		    (!ip_restrict_interzone_loopback ||
21569 		    ire_local_same_ill_group(ire, src_ire))) {
21570 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21571 				ipha->ipha_src = src_ire->ire_src_addr;
21572 			ire_refrele(src_ire);
21573 		} else {
21574 			ire_refrele(ire);
21575 			if (conn_outgoing_ill != NULL)
21576 				ill_refrele(conn_outgoing_ill);
21577 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21578 			if (src_ire != NULL) {
21579 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21580 					ire_refrele(src_ire);
21581 					freemsg(mp);
21582 					return;
21583 				}
21584 				ire_refrele(src_ire);
21585 			}
21586 			if (ip_hdr_complete(ipha, zoneid)) {
21587 				/* Failed */
21588 				freemsg(mp);
21589 				return;
21590 			}
21591 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21592 			return;
21593 		}
21594 	}
21595 
21596 	if (mp->b_datap->db_type == M_CTL ||
21597 	    ipsec_outbound_v4_policy_present) {
21598 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21599 		    unspec_src, zoneid);
21600 		if (mp == NULL) {
21601 			ire_refrele(ire);
21602 			if (conn_outgoing_ill != NULL)
21603 				ill_refrele(conn_outgoing_ill);
21604 			return;
21605 		}
21606 	}
21607 
21608 	first_mp = mp;
21609 	ipsec_len = 0;
21610 
21611 	if (first_mp->b_datap->db_type == M_CTL) {
21612 		io = (ipsec_out_t *)first_mp->b_rptr;
21613 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21614 		mp = first_mp->b_cont;
21615 		ipsec_len = ipsec_out_extra_length(first_mp);
21616 		ASSERT(ipsec_len >= 0);
21617 		/* We already picked up the zoneid from the M_CTL above */
21618 		ASSERT(zoneid == io->ipsec_out_zoneid);
21619 		ASSERT(zoneid != ALL_ZONES);
21620 
21621 		/*
21622 		 * Drop M_CTL here if IPsec processing is not needed.
21623 		 * (Non-IPsec use of M_CTL extracted any information it
21624 		 * needed above).
21625 		 */
21626 		if (ipsec_len == 0) {
21627 			freeb(first_mp);
21628 			first_mp = mp;
21629 		}
21630 	}
21631 
21632 	/*
21633 	 * Fast path for ip_wput_ire
21634 	 */
21635 
21636 	ipha = (ipha_t *)mp->b_rptr;
21637 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21638 	dst = ipha->ipha_dst;
21639 
21640 	/*
21641 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21642 	 * if the socket is a SOCK_RAW type. The transport checksum should
21643 	 * be provided in the pre-built packet, so we don't need to compute it.
21644 	 * Also, other application set flags, like DF, should not be altered.
21645 	 * Other transport MUST pass down zero.
21646 	 */
21647 	ip_hdr_included = ipha->ipha_ident;
21648 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21649 
21650 	if (CLASSD(dst)) {
21651 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21652 		    ntohl(dst),
21653 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21654 		    ntohl(ire->ire_addr)));
21655 	}
21656 
21657 /* Macros to extract header fields from data already in registers */
21658 #ifdef	_BIG_ENDIAN
21659 #define	V_HLEN	(v_hlen_tos_len >> 24)
21660 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21661 #define	PROTO	(ttl_protocol & 0xFF)
21662 #else
21663 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21664 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21665 #define	PROTO	(ttl_protocol >> 8)
21666 #endif
21667 
21668 
21669 	orig_src = src = ipha->ipha_src;
21670 	/* (The loop back to "another" is explained down below.) */
21671 another:;
21672 	/*
21673 	 * Assign an ident value for this packet.  We assign idents on
21674 	 * a per destination basis out of the IRE.  There could be
21675 	 * other threads targeting the same destination, so we have to
21676 	 * arrange for a atomic increment.  Note that we use a 32-bit
21677 	 * atomic add because it has better performance than its
21678 	 * 16-bit sibling.
21679 	 *
21680 	 * If running in cluster mode and if the source address
21681 	 * belongs to a replicated service then vector through
21682 	 * cl_inet_ipident vector to allocate ip identifier
21683 	 * NOTE: This is a contract private interface with the
21684 	 * clustering group.
21685 	 */
21686 	clusterwide = 0;
21687 	if (cl_inet_ipident) {
21688 		ASSERT(cl_inet_isclusterwide);
21689 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21690 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21691 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21692 			    AF_INET, (uint8_t *)(uintptr_t)src,
21693 			    (uint8_t *)(uintptr_t)dst);
21694 			clusterwide = 1;
21695 		}
21696 	}
21697 	if (!clusterwide) {
21698 		ipha->ipha_ident =
21699 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21700 	}
21701 
21702 #ifndef _BIG_ENDIAN
21703 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21704 #endif
21705 
21706 	/*
21707 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21708 	 * This is needed to obey conn_unspec_src when packets go through
21709 	 * ip_newroute + arp.
21710 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21711 	 */
21712 	if (src == INADDR_ANY && !unspec_src) {
21713 		/*
21714 		 * Assign the appropriate source address from the IRE if none
21715 		 * was specified.
21716 		 */
21717 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21718 
21719 		/*
21720 		 * With IP multipathing, broadcast packets are sent on the ire
21721 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21722 		 * the group. However, this ire might not be in the same zone so
21723 		 * we can't always use its source address. We look for a
21724 		 * broadcast ire in the same group and in the right zone.
21725 		 */
21726 		if (ire->ire_type == IRE_BROADCAST &&
21727 		    ire->ire_zoneid != zoneid) {
21728 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21729 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21730 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21731 			if (src_ire != NULL) {
21732 				src = src_ire->ire_src_addr;
21733 				ire_refrele(src_ire);
21734 			} else {
21735 				ire_refrele(ire);
21736 				if (conn_outgoing_ill != NULL)
21737 					ill_refrele(conn_outgoing_ill);
21738 				freemsg(first_mp);
21739 				BUMP_MIB(&ip_mib, ipOutDiscards);
21740 				return;
21741 			}
21742 		} else {
21743 			src = ire->ire_src_addr;
21744 		}
21745 
21746 		if (connp == NULL) {
21747 			ip1dbg(("ip_wput_ire: no connp and no src "
21748 			    "address for dst 0x%x, using src 0x%x\n",
21749 			    ntohl(dst),
21750 			    ntohl(src)));
21751 		}
21752 		ipha->ipha_src = src;
21753 	}
21754 	stq = ire->ire_stq;
21755 
21756 	/*
21757 	 * We only allow ire chains for broadcasts since there will
21758 	 * be multiple IRE_CACHE entries for the same multicast
21759 	 * address (one per ipif).
21760 	 */
21761 	next_mp = NULL;
21762 
21763 	/* broadcast packet */
21764 	if (ire->ire_type == IRE_BROADCAST)
21765 		goto broadcast;
21766 
21767 	/* loopback ? */
21768 	if (stq == NULL)
21769 		goto nullstq;
21770 
21771 	/* The ill_index for outbound ILL */
21772 	ill_index = Q_TO_INDEX(stq);
21773 
21774 	BUMP_MIB(&ip_mib, ipOutRequests);
21775 	ttl_protocol = ((uint16_t *)ipha)[4];
21776 
21777 	/* pseudo checksum (do it in parts for IP header checksum) */
21778 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21779 
21780 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21781 		queue_t *dev_q = stq->q_next;
21782 
21783 		/* flow controlled */
21784 		if ((dev_q->q_next || dev_q->q_first) &&
21785 		    !canput(dev_q))
21786 			goto blocked;
21787 		if ((PROTO == IPPROTO_UDP) &&
21788 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21789 			hlen = (V_HLEN & 0xF) << 2;
21790 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21791 			if (*up != 0) {
21792 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21793 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21794 				/* Software checksum? */
21795 				if (DB_CKSUMFLAGS(mp) == 0) {
21796 					IP_STAT(ip_out_sw_cksum);
21797 					IP_STAT_UPDATE(
21798 					    ip_udp_out_sw_cksum_bytes,
21799 					    LENGTH - hlen);
21800 				}
21801 			}
21802 		}
21803 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21804 		hlen = (V_HLEN & 0xF) << 2;
21805 		if (PROTO == IPPROTO_TCP) {
21806 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21807 			/*
21808 			 * The packet header is processed once and for all, even
21809 			 * in the multirouting case. We disable hardware
21810 			 * checksum if the packet is multirouted, as it will be
21811 			 * replicated via several interfaces, and not all of
21812 			 * them may have this capability.
21813 			 */
21814 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21815 			    LENGTH, max_frag, ipsec_len, cksum);
21816 			/* Software checksum? */
21817 			if (DB_CKSUMFLAGS(mp) == 0) {
21818 				IP_STAT(ip_out_sw_cksum);
21819 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21820 				    LENGTH - hlen);
21821 			}
21822 		} else {
21823 			sctp_hdr_t	*sctph;
21824 
21825 			ASSERT(PROTO == IPPROTO_SCTP);
21826 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21827 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21828 			/*
21829 			 * Zero out the checksum field to ensure proper
21830 			 * checksum calculation.
21831 			 */
21832 			sctph->sh_chksum = 0;
21833 #ifdef	DEBUG
21834 			if (!skip_sctp_cksum)
21835 #endif
21836 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21837 		}
21838 	}
21839 
21840 	/*
21841 	 * If this is a multicast packet and originated from ip_wput
21842 	 * we need to do loopback and forwarding checks. If it comes
21843 	 * from ip_wput_multicast, we SHOULD not do this.
21844 	 */
21845 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21846 
21847 	/* checksum */
21848 	cksum += ttl_protocol;
21849 
21850 	/* fragment the packet */
21851 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21852 		goto fragmentit;
21853 	/*
21854 	 * Don't use frag_flag if packet is pre-built or source
21855 	 * routed or if multicast (since multicast packets do
21856 	 * not solicit ICMP "packet too big" messages).
21857 	 */
21858 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21859 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21860 	    !ip_source_route_included(ipha)) &&
21861 	    !CLASSD(ipha->ipha_dst))
21862 		ipha->ipha_fragment_offset_and_flags |=
21863 		    htons(ire->ire_frag_flag);
21864 
21865 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21866 		/* calculate IP header checksum */
21867 		cksum += ipha->ipha_ident;
21868 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21869 		cksum += ipha->ipha_fragment_offset_and_flags;
21870 
21871 		/* IP options present */
21872 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21873 		if (hlen)
21874 			goto checksumoptions;
21875 
21876 		/* calculate hdr checksum */
21877 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21878 		cksum = ~(cksum + (cksum >> 16));
21879 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21880 	}
21881 	if (ipsec_len != 0) {
21882 		/*
21883 		 * We will do the rest of the processing after
21884 		 * we come back from IPSEC in ip_wput_ipsec_out().
21885 		 */
21886 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21887 
21888 		io = (ipsec_out_t *)first_mp->b_rptr;
21889 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21890 				ill_phyint->phyint_ifindex;
21891 
21892 		ipsec_out_process(q, first_mp, ire, ill_index);
21893 		ire_refrele(ire);
21894 		if (conn_outgoing_ill != NULL)
21895 			ill_refrele(conn_outgoing_ill);
21896 		return;
21897 	}
21898 
21899 	/*
21900 	 * In most cases, the emission loop below is entered only
21901 	 * once. Only in the case where the ire holds the
21902 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21903 	 * flagged ires in the bucket, and send the packet
21904 	 * through all crossed RTF_MULTIRT routes.
21905 	 */
21906 	if (ire->ire_flags & RTF_MULTIRT) {
21907 		multirt_send = B_TRUE;
21908 	}
21909 	do {
21910 		if (multirt_send) {
21911 			irb_t *irb;
21912 			/*
21913 			 * We are in a multiple send case, need to get
21914 			 * the next ire and make a duplicate of the packet.
21915 			 * ire1 holds here the next ire to process in the
21916 			 * bucket. If multirouting is expected,
21917 			 * any non-RTF_MULTIRT ire that has the
21918 			 * right destination address is ignored.
21919 			 */
21920 			irb = ire->ire_bucket;
21921 			ASSERT(irb != NULL);
21922 
21923 			IRB_REFHOLD(irb);
21924 			for (ire1 = ire->ire_next;
21925 			    ire1 != NULL;
21926 			    ire1 = ire1->ire_next) {
21927 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21928 					continue;
21929 				if (ire1->ire_addr != ire->ire_addr)
21930 					continue;
21931 				if (ire1->ire_marks &
21932 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21933 					continue;
21934 
21935 				/* Got one */
21936 				IRE_REFHOLD(ire1);
21937 				break;
21938 			}
21939 			IRB_REFRELE(irb);
21940 
21941 			if (ire1 != NULL) {
21942 				next_mp = copyb(mp);
21943 				if ((next_mp == NULL) ||
21944 				    ((mp->b_cont != NULL) &&
21945 				    ((next_mp->b_cont =
21946 				    dupmsg(mp->b_cont)) == NULL))) {
21947 					freemsg(next_mp);
21948 					next_mp = NULL;
21949 					ire_refrele(ire1);
21950 					ire1 = NULL;
21951 				}
21952 			}
21953 
21954 			/* Last multiroute ire; don't loop anymore. */
21955 			if (ire1 == NULL) {
21956 				multirt_send = B_FALSE;
21957 			}
21958 		}
21959 
21960 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21961 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21962 		    mblk_t *, mp);
21963 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21964 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
21965 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21966 		if (mp == NULL)
21967 			goto release_ire_and_ill;
21968 
21969 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21970 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21971 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21972 		if ((pktxmit_state == SEND_FAILED) ||
21973 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21974 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21975 			    "- packet dropped\n"));
21976 release_ire_and_ill:
21977 			ire_refrele(ire);
21978 			if (next_mp != NULL) {
21979 				freemsg(next_mp);
21980 				ire_refrele(ire1);
21981 			}
21982 			if (conn_outgoing_ill != NULL)
21983 				ill_refrele(conn_outgoing_ill);
21984 			return;
21985 		}
21986 
21987 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21988 		    "ip_wput_ire_end: q %p (%S)",
21989 		    q, "last copy out");
21990 		IRE_REFRELE(ire);
21991 
21992 		if (multirt_send) {
21993 			ASSERT(ire1);
21994 			/*
21995 			 * Proceed with the next RTF_MULTIRT ire,
21996 			 * Also set up the send-to queue accordingly.
21997 			 */
21998 			ire = ire1;
21999 			ire1 = NULL;
22000 			stq = ire->ire_stq;
22001 			mp = next_mp;
22002 			next_mp = NULL;
22003 			ipha = (ipha_t *)mp->b_rptr;
22004 			ill_index = Q_TO_INDEX(stq);
22005 		}
22006 	} while (multirt_send);
22007 	if (conn_outgoing_ill != NULL)
22008 		ill_refrele(conn_outgoing_ill);
22009 	return;
22010 
22011 	/*
22012 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22013 	 */
22014 broadcast:
22015 	{
22016 		/*
22017 		 * Avoid broadcast storms by setting the ttl to 1
22018 		 * for broadcasts. This parameter can be set
22019 		 * via ndd, so make sure that for the SO_DONTROUTE
22020 		 * case that ipha_ttl is always set to 1.
22021 		 * In the event that we are replying to incoming
22022 		 * ICMP packets, conn could be NULL.
22023 		 */
22024 		if ((connp != NULL) && connp->conn_dontroute)
22025 			ipha->ipha_ttl = 1;
22026 		else
22027 			ipha->ipha_ttl = ip_broadcast_ttl;
22028 
22029 		/*
22030 		 * Note that we are not doing a IRB_REFHOLD here.
22031 		 * Actually we don't care if the list changes i.e
22032 		 * if somebody deletes an IRE from the list while
22033 		 * we drop the lock, the next time we come around
22034 		 * ire_next will be NULL and hence we won't send
22035 		 * out multiple copies which is fine.
22036 		 */
22037 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22038 		ire1 = ire->ire_next;
22039 		if (conn_outgoing_ill != NULL) {
22040 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22041 				ASSERT(ire1 == ire->ire_next);
22042 				if (ire1 != NULL && ire1->ire_addr == dst) {
22043 					ire_refrele(ire);
22044 					ire = ire1;
22045 					IRE_REFHOLD(ire);
22046 					ire1 = ire->ire_next;
22047 					continue;
22048 				}
22049 				rw_exit(&ire->ire_bucket->irb_lock);
22050 				/* Did not find a matching ill */
22051 				ip1dbg(("ip_wput_ire: broadcast with no "
22052 				    "matching IP_BOUND_IF ill %s\n",
22053 				    conn_outgoing_ill->ill_name));
22054 				freemsg(first_mp);
22055 				if (ire != NULL)
22056 					ire_refrele(ire);
22057 				ill_refrele(conn_outgoing_ill);
22058 				return;
22059 			}
22060 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22061 			/*
22062 			 * If the next IRE has the same address and is not one
22063 			 * of the two copies that we need to send, try to see
22064 			 * whether this copy should be sent at all. This
22065 			 * assumes that we insert loopbacks first and then
22066 			 * non-loopbacks. This is acheived by inserting the
22067 			 * loopback always before non-loopback.
22068 			 * This is used to send a single copy of a broadcast
22069 			 * packet out all physical interfaces that have an
22070 			 * matching IRE_BROADCAST while also looping
22071 			 * back one copy (to ip_wput_local) for each
22072 			 * matching physical interface. However, we avoid
22073 			 * sending packets out different logical that match by
22074 			 * having ipif_up/ipif_down supress duplicate
22075 			 * IRE_BROADCASTS.
22076 			 *
22077 			 * This feature is currently used to get broadcasts
22078 			 * sent to multiple interfaces, when the broadcast
22079 			 * address being used applies to multiple interfaces.
22080 			 * For example, a whole net broadcast will be
22081 			 * replicated on every connected subnet of
22082 			 * the target net.
22083 			 *
22084 			 * Each zone has its own set of IRE_BROADCASTs, so that
22085 			 * we're able to distribute inbound packets to multiple
22086 			 * zones who share a broadcast address. We avoid looping
22087 			 * back outbound packets in different zones but on the
22088 			 * same ill, as the application would see duplicates.
22089 			 *
22090 			 * If the interfaces are part of the same group,
22091 			 * we would want to send only one copy out for
22092 			 * whole group.
22093 			 *
22094 			 * This logic assumes that ire_add_v4() groups the
22095 			 * IRE_BROADCAST entries so that those with the same
22096 			 * ire_addr and ill_group are kept together.
22097 			 */
22098 			ire_ill = ire->ire_ipif->ipif_ill;
22099 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22100 				if (ire_ill->ill_group != NULL &&
22101 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22102 					/*
22103 					 * If the current zone only has an ire
22104 					 * broadcast for this address marked
22105 					 * NORECV, the ire we want is ahead in
22106 					 * the bucket, so we look it up
22107 					 * deliberately ignoring the zoneid.
22108 					 */
22109 					for (ire1 = ire->ire_bucket->irb_ire;
22110 					    ire1 != NULL;
22111 					    ire1 = ire1->ire_next) {
22112 						ire1_ill =
22113 						    ire1->ire_ipif->ipif_ill;
22114 						if (ire1->ire_addr != dst)
22115 							continue;
22116 						/* skip over the current ire */
22117 						if (ire1 == ire)
22118 							continue;
22119 						/* skip over deleted ires */
22120 						if (ire1->ire_marks &
22121 						    IRE_MARK_CONDEMNED)
22122 							continue;
22123 						/*
22124 						 * non-loopback ire in our
22125 						 * group: use it for the next
22126 						 * pass in the loop
22127 						 */
22128 						if (ire1->ire_stq != NULL &&
22129 						    ire1_ill->ill_group ==
22130 						    ire_ill->ill_group)
22131 							break;
22132 					}
22133 				}
22134 			} else {
22135 				while (ire1 != NULL && ire1->ire_addr == dst) {
22136 					ire1_ill = ire1->ire_ipif->ipif_ill;
22137 					/*
22138 					 * We can have two broadcast ires on the
22139 					 * same ill in different zones; here
22140 					 * we'll send a copy of the packet on
22141 					 * each ill and the fanout code will
22142 					 * call conn_wantpacket() to check that
22143 					 * the zone has the broadcast address
22144 					 * configured on the ill. If the two
22145 					 * ires are in the same group we only
22146 					 * send one copy up.
22147 					 */
22148 					if (ire1_ill != ire_ill &&
22149 					    (ire1_ill->ill_group == NULL ||
22150 					    ire_ill->ill_group == NULL ||
22151 					    ire1_ill->ill_group !=
22152 					    ire_ill->ill_group)) {
22153 						break;
22154 					}
22155 					ire1 = ire1->ire_next;
22156 				}
22157 			}
22158 		}
22159 		ASSERT(multirt_send == B_FALSE);
22160 		if (ire1 != NULL && ire1->ire_addr == dst) {
22161 			if ((ire->ire_flags & RTF_MULTIRT) &&
22162 			    (ire1->ire_flags & RTF_MULTIRT)) {
22163 				/*
22164 				 * We are in the multirouting case.
22165 				 * The message must be sent at least
22166 				 * on both ires. These ires have been
22167 				 * inserted AFTER the standard ones
22168 				 * in ip_rt_add(). There are thus no
22169 				 * other ire entries for the destination
22170 				 * address in the rest of the bucket
22171 				 * that do not have the RTF_MULTIRT
22172 				 * flag. We don't process a copy
22173 				 * of the message here. This will be
22174 				 * done in the final sending loop.
22175 				 */
22176 				multirt_send = B_TRUE;
22177 			} else {
22178 				next_mp = ip_copymsg(first_mp);
22179 				if (next_mp != NULL)
22180 					IRE_REFHOLD(ire1);
22181 			}
22182 		}
22183 		rw_exit(&ire->ire_bucket->irb_lock);
22184 	}
22185 
22186 	if (stq) {
22187 		/*
22188 		 * A non-NULL send-to queue means this packet is going
22189 		 * out of this machine.
22190 		 */
22191 
22192 		BUMP_MIB(&ip_mib, ipOutRequests);
22193 		ttl_protocol = ((uint16_t *)ipha)[4];
22194 		/*
22195 		 * We accumulate the pseudo header checksum in cksum.
22196 		 * This is pretty hairy code, so watch close.  One
22197 		 * thing to keep in mind is that UDP and TCP have
22198 		 * stored their respective datagram lengths in their
22199 		 * checksum fields.  This lines things up real nice.
22200 		 */
22201 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22202 		    (src >> 16) + (src & 0xFFFF);
22203 		/*
22204 		 * We assume the udp checksum field contains the
22205 		 * length, so to compute the pseudo header checksum,
22206 		 * all we need is the protocol number and src/dst.
22207 		 */
22208 		/* Provide the checksums for UDP and TCP. */
22209 		if ((PROTO == IPPROTO_TCP) &&
22210 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22211 			/* hlen gets the number of uchar_ts in the IP header */
22212 			hlen = (V_HLEN & 0xF) << 2;
22213 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22214 			IP_STAT(ip_out_sw_cksum);
22215 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22216 			    LENGTH - hlen);
22217 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22218 			if (*up == 0)
22219 				*up = 0xFFFF;
22220 		} else if (PROTO == IPPROTO_SCTP &&
22221 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22222 			sctp_hdr_t	*sctph;
22223 
22224 			hlen = (V_HLEN & 0xF) << 2;
22225 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22226 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22227 			sctph->sh_chksum = 0;
22228 #ifdef	DEBUG
22229 			if (!skip_sctp_cksum)
22230 #endif
22231 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22232 		} else {
22233 			queue_t *dev_q = stq->q_next;
22234 
22235 			if ((dev_q->q_next || dev_q->q_first) &&
22236 			    !canput(dev_q)) {
22237 			    blocked:
22238 				ipha->ipha_ident = ip_hdr_included;
22239 				/*
22240 				 * If we don't have a conn to apply
22241 				 * backpressure, free the message.
22242 				 * In the ire_send path, we don't know
22243 				 * the position to requeue the packet. Rather
22244 				 * than reorder packets, we just drop this
22245 				 * packet.
22246 				 */
22247 				if (ip_output_queue && connp != NULL &&
22248 				    caller != IRE_SEND) {
22249 					if (caller == IP_WSRV) {
22250 						connp->conn_did_putbq = 1;
22251 						(void) putbq(connp->conn_wq,
22252 						    first_mp);
22253 						conn_drain_insert(connp);
22254 						/*
22255 						 * This is the service thread,
22256 						 * and the queue is already
22257 						 * noenabled. The check for
22258 						 * canput and the putbq is not
22259 						 * atomic. So we need to check
22260 						 * again.
22261 						 */
22262 						if (canput(stq->q_next))
22263 							connp->conn_did_putbq
22264 							    = 0;
22265 						IP_STAT(ip_conn_flputbq);
22266 					} else {
22267 						/*
22268 						 * We are not the service proc.
22269 						 * ip_wsrv will be scheduled or
22270 						 * is already running.
22271 						 */
22272 						(void) putq(connp->conn_wq,
22273 						    first_mp);
22274 					}
22275 				} else {
22276 					BUMP_MIB(&ip_mib, ipOutDiscards);
22277 					freemsg(first_mp);
22278 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22279 					    "ip_wput_ire_end: q %p (%S)",
22280 					    q, "discard");
22281 				}
22282 				ire_refrele(ire);
22283 				if (next_mp) {
22284 					ire_refrele(ire1);
22285 					freemsg(next_mp);
22286 				}
22287 				if (conn_outgoing_ill != NULL)
22288 					ill_refrele(conn_outgoing_ill);
22289 				return;
22290 			}
22291 			if ((PROTO == IPPROTO_UDP) &&
22292 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22293 				/*
22294 				 * hlen gets the number of uchar_ts in the
22295 				 * IP header
22296 				 */
22297 				hlen = (V_HLEN & 0xF) << 2;
22298 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22299 				max_frag = ire->ire_max_frag;
22300 				if (*up != 0) {
22301 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22302 					    up, PROTO, hlen, LENGTH, max_frag,
22303 					    ipsec_len, cksum);
22304 					/* Software checksum? */
22305 					if (DB_CKSUMFLAGS(mp) == 0) {
22306 						IP_STAT(ip_out_sw_cksum);
22307 						IP_STAT_UPDATE(
22308 						    ip_udp_out_sw_cksum_bytes,
22309 						    LENGTH - hlen);
22310 					}
22311 				}
22312 			}
22313 		}
22314 		/*
22315 		 * Need to do this even when fragmenting. The local
22316 		 * loopback can be done without computing checksums
22317 		 * but forwarding out other interface must be done
22318 		 * after the IP checksum (and ULP checksums) have been
22319 		 * computed.
22320 		 *
22321 		 * NOTE : multicast_forward is set only if this packet
22322 		 * originated from ip_wput. For packets originating from
22323 		 * ip_wput_multicast, it is not set.
22324 		 */
22325 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22326 		    multi_loopback:
22327 			ip2dbg(("ip_wput: multicast, loop %d\n",
22328 			    conn_multicast_loop));
22329 
22330 			/*  Forget header checksum offload */
22331 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22332 
22333 			/*
22334 			 * Local loopback of multicasts?  Check the
22335 			 * ill.
22336 			 *
22337 			 * Note that the loopback function will not come
22338 			 * in through ip_rput - it will only do the
22339 			 * client fanout thus we need to do an mforward
22340 			 * as well.  The is different from the BSD
22341 			 * logic.
22342 			 */
22343 			if (ill != NULL) {
22344 				ilm_t	*ilm;
22345 
22346 				ILM_WALKER_HOLD(ill);
22347 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22348 				    ALL_ZONES);
22349 				ILM_WALKER_RELE(ill);
22350 				if (ilm != NULL) {
22351 					/*
22352 					 * Pass along the virtual output q.
22353 					 * ip_wput_local() will distribute the
22354 					 * packet to all the matching zones,
22355 					 * except the sending zone when
22356 					 * IP_MULTICAST_LOOP is false.
22357 					 */
22358 					ip_multicast_loopback(q, ill, first_mp,
22359 					    conn_multicast_loop ? 0 :
22360 					    IP_FF_NO_MCAST_LOOP, zoneid);
22361 				}
22362 			}
22363 			if (ipha->ipha_ttl == 0) {
22364 				/*
22365 				 * 0 => only to this host i.e. we are
22366 				 * done. We are also done if this was the
22367 				 * loopback interface since it is sufficient
22368 				 * to loopback one copy of a multicast packet.
22369 				 */
22370 				freemsg(first_mp);
22371 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22372 				    "ip_wput_ire_end: q %p (%S)",
22373 				    q, "loopback");
22374 				ire_refrele(ire);
22375 				if (conn_outgoing_ill != NULL)
22376 					ill_refrele(conn_outgoing_ill);
22377 				return;
22378 			}
22379 			/*
22380 			 * ILLF_MULTICAST is checked in ip_newroute
22381 			 * i.e. we don't need to check it here since
22382 			 * all IRE_CACHEs come from ip_newroute.
22383 			 * For multicast traffic, SO_DONTROUTE is interpreted
22384 			 * to mean only send the packet out the interface
22385 			 * (optionally specified with IP_MULTICAST_IF)
22386 			 * and do not forward it out additional interfaces.
22387 			 * RSVP and the rsvp daemon is an example of a
22388 			 * protocol and user level process that
22389 			 * handles it's own routing. Hence, it uses the
22390 			 * SO_DONTROUTE option to accomplish this.
22391 			 */
22392 
22393 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22394 				/* Unconditionally redo the checksum */
22395 				ipha->ipha_hdr_checksum = 0;
22396 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22397 
22398 				/*
22399 				 * If this needs to go out secure, we need
22400 				 * to wait till we finish the IPSEC
22401 				 * processing.
22402 				 */
22403 				if (ipsec_len == 0 &&
22404 				    ip_mforward(ill, ipha, mp)) {
22405 					freemsg(first_mp);
22406 					ip1dbg(("ip_wput: mforward failed\n"));
22407 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22408 					    "ip_wput_ire_end: q %p (%S)",
22409 					    q, "mforward failed");
22410 					ire_refrele(ire);
22411 					if (conn_outgoing_ill != NULL)
22412 						ill_refrele(conn_outgoing_ill);
22413 					return;
22414 				}
22415 			}
22416 		}
22417 		max_frag = ire->ire_max_frag;
22418 		cksum += ttl_protocol;
22419 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22420 			/* No fragmentation required for this one. */
22421 			/*
22422 			 * Don't use frag_flag if packet is pre-built or source
22423 			 * routed or if multicast (since multicast packets do
22424 			 * not solicit ICMP "packet too big" messages).
22425 			 */
22426 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22427 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22428 			    !ip_source_route_included(ipha)) &&
22429 			    !CLASSD(ipha->ipha_dst))
22430 				ipha->ipha_fragment_offset_and_flags |=
22431 				    htons(ire->ire_frag_flag);
22432 
22433 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22434 				/* Complete the IP header checksum. */
22435 				cksum += ipha->ipha_ident;
22436 				cksum += (v_hlen_tos_len >> 16)+
22437 				    (v_hlen_tos_len & 0xFFFF);
22438 				cksum += ipha->ipha_fragment_offset_and_flags;
22439 				hlen = (V_HLEN & 0xF) -
22440 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22441 				if (hlen) {
22442 				    checksumoptions:
22443 					/*
22444 					 * Account for the IP Options in the IP
22445 					 * header checksum.
22446 					 */
22447 					up = (uint16_t *)(rptr+
22448 					    IP_SIMPLE_HDR_LENGTH);
22449 					do {
22450 						cksum += up[0];
22451 						cksum += up[1];
22452 						up += 2;
22453 					} while (--hlen);
22454 				}
22455 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22456 				cksum = ~(cksum + (cksum >> 16));
22457 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22458 			}
22459 			if (ipsec_len != 0) {
22460 				ipsec_out_process(q, first_mp, ire, ill_index);
22461 				if (!next_mp) {
22462 					ire_refrele(ire);
22463 					if (conn_outgoing_ill != NULL)
22464 						ill_refrele(conn_outgoing_ill);
22465 					return;
22466 				}
22467 				goto next;
22468 			}
22469 
22470 			/*
22471 			 * multirt_send has already been handled
22472 			 * for broadcast, but not yet for multicast
22473 			 * or IP options.
22474 			 */
22475 			if (next_mp == NULL) {
22476 				if (ire->ire_flags & RTF_MULTIRT) {
22477 					multirt_send = B_TRUE;
22478 				}
22479 			}
22480 
22481 			/*
22482 			 * In most cases, the emission loop below is
22483 			 * entered only once. Only in the case where
22484 			 * the ire holds the RTF_MULTIRT flag, do we loop
22485 			 * to process all RTF_MULTIRT ires in the bucket,
22486 			 * and send the packet through all crossed
22487 			 * RTF_MULTIRT routes.
22488 			 */
22489 			do {
22490 				if (multirt_send) {
22491 					irb_t *irb;
22492 
22493 					irb = ire->ire_bucket;
22494 					ASSERT(irb != NULL);
22495 					/*
22496 					 * We are in a multiple send case,
22497 					 * need to get the next IRE and make
22498 					 * a duplicate of the packet.
22499 					 */
22500 					IRB_REFHOLD(irb);
22501 					for (ire1 = ire->ire_next;
22502 					    ire1 != NULL;
22503 					    ire1 = ire1->ire_next) {
22504 						if (!(ire1->ire_flags &
22505 						    RTF_MULTIRT))
22506 							continue;
22507 						if (ire1->ire_addr !=
22508 						    ire->ire_addr)
22509 							continue;
22510 						if (ire1->ire_marks &
22511 						    (IRE_MARK_CONDEMNED|
22512 							IRE_MARK_HIDDEN))
22513 							continue;
22514 
22515 						/* Got one */
22516 						IRE_REFHOLD(ire1);
22517 						break;
22518 					}
22519 					IRB_REFRELE(irb);
22520 
22521 					if (ire1 != NULL) {
22522 						next_mp = copyb(mp);
22523 						if ((next_mp == NULL) ||
22524 						    ((mp->b_cont != NULL) &&
22525 						    ((next_mp->b_cont =
22526 						    dupmsg(mp->b_cont))
22527 						    == NULL))) {
22528 							freemsg(next_mp);
22529 							next_mp = NULL;
22530 							ire_refrele(ire1);
22531 							ire1 = NULL;
22532 						}
22533 					}
22534 
22535 					/*
22536 					 * Last multiroute ire; don't loop
22537 					 * anymore. The emission is over
22538 					 * and next_mp is NULL.
22539 					 */
22540 					if (ire1 == NULL) {
22541 						multirt_send = B_FALSE;
22542 					}
22543 				}
22544 
22545 				out_ill = ire->ire_ipif->ipif_ill;
22546 				DTRACE_PROBE4(ip4__physical__out__start,
22547 				    ill_t *, NULL,
22548 				    ill_t *, out_ill,
22549 				    ipha_t *, ipha, mblk_t *, mp);
22550 				FW_HOOKS(ip4_physical_out_event,
22551 				    ipv4firewall_physical_out,
22552 				    NULL, out_ill, ipha, mp, mp);
22553 				DTRACE_PROBE1(ip4__physical__out__end,
22554 				    mblk_t *, mp);
22555 				if (mp == NULL)
22556 					goto release_ire_and_ill_2;
22557 
22558 				ASSERT(ipsec_len == 0);
22559 				mp->b_prev =
22560 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22561 				DTRACE_PROBE2(ip__xmit__2,
22562 				    mblk_t *, mp, ire_t *, ire);
22563 				pktxmit_state = ip_xmit_v4(mp, ire,
22564 				    NULL, B_TRUE);
22565 				if ((pktxmit_state == SEND_FAILED) ||
22566 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22567 release_ire_and_ill_2:
22568 					if (next_mp) {
22569 						freemsg(next_mp);
22570 						ire_refrele(ire1);
22571 					}
22572 					ire_refrele(ire);
22573 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22574 					    "ip_wput_ire_end: q %p (%S)",
22575 					    q, "discard MDATA");
22576 					if (conn_outgoing_ill != NULL)
22577 						ill_refrele(conn_outgoing_ill);
22578 					return;
22579 				}
22580 
22581 				if (multirt_send) {
22582 					/*
22583 					 * We are in a multiple send case,
22584 					 * need to re-enter the sending loop
22585 					 * using the next ire.
22586 					 */
22587 					ire_refrele(ire);
22588 					ire = ire1;
22589 					stq = ire->ire_stq;
22590 					mp = next_mp;
22591 					next_mp = NULL;
22592 					ipha = (ipha_t *)mp->b_rptr;
22593 					ill_index = Q_TO_INDEX(stq);
22594 				}
22595 			} while (multirt_send);
22596 
22597 			if (!next_mp) {
22598 				/*
22599 				 * Last copy going out (the ultra-common
22600 				 * case).  Note that we intentionally replicate
22601 				 * the putnext rather than calling it before
22602 				 * the next_mp check in hopes of a little
22603 				 * tail-call action out of the compiler.
22604 				 */
22605 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22606 				    "ip_wput_ire_end: q %p (%S)",
22607 				    q, "last copy out(1)");
22608 				ire_refrele(ire);
22609 				if (conn_outgoing_ill != NULL)
22610 					ill_refrele(conn_outgoing_ill);
22611 				return;
22612 			}
22613 			/* More copies going out below. */
22614 		} else {
22615 			int offset;
22616 		    fragmentit:
22617 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22618 			/*
22619 			 * If this would generate a icmp_frag_needed message,
22620 			 * we need to handle it before we do the IPSEC
22621 			 * processing. Otherwise, we need to strip the IPSEC
22622 			 * headers before we send up the message to the ULPs
22623 			 * which becomes messy and difficult.
22624 			 */
22625 			if (ipsec_len != 0) {
22626 				if ((max_frag < (unsigned int)(LENGTH +
22627 				    ipsec_len)) && (offset & IPH_DF)) {
22628 
22629 					BUMP_MIB(&ip_mib, ipFragFails);
22630 					ipha->ipha_hdr_checksum = 0;
22631 					ipha->ipha_hdr_checksum =
22632 					    (uint16_t)ip_csum_hdr(ipha);
22633 					icmp_frag_needed(ire->ire_stq, first_mp,
22634 					    max_frag, zoneid);
22635 					if (!next_mp) {
22636 						ire_refrele(ire);
22637 						if (conn_outgoing_ill != NULL) {
22638 							ill_refrele(
22639 							    conn_outgoing_ill);
22640 						}
22641 						return;
22642 					}
22643 				} else {
22644 					/*
22645 					 * This won't cause a icmp_frag_needed
22646 					 * message. to be gnerated. Send it on
22647 					 * the wire. Note that this could still
22648 					 * cause fragmentation and all we
22649 					 * do is the generation of the message
22650 					 * to the ULP if needed before IPSEC.
22651 					 */
22652 					if (!next_mp) {
22653 						ipsec_out_process(q, first_mp,
22654 						    ire, ill_index);
22655 						TRACE_2(TR_FAC_IP,
22656 						    TR_IP_WPUT_IRE_END,
22657 						    "ip_wput_ire_end: q %p "
22658 						    "(%S)", q,
22659 						    "last ipsec_out_process");
22660 						ire_refrele(ire);
22661 						if (conn_outgoing_ill != NULL) {
22662 							ill_refrele(
22663 							    conn_outgoing_ill);
22664 						}
22665 						return;
22666 					}
22667 					ipsec_out_process(q, first_mp,
22668 					    ire, ill_index);
22669 				}
22670 			} else {
22671 				/*
22672 				 * Initiate IPPF processing. For
22673 				 * fragmentable packets we finish
22674 				 * all QOS packet processing before
22675 				 * calling:
22676 				 * ip_wput_ire_fragmentit->ip_wput_frag
22677 				 */
22678 
22679 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22680 					ip_process(IPP_LOCAL_OUT, &mp,
22681 					    ill_index);
22682 					if (mp == NULL) {
22683 						BUMP_MIB(&ip_mib,
22684 						    ipOutDiscards);
22685 						if (next_mp != NULL) {
22686 							freemsg(next_mp);
22687 							ire_refrele(ire1);
22688 						}
22689 						ire_refrele(ire);
22690 						TRACE_2(TR_FAC_IP,
22691 						    TR_IP_WPUT_IRE_END,
22692 						    "ip_wput_ire: q %p (%S)",
22693 						    q, "discard MDATA");
22694 						if (conn_outgoing_ill != NULL) {
22695 							ill_refrele(
22696 							    conn_outgoing_ill);
22697 						}
22698 						return;
22699 					}
22700 				}
22701 				if (!next_mp) {
22702 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22703 					    "ip_wput_ire_end: q %p (%S)",
22704 					    q, "last fragmentation");
22705 					ip_wput_ire_fragmentit(mp, ire,
22706 					    zoneid);
22707 					ire_refrele(ire);
22708 					if (conn_outgoing_ill != NULL)
22709 						ill_refrele(conn_outgoing_ill);
22710 					return;
22711 				}
22712 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22713 			}
22714 		}
22715 	} else {
22716 	    nullstq:
22717 		/* A NULL stq means the destination address is local. */
22718 		UPDATE_OB_PKT_COUNT(ire);
22719 		ire->ire_last_used_time = lbolt;
22720 		ASSERT(ire->ire_ipif != NULL);
22721 		if (!next_mp) {
22722 			/*
22723 			 * Is there an "in" and "out" for traffic local
22724 			 * to a host (loopback)?  The code in Solaris doesn't
22725 			 * explicitly draw a line in its code for in vs out,
22726 			 * so we've had to draw a line in the sand: ip_wput_ire
22727 			 * is considered to be the "output" side and
22728 			 * ip_wput_local to be the "input" side.
22729 			 */
22730 			out_ill = ire->ire_ipif->ipif_ill;
22731 
22732 			DTRACE_PROBE4(ip4__loopback__out__start,
22733 			    ill_t *, NULL, ill_t *, out_ill,
22734 			    ipha_t *, ipha, mblk_t *, first_mp);
22735 
22736 			FW_HOOKS(ip4_loopback_out_event,
22737 			    ipv4firewall_loopback_out,
22738 			    NULL, out_ill, ipha, first_mp, mp);
22739 
22740 			DTRACE_PROBE1(ip4__loopback__out_end,
22741 			    mblk_t *, first_mp);
22742 
22743 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22744 			    "ip_wput_ire_end: q %p (%S)",
22745 			    q, "local address");
22746 
22747 			if (first_mp != NULL)
22748 				ip_wput_local(q, out_ill, ipha,
22749 				    first_mp, ire, 0, ire->ire_zoneid);
22750 			ire_refrele(ire);
22751 			if (conn_outgoing_ill != NULL)
22752 				ill_refrele(conn_outgoing_ill);
22753 			return;
22754 		}
22755 
22756 		out_ill = ire->ire_ipif->ipif_ill;
22757 
22758 		DTRACE_PROBE4(ip4__loopback__out__start,
22759 		    ill_t *, NULL, ill_t *, out_ill,
22760 		    ipha_t *, ipha, mblk_t *, first_mp);
22761 
22762 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22763 		    NULL, out_ill, ipha, first_mp, mp);
22764 
22765 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22766 
22767 		if (first_mp != NULL)
22768 			ip_wput_local(q, out_ill, ipha,
22769 			    first_mp, ire, 0, ire->ire_zoneid);
22770 	}
22771 next:
22772 	/*
22773 	 * More copies going out to additional interfaces.
22774 	 * ire1 has already been held. We don't need the
22775 	 * "ire" anymore.
22776 	 */
22777 	ire_refrele(ire);
22778 	ire = ire1;
22779 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22780 	mp = next_mp;
22781 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22782 	ill = ire_to_ill(ire);
22783 	first_mp = mp;
22784 	if (ipsec_len != 0) {
22785 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22786 		mp = mp->b_cont;
22787 	}
22788 	dst = ire->ire_addr;
22789 	ipha = (ipha_t *)mp->b_rptr;
22790 	/*
22791 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22792 	 * Restore ipha_ident "no checksum" flag.
22793 	 */
22794 	src = orig_src;
22795 	ipha->ipha_ident = ip_hdr_included;
22796 	goto another;
22797 
22798 #undef	rptr
22799 #undef	Q_TO_INDEX
22800 }
22801 
22802 /*
22803  * Routine to allocate a message that is used to notify the ULP about MDT.
22804  * The caller may provide a pointer to the link-layer MDT capabilities,
22805  * or NULL if MDT is to be disabled on the stream.
22806  */
22807 mblk_t *
22808 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22809 {
22810 	mblk_t *mp;
22811 	ip_mdt_info_t *mdti;
22812 	ill_mdt_capab_t *idst;
22813 
22814 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22815 		DB_TYPE(mp) = M_CTL;
22816 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22817 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22818 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22819 		idst = &(mdti->mdt_capab);
22820 
22821 		/*
22822 		 * If the caller provides us with the capability, copy
22823 		 * it over into our notification message; otherwise
22824 		 * we zero out the capability portion.
22825 		 */
22826 		if (isrc != NULL)
22827 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22828 		else
22829 			bzero((caddr_t)idst, sizeof (*idst));
22830 	}
22831 	return (mp);
22832 }
22833 
22834 /*
22835  * Routine which determines whether MDT can be enabled on the destination
22836  * IRE and IPC combination, and if so, allocates and returns the MDT
22837  * notification mblk that may be used by ULP.  We also check if we need to
22838  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22839  * MDT usage in the past have been lifted.  This gets called during IP
22840  * and ULP binding.
22841  */
22842 mblk_t *
22843 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22844     ill_mdt_capab_t *mdt_cap)
22845 {
22846 	mblk_t *mp;
22847 	boolean_t rc = B_FALSE;
22848 
22849 	ASSERT(dst_ire != NULL);
22850 	ASSERT(connp != NULL);
22851 	ASSERT(mdt_cap != NULL);
22852 
22853 	/*
22854 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22855 	 * Multidata, which is handled in tcp_multisend().  This
22856 	 * is the reason why we do all these checks here, to ensure
22857 	 * that we don't enable Multidata for the cases which we
22858 	 * can't handle at the moment.
22859 	 */
22860 	do {
22861 		/* Only do TCP at the moment */
22862 		if (connp->conn_ulp != IPPROTO_TCP)
22863 			break;
22864 
22865 		/*
22866 		 * IPSEC outbound policy present?  Note that we get here
22867 		 * after calling ipsec_conn_cache_policy() where the global
22868 		 * policy checking is performed.  conn_latch will be
22869 		 * non-NULL as long as there's a policy defined,
22870 		 * i.e. conn_out_enforce_policy may be NULL in such case
22871 		 * when the connection is non-secure, and hence we check
22872 		 * further if the latch refers to an outbound policy.
22873 		 */
22874 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22875 			break;
22876 
22877 		/* CGTP (multiroute) is enabled? */
22878 		if (dst_ire->ire_flags & RTF_MULTIRT)
22879 			break;
22880 
22881 		/* Outbound IPQoS enabled? */
22882 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22883 			/*
22884 			 * In this case, we disable MDT for this and all
22885 			 * future connections going over the interface.
22886 			 */
22887 			mdt_cap->ill_mdt_on = 0;
22888 			break;
22889 		}
22890 
22891 		/* socket option(s) present? */
22892 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
22893 			break;
22894 
22895 		rc = B_TRUE;
22896 	/* CONSTCOND */
22897 	} while (0);
22898 
22899 	/* Remember the result */
22900 	connp->conn_mdt_ok = rc;
22901 
22902 	if (!rc)
22903 		return (NULL);
22904 	else if (!mdt_cap->ill_mdt_on) {
22905 		/*
22906 		 * If MDT has been previously turned off in the past, and we
22907 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22908 		 * then enable it for this interface.
22909 		 */
22910 		mdt_cap->ill_mdt_on = 1;
22911 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22912 		    "interface %s\n", ill_name));
22913 	}
22914 
22915 	/* Allocate the MDT info mblk */
22916 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22917 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22918 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22919 		return (NULL);
22920 	}
22921 	return (mp);
22922 }
22923 
22924 /*
22925  * Routine to allocate a message that is used to notify the ULP about LSO.
22926  * The caller may provide a pointer to the link-layer LSO capabilities,
22927  * or NULL if LSO is to be disabled on the stream.
22928  */
22929 mblk_t *
22930 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
22931 {
22932 	mblk_t *mp;
22933 	ip_lso_info_t *lsoi;
22934 	ill_lso_capab_t *idst;
22935 
22936 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
22937 		DB_TYPE(mp) = M_CTL;
22938 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
22939 		lsoi = (ip_lso_info_t *)mp->b_rptr;
22940 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
22941 		idst = &(lsoi->lso_capab);
22942 
22943 		/*
22944 		 * If the caller provides us with the capability, copy
22945 		 * it over into our notification message; otherwise
22946 		 * we zero out the capability portion.
22947 		 */
22948 		if (isrc != NULL)
22949 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22950 		else
22951 			bzero((caddr_t)idst, sizeof (*idst));
22952 	}
22953 	return (mp);
22954 }
22955 
22956 /*
22957  * Routine which determines whether LSO can be enabled on the destination
22958  * IRE and IPC combination, and if so, allocates and returns the LSO
22959  * notification mblk that may be used by ULP.  We also check if we need to
22960  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
22961  * LSO usage in the past have been lifted.  This gets called during IP
22962  * and ULP binding.
22963  */
22964 mblk_t *
22965 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22966     ill_lso_capab_t *lso_cap)
22967 {
22968 	mblk_t *mp;
22969 
22970 	ASSERT(dst_ire != NULL);
22971 	ASSERT(connp != NULL);
22972 	ASSERT(lso_cap != NULL);
22973 
22974 	connp->conn_lso_ok = B_TRUE;
22975 
22976 	if ((connp->conn_ulp != IPPROTO_TCP) ||
22977 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
22978 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
22979 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
22980 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
22981 		connp->conn_lso_ok = B_FALSE;
22982 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22983 			/*
22984 			 * Disable LSO for this and all future connections going
22985 			 * over the interface.
22986 			 */
22987 			lso_cap->ill_lso_on = 0;
22988 		}
22989 	}
22990 
22991 	if (!connp->conn_lso_ok)
22992 		return (NULL);
22993 	else if (!lso_cap->ill_lso_on) {
22994 		/*
22995 		 * If LSO has been previously turned off in the past, and we
22996 		 * currently can do LSO (due to IPQoS policy removal, etc.)
22997 		 * then enable it for this interface.
22998 		 */
22999 		lso_cap->ill_lso_on = 1;
23000 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23001 		    ill_name));
23002 	}
23003 
23004 	/* Allocate the LSO info mblk */
23005 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23006 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23007 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23008 
23009 	return (mp);
23010 }
23011 
23012 /*
23013  * Create destination address attribute, and fill it with the physical
23014  * destination address and SAP taken from the template DL_UNITDATA_REQ
23015  * message block.
23016  */
23017 boolean_t
23018 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23019 {
23020 	dl_unitdata_req_t *dlurp;
23021 	pattr_t *pa;
23022 	pattrinfo_t pa_info;
23023 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23024 	uint_t das_len, das_off;
23025 
23026 	ASSERT(dlmp != NULL);
23027 
23028 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23029 	das_len = dlurp->dl_dest_addr_length;
23030 	das_off = dlurp->dl_dest_addr_offset;
23031 
23032 	pa_info.type = PATTR_DSTADDRSAP;
23033 	pa_info.len = sizeof (**das) + das_len - 1;
23034 
23035 	/* create and associate the attribute */
23036 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23037 	if (pa != NULL) {
23038 		ASSERT(*das != NULL);
23039 		(*das)->addr_is_group = 0;
23040 		(*das)->addr_len = (uint8_t)das_len;
23041 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23042 	}
23043 
23044 	return (pa != NULL);
23045 }
23046 
23047 /*
23048  * Create hardware checksum attribute and fill it with the values passed.
23049  */
23050 boolean_t
23051 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23052     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23053 {
23054 	pattr_t *pa;
23055 	pattrinfo_t pa_info;
23056 
23057 	ASSERT(mmd != NULL);
23058 
23059 	pa_info.type = PATTR_HCKSUM;
23060 	pa_info.len = sizeof (pattr_hcksum_t);
23061 
23062 	/* create and associate the attribute */
23063 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23064 	if (pa != NULL) {
23065 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23066 
23067 		hck->hcksum_start_offset = start_offset;
23068 		hck->hcksum_stuff_offset = stuff_offset;
23069 		hck->hcksum_end_offset = end_offset;
23070 		hck->hcksum_flags = flags;
23071 	}
23072 	return (pa != NULL);
23073 }
23074 
23075 /*
23076  * Create zerocopy attribute and fill it with the specified flags
23077  */
23078 boolean_t
23079 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23080 {
23081 	pattr_t *pa;
23082 	pattrinfo_t pa_info;
23083 
23084 	ASSERT(mmd != NULL);
23085 	pa_info.type = PATTR_ZCOPY;
23086 	pa_info.len = sizeof (pattr_zcopy_t);
23087 
23088 	/* create and associate the attribute */
23089 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23090 	if (pa != NULL) {
23091 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23092 
23093 		zcopy->zcopy_flags = flags;
23094 	}
23095 	return (pa != NULL);
23096 }
23097 
23098 /*
23099  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23100  * block chain. We could rewrite to handle arbitrary message block chains but
23101  * that would make the code complicated and slow. Right now there three
23102  * restrictions:
23103  *
23104  *   1. The first message block must contain the complete IP header and
23105  *	at least 1 byte of payload data.
23106  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23107  *	so that we can use a single Multidata message.
23108  *   3. No frag must be distributed over two or more message blocks so
23109  *	that we don't need more than two packet descriptors per frag.
23110  *
23111  * The above restrictions allow us to support userland applications (which
23112  * will send down a single message block) and NFS over UDP (which will
23113  * send down a chain of at most three message blocks).
23114  *
23115  * We also don't use MDT for payloads with less than or equal to
23116  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23117  */
23118 boolean_t
23119 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23120 {
23121 	int	blocks;
23122 	ssize_t	total, missing, size;
23123 
23124 	ASSERT(mp != NULL);
23125 	ASSERT(hdr_len > 0);
23126 
23127 	size = MBLKL(mp) - hdr_len;
23128 	if (size <= 0)
23129 		return (B_FALSE);
23130 
23131 	/* The first mblk contains the header and some payload. */
23132 	blocks = 1;
23133 	total = size;
23134 	size %= len;
23135 	missing = (size == 0) ? 0 : (len - size);
23136 	mp = mp->b_cont;
23137 
23138 	while (mp != NULL) {
23139 		/*
23140 		 * Give up if we encounter a zero length message block.
23141 		 * In practice, this should rarely happen and therefore
23142 		 * not worth the trouble of freeing and re-linking the
23143 		 * mblk from the chain to handle such case.
23144 		 */
23145 		if ((size = MBLKL(mp)) == 0)
23146 			return (B_FALSE);
23147 
23148 		/* Too many payload buffers for a single Multidata message? */
23149 		if (++blocks > MULTIDATA_MAX_PBUFS)
23150 			return (B_FALSE);
23151 
23152 		total += size;
23153 		/* Is a frag distributed over two or more message blocks? */
23154 		if (missing > size)
23155 			return (B_FALSE);
23156 		size -= missing;
23157 
23158 		size %= len;
23159 		missing = (size == 0) ? 0 : (len - size);
23160 
23161 		mp = mp->b_cont;
23162 	}
23163 
23164 	return (total > ip_wput_frag_mdt_min);
23165 }
23166 
23167 /*
23168  * Outbound IPv4 fragmentation routine using MDT.
23169  */
23170 static void
23171 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23172     uint32_t frag_flag, int offset)
23173 {
23174 	ipha_t		*ipha_orig;
23175 	int		i1, ip_data_end;
23176 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23177 	mblk_t		*hdr_mp, *md_mp = NULL;
23178 	unsigned char	*hdr_ptr, *pld_ptr;
23179 	multidata_t	*mmd;
23180 	ip_pdescinfo_t	pdi;
23181 
23182 	ASSERT(DB_TYPE(mp) == M_DATA);
23183 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23184 
23185 	ipha_orig = (ipha_t *)mp->b_rptr;
23186 	mp->b_rptr += sizeof (ipha_t);
23187 
23188 	/* Calculate how many packets we will send out */
23189 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23190 	pkts = (i1 + len - 1) / len;
23191 	ASSERT(pkts > 1);
23192 
23193 	/* Allocate a message block which will hold all the IP Headers. */
23194 	wroff = ip_wroff_extra;
23195 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23196 
23197 	i1 = pkts * hdr_chunk_len;
23198 	/*
23199 	 * Create the header buffer, Multidata and destination address
23200 	 * and SAP attribute that should be associated with it.
23201 	 */
23202 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23203 	    ((hdr_mp->b_wptr += i1),
23204 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23205 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23206 		freemsg(mp);
23207 		if (md_mp == NULL) {
23208 			freemsg(hdr_mp);
23209 		} else {
23210 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23211 			freemsg(md_mp);
23212 		}
23213 		IP_STAT(ip_frag_mdt_allocfail);
23214 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23215 		return;
23216 	}
23217 	IP_STAT(ip_frag_mdt_allocd);
23218 
23219 	/*
23220 	 * Add a payload buffer to the Multidata; this operation must not
23221 	 * fail, or otherwise our logic in this routine is broken.  There
23222 	 * is no memory allocation done by the routine, so any returned
23223 	 * failure simply tells us that we've done something wrong.
23224 	 *
23225 	 * A failure tells us that either we're adding the same payload
23226 	 * buffer more than once, or we're trying to add more buffers than
23227 	 * allowed.  None of the above cases should happen, and we panic
23228 	 * because either there's horrible heap corruption, and/or
23229 	 * programming mistake.
23230 	 */
23231 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23232 		goto pbuf_panic;
23233 
23234 	hdr_ptr = hdr_mp->b_rptr;
23235 	pld_ptr = mp->b_rptr;
23236 
23237 	/* Establish the ending byte offset, based on the starting offset. */
23238 	offset <<= 3;
23239 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23240 	    IP_SIMPLE_HDR_LENGTH;
23241 
23242 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23243 
23244 	while (pld_ptr < mp->b_wptr) {
23245 		ipha_t		*ipha;
23246 		uint16_t	offset_and_flags;
23247 		uint16_t	ip_len;
23248 		int		error;
23249 
23250 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23251 		ipha = (ipha_t *)(hdr_ptr + wroff);
23252 		ASSERT(OK_32PTR(ipha));
23253 		*ipha = *ipha_orig;
23254 
23255 		if (ip_data_end - offset > len) {
23256 			offset_and_flags = IPH_MF;
23257 		} else {
23258 			/*
23259 			 * Last frag. Set len to the length of this last piece.
23260 			 */
23261 			len = ip_data_end - offset;
23262 			/* A frag of a frag might have IPH_MF non-zero */
23263 			offset_and_flags =
23264 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23265 			    IPH_MF;
23266 		}
23267 		offset_and_flags |= (uint16_t)(offset >> 3);
23268 		offset_and_flags |= (uint16_t)frag_flag;
23269 		/* Store the offset and flags in the IP header. */
23270 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23271 
23272 		/* Store the length in the IP header. */
23273 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23274 		ipha->ipha_length = htons(ip_len);
23275 
23276 		/*
23277 		 * Set the IP header checksum.  Note that mp is just
23278 		 * the header, so this is easy to pass to ip_csum.
23279 		 */
23280 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23281 
23282 		/*
23283 		 * Record offset and size of header and data of the next packet
23284 		 * in the multidata message.
23285 		 */
23286 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23287 		PDESC_PLD_INIT(&pdi);
23288 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23289 		ASSERT(i1 > 0);
23290 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23291 		if (i1 == len) {
23292 			pld_ptr += len;
23293 		} else {
23294 			i1 = len - i1;
23295 			mp = mp->b_cont;
23296 			ASSERT(mp != NULL);
23297 			ASSERT(MBLKL(mp) >= i1);
23298 			/*
23299 			 * Attach the next payload message block to the
23300 			 * multidata message.
23301 			 */
23302 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23303 				goto pbuf_panic;
23304 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23305 			pld_ptr = mp->b_rptr + i1;
23306 		}
23307 
23308 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23309 		    KM_NOSLEEP)) == NULL) {
23310 			/*
23311 			 * Any failure other than ENOMEM indicates that we
23312 			 * have passed in invalid pdesc info or parameters
23313 			 * to mmd_addpdesc, which must not happen.
23314 			 *
23315 			 * EINVAL is a result of failure on boundary checks
23316 			 * against the pdesc info contents.  It should not
23317 			 * happen, and we panic because either there's
23318 			 * horrible heap corruption, and/or programming
23319 			 * mistake.
23320 			 */
23321 			if (error != ENOMEM) {
23322 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23323 				    "pdesc logic error detected for "
23324 				    "mmd %p pinfo %p (%d)\n",
23325 				    (void *)mmd, (void *)&pdi, error);
23326 				/* NOTREACHED */
23327 			}
23328 			IP_STAT(ip_frag_mdt_addpdescfail);
23329 			/* Free unattached payload message blocks as well */
23330 			md_mp->b_cont = mp->b_cont;
23331 			goto free_mmd;
23332 		}
23333 
23334 		/* Advance fragment offset. */
23335 		offset += len;
23336 
23337 		/* Advance to location for next header in the buffer. */
23338 		hdr_ptr += hdr_chunk_len;
23339 
23340 		/* Did we reach the next payload message block? */
23341 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23342 			mp = mp->b_cont;
23343 			/*
23344 			 * Attach the next message block with payload
23345 			 * data to the multidata message.
23346 			 */
23347 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23348 				goto pbuf_panic;
23349 			pld_ptr = mp->b_rptr;
23350 		}
23351 	}
23352 
23353 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23354 	ASSERT(mp->b_wptr == pld_ptr);
23355 
23356 	/* Update IP statistics */
23357 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23358 	BUMP_MIB(&ip_mib, ipFragOKs);
23359 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23360 
23361 	if (pkt_type == OB_PKT) {
23362 		ire->ire_ob_pkt_count += pkts;
23363 		if (ire->ire_ipif != NULL)
23364 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23365 	} else {
23366 		/*
23367 		 * The type is IB_PKT in the forwarding path and in
23368 		 * the mobile IP case when the packet is being reverse-
23369 		 * tunneled to the home agent.
23370 		 */
23371 		ire->ire_ib_pkt_count += pkts;
23372 		ASSERT(!IRE_IS_LOCAL(ire));
23373 		if (ire->ire_type & IRE_BROADCAST)
23374 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23375 		else
23376 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23377 	}
23378 	ire->ire_last_used_time = lbolt;
23379 	/* Send it down */
23380 	putnext(ire->ire_stq, md_mp);
23381 	return;
23382 
23383 pbuf_panic:
23384 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23385 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23386 	    pbuf_idx);
23387 	/* NOTREACHED */
23388 }
23389 
23390 /*
23391  * Outbound IP fragmentation routine.
23392  *
23393  * NOTE : This routine does not ire_refrele the ire that is passed in
23394  * as the argument.
23395  */
23396 static void
23397 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23398     uint32_t frag_flag, zoneid_t zoneid)
23399 {
23400 	int		i1;
23401 	mblk_t		*ll_hdr_mp;
23402 	int 		ll_hdr_len;
23403 	int		hdr_len;
23404 	mblk_t		*hdr_mp;
23405 	ipha_t		*ipha;
23406 	int		ip_data_end;
23407 	int		len;
23408 	mblk_t		*mp = mp_orig, *mp1;
23409 	int		offset;
23410 	queue_t		*q;
23411 	uint32_t	v_hlen_tos_len;
23412 	mblk_t		*first_mp;
23413 	boolean_t	mctl_present;
23414 	ill_t		*ill;
23415 	ill_t		*out_ill;
23416 	mblk_t		*xmit_mp;
23417 	mblk_t		*carve_mp;
23418 	ire_t		*ire1 = NULL;
23419 	ire_t		*save_ire = NULL;
23420 	mblk_t  	*next_mp = NULL;
23421 	boolean_t	last_frag = B_FALSE;
23422 	boolean_t	multirt_send = B_FALSE;
23423 	ire_t		*first_ire = NULL;
23424 	irb_t		*irb = NULL;
23425 
23426 	/*
23427 	 * IPSEC does not allow hw accelerated packets to be fragmented
23428 	 * This check is made in ip_wput_ipsec_out prior to coming here
23429 	 * via ip_wput_ire_fragmentit.
23430 	 *
23431 	 * If at this point we have an ire whose ARP request has not
23432 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23433 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23434 	 * This packet and all fragmentable packets for this ire will
23435 	 * continue to get dropped while ire_nce->nce_state remains in
23436 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23437 	 * ND_REACHABLE, all subsquent large packets for this ire will
23438 	 * get fragemented and sent out by this function.
23439 	 */
23440 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23441 		/* If nce_state is ND_INITIAL, trigger ARP query */
23442 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23443 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23444 		    " -  dropping packet\n"));
23445 		BUMP_MIB(&ip_mib, ipFragFails);
23446 		freemsg(mp);
23447 		return;
23448 	}
23449 
23450 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23451 	    "ip_wput_frag_start:");
23452 
23453 	if (mp->b_datap->db_type == M_CTL) {
23454 		first_mp = mp;
23455 		mp_orig = mp = mp->b_cont;
23456 		mctl_present = B_TRUE;
23457 	} else {
23458 		first_mp = mp;
23459 		mctl_present = B_FALSE;
23460 	}
23461 
23462 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23463 	ipha = (ipha_t *)mp->b_rptr;
23464 
23465 	/*
23466 	 * If the Don't Fragment flag is on, generate an ICMP destination
23467 	 * unreachable, fragmentation needed.
23468 	 */
23469 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23470 	if (offset & IPH_DF) {
23471 		BUMP_MIB(&ip_mib, ipFragFails);
23472 		/*
23473 		 * Need to compute hdr checksum if called from ip_wput_ire.
23474 		 * Note that ip_rput_forward verifies the checksum before
23475 		 * calling this routine so in that case this is a noop.
23476 		 */
23477 		ipha->ipha_hdr_checksum = 0;
23478 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23479 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23480 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23481 		    "ip_wput_frag_end:(%S)",
23482 		    "don't fragment");
23483 		return;
23484 	}
23485 	if (mctl_present)
23486 		freeb(first_mp);
23487 	/*
23488 	 * Establish the starting offset.  May not be zero if we are fragging
23489 	 * a fragment that is being forwarded.
23490 	 */
23491 	offset = offset & IPH_OFFSET;
23492 
23493 	/* TODO why is this test needed? */
23494 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23495 	if (((max_frag - LENGTH) & ~7) < 8) {
23496 		/* TODO: notify ulp somehow */
23497 		BUMP_MIB(&ip_mib, ipFragFails);
23498 		freemsg(mp);
23499 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23500 		    "ip_wput_frag_end:(%S)",
23501 		    "len < 8");
23502 		return;
23503 	}
23504 
23505 	hdr_len = (V_HLEN & 0xF) << 2;
23506 
23507 	ipha->ipha_hdr_checksum = 0;
23508 
23509 	/*
23510 	 * Establish the number of bytes maximum per frag, after putting
23511 	 * in the header.
23512 	 */
23513 	len = (max_frag - hdr_len) & ~7;
23514 
23515 	/* Check if we can use MDT to send out the frags. */
23516 	ASSERT(!IRE_IS_LOCAL(ire));
23517 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23518 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23519 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23520 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23521 		ASSERT(ill->ill_mdt_capab != NULL);
23522 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23523 			/*
23524 			 * If MDT has been previously turned off in the past,
23525 			 * and we currently can do MDT (due to IPQoS policy
23526 			 * removal, etc.) then enable it for this interface.
23527 			 */
23528 			ill->ill_mdt_capab->ill_mdt_on = 1;
23529 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23530 			    ill->ill_name));
23531 		}
23532 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23533 		    offset);
23534 		return;
23535 	}
23536 
23537 	/* Get a copy of the header for the trailing frags */
23538 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23539 	if (!hdr_mp) {
23540 		BUMP_MIB(&ip_mib, ipOutDiscards);
23541 		freemsg(mp);
23542 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23543 		    "ip_wput_frag_end:(%S)",
23544 		    "couldn't copy hdr");
23545 		return;
23546 	}
23547 	if (DB_CRED(mp) != NULL)
23548 		mblk_setcred(hdr_mp, DB_CRED(mp));
23549 
23550 	/* Store the starting offset, with the MoreFrags flag. */
23551 	i1 = offset | IPH_MF | frag_flag;
23552 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23553 
23554 	/* Establish the ending byte offset, based on the starting offset. */
23555 	offset <<= 3;
23556 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23557 
23558 	/* Store the length of the first fragment in the IP header. */
23559 	i1 = len + hdr_len;
23560 	ASSERT(i1 <= IP_MAXPACKET);
23561 	ipha->ipha_length = htons((uint16_t)i1);
23562 
23563 	/*
23564 	 * Compute the IP header checksum for the first frag.  We have to
23565 	 * watch out that we stop at the end of the header.
23566 	 */
23567 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23568 
23569 	/*
23570 	 * Now carve off the first frag.  Note that this will include the
23571 	 * original IP header.
23572 	 */
23573 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23574 		BUMP_MIB(&ip_mib, ipOutDiscards);
23575 		freeb(hdr_mp);
23576 		freemsg(mp_orig);
23577 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23578 		    "ip_wput_frag_end:(%S)",
23579 		    "couldn't carve first");
23580 		return;
23581 	}
23582 
23583 	/*
23584 	 * Multirouting case. Each fragment is replicated
23585 	 * via all non-condemned RTF_MULTIRT routes
23586 	 * currently resolved.
23587 	 * We ensure that first_ire is the first RTF_MULTIRT
23588 	 * ire in the bucket.
23589 	 */
23590 	if (ire->ire_flags & RTF_MULTIRT) {
23591 		irb = ire->ire_bucket;
23592 		ASSERT(irb != NULL);
23593 
23594 		multirt_send = B_TRUE;
23595 
23596 		/* Make sure we do not omit any multiroute ire. */
23597 		IRB_REFHOLD(irb);
23598 		for (first_ire = irb->irb_ire;
23599 		    first_ire != NULL;
23600 		    first_ire = first_ire->ire_next) {
23601 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23602 			    (first_ire->ire_addr == ire->ire_addr) &&
23603 			    !(first_ire->ire_marks &
23604 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23605 				break;
23606 		}
23607 
23608 		if (first_ire != NULL) {
23609 			if (first_ire != ire) {
23610 				IRE_REFHOLD(first_ire);
23611 				/*
23612 				 * Do not release the ire passed in
23613 				 * as the argument.
23614 				 */
23615 				ire = first_ire;
23616 			} else {
23617 				first_ire = NULL;
23618 			}
23619 		}
23620 		IRB_REFRELE(irb);
23621 
23622 		/*
23623 		 * Save the first ire; we will need to restore it
23624 		 * for the trailing frags.
23625 		 * We REFHOLD save_ire, as each iterated ire will be
23626 		 * REFRELEd.
23627 		 */
23628 		save_ire = ire;
23629 		IRE_REFHOLD(save_ire);
23630 	}
23631 
23632 	/*
23633 	 * First fragment emission loop.
23634 	 * In most cases, the emission loop below is entered only
23635 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23636 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23637 	 * bucket, and send the fragment through all crossed
23638 	 * RTF_MULTIRT routes.
23639 	 */
23640 	do {
23641 		if (ire->ire_flags & RTF_MULTIRT) {
23642 			/*
23643 			 * We are in a multiple send case, need to get
23644 			 * the next ire and make a copy of the packet.
23645 			 * ire1 holds here the next ire to process in the
23646 			 * bucket. If multirouting is expected,
23647 			 * any non-RTF_MULTIRT ire that has the
23648 			 * right destination address is ignored.
23649 			 *
23650 			 * We have to take into account the MTU of
23651 			 * each walked ire. max_frag is set by the
23652 			 * the caller and generally refers to
23653 			 * the primary ire entry. Here we ensure that
23654 			 * no route with a lower MTU will be used, as
23655 			 * fragments are carved once for all ires,
23656 			 * then replicated.
23657 			 */
23658 			ASSERT(irb != NULL);
23659 			IRB_REFHOLD(irb);
23660 			for (ire1 = ire->ire_next;
23661 			    ire1 != NULL;
23662 			    ire1 = ire1->ire_next) {
23663 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23664 					continue;
23665 				if (ire1->ire_addr != ire->ire_addr)
23666 					continue;
23667 				if (ire1->ire_marks &
23668 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23669 					continue;
23670 				/*
23671 				 * Ensure we do not exceed the MTU
23672 				 * of the next route.
23673 				 */
23674 				if (ire1->ire_max_frag < max_frag) {
23675 					ip_multirt_bad_mtu(ire1, max_frag);
23676 					continue;
23677 				}
23678 
23679 				/* Got one. */
23680 				IRE_REFHOLD(ire1);
23681 				break;
23682 			}
23683 			IRB_REFRELE(irb);
23684 
23685 			if (ire1 != NULL) {
23686 				next_mp = copyb(mp);
23687 				if ((next_mp == NULL) ||
23688 				    ((mp->b_cont != NULL) &&
23689 				    ((next_mp->b_cont =
23690 				    dupmsg(mp->b_cont)) == NULL))) {
23691 					freemsg(next_mp);
23692 					next_mp = NULL;
23693 					ire_refrele(ire1);
23694 					ire1 = NULL;
23695 				}
23696 			}
23697 
23698 			/* Last multiroute ire; don't loop anymore. */
23699 			if (ire1 == NULL) {
23700 				multirt_send = B_FALSE;
23701 			}
23702 		}
23703 
23704 		ll_hdr_len = 0;
23705 		LOCK_IRE_FP_MP(ire);
23706 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23707 		if (ll_hdr_mp != NULL) {
23708 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23709 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23710 		} else {
23711 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23712 		}
23713 
23714 		/* If there is a transmit header, get a copy for this frag. */
23715 		/*
23716 		 * TODO: should check db_ref before calling ip_carve_mp since
23717 		 * it might give us a dup.
23718 		 */
23719 		if (!ll_hdr_mp) {
23720 			/* No xmit header. */
23721 			xmit_mp = mp;
23722 
23723 		/* We have a link-layer header that can fit in our mblk. */
23724 		} else if (mp->b_datap->db_ref == 1 &&
23725 		    ll_hdr_len != 0 &&
23726 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23727 			/* M_DATA fastpath */
23728 			mp->b_rptr -= ll_hdr_len;
23729 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23730 			xmit_mp = mp;
23731 
23732 		/* Corner case if copyb has failed */
23733 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23734 			UNLOCK_IRE_FP_MP(ire);
23735 			BUMP_MIB(&ip_mib, ipOutDiscards);
23736 			freeb(hdr_mp);
23737 			freemsg(mp);
23738 			freemsg(mp_orig);
23739 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23740 			    "ip_wput_frag_end:(%S)",
23741 			    "discard");
23742 
23743 			if (multirt_send) {
23744 				ASSERT(ire1);
23745 				ASSERT(next_mp);
23746 
23747 				freemsg(next_mp);
23748 				ire_refrele(ire1);
23749 			}
23750 			if (save_ire != NULL)
23751 				IRE_REFRELE(save_ire);
23752 
23753 			if (first_ire != NULL)
23754 				ire_refrele(first_ire);
23755 			return;
23756 
23757 		/*
23758 		 * Case of res_mp OR the fastpath mp can't fit
23759 		 * in the mblk
23760 		 */
23761 		} else {
23762 			xmit_mp->b_cont = mp;
23763 			if (DB_CRED(mp) != NULL)
23764 				mblk_setcred(xmit_mp, DB_CRED(mp));
23765 			/*
23766 			 * Get priority marking, if any.
23767 			 * We propagate the CoS marking from the
23768 			 * original packet that went to QoS processing
23769 			 * in ip_wput_ire to the newly carved mp.
23770 			 */
23771 			if (DB_TYPE(xmit_mp) == M_DATA)
23772 				xmit_mp->b_band = mp->b_band;
23773 		}
23774 		UNLOCK_IRE_FP_MP(ire);
23775 		q = ire->ire_stq;
23776 		BUMP_MIB(&ip_mib, ipFragCreates);
23777 
23778 		out_ill = (ill_t *)q->q_ptr;
23779 
23780 		DTRACE_PROBE4(ip4__physical__out__start,
23781 		    ill_t *, NULL, ill_t *, out_ill,
23782 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23783 
23784 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23785 		    NULL, out_ill, ipha, xmit_mp, mp);
23786 
23787 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23788 
23789 		if (xmit_mp != NULL) {
23790 			putnext(q, xmit_mp);
23791 			if (pkt_type != OB_PKT) {
23792 				/*
23793 				 * Update the packet count of trailing
23794 				 * RTF_MULTIRT ires.
23795 				 */
23796 				UPDATE_OB_PKT_COUNT(ire);
23797 			}
23798 		}
23799 
23800 		if (multirt_send) {
23801 			/*
23802 			 * We are in a multiple send case; look for
23803 			 * the next ire and re-enter the loop.
23804 			 */
23805 			ASSERT(ire1);
23806 			ASSERT(next_mp);
23807 			/* REFRELE the current ire before looping */
23808 			ire_refrele(ire);
23809 			ire = ire1;
23810 			ire1 = NULL;
23811 			mp = next_mp;
23812 			next_mp = NULL;
23813 		}
23814 	} while (multirt_send);
23815 
23816 	ASSERT(ire1 == NULL);
23817 
23818 	/* Restore the original ire; we need it for the trailing frags */
23819 	if (save_ire != NULL) {
23820 		/* REFRELE the last iterated ire */
23821 		ire_refrele(ire);
23822 		/* save_ire has been REFHOLDed */
23823 		ire = save_ire;
23824 		save_ire = NULL;
23825 		q = ire->ire_stq;
23826 	}
23827 
23828 	if (pkt_type == OB_PKT) {
23829 		UPDATE_OB_PKT_COUNT(ire);
23830 	} else {
23831 		UPDATE_IB_PKT_COUNT(ire);
23832 	}
23833 
23834 	/* Advance the offset to the second frag starting point. */
23835 	offset += len;
23836 	/*
23837 	 * Update hdr_len from the copied header - there might be less options
23838 	 * in the later fragments.
23839 	 */
23840 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23841 	/* Loop until done. */
23842 	for (;;) {
23843 		uint16_t	offset_and_flags;
23844 		uint16_t	ip_len;
23845 
23846 		if (ip_data_end - offset > len) {
23847 			/*
23848 			 * Carve off the appropriate amount from the original
23849 			 * datagram.
23850 			 */
23851 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23852 				mp = NULL;
23853 				break;
23854 			}
23855 			/*
23856 			 * More frags after this one.  Get another copy
23857 			 * of the header.
23858 			 */
23859 			if (carve_mp->b_datap->db_ref == 1 &&
23860 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23861 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23862 				/* Inline IP header */
23863 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23864 				    hdr_mp->b_rptr;
23865 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23866 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23867 				mp = carve_mp;
23868 			} else {
23869 				if (!(mp = copyb(hdr_mp))) {
23870 					freemsg(carve_mp);
23871 					break;
23872 				}
23873 				/* Get priority marking, if any. */
23874 				mp->b_band = carve_mp->b_band;
23875 				mp->b_cont = carve_mp;
23876 			}
23877 			ipha = (ipha_t *)mp->b_rptr;
23878 			offset_and_flags = IPH_MF;
23879 		} else {
23880 			/*
23881 			 * Last frag.  Consume the header. Set len to
23882 			 * the length of this last piece.
23883 			 */
23884 			len = ip_data_end - offset;
23885 
23886 			/*
23887 			 * Carve off the appropriate amount from the original
23888 			 * datagram.
23889 			 */
23890 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23891 				mp = NULL;
23892 				break;
23893 			}
23894 			if (carve_mp->b_datap->db_ref == 1 &&
23895 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23896 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23897 				/* Inline IP header */
23898 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23899 				    hdr_mp->b_rptr;
23900 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23901 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23902 				mp = carve_mp;
23903 				freeb(hdr_mp);
23904 				hdr_mp = mp;
23905 			} else {
23906 				mp = hdr_mp;
23907 				/* Get priority marking, if any. */
23908 				mp->b_band = carve_mp->b_band;
23909 				mp->b_cont = carve_mp;
23910 			}
23911 			ipha = (ipha_t *)mp->b_rptr;
23912 			/* A frag of a frag might have IPH_MF non-zero */
23913 			offset_and_flags =
23914 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23915 			    IPH_MF;
23916 		}
23917 		offset_and_flags |= (uint16_t)(offset >> 3);
23918 		offset_and_flags |= (uint16_t)frag_flag;
23919 		/* Store the offset and flags in the IP header. */
23920 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23921 
23922 		/* Store the length in the IP header. */
23923 		ip_len = (uint16_t)(len + hdr_len);
23924 		ipha->ipha_length = htons(ip_len);
23925 
23926 		/*
23927 		 * Set the IP header checksum.	Note that mp is just
23928 		 * the header, so this is easy to pass to ip_csum.
23929 		 */
23930 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23931 
23932 		/* Attach a transmit header, if any, and ship it. */
23933 		if (pkt_type == OB_PKT) {
23934 			UPDATE_OB_PKT_COUNT(ire);
23935 		} else {
23936 			UPDATE_IB_PKT_COUNT(ire);
23937 		}
23938 
23939 		if (ire->ire_flags & RTF_MULTIRT) {
23940 			irb = ire->ire_bucket;
23941 			ASSERT(irb != NULL);
23942 
23943 			multirt_send = B_TRUE;
23944 
23945 			/*
23946 			 * Save the original ire; we will need to restore it
23947 			 * for the tailing frags.
23948 			 */
23949 			save_ire = ire;
23950 			IRE_REFHOLD(save_ire);
23951 		}
23952 		/*
23953 		 * Emission loop for this fragment, similar
23954 		 * to what is done for the first fragment.
23955 		 */
23956 		do {
23957 			if (multirt_send) {
23958 				/*
23959 				 * We are in a multiple send case, need to get
23960 				 * the next ire and make a copy of the packet.
23961 				 */
23962 				ASSERT(irb != NULL);
23963 				IRB_REFHOLD(irb);
23964 				for (ire1 = ire->ire_next;
23965 				    ire1 != NULL;
23966 				    ire1 = ire1->ire_next) {
23967 					if (!(ire1->ire_flags & RTF_MULTIRT))
23968 						continue;
23969 					if (ire1->ire_addr != ire->ire_addr)
23970 						continue;
23971 					if (ire1->ire_marks &
23972 					    (IRE_MARK_CONDEMNED|
23973 						IRE_MARK_HIDDEN))
23974 						continue;
23975 					/*
23976 					 * Ensure we do not exceed the MTU
23977 					 * of the next route.
23978 					 */
23979 					if (ire1->ire_max_frag < max_frag) {
23980 						ip_multirt_bad_mtu(ire1,
23981 						    max_frag);
23982 						continue;
23983 					}
23984 
23985 					/* Got one. */
23986 					IRE_REFHOLD(ire1);
23987 					break;
23988 				}
23989 				IRB_REFRELE(irb);
23990 
23991 				if (ire1 != NULL) {
23992 					next_mp = copyb(mp);
23993 					if ((next_mp == NULL) ||
23994 					    ((mp->b_cont != NULL) &&
23995 					    ((next_mp->b_cont =
23996 					    dupmsg(mp->b_cont)) == NULL))) {
23997 						freemsg(next_mp);
23998 						next_mp = NULL;
23999 						ire_refrele(ire1);
24000 						ire1 = NULL;
24001 					}
24002 				}
24003 
24004 				/* Last multiroute ire; don't loop anymore. */
24005 				if (ire1 == NULL) {
24006 					multirt_send = B_FALSE;
24007 				}
24008 			}
24009 
24010 			/* Update transmit header */
24011 			ll_hdr_len = 0;
24012 			LOCK_IRE_FP_MP(ire);
24013 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24014 			if (ll_hdr_mp != NULL) {
24015 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24016 				ll_hdr_len = MBLKL(ll_hdr_mp);
24017 			} else {
24018 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24019 			}
24020 
24021 			if (!ll_hdr_mp) {
24022 				xmit_mp = mp;
24023 
24024 			/*
24025 			 * We have link-layer header that can fit in
24026 			 * our mblk.
24027 			 */
24028 			} else if (mp->b_datap->db_ref == 1 &&
24029 			    ll_hdr_len != 0 &&
24030 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24031 				/* M_DATA fastpath */
24032 				mp->b_rptr -= ll_hdr_len;
24033 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24034 				    ll_hdr_len);
24035 				xmit_mp = mp;
24036 
24037 			/*
24038 			 * Case of res_mp OR the fastpath mp can't fit
24039 			 * in the mblk
24040 			 */
24041 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24042 				xmit_mp->b_cont = mp;
24043 				if (DB_CRED(mp) != NULL)
24044 					mblk_setcred(xmit_mp, DB_CRED(mp));
24045 				/* Get priority marking, if any. */
24046 				if (DB_TYPE(xmit_mp) == M_DATA)
24047 					xmit_mp->b_band = mp->b_band;
24048 
24049 			/* Corner case if copyb failed */
24050 			} else {
24051 				/*
24052 				 * Exit both the replication and
24053 				 * fragmentation loops.
24054 				 */
24055 				UNLOCK_IRE_FP_MP(ire);
24056 				goto drop_pkt;
24057 			}
24058 			UNLOCK_IRE_FP_MP(ire);
24059 			BUMP_MIB(&ip_mib, ipFragCreates);
24060 
24061 			mp1 = mp;
24062 			out_ill = (ill_t *)q->q_ptr;
24063 
24064 			DTRACE_PROBE4(ip4__physical__out__start,
24065 			    ill_t *, NULL, ill_t *, out_ill,
24066 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24067 
24068 			FW_HOOKS(ip4_physical_out_event,
24069 			    ipv4firewall_physical_out,
24070 			    NULL, out_ill, ipha, xmit_mp, mp);
24071 
24072 			DTRACE_PROBE1(ip4__physical__out__end,
24073 			    mblk_t *, xmit_mp);
24074 
24075 			if (mp != mp1 && hdr_mp == mp1)
24076 				hdr_mp = mp;
24077 			if (mp != mp1 && mp_orig == mp1)
24078 				mp_orig = mp;
24079 
24080 			if (xmit_mp != NULL) {
24081 				putnext(q, xmit_mp);
24082 
24083 				if (pkt_type != OB_PKT) {
24084 					/*
24085 					 * Update the packet count of trailing
24086 					 * RTF_MULTIRT ires.
24087 					 */
24088 					UPDATE_OB_PKT_COUNT(ire);
24089 				}
24090 			}
24091 
24092 			/* All done if we just consumed the hdr_mp. */
24093 			if (mp == hdr_mp) {
24094 				last_frag = B_TRUE;
24095 			}
24096 
24097 			if (multirt_send) {
24098 				/*
24099 				 * We are in a multiple send case; look for
24100 				 * the next ire and re-enter the loop.
24101 				 */
24102 				ASSERT(ire1);
24103 				ASSERT(next_mp);
24104 				/* REFRELE the current ire before looping */
24105 				ire_refrele(ire);
24106 				ire = ire1;
24107 				ire1 = NULL;
24108 				q = ire->ire_stq;
24109 				mp = next_mp;
24110 				next_mp = NULL;
24111 			}
24112 		} while (multirt_send);
24113 		/*
24114 		 * Restore the original ire; we need it for the
24115 		 * trailing frags
24116 		 */
24117 		if (save_ire != NULL) {
24118 			ASSERT(ire1 == NULL);
24119 			/* REFRELE the last iterated ire */
24120 			ire_refrele(ire);
24121 			/* save_ire has been REFHOLDed */
24122 			ire = save_ire;
24123 			q = ire->ire_stq;
24124 			save_ire = NULL;
24125 		}
24126 
24127 		if (last_frag) {
24128 			BUMP_MIB(&ip_mib, ipFragOKs);
24129 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24130 			    "ip_wput_frag_end:(%S)",
24131 			    "consumed hdr_mp");
24132 
24133 			if (first_ire != NULL)
24134 				ire_refrele(first_ire);
24135 			return;
24136 		}
24137 		/* Otherwise, advance and loop. */
24138 		offset += len;
24139 	}
24140 
24141 drop_pkt:
24142 	/* Clean up following allocation failure. */
24143 	BUMP_MIB(&ip_mib, ipOutDiscards);
24144 	freemsg(mp);
24145 	if (mp != hdr_mp)
24146 		freeb(hdr_mp);
24147 	if (mp != mp_orig)
24148 		freemsg(mp_orig);
24149 
24150 	if (save_ire != NULL)
24151 		IRE_REFRELE(save_ire);
24152 	if (first_ire != NULL)
24153 		ire_refrele(first_ire);
24154 
24155 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24156 	    "ip_wput_frag_end:(%S)",
24157 	    "end--alloc failure");
24158 }
24159 
24160 /*
24161  * Copy the header plus those options which have the copy bit set
24162  */
24163 static mblk_t *
24164 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24165 {
24166 	mblk_t	*mp;
24167 	uchar_t	*up;
24168 
24169 	/*
24170 	 * Quick check if we need to look for options without the copy bit
24171 	 * set
24172 	 */
24173 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24174 	if (!mp)
24175 		return (mp);
24176 	mp->b_rptr += ip_wroff_extra;
24177 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24178 		bcopy(rptr, mp->b_rptr, hdr_len);
24179 		mp->b_wptr += hdr_len + ip_wroff_extra;
24180 		return (mp);
24181 	}
24182 	up  = mp->b_rptr;
24183 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24184 	up += IP_SIMPLE_HDR_LENGTH;
24185 	rptr += IP_SIMPLE_HDR_LENGTH;
24186 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24187 	while (hdr_len > 0) {
24188 		uint32_t optval;
24189 		uint32_t optlen;
24190 
24191 		optval = *rptr;
24192 		if (optval == IPOPT_EOL)
24193 			break;
24194 		if (optval == IPOPT_NOP)
24195 			optlen = 1;
24196 		else
24197 			optlen = rptr[1];
24198 		if (optval & IPOPT_COPY) {
24199 			bcopy(rptr, up, optlen);
24200 			up += optlen;
24201 		}
24202 		rptr += optlen;
24203 		hdr_len -= optlen;
24204 	}
24205 	/*
24206 	 * Make sure that we drop an even number of words by filling
24207 	 * with EOL to the next word boundary.
24208 	 */
24209 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24210 	    hdr_len & 0x3; hdr_len++)
24211 		*up++ = IPOPT_EOL;
24212 	mp->b_wptr = up;
24213 	/* Update header length */
24214 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24215 	return (mp);
24216 }
24217 
24218 /*
24219  * Delivery to local recipients including fanout to multiple recipients.
24220  * Does not do checksumming of UDP/TCP.
24221  * Note: q should be the read side queue for either the ill or conn.
24222  * Note: rq should be the read side q for the lower (ill) stream.
24223  * We don't send packets to IPPF processing, thus the last argument
24224  * to all the fanout calls are B_FALSE.
24225  */
24226 void
24227 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24228     int fanout_flags, zoneid_t zoneid)
24229 {
24230 	uint32_t	protocol;
24231 	mblk_t		*first_mp;
24232 	boolean_t	mctl_present;
24233 	int		ire_type;
24234 #define	rptr	((uchar_t *)ipha)
24235 
24236 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24237 	    "ip_wput_local_start: q %p", q);
24238 
24239 	if (ire != NULL) {
24240 		ire_type = ire->ire_type;
24241 	} else {
24242 		/*
24243 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24244 		 * packet is not multicast, we can't tell the ire type.
24245 		 */
24246 		ASSERT(CLASSD(ipha->ipha_dst));
24247 		ire_type = IRE_BROADCAST;
24248 	}
24249 
24250 	first_mp = mp;
24251 	if (first_mp->b_datap->db_type == M_CTL) {
24252 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24253 		if (!io->ipsec_out_secure) {
24254 			/*
24255 			 * This ipsec_out_t was allocated in ip_wput
24256 			 * for multicast packets to store the ill_index.
24257 			 * As this is being delivered locally, we don't
24258 			 * need this anymore.
24259 			 */
24260 			mp = first_mp->b_cont;
24261 			freeb(first_mp);
24262 			first_mp = mp;
24263 			mctl_present = B_FALSE;
24264 		} else {
24265 			/*
24266 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24267 			 * security properties for the looped-back packet.
24268 			 */
24269 			mctl_present = B_TRUE;
24270 			mp = first_mp->b_cont;
24271 			ASSERT(mp != NULL);
24272 			ipsec_out_to_in(first_mp);
24273 		}
24274 	} else {
24275 		mctl_present = B_FALSE;
24276 	}
24277 
24278 	DTRACE_PROBE4(ip4__loopback__in__start,
24279 	    ill_t *, ill, ill_t *, NULL,
24280 	    ipha_t *, ipha, mblk_t *, first_mp);
24281 
24282 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24283 	    ill, NULL, ipha, first_mp, mp);
24284 
24285 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24286 
24287 	if (first_mp == NULL)
24288 		return;
24289 
24290 	loopback_packets++;
24291 
24292 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24293 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24294 	if (!IS_SIMPLE_IPH(ipha)) {
24295 		ip_wput_local_options(ipha);
24296 	}
24297 
24298 	protocol = ipha->ipha_protocol;
24299 	switch (protocol) {
24300 	case IPPROTO_ICMP: {
24301 		ire_t		*ire_zone;
24302 		ilm_t		*ilm;
24303 		mblk_t		*mp1;
24304 		zoneid_t	last_zoneid;
24305 
24306 		if (CLASSD(ipha->ipha_dst) &&
24307 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24308 			ASSERT(ire_type == IRE_BROADCAST);
24309 			/*
24310 			 * In the multicast case, applications may have joined
24311 			 * the group from different zones, so we need to deliver
24312 			 * the packet to each of them. Loop through the
24313 			 * multicast memberships structures (ilm) on the receive
24314 			 * ill and send a copy of the packet up each matching
24315 			 * one. However, we don't do this for multicasts sent on
24316 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24317 			 * they must stay in the sender's zone.
24318 			 *
24319 			 * ilm_add_v6() ensures that ilms in the same zone are
24320 			 * contiguous in the ill_ilm list. We use this property
24321 			 * to avoid sending duplicates needed when two
24322 			 * applications in the same zone join the same group on
24323 			 * different logical interfaces: we ignore the ilm if
24324 			 * it's zoneid is the same as the last matching one.
24325 			 * In addition, the sending of the packet for
24326 			 * ire_zoneid is delayed until all of the other ilms
24327 			 * have been exhausted.
24328 			 */
24329 			last_zoneid = -1;
24330 			ILM_WALKER_HOLD(ill);
24331 			for (ilm = ill->ill_ilm; ilm != NULL;
24332 			    ilm = ilm->ilm_next) {
24333 				if ((ilm->ilm_flags & ILM_DELETED) ||
24334 				    ipha->ipha_dst != ilm->ilm_addr ||
24335 				    ilm->ilm_zoneid == last_zoneid ||
24336 				    ilm->ilm_zoneid == zoneid ||
24337 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24338 					continue;
24339 				mp1 = ip_copymsg(first_mp);
24340 				if (mp1 == NULL)
24341 					continue;
24342 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24343 				    mctl_present, B_FALSE, ill,
24344 				    ilm->ilm_zoneid);
24345 				last_zoneid = ilm->ilm_zoneid;
24346 			}
24347 			ILM_WALKER_RELE(ill);
24348 			/*
24349 			 * Loopback case: the sending endpoint has
24350 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24351 			 * dispatch the multicast packet to the sending zone.
24352 			 */
24353 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24354 				freemsg(first_mp);
24355 				return;
24356 			}
24357 		} else if (ire_type == IRE_BROADCAST) {
24358 			/*
24359 			 * In the broadcast case, there may be many zones
24360 			 * which need a copy of the packet delivered to them.
24361 			 * There is one IRE_BROADCAST per broadcast address
24362 			 * and per zone; we walk those using a helper function.
24363 			 * In addition, the sending of the packet for zoneid is
24364 			 * delayed until all of the other ires have been
24365 			 * processed.
24366 			 */
24367 			IRB_REFHOLD(ire->ire_bucket);
24368 			ire_zone = NULL;
24369 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24370 			    ire)) != NULL) {
24371 				mp1 = ip_copymsg(first_mp);
24372 				if (mp1 == NULL)
24373 					continue;
24374 
24375 				UPDATE_IB_PKT_COUNT(ire_zone);
24376 				ire_zone->ire_last_used_time = lbolt;
24377 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24378 				    mctl_present, B_FALSE, ill,
24379 				    ire_zone->ire_zoneid);
24380 			}
24381 			IRB_REFRELE(ire->ire_bucket);
24382 		}
24383 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24384 		    0, mctl_present, B_FALSE, ill, zoneid);
24385 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24386 		    "ip_wput_local_end: q %p (%S)",
24387 		    q, "icmp");
24388 		return;
24389 	}
24390 	case IPPROTO_IGMP:
24391 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24392 			/* Bad packet - discarded by igmp_input */
24393 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24394 			    "ip_wput_local_end: q %p (%S)",
24395 			    q, "igmp_input--bad packet");
24396 			if (mctl_present)
24397 				freeb(first_mp);
24398 			return;
24399 		}
24400 		/*
24401 		 * igmp_input() may have returned the pulled up message.
24402 		 * So first_mp and ipha need to be reinitialized.
24403 		 */
24404 		ipha = (ipha_t *)mp->b_rptr;
24405 		if (mctl_present)
24406 			first_mp->b_cont = mp;
24407 		else
24408 			first_mp = mp;
24409 		/* deliver to local raw users */
24410 		break;
24411 	case IPPROTO_ENCAP:
24412 		/*
24413 		 * This case is covered by either ip_fanout_proto, or by
24414 		 * the above security processing for self-tunneled packets.
24415 		 */
24416 		break;
24417 	case IPPROTO_UDP: {
24418 		uint16_t	*up;
24419 		uint32_t	ports;
24420 
24421 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24422 		    UDP_PORTS_OFFSET);
24423 		/* Force a 'valid' checksum. */
24424 		up[3] = 0;
24425 
24426 		ports = *(uint32_t *)up;
24427 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24428 		    (ire_type == IRE_BROADCAST),
24429 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24430 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24431 		    ill, zoneid);
24432 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24433 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24434 		return;
24435 	}
24436 	case IPPROTO_TCP: {
24437 
24438 		/*
24439 		 * For TCP, discard broadcast packets.
24440 		 */
24441 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24442 			freemsg(first_mp);
24443 			BUMP_MIB(&ip_mib, ipInDiscards);
24444 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24445 			return;
24446 		}
24447 
24448 		if (mp->b_datap->db_type == M_DATA) {
24449 			/*
24450 			 * M_DATA mblk, so init mblk (chain) for no struio().
24451 			 */
24452 			mblk_t	*mp1 = mp;
24453 
24454 			do
24455 				mp1->b_datap->db_struioflag = 0;
24456 			while ((mp1 = mp1->b_cont) != NULL);
24457 		}
24458 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24459 		    <= mp->b_wptr);
24460 		ip_fanout_tcp(q, first_mp, ill, ipha,
24461 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24462 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24463 		    mctl_present, B_FALSE, zoneid);
24464 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24465 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24466 		return;
24467 	}
24468 	case IPPROTO_SCTP:
24469 	{
24470 		uint32_t	ports;
24471 
24472 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24473 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24474 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24475 		    IP_FF_IP6INFO,
24476 		    mctl_present, B_FALSE, 0, zoneid);
24477 		return;
24478 	}
24479 
24480 	default:
24481 		break;
24482 	}
24483 	/*
24484 	 * Find a client for some other protocol.  We give
24485 	 * copies to multiple clients, if more than one is
24486 	 * bound.
24487 	 */
24488 	ip_fanout_proto(q, first_mp, ill, ipha,
24489 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24490 	    mctl_present, B_FALSE, ill, zoneid);
24491 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24492 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24493 #undef	rptr
24494 }
24495 
24496 /*
24497  * Update any source route, record route, or timestamp options.
24498  * Check that we are at end of strict source route.
24499  * The options have been sanity checked by ip_wput_options().
24500  */
24501 static void
24502 ip_wput_local_options(ipha_t *ipha)
24503 {
24504 	ipoptp_t	opts;
24505 	uchar_t		*opt;
24506 	uint8_t		optval;
24507 	uint8_t		optlen;
24508 	ipaddr_t	dst;
24509 	uint32_t	ts;
24510 	ire_t		*ire;
24511 	timestruc_t	now;
24512 
24513 	ip2dbg(("ip_wput_local_options\n"));
24514 	for (optval = ipoptp_first(&opts, ipha);
24515 	    optval != IPOPT_EOL;
24516 	    optval = ipoptp_next(&opts)) {
24517 		opt = opts.ipoptp_cur;
24518 		optlen = opts.ipoptp_len;
24519 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24520 		switch (optval) {
24521 			uint32_t off;
24522 		case IPOPT_SSRR:
24523 		case IPOPT_LSRR:
24524 			off = opt[IPOPT_OFFSET];
24525 			off--;
24526 			if (optlen < IP_ADDR_LEN ||
24527 			    off > optlen - IP_ADDR_LEN) {
24528 				/* End of source route */
24529 				break;
24530 			}
24531 			/*
24532 			 * This will only happen if two consecutive entries
24533 			 * in the source route contains our address or if
24534 			 * it is a packet with a loose source route which
24535 			 * reaches us before consuming the whole source route
24536 			 */
24537 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24538 			if (optval == IPOPT_SSRR) {
24539 				return;
24540 			}
24541 			/*
24542 			 * Hack: instead of dropping the packet truncate the
24543 			 * source route to what has been used by filling the
24544 			 * rest with IPOPT_NOP.
24545 			 */
24546 			opt[IPOPT_OLEN] = (uint8_t)off;
24547 			while (off < optlen) {
24548 				opt[off++] = IPOPT_NOP;
24549 			}
24550 			break;
24551 		case IPOPT_RR:
24552 			off = opt[IPOPT_OFFSET];
24553 			off--;
24554 			if (optlen < IP_ADDR_LEN ||
24555 			    off > optlen - IP_ADDR_LEN) {
24556 				/* No more room - ignore */
24557 				ip1dbg((
24558 				    "ip_wput_forward_options: end of RR\n"));
24559 				break;
24560 			}
24561 			dst = htonl(INADDR_LOOPBACK);
24562 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24563 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24564 			break;
24565 		case IPOPT_TS:
24566 			/* Insert timestamp if there is romm */
24567 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24568 			case IPOPT_TS_TSONLY:
24569 				off = IPOPT_TS_TIMELEN;
24570 				break;
24571 			case IPOPT_TS_PRESPEC:
24572 			case IPOPT_TS_PRESPEC_RFC791:
24573 				/* Verify that the address matched */
24574 				off = opt[IPOPT_OFFSET] - 1;
24575 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24576 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24577 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24578 				if (ire == NULL) {
24579 					/* Not for us */
24580 					break;
24581 				}
24582 				ire_refrele(ire);
24583 				/* FALLTHRU */
24584 			case IPOPT_TS_TSANDADDR:
24585 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24586 				break;
24587 			default:
24588 				/*
24589 				 * ip_*put_options should have already
24590 				 * dropped this packet.
24591 				 */
24592 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24593 				    "unknown IT - bug in ip_wput_options?\n");
24594 				return;	/* Keep "lint" happy */
24595 			}
24596 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24597 				/* Increase overflow counter */
24598 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24599 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24600 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24601 				    (off << 4);
24602 				break;
24603 			}
24604 			off = opt[IPOPT_OFFSET] - 1;
24605 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24606 			case IPOPT_TS_PRESPEC:
24607 			case IPOPT_TS_PRESPEC_RFC791:
24608 			case IPOPT_TS_TSANDADDR:
24609 				dst = htonl(INADDR_LOOPBACK);
24610 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24611 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24612 				/* FALLTHRU */
24613 			case IPOPT_TS_TSONLY:
24614 				off = opt[IPOPT_OFFSET] - 1;
24615 				/* Compute # of milliseconds since midnight */
24616 				gethrestime(&now);
24617 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24618 				    now.tv_nsec / (NANOSEC / MILLISEC);
24619 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24620 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24621 				break;
24622 			}
24623 			break;
24624 		}
24625 	}
24626 }
24627 
24628 /*
24629  * Send out a multicast packet on interface ipif.
24630  * The sender does not have an conn.
24631  * Caller verifies that this isn't a PHYI_LOOPBACK.
24632  */
24633 void
24634 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24635 {
24636 	ipha_t	*ipha;
24637 	ire_t	*ire;
24638 	ipaddr_t	dst;
24639 	mblk_t		*first_mp;
24640 
24641 	/* igmp_sendpkt always allocates a ipsec_out_t */
24642 	ASSERT(mp->b_datap->db_type == M_CTL);
24643 	ASSERT(!ipif->ipif_isv6);
24644 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24645 
24646 	first_mp = mp;
24647 	mp = first_mp->b_cont;
24648 	ASSERT(mp->b_datap->db_type == M_DATA);
24649 	ipha = (ipha_t *)mp->b_rptr;
24650 
24651 	/*
24652 	 * Find an IRE which matches the destination and the outgoing
24653 	 * queue (i.e. the outgoing interface.)
24654 	 */
24655 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24656 		dst = ipif->ipif_pp_dst_addr;
24657 	else
24658 		dst = ipha->ipha_dst;
24659 	/*
24660 	 * The source address has already been initialized by the
24661 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24662 	 * be sufficient rather than MATCH_IRE_IPIF.
24663 	 *
24664 	 * This function is used for sending IGMP packets. We need
24665 	 * to make sure that we send the packet out of the interface
24666 	 * (ipif->ipif_ill) where we joined the group. This is to
24667 	 * prevent from switches doing IGMP snooping to send us multicast
24668 	 * packets for a given group on the interface we have joined.
24669 	 * If we can't find an ire, igmp_sendpkt has already initialized
24670 	 * ipsec_out_attach_if so that this will not be load spread in
24671 	 * ip_newroute_ipif.
24672 	 */
24673 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24674 	    MATCH_IRE_ILL);
24675 	if (!ire) {
24676 		/*
24677 		 * Mark this packet to make it be delivered to
24678 		 * ip_wput_ire after the new ire has been
24679 		 * created.
24680 		 */
24681 		mp->b_prev = NULL;
24682 		mp->b_next = NULL;
24683 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24684 		    zoneid);
24685 		return;
24686 	}
24687 
24688 	/*
24689 	 * Honor the RTF_SETSRC flag; this is the only case
24690 	 * where we force this addr whatever the current src addr is,
24691 	 * because this address is set by igmp_sendpkt(), and
24692 	 * cannot be specified by any user.
24693 	 */
24694 	if (ire->ire_flags & RTF_SETSRC) {
24695 		ipha->ipha_src = ire->ire_src_addr;
24696 	}
24697 
24698 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24699 }
24700 
24701 /*
24702  * NOTE : This function does not ire_refrele the ire argument passed in.
24703  *
24704  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24705  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24706  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24707  * the ire_lock to access the nce_fp_mp in this case.
24708  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24709  * prepending a fastpath message IPQoS processing must precede it, we also set
24710  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24711  * (IPQoS might have set the b_band for CoS marking).
24712  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24713  * must follow it so that IPQoS can mark the dl_priority field for CoS
24714  * marking, if needed.
24715  */
24716 static mblk_t *
24717 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24718 {
24719 	uint_t	hlen;
24720 	ipha_t *ipha;
24721 	mblk_t *mp1;
24722 	boolean_t qos_done = B_FALSE;
24723 	uchar_t	*ll_hdr;
24724 
24725 #define	rptr	((uchar_t *)ipha)
24726 
24727 	ipha = (ipha_t *)mp->b_rptr;
24728 	hlen = 0;
24729 	LOCK_IRE_FP_MP(ire);
24730 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24731 		ASSERT(DB_TYPE(mp1) == M_DATA);
24732 		/* Initiate IPPF processing */
24733 		if ((proc != 0) && IPP_ENABLED(proc)) {
24734 			UNLOCK_IRE_FP_MP(ire);
24735 			ip_process(proc, &mp, ill_index);
24736 			if (mp == NULL)
24737 				return (NULL);
24738 
24739 			ipha = (ipha_t *)mp->b_rptr;
24740 			LOCK_IRE_FP_MP(ire);
24741 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24742 				qos_done = B_TRUE;
24743 				goto no_fp_mp;
24744 			}
24745 			ASSERT(DB_TYPE(mp1) == M_DATA);
24746 		}
24747 		hlen = MBLKL(mp1);
24748 		/*
24749 		 * Check if we have enough room to prepend fastpath
24750 		 * header
24751 		 */
24752 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24753 			ll_hdr = rptr - hlen;
24754 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24755 			/*
24756 			 * Set the b_rptr to the start of the link layer
24757 			 * header
24758 			 */
24759 			mp->b_rptr = ll_hdr;
24760 			mp1 = mp;
24761 		} else {
24762 			mp1 = copyb(mp1);
24763 			if (mp1 == NULL)
24764 				goto unlock_err;
24765 			mp1->b_band = mp->b_band;
24766 			mp1->b_cont = mp;
24767 			/*
24768 			 * certain system generated traffic may not
24769 			 * have cred/label in ip header block. This
24770 			 * is true even for a labeled system. But for
24771 			 * labeled traffic, inherit the label in the
24772 			 * new header.
24773 			 */
24774 			if (DB_CRED(mp) != NULL)
24775 				mblk_setcred(mp1, DB_CRED(mp));
24776 			/*
24777 			 * XXX disable ICK_VALID and compute checksum
24778 			 * here; can happen if nce_fp_mp changes and
24779 			 * it can't be copied now due to insufficient
24780 			 * space. (unlikely, fp mp can change, but it
24781 			 * does not increase in length)
24782 			 */
24783 		}
24784 		UNLOCK_IRE_FP_MP(ire);
24785 	} else {
24786 no_fp_mp:
24787 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24788 		if (mp1 == NULL) {
24789 unlock_err:
24790 			UNLOCK_IRE_FP_MP(ire);
24791 			freemsg(mp);
24792 			return (NULL);
24793 		}
24794 		UNLOCK_IRE_FP_MP(ire);
24795 		mp1->b_cont = mp;
24796 		/*
24797 		 * certain system generated traffic may not
24798 		 * have cred/label in ip header block. This
24799 		 * is true even for a labeled system. But for
24800 		 * labeled traffic, inherit the label in the
24801 		 * new header.
24802 		 */
24803 		if (DB_CRED(mp) != NULL)
24804 			mblk_setcred(mp1, DB_CRED(mp));
24805 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24806 			ip_process(proc, &mp1, ill_index);
24807 			if (mp1 == NULL)
24808 				return (NULL);
24809 		}
24810 	}
24811 	return (mp1);
24812 #undef rptr
24813 }
24814 
24815 /*
24816  * Finish the outbound IPsec processing for an IPv6 packet. This function
24817  * is called from ipsec_out_process() if the IPsec packet was processed
24818  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24819  * asynchronously.
24820  */
24821 void
24822 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24823     ire_t *ire_arg)
24824 {
24825 	in6_addr_t *v6dstp;
24826 	ire_t *ire;
24827 	mblk_t *mp;
24828 	ip6_t *ip6h1;
24829 	uint_t	ill_index;
24830 	ipsec_out_t *io;
24831 	boolean_t attach_if, hwaccel;
24832 	uint32_t flags = IP6_NO_IPPOLICY;
24833 	int match_flags;
24834 	zoneid_t zoneid;
24835 	boolean_t ill_need_rele = B_FALSE;
24836 	boolean_t ire_need_rele = B_FALSE;
24837 
24838 	mp = ipsec_mp->b_cont;
24839 	ip6h1 = (ip6_t *)mp->b_rptr;
24840 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24841 	ill_index = io->ipsec_out_ill_index;
24842 	if (io->ipsec_out_reachable) {
24843 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24844 	}
24845 	attach_if = io->ipsec_out_attach_if;
24846 	hwaccel = io->ipsec_out_accelerated;
24847 	zoneid = io->ipsec_out_zoneid;
24848 	ASSERT(zoneid != ALL_ZONES);
24849 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24850 	/* Multicast addresses should have non-zero ill_index. */
24851 	v6dstp = &ip6h->ip6_dst;
24852 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24853 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24854 	ASSERT(!attach_if || ill_index != 0);
24855 	if (ill_index != 0) {
24856 		if (ill == NULL) {
24857 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24858 			    B_TRUE);
24859 
24860 			/* Failure case frees things for us. */
24861 			if (ill == NULL)
24862 				return;
24863 
24864 			ill_need_rele = B_TRUE;
24865 		}
24866 		/*
24867 		 * If this packet needs to go out on a particular interface
24868 		 * honor it.
24869 		 */
24870 		if (attach_if) {
24871 			match_flags = MATCH_IRE_ILL;
24872 
24873 			/*
24874 			 * Check if we need an ire that will not be
24875 			 * looked up by anybody else i.e. HIDDEN.
24876 			 */
24877 			if (ill_is_probeonly(ill)) {
24878 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24879 			}
24880 		}
24881 	}
24882 	ASSERT(mp != NULL);
24883 
24884 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24885 		boolean_t unspec_src;
24886 		ipif_t	*ipif;
24887 
24888 		/*
24889 		 * Use the ill_index to get the right ill.
24890 		 */
24891 		unspec_src = io->ipsec_out_unspec_src;
24892 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24893 		if (ipif == NULL) {
24894 			if (ill_need_rele)
24895 				ill_refrele(ill);
24896 			freemsg(ipsec_mp);
24897 			return;
24898 		}
24899 
24900 		if (ire_arg != NULL) {
24901 			ire = ire_arg;
24902 		} else {
24903 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24904 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24905 			ire_need_rele = B_TRUE;
24906 		}
24907 		if (ire != NULL) {
24908 			ipif_refrele(ipif);
24909 			/*
24910 			 * XXX Do the multicast forwarding now, as the IPSEC
24911 			 * processing has been done.
24912 			 */
24913 			goto send;
24914 		}
24915 
24916 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24917 		mp->b_prev = NULL;
24918 		mp->b_next = NULL;
24919 
24920 		/*
24921 		 * If the IPsec packet was processed asynchronously,
24922 		 * drop it now.
24923 		 */
24924 		if (q == NULL) {
24925 			if (ill_need_rele)
24926 				ill_refrele(ill);
24927 			freemsg(ipsec_mp);
24928 			return;
24929 		}
24930 
24931 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24932 		    unspec_src, zoneid);
24933 		ipif_refrele(ipif);
24934 	} else {
24935 		if (attach_if) {
24936 			ipif_t	*ipif;
24937 
24938 			ipif = ipif_get_next_ipif(NULL, ill);
24939 			if (ipif == NULL) {
24940 				if (ill_need_rele)
24941 					ill_refrele(ill);
24942 				freemsg(ipsec_mp);
24943 				return;
24944 			}
24945 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24946 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24947 			ire_need_rele = B_TRUE;
24948 			ipif_refrele(ipif);
24949 		} else {
24950 			if (ire_arg != NULL) {
24951 				ire = ire_arg;
24952 			} else {
24953 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24954 				ire_need_rele = B_TRUE;
24955 			}
24956 		}
24957 		if (ire != NULL)
24958 			goto send;
24959 		/*
24960 		 * ire disappeared underneath.
24961 		 *
24962 		 * What we need to do here is the ip_newroute
24963 		 * logic to get the ire without doing the IPSEC
24964 		 * processing. Follow the same old path. But this
24965 		 * time, ip_wput or ire_add_then_send will call us
24966 		 * directly as all the IPSEC operations are done.
24967 		 */
24968 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24969 		mp->b_prev = NULL;
24970 		mp->b_next = NULL;
24971 
24972 		/*
24973 		 * If the IPsec packet was processed asynchronously,
24974 		 * drop it now.
24975 		 */
24976 		if (q == NULL) {
24977 			if (ill_need_rele)
24978 				ill_refrele(ill);
24979 			freemsg(ipsec_mp);
24980 			return;
24981 		}
24982 
24983 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24984 		    zoneid);
24985 	}
24986 	if (ill != NULL && ill_need_rele)
24987 		ill_refrele(ill);
24988 	return;
24989 send:
24990 	if (ill != NULL && ill_need_rele)
24991 		ill_refrele(ill);
24992 
24993 	/* Local delivery */
24994 	if (ire->ire_stq == NULL) {
24995 		ill_t	*out_ill;
24996 		ASSERT(q != NULL);
24997 
24998 		/* PFHooks: LOOPBACK_OUT */
24999 		out_ill = ire->ire_ipif->ipif_ill;
25000 
25001 		DTRACE_PROBE4(ip6__loopback__out__start,
25002 		    ill_t *, NULL, ill_t *, out_ill,
25003 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25004 
25005 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25006 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25007 
25008 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25009 
25010 		if (ipsec_mp != NULL)
25011 			ip_wput_local_v6(RD(q), out_ill,
25012 			    ip6h, ipsec_mp, ire, 0);
25013 		if (ire_need_rele)
25014 			ire_refrele(ire);
25015 		return;
25016 	}
25017 	/*
25018 	 * Everything is done. Send it out on the wire.
25019 	 * We force the insertion of a fragment header using the
25020 	 * IPH_FRAG_HDR flag in two cases:
25021 	 * - after reception of an ICMPv6 "packet too big" message
25022 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25023 	 * - for multirouted IPv6 packets, so that the receiver can
25024 	 *   discard duplicates according to their fragment identifier
25025 	 */
25026 	/* XXX fix flow control problems. */
25027 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25028 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25029 		if (hwaccel) {
25030 			/*
25031 			 * hardware acceleration does not handle these
25032 			 * "slow path" cases.
25033 			 */
25034 			/* IPsec KSTATS: should bump bean counter here. */
25035 			if (ire_need_rele)
25036 				ire_refrele(ire);
25037 			freemsg(ipsec_mp);
25038 			return;
25039 		}
25040 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25041 		    (mp->b_cont ? msgdsize(mp) :
25042 		    mp->b_wptr - (uchar_t *)ip6h)) {
25043 			/* IPsec KSTATS: should bump bean counter here. */
25044 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25045 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25046 			    msgdsize(mp)));
25047 			if (ire_need_rele)
25048 				ire_refrele(ire);
25049 			freemsg(ipsec_mp);
25050 			return;
25051 		}
25052 		ASSERT(mp->b_prev == NULL);
25053 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25054 		    ntohs(ip6h->ip6_plen) +
25055 		    IPV6_HDR_LEN, ire->ire_max_frag));
25056 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25057 		    ire->ire_max_frag);
25058 	} else {
25059 		UPDATE_OB_PKT_COUNT(ire);
25060 		ire->ire_last_used_time = lbolt;
25061 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25062 	}
25063 	if (ire_need_rele)
25064 		ire_refrele(ire);
25065 	freeb(ipsec_mp);
25066 }
25067 
25068 void
25069 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25070 {
25071 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25072 	da_ipsec_t *hada;	/* data attributes */
25073 	ill_t *ill = (ill_t *)q->q_ptr;
25074 
25075 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25076 
25077 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25078 		/* IPsec KSTATS: Bump lose counter here! */
25079 		freemsg(mp);
25080 		return;
25081 	}
25082 
25083 	/*
25084 	 * It's an IPsec packet that must be
25085 	 * accelerated by the Provider, and the
25086 	 * outbound ill is IPsec acceleration capable.
25087 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25088 	 * to the ill.
25089 	 * IPsec KSTATS: should bump packet counter here.
25090 	 */
25091 
25092 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25093 	if (hada_mp == NULL) {
25094 		/* IPsec KSTATS: should bump packet counter here. */
25095 		freemsg(mp);
25096 		return;
25097 	}
25098 
25099 	hada_mp->b_datap->db_type = M_CTL;
25100 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25101 	hada_mp->b_cont = mp;
25102 
25103 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25104 	bzero(hada, sizeof (da_ipsec_t));
25105 	hada->da_type = IPHADA_M_CTL;
25106 
25107 	putnext(q, hada_mp);
25108 }
25109 
25110 /*
25111  * Finish the outbound IPsec processing. This function is called from
25112  * ipsec_out_process() if the IPsec packet was processed
25113  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25114  * asynchronously.
25115  */
25116 void
25117 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25118     ire_t *ire_arg)
25119 {
25120 	uint32_t v_hlen_tos_len;
25121 	ipaddr_t	dst;
25122 	ipif_t	*ipif = NULL;
25123 	ire_t *ire;
25124 	ire_t *ire1 = NULL;
25125 	mblk_t *next_mp = NULL;
25126 	uint32_t max_frag;
25127 	boolean_t multirt_send = B_FALSE;
25128 	mblk_t *mp;
25129 	mblk_t *mp1;
25130 	ipha_t *ipha1;
25131 	uint_t	ill_index;
25132 	ipsec_out_t *io;
25133 	boolean_t attach_if;
25134 	int match_flags, offset;
25135 	irb_t *irb = NULL;
25136 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25137 	zoneid_t zoneid;
25138 	uint32_t cksum;
25139 	uint16_t *up;
25140 	ipxmit_state_t	pktxmit_state;
25141 #ifdef	_BIG_ENDIAN
25142 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25143 #else
25144 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25145 #endif
25146 
25147 	mp = ipsec_mp->b_cont;
25148 	ipha1 = (ipha_t *)mp->b_rptr;
25149 	ASSERT(mp != NULL);
25150 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25151 	dst = ipha->ipha_dst;
25152 
25153 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25154 	ill_index = io->ipsec_out_ill_index;
25155 	attach_if = io->ipsec_out_attach_if;
25156 	zoneid = io->ipsec_out_zoneid;
25157 	ASSERT(zoneid != ALL_ZONES);
25158 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25159 	if (ill_index != 0) {
25160 		if (ill == NULL) {
25161 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25162 			    ill_index, B_FALSE);
25163 
25164 			/* Failure case frees things for us. */
25165 			if (ill == NULL)
25166 				return;
25167 
25168 			ill_need_rele = B_TRUE;
25169 		}
25170 		/*
25171 		 * If this packet needs to go out on a particular interface
25172 		 * honor it.
25173 		 */
25174 		if (attach_if) {
25175 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25176 
25177 			/*
25178 			 * Check if we need an ire that will not be
25179 			 * looked up by anybody else i.e. HIDDEN.
25180 			 */
25181 			if (ill_is_probeonly(ill)) {
25182 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25183 			}
25184 		}
25185 	}
25186 
25187 	if (CLASSD(dst)) {
25188 		boolean_t conn_dontroute;
25189 		/*
25190 		 * Use the ill_index to get the right ipif.
25191 		 */
25192 		conn_dontroute = io->ipsec_out_dontroute;
25193 		if (ill_index == 0)
25194 			ipif = ipif_lookup_group(dst, zoneid);
25195 		else
25196 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25197 		if (ipif == NULL) {
25198 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25199 			    " multicast\n"));
25200 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25201 			freemsg(ipsec_mp);
25202 			goto done;
25203 		}
25204 		/*
25205 		 * ipha_src has already been intialized with the
25206 		 * value of the ipif in ip_wput. All we need now is
25207 		 * an ire to send this downstream.
25208 		 */
25209 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25210 		    MBLK_GETLABEL(mp), match_flags);
25211 		if (ire != NULL) {
25212 			ill_t *ill1;
25213 			/*
25214 			 * Do the multicast forwarding now, as the IPSEC
25215 			 * processing has been done.
25216 			 */
25217 			if (ip_g_mrouter && !conn_dontroute &&
25218 			    (ill1 = ire_to_ill(ire))) {
25219 				if (ip_mforward(ill1, ipha, mp)) {
25220 					freemsg(ipsec_mp);
25221 					ip1dbg(("ip_wput_ipsec_out: mforward "
25222 					    "failed\n"));
25223 					ire_refrele(ire);
25224 					goto done;
25225 				}
25226 			}
25227 			goto send;
25228 		}
25229 
25230 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25231 		mp->b_prev = NULL;
25232 		mp->b_next = NULL;
25233 
25234 		/*
25235 		 * If the IPsec packet was processed asynchronously,
25236 		 * drop it now.
25237 		 */
25238 		if (q == NULL) {
25239 			freemsg(ipsec_mp);
25240 			goto done;
25241 		}
25242 
25243 		/*
25244 		 * We may be using a wrong ipif to create the ire.
25245 		 * But it is okay as the source address is assigned
25246 		 * for the packet already. Next outbound packet would
25247 		 * create the IRE with the right IPIF in ip_wput.
25248 		 *
25249 		 * Also handle RTF_MULTIRT routes.
25250 		 */
25251 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25252 		    zoneid);
25253 	} else {
25254 		if (attach_if) {
25255 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25256 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25257 		} else {
25258 			if (ire_arg != NULL) {
25259 				ire = ire_arg;
25260 				ire_need_rele = B_FALSE;
25261 			} else {
25262 				ire = ire_cache_lookup(dst, zoneid,
25263 				    MBLK_GETLABEL(mp));
25264 			}
25265 		}
25266 		if (ire != NULL) {
25267 			goto send;
25268 		}
25269 
25270 		/*
25271 		 * ire disappeared underneath.
25272 		 *
25273 		 * What we need to do here is the ip_newroute
25274 		 * logic to get the ire without doing the IPSEC
25275 		 * processing. Follow the same old path. But this
25276 		 * time, ip_wput or ire_add_then_put will call us
25277 		 * directly as all the IPSEC operations are done.
25278 		 */
25279 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25280 		mp->b_prev = NULL;
25281 		mp->b_next = NULL;
25282 
25283 		/*
25284 		 * If the IPsec packet was processed asynchronously,
25285 		 * drop it now.
25286 		 */
25287 		if (q == NULL) {
25288 			freemsg(ipsec_mp);
25289 			goto done;
25290 		}
25291 
25292 		/*
25293 		 * Since we're going through ip_newroute() again, we
25294 		 * need to make sure we don't:
25295 		 *
25296 		 *	1.) Trigger the ASSERT() with the ipha_ident
25297 		 *	    overloading.
25298 		 *	2.) Redo transport-layer checksumming, since we've
25299 		 *	    already done all that to get this far.
25300 		 *
25301 		 * The easiest way not do either of the above is to set
25302 		 * the ipha_ident field to IP_HDR_INCLUDED.
25303 		 */
25304 		ipha->ipha_ident = IP_HDR_INCLUDED;
25305 		ip_newroute(q, ipsec_mp, dst, NULL,
25306 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25307 	}
25308 	goto done;
25309 send:
25310 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25311 		/*
25312 		 * ESP NAT-Traversal packet.
25313 		 *
25314 		 * Just do software checksum for now.
25315 		 */
25316 
25317 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25318 		IP_STAT(ip_out_sw_cksum);
25319 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25320 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25321 #define	iphs	((uint16_t *)ipha)
25322 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25323 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25324 		    IP_SIMPLE_HDR_LENGTH);
25325 #undef iphs
25326 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25327 			cksum = 0xFFFF;
25328 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25329 			if (mp1->b_wptr - mp1->b_rptr >=
25330 			    offset + sizeof (uint16_t)) {
25331 				up = (uint16_t *)(mp1->b_rptr + offset);
25332 				*up = cksum;
25333 				break;	/* out of for loop */
25334 			} else {
25335 				offset -= (mp->b_wptr - mp->b_rptr);
25336 			}
25337 	} /* Otherwise, just keep the all-zero checksum. */
25338 
25339 	if (ire->ire_stq == NULL) {
25340 		ill_t	*out_ill;
25341 		/*
25342 		 * Loopbacks go through ip_wput_local except for one case.
25343 		 * We come here if we generate a icmp_frag_needed message
25344 		 * after IPSEC processing is over. When this function calls
25345 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25346 		 * icmp_frag_needed. The message generated comes back here
25347 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25348 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25349 		 * source address as it is usually set in ip_wput_ire. As
25350 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25351 		 * and we end up here. We can't enter ip_wput_ire once the
25352 		 * IPSEC processing is over and hence we need to do it here.
25353 		 */
25354 		ASSERT(q != NULL);
25355 		UPDATE_OB_PKT_COUNT(ire);
25356 		ire->ire_last_used_time = lbolt;
25357 		if (ipha->ipha_src == 0)
25358 			ipha->ipha_src = ire->ire_src_addr;
25359 
25360 		/* PFHooks: LOOPBACK_OUT */
25361 		out_ill = ire->ire_ipif->ipif_ill;
25362 
25363 		DTRACE_PROBE4(ip4__loopback__out__start,
25364 		    ill_t *, NULL, ill_t *, out_ill,
25365 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25366 
25367 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25368 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25369 
25370 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25371 
25372 		if (ipsec_mp != NULL)
25373 			ip_wput_local(RD(q), out_ill,
25374 			    ipha, ipsec_mp, ire, 0, zoneid);
25375 		if (ire_need_rele)
25376 			ire_refrele(ire);
25377 		goto done;
25378 	}
25379 
25380 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25381 		/*
25382 		 * We are through with IPSEC processing.
25383 		 * Fragment this and send it on the wire.
25384 		 */
25385 		if (io->ipsec_out_accelerated) {
25386 			/*
25387 			 * The packet has been accelerated but must
25388 			 * be fragmented. This should not happen
25389 			 * since AH and ESP must not accelerate
25390 			 * packets that need fragmentation, however
25391 			 * the configuration could have changed
25392 			 * since the AH or ESP processing.
25393 			 * Drop packet.
25394 			 * IPsec KSTATS: bump bean counter here.
25395 			 */
25396 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25397 			    "fragmented accelerated packet!\n"));
25398 			freemsg(ipsec_mp);
25399 		} else {
25400 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25401 		}
25402 		if (ire_need_rele)
25403 			ire_refrele(ire);
25404 		goto done;
25405 	}
25406 
25407 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25408 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25409 	    (void *)ire->ire_ipif, (void *)ipif));
25410 
25411 	/*
25412 	 * Multiroute the secured packet, unless IPsec really
25413 	 * requires the packet to go out only through a particular
25414 	 * interface.
25415 	 */
25416 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25417 		ire_t *first_ire;
25418 		irb = ire->ire_bucket;
25419 		ASSERT(irb != NULL);
25420 		/*
25421 		 * This ire has been looked up as the one that
25422 		 * goes through the given ipif;
25423 		 * make sure we do not omit any other multiroute ire
25424 		 * that may be present in the bucket before this one.
25425 		 */
25426 		IRB_REFHOLD(irb);
25427 		for (first_ire = irb->irb_ire;
25428 		    first_ire != NULL;
25429 		    first_ire = first_ire->ire_next) {
25430 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25431 			    (first_ire->ire_addr == ire->ire_addr) &&
25432 			    !(first_ire->ire_marks &
25433 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25434 				break;
25435 		}
25436 
25437 		if ((first_ire != NULL) && (first_ire != ire)) {
25438 			/*
25439 			 * Don't change the ire if the packet must
25440 			 * be fragmented if sent via this new one.
25441 			 */
25442 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25443 				IRE_REFHOLD(first_ire);
25444 				if (ire_need_rele)
25445 					ire_refrele(ire);
25446 				else
25447 					ire_need_rele = B_TRUE;
25448 				ire = first_ire;
25449 			}
25450 		}
25451 		IRB_REFRELE(irb);
25452 
25453 		multirt_send = B_TRUE;
25454 		max_frag = ire->ire_max_frag;
25455 	} else {
25456 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25457 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25458 			    "flag, attach_if %d\n", attach_if));
25459 		}
25460 	}
25461 
25462 	/*
25463 	 * In most cases, the emission loop below is entered only once.
25464 	 * Only in the case where the ire holds the RTF_MULTIRT
25465 	 * flag, we loop to process all RTF_MULTIRT ires in the
25466 	 * bucket, and send the packet through all crossed
25467 	 * RTF_MULTIRT routes.
25468 	 */
25469 	do {
25470 		if (multirt_send) {
25471 			/*
25472 			 * ire1 holds here the next ire to process in the
25473 			 * bucket. If multirouting is expected,
25474 			 * any non-RTF_MULTIRT ire that has the
25475 			 * right destination address is ignored.
25476 			 */
25477 			ASSERT(irb != NULL);
25478 			IRB_REFHOLD(irb);
25479 			for (ire1 = ire->ire_next;
25480 			    ire1 != NULL;
25481 			    ire1 = ire1->ire_next) {
25482 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25483 					continue;
25484 				if (ire1->ire_addr != ire->ire_addr)
25485 					continue;
25486 				if (ire1->ire_marks &
25487 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25488 					continue;
25489 				/* No loopback here */
25490 				if (ire1->ire_stq == NULL)
25491 					continue;
25492 				/*
25493 				 * Ensure we do not exceed the MTU
25494 				 * of the next route.
25495 				 */
25496 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25497 					ip_multirt_bad_mtu(ire1, max_frag);
25498 					continue;
25499 				}
25500 
25501 				IRE_REFHOLD(ire1);
25502 				break;
25503 			}
25504 			IRB_REFRELE(irb);
25505 			if (ire1 != NULL) {
25506 				/*
25507 				 * We are in a multiple send case, need to
25508 				 * make a copy of the packet.
25509 				 */
25510 				next_mp = copymsg(ipsec_mp);
25511 				if (next_mp == NULL) {
25512 					ire_refrele(ire1);
25513 					ire1 = NULL;
25514 				}
25515 			}
25516 		}
25517 		/*
25518 		 * Everything is done. Send it out on the wire
25519 		 *
25520 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25521 		 * either send it on the wire or, in the case of
25522 		 * HW acceleration, call ipsec_hw_putnext.
25523 		 */
25524 		if (ire->ire_nce &&
25525 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25526 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25527 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25528 			/*
25529 			 * If ire's link-layer is unresolved (this
25530 			 * would only happen if the incomplete ire
25531 			 * was added to cachetable via forwarding path)
25532 			 * don't bother going to ip_xmit_v4. Just drop the
25533 			 * packet.
25534 			 * There is a slight risk here, in that, if we
25535 			 * have the forwarding path create an incomplete
25536 			 * IRE, then until the IRE is completed, any
25537 			 * transmitted IPSEC packets will be dropped
25538 			 * instead of being queued waiting for resolution.
25539 			 *
25540 			 * But the likelihood of a forwarding packet and a wput
25541 			 * packet sending to the same dst at the same time
25542 			 * and there not yet be an ARP entry for it is small.
25543 			 * Furthermore, if this actually happens, it might
25544 			 * be likely that wput would generate multiple
25545 			 * packets (and forwarding would also have a train
25546 			 * of packets) for that destination. If this is
25547 			 * the case, some of them would have been dropped
25548 			 * anyway, since ARP only queues a few packets while
25549 			 * waiting for resolution
25550 			 *
25551 			 * NOTE: We should really call ip_xmit_v4,
25552 			 * and let it queue the packet and send the
25553 			 * ARP query and have ARP come back thus:
25554 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25555 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25556 			 * hw accel work. But it's too complex to get
25557 			 * the IPsec hw  acceleration approach to fit
25558 			 * well with ip_xmit_v4 doing ARP without
25559 			 * doing IPSEC simplification. For now, we just
25560 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25561 			 * that we can continue with the send on the next
25562 			 * attempt.
25563 			 *
25564 			 * XXX THis should be revisited, when
25565 			 * the IPsec/IP interaction is cleaned up
25566 			 */
25567 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25568 			    " - dropping packet\n"));
25569 			freemsg(ipsec_mp);
25570 			/*
25571 			 * Call ip_xmit_v4() to trigger ARP query
25572 			 * in case the nce_state is ND_INITIAL
25573 			 */
25574 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25575 			goto drop_pkt;
25576 		}
25577 
25578 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25579 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25580 		    mblk_t *, mp);
25581 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25582 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25583 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25584 		if (mp == NULL)
25585 			goto drop_pkt;
25586 
25587 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25588 		pktxmit_state = ip_xmit_v4(mp, ire,
25589 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25590 
25591 		if ((pktxmit_state ==  SEND_FAILED) ||
25592 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25593 
25594 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25595 drop_pkt:
25596 			BUMP_MIB(&ip_mib, ipOutDiscards);
25597 			if (ire_need_rele)
25598 				ire_refrele(ire);
25599 			if (ire1 != NULL) {
25600 				ire_refrele(ire1);
25601 				freemsg(next_mp);
25602 			}
25603 			goto done;
25604 		}
25605 
25606 		freeb(ipsec_mp);
25607 		if (ire_need_rele)
25608 			ire_refrele(ire);
25609 
25610 		if (ire1 != NULL) {
25611 			ire = ire1;
25612 			ire_need_rele = B_TRUE;
25613 			ASSERT(next_mp);
25614 			ipsec_mp = next_mp;
25615 			mp = ipsec_mp->b_cont;
25616 			ire1 = NULL;
25617 			next_mp = NULL;
25618 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25619 		} else {
25620 			multirt_send = B_FALSE;
25621 		}
25622 	} while (multirt_send);
25623 done:
25624 	if (ill != NULL && ill_need_rele)
25625 		ill_refrele(ill);
25626 	if (ipif != NULL)
25627 		ipif_refrele(ipif);
25628 }
25629 
25630 /*
25631  * Get the ill corresponding to the specified ire, and compare its
25632  * capabilities with the protocol and algorithms specified by the
25633  * the SA obtained from ipsec_out. If they match, annotate the
25634  * ipsec_out structure to indicate that the packet needs acceleration.
25635  *
25636  *
25637  * A packet is eligible for outbound hardware acceleration if the
25638  * following conditions are satisfied:
25639  *
25640  * 1. the packet will not be fragmented
25641  * 2. the provider supports the algorithm
25642  * 3. there is no pending control message being exchanged
25643  * 4. snoop is not attached
25644  * 5. the destination address is not a broadcast or multicast address.
25645  *
25646  * Rationale:
25647  *	- Hardware drivers do not support fragmentation with
25648  *	  the current interface.
25649  *	- snoop, multicast, and broadcast may result in exposure of
25650  *	  a cleartext datagram.
25651  * We check all five of these conditions here.
25652  *
25653  * XXX would like to nuke "ire_t *" parameter here; problem is that
25654  * IRE is only way to figure out if a v4 address is a broadcast and
25655  * thus ineligible for acceleration...
25656  */
25657 static void
25658 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25659 {
25660 	ipsec_out_t *io;
25661 	mblk_t *data_mp;
25662 	uint_t plen, overhead;
25663 
25664 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25665 		return;
25666 
25667 	if (ill == NULL)
25668 		return;
25669 
25670 	/*
25671 	 * Destination address is a broadcast or multicast.  Punt.
25672 	 */
25673 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25674 	    IRE_LOCAL)))
25675 		return;
25676 
25677 	data_mp = ipsec_mp->b_cont;
25678 
25679 	if (ill->ill_isv6) {
25680 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25681 
25682 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25683 			return;
25684 
25685 		plen = ip6h->ip6_plen;
25686 	} else {
25687 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25688 
25689 		if (CLASSD(ipha->ipha_dst))
25690 			return;
25691 
25692 		plen = ipha->ipha_length;
25693 	}
25694 	/*
25695 	 * Is there a pending DLPI control message being exchanged
25696 	 * between IP/IPsec and the DLS Provider? If there is, it
25697 	 * could be a SADB update, and the state of the DLS Provider
25698 	 * SADB might not be in sync with the SADB maintained by
25699 	 * IPsec. To avoid dropping packets or using the wrong keying
25700 	 * material, we do not accelerate this packet.
25701 	 */
25702 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25703 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25704 		    "ill_dlpi_pending! don't accelerate packet\n"));
25705 		return;
25706 	}
25707 
25708 	/*
25709 	 * Is the Provider in promiscous mode? If it does, we don't
25710 	 * accelerate the packet since it will bounce back up to the
25711 	 * listeners in the clear.
25712 	 */
25713 	if (ill->ill_promisc_on_phys) {
25714 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25715 		    "ill in promiscous mode, don't accelerate packet\n"));
25716 		return;
25717 	}
25718 
25719 	/*
25720 	 * Will the packet require fragmentation?
25721 	 */
25722 
25723 	/*
25724 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25725 	 * as is used elsewhere.
25726 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25727 	 *	+ 2-byte trailer
25728 	 */
25729 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25730 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25731 
25732 	if ((plen + overhead) > ill->ill_max_mtu)
25733 		return;
25734 
25735 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25736 
25737 	/*
25738 	 * Can the ill accelerate this IPsec protocol and algorithm
25739 	 * specified by the SA?
25740 	 */
25741 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25742 	    ill->ill_isv6, sa)) {
25743 		return;
25744 	}
25745 
25746 	/*
25747 	 * Tell AH or ESP that the outbound ill is capable of
25748 	 * accelerating this packet.
25749 	 */
25750 	io->ipsec_out_is_capab_ill = B_TRUE;
25751 }
25752 
25753 /*
25754  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25755  *
25756  * If this function returns B_TRUE, the requested SA's have been filled
25757  * into the ipsec_out_*_sa pointers.
25758  *
25759  * If the function returns B_FALSE, the packet has been "consumed", most
25760  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25761  *
25762  * The SA references created by the protocol-specific "select"
25763  * function will be released when the ipsec_mp is freed, thanks to the
25764  * ipsec_out_free destructor -- see spd.c.
25765  */
25766 static boolean_t
25767 ipsec_out_select_sa(mblk_t *ipsec_mp)
25768 {
25769 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25770 	ipsec_out_t *io;
25771 	ipsec_policy_t *pp;
25772 	ipsec_action_t *ap;
25773 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25774 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25775 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25776 
25777 	if (!io->ipsec_out_secure) {
25778 		/*
25779 		 * We came here by mistake.
25780 		 * Don't bother with ipsec processing
25781 		 * We should "discourage" this path in the future.
25782 		 */
25783 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25784 		return (B_FALSE);
25785 	}
25786 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25787 	ASSERT((io->ipsec_out_policy != NULL) ||
25788 	    (io->ipsec_out_act != NULL));
25789 
25790 	ASSERT(io->ipsec_out_failed == B_FALSE);
25791 
25792 	/*
25793 	 * IPSEC processing has started.
25794 	 */
25795 	io->ipsec_out_proc_begin = B_TRUE;
25796 	ap = io->ipsec_out_act;
25797 	if (ap == NULL) {
25798 		pp = io->ipsec_out_policy;
25799 		ASSERT(pp != NULL);
25800 		ap = pp->ipsp_act;
25801 		ASSERT(ap != NULL);
25802 	}
25803 
25804 	/*
25805 	 * We have an action.  now, let's select SA's.
25806 	 * (In the future, we can cache this in the conn_t..)
25807 	 */
25808 	if (ap->ipa_want_esp) {
25809 		if (io->ipsec_out_esp_sa == NULL) {
25810 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25811 			    IPPROTO_ESP);
25812 		}
25813 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25814 	}
25815 
25816 	if (ap->ipa_want_ah) {
25817 		if (io->ipsec_out_ah_sa == NULL) {
25818 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25819 			    IPPROTO_AH);
25820 		}
25821 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25822 		/*
25823 		 * The ESP and AH processing order needs to be preserved
25824 		 * when both protocols are required (ESP should be applied
25825 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25826 		 * when both ESP and AH are required, and an AH ACQUIRE
25827 		 * is needed.
25828 		 */
25829 		if (ap->ipa_want_esp && need_ah_acquire)
25830 			need_esp_acquire = B_TRUE;
25831 	}
25832 
25833 	/*
25834 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25835 	 * Release SAs that got referenced, but will not be used until we
25836 	 * acquire _all_ of the SAs we need.
25837 	 */
25838 	if (need_ah_acquire || need_esp_acquire) {
25839 		if (io->ipsec_out_ah_sa != NULL) {
25840 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25841 			io->ipsec_out_ah_sa = NULL;
25842 		}
25843 		if (io->ipsec_out_esp_sa != NULL) {
25844 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25845 			io->ipsec_out_esp_sa = NULL;
25846 		}
25847 
25848 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25849 		return (B_FALSE);
25850 	}
25851 
25852 	return (B_TRUE);
25853 }
25854 
25855 /*
25856  * Process an IPSEC_OUT message and see what you can
25857  * do with it.
25858  * IPQoS Notes:
25859  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25860  * IPSec.
25861  * XXX would like to nuke ire_t.
25862  * XXX ill_index better be "real"
25863  */
25864 void
25865 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25866 {
25867 	ipsec_out_t *io;
25868 	ipsec_policy_t *pp;
25869 	ipsec_action_t *ap;
25870 	ipha_t *ipha;
25871 	ip6_t *ip6h;
25872 	mblk_t *mp;
25873 	ill_t *ill;
25874 	zoneid_t zoneid;
25875 	ipsec_status_t ipsec_rc;
25876 	boolean_t ill_need_rele = B_FALSE;
25877 
25878 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25879 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25880 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25881 	mp = ipsec_mp->b_cont;
25882 
25883 	/*
25884 	 * Initiate IPPF processing. We do it here to account for packets
25885 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25886 	 * We can check for ipsec_out_proc_begin even for such packets, as
25887 	 * they will always be false (asserted below).
25888 	 */
25889 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25890 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25891 		    io->ipsec_out_ill_index : ill_index);
25892 		if (mp == NULL) {
25893 			ip2dbg(("ipsec_out_process: packet dropped "\
25894 			    "during IPPF processing\n"));
25895 			freeb(ipsec_mp);
25896 			BUMP_MIB(&ip_mib, ipOutDiscards);
25897 			return;
25898 		}
25899 	}
25900 
25901 	if (!io->ipsec_out_secure) {
25902 		/*
25903 		 * We came here by mistake.
25904 		 * Don't bother with ipsec processing
25905 		 * Should "discourage" this path in the future.
25906 		 */
25907 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25908 		goto done;
25909 	}
25910 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25911 	ASSERT((io->ipsec_out_policy != NULL) ||
25912 	    (io->ipsec_out_act != NULL));
25913 	ASSERT(io->ipsec_out_failed == B_FALSE);
25914 
25915 	if (!ipsec_loaded()) {
25916 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25917 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25918 			BUMP_MIB(&ip_mib, ipOutDiscards);
25919 		} else {
25920 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25921 		}
25922 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25923 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25924 		return;
25925 	}
25926 
25927 	/*
25928 	 * IPSEC processing has started.
25929 	 */
25930 	io->ipsec_out_proc_begin = B_TRUE;
25931 	ap = io->ipsec_out_act;
25932 	if (ap == NULL) {
25933 		pp = io->ipsec_out_policy;
25934 		ASSERT(pp != NULL);
25935 		ap = pp->ipsp_act;
25936 		ASSERT(ap != NULL);
25937 	}
25938 
25939 	/*
25940 	 * Save the outbound ill index. When the packet comes back
25941 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25942 	 * before sending it the accelerated packet.
25943 	 */
25944 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25945 		int ifindex;
25946 		ill = ire_to_ill(ire);
25947 		ifindex = ill->ill_phyint->phyint_ifindex;
25948 		io->ipsec_out_capab_ill_index = ifindex;
25949 	}
25950 
25951 	/*
25952 	 * The order of processing is first insert a IP header if needed.
25953 	 * Then insert the ESP header and then the AH header.
25954 	 */
25955 	if ((io->ipsec_out_se_done == B_FALSE) &&
25956 	    (ap->ipa_want_se)) {
25957 		/*
25958 		 * First get the outer IP header before sending
25959 		 * it to ESP.
25960 		 */
25961 		ipha_t *oipha, *iipha;
25962 		mblk_t *outer_mp, *inner_mp;
25963 
25964 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25965 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25966 			    "ipsec_out_process: "
25967 			    "Self-Encapsulation failed: Out of memory\n");
25968 			freemsg(ipsec_mp);
25969 			BUMP_MIB(&ip_mib, ipOutDiscards);
25970 			return;
25971 		}
25972 		inner_mp = ipsec_mp->b_cont;
25973 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25974 		oipha = (ipha_t *)outer_mp->b_rptr;
25975 		iipha = (ipha_t *)inner_mp->b_rptr;
25976 		*oipha = *iipha;
25977 		outer_mp->b_wptr += sizeof (ipha_t);
25978 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25979 		    sizeof (ipha_t));
25980 		oipha->ipha_protocol = IPPROTO_ENCAP;
25981 		oipha->ipha_version_and_hdr_length =
25982 		    IP_SIMPLE_HDR_VERSION;
25983 		oipha->ipha_hdr_checksum = 0;
25984 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25985 		outer_mp->b_cont = inner_mp;
25986 		ipsec_mp->b_cont = outer_mp;
25987 
25988 		io->ipsec_out_se_done = B_TRUE;
25989 		io->ipsec_out_tunnel = B_TRUE;
25990 	}
25991 
25992 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25993 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25994 	    !ipsec_out_select_sa(ipsec_mp))
25995 		return;
25996 
25997 	/*
25998 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25999 	 * to do the heavy lifting.
26000 	 */
26001 	zoneid = io->ipsec_out_zoneid;
26002 	ASSERT(zoneid != ALL_ZONES);
26003 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26004 		ASSERT(io->ipsec_out_esp_sa != NULL);
26005 		io->ipsec_out_esp_done = B_TRUE;
26006 		/*
26007 		 * Note that since hw accel can only apply one transform,
26008 		 * not two, we skip hw accel for ESP if we also have AH
26009 		 * This is an design limitation of the interface
26010 		 * which should be revisited.
26011 		 */
26012 		ASSERT(ire != NULL);
26013 		if (io->ipsec_out_ah_sa == NULL) {
26014 			ill = (ill_t *)ire->ire_stq->q_ptr;
26015 			ipsec_out_is_accelerated(ipsec_mp,
26016 			    io->ipsec_out_esp_sa, ill, ire);
26017 		}
26018 
26019 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26020 		switch (ipsec_rc) {
26021 		case IPSEC_STATUS_SUCCESS:
26022 			break;
26023 		case IPSEC_STATUS_FAILED:
26024 			BUMP_MIB(&ip_mib, ipOutDiscards);
26025 			/* FALLTHRU */
26026 		case IPSEC_STATUS_PENDING:
26027 			return;
26028 		}
26029 	}
26030 
26031 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26032 		ASSERT(io->ipsec_out_ah_sa != NULL);
26033 		io->ipsec_out_ah_done = B_TRUE;
26034 		if (ire == NULL) {
26035 			int idx = io->ipsec_out_capab_ill_index;
26036 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26037 			    NULL, NULL, NULL, NULL);
26038 			ill_need_rele = B_TRUE;
26039 		} else {
26040 			ill = (ill_t *)ire->ire_stq->q_ptr;
26041 		}
26042 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26043 		    ire);
26044 
26045 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26046 		switch (ipsec_rc) {
26047 		case IPSEC_STATUS_SUCCESS:
26048 			break;
26049 		case IPSEC_STATUS_FAILED:
26050 			BUMP_MIB(&ip_mib, ipOutDiscards);
26051 			/* FALLTHRU */
26052 		case IPSEC_STATUS_PENDING:
26053 			if (ill != NULL && ill_need_rele)
26054 				ill_refrele(ill);
26055 			return;
26056 		}
26057 	}
26058 	/*
26059 	 * We are done with IPSEC processing. Send it over
26060 	 * the wire.
26061 	 */
26062 done:
26063 	mp = ipsec_mp->b_cont;
26064 	ipha = (ipha_t *)mp->b_rptr;
26065 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26066 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26067 	} else {
26068 		ip6h = (ip6_t *)ipha;
26069 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26070 	}
26071 	if (ill != NULL && ill_need_rele)
26072 		ill_refrele(ill);
26073 }
26074 
26075 /* ARGSUSED */
26076 void
26077 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26078 {
26079 	opt_restart_t	*or;
26080 	int	err;
26081 	conn_t	*connp;
26082 
26083 	ASSERT(CONN_Q(q));
26084 	connp = Q_TO_CONN(q);
26085 
26086 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26087 	or = (opt_restart_t *)first_mp->b_rptr;
26088 	/*
26089 	 * We don't need to pass any credentials here since this is just
26090 	 * a restart. The credentials are passed in when svr4_optcom_req
26091 	 * is called the first time (from ip_wput_nondata).
26092 	 */
26093 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26094 		err = svr4_optcom_req(q, first_mp, NULL,
26095 		    &ip_opt_obj);
26096 	} else {
26097 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26098 		err = tpi_optcom_req(q, first_mp, NULL,
26099 		    &ip_opt_obj);
26100 	}
26101 	if (err != EINPROGRESS) {
26102 		/* operation is done */
26103 		CONN_OPER_PENDING_DONE(connp);
26104 	}
26105 }
26106 
26107 /*
26108  * ioctls that go through a down/up sequence may need to wait for the down
26109  * to complete. This involves waiting for the ire and ipif refcnts to go down
26110  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26111  */
26112 /* ARGSUSED */
26113 void
26114 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26115 {
26116 	struct iocblk *iocp;
26117 	mblk_t *mp1;
26118 	ipif_t	*ipif;
26119 	ip_ioctl_cmd_t *ipip;
26120 	int err;
26121 	sin_t	*sin;
26122 	struct lifreq *lifr;
26123 	struct ifreq *ifr;
26124 
26125 	iocp = (struct iocblk *)mp->b_rptr;
26126 	ASSERT(ipsq != NULL);
26127 	/* Existence of mp1 verified in ip_wput_nondata */
26128 	mp1 = mp->b_cont->b_cont;
26129 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26130 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26131 		ill_t *ill;
26132 		/*
26133 		 * Special case where ipsq_current_ipif may not be set.
26134 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26135 		 * ill could also have become part of a ipmp group in the
26136 		 * process, we are here as were not able to complete the
26137 		 * operation in ipif_set_values because we could not become
26138 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26139 		 * will not be set so we need to set it.
26140 		 */
26141 		ill = (ill_t *)q->q_ptr;
26142 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26143 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26144 	}
26145 
26146 	ipif = ipsq->ipsq_current_ipif;
26147 	ASSERT(ipif != NULL);
26148 	if (ipip->ipi_cmd_type == IF_CMD) {
26149 		/* This a old style SIOC[GS]IF* command */
26150 		ifr = (struct ifreq *)mp1->b_rptr;
26151 		sin = (sin_t *)&ifr->ifr_addr;
26152 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26153 		/* This a new style SIOC[GS]LIF* command */
26154 		lifr = (struct lifreq *)mp1->b_rptr;
26155 		sin = (sin_t *)&lifr->lifr_addr;
26156 	} else {
26157 		sin = NULL;
26158 	}
26159 
26160 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26161 	    (void *)mp1->b_rptr);
26162 
26163 	/* SIOCLIFREMOVEIF could have removed the ipif */
26164 	ip_ioctl_finish(q, mp, err,
26165 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26166 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26167 }
26168 
26169 /*
26170  * ioctl processing
26171  *
26172  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26173  * the ioctl command in the ioctl tables and determines the copyin data size
26174  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26175  * size.
26176  *
26177  * ioctl processing then continues when the M_IOCDATA makes its way down.
26178  * Now the ioctl is looked up again in the ioctl table, and its properties are
26179  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26180  * and the general ioctl processing function ip_process_ioctl is called.
26181  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26182  * so goes thru the serialization primitive ipsq_try_enter. Then the
26183  * appropriate function to handle the ioctl is called based on the entry in
26184  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26185  * which also refreleases the 'conn' that was refheld at the start of the
26186  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26187  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26188  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26189  *
26190  * Many exclusive ioctls go thru an internal down up sequence as part of
26191  * the operation. For example an attempt to change the IP address of an
26192  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26193  * does all the cleanup such as deleting all ires that use this address.
26194  * Then we need to wait till all references to the interface go away.
26195  */
26196 void
26197 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26198 {
26199 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26200 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26201 	cmd_info_t ci;
26202 	int err;
26203 	boolean_t entered_ipsq = B_FALSE;
26204 
26205 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26206 
26207 	if (ipip == NULL)
26208 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26209 
26210 	/*
26211 	 * SIOCLIFADDIF needs to go thru a special path since the
26212 	 * ill may not exist yet. This happens in the case of lo0
26213 	 * which is created using this ioctl.
26214 	 */
26215 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26216 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26217 		ip_ioctl_finish(q, mp, err,
26218 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26219 		    NULL, NULL);
26220 		return;
26221 	}
26222 
26223 	ci.ci_ipif = NULL;
26224 	switch (ipip->ipi_cmd_type) {
26225 	case IF_CMD:
26226 	case LIF_CMD:
26227 		/*
26228 		 * ioctls that pass in a [l]ifreq appear here.
26229 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26230 		 * ci.ci_ipif
26231 		 */
26232 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26233 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26234 		if (err != 0) {
26235 			ip_ioctl_finish(q, mp, err,
26236 			    ipip->ipi_flags & IPI_GET_CMD ?
26237 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26238 			return;
26239 		}
26240 		ASSERT(ci.ci_ipif != NULL);
26241 		break;
26242 
26243 	case TUN_CMD:
26244 		/*
26245 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26246 		 * a refheld ipif in ci.ci_ipif
26247 		 */
26248 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26249 		if (err != 0) {
26250 			ip_ioctl_finish(q, mp, err,
26251 			    ipip->ipi_flags & IPI_GET_CMD ?
26252 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26253 			return;
26254 		}
26255 		ASSERT(ci.ci_ipif != NULL);
26256 		break;
26257 
26258 	case MISC_CMD:
26259 		/*
26260 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26261 		 * For eg. SIOCGLIFCONF will appear here.
26262 		 */
26263 		switch (ipip->ipi_cmd) {
26264 		case IF_UNITSEL:
26265 			/* ioctl comes down the ill */
26266 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26267 			ipif_refhold(ci.ci_ipif);
26268 			break;
26269 		case SIOCGMSFILTER:
26270 		case SIOCSMSFILTER:
26271 		case SIOCGIPMSFILTER:
26272 		case SIOCSIPMSFILTER:
26273 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26274 			    ip_process_ioctl);
26275 			if (err != 0) {
26276 				ip_ioctl_finish(q, mp, err,
26277 				    ipip->ipi_flags & IPI_GET_CMD ?
26278 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26279 				return;
26280 			}
26281 			break;
26282 		}
26283 		err = 0;
26284 		ci.ci_sin = NULL;
26285 		ci.ci_sin6 = NULL;
26286 		ci.ci_lifr = NULL;
26287 		break;
26288 	}
26289 
26290 	/*
26291 	 * If ipsq is non-null, we are already being called exclusively
26292 	 */
26293 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26294 	if (!(ipip->ipi_flags & IPI_WR)) {
26295 		/*
26296 		 * A return value of EINPROGRESS means the ioctl is
26297 		 * either queued and waiting for some reason or has
26298 		 * already completed.
26299 		 */
26300 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26301 		    ci.ci_lifr);
26302 		if (ci.ci_ipif != NULL)
26303 			ipif_refrele(ci.ci_ipif);
26304 		ip_ioctl_finish(q, mp, err,
26305 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26306 		    NULL, NULL);
26307 		return;
26308 	}
26309 
26310 	ASSERT(ci.ci_ipif != NULL);
26311 
26312 	if (ipsq == NULL) {
26313 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26314 		    ip_process_ioctl, NEW_OP, B_TRUE);
26315 		entered_ipsq = B_TRUE;
26316 	}
26317 	/*
26318 	 * Release the ipif so that ipif_down and friends that wait for
26319 	 * references to go away are not misled about the current ipif_refcnt
26320 	 * values. We are writer so we can access the ipif even after releasing
26321 	 * the ipif.
26322 	 */
26323 	ipif_refrele(ci.ci_ipif);
26324 	if (ipsq == NULL)
26325 		return;
26326 
26327 	mutex_enter(&ipsq->ipsq_lock);
26328 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26329 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26330 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26331 	mutex_exit(&ipsq->ipsq_lock);
26332 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26333 	/*
26334 	 * For most set ioctls that come here, this serves as a single point
26335 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26336 	 * be any new references to the ipif. This helps functions that go
26337 	 * through this path and end up trying to wait for the refcnts
26338 	 * associated with the ipif to go down to zero. Some exceptions are
26339 	 * Failover, Failback, and Groupname commands that operate on more than
26340 	 * just the ci.ci_ipif. These commands internally determine the
26341 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26342 	 * flags on that set. Another exception is the Removeif command that
26343 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26344 	 * ipif to operate on.
26345 	 */
26346 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26347 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26348 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26349 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26350 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26351 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26352 
26353 	/*
26354 	 * A return value of EINPROGRESS means the ioctl is
26355 	 * either queued and waiting for some reason or has
26356 	 * already completed.
26357 	 */
26358 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26359 	    ci.ci_lifr);
26360 
26361 	/* SIOCLIFREMOVEIF could have removed the ipif */
26362 	ip_ioctl_finish(q, mp, err,
26363 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26364 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26365 
26366 	if (entered_ipsq)
26367 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26368 }
26369 
26370 /*
26371  * Complete the ioctl. Typically ioctls use the mi package and need to
26372  * do mi_copyout/mi_copy_done.
26373  */
26374 void
26375 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26376     ipif_t *ipif, ipsq_t *ipsq)
26377 {
26378 	conn_t	*connp = NULL;
26379 	hook_nic_event_t *info;
26380 
26381 	if (err == EINPROGRESS)
26382 		return;
26383 
26384 	if (CONN_Q(q)) {
26385 		connp = Q_TO_CONN(q);
26386 		ASSERT(connp->conn_ref >= 2);
26387 	}
26388 
26389 	switch (mode) {
26390 	case COPYOUT:
26391 		if (err == 0)
26392 			mi_copyout(q, mp);
26393 		else
26394 			mi_copy_done(q, mp, err);
26395 		break;
26396 
26397 	case NO_COPYOUT:
26398 		mi_copy_done(q, mp, err);
26399 		break;
26400 
26401 	default:
26402 		/* An ioctl aborted through a conn close would take this path */
26403 		break;
26404 	}
26405 
26406 	/*
26407 	 * The refhold placed at the start of the ioctl is released here.
26408 	 */
26409 	if (connp != NULL)
26410 		CONN_OPER_PENDING_DONE(connp);
26411 
26412 	/*
26413 	 * If the ioctl were an exclusive ioctl it would have set
26414 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26415 	 */
26416 	if (ipif != NULL) {
26417 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26418 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26419 
26420 		/*
26421 		 * Unhook the nic event message from the ill and enqueue it into
26422 		 * the nic event taskq.
26423 		 */
26424 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26425 			if (ddi_taskq_dispatch(eventq_queue_nic,
26426 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26427 			    == DDI_FAILURE) {
26428 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26429 				    "failed\n"));
26430 				if (info->hne_data != NULL)
26431 					kmem_free(info->hne_data,
26432 					    info->hne_datalen);
26433 				kmem_free(info, sizeof (hook_nic_event_t));
26434 			}
26435 
26436 			ipif->ipif_ill->ill_nic_event_info = NULL;
26437 		}
26438 
26439 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26440 	}
26441 
26442 	/*
26443 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26444 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26445 	 * entering the ipsq
26446 	 */
26447 	if (ipsq != NULL) {
26448 		mutex_enter(&ipsq->ipsq_lock);
26449 		ipsq->ipsq_current_ipif = NULL;
26450 		mutex_exit(&ipsq->ipsq_lock);
26451 	}
26452 }
26453 
26454 /*
26455  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26456  */
26457 /* ARGSUSED */
26458 void
26459 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26460 {
26461 	conn_t *connp = arg;
26462 	tcp_t	*tcp;
26463 
26464 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26465 	tcp = connp->conn_tcp;
26466 
26467 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26468 		freemsg(mp);
26469 	else
26470 		tcp_rput_other(tcp, mp);
26471 	CONN_OPER_PENDING_DONE(connp);
26472 }
26473 
26474 /* Called from ip_wput for all non data messages */
26475 /* ARGSUSED */
26476 void
26477 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26478 {
26479 	mblk_t		*mp1;
26480 	ire_t		*ire, *fake_ire;
26481 	ill_t		*ill;
26482 	struct iocblk	*iocp;
26483 	ip_ioctl_cmd_t	*ipip;
26484 	cred_t		*cr;
26485 	conn_t		*connp = NULL;
26486 	int		cmd, err;
26487 	nce_t		*nce;
26488 	ipif_t		*ipif;
26489 
26490 	if (CONN_Q(q))
26491 		connp = Q_TO_CONN(q);
26492 
26493 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26494 
26495 	/* Check if it is a queue to /dev/sctp. */
26496 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26497 	    connp->conn_rq == NULL) {
26498 		sctp_wput(q, mp);
26499 		return;
26500 	}
26501 
26502 	switch (DB_TYPE(mp)) {
26503 	case M_IOCTL:
26504 		/*
26505 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26506 		 * will arrange to copy in associated control structures.
26507 		 */
26508 		ip_sioctl_copyin_setup(q, mp);
26509 		return;
26510 	case M_IOCDATA:
26511 		/*
26512 		 * Ensure that this is associated with one of our trans-
26513 		 * parent ioctls.  If it's not ours, discard it if we're
26514 		 * running as a driver, or pass it on if we're a module.
26515 		 */
26516 		iocp = (struct iocblk *)mp->b_rptr;
26517 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26518 		if (ipip == NULL) {
26519 			if (q->q_next == NULL) {
26520 				goto nak;
26521 			} else {
26522 				putnext(q, mp);
26523 			}
26524 			return;
26525 		} else if ((q->q_next != NULL) &&
26526 		    !(ipip->ipi_flags & IPI_MODOK)) {
26527 			/*
26528 			 * the ioctl is one we recognise, but is not
26529 			 * consumed by IP as a module, pass M_IOCDATA
26530 			 * for processing downstream, but only for
26531 			 * common Streams ioctls.
26532 			 */
26533 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26534 				putnext(q, mp);
26535 				return;
26536 			} else {
26537 				goto nak;
26538 			}
26539 		}
26540 
26541 		/* IOCTL continuation following copyin or copyout. */
26542 		if (mi_copy_state(q, mp, NULL) == -1) {
26543 			/*
26544 			 * The copy operation failed.  mi_copy_state already
26545 			 * cleaned up, so we're out of here.
26546 			 */
26547 			return;
26548 		}
26549 		/*
26550 		 * If we just completed a copy in, we become writer and
26551 		 * continue processing in ip_sioctl_copyin_done.  If it
26552 		 * was a copy out, we call mi_copyout again.  If there is
26553 		 * nothing more to copy out, it will complete the IOCTL.
26554 		 */
26555 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26556 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26557 				mi_copy_done(q, mp, EPROTO);
26558 				return;
26559 			}
26560 			/*
26561 			 * Check for cases that need more copying.  A return
26562 			 * value of 0 means a second copyin has been started,
26563 			 * so we return; a return value of 1 means no more
26564 			 * copying is needed, so we continue.
26565 			 */
26566 			cmd = iocp->ioc_cmd;
26567 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26568 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26569 			    MI_COPY_COUNT(mp) == 1) {
26570 				if (ip_copyin_msfilter(q, mp) == 0)
26571 					return;
26572 			}
26573 			/*
26574 			 * Refhold the conn, till the ioctl completes. This is
26575 			 * needed in case the ioctl ends up in the pending mp
26576 			 * list. Every mp in the ill_pending_mp list and
26577 			 * the ipsq_pending_mp must have a refhold on the conn
26578 			 * to resume processing. The refhold is released when
26579 			 * the ioctl completes. (normally or abnormally)
26580 			 * In all cases ip_ioctl_finish is called to finish
26581 			 * the ioctl.
26582 			 */
26583 			if (connp != NULL) {
26584 				/* This is not a reentry */
26585 				ASSERT(ipsq == NULL);
26586 				CONN_INC_REF(connp);
26587 			} else {
26588 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26589 					mi_copy_done(q, mp, EINVAL);
26590 					return;
26591 				}
26592 			}
26593 
26594 			ip_process_ioctl(ipsq, q, mp, ipip);
26595 
26596 		} else {
26597 			mi_copyout(q, mp);
26598 		}
26599 		return;
26600 nak:
26601 		iocp->ioc_error = EINVAL;
26602 		mp->b_datap->db_type = M_IOCNAK;
26603 		iocp->ioc_count = 0;
26604 		qreply(q, mp);
26605 		return;
26606 
26607 	case M_IOCNAK:
26608 		/*
26609 		 * The only way we could get here is if a resolver didn't like
26610 		 * an IOCTL we sent it.	 This shouldn't happen.
26611 		 */
26612 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26613 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26614 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26615 		freemsg(mp);
26616 		return;
26617 	case M_IOCACK:
26618 		/* Finish socket ioctls passed through to ARP. */
26619 		ip_sioctl_iocack(q, mp);
26620 		return;
26621 	case M_FLUSH:
26622 		if (*mp->b_rptr & FLUSHW)
26623 			flushq(q, FLUSHALL);
26624 		if (q->q_next) {
26625 			/*
26626 			 * M_FLUSH is sent up to IP by some drivers during
26627 			 * unbind. ip_rput has already replied to it. We are
26628 			 * here for the M_FLUSH that we originated in IP
26629 			 * before sending the unbind request to the driver.
26630 			 * Just free it as we don't queue packets in IP
26631 			 * on the write side of the device instance.
26632 			 */
26633 			freemsg(mp);
26634 			return;
26635 		}
26636 		if (*mp->b_rptr & FLUSHR) {
26637 			*mp->b_rptr &= ~FLUSHW;
26638 			qreply(q, mp);
26639 			return;
26640 		}
26641 		freemsg(mp);
26642 		return;
26643 	case IRE_DB_REQ_TYPE:
26644 		/* An Upper Level Protocol wants a copy of an IRE. */
26645 		ip_ire_req(q, mp);
26646 		return;
26647 	case M_CTL:
26648 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26649 			break;
26650 
26651 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
26652 		    TUN_HELLO) {
26653 			ASSERT(connp != NULL);
26654 			connp->conn_flags |= IPCL_IPTUN;
26655 			freeb(mp);
26656 			return;
26657 		}
26658 
26659 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26660 		    IP_ULP_OUT_LABELED) {
26661 			out_labeled_t *olp;
26662 
26663 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26664 				break;
26665 			olp = (out_labeled_t *)mp->b_rptr;
26666 			connp->conn_ulp_labeled = olp->out_qnext == q;
26667 			freemsg(mp);
26668 			return;
26669 		}
26670 
26671 		/* M_CTL messages are used by ARP to tell us things. */
26672 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26673 			break;
26674 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26675 		case AR_ENTRY_SQUERY:
26676 			ip_wput_ctl(q, mp);
26677 			return;
26678 		case AR_CLIENT_NOTIFY:
26679 			ip_arp_news(q, mp);
26680 			return;
26681 		case AR_DLPIOP_DONE:
26682 			ASSERT(q->q_next != NULL);
26683 			ill = (ill_t *)q->q_ptr;
26684 			/* qwriter_ip releases the refhold */
26685 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26686 			ill_refhold(ill);
26687 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26688 			    CUR_OP, B_FALSE);
26689 			return;
26690 		case AR_ARP_CLOSING:
26691 			/*
26692 			 * ARP (above us) is closing. If no ARP bringup is
26693 			 * currently pending, ack the message so that ARP
26694 			 * can complete its close. Also mark ill_arp_closing
26695 			 * so that new ARP bringups will fail. If any
26696 			 * ARP bringup is currently in progress, we will
26697 			 * ack this when the current ARP bringup completes.
26698 			 */
26699 			ASSERT(q->q_next != NULL);
26700 			ill = (ill_t *)q->q_ptr;
26701 			mutex_enter(&ill->ill_lock);
26702 			ill->ill_arp_closing = 1;
26703 			if (!ill->ill_arp_bringup_pending) {
26704 				mutex_exit(&ill->ill_lock);
26705 				qreply(q, mp);
26706 			} else {
26707 				mutex_exit(&ill->ill_lock);
26708 				freemsg(mp);
26709 			}
26710 			return;
26711 		case AR_ARP_EXTEND:
26712 			/*
26713 			 * The ARP module above us is capable of duplicate
26714 			 * address detection.  Old ATM drivers will not send
26715 			 * this message.
26716 			 */
26717 			ASSERT(q->q_next != NULL);
26718 			ill = (ill_t *)q->q_ptr;
26719 			ill->ill_arp_extend = B_TRUE;
26720 			freemsg(mp);
26721 			return;
26722 		default:
26723 			break;
26724 		}
26725 		break;
26726 	case M_PROTO:
26727 	case M_PCPROTO:
26728 		/*
26729 		 * The only PROTO messages we expect are ULP binds and
26730 		 * copies of option negotiation acknowledgements.
26731 		 */
26732 		switch (((union T_primitives *)mp->b_rptr)->type) {
26733 		case O_T_BIND_REQ:
26734 		case T_BIND_REQ: {
26735 			/* Request can get queued in bind */
26736 			ASSERT(connp != NULL);
26737 			/*
26738 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26739 			 * instead of going through this path.  We only get
26740 			 * here in the following cases:
26741 			 *
26742 			 * a. Bind retries, where ipsq is non-NULL.
26743 			 * b. T_BIND_REQ is issued from non TCP/UDP
26744 			 *    transport, e.g. icmp for raw socket,
26745 			 *    in which case ipsq will be NULL.
26746 			 */
26747 			ASSERT(ipsq != NULL ||
26748 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26749 
26750 			/* Don't increment refcnt if this is a re-entry */
26751 			if (ipsq == NULL)
26752 				CONN_INC_REF(connp);
26753 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26754 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26755 			if (mp == NULL)
26756 				return;
26757 			if (IPCL_IS_TCP(connp)) {
26758 				/*
26759 				 * In the case of TCP endpoint we
26760 				 * come here only for bind retries
26761 				 */
26762 				ASSERT(ipsq != NULL);
26763 				CONN_INC_REF(connp);
26764 				squeue_fill(connp->conn_sqp, mp,
26765 				    ip_resume_tcp_bind, connp,
26766 				    SQTAG_BIND_RETRY);
26767 				return;
26768 			} else if (IPCL_IS_UDP(connp)) {
26769 				/*
26770 				 * In the case of UDP endpoint we
26771 				 * come here only for bind retries
26772 				 */
26773 				ASSERT(ipsq != NULL);
26774 				udp_resume_bind(connp, mp);
26775 				return;
26776 			}
26777 			qreply(q, mp);
26778 			CONN_OPER_PENDING_DONE(connp);
26779 			return;
26780 		}
26781 		case T_SVR4_OPTMGMT_REQ:
26782 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26783 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26784 
26785 			ASSERT(connp != NULL);
26786 			if (!snmpcom_req(q, mp, ip_snmp_set,
26787 			    ip_snmp_get, cr)) {
26788 				/*
26789 				 * Call svr4_optcom_req so that it can
26790 				 * generate the ack. We don't come here
26791 				 * if this operation is being restarted.
26792 				 * ip_restart_optmgmt will drop the conn ref.
26793 				 * In the case of ipsec option after the ipsec
26794 				 * load is complete conn_restart_ipsec_waiter
26795 				 * drops the conn ref.
26796 				 */
26797 				ASSERT(ipsq == NULL);
26798 				CONN_INC_REF(connp);
26799 				if (ip_check_for_ipsec_opt(q, mp))
26800 					return;
26801 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26802 				if (err != EINPROGRESS) {
26803 					/* Operation is done */
26804 					CONN_OPER_PENDING_DONE(connp);
26805 				}
26806 			}
26807 			return;
26808 		case T_OPTMGMT_REQ:
26809 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26810 			/*
26811 			 * Note: No snmpcom_req support through new
26812 			 * T_OPTMGMT_REQ.
26813 			 * Call tpi_optcom_req so that it can
26814 			 * generate the ack.
26815 			 */
26816 			ASSERT(connp != NULL);
26817 			ASSERT(ipsq == NULL);
26818 			/*
26819 			 * We don't come here for restart. ip_restart_optmgmt
26820 			 * will drop the conn ref. In the case of ipsec option
26821 			 * after the ipsec load is complete
26822 			 * conn_restart_ipsec_waiter drops the conn ref.
26823 			 */
26824 			CONN_INC_REF(connp);
26825 			if (ip_check_for_ipsec_opt(q, mp))
26826 				return;
26827 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26828 			if (err != EINPROGRESS) {
26829 				/* Operation is done */
26830 				CONN_OPER_PENDING_DONE(connp);
26831 			}
26832 			return;
26833 		case T_UNBIND_REQ:
26834 			mp = ip_unbind(q, mp);
26835 			qreply(q, mp);
26836 			return;
26837 		default:
26838 			/*
26839 			 * Have to drop any DLPI messages coming down from
26840 			 * arp (such as an info_req which would cause ip
26841 			 * to receive an extra info_ack if it was passed
26842 			 * through.
26843 			 */
26844 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26845 			    (int)*(uint_t *)mp->b_rptr));
26846 			freemsg(mp);
26847 			return;
26848 		}
26849 		/* NOTREACHED */
26850 	case IRE_DB_TYPE: {
26851 		nce_t		*nce;
26852 		ill_t		*ill;
26853 		in6_addr_t	gw_addr_v6;
26854 
26855 
26856 		/*
26857 		 * This is a response back from a resolver.  It
26858 		 * consists of a message chain containing:
26859 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26860 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26861 		 * The LL_HDR_MBLK is the DLPI header to use to get
26862 		 * the attached packet, and subsequent ones for the
26863 		 * same destination, transmitted.
26864 		 */
26865 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26866 			break;
26867 		/*
26868 		 * First, check to make sure the resolution succeeded.
26869 		 * If it failed, the second mblk will be empty.
26870 		 * If it is, free the chain, dropping the packet.
26871 		 * (We must ire_delete the ire; that frees the ire mblk)
26872 		 * We're doing this now to support PVCs for ATM; it's
26873 		 * a partial xresolv implementation. When we fully implement
26874 		 * xresolv interfaces, instead of freeing everything here
26875 		 * we'll initiate neighbor discovery.
26876 		 *
26877 		 * For v4 (ARP and other external resolvers) the resolver
26878 		 * frees the message, so no check is needed. This check
26879 		 * is required, though, for a full xresolve implementation.
26880 		 * Including this code here now both shows how external
26881 		 * resolvers can NACK a resolution request using an
26882 		 * existing design that has no specific provisions for NACKs,
26883 		 * and also takes into account that the current non-ARP
26884 		 * external resolver has been coded to use this method of
26885 		 * NACKing for all IPv6 (xresolv) cases,
26886 		 * whether our xresolv implementation is complete or not.
26887 		 *
26888 		 */
26889 		ire = (ire_t *)mp->b_rptr;
26890 		ill = ire_to_ill(ire);
26891 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26892 		if (mp1->b_rptr == mp1->b_wptr) {
26893 			if (ire->ire_ipversion == IPV6_VERSION) {
26894 				/*
26895 				 * XRESOLV interface.
26896 				 */
26897 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26898 				mutex_enter(&ire->ire_lock);
26899 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26900 				mutex_exit(&ire->ire_lock);
26901 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26902 					nce = ndp_lookup_v6(ill,
26903 					    &ire->ire_addr_v6, B_FALSE);
26904 				} else {
26905 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26906 					    B_FALSE);
26907 				}
26908 				if (nce != NULL) {
26909 					nce_resolv_failed(nce);
26910 					ndp_delete(nce);
26911 					NCE_REFRELE(nce);
26912 				}
26913 			}
26914 			mp->b_cont = NULL;
26915 			freemsg(mp1);		/* frees the pkt as well */
26916 			ASSERT(ire->ire_nce == NULL);
26917 			ire_delete((ire_t *)mp->b_rptr);
26918 			return;
26919 		}
26920 
26921 		/*
26922 		 * Split them into IRE_MBLK and pkt and feed it into
26923 		 * ire_add_then_send. Then in ire_add_then_send
26924 		 * the IRE will be added, and then the packet will be
26925 		 * run back through ip_wput. This time it will make
26926 		 * it to the wire.
26927 		 */
26928 		mp->b_cont = NULL;
26929 		mp = mp1->b_cont;		/* now, mp points to pkt */
26930 		mp1->b_cont = NULL;
26931 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26932 		if (ire->ire_ipversion == IPV6_VERSION) {
26933 			/*
26934 			 * XRESOLV interface. Find the nce and put a copy
26935 			 * of the dl_unitdata_req in nce_res_mp
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, &ire->ire_addr_v6,
26943 				    B_FALSE);
26944 			} else {
26945 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26946 			}
26947 			if (nce != NULL) {
26948 				/*
26949 				 * We have to protect nce_res_mp here
26950 				 * from being accessed by other threads
26951 				 * while we change the mblk pointer.
26952 				 * Other functions will also lock the nce when
26953 				 * accessing nce_res_mp.
26954 				 *
26955 				 * The reason we change the mblk pointer
26956 				 * here rather than copying the resolved address
26957 				 * into the template is that, unlike with
26958 				 * ethernet, we have no guarantee that the
26959 				 * resolved address length will be
26960 				 * smaller than or equal to the lla length
26961 				 * with which the template was allocated,
26962 				 * (for ethernet, they're equal)
26963 				 * so we have to use the actual resolved
26964 				 * address mblk - which holds the real
26965 				 * dl_unitdata_req with the resolved address.
26966 				 *
26967 				 * Doing this is the same behavior as was
26968 				 * previously used in the v4 ARP case.
26969 				 */
26970 				mutex_enter(&nce->nce_lock);
26971 				if (nce->nce_res_mp != NULL)
26972 					freemsg(nce->nce_res_mp);
26973 				nce->nce_res_mp = mp1;
26974 				mutex_exit(&nce->nce_lock);
26975 				/*
26976 				 * We do a fastpath probe here because
26977 				 * we have resolved the address without
26978 				 * using Neighbor Discovery.
26979 				 * In the non-XRESOLV v6 case, the fastpath
26980 				 * probe is done right after neighbor
26981 				 * discovery completes.
26982 				 */
26983 				if (nce->nce_res_mp != NULL) {
26984 					int res;
26985 					nce_fastpath_list_add(nce);
26986 					res = ill_fastpath_probe(ill,
26987 					    nce->nce_res_mp);
26988 					if (res != 0 && res != EAGAIN)
26989 						nce_fastpath_list_delete(nce);
26990 				}
26991 
26992 				ire_add_then_send(q, ire, mp);
26993 				/*
26994 				 * Now we have to clean out any packets
26995 				 * that may have been queued on the nce
26996 				 * while it was waiting for address resolution
26997 				 * to complete.
26998 				 */
26999 				mutex_enter(&nce->nce_lock);
27000 				mp1 = nce->nce_qd_mp;
27001 				nce->nce_qd_mp = NULL;
27002 				mutex_exit(&nce->nce_lock);
27003 				while (mp1 != NULL) {
27004 					mblk_t *nxt_mp;
27005 					queue_t *fwdq = NULL;
27006 					ill_t   *inbound_ill;
27007 					uint_t ifindex;
27008 
27009 					nxt_mp = mp1->b_next;
27010 					mp1->b_next = NULL;
27011 					/*
27012 					 * Retrieve ifindex stored in
27013 					 * ip_rput_data_v6()
27014 					 */
27015 					ifindex =
27016 					    (uint_t)(uintptr_t)mp1->b_prev;
27017 					inbound_ill =
27018 						ill_lookup_on_ifindex(ifindex,
27019 						    B_TRUE, NULL, NULL, NULL,
27020 						    NULL);
27021 					mp1->b_prev = NULL;
27022 					if (inbound_ill != NULL)
27023 						fwdq = inbound_ill->ill_rq;
27024 
27025 					if (fwdq != NULL) {
27026 						put(fwdq, mp1);
27027 						ill_refrele(inbound_ill);
27028 					} else
27029 						put(WR(ill->ill_rq), mp1);
27030 					mp1 = nxt_mp;
27031 				}
27032 				NCE_REFRELE(nce);
27033 			} else {	/* nce is NULL; clean up */
27034 				ire_delete(ire);
27035 				freemsg(mp);
27036 				freemsg(mp1);
27037 				return;
27038 			}
27039 		} else {
27040 			nce_t *arpce;
27041 			/*
27042 			 * Link layer resolution succeeded. Recompute the
27043 			 * ire_nce.
27044 			 */
27045 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27046 			if ((arpce = ndp_lookup_v4(ill,
27047 			    (ire->ire_gateway_addr != INADDR_ANY ?
27048 			    &ire->ire_gateway_addr : &ire->ire_addr),
27049 			    B_FALSE)) == NULL) {
27050 				freeb(ire->ire_mp);
27051 				freeb(mp1);
27052 				freemsg(mp);
27053 				return;
27054 			}
27055 			mutex_enter(&arpce->nce_lock);
27056 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27057 			if (arpce->nce_state == ND_REACHABLE) {
27058 				/*
27059 				 * Someone resolved this before us;
27060 				 * cleanup the res_mp. Since ire has
27061 				 * not been added yet, the call to ire_add_v4
27062 				 * from ire_add_then_send (when a dup is
27063 				 * detected) will clean up the ire.
27064 				 */
27065 				freeb(mp1);
27066 			} else {
27067 				if (arpce->nce_res_mp != NULL)
27068 					freemsg(arpce->nce_res_mp);
27069 				arpce->nce_res_mp = mp1;
27070 				arpce->nce_state = ND_REACHABLE;
27071 			}
27072 			mutex_exit(&arpce->nce_lock);
27073 			if (ire->ire_marks & IRE_MARK_NOADD) {
27074 				/*
27075 				 * this ire will not be added to the ire
27076 				 * cache table, so we can set the ire_nce
27077 				 * here, as there are no atomicity constraints.
27078 				 */
27079 				ire->ire_nce = arpce;
27080 				/*
27081 				 * We are associating this nce with the ire
27082 				 * so change the nce ref taken in
27083 				 * ndp_lookup_v4() from
27084 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27085 				 */
27086 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27087 			} else {
27088 				NCE_REFRELE(arpce);
27089 			}
27090 			ire_add_then_send(q, ire, mp);
27091 		}
27092 		return;	/* All is well, the packet has been sent. */
27093 	}
27094 	case IRE_ARPRESOLVE_TYPE: {
27095 
27096 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27097 			break;
27098 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27099 		mp->b_cont = NULL;
27100 		/*
27101 		 * First, check to make sure the resolution succeeded.
27102 		 * If it failed, the second mblk will be empty.
27103 		 */
27104 		if (mp1->b_rptr == mp1->b_wptr) {
27105 			/* cleanup  the incomplete ire, free queued packets */
27106 			freemsg(mp); /* fake ire */
27107 			freeb(mp1);  /* dl_unitdata response */
27108 			return;
27109 		}
27110 
27111 		/*
27112 		 * update any incomplete nce_t found. we lookup the ctable
27113 		 * and find the nce from the ire->ire_nce because we need
27114 		 * to pass the ire to ip_xmit_v4 later, and can find both
27115 		 * ire and nce in one lookup from the ctable.
27116 		 */
27117 		fake_ire = (ire_t *)mp->b_rptr;
27118 		/*
27119 		 * By the time we come back here from ARP
27120 		 * the logical outgoing interface  of the incomplete ire
27121 		 * we added in ire_forward could have disappeared,
27122 		 * causing the incomplete ire to also have
27123 		 * dissapeared. So we need to retreive the
27124 		 * proper ipif for the ire  before looking
27125 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27126 		 */
27127 		ill = q->q_ptr;
27128 
27129 		/* Get the outgoing ipif */
27130 		mutex_enter(&ill->ill_lock);
27131 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27132 			mutex_exit(&ill->ill_lock);
27133 			freemsg(mp); /* fake ire */
27134 			freeb(mp1);  /* dl_unitdata response */
27135 			return;
27136 		}
27137 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27138 
27139 		if (ipif == NULL) {
27140 			mutex_exit(&ill->ill_lock);
27141 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27142 			freemsg(mp);
27143 			freeb(mp1);
27144 			return;
27145 		}
27146 		ipif_refhold_locked(ipif);
27147 		mutex_exit(&ill->ill_lock);
27148 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27149 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27150 		    ipif, fake_ire->ire_zoneid, NULL,
27151 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27152 		ipif_refrele(ipif);
27153 		if (ire == NULL) {
27154 			/*
27155 			 * no ire was found; check if there is an nce
27156 			 * for this lookup; if it has no ire's pointing at it
27157 			 * cleanup.
27158 			 */
27159 			if ((nce = ndp_lookup_v4(ill,
27160 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27161 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27162 			    B_FALSE)) != NULL) {
27163 				/*
27164 				 * cleanup: just reset nce.
27165 				 * We check for refcnt 2 (one for the nce
27166 				 * hash list + 1 for the ref taken by
27167 				 * ndp_lookup_v4) to ensure that there are
27168 				 * no ire's pointing at the nce.
27169 				 */
27170 				if (nce->nce_refcnt == 2) {
27171 					nce = nce_reinit(nce);
27172 				}
27173 				if (nce != NULL)
27174 					NCE_REFRELE(nce);
27175 			}
27176 			freeb(mp1);  /* dl_unitdata response */
27177 			freemsg(mp); /* fake ire */
27178 			return;
27179 		}
27180 		nce = ire->ire_nce;
27181 		DTRACE_PROBE2(ire__arpresolve__type,
27182 		    ire_t *, ire, nce_t *, nce);
27183 		ASSERT(nce->nce_state != ND_INITIAL);
27184 		mutex_enter(&nce->nce_lock);
27185 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27186 		if (nce->nce_state == ND_REACHABLE) {
27187 			/*
27188 			 * Someone resolved this before us;
27189 			 * our response is not needed any more.
27190 			 */
27191 			mutex_exit(&nce->nce_lock);
27192 			freeb(mp1);  /* dl_unitdata response */
27193 		} else {
27194 			if (nce->nce_res_mp != NULL) {
27195 				freemsg(nce->nce_res_mp);
27196 				/* existing dl_unitdata template */
27197 			}
27198 			nce->nce_res_mp = mp1;
27199 			nce->nce_state = ND_REACHABLE;
27200 			mutex_exit(&nce->nce_lock);
27201 			ire_fastpath(ire);
27202 		}
27203 		/*
27204 		 * The cached nce_t has been updated to be reachable;
27205 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27206 		 */
27207 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27208 		freemsg(mp);
27209 		/*
27210 		 * send out queued packets.
27211 		 */
27212 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27213 
27214 		IRE_REFRELE(ire);
27215 		return;
27216 	}
27217 	default:
27218 		break;
27219 	}
27220 	if (q->q_next) {
27221 		putnext(q, mp);
27222 	} else
27223 		freemsg(mp);
27224 }
27225 
27226 /*
27227  * Process IP options in an outbound packet.  Modify the destination if there
27228  * is a source route option.
27229  * Returns non-zero if something fails in which case an ICMP error has been
27230  * sent and mp freed.
27231  */
27232 static int
27233 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27234     boolean_t mctl_present, zoneid_t zoneid)
27235 {
27236 	ipoptp_t	opts;
27237 	uchar_t		*opt;
27238 	uint8_t		optval;
27239 	uint8_t		optlen;
27240 	ipaddr_t	dst;
27241 	intptr_t	code = 0;
27242 	mblk_t		*mp;
27243 	ire_t		*ire = NULL;
27244 
27245 	ip2dbg(("ip_wput_options\n"));
27246 	mp = ipsec_mp;
27247 	if (mctl_present) {
27248 		mp = ipsec_mp->b_cont;
27249 	}
27250 
27251 	dst = ipha->ipha_dst;
27252 	for (optval = ipoptp_first(&opts, ipha);
27253 	    optval != IPOPT_EOL;
27254 	    optval = ipoptp_next(&opts)) {
27255 		opt = opts.ipoptp_cur;
27256 		optlen = opts.ipoptp_len;
27257 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27258 		    optval, optlen));
27259 		switch (optval) {
27260 			uint32_t off;
27261 		case IPOPT_SSRR:
27262 		case IPOPT_LSRR:
27263 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27264 				ip1dbg((
27265 				    "ip_wput_options: bad option offset\n"));
27266 				code = (char *)&opt[IPOPT_OLEN] -
27267 				    (char *)ipha;
27268 				goto param_prob;
27269 			}
27270 			off = opt[IPOPT_OFFSET];
27271 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27272 			    ntohl(dst)));
27273 			/*
27274 			 * For strict: verify that dst is directly
27275 			 * reachable.
27276 			 */
27277 			if (optval == IPOPT_SSRR) {
27278 				ire = ire_ftable_lookup(dst, 0, 0,
27279 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27280 				    MBLK_GETLABEL(mp),
27281 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27282 				if (ire == NULL) {
27283 					ip1dbg(("ip_wput_options: SSRR not"
27284 					    " directly reachable: 0x%x\n",
27285 					    ntohl(dst)));
27286 					goto bad_src_route;
27287 				}
27288 				ire_refrele(ire);
27289 			}
27290 			break;
27291 		case IPOPT_RR:
27292 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27293 				ip1dbg((
27294 				    "ip_wput_options: bad option offset\n"));
27295 				code = (char *)&opt[IPOPT_OLEN] -
27296 				    (char *)ipha;
27297 				goto param_prob;
27298 			}
27299 			break;
27300 		case IPOPT_TS:
27301 			/*
27302 			 * Verify that length >=5 and that there is either
27303 			 * room for another timestamp or that the overflow
27304 			 * counter is not maxed out.
27305 			 */
27306 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27307 			if (optlen < IPOPT_MINLEN_IT) {
27308 				goto param_prob;
27309 			}
27310 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27311 				ip1dbg((
27312 				    "ip_wput_options: bad option offset\n"));
27313 				code = (char *)&opt[IPOPT_OFFSET] -
27314 				    (char *)ipha;
27315 				goto param_prob;
27316 			}
27317 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27318 			case IPOPT_TS_TSONLY:
27319 				off = IPOPT_TS_TIMELEN;
27320 				break;
27321 			case IPOPT_TS_TSANDADDR:
27322 			case IPOPT_TS_PRESPEC:
27323 			case IPOPT_TS_PRESPEC_RFC791:
27324 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27325 				break;
27326 			default:
27327 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27328 				    (char *)ipha;
27329 				goto param_prob;
27330 			}
27331 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27332 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27333 				/*
27334 				 * No room and the overflow counter is 15
27335 				 * already.
27336 				 */
27337 				goto param_prob;
27338 			}
27339 			break;
27340 		}
27341 	}
27342 
27343 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27344 		return (0);
27345 
27346 	ip1dbg(("ip_wput_options: error processing IP options."));
27347 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27348 
27349 param_prob:
27350 	/*
27351 	 * Since ip_wput() isn't close to finished, we fill
27352 	 * in enough of the header for credible error reporting.
27353 	 */
27354 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27355 		/* Failed */
27356 		freemsg(ipsec_mp);
27357 		return (-1);
27358 	}
27359 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27360 	return (-1);
27361 
27362 bad_src_route:
27363 	/*
27364 	 * Since ip_wput() isn't close to finished, we fill
27365 	 * in enough of the header for credible error reporting.
27366 	 */
27367 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27368 		/* Failed */
27369 		freemsg(ipsec_mp);
27370 		return (-1);
27371 	}
27372 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27373 	return (-1);
27374 }
27375 
27376 /*
27377  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27378  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27379  * thru /etc/system.
27380  */
27381 #define	CONN_MAXDRAINCNT	64
27382 
27383 static void
27384 conn_drain_init(void)
27385 {
27386 	int i;
27387 
27388 	conn_drain_list_cnt = conn_drain_nthreads;
27389 
27390 	if ((conn_drain_list_cnt == 0) ||
27391 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27392 		/*
27393 		 * Default value of the number of drainers is the
27394 		 * number of cpus, subject to maximum of 8 drainers.
27395 		 */
27396 		if (boot_max_ncpus != -1)
27397 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27398 		else
27399 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27400 	}
27401 
27402 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27403 	    KM_SLEEP);
27404 
27405 	for (i = 0; i < conn_drain_list_cnt; i++) {
27406 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27407 		    MUTEX_DEFAULT, NULL);
27408 	}
27409 }
27410 
27411 static void
27412 conn_drain_fini(void)
27413 {
27414 	int i;
27415 
27416 	for (i = 0; i < conn_drain_list_cnt; i++)
27417 		mutex_destroy(&conn_drain_list[i].idl_lock);
27418 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27419 	conn_drain_list = NULL;
27420 }
27421 
27422 /*
27423  * Note: For an overview of how flowcontrol is handled in IP please see the
27424  * IP Flowcontrol notes at the top of this file.
27425  *
27426  * Flow control has blocked us from proceeding. Insert the given conn in one
27427  * of the conn drain lists. These conn wq's will be qenabled later on when
27428  * STREAMS flow control does a backenable. conn_walk_drain will enable
27429  * the first conn in each of these drain lists. Each of these qenabled conns
27430  * in turn enables the next in the list, after it runs, or when it closes,
27431  * thus sustaining the drain process.
27432  *
27433  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27434  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27435  * running at any time, on a given conn, since there can be only 1 service proc
27436  * running on a queue at any time.
27437  */
27438 void
27439 conn_drain_insert(conn_t *connp)
27440 {
27441 	idl_t	*idl;
27442 	uint_t	index;
27443 
27444 	mutex_enter(&connp->conn_lock);
27445 	if (connp->conn_state_flags & CONN_CLOSING) {
27446 		/*
27447 		 * The conn is closing as a result of which CONN_CLOSING
27448 		 * is set. Return.
27449 		 */
27450 		mutex_exit(&connp->conn_lock);
27451 		return;
27452 	} else if (connp->conn_idl == NULL) {
27453 		/*
27454 		 * Assign the next drain list round robin. We dont' use
27455 		 * a lock, and thus it may not be strictly round robin.
27456 		 * Atomicity of load/stores is enough to make sure that
27457 		 * conn_drain_list_index is always within bounds.
27458 		 */
27459 		index = conn_drain_list_index;
27460 		ASSERT(index < conn_drain_list_cnt);
27461 		connp->conn_idl = &conn_drain_list[index];
27462 		index++;
27463 		if (index == conn_drain_list_cnt)
27464 			index = 0;
27465 		conn_drain_list_index = index;
27466 	}
27467 	mutex_exit(&connp->conn_lock);
27468 
27469 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27470 	if ((connp->conn_drain_prev != NULL) ||
27471 	    (connp->conn_state_flags & CONN_CLOSING)) {
27472 		/*
27473 		 * The conn is already in the drain list, OR
27474 		 * the conn is closing. We need to check again for
27475 		 * the closing case again since close can happen
27476 		 * after we drop the conn_lock, and before we
27477 		 * acquire the CONN_DRAIN_LIST_LOCK.
27478 		 */
27479 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27480 		return;
27481 	} else {
27482 		idl = connp->conn_idl;
27483 	}
27484 
27485 	/*
27486 	 * The conn is not in the drain list. Insert it at the
27487 	 * tail of the drain list. The drain list is circular
27488 	 * and doubly linked. idl_conn points to the 1st element
27489 	 * in the list.
27490 	 */
27491 	if (idl->idl_conn == NULL) {
27492 		idl->idl_conn = connp;
27493 		connp->conn_drain_next = connp;
27494 		connp->conn_drain_prev = connp;
27495 	} else {
27496 		conn_t *head = idl->idl_conn;
27497 
27498 		connp->conn_drain_next = head;
27499 		connp->conn_drain_prev = head->conn_drain_prev;
27500 		head->conn_drain_prev->conn_drain_next = connp;
27501 		head->conn_drain_prev = connp;
27502 	}
27503 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27504 }
27505 
27506 /*
27507  * This conn is closing, and we are called from ip_close. OR
27508  * This conn has been serviced by ip_wsrv, and we need to do the tail
27509  * processing.
27510  * If this conn is part of the drain list, we may need to sustain the drain
27511  * process by qenabling the next conn in the drain list. We may also need to
27512  * remove this conn from the list, if it is done.
27513  */
27514 static void
27515 conn_drain_tail(conn_t *connp, boolean_t closing)
27516 {
27517 	idl_t *idl;
27518 
27519 	/*
27520 	 * connp->conn_idl is stable at this point, and no lock is needed
27521 	 * to check it. If we are called from ip_close, close has already
27522 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27523 	 * called us only because conn_idl is non-null. If we are called thru
27524 	 * service, conn_idl could be null, but it cannot change because
27525 	 * service is single-threaded per queue, and there cannot be another
27526 	 * instance of service trying to call conn_drain_insert on this conn
27527 	 * now.
27528 	 */
27529 	ASSERT(!closing || (connp->conn_idl != NULL));
27530 
27531 	/*
27532 	 * If connp->conn_idl is null, the conn has not been inserted into any
27533 	 * drain list even once since creation of the conn. Just return.
27534 	 */
27535 	if (connp->conn_idl == NULL)
27536 		return;
27537 
27538 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27539 
27540 	if (connp->conn_drain_prev == NULL) {
27541 		/* This conn is currently not in the drain list.  */
27542 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27543 		return;
27544 	}
27545 	idl = connp->conn_idl;
27546 	if (idl->idl_conn_draining == connp) {
27547 		/*
27548 		 * This conn is the current drainer. If this is the last conn
27549 		 * in the drain list, we need to do more checks, in the 'if'
27550 		 * below. Otherwwise we need to just qenable the next conn,
27551 		 * to sustain the draining, and is handled in the 'else'
27552 		 * below.
27553 		 */
27554 		if (connp->conn_drain_next == idl->idl_conn) {
27555 			/*
27556 			 * This conn is the last in this list. This round
27557 			 * of draining is complete. If idl_repeat is set,
27558 			 * it means another flow enabling has happened from
27559 			 * the driver/streams and we need to another round
27560 			 * of draining.
27561 			 * If there are more than 2 conns in the drain list,
27562 			 * do a left rotate by 1, so that all conns except the
27563 			 * conn at the head move towards the head by 1, and the
27564 			 * the conn at the head goes to the tail. This attempts
27565 			 * a more even share for all queues that are being
27566 			 * drained.
27567 			 */
27568 			if ((connp->conn_drain_next != connp) &&
27569 			    (idl->idl_conn->conn_drain_next != connp)) {
27570 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27571 			}
27572 			if (idl->idl_repeat) {
27573 				qenable(idl->idl_conn->conn_wq);
27574 				idl->idl_conn_draining = idl->idl_conn;
27575 				idl->idl_repeat = 0;
27576 			} else {
27577 				idl->idl_conn_draining = NULL;
27578 			}
27579 		} else {
27580 			/*
27581 			 * If the next queue that we are now qenable'ing,
27582 			 * is closing, it will remove itself from this list
27583 			 * and qenable the subsequent queue in ip_close().
27584 			 * Serialization is acheived thru idl_lock.
27585 			 */
27586 			qenable(connp->conn_drain_next->conn_wq);
27587 			idl->idl_conn_draining = connp->conn_drain_next;
27588 		}
27589 	}
27590 	if (!connp->conn_did_putbq || closing) {
27591 		/*
27592 		 * Remove ourself from the drain list, if we did not do
27593 		 * a putbq, or if the conn is closing.
27594 		 * Note: It is possible that q->q_first is non-null. It means
27595 		 * that these messages landed after we did a enableok() in
27596 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27597 		 * service them.
27598 		 */
27599 		if (connp->conn_drain_next == connp) {
27600 			/* Singleton in the list */
27601 			ASSERT(connp->conn_drain_prev == connp);
27602 			idl->idl_conn = NULL;
27603 			idl->idl_conn_draining = NULL;
27604 		} else {
27605 			connp->conn_drain_prev->conn_drain_next =
27606 			    connp->conn_drain_next;
27607 			connp->conn_drain_next->conn_drain_prev =
27608 			    connp->conn_drain_prev;
27609 			if (idl->idl_conn == connp)
27610 				idl->idl_conn = connp->conn_drain_next;
27611 			ASSERT(idl->idl_conn_draining != connp);
27612 
27613 		}
27614 		connp->conn_drain_next = NULL;
27615 		connp->conn_drain_prev = NULL;
27616 	}
27617 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27618 }
27619 
27620 /*
27621  * Write service routine. Shared perimeter entry point.
27622  * ip_wsrv can be called in any of the following ways.
27623  * 1. The device queue's messages has fallen below the low water mark
27624  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27625  *    the drain lists and backenable the first conn in each list.
27626  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27627  *    qenabled non-tcp upper layers. We start dequeing messages and call
27628  *    ip_wput for each message.
27629  */
27630 
27631 void
27632 ip_wsrv(queue_t *q)
27633 {
27634 	conn_t	*connp;
27635 	ill_t	*ill;
27636 	mblk_t	*mp;
27637 
27638 	if (q->q_next) {
27639 		ill = (ill_t *)q->q_ptr;
27640 		if (ill->ill_state_flags == 0) {
27641 			/*
27642 			 * The device flow control has opened up.
27643 			 * Walk through conn drain lists and qenable the
27644 			 * first conn in each list. This makes sense only
27645 			 * if the stream is fully plumbed and setup.
27646 			 * Hence the if check above.
27647 			 */
27648 			ip1dbg(("ip_wsrv: walking\n"));
27649 			conn_walk_drain();
27650 		}
27651 		return;
27652 	}
27653 
27654 	connp = Q_TO_CONN(q);
27655 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27656 
27657 	/*
27658 	 * 1. Set conn_draining flag to signal that service is active.
27659 	 *
27660 	 * 2. ip_output determines whether it has been called from service,
27661 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27662 	 *    has been called from service.
27663 	 *
27664 	 * 3. Message ordering is preserved by the following logic.
27665 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27666 	 *    the message at the tail, if conn_draining is set (i.e. service
27667 	 *    is running) or if q->q_first is non-null.
27668 	 *
27669 	 *    ii. If ip_output is called from service, and if ip_output cannot
27670 	 *    putnext due to flow control, it does a putbq.
27671 	 *
27672 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27673 	 *    (causing an infinite loop).
27674 	 */
27675 	ASSERT(!connp->conn_did_putbq);
27676 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27677 		connp->conn_draining = 1;
27678 		noenable(q);
27679 		while ((mp = getq(q)) != NULL) {
27680 			ASSERT(CONN_Q(q));
27681 
27682 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27683 			if (connp->conn_did_putbq) {
27684 				/* ip_wput did a putbq */
27685 				break;
27686 			}
27687 		}
27688 		/*
27689 		 * At this point, a thread coming down from top, calling
27690 		 * ip_wput, may end up queueing the message. We have not yet
27691 		 * enabled the queue, so ip_wsrv won't be called again.
27692 		 * To avoid this race, check q->q_first again (in the loop)
27693 		 * If the other thread queued the message before we call
27694 		 * enableok(), we will catch it in the q->q_first check.
27695 		 * If the other thread queues the message after we call
27696 		 * enableok(), ip_wsrv will be called again by STREAMS.
27697 		 */
27698 		connp->conn_draining = 0;
27699 		enableok(q);
27700 	}
27701 
27702 	/* Enable the next conn for draining */
27703 	conn_drain_tail(connp, B_FALSE);
27704 
27705 	connp->conn_did_putbq = 0;
27706 }
27707 
27708 /*
27709  * Walk the list of all conn's calling the function provided with the
27710  * specified argument for each.	 Note that this only walks conn's that
27711  * have been bound.
27712  * Applies to both IPv4 and IPv6.
27713  */
27714 static void
27715 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27716 {
27717 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27718 	    func, arg, zoneid);
27719 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27720 	    func, arg, zoneid);
27721 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27722 	    func, arg, zoneid);
27723 	conn_walk_fanout_table(ipcl_proto_fanout,
27724 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27725 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27726 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27727 }
27728 
27729 /*
27730  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27731  * of conns that need to be drained, check if drain is already in progress.
27732  * If so set the idl_repeat bit, indicating that the last conn in the list
27733  * needs to reinitiate the drain once again, for the list. If drain is not
27734  * in progress for the list, initiate the draining, by qenabling the 1st
27735  * conn in the list. The drain is self-sustaining, each qenabled conn will
27736  * in turn qenable the next conn, when it is done/blocked/closing.
27737  */
27738 static void
27739 conn_walk_drain(void)
27740 {
27741 	int i;
27742 	idl_t *idl;
27743 
27744 	IP_STAT(ip_conn_walk_drain);
27745 
27746 	for (i = 0; i < conn_drain_list_cnt; i++) {
27747 		idl = &conn_drain_list[i];
27748 		mutex_enter(&idl->idl_lock);
27749 		if (idl->idl_conn == NULL) {
27750 			mutex_exit(&idl->idl_lock);
27751 			continue;
27752 		}
27753 		/*
27754 		 * If this list is not being drained currently by
27755 		 * an ip_wsrv thread, start the process.
27756 		 */
27757 		if (idl->idl_conn_draining == NULL) {
27758 			ASSERT(idl->idl_repeat == 0);
27759 			qenable(idl->idl_conn->conn_wq);
27760 			idl->idl_conn_draining = idl->idl_conn;
27761 		} else {
27762 			idl->idl_repeat = 1;
27763 		}
27764 		mutex_exit(&idl->idl_lock);
27765 	}
27766 }
27767 
27768 /*
27769  * Walk an conn hash table of `count' buckets, calling func for each entry.
27770  */
27771 static void
27772 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27773     zoneid_t zoneid)
27774 {
27775 	conn_t	*connp;
27776 
27777 	while (count-- > 0) {
27778 		mutex_enter(&connfp->connf_lock);
27779 		for (connp = connfp->connf_head; connp != NULL;
27780 		    connp = connp->conn_next) {
27781 			if (zoneid == GLOBAL_ZONEID ||
27782 			    zoneid == connp->conn_zoneid) {
27783 				CONN_INC_REF(connp);
27784 				mutex_exit(&connfp->connf_lock);
27785 				(*func)(connp, arg);
27786 				mutex_enter(&connfp->connf_lock);
27787 				CONN_DEC_REF(connp);
27788 			}
27789 		}
27790 		mutex_exit(&connfp->connf_lock);
27791 		connfp++;
27792 	}
27793 }
27794 
27795 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27796 static void
27797 conn_report1(conn_t *connp, void *mp)
27798 {
27799 	char	buf1[INET6_ADDRSTRLEN];
27800 	char	buf2[INET6_ADDRSTRLEN];
27801 	uint_t	print_len, buf_len;
27802 
27803 	ASSERT(connp != NULL);
27804 
27805 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27806 	if (buf_len <= 0)
27807 		return;
27808 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27809 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27810 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27811 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27812 	    "%5d %s/%05d %s/%05d\n",
27813 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27814 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27815 	    buf1, connp->conn_lport,
27816 	    buf2, connp->conn_fport);
27817 	if (print_len < buf_len) {
27818 		((mblk_t *)mp)->b_wptr += print_len;
27819 	} else {
27820 		((mblk_t *)mp)->b_wptr += buf_len;
27821 	}
27822 }
27823 
27824 /*
27825  * Named Dispatch routine to produce a formatted report on all conns
27826  * that are listed in one of the fanout tables.
27827  * This report is accessed by using the ndd utility to "get" ND variable
27828  * "ip_conn_status".
27829  */
27830 /* ARGSUSED */
27831 static int
27832 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27833 {
27834 	(void) mi_mpprintf(mp,
27835 	    "CONN      " MI_COL_HDRPAD_STR
27836 	    "rfq      " MI_COL_HDRPAD_STR
27837 	    "stq      " MI_COL_HDRPAD_STR
27838 	    " zone local                 remote");
27839 
27840 	/*
27841 	 * Because of the ndd constraint, at most we can have 64K buffer
27842 	 * to put in all conn info.  So to be more efficient, just
27843 	 * allocate a 64K buffer here, assuming we need that large buffer.
27844 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27845 	 */
27846 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27847 		/* The following may work even if we cannot get a large buf. */
27848 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27849 		return (0);
27850 	}
27851 
27852 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27853 	return (0);
27854 }
27855 
27856 /*
27857  * Determine if the ill and multicast aspects of that packets
27858  * "matches" the conn.
27859  */
27860 boolean_t
27861 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27862     zoneid_t zoneid)
27863 {
27864 	ill_t *in_ill;
27865 	boolean_t found;
27866 	ipif_t *ipif;
27867 	ire_t *ire;
27868 	ipaddr_t dst, src;
27869 
27870 	dst = ipha->ipha_dst;
27871 	src = ipha->ipha_src;
27872 
27873 	/*
27874 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27875 	 * unicast, broadcast and multicast reception to
27876 	 * conn_incoming_ill. conn_wantpacket itself is called
27877 	 * only for BROADCAST and multicast.
27878 	 *
27879 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27880 	 *    is part of a group. Hence, we should be receiving
27881 	 *    just one copy of broadcast for the whole group.
27882 	 *    Thus, if it is part of the group the packet could
27883 	 *    come on any ill of the group and hence we need a
27884 	 *    match on the group. Otherwise, match on ill should
27885 	 *    be sufficient.
27886 	 *
27887 	 * 2) ip_rput does not suppress duplicate multicast packets.
27888 	 *    If there are two interfaces in a ill group and we have
27889 	 *    2 applications (conns) joined a multicast group G on
27890 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27891 	 *    will give us two packets because we join G on both the
27892 	 *    interfaces rather than nominating just one interface
27893 	 *    for receiving multicast like broadcast above. So,
27894 	 *    we have to call ilg_lookup_ill to filter out duplicate
27895 	 *    copies, if ill is part of a group.
27896 	 */
27897 	in_ill = connp->conn_incoming_ill;
27898 	if (in_ill != NULL) {
27899 		if (in_ill->ill_group == NULL) {
27900 			if (in_ill != ill)
27901 				return (B_FALSE);
27902 		} else if (in_ill->ill_group != ill->ill_group) {
27903 			return (B_FALSE);
27904 		}
27905 	}
27906 
27907 	if (!CLASSD(dst)) {
27908 		if (IPCL_ZONE_MATCH(connp, zoneid))
27909 			return (B_TRUE);
27910 		/*
27911 		 * The conn is in a different zone; we need to check that this
27912 		 * broadcast address is configured in the application's zone and
27913 		 * on one ill in the group.
27914 		 */
27915 		ipif = ipif_get_next_ipif(NULL, ill);
27916 		if (ipif == NULL)
27917 			return (B_FALSE);
27918 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27919 		    connp->conn_zoneid, NULL,
27920 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27921 		ipif_refrele(ipif);
27922 		if (ire != NULL) {
27923 			ire_refrele(ire);
27924 			return (B_TRUE);
27925 		} else {
27926 			return (B_FALSE);
27927 		}
27928 	}
27929 
27930 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27931 	    connp->conn_zoneid == zoneid) {
27932 		/*
27933 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27934 		 * disabled, therefore we don't dispatch the multicast packet to
27935 		 * the sending zone.
27936 		 */
27937 		return (B_FALSE);
27938 	}
27939 
27940 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27941 	    connp->conn_zoneid != zoneid) {
27942 		/*
27943 		 * Multicast packet on the loopback interface: we only match
27944 		 * conns who joined the group in the specified zone.
27945 		 */
27946 		return (B_FALSE);
27947 	}
27948 
27949 	if (connp->conn_multi_router) {
27950 		/* multicast packet and multicast router socket: send up */
27951 		return (B_TRUE);
27952 	}
27953 
27954 	mutex_enter(&connp->conn_lock);
27955 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27956 	mutex_exit(&connp->conn_lock);
27957 	return (found);
27958 }
27959 
27960 /*
27961  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27962  */
27963 /* ARGSUSED */
27964 static void
27965 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27966 {
27967 	ill_t *ill = (ill_t *)q->q_ptr;
27968 	mblk_t	*mp1, *mp2;
27969 	ipif_t  *ipif;
27970 	int err = 0;
27971 	conn_t *connp = NULL;
27972 	ipsq_t	*ipsq;
27973 	arc_t	*arc;
27974 
27975 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27976 
27977 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27978 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27979 
27980 	ASSERT(IAM_WRITER_ILL(ill));
27981 	mp2 = mp->b_cont;
27982 	mp->b_cont = NULL;
27983 
27984 	/*
27985 	 * We have now received the arp bringup completion message
27986 	 * from ARP. Mark the arp bringup as done. Also if the arp
27987 	 * stream has already started closing, send up the AR_ARP_CLOSING
27988 	 * ack now since ARP is waiting in close for this ack.
27989 	 */
27990 	mutex_enter(&ill->ill_lock);
27991 	ill->ill_arp_bringup_pending = 0;
27992 	if (ill->ill_arp_closing) {
27993 		mutex_exit(&ill->ill_lock);
27994 		/* Let's reuse the mp for sending the ack */
27995 		arc = (arc_t *)mp->b_rptr;
27996 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27997 		arc->arc_cmd = AR_ARP_CLOSING;
27998 		qreply(q, mp);
27999 	} else {
28000 		mutex_exit(&ill->ill_lock);
28001 		freeb(mp);
28002 	}
28003 
28004 	/* We should have an IOCTL waiting on this. */
28005 	ipsq = ill->ill_phyint->phyint_ipsq;
28006 	ipif = ipsq->ipsq_pending_ipif;
28007 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28008 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
28009 	if (mp1 == NULL) {
28010 		/* bringup was aborted by the user */
28011 		freemsg(mp2);
28012 		return;
28013 	}
28014 	ASSERT(connp != NULL);
28015 	q = CONNP_TO_WQ(connp);
28016 	/*
28017 	 * If the DL_BIND_REQ fails, it is noted
28018 	 * in arc_name_offset.
28019 	 */
28020 	err = *((int *)mp2->b_rptr);
28021 	if (err == 0) {
28022 		if (ipif->ipif_isv6) {
28023 			if ((err = ipif_up_done_v6(ipif)) != 0)
28024 				ip0dbg(("ip_arp_done: init failed\n"));
28025 		} else {
28026 			if ((err = ipif_up_done(ipif)) != 0)
28027 				ip0dbg(("ip_arp_done: init failed\n"));
28028 		}
28029 	} else {
28030 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28031 	}
28032 
28033 	freemsg(mp2);
28034 
28035 	if ((err == 0) && (ill->ill_up_ipifs)) {
28036 		err = ill_up_ipifs(ill, q, mp1);
28037 		if (err == EINPROGRESS)
28038 			return;
28039 	}
28040 
28041 	if (ill->ill_up_ipifs) {
28042 		ill_group_cleanup(ill);
28043 	}
28044 
28045 	/*
28046 	 * The ioctl must complete now without EINPROGRESS
28047 	 * since ipsq_pending_mp_get has removed the ioctl mblk
28048 	 * from ipsq_pending_mp. Otherwise the ioctl will be
28049 	 * stuck for ever in the ipsq.
28050 	 */
28051 	ASSERT(err != EINPROGRESS);
28052 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
28053 }
28054 
28055 /* Allocate the private structure */
28056 static int
28057 ip_priv_alloc(void **bufp)
28058 {
28059 	void	*buf;
28060 
28061 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28062 		return (ENOMEM);
28063 
28064 	*bufp = buf;
28065 	return (0);
28066 }
28067 
28068 /* Function to delete the private structure */
28069 void
28070 ip_priv_free(void *buf)
28071 {
28072 	ASSERT(buf != NULL);
28073 	kmem_free(buf, sizeof (ip_priv_t));
28074 }
28075 
28076 /*
28077  * The entry point for IPPF processing.
28078  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28079  * routine just returns.
28080  *
28081  * When called, ip_process generates an ipp_packet_t structure
28082  * which holds the state information for this packet and invokes the
28083  * the classifier (via ipp_packet_process). The classification, depending on
28084  * configured filters, results in a list of actions for this packet. Invoking
28085  * an action may cause the packet to be dropped, in which case the resulting
28086  * mblk (*mpp) is NULL. proc indicates the callout position for
28087  * this packet and ill_index is the interface this packet on or will leave
28088  * on (inbound and outbound resp.).
28089  */
28090 void
28091 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28092 {
28093 	mblk_t		*mp;
28094 	ip_priv_t	*priv;
28095 	ipp_action_id_t	aid;
28096 	int		rc = 0;
28097 	ipp_packet_t	*pp;
28098 #define	IP_CLASS	"ip"
28099 
28100 	/* If the classifier is not loaded, return  */
28101 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28102 		return;
28103 	}
28104 
28105 	mp = *mpp;
28106 	ASSERT(mp != NULL);
28107 
28108 	/* Allocate the packet structure */
28109 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28110 	if (rc != 0) {
28111 		*mpp = NULL;
28112 		freemsg(mp);
28113 		return;
28114 	}
28115 
28116 	/* Allocate the private structure */
28117 	rc = ip_priv_alloc((void **)&priv);
28118 	if (rc != 0) {
28119 		*mpp = NULL;
28120 		freemsg(mp);
28121 		ipp_packet_free(pp);
28122 		return;
28123 	}
28124 	priv->proc = proc;
28125 	priv->ill_index = ill_index;
28126 	ipp_packet_set_private(pp, priv, ip_priv_free);
28127 	ipp_packet_set_data(pp, mp);
28128 
28129 	/* Invoke the classifier */
28130 	rc = ipp_packet_process(&pp);
28131 	if (pp != NULL) {
28132 		mp = ipp_packet_get_data(pp);
28133 		ipp_packet_free(pp);
28134 		if (rc != 0) {
28135 			freemsg(mp);
28136 			*mpp = NULL;
28137 		}
28138 	} else {
28139 		*mpp = NULL;
28140 	}
28141 #undef	IP_CLASS
28142 }
28143 
28144 /*
28145  * Propagate a multicast group membership operation (add/drop) on
28146  * all the interfaces crossed by the related multirt routes.
28147  * The call is considered successful if the operation succeeds
28148  * on at least one interface.
28149  */
28150 static int
28151 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28152     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28153     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28154     mblk_t *first_mp)
28155 {
28156 	ire_t		*ire_gw;
28157 	irb_t		*irb;
28158 	int		error = 0;
28159 	opt_restart_t	*or;
28160 
28161 	irb = ire->ire_bucket;
28162 	ASSERT(irb != NULL);
28163 
28164 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28165 
28166 	or = (opt_restart_t *)first_mp->b_rptr;
28167 	IRB_REFHOLD(irb);
28168 	for (; ire != NULL; ire = ire->ire_next) {
28169 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28170 			continue;
28171 		if (ire->ire_addr != group)
28172 			continue;
28173 
28174 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28175 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28176 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28177 		/* No resolver exists for the gateway; skip this ire. */
28178 		if (ire_gw == NULL)
28179 			continue;
28180 
28181 		/*
28182 		 * This function can return EINPROGRESS. If so the operation
28183 		 * will be restarted from ip_restart_optmgmt which will
28184 		 * call ip_opt_set and option processing will restart for
28185 		 * this option. So we may end up calling 'fn' more than once.
28186 		 * This requires that 'fn' is idempotent except for the
28187 		 * return value. The operation is considered a success if
28188 		 * it succeeds at least once on any one interface.
28189 		 */
28190 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28191 		    NULL, fmode, src, first_mp);
28192 		if (error == 0)
28193 			or->or_private = CGTP_MCAST_SUCCESS;
28194 
28195 		if (ip_debug > 0) {
28196 			ulong_t	off;
28197 			char	*ksym;
28198 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28199 			ip2dbg(("ip_multirt_apply_membership: "
28200 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28201 			    "error %d [success %u]\n",
28202 			    ksym ? ksym : "?",
28203 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28204 			    error, or->or_private));
28205 		}
28206 
28207 		ire_refrele(ire_gw);
28208 		if (error == EINPROGRESS) {
28209 			IRB_REFRELE(irb);
28210 			return (error);
28211 		}
28212 	}
28213 	IRB_REFRELE(irb);
28214 	/*
28215 	 * Consider the call as successful if we succeeded on at least
28216 	 * one interface. Otherwise, return the last encountered error.
28217 	 */
28218 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28219 }
28220 
28221 
28222 /*
28223  * Issue a warning regarding a route crossing an interface with an
28224  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28225  * amount of time is logged.
28226  */
28227 static void
28228 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28229 {
28230 	hrtime_t	current = gethrtime();
28231 	char		buf[INET_ADDRSTRLEN];
28232 
28233 	/* Convert interval in ms to hrtime in ns */
28234 	if (multirt_bad_mtu_last_time +
28235 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28236 	    current) {
28237 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28238 		    "to %s, incorrect MTU %u (expected %u)\n",
28239 		    ip_dot_addr(ire->ire_addr, buf),
28240 		    ire->ire_max_frag, max_frag);
28241 
28242 		multirt_bad_mtu_last_time = current;
28243 	}
28244 }
28245 
28246 
28247 /*
28248  * Get the CGTP (multirouting) filtering status.
28249  * If 0, the CGTP hooks are transparent.
28250  */
28251 /* ARGSUSED */
28252 static int
28253 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28254 {
28255 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28256 
28257 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28258 	return (0);
28259 }
28260 
28261 
28262 /*
28263  * Set the CGTP (multirouting) filtering status.
28264  * If the status is changed from active to transparent
28265  * or from transparent to active, forward the new status
28266  * to the filtering module (if loaded).
28267  */
28268 /* ARGSUSED */
28269 static int
28270 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28271     cred_t *ioc_cr)
28272 {
28273 	long		new_value;
28274 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28275 
28276 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28277 	    new_value < 0 || new_value > 1) {
28278 		return (EINVAL);
28279 	}
28280 
28281 	/*
28282 	 * Do not enable CGTP filtering - thus preventing the hooks
28283 	 * from being invoked - if the version number of the
28284 	 * filtering module hooks does not match.
28285 	 */
28286 	if ((ip_cgtp_filter_ops != NULL) &&
28287 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28288 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28289 		    "(module hooks version %d, expecting %d)\n",
28290 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28291 		return (ENOTSUP);
28292 	}
28293 
28294 	if ((!*ip_cgtp_filter_value) && new_value) {
28295 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28296 		    ip_cgtp_filter_ops == NULL ?
28297 		    " (module not loaded)" : "");
28298 	}
28299 	if (*ip_cgtp_filter_value && (!new_value)) {
28300 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28301 		    ip_cgtp_filter_ops == NULL ?
28302 		    " (module not loaded)" : "");
28303 	}
28304 
28305 	if (ip_cgtp_filter_ops != NULL) {
28306 		int	res;
28307 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28308 			return (res);
28309 		}
28310 	}
28311 
28312 	*ip_cgtp_filter_value = (boolean_t)new_value;
28313 
28314 	return (0);
28315 }
28316 
28317 
28318 /*
28319  * Return the expected CGTP hooks version number.
28320  */
28321 int
28322 ip_cgtp_filter_supported(void)
28323 {
28324 	return (ip_cgtp_filter_rev);
28325 }
28326 
28327 
28328 /*
28329  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28330  * or by invoking this function. In the first case, the version number
28331  * of the registered structure is checked at hooks activation time
28332  * in ip_cgtp_filter_set().
28333  */
28334 int
28335 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28336 {
28337 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28338 		return (ENOTSUP);
28339 
28340 	ip_cgtp_filter_ops = ops;
28341 	return (0);
28342 }
28343 
28344 static squeue_func_t
28345 ip_squeue_switch(int val)
28346 {
28347 	squeue_func_t rval = squeue_fill;
28348 
28349 	switch (val) {
28350 	case IP_SQUEUE_ENTER_NODRAIN:
28351 		rval = squeue_enter_nodrain;
28352 		break;
28353 	case IP_SQUEUE_ENTER:
28354 		rval = squeue_enter;
28355 		break;
28356 	default:
28357 		break;
28358 	}
28359 	return (rval);
28360 }
28361 
28362 /* ARGSUSED */
28363 static int
28364 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28365     caddr_t addr, cred_t *cr)
28366 {
28367 	int *v = (int *)addr;
28368 	long new_value;
28369 
28370 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28371 		return (EINVAL);
28372 
28373 	ip_input_proc = ip_squeue_switch(new_value);
28374 	*v = new_value;
28375 	return (0);
28376 }
28377 
28378 /* ARGSUSED */
28379 static int
28380 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28381     caddr_t addr, cred_t *cr)
28382 {
28383 	int *v = (int *)addr;
28384 	long new_value;
28385 
28386 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28387 		return (EINVAL);
28388 
28389 	*v = new_value;
28390 	return (0);
28391 }
28392 
28393 static void
28394 ip_kstat_init(void)
28395 {
28396 	ip_named_kstat_t template = {
28397 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28398 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28399 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28400 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28401 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28402 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28403 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28404 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28405 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28406 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28407 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28408 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28409 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28410 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28411 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28412 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28413 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28414 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28415 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28416 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28417 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28418 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28419 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28420 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28421 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28422 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28423 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28424 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28425 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28426 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28427 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28428 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28429 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28430 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28431 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28432 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28433 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28434 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28435 	};
28436 
28437 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28438 					NUM_OF_FIELDS(ip_named_kstat_t),
28439 					0);
28440 	if (!ip_mibkp)
28441 		return;
28442 
28443 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28444 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28445 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28446 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28447 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28448 
28449 	template.netToMediaEntrySize.value.i32 =
28450 		sizeof (mib2_ipNetToMediaEntry_t);
28451 
28452 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28453 
28454 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28455 
28456 	ip_mibkp->ks_update = ip_kstat_update;
28457 
28458 	kstat_install(ip_mibkp);
28459 }
28460 
28461 static void
28462 ip_kstat_fini(void)
28463 {
28464 
28465 	if (ip_mibkp != NULL) {
28466 		kstat_delete(ip_mibkp);
28467 		ip_mibkp = NULL;
28468 	}
28469 }
28470 
28471 static int
28472 ip_kstat_update(kstat_t *kp, int rw)
28473 {
28474 	ip_named_kstat_t *ipkp;
28475 
28476 	if (!kp || !kp->ks_data)
28477 		return (EIO);
28478 
28479 	if (rw == KSTAT_WRITE)
28480 		return (EACCES);
28481 
28482 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28483 
28484 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28485 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28486 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28487 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28488 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28489 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28490 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28491 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28492 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28493 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28494 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28495 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28496 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28497 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28498 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28499 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28500 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28501 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28502 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28503 
28504 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28505 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28506 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28507 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28508 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28509 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28510 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28511 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28512 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28513 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28514 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28515 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28516 
28517 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28518 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28519 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28520 
28521 	return (0);
28522 }
28523 
28524 static void
28525 icmp_kstat_init(void)
28526 {
28527 	icmp_named_kstat_t template = {
28528 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28529 		{ "inErrors",		KSTAT_DATA_UINT32 },
28530 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28531 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28532 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28533 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28534 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28535 		{ "inEchos",		KSTAT_DATA_UINT32 },
28536 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28537 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28538 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28539 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28540 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28541 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28542 		{ "outErrors",		KSTAT_DATA_UINT32 },
28543 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28544 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28545 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28546 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28547 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28548 		{ "outEchos",		KSTAT_DATA_UINT32 },
28549 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28550 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28551 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28552 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28553 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28554 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28555 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28556 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28557 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28558 		{ "outDrops",		KSTAT_DATA_UINT32 },
28559 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28560 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28561 	};
28562 
28563 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28564 					NUM_OF_FIELDS(icmp_named_kstat_t),
28565 					0);
28566 	if (icmp_mibkp == NULL)
28567 		return;
28568 
28569 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28570 
28571 	icmp_mibkp->ks_update = icmp_kstat_update;
28572 
28573 	kstat_install(icmp_mibkp);
28574 }
28575 
28576 static void
28577 icmp_kstat_fini(void)
28578 {
28579 
28580 	if (icmp_mibkp != NULL) {
28581 		kstat_delete(icmp_mibkp);
28582 		icmp_mibkp = NULL;
28583 	}
28584 }
28585 
28586 static int
28587 icmp_kstat_update(kstat_t *kp, int rw)
28588 {
28589 	icmp_named_kstat_t *icmpkp;
28590 
28591 	if ((kp == NULL) || (kp->ks_data == NULL))
28592 		return (EIO);
28593 
28594 	if (rw == KSTAT_WRITE)
28595 		return (EACCES);
28596 
28597 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28598 
28599 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28600 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28601 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28602 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28603 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28604 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28605 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28606 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28607 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28608 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28609 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28610 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28611 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28612 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28613 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28614 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28615 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28616 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28617 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28618 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28619 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28620 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28621 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28622 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28623 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28624 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28625 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28626 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28627 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28628 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28629 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28630 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28631 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28632 
28633 	return (0);
28634 }
28635 
28636 /*
28637  * This is the fanout function for raw socket opened for SCTP.  Note
28638  * that it is called after SCTP checks that there is no socket which
28639  * wants a packet.  Then before SCTP handles this out of the blue packet,
28640  * this function is called to see if there is any raw socket for SCTP.
28641  * If there is and it is bound to the correct address, the packet will
28642  * be sent to that socket.  Note that only one raw socket can be bound to
28643  * a port.  This is assured in ipcl_sctp_hash_insert();
28644  */
28645 void
28646 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28647     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28648     uint_t ipif_seqid, zoneid_t zoneid)
28649 {
28650 	conn_t		*connp;
28651 	queue_t		*rq;
28652 	mblk_t		*first_mp;
28653 	boolean_t	secure;
28654 	ip6_t		*ip6h;
28655 
28656 	first_mp = mp;
28657 	if (mctl_present) {
28658 		mp = first_mp->b_cont;
28659 		secure = ipsec_in_is_secure(first_mp);
28660 		ASSERT(mp != NULL);
28661 	} else {
28662 		secure = B_FALSE;
28663 	}
28664 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28665 
28666 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28667 	if (connp == NULL) {
28668 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28669 		    mctl_present);
28670 		return;
28671 	}
28672 	rq = connp->conn_rq;
28673 	if (!canputnext(rq)) {
28674 		CONN_DEC_REF(connp);
28675 		BUMP_MIB(&ip_mib, rawipInOverflows);
28676 		freemsg(first_mp);
28677 		return;
28678 	}
28679 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28680 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28681 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28682 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28683 		if (first_mp == NULL) {
28684 			CONN_DEC_REF(connp);
28685 			return;
28686 		}
28687 	}
28688 	/*
28689 	 * We probably should not send M_CTL message up to
28690 	 * raw socket.
28691 	 */
28692 	if (mctl_present)
28693 		freeb(first_mp);
28694 
28695 	/* Initiate IPPF processing here if needed. */
28696 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28697 	    (!isv4 && IP6_IN_IPP(flags))) {
28698 		ip_process(IPP_LOCAL_IN, &mp,
28699 		    recv_ill->ill_phyint->phyint_ifindex);
28700 		if (mp == NULL) {
28701 			CONN_DEC_REF(connp);
28702 			return;
28703 		}
28704 	}
28705 
28706 	if (connp->conn_recvif || connp->conn_recvslla ||
28707 	    ((connp->conn_ipv6_recvpktinfo ||
28708 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28709 	    (flags & IP_FF_IP6INFO))) {
28710 		int in_flags = 0;
28711 
28712 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28713 			in_flags = IPF_RECVIF;
28714 		}
28715 		if (connp->conn_recvslla) {
28716 			in_flags |= IPF_RECVSLLA;
28717 		}
28718 		if (isv4) {
28719 			mp = ip_add_info(mp, recv_ill, in_flags);
28720 		} else {
28721 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28722 			if (mp == NULL) {
28723 				CONN_DEC_REF(connp);
28724 				return;
28725 			}
28726 		}
28727 	}
28728 
28729 	BUMP_MIB(&ip_mib, ipInDelivers);
28730 	/*
28731 	 * We are sending the IPSEC_IN message also up. Refer
28732 	 * to comments above this function.
28733 	 */
28734 	putnext(rq, mp);
28735 	CONN_DEC_REF(connp);
28736 }
28737 
28738 /*
28739  * This function should be called only if all packet processing
28740  * including fragmentation is complete. Callers of this function
28741  * must set mp->b_prev to one of these values:
28742  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28743  * prior to handing over the mp as first argument to this function.
28744  *
28745  * If the ire passed by caller is incomplete, this function
28746  * queues the packet and if necessary, sends ARP request and bails.
28747  * If the ire passed is fully resolved, we simply prepend
28748  * the link-layer header to the packet, do ipsec hw acceleration
28749  * work if necessary, and send the packet out on the wire.
28750  *
28751  * NOTE: IPSEC will only call this function with fully resolved
28752  * ires if hw acceleration is involved.
28753  * TODO list :
28754  * 	a Handle M_MULTIDATA so that
28755  *	  tcp_multisend->tcp_multisend_data can
28756  *	  call ip_xmit_v4 directly
28757  *	b Handle post-ARP work for fragments so that
28758  *	  ip_wput_frag can call this function.
28759  */
28760 ipxmit_state_t
28761 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28762 {
28763 	nce_t		*arpce;
28764 	queue_t		*q;
28765 	int		ill_index;
28766 	mblk_t		*nxt_mp, *first_mp;
28767 	boolean_t	xmit_drop = B_FALSE;
28768 	ip_proc_t	proc;
28769 	ill_t		*out_ill;
28770 
28771 	arpce = ire->ire_nce;
28772 	ASSERT(arpce != NULL);
28773 
28774 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28775 
28776 	mutex_enter(&arpce->nce_lock);
28777 	switch (arpce->nce_state) {
28778 	case ND_REACHABLE:
28779 		/* If there are other queued packets, queue this packet */
28780 		if (arpce->nce_qd_mp != NULL) {
28781 			if (mp != NULL)
28782 				nce_queue_mp_common(arpce, mp, B_FALSE);
28783 			mp = arpce->nce_qd_mp;
28784 		}
28785 		arpce->nce_qd_mp = NULL;
28786 		mutex_exit(&arpce->nce_lock);
28787 
28788 		/*
28789 		 * Flush the queue.  In the common case, where the
28790 		 * ARP is already resolved,  it will go through the
28791 		 * while loop only once.
28792 		 */
28793 		while (mp != NULL) {
28794 
28795 			nxt_mp = mp->b_next;
28796 			mp->b_next = NULL;
28797 			/*
28798 			 * This info is needed for IPQOS to do COS marking
28799 			 * in ip_wput_attach_llhdr->ip_process.
28800 			 */
28801 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28802 			mp->b_prev = NULL;
28803 
28804 			/* set up ill index for outbound qos processing */
28805 			out_ill = ire->ire_ipif->ipif_ill;
28806 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28807 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28808 			    ill_index);
28809 			if (first_mp == NULL) {
28810 				xmit_drop = B_TRUE;
28811 				if (proc == IPP_FWD_OUT) {
28812 					BUMP_MIB(&ip_mib, ipInDiscards);
28813 				} else {
28814 					BUMP_MIB(&ip_mib, ipOutDiscards);
28815 				}
28816 				goto next_mp;
28817 			}
28818 			/* non-ipsec hw accel case */
28819 			if (io == NULL || !io->ipsec_out_accelerated) {
28820 				/* send it */
28821 				q = ire->ire_stq;
28822 				if (proc == IPP_FWD_OUT) {
28823 					UPDATE_IB_PKT_COUNT(ire);
28824 				} else {
28825 					UPDATE_OB_PKT_COUNT(ire);
28826 				}
28827 				ire->ire_last_used_time = lbolt;
28828 
28829 				if (flow_ctl_enabled || canputnext(q))  {
28830 					if (proc == IPP_FWD_OUT) {
28831 						BUMP_MIB(&ip_mib,
28832 						    ipForwDatagrams);
28833 					}
28834 
28835 					if (mp == NULL)
28836 						goto next_mp;
28837 					putnext(q, first_mp);
28838 				} else {
28839 					BUMP_MIB(&ip_mib,
28840 					    ipOutDiscards);
28841 					xmit_drop = B_TRUE;
28842 					freemsg(first_mp);
28843 				}
28844 			} else {
28845 				/*
28846 				 * Safety Pup says: make sure this
28847 				 *  is going to the right interface!
28848 				 */
28849 				ill_t *ill1 =
28850 				    (ill_t *)ire->ire_stq->q_ptr;
28851 				int ifindex =
28852 				    ill1->ill_phyint->phyint_ifindex;
28853 				if (ifindex !=
28854 				    io->ipsec_out_capab_ill_index) {
28855 					xmit_drop = B_TRUE;
28856 					freemsg(mp);
28857 				} else {
28858 					ipsec_hw_putnext(ire->ire_stq,
28859 					    mp);
28860 				}
28861 			}
28862 next_mp:
28863 			mp = nxt_mp;
28864 		} /* while (mp != NULL) */
28865 		if (xmit_drop)
28866 			return (SEND_FAILED);
28867 		else
28868 			return (SEND_PASSED);
28869 
28870 	case ND_INITIAL:
28871 	case ND_INCOMPLETE:
28872 
28873 		/*
28874 		 * While we do send off packets to dests that
28875 		 * use fully-resolved CGTP routes, we do not
28876 		 * handle unresolved CGTP routes.
28877 		 */
28878 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28879 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28880 
28881 		if (mp != NULL) {
28882 			/* queue the packet */
28883 			nce_queue_mp_common(arpce, mp, B_FALSE);
28884 		}
28885 
28886 		if (arpce->nce_state == ND_INCOMPLETE) {
28887 			mutex_exit(&arpce->nce_lock);
28888 			DTRACE_PROBE3(ip__xmit__incomplete,
28889 			    (ire_t *), ire, (mblk_t *), mp,
28890 			    (ipsec_out_t *), io);
28891 			return (LOOKUP_IN_PROGRESS);
28892 		}
28893 
28894 		arpce->nce_state = ND_INCOMPLETE;
28895 		mutex_exit(&arpce->nce_lock);
28896 		/*
28897 		 * Note that ire_add() (called from ire_forward())
28898 		 * holds a ref on the ire until ARP is completed.
28899 		 */
28900 
28901 		ire_arpresolve(ire, ire_to_ill(ire));
28902 		return (LOOKUP_IN_PROGRESS);
28903 	default:
28904 		ASSERT(0);
28905 		mutex_exit(&arpce->nce_lock);
28906 		return (LLHDR_RESLV_FAILED);
28907 	}
28908 }
28909 
28910 /*
28911  * Return B_TRUE if the buffers differ in length or content.
28912  * This is used for comparing extension header buffers.
28913  * Note that an extension header would be declared different
28914  * even if all that changed was the next header value in that header i.e.
28915  * what really changed is the next extension header.
28916  */
28917 boolean_t
28918 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28919     uint_t blen)
28920 {
28921 	if (!b_valid)
28922 		blen = 0;
28923 
28924 	if (alen != blen)
28925 		return (B_TRUE);
28926 	if (alen == 0)
28927 		return (B_FALSE);	/* Both zero length */
28928 	return (bcmp(abuf, bbuf, alen));
28929 }
28930 
28931 /*
28932  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28933  * Return B_FALSE if memory allocation fails - don't change any state!
28934  */
28935 boolean_t
28936 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28937     const void *src, uint_t srclen)
28938 {
28939 	void *dst;
28940 
28941 	if (!src_valid)
28942 		srclen = 0;
28943 
28944 	ASSERT(*dstlenp == 0);
28945 	if (src != NULL && srclen != 0) {
28946 		dst = mi_alloc(srclen, BPRI_MED);
28947 		if (dst == NULL)
28948 			return (B_FALSE);
28949 	} else {
28950 		dst = NULL;
28951 	}
28952 	if (*dstp != NULL)
28953 		mi_free(*dstp);
28954 	*dstp = dst;
28955 	*dstlenp = dst == NULL ? 0 : srclen;
28956 	return (B_TRUE);
28957 }
28958 
28959 /*
28960  * Replace what is in *dst, *dstlen with the source.
28961  * Assumes ip_allocbuf has already been called.
28962  */
28963 void
28964 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28965     const void *src, uint_t srclen)
28966 {
28967 	if (!src_valid)
28968 		srclen = 0;
28969 
28970 	ASSERT(*dstlenp == srclen);
28971 	if (src != NULL && srclen != 0)
28972 		bcopy(src, *dstp, srclen);
28973 }
28974 
28975 /*
28976  * Free the storage pointed to by the members of an ip6_pkt_t.
28977  */
28978 void
28979 ip6_pkt_free(ip6_pkt_t *ipp)
28980 {
28981 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28982 
28983 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28984 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28985 		ipp->ipp_hopopts = NULL;
28986 		ipp->ipp_hopoptslen = 0;
28987 	}
28988 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28989 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28990 		ipp->ipp_rtdstopts = NULL;
28991 		ipp->ipp_rtdstoptslen = 0;
28992 	}
28993 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28994 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28995 		ipp->ipp_dstopts = NULL;
28996 		ipp->ipp_dstoptslen = 0;
28997 	}
28998 	if (ipp->ipp_fields & IPPF_RTHDR) {
28999 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29000 		ipp->ipp_rthdr = NULL;
29001 		ipp->ipp_rthdrlen = 0;
29002 	}
29003 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29004 	    IPPF_RTHDR);
29005 }
29006