xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision afd1ac7b1c9a8cdf273c865aa5e9a14620341443)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_rts.h>
87 #include <inet/optcom.h>
88 #include <inet/ip_ndp.h>
89 #include <inet/ip_listutils.h>
90 #include <netinet/igmp.h>
91 #include <netinet/ip_mroute.h>
92 #include <inet/ipp_common.h>
93 
94 #include <net/pfkeyv2.h>
95 #include <inet/ipsec_info.h>
96 #include <inet/sadb.h>
97 #include <inet/ipsec_impl.h>
98 #include <sys/iphada.h>
99 #include <inet/tun.h>
100 #include <inet/ipdrop.h>
101 
102 #include <sys/ethernet.h>
103 #include <net/if_types.h>
104 #include <sys/cpuvar.h>
105 
106 #include <ipp/ipp.h>
107 #include <ipp/ipp_impl.h>
108 #include <ipp/ipgpc/ipgpc.h>
109 
110 #include <sys/multidata.h>
111 #include <sys/pattr.h>
112 
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/udp_impl.h>
116 
117 /*
118  * Values for squeue switch:
119  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
120  * IP_SQUEUE_ENTER: squeue_enter
121  * IP_SQUEUE_FILL: squeue_fill
122  */
123 int ip_squeue_enter = 2;
124 squeue_func_t ip_input_proc;
125 /*
126  * IP statistics.
127  */
128 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
129 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
130 
131 typedef struct ip_stat {
132 	kstat_named_t	ipsec_fanout_proto;
133 	kstat_named_t	ip_udp_fannorm;
134 	kstat_named_t	ip_udp_fanmb;
135 	kstat_named_t	ip_udp_fanothers;
136 	kstat_named_t	ip_udp_fast_path;
137 	kstat_named_t	ip_udp_slow_path;
138 	kstat_named_t	ip_udp_input_err;
139 	kstat_named_t	ip_tcppullup;
140 	kstat_named_t	ip_tcpoptions;
141 	kstat_named_t	ip_multipkttcp;
142 	kstat_named_t	ip_tcp_fast_path;
143 	kstat_named_t	ip_tcp_slow_path;
144 	kstat_named_t	ip_tcp_input_error;
145 	kstat_named_t	ip_db_ref;
146 	kstat_named_t	ip_notaligned1;
147 	kstat_named_t	ip_notaligned2;
148 	kstat_named_t	ip_multimblk3;
149 	kstat_named_t	ip_multimblk4;
150 	kstat_named_t	ip_ipoptions;
151 	kstat_named_t	ip_classify_fail;
152 	kstat_named_t	ip_opt;
153 	kstat_named_t	ip_udp_rput_local;
154 	kstat_named_t	ipsec_proto_ahesp;
155 	kstat_named_t	ip_conn_flputbq;
156 	kstat_named_t	ip_conn_walk_drain;
157 	kstat_named_t   ip_out_sw_cksum;
158 	kstat_named_t   ip_in_sw_cksum;
159 	kstat_named_t   ip_trash_ire_reclaim_calls;
160 	kstat_named_t   ip_trash_ire_reclaim_success;
161 	kstat_named_t   ip_ire_arp_timer_expired;
162 	kstat_named_t   ip_ire_redirect_timer_expired;
163 	kstat_named_t	ip_ire_pmtu_timer_expired;
164 	kstat_named_t	ip_input_multi_squeue;
165 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
166 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
167 	kstat_named_t	ip_tcp_in_sw_cksum_err;
168 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
169 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
170 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
171 	kstat_named_t	ip_udp_in_sw_cksum_err;
172 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
173 	kstat_named_t	ip_frag_mdt_pkt_out;
174 	kstat_named_t	ip_frag_mdt_discarded;
175 	kstat_named_t	ip_frag_mdt_allocfail;
176 	kstat_named_t	ip_frag_mdt_addpdescfail;
177 	kstat_named_t	ip_frag_mdt_allocd;
178 } ip_stat_t;
179 
180 static ip_stat_t ip_statistics = {
181 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
182 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
183 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
184 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
185 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
186 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
187 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
188 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
189 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
190 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
191 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
192 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
193 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
194 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
195 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
196 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
197 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
198 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
199 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
200 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
201 	{ "ip_opt",				KSTAT_DATA_UINT64 },
202 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
203 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
204 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
205 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
206 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
207 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
208 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
209 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
210 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
211 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
212 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
213 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
214 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
215 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
216 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
217 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
218 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
219 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
220 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
221 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
222 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
223 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
224 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
225 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
226 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
227 };
228 
229 static kstat_t *ip_kstat;
230 
231 #define	TCP6 "tcp6"
232 #define	TCP "tcp"
233 #define	SCTP "sctp"
234 #define	SCTP6 "sctp6"
235 
236 major_t TCP6_MAJ;
237 major_t TCP_MAJ;
238 major_t SCTP_MAJ;
239 major_t SCTP6_MAJ;
240 
241 int ip_poll_normal_ms = 100;
242 int ip_poll_normal_ticks = 0;
243 
244 /*
245  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
246  */
247 
248 struct listptr_s {
249 	mblk_t	*lp_head;	/* pointer to the head of the list */
250 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
251 };
252 
253 typedef struct listptr_s listptr_t;
254 
255 /*
256  * Cluster specific hooks. These should be NULL when booted as a non-cluster
257  */
258 
259 /*
260  * Hook functions to enable cluster networking
261  * On non-clustered systems these vectors must always be NULL.
262  *
263  * Hook function to Check ip specified ip address is a shared ip address
264  * in the cluster
265  *
266  */
267 int (*cl_inet_isclusterwide)(uint8_t protocol,
268     sa_family_t addr_family, uint8_t *laddrp) = NULL;
269 
270 /*
271  * Hook function to generate cluster wide ip fragment identifier
272  */
273 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
274     uint8_t *laddrp, uint8_t *faddrp) = NULL;
275 
276 /*
277  * Synchronization notes:
278  *
279  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
280  * MT level protection given by STREAMS. IP uses a combination of its own
281  * internal serialization mechanism and standard Solaris locking techniques.
282  * The internal serialization is per phyint (no IPMP) or per IPMP group.
283  * This is used to serialize plumbing operations, IPMP operations, certain
284  * multicast operations, most set ioctls, igmp/mld timers etc.
285  *
286  * Plumbing is a long sequence of operations involving message
287  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
288  * involved in plumbing operations. A natural model is to serialize these
289  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
290  * parallel without any interference. But various set ioctls on hme0 are best
291  * serialized. However if the system uses IPMP, the operations are easier if
292  * they are serialized on a per IPMP group basis since IPMP operations
293  * happen across ill's of a group. Thus the lowest common denominator is to
294  * serialize most set ioctls, multicast join/leave operations, IPMP operations
295  * igmp/mld timer operations, and processing of DLPI control messages received
296  * from drivers on a per IPMP group basis. If the system does not employ
297  * IPMP the serialization is on a per phyint basis. This serialization is
298  * provided by the ipsq_t and primitives operating on this. Details can
299  * be found in ip_if.c above the core primitives operating on ipsq_t.
300  *
301  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
302  * Simiarly lookup of an ire by a thread also returns a refheld ire.
303  * In addition ipif's and ill's referenced by the ire are also indirectly
304  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
305  * the ipif's address or netmask change as long as an ipif is refheld
306  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
307  * address of an ipif has to go through the ipsq_t. This ensures that only
308  * 1 such exclusive operation proceeds at any time on the ipif. It then
309  * deletes all ires associated with this ipif, and waits for all refcnts
310  * associated with this ipif to come down to zero. The address is changed
311  * only after the ipif has been quiesced. Then the ipif is brought up again.
312  * More details are described above the comment in ip_sioctl_flags.
313  *
314  * Packet processing is based mostly on IREs and are fully multi-threaded
315  * using standard Solaris MT techniques.
316  *
317  * There are explicit locks in IP to handle:
318  * - The ip_g_head list maintained by mi_open_link() and friends.
319  *
320  * - The reassembly data structures (one lock per hash bucket)
321  *
322  * - conn_lock is meant to protect conn_t fields. The fields actually
323  *   protected by conn_lock are documented in the conn_t definition.
324  *
325  * - ire_lock to protect some of the fields of the ire, IRE tables
326  *   (one lock per hash bucket). Refer to ip_ire.c for details.
327  *
328  * - ndp_g_lock and nce_lock for protecting NCEs.
329  *
330  * - ill_lock protects fields of the ill and ipif. Details in ip.h
331  *
332  * - ill_g_lock: This is a global reader/writer lock. Protects the following
333  *	* The AVL tree based global multi list of all ills.
334  *	* The linked list of all ipifs of an ill
335  *	* The <ill-ipsq> mapping
336  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
337  *	* The illgroup list threaded by ill_group_next.
338  *	* <ill-phyint> association
339  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
340  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
341  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
342  *   will all have to hold the ill_g_lock as writer for the actual duration
343  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
344  *   may be found in the IPMP section.
345  *
346  * - ill_lock:  This is a per ill mutex.
347  *   It protects some members of the ill and is documented below.
348  *   It also protects the <ill-ipsq> mapping
349  *   It also protects the illgroup list threaded by ill_group_next.
350  *   It also protects the <ill-phyint> assoc.
351  *   It also protects the list of ipifs hanging off the ill.
352  *
353  * - ipsq_lock: This is a per ipsq_t mutex lock.
354  *   This protects all the other members of the ipsq struct except
355  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
356  *
357  * - illgrp_lock: This is a per ill_group mutex lock.
358  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
359  *   which dictates which is the next ill in an ill_group that is to be chosen
360  *   for sending outgoing packets, through creation of an IRE_CACHE that
361  *   references this ill.
362  *
363  * - phyint_lock: This is a per phyint mutex lock. Protects just the
364  *   phyint_flags
365  *
366  * - ip_g_nd_lock: This is a global reader/writer lock.
367  *   Any call to nd_load to load a new parameter to the ND table must hold the
368  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
369  *   as reader.
370  *
371  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
372  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
373  *   uniqueness check also done atomically.
374  *
375  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
376  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
377  *   as a writer when adding or deleting elements from these lists, and
378  *   as a reader when walking these lists to send a SADB update to the
379  *   IPsec capable ills.
380  *
381  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
382  *   group list linked by ill_usesrc_grp_next. It also protects the
383  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
384  *   group is being added or deleted.  This lock is taken as a reader when
385  *   walking the list/group(eg: to get the number of members in a usesrc group).
386  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
387  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
388  *   example, it is not necessary to take this lock in the initial portion
389  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
390  *   ip_sioctl_flags since the these operations are executed exclusively and
391  *   that ensures that the "usesrc group state" cannot change. The "usesrc
392  *   group state" change can happen only in the latter part of
393  *   ip_sioctl_slifusesrc and in ill_delete.
394  *
395  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
396  *
397  * To change the <ill-phyint> association, the ill_g_lock must be held
398  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
399  * must be held.
400  *
401  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
402  * and the ill_lock of the ill in question must be held.
403  *
404  * To change the <ill-illgroup> association the ill_g_lock must be held as
405  * writer and the ill_lock of the ill in question must be held.
406  *
407  * To add or delete an ipif from the list of ipifs hanging off the ill,
408  * ill_g_lock (writer) and ill_lock must be held and the thread must be
409  * a writer on the associated ipsq,.
410  *
411  * To add or delete an ill to the system, the ill_g_lock must be held as
412  * writer and the thread must be a writer on the associated ipsq.
413  *
414  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
415  * must be a writer on the associated ipsq.
416  *
417  * Lock hierarchy
418  *
419  * Some lock hierarchy scenarios are listed below.
420  *
421  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
422  * ill_g_lock -> illgrp_lock -> ill_lock
423  * ill_g_lock -> ill_lock(s) -> phyint_lock
424  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
425  * ill_g_lock -> ip_addr_avail_lock
426  * conn_lock -> irb_lock -> ill_lock -> ire_lock
427  * ipsa_lock -> ill_g_lock -> ill_lock
428  * ill_g_lock -> ip_g_nd_lock
429  * irb_lock -> ill_lock -> ire_mrtun_lock
430  * irb_lock -> ill_lock -> ire_srcif_table_lock
431  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
432  * ipsec_capab_ills_lock -> ipsa_lock
433  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
434  *
435  * When more than 1 ill lock is needed to be held, all ill lock addresses
436  * are sorted on address and locked starting from highest addressed lock
437  * downward.
438  *
439  * IPSEC notes :
440  *
441  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
442  * in front of the actual packet. For outbound datagrams, the M_CTL
443  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
444  * information used by the IPSEC code for applying the right level of
445  * protection. The information initialized by IP in the ipsec_out_t
446  * is determined by the per-socket policy or global policy in the system.
447  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
448  * ipsec_info.h) which starts out with nothing in it. It gets filled
449  * with the right information if it goes through the AH/ESP code, which
450  * happens if the incoming packet is secure. The information initialized
451  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
452  * the policy requirements needed by per-socket policy or global policy
453  * is met or not.
454  *
455  * If there is both per-socket policy (set using setsockopt) and there
456  * is also global policy match for the 5 tuples of the socket,
457  * ipsec_override_policy() makes the decision of which one to use.
458  *
459  * For fully connected sockets i.e dst, src [addr, port] is known,
460  * conn_policy_cached is set indicating that policy has been cached.
461  * conn_in_enforce_policy may or may not be set depending on whether
462  * there is a global policy match or per-socket policy match.
463  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
464  * Once the right policy is set on the conn_t, policy cannot change for
465  * this socket. This makes life simpler for TCP (UDP ?) where
466  * re-transmissions go out with the same policy. For symmetry, policy
467  * is cached for fully connected UDP sockets also. Thus if policy is cached,
468  * it also implies that policy is latched i.e policy cannot change
469  * on these sockets. As we have the right policy on the conn, we don't
470  * have to lookup global policy for every outbound and inbound datagram
471  * and thus serving as an optimization. Note that a global policy change
472  * does not affect fully connected sockets if they have policy. If fully
473  * connected sockets did not have any policy associated with it, global
474  * policy change may affect them.
475  *
476  * IP Flow control notes:
477  *
478  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
479  * cannot be sent down to the driver by IP, because of a canput failure, IP
480  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
481  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
482  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
483  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
484  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
485  * the queued messages, and removes the conn from the drain list, if all
486  * messages were drained. It also qenables the next conn in the drain list to
487  * continue the drain process.
488  *
489  * In reality the drain list is not a single list, but a configurable number
490  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
491  * list. If the ip_wsrv of the next qenabled conn does not run, because the
492  * stream closes, ip_close takes responsibility to qenable the next conn in
493  * the drain list. The directly called ip_wput path always does a putq, if
494  * it cannot putnext. Thus synchronization problems are handled between
495  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
496  * functions that manipulate this drain list. Furthermore conn_drain_insert
497  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
498  * running on a queue at any time. conn_drain_tail can be simultaneously called
499  * from both ip_wsrv and ip_close.
500  *
501  * IPQOS notes:
502  *
503  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
504  * and IPQoS modules. IPPF includes hooks in IP at different control points
505  * (callout positions) which direct packets to IPQoS modules for policy
506  * processing. Policies, if present, are global.
507  *
508  * The callout positions are located in the following paths:
509  *		o local_in (packets destined for this host)
510  *		o local_out (packets orginating from this host )
511  *		o fwd_in  (packets forwarded by this m/c - inbound)
512  *		o fwd_out (packets forwarded by this m/c - outbound)
513  * Hooks at these callout points can be enabled/disabled using the ndd variable
514  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
515  * By default all the callout positions are enabled.
516  *
517  * Outbound (local_out)
518  * Hooks are placed in ip_wput_ire and ipsec_out_process.
519  *
520  * Inbound (local_in)
521  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
522  * TCP and UDP fanout routines.
523  *
524  * Forwarding (in and out)
525  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
526  *
527  * IP Policy Framework processing (IPPF processing)
528  * Policy processing for a packet is initiated by ip_process, which ascertains
529  * that the classifier (ipgpc) is loaded and configured, failing which the
530  * packet resumes normal processing in IP. If the clasifier is present, the
531  * packet is acted upon by one or more IPQoS modules (action instances), per
532  * filters configured in ipgpc and resumes normal IP processing thereafter.
533  * An action instance can drop a packet in course of its processing.
534  *
535  * A boolean variable, ip_policy, is used in all the fanout routines that can
536  * invoke ip_process for a packet. This variable indicates if the packet should
537  * to be sent for policy processing. The variable is set to B_TRUE by default,
538  * i.e. when the routines are invoked in the normal ip procesing path for a
539  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
540  * ip_policy is set to B_FALSE for all the routines called in these two
541  * functions because, in the former case,  we don't process loopback traffic
542  * currently while in the latter, the packets have already been processed in
543  * icmp_inbound.
544  *
545  * Zones notes:
546  *
547  * The partitioning rules for networking are as follows:
548  * 1) Packets coming from a zone must have a source address belonging to that
549  * zone.
550  * 2) Packets coming from a zone can only be sent on a physical interface on
551  * which the zone has an IP address.
552  * 3) Between two zones on the same machine, packet delivery is only allowed if
553  * there's a matching route for the destination and zone in the forwarding
554  * table.
555  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
556  * different zones can bind to the same port with the wildcard address
557  * (INADDR_ANY).
558  *
559  * The granularity of interface partitioning is at the logical interface level.
560  * Therefore, every zone has its own IP addresses, and incoming packets can be
561  * attributed to a zone unambiguously. A logical interface is placed into a zone
562  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
563  * structure. Rule (1) is implemented by modifying the source address selection
564  * algorithm so that the list of eligible addresses is filtered based on the
565  * sending process zone.
566  *
567  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
568  * across all zones, depending on their type. Here is the break-up:
569  *
570  * IRE type				Shared/exclusive
571  * --------				----------------
572  * IRE_BROADCAST			Exclusive
573  * IRE_DEFAULT (default routes)		Shared (*)
574  * IRE_LOCAL				Exclusive
575  * IRE_LOOPBACK				Exclusive
576  * IRE_PREFIX (net routes)		Shared (*)
577  * IRE_CACHE				Exclusive
578  * IRE_IF_NORESOLVER (interface routes)	Exclusive
579  * IRE_IF_RESOLVER (interface routes)	Exclusive
580  * IRE_HOST (host routes)		Shared (*)
581  *
582  * (*) A zone can only use a default or off-subnet route if the gateway is
583  * directly reachable from the zone, that is, if the gateway's address matches
584  * one of the zone's logical interfaces.
585  *
586  * Multiple zones can share a common broadcast address; typically all zones
587  * share the 255.255.255.255 address. Incoming as well as locally originated
588  * broadcast packets must be dispatched to all the zones on the broadcast
589  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
590  * since some zones may not be on the 10.16.72/24 network. To handle this, each
591  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
592  * sent to every zone that has an IRE_BROADCAST entry for the destination
593  * address on the input ill, see conn_wantpacket().
594  *
595  * Applications in different zones can join the same multicast group address.
596  * For IPv4, group memberships are per-logical interface, so they're already
597  * inherently part of a zone. For IPv6, group memberships are per-physical
598  * interface, so we distinguish IPv6 group memberships based on group address,
599  * interface and zoneid. In both cases, received multicast packets are sent to
600  * every zone for which a group membership entry exists. On IPv6 we need to
601  * check that the target zone still has an address on the receiving physical
602  * interface; it could have been removed since the application issued the
603  * IPV6_JOIN_GROUP.
604  */
605 
606 /*
607  * Squeue Fanout flags:
608  *	0: No fanout.
609  *	1: Fanout across all squeues
610  */
611 boolean_t	ip_squeue_fanout = 0;
612 
613 /*
614  * Maximum dups allowed per packet.
615  */
616 uint_t ip_max_frag_dups = 10;
617 
618 #define	IS_SIMPLE_IPH(ipha)						\
619 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
620 
621 /* RFC1122 Conformance */
622 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
623 
624 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
625 
626 /* Leave room for ip_newroute to tack on the src and target addresses */
627 #define	OK_RESOLVER_MP(mp)						\
628 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
629 
630 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
631 
632 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
633 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
634 
635 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
636 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
637     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
638 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
639 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
640 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
641 		    ill_t *, zoneid_t);
642 static void	icmp_options_update(ipha_t *);
643 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
644 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
645 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
646 static void	icmp_redirect(mblk_t *);
647 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
648 
649 static void	ip_arp_news(queue_t *, mblk_t *);
650 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
651 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
652 char		*ip_dot_addr(ipaddr_t, char *);
653 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
654 int		ip_close(queue_t *, int);
655 static char	*ip_dot_saddr(uchar_t *, char *);
656 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
657 		    boolean_t, boolean_t, ill_t *, zoneid_t);
658 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
659 		    boolean_t, boolean_t, zoneid_t);
660 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
661 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
662 static void	ip_lrput(queue_t *, mblk_t *);
663 ipaddr_t	ip_massage_options(ipha_t *);
664 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
665 ipaddr_t	ip_net_mask(ipaddr_t);
666 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
667 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
668 		    conn_t *, uint32_t);
669 static int	ip_hdr_complete(ipha_t *, zoneid_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
672 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
673 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
674 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
675 			    size_t);
676 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
677 void	ip_rput(queue_t *, mblk_t *);
678 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
679 		    void *dummy_arg);
680 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
681 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
682 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
683 			    ire_t *);
684 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
685 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
686 		    uint16_t *);
687 int		ip_snmp_get(queue_t *, mblk_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
689 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
690 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
691 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
692 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
693 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
694 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
695 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
696 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
698 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
699 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
700 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
701 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
704 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
705 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 
711 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
712 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
713 static void	ip_wput_local_options(ipha_t *);
714 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
715     zoneid_t);
716 
717 static void	conn_drain_init(void);
718 static void	conn_drain_fini(void);
719 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
720 
721 static void	conn_walk_drain(void);
722 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
723     zoneid_t);
724 
725 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
726     zoneid_t);
727 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
728     void *dummy_arg);
729 
730 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
731 
732 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
733     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
734     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
735 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
736 
737 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
738 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
739     caddr_t, cred_t *);
740 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
741     caddr_t cp, cred_t *cr);
742 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
743     cred_t *);
744 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
745     caddr_t cp, cred_t *cr);
746 static int	ip_fanout_set(queue_t *, mblk_t *, char *, caddr_t,
747     cred_t *);
748 static squeue_func_t ip_squeue_switch(int);
749 
750 static void	ip_kstat_init(void);
751 static void	ip_kstat_fini(void);
752 static int	ip_kstat_update(kstat_t *kp, int rw);
753 static void	icmp_kstat_init(void);
754 static void	icmp_kstat_fini(void);
755 static int	icmp_kstat_update(kstat_t *kp, int rw);
756 
757 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
758 
759 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
760 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
761 
762 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
763     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
764 
765 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
766 
767 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
768 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
769 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
770 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
771 
772 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
773 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
774 
775 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
776 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
777 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
778 
779 /* How long, in seconds, we allow frags to hang around. */
780 #define	IP_FRAG_TIMEOUT	60
781 
782 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
783 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
784 
785 /*
786  * Threshold which determines whether MDT should be used when
787  * generating IP fragments; payload size must be greater than
788  * this threshold for MDT to take place.
789  */
790 #define	IP_WPUT_FRAG_MDT_MIN	32768
791 
792 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
793 
794 /* Protected by ip_mi_lock */
795 static void	*ip_g_head;		/* Instance Data List Head */
796 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
797 
798 /* Only modified during _init and _fini thus no locking is needed. */
799 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
800 
801 
802 static long ip_rput_pullups;
803 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
804 
805 vmem_t *ip_minor_arena;
806 
807 /*
808  * MIB-2 stuff for SNMP (both IP and ICMP)
809  */
810 mib2_ip_t	ip_mib;
811 mib2_icmp_t	icmp_mib;
812 
813 #ifdef DEBUG
814 uint32_t ipsechw_debug = 0;
815 #endif
816 
817 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
818 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
819 
820 uint_t	loopback_packets = 0;
821 
822 /*
823  * Multirouting/CGTP stuff
824  */
825 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
826 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
827 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
828 /* Interval (in ms) between consecutive 'bad MTU' warnings */
829 hrtime_t ip_multirt_log_interval = 1000;
830 /* Time since last warning issued. */
831 static hrtime_t	multirt_bad_mtu_last_time = 0;
832 
833 kmutex_t ip_trash_timer_lock;
834 krwlock_t ip_g_nd_lock;
835 
836 /*
837  * XXX following really should only be in a header. Would need more
838  * header and .c clean up first.
839  */
840 extern optdb_obj_t	ip_opt_obj;
841 
842 ulong_t ip_squeue_enter_unbound = 0;
843 
844 /*
845  * Named Dispatch Parameter Table.
846  * All of these are alterable, within the min/max values given, at run time.
847  */
848 static ipparam_t	lcl_param_arr[] = {
849 	/* min	max	value	name */
850 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
851 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
852 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
853 	{  0,	1,	0,	"ip_respond_to_timestamp"},
854 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
855 	{  0,	1,	1,	"ip_send_redirects"},
856 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
857 	{  0,	10,	0,	"ip_debug"},
858 	{  0,	10,	0,	"ip_mrtdebug"},
859 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
860 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
861 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
862 	{  1,	255,	255,	"ip_def_ttl" },
863 	{  0,	1,	0,	"ip_forward_src_routed"},
864 	{  0,	256,	32,	"ip_wroff_extra" },
865 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
866 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
867 	{  0,	1,	1,	"ip_path_mtu_discovery" },
868 	{  0,	240,	30,	"ip_ignore_delete_time" },
869 	{  0,	1,	0,	"ip_ignore_redirect" },
870 	{  0,	1,	1,	"ip_output_queue" },
871 	{  1,	254,	1,	"ip_broadcast_ttl" },
872 	{  0,	99999,	100,	"ip_icmp_err_interval" },
873 	{  1,	99999,	10,	"ip_icmp_err_burst" },
874 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
875 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
876 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
877 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
878 	{  0,	1,	1,	"icmp_accept_clear_messages" },
879 	{  0,	1,	1,	"igmp_accept_clear_messages" },
880 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
881 				"ip_ndp_delay_first_probe_time"},
882 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
883 				"ip_ndp_max_unicast_solicit"},
884 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
885 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
886 	{  0,	1,	0,	"ip6_forward_src_routed"},
887 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
888 	{  0,	1,	1,	"ip6_send_redirects"},
889 	{  0,	1,	0,	"ip6_ignore_redirect" },
890 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
891 
892 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
893 
894 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
895 
896 	{  0,	1,	1,	"pim_accept_clear_messages" },
897 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
898 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
899 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
900 	{  0,	15,	0,	"ip_policy_mask" },
901 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
902 	{  0,	255,	1,	"ip_multirt_ttl" },
903 	{  0,	1,	1,	"ip_multidata_outbound" },
904 #ifdef DEBUG
905 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
906 #endif
907 };
908 
909 ipparam_t	*ip_param_arr = lcl_param_arr;
910 
911 /* Extended NDP table */
912 static ipndp_t	lcl_ndp_arr[] = {
913 	/* getf			setf		data			name */
914 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
915 	    "ip_forwarding" },
916 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
917 	    "ip6_forwarding" },
918 	{  ip_ill_report,	NULL,		NULL,
919 	    "ip_ill_status" },
920 	{  ip_ipif_report,	NULL,		NULL,
921 	    "ip_ipif_status" },
922 	{  ip_ire_report,	NULL,		NULL,
923 	    "ipv4_ire_status" },
924 	{  ip_ire_report_mrtun,	NULL,		NULL,
925 	    "ipv4_mrtun_ire_status" },
926 	{  ip_ire_report_srcif,	NULL,		NULL,
927 	    "ipv4_srcif_ire_status" },
928 	{  ip_ire_report_v6,	NULL,		NULL,
929 	    "ipv6_ire_status" },
930 	{  ip_conn_report,	NULL,		NULL,
931 	    "ip_conn_status" },
932 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
933 	    "ip_rput_pullups" },
934 	{  ndp_report,		NULL,		NULL,
935 	    "ip_ndp_cache_report" },
936 	{  ip_srcid_report,	NULL,		NULL,
937 	    "ip_srcid_status" },
938 	{ ip_param_generic_get, ip_squeue_profile_set,
939 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
940 	{ ip_param_generic_get, ip_squeue_bind_set,
941 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
942 	{ ip_param_generic_get, ip_input_proc_set,
943 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
944 	{ ip_param_generic_get, ip_fanout_set,
945 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
946 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
947 	    "ip_cgtp_filter" }
948 };
949 
950 /*
951  * ip_g_forward controls IP forwarding.  It takes two values:
952  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
953  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
954  *
955  * RFC1122 says there must be a configuration switch to control forwarding,
956  * but that the default MUST be to not forward packets ever.  Implicit
957  * control based on configuration of multiple interfaces MUST NOT be
958  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
959  * and, in fact, it was the default.  That capability is now provided in the
960  * /etc/rc2.d/S69inet script.
961  */
962 int ip_g_forward = IP_FORWARD_DEFAULT;
963 
964 /* It also has an IPv6 counterpart. */
965 
966 int ipv6_forward = IP_FORWARD_DEFAULT;
967 
968 /* Following line is external, and in ip.h.  Normally marked with * *. */
969 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
970 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
971 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
972 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
973 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
974 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
975 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
976 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
977 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
978 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
979 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
980 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
981 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
982 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
983 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
984 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
985 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
986 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
987 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
988 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
989 #define	ip_output_queue			ip_param_arr[20].ip_param_value
990 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
991 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
992 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
993 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
994 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
995 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
996 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
997 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
998 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
999 
1000 /* IPv6 configuration knobs */
1001 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1002 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1003 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1004 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1005 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1006 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1007 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1008 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1009 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1010 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1011 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1012 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1013 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1014 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1015 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1016 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1017 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1018 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1019 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1020 #ifdef DEBUG
1021 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1022 #else
1023 #define	ipv6_drop_inbound_icmpv6	0
1024 #endif
1025 
1026 
1027 /*
1028  * Table of IP ioctls encoding the various properties of the ioctl and
1029  * indexed based on the last byte of the ioctl command. Occasionally there
1030  * is a clash, and there is more than 1 ioctl with the same last byte.
1031  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1032  * ioctls are encoded in the misc table. An entry in the ndx table is
1033  * retrieved by indexing on the last byte of the ioctl command and comparing
1034  * the ioctl command with the value in the ndx table. In the event of a
1035  * mismatch the misc table is then searched sequentially for the desired
1036  * ioctl command.
1037  *
1038  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1039  */
1040 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1041 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 
1052 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1053 			MISC_CMD, ip_siocaddrt, NULL },
1054 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1055 			MISC_CMD, ip_siocdelrt, NULL },
1056 
1057 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1058 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1059 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1060 			IF_CMD, ip_sioctl_get_addr, NULL },
1061 
1062 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1063 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1064 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1065 			IPI_GET_CMD | IPI_REPL,
1066 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1067 
1068 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1069 			IPI_PRIV | IPI_WR | IPI_REPL,
1070 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1071 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1072 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1073 			IF_CMD, ip_sioctl_get_flags, NULL },
1074 
1075 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* copyin size cannot be coded for SIOCGIFCONF */
1079 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1080 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1081 
1082 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_mtu, NULL },
1084 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_mtu, NULL },
1086 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1087 			IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1089 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1090 			IF_CMD, ip_sioctl_brdaddr, NULL },
1091 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1092 			IPI_GET_CMD | IPI_REPL,
1093 			IF_CMD, ip_sioctl_get_netmask, NULL },
1094 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1095 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1096 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1097 			IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_metric, NULL },
1099 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1100 			IF_CMD, ip_sioctl_metric, NULL },
1101 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* See 166-168 below for extended SIOC*XARP ioctls */
1104 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1105 			MISC_CMD, ip_sioctl_arp, NULL },
1106 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1107 			MISC_CMD, ip_sioctl_arp, NULL },
1108 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1109 			MISC_CMD, ip_sioctl_arp, NULL },
1110 
1111 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 
1133 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1134 			MISC_CMD, if_unitsel, if_unitsel_restart },
1135 
1136 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 
1155 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1156 			IPI_PRIV | IPI_WR | IPI_MODOK,
1157 			IF_CMD, ip_sioctl_sifname, NULL },
1158 
1159 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 
1173 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1174 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1175 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1176 			IF_CMD, ip_sioctl_get_muxid, NULL },
1177 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR | IPI_REPL,
1179 			IF_CMD, ip_sioctl_muxid, NULL },
1180 
1181 	/* Both if and lif variants share same func */
1182 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1183 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1184 	/* Both if and lif variants share same func */
1185 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1186 			IPI_PRIV | IPI_WR | IPI_REPL,
1187 			IF_CMD, ip_sioctl_slifindex, NULL },
1188 
1189 	/* copyin size cannot be coded for SIOCGIFCONF */
1190 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1191 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1192 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 
1210 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			LIF_CMD, ip_sioctl_removeif,
1213 			ip_sioctl_removeif_restart },
1214 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1215 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1216 			LIF_CMD, ip_sioctl_addif, NULL },
1217 #define	SIOCLIFADDR_NDX 112
1218 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1219 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1220 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1221 			IPI_GET_CMD | IPI_REPL,
1222 			LIF_CMD, ip_sioctl_get_addr, NULL },
1223 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1224 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1225 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1226 			IPI_GET_CMD | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1228 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR | IPI_REPL,
1230 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1231 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1232 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1233 			LIF_CMD, ip_sioctl_get_flags, NULL },
1234 
1235 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 
1238 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1239 			ip_sioctl_get_lifconf, NULL },
1240 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1241 			LIF_CMD, ip_sioctl_mtu, NULL },
1242 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1244 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1247 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1248 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1249 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1250 			IPI_GET_CMD | IPI_REPL,
1251 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1252 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1253 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1254 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1255 			IPI_GET_CMD | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_get_metric, NULL },
1257 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1258 			LIF_CMD, ip_sioctl_metric, NULL },
1259 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1260 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1261 			LIF_CMD, ip_sioctl_slifname,
1262 			ip_sioctl_slifname_restart },
1263 
1264 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1265 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1266 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1269 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1270 			IPI_PRIV | IPI_WR | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_muxid, NULL },
1272 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1273 			IPI_GET_CMD | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1275 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1276 			IPI_PRIV | IPI_WR | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_slifindex, 0 },
1278 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_token, NULL },
1280 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_token, NULL },
1283 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1285 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1286 			IPI_GET_CMD | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1288 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1290 
1291 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1294 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1295 			LIF_CMD, ip_siocdelndp_v6, NULL },
1296 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1297 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1298 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1299 			LIF_CMD, ip_siocsetndp_v6, NULL },
1300 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1302 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1303 			MISC_CMD, ip_sioctl_tonlink, NULL },
1304 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1305 			MISC_CMD, ip_sioctl_tmysite, NULL },
1306 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1307 			TUN_CMD, ip_sioctl_tunparam, NULL },
1308 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1309 			IPI_PRIV | IPI_WR,
1310 			TUN_CMD, ip_sioctl_tunparam, NULL },
1311 
1312 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1313 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1314 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1315 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1316 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1317 
1318 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1319 			IPI_PRIV | IPI_WR | IPI_REPL,
1320 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1321 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1322 			IPI_PRIV | IPI_WR | IPI_REPL,
1323 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1324 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR,
1326 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1327 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1328 			IPI_GET_CMD | IPI_REPL,
1329 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1330 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1331 			IPI_GET_CMD | IPI_REPL,
1332 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1333 
1334 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1335 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1336 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1337 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1338 
1339 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1340 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1341 
1342 	/* These are handled in ip_sioctl_copyin_setup itself */
1343 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1344 			MISC_CMD, NULL, NULL },
1345 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1346 			MISC_CMD, NULL, NULL },
1347 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1348 
1349 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1350 			ip_sioctl_get_lifconf, NULL },
1351 
1352 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1353 			MISC_CMD, ip_sioctl_xarp, NULL },
1354 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1355 			MISC_CMD, ip_sioctl_xarp, NULL },
1356 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1357 			MISC_CMD, ip_sioctl_xarp, NULL },
1358 
1359 	/* SIOCPOPSOCKFS is not handled by IP */
1360 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1361 
1362 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1363 			IPI_GET_CMD | IPI_REPL,
1364 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1365 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1366 			IPI_PRIV | IPI_WR | IPI_REPL,
1367 			LIF_CMD, ip_sioctl_slifzone,
1368 			ip_sioctl_slifzone_restart },
1369 	/* 172-174 are SCTP ioctls and not handled by IP */
1370 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1371 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1372 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1373 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1374 			IPI_GET_CMD, LIF_CMD,
1375 			ip_sioctl_get_lifusesrc, 0 },
1376 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1377 			IPI_PRIV | IPI_WR,
1378 			LIF_CMD, ip_sioctl_slifusesrc,
1379 			NULL },
1380 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1381 			ip_sioctl_get_lifsrcof, NULL },
1382 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1383 			MISC_CMD, ip_sioctl_msfilter, NULL },
1384 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1385 			MISC_CMD, ip_sioctl_msfilter, NULL },
1386 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1387 			MISC_CMD, ip_sioctl_msfilter, NULL },
1388 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1389 			MISC_CMD, ip_sioctl_msfilter, NULL },
1390 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1391 			ip_sioctl_set_ipmpfailback, NULL }
1392 };
1393 
1394 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1395 
1396 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1397 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1398 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1399 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1400 		TUN_CMD, ip_sioctl_tunparam, NULL },
1401 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1402 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1403 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1404 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1405 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1406 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1407 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1408 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1409 		MISC_CMD, mrt_ioctl},
1410 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1411 		MISC_CMD, mrt_ioctl},
1412 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1413 		MISC_CMD, mrt_ioctl}
1414 };
1415 
1416 int ip_misc_ioctl_count =
1417     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1418 
1419 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1420 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1421 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1422 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1423 					/* Settable in /etc/system */
1424 
1425 /* Defined in ip_ire.c */
1426 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1427 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1428 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1429 
1430 static nv_t	ire_nv_arr[] = {
1431 	{ IRE_BROADCAST, "BROADCAST" },
1432 	{ IRE_LOCAL, "LOCAL" },
1433 	{ IRE_LOOPBACK, "LOOPBACK" },
1434 	{ IRE_CACHE, "CACHE" },
1435 	{ IRE_DEFAULT, "DEFAULT" },
1436 	{ IRE_PREFIX, "PREFIX" },
1437 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1438 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1439 	{ IRE_HOST, "HOST" },
1440 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1441 	{ 0 }
1442 };
1443 
1444 nv_t	*ire_nv_tbl = ire_nv_arr;
1445 
1446 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1447 extern krwlock_t ipsec_capab_ills_lock;
1448 
1449 /* Packet dropper for IP IPsec processing failures */
1450 ipdropper_t ip_dropper;
1451 
1452 /* Simple ICMP IP Header Template */
1453 static ipha_t icmp_ipha = {
1454 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1455 };
1456 
1457 struct module_info ip_mod_info = {
1458 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1459 };
1460 
1461 static struct qinit rinit = {
1462 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1463 	&ip_mod_info
1464 };
1465 
1466 static struct qinit winit = {
1467 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1468 	&ip_mod_info
1469 };
1470 
1471 static struct qinit lrinit = {
1472 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1473 	&ip_mod_info
1474 };
1475 
1476 static struct qinit lwinit = {
1477 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1478 	&ip_mod_info
1479 };
1480 
1481 struct streamtab ipinfo = {
1482 	&rinit, &winit, &lrinit, &lwinit
1483 };
1484 
1485 #ifdef	DEBUG
1486 static boolean_t skip_sctp_cksum = B_FALSE;
1487 #endif
1488 /*
1489  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1490  */
1491 mblk_t *
1492 ip_copymsg(mblk_t *mp)
1493 {
1494 	mblk_t *nmp;
1495 	ipsec_info_t *in;
1496 
1497 	if (mp->b_datap->db_type != M_CTL)
1498 		return (copymsg(mp));
1499 
1500 	in = (ipsec_info_t *)mp->b_rptr;
1501 
1502 	/*
1503 	 * Note that M_CTL is also used for delivering ICMP error messages
1504 	 * upstream to transport layers.
1505 	 */
1506 	if (in->ipsec_info_type != IPSEC_OUT &&
1507 	    in->ipsec_info_type != IPSEC_IN)
1508 		return (copymsg(mp));
1509 
1510 	nmp = copymsg(mp->b_cont);
1511 
1512 	if (in->ipsec_info_type == IPSEC_OUT)
1513 		return (ipsec_out_tag(mp, nmp));
1514 	else
1515 		return (ipsec_in_tag(mp, nmp));
1516 }
1517 
1518 /* Generate an ICMP fragmentation needed message. */
1519 static void
1520 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1521 {
1522 	icmph_t	icmph;
1523 	mblk_t *first_mp;
1524 	boolean_t mctl_present;
1525 
1526 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1527 
1528 	if (!(mp = icmp_pkt_err_ok(mp))) {
1529 		if (mctl_present)
1530 			freeb(first_mp);
1531 		return;
1532 	}
1533 
1534 	bzero(&icmph, sizeof (icmph_t));
1535 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1536 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1537 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1538 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1539 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1540 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1541 }
1542 
1543 /*
1544  * icmp_inbound deals with ICMP messages in the following ways.
1545  *
1546  * 1) It needs to send a reply back and possibly delivering it
1547  *    to the "interested" upper clients.
1548  * 2) It needs to send it to the upper clients only.
1549  * 3) It needs to change some values in IP only.
1550  * 4) It needs to change some values in IP and upper layers e.g TCP.
1551  *
1552  * We need to accomodate icmp messages coming in clear until we get
1553  * everything secure from the wire. If icmp_accept_clear_messages
1554  * is zero we check with the global policy and act accordingly. If
1555  * it is non-zero, we accept the message without any checks. But
1556  * *this does not mean* that this will be delivered to the upper
1557  * clients. By accepting we might send replies back, change our MTU
1558  * value etc. but delivery to the ULP/clients depends on their policy
1559  * dispositions.
1560  *
1561  * We handle the above 4 cases in the context of IPSEC in the
1562  * following way :
1563  *
1564  * 1) Send the reply back in the same way as the request came in.
1565  *    If it came in encrypted, it goes out encrypted. If it came in
1566  *    clear, it goes out in clear. Thus, this will prevent chosen
1567  *    plain text attack.
1568  * 2) The client may or may not expect things to come in secure.
1569  *    If it comes in secure, the policy constraints are checked
1570  *    before delivering it to the upper layers. If it comes in
1571  *    clear, ipsec_inbound_accept_clear will decide whether to
1572  *    accept this in clear or not. In both the cases, if the returned
1573  *    message (IP header + 8 bytes) that caused the icmp message has
1574  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1575  *    sending up. If there are only 8 bytes of returned message, then
1576  *    upper client will not be notified.
1577  * 3) Check with global policy to see whether it matches the constaints.
1578  *    But this will be done only if icmp_accept_messages_in_clear is
1579  *    zero.
1580  * 4) If we need to change both in IP and ULP, then the decision taken
1581  *    while affecting the values in IP and while delivering up to TCP
1582  *    should be the same.
1583  *
1584  * 	There are two cases.
1585  *
1586  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1587  *	   failed), we will not deliver it to the ULP, even though they
1588  *	   are *willing* to accept in *clear*. This is fine as our global
1589  *	   disposition to icmp messages asks us reject the datagram.
1590  *
1591  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1592  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1593  *	   to deliver it to ULP (policy failed), it can lead to
1594  *	   consistency problems. The cases known at this time are
1595  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1596  *	   values :
1597  *
1598  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1599  *	     and Upper layer rejects. Then the communication will
1600  *	     come to a stop. This is solved by making similar decisions
1601  *	     at both levels. Currently, when we are unable to deliver
1602  *	     to the Upper Layer (due to policy failures) while IP has
1603  *	     adjusted ire_max_frag, the next outbound datagram would
1604  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1605  *	     will be with the right level of protection. Thus the right
1606  *	     value will be communicated even if we are not able to
1607  *	     communicate when we get from the wire initially. But this
1608  *	     assumes there would be at least one outbound datagram after
1609  *	     IP has adjusted its ire_max_frag value. To make things
1610  *	     simpler, we accept in clear after the validation of
1611  *	     AH/ESP headers.
1612  *
1613  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1614  *	     upper layer depending on the level of protection the upper
1615  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1616  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1617  *	     should be accepted in clear when the Upper layer expects secure.
1618  *	     Thus the communication may get aborted by some bad ICMP
1619  *	     packets.
1620  *
1621  * IPQoS Notes:
1622  * The only instance when a packet is sent for processing is when there
1623  * isn't an ICMP client and if we are interested in it.
1624  * If there is a client, IPPF processing will take place in the
1625  * ip_fanout_proto routine.
1626  *
1627  * Zones notes:
1628  * The packet is only processed in the context of the specified zone: typically
1629  * only this zone will reply to an echo request, and only interested clients in
1630  * this zone will receive a copy of the packet. This means that the caller must
1631  * call icmp_inbound() for each relevant zone.
1632  */
1633 static void
1634 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1635     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1636     ill_t *recv_ill, zoneid_t zoneid)
1637 {
1638 	icmph_t	*icmph;
1639 	ipha_t	*ipha;
1640 	int	iph_hdr_length;
1641 	int	hdr_length;
1642 	boolean_t	interested;
1643 	uint32_t	ts;
1644 	uchar_t	*wptr;
1645 	ipif_t	*ipif;
1646 	mblk_t *first_mp;
1647 	ipsec_in_t *ii;
1648 	ire_t *src_ire;
1649 	boolean_t onlink;
1650 	timestruc_t now;
1651 	uint32_t ill_index;
1652 
1653 	ASSERT(ill != NULL);
1654 
1655 	first_mp = mp;
1656 	if (mctl_present) {
1657 		mp = first_mp->b_cont;
1658 		ASSERT(mp != NULL);
1659 	}
1660 
1661 	ipha = (ipha_t *)mp->b_rptr;
1662 	if (icmp_accept_clear_messages == 0) {
1663 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1664 		    ipha, NULL, mctl_present);
1665 		if (first_mp == NULL)
1666 			return;
1667 	}
1668 	/*
1669 	 * We have accepted the ICMP message. It means that we will
1670 	 * respond to the packet if needed. It may not be delivered
1671 	 * to the upper client depending on the policy constraints
1672 	 * and the disposition in ipsec_inbound_accept_clear.
1673 	 */
1674 
1675 	ASSERT(ill != NULL);
1676 
1677 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1678 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1679 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1680 		/* Last chance to get real. */
1681 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1682 			BUMP_MIB(&icmp_mib, icmpInErrors);
1683 			freemsg(first_mp);
1684 			return;
1685 		}
1686 		/* Refresh iph following the pullup. */
1687 		ipha = (ipha_t *)mp->b_rptr;
1688 	}
1689 	/* ICMP header checksum, including checksum field, should be zero. */
1690 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1691 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1692 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1693 		freemsg(first_mp);
1694 		return;
1695 	}
1696 	/* The IP header will always be a multiple of four bytes */
1697 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1698 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1699 	    icmph->icmph_code));
1700 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1701 	/* We will set "interested" to "true" if we want a copy */
1702 	interested = B_FALSE;
1703 	switch (icmph->icmph_type) {
1704 	case ICMP_ECHO_REPLY:
1705 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1706 		break;
1707 	case ICMP_DEST_UNREACHABLE:
1708 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1709 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1710 		interested = B_TRUE;	/* Pass up to transport */
1711 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1712 		break;
1713 	case ICMP_SOURCE_QUENCH:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1716 		break;
1717 	case ICMP_REDIRECT:
1718 		if (!ip_ignore_redirect)
1719 			interested = B_TRUE;
1720 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1721 		break;
1722 	case ICMP_ECHO_REQUEST:
1723 		/*
1724 		 * Whether to respond to echo requests that come in as IP
1725 		 * broadcasts or as IP multicast is subject to debate
1726 		 * (what isn't?).  We aim to please, you pick it.
1727 		 * Default is do it.
1728 		 */
1729 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1730 			/* unicast: always respond */
1731 			interested = B_TRUE;
1732 		} else if (CLASSD(ipha->ipha_dst)) {
1733 			/* multicast: respond based on tunable */
1734 			interested = ip_g_resp_to_echo_mcast;
1735 		} else if (broadcast) {
1736 			/* broadcast: respond based on tunable */
1737 			interested = ip_g_resp_to_echo_bcast;
1738 		}
1739 		BUMP_MIB(&icmp_mib, icmpInEchos);
1740 		break;
1741 	case ICMP_ROUTER_ADVERTISEMENT:
1742 	case ICMP_ROUTER_SOLICITATION:
1743 		break;
1744 	case ICMP_TIME_EXCEEDED:
1745 		interested = B_TRUE;	/* Pass up to transport */
1746 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1747 		break;
1748 	case ICMP_PARAM_PROBLEM:
1749 		interested = B_TRUE;	/* Pass up to transport */
1750 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1751 		break;
1752 	case ICMP_TIME_STAMP_REQUEST:
1753 		/* Response to Time Stamp Requests is local policy. */
1754 		if (ip_g_resp_to_timestamp &&
1755 		    /* So is whether to respond if it was an IP broadcast. */
1756 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1757 			int tstamp_len = 3 * sizeof (uint32_t);
1758 
1759 			if (wptr +  tstamp_len > mp->b_wptr) {
1760 				if (!pullupmsg(mp, wptr + tstamp_len -
1761 				    mp->b_rptr)) {
1762 					BUMP_MIB(&ip_mib, ipInDiscards);
1763 					freemsg(first_mp);
1764 					return;
1765 				}
1766 				/* Refresh ipha following the pullup. */
1767 				ipha = (ipha_t *)mp->b_rptr;
1768 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1769 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1770 			}
1771 			interested = B_TRUE;
1772 		}
1773 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1774 		break;
1775 	case ICMP_TIME_STAMP_REPLY:
1776 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1777 		break;
1778 	case ICMP_INFO_REQUEST:
1779 		/* Per RFC 1122 3.2.2.7, ignore this. */
1780 	case ICMP_INFO_REPLY:
1781 		break;
1782 	case ICMP_ADDRESS_MASK_REQUEST:
1783 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1784 		    /* TODO m_pullup of complete header? */
1785 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1786 			interested = B_TRUE;
1787 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1788 		break;
1789 	case ICMP_ADDRESS_MASK_REPLY:
1790 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1791 		break;
1792 	default:
1793 		interested = B_TRUE;	/* Pass up to transport */
1794 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1795 		break;
1796 	}
1797 	/* See if there is an ICMP client. */
1798 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1799 		/* If there is an ICMP client and we want one too, copy it. */
1800 		mblk_t *first_mp1;
1801 
1802 		if (!interested) {
1803 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1804 			    ip_policy, recv_ill, zoneid);
1805 			return;
1806 		}
1807 		first_mp1 = ip_copymsg(first_mp);
1808 		if (first_mp1 != NULL) {
1809 			ip_fanout_proto(q, first_mp1, ill, ipha,
1810 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1811 		}
1812 	} else if (!interested) {
1813 		freemsg(first_mp);
1814 		return;
1815 	} else {
1816 		/*
1817 		 * Initiate policy processing for this packet if ip_policy
1818 		 * is true.
1819 		 */
1820 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1821 			ill_index = ill->ill_phyint->phyint_ifindex;
1822 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1823 			if (mp == NULL) {
1824 				if (mctl_present) {
1825 					freeb(first_mp);
1826 				}
1827 				BUMP_MIB(&icmp_mib, icmpInErrors);
1828 				return;
1829 			}
1830 		}
1831 	}
1832 	/* We want to do something with it. */
1833 	/* Check db_ref to make sure we can modify the packet. */
1834 	if (mp->b_datap->db_ref > 1) {
1835 		mblk_t	*first_mp1;
1836 
1837 		first_mp1 = ip_copymsg(first_mp);
1838 		freemsg(first_mp);
1839 		if (!first_mp1) {
1840 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1841 			return;
1842 		}
1843 		first_mp = first_mp1;
1844 		if (mctl_present) {
1845 			mp = first_mp->b_cont;
1846 			ASSERT(mp != NULL);
1847 		} else {
1848 			mp = first_mp;
1849 		}
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 	switch (icmph->icmph_type) {
1855 	case ICMP_ADDRESS_MASK_REQUEST:
1856 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1857 		if (ipif == NULL) {
1858 			freemsg(first_mp);
1859 			return;
1860 		}
1861 		/*
1862 		 * outging interface must be IPv4
1863 		 */
1864 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1865 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1866 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1867 		ipif_refrele(ipif);
1868 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1869 		break;
1870 	case ICMP_ECHO_REQUEST:
1871 		icmph->icmph_type = ICMP_ECHO_REPLY;
1872 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1873 		break;
1874 	case ICMP_TIME_STAMP_REQUEST: {
1875 		uint32_t *tsp;
1876 
1877 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1878 		tsp = (uint32_t *)wptr;
1879 		tsp++;		/* Skip past 'originate time' */
1880 		/* Compute # of milliseconds since midnight */
1881 		gethrestime(&now);
1882 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1883 		    now.tv_nsec / (NANOSEC / MILLISEC);
1884 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1885 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1886 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1887 		break;
1888 	}
1889 	default:
1890 		ipha = (ipha_t *)&icmph[1];
1891 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1892 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1893 				BUMP_MIB(&ip_mib, ipInDiscards);
1894 				freemsg(first_mp);
1895 				return;
1896 			}
1897 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 			ipha = (ipha_t *)&icmph[1];
1899 		}
1900 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1901 			BUMP_MIB(&ip_mib, ipInDiscards);
1902 			freemsg(first_mp);
1903 			return;
1904 		}
1905 		hdr_length = IPH_HDR_LENGTH(ipha);
1906 		if (hdr_length < sizeof (ipha_t)) {
1907 			BUMP_MIB(&ip_mib, ipInDiscards);
1908 			freemsg(first_mp);
1909 			return;
1910 		}
1911 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1912 			if (!pullupmsg(mp,
1913 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1914 				BUMP_MIB(&ip_mib, ipInDiscards);
1915 				freemsg(first_mp);
1916 				return;
1917 			}
1918 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1919 			ipha = (ipha_t *)&icmph[1];
1920 		}
1921 		switch (icmph->icmph_type) {
1922 		case ICMP_REDIRECT:
1923 			/*
1924 			 * As there is no upper client to deliver, we don't
1925 			 * need the first_mp any more.
1926 			 */
1927 			if (mctl_present) {
1928 				freeb(first_mp);
1929 			}
1930 			icmp_redirect(mp);
1931 			return;
1932 		case ICMP_DEST_UNREACHABLE:
1933 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1934 				if (!icmp_inbound_too_big(icmph, ipha)) {
1935 					freemsg(first_mp);
1936 					return;
1937 				}
1938 			}
1939 			/* FALLTHRU */
1940 		default :
1941 			/*
1942 			 * IPQoS notes: Since we have already done IPQoS
1943 			 * processing we don't want to do it again in
1944 			 * the fanout routines called by
1945 			 * icmp_inbound_error_fanout, hence the last
1946 			 * argument, ip_policy, is B_FALSE.
1947 			 */
1948 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1949 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1950 			    B_FALSE, recv_ill, zoneid);
1951 		}
1952 		return;
1953 	}
1954 	/* Send out an ICMP packet */
1955 	icmph->icmph_checksum = 0;
1956 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1957 	if (icmph->icmph_checksum == 0)
1958 		icmph->icmph_checksum = 0xFFFF;
1959 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1960 		ipif_t	*ipif_chosen;
1961 		/*
1962 		 * Make it look like it was directed to us, so we don't look
1963 		 * like a fool with a broadcast or multicast source address.
1964 		 */
1965 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1966 		/*
1967 		 * Make sure that we haven't grabbed an interface that's DOWN.
1968 		 */
1969 		if (ipif != NULL) {
1970 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1971 			    ipha->ipha_src, zoneid);
1972 			if (ipif_chosen != NULL) {
1973 				ipif_refrele(ipif);
1974 				ipif = ipif_chosen;
1975 			}
1976 		}
1977 		if (ipif == NULL) {
1978 			ip0dbg(("icmp_inbound: "
1979 			    "No source for broadcast/multicast:\n"
1980 			    "\tsrc 0x%x dst 0x%x ill %p "
1981 			    "ipif_lcl_addr 0x%x\n",
1982 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1983 			    (void *)ill,
1984 			    ill->ill_ipif->ipif_lcl_addr));
1985 			freemsg(first_mp);
1986 			return;
1987 		}
1988 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1989 		ipha->ipha_dst = ipif->ipif_src_addr;
1990 		ipif_refrele(ipif);
1991 	}
1992 	/* Reset time to live. */
1993 	ipha->ipha_ttl = ip_def_ttl;
1994 	{
1995 		/* Swap source and destination addresses */
1996 		ipaddr_t tmp;
1997 
1998 		tmp = ipha->ipha_src;
1999 		ipha->ipha_src = ipha->ipha_dst;
2000 		ipha->ipha_dst = tmp;
2001 	}
2002 	ipha->ipha_ident = 0;
2003 	if (!IS_SIMPLE_IPH(ipha))
2004 		icmp_options_update(ipha);
2005 
2006 	/*
2007 	 * ICMP echo replies should go out on the same interface
2008 	 * the request came on as probes used by in.mpathd for detecting
2009 	 * NIC failures are ECHO packets. We turn-off load spreading
2010 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2011 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2012 	 * function. This is in turn handled by ip_wput and ip_newroute
2013 	 * to make sure that the packet goes out on the interface it came
2014 	 * in on. If we don't turnoff load spreading, the packets might get
2015 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2016 	 * to go out and in.mpathd would wrongly detect a failure or
2017 	 * mis-detect a NIC failure for link failure. As load spreading
2018 	 * can happen only if ill_group is not NULL, we do only for
2019 	 * that case and this does not affect the normal case.
2020 	 *
2021 	 * We turn off load spreading only on echo packets that came from
2022 	 * on-link hosts. If the interface route has been deleted, this will
2023 	 * not be enforced as we can't do much. For off-link hosts, as the
2024 	 * default routes in IPv4 does not typically have an ire_ipif
2025 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2026 	 * Moreover, expecting a default route through this interface may
2027 	 * not be correct. We use ipha_dst because of the swap above.
2028 	 */
2029 	onlink = B_FALSE;
2030 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2031 		/*
2032 		 * First, we need to make sure that it is not one of our
2033 		 * local addresses. If we set onlink when it is one of
2034 		 * our local addresses, we will end up creating IRE_CACHES
2035 		 * for one of our local addresses. Then, we will never
2036 		 * accept packets for them afterwards.
2037 		 */
2038 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2039 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2040 		if (src_ire == NULL) {
2041 			ipif = ipif_get_next_ipif(NULL, ill);
2042 			if (ipif == NULL) {
2043 				BUMP_MIB(&ip_mib, ipInDiscards);
2044 				freemsg(mp);
2045 				return;
2046 			}
2047 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2048 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2049 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2050 			ipif_refrele(ipif);
2051 			if (src_ire != NULL) {
2052 				onlink = B_TRUE;
2053 				ire_refrele(src_ire);
2054 			}
2055 		} else {
2056 			ire_refrele(src_ire);
2057 		}
2058 	}
2059 	if (!mctl_present) {
2060 		/*
2061 		 * This packet should go out the same way as it
2062 		 * came in i.e in clear. To make sure that global
2063 		 * policy will not be applied to this in ip_wput_ire,
2064 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2065 		 */
2066 		ASSERT(first_mp == mp);
2067 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2068 			BUMP_MIB(&ip_mib, ipInDiscards);
2069 			freemsg(mp);
2070 			return;
2071 		}
2072 		ii = (ipsec_in_t *)first_mp->b_rptr;
2073 
2074 		/* This is not a secure packet */
2075 		ii->ipsec_in_secure = B_FALSE;
2076 		if (onlink) {
2077 			ii->ipsec_in_attach_if = B_TRUE;
2078 			ii->ipsec_in_ill_index =
2079 			    ill->ill_phyint->phyint_ifindex;
2080 			ii->ipsec_in_rill_index =
2081 			    recv_ill->ill_phyint->phyint_ifindex;
2082 		}
2083 		first_mp->b_cont = mp;
2084 	} else if (onlink) {
2085 		ii = (ipsec_in_t *)first_mp->b_rptr;
2086 		ii->ipsec_in_attach_if = B_TRUE;
2087 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2088 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2089 	} else {
2090 		ii = (ipsec_in_t *)first_mp->b_rptr;
2091 	}
2092 	ii->ipsec_in_zoneid = zoneid;
2093 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2094 		BUMP_MIB(&ip_mib, ipInDiscards);
2095 		return;
2096 	}
2097 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2098 	put(WR(q), first_mp);
2099 }
2100 
2101 /* Table from RFC 1191 */
2102 static int icmp_frag_size_table[] =
2103 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2104 
2105 /*
2106  * Process received ICMP Packet too big.
2107  * After updating any IRE it does the fanout to any matching transport streams.
2108  * Assumes the message has been pulled up till the IP header that caused
2109  * the error.
2110  *
2111  * Returns B_FALSE on failure and B_TRUE on success.
2112  */
2113 static boolean_t
2114 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2115 {
2116 	ire_t	*ire, *first_ire;
2117 	int	mtu;
2118 	int	hdr_length;
2119 
2120 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2121 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2122 
2123 	hdr_length = IPH_HDR_LENGTH(ipha);
2124 
2125 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2126 	    ALL_ZONES, MATCH_IRE_TYPE);
2127 
2128 	if (!first_ire) {
2129 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2130 		    ntohl(ipha->ipha_dst)));
2131 		return (B_FALSE);
2132 	}
2133 	/* Drop if the original packet contained a source route */
2134 	if (ip_source_route_included(ipha)) {
2135 		ire_refrele(first_ire);
2136 		return (B_FALSE);
2137 	}
2138 	/* Check for MTU discovery advice as described in RFC 1191 */
2139 	mtu = ntohs(icmph->icmph_du_mtu);
2140 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2141 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2142 	    ire = ire->ire_next) {
2143 		mutex_enter(&ire->ire_lock);
2144 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2145 			/* Reduce the IRE max frag value as advised. */
2146 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2147 			ip1dbg(("Received mtu from router: %d\n", mtu));
2148 		} else {
2149 			uint32_t length;
2150 			int	i;
2151 
2152 			/*
2153 			 * Use the table from RFC 1191 to figure out
2154 			 * the next "plateau" based on the length in
2155 			 * the original IP packet.
2156 			 */
2157 			length = ntohs(ipha->ipha_length);
2158 			if (ire->ire_max_frag <= length &&
2159 			    ire->ire_max_frag >= length - hdr_length) {
2160 				/*
2161 				 * Handle broken BSD 4.2 systems that
2162 				 * return the wrong iph_length in ICMP
2163 				 * errors.
2164 				 */
2165 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2166 				    length, ire->ire_max_frag));
2167 				length -= hdr_length;
2168 			}
2169 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2170 				if (length > icmp_frag_size_table[i])
2171 					break;
2172 			}
2173 			if (i == A_CNT(icmp_frag_size_table)) {
2174 				/* Smaller than 68! */
2175 				ip1dbg(("Too big for packet size %d\n",
2176 				    length));
2177 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2178 				ire->ire_frag_flag = 0;
2179 			} else {
2180 				mtu = icmp_frag_size_table[i];
2181 				ip1dbg(("Calculated mtu %d, packet size %d, "
2182 				    "before %d", mtu, length,
2183 				    ire->ire_max_frag));
2184 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2185 				ip1dbg((", after %d\n", ire->ire_max_frag));
2186 			}
2187 			/* Record the new max frag size for the ULP. */
2188 			icmph->icmph_du_zero = 0;
2189 			icmph->icmph_du_mtu =
2190 			    htons((uint16_t)ire->ire_max_frag);
2191 		}
2192 		mutex_exit(&ire->ire_lock);
2193 	}
2194 	rw_exit(&first_ire->ire_bucket->irb_lock);
2195 	ire_refrele(first_ire);
2196 	return (B_TRUE);
2197 }
2198 
2199 /*
2200  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2201  * calls this function.
2202  */
2203 static mblk_t *
2204 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2205 {
2206 	ipha_t *ipha;
2207 	icmph_t *icmph;
2208 	ipha_t *in_ipha;
2209 	int length;
2210 
2211 	ASSERT(mp->b_datap->db_type == M_DATA);
2212 
2213 	/*
2214 	 * For Self-encapsulated packets, we added an extra IP header
2215 	 * without the options. Inner IP header is the one from which
2216 	 * the outer IP header was formed. Thus, we need to remove the
2217 	 * outer IP header. To do this, we pullup the whole message
2218 	 * and overlay whatever follows the outer IP header over the
2219 	 * outer IP header.
2220 	 */
2221 
2222 	if (!pullupmsg(mp, -1)) {
2223 		BUMP_MIB(&ip_mib, ipInDiscards);
2224 		return (NULL);
2225 	}
2226 
2227 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2228 	ipha = (ipha_t *)&icmph[1];
2229 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2230 
2231 	/*
2232 	 * The length that we want to overlay is following the inner
2233 	 * IP header. Subtracting the IP header + icmp header + outer
2234 	 * IP header's length should give us the length that we want to
2235 	 * overlay.
2236 	 */
2237 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2238 	    hdr_length;
2239 	/*
2240 	 * Overlay whatever follows the inner header over the
2241 	 * outer header.
2242 	 */
2243 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2244 
2245 	/* Set the wptr to account for the outer header */
2246 	mp->b_wptr -= hdr_length;
2247 	return (mp);
2248 }
2249 
2250 /*
2251  * Try to pass the ICMP message upstream in case the ULP cares.
2252  *
2253  * If the packet that caused the ICMP error is secure, we send
2254  * it to AH/ESP to make sure that the attached packet has a
2255  * valid association. ipha in the code below points to the
2256  * IP header of the packet that caused the error.
2257  *
2258  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2259  * in the context of IPSEC. Normally we tell the upper layer
2260  * whenever we send the ire (including ip_bind), the IPSEC header
2261  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2262  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2263  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2264  * same thing. As TCP has the IPSEC options size that needs to be
2265  * adjusted, we just pass the MTU unchanged.
2266  *
2267  * IFN could have been generated locally or by some router.
2268  *
2269  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2270  *	    This happens because IP adjusted its value of MTU on an
2271  *	    earlier IFN message and could not tell the upper layer,
2272  *	    the new adjusted value of MTU e.g. Packet was encrypted
2273  *	    or there was not enough information to fanout to upper
2274  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2275  *	    generates the IFN, where IPSEC processing has *not* been
2276  *	    done.
2277  *
2278  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2279  *	    could have generated this. This happens because ire_max_frag
2280  *	    value in IP was set to a new value, while the IPSEC processing
2281  *	    was being done and after we made the fragmentation check in
2282  *	    ip_wput_ire. Thus on return from IPSEC processing,
2283  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2284  *	    and generates the IFN. As IPSEC processing is over, we fanout
2285  *	    to AH/ESP to remove the header.
2286  *
2287  *	    In both these cases, ipsec_in_loopback will be set indicating
2288  *	    that IFN was generated locally.
2289  *
2290  * ROUTER : IFN could be secure or non-secure.
2291  *
2292  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2293  *	      packet in error has AH/ESP headers to validate the AH/ESP
2294  *	      headers. AH/ESP will verify whether there is a valid SA or
2295  *	      not and send it back. We will fanout again if we have more
2296  *	      data in the packet.
2297  *
2298  *	      If the packet in error does not have AH/ESP, we handle it
2299  *	      like any other case.
2300  *
2301  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2302  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2303  *	      for validation. AH/ESP will verify whether there is a
2304  *	      valid SA or not and send it back. We will fanout again if
2305  *	      we have more data in the packet.
2306  *
2307  *	      If the packet in error does not have AH/ESP, we handle it
2308  *	      like any other case.
2309  */
2310 static void
2311 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2312     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2313     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2314     zoneid_t zoneid)
2315 {
2316 	uint16_t *up;	/* Pointer to ports in ULP header */
2317 	uint32_t ports;	/* reversed ports for fanout */
2318 	ipha_t ripha;	/* With reversed addresses */
2319 	mblk_t *first_mp;
2320 	ipsec_in_t *ii;
2321 	tcph_t	*tcph;
2322 	conn_t	*connp;
2323 
2324 	first_mp = mp;
2325 	if (mctl_present) {
2326 		mp = first_mp->b_cont;
2327 		ASSERT(mp != NULL);
2328 
2329 		ii = (ipsec_in_t *)first_mp->b_rptr;
2330 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2331 	} else {
2332 		ii = NULL;
2333 	}
2334 
2335 	switch (ipha->ipha_protocol) {
2336 	case IPPROTO_UDP:
2337 		/*
2338 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2339 		 * transport header.
2340 		 */
2341 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2342 		    mp->b_wptr) {
2343 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2344 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2345 				BUMP_MIB(&ip_mib, ipInDiscards);
2346 				goto drop_pkt;
2347 			}
2348 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2349 			ipha = (ipha_t *)&icmph[1];
2350 		}
2351 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2352 
2353 		/*
2354 		 * Attempt to find a client stream based on port.
2355 		 * Note that we do a reverse lookup since the header is
2356 		 * in the form we sent it out.
2357 		 * The ripha header is only used for the IP_UDP_MATCH and we
2358 		 * only set the src and dst addresses and protocol.
2359 		 */
2360 		ripha.ipha_src = ipha->ipha_dst;
2361 		ripha.ipha_dst = ipha->ipha_src;
2362 		ripha.ipha_protocol = ipha->ipha_protocol;
2363 		((uint16_t *)&ports)[0] = up[1];
2364 		((uint16_t *)&ports)[1] = up[0];
2365 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2366 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2367 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2368 		    icmph->icmph_type, icmph->icmph_code));
2369 
2370 		/* Have to change db_type after any pullupmsg */
2371 		DB_TYPE(mp) = M_CTL;
2372 
2373 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2374 		    mctl_present, ip_policy, recv_ill, zoneid);
2375 		return;
2376 
2377 	case IPPROTO_TCP:
2378 		/*
2379 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2380 		 * transport header.
2381 		 */
2382 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2383 		    mp->b_wptr) {
2384 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2385 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2386 				BUMP_MIB(&ip_mib, ipInDiscards);
2387 				goto drop_pkt;
2388 			}
2389 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2390 			ipha = (ipha_t *)&icmph[1];
2391 		}
2392 		/*
2393 		 * Find a TCP client stream for this packet.
2394 		 * Note that we do a reverse lookup since the header is
2395 		 * in the form we sent it out.
2396 		 */
2397 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2398 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2399 		if (connp == NULL) {
2400 			BUMP_MIB(&ip_mib, ipInDiscards);
2401 			goto drop_pkt;
2402 		}
2403 
2404 		/* Have to change db_type after any pullupmsg */
2405 		DB_TYPE(mp) = M_CTL;
2406 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2407 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2408 		return;
2409 
2410 	case IPPROTO_SCTP:
2411 		/*
2412 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2413 		 * transport header.
2414 		 */
2415 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2416 		    mp->b_wptr) {
2417 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2418 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2419 				BUMP_MIB(&ip_mib, ipInDiscards);
2420 				goto drop_pkt;
2421 			}
2422 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2423 			ipha = (ipha_t *)&icmph[1];
2424 		}
2425 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2426 		/*
2427 		 * Find a SCTP client stream for this packet.
2428 		 * Note that we do a reverse lookup since the header is
2429 		 * in the form we sent it out.
2430 		 * The ripha header is only used for the matching and we
2431 		 * only set the src and dst addresses, protocol, and version.
2432 		 */
2433 		ripha.ipha_src = ipha->ipha_dst;
2434 		ripha.ipha_dst = ipha->ipha_src;
2435 		ripha.ipha_protocol = ipha->ipha_protocol;
2436 		ripha.ipha_version_and_hdr_length =
2437 		    ipha->ipha_version_and_hdr_length;
2438 		((uint16_t *)&ports)[0] = up[1];
2439 		((uint16_t *)&ports)[1] = up[0];
2440 
2441 		/* Have to change db_type after any pullupmsg */
2442 		DB_TYPE(mp) = M_CTL;
2443 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2444 		    mctl_present, ip_policy, 0, zoneid);
2445 		return;
2446 
2447 	case IPPROTO_ESP:
2448 	case IPPROTO_AH: {
2449 		int ipsec_rc;
2450 
2451 		/*
2452 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2453 		 * We will re-use the IPSEC_IN if it is already present as
2454 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2455 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2456 		 * one and attach it in the front.
2457 		 */
2458 		if (ii != NULL) {
2459 			/*
2460 			 * ip_fanout_proto_again converts the ICMP errors
2461 			 * that come back from AH/ESP to M_DATA so that
2462 			 * if it is non-AH/ESP and we do a pullupmsg in
2463 			 * this function, it would work. Convert it back
2464 			 * to M_CTL before we send up as this is a ICMP
2465 			 * error. This could have been generated locally or
2466 			 * by some router. Validate the inner IPSEC
2467 			 * headers.
2468 			 *
2469 			 * NOTE : ill_index is used by ip_fanout_proto_again
2470 			 * to locate the ill.
2471 			 */
2472 			ASSERT(ill != NULL);
2473 			ii->ipsec_in_ill_index =
2474 			    ill->ill_phyint->phyint_ifindex;
2475 			ii->ipsec_in_rill_index =
2476 			    recv_ill->ill_phyint->phyint_ifindex;
2477 			DB_TYPE(first_mp->b_cont) = M_CTL;
2478 		} else {
2479 			/*
2480 			 * IPSEC_IN is not present. We attach a ipsec_in
2481 			 * message and send up to IPSEC for validating
2482 			 * and removing the IPSEC headers. Clear
2483 			 * ipsec_in_secure so that when we return
2484 			 * from IPSEC, we don't mistakenly think that this
2485 			 * is a secure packet came from the network.
2486 			 *
2487 			 * NOTE : ill_index is used by ip_fanout_proto_again
2488 			 * to locate the ill.
2489 			 */
2490 			ASSERT(first_mp == mp);
2491 			first_mp = ipsec_in_alloc(B_TRUE);
2492 			if (first_mp == NULL) {
2493 				freemsg(mp);
2494 				BUMP_MIB(&ip_mib, ipInDiscards);
2495 				return;
2496 			}
2497 			ii = (ipsec_in_t *)first_mp->b_rptr;
2498 
2499 			/* This is not a secure packet */
2500 			ii->ipsec_in_secure = B_FALSE;
2501 			first_mp->b_cont = mp;
2502 			DB_TYPE(mp) = M_CTL;
2503 			ASSERT(ill != NULL);
2504 			ii->ipsec_in_ill_index =
2505 			    ill->ill_phyint->phyint_ifindex;
2506 			ii->ipsec_in_rill_index =
2507 			    recv_ill->ill_phyint->phyint_ifindex;
2508 		}
2509 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2510 
2511 		if (!ipsec_loaded()) {
2512 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2513 			return;
2514 		}
2515 
2516 		if (ipha->ipha_protocol == IPPROTO_ESP)
2517 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2518 		else
2519 			ipsec_rc = ipsecah_icmp_error(first_mp);
2520 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2521 			return;
2522 
2523 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2524 		return;
2525 	}
2526 	default:
2527 		/*
2528 		 * The ripha header is only used for the lookup and we
2529 		 * only set the src and dst addresses and protocol.
2530 		 */
2531 		ripha.ipha_src = ipha->ipha_dst;
2532 		ripha.ipha_dst = ipha->ipha_src;
2533 		ripha.ipha_protocol = ipha->ipha_protocol;
2534 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2535 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2536 		    ntohl(ipha->ipha_dst),
2537 		    icmph->icmph_type, icmph->icmph_code));
2538 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2539 			ipha_t *in_ipha;
2540 
2541 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2542 			    mp->b_wptr) {
2543 				if (!pullupmsg(mp, (uchar_t *)ipha +
2544 				    hdr_length + sizeof (ipha_t) -
2545 				    mp->b_rptr)) {
2546 
2547 					BUMP_MIB(&ip_mib, ipInDiscards);
2548 					goto drop_pkt;
2549 				}
2550 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2551 				ipha = (ipha_t *)&icmph[1];
2552 			}
2553 			/*
2554 			 * Caller has verified that length has to be
2555 			 * at least the size of IP header.
2556 			 */
2557 			ASSERT(hdr_length >= sizeof (ipha_t));
2558 			/*
2559 			 * Check the sanity of the inner IP header like
2560 			 * we did for the outer header.
2561 			 */
2562 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2563 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2564 				BUMP_MIB(&ip_mib, ipInDiscards);
2565 				goto drop_pkt;
2566 			}
2567 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2568 				BUMP_MIB(&ip_mib, ipInDiscards);
2569 				goto drop_pkt;
2570 			}
2571 			/* Check for Self-encapsulated tunnels */
2572 			if (in_ipha->ipha_src == ipha->ipha_src &&
2573 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2574 
2575 				mp = icmp_inbound_self_encap_error(mp,
2576 				    iph_hdr_length, hdr_length);
2577 				if (mp == NULL)
2578 					goto drop_pkt;
2579 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2580 				ipha = (ipha_t *)&icmph[1];
2581 				hdr_length = IPH_HDR_LENGTH(ipha);
2582 				/*
2583 				 * The packet in error is self-encapsualted.
2584 				 * And we are finding it further encapsulated
2585 				 * which we could not have possibly generated.
2586 				 */
2587 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2588 					BUMP_MIB(&ip_mib, ipInDiscards);
2589 					goto drop_pkt;
2590 				}
2591 				icmp_inbound_error_fanout(q, ill, first_mp,
2592 				    icmph, ipha, iph_hdr_length, hdr_length,
2593 				    mctl_present, ip_policy, recv_ill, zoneid);
2594 				return;
2595 			}
2596 		}
2597 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2598 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2599 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2600 		    ii != NULL &&
2601 		    ii->ipsec_in_loopback &&
2602 		    ii->ipsec_in_secure) {
2603 			/*
2604 			 * For IP tunnels that get a looped-back
2605 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2606 			 * reported new MTU to take into account the IPsec
2607 			 * headers protecting this configured tunnel.
2608 			 *
2609 			 * This allows the tunnel module (tun.c) to blindly
2610 			 * accept the MTU reported in an ICMP "too big"
2611 			 * message.
2612 			 *
2613 			 * Non-looped back ICMP messages will just be
2614 			 * handled by the security protocols (if needed),
2615 			 * and the first subsequent packet will hit this
2616 			 * path.
2617 			 */
2618 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2619 			    ipsec_in_extra_length(first_mp));
2620 		}
2621 		/* Have to change db_type after any pullupmsg */
2622 		DB_TYPE(mp) = M_CTL;
2623 
2624 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2625 		    ip_policy, recv_ill, zoneid);
2626 		return;
2627 	}
2628 	/* NOTREACHED */
2629 drop_pkt:;
2630 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2631 	freemsg(first_mp);
2632 }
2633 
2634 /*
2635  * Common IP options parser.
2636  *
2637  * Setup routine: fill in *optp with options-parsing state, then
2638  * tail-call ipoptp_next to return the first option.
2639  */
2640 uint8_t
2641 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2642 {
2643 	uint32_t totallen; /* total length of all options */
2644 
2645 	totallen = ipha->ipha_version_and_hdr_length -
2646 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2647 	totallen <<= 2;
2648 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2649 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2650 	optp->ipoptp_flags = 0;
2651 	return (ipoptp_next(optp));
2652 }
2653 
2654 /*
2655  * Common IP options parser: extract next option.
2656  */
2657 uint8_t
2658 ipoptp_next(ipoptp_t *optp)
2659 {
2660 	uint8_t *end = optp->ipoptp_end;
2661 	uint8_t *cur = optp->ipoptp_next;
2662 	uint8_t opt, len, pointer;
2663 
2664 	/*
2665 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2666 	 * has been corrupted.
2667 	 */
2668 	ASSERT(cur <= end);
2669 
2670 	if (cur == end)
2671 		return (IPOPT_EOL);
2672 
2673 	opt = cur[IPOPT_OPTVAL];
2674 
2675 	/*
2676 	 * Skip any NOP options.
2677 	 */
2678 	while (opt == IPOPT_NOP) {
2679 		cur++;
2680 		if (cur == end)
2681 			return (IPOPT_EOL);
2682 		opt = cur[IPOPT_OPTVAL];
2683 	}
2684 
2685 	if (opt == IPOPT_EOL)
2686 		return (IPOPT_EOL);
2687 
2688 	/*
2689 	 * Option requiring a length.
2690 	 */
2691 	if ((cur + 1) >= end) {
2692 		optp->ipoptp_flags |= IPOPTP_ERROR;
2693 		return (IPOPT_EOL);
2694 	}
2695 	len = cur[IPOPT_OLEN];
2696 	if (len < 2) {
2697 		optp->ipoptp_flags |= IPOPTP_ERROR;
2698 		return (IPOPT_EOL);
2699 	}
2700 	optp->ipoptp_cur = cur;
2701 	optp->ipoptp_len = len;
2702 	optp->ipoptp_next = cur + len;
2703 	if (cur + len > end) {
2704 		optp->ipoptp_flags |= IPOPTP_ERROR;
2705 		return (IPOPT_EOL);
2706 	}
2707 
2708 	/*
2709 	 * For the options which require a pointer field, make sure
2710 	 * its there, and make sure it points to either something
2711 	 * inside this option, or the end of the option.
2712 	 */
2713 	switch (opt) {
2714 	case IPOPT_RR:
2715 	case IPOPT_TS:
2716 	case IPOPT_LSRR:
2717 	case IPOPT_SSRR:
2718 		if (len <= IPOPT_OFFSET) {
2719 			optp->ipoptp_flags |= IPOPTP_ERROR;
2720 			return (opt);
2721 		}
2722 		pointer = cur[IPOPT_OFFSET];
2723 		if (pointer - 1 > len) {
2724 			optp->ipoptp_flags |= IPOPTP_ERROR;
2725 			return (opt);
2726 		}
2727 		break;
2728 	}
2729 
2730 	/*
2731 	 * Sanity check the pointer field based on the type of the
2732 	 * option.
2733 	 */
2734 	switch (opt) {
2735 	case IPOPT_RR:
2736 	case IPOPT_SSRR:
2737 	case IPOPT_LSRR:
2738 		if (pointer < IPOPT_MINOFF_SR)
2739 			optp->ipoptp_flags |= IPOPTP_ERROR;
2740 		break;
2741 	case IPOPT_TS:
2742 		if (pointer < IPOPT_MINOFF_IT)
2743 			optp->ipoptp_flags |= IPOPTP_ERROR;
2744 		/*
2745 		 * Note that the Internet Timestamp option also
2746 		 * contains two four bit fields (the Overflow field,
2747 		 * and the Flag field), which follow the pointer
2748 		 * field.  We don't need to check that these fields
2749 		 * fall within the length of the option because this
2750 		 * was implicitely done above.  We've checked that the
2751 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2752 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2753 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2754 		 */
2755 		ASSERT(len > IPOPT_POS_OV_FLG);
2756 		break;
2757 	}
2758 
2759 	return (opt);
2760 }
2761 
2762 /*
2763  * Update any record route or timestamp options to include this host.
2764  * Reverse any source route option.
2765  * This routine assumes that the options are well formed i.e. that they
2766  * have already been checked.
2767  */
2768 static void
2769 icmp_options_update(ipha_t *ipha)
2770 {
2771 	ipoptp_t	opts;
2772 	uchar_t		*opt;
2773 	uint8_t		optval;
2774 	ipaddr_t	src;		/* Our local address */
2775 	ipaddr_t	dst;
2776 
2777 	ip2dbg(("icmp_options_update\n"));
2778 	src = ipha->ipha_src;
2779 	dst = ipha->ipha_dst;
2780 
2781 	for (optval = ipoptp_first(&opts, ipha);
2782 	    optval != IPOPT_EOL;
2783 	    optval = ipoptp_next(&opts)) {
2784 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2785 		opt = opts.ipoptp_cur;
2786 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2787 		    optval, opts.ipoptp_len));
2788 		switch (optval) {
2789 			int off1, off2;
2790 		case IPOPT_SSRR:
2791 		case IPOPT_LSRR:
2792 			/*
2793 			 * Reverse the source route.  The first entry
2794 			 * should be the next to last one in the current
2795 			 * source route (the last entry is our address).
2796 			 * The last entry should be the final destination.
2797 			 */
2798 			off1 = IPOPT_MINOFF_SR - 1;
2799 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2800 			if (off2 < 0) {
2801 				/* No entries in source route */
2802 				ip1dbg((
2803 				    "icmp_options_update: bad src route\n"));
2804 				break;
2805 			}
2806 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2807 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2808 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2809 			off2 -= IP_ADDR_LEN;
2810 
2811 			while (off1 < off2) {
2812 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2813 				bcopy((char *)opt + off2, (char *)opt + off1,
2814 				    IP_ADDR_LEN);
2815 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2816 				off1 += IP_ADDR_LEN;
2817 				off2 -= IP_ADDR_LEN;
2818 			}
2819 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2820 			break;
2821 		}
2822 	}
2823 }
2824 
2825 /*
2826  * Process received ICMP Redirect messages.
2827  */
2828 /* ARGSUSED */
2829 static void
2830 icmp_redirect(mblk_t *mp)
2831 {
2832 	ipha_t	*ipha;
2833 	int	iph_hdr_length;
2834 	icmph_t	*icmph;
2835 	ipha_t	*ipha_err;
2836 	ire_t	*ire;
2837 	ire_t	*prev_ire;
2838 	ire_t	*save_ire;
2839 	ipaddr_t  src, dst, gateway;
2840 	iulp_t	ulp_info = { 0 };
2841 	int	error;
2842 
2843 	ipha = (ipha_t *)mp->b_rptr;
2844 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2845 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2846 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2847 		BUMP_MIB(&icmp_mib, icmpInErrors);
2848 		freemsg(mp);
2849 		return;
2850 	}
2851 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2852 	ipha_err = (ipha_t *)&icmph[1];
2853 	src = ipha->ipha_src;
2854 	dst = ipha_err->ipha_dst;
2855 	gateway = icmph->icmph_rd_gateway;
2856 	/* Make sure the new gateway is reachable somehow. */
2857 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2858 	    ALL_ZONES, MATCH_IRE_TYPE);
2859 	/*
2860 	 * Make sure we had a route for the dest in question and that
2861 	 * that route was pointing to the old gateway (the source of the
2862 	 * redirect packet.)
2863 	 */
2864 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2865 	    MATCH_IRE_GW);
2866 	/*
2867 	 * Check that
2868 	 *	the redirect was not from ourselves
2869 	 *	the new gateway and the old gateway are directly reachable
2870 	 */
2871 	if (!prev_ire ||
2872 	    !ire ||
2873 	    ire->ire_type == IRE_LOCAL) {
2874 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2875 		freemsg(mp);
2876 		if (ire != NULL)
2877 			ire_refrele(ire);
2878 		if (prev_ire != NULL)
2879 			ire_refrele(prev_ire);
2880 		return;
2881 	}
2882 
2883 	/*
2884 	 * Should we use the old ULP info to create the new gateway?  From
2885 	 * a user's perspective, we should inherit the info so that it
2886 	 * is a "smooth" transition.  If we do not do that, then new
2887 	 * connections going thru the new gateway will have no route metrics,
2888 	 * which is counter-intuitive to user.  From a network point of
2889 	 * view, this may or may not make sense even though the new gateway
2890 	 * is still directly connected to us so the route metrics should not
2891 	 * change much.
2892 	 *
2893 	 * But if the old ire_uinfo is not initialized, we do another
2894 	 * recursive lookup on the dest using the new gateway.  There may
2895 	 * be a route to that.  If so, use it to initialize the redirect
2896 	 * route.
2897 	 */
2898 	if (prev_ire->ire_uinfo.iulp_set) {
2899 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2900 	} else {
2901 		ire_t *tmp_ire;
2902 		ire_t *sire;
2903 
2904 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2905 		    ALL_ZONES, 0,
2906 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2907 		if (sire != NULL) {
2908 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2909 			/*
2910 			 * If sire != NULL, ire_ftable_lookup() should not
2911 			 * return a NULL value.
2912 			 */
2913 			ASSERT(tmp_ire != NULL);
2914 			ire_refrele(tmp_ire);
2915 			ire_refrele(sire);
2916 		} else if (tmp_ire != NULL) {
2917 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2918 			    sizeof (iulp_t));
2919 			ire_refrele(tmp_ire);
2920 		}
2921 	}
2922 	if (prev_ire->ire_type == IRE_CACHE)
2923 		ire_delete(prev_ire);
2924 	ire_refrele(prev_ire);
2925 	/*
2926 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2927 	 * require TOS routing
2928 	 */
2929 	switch (icmph->icmph_code) {
2930 	case 0:
2931 	case 1:
2932 		/* TODO: TOS specificity for cases 2 and 3 */
2933 	case 2:
2934 	case 3:
2935 		break;
2936 	default:
2937 		freemsg(mp);
2938 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2939 		ire_refrele(ire);
2940 		return;
2941 	}
2942 	/*
2943 	 * Create a Route Association.  This will allow us to remember that
2944 	 * someone we believe told us to use the particular gateway.
2945 	 */
2946 	save_ire = ire;
2947 	ire = ire_create(
2948 		(uchar_t *)&dst,			/* dest addr */
2949 		(uchar_t *)&ip_g_all_ones,		/* mask */
2950 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2951 		(uchar_t *)&gateway,			/* gateway addr */
2952 		NULL,					/* no in_srcaddr */
2953 		&save_ire->ire_max_frag,		/* max frag */
2954 		NULL,					/* Fast Path header */
2955 		NULL,					/* no rfq */
2956 		NULL,					/* no stq */
2957 		IRE_HOST_REDIRECT,
2958 		NULL,
2959 		NULL,
2960 		NULL,
2961 		0,
2962 		0,
2963 		0,
2964 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2965 		&ulp_info);
2966 
2967 	if (ire == NULL) {
2968 		freemsg(mp);
2969 		ire_refrele(save_ire);
2970 		return;
2971 	}
2972 	error = ire_add(&ire, NULL, NULL, NULL);
2973 	ire_refrele(save_ire);
2974 	if (error == 0) {
2975 		ire_refrele(ire);		/* Held in ire_add_v4 */
2976 		/* tell routing sockets that we received a redirect */
2977 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2978 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2979 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2980 	}
2981 
2982 	/*
2983 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2984 	 * This together with the added IRE has the effect of
2985 	 * modifying an existing redirect.
2986 	 */
2987 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2988 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2989 	if (prev_ire) {
2990 		ire_delete(prev_ire);
2991 		ire_refrele(prev_ire);
2992 	}
2993 
2994 	freemsg(mp);
2995 }
2996 
2997 /*
2998  * Generate an ICMP parameter problem message.
2999  */
3000 static void
3001 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3002 {
3003 	icmph_t	icmph;
3004 	boolean_t mctl_present;
3005 	mblk_t *first_mp;
3006 
3007 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3008 
3009 	if (!(mp = icmp_pkt_err_ok(mp))) {
3010 		if (mctl_present)
3011 			freeb(first_mp);
3012 		return;
3013 	}
3014 
3015 	bzero(&icmph, sizeof (icmph_t));
3016 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3017 	icmph.icmph_pp_ptr = ptr;
3018 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3019 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3020 }
3021 
3022 /*
3023  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3024  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3025  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3026  * an icmp error packet can be sent.
3027  * Assigns an appropriate source address to the packet. If ipha_dst is
3028  * one of our addresses use it for source. Otherwise pick a source based
3029  * on a route lookup back to ipha_src.
3030  * Note that ipha_src must be set here since the
3031  * packet is likely to arrive on an ill queue in ip_wput() which will
3032  * not set a source address.
3033  */
3034 static void
3035 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3036     boolean_t mctl_present)
3037 {
3038 	ipaddr_t dst;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha;
3041 	uint_t	len_needed;
3042 	size_t	msg_len;
3043 	mblk_t	*mp1;
3044 	ipaddr_t src;
3045 	ire_t	*ire;
3046 	mblk_t *ipsec_mp;
3047 	ipsec_out_t	*io = NULL;
3048 	boolean_t xmit_if_on = B_FALSE;
3049 	zoneid_t	zoneid;
3050 
3051 	if (mctl_present) {
3052 		/*
3053 		 * If it is :
3054 		 *
3055 		 * 1) a IPSEC_OUT, then this is caused by outbound
3056 		 *    datagram originating on this host. IPSEC processing
3057 		 *    may or may not have been done. Refer to comments above
3058 		 *    icmp_inbound_error_fanout for details.
3059 		 *
3060 		 * 2) a IPSEC_IN if we are generating a icmp_message
3061 		 *    for an incoming datagram destined for us i.e called
3062 		 *    from ip_fanout_send_icmp.
3063 		 */
3064 		ipsec_info_t *in;
3065 		ipsec_mp = mp;
3066 		mp = ipsec_mp->b_cont;
3067 
3068 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3069 		ipha = (ipha_t *)mp->b_rptr;
3070 
3071 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3072 		    in->ipsec_info_type == IPSEC_IN);
3073 
3074 		if (in->ipsec_info_type == IPSEC_IN) {
3075 			/*
3076 			 * Convert the IPSEC_IN to IPSEC_OUT.
3077 			 */
3078 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3079 				BUMP_MIB(&ip_mib, ipOutDiscards);
3080 				return;
3081 			}
3082 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3083 		} else {
3084 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3085 			io = (ipsec_out_t *)in;
3086 			if (io->ipsec_out_xmit_if)
3087 				xmit_if_on = B_TRUE;
3088 			/*
3089 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3090 			 * ire lookup.
3091 			 */
3092 			io->ipsec_out_proc_begin = B_FALSE;
3093 		}
3094 		zoneid = io->ipsec_out_zoneid;
3095 		ASSERT(zoneid != ALL_ZONES);
3096 	} else {
3097 		/*
3098 		 * This is in clear. The icmp message we are building
3099 		 * here should go out in clear.
3100 		 *
3101 		 * Pardon the convolution of it all, but it's easier to
3102 		 * allocate a "use cleartext" IPSEC_IN message and convert
3103 		 * it than it is to allocate a new one.
3104 		 */
3105 		ipsec_in_t *ii;
3106 		ASSERT(DB_TYPE(mp) == M_DATA);
3107 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3108 			freemsg(mp);
3109 			BUMP_MIB(&ip_mib, ipOutDiscards);
3110 			return;
3111 		}
3112 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3113 
3114 		/* This is not a secure packet */
3115 		ii->ipsec_in_secure = B_FALSE;
3116 		if (CONN_Q(q)) {
3117 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3118 		} else {
3119 			zoneid = GLOBAL_ZONEID;
3120 		}
3121 		ii->ipsec_in_zoneid = zoneid;
3122 		ipsec_mp->b_cont = mp;
3123 		ipha = (ipha_t *)mp->b_rptr;
3124 		/*
3125 		 * Convert the IPSEC_IN to IPSEC_OUT.
3126 		 */
3127 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3128 			BUMP_MIB(&ip_mib, ipOutDiscards);
3129 			return;
3130 		}
3131 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3132 	}
3133 
3134 	/* Remember our eventual destination */
3135 	dst = ipha->ipha_src;
3136 
3137 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3138 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3139 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3140 		src = ipha->ipha_dst;
3141 	} else if (!xmit_if_on) {
3142 		if (ire != NULL)
3143 			ire_refrele(ire);
3144 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3145 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3146 		if (ire == NULL) {
3147 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3148 			freemsg(ipsec_mp);
3149 			return;
3150 		}
3151 		src = ire->ire_src_addr;
3152 	} else {
3153 		ipif_t	*ipif = NULL;
3154 		ill_t	*ill;
3155 		/*
3156 		 * This must be an ICMP error coming from
3157 		 * ip_mrtun_forward(). The src addr should
3158 		 * be equal to the IP-addr of the outgoing
3159 		 * interface.
3160 		 */
3161 		if (io == NULL) {
3162 			/* This is not a IPSEC_OUT type control msg */
3163 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3164 			freemsg(ipsec_mp);
3165 			return;
3166 		}
3167 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3168 		    NULL, NULL, NULL, NULL);
3169 		if (ill != NULL) {
3170 			ipif = ipif_get_next_ipif(NULL, ill);
3171 			ill_refrele(ill);
3172 		}
3173 		if (ipif == NULL) {
3174 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3175 			freemsg(ipsec_mp);
3176 			return;
3177 		}
3178 		src = ipif->ipif_src_addr;
3179 		ipif_refrele(ipif);
3180 	}
3181 
3182 	if (ire != NULL)
3183 		ire_refrele(ire);
3184 
3185 	/*
3186 	 * Check if we can send back more then 8 bytes in addition
3187 	 * to the IP header. We will include as much as 64 bytes.
3188 	 */
3189 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3190 	msg_len = msgdsize(mp);
3191 	if (msg_len > len_needed) {
3192 		(void) adjmsg(mp, len_needed - msg_len);
3193 		msg_len = len_needed;
3194 	}
3195 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3196 	if (!mp1) {
3197 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3198 		freemsg(ipsec_mp);
3199 		return;
3200 	}
3201 	mp1->b_cont = mp;
3202 	mp = mp1;
3203 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3204 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3205 	    io->ipsec_out_type == IPSEC_OUT);
3206 	ipsec_mp->b_cont = mp;
3207 
3208 	/*
3209 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3210 	 * node generates be accepted in peace by all on-host destinations.
3211 	 * If we do NOT assume that all on-host destinations trust
3212 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3213 	 * (Look for ipsec_out_icmp_loopback).
3214 	 */
3215 	io->ipsec_out_icmp_loopback = B_TRUE;
3216 
3217 	ipha = (ipha_t *)mp->b_rptr;
3218 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3219 	*ipha = icmp_ipha;
3220 	ipha->ipha_src = src;
3221 	ipha->ipha_dst = dst;
3222 	ipha->ipha_ttl = ip_def_ttl;
3223 	msg_len += sizeof (icmp_ipha) + len;
3224 	if (msg_len > IP_MAXPACKET) {
3225 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3226 		msg_len = IP_MAXPACKET;
3227 	}
3228 	ipha->ipha_length = htons((uint16_t)msg_len);
3229 	icmph = (icmph_t *)&ipha[1];
3230 	bcopy(stuff, icmph, len);
3231 	icmph->icmph_checksum = 0;
3232 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3233 	if (icmph->icmph_checksum == 0)
3234 		icmph->icmph_checksum = 0xFFFF;
3235 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3236 	put(q, ipsec_mp);
3237 }
3238 
3239 /*
3240  * Determine if an ICMP error packet can be sent given the rate limit.
3241  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3242  * in milliseconds) and a burst size. Burst size number of packets can
3243  * be sent arbitrarely closely spaced.
3244  * The state is tracked using two variables to implement an approximate
3245  * token bucket filter:
3246  *	icmp_pkt_err_last - lbolt value when the last burst started
3247  *	icmp_pkt_err_sent - number of packets sent in current burst
3248  */
3249 boolean_t
3250 icmp_err_rate_limit(void)
3251 {
3252 	clock_t now = TICK_TO_MSEC(lbolt);
3253 	uint_t refilled; /* Number of packets refilled in tbf since last */
3254 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3255 
3256 	if (err_interval == 0)
3257 		return (B_FALSE);
3258 
3259 	if (icmp_pkt_err_last > now) {
3260 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3261 		icmp_pkt_err_last = 0;
3262 		icmp_pkt_err_sent = 0;
3263 	}
3264 	/*
3265 	 * If we are in a burst update the token bucket filter.
3266 	 * Update the "last" time to be close to "now" but make sure
3267 	 * we don't loose precision.
3268 	 */
3269 	if (icmp_pkt_err_sent != 0) {
3270 		refilled = (now - icmp_pkt_err_last)/err_interval;
3271 		if (refilled > icmp_pkt_err_sent) {
3272 			icmp_pkt_err_sent = 0;
3273 		} else {
3274 			icmp_pkt_err_sent -= refilled;
3275 			icmp_pkt_err_last += refilled * err_interval;
3276 		}
3277 	}
3278 	if (icmp_pkt_err_sent == 0) {
3279 		/* Start of new burst */
3280 		icmp_pkt_err_last = now;
3281 	}
3282 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3283 		icmp_pkt_err_sent++;
3284 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3285 		    icmp_pkt_err_sent));
3286 		return (B_FALSE);
3287 	}
3288 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3289 	return (B_TRUE);
3290 }
3291 
3292 /*
3293  * Check if it is ok to send an IPv4 ICMP error packet in
3294  * response to the IPv4 packet in mp.
3295  * Free the message and return null if no
3296  * ICMP error packet should be sent.
3297  */
3298 static mblk_t *
3299 icmp_pkt_err_ok(mblk_t *mp)
3300 {
3301 	icmph_t	*icmph;
3302 	ipha_t	*ipha;
3303 	uint_t	len_needed;
3304 	ire_t	*src_ire;
3305 	ire_t	*dst_ire;
3306 
3307 	if (!mp)
3308 		return (NULL);
3309 	ipha = (ipha_t *)mp->b_rptr;
3310 	if (ip_csum_hdr(ipha)) {
3311 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3312 		freemsg(mp);
3313 		return (NULL);
3314 	}
3315 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3316 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3317 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3318 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3319 	if (src_ire != NULL || dst_ire != NULL ||
3320 	    CLASSD(ipha->ipha_dst) ||
3321 	    CLASSD(ipha->ipha_src) ||
3322 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3323 		/* Note: only errors to the fragment with offset 0 */
3324 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3325 		freemsg(mp);
3326 		if (src_ire != NULL)
3327 			ire_refrele(src_ire);
3328 		if (dst_ire != NULL)
3329 			ire_refrele(dst_ire);
3330 		return (NULL);
3331 	}
3332 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3333 		/*
3334 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3335 		 * errors in response to any ICMP errors.
3336 		 */
3337 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3338 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3339 			if (!pullupmsg(mp, len_needed)) {
3340 				BUMP_MIB(&icmp_mib, icmpInErrors);
3341 				freemsg(mp);
3342 				return (NULL);
3343 			}
3344 			ipha = (ipha_t *)mp->b_rptr;
3345 		}
3346 		icmph = (icmph_t *)
3347 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3348 		switch (icmph->icmph_type) {
3349 		case ICMP_DEST_UNREACHABLE:
3350 		case ICMP_SOURCE_QUENCH:
3351 		case ICMP_TIME_EXCEEDED:
3352 		case ICMP_PARAM_PROBLEM:
3353 		case ICMP_REDIRECT:
3354 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3355 			freemsg(mp);
3356 			return (NULL);
3357 		default:
3358 			break;
3359 		}
3360 	}
3361 	if (icmp_err_rate_limit()) {
3362 		/*
3363 		 * Only send ICMP error packets every so often.
3364 		 * This should be done on a per port/source basis,
3365 		 * but for now this will suffice.
3366 		 */
3367 		freemsg(mp);
3368 		return (NULL);
3369 	}
3370 	return (mp);
3371 }
3372 
3373 /*
3374  * Generate an ICMP redirect message.
3375  */
3376 static void
3377 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3378 {
3379 	icmph_t	icmph;
3380 
3381 	/*
3382 	 * We are called from ip_rput where we could
3383 	 * not have attached an IPSEC_IN.
3384 	 */
3385 	ASSERT(mp->b_datap->db_type == M_DATA);
3386 
3387 	if (!(mp = icmp_pkt_err_ok(mp))) {
3388 		return;
3389 	}
3390 
3391 	bzero(&icmph, sizeof (icmph_t));
3392 	icmph.icmph_type = ICMP_REDIRECT;
3393 	icmph.icmph_code = 1;
3394 	icmph.icmph_rd_gateway = gateway;
3395 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3396 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3397 }
3398 
3399 /*
3400  * Generate an ICMP time exceeded message.
3401  */
3402 void
3403 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3404 {
3405 	icmph_t	icmph;
3406 	boolean_t mctl_present;
3407 	mblk_t *first_mp;
3408 
3409 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3410 
3411 	if (!(mp = icmp_pkt_err_ok(mp))) {
3412 		if (mctl_present)
3413 			freeb(first_mp);
3414 		return;
3415 	}
3416 
3417 	bzero(&icmph, sizeof (icmph_t));
3418 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3419 	icmph.icmph_code = code;
3420 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3421 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3422 }
3423 
3424 /*
3425  * Generate an ICMP unreachable message.
3426  */
3427 void
3428 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3429 {
3430 	icmph_t	icmph;
3431 	mblk_t *first_mp;
3432 	boolean_t mctl_present;
3433 
3434 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3435 
3436 	if (!(mp = icmp_pkt_err_ok(mp))) {
3437 		if (mctl_present)
3438 			freeb(first_mp);
3439 		return;
3440 	}
3441 
3442 	bzero(&icmph, sizeof (icmph_t));
3443 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3444 	icmph.icmph_code = code;
3445 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3446 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3447 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3448 }
3449 
3450 /*
3451  * News from ARP.  ARP sends notification of interesting events down
3452  * to its clients using M_CTL messages with the interesting ARP packet
3453  * attached via b_cont.
3454  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3455  * queue as opposed to ARP sending the message to all the clients, i.e. all
3456  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3457  * table if a cache IRE is found to delete all the entries for the address in
3458  * the packet.
3459  */
3460 static void
3461 ip_arp_news(queue_t *q, mblk_t *mp)
3462 {
3463 	arcn_t		*arcn;
3464 	arh_t		*arh;
3465 	char		*cp1;
3466 	uchar_t		*cp2;
3467 	ire_t		*ire = NULL;
3468 	int		i1;
3469 	char		hbuf[128];
3470 	char		sbuf[16];
3471 	ipaddr_t	src;
3472 	in6_addr_t	v6src;
3473 	boolean_t	isv6 = B_FALSE;
3474 
3475 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3476 		if (q->q_next) {
3477 			putnext(q, mp);
3478 		} else
3479 			freemsg(mp);
3480 		return;
3481 	}
3482 	arh = (arh_t *)mp->b_cont->b_rptr;
3483 	/* Is it one we are interested in? */
3484 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3485 		isv6 = B_TRUE;
3486 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3487 		    IPV6_ADDR_LEN);
3488 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3489 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3490 		    IP_ADDR_LEN);
3491 	} else {
3492 		freemsg(mp);
3493 		return;
3494 	}
3495 
3496 	arcn = (arcn_t *)mp->b_rptr;
3497 	switch (arcn->arcn_code) {
3498 	case AR_CN_BOGON:
3499 		/*
3500 		 * Someone is sending ARP packets with a source protocol
3501 		 * address which we have published.  Either they are
3502 		 * pretending to be us, or we have been asked to proxy
3503 		 * for a machine that can do fine for itself, or two
3504 		 * different machines are providing proxy service for the
3505 		 * same protocol address, or something.  We try and do
3506 		 * something appropriate here.
3507 		 */
3508 		cp2 = (uchar_t *)&arh[1];
3509 		cp1 = hbuf;
3510 		*cp1 = '\0';
3511 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3512 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3513 		if (cp1 != hbuf)
3514 			cp1[-1] = '\0';
3515 		(void) ip_dot_addr(src, sbuf);
3516 		if (isv6)
3517 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3518 		else
3519 			ire = ire_cache_lookup(src, ALL_ZONES);
3520 
3521 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3522 			cmn_err(CE_WARN,
3523 			    "IP: Hardware address '%s' trying"
3524 			    " to be our address %s!",
3525 			    hbuf, sbuf);
3526 		} else {
3527 			cmn_err(CE_WARN,
3528 			    "IP: Proxy ARP problem?  "
3529 			    "Hardware address '%s' thinks it is %s",
3530 			    hbuf, sbuf);
3531 		}
3532 		if (ire != NULL)
3533 			ire_refrele(ire);
3534 		break;
3535 	case AR_CN_ANNOUNCE:
3536 		if (isv6) {
3537 			/*
3538 			 * For XRESOLV interfaces.
3539 			 * Delete the IRE cache entry and NCE for this
3540 			 * v6 address
3541 			 */
3542 			ip_ire_clookup_and_delete_v6(&v6src);
3543 			/*
3544 			 * If v6src is a non-zero, it's a router address
3545 			 * as below. Do the same sort of thing to clean
3546 			 * out off-net IRE_CACHE entries that go through
3547 			 * the router.
3548 			 */
3549 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3550 				ire_walk_v6(ire_delete_cache_gw_v6,
3551 				    (char *)&v6src, ALL_ZONES);
3552 			}
3553 			break;
3554 		}
3555 		/*
3556 		 * ARP gives us a copy of any broadcast packet with identical
3557 		 * sender and receiver protocol address, in
3558 		 * case we want to intuit something from it.  Such a packet
3559 		 * usually means that a machine has just come up on the net.
3560 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3561 		 * immediately pick up the rare case of a host changing
3562 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3563 		 *
3564 		 * The address in "src" may be an entry for a router.
3565 		 * (Default router, or non-default router.)  If
3566 		 * that's true, then any off-net IRE_CACHE entries
3567 		 * that go through the router with address "src"
3568 		 * must be clobbered.  Use ire_walk to achieve this
3569 		 * goal.
3570 		 *
3571 		 * It should be possible to determine if the address
3572 		 * in src is or is not for a router.  This way,
3573 		 * the ire_walk() isn't called all of the time here.
3574 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3575 		 * as it would remove all IRE_CACHE entries for onlink
3576 		 * destinations. All onlink destinations have
3577 		 * ire_gateway_addr == 0.
3578 		 */
3579 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3580 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3581 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3582 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3583 			    ALL_ZONES);
3584 		}
3585 		/* From ire_ftable_lookup */
3586 		if (ire != NULL)
3587 			ire_refrele(ire);
3588 		break;
3589 	default:
3590 		if (ire != NULL)
3591 			ire_refrele(ire);
3592 		break;
3593 	}
3594 	freemsg(mp);
3595 }
3596 
3597 /*
3598  * Create a mblk suitable for carrying the interface index and/or source link
3599  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3600  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3601  * application.
3602  */
3603 mblk_t *
3604 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3605 {
3606 	mblk_t		*mp;
3607 	in_pktinfo_t	*pinfo;
3608 	ipha_t *ipha;
3609 	struct ether_header *pether;
3610 
3611 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3612 	if (mp == NULL) {
3613 		ip1dbg(("ip_add_info: allocation failure.\n"));
3614 		return (data_mp);
3615 	}
3616 
3617 	ipha	= (ipha_t *)data_mp->b_rptr;
3618 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3619 	bzero(pinfo, sizeof (in_pktinfo_t));
3620 	pinfo->in_pkt_flags = (uchar_t)flags;
3621 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3622 
3623 	if (flags & IPF_RECVIF)
3624 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3625 
3626 	pether = (struct ether_header *)((char *)ipha
3627 	    - sizeof (struct ether_header));
3628 	/*
3629 	 * Make sure the interface is an ethernet type, since this option
3630 	 * is currently supported only on this type of interface. Also make
3631 	 * sure we are pointing correctly above db_base.
3632 	 */
3633 
3634 	if ((flags & IPF_RECVSLLA) &&
3635 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3636 	    (ill->ill_type == IFT_ETHER) &&
3637 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3638 
3639 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3640 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3641 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3642 	} else {
3643 		/*
3644 		 * Clear the bit. Indicate to upper layer that IP is not
3645 		 * sending this ancillary info.
3646 		 */
3647 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3648 	}
3649 
3650 	mp->b_datap->db_type = M_CTL;
3651 	mp->b_wptr += sizeof (in_pktinfo_t);
3652 	mp->b_cont = data_mp;
3653 
3654 	return (mp);
3655 }
3656 
3657 /*
3658  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3659  * part of the bind request.
3660  */
3661 
3662 boolean_t
3663 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3664 {
3665 	ipsec_in_t *ii;
3666 
3667 	ASSERT(policy_mp != NULL);
3668 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3669 
3670 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3671 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3672 
3673 	connp->conn_policy = ii->ipsec_in_policy;
3674 	ii->ipsec_in_policy = NULL;
3675 
3676 	if (ii->ipsec_in_action != NULL) {
3677 		if (connp->conn_latch == NULL) {
3678 			connp->conn_latch = iplatch_create();
3679 			if (connp->conn_latch == NULL)
3680 				return (B_FALSE);
3681 		}
3682 		ipsec_latch_inbound(connp->conn_latch, ii);
3683 	}
3684 	return (B_TRUE);
3685 }
3686 
3687 /*
3688  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3689  * and to arrange for power-fanout assist.  The ULP is identified by
3690  * adding a single byte at the end of the original bind message.
3691  * A ULP other than UDP or TCP that wishes to be recognized passes
3692  * down a bind with a zero length address.
3693  *
3694  * The binding works as follows:
3695  * - A zero byte address means just bind to the protocol.
3696  * - A four byte address is treated as a request to validate
3697  *   that the address is a valid local address, appropriate for
3698  *   an application to bind to. This does not affect any fanout
3699  *   information in IP.
3700  * - A sizeof sin_t byte address is used to bind to only the local address
3701  *   and port.
3702  * - A sizeof ipa_conn_t byte address contains complete fanout information
3703  *   consisting of local and remote addresses and ports.  In
3704  *   this case, the addresses are both validated as appropriate
3705  *   for this operation, and, if so, the information is retained
3706  *   for use in the inbound fanout.
3707  *
3708  * The ULP (except in the zero-length bind) can append an
3709  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3710  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3711  * a copy of the source or destination IRE (source for local bind;
3712  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3713  * policy information contained should be copied on to the conn.
3714  *
3715  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3716  */
3717 mblk_t *
3718 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3719 {
3720 	ssize_t		len;
3721 	struct T_bind_req	*tbr;
3722 	sin_t		*sin;
3723 	ipa_conn_t	*ac;
3724 	uchar_t		*ucp;
3725 	mblk_t		*mp1;
3726 	boolean_t	ire_requested;
3727 	boolean_t	ipsec_policy_set = B_FALSE;
3728 	int		error = 0;
3729 	int		protocol;
3730 	ipa_conn_x_t	*acx;
3731 
3732 	ASSERT(!connp->conn_af_isv6);
3733 	connp->conn_pkt_isv6 = B_FALSE;
3734 
3735 	len = MBLKL(mp);
3736 	if (len < (sizeof (*tbr) + 1)) {
3737 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3738 		    "ip_bind: bogus msg, len %ld", len);
3739 		/* XXX: Need to return something better */
3740 		goto bad_addr;
3741 	}
3742 	/* Back up and extract the protocol identifier. */
3743 	mp->b_wptr--;
3744 	protocol = *mp->b_wptr & 0xFF;
3745 	tbr = (struct T_bind_req *)mp->b_rptr;
3746 	/* Reset the message type in preparation for shipping it back. */
3747 	DB_TYPE(mp) = M_PCPROTO;
3748 
3749 	connp->conn_ulp = (uint8_t)protocol;
3750 
3751 	/*
3752 	 * Check for a zero length address.  This is from a protocol that
3753 	 * wants to register to receive all packets of its type.
3754 	 */
3755 	if (tbr->ADDR_length == 0) {
3756 		/*
3757 		 * These protocols are now intercepted in ip_bind_v6().
3758 		 * Reject protocol-level binds here for now.
3759 		 *
3760 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3761 		 * so that the protocol type cannot be SCTP.
3762 		 */
3763 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3764 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3765 			goto bad_addr;
3766 		}
3767 
3768 		/* No hash here really.  The table is big enough. */
3769 		connp->conn_srcv6 = ipv6_all_zeros;
3770 
3771 		ipcl_proto_insert(connp, protocol);
3772 
3773 		tbr->PRIM_type = T_BIND_ACK;
3774 		return (mp);
3775 	}
3776 
3777 	/* Extract the address pointer from the message. */
3778 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3779 	    tbr->ADDR_length);
3780 	if (ucp == NULL) {
3781 		ip1dbg(("ip_bind: no address\n"));
3782 		goto bad_addr;
3783 	}
3784 	if (!OK_32PTR(ucp)) {
3785 		ip1dbg(("ip_bind: unaligned address\n"));
3786 		goto bad_addr;
3787 	}
3788 	/*
3789 	 * Check for trailing mps.
3790 	 */
3791 
3792 	mp1 = mp->b_cont;
3793 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
3794 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
3795 
3796 	switch (tbr->ADDR_length) {
3797 	default:
3798 		ip1dbg(("ip_bind: bad address length %d\n",
3799 		    (int)tbr->ADDR_length));
3800 		goto bad_addr;
3801 
3802 	case IP_ADDR_LEN:
3803 		/* Verification of local address only */
3804 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3805 		    ire_requested, ipsec_policy_set, B_FALSE);
3806 		break;
3807 
3808 	case sizeof (sin_t):
3809 		sin = (sin_t *)ucp;
3810 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3811 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3812 		if (protocol == IPPROTO_TCP)
3813 			connp->conn_recv = tcp_conn_request;
3814 		break;
3815 
3816 	case sizeof (ipa_conn_t):
3817 		ac = (ipa_conn_t *)ucp;
3818 		/* For raw socket, the local port is not set. */
3819 		if (ac->ac_lport == 0)
3820 			ac->ac_lport = connp->conn_lport;
3821 		/* Always verify destination reachability. */
3822 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3823 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3824 		    ipsec_policy_set, B_TRUE, B_TRUE);
3825 		if (protocol == IPPROTO_TCP)
3826 			connp->conn_recv = tcp_input;
3827 		break;
3828 
3829 	case sizeof (ipa_conn_x_t):
3830 		acx = (ipa_conn_x_t *)ucp;
3831 		/*
3832 		 * Whether or not to verify destination reachability depends
3833 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3834 		 */
3835 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3836 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3837 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3838 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3839 		if (protocol == IPPROTO_TCP)
3840 			connp->conn_recv = tcp_input;
3841 		break;
3842 	}
3843 	if (error == EINPROGRESS)
3844 		return (NULL);
3845 	else if (error != 0)
3846 		goto bad_addr;
3847 	/*
3848 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3849 	 * We can't do this in ip_bind_insert_ire because the policy
3850 	 * may not have been inherited at that point in time and hence
3851 	 * conn_out_enforce_policy may not be set.
3852 	 */
3853 	mp1 = mp->b_cont;
3854 	if (ire_requested && connp->conn_out_enforce_policy &&
3855 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3856 		ire_t *ire = (ire_t *)mp1->b_rptr;
3857 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3858 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3859 	}
3860 
3861 	/* Send it home. */
3862 	mp->b_datap->db_type = M_PCPROTO;
3863 	tbr->PRIM_type = T_BIND_ACK;
3864 	return (mp);
3865 
3866 bad_addr:
3867 	/*
3868 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3869 	 * a unix errno.
3870 	 */
3871 	if (error > 0)
3872 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3873 	else
3874 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3875 	return (mp);
3876 }
3877 
3878 /*
3879  * Here address is verified to be a valid local address.
3880  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3881  * address is also considered a valid local address.
3882  * In the case of a broadcast/multicast address, however, the
3883  * upper protocol is expected to reset the src address
3884  * to 0 if it sees a IRE_BROADCAST type returned so that
3885  * no packets are emitted with broadcast/multicast address as
3886  * source address (that violates hosts requirements RFC1122)
3887  * The addresses valid for bind are:
3888  *	(1) - INADDR_ANY (0)
3889  *	(2) - IP address of an UP interface
3890  *	(3) - IP address of a DOWN interface
3891  *	(4) - valid local IP broadcast addresses. In this case
3892  *	the conn will only receive packets destined to
3893  *	the specified broadcast address.
3894  *	(5) - a multicast address. In this case
3895  *	the conn will only receive packets destined to
3896  *	the specified multicast address. Note: the
3897  *	application still has to issue an
3898  *	IP_ADD_MEMBERSHIP socket option.
3899  *
3900  * On error, return -1 for TBADADDR otherwise pass the
3901  * errno with TSYSERR reply.
3902  *
3903  * In all the above cases, the bound address must be valid in the current zone.
3904  * When the address is loopback, multicast or broadcast, there might be many
3905  * matching IREs so bind has to look up based on the zone.
3906  */
3907 int
3908 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3909     boolean_t ire_requested, boolean_t ipsec_policy_set,
3910     boolean_t fanout_insert)
3911 {
3912 	int		error = 0;
3913 	ire_t		*src_ire;
3914 	mblk_t		*policy_mp;
3915 	ipif_t		*ipif;
3916 	zoneid_t	zoneid;
3917 
3918 	if (ipsec_policy_set) {
3919 		policy_mp = mp->b_cont;
3920 	}
3921 
3922 	/*
3923 	 * If it was previously connected, conn_fully_bound would have
3924 	 * been set.
3925 	 */
3926 	connp->conn_fully_bound = B_FALSE;
3927 
3928 	src_ire = NULL;
3929 	ipif = NULL;
3930 
3931 	zoneid = connp->conn_zoneid;
3932 
3933 	if (src_addr) {
3934 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3935 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3936 		/*
3937 		 * If an address other than 0.0.0.0 is requested,
3938 		 * we verify that it is a valid address for bind
3939 		 * Note: Following code is in if-else-if form for
3940 		 * readability compared to a condition check.
3941 		 */
3942 		/* LINTED - statement has no consequent */
3943 		if (IRE_IS_LOCAL(src_ire)) {
3944 			/*
3945 			 * (2) Bind to address of local UP interface
3946 			 */
3947 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3948 			/*
3949 			 * (4) Bind to broadcast address
3950 			 * Note: permitted only from transports that
3951 			 * request IRE
3952 			 */
3953 			if (!ire_requested)
3954 				error = EADDRNOTAVAIL;
3955 		} else {
3956 			/*
3957 			 * (3) Bind to address of local DOWN interface
3958 			 * (ipif_lookup_addr() looks up all interfaces
3959 			 * but we do not get here for UP interfaces
3960 			 * - case (2) above)
3961 			 * We put the protocol byte back into the mblk
3962 			 * since we may come back via ip_wput_nondata()
3963 			 * later with this mblk if ipif_lookup_addr chooses
3964 			 * to defer processing.
3965 			 */
3966 			*mp->b_wptr++ = (char)connp->conn_ulp;
3967 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3968 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3969 			    &error)) != NULL) {
3970 				ipif_refrele(ipif);
3971 			} else if (error == EINPROGRESS) {
3972 				if (src_ire != NULL)
3973 					ire_refrele(src_ire);
3974 				return (EINPROGRESS);
3975 			} else if (CLASSD(src_addr)) {
3976 				error = 0;
3977 				if (src_ire != NULL)
3978 					ire_refrele(src_ire);
3979 				/*
3980 				 * (5) bind to multicast address.
3981 				 * Fake out the IRE returned to upper
3982 				 * layer to be a broadcast IRE.
3983 				 */
3984 				src_ire = ire_ctable_lookup(
3985 				    INADDR_BROADCAST, INADDR_ANY,
3986 				    IRE_BROADCAST, NULL, zoneid,
3987 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3988 				if (src_ire == NULL || !ire_requested)
3989 					error = EADDRNOTAVAIL;
3990 			} else {
3991 				/*
3992 				 * Not a valid address for bind
3993 				 */
3994 				error = EADDRNOTAVAIL;
3995 			}
3996 			/*
3997 			 * Just to keep it consistent with the processing in
3998 			 * ip_bind_v4()
3999 			 */
4000 			mp->b_wptr--;
4001 		}
4002 		if (error) {
4003 			/* Red Alert!  Attempting to be a bogon! */
4004 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4005 			    ntohl(src_addr)));
4006 			goto bad_addr;
4007 		}
4008 	}
4009 
4010 	/*
4011 	 * Allow setting new policies. For example, disconnects come
4012 	 * down as ipa_t bind. As we would have set conn_policy_cached
4013 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4014 	 * can change after the disconnect.
4015 	 */
4016 	connp->conn_policy_cached = B_FALSE;
4017 
4018 	/*
4019 	 * If not fanout_insert this was just an address verification
4020 	 */
4021 	if (fanout_insert) {
4022 		/*
4023 		 * The addresses have been verified. Time to insert in
4024 		 * the correct fanout list.
4025 		 */
4026 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4027 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4028 		connp->conn_lport = lport;
4029 		connp->conn_fport = 0;
4030 		/*
4031 		 * Do we need to add a check to reject Multicast packets
4032 		 */
4033 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4034 	}
4035 done:
4036 	if (error == 0) {
4037 		if (ire_requested) {
4038 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4039 				error = -1;
4040 				/* Falls through to bad_addr */
4041 			}
4042 		} else if (ipsec_policy_set) {
4043 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4044 				error = -1;
4045 				/* Falls through to bad_addr */
4046 			}
4047 		}
4048 	}
4049 bad_addr:
4050 	if (src_ire != NULL)
4051 		IRE_REFRELE(src_ire);
4052 	if (ipsec_policy_set) {
4053 		ASSERT(policy_mp == mp->b_cont);
4054 		ASSERT(policy_mp != NULL);
4055 		freeb(policy_mp);
4056 		/*
4057 		 * As of now assume that nothing else accompanies
4058 		 * IPSEC_POLICY_SET.
4059 		 */
4060 		mp->b_cont = NULL;
4061 	}
4062 	return (error);
4063 }
4064 
4065 /*
4066  * Verify that both the source and destination addresses
4067  * are valid.  If verify_dst is false, then the destination address may be
4068  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4069  * destination reachability, while tunnels do not.
4070  * Note that we allow connect to broadcast and multicast
4071  * addresses when ire_requested is set. Thus the ULP
4072  * has to check for IRE_BROADCAST and multicast.
4073  *
4074  * Returns zero if ok.
4075  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4076  * (for use with TSYSERR reply).
4077  */
4078 int
4079 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4080     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4081     boolean_t ire_requested, boolean_t ipsec_policy_set,
4082     boolean_t fanout_insert, boolean_t verify_dst)
4083 {
4084 	ire_t		*src_ire;
4085 	ire_t		*dst_ire;
4086 	int		error = 0;
4087 	int 		protocol;
4088 	mblk_t		*policy_mp;
4089 	ire_t		*sire = NULL;
4090 	ire_t		*md_dst_ire = NULL;
4091 	ill_t		*md_ill = NULL;
4092 	zoneid_t	zoneid;
4093 	ipaddr_t	src_addr = *src_addrp;
4094 
4095 	src_ire = dst_ire = NULL;
4096 	protocol = *mp->b_wptr & 0xFF;
4097 
4098 	/*
4099 	 * If we never got a disconnect before, clear it now.
4100 	 */
4101 	connp->conn_fully_bound = B_FALSE;
4102 
4103 	if (ipsec_policy_set) {
4104 		policy_mp = mp->b_cont;
4105 	}
4106 
4107 	zoneid = connp->conn_zoneid;
4108 
4109 	if (CLASSD(dst_addr)) {
4110 		/* Pick up an IRE_BROADCAST */
4111 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4112 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4113 		    MATCH_IRE_RJ_BHOLE));
4114 	} else {
4115 		/*
4116 		 * If conn_dontroute is set, and onlink ipif is not found
4117 		 * set ENETUNREACH error
4118 		 */
4119 		if (connp->conn_dontroute) {
4120 			ipif_t *ipif;
4121 
4122 			ipif = ipif_lookup_onlink_addr(dst_addr, zoneid);
4123 			if (ipif == NULL) {
4124 				error = ENETUNREACH;
4125 				goto bad_addr;
4126 			}
4127 			ipif_refrele(ipif);
4128 		}
4129 		dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL, &sire,
4130 		    zoneid,
4131 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4132 		    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4133 	}
4134 	/*
4135 	 * dst_ire can't be a broadcast when not ire_requested.
4136 	 * We also prevent ire's with src address INADDR_ANY to
4137 	 * be used, which are created temporarily for
4138 	 * sending out packets from endpoints that have
4139 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4140 	 * reachable.  If verify_dst is false, the destination needn't be
4141 	 * reachable.
4142 	 *
4143 	 * If we match on a reject or black hole, then we've got a
4144 	 * local failure.  May as well fail out the connect() attempt,
4145 	 * since it's never going to succeed.
4146 	 */
4147 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4148 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4149 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4150 		/*
4151 		 * If we're verifying destination reachability, we always want
4152 		 * to complain here.
4153 		 *
4154 		 * If we're not verifying destination reachability but the
4155 		 * destination has a route, we still want to fail on the
4156 		 * temporary address and broadcast address tests.
4157 		 */
4158 		if (verify_dst || (dst_ire != NULL)) {
4159 			if (ip_debug > 2) {
4160 				pr_addr_dbg("ip_bind_connected: bad connected "
4161 				    "dst %s\n", AF_INET, &dst_addr);
4162 			}
4163 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4164 				error = ENETUNREACH;
4165 			else
4166 				error = EHOSTUNREACH;
4167 			goto bad_addr;
4168 		}
4169 	}
4170 	/*
4171 	 * If the app does a connect(), it means that it will most likely
4172 	 * send more than 1 packet to the destination.  It makes sense
4173 	 * to clear the temporary flag.
4174 	 */
4175 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4176 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4177 		irb_t *irb = dst_ire->ire_bucket;
4178 
4179 		rw_enter(&irb->irb_lock, RW_WRITER);
4180 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4181 		irb->irb_tmp_ire_cnt--;
4182 		rw_exit(&irb->irb_lock);
4183 	}
4184 
4185 	/*
4186 	 * See if we should notify ULP about MDT; we do this whether or not
4187 	 * ire_requested is TRUE, in order to handle active connects; MDT
4188 	 * eligibility tests for passive connects are handled separately
4189 	 * through tcp_adapt_ire().  We do this before the source address
4190 	 * selection, because dst_ire may change after a call to
4191 	 * ipif_select_source().  This is a best-effort check, as the
4192 	 * packet for this connection may not actually go through
4193 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4194 	 * calling ip_newroute().  This is why we further check on the
4195 	 * IRE during Multidata packet transmission in tcp_multisend().
4196 	 */
4197 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4198 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4199 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4200 	    ILL_MDT_CAPABLE(md_ill)) {
4201 		md_dst_ire = dst_ire;
4202 		IRE_REFHOLD(md_dst_ire);
4203 	}
4204 
4205 	if (dst_ire != NULL &&
4206 	    dst_ire->ire_type == IRE_LOCAL &&
4207 	    dst_ire->ire_zoneid != zoneid) {
4208 		/*
4209 		 * If the IRE belongs to a different zone, look for a matching
4210 		 * route in the forwarding table and use the source address from
4211 		 * that route.
4212 		 */
4213 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4214 		    zoneid, 0,
4215 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4216 		    MATCH_IRE_RJ_BHOLE);
4217 		if (src_ire == NULL) {
4218 			error = EHOSTUNREACH;
4219 			goto bad_addr;
4220 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4221 			if (!(src_ire->ire_type & IRE_HOST))
4222 				error = ENETUNREACH;
4223 			else
4224 				error = EHOSTUNREACH;
4225 			goto bad_addr;
4226 		}
4227 		if (src_addr == INADDR_ANY)
4228 			src_addr = src_ire->ire_src_addr;
4229 		ire_refrele(src_ire);
4230 		src_ire = NULL;
4231 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4232 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4233 			src_addr = sire->ire_src_addr;
4234 			ire_refrele(dst_ire);
4235 			dst_ire = sire;
4236 			sire = NULL;
4237 		} else {
4238 			/*
4239 			 * Pick a source address so that a proper inbound
4240 			 * load spreading would happen.
4241 			 */
4242 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4243 			ipif_t *src_ipif = NULL;
4244 			ire_t *ipif_ire;
4245 
4246 			/*
4247 			 * Supply a local source address such that inbound
4248 			 * load spreading happens.
4249 			 *
4250 			 * Determine the best source address on this ill for
4251 			 * the destination.
4252 			 *
4253 			 * 1) For broadcast, we should return a broadcast ire
4254 			 *    found above so that upper layers know that the
4255 			 *    destination address is a broadcast address.
4256 			 *
4257 			 * 2) If this is part of a group, select a better
4258 			 *    source address so that better inbound load
4259 			 *    balancing happens. Do the same if the ipif
4260 			 *    is DEPRECATED.
4261 			 *
4262 			 * 3) If the outgoing interface is part of a usesrc
4263 			 *    group, then try selecting a source address from
4264 			 *    the usesrc ILL.
4265 			 */
4266 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4267 			    ((dst_ill->ill_group != NULL) ||
4268 			    (dst_ire->ire_ipif->ipif_flags &
4269 			    IPIF_DEPRECATED) ||
4270 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4271 				src_ipif = ipif_select_source(dst_ill,
4272 				    dst_addr, zoneid);
4273 				if (src_ipif != NULL) {
4274 					if (IS_VNI(src_ipif->ipif_ill)) {
4275 						/*
4276 						 * For VNI there is no
4277 						 * interface route
4278 						 */
4279 						src_addr =
4280 						    src_ipif->ipif_src_addr;
4281 					} else {
4282 						ipif_ire =
4283 						    ipif_to_ire(src_ipif);
4284 						if (ipif_ire != NULL) {
4285 							IRE_REFRELE(dst_ire);
4286 							dst_ire = ipif_ire;
4287 						}
4288 						src_addr =
4289 						    dst_ire->ire_src_addr;
4290 					}
4291 					ipif_refrele(src_ipif);
4292 				} else {
4293 					src_addr = dst_ire->ire_src_addr;
4294 				}
4295 			} else {
4296 				src_addr = dst_ire->ire_src_addr;
4297 			}
4298 		}
4299 	}
4300 
4301 	/*
4302 	 * We do ire_route_lookup() here (and not
4303 	 * interface lookup as we assert that
4304 	 * src_addr should only come from an
4305 	 * UP interface for hard binding.
4306 	 */
4307 	ASSERT(src_ire == NULL);
4308 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4309 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4310 	/* src_ire must be a local|loopback */
4311 	if (!IRE_IS_LOCAL(src_ire)) {
4312 		if (ip_debug > 2) {
4313 			pr_addr_dbg("ip_bind_connected: bad connected "
4314 			    "src %s\n", AF_INET, &src_addr);
4315 		}
4316 		error = EADDRNOTAVAIL;
4317 		goto bad_addr;
4318 	}
4319 
4320 	/*
4321 	 * If the source address is a loopback address, the
4322 	 * destination had best be local or multicast.
4323 	 * The transports that can't handle multicast will reject
4324 	 * those addresses.
4325 	 */
4326 	if (src_ire->ire_type == IRE_LOOPBACK &&
4327 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4328 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4329 		error = -1;
4330 		goto bad_addr;
4331 	}
4332 
4333 	/*
4334 	 * Allow setting new policies. For example, disconnects come
4335 	 * down as ipa_t bind. As we would have set conn_policy_cached
4336 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4337 	 * can change after the disconnect.
4338 	 */
4339 	connp->conn_policy_cached = B_FALSE;
4340 
4341 	/*
4342 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4343 	 * can handle their passed-in conn's.
4344 	 */
4345 
4346 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4347 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4348 	connp->conn_lport = lport;
4349 	connp->conn_fport = fport;
4350 	*src_addrp = src_addr;
4351 
4352 	ASSERT(!(ipsec_policy_set && ire_requested));
4353 	if (ire_requested) {
4354 		iulp_t *ulp_info = NULL;
4355 
4356 		/*
4357 		 * Note that sire will not be NULL if this is an off-link
4358 		 * connection and there is not cache for that dest yet.
4359 		 *
4360 		 * XXX Because of an existing bug, if there are multiple
4361 		 * default routes, the IRE returned now may not be the actual
4362 		 * default route used (default routes are chosen in a
4363 		 * round robin fashion).  So if the metrics for different
4364 		 * default routes are different, we may return the wrong
4365 		 * metrics.  This will not be a problem if the existing
4366 		 * bug is fixed.
4367 		 */
4368 		if (sire != NULL) {
4369 			ulp_info = &(sire->ire_uinfo);
4370 		}
4371 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4372 			error = -1;
4373 			goto bad_addr;
4374 		}
4375 	} else if (ipsec_policy_set) {
4376 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4377 			error = -1;
4378 			goto bad_addr;
4379 		}
4380 	}
4381 
4382 	/*
4383 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4384 	 * we'll cache that.  If we don't, we'll inherit global policy.
4385 	 *
4386 	 * We can't insert until the conn reflects the policy. Note that
4387 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4388 	 * connections where we don't have a policy. This is to prevent
4389 	 * global policy lookups in the inbound path.
4390 	 *
4391 	 * If we insert before we set conn_policy_cached,
4392 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4393 	 * because global policy cound be non-empty. We normally call
4394 	 * ipsec_check_policy() for conn_policy_cached connections only if
4395 	 * ipc_in_enforce_policy is set. But in this case,
4396 	 * conn_policy_cached can get set anytime since we made the
4397 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4398 	 * called, which will make the above assumption false.  Thus, we
4399 	 * need to insert after we set conn_policy_cached.
4400 	 */
4401 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4402 		goto bad_addr;
4403 
4404 	if (fanout_insert) {
4405 		/*
4406 		 * The addresses have been verified. Time to insert in
4407 		 * the correct fanout list.
4408 		 */
4409 		error = ipcl_conn_insert(connp, protocol, src_addr,
4410 		    dst_addr, connp->conn_ports);
4411 	}
4412 
4413 	if (error == 0) {
4414 		connp->conn_fully_bound = B_TRUE;
4415 		/*
4416 		 * Our initial checks for MDT have passed; the IRE is not
4417 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4418 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4419 		 * ip_mdinfo_return(), which performs further checks
4420 		 * against them and upon success, returns the MDT info
4421 		 * mblk which we will attach to the bind acknowledgment.
4422 		 */
4423 		if (md_dst_ire != NULL) {
4424 			mblk_t *mdinfo_mp;
4425 
4426 			ASSERT(md_ill != NULL);
4427 			ASSERT(md_ill->ill_mdt_capab != NULL);
4428 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4429 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4430 				linkb(mp, mdinfo_mp);
4431 		}
4432 	}
4433 bad_addr:
4434 	if (ipsec_policy_set) {
4435 		ASSERT(policy_mp == mp->b_cont);
4436 		ASSERT(policy_mp != NULL);
4437 		freeb(policy_mp);
4438 		/*
4439 		 * As of now assume that nothing else accompanies
4440 		 * IPSEC_POLICY_SET.
4441 		 */
4442 		mp->b_cont = NULL;
4443 	}
4444 	if (src_ire != NULL)
4445 		IRE_REFRELE(src_ire);
4446 	if (dst_ire != NULL)
4447 		IRE_REFRELE(dst_ire);
4448 	if (sire != NULL)
4449 		IRE_REFRELE(sire);
4450 	if (md_dst_ire != NULL)
4451 		IRE_REFRELE(md_dst_ire);
4452 	return (error);
4453 }
4454 
4455 /*
4456  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4457  * Prefers dst_ire over src_ire.
4458  */
4459 static boolean_t
4460 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4461 {
4462 	mblk_t	*mp1;
4463 	ire_t *ret_ire = NULL;
4464 
4465 	mp1 = mp->b_cont;
4466 	ASSERT(mp1 != NULL);
4467 
4468 	if (ire != NULL) {
4469 		/*
4470 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4471 		 * appended mblk. Its <upper protocol>'s
4472 		 * job to make sure there is room.
4473 		 */
4474 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4475 			return (0);
4476 
4477 		mp1->b_datap->db_type = IRE_DB_TYPE;
4478 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4479 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4480 		ret_ire = (ire_t *)mp1->b_rptr;
4481 		/*
4482 		 * Pass the latest setting of the ip_path_mtu_discovery and
4483 		 * copy the ulp info if any.
4484 		 */
4485 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4486 		    IPH_DF : 0;
4487 		if (ulp_info != NULL) {
4488 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4489 			    sizeof (iulp_t));
4490 		}
4491 		ret_ire->ire_mp = mp1;
4492 	} else {
4493 		/*
4494 		 * No IRE was found. Remove IRE mblk.
4495 		 */
4496 		mp->b_cont = mp1->b_cont;
4497 		freeb(mp1);
4498 	}
4499 
4500 	return (1);
4501 }
4502 
4503 /*
4504  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4505  * the final piece where we don't.  Return a pointer to the first mblk in the
4506  * result, and update the pointer to the next mblk to chew on.  If anything
4507  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4508  * NULL pointer.
4509  */
4510 mblk_t *
4511 ip_carve_mp(mblk_t **mpp, ssize_t len)
4512 {
4513 	mblk_t	*mp0;
4514 	mblk_t	*mp1;
4515 	mblk_t	*mp2;
4516 
4517 	if (!len || !mpp || !(mp0 = *mpp))
4518 		return (NULL);
4519 	/* If we aren't going to consume the first mblk, we need a dup. */
4520 	if (mp0->b_wptr - mp0->b_rptr > len) {
4521 		mp1 = dupb(mp0);
4522 		if (mp1) {
4523 			/* Partition the data between the two mblks. */
4524 			mp1->b_wptr = mp1->b_rptr + len;
4525 			mp0->b_rptr = mp1->b_wptr;
4526 			/*
4527 			 * after adjustments if mblk not consumed is now
4528 			 * unaligned, try to align it. If this fails free
4529 			 * all messages and let upper layer recover.
4530 			 */
4531 			if (!OK_32PTR(mp0->b_rptr)) {
4532 				if (!pullupmsg(mp0, -1)) {
4533 					freemsg(mp0);
4534 					freemsg(mp1);
4535 					*mpp = NULL;
4536 					return (NULL);
4537 				}
4538 			}
4539 		}
4540 		return (mp1);
4541 	}
4542 	/* Eat through as many mblks as we need to get len bytes. */
4543 	len -= mp0->b_wptr - mp0->b_rptr;
4544 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4545 		if (mp2->b_wptr - mp2->b_rptr > len) {
4546 			/*
4547 			 * We won't consume the entire last mblk.  Like
4548 			 * above, dup and partition it.
4549 			 */
4550 			mp1->b_cont = dupb(mp2);
4551 			mp1 = mp1->b_cont;
4552 			if (!mp1) {
4553 				/*
4554 				 * Trouble.  Rather than go to a lot of
4555 				 * trouble to clean up, we free the messages.
4556 				 * This won't be any worse than losing it on
4557 				 * the wire.
4558 				 */
4559 				freemsg(mp0);
4560 				freemsg(mp2);
4561 				*mpp = NULL;
4562 				return (NULL);
4563 			}
4564 			mp1->b_wptr = mp1->b_rptr + len;
4565 			mp2->b_rptr = mp1->b_wptr;
4566 			/*
4567 			 * after adjustments if mblk not consumed is now
4568 			 * unaligned, try to align it. If this fails free
4569 			 * all messages and let upper layer recover.
4570 			 */
4571 			if (!OK_32PTR(mp2->b_rptr)) {
4572 				if (!pullupmsg(mp2, -1)) {
4573 					freemsg(mp0);
4574 					freemsg(mp2);
4575 					*mpp = NULL;
4576 					return (NULL);
4577 				}
4578 			}
4579 			*mpp = mp2;
4580 			return (mp0);
4581 		}
4582 		/* Decrement len by the amount we just got. */
4583 		len -= mp2->b_wptr - mp2->b_rptr;
4584 	}
4585 	/*
4586 	 * len should be reduced to zero now.  If not our caller has
4587 	 * screwed up.
4588 	 */
4589 	if (len) {
4590 		/* Shouldn't happen! */
4591 		freemsg(mp0);
4592 		*mpp = NULL;
4593 		return (NULL);
4594 	}
4595 	/*
4596 	 * We consumed up to exactly the end of an mblk.  Detach the part
4597 	 * we are returning from the rest of the chain.
4598 	 */
4599 	mp1->b_cont = NULL;
4600 	*mpp = mp2;
4601 	return (mp0);
4602 }
4603 
4604 /* The ill stream is being unplumbed. Called from ip_close */
4605 int
4606 ip_modclose(ill_t *ill)
4607 {
4608 
4609 	boolean_t success;
4610 	ipsq_t	*ipsq;
4611 	ipif_t	*ipif;
4612 	queue_t	*q = ill->ill_rq;
4613 
4614 	/*
4615 	 * Forcibly enter the ipsq after some delay. This is to take
4616 	 * care of the case when some ioctl does not complete because
4617 	 * we sent a control message to the driver and it did not
4618 	 * send us a reply. We want to be able to at least unplumb
4619 	 * and replumb rather than force the user to reboot the system.
4620 	 */
4621 	success = ipsq_enter(ill, B_FALSE);
4622 
4623 	/*
4624 	 * Open/close/push/pop is guaranteed to be single threaded
4625 	 * per stream by STREAMS. FS guarantees that all references
4626 	 * from top are gone before close is called. So there can't
4627 	 * be another close thread that has set CONDEMNED on this ill.
4628 	 * and cause ipsq_enter to return failure.
4629 	 */
4630 	ASSERT(success);
4631 	ipsq = ill->ill_phyint->phyint_ipsq;
4632 
4633 	/*
4634 	 * Mark it condemned. No new reference will be made to this ill.
4635 	 * Lookup functions will return an error. Threads that try to
4636 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4637 	 * that the refcnt will drop down to zero.
4638 	 */
4639 	mutex_enter(&ill->ill_lock);
4640 	ill->ill_state_flags |= ILL_CONDEMNED;
4641 	for (ipif = ill->ill_ipif; ipif != NULL;
4642 	    ipif = ipif->ipif_next) {
4643 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4644 	}
4645 	/*
4646 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4647 	 * returns  error if ILL_CONDEMNED is set
4648 	 */
4649 	cv_broadcast(&ill->ill_cv);
4650 	mutex_exit(&ill->ill_lock);
4651 
4652 	/*
4653 	 * Shut down fragmentation reassembly.
4654 	 * ill_frag_timer won't start a timer again.
4655 	 * Now cancel any existing timer
4656 	 */
4657 	(void) untimeout(ill->ill_frag_timer_id);
4658 	(void) ill_frag_timeout(ill, 0);
4659 
4660 	/*
4661 	 * If MOVE was in progress, clear the
4662 	 * move_in_progress fields also.
4663 	 */
4664 	if (ill->ill_move_in_progress) {
4665 		ILL_CLEAR_MOVE(ill);
4666 	}
4667 
4668 	/*
4669 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4670 	 * this ill. Then wait for the refcnts to drop to zero.
4671 	 * ill_is_quiescent checks whether the ill is really quiescent.
4672 	 * Then make sure that threads that are waiting to enter the
4673 	 * ipsq have seen the error returned by ipsq_enter and have
4674 	 * gone away. Then we call ill_delete_tail which does the
4675 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4676 	 */
4677 	ill_delete(ill);
4678 	mutex_enter(&ill->ill_lock);
4679 	while (!ill_is_quiescent(ill))
4680 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4681 	while (ill->ill_waiters)
4682 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4683 
4684 	mutex_exit(&ill->ill_lock);
4685 
4686 	/* qprocsoff is called in ill_delete_tail */
4687 	ill_delete_tail(ill);
4688 
4689 	/*
4690 	 * Walk through all upper (conn) streams and qenable
4691 	 * those that have queued data.
4692 	 * close synchronization needs this to
4693 	 * be done to ensure that all upper layers blocked
4694 	 * due to flow control to the closing device
4695 	 * get unblocked.
4696 	 */
4697 	ip1dbg(("ip_wsrv: walking\n"));
4698 	conn_walk_drain();
4699 
4700 	mutex_enter(&ip_mi_lock);
4701 	mi_close_unlink(&ip_g_head, (IDP)ill);
4702 	mutex_exit(&ip_mi_lock);
4703 
4704 	/*
4705 	 * credp could be null if the open didn't succeed and ip_modopen
4706 	 * itself calls ip_close.
4707 	 */
4708 	if (ill->ill_credp != NULL)
4709 		crfree(ill->ill_credp);
4710 
4711 	mi_close_free((IDP)ill);
4712 	q->q_ptr = WR(q)->q_ptr = NULL;
4713 
4714 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4715 
4716 	return (0);
4717 }
4718 
4719 /*
4720  * This is called as part of close() for both IP and UDP
4721  * in order to quiesce the conn.
4722  */
4723 void
4724 ip_quiesce_conn(conn_t *connp)
4725 {
4726 	boolean_t	drain_cleanup_reqd = B_FALSE;
4727 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4728 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4729 
4730 	ASSERT(!IPCL_IS_TCP(connp));
4731 
4732 	/*
4733 	 * Mark the conn as closing, and this conn must not be
4734 	 * inserted in future into any list. Eg. conn_drain_insert(),
4735 	 * won't insert this conn into the conn_drain_list.
4736 	 * Similarly ill_pending_mp_add() will not add any mp to
4737 	 * the pending mp list, after this conn has started closing.
4738 	 *
4739 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4740 	 * cannot get set henceforth.
4741 	 */
4742 	mutex_enter(&connp->conn_lock);
4743 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4744 	connp->conn_state_flags |= CONN_CLOSING;
4745 	if (connp->conn_idl != NULL)
4746 		drain_cleanup_reqd = B_TRUE;
4747 	if (connp->conn_oper_pending_ill != NULL)
4748 		conn_ioctl_cleanup_reqd = B_TRUE;
4749 	if (connp->conn_ilg_inuse != 0)
4750 		ilg_cleanup_reqd = B_TRUE;
4751 	mutex_exit(&connp->conn_lock);
4752 
4753 	if (IPCL_IS_UDP(connp))
4754 		udp_quiesce_conn(connp);
4755 
4756 	if (conn_ioctl_cleanup_reqd)
4757 		conn_ioctl_cleanup(connp);
4758 
4759 	/*
4760 	 * Remove this conn from any fanout list it is on.
4761 	 * and then wait for any threads currently operating
4762 	 * on this endpoint to finish
4763 	 */
4764 	ipcl_hash_remove(connp);
4765 
4766 	/*
4767 	 * Remove this conn from the drain list, and do
4768 	 * any other cleanup that may be required.
4769 	 * (Only non-tcp streams may have a non-null conn_idl.
4770 	 * TCP streams are never flow controlled, and
4771 	 * conn_idl will be null)
4772 	 */
4773 	if (drain_cleanup_reqd)
4774 		conn_drain_tail(connp, B_TRUE);
4775 
4776 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4777 		(void) ip_mrouter_done(NULL);
4778 
4779 	if (ilg_cleanup_reqd)
4780 		ilg_delete_all(connp);
4781 
4782 	conn_delete_ire(connp, NULL);
4783 
4784 	/*
4785 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4786 	 * callers from write side can't be there now because close
4787 	 * is in progress. The only other caller is ipcl_walk
4788 	 * which checks for the condemned flag.
4789 	 */
4790 	mutex_enter(&connp->conn_lock);
4791 	connp->conn_state_flags |= CONN_CONDEMNED;
4792 	while (connp->conn_ref != 1)
4793 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4794 	connp->conn_state_flags |= CONN_QUIESCED;
4795 	mutex_exit(&connp->conn_lock);
4796 }
4797 
4798 /* ARGSUSED */
4799 int
4800 ip_close(queue_t *q, int flags)
4801 {
4802 	conn_t		*connp;
4803 
4804 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4805 
4806 	/*
4807 	 * Call the appropriate delete routine depending on whether this is
4808 	 * a module or device.
4809 	 */
4810 	if (WR(q)->q_next != NULL) {
4811 		/* This is a module close */
4812 		return (ip_modclose((ill_t *)q->q_ptr));
4813 	}
4814 
4815 	connp = q->q_ptr;
4816 	ip_quiesce_conn(connp);
4817 
4818 	qprocsoff(q);
4819 
4820 	/*
4821 	 * Now we are truly single threaded on this stream, and can
4822 	 * delete the things hanging off the connp, and finally the connp.
4823 	 * We removed this connp from the fanout list, it cannot be
4824 	 * accessed thru the fanouts, and we already waited for the
4825 	 * conn_ref to drop to 0. We are already in close, so
4826 	 * there cannot be any other thread from the top. qprocsoff
4827 	 * has completed, and service has completed or won't run in
4828 	 * future.
4829 	 */
4830 	ASSERT(connp->conn_ref == 1);
4831 
4832 	/*
4833 	 * A conn which was previously marked as IPCL_UDP cannot
4834 	 * retain the flag because it would have been cleared by
4835 	 * udp_close().
4836 	 */
4837 	ASSERT(!IPCL_IS_UDP(connp));
4838 
4839 	if (connp->conn_latch != NULL) {
4840 		IPLATCH_REFRELE(connp->conn_latch);
4841 		connp->conn_latch = NULL;
4842 	}
4843 	if (connp->conn_policy != NULL) {
4844 		IPPH_REFRELE(connp->conn_policy);
4845 		connp->conn_policy = NULL;
4846 	}
4847 	if (connp->conn_ipsec_opt_mp != NULL) {
4848 		freemsg(connp->conn_ipsec_opt_mp);
4849 		connp->conn_ipsec_opt_mp = NULL;
4850 	}
4851 	if (connp->conn_cred != NULL) {
4852 		crfree(connp->conn_cred);
4853 		connp->conn_cred = NULL;
4854 	}
4855 
4856 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4857 
4858 	connp->conn_ref--;
4859 	ipcl_conn_destroy(connp);
4860 
4861 	q->q_ptr = WR(q)->q_ptr = NULL;
4862 	return (0);
4863 }
4864 
4865 int
4866 ip_snmpmod_close(queue_t *q)
4867 {
4868 	conn_t *connp = Q_TO_CONN(q);
4869 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4870 
4871 	qprocsoff(q);
4872 
4873 	if (connp->conn_flags & IPCL_UDPMOD)
4874 		udp_close_free(connp);
4875 
4876 	if (connp->conn_cred != NULL) {
4877 		crfree(connp->conn_cred);
4878 		connp->conn_cred = NULL;
4879 	}
4880 	CONN_DEC_REF(connp);
4881 	q->q_ptr = WR(q)->q_ptr = NULL;
4882 	return (0);
4883 }
4884 
4885 /*
4886  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
4887  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
4888  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
4889  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
4890  * queues as we never enqueue messages there and we don't handle any ioctls.
4891  * Everything else is freed.
4892  */
4893 void
4894 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
4895 {
4896 	conn_t	*connp = q->q_ptr;
4897 	pfi_t	setfn;
4898 	pfi_t	getfn;
4899 
4900 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4901 
4902 	switch (DB_TYPE(mp)) {
4903 	case M_PROTO:
4904 	case M_PCPROTO:
4905 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
4906 		    ((((union T_primitives *)mp->b_rptr)->type ==
4907 			T_SVR4_OPTMGMT_REQ) ||
4908 		    (((union T_primitives *)mp->b_rptr)->type ==
4909 			T_OPTMGMT_REQ))) {
4910 			/*
4911 			 * This is the only TPI primitive supported. Its
4912 			 * handling does not require tcp_t, but it does require
4913 			 * conn_t to check permissions.
4914 			 */
4915 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
4916 
4917 			if (connp->conn_flags & IPCL_TCPMOD) {
4918 				setfn = tcp_snmp_set;
4919 				getfn = tcp_snmp_get;
4920 			} else {
4921 				setfn = udp_snmp_set;
4922 				getfn = udp_snmp_get;
4923 			}
4924 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
4925 				freemsg(mp);
4926 				return;
4927 			}
4928 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
4929 		    != NULL)
4930 			qreply(q, mp);
4931 		break;
4932 	case M_FLUSH:
4933 	case M_IOCTL:
4934 		putnext(q, mp);
4935 		break;
4936 	default:
4937 		freemsg(mp);
4938 		break;
4939 	}
4940 }
4941 
4942 /* Return the IP checksum for the IP header at "iph". */
4943 uint16_t
4944 ip_csum_hdr(ipha_t *ipha)
4945 {
4946 	uint16_t	*uph;
4947 	uint32_t	sum;
4948 	int		opt_len;
4949 
4950 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4951 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4952 	uph = (uint16_t *)ipha;
4953 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4954 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4955 	if (opt_len > 0) {
4956 		do {
4957 			sum += uph[10];
4958 			sum += uph[11];
4959 			uph += 2;
4960 		} while (--opt_len);
4961 	}
4962 	sum = (sum & 0xFFFF) + (sum >> 16);
4963 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4964 	if (sum == 0xffff)
4965 		sum = 0;
4966 	return ((uint16_t)sum);
4967 }
4968 
4969 void
4970 ip_ddi_destroy(void)
4971 {
4972 	tcp_ddi_destroy();
4973 	sctp_ddi_destroy();
4974 	ipsec_loader_destroy();
4975 	ipsec_policy_destroy();
4976 	ipsec_kstat_destroy();
4977 	nd_free(&ip_g_nd);
4978 	mutex_destroy(&igmp_timer_lock);
4979 	mutex_destroy(&mld_timer_lock);
4980 	mutex_destroy(&igmp_slowtimeout_lock);
4981 	mutex_destroy(&mld_slowtimeout_lock);
4982 	mutex_destroy(&ip_mi_lock);
4983 	mutex_destroy(&rts_clients.connf_lock);
4984 	ip_ire_fini();
4985 	ip6_asp_free();
4986 	conn_drain_fini();
4987 	ipcl_destroy();
4988 	inet_minor_destroy(ip_minor_arena);
4989 	icmp_kstat_fini();
4990 	ip_kstat_fini();
4991 	rw_destroy(&ipsec_capab_ills_lock);
4992 	rw_destroy(&ill_g_usesrc_lock);
4993 	ip_drop_unregister(&ip_dropper);
4994 }
4995 
4996 
4997 void
4998 ip_ddi_init(void)
4999 {
5000 	TCP6_MAJ = ddi_name_to_major(TCP6);
5001 	TCP_MAJ	= ddi_name_to_major(TCP);
5002 	SCTP_MAJ = ddi_name_to_major(SCTP);
5003 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5004 
5005 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5006 
5007 	/* IP's IPsec code calls the packet dropper */
5008 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5009 
5010 	if (!ip_g_nd) {
5011 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5012 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5013 			nd_free(&ip_g_nd);
5014 		}
5015 	}
5016 
5017 	ipsec_loader_init();
5018 	ipsec_policy_init();
5019 	ipsec_kstat_init();
5020 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5021 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5022 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5023 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5024 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5025 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5026 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5027 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5028 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5029 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5030 
5031 	/*
5032 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5033 	 * initial devices: ip, ip6, tcp, tcp6.
5034 	 */
5035 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5036 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5037 		cmn_err(CE_PANIC,
5038 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5039 	}
5040 
5041 	ipcl_init();
5042 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5043 	ip_ire_init();
5044 	ip6_asp_init();
5045 	ipif_init();
5046 	conn_drain_init();
5047 	tcp_ddi_init();
5048 	sctp_ddi_init();
5049 
5050 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5051 
5052 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5053 		"net", KSTAT_TYPE_NAMED,
5054 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5055 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5056 		ip_kstat->ks_data = &ip_statistics;
5057 		kstat_install(ip_kstat);
5058 	}
5059 	ip_kstat_init();
5060 	ip6_kstat_init();
5061 	icmp_kstat_init();
5062 
5063 	ipsec_loader_start();
5064 }
5065 
5066 /*
5067  * Allocate and initialize a DLPI template of the specified length.  (May be
5068  * called as writer.)
5069  */
5070 mblk_t *
5071 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5072 {
5073 	mblk_t	*mp;
5074 
5075 	mp = allocb(len, BPRI_MED);
5076 	if (!mp)
5077 		return (NULL);
5078 
5079 	/*
5080 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5081 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5082 	 * that other DLPI are M_PROTO.
5083 	 */
5084 	if (prim == DL_INFO_REQ) {
5085 		mp->b_datap->db_type = M_PCPROTO;
5086 	} else {
5087 		mp->b_datap->db_type = M_PROTO;
5088 	}
5089 
5090 	mp->b_wptr = mp->b_rptr + len;
5091 	bzero(mp->b_rptr, len);
5092 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5093 	return (mp);
5094 }
5095 
5096 const char *
5097 dlpi_prim_str(int prim)
5098 {
5099 	switch (prim) {
5100 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5101 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5102 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5103 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5104 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5105 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5106 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5107 	case DL_OK_ACK:		return ("DL_OK_ACK");
5108 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5109 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5110 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5111 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5112 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5113 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5114 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5115 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5116 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5117 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5118 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5119 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5120 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5121 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5122 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5123 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5124 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5125 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5126 	default:		return ("<unknown primitive>");
5127 	}
5128 }
5129 
5130 const char *
5131 dlpi_err_str(int err)
5132 {
5133 	switch (err) {
5134 	case DL_ACCESS:		return ("DL_ACCESS");
5135 	case DL_BADADDR:	return ("DL_BADADDR");
5136 	case DL_BADCORR:	return ("DL_BADCORR");
5137 	case DL_BADDATA:	return ("DL_BADDATA");
5138 	case DL_BADPPA:		return ("DL_BADPPA");
5139 	case DL_BADPRIM:	return ("DL_BADPRIM");
5140 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5141 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5142 	case DL_BADSAP:		return ("DL_BADSAP");
5143 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5144 	case DL_BOUND:		return ("DL_BOUND");
5145 	case DL_INITFAILED:	return ("DL_INITFAILED");
5146 	case DL_NOADDR:		return ("DL_NOADDR");
5147 	case DL_NOTINIT:	return ("DL_NOTINIT");
5148 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5149 	case DL_SYSERR:		return ("DL_SYSERR");
5150 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5151 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5152 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5153 	case DL_TOOMANY:	return ("DL_TOOMANY");
5154 	case DL_NOTENAB:	return ("DL_NOTENAB");
5155 	case DL_BUSY:		return ("DL_BUSY");
5156 	case DL_NOAUTO:		return ("DL_NOAUTO");
5157 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5158 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5159 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5160 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5161 	case DL_PENDING:	return ("DL_PENDING");
5162 	default:		return ("<unknown error>");
5163 	}
5164 }
5165 
5166 /*
5167  * Debug formatting routine.  Returns a character string representation of the
5168  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5169  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5170  */
5171 char *
5172 ip_dot_addr(ipaddr_t addr, char *buf)
5173 {
5174 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5175 }
5176 
5177 /*
5178  * Debug formatting routine.  Returns a character string representation of the
5179  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5180  * as a pointer.  The "xxx" parts including left zero padding so the final
5181  * string will fit easily in tables.  It would be nice to take a padding
5182  * length argument instead.
5183  */
5184 static char *
5185 ip_dot_saddr(uchar_t *addr, char *buf)
5186 {
5187 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5188 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5189 	return (buf);
5190 }
5191 
5192 /*
5193  * Send an ICMP error after patching up the packet appropriately.  Returns
5194  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5195  */
5196 static boolean_t
5197 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5198     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5199 {
5200 	ipha_t *ipha;
5201 	mblk_t *first_mp;
5202 	boolean_t secure;
5203 	unsigned char db_type;
5204 
5205 	first_mp = mp;
5206 	if (mctl_present) {
5207 		mp = mp->b_cont;
5208 		secure = ipsec_in_is_secure(first_mp);
5209 		ASSERT(mp != NULL);
5210 	} else {
5211 		/*
5212 		 * If this is an ICMP error being reported - which goes
5213 		 * up as M_CTLs, we need to convert them to M_DATA till
5214 		 * we finish checking with global policy because
5215 		 * ipsec_check_global_policy() assumes M_DATA as clear
5216 		 * and M_CTL as secure.
5217 		 */
5218 		db_type = DB_TYPE(mp);
5219 		DB_TYPE(mp) = M_DATA;
5220 		secure = B_FALSE;
5221 	}
5222 	/*
5223 	 * We are generating an icmp error for some inbound packet.
5224 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5225 	 * Before we generate an error, check with global policy
5226 	 * to see whether this is allowed to enter the system. As
5227 	 * there is no "conn", we are checking with global policy.
5228 	 */
5229 	ipha = (ipha_t *)mp->b_rptr;
5230 	if (secure || ipsec_inbound_v4_policy_present) {
5231 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5232 		    ipha, NULL, mctl_present);
5233 		if (first_mp == NULL)
5234 			return (B_FALSE);
5235 	}
5236 
5237 	if (!mctl_present)
5238 		DB_TYPE(mp) = db_type;
5239 
5240 	if (flags & IP_FF_SEND_ICMP) {
5241 		if (flags & IP_FF_HDR_COMPLETE) {
5242 			if (ip_hdr_complete(ipha, zoneid)) {
5243 				freemsg(first_mp);
5244 				return (B_TRUE);
5245 			}
5246 		}
5247 		if (flags & IP_FF_CKSUM) {
5248 			/*
5249 			 * Have to correct checksum since
5250 			 * the packet might have been
5251 			 * fragmented and the reassembly code in ip_rput
5252 			 * does not restore the IP checksum.
5253 			 */
5254 			ipha->ipha_hdr_checksum = 0;
5255 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5256 		}
5257 		switch (icmp_type) {
5258 		case ICMP_DEST_UNREACHABLE:
5259 			icmp_unreachable(WR(q), first_mp, icmp_code);
5260 			break;
5261 		default:
5262 			freemsg(first_mp);
5263 			break;
5264 		}
5265 	} else {
5266 		freemsg(first_mp);
5267 		return (B_FALSE);
5268 	}
5269 
5270 	return (B_TRUE);
5271 }
5272 
5273 #ifdef DEBUG
5274 /*
5275  * Copy the header into the IPSEC_IN message.
5276  */
5277 static void
5278 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5279 {
5280 	mblk_t *data_mp = ipsec_mp->b_cont;
5281 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5282 	ipha_t *ipha;
5283 
5284 	if (ii->ipsec_in_type != IPSEC_IN)
5285 		return;
5286 	ASSERT(data_mp != NULL);
5287 
5288 	ipha = (ipha_t *)data_mp->b_rptr;
5289 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5290 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5291 	    sizeof (ipha_t) : sizeof (ip6_t));
5292 }
5293 #else
5294 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5295 #endif	/* DEBUG */
5296 
5297 /*
5298  * Used to send an ICMP error message when a packet is received for
5299  * a protocol that is not supported. The mblk passed as argument
5300  * is consumed by this function.
5301  */
5302 void
5303 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5304 {
5305 	mblk_t *mp;
5306 	ipha_t *ipha;
5307 	ill_t *ill;
5308 	ipsec_in_t *ii;
5309 
5310 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5311 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5312 
5313 	mp = ipsec_mp->b_cont;
5314 	ipsec_mp->b_cont = NULL;
5315 	ipha = (ipha_t *)mp->b_rptr;
5316 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5317 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5318 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5319 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5320 		}
5321 	} else {
5322 		/* Get ill from index in ipsec_in_t. */
5323 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5324 		    B_TRUE, NULL, NULL, NULL, NULL);
5325 		if (ill != NULL) {
5326 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5327 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5328 			    0, B_FALSE, zoneid)) {
5329 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5330 			}
5331 
5332 			ill_refrele(ill);
5333 		} else { /* re-link for the freemsg() below. */
5334 			ipsec_mp->b_cont = mp;
5335 		}
5336 	}
5337 
5338 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5339 	freemsg(ipsec_mp);
5340 }
5341 
5342 /*
5343  * See if the inbound datagram has had IPsec processing applied to it.
5344  */
5345 boolean_t
5346 ipsec_in_is_secure(mblk_t *ipsec_mp)
5347 {
5348 	ipsec_in_t *ii;
5349 
5350 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5351 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5352 
5353 	if (ii->ipsec_in_loopback) {
5354 		return (ii->ipsec_in_secure);
5355 	} else {
5356 		return (ii->ipsec_in_ah_sa != NULL ||
5357 		    ii->ipsec_in_esp_sa != NULL ||
5358 		    ii->ipsec_in_decaps);
5359 	}
5360 }
5361 
5362 /*
5363  * Handle protocols with which IP is less intimate.  There
5364  * can be more than one stream bound to a particular
5365  * protocol.  When this is the case, normally each one gets a copy
5366  * of any incoming packets.
5367  *
5368  * IPSEC NOTE :
5369  *
5370  * Don't allow a secure packet going up a non-secure connection.
5371  * We don't allow this because
5372  *
5373  * 1) Reply might go out in clear which will be dropped at
5374  *    the sending side.
5375  * 2) If the reply goes out in clear it will give the
5376  *    adversary enough information for getting the key in
5377  *    most of the cases.
5378  *
5379  * Moreover getting a secure packet when we expect clear
5380  * implies that SA's were added without checking for
5381  * policy on both ends. This should not happen once ISAKMP
5382  * is used to negotiate SAs as SAs will be added only after
5383  * verifying the policy.
5384  *
5385  * NOTE : If the packet was tunneled and not multicast we only send
5386  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5387  * back to delivering packets to AF_INET6 raw sockets.
5388  *
5389  * IPQoS Notes:
5390  * Once we have determined the client, invoke IPPF processing.
5391  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5392  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5393  * ip_policy will be false.
5394  *
5395  * Zones notes:
5396  * Currently only applications in the global zone can create raw sockets for
5397  * protocols other than ICMP. So unlike the broadcast / multicast case of
5398  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5399  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5400  */
5401 static void
5402 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5403     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5404     zoneid_t zoneid)
5405 {
5406 	queue_t	*rq;
5407 	mblk_t	*mp1, *first_mp1;
5408 	uint_t	protocol = ipha->ipha_protocol;
5409 	ipaddr_t dst;
5410 	boolean_t one_only;
5411 	mblk_t *first_mp = mp;
5412 	boolean_t secure;
5413 	uint32_t ill_index;
5414 	conn_t	*connp, *first_connp, *next_connp;
5415 	connf_t	*connfp;
5416 
5417 	if (mctl_present) {
5418 		mp = first_mp->b_cont;
5419 		secure = ipsec_in_is_secure(first_mp);
5420 		ASSERT(mp != NULL);
5421 	} else {
5422 		secure = B_FALSE;
5423 	}
5424 	dst = ipha->ipha_dst;
5425 	/*
5426 	 * If the packet was tunneled and not multicast we only send to it
5427 	 * the first match.
5428 	 */
5429 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5430 	    !CLASSD(dst));
5431 
5432 	connfp = &ipcl_proto_fanout[protocol];
5433 	mutex_enter(&connfp->connf_lock);
5434 	connp = connfp->connf_head;
5435 	for (connp = connfp->connf_head; connp != NULL;
5436 		connp = connp->conn_next) {
5437 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5438 			break;
5439 	}
5440 
5441 	if (connp == NULL || connp->conn_upq == NULL) {
5442 		/*
5443 		 * No one bound to these addresses.  Is
5444 		 * there a client that wants all
5445 		 * unclaimed datagrams?
5446 		 */
5447 		mutex_exit(&connfp->connf_lock);
5448 		/*
5449 		 * Check for IPPROTO_ENCAP...
5450 		 */
5451 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5452 			/*
5453 			 * XXX If an IPsec mblk is here on a multicast
5454 			 * tunnel (using ip_mroute stuff), what should
5455 			 * I do?
5456 			 *
5457 			 * For now, just free the IPsec mblk before
5458 			 * passing it up to the multicast routing
5459 			 * stuff.
5460 			 *
5461 			 * BTW,  If I match a configured IP-in-IP
5462 			 * tunnel, ip_mroute_decap will never be
5463 			 * called.
5464 			 */
5465 			if (mp != first_mp)
5466 				freeb(first_mp);
5467 			ip_mroute_decap(q, mp);
5468 		} else {
5469 			/*
5470 			 * Otherwise send an ICMP protocol unreachable.
5471 			 */
5472 			if (ip_fanout_send_icmp(q, first_mp, flags,
5473 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5474 			    mctl_present, zoneid)) {
5475 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5476 			}
5477 		}
5478 		return;
5479 	}
5480 	CONN_INC_REF(connp);
5481 	first_connp = connp;
5482 
5483 	/*
5484 	 * Only send message to one tunnel driver by immediately
5485 	 * terminating the loop.
5486 	 */
5487 	connp = one_only ? NULL : connp->conn_next;
5488 
5489 	for (;;) {
5490 		while (connp != NULL) {
5491 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5492 			    flags, zoneid))
5493 				break;
5494 			connp = connp->conn_next;
5495 		}
5496 
5497 		/*
5498 		 * Copy the packet.
5499 		 */
5500 		if (connp == NULL || connp->conn_upq == NULL ||
5501 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5502 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5503 			/*
5504 			 * No more interested clients or memory
5505 			 * allocation failed
5506 			 */
5507 			connp = first_connp;
5508 			break;
5509 		}
5510 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5511 		CONN_INC_REF(connp);
5512 		mutex_exit(&connfp->connf_lock);
5513 		rq = connp->conn_rq;
5514 		if (!canputnext(rq)) {
5515 			if (flags & IP_FF_RAWIP) {
5516 				BUMP_MIB(&ip_mib, rawipInOverflows);
5517 			} else {
5518 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5519 			}
5520 
5521 			freemsg(first_mp1);
5522 		} else {
5523 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5524 				first_mp1 = ipsec_check_inbound_policy
5525 				    (first_mp1, connp, ipha, NULL,
5526 				    mctl_present);
5527 			}
5528 			if (first_mp1 != NULL) {
5529 				/*
5530 				 * ip_fanout_proto also gets called from
5531 				 * icmp_inbound_error_fanout, in which case
5532 				 * the msg type is M_CTL.  Don't add info
5533 				 * in this case for the time being. In future
5534 				 * when there is a need for knowing the
5535 				 * inbound iface index for ICMP error msgs,
5536 				 * then this can be changed.
5537 				 */
5538 				if ((connp->conn_recvif != 0) &&
5539 				    (mp->b_datap->db_type != M_CTL)) {
5540 					/*
5541 					 * the actual data will be
5542 					 * contained in b_cont upon
5543 					 * successful return of the
5544 					 * following call else
5545 					 * original mblk is returned
5546 					 */
5547 					ASSERT(recv_ill != NULL);
5548 					mp1 = ip_add_info(mp1, recv_ill,
5549 						IPF_RECVIF);
5550 				}
5551 				BUMP_MIB(&ip_mib, ipInDelivers);
5552 				if (mctl_present)
5553 					freeb(first_mp1);
5554 				putnext(rq, mp1);
5555 			}
5556 		}
5557 		mutex_enter(&connfp->connf_lock);
5558 		/* Follow the next pointer before releasing the conn. */
5559 		next_connp = connp->conn_next;
5560 		CONN_DEC_REF(connp);
5561 		connp = next_connp;
5562 	}
5563 
5564 	/* Last one.  Send it upstream. */
5565 	mutex_exit(&connfp->connf_lock);
5566 
5567 	/*
5568 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5569 	 * will be set to false.
5570 	 */
5571 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5572 		ill_index = ill->ill_phyint->phyint_ifindex;
5573 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5574 		if (mp == NULL) {
5575 			CONN_DEC_REF(connp);
5576 			if (mctl_present) {
5577 				freeb(first_mp);
5578 			}
5579 			return;
5580 		}
5581 	}
5582 
5583 	rq = connp->conn_rq;
5584 	if (!canputnext(rq)) {
5585 		if (flags & IP_FF_RAWIP) {
5586 			BUMP_MIB(&ip_mib, rawipInOverflows);
5587 		} else {
5588 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5589 		}
5590 
5591 		freemsg(first_mp);
5592 	} else {
5593 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5594 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5595 			    ipha, NULL, mctl_present);
5596 		}
5597 		if (first_mp != NULL) {
5598 			/*
5599 			 * ip_fanout_proto also gets called
5600 			 * from icmp_inbound_error_fanout, in
5601 			 * which case the msg type is M_CTL.
5602 			 * Don't add info in this case for time
5603 			 * being. In future when there is a
5604 			 * need for knowing the inbound iface
5605 			 * index for ICMP error msgs, then this
5606 			 * can be changed
5607 			 */
5608 			if ((connp->conn_recvif != 0) &&
5609 			    (mp->b_datap->db_type != M_CTL)) {
5610 				/*
5611 				 * the actual data will be contained in
5612 				 * b_cont upon successful return
5613 				 * of the following call else original
5614 				 * mblk is returned
5615 				 */
5616 				ASSERT(recv_ill != NULL);
5617 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5618 			}
5619 			BUMP_MIB(&ip_mib, ipInDelivers);
5620 			putnext(rq, mp);
5621 			if (mctl_present)
5622 				freeb(first_mp);
5623 		}
5624 	}
5625 	CONN_DEC_REF(connp);
5626 }
5627 
5628 /*
5629  * Fanout for TCP packets
5630  * The caller puts <fport, lport> in the ports parameter.
5631  *
5632  * IPQoS Notes
5633  * Before sending it to the client, invoke IPPF processing.
5634  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5635  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5636  * ip_policy is false.
5637  */
5638 static void
5639 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5640     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5641 {
5642 	mblk_t  *first_mp;
5643 	boolean_t secure;
5644 	uint32_t ill_index;
5645 	int	ip_hdr_len;
5646 	tcph_t	*tcph;
5647 	boolean_t syn_present = B_FALSE;
5648 	conn_t	*connp;
5649 
5650 	first_mp = mp;
5651 	if (mctl_present) {
5652 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5653 		mp = first_mp->b_cont;
5654 		secure = ipsec_in_is_secure(first_mp);
5655 		ASSERT(mp != NULL);
5656 	} else {
5657 		secure = B_FALSE;
5658 	}
5659 
5660 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5661 
5662 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5663 	    NULL) {
5664 		/*
5665 		 * No connected connection or listener. Send a
5666 		 * TH_RST via tcp_xmit_listeners_reset.
5667 		 */
5668 
5669 		/* Initiate IPPf processing, if needed. */
5670 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5671 			uint32_t ill_index;
5672 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5673 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5674 			if (first_mp == NULL)
5675 				return;
5676 		}
5677 		BUMP_MIB(&ip_mib, ipInDelivers);
5678 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5679 		return;
5680 	}
5681 
5682 	/*
5683 	 * Allocate the SYN for the TCP connection here itself
5684 	 */
5685 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5686 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5687 		if (IPCL_IS_TCP(connp)) {
5688 			squeue_t *sqp;
5689 
5690 			/*
5691 			 * For fused tcp loopback, assign the eager's
5692 			 * squeue to be that of the active connect's.
5693 			 * Note that we don't check for IP_FF_LOOPBACK
5694 			 * here since this routine gets called only
5695 			 * for loopback (unlike the IPv6 counterpart).
5696 			 */
5697 			if (do_tcp_fusion &&
5698 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5699 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy) {
5700 				ASSERT(Q_TO_CONN(q) != NULL);
5701 				sqp = Q_TO_CONN(q)->conn_sqp;
5702 			} else {
5703 				sqp = IP_SQUEUE_GET(lbolt);
5704 			}
5705 
5706 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5707 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
5708 			syn_present = B_TRUE;
5709 		}
5710 	}
5711 
5712 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5713 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5714 		if ((flags & TH_RST) || (flags & TH_URG)) {
5715 			CONN_DEC_REF(connp);
5716 			freemsg(first_mp);
5717 			return;
5718 		}
5719 		if (flags & TH_ACK) {
5720 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5721 			CONN_DEC_REF(connp);
5722 			return;
5723 		}
5724 
5725 		CONN_DEC_REF(connp);
5726 		freemsg(first_mp);
5727 		return;
5728 	}
5729 
5730 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5731 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5732 		    NULL, mctl_present);
5733 		if (first_mp == NULL) {
5734 			CONN_DEC_REF(connp);
5735 			return;
5736 		}
5737 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5738 			ASSERT(syn_present);
5739 			if (mctl_present) {
5740 				ASSERT(first_mp != mp);
5741 				first_mp->b_datap->db_struioflag |=
5742 				    STRUIO_POLICY;
5743 			} else {
5744 				ASSERT(first_mp == mp);
5745 				mp->b_datap->db_struioflag &=
5746 				    ~STRUIO_EAGER;
5747 				mp->b_datap->db_struioflag |=
5748 				    STRUIO_POLICY;
5749 			}
5750 		} else {
5751 			/*
5752 			 * Discard first_mp early since we're dealing with a
5753 			 * fully-connected conn_t and tcp doesn't do policy in
5754 			 * this case.
5755 			 */
5756 			if (mctl_present) {
5757 				freeb(first_mp);
5758 				mctl_present = B_FALSE;
5759 			}
5760 			first_mp = mp;
5761 		}
5762 	}
5763 
5764 	/*
5765 	 * Initiate policy processing here if needed. If we get here from
5766 	 * icmp_inbound_error_fanout, ip_policy is false.
5767 	 */
5768 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5769 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5770 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5771 		if (mp == NULL) {
5772 			CONN_DEC_REF(connp);
5773 			if (mctl_present)
5774 				freeb(first_mp);
5775 			return;
5776 		} else if (mctl_present) {
5777 			ASSERT(first_mp != mp);
5778 			first_mp->b_cont = mp;
5779 		} else {
5780 			first_mp = mp;
5781 		}
5782 	}
5783 
5784 
5785 
5786 	/* Handle IPv6 socket options. */
5787 	if (!syn_present &&
5788 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5789 		/* Add header */
5790 		ASSERT(recv_ill != NULL);
5791 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5792 		if (mp == NULL) {
5793 			CONN_DEC_REF(connp);
5794 			if (mctl_present)
5795 				freeb(first_mp);
5796 			return;
5797 		} else if (mctl_present) {
5798 			/*
5799 			 * ip_add_info might return a new mp.
5800 			 */
5801 			ASSERT(first_mp != mp);
5802 			first_mp->b_cont = mp;
5803 		} else {
5804 			first_mp = mp;
5805 		}
5806 	}
5807 
5808 	BUMP_MIB(&ip_mib, ipInDelivers);
5809 	if (IPCL_IS_TCP(connp)) {
5810 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5811 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5812 	} else {
5813 		putnext(connp->conn_rq, first_mp);
5814 		CONN_DEC_REF(connp);
5815 	}
5816 }
5817 
5818 /*
5819  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5820  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5821  * Caller is responsible for dropping references to the conn, and freeing
5822  * first_mp.
5823  *
5824  * IPQoS Notes
5825  * Before sending it to the client, invoke IPPF processing. Policy processing
5826  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5827  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5828  * ip_wput_local, ip_policy is false.
5829  */
5830 static void
5831 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5832     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5833     boolean_t ip_policy)
5834 {
5835 	boolean_t	mctl_present = (first_mp != NULL);
5836 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5837 	uint32_t	ill_index;
5838 
5839 	if (mctl_present)
5840 		first_mp->b_cont = mp;
5841 	else
5842 		first_mp = mp;
5843 
5844 	if (CONN_UDP_FLOWCTLD(connp)) {
5845 		BUMP_MIB(&ip_mib, udpInOverflows);
5846 		freemsg(first_mp);
5847 		return;
5848 	}
5849 
5850 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5851 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5852 		    NULL, mctl_present);
5853 		if (first_mp == NULL)
5854 			return;	/* Freed by ipsec_check_inbound_policy(). */
5855 	}
5856 	if (mctl_present)
5857 		freeb(first_mp);
5858 
5859 	if (connp->conn_recvif)
5860 		in_flags = IPF_RECVIF;
5861 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5862 		in_flags |= IPF_RECVSLLA;
5863 
5864 	/* Handle IPv6 options. */
5865 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5866 		in_flags |= IPF_RECVIF;
5867 
5868 	/*
5869 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5870 	 * freed if the packet is dropped. The caller will do so.
5871 	 */
5872 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5873 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5874 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5875 		if (mp == NULL) {
5876 			return;
5877 		}
5878 	}
5879 	if ((in_flags != 0) &&
5880 	    (mp->b_datap->db_type != M_CTL)) {
5881 		/*
5882 		 * The actual data will be contained in b_cont
5883 		 * upon successful return of the following call
5884 		 * else original mblk is returned
5885 		 */
5886 		ASSERT(recv_ill != NULL);
5887 		mp = ip_add_info(mp, recv_ill, in_flags);
5888 	}
5889 	BUMP_MIB(&ip_mib, ipInDelivers);
5890 
5891 	/* Send it upstream */
5892 	CONN_UDP_RECV(connp, mp);
5893 }
5894 
5895 /*
5896  * Fanout for UDP packets.
5897  * The caller puts <fport, lport> in the ports parameter.
5898  *
5899  * If SO_REUSEADDR is set all multicast and broadcast packets
5900  * will be delivered to all streams bound to the same port.
5901  *
5902  * Zones notes:
5903  * Multicast and broadcast packets will be distributed to streams in all zones.
5904  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5905  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5906  * packets. To maintain this behavior with multiple zones, the conns are grouped
5907  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5908  * each zone. If unset, all the following conns in the same zone are skipped.
5909  */
5910 static void
5911 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5912     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5913     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5914 {
5915 	uint32_t	dstport, srcport;
5916 	ipaddr_t	dst;
5917 	mblk_t		*first_mp;
5918 	boolean_t	secure;
5919 	in6_addr_t	v6src;
5920 	conn_t		*connp;
5921 	connf_t		*connfp;
5922 	conn_t		*first_connp;
5923 	conn_t		*next_connp;
5924 	mblk_t		*mp1, *first_mp1;
5925 	ipaddr_t	src;
5926 	zoneid_t	last_zoneid;
5927 	boolean_t	reuseaddr;
5928 
5929 	first_mp = mp;
5930 	if (mctl_present) {
5931 		mp = first_mp->b_cont;
5932 		first_mp->b_cont = NULL;
5933 		secure = ipsec_in_is_secure(first_mp);
5934 		ASSERT(mp != NULL);
5935 	} else {
5936 		first_mp = NULL;
5937 		secure = B_FALSE;
5938 	}
5939 
5940 	/* Extract ports in net byte order */
5941 	dstport = htons(ntohl(ports) & 0xFFFF);
5942 	srcport = htons(ntohl(ports) >> 16);
5943 	dst = ipha->ipha_dst;
5944 	src = ipha->ipha_src;
5945 
5946 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5947 	mutex_enter(&connfp->connf_lock);
5948 	connp = connfp->connf_head;
5949 	if (!broadcast && !CLASSD(dst)) {
5950 		/*
5951 		 * Not broadcast or multicast. Send to the one (first)
5952 		 * client we find. No need to check conn_wantpacket()
5953 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5954 		 * IPv4 unicast packets.
5955 		 */
5956 		while ((connp != NULL) &&
5957 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5958 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5959 			connp = connp->conn_next;
5960 		}
5961 
5962 		if (connp == NULL || connp->conn_upq == NULL)
5963 			goto notfound;
5964 		CONN_INC_REF(connp);
5965 		mutex_exit(&connfp->connf_lock);
5966 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5967 		    recv_ill, ip_policy);
5968 		IP_STAT(ip_udp_fannorm);
5969 		CONN_DEC_REF(connp);
5970 		return;
5971 	}
5972 
5973 	/*
5974 	 * Broadcast and multicast case
5975 	 *
5976 	 * Need to check conn_wantpacket().
5977 	 * If SO_REUSEADDR has been set on the first we send the
5978 	 * packet to all clients that have joined the group and
5979 	 * match the port.
5980 	 */
5981 
5982 	while (connp != NULL) {
5983 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
5984 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5985 			break;
5986 		connp = connp->conn_next;
5987 	}
5988 
5989 	if (connp == NULL || connp->conn_upq == NULL)
5990 		goto notfound;
5991 
5992 	first_connp = connp;
5993 	/*
5994 	 * When SO_REUSEADDR is not set, send the packet only to the first
5995 	 * matching connection in its zone by keeping track of the zoneid.
5996 	 */
5997 	reuseaddr = first_connp->conn_reuseaddr;
5998 	last_zoneid = first_connp->conn_zoneid;
5999 
6000 	CONN_INC_REF(connp);
6001 	connp = connp->conn_next;
6002 	for (;;) {
6003 		while (connp != NULL) {
6004 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6005 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6006 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6007 				break;
6008 			connp = connp->conn_next;
6009 		}
6010 		/*
6011 		 * Just copy the data part alone. The mctl part is
6012 		 * needed just for verifying policy and it is never
6013 		 * sent up.
6014 		 */
6015 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6016 		    ((mp1 = copymsg(mp)) == NULL))) {
6017 			/*
6018 			 * No more interested clients or memory
6019 			 * allocation failed
6020 			 */
6021 			connp = first_connp;
6022 			break;
6023 		}
6024 		if (connp->conn_zoneid != last_zoneid) {
6025 			/*
6026 			 * Update the zoneid so that the packet isn't sent to
6027 			 * any more conns in the same zone unless SO_REUSEADDR
6028 			 * is set.
6029 			 */
6030 			reuseaddr = connp->conn_reuseaddr;
6031 			last_zoneid = connp->conn_zoneid;
6032 		}
6033 		if (first_mp != NULL) {
6034 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6035 			    ipsec_info_type == IPSEC_IN);
6036 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6037 			if (first_mp1 == NULL) {
6038 				freemsg(mp1);
6039 				connp = first_connp;
6040 				break;
6041 			}
6042 		} else {
6043 			first_mp1 = NULL;
6044 		}
6045 		CONN_INC_REF(connp);
6046 		mutex_exit(&connfp->connf_lock);
6047 		/*
6048 		 * IPQoS notes: We don't send the packet for policy
6049 		 * processing here, will do it for the last one (below).
6050 		 * i.e. we do it per-packet now, but if we do policy
6051 		 * processing per-conn, then we would need to do it
6052 		 * here too.
6053 		 */
6054 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6055 		    ipha, flags, recv_ill, B_FALSE);
6056 		mutex_enter(&connfp->connf_lock);
6057 		/* Follow the next pointer before releasing the conn. */
6058 		next_connp = connp->conn_next;
6059 		IP_STAT(ip_udp_fanmb);
6060 		CONN_DEC_REF(connp);
6061 		connp = next_connp;
6062 	}
6063 
6064 	/* Last one.  Send it upstream. */
6065 	mutex_exit(&connfp->connf_lock);
6066 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6067 	    ip_policy);
6068 	IP_STAT(ip_udp_fanmb);
6069 	CONN_DEC_REF(connp);
6070 	return;
6071 
6072 notfound:
6073 
6074 	mutex_exit(&connfp->connf_lock);
6075 	IP_STAT(ip_udp_fanothers);
6076 	/*
6077 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6078 	 * have already been matched above, since they live in the IPv4
6079 	 * fanout tables. This implies we only need to
6080 	 * check for IPv6 in6addr_any endpoints here.
6081 	 * Thus we compare using ipv6_all_zeros instead of the destination
6082 	 * address, except for the multicast group membership lookup which
6083 	 * uses the IPv4 destination.
6084 	 */
6085 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6086 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6087 	mutex_enter(&connfp->connf_lock);
6088 	connp = connfp->connf_head;
6089 	if (!broadcast && !CLASSD(dst)) {
6090 		while (connp != NULL) {
6091 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6092 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6093 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6094 			    !connp->conn_ipv6_v6only)
6095 				break;
6096 			connp = connp->conn_next;
6097 		}
6098 
6099 		if (connp == NULL || connp->conn_upq == NULL) {
6100 			/*
6101 			 * No one bound to this port.  Is
6102 			 * there a client that wants all
6103 			 * unclaimed datagrams?
6104 			 */
6105 			mutex_exit(&connfp->connf_lock);
6106 
6107 			if (mctl_present)
6108 				first_mp->b_cont = mp;
6109 			else
6110 				first_mp = mp;
6111 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6112 				ip_fanout_proto(q, first_mp, ill, ipha,
6113 				    flags | IP_FF_RAWIP, mctl_present,
6114 				    ip_policy, recv_ill, zoneid);
6115 			} else {
6116 				if (ip_fanout_send_icmp(q, first_mp, flags,
6117 				    ICMP_DEST_UNREACHABLE,
6118 				    ICMP_PORT_UNREACHABLE,
6119 				    mctl_present, zoneid)) {
6120 					BUMP_MIB(&ip_mib, udpNoPorts);
6121 				}
6122 			}
6123 			return;
6124 		}
6125 		CONN_INC_REF(connp);
6126 		mutex_exit(&connfp->connf_lock);
6127 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6128 		    recv_ill, ip_policy);
6129 		CONN_DEC_REF(connp);
6130 		return;
6131 	}
6132 	/*
6133 	 * IPv4 multicast packet being delivered to an AF_INET6
6134 	 * in6addr_any endpoint.
6135 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6136 	 * and not conn_wantpacket_v6() since any multicast membership is
6137 	 * for an IPv4-mapped multicast address.
6138 	 * The packet is sent to all clients in all zones that have joined the
6139 	 * group and match the port.
6140 	 */
6141 	while (connp != NULL) {
6142 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6143 		    srcport, v6src) &&
6144 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6145 			break;
6146 		connp = connp->conn_next;
6147 	}
6148 
6149 	if (connp == NULL || connp->conn_upq == NULL) {
6150 		/*
6151 		 * No one bound to this port.  Is
6152 		 * there a client that wants all
6153 		 * unclaimed datagrams?
6154 		 */
6155 		mutex_exit(&connfp->connf_lock);
6156 
6157 		if (mctl_present)
6158 			first_mp->b_cont = mp;
6159 		else
6160 			first_mp = mp;
6161 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6162 			ip_fanout_proto(q, first_mp, ill, ipha,
6163 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6164 			    recv_ill, zoneid);
6165 		} else {
6166 			/*
6167 			 * We used to attempt to send an icmp error here, but
6168 			 * since this is known to be a multicast packet
6169 			 * and we don't send icmp errors in response to
6170 			 * multicast, just drop the packet and give up sooner.
6171 			 */
6172 			BUMP_MIB(&ip_mib, udpNoPorts);
6173 			freemsg(first_mp);
6174 		}
6175 		return;
6176 	}
6177 
6178 	first_connp = connp;
6179 
6180 	CONN_INC_REF(connp);
6181 	connp = connp->conn_next;
6182 	for (;;) {
6183 		while (connp != NULL) {
6184 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6185 			    ipv6_all_zeros, srcport, v6src) &&
6186 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6187 				break;
6188 			connp = connp->conn_next;
6189 		}
6190 		/*
6191 		 * Just copy the data part alone. The mctl part is
6192 		 * needed just for verifying policy and it is never
6193 		 * sent up.
6194 		 */
6195 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6196 		    ((mp1 = copymsg(mp)) == NULL))) {
6197 			/*
6198 			 * No more intested clients or memory
6199 			 * allocation failed
6200 			 */
6201 			connp = first_connp;
6202 			break;
6203 		}
6204 		if (first_mp != NULL) {
6205 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6206 			    ipsec_info_type == IPSEC_IN);
6207 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6208 			if (first_mp1 == NULL) {
6209 				freemsg(mp1);
6210 				connp = first_connp;
6211 				break;
6212 			}
6213 		} else {
6214 			first_mp1 = NULL;
6215 		}
6216 		CONN_INC_REF(connp);
6217 		mutex_exit(&connfp->connf_lock);
6218 		/*
6219 		 * IPQoS notes: We don't send the packet for policy
6220 		 * processing here, will do it for the last one (below).
6221 		 * i.e. we do it per-packet now, but if we do policy
6222 		 * processing per-conn, then we would need to do it
6223 		 * here too.
6224 		 */
6225 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6226 		    ipha, flags, recv_ill, B_FALSE);
6227 		mutex_enter(&connfp->connf_lock);
6228 		/* Follow the next pointer before releasing the conn. */
6229 		next_connp = connp->conn_next;
6230 		CONN_DEC_REF(connp);
6231 		connp = next_connp;
6232 	}
6233 
6234 	/* Last one.  Send it upstream. */
6235 	mutex_exit(&connfp->connf_lock);
6236 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6237 	    ip_policy);
6238 	CONN_DEC_REF(connp);
6239 }
6240 
6241 /*
6242  * Complete the ip_wput header so that it
6243  * is possible to generate ICMP
6244  * errors.
6245  */
6246 static int
6247 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6248 {
6249 	ire_t *ire;
6250 
6251 	if (ipha->ipha_src == INADDR_ANY) {
6252 		ire = ire_lookup_local(zoneid);
6253 		if (ire == NULL) {
6254 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6255 			return (1);
6256 		}
6257 		ipha->ipha_src = ire->ire_addr;
6258 		ire_refrele(ire);
6259 	}
6260 	ipha->ipha_ttl = ip_def_ttl;
6261 	ipha->ipha_hdr_checksum = 0;
6262 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6263 	return (0);
6264 }
6265 
6266 /*
6267  * Nobody should be sending
6268  * packets up this stream
6269  */
6270 static void
6271 ip_lrput(queue_t *q, mblk_t *mp)
6272 {
6273 	mblk_t *mp1;
6274 
6275 	switch (mp->b_datap->db_type) {
6276 	case M_FLUSH:
6277 		/* Turn around */
6278 		if (*mp->b_rptr & FLUSHW) {
6279 			*mp->b_rptr &= ~FLUSHR;
6280 			qreply(q, mp);
6281 			return;
6282 		}
6283 		break;
6284 	}
6285 	/* Could receive messages that passed through ar_rput */
6286 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6287 		mp1->b_prev = mp1->b_next = NULL;
6288 	freemsg(mp);
6289 }
6290 
6291 /* Nobody should be sending packets down this stream */
6292 /* ARGSUSED */
6293 void
6294 ip_lwput(queue_t *q, mblk_t *mp)
6295 {
6296 	freemsg(mp);
6297 }
6298 
6299 /*
6300  * Move the first hop in any source route to ipha_dst and remove that part of
6301  * the source route.  Called by other protocols.  Errors in option formatting
6302  * are ignored - will be handled by ip_wput_options Return the final
6303  * destination (either ipha_dst or the last entry in a source route.)
6304  */
6305 ipaddr_t
6306 ip_massage_options(ipha_t *ipha)
6307 {
6308 	ipoptp_t	opts;
6309 	uchar_t		*opt;
6310 	uint8_t		optval;
6311 	uint8_t		optlen;
6312 	ipaddr_t	dst;
6313 	int		i;
6314 	ire_t		*ire;
6315 
6316 	ip2dbg(("ip_massage_options\n"));
6317 	dst = ipha->ipha_dst;
6318 	for (optval = ipoptp_first(&opts, ipha);
6319 	    optval != IPOPT_EOL;
6320 	    optval = ipoptp_next(&opts)) {
6321 		opt = opts.ipoptp_cur;
6322 		switch (optval) {
6323 			uint8_t off;
6324 		case IPOPT_SSRR:
6325 		case IPOPT_LSRR:
6326 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6327 				ip1dbg(("ip_massage_options: bad src route\n"));
6328 				break;
6329 			}
6330 			optlen = opts.ipoptp_len;
6331 			off = opt[IPOPT_OFFSET];
6332 			off--;
6333 		redo_srr:
6334 			if (optlen < IP_ADDR_LEN ||
6335 			    off > optlen - IP_ADDR_LEN) {
6336 				/* End of source route */
6337 				ip1dbg(("ip_massage_options: end of SR\n"));
6338 				break;
6339 			}
6340 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6341 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6342 			    ntohl(dst)));
6343 			/*
6344 			 * Check if our address is present more than
6345 			 * once as consecutive hops in source route.
6346 			 * XXX verify per-interface ip_forwarding
6347 			 * for source route?
6348 			 */
6349 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6350 			    ALL_ZONES, MATCH_IRE_TYPE);
6351 			if (ire != NULL) {
6352 				ire_refrele(ire);
6353 				off += IP_ADDR_LEN;
6354 				goto redo_srr;
6355 			}
6356 			if (dst == htonl(INADDR_LOOPBACK)) {
6357 				ip1dbg(("ip_massage_options: loopback addr in "
6358 				    "source route!\n"));
6359 				break;
6360 			}
6361 			/*
6362 			 * Update ipha_dst to be the first hop and remove the
6363 			 * first hop from the source route (by overwriting
6364 			 * part of the option with NOP options).
6365 			 */
6366 			ipha->ipha_dst = dst;
6367 			/* Put the last entry in dst */
6368 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6369 			    3;
6370 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6371 
6372 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6373 			    ntohl(dst)));
6374 			/* Move down and overwrite */
6375 			opt[IP_ADDR_LEN] = opt[0];
6376 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6377 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6378 			for (i = 0; i < IP_ADDR_LEN; i++)
6379 				opt[i] = IPOPT_NOP;
6380 			break;
6381 		}
6382 	}
6383 	return (dst);
6384 }
6385 
6386 /*
6387  * This function's job is to forward data to the reverse tunnel (FA->HA)
6388  * after doing a few checks. It is assumed that the incoming interface
6389  * of the packet is always different than the outgoing interface and the
6390  * ire_type of the found ire has to be a non-resolver type.
6391  *
6392  * IPQoS notes
6393  * IP policy is invoked twice for a forwarded packet, once on the read side
6394  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6395  * enabled.
6396  */
6397 static void
6398 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6399 {
6400 	ipha_t		*ipha;
6401 	queue_t		*q;
6402 	uint32_t 	pkt_len;
6403 #define	rptr    ((uchar_t *)ipha)
6404 	uint32_t 	sum;
6405 	uint32_t 	max_frag;
6406 	mblk_t		*first_mp;
6407 	uint32_t	ill_index;
6408 
6409 	ASSERT(ire != NULL);
6410 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6411 	ASSERT(ire->ire_stq != NULL);
6412 
6413 	/* Initiate read side IPPF processing */
6414 	if (IPP_ENABLED(IPP_FWD_IN)) {
6415 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6416 		ip_process(IPP_FWD_IN, &mp, ill_index);
6417 		if (mp == NULL) {
6418 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6419 			    "dropped during IPPF processing\n"));
6420 			return;
6421 		}
6422 	}
6423 
6424 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6425 		ILLF_ROUTER) == 0) ||
6426 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6427 		BUMP_MIB(&ip_mib, ipForwProhibits);
6428 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6429 		    "forwarding is not turned on\n"));
6430 		goto drop_pkt;
6431 	}
6432 
6433 	/*
6434 	 * Don't forward if the interface is down
6435 	 */
6436 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6437 		BUMP_MIB(&ip_mib, ipInDiscards);
6438 		goto drop_pkt;
6439 	}
6440 
6441 	ipha = (ipha_t *)mp->b_rptr;
6442 	pkt_len = ntohs(ipha->ipha_length);
6443 	/* Adjust the checksum to reflect the ttl decrement. */
6444 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6445 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6446 	if (ipha->ipha_ttl-- <= 1) {
6447 		if (ip_csum_hdr(ipha)) {
6448 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6449 			goto drop_pkt;
6450 		}
6451 		q = ire->ire_stq;
6452 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6453 		    BPRI_HI)) == NULL) {
6454 			goto drop_pkt;
6455 		}
6456 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6457 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6458 
6459 		return;
6460 	}
6461 
6462 	/* Get the ill_index of the ILL */
6463 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6464 
6465 	/*
6466 	 * ip_mrtun_forward is only used by foreign agent to reverse
6467 	 * tunnel the incoming packet. So it does not do any option
6468 	 * processing for source routing.
6469 	 */
6470 	max_frag = ire->ire_max_frag;
6471 	if (pkt_len > max_frag) {
6472 		/*
6473 		 * It needs fragging on its way out.  We haven't
6474 		 * verified the header checksum yet.  Since we
6475 		 * are going to put a surely good checksum in the
6476 		 * outgoing header, we have to make sure that it
6477 		 * was good coming in.
6478 		 */
6479 		if (ip_csum_hdr(ipha)) {
6480 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6481 			goto drop_pkt;
6482 		}
6483 
6484 		/* Initiate write side IPPF processing */
6485 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6486 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6487 			if (mp == NULL) {
6488 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6489 				    "dropped/deferred during ip policy "\
6490 				    "processing\n"));
6491 				return;
6492 			}
6493 		}
6494 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6495 		    BPRI_HI)) == NULL) {
6496 			goto drop_pkt;
6497 		}
6498 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6499 		mp = first_mp;
6500 
6501 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6502 		return;
6503 	}
6504 
6505 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6506 
6507 	ASSERT(ire->ire_ipif != NULL);
6508 
6509 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6510 	if (mp == NULL) {
6511 		BUMP_MIB(&ip_mib, ipInDiscards);
6512 		return;
6513 	}
6514 
6515 	/* Now send the packet to the tunnel interface */
6516 	q = ire->ire_stq;
6517 	UPDATE_IB_PKT_COUNT(ire);
6518 	ire->ire_last_used_time = lbolt;
6519 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6520 	putnext(q, mp);
6521 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6522 	return;
6523 
6524 drop_pkt:;
6525 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6526 	freemsg(mp);
6527 #undef	rptr
6528 }
6529 
6530 /*
6531  * Fills the ipsec_out_t data structure with appropriate fields and
6532  * prepends it to mp which contains the IP hdr + data that was meant
6533  * to be forwarded. Please note that ipsec_out_info data structure
6534  * is used here to communicate the outgoing ill path at ip_wput()
6535  * for the ICMP error packet. This has nothing to do with ipsec IP
6536  * security. ipsec_out_t is really used to pass the info to the module
6537  * IP where this information cannot be extracted from conn.
6538  * This functions is called by ip_mrtun_forward().
6539  */
6540 void
6541 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6542 {
6543 	ipsec_out_t	*io;
6544 
6545 	ASSERT(xmit_ill != NULL);
6546 	first_mp->b_datap->db_type = M_CTL;
6547 	first_mp->b_wptr += sizeof (ipsec_info_t);
6548 	/*
6549 	 * This is to pass info to ip_wput in absence of conn.
6550 	 * ipsec_out_secure will be B_FALSE because of this.
6551 	 * Thus ipsec_out_secure being B_FALSE indicates that
6552 	 * this is not IPSEC security related information.
6553 	 */
6554 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6555 	io = (ipsec_out_t *)first_mp->b_rptr;
6556 	io->ipsec_out_type = IPSEC_OUT;
6557 	io->ipsec_out_len = sizeof (ipsec_out_t);
6558 	first_mp->b_cont = mp;
6559 	io->ipsec_out_ill_index =
6560 	    xmit_ill->ill_phyint->phyint_ifindex;
6561 	io->ipsec_out_xmit_if = B_TRUE;
6562 }
6563 
6564 /*
6565  * Return the network mask
6566  * associated with the specified address.
6567  */
6568 ipaddr_t
6569 ip_net_mask(ipaddr_t addr)
6570 {
6571 	uchar_t	*up = (uchar_t *)&addr;
6572 	ipaddr_t mask = 0;
6573 	uchar_t	*maskp = (uchar_t *)&mask;
6574 
6575 #if defined(__i386) || defined(__amd64)
6576 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6577 #endif
6578 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6579 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6580 #endif
6581 	if (CLASSD(addr)) {
6582 		maskp[0] = 0xF0;
6583 		return (mask);
6584 	}
6585 	if (addr == 0)
6586 		return (0);
6587 	maskp[0] = 0xFF;
6588 	if ((up[0] & 0x80) == 0)
6589 		return (mask);
6590 
6591 	maskp[1] = 0xFF;
6592 	if ((up[0] & 0xC0) == 0x80)
6593 		return (mask);
6594 
6595 	maskp[2] = 0xFF;
6596 	if ((up[0] & 0xE0) == 0xC0)
6597 		return (mask);
6598 
6599 	/* Must be experimental or multicast, indicate as much */
6600 	return ((ipaddr_t)0);
6601 }
6602 
6603 /*
6604  * Select an ill for the packet by considering load spreading across
6605  * a different ill in the group if dst_ill is part of some group.
6606  */
6607 static ill_t *
6608 ip_newroute_get_dst_ill(ill_t *dst_ill)
6609 {
6610 	ill_t *ill;
6611 
6612 	/*
6613 	 * We schedule irrespective of whether the source address is
6614 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6615 	 */
6616 	ill = illgrp_scheduler(dst_ill);
6617 	if (ill == NULL)
6618 		return (NULL);
6619 
6620 	/*
6621 	 * For groups with names ip_sioctl_groupname ensures that all
6622 	 * ills are of same type. For groups without names, ifgrp_insert
6623 	 * ensures this.
6624 	 */
6625 	ASSERT(dst_ill->ill_type == ill->ill_type);
6626 
6627 	return (ill);
6628 }
6629 
6630 /*
6631  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6632  */
6633 ill_t *
6634 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6635 {
6636 	ill_t *ret_ill;
6637 
6638 	ASSERT(ifindex != 0);
6639 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6640 	if (ret_ill == NULL ||
6641 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6642 		if (isv6) {
6643 			if (ill != NULL) {
6644 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6645 			} else {
6646 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6647 			}
6648 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6649 			    "bad ifindex %d.\n", ifindex));
6650 		} else {
6651 			BUMP_MIB(&ip_mib, ipOutDiscards);
6652 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6653 			    "bad ifindex %d.\n", ifindex));
6654 		}
6655 		if (ret_ill != NULL)
6656 			ill_refrele(ret_ill);
6657 		freemsg(first_mp);
6658 		return (NULL);
6659 	}
6660 
6661 	return (ret_ill);
6662 }
6663 
6664 /*
6665  * IPv4 -
6666  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6667  * out a packet to a destination address for which we do not have specific
6668  * (or sufficient) routing information.
6669  *
6670  * NOTE : These are the scopes of some of the variables that point at IRE,
6671  *	  which needs to be followed while making any future modifications
6672  *	  to avoid memory leaks.
6673  *
6674  *	- ire and sire are the entries looked up initially by
6675  *	  ire_ftable_lookup.
6676  *	- ipif_ire is used to hold the interface ire associated with
6677  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6678  *	  it before branching out to error paths.
6679  *	- save_ire is initialized before ire_create, so that ire returned
6680  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6681  *	  before breaking out of the switch.
6682  *
6683  *	Thus on failures, we have to REFRELE only ire and sire, if they
6684  *	are not NULL.
6685  */
6686 void
6687 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6688 {
6689 	areq_t	*areq;
6690 	ipaddr_t gw = 0;
6691 	ire_t	*ire = NULL;
6692 	mblk_t	*res_mp;
6693 	ipaddr_t *addrp;
6694 	ipif_t  *src_ipif = NULL;
6695 	ill_t	*dst_ill = NULL;
6696 	ipha_t  *ipha;
6697 	ire_t	*sire = NULL;
6698 	mblk_t	*first_mp;
6699 	ire_t	*save_ire;
6700 	mblk_t	*dlureq_mp;
6701 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6702 	ushort_t ire_marks = 0;
6703 	boolean_t mctl_present;
6704 	ipsec_out_t *io;
6705 	mblk_t	*saved_mp;
6706 	ire_t	*first_sire = NULL;
6707 	mblk_t	*copy_mp = NULL;
6708 	mblk_t	*xmit_mp = NULL;
6709 	ipaddr_t save_dst;
6710 	uint32_t multirt_flags =
6711 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6712 	boolean_t multirt_is_resolvable;
6713 	boolean_t multirt_resolve_next;
6714 	boolean_t do_attach_ill = B_FALSE;
6715 	zoneid_t zoneid;
6716 
6717 	if (ip_debug > 2) {
6718 		/* ip1dbg */
6719 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6720 	}
6721 
6722 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6723 	if (mctl_present) {
6724 		io = (ipsec_out_t *)first_mp->b_rptr;
6725 		zoneid = io->ipsec_out_zoneid;
6726 		ASSERT(zoneid != ALL_ZONES);
6727 	} else if (connp != NULL) {
6728 		zoneid = connp->conn_zoneid;
6729 	} else {
6730 		zoneid = GLOBAL_ZONEID;
6731 	}
6732 
6733 	ipha = (ipha_t *)mp->b_rptr;
6734 
6735 	/* All multicast lookups come through ip_newroute_ipif() */
6736 	if (CLASSD(dst)) {
6737 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6738 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6739 		freemsg(first_mp);
6740 		return;
6741 	}
6742 
6743 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6744 		goto icmp_err_ret;
6745 	}
6746 
6747 	if (mctl_present && io->ipsec_out_attach_if) {
6748 		/* ip_grab_attach_ill returns a held ill */
6749 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6750 		    io->ipsec_out_ill_index, B_FALSE);
6751 
6752 		/* Failure case frees things for us. */
6753 		if (attach_ill == NULL)
6754 			return;
6755 
6756 		/*
6757 		 * Check if we need an ire that will not be
6758 		 * looked up by anybody else i.e. HIDDEN.
6759 		 */
6760 		if (ill_is_probeonly(attach_ill))
6761 			ire_marks = IRE_MARK_HIDDEN;
6762 	}
6763 	/*
6764 	 * If this IRE is created for forwarding or it is not for
6765 	 * traffic for congestion controlled protocols, mark it as temporary.
6766 	 */
6767 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6768 		ire_marks |= IRE_MARK_TEMPORARY;
6769 
6770 	/*
6771 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6772 	 * chain until it gets the most specific information available.
6773 	 * For example, we know that there is no IRE_CACHE for this dest,
6774 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6775 	 * ire_ftable_lookup will look up the gateway, etc.
6776 	 * Check if in_ill != NULL. If it is true, the packet must be
6777 	 * from an incoming interface where RTA_SRCIFP is set.
6778 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6779 	 * to the destination, of equal netmask length in the forward table,
6780 	 * will be recursively explored. If no information is available
6781 	 * for the final gateway of that route, we force the returned ire
6782 	 * to be equal to sire using MATCH_IRE_PARENT.
6783 	 * At least, in this case we have a starting point (in the buckets)
6784 	 * to look for other routes to the destination in the forward table.
6785 	 * This is actually used only for multirouting, where a list
6786 	 * of routes has to be processed in sequence.
6787 	 */
6788 	if (in_ill != NULL) {
6789 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6790 		    in_ill, MATCH_IRE_TYPE);
6791 	} else if (attach_ill == NULL) {
6792 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6793 		    NULL, &sire, zoneid, 0,
6794 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6795 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6796 	} else {
6797 		/*
6798 		 * attach_ill is set only for communicating with
6799 		 * on-link hosts. So, don't look for DEFAULT.
6800 		 */
6801 		ipif_t	*attach_ipif;
6802 
6803 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6804 		if (attach_ipif == NULL) {
6805 			ill_refrele(attach_ill);
6806 			goto icmp_err_ret;
6807 		}
6808 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6809 		    &sire, zoneid, 0,
6810 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6811 		ipif_refrele(attach_ipif);
6812 	}
6813 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6814 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6815 
6816 	/*
6817 	 * This loop is run only once in most cases.
6818 	 * We loop to resolve further routes only when the destination
6819 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6820 	 */
6821 	do {
6822 		/* Clear the previous iteration's values */
6823 		if (src_ipif != NULL) {
6824 			ipif_refrele(src_ipif);
6825 			src_ipif = NULL;
6826 		}
6827 		if (dst_ill != NULL) {
6828 			ill_refrele(dst_ill);
6829 			dst_ill = NULL;
6830 		}
6831 
6832 		multirt_resolve_next = B_FALSE;
6833 		/*
6834 		 * We check if packets have to be multirouted.
6835 		 * In this case, given the current <ire, sire> couple,
6836 		 * we look for the next suitable <ire, sire>.
6837 		 * This check is done in ire_multirt_lookup(),
6838 		 * which applies various criteria to find the next route
6839 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6840 		 * unchanged if it detects it has not been tried yet.
6841 		 */
6842 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6843 			ip3dbg(("ip_newroute: starting next_resolution "
6844 			    "with first_mp %p, tag %d\n",
6845 			    (void *)first_mp,
6846 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6847 
6848 			ASSERT(sire != NULL);
6849 			multirt_is_resolvable =
6850 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6851 
6852 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6853 			    "ire %p, sire %p\n",
6854 			    multirt_is_resolvable,
6855 			    (void *)ire, (void *)sire));
6856 
6857 			if (!multirt_is_resolvable) {
6858 				/*
6859 				 * No more multirt route to resolve; give up
6860 				 * (all routes resolved or no more
6861 				 * resolvable routes).
6862 				 */
6863 				if (ire != NULL) {
6864 					ire_refrele(ire);
6865 					ire = NULL;
6866 				}
6867 			} else {
6868 				ASSERT(sire != NULL);
6869 				ASSERT(ire != NULL);
6870 				/*
6871 				 * We simply use first_sire as a flag that
6872 				 * indicates if a resolvable multirt route
6873 				 * has already been found.
6874 				 * If it is not the case, we may have to send
6875 				 * an ICMP error to report that the
6876 				 * destination is unreachable.
6877 				 * We do not IRE_REFHOLD first_sire.
6878 				 */
6879 				if (first_sire == NULL) {
6880 					first_sire = sire;
6881 				}
6882 			}
6883 		}
6884 		if (ire == NULL) {
6885 			if (ip_debug > 3) {
6886 				/* ip2dbg */
6887 				pr_addr_dbg("ip_newroute: "
6888 				    "can't resolve %s\n", AF_INET, &dst);
6889 			}
6890 			ip3dbg(("ip_newroute: "
6891 			    "ire %p, sire %p, first_sire %p\n",
6892 			    (void *)ire, (void *)sire, (void *)first_sire));
6893 
6894 			if (sire != NULL) {
6895 				ire_refrele(sire);
6896 				sire = NULL;
6897 			}
6898 
6899 			if (first_sire != NULL) {
6900 				/*
6901 				 * At least one multirt route has been found
6902 				 * in the same call to ip_newroute();
6903 				 * there is no need to report an ICMP error.
6904 				 * first_sire was not IRE_REFHOLDed.
6905 				 */
6906 				MULTIRT_DEBUG_UNTAG(first_mp);
6907 				freemsg(first_mp);
6908 				return;
6909 			}
6910 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6911 			    RTA_DST);
6912 			if (attach_ill != NULL)
6913 				ill_refrele(attach_ill);
6914 			goto icmp_err_ret;
6915 		}
6916 
6917 		/*
6918 		 * When RTA_SRCIFP is used to add a route, then an interface
6919 		 * route is added in the source interface's routing table.
6920 		 * If the outgoing interface of this route is of type
6921 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6922 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6923 		 * first used for forwarding packet, ip_newroute() is called
6924 		 * to resolve the hardware address of the outgoing ipif.
6925 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6926 		 * source interface based table. We only come here if the
6927 		 * outgoing interface is a resolver interface and we don't
6928 		 * have the ire_dlureq_mp information yet.
6929 		 * If in_ill is not null that means it is called from
6930 		 * ip_rput.
6931 		 */
6932 
6933 		ASSERT(ire->ire_in_ill == NULL ||
6934 		    (ire->ire_type == IRE_IF_RESOLVER &&
6935 		    ire->ire_dlureq_mp == NULL));
6936 
6937 		/*
6938 		 * Verify that the returned IRE does not have either
6939 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6940 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6941 		 */
6942 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
6943 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
6944 			if (attach_ill != NULL)
6945 				ill_refrele(attach_ill);
6946 			goto icmp_err_ret;
6947 		}
6948 		/*
6949 		 * Increment the ire_ob_pkt_count field for ire if it is an
6950 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
6951 		 * increment the same for the parent IRE, sire, if it is some
6952 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
6953 		 * and HOST_REDIRECT).
6954 		 */
6955 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
6956 			UPDATE_OB_PKT_COUNT(ire);
6957 			ire->ire_last_used_time = lbolt;
6958 		}
6959 
6960 		if (sire != NULL) {
6961 			gw = sire->ire_gateway_addr;
6962 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
6963 			    IRE_INTERFACE)) == 0);
6964 			UPDATE_OB_PKT_COUNT(sire);
6965 			sire->ire_last_used_time = lbolt;
6966 		}
6967 		/*
6968 		 * We have a route to reach the destination.
6969 		 *
6970 		 * 1) If the interface is part of ill group, try to get a new
6971 		 *    ill taking load spreading into account.
6972 		 *
6973 		 * 2) After selecting the ill, get a source address that
6974 		 *    might create good inbound load spreading.
6975 		 *    ipif_select_source does this for us.
6976 		 *
6977 		 * If the application specified the ill (ifindex), we still
6978 		 * load spread. Only if the packets needs to go out
6979 		 * specifically on a given ill e.g. binding to
6980 		 * IPIF_NOFAILOVER address, then we don't try to use a
6981 		 * different ill for load spreading.
6982 		 */
6983 		if (attach_ill == NULL) {
6984 			/*
6985 			 * Don't perform outbound load spreading in the
6986 			 * case of an RTF_MULTIRT route, as we actually
6987 			 * typically want to replicate outgoing packets
6988 			 * through particular interfaces.
6989 			 */
6990 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6991 				dst_ill = ire->ire_ipif->ipif_ill;
6992 				/* for uniformity */
6993 				ill_refhold(dst_ill);
6994 			} else {
6995 				/*
6996 				 * If we are here trying to create an IRE_CACHE
6997 				 * for an offlink destination and have the
6998 				 * IRE_CACHE for the next hop and the latter is
6999 				 * using virtual IP source address selection i.e
7000 				 * it's ire->ire_ipif is pointing to a virtual
7001 				 * network interface (vni) then
7002 				 * ip_newroute_get_dst_ll() will return the vni
7003 				 * interface as the dst_ill. Since the vni is
7004 				 * virtual i.e not associated with any physical
7005 				 * interface, it cannot be the dst_ill, hence
7006 				 * in such a case call ip_newroute_get_dst_ll()
7007 				 * with the stq_ill instead of the ire_ipif ILL.
7008 				 * The function returns a refheld ill.
7009 				 */
7010 				if ((ire->ire_type == IRE_CACHE) &&
7011 				    IS_VNI(ire->ire_ipif->ipif_ill))
7012 					dst_ill = ip_newroute_get_dst_ill(
7013 						ire->ire_stq->q_ptr);
7014 				else
7015 					dst_ill = ip_newroute_get_dst_ill(
7016 						ire->ire_ipif->ipif_ill);
7017 			}
7018 			if (dst_ill == NULL) {
7019 				if (ip_debug > 2) {
7020 					pr_addr_dbg("ip_newroute: "
7021 					    "no dst ill for dst"
7022 					    " %s\n", AF_INET, &dst);
7023 				}
7024 				goto icmp_err_ret;
7025 			}
7026 		} else {
7027 			dst_ill = ire->ire_ipif->ipif_ill;
7028 			/* for uniformity */
7029 			ill_refhold(dst_ill);
7030 			/*
7031 			 * We should have found a route matching ill as we
7032 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7033 			 * Rather than asserting, when there is a mismatch,
7034 			 * we just drop the packet.
7035 			 */
7036 			if (dst_ill != attach_ill) {
7037 				ip0dbg(("ip_newroute: Packet dropped as "
7038 				    "IPIF_NOFAILOVER ill is %s, "
7039 				    "ire->ire_ipif->ipif_ill is %s\n",
7040 				    attach_ill->ill_name,
7041 				    dst_ill->ill_name));
7042 				ill_refrele(attach_ill);
7043 				goto icmp_err_ret;
7044 			}
7045 		}
7046 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7047 		if (attach_ill != NULL) {
7048 			ill_refrele(attach_ill);
7049 			attach_ill = NULL;
7050 			do_attach_ill = B_TRUE;
7051 		}
7052 		ASSERT(dst_ill != NULL);
7053 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7054 
7055 		/*
7056 		 * Pick the best source address from dst_ill.
7057 		 *
7058 		 * 1) If it is part of a multipathing group, we would
7059 		 *    like to spread the inbound packets across different
7060 		 *    interfaces. ipif_select_source picks a random source
7061 		 *    across the different ills in the group.
7062 		 *
7063 		 * 2) If it is not part of a multipathing group, we try
7064 		 *    to pick the source address from the destination
7065 		 *    route. Clustering assumes that when we have multiple
7066 		 *    prefixes hosted on an interface, the prefix of the
7067 		 *    source address matches the prefix of the destination
7068 		 *    route. We do this only if the address is not
7069 		 *    DEPRECATED.
7070 		 *
7071 		 * 3) If the conn is in a different zone than the ire, we
7072 		 *    need to pick a source address from the right zone.
7073 		 *
7074 		 * NOTE : If we hit case (1) above, the prefix of the source
7075 		 *	  address picked may not match the prefix of the
7076 		 *	  destination routes prefix as ipif_select_source
7077 		 *	  does not look at "dst" while picking a source
7078 		 *	  address.
7079 		 *	  If we want the same behavior as (2), we will need
7080 		 *	  to change the behavior of ipif_select_source.
7081 		 */
7082 		ASSERT(src_ipif == NULL);
7083 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7084 			/*
7085 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7086 			 * Check that the ipif matching the requested source
7087 			 * address still exists.
7088 			 */
7089 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7090 			    zoneid, NULL, NULL, NULL, NULL);
7091 		}
7092 		if (src_ipif == NULL) {
7093 			ire_marks |= IRE_MARK_USESRC_CHECK;
7094 			if ((dst_ill->ill_group != NULL) ||
7095 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7096 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
7097 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7098 				src_ipif = ipif_select_source(dst_ill, dst,
7099 				    zoneid);
7100 				if (src_ipif == NULL) {
7101 					if (ip_debug > 2) {
7102 						pr_addr_dbg("ip_newroute: "
7103 						    "no src for dst %s ",
7104 						    AF_INET, &dst);
7105 						printf("through interface %s\n",
7106 						    dst_ill->ill_name);
7107 					}
7108 					goto icmp_err_ret;
7109 				}
7110 			} else {
7111 				src_ipif = ire->ire_ipif;
7112 				ASSERT(src_ipif != NULL);
7113 				/* hold src_ipif for uniformity */
7114 				ipif_refhold(src_ipif);
7115 			}
7116 		}
7117 
7118 		/*
7119 		 * Assign a source address while we have the conn.
7120 		 * We can't have ip_wput_ire pick a source address when the
7121 		 * packet returns from arp since we need to look at
7122 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7123 		 * going through arp.
7124 		 *
7125 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7126 		 *	  it uses ip6i to store this information.
7127 		 */
7128 		if (ipha->ipha_src == INADDR_ANY &&
7129 		    (connp == NULL || !connp->conn_unspec_src)) {
7130 			ipha->ipha_src = src_ipif->ipif_src_addr;
7131 		}
7132 		if (ip_debug > 3) {
7133 			/* ip2dbg */
7134 			pr_addr_dbg("ip_newroute: first hop %s\n",
7135 			    AF_INET, &gw);
7136 		}
7137 		ip2dbg(("\tire type %s (%d)\n",
7138 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7139 
7140 		/*
7141 		 * The TTL of multirouted packets is bounded by the
7142 		 * ip_multirt_ttl ndd variable.
7143 		 */
7144 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7145 			/* Force TTL of multirouted packets */
7146 			if ((ip_multirt_ttl > 0) &&
7147 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7148 				ip2dbg(("ip_newroute: forcing multirt TTL "
7149 				    "to %d (was %d), dst 0x%08x\n",
7150 				    ip_multirt_ttl, ipha->ipha_ttl,
7151 				    ntohl(sire->ire_addr)));
7152 				ipha->ipha_ttl = ip_multirt_ttl;
7153 			}
7154 		}
7155 		/*
7156 		 * At this point in ip_newroute(), ire is either the
7157 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7158 		 * destination or an IRE_INTERFACE type that should be used
7159 		 * to resolve an on-subnet destination or an on-subnet
7160 		 * next-hop gateway.
7161 		 *
7162 		 * In the IRE_CACHE case, we have the following :
7163 		 *
7164 		 * 1) src_ipif - used for getting a source address.
7165 		 *
7166 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7167 		 *    means packets using this IRE_CACHE will go out on
7168 		 *    dst_ill.
7169 		 *
7170 		 * 3) The IRE sire will point to the prefix that is the
7171 		 *    longest  matching route for the destination. These
7172 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7173 		 *    and IRE_HOST_REDIRECT.
7174 		 *
7175 		 *    The newly created IRE_CACHE entry for the off-subnet
7176 		 *    destination is tied to both the prefix route and the
7177 		 *    interface route used to resolve the next-hop gateway
7178 		 *    via the ire_phandle and ire_ihandle fields,
7179 		 *    respectively.
7180 		 *
7181 		 * In the IRE_INTERFACE case, we have the following :
7182 		 *
7183 		 * 1) src_ipif - used for getting a source address.
7184 		 *
7185 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7186 		 *    means packets using the IRE_CACHE that we will build
7187 		 *    here will go out on dst_ill.
7188 		 *
7189 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7190 		 *    to be created will only be tied to the IRE_INTERFACE
7191 		 *    that was derived from the ire_ihandle field.
7192 		 *
7193 		 *    If sire is non-NULL, it means the destination is
7194 		 *    off-link and we will first create the IRE_CACHE for the
7195 		 *    gateway. Next time through ip_newroute, we will create
7196 		 *    the IRE_CACHE for the final destination as described
7197 		 *    above.
7198 		 *
7199 		 * In both cases, after the current resolution has been
7200 		 * completed (or possibly initialised, in the IRE_INTERFACE
7201 		 * case), the loop may be re-entered to attempt the resolution
7202 		 * of another RTF_MULTIRT route.
7203 		 *
7204 		 * When an IRE_CACHE entry for the off-subnet destination is
7205 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7206 		 * for further processing in emission loops.
7207 		 */
7208 		save_ire = ire;
7209 		switch (ire->ire_type) {
7210 		case IRE_CACHE: {
7211 			ire_t	*ipif_ire;
7212 			mblk_t	*ire_fp_mp;
7213 
7214 			ASSERT(sire != NULL);
7215 			if (gw == 0)
7216 				gw = ire->ire_gateway_addr;
7217 			/*
7218 			 * We need 3 ire's to create a new cache ire for an
7219 			 * off-link destination from the cache ire of the
7220 			 * gateway.
7221 			 *
7222 			 *	1. The prefix ire 'sire'
7223 			 *	2. The cache ire of the gateway 'ire'
7224 			 *	3. The interface ire 'ipif_ire'
7225 			 *
7226 			 * We have (1) and (2). We lookup (3) below.
7227 			 *
7228 			 * If there is no interface route to the gateway,
7229 			 * it is a race condition, where we found the cache
7230 			 * but the inteface route has been deleted.
7231 			 */
7232 			ipif_ire = ire_ihandle_lookup_offlink(ire, sire);
7233 			if (ipif_ire == NULL) {
7234 				ip1dbg(("ip_newroute: "
7235 				    "ire_ihandle_lookup_offlink failed\n"));
7236 				goto icmp_err_ret;
7237 			}
7238 			/*
7239 			 * XXX We are using the same dlureq_mp
7240 			 * (DL_UNITDATA_REQ) though the save_ire is not
7241 			 * pointing at the same ill.
7242 			 * This is incorrect. We need to send it up to the
7243 			 * resolver to get the right dlureq_mp. For ethernets
7244 			 * this may be okay (ill_type == DL_ETHER).
7245 			 */
7246 			dlureq_mp = save_ire->ire_dlureq_mp;
7247 			ire_fp_mp = NULL;
7248 			/*
7249 			 * save_ire's ire_fp_mp can't change since it is
7250 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7251 			 * LOCK_IRE_FP_MP does not do any useful work in
7252 			 * the case of IRE_CACHE. So we don't use it below.
7253 			 */
7254 			if (save_ire->ire_stq == dst_ill->ill_wq)
7255 				ire_fp_mp = save_ire->ire_fp_mp;
7256 
7257 			ire = ire_create(
7258 			    (uchar_t *)&dst,		/* dest address */
7259 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7260 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7261 			    (uchar_t *)&gw,		/* gateway address */
7262 			    NULL,
7263 			    &save_ire->ire_max_frag,
7264 			    ire_fp_mp,			/* Fast Path header */
7265 			    dst_ill->ill_rq,		/* recv-from queue */
7266 			    dst_ill->ill_wq,		/* send-to queue */
7267 			    IRE_CACHE,			/* IRE type */
7268 			    save_ire->ire_dlureq_mp,
7269 			    src_ipif,
7270 			    in_ill,			/* incoming ill */
7271 			    sire->ire_mask,		/* Parent mask */
7272 			    sire->ire_phandle,		/* Parent handle */
7273 			    ipif_ire->ire_ihandle,	/* Interface handle */
7274 			    sire->ire_flags &
7275 				(RTF_SETSRC | RTF_MULTIRT), /* flags if any */
7276 			    &(sire->ire_uinfo));
7277 
7278 			if (ire == NULL) {
7279 				ire_refrele(ipif_ire);
7280 				ire_refrele(save_ire);
7281 				break;
7282 			}
7283 
7284 			ire->ire_marks |= ire_marks;
7285 
7286 			/*
7287 			 * Prevent sire and ipif_ire from getting deleted.
7288 			 * The newly created ire is tied to both of them via
7289 			 * the phandle and ihandle respectively.
7290 			 */
7291 			IRB_REFHOLD(sire->ire_bucket);
7292 			/* Has it been removed already ? */
7293 			if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7294 				IRB_REFRELE(sire->ire_bucket);
7295 				ire_refrele(ipif_ire);
7296 				ire_refrele(save_ire);
7297 				break;
7298 			}
7299 
7300 			IRB_REFHOLD(ipif_ire->ire_bucket);
7301 			/* Has it been removed already ? */
7302 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7303 				IRB_REFRELE(ipif_ire->ire_bucket);
7304 				IRB_REFRELE(sire->ire_bucket);
7305 				ire_refrele(ipif_ire);
7306 				ire_refrele(save_ire);
7307 				break;
7308 			}
7309 
7310 			xmit_mp = first_mp;
7311 			/*
7312 			 * In the case of multirouting, a copy
7313 			 * of the packet is done before its sending.
7314 			 * The copy is used to attempt another
7315 			 * route resolution, in a next loop.
7316 			 */
7317 			if (ire->ire_flags & RTF_MULTIRT) {
7318 				copy_mp = copymsg(first_mp);
7319 				if (copy_mp != NULL) {
7320 					xmit_mp = copy_mp;
7321 					MULTIRT_DEBUG_TAG(first_mp);
7322 				}
7323 			}
7324 			ire_add_then_send(q, ire, xmit_mp);
7325 			ire_refrele(save_ire);
7326 
7327 			/* Assert that sire is not deleted yet. */
7328 			ASSERT(sire->ire_ptpn != NULL);
7329 			IRB_REFRELE(sire->ire_bucket);
7330 
7331 			/* Assert that ipif_ire is not deleted yet. */
7332 			ASSERT(ipif_ire->ire_ptpn != NULL);
7333 			IRB_REFRELE(ipif_ire->ire_bucket);
7334 			ire_refrele(ipif_ire);
7335 
7336 			/*
7337 			 * If copy_mp is not NULL, multirouting was
7338 			 * requested. We loop to initiate a next
7339 			 * route resolution attempt, starting from sire.
7340 			 */
7341 			if (copy_mp != NULL) {
7342 				/*
7343 				 * Search for the next unresolved
7344 				 * multirt route.
7345 				 */
7346 				copy_mp = NULL;
7347 				ipif_ire = NULL;
7348 				ire = NULL;
7349 				multirt_resolve_next = B_TRUE;
7350 				continue;
7351 			}
7352 
7353 			ire_refrele(sire);
7354 			ipif_refrele(src_ipif);
7355 			ill_refrele(dst_ill);
7356 			return;
7357 		}
7358 		case IRE_IF_NORESOLVER: {
7359 			/*
7360 			 * We have what we need to build an IRE_CACHE.
7361 			 *
7362 			 * Create a new dlureq_mp with the IP gateway address
7363 			 * in destination address in the DLPI hdr if the
7364 			 * physical length is exactly 4 bytes.
7365 			 */
7366 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7367 				uchar_t *addr;
7368 
7369 				if (gw)
7370 					addr = (uchar_t *)&gw;
7371 				else
7372 					addr = (uchar_t *)&dst;
7373 
7374 				dlureq_mp = ill_dlur_gen(addr,
7375 				    dst_ill->ill_phys_addr_length,
7376 				    dst_ill->ill_sap,
7377 				    dst_ill->ill_sap_length);
7378 			} else {
7379 				dlureq_mp = ire->ire_dlureq_mp;
7380 			}
7381 
7382 			if (dlureq_mp == NULL) {
7383 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7384 				break;
7385 			}
7386 
7387 			ire = ire_create(
7388 			    (uchar_t *)&dst,		/* dest address */
7389 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7390 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7391 			    (uchar_t *)&gw,		/* gateway address */
7392 			    NULL,
7393 			    &save_ire->ire_max_frag,
7394 			    NULL,			/* Fast Path header */
7395 			    dst_ill->ill_rq,		/* recv-from queue */
7396 			    dst_ill->ill_wq,		/* send-to queue */
7397 			    IRE_CACHE,
7398 			    dlureq_mp,
7399 			    src_ipif,
7400 			    in_ill,			/* Incoming ill */
7401 			    save_ire->ire_mask,		/* Parent mask */
7402 			    (sire != NULL) ?		/* Parent handle */
7403 				sire->ire_phandle : 0,
7404 			    save_ire->ire_ihandle,	/* Interface handle */
7405 			    (sire != NULL) ? sire->ire_flags &
7406 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7407 			    &(save_ire->ire_uinfo));
7408 
7409 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7410 				freeb(dlureq_mp);
7411 
7412 			if (ire == NULL) {
7413 				ire_refrele(save_ire);
7414 				break;
7415 			}
7416 
7417 			ire->ire_marks |= ire_marks;
7418 
7419 			/* Prevent save_ire from getting deleted */
7420 			IRB_REFHOLD(save_ire->ire_bucket);
7421 			/* Has it been removed already ? */
7422 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7423 				IRB_REFRELE(save_ire->ire_bucket);
7424 				ire_refrele(save_ire);
7425 				break;
7426 			}
7427 
7428 			/*
7429 			 * In the case of multirouting, a copy
7430 			 * of the packet is made before it is sent.
7431 			 * The copy is used in the next
7432 			 * loop to attempt another resolution.
7433 			 */
7434 			xmit_mp = first_mp;
7435 			if ((sire != NULL) &&
7436 			    (sire->ire_flags & RTF_MULTIRT)) {
7437 				copy_mp = copymsg(first_mp);
7438 				if (copy_mp != NULL) {
7439 					xmit_mp = copy_mp;
7440 					MULTIRT_DEBUG_TAG(first_mp);
7441 				}
7442 			}
7443 			ire_add_then_send(q, ire, xmit_mp);
7444 
7445 			/* Assert that it is not deleted yet. */
7446 			ASSERT(save_ire->ire_ptpn != NULL);
7447 			IRB_REFRELE(save_ire->ire_bucket);
7448 			ire_refrele(save_ire);
7449 
7450 			if (copy_mp != NULL) {
7451 				/*
7452 				 * If we found a (no)resolver, we ignore any
7453 				 * trailing top priority IRE_CACHE in further
7454 				 * loops. This ensures that we do not omit any
7455 				 * (no)resolver.
7456 				 * This IRE_CACHE, if any, will be processed
7457 				 * by another thread entering ip_newroute().
7458 				 * IRE_CACHE entries, if any, will be processed
7459 				 * by another thread entering ip_newroute(),
7460 				 * (upon resolver response, for instance).
7461 				 * This aims to force parallel multirt
7462 				 * resolutions as soon as a packet must be sent.
7463 				 * In the best case, after the tx of only one
7464 				 * packet, all reachable routes are resolved.
7465 				 * Otherwise, the resolution of all RTF_MULTIRT
7466 				 * routes would require several emissions.
7467 				 */
7468 				multirt_flags &= ~MULTIRT_CACHEGW;
7469 
7470 				/*
7471 				 * Search for the next unresolved multirt
7472 				 * route.
7473 				 */
7474 				copy_mp = NULL;
7475 				save_ire = NULL;
7476 				ire = NULL;
7477 				multirt_resolve_next = B_TRUE;
7478 				continue;
7479 			}
7480 
7481 			/*
7482 			 * Don't need sire anymore
7483 			 */
7484 			if (sire != NULL)
7485 				ire_refrele(sire);
7486 
7487 			ipif_refrele(src_ipif);
7488 			ill_refrele(dst_ill);
7489 			return;
7490 		}
7491 		case IRE_IF_RESOLVER:
7492 			/*
7493 			 * We can't build an IRE_CACHE yet, but at least we
7494 			 * found a resolver that can help.
7495 			 */
7496 			res_mp = dst_ill->ill_resolver_mp;
7497 			if (!OK_RESOLVER_MP(res_mp))
7498 				break;
7499 			/*
7500 			 * To be at this point in the code with a non-zero gw
7501 			 * means that dst is reachable through a gateway that
7502 			 * we have never resolved.  By changing dst to the gw
7503 			 * addr we resolve the gateway first.
7504 			 * When ire_add_then_send() tries to put the IP dg
7505 			 * to dst, it will reenter ip_newroute() at which
7506 			 * time we will find the IRE_CACHE for the gw and
7507 			 * create another IRE_CACHE in case IRE_CACHE above.
7508 			 */
7509 			if (gw != INADDR_ANY) {
7510 				/*
7511 				 * The source ipif that was determined above was
7512 				 * relative to the destination address, not the
7513 				 * gateway's. If src_ipif was not taken out of
7514 				 * the IRE_IF_RESOLVER entry, we'll need to call
7515 				 * ipif_select_source() again.
7516 				 */
7517 				if (src_ipif != ire->ire_ipif) {
7518 					ipif_refrele(src_ipif);
7519 					src_ipif = ipif_select_source(dst_ill,
7520 					    gw, zoneid);
7521 					if (src_ipif == NULL) {
7522 						if (ip_debug > 2) {
7523 							pr_addr_dbg(
7524 							    "ip_newroute: no "
7525 							    "src for gw %s ",
7526 							    AF_INET, &gw);
7527 							printf("through "
7528 							    "interface %s\n",
7529 							    dst_ill->ill_name);
7530 						}
7531 						goto icmp_err_ret;
7532 					}
7533 				}
7534 				save_dst = dst;
7535 				dst = gw;
7536 				gw = INADDR_ANY;
7537 			}
7538 			/*
7539 			 * We obtain a partial IRE_CACHE which we will pass
7540 			 * along with the resolver query.  When the response
7541 			 * comes back it will be there ready for us to add.
7542 			 * The ire_max_frag is atomically set under the
7543 			 * irebucket lock in ire_add_v[46].
7544 			 */
7545 			ire = ire_create_mp(
7546 			    (uchar_t *)&dst,		/* dest address */
7547 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7548 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7549 			    (uchar_t *)&gw,		/* gateway address */
7550 			    NULL,			/* no in_src_addr */
7551 			    NULL,			/* ire_max_frag */
7552 			    NULL,			/* Fast Path header */
7553 			    dst_ill->ill_rq,		/* recv-from queue */
7554 			    dst_ill->ill_wq,		/* send-to queue */
7555 			    IRE_CACHE,
7556 			    res_mp,
7557 			    src_ipif,			/* Interface ipif */
7558 			    in_ill,			/* Incoming ILL */
7559 			    save_ire->ire_mask,		/* Parent mask */
7560 			    0,
7561 			    save_ire->ire_ihandle,	/* Interface handle */
7562 			    0,				/* flags if any */
7563 			    &(save_ire->ire_uinfo));
7564 
7565 			if (ire == NULL) {
7566 				ire_refrele(save_ire);
7567 				break;
7568 			}
7569 
7570 			if ((sire != NULL) &&
7571 			    (sire->ire_flags & RTF_MULTIRT)) {
7572 				copy_mp = copymsg(first_mp);
7573 				if (copy_mp != NULL)
7574 					MULTIRT_DEBUG_TAG(copy_mp);
7575 			}
7576 
7577 			ire->ire_marks |= ire_marks;
7578 
7579 			/*
7580 			 * Construct message chain for the resolver
7581 			 * of the form:
7582 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7583 			 * Packet could contain a IPSEC_OUT mp.
7584 			 *
7585 			 * NOTE : ire will be added later when the response
7586 			 * comes back from ARP. If the response does not
7587 			 * come back, ARP frees the packet. For this reason,
7588 			 * we can't REFHOLD the bucket of save_ire to prevent
7589 			 * deletions. We may not be able to REFRELE the bucket
7590 			 * if the response never comes back. Thus, before
7591 			 * adding the ire, ire_add_v4 will make sure that the
7592 			 * interface route does not get deleted. This is the
7593 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7594 			 * where we can always prevent deletions because of
7595 			 * the synchronous nature of adding IRES i.e
7596 			 * ire_add_then_send is called after creating the IRE.
7597 			 */
7598 			ASSERT(ire->ire_mp != NULL);
7599 			ire->ire_mp->b_cont = first_mp;
7600 			/* Have saved_mp handy, for cleanup if canput fails */
7601 			saved_mp = mp;
7602 			mp = ire->ire_dlureq_mp;
7603 			ASSERT(mp != NULL);
7604 			ire->ire_dlureq_mp = NULL;
7605 			linkb(mp, ire->ire_mp);
7606 
7607 
7608 			/*
7609 			 * Fill in the source and dest addrs for the resolver.
7610 			 * NOTE: this depends on memory layouts imposed by
7611 			 * ill_init().
7612 			 */
7613 			areq = (areq_t *)mp->b_rptr;
7614 			addrp = (ipaddr_t *)((char *)areq +
7615 			    areq->areq_sender_addr_offset);
7616 			if (do_attach_ill) {
7617 				/*
7618 				 * This is bind to no failover case.
7619 				 * arp packet also must go out on attach_ill.
7620 				 */
7621 				ASSERT(ipha->ipha_src != NULL);
7622 				*addrp = ipha->ipha_src;
7623 			} else {
7624 				*addrp = save_ire->ire_src_addr;
7625 			}
7626 
7627 			ire_refrele(save_ire);
7628 			addrp = (ipaddr_t *)((char *)areq +
7629 			    areq->areq_target_addr_offset);
7630 			*addrp = dst;
7631 			/* Up to the resolver. */
7632 			if (canputnext(dst_ill->ill_rq)) {
7633 				putnext(dst_ill->ill_rq, mp);
7634 				ire = NULL;
7635 				if (copy_mp != NULL) {
7636 					/*
7637 					 * If we found a resolver, we ignore
7638 					 * any trailing top priority IRE_CACHE
7639 					 * in the further loops. This ensures
7640 					 * that we do not omit any resolver.
7641 					 * IRE_CACHE entries, if any, will be
7642 					 * processed next time we enter
7643 					 * ip_newroute().
7644 					 */
7645 					multirt_flags &= ~MULTIRT_CACHEGW;
7646 					/*
7647 					 * Search for the next unresolved
7648 					 * multirt route.
7649 					 */
7650 					first_mp = copy_mp;
7651 					copy_mp = NULL;
7652 					/* Prepare the next resolution loop. */
7653 					mp = first_mp;
7654 					EXTRACT_PKT_MP(mp, first_mp,
7655 					    mctl_present);
7656 					if (mctl_present)
7657 						io = (ipsec_out_t *)
7658 						    first_mp->b_rptr;
7659 					ipha = (ipha_t *)mp->b_rptr;
7660 
7661 					ASSERT(sire != NULL);
7662 
7663 					dst = save_dst;
7664 					multirt_resolve_next = B_TRUE;
7665 					continue;
7666 				}
7667 
7668 				if (sire != NULL)
7669 					ire_refrele(sire);
7670 
7671 				/*
7672 				 * The response will come back in ip_wput
7673 				 * with db_type IRE_DB_TYPE.
7674 				 */
7675 				ipif_refrele(src_ipif);
7676 				ill_refrele(dst_ill);
7677 				return;
7678 			} else {
7679 				/* Prepare for cleanup */
7680 				ire->ire_dlureq_mp = mp;
7681 				mp->b_cont = NULL;
7682 				ire_delete(ire);
7683 				mp = saved_mp;
7684 				ire = NULL;
7685 				if (copy_mp != NULL) {
7686 					MULTIRT_DEBUG_UNTAG(copy_mp);
7687 					freemsg(copy_mp);
7688 					copy_mp = NULL;
7689 				}
7690 				break;
7691 			}
7692 		default:
7693 			break;
7694 		}
7695 	} while (multirt_resolve_next);
7696 
7697 	ip1dbg(("ip_newroute: dropped\n"));
7698 	/* Did this packet originate externally? */
7699 	if (mp->b_prev) {
7700 		mp->b_next = NULL;
7701 		mp->b_prev = NULL;
7702 		BUMP_MIB(&ip_mib, ipInDiscards);
7703 	} else {
7704 		BUMP_MIB(&ip_mib, ipOutDiscards);
7705 	}
7706 	ASSERT(copy_mp == NULL);
7707 	MULTIRT_DEBUG_UNTAG(first_mp);
7708 	freemsg(first_mp);
7709 	if (ire != NULL)
7710 		ire_refrele(ire);
7711 	if (sire != NULL)
7712 		ire_refrele(sire);
7713 	if (src_ipif != NULL)
7714 		ipif_refrele(src_ipif);
7715 	if (dst_ill != NULL)
7716 		ill_refrele(dst_ill);
7717 	return;
7718 
7719 icmp_err_ret:
7720 	ip1dbg(("ip_newroute: no route\n"));
7721 	if (src_ipif != NULL)
7722 		ipif_refrele(src_ipif);
7723 	if (dst_ill != NULL)
7724 		ill_refrele(dst_ill);
7725 	if (sire != NULL)
7726 		ire_refrele(sire);
7727 	/* Did this packet originate externally? */
7728 	if (mp->b_prev) {
7729 		mp->b_next = NULL;
7730 		mp->b_prev = NULL;
7731 		/* XXX ipInNoRoutes */
7732 		q = WR(q);
7733 	} else {
7734 		/*
7735 		 * Since ip_wput() isn't close to finished, we fill
7736 		 * in enough of the header for credible error reporting.
7737 		 */
7738 		if (ip_hdr_complete(ipha, zoneid)) {
7739 			/* Failed */
7740 			MULTIRT_DEBUG_UNTAG(first_mp);
7741 			freemsg(first_mp);
7742 			if (ire != NULL)
7743 				ire_refrele(ire);
7744 			return;
7745 		}
7746 	}
7747 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7748 
7749 	/*
7750 	 * At this point we will have ire only if RTF_BLACKHOLE
7751 	 * or RTF_REJECT flags are set on the IRE. It will not
7752 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7753 	 */
7754 	if (ire != NULL) {
7755 		if (ire->ire_flags & RTF_BLACKHOLE) {
7756 			ire_refrele(ire);
7757 			MULTIRT_DEBUG_UNTAG(first_mp);
7758 			freemsg(first_mp);
7759 			return;
7760 		}
7761 		ire_refrele(ire);
7762 	}
7763 	if (ip_source_routed(ipha)) {
7764 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7765 		return;
7766 	}
7767 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7768 }
7769 
7770 /*
7771  * IPv4 -
7772  * ip_newroute_ipif is called by ip_wput_multicast and
7773  * ip_rput_forward_multicast whenever we need to send
7774  * out a packet to a destination address for which we do not have specific
7775  * routing information. It is used when the packet will be sent out
7776  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7777  * socket option is set or icmp error message wants to go out on a particular
7778  * interface for a unicast packet.
7779  *
7780  * In most cases, the destination address is resolved thanks to the ipif
7781  * intrinsic resolver. However, there are some cases where the call to
7782  * ip_newroute_ipif must take into account the potential presence of
7783  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7784  * that uses the interface. This is specified through flags,
7785  * which can be a combination of:
7786  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7787  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7788  *   and flags. Additionally, the packet source address has to be set to
7789  *   the specified address. The caller is thus expected to set this flag
7790  *   if the packet has no specific source address yet.
7791  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7792  *   flag, the resulting ire will inherit the flag. All unresolved routes
7793  *   to the destination must be explored in the same call to
7794  *   ip_newroute_ipif().
7795  */
7796 static void
7797 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7798     conn_t *connp, uint32_t flags)
7799 {
7800 	areq_t	*areq;
7801 	ire_t	*ire = NULL;
7802 	mblk_t	*res_mp;
7803 	ipaddr_t *addrp;
7804 	mblk_t *first_mp;
7805 	ire_t	*save_ire = NULL;
7806 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7807 	ipif_t	*src_ipif = NULL;
7808 	ushort_t ire_marks = 0;
7809 	ill_t	*dst_ill = NULL;
7810 	boolean_t mctl_present;
7811 	ipsec_out_t *io;
7812 	ipha_t *ipha;
7813 	int	ihandle = 0;
7814 	mblk_t	*saved_mp;
7815 	ire_t   *fire = NULL;
7816 	mblk_t  *copy_mp = NULL;
7817 	boolean_t multirt_resolve_next;
7818 	ipaddr_t ipha_dst;
7819 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7820 
7821 	/*
7822 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7823 	 * here for uniformity
7824 	 */
7825 	ipif_refhold(ipif);
7826 
7827 	/*
7828 	 * This loop is run only once in most cases.
7829 	 * We loop to resolve further routes only when the destination
7830 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7831 	 */
7832 	do {
7833 		if (dst_ill != NULL) {
7834 			ill_refrele(dst_ill);
7835 			dst_ill = NULL;
7836 		}
7837 		if (src_ipif != NULL) {
7838 			ipif_refrele(src_ipif);
7839 			src_ipif = NULL;
7840 		}
7841 		multirt_resolve_next = B_FALSE;
7842 
7843 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7844 		    ipif->ipif_ill->ill_name));
7845 
7846 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7847 		if (mctl_present)
7848 			io = (ipsec_out_t *)first_mp->b_rptr;
7849 
7850 		ipha = (ipha_t *)mp->b_rptr;
7851 
7852 		/*
7853 		 * Save the packet destination address, we may need it after
7854 		 * the packet has been consumed.
7855 		 */
7856 		ipha_dst = ipha->ipha_dst;
7857 
7858 		/*
7859 		 * If the interface is a pt-pt interface we look for an
7860 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7861 		 * local_address and the pt-pt destination address. Otherwise
7862 		 * we just match the local address.
7863 		 * NOTE: dst could be different than ipha->ipha_dst in case
7864 		 * of sending igmp multicast packets over a point-to-point
7865 		 * connection.
7866 		 * Thus we must be careful enough to check ipha_dst to be a
7867 		 * multicast address, otherwise it will take xmit_if path for
7868 		 * multicast packets resulting into kernel stack overflow by
7869 		 * repeated calls to ip_newroute_ipif from ire_send().
7870 		 */
7871 		if (CLASSD(ipha_dst) &&
7872 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7873 			goto err_ret;
7874 		}
7875 
7876 		/*
7877 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7878 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7879 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7880 		 * propagate its flags to the new ire.
7881 		 */
7882 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7883 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7884 			ip2dbg(("ip_newroute_ipif: "
7885 			    "ipif_lookup_multi_ire("
7886 			    "ipif %p, dst %08x) = fire %p\n",
7887 			    (void *)ipif, ntohl(dst), (void *)fire));
7888 		}
7889 
7890 		if (mctl_present && io->ipsec_out_attach_if) {
7891 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7892 			    io->ipsec_out_ill_index, B_FALSE);
7893 
7894 			/* Failure case frees things for us. */
7895 			if (attach_ill == NULL) {
7896 				ipif_refrele(ipif);
7897 				if (fire != NULL)
7898 					ire_refrele(fire);
7899 				return;
7900 			}
7901 
7902 			/*
7903 			 * Check if we need an ire that will not be
7904 			 * looked up by anybody else i.e. HIDDEN.
7905 			 */
7906 			if (ill_is_probeonly(attach_ill)) {
7907 				ire_marks = IRE_MARK_HIDDEN;
7908 			}
7909 			/*
7910 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
7911 			 * case.
7912 			 */
7913 			dst_ill = ipif->ipif_ill;
7914 			/* attach_ill has been refheld by ip_grab_attach_ill */
7915 			ASSERT(dst_ill == attach_ill);
7916 		} else {
7917 			/*
7918 			 * If this is set by IP_XMIT_IF, then make sure that
7919 			 * ipif is pointing to the same ill as the IP_XMIT_IF
7920 			 * specified ill.
7921 			 */
7922 			ASSERT((connp == NULL) ||
7923 			    (connp->conn_xmit_if_ill == NULL) ||
7924 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
7925 			/*
7926 			 * If the interface belongs to an interface group,
7927 			 * make sure the next possible interface in the group
7928 			 * is used.  This encourages load spreading among
7929 			 * peers in an interface group.
7930 			 * Note: load spreading is disabled for RTF_MULTIRT
7931 			 * routes.
7932 			 */
7933 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7934 			    (fire->ire_flags & RTF_MULTIRT)) {
7935 				/*
7936 				 * Don't perform outbound load spreading
7937 				 * in the case of an RTF_MULTIRT issued route,
7938 				 * we actually typically want to replicate
7939 				 * outgoing packets through particular
7940 				 * interfaces.
7941 				 */
7942 				dst_ill = ipif->ipif_ill;
7943 				ill_refhold(dst_ill);
7944 			} else {
7945 				dst_ill = ip_newroute_get_dst_ill(
7946 				    ipif->ipif_ill);
7947 			}
7948 			if (dst_ill == NULL) {
7949 				if (ip_debug > 2) {
7950 					pr_addr_dbg("ip_newroute_ipif: "
7951 					    "no dst ill for dst %s\n",
7952 					    AF_INET, &dst);
7953 				}
7954 				goto err_ret;
7955 			}
7956 		}
7957 
7958 		/*
7959 		 * Pick a source address preferring non-deprecated ones.
7960 		 * Unlike ip_newroute, we don't do any source address
7961 		 * selection here since for multicast it really does not help
7962 		 * in inbound load spreading as in the unicast case.
7963 		 */
7964 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
7965 		    (fire->ire_flags & RTF_SETSRC)) {
7966 			/*
7967 			 * As requested by flags, an IRE_OFFSUBNET was looked up
7968 			 * on that interface. This ire has RTF_SETSRC flag, so
7969 			 * the source address of the packet must be changed.
7970 			 * Check that the ipif matching the requested source
7971 			 * address still exists.
7972 			 */
7973 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
7974 			    zoneid, NULL, NULL, NULL, NULL);
7975 		}
7976 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
7977 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
7978 		    (src_ipif == NULL)) {
7979 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
7980 			if (src_ipif == NULL) {
7981 				if (ip_debug > 2) {
7982 					/* ip1dbg */
7983 					pr_addr_dbg("ip_newroute_ipif: "
7984 					    "no src for dst %s",
7985 					    AF_INET, &dst);
7986 				}
7987 				ip1dbg((" through interface %s\n",
7988 				    dst_ill->ill_name));
7989 				goto err_ret;
7990 			}
7991 			ipif_refrele(ipif);
7992 			ipif = src_ipif;
7993 			ipif_refhold(ipif);
7994 		}
7995 		if (src_ipif == NULL) {
7996 			src_ipif = ipif;
7997 			ipif_refhold(src_ipif);
7998 		}
7999 
8000 		/*
8001 		 * Assign a source address while we have the conn.
8002 		 * We can't have ip_wput_ire pick a source address when the
8003 		 * packet returns from arp since conn_unspec_src might be set
8004 		 * and we loose the conn when going through arp.
8005 		 */
8006 		if (ipha->ipha_src == INADDR_ANY &&
8007 		    (connp == NULL || !connp->conn_unspec_src)) {
8008 			ipha->ipha_src = src_ipif->ipif_src_addr;
8009 		}
8010 
8011 		/*
8012 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8013 		 * interface does not have an interface ire.
8014 		 * Example: Thousands of mobileip PPP interfaces to mobile
8015 		 * nodes. We don't want to create interface ires because
8016 		 * packets from other mobile nodes must not take the route
8017 		 * via interface ires to the visiting mobile node without
8018 		 * going through the home agent, in absence of mobileip
8019 		 * route optimization.
8020 		 */
8021 		if (CLASSD(ipha_dst) && (connp == NULL ||
8022 		    connp->conn_xmit_if_ill == NULL)) {
8023 			/* ipif_to_ire returns an held ire */
8024 			ire = ipif_to_ire(ipif);
8025 			if (ire == NULL)
8026 				goto err_ret;
8027 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8028 				goto err_ret;
8029 			/*
8030 			 * ihandle is needed when the ire is added to
8031 			 * cache table.
8032 			 */
8033 			save_ire = ire;
8034 			ihandle = save_ire->ire_ihandle;
8035 
8036 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8037 			    "flags %04x\n",
8038 			    (void *)ire, (void *)ipif, flags));
8039 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8040 			    (fire->ire_flags & RTF_MULTIRT)) {
8041 				/*
8042 				 * As requested by flags, an IRE_OFFSUBNET was
8043 				 * looked up on that interface. This ire has
8044 				 * RTF_MULTIRT flag, so the resolution loop will
8045 				 * be re-entered to resolve additional routes on
8046 				 * other interfaces. For that purpose, a copy of
8047 				 * the packet is performed at this point.
8048 				 */
8049 				fire->ire_last_used_time = lbolt;
8050 				copy_mp = copymsg(first_mp);
8051 				if (copy_mp) {
8052 					MULTIRT_DEBUG_TAG(copy_mp);
8053 				}
8054 			}
8055 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8056 			    (fire->ire_flags & RTF_SETSRC)) {
8057 				/*
8058 				 * As requested by flags, an IRE_OFFSUBET was
8059 				 * looked up on that interface. This ire has
8060 				 * RTF_SETSRC flag, so the source address of the
8061 				 * packet must be changed.
8062 				 */
8063 				ipha->ipha_src = fire->ire_src_addr;
8064 			}
8065 		} else {
8066 			ASSERT((connp == NULL) ||
8067 			    (connp->conn_xmit_if_ill != NULL) ||
8068 			    (connp->conn_dontroute));
8069 			/*
8070 			 * The only ways we can come here are:
8071 			 * 1) IP_XMIT_IF socket option is set
8072 			 * 2) ICMP error message generated from
8073 			 *    ip_mrtun_forward() routine and it needs
8074 			 *    to go through the specified ill.
8075 			 * 3) SO_DONTROUTE socket option is set
8076 			 * In all cases, the new ire will not be added
8077 			 * into cache table.
8078 			 */
8079 			ire_marks |= IRE_MARK_NOADD;
8080 		}
8081 
8082 		switch (ipif->ipif_net_type) {
8083 		case IRE_IF_NORESOLVER: {
8084 			/* We have what we need to build an IRE_CACHE. */
8085 			mblk_t	*dlureq_mp;
8086 
8087 			/*
8088 			 * Create a new dlureq_mp with the
8089 			 * IP gateway address as destination address in the
8090 			 * DLPI hdr if the physical length is exactly 4 bytes.
8091 			 */
8092 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8093 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8094 				    dst_ill->ill_phys_addr_length,
8095 				    dst_ill->ill_sap,
8096 				    dst_ill->ill_sap_length);
8097 			} else {
8098 				/* use the value set in ip_ll_subnet_defaults */
8099 				dlureq_mp = ill_dlur_gen(NULL,
8100 				    dst_ill->ill_phys_addr_length,
8101 				    dst_ill->ill_sap,
8102 				    dst_ill->ill_sap_length);
8103 			}
8104 
8105 			if (dlureq_mp == NULL)
8106 				break;
8107 			/*
8108 			 * The new ire inherits the IRE_OFFSUBNET flags
8109 			 * and source address, if this was requested.
8110 			 */
8111 			ire = ire_create(
8112 			    (uchar_t *)&dst,		/* dest address */
8113 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8114 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8115 			    NULL,			/* gateway address */
8116 			    NULL,
8117 			    &ipif->ipif_mtu,
8118 			    NULL,			/* Fast Path header */
8119 			    dst_ill->ill_rq,		/* recv-from queue */
8120 			    dst_ill->ill_wq,		/* send-to queue */
8121 			    IRE_CACHE,
8122 			    dlureq_mp,
8123 			    src_ipif,
8124 			    NULL,
8125 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8126 			    (fire != NULL) ?		/* Parent handle */
8127 				fire->ire_phandle : 0,
8128 			    ihandle,			/* Interface handle */
8129 			    (fire != NULL) ?
8130 				(fire->ire_flags &
8131 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8132 			    (save_ire == NULL ? &ire_uinfo_null :
8133 				&save_ire->ire_uinfo));
8134 
8135 			freeb(dlureq_mp);
8136 
8137 			if (ire == NULL) {
8138 				if (save_ire != NULL)
8139 					ire_refrele(save_ire);
8140 				break;
8141 			}
8142 
8143 			ire->ire_marks |= ire_marks;
8144 
8145 			/* Prevent save_ire from getting deleted */
8146 			if (save_ire != NULL) {
8147 				IRB_REFHOLD(save_ire->ire_bucket);
8148 				/* Has it been removed already ? */
8149 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8150 					IRB_REFRELE(save_ire->ire_bucket);
8151 					ire_refrele(save_ire);
8152 					break;
8153 				}
8154 			}
8155 
8156 			ire_add_then_send(q, ire, first_mp);
8157 
8158 			/* Assert that save_ire is not deleted yet. */
8159 			if (save_ire != NULL) {
8160 				ASSERT(save_ire->ire_ptpn != NULL);
8161 				IRB_REFRELE(save_ire->ire_bucket);
8162 				ire_refrele(save_ire);
8163 				save_ire = NULL;
8164 			}
8165 			if (fire != NULL) {
8166 				ire_refrele(fire);
8167 				fire = NULL;
8168 			}
8169 
8170 			/*
8171 			 * the resolution loop is re-entered if this
8172 			 * was requested through flags and if we
8173 			 * actually are in a multirouting case.
8174 			 */
8175 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8176 				boolean_t need_resolve =
8177 				    ire_multirt_need_resolve(ipha_dst);
8178 				if (!need_resolve) {
8179 					MULTIRT_DEBUG_UNTAG(copy_mp);
8180 					freemsg(copy_mp);
8181 					copy_mp = NULL;
8182 				} else {
8183 					/*
8184 					 * ipif_lookup_group() calls
8185 					 * ire_lookup_multi() that uses
8186 					 * ire_ftable_lookup() to find
8187 					 * an IRE_INTERFACE for the group.
8188 					 * In the multirt case,
8189 					 * ire_lookup_multi() then invokes
8190 					 * ire_multirt_lookup() to find
8191 					 * the next resolvable ire.
8192 					 * As a result, we obtain an new
8193 					 * interface, derived from the
8194 					 * next ire.
8195 					 */
8196 					ipif_refrele(ipif);
8197 					ipif = ipif_lookup_group(ipha_dst,
8198 					    zoneid);
8199 					ip2dbg(("ip_newroute_ipif: "
8200 					    "multirt dst %08x, ipif %p\n",
8201 					    htonl(dst), (void *)ipif));
8202 					if (ipif != NULL) {
8203 						mp = copy_mp;
8204 						copy_mp = NULL;
8205 						multirt_resolve_next = B_TRUE;
8206 						continue;
8207 					} else {
8208 						freemsg(copy_mp);
8209 					}
8210 				}
8211 			}
8212 			if (ipif != NULL)
8213 				ipif_refrele(ipif);
8214 			ill_refrele(dst_ill);
8215 			ipif_refrele(src_ipif);
8216 			return;
8217 		}
8218 		case IRE_IF_RESOLVER:
8219 			/*
8220 			 * We can't build an IRE_CACHE yet, but at least
8221 			 * we found a resolver that can help.
8222 			 */
8223 			res_mp = dst_ill->ill_resolver_mp;
8224 			if (!OK_RESOLVER_MP(res_mp))
8225 				break;
8226 
8227 			/*
8228 			 * We obtain a partial IRE_CACHE which we will pass
8229 			 * along with the resolver query.  When the response
8230 			 * comes back it will be there ready for us to add.
8231 			 * The new ire inherits the IRE_OFFSUBNET flags
8232 			 * and source address, if this was requested.
8233 			 * The ire_max_frag is atomically set under the
8234 			 * irebucket lock in ire_add_v[46]. Only in the
8235 			 * case of IRE_MARK_NOADD, we set it here itself.
8236 			 */
8237 			ire = ire_create_mp(
8238 			    (uchar_t *)&dst,		/* dest address */
8239 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8240 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8241 			    NULL,			/* gateway address */
8242 			    NULL,			/* no in_src_addr */
8243 			    (ire_marks & IRE_MARK_NOADD) ?
8244 				ipif->ipif_mtu : 0,	/* max_frag */
8245 			    NULL,			/* Fast path header */
8246 			    dst_ill->ill_rq,		/* recv-from queue */
8247 			    dst_ill->ill_wq,		/* send-to queue */
8248 			    IRE_CACHE,
8249 			    res_mp,
8250 			    src_ipif,
8251 			    NULL,
8252 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8253 			    (fire != NULL) ?		/* Parent handle */
8254 				fire->ire_phandle : 0,
8255 			    ihandle,			/* Interface handle */
8256 			    (fire != NULL) ?		/* flags if any */
8257 				(fire->ire_flags &
8258 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8259 			    (save_ire == NULL ? &ire_uinfo_null :
8260 				&save_ire->ire_uinfo));
8261 
8262 			if (save_ire != NULL) {
8263 				ire_refrele(save_ire);
8264 				save_ire = NULL;
8265 			}
8266 			if (ire == NULL)
8267 				break;
8268 
8269 			ire->ire_marks |= ire_marks;
8270 			/*
8271 			 * Construct message chain for the resolver of the
8272 			 * form:
8273 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8274 			 *
8275 			 * NOTE : ire will be added later when the response
8276 			 * comes back from ARP. If the response does not
8277 			 * come back, ARP frees the packet. For this reason,
8278 			 * we can't REFHOLD the bucket of save_ire to prevent
8279 			 * deletions. We may not be able to REFRELE the
8280 			 * bucket if the response never comes back.
8281 			 * Thus, before adding the ire, ire_add_v4 will make
8282 			 * sure that the interface route does not get deleted.
8283 			 * This is the only case unlike ip_newroute_v6,
8284 			 * ip_newroute_ipif_v6 where we can always prevent
8285 			 * deletions because ire_add_then_send is called after
8286 			 * creating the IRE.
8287 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8288 			 * does not add this IRE into the IRE CACHE.
8289 			 */
8290 			ASSERT(ire->ire_mp != NULL);
8291 			ire->ire_mp->b_cont = first_mp;
8292 			/* Have saved_mp handy, for cleanup if canput fails */
8293 			saved_mp = mp;
8294 			mp = ire->ire_dlureq_mp;
8295 			ASSERT(mp != NULL);
8296 			ire->ire_dlureq_mp = NULL;
8297 			linkb(mp, ire->ire_mp);
8298 
8299 			/*
8300 			 * Fill in the source and dest addrs for the resolver.
8301 			 * NOTE: this depends on memory layouts imposed by
8302 			 * ill_init().
8303 			 */
8304 			areq = (areq_t *)mp->b_rptr;
8305 			addrp = (ipaddr_t *)((char *)areq +
8306 			    areq->areq_sender_addr_offset);
8307 			*addrp = ire->ire_src_addr;
8308 			addrp = (ipaddr_t *)((char *)areq +
8309 			    areq->areq_target_addr_offset);
8310 			*addrp = dst;
8311 			/* Up to the resolver. */
8312 			if (canputnext(dst_ill->ill_rq)) {
8313 				putnext(dst_ill->ill_rq, mp);
8314 				/*
8315 				 * The response will come back in ip_wput
8316 				 * with db_type IRE_DB_TYPE.
8317 				 */
8318 			} else {
8319 				ire->ire_dlureq_mp = mp;
8320 				mp->b_cont = NULL;
8321 				ire_delete(ire);
8322 				saved_mp->b_next = NULL;
8323 				saved_mp->b_prev = NULL;
8324 				freemsg(first_mp);
8325 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8326 			}
8327 
8328 			if (fire != NULL) {
8329 				ire_refrele(fire);
8330 				fire = NULL;
8331 			}
8332 
8333 
8334 			/*
8335 			 * The resolution loop is re-entered if this was
8336 			 * requested through flags and we actually are
8337 			 * in a multirouting case.
8338 			 */
8339 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8340 				boolean_t need_resolve =
8341 				    ire_multirt_need_resolve(ipha_dst);
8342 				if (!need_resolve) {
8343 					MULTIRT_DEBUG_UNTAG(copy_mp);
8344 					freemsg(copy_mp);
8345 					copy_mp = NULL;
8346 				} else {
8347 					/*
8348 					 * ipif_lookup_group() calls
8349 					 * ire_lookup_multi() that uses
8350 					 * ire_ftable_lookup() to find
8351 					 * an IRE_INTERFACE for the group.
8352 					 * In the multirt case,
8353 					 * ire_lookup_multi() then invokes
8354 					 * ire_multirt_lookup() to find
8355 					 * the next resolvable ire.
8356 					 * As a result, we obtain an new
8357 					 * interface, derived from the
8358 					 * next ire.
8359 					 */
8360 					ipif_refrele(ipif);
8361 					ipif = ipif_lookup_group(ipha_dst,
8362 					    zoneid);
8363 					if (ipif != NULL) {
8364 						mp = copy_mp;
8365 						copy_mp = NULL;
8366 						multirt_resolve_next = B_TRUE;
8367 						continue;
8368 					} else {
8369 						freemsg(copy_mp);
8370 					}
8371 				}
8372 			}
8373 			if (ipif != NULL)
8374 				ipif_refrele(ipif);
8375 			ill_refrele(dst_ill);
8376 			ipif_refrele(src_ipif);
8377 			return;
8378 		default:
8379 			break;
8380 		}
8381 	} while (multirt_resolve_next);
8382 
8383 err_ret:
8384 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8385 	if (fire != NULL)
8386 		ire_refrele(fire);
8387 	ipif_refrele(ipif);
8388 	/* Did this packet originate externally? */
8389 	if (dst_ill != NULL)
8390 		ill_refrele(dst_ill);
8391 	if (src_ipif != NULL)
8392 		ipif_refrele(src_ipif);
8393 	if (mp->b_prev || mp->b_next) {
8394 		mp->b_next = NULL;
8395 		mp->b_prev = NULL;
8396 	} else {
8397 		/*
8398 		 * Since ip_wput() isn't close to finished, we fill
8399 		 * in enough of the header for credible error reporting.
8400 		 */
8401 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8402 			/* Failed */
8403 			freemsg(first_mp);
8404 			if (ire != NULL)
8405 				ire_refrele(ire);
8406 			return;
8407 		}
8408 	}
8409 	/*
8410 	 * At this point we will have ire only if RTF_BLACKHOLE
8411 	 * or RTF_REJECT flags are set on the IRE. It will not
8412 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8413 	 */
8414 	if (ire != NULL) {
8415 		if (ire->ire_flags & RTF_BLACKHOLE) {
8416 			ire_refrele(ire);
8417 			freemsg(first_mp);
8418 			return;
8419 		}
8420 		ire_refrele(ire);
8421 	}
8422 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8423 }
8424 
8425 /* Name/Value Table Lookup Routine */
8426 char *
8427 ip_nv_lookup(nv_t *nv, int value)
8428 {
8429 	if (!nv)
8430 		return (NULL);
8431 	for (; nv->nv_name; nv++) {
8432 		if (nv->nv_value == value)
8433 			return (nv->nv_name);
8434 	}
8435 	return ("unknown");
8436 }
8437 
8438 /*
8439  * one day it can be patched to 1 from /etc/system for machines that have few
8440  * fast network interfaces feeding multiple cpus.
8441  */
8442 int ill_stream_putlocks = 0;
8443 
8444 /*
8445  * This is a module open, i.e. this is a control stream for access
8446  * to a DLPI device.  We allocate an ill_t as the instance data in
8447  * this case.
8448  */
8449 int
8450 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8451 {
8452 	uint32_t mem_cnt;
8453 	uint32_t cpu_cnt;
8454 	uint32_t min_cnt;
8455 	pgcnt_t mem_avail;
8456 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8457 	ill_t	*ill;
8458 	int	err;
8459 
8460 	/*
8461 	 * Prevent unprivileged processes from pushing IP so that
8462 	 * they can't send raw IP.
8463 	 */
8464 	if (secpolicy_net_rawaccess(credp) != 0)
8465 		return (EPERM);
8466 
8467 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8468 	q->q_ptr = WR(q)->q_ptr = ill;
8469 
8470 	/*
8471 	 * ill_init initializes the ill fields and then sends down
8472 	 * down a DL_INFO_REQ after calling qprocson.
8473 	 */
8474 	err = ill_init(q, ill);
8475 	if (err != 0) {
8476 		mi_free(ill);
8477 		q->q_ptr = NULL;
8478 		WR(q)->q_ptr = NULL;
8479 		return (err);
8480 	}
8481 
8482 	/* ill_init initializes the ipsq marking this thread as writer */
8483 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8484 	/* Wait for the DL_INFO_ACK */
8485 	mutex_enter(&ill->ill_lock);
8486 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8487 		/*
8488 		 * Return value of 0 indicates a pending signal.
8489 		 */
8490 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8491 		if (err == 0) {
8492 			mutex_exit(&ill->ill_lock);
8493 			(void) ip_close(q, 0);
8494 			return (EINTR);
8495 		}
8496 	}
8497 	mutex_exit(&ill->ill_lock);
8498 
8499 	/*
8500 	 * ip_rput_other could have set an error  in ill_error on
8501 	 * receipt of M_ERROR.
8502 	 */
8503 
8504 	err = ill->ill_error;
8505 	if (err != 0) {
8506 		(void) ip_close(q, 0);
8507 		return (err);
8508 	}
8509 
8510 	/*
8511 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8512 	 * size and the cpu speed of the machine. This is upper
8513 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8514 	 * and is lower bounded by the compile time value of
8515 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8516 	 * ip6_ire_max_bucket_cnt.
8517 	 */
8518 	mem_avail = kmem_avail();
8519 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8520 	    ip_cache_table_size / sizeof (ire_t);
8521 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8522 
8523 	min_cnt = MIN(cpu_cnt, mem_cnt);
8524 	if (min_cnt < ip_ire_min_bucket_cnt)
8525 		min_cnt = ip_ire_min_bucket_cnt;
8526 	if (ip_ire_max_bucket_cnt > min_cnt) {
8527 		ip_ire_max_bucket_cnt = min_cnt;
8528 	}
8529 
8530 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8531 	    ip6_cache_table_size / sizeof (ire_t);
8532 	min_cnt = MIN(cpu_cnt, mem_cnt);
8533 	if (min_cnt < ip6_ire_min_bucket_cnt)
8534 		min_cnt = ip6_ire_min_bucket_cnt;
8535 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8536 		ip6_ire_max_bucket_cnt = min_cnt;
8537 	}
8538 
8539 	ill->ill_credp = credp;
8540 	crhold(credp);
8541 
8542 	mutex_enter(&ip_mi_lock);
8543 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8544 	mutex_exit(&ip_mi_lock);
8545 	if (err) {
8546 		(void) ip_close(q, 0);
8547 		return (err);
8548 	}
8549 	return (0);
8550 }
8551 
8552 /* IP open routine. */
8553 int
8554 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8555 {
8556 	conn_t 		*connp;
8557 	major_t		maj;
8558 
8559 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8560 
8561 	/* Allow reopen. */
8562 	if (q->q_ptr != NULL)
8563 		return (0);
8564 
8565 	if (sflag & MODOPEN) {
8566 		/* This is a module open */
8567 		return (ip_modopen(q, devp, flag, sflag, credp));
8568 	}
8569 
8570 	/*
8571 	 * We are opening as a device. This is an IP client stream, and we
8572 	 * allocate an conn_t as the instance data.
8573 	 */
8574 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8575 	connp->conn_upq = q;
8576 	q->q_ptr = WR(q)->q_ptr = connp;
8577 
8578 	if (flag & SO_SOCKSTR)
8579 		connp->conn_flags |= IPCL_SOCKET;
8580 
8581 	/* Minor tells us which /dev entry was opened */
8582 	if (geteminor(*devp) == IPV6_MINOR) {
8583 		connp->conn_flags |= IPCL_ISV6;
8584 		connp->conn_af_isv6 = B_TRUE;
8585 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8586 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8587 	} else {
8588 		connp->conn_af_isv6 = B_FALSE;
8589 		connp->conn_pkt_isv6 = B_FALSE;
8590 	}
8591 
8592 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
8593 		q->q_ptr = WR(q)->q_ptr = NULL;
8594 		CONN_DEC_REF(connp);
8595 		return (EBUSY);
8596 	}
8597 
8598 	maj = getemajor(*devp);
8599 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8600 
8601 	/*
8602 	 * connp->conn_cred is crfree()ed in ip_close().
8603 	 */
8604 	connp->conn_cred = credp;
8605 	crhold(connp->conn_cred);
8606 
8607 	connp->conn_zoneid = getzoneid();
8608 
8609 	/*
8610 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8611 	 * administrative ops.  In these cases, we just need a normal conn_t
8612 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8613 	 * an error will be returned.
8614 	 */
8615 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8616 		connp->conn_rq = q;
8617 		connp->conn_wq = WR(q);
8618 	} else {
8619 		connp->conn_ulp = IPPROTO_SCTP;
8620 		connp->conn_rq = connp->conn_wq = NULL;
8621 	}
8622 	/* Non-zero default values */
8623 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8624 
8625 	/*
8626 	 * Make the conn globally visible to walkers
8627 	 */
8628 	mutex_enter(&connp->conn_lock);
8629 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8630 	mutex_exit(&connp->conn_lock);
8631 	ASSERT(connp->conn_ref == 1);
8632 
8633 	qprocson(q);
8634 
8635 	return (0);
8636 }
8637 
8638 /*
8639  * Change q_qinfo based on the value of isv6.
8640  * This can not called on an ill queue.
8641  * Note that there is no race since either q_qinfo works for conn queues - it
8642  * is just an optimization to enter the best wput routine directly.
8643  */
8644 void
8645 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8646 {
8647 	ASSERT(q->q_flag & QREADR);
8648 	ASSERT(WR(q)->q_next == NULL);
8649 	ASSERT(q->q_ptr != NULL);
8650 
8651 	if (minor == IPV6_MINOR)  {
8652 		if (bump_mib)
8653 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8654 		q->q_qinfo = &rinit_ipv6;
8655 		WR(q)->q_qinfo = &winit_ipv6;
8656 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8657 	} else {
8658 		if (bump_mib)
8659 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8660 		q->q_qinfo = &rinit;
8661 		WR(q)->q_qinfo = &winit;
8662 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8663 	}
8664 
8665 }
8666 
8667 /*
8668  * See if IPsec needs loading because of the options in mp.
8669  */
8670 static boolean_t
8671 ipsec_opt_present(mblk_t *mp)
8672 {
8673 	uint8_t *optcp, *next_optcp, *opt_endcp;
8674 	struct opthdr *opt;
8675 	struct T_opthdr *topt;
8676 	int opthdr_len;
8677 	t_uscalar_t optname, optlevel;
8678 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8679 	ipsec_req_t *ipsr;
8680 
8681 	/*
8682 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8683 	 * return TRUE.
8684 	 */
8685 
8686 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8687 	opt_endcp = optcp + tor->OPT_length;
8688 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8689 		opthdr_len = sizeof (struct T_opthdr);
8690 	} else {		/* O_OPTMGMT_REQ */
8691 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8692 		opthdr_len = sizeof (struct opthdr);
8693 	}
8694 	for (; optcp < opt_endcp; optcp = next_optcp) {
8695 		if (optcp + opthdr_len > opt_endcp)
8696 			return (B_FALSE);	/* Not enough option header. */
8697 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8698 			topt = (struct T_opthdr *)optcp;
8699 			optlevel = topt->level;
8700 			optname = topt->name;
8701 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8702 		} else {
8703 			opt = (struct opthdr *)optcp;
8704 			optlevel = opt->level;
8705 			optname = opt->name;
8706 			next_optcp = optcp + opthdr_len +
8707 			    _TPI_ALIGN_OPT(opt->len);
8708 		}
8709 		if ((next_optcp < optcp) || /* wraparound pointer space */
8710 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8711 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8712 			return (B_FALSE); /* bad option buffer */
8713 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8714 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8715 			/*
8716 			 * Check to see if it's an all-bypass or all-zeroes
8717 			 * IPsec request.  Don't bother loading IPsec if
8718 			 * the socket doesn't want to use it.  (A good example
8719 			 * is a bypass request.)
8720 			 *
8721 			 * Basically, if any of the non-NEVER bits are set,
8722 			 * load IPsec.
8723 			 */
8724 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8725 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8726 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8727 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8728 			    != 0)
8729 				return (B_TRUE);
8730 		}
8731 	}
8732 	return (B_FALSE);
8733 }
8734 
8735 /*
8736  * If conn is is waiting for ipsec to finish loading, kick it.
8737  */
8738 /* ARGSUSED */
8739 static void
8740 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8741 {
8742 	t_scalar_t	optreq_prim;
8743 	mblk_t		*mp;
8744 	cred_t		*cr;
8745 	int		err = 0;
8746 
8747 	/*
8748 	 * This function is called, after ipsec loading is complete.
8749 	 * Since IP checks exclusively and atomically (i.e it prevents
8750 	 * ipsec load from completing until ip_optcom_req completes)
8751 	 * whether ipsec load is complete, there cannot be a race with IP
8752 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8753 	 */
8754 	mutex_enter(&connp->conn_lock);
8755 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8756 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8757 		mp = connp->conn_ipsec_opt_mp;
8758 		connp->conn_ipsec_opt_mp = NULL;
8759 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8760 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8761 		mutex_exit(&connp->conn_lock);
8762 
8763 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8764 
8765 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8766 		if (optreq_prim == T_OPTMGMT_REQ) {
8767 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8768 			    &ip_opt_obj);
8769 		} else {
8770 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8771 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8772 			    &ip_opt_obj);
8773 		}
8774 		if (err != EINPROGRESS)
8775 			CONN_OPER_PENDING_DONE(connp);
8776 		return;
8777 	}
8778 	mutex_exit(&connp->conn_lock);
8779 }
8780 
8781 /*
8782  * Called from the ipsec_loader thread, outside any perimeter, to tell
8783  * ip qenable any of the queues waiting for the ipsec loader to
8784  * complete.
8785  *
8786  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8787  * are done with this lock held, so it's guaranteed that none of the
8788  * links will change along the way.
8789  */
8790 void
8791 ip_ipsec_load_complete()
8792 {
8793 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8794 }
8795 
8796 /*
8797  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8798  * determines the grp on which it has to become exclusive, queues the mp
8799  * and sq draining restarts the optmgmt
8800  */
8801 static boolean_t
8802 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8803 {
8804 	conn_t *connp;
8805 
8806 	/*
8807 	 * Take IPsec requests and treat them special.
8808 	 */
8809 	if (ipsec_opt_present(mp)) {
8810 		/* First check if IPsec is loaded. */
8811 		mutex_enter(&ipsec_loader_lock);
8812 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8813 			mutex_exit(&ipsec_loader_lock);
8814 			return (B_FALSE);
8815 		}
8816 		connp = Q_TO_CONN(q);
8817 		mutex_enter(&connp->conn_lock);
8818 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8819 
8820 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8821 		connp->conn_ipsec_opt_mp = mp;
8822 		mutex_exit(&connp->conn_lock);
8823 		mutex_exit(&ipsec_loader_lock);
8824 
8825 		ipsec_loader_loadnow();
8826 		return (B_TRUE);
8827 	}
8828 	return (B_FALSE);
8829 }
8830 
8831 /*
8832  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8833  * all of them are copied to the conn_t. If the req is "zero", the policy is
8834  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8835  * fields.
8836  * We keep only the latest setting of the policy and thus policy setting
8837  * is not incremental/cumulative.
8838  *
8839  * Requests to set policies with multiple alternative actions will
8840  * go through a different API.
8841  */
8842 int
8843 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8844 {
8845 	uint_t ah_req = 0;
8846 	uint_t esp_req = 0;
8847 	uint_t se_req = 0;
8848 	ipsec_selkey_t sel;
8849 	ipsec_act_t *actp = NULL;
8850 	uint_t nact;
8851 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8852 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8853 	ipsec_policy_root_t *pr;
8854 	ipsec_policy_head_t *ph;
8855 	int fam;
8856 	boolean_t is_pol_reset;
8857 	int error = 0;
8858 
8859 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8860 
8861 	/*
8862 	 * The IP_SEC_OPT option does not allow variable length parameters,
8863 	 * hence a request cannot be NULL.
8864 	 */
8865 	if (req == NULL)
8866 		return (EINVAL);
8867 
8868 	ah_req = req->ipsr_ah_req;
8869 	esp_req = req->ipsr_esp_req;
8870 	se_req = req->ipsr_self_encap_req;
8871 
8872 	/*
8873 	 * Are we dealing with a request to reset the policy (i.e.
8874 	 * zero requests).
8875 	 */
8876 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8877 	    (esp_req & REQ_MASK) == 0 &&
8878 	    (se_req & REQ_MASK) == 0);
8879 
8880 	if (!is_pol_reset) {
8881 		/*
8882 		 * If we couldn't load IPsec, fail with "protocol
8883 		 * not supported".
8884 		 * IPsec may not have been loaded for a request with zero
8885 		 * policies, so we don't fail in this case.
8886 		 */
8887 		mutex_enter(&ipsec_loader_lock);
8888 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8889 			mutex_exit(&ipsec_loader_lock);
8890 			return (EPROTONOSUPPORT);
8891 		}
8892 		mutex_exit(&ipsec_loader_lock);
8893 
8894 		/*
8895 		 * Test for valid requests. Invalid algorithms
8896 		 * need to be tested by IPSEC code because new
8897 		 * algorithms can be added dynamically.
8898 		 */
8899 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8900 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8901 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8902 			return (EINVAL);
8903 		}
8904 
8905 		/*
8906 		 * Only privileged users can issue these
8907 		 * requests.
8908 		 */
8909 		if (((ah_req & IPSEC_PREF_NEVER) ||
8910 		    (esp_req & IPSEC_PREF_NEVER) ||
8911 		    (se_req & IPSEC_PREF_NEVER)) &&
8912 		    secpolicy_net_config(cr, B_FALSE) != 0) {
8913 			return (EPERM);
8914 		}
8915 
8916 		/*
8917 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
8918 		 * are mutually exclusive.
8919 		 */
8920 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
8921 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
8922 		    ((se_req & REQ_MASK) == REQ_MASK)) {
8923 			/* Both of them are set */
8924 			return (EINVAL);
8925 		}
8926 	}
8927 
8928 	mutex_enter(&connp->conn_lock);
8929 
8930 	/*
8931 	 * If we have already cached policies in ip_bind_connected*(), don't
8932 	 * let them change now. We cache policies for connections
8933 	 * whose src,dst [addr, port] is known.  The exception to this is
8934 	 * tunnels.  Tunnels are allowed to change policies after having
8935 	 * become fully bound.
8936 	 */
8937 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
8938 		mutex_exit(&connp->conn_lock);
8939 		return (EINVAL);
8940 	}
8941 
8942 	/*
8943 	 * We have a zero policies, reset the connection policy if already
8944 	 * set. This will cause the connection to inherit the
8945 	 * global policy, if any.
8946 	 */
8947 	if (is_pol_reset) {
8948 		if (connp->conn_policy != NULL) {
8949 			IPPH_REFRELE(connp->conn_policy);
8950 			connp->conn_policy = NULL;
8951 		}
8952 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
8953 		connp->conn_in_enforce_policy = B_FALSE;
8954 		connp->conn_out_enforce_policy = B_FALSE;
8955 		mutex_exit(&connp->conn_lock);
8956 		return (0);
8957 	}
8958 
8959 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
8960 	if (ph == NULL)
8961 		goto enomem;
8962 
8963 	ipsec_actvec_from_req(req, &actp, &nact);
8964 	if (actp == NULL)
8965 		goto enomem;
8966 
8967 	/*
8968 	 * Always allocate IPv4 policy entries, since they can also
8969 	 * apply to ipv6 sockets being used in ipv4-compat mode.
8970 	 */
8971 	bzero(&sel, sizeof (sel));
8972 	sel.ipsl_valid = IPSL_IPV4;
8973 
8974 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8975 	if (pin4 == NULL)
8976 		goto enomem;
8977 
8978 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8979 	if (pout4 == NULL)
8980 		goto enomem;
8981 
8982 	if (connp->conn_pkt_isv6) {
8983 		/*
8984 		 * We're looking at a v6 socket, also allocate the
8985 		 * v6-specific entries...
8986 		 */
8987 		sel.ipsl_valid = IPSL_IPV6;
8988 		pin6 = ipsec_policy_create(&sel, actp, nact,
8989 		    IPSEC_PRIO_SOCKET);
8990 		if (pin6 == NULL)
8991 			goto enomem;
8992 
8993 		pout6 = ipsec_policy_create(&sel, actp, nact,
8994 		    IPSEC_PRIO_SOCKET);
8995 		if (pout6 == NULL)
8996 			goto enomem;
8997 
8998 		/*
8999 		 * .. and file them away in the right place.
9000 		 */
9001 		fam = IPSEC_AF_V6;
9002 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9003 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9004 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9005 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9006 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9007 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9008 	}
9009 
9010 	ipsec_actvec_free(actp, nact);
9011 
9012 	/*
9013 	 * File the v4 policies.
9014 	 */
9015 	fam = IPSEC_AF_V4;
9016 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9017 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9018 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9019 
9020 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9021 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9022 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9023 
9024 	/*
9025 	 * If the requests need security, set enforce_policy.
9026 	 * If the requests are IPSEC_PREF_NEVER, one should
9027 	 * still set conn_out_enforce_policy so that an ipsec_out
9028 	 * gets attached in ip_wput. This is needed so that
9029 	 * for connections that we don't cache policy in ip_bind,
9030 	 * if global policy matches in ip_wput_attach_policy, we
9031 	 * don't wrongly inherit global policy. Similarly, we need
9032 	 * to set conn_in_enforce_policy also so that we don't verify
9033 	 * policy wrongly.
9034 	 */
9035 	if ((ah_req & REQ_MASK) != 0 ||
9036 	    (esp_req & REQ_MASK) != 0 ||
9037 	    (se_req & REQ_MASK) != 0) {
9038 		connp->conn_in_enforce_policy = B_TRUE;
9039 		connp->conn_out_enforce_policy = B_TRUE;
9040 		connp->conn_flags |= IPCL_CHECK_POLICY;
9041 	}
9042 
9043 	/*
9044 	 * Tunnels are allowed to set policy after having been fully bound.
9045 	 * If that's the case, cache policy here.
9046 	 */
9047 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9048 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9049 
9050 	mutex_exit(&connp->conn_lock);
9051 	return (error);
9052 #undef REQ_MASK
9053 
9054 	/*
9055 	 * Common memory-allocation-failure exit path.
9056 	 */
9057 enomem:
9058 	mutex_exit(&connp->conn_lock);
9059 	if (actp != NULL)
9060 		ipsec_actvec_free(actp, nact);
9061 	if (pin4 != NULL)
9062 		IPPOL_REFRELE(pin4);
9063 	if (pout4 != NULL)
9064 		IPPOL_REFRELE(pout4);
9065 	if (pin6 != NULL)
9066 		IPPOL_REFRELE(pin6);
9067 	if (pout6 != NULL)
9068 		IPPOL_REFRELE(pout6);
9069 	return (ENOMEM);
9070 }
9071 
9072 /*
9073  * Only for options that pass in an IP addr. Currently only V4 options
9074  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9075  * So this function assumes level is IPPROTO_IP
9076  */
9077 int
9078 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9079     mblk_t *first_mp)
9080 {
9081 	ipif_t *ipif = NULL;
9082 	int error;
9083 	ill_t *ill;
9084 
9085 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9086 
9087 	if (addr != INADDR_ANY || checkonly) {
9088 		ASSERT(connp != NULL);
9089 		ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9090 		    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt, &error);
9091 		if (ipif == NULL) {
9092 			if (error == EINPROGRESS)
9093 				return (error);
9094 			else if (option == IP_MULTICAST_IF)
9095 				return (EHOSTUNREACH);
9096 			else
9097 				return (EINVAL);
9098 		} else if (checkonly) {
9099 			if (option == IP_MULTICAST_IF) {
9100 				ill = ipif->ipif_ill;
9101 				/* not supported by the virtual network iface */
9102 				if (IS_VNI(ill)) {
9103 					ipif_refrele(ipif);
9104 					return (EINVAL);
9105 				}
9106 			}
9107 			ipif_refrele(ipif);
9108 			return (0);
9109 		}
9110 		ill = ipif->ipif_ill;
9111 		mutex_enter(&connp->conn_lock);
9112 		mutex_enter(&ill->ill_lock);
9113 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9114 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9115 			mutex_exit(&ill->ill_lock);
9116 			mutex_exit(&connp->conn_lock);
9117 			ipif_refrele(ipif);
9118 			return (option == IP_MULTICAST_IF ?
9119 			    EHOSTUNREACH : EINVAL);
9120 		}
9121 	} else {
9122 		mutex_enter(&connp->conn_lock);
9123 	}
9124 
9125 	/* None of the options below are supported on the VNI */
9126 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9127 		mutex_exit(&ill->ill_lock);
9128 		mutex_exit(&connp->conn_lock);
9129 		ipif_refrele(ipif);
9130 		return (EINVAL);
9131 	}
9132 
9133 	switch (option) {
9134 	case IP_DONTFAILOVER_IF:
9135 		/*
9136 		 * This option is used by in.mpathd to ensure
9137 		 * that IPMP probe packets only go out on the
9138 		 * test interfaces. in.mpathd sets this option
9139 		 * on the non-failover interfaces.
9140 		 * For backward compatibility, this option
9141 		 * implicitly sets IP_MULTICAST_IF, as used
9142 		 * be done in bind(), so that ip_wput gets
9143 		 * this ipif to send mcast packets.
9144 		 */
9145 		if (ipif != NULL) {
9146 			ASSERT(addr != INADDR_ANY);
9147 			connp->conn_nofailover_ill = ipif->ipif_ill;
9148 			connp->conn_multicast_ipif = ipif;
9149 		} else {
9150 			ASSERT(addr == INADDR_ANY);
9151 			connp->conn_nofailover_ill = NULL;
9152 			connp->conn_multicast_ipif = NULL;
9153 		}
9154 		break;
9155 
9156 	case IP_MULTICAST_IF:
9157 		connp->conn_multicast_ipif = ipif;
9158 		break;
9159 	}
9160 
9161 	if (ipif != NULL) {
9162 		mutex_exit(&ill->ill_lock);
9163 		mutex_exit(&connp->conn_lock);
9164 		ipif_refrele(ipif);
9165 		return (0);
9166 	}
9167 	mutex_exit(&connp->conn_lock);
9168 	/* We succeded in cleared the option */
9169 	return (0);
9170 }
9171 
9172 /*
9173  * For options that pass in an ifindex specifying the ill. V6 options always
9174  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9175  */
9176 int
9177 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9178     int level, int option, mblk_t *first_mp)
9179 {
9180 	ill_t *ill = NULL;
9181 	int error = 0;
9182 
9183 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9184 	if (ifindex != 0) {
9185 		ASSERT(connp != NULL);
9186 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9187 		    first_mp, ip_restart_optmgmt, &error);
9188 		if (ill != NULL) {
9189 			if (checkonly) {
9190 				/* not supported by the virtual network iface */
9191 				if (IS_VNI(ill)) {
9192 					ill_refrele(ill);
9193 					return (EINVAL);
9194 				}
9195 				ill_refrele(ill);
9196 				return (0);
9197 			}
9198 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9199 			    0, NULL)) {
9200 				ill_refrele(ill);
9201 				ill = NULL;
9202 				mutex_enter(&connp->conn_lock);
9203 				goto setit;
9204 			}
9205 			mutex_enter(&connp->conn_lock);
9206 			mutex_enter(&ill->ill_lock);
9207 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9208 				mutex_exit(&ill->ill_lock);
9209 				mutex_exit(&connp->conn_lock);
9210 				ill_refrele(ill);
9211 				ill = NULL;
9212 				mutex_enter(&connp->conn_lock);
9213 			}
9214 			goto setit;
9215 		} else if (error == EINPROGRESS) {
9216 			return (error);
9217 		} else {
9218 			error = 0;
9219 		}
9220 	}
9221 	mutex_enter(&connp->conn_lock);
9222 setit:
9223 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9224 
9225 	/*
9226 	 * The options below assume that the ILL (if any) transmits and/or
9227 	 * receives traffic. Neither of which is true for the virtual network
9228 	 * interface, so fail setting these on a VNI.
9229 	 */
9230 	if (IS_VNI(ill)) {
9231 		ASSERT(ill != NULL);
9232 		mutex_exit(&ill->ill_lock);
9233 		mutex_exit(&connp->conn_lock);
9234 		ill_refrele(ill);
9235 		return (EINVAL);
9236 	}
9237 
9238 	if (level == IPPROTO_IP) {
9239 		switch (option) {
9240 		case IP_BOUND_IF:
9241 			connp->conn_incoming_ill = ill;
9242 			connp->conn_outgoing_ill = ill;
9243 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9244 			    0 : ifindex;
9245 			break;
9246 
9247 		case IP_XMIT_IF:
9248 			/*
9249 			 * Similar to IP_BOUND_IF, but this only
9250 			 * determines the outgoing interface for
9251 			 * unicast packets. Also no IRE_CACHE entry
9252 			 * is added for the destination of the
9253 			 * outgoing packets. This feature is needed
9254 			 * for mobile IP.
9255 			 */
9256 			connp->conn_xmit_if_ill = ill;
9257 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9258 			    0 : ifindex;
9259 			break;
9260 
9261 		case IP_MULTICAST_IF:
9262 			/*
9263 			 * This option is an internal special. The socket
9264 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9265 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9266 			 * specifies an ifindex and we try first on V6 ill's.
9267 			 * If we don't find one, we they try using on v4 ill's
9268 			 * intenally and we come here.
9269 			 */
9270 			if (!checkonly && ill != NULL) {
9271 				ipif_t	*ipif;
9272 				ipif = ill->ill_ipif;
9273 
9274 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9275 					mutex_exit(&ill->ill_lock);
9276 					mutex_exit(&connp->conn_lock);
9277 					ill_refrele(ill);
9278 					ill = NULL;
9279 					mutex_enter(&connp->conn_lock);
9280 				} else {
9281 					connp->conn_multicast_ipif = ipif;
9282 				}
9283 			}
9284 			break;
9285 		}
9286 	} else {
9287 		switch (option) {
9288 		case IPV6_BOUND_IF:
9289 			connp->conn_incoming_ill = ill;
9290 			connp->conn_outgoing_ill = ill;
9291 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9292 			    0 : ifindex;
9293 			break;
9294 
9295 		case IPV6_BOUND_PIF:
9296 			/*
9297 			 * Limit all transmit to this ill.
9298 			 * Unlike IPV6_BOUND_IF, using this option
9299 			 * prevents load spreading and failover from
9300 			 * happening when the interface is part of the
9301 			 * group. That's why we don't need to remember
9302 			 * the ifindex in orig_bound_ifindex as in
9303 			 * IPV6_BOUND_IF.
9304 			 */
9305 			connp->conn_outgoing_pill = ill;
9306 			break;
9307 
9308 		case IPV6_DONTFAILOVER_IF:
9309 			/*
9310 			 * This option is used by in.mpathd to ensure
9311 			 * that IPMP probe packets only go out on the
9312 			 * test interfaces. in.mpathd sets this option
9313 			 * on the non-failover interfaces.
9314 			 */
9315 			connp->conn_nofailover_ill = ill;
9316 			/*
9317 			 * For backward compatibility, this option
9318 			 * implicitly sets ip_multicast_ill as used in
9319 			 * IP_MULTICAST_IF so that ip_wput gets
9320 			 * this ipif to send mcast packets.
9321 			 */
9322 			connp->conn_multicast_ill = ill;
9323 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9324 			    0 : ifindex;
9325 			break;
9326 
9327 		case IPV6_MULTICAST_IF:
9328 			/*
9329 			 * Set conn_multicast_ill to be the IPv6 ill.
9330 			 * Set conn_multicast_ipif to be an IPv4 ipif
9331 			 * for ifindex to make IPv4 mapped addresses
9332 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9333 			 * Even if no IPv6 ill exists for the ifindex
9334 			 * we need to check for an IPv4 ifindex in order
9335 			 * for this to work with mapped addresses. In that
9336 			 * case only set conn_multicast_ipif.
9337 			 */
9338 			if (!checkonly) {
9339 				if (ifindex == 0) {
9340 					connp->conn_multicast_ill = NULL;
9341 					connp->conn_orig_multicast_ifindex = 0;
9342 					connp->conn_multicast_ipif = NULL;
9343 				} else if (ill != NULL) {
9344 					connp->conn_multicast_ill = ill;
9345 					connp->conn_orig_multicast_ifindex =
9346 					    ifindex;
9347 				}
9348 			}
9349 			break;
9350 		}
9351 	}
9352 
9353 	if (ill != NULL) {
9354 		mutex_exit(&ill->ill_lock);
9355 		mutex_exit(&connp->conn_lock);
9356 		ill_refrele(ill);
9357 		return (0);
9358 	}
9359 	mutex_exit(&connp->conn_lock);
9360 	/*
9361 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9362 	 * locate the ill and could not set the option (ifindex != 0)
9363 	 */
9364 	return (ifindex == 0 ? 0 : EINVAL);
9365 }
9366 
9367 /* This routine sets socket options. */
9368 /* ARGSUSED */
9369 int
9370 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9371     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9372     void *dummy, cred_t *cr, mblk_t *first_mp)
9373 {
9374 	int		*i1 = (int *)invalp;
9375 	conn_t		*connp = Q_TO_CONN(q);
9376 	int		error = 0;
9377 	boolean_t	checkonly;
9378 	ire_t		*ire;
9379 	boolean_t	found;
9380 
9381 	switch (optset_context) {
9382 
9383 	case SETFN_OPTCOM_CHECKONLY:
9384 		checkonly = B_TRUE;
9385 		/*
9386 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9387 		 * inlen != 0 implies value supplied and
9388 		 * 	we have to "pretend" to set it.
9389 		 * inlen == 0 implies that there is no
9390 		 * 	value part in T_CHECK request and just validation
9391 		 * done elsewhere should be enough, we just return here.
9392 		 */
9393 		if (inlen == 0) {
9394 			*outlenp = 0;
9395 			return (0);
9396 		}
9397 		break;
9398 	case SETFN_OPTCOM_NEGOTIATE:
9399 	case SETFN_UD_NEGOTIATE:
9400 	case SETFN_CONN_NEGOTIATE:
9401 		checkonly = B_FALSE;
9402 		break;
9403 	default:
9404 		/*
9405 		 * We should never get here
9406 		 */
9407 		*outlenp = 0;
9408 		return (EINVAL);
9409 	}
9410 
9411 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9412 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9413 
9414 	/*
9415 	 * For fixed length options, no sanity check
9416 	 * of passed in length is done. It is assumed *_optcom_req()
9417 	 * routines do the right thing.
9418 	 */
9419 
9420 	switch (level) {
9421 	case SOL_SOCKET:
9422 		/*
9423 		 * conn_lock protects the bitfields, and is used to
9424 		 * set the fields atomically.
9425 		 */
9426 		switch (name) {
9427 		case SO_BROADCAST:
9428 			if (!checkonly) {
9429 				/* TODO: use value someplace? */
9430 				mutex_enter(&connp->conn_lock);
9431 				connp->conn_broadcast = *i1 ? 1 : 0;
9432 				mutex_exit(&connp->conn_lock);
9433 			}
9434 			break;	/* goto sizeof (int) option return */
9435 		case SO_USELOOPBACK:
9436 			if (!checkonly) {
9437 				/* TODO: use value someplace? */
9438 				mutex_enter(&connp->conn_lock);
9439 				connp->conn_loopback = *i1 ? 1 : 0;
9440 				mutex_exit(&connp->conn_lock);
9441 			}
9442 			break;	/* goto sizeof (int) option return */
9443 		case SO_DONTROUTE:
9444 			if (!checkonly) {
9445 				mutex_enter(&connp->conn_lock);
9446 				connp->conn_dontroute = *i1 ? 1 : 0;
9447 				mutex_exit(&connp->conn_lock);
9448 			}
9449 			break;	/* goto sizeof (int) option return */
9450 		case SO_REUSEADDR:
9451 			if (!checkonly) {
9452 				mutex_enter(&connp->conn_lock);
9453 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9454 				mutex_exit(&connp->conn_lock);
9455 			}
9456 			break;	/* goto sizeof (int) option return */
9457 		case SO_PROTOTYPE:
9458 			if (!checkonly) {
9459 				mutex_enter(&connp->conn_lock);
9460 				connp->conn_proto = *i1;
9461 				mutex_exit(&connp->conn_lock);
9462 			}
9463 			break;	/* goto sizeof (int) option return */
9464 		default:
9465 			/*
9466 			 * "soft" error (negative)
9467 			 * option not handled at this level
9468 			 * Note: Do not modify *outlenp
9469 			 */
9470 			return (-EINVAL);
9471 		}
9472 		break;
9473 	case IPPROTO_IP:
9474 		switch (name) {
9475 		case IP_MULTICAST_IF:
9476 		case IP_DONTFAILOVER_IF: {
9477 			ipaddr_t addr = *i1;
9478 
9479 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9480 			    first_mp);
9481 			if (error != 0)
9482 				return (error);
9483 			break;	/* goto sizeof (int) option return */
9484 		}
9485 
9486 		case IP_MULTICAST_TTL:
9487 			/* Recorded in transport above IP */
9488 			*outvalp = *invalp;
9489 			*outlenp = sizeof (uchar_t);
9490 			return (0);
9491 		case IP_MULTICAST_LOOP:
9492 			if (!checkonly) {
9493 				mutex_enter(&connp->conn_lock);
9494 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9495 				mutex_exit(&connp->conn_lock);
9496 			}
9497 			*outvalp = *invalp;
9498 			*outlenp = sizeof (uchar_t);
9499 			return (0);
9500 		case IP_ADD_MEMBERSHIP:
9501 		case MCAST_JOIN_GROUP:
9502 		case IP_DROP_MEMBERSHIP:
9503 		case MCAST_LEAVE_GROUP: {
9504 			struct ip_mreq *mreqp;
9505 			struct group_req *greqp;
9506 			ire_t *ire;
9507 			boolean_t done = B_FALSE;
9508 			ipaddr_t group, ifaddr;
9509 			struct sockaddr_in *sin;
9510 			uint32_t *ifindexp;
9511 			boolean_t mcast_opt = B_TRUE;
9512 			mcast_record_t fmode;
9513 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9514 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9515 
9516 			switch (name) {
9517 			case IP_ADD_MEMBERSHIP:
9518 				mcast_opt = B_FALSE;
9519 				/* FALLTHRU */
9520 			case MCAST_JOIN_GROUP:
9521 				fmode = MODE_IS_EXCLUDE;
9522 				optfn = ip_opt_add_group;
9523 				break;
9524 
9525 			case IP_DROP_MEMBERSHIP:
9526 				mcast_opt = B_FALSE;
9527 				/* FALLTHRU */
9528 			case MCAST_LEAVE_GROUP:
9529 				fmode = MODE_IS_INCLUDE;
9530 				optfn = ip_opt_delete_group;
9531 				break;
9532 			}
9533 
9534 			if (mcast_opt) {
9535 				greqp = (struct group_req *)i1;
9536 				sin = (struct sockaddr_in *)&greqp->gr_group;
9537 				if (sin->sin_family != AF_INET) {
9538 					*outlenp = 0;
9539 					return (ENOPROTOOPT);
9540 				}
9541 				group = (ipaddr_t)sin->sin_addr.s_addr;
9542 				ifaddr = INADDR_ANY;
9543 				ifindexp = &greqp->gr_interface;
9544 			} else {
9545 				mreqp = (struct ip_mreq *)i1;
9546 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9547 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9548 				ifindexp = NULL;
9549 			}
9550 
9551 			/*
9552 			 * In the multirouting case, we need to replicate
9553 			 * the request on all interfaces that will take part
9554 			 * in replication.  We do so because multirouting is
9555 			 * reflective, thus we will probably receive multi-
9556 			 * casts on those interfaces.
9557 			 * The ip_multirt_apply_membership() succeeds if the
9558 			 * operation succeeds on at least one interface.
9559 			 */
9560 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9561 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9562 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9563 			if (ire != NULL) {
9564 				if (ire->ire_flags & RTF_MULTIRT) {
9565 					error = ip_multirt_apply_membership(
9566 					    optfn, ire, connp, checkonly, group,
9567 					    fmode, INADDR_ANY, first_mp);
9568 					done = B_TRUE;
9569 				}
9570 				ire_refrele(ire);
9571 			}
9572 			if (!done) {
9573 				error = optfn(connp, checkonly, group, ifaddr,
9574 				    ifindexp, fmode, INADDR_ANY, first_mp);
9575 			}
9576 			if (error) {
9577 				/*
9578 				 * EINPROGRESS is a soft error, needs retry
9579 				 * so don't make *outlenp zero.
9580 				 */
9581 				if (error != EINPROGRESS)
9582 					*outlenp = 0;
9583 				return (error);
9584 			}
9585 			/* OK return - copy input buffer into output buffer */
9586 			if (invalp != outvalp) {
9587 				/* don't trust bcopy for identical src/dst */
9588 				bcopy(invalp, outvalp, inlen);
9589 			}
9590 			*outlenp = inlen;
9591 			return (0);
9592 		}
9593 		case IP_BLOCK_SOURCE:
9594 		case IP_UNBLOCK_SOURCE:
9595 		case IP_ADD_SOURCE_MEMBERSHIP:
9596 		case IP_DROP_SOURCE_MEMBERSHIP:
9597 		case MCAST_BLOCK_SOURCE:
9598 		case MCAST_UNBLOCK_SOURCE:
9599 		case MCAST_JOIN_SOURCE_GROUP:
9600 		case MCAST_LEAVE_SOURCE_GROUP: {
9601 			struct ip_mreq_source *imreqp;
9602 			struct group_source_req *gsreqp;
9603 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9604 			uint32_t ifindex = 0;
9605 			mcast_record_t fmode;
9606 			struct sockaddr_in *sin;
9607 			ire_t *ire;
9608 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9609 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9610 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9611 
9612 			switch (name) {
9613 			case IP_BLOCK_SOURCE:
9614 				mcast_opt = B_FALSE;
9615 				/* FALLTHRU */
9616 			case MCAST_BLOCK_SOURCE:
9617 				fmode = MODE_IS_EXCLUDE;
9618 				optfn = ip_opt_add_group;
9619 				break;
9620 
9621 			case IP_UNBLOCK_SOURCE:
9622 				mcast_opt = B_FALSE;
9623 				/* FALLTHRU */
9624 			case MCAST_UNBLOCK_SOURCE:
9625 				fmode = MODE_IS_EXCLUDE;
9626 				optfn = ip_opt_delete_group;
9627 				break;
9628 
9629 			case IP_ADD_SOURCE_MEMBERSHIP:
9630 				mcast_opt = B_FALSE;
9631 				/* FALLTHRU */
9632 			case MCAST_JOIN_SOURCE_GROUP:
9633 				fmode = MODE_IS_INCLUDE;
9634 				optfn = ip_opt_add_group;
9635 				break;
9636 
9637 			case IP_DROP_SOURCE_MEMBERSHIP:
9638 				mcast_opt = B_FALSE;
9639 				/* FALLTHRU */
9640 			case MCAST_LEAVE_SOURCE_GROUP:
9641 				fmode = MODE_IS_INCLUDE;
9642 				optfn = ip_opt_delete_group;
9643 				break;
9644 			}
9645 
9646 			if (mcast_opt) {
9647 				gsreqp = (struct group_source_req *)i1;
9648 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9649 					*outlenp = 0;
9650 					return (ENOPROTOOPT);
9651 				}
9652 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9653 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9654 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9655 				src = (ipaddr_t)sin->sin_addr.s_addr;
9656 				ifindex = gsreqp->gsr_interface;
9657 			} else {
9658 				imreqp = (struct ip_mreq_source *)i1;
9659 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9660 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9661 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9662 			}
9663 
9664 			/*
9665 			 * In the multirouting case, we need to replicate
9666 			 * the request as noted in the mcast cases above.
9667 			 */
9668 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9669 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9670 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9671 			if (ire != NULL) {
9672 				if (ire->ire_flags & RTF_MULTIRT) {
9673 					error = ip_multirt_apply_membership(
9674 					    optfn, ire, connp, checkonly, grp,
9675 					    fmode, src, first_mp);
9676 					done = B_TRUE;
9677 				}
9678 				ire_refrele(ire);
9679 			}
9680 			if (!done) {
9681 				error = optfn(connp, checkonly, grp, ifaddr,
9682 				    &ifindex, fmode, src, first_mp);
9683 			}
9684 			if (error != 0) {
9685 				/*
9686 				 * EINPROGRESS is a soft error, needs retry
9687 				 * so don't make *outlenp zero.
9688 				 */
9689 				if (error != EINPROGRESS)
9690 					*outlenp = 0;
9691 				return (error);
9692 			}
9693 			/* OK return - copy input buffer into output buffer */
9694 			if (invalp != outvalp) {
9695 				bcopy(invalp, outvalp, inlen);
9696 			}
9697 			*outlenp = inlen;
9698 			return (0);
9699 		}
9700 		case IP_SEC_OPT:
9701 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9702 			if (error != 0) {
9703 				*outlenp = 0;
9704 				return (error);
9705 			}
9706 			break;
9707 		case IP_HDRINCL:
9708 		case IP_OPTIONS:
9709 		case T_IP_OPTIONS:
9710 		case IP_TOS:
9711 		case T_IP_TOS:
9712 		case IP_TTL:
9713 		case IP_RECVDSTADDR:
9714 		case IP_RECVOPTS:
9715 			/* OK return - copy input buffer into output buffer */
9716 			if (invalp != outvalp) {
9717 				/* don't trust bcopy for identical src/dst */
9718 				bcopy(invalp, outvalp, inlen);
9719 			}
9720 			*outlenp = inlen;
9721 			return (0);
9722 		case IP_RECVIF:
9723 			/* Retrieve the inbound interface index */
9724 			if (!checkonly) {
9725 				mutex_enter(&connp->conn_lock);
9726 				connp->conn_recvif = *i1 ? 1 : 0;
9727 				mutex_exit(&connp->conn_lock);
9728 			}
9729 			break;	/* goto sizeof (int) option return */
9730 		case IP_RECVSLLA:
9731 			/* Retrieve the source link layer address */
9732 			if (!checkonly) {
9733 				mutex_enter(&connp->conn_lock);
9734 				connp->conn_recvslla = *i1 ? 1 : 0;
9735 				mutex_exit(&connp->conn_lock);
9736 			}
9737 			break;	/* goto sizeof (int) option return */
9738 		case MRT_INIT:
9739 		case MRT_DONE:
9740 		case MRT_ADD_VIF:
9741 		case MRT_DEL_VIF:
9742 		case MRT_ADD_MFC:
9743 		case MRT_DEL_MFC:
9744 		case MRT_ASSERT:
9745 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9746 				*outlenp = 0;
9747 				return (error);
9748 			}
9749 			error = ip_mrouter_set((int)name, q, checkonly,
9750 			    (uchar_t *)invalp, inlen, first_mp);
9751 			if (error) {
9752 				*outlenp = 0;
9753 				return (error);
9754 			}
9755 			/* OK return - copy input buffer into output buffer */
9756 			if (invalp != outvalp) {
9757 				/* don't trust bcopy for identical src/dst */
9758 				bcopy(invalp, outvalp, inlen);
9759 			}
9760 			*outlenp = inlen;
9761 			return (0);
9762 		case IP_BOUND_IF:
9763 		case IP_XMIT_IF:
9764 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9765 			    level, name, first_mp);
9766 			if (error != 0)
9767 				return (error);
9768 			break; 		/* goto sizeof (int) option return */
9769 
9770 		case IP_UNSPEC_SRC:
9771 			/* Allow sending with a zero source address */
9772 			if (!checkonly) {
9773 				mutex_enter(&connp->conn_lock);
9774 				connp->conn_unspec_src = *i1 ? 1 : 0;
9775 				mutex_exit(&connp->conn_lock);
9776 			}
9777 			break;	/* goto sizeof (int) option return */
9778 		default:
9779 			/*
9780 			 * "soft" error (negative)
9781 			 * option not handled at this level
9782 			 * Note: Do not modify *outlenp
9783 			 */
9784 			return (-EINVAL);
9785 		}
9786 		break;
9787 	case IPPROTO_IPV6:
9788 		switch (name) {
9789 		case IPV6_BOUND_IF:
9790 		case IPV6_BOUND_PIF:
9791 		case IPV6_DONTFAILOVER_IF:
9792 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9793 			    level, name, first_mp);
9794 			if (error != 0)
9795 				return (error);
9796 			break; 		/* goto sizeof (int) option return */
9797 
9798 		case IPV6_MULTICAST_IF:
9799 			/*
9800 			 * The only possible errors are EINPROGRESS and
9801 			 * EINVAL. EINPROGRESS will be restarted and is not
9802 			 * a hard error. We call this option on both V4 and V6
9803 			 * If both return EINVAL, then this call returns
9804 			 * EINVAL. If at least one of them succeeds we
9805 			 * return success.
9806 			 */
9807 			found = B_FALSE;
9808 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9809 			    level, name, first_mp);
9810 			if (error == EINPROGRESS)
9811 				return (error);
9812 			if (error == 0)
9813 				found = B_TRUE;
9814 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9815 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9816 			if (error == 0)
9817 				found = B_TRUE;
9818 			if (!found)
9819 				return (error);
9820 			break; 		/* goto sizeof (int) option return */
9821 
9822 		case IPV6_MULTICAST_HOPS:
9823 			/* Recorded in transport above IP */
9824 			break;	/* goto sizeof (int) option return */
9825 		case IPV6_MULTICAST_LOOP:
9826 			if (!checkonly) {
9827 				mutex_enter(&connp->conn_lock);
9828 				connp->conn_multicast_loop = *i1;
9829 				mutex_exit(&connp->conn_lock);
9830 			}
9831 			break;	/* goto sizeof (int) option return */
9832 		case IPV6_JOIN_GROUP:
9833 		case MCAST_JOIN_GROUP:
9834 		case IPV6_LEAVE_GROUP:
9835 		case MCAST_LEAVE_GROUP: {
9836 			struct ipv6_mreq *ip_mreqp;
9837 			struct group_req *greqp;
9838 			ire_t *ire;
9839 			boolean_t done = B_FALSE;
9840 			in6_addr_t groupv6;
9841 			uint32_t ifindex;
9842 			boolean_t mcast_opt = B_TRUE;
9843 			mcast_record_t fmode;
9844 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9845 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9846 
9847 			switch (name) {
9848 			case IPV6_JOIN_GROUP:
9849 				mcast_opt = B_FALSE;
9850 				/* FALLTHRU */
9851 			case MCAST_JOIN_GROUP:
9852 				fmode = MODE_IS_EXCLUDE;
9853 				optfn = ip_opt_add_group_v6;
9854 				break;
9855 
9856 			case IPV6_LEAVE_GROUP:
9857 				mcast_opt = B_FALSE;
9858 				/* FALLTHRU */
9859 			case MCAST_LEAVE_GROUP:
9860 				fmode = MODE_IS_INCLUDE;
9861 				optfn = ip_opt_delete_group_v6;
9862 				break;
9863 			}
9864 
9865 			if (mcast_opt) {
9866 				struct sockaddr_in *sin;
9867 				struct sockaddr_in6 *sin6;
9868 				greqp = (struct group_req *)i1;
9869 				if (greqp->gr_group.ss_family == AF_INET) {
9870 					sin = (struct sockaddr_in *)
9871 					    &(greqp->gr_group);
9872 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9873 					    &groupv6);
9874 				} else {
9875 					sin6 = (struct sockaddr_in6 *)
9876 					    &(greqp->gr_group);
9877 					groupv6 = sin6->sin6_addr;
9878 				}
9879 				ifindex = greqp->gr_interface;
9880 			} else {
9881 				ip_mreqp = (struct ipv6_mreq *)i1;
9882 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9883 				ifindex = ip_mreqp->ipv6mr_interface;
9884 			}
9885 			/*
9886 			 * In the multirouting case, we need to replicate
9887 			 * the request on all interfaces that will take part
9888 			 * in replication.  We do so because multirouting is
9889 			 * reflective, thus we will probably receive multi-
9890 			 * casts on those interfaces.
9891 			 * The ip_multirt_apply_membership_v6() succeeds if
9892 			 * the operation succeeds on at least one interface.
9893 			 */
9894 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9895 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9896 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9897 			if (ire != NULL) {
9898 				if (ire->ire_flags & RTF_MULTIRT) {
9899 					error = ip_multirt_apply_membership_v6(
9900 					    optfn, ire, connp, checkonly,
9901 					    &groupv6, fmode, &ipv6_all_zeros,
9902 					    first_mp);
9903 					done = B_TRUE;
9904 				}
9905 				ire_refrele(ire);
9906 			}
9907 			if (!done) {
9908 				error = optfn(connp, checkonly, &groupv6,
9909 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
9910 			}
9911 			if (error) {
9912 				/*
9913 				 * EINPROGRESS is a soft error, needs retry
9914 				 * so don't make *outlenp zero.
9915 				 */
9916 				if (error != EINPROGRESS)
9917 					*outlenp = 0;
9918 				return (error);
9919 			}
9920 			/* OK return - copy input buffer into output buffer */
9921 			if (invalp != outvalp) {
9922 				/* don't trust bcopy for identical src/dst */
9923 				bcopy(invalp, outvalp, inlen);
9924 			}
9925 			*outlenp = inlen;
9926 			return (0);
9927 		}
9928 		case MCAST_BLOCK_SOURCE:
9929 		case MCAST_UNBLOCK_SOURCE:
9930 		case MCAST_JOIN_SOURCE_GROUP:
9931 		case MCAST_LEAVE_SOURCE_GROUP: {
9932 			struct group_source_req *gsreqp;
9933 			in6_addr_t v6grp, v6src;
9934 			uint32_t ifindex;
9935 			mcast_record_t fmode;
9936 			ire_t *ire;
9937 			boolean_t done = B_FALSE;
9938 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9939 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9940 
9941 			switch (name) {
9942 			case MCAST_BLOCK_SOURCE:
9943 				fmode = MODE_IS_EXCLUDE;
9944 				optfn = ip_opt_add_group_v6;
9945 				break;
9946 			case MCAST_UNBLOCK_SOURCE:
9947 				fmode = MODE_IS_EXCLUDE;
9948 				optfn = ip_opt_delete_group_v6;
9949 				break;
9950 			case MCAST_JOIN_SOURCE_GROUP:
9951 				fmode = MODE_IS_INCLUDE;
9952 				optfn = ip_opt_add_group_v6;
9953 				break;
9954 			case MCAST_LEAVE_SOURCE_GROUP:
9955 				fmode = MODE_IS_INCLUDE;
9956 				optfn = ip_opt_delete_group_v6;
9957 				break;
9958 			}
9959 
9960 			gsreqp = (struct group_source_req *)i1;
9961 			ifindex = gsreqp->gsr_interface;
9962 			if (gsreqp->gsr_group.ss_family == AF_INET) {
9963 				struct sockaddr_in *s;
9964 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
9965 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
9966 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
9967 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
9968 			} else {
9969 				struct sockaddr_in6 *s6;
9970 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
9971 				v6grp = s6->sin6_addr;
9972 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
9973 				v6src = s6->sin6_addr;
9974 			}
9975 
9976 			/*
9977 			 * In the multirouting case, we need to replicate
9978 			 * the request as noted in the mcast cases above.
9979 			 */
9980 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
9981 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9982 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9983 			if (ire != NULL) {
9984 				if (ire->ire_flags & RTF_MULTIRT) {
9985 					error = ip_multirt_apply_membership_v6(
9986 					    optfn, ire, connp, checkonly,
9987 					    &v6grp, fmode, &v6src, first_mp);
9988 					done = B_TRUE;
9989 				}
9990 				ire_refrele(ire);
9991 			}
9992 			if (!done) {
9993 				error = optfn(connp, checkonly, &v6grp,
9994 				    ifindex, fmode, &v6src, first_mp);
9995 			}
9996 			if (error != 0) {
9997 				/*
9998 				 * EINPROGRESS is a soft error, needs retry
9999 				 * so don't make *outlenp zero.
10000 				 */
10001 				if (error != EINPROGRESS)
10002 					*outlenp = 0;
10003 				return (error);
10004 			}
10005 			/* OK return - copy input buffer into output buffer */
10006 			if (invalp != outvalp) {
10007 				bcopy(invalp, outvalp, inlen);
10008 			}
10009 			*outlenp = inlen;
10010 			return (0);
10011 		}
10012 		case IPV6_UNICAST_HOPS:
10013 			/* Recorded in transport above IP */
10014 			break;	/* goto sizeof (int) option return */
10015 		case IPV6_UNSPEC_SRC:
10016 			/* Allow sending with a zero source address */
10017 			if (!checkonly) {
10018 				mutex_enter(&connp->conn_lock);
10019 				connp->conn_unspec_src = *i1 ? 1 : 0;
10020 				mutex_exit(&connp->conn_lock);
10021 			}
10022 			break;	/* goto sizeof (int) option return */
10023 		case IPV6_RECVPKTINFO:
10024 			if (!checkonly) {
10025 				mutex_enter(&connp->conn_lock);
10026 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10027 				mutex_exit(&connp->conn_lock);
10028 			}
10029 			break;	/* goto sizeof (int) option return */
10030 		case IPV6_RECVTCLASS:
10031 			if (!checkonly) {
10032 				if (*i1 < 0 || *i1 > 1) {
10033 					return (EINVAL);
10034 				}
10035 				mutex_enter(&connp->conn_lock);
10036 				connp->conn_ipv6_recvtclass = *i1;
10037 				mutex_exit(&connp->conn_lock);
10038 			}
10039 			break;
10040 		case IPV6_RECVPATHMTU:
10041 			if (!checkonly) {
10042 				if (*i1 < 0 || *i1 > 1) {
10043 					return (EINVAL);
10044 				}
10045 				mutex_enter(&connp->conn_lock);
10046 				connp->conn_ipv6_recvpathmtu = *i1;
10047 				mutex_exit(&connp->conn_lock);
10048 			}
10049 			break;
10050 		case IPV6_RECVHOPLIMIT:
10051 			if (!checkonly) {
10052 				mutex_enter(&connp->conn_lock);
10053 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10054 				mutex_exit(&connp->conn_lock);
10055 			}
10056 			break;	/* goto sizeof (int) option return */
10057 		case IPV6_RECVHOPOPTS:
10058 			if (!checkonly) {
10059 				mutex_enter(&connp->conn_lock);
10060 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10061 				mutex_exit(&connp->conn_lock);
10062 			}
10063 			break;	/* goto sizeof (int) option return */
10064 		case IPV6_RECVDSTOPTS:
10065 			if (!checkonly) {
10066 				mutex_enter(&connp->conn_lock);
10067 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10068 				mutex_exit(&connp->conn_lock);
10069 			}
10070 			break;	/* goto sizeof (int) option return */
10071 		case IPV6_RECVRTHDR:
10072 			if (!checkonly) {
10073 				mutex_enter(&connp->conn_lock);
10074 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10075 				mutex_exit(&connp->conn_lock);
10076 			}
10077 			break;	/* goto sizeof (int) option return */
10078 		case IPV6_RECVRTHDRDSTOPTS:
10079 			if (!checkonly) {
10080 				mutex_enter(&connp->conn_lock);
10081 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10082 				mutex_exit(&connp->conn_lock);
10083 			}
10084 			break;	/* goto sizeof (int) option return */
10085 		case IPV6_PKTINFO:
10086 			if (inlen == 0)
10087 				return (-EINVAL);	/* clearing option */
10088 			error = ip6_set_pktinfo(cr, connp,
10089 			    (struct in6_pktinfo *)invalp, first_mp);
10090 			if (error != 0)
10091 				*outlenp = 0;
10092 			else
10093 				*outlenp = inlen;
10094 			return (error);
10095 		case IPV6_NEXTHOP: {
10096 			struct sockaddr_in6 *sin6;
10097 
10098 			/* Verify that the nexthop is reachable */
10099 			if (inlen == 0)
10100 				return (-EINVAL);	/* clearing option */
10101 
10102 			sin6 = (struct sockaddr_in6 *)invalp;
10103 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10104 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10105 			    MATCH_IRE_DEFAULT);
10106 
10107 			if (ire == NULL) {
10108 				*outlenp = 0;
10109 				return (EHOSTUNREACH);
10110 			}
10111 			ire_refrele(ire);
10112 			return (-EINVAL);
10113 		}
10114 		case IPV6_SEC_OPT:
10115 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10116 			if (error != 0) {
10117 				*outlenp = 0;
10118 				return (error);
10119 			}
10120 			break;
10121 		case IPV6_SRC_PREFERENCES: {
10122 			/*
10123 			 * This is implemented strictly in the ip module
10124 			 * (here and in tcp_opt_*() to accomodate tcp
10125 			 * sockets).  Modules above ip pass this option
10126 			 * down here since ip is the only one that needs to
10127 			 * be aware of source address preferences.
10128 			 *
10129 			 * This socket option only affects connected
10130 			 * sockets that haven't already bound to a specific
10131 			 * IPv6 address.  In other words, sockets that
10132 			 * don't call bind() with an address other than the
10133 			 * unspecified address and that call connect().
10134 			 * ip_bind_connected_v6() passes these preferences
10135 			 * to the ipif_select_source_v6() function.
10136 			 */
10137 			if (inlen != sizeof (uint32_t))
10138 				return (EINVAL);
10139 			error = ip6_set_src_preferences(connp,
10140 			    *(uint32_t *)invalp);
10141 			if (error != 0) {
10142 				*outlenp = 0;
10143 				return (error);
10144 			} else {
10145 				*outlenp = sizeof (uint32_t);
10146 			}
10147 			break;
10148 		}
10149 		case IPV6_V6ONLY:
10150 			if (*i1 < 0 || *i1 > 1) {
10151 				return (EINVAL);
10152 			}
10153 			mutex_enter(&connp->conn_lock);
10154 			connp->conn_ipv6_v6only = *i1;
10155 			mutex_exit(&connp->conn_lock);
10156 			break;
10157 		default:
10158 			return (-EINVAL);
10159 		}
10160 		break;
10161 	default:
10162 		/*
10163 		 * "soft" error (negative)
10164 		 * option not handled at this level
10165 		 * Note: Do not modify *outlenp
10166 		 */
10167 		return (-EINVAL);
10168 	}
10169 	/*
10170 	 * Common case of return from an option that is sizeof (int)
10171 	 */
10172 	*(int *)outvalp = *i1;
10173 	*outlenp = sizeof (int);
10174 	return (0);
10175 }
10176 
10177 /*
10178  * This routine gets default values of certain options whose default
10179  * values are maintained by protocol specific code
10180  */
10181 /* ARGSUSED */
10182 int
10183 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10184 {
10185 	int *i1 = (int *)ptr;
10186 
10187 	switch (level) {
10188 	case IPPROTO_IP:
10189 		switch (name) {
10190 		case IP_MULTICAST_TTL:
10191 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10192 			return (sizeof (uchar_t));
10193 		case IP_MULTICAST_LOOP:
10194 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10195 			return (sizeof (uchar_t));
10196 		default:
10197 			return (-1);
10198 		}
10199 	case IPPROTO_IPV6:
10200 		switch (name) {
10201 		case IPV6_UNICAST_HOPS:
10202 			*i1 = ipv6_def_hops;
10203 			return (sizeof (int));
10204 		case IPV6_MULTICAST_HOPS:
10205 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10206 			return (sizeof (int));
10207 		case IPV6_MULTICAST_LOOP:
10208 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10209 			return (sizeof (int));
10210 		case IPV6_V6ONLY:
10211 			*i1 = 1;
10212 			return (sizeof (int));
10213 		default:
10214 			return (-1);
10215 		}
10216 	default:
10217 		return (-1);
10218 	}
10219 	/* NOTREACHED */
10220 }
10221 
10222 /*
10223  * Given a destination address and a pointer to where to put the information
10224  * this routine fills in the mtuinfo.
10225  */
10226 int
10227 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10228     struct ip6_mtuinfo *mtuinfo)
10229 {
10230 	ire_t *ire;
10231 
10232 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10233 		return (-1);
10234 
10235 	bzero(mtuinfo, sizeof (*mtuinfo));
10236 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10237 	mtuinfo->ip6m_addr.sin6_port = port;
10238 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10239 
10240 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10241 	if (ire != NULL) {
10242 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10243 		ire_refrele(ire);
10244 	} else {
10245 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10246 	}
10247 	return (sizeof (struct ip6_mtuinfo));
10248 }
10249 
10250 /*
10251  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10252  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10253  * isn't.  This doesn't matter as the error checking is done properly for the
10254  * other MRT options coming in through ip_opt_set.
10255  */
10256 int
10257 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10258 {
10259 	conn_t		*connp = Q_TO_CONN(q);
10260 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10261 
10262 	switch (level) {
10263 	case IPPROTO_IP:
10264 		switch (name) {
10265 		case MRT_VERSION:
10266 		case MRT_ASSERT:
10267 			(void) ip_mrouter_get(name, q, ptr);
10268 			return (sizeof (int));
10269 		case IP_SEC_OPT:
10270 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10271 		default:
10272 			break;
10273 		}
10274 		break;
10275 	case IPPROTO_IPV6:
10276 		switch (name) {
10277 		case IPV6_SEC_OPT:
10278 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10279 		case IPV6_SRC_PREFERENCES: {
10280 			return (ip6_get_src_preferences(connp,
10281 			    (uint32_t *)ptr));
10282 		}
10283 		case IPV6_V6ONLY:
10284 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10285 			return (sizeof (int));
10286 		case IPV6_PATHMTU:
10287 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10288 				(struct ip6_mtuinfo *)ptr));
10289 		default:
10290 			break;
10291 		}
10292 		break;
10293 	default:
10294 		break;
10295 	}
10296 	return (-1);
10297 }
10298 
10299 /* Named Dispatch routine to get a current value out of our parameter table. */
10300 /* ARGSUSED */
10301 static int
10302 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10303 {
10304 	ipparam_t *ippa = (ipparam_t *)cp;
10305 
10306 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10307 	return (0);
10308 }
10309 
10310 /* ARGSUSED */
10311 static int
10312 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10313 {
10314 
10315 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10316 	return (0);
10317 }
10318 
10319 /*
10320  * Set ip{,6}_forwarding values.  This means walking through all of the
10321  * ill's and toggling their forwarding values.
10322  */
10323 /* ARGSUSED */
10324 static int
10325 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10326 {
10327 	long new_value;
10328 	int *forwarding_value = (int *)cp;
10329 	ill_t *walker;
10330 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10331 	ill_walk_context_t ctx;
10332 
10333 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10334 	    new_value < 0 || new_value > 1) {
10335 		return (EINVAL);
10336 	}
10337 
10338 	*forwarding_value = new_value;
10339 
10340 	/*
10341 	 * Regardless of the current value of ip_forwarding, set all per-ill
10342 	 * values of ip_forwarding to the value being set.
10343 	 *
10344 	 * Bring all the ill's up to date with the new global value.
10345 	 */
10346 	rw_enter(&ill_g_lock, RW_READER);
10347 
10348 	if (isv6)
10349 		walker = ILL_START_WALK_V6(&ctx);
10350 	else
10351 		walker = ILL_START_WALK_V4(&ctx);
10352 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10353 		(void) ill_forward_set(q, mp, (new_value != 0),
10354 		    (caddr_t)walker);
10355 	}
10356 	rw_exit(&ill_g_lock);
10357 
10358 	return (0);
10359 }
10360 
10361 /*
10362  * Walk through the param array specified registering each element with the
10363  * Named Dispatch handler. This is called only during init. So it is ok
10364  * not to acquire any locks
10365  */
10366 static boolean_t
10367 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10368     ipndp_t *ipnd, size_t ipnd_cnt)
10369 {
10370 	for (; ippa_cnt-- > 0; ippa++) {
10371 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10372 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10373 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10374 				nd_free(&ip_g_nd);
10375 				return (B_FALSE);
10376 			}
10377 		}
10378 	}
10379 
10380 	for (; ipnd_cnt-- > 0; ipnd++) {
10381 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10382 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10383 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10384 			    ipnd->ip_ndp_data)) {
10385 				nd_free(&ip_g_nd);
10386 				return (B_FALSE);
10387 			}
10388 		}
10389 	}
10390 
10391 	return (B_TRUE);
10392 }
10393 
10394 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10395 /* ARGSUSED */
10396 static int
10397 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10398 {
10399 	long		new_value;
10400 	ipparam_t	*ippa = (ipparam_t *)cp;
10401 
10402 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10403 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10404 		return (EINVAL);
10405 	}
10406 	ippa->ip_param_value = new_value;
10407 	return (0);
10408 }
10409 
10410 /*
10411  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10412  * When an ipf is passed here for the first time, if
10413  * we already have in-order fragments on the queue, we convert from the fast-
10414  * path reassembly scheme to the hard-case scheme.  From then on, additional
10415  * fragments are reassembled here.  We keep track of the start and end offsets
10416  * of each piece, and the number of holes in the chain.  When the hole count
10417  * goes to zero, we are done!
10418  *
10419  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10420  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10421  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10422  * after the call to ip_reassemble().
10423  */
10424 int
10425 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10426     size_t msg_len)
10427 {
10428 	uint_t	end;
10429 	mblk_t	*next_mp;
10430 	mblk_t	*mp1;
10431 	uint_t	offset;
10432 	boolean_t incr_dups = B_TRUE;
10433 	boolean_t offset_zero_seen = B_FALSE;
10434 	boolean_t pkt_boundary_checked = B_FALSE;
10435 
10436 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10437 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10438 
10439 	/* Add in byte count */
10440 	ipf->ipf_count += msg_len;
10441 	if (ipf->ipf_end) {
10442 		/*
10443 		 * We were part way through in-order reassembly, but now there
10444 		 * is a hole.  We walk through messages already queued, and
10445 		 * mark them for hard case reassembly.  We know that up till
10446 		 * now they were in order starting from offset zero.
10447 		 */
10448 		offset = 0;
10449 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10450 			IP_REASS_SET_START(mp1, offset);
10451 			if (offset == 0) {
10452 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10453 				offset = -ipf->ipf_nf_hdr_len;
10454 			}
10455 			offset += mp1->b_wptr - mp1->b_rptr;
10456 			IP_REASS_SET_END(mp1, offset);
10457 		}
10458 		/* One hole at the end. */
10459 		ipf->ipf_hole_cnt = 1;
10460 		/* Brand it as a hard case, forever. */
10461 		ipf->ipf_end = 0;
10462 	}
10463 	/* Walk through all the new pieces. */
10464 	do {
10465 		end = start + (mp->b_wptr - mp->b_rptr);
10466 		/*
10467 		 * If start is 0, decrease 'end' only for the first mblk of
10468 		 * the fragment. Otherwise 'end' can get wrong value in the
10469 		 * second pass of the loop if first mblk is exactly the
10470 		 * size of ipf_nf_hdr_len.
10471 		 */
10472 		if (start == 0 && !offset_zero_seen) {
10473 			/* First segment */
10474 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10475 			end -= ipf->ipf_nf_hdr_len;
10476 			offset_zero_seen = B_TRUE;
10477 		}
10478 		next_mp = mp->b_cont;
10479 		/*
10480 		 * We are checking to see if there is any interesing data
10481 		 * to process.  If there isn't and the mblk isn't the
10482 		 * one which carries the unfragmentable header then we
10483 		 * drop it.  It's possible to have just the unfragmentable
10484 		 * header come through without any data.  That needs to be
10485 		 * saved.
10486 		 *
10487 		 * If the assert at the top of this function holds then the
10488 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10489 		 * is infrequently traveled enough that the test is left in
10490 		 * to protect against future code changes which break that
10491 		 * invariant.
10492 		 */
10493 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10494 			/* Empty.  Blast it. */
10495 			IP_REASS_SET_START(mp, 0);
10496 			IP_REASS_SET_END(mp, 0);
10497 			/*
10498 			 * If the ipf points to the mblk we are about to free,
10499 			 * update ipf to point to the next mblk (or NULL
10500 			 * if none).
10501 			 */
10502 			if (ipf->ipf_mp->b_cont == mp)
10503 				ipf->ipf_mp->b_cont = next_mp;
10504 			freeb(mp);
10505 			continue;
10506 		}
10507 		mp->b_cont = NULL;
10508 		IP_REASS_SET_START(mp, start);
10509 		IP_REASS_SET_END(mp, end);
10510 		if (!ipf->ipf_tail_mp) {
10511 			ipf->ipf_tail_mp = mp;
10512 			ipf->ipf_mp->b_cont = mp;
10513 			if (start == 0 || !more) {
10514 				ipf->ipf_hole_cnt = 1;
10515 				/*
10516 				 * if the first fragment comes in more than one
10517 				 * mblk, this loop will be executed for each
10518 				 * mblk. Need to adjust hole count so exiting
10519 				 * this routine will leave hole count at 1.
10520 				 */
10521 				if (next_mp)
10522 					ipf->ipf_hole_cnt++;
10523 			} else
10524 				ipf->ipf_hole_cnt = 2;
10525 			continue;
10526 		} else if (ipf->ipf_last_frag_seen && !more &&
10527 			    !pkt_boundary_checked) {
10528 			/*
10529 			 * We check datagram boundary only if this fragment
10530 			 * claims to be the last fragment and we have seen a
10531 			 * last fragment in the past too. We do this only
10532 			 * once for a given fragment.
10533 			 *
10534 			 * start cannot be 0 here as fragments with start=0
10535 			 * and MF=0 gets handled as a complete packet. These
10536 			 * fragments should not reach here.
10537 			 */
10538 
10539 			if (start + msgdsize(mp) !=
10540 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10541 				/*
10542 				 * We have two fragments both of which claim
10543 				 * to be the last fragment but gives conflicting
10544 				 * information about the whole datagram size.
10545 				 * Something fishy is going on. Drop the
10546 				 * fragment and free up the reassembly list.
10547 				 */
10548 				return (IP_REASS_FAILED);
10549 			}
10550 
10551 			/*
10552 			 * We shouldn't come to this code block again for this
10553 			 * particular fragment.
10554 			 */
10555 			pkt_boundary_checked = B_TRUE;
10556 		}
10557 
10558 		/* New stuff at or beyond tail? */
10559 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10560 		if (start >= offset) {
10561 			if (ipf->ipf_last_frag_seen) {
10562 				/* current fragment is beyond last fragment */
10563 				return (IP_REASS_FAILED);
10564 			}
10565 			/* Link it on end. */
10566 			ipf->ipf_tail_mp->b_cont = mp;
10567 			ipf->ipf_tail_mp = mp;
10568 			if (more) {
10569 				if (start != offset)
10570 					ipf->ipf_hole_cnt++;
10571 			} else if (start == offset && next_mp == NULL)
10572 					ipf->ipf_hole_cnt--;
10573 			continue;
10574 		}
10575 		mp1 = ipf->ipf_mp->b_cont;
10576 		offset = IP_REASS_START(mp1);
10577 		/* New stuff at the front? */
10578 		if (start < offset) {
10579 			if (start == 0) {
10580 				if (end >= offset) {
10581 					/* Nailed the hole at the begining. */
10582 					ipf->ipf_hole_cnt--;
10583 				}
10584 			} else if (end < offset) {
10585 				/*
10586 				 * A hole, stuff, and a hole where there used
10587 				 * to be just a hole.
10588 				 */
10589 				ipf->ipf_hole_cnt++;
10590 			}
10591 			mp->b_cont = mp1;
10592 			/* Check for overlap. */
10593 			while (end > offset) {
10594 				if (end < IP_REASS_END(mp1)) {
10595 					mp->b_wptr -= end - offset;
10596 					IP_REASS_SET_END(mp, offset);
10597 					if (ill->ill_isv6) {
10598 						BUMP_MIB(ill->ill_ip6_mib,
10599 						    ipv6ReasmPartDups);
10600 					} else {
10601 						BUMP_MIB(&ip_mib,
10602 						    ipReasmPartDups);
10603 					}
10604 					break;
10605 				}
10606 				/* Did we cover another hole? */
10607 				if ((mp1->b_cont &&
10608 				    IP_REASS_END(mp1) !=
10609 				    IP_REASS_START(mp1->b_cont) &&
10610 				    end >= IP_REASS_START(mp1->b_cont)) ||
10611 				    (!ipf->ipf_last_frag_seen && !more)) {
10612 					ipf->ipf_hole_cnt--;
10613 				}
10614 				/* Clip out mp1. */
10615 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10616 					/*
10617 					 * After clipping out mp1, this guy
10618 					 * is now hanging off the end.
10619 					 */
10620 					ipf->ipf_tail_mp = mp;
10621 				}
10622 				IP_REASS_SET_START(mp1, 0);
10623 				IP_REASS_SET_END(mp1, 0);
10624 				/* Subtract byte count */
10625 				ipf->ipf_count -= mp1->b_datap->db_lim -
10626 				    mp1->b_datap->db_base;
10627 				freeb(mp1);
10628 				if (ill->ill_isv6) {
10629 					BUMP_MIB(ill->ill_ip6_mib,
10630 					    ipv6ReasmPartDups);
10631 				} else {
10632 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10633 				}
10634 				mp1 = mp->b_cont;
10635 				if (!mp1)
10636 					break;
10637 				offset = IP_REASS_START(mp1);
10638 			}
10639 			ipf->ipf_mp->b_cont = mp;
10640 			continue;
10641 		}
10642 		/*
10643 		 * The new piece starts somewhere between the start of the head
10644 		 * and before the end of the tail.
10645 		 */
10646 		for (; mp1; mp1 = mp1->b_cont) {
10647 			offset = IP_REASS_END(mp1);
10648 			if (start < offset) {
10649 				if (end <= offset) {
10650 					/* Nothing new. */
10651 					IP_REASS_SET_START(mp, 0);
10652 					IP_REASS_SET_END(mp, 0);
10653 					/* Subtract byte count */
10654 					ipf->ipf_count -= mp->b_datap->db_lim -
10655 					    mp->b_datap->db_base;
10656 					if (incr_dups) {
10657 						ipf->ipf_num_dups++;
10658 						incr_dups = B_FALSE;
10659 					}
10660 					freeb(mp);
10661 					if (ill->ill_isv6) {
10662 						BUMP_MIB(ill->ill_ip6_mib,
10663 						    ipv6ReasmDuplicates);
10664 					} else {
10665 						BUMP_MIB(&ip_mib,
10666 						    ipReasmDuplicates);
10667 					}
10668 					break;
10669 				}
10670 				/*
10671 				 * Trim redundant stuff off beginning of new
10672 				 * piece.
10673 				 */
10674 				IP_REASS_SET_START(mp, offset);
10675 				mp->b_rptr += offset - start;
10676 				if (ill->ill_isv6) {
10677 					BUMP_MIB(ill->ill_ip6_mib,
10678 					    ipv6ReasmPartDups);
10679 				} else {
10680 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10681 				}
10682 				start = offset;
10683 				if (!mp1->b_cont) {
10684 					/*
10685 					 * After trimming, this guy is now
10686 					 * hanging off the end.
10687 					 */
10688 					mp1->b_cont = mp;
10689 					ipf->ipf_tail_mp = mp;
10690 					if (!more) {
10691 						ipf->ipf_hole_cnt--;
10692 					}
10693 					break;
10694 				}
10695 			}
10696 			if (start >= IP_REASS_START(mp1->b_cont))
10697 				continue;
10698 			/* Fill a hole */
10699 			if (start > offset)
10700 				ipf->ipf_hole_cnt++;
10701 			mp->b_cont = mp1->b_cont;
10702 			mp1->b_cont = mp;
10703 			mp1 = mp->b_cont;
10704 			offset = IP_REASS_START(mp1);
10705 			if (end >= offset) {
10706 				ipf->ipf_hole_cnt--;
10707 				/* Check for overlap. */
10708 				while (end > offset) {
10709 					if (end < IP_REASS_END(mp1)) {
10710 						mp->b_wptr -= end - offset;
10711 						IP_REASS_SET_END(mp, offset);
10712 						/*
10713 						 * TODO we might bump
10714 						 * this up twice if there is
10715 						 * overlap at both ends.
10716 						 */
10717 						if (ill->ill_isv6) {
10718 							BUMP_MIB(
10719 							    ill->ill_ip6_mib,
10720 							    ipv6ReasmPartDups);
10721 						} else {
10722 							BUMP_MIB(&ip_mib,
10723 							    ipReasmPartDups);
10724 						}
10725 						break;
10726 					}
10727 					/* Did we cover another hole? */
10728 					if ((mp1->b_cont &&
10729 					    IP_REASS_END(mp1)
10730 					    != IP_REASS_START(mp1->b_cont) &&
10731 					    end >=
10732 					    IP_REASS_START(mp1->b_cont)) ||
10733 					    (!ipf->ipf_last_frag_seen &&
10734 					    !more)) {
10735 						ipf->ipf_hole_cnt--;
10736 					}
10737 					/* Clip out mp1. */
10738 					if ((mp->b_cont = mp1->b_cont) ==
10739 					    NULL) {
10740 						/*
10741 						 * After clipping out mp1,
10742 						 * this guy is now hanging
10743 						 * off the end.
10744 						 */
10745 						ipf->ipf_tail_mp = mp;
10746 					}
10747 					IP_REASS_SET_START(mp1, 0);
10748 					IP_REASS_SET_END(mp1, 0);
10749 					/* Subtract byte count */
10750 					ipf->ipf_count -=
10751 					    mp1->b_datap->db_lim -
10752 					    mp1->b_datap->db_base;
10753 					freeb(mp1);
10754 					if (ill->ill_isv6) {
10755 						BUMP_MIB(ill->ill_ip6_mib,
10756 						    ipv6ReasmPartDups);
10757 					} else {
10758 						BUMP_MIB(&ip_mib,
10759 						    ipReasmPartDups);
10760 					}
10761 					mp1 = mp->b_cont;
10762 					if (!mp1)
10763 						break;
10764 					offset = IP_REASS_START(mp1);
10765 				}
10766 			}
10767 			break;
10768 		}
10769 	} while (start = end, mp = next_mp);
10770 
10771 	/* Fragment just processed could be the last one. Remember this fact */
10772 	if (!more)
10773 		ipf->ipf_last_frag_seen = B_TRUE;
10774 
10775 	/* Still got holes? */
10776 	if (ipf->ipf_hole_cnt)
10777 		return (IP_REASS_PARTIAL);
10778 	/* Clean up overloaded fields to avoid upstream disasters. */
10779 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10780 		IP_REASS_SET_START(mp1, 0);
10781 		IP_REASS_SET_END(mp1, 0);
10782 	}
10783 	return (IP_REASS_COMPLETE);
10784 }
10785 
10786 /*
10787  * ipsec processing for the fast path, used for input UDP Packets
10788  */
10789 static boolean_t
10790 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10791     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10792 {
10793 	uint32_t	ill_index;
10794 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10795 
10796 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10797 	/* The ill_index of the incoming ILL */
10798 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10799 
10800 	/* pass packet up to the transport */
10801 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10802 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10803 		    NULL, mctl_present);
10804 		if (*first_mpp == NULL) {
10805 			return (B_FALSE);
10806 		}
10807 	}
10808 
10809 	/* Initiate IPPF processing for fastpath UDP */
10810 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10811 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10812 		if (*mpp == NULL) {
10813 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10814 			    "deferred/dropped during IPPF processing\n"));
10815 			return (B_FALSE);
10816 		}
10817 	}
10818 	/*
10819 	 * We make the checks as below since we are in the fast path
10820 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10821 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10822 	 */
10823 	if (connp->conn_recvif || connp->conn_recvslla ||
10824 	    connp->conn_ipv6_recvpktinfo) {
10825 		if (connp->conn_recvif ||
10826 		    connp->conn_ipv6_recvpktinfo) {
10827 			in_flags = IPF_RECVIF;
10828 		}
10829 		if (connp->conn_recvslla) {
10830 			in_flags |= IPF_RECVSLLA;
10831 		}
10832 		/*
10833 		 * since in_flags are being set ill will be
10834 		 * referenced in ip_add_info, so it better not
10835 		 * be NULL.
10836 		 */
10837 		/*
10838 		 * the actual data will be contained in b_cont
10839 		 * upon successful return of the following call.
10840 		 * If the call fails then the original mblk is
10841 		 * returned.
10842 		 */
10843 		*mpp = ip_add_info(*mpp, ill, in_flags);
10844 	}
10845 
10846 	return (B_TRUE);
10847 }
10848 
10849 /*
10850  * Fragmentation reassembly.  Each ILL has a hash table for
10851  * queuing packets undergoing reassembly for all IPIFs
10852  * associated with the ILL.  The hash is based on the packet
10853  * IP ident field.  The ILL frag hash table was allocated
10854  * as a timer block at the time the ILL was created.  Whenever
10855  * there is anything on the reassembly queue, the timer will
10856  * be running.  Returns B_TRUE if successful else B_FALSE;
10857  * frees mp on failure.
10858  */
10859 static boolean_t
10860 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
10861     uint32_t *cksum_val, uint16_t *cksum_flags)
10862 {
10863 	uint32_t	frag_offset_flags;
10864 	ill_t		*ill = (ill_t *)q->q_ptr;
10865 	mblk_t		*mp = *mpp;
10866 	mblk_t		*t_mp;
10867 	ipaddr_t	dst;
10868 	uint8_t		proto = ipha->ipha_protocol;
10869 	uint32_t	sum_val;
10870 	uint16_t	sum_flags;
10871 	ipf_t		*ipf;
10872 	ipf_t		**ipfp;
10873 	ipfb_t		*ipfb;
10874 	uint16_t	ident;
10875 	uint32_t	offset;
10876 	ipaddr_t	src;
10877 	uint_t		hdr_length;
10878 	uint32_t	end;
10879 	mblk_t		*mp1;
10880 	mblk_t		*tail_mp;
10881 	size_t		count;
10882 	size_t		msg_len;
10883 	uint8_t		ecn_info = 0;
10884 	uint32_t	packet_size;
10885 	boolean_t	pruned = B_FALSE;
10886 
10887 	if (cksum_val != NULL)
10888 		*cksum_val = 0;
10889 	if (cksum_flags != NULL)
10890 		*cksum_flags = 0;
10891 
10892 	/*
10893 	 * Drop the fragmented as early as possible, if
10894 	 * we don't have resource(s) to re-assemble.
10895 	 */
10896 	if (ip_reass_queue_bytes == 0) {
10897 		freemsg(mp);
10898 		return (B_FALSE);
10899 	}
10900 
10901 	/* Check for fragmentation offset; return if there's none */
10902 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
10903 	    (IPH_MF | IPH_OFFSET)) == 0)
10904 		return (B_TRUE);
10905 
10906 	/*
10907 	 * We utilize hardware computed checksum info only for UDP since
10908 	 * IP fragmentation is a normal occurence for the protocol.  In
10909 	 * addition, checksum offload support for IP fragments carrying
10910 	 * UDP payload is commonly implemented across network adapters.
10911 	 */
10912 	ASSERT(ill != NULL);
10913 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
10914 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
10915 		mblk_t *mp1 = mp->b_cont;
10916 		int32_t len;
10917 
10918 		/* Record checksum information from the packet */
10919 		sum_val = (uint32_t)DB_CKSUM16(mp);
10920 		sum_flags = DB_CKSUMFLAGS(mp);
10921 
10922 		/* IP payload offset from beginning of mblk */
10923 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
10924 
10925 		if ((sum_flags & HCK_PARTIALCKSUM) &&
10926 		    (mp1 == NULL || mp1->b_cont == NULL) &&
10927 		    offset >= DB_CKSUMSTART(mp) &&
10928 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
10929 			uint32_t adj;
10930 			/*
10931 			 * Partial checksum has been calculated by hardware
10932 			 * and attached to the packet; in addition, any
10933 			 * prepended extraneous data is even byte aligned.
10934 			 * If any such data exists, we adjust the checksum;
10935 			 * this would also handle any postpended data.
10936 			 */
10937 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
10938 			    mp, mp1, len, adj);
10939 
10940 			/* One's complement subtract extraneous checksum */
10941 			if (adj >= sum_val)
10942 				sum_val = ~(adj - sum_val) & 0xFFFF;
10943 			else
10944 				sum_val -= adj;
10945 		}
10946 	} else {
10947 		sum_val = 0;
10948 		sum_flags = 0;
10949 	}
10950 
10951 	/* Clear hardware checksumming flag */
10952 	DB_CKSUMFLAGS(mp) = 0;
10953 
10954 	ident = ipha->ipha_ident;
10955 	offset = (frag_offset_flags << 3) & 0xFFFF;
10956 	src = ipha->ipha_src;
10957 	dst = ipha->ipha_dst;
10958 	hdr_length = IPH_HDR_LENGTH(ipha);
10959 	end = ntohs(ipha->ipha_length) - hdr_length;
10960 
10961 	/* If end == 0 then we have a packet with no data, so just free it */
10962 	if (end == 0) {
10963 		freemsg(mp);
10964 		return (B_FALSE);
10965 	}
10966 
10967 	/* Record the ECN field info. */
10968 	ecn_info = (ipha->ipha_type_of_service & 0x3);
10969 	if (offset != 0) {
10970 		/*
10971 		 * If this isn't the first piece, strip the header, and
10972 		 * add the offset to the end value.
10973 		 */
10974 		mp->b_rptr += hdr_length;
10975 		end += offset;
10976 	}
10977 
10978 	msg_len = MBLKSIZE(mp);
10979 	tail_mp = mp;
10980 	while (tail_mp->b_cont != NULL) {
10981 		tail_mp = tail_mp->b_cont;
10982 		msg_len += MBLKSIZE(tail_mp);
10983 	}
10984 
10985 	/* If the reassembly list for this ILL will get too big, prune it */
10986 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
10987 	    ip_reass_queue_bytes) {
10988 		ill_frag_prune(ill,
10989 		    (ip_reass_queue_bytes < msg_len) ? 0 :
10990 		    (ip_reass_queue_bytes - msg_len));
10991 		pruned = B_TRUE;
10992 	}
10993 
10994 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
10995 	mutex_enter(&ipfb->ipfb_lock);
10996 
10997 	ipfp = &ipfb->ipfb_ipf;
10998 	/* Try to find an existing fragment queue for this packet. */
10999 	for (;;) {
11000 		ipf = ipfp[0];
11001 		if (ipf != NULL) {
11002 			/*
11003 			 * It has to match on ident and src/dst address.
11004 			 */
11005 			if (ipf->ipf_ident == ident &&
11006 			    ipf->ipf_src == src &&
11007 			    ipf->ipf_dst == dst &&
11008 			    ipf->ipf_protocol == proto) {
11009 				/*
11010 				 * If we have received too many
11011 				 * duplicate fragments for this packet
11012 				 * free it.
11013 				 */
11014 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11015 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11016 					freemsg(mp);
11017 					mutex_exit(&ipfb->ipfb_lock);
11018 					return (B_FALSE);
11019 				}
11020 				/* Found it. */
11021 				break;
11022 			}
11023 			ipfp = &ipf->ipf_hash_next;
11024 			continue;
11025 		}
11026 
11027 		/*
11028 		 * If we pruned the list, do we want to store this new
11029 		 * fragment?. We apply an optimization here based on the
11030 		 * fact that most fragments will be received in order.
11031 		 * So if the offset of this incoming fragment is zero,
11032 		 * it is the first fragment of a new packet. We will
11033 		 * keep it.  Otherwise drop the fragment, as we have
11034 		 * probably pruned the packet already (since the
11035 		 * packet cannot be found).
11036 		 */
11037 		if (pruned && offset != 0) {
11038 			mutex_exit(&ipfb->ipfb_lock);
11039 			freemsg(mp);
11040 			return (B_FALSE);
11041 		}
11042 
11043 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11044 			/*
11045 			 * Too many fragmented packets in this hash
11046 			 * bucket. Free the oldest.
11047 			 */
11048 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11049 		}
11050 
11051 		/* New guy.  Allocate a frag message. */
11052 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11053 		if (mp1 == NULL) {
11054 			BUMP_MIB(&ip_mib, ipInDiscards);
11055 			freemsg(mp);
11056 reass_done:
11057 			mutex_exit(&ipfb->ipfb_lock);
11058 			return (B_FALSE);
11059 		}
11060 
11061 
11062 		BUMP_MIB(&ip_mib, ipReasmReqds);
11063 		mp1->b_cont = mp;
11064 
11065 		/* Initialize the fragment header. */
11066 		ipf = (ipf_t *)mp1->b_rptr;
11067 		ipf->ipf_mp = mp1;
11068 		ipf->ipf_ptphn = ipfp;
11069 		ipfp[0] = ipf;
11070 		ipf->ipf_hash_next = NULL;
11071 		ipf->ipf_ident = ident;
11072 		ipf->ipf_protocol = proto;
11073 		ipf->ipf_src = src;
11074 		ipf->ipf_dst = dst;
11075 		ipf->ipf_nf_hdr_len = 0;
11076 		/* Record reassembly start time. */
11077 		ipf->ipf_timestamp = gethrestime_sec();
11078 		/* Record ipf generation and account for frag header */
11079 		ipf->ipf_gen = ill->ill_ipf_gen++;
11080 		ipf->ipf_count = MBLKSIZE(mp1);
11081 		ipf->ipf_last_frag_seen = B_FALSE;
11082 		ipf->ipf_ecn = ecn_info;
11083 		ipf->ipf_num_dups = 0;
11084 		ipfb->ipfb_frag_pkts++;
11085 		ipf->ipf_checksum = 0;
11086 		ipf->ipf_checksum_flags = 0;
11087 
11088 		/* Store checksum value in fragment header */
11089 		if (sum_flags != 0) {
11090 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11091 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11092 			ipf->ipf_checksum = sum_val;
11093 			ipf->ipf_checksum_flags = sum_flags;
11094 		}
11095 
11096 		/*
11097 		 * We handle reassembly two ways.  In the easy case,
11098 		 * where all the fragments show up in order, we do
11099 		 * minimal bookkeeping, and just clip new pieces on
11100 		 * the end.  If we ever see a hole, then we go off
11101 		 * to ip_reassemble which has to mark the pieces and
11102 		 * keep track of the number of holes, etc.  Obviously,
11103 		 * the point of having both mechanisms is so we can
11104 		 * handle the easy case as efficiently as possible.
11105 		 */
11106 		if (offset == 0) {
11107 			/* Easy case, in-order reassembly so far. */
11108 			ipf->ipf_count += msg_len;
11109 			ipf->ipf_tail_mp = tail_mp;
11110 			/*
11111 			 * Keep track of next expected offset in
11112 			 * ipf_end.
11113 			 */
11114 			ipf->ipf_end = end;
11115 			ipf->ipf_nf_hdr_len = hdr_length;
11116 		} else {
11117 			/* Hard case, hole at the beginning. */
11118 			ipf->ipf_tail_mp = NULL;
11119 			/*
11120 			 * ipf_end == 0 means that we have given up
11121 			 * on easy reassembly.
11122 			 */
11123 			ipf->ipf_end = 0;
11124 
11125 			/* Forget checksum offload from now on */
11126 			ipf->ipf_checksum_flags = 0;
11127 
11128 			/*
11129 			 * ipf_hole_cnt is set by ip_reassemble.
11130 			 * ipf_count is updated by ip_reassemble.
11131 			 * No need to check for return value here
11132 			 * as we don't expect reassembly to complete
11133 			 * or fail for the first fragment itself.
11134 			 */
11135 			(void) ip_reassemble(mp, ipf,
11136 			    (frag_offset_flags & IPH_OFFSET) << 3,
11137 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11138 		}
11139 		/* Update per ipfb and ill byte counts */
11140 		ipfb->ipfb_count += ipf->ipf_count;
11141 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11142 		ill->ill_frag_count += ipf->ipf_count;
11143 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11144 		/* If the frag timer wasn't already going, start it. */
11145 		mutex_enter(&ill->ill_lock);
11146 		ill_frag_timer_start(ill);
11147 		mutex_exit(&ill->ill_lock);
11148 		goto reass_done;
11149 	}
11150 
11151 	/*
11152 	 * If the packet's flag has changed (it could be coming up
11153 	 * from an interface different than the previous, therefore
11154 	 * possibly different checksum capability), then forget about
11155 	 * any stored checksum states.  Otherwise add the value to
11156 	 * the existing one stored in the fragment header.
11157 	 */
11158 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11159 		sum_val += ipf->ipf_checksum;
11160 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11161 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11162 		ipf->ipf_checksum = sum_val;
11163 	} else if (ipf->ipf_checksum_flags != 0) {
11164 		/* Forget checksum offload from now on */
11165 		ipf->ipf_checksum_flags = 0;
11166 	}
11167 
11168 	/*
11169 	 * We have a new piece of a datagram which is already being
11170 	 * reassembled.  Update the ECN info if all IP fragments
11171 	 * are ECN capable.  If there is one which is not, clear
11172 	 * all the info.  If there is at least one which has CE
11173 	 * code point, IP needs to report that up to transport.
11174 	 */
11175 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11176 		if (ecn_info == IPH_ECN_CE)
11177 			ipf->ipf_ecn = IPH_ECN_CE;
11178 	} else {
11179 		ipf->ipf_ecn = IPH_ECN_NECT;
11180 	}
11181 	if (offset && ipf->ipf_end == offset) {
11182 		/* The new fragment fits at the end */
11183 		ipf->ipf_tail_mp->b_cont = mp;
11184 		/* Update the byte count */
11185 		ipf->ipf_count += msg_len;
11186 		/* Update per ipfb and ill byte counts */
11187 		ipfb->ipfb_count += msg_len;
11188 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11189 		ill->ill_frag_count += msg_len;
11190 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11191 		if (frag_offset_flags & IPH_MF) {
11192 			/* More to come. */
11193 			ipf->ipf_end = end;
11194 			ipf->ipf_tail_mp = tail_mp;
11195 			goto reass_done;
11196 		}
11197 	} else {
11198 		/* Go do the hard cases. */
11199 		int ret;
11200 
11201 		if (offset == 0)
11202 			ipf->ipf_nf_hdr_len = hdr_length;
11203 
11204 		/* Save current byte count */
11205 		count = ipf->ipf_count;
11206 		ret = ip_reassemble(mp, ipf,
11207 		    (frag_offset_flags & IPH_OFFSET) << 3,
11208 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11209 		/* Count of bytes added and subtracted (freeb()ed) */
11210 		count = ipf->ipf_count - count;
11211 		if (count) {
11212 			/* Update per ipfb and ill byte counts */
11213 			ipfb->ipfb_count += count;
11214 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11215 			ill->ill_frag_count += count;
11216 			ASSERT(ill->ill_frag_count > 0);
11217 		}
11218 		if (ret == IP_REASS_PARTIAL) {
11219 			goto reass_done;
11220 		} else if (ret == IP_REASS_FAILED) {
11221 			/* Reassembly failed. Free up all resources */
11222 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11223 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11224 				IP_REASS_SET_START(t_mp, 0);
11225 				IP_REASS_SET_END(t_mp, 0);
11226 			}
11227 			freemsg(mp);
11228 			goto reass_done;
11229 		}
11230 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11231 	}
11232 	/*
11233 	 * We have completed reassembly.  Unhook the frag header from
11234 	 * the reassembly list.
11235 	 *
11236 	 * Before we free the frag header, record the ECN info
11237 	 * to report back to the transport.
11238 	 */
11239 	ecn_info = ipf->ipf_ecn;
11240 	BUMP_MIB(&ip_mib, ipReasmOKs);
11241 	ipfp = ipf->ipf_ptphn;
11242 
11243 	/* We need to supply these to caller */
11244 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11245 		sum_val = ipf->ipf_checksum;
11246 	else
11247 		sum_val = 0;
11248 
11249 	mp1 = ipf->ipf_mp;
11250 	count = ipf->ipf_count;
11251 	ipf = ipf->ipf_hash_next;
11252 	if (ipf != NULL)
11253 		ipf->ipf_ptphn = ipfp;
11254 	ipfp[0] = ipf;
11255 	ill->ill_frag_count -= count;
11256 	ASSERT(ipfb->ipfb_count >= count);
11257 	ipfb->ipfb_count -= count;
11258 	ipfb->ipfb_frag_pkts--;
11259 	mutex_exit(&ipfb->ipfb_lock);
11260 	/* Ditch the frag header. */
11261 	mp = mp1->b_cont;
11262 
11263 	freeb(mp1);
11264 
11265 	/* Restore original IP length in header. */
11266 	packet_size = (uint32_t)msgdsize(mp);
11267 	if (packet_size > IP_MAXPACKET) {
11268 		freemsg(mp);
11269 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11270 		return (B_FALSE);
11271 	}
11272 
11273 	if (DB_REF(mp) > 1) {
11274 		mblk_t *mp2 = copymsg(mp);
11275 
11276 		freemsg(mp);
11277 		if (mp2 == NULL) {
11278 			BUMP_MIB(&ip_mib, ipInDiscards);
11279 			return (B_FALSE);
11280 		}
11281 		mp = mp2;
11282 	}
11283 	ipha = (ipha_t *)mp->b_rptr;
11284 
11285 	ipha->ipha_length = htons((uint16_t)packet_size);
11286 	/* We're now complete, zip the frag state */
11287 	ipha->ipha_fragment_offset_and_flags = 0;
11288 	/* Record the ECN info. */
11289 	ipha->ipha_type_of_service &= 0xFC;
11290 	ipha->ipha_type_of_service |= ecn_info;
11291 	*mpp = mp;
11292 
11293 	/* Reassembly is successful; return checksum information if needed */
11294 	if (cksum_val != NULL)
11295 		*cksum_val = sum_val;
11296 	if (cksum_flags != NULL)
11297 		*cksum_flags = sum_flags;
11298 
11299 	return (B_TRUE);
11300 }
11301 
11302 /*
11303  * Perform ip header check sum update local options.
11304  * return B_TRUE if all is well, else return B_FALSE and release
11305  * the mp. caller is responsible for decrementing ire ref cnt.
11306  */
11307 static boolean_t
11308 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11309 {
11310 	mblk_t		*first_mp;
11311 	boolean_t	mctl_present;
11312 	uint16_t	sum;
11313 
11314 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11315 	/*
11316 	 * Don't do the checksum if it has gone through AH/ESP
11317 	 * processing.
11318 	 */
11319 	if (!mctl_present) {
11320 		sum = ip_csum_hdr(ipha);
11321 		if (sum != 0) {
11322 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11323 			freemsg(first_mp);
11324 			return (B_FALSE);
11325 		}
11326 	}
11327 
11328 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11329 		if (mctl_present)
11330 			freeb(first_mp);
11331 		return (B_FALSE);
11332 	}
11333 
11334 	return (B_TRUE);
11335 }
11336 
11337 /*
11338  * All udp packet are delivered to the local host via this routine.
11339  */
11340 void
11341 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11342     ill_t *recv_ill)
11343 {
11344 	uint32_t	sum;
11345 	uint32_t	u1;
11346 	boolean_t	mctl_present;
11347 	conn_t		*connp;
11348 	mblk_t		*first_mp;
11349 	uint16_t	*up;
11350 	ill_t		*ill = (ill_t *)q->q_ptr;
11351 	uint16_t	reass_hck_flags = 0;
11352 
11353 #define	rptr    ((uchar_t *)ipha)
11354 
11355 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11356 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11357 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11358 
11359 	/*
11360 	 * FAST PATH for udp packets
11361 	 */
11362 
11363 	/* u1 is # words of IP options */
11364 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11365 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11366 
11367 	/* IP options present */
11368 	if (u1 != 0)
11369 		goto ipoptions;
11370 
11371 	/* Check the IP header checksum.  */
11372 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11373 		/* Clear the IP header h/w cksum flag */
11374 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11375 	} else {
11376 #define	uph	((uint16_t *)ipha)
11377 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11378 		    uph[6] + uph[7] + uph[8] + uph[9];
11379 #undef	uph
11380 		/* finish doing IP checksum */
11381 		sum = (sum & 0xFFFF) + (sum >> 16);
11382 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11383 		/*
11384 		 * Don't verify header checksum if this packet is coming
11385 		 * back from AH/ESP as we already did it.
11386 		 */
11387 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
11388 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11389 			freemsg(first_mp);
11390 			return;
11391 		}
11392 	}
11393 
11394 	/*
11395 	 * Count for SNMP of inbound packets for ire.
11396 	 * if mctl is present this might be a secure packet and
11397 	 * has already been counted for in ip_proto_input().
11398 	 */
11399 	if (!mctl_present) {
11400 		UPDATE_IB_PKT_COUNT(ire);
11401 		ire->ire_last_used_time = lbolt;
11402 	}
11403 
11404 	/* packet part of fragmented IP packet? */
11405 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11406 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11407 		goto fragmented;
11408 	}
11409 
11410 	/* u1 = IP header length (20 bytes) */
11411 	u1 = IP_SIMPLE_HDR_LENGTH;
11412 
11413 	/* packet does not contain complete IP & UDP headers */
11414 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11415 		goto udppullup;
11416 
11417 	/* up points to UDP header */
11418 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11419 #define	iphs    ((uint16_t *)ipha)
11420 
11421 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11422 	if (up[3] != 0) {
11423 		mblk_t *mp1 = mp->b_cont;
11424 		boolean_t cksum_err;
11425 		uint16_t hck_flags = 0;
11426 
11427 		/* Pseudo-header checksum */
11428 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11429 		    iphs[9] + up[2];
11430 
11431 		/*
11432 		 * Revert to software checksum calculation if the interface
11433 		 * isn't capable of checksum offload or if IPsec is present.
11434 		 */
11435 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11436 			hck_flags = DB_CKSUMFLAGS(mp);
11437 
11438 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11439 			IP_STAT(ip_in_sw_cksum);
11440 
11441 		IP_CKSUM_RECV(hck_flags, u1,
11442 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11443 		    (int32_t)((uchar_t *)up - rptr),
11444 		    mp, mp1, cksum_err);
11445 
11446 		if (cksum_err) {
11447 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11448 
11449 			if (hck_flags & HCK_FULLCKSUM)
11450 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11451 			else if (hck_flags & HCK_PARTIALCKSUM)
11452 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11453 			else
11454 				IP_STAT(ip_udp_in_sw_cksum_err);
11455 
11456 			freemsg(first_mp);
11457 			return;
11458 		}
11459 	}
11460 
11461 	/* Non-fragmented broadcast or multicast packet? */
11462 	if (ire->ire_type == IRE_BROADCAST)
11463 		goto udpslowpath;
11464 
11465 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11466 	    ire->ire_zoneid)) != NULL) {
11467 		ASSERT(connp->conn_upq != NULL);
11468 		IP_STAT(ip_udp_fast_path);
11469 
11470 		if (CONN_UDP_FLOWCTLD(connp)) {
11471 			freemsg(mp);
11472 			BUMP_MIB(&ip_mib, udpInOverflows);
11473 		} else {
11474 			if (!mctl_present) {
11475 				BUMP_MIB(&ip_mib, ipInDelivers);
11476 			}
11477 			/*
11478 			 * mp and first_mp can change.
11479 			 */
11480 			if (ip_udp_check(q, connp, recv_ill,
11481 			    ipha, &mp, &first_mp, mctl_present)) {
11482 				/* Send it upstream */
11483 				CONN_UDP_RECV(connp, mp);
11484 			}
11485 		}
11486 		/*
11487 		 * freeb() cannot deal with null mblk being passed
11488 		 * in and first_mp can be set to null in the call
11489 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11490 		 */
11491 		if (mctl_present && first_mp != NULL) {
11492 			freeb(first_mp);
11493 		}
11494 		CONN_DEC_REF(connp);
11495 		return;
11496 	}
11497 
11498 	/*
11499 	 * if we got here we know the packet is not fragmented and
11500 	 * has no options. The classifier could not find a conn_t and
11501 	 * most likely its an icmp packet so send it through slow path.
11502 	 */
11503 
11504 	goto udpslowpath;
11505 
11506 ipoptions:
11507 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11508 		goto slow_done;
11509 	}
11510 
11511 	UPDATE_IB_PKT_COUNT(ire);
11512 	ire->ire_last_used_time = lbolt;
11513 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11514 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11515 fragmented:
11516 		/*
11517 		 * "sum" and "reass_hck_flags" are non-zero if the
11518 		 * reassembled packet has a valid hardware computed
11519 		 * checksum information associated with it.
11520 		 */
11521 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
11522 			goto slow_done;
11523 		/*
11524 		 * Make sure that first_mp points back to mp as
11525 		 * the mp we came in with could have changed in
11526 		 * ip_rput_fragment().
11527 		 */
11528 		ASSERT(!mctl_present);
11529 		ipha = (ipha_t *)mp->b_rptr;
11530 		first_mp = mp;
11531 	}
11532 
11533 	/* Now we have a complete datagram, destined for this machine. */
11534 	u1 = IPH_HDR_LENGTH(ipha);
11535 	/* Pull up the UDP header, if necessary. */
11536 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
11537 udppullup:
11538 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11539 			BUMP_MIB(&ip_mib, ipInDiscards);
11540 			freemsg(first_mp);
11541 			goto slow_done;
11542 		}
11543 		ipha = (ipha_t *)mp->b_rptr;
11544 	}
11545 
11546 	/*
11547 	 * Validate the checksum for the reassembled packet; for the
11548 	 * pullup case we calculate the payload checksum in software.
11549 	 */
11550 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11551 	if (up[3] != 0) {
11552 		boolean_t cksum_err;
11553 
11554 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11555 			IP_STAT(ip_in_sw_cksum);
11556 
11557 		IP_CKSUM_RECV_REASS(reass_hck_flags,
11558 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11559 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11560 		    iphs[9] + up[2], sum, cksum_err);
11561 
11562 		if (cksum_err) {
11563 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11564 
11565 			if (reass_hck_flags & HCK_FULLCKSUM)
11566 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11567 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
11568 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11569 			else
11570 				IP_STAT(ip_udp_in_sw_cksum_err);
11571 
11572 			freemsg(first_mp);
11573 			goto slow_done;
11574 		}
11575 	}
11576 udpslowpath:
11577 
11578 	/* Clear hardware checksum flag to be safe */
11579 	DB_CKSUMFLAGS(mp) = 0;
11580 
11581 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
11582 	    (ire->ire_type == IRE_BROADCAST),
11583 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11584 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11585 
11586 slow_done:
11587 	IP_STAT(ip_udp_slow_path);
11588 	return;
11589 
11590 #undef  iphs
11591 #undef  rptr
11592 }
11593 
11594 /* ARGSUSED */
11595 static mblk_t *
11596 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11597     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11598     ill_rx_ring_t *ill_ring)
11599 {
11600 	conn_t		*connp;
11601 	uint32_t	sum;
11602 	uint32_t	u1;
11603 	uint16_t	*up;
11604 	int		offset;
11605 	ssize_t		len;
11606 	mblk_t		*mp1;
11607 	boolean_t	syn_present = B_FALSE;
11608 	tcph_t		*tcph;
11609 	uint_t		ip_hdr_len;
11610 	ill_t		*ill = (ill_t *)q->q_ptr;
11611 	zoneid_t	zoneid = ire->ire_zoneid;
11612 	boolean_t	cksum_err;
11613 	uint16_t	hck_flags = 0;
11614 
11615 #define	rptr	((uchar_t *)ipha)
11616 
11617 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11618 
11619 	/*
11620 	 * FAST PATH for tcp packets
11621 	 */
11622 
11623 	/* u1 is # words of IP options */
11624 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11625 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11626 
11627 	/* IP options present */
11628 	if (u1) {
11629 		goto ipoptions;
11630 	} else {
11631 		/* Check the IP header checksum.  */
11632 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11633 			/* Clear the IP header h/w cksum flag */
11634 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11635 		} else {
11636 #define	uph	((uint16_t *)ipha)
11637 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11638 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11639 #undef	uph
11640 			/* finish doing IP checksum */
11641 			sum = (sum & 0xFFFF) + (sum >> 16);
11642 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11643 			/*
11644 			 * Don't verify header checksum if this packet
11645 			 * is coming back from AH/ESP as we already did it.
11646 			 */
11647 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11648 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11649 				goto error;
11650 			}
11651 		}
11652 	}
11653 
11654 	if (!mctl_present) {
11655 		UPDATE_IB_PKT_COUNT(ire);
11656 		ire->ire_last_used_time = lbolt;
11657 	}
11658 
11659 	/* packet part of fragmented IP packet? */
11660 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11661 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11662 		goto fragmented;
11663 	}
11664 
11665 	/* u1 = IP header length (20 bytes) */
11666 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11667 
11668 	/* does packet contain IP+TCP headers? */
11669 	len = mp->b_wptr - rptr;
11670 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11671 		IP_STAT(ip_tcppullup);
11672 		goto tcppullup;
11673 	}
11674 
11675 	/* TCP options present? */
11676 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11677 
11678 	/*
11679 	 * If options need to be pulled up, then goto tcpoptions.
11680 	 * otherwise we are still in the fast path
11681 	 */
11682 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11683 		IP_STAT(ip_tcpoptions);
11684 		goto tcpoptions;
11685 	}
11686 
11687 	/* multiple mblks of tcp data? */
11688 	if ((mp1 = mp->b_cont) != NULL) {
11689 		/* more then two? */
11690 		if (mp1->b_cont != NULL) {
11691 			IP_STAT(ip_multipkttcp);
11692 			goto multipkttcp;
11693 		}
11694 		len += mp1->b_wptr - mp1->b_rptr;
11695 	}
11696 
11697 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11698 
11699 	/* part of pseudo checksum */
11700 
11701 	/* TCP datagram length */
11702 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11703 
11704 #define	iphs    ((uint16_t *)ipha)
11705 
11706 #ifdef	_BIG_ENDIAN
11707 	u1 += IPPROTO_TCP;
11708 #else
11709 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11710 #endif
11711 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11712 
11713 	/*
11714 	 * Revert to software checksum calculation if the interface
11715 	 * isn't capable of checksum offload or if IPsec is present.
11716 	 */
11717 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11718 		hck_flags = DB_CKSUMFLAGS(mp);
11719 
11720 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11721 		IP_STAT(ip_in_sw_cksum);
11722 
11723 	IP_CKSUM_RECV(hck_flags, u1,
11724 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11725 	    (int32_t)((uchar_t *)up - rptr),
11726 	    mp, mp1, cksum_err);
11727 
11728 	if (cksum_err) {
11729 		BUMP_MIB(&ip_mib, tcpInErrs);
11730 
11731 		if (hck_flags & HCK_FULLCKSUM)
11732 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
11733 		else if (hck_flags & HCK_PARTIALCKSUM)
11734 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
11735 		else
11736 			IP_STAT(ip_tcp_in_sw_cksum_err);
11737 
11738 		goto error;
11739 	}
11740 
11741 try_again:
11742 
11743 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11744 	    NULL) {
11745 		/* Send the TH_RST */
11746 		goto no_conn;
11747 	}
11748 
11749 	/*
11750 	 * TCP FAST PATH for AF_INET socket.
11751 	 *
11752 	 * TCP fast path to avoid extra work. An AF_INET socket type
11753 	 * does not have facility to receive extra information via
11754 	 * ip_process or ip_add_info. Also, when the connection was
11755 	 * established, we made a check if this connection is impacted
11756 	 * by any global IPSec policy or per connection policy (a
11757 	 * policy that comes in effect later will not apply to this
11758 	 * connection). Since all this can be determined at the
11759 	 * connection establishment time, a quick check of flags
11760 	 * can avoid extra work.
11761 	 */
11762 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11763 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11764 		ASSERT(first_mp == mp);
11765 		SET_SQUEUE(mp, tcp_rput_data, connp);
11766 		return (mp);
11767 	}
11768 
11769 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11770 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11771 		if (IPCL_IS_TCP(connp)) {
11772 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11773 			DB_CKSUMSTART(mp) =
11774 			    (intptr_t)ip_squeue_get(ill_ring);
11775 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11776 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11777 				SET_SQUEUE(mp, connp->conn_recv, connp);
11778 				return (mp);
11779 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11780 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11781 				ip_squeue_enter_unbound++;
11782 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11783 				    connp);
11784 				return (mp);
11785 			}
11786 			syn_present = B_TRUE;
11787 		}
11788 
11789 	}
11790 
11791 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11792 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11793 
11794 		/* No need to send this packet to TCP */
11795 		if ((flags & TH_RST) || (flags & TH_URG)) {
11796 			CONN_DEC_REF(connp);
11797 			freemsg(first_mp);
11798 			return (NULL);
11799 		}
11800 		if (flags & TH_ACK) {
11801 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11802 			CONN_DEC_REF(connp);
11803 			return (NULL);
11804 		}
11805 
11806 		CONN_DEC_REF(connp);
11807 		freemsg(first_mp);
11808 		return (NULL);
11809 	}
11810 
11811 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11812 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11813 		    ipha, NULL, mctl_present);
11814 		if (first_mp == NULL) {
11815 			CONN_DEC_REF(connp);
11816 			return (NULL);
11817 		}
11818 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11819 			ASSERT(syn_present);
11820 			if (mctl_present) {
11821 				ASSERT(first_mp != mp);
11822 				first_mp->b_datap->db_struioflag |=
11823 				    STRUIO_POLICY;
11824 			} else {
11825 				ASSERT(first_mp == mp);
11826 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11827 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11828 			}
11829 		} else {
11830 			/*
11831 			 * Discard first_mp early since we're dealing with a
11832 			 * fully-connected conn_t and tcp doesn't do policy in
11833 			 * this case.
11834 			 */
11835 			if (mctl_present) {
11836 				freeb(first_mp);
11837 				mctl_present = B_FALSE;
11838 			}
11839 			first_mp = mp;
11840 		}
11841 	}
11842 
11843 	/* Initiate IPPF processing for fastpath */
11844 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11845 		uint32_t	ill_index;
11846 
11847 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11848 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11849 		if (mp == NULL) {
11850 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11851 			    "deferred/dropped during IPPF processing\n"));
11852 			CONN_DEC_REF(connp);
11853 			if (mctl_present)
11854 				freeb(first_mp);
11855 			return (NULL);
11856 		} else if (mctl_present) {
11857 			/*
11858 			 * ip_process might return a new mp.
11859 			 */
11860 			ASSERT(first_mp != mp);
11861 			first_mp->b_cont = mp;
11862 		} else {
11863 			first_mp = mp;
11864 		}
11865 
11866 	}
11867 
11868 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11869 		mp = ip_add_info(mp, recv_ill, flags);
11870 		if (mp == NULL) {
11871 			CONN_DEC_REF(connp);
11872 			if (mctl_present)
11873 				freeb(first_mp);
11874 			return (NULL);
11875 		} else if (mctl_present) {
11876 			/*
11877 			 * ip_add_info might return a new mp.
11878 			 */
11879 			ASSERT(first_mp != mp);
11880 			first_mp->b_cont = mp;
11881 		} else {
11882 			first_mp = mp;
11883 		}
11884 	}
11885 
11886 	if (IPCL_IS_TCP(connp)) {
11887 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11888 		return (first_mp);
11889 	} else {
11890 		putnext(connp->conn_rq, first_mp);
11891 		CONN_DEC_REF(connp);
11892 		return (NULL);
11893 	}
11894 
11895 no_conn:
11896 	/* Initiate IPPf processing, if needed. */
11897 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11898 		uint32_t ill_index;
11899 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11900 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
11901 		if (first_mp == NULL) {
11902 			return (NULL);
11903 		}
11904 	}
11905 	BUMP_MIB(&ip_mib, ipInDelivers);
11906 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
11907 	return (NULL);
11908 ipoptions:
11909 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
11910 		goto slow_done;
11911 	}
11912 
11913 	UPDATE_IB_PKT_COUNT(ire);
11914 	ire->ire_last_used_time = lbolt;
11915 
11916 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11917 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11918 fragmented:
11919 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
11920 			if (mctl_present)
11921 				freeb(first_mp);
11922 			goto slow_done;
11923 		}
11924 		/*
11925 		 * Make sure that first_mp points back to mp as
11926 		 * the mp we came in with could have changed in
11927 		 * ip_rput_fragment().
11928 		 */
11929 		ASSERT(!mctl_present);
11930 		ipha = (ipha_t *)mp->b_rptr;
11931 		first_mp = mp;
11932 	}
11933 
11934 tcp_slow:
11935 	/* Now we have a complete datagram, destined for this machine. */
11936 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
11937 
11938 	len = mp->b_wptr - mp->b_rptr;
11939 	/* Pull up a minimal TCP header, if necessary. */
11940 	if (len < (u1 + 20)) {
11941 tcppullup:
11942 		if (!pullupmsg(mp, u1 + 20)) {
11943 			BUMP_MIB(&ip_mib, ipInDiscards);
11944 			goto error;
11945 		}
11946 		ipha = (ipha_t *)mp->b_rptr;
11947 		len = mp->b_wptr - mp->b_rptr;
11948 	}
11949 
11950 	/*
11951 	 * Extract the offset field from the TCP header.  As usual, we
11952 	 * try to help the compiler more than the reader.
11953 	 */
11954 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
11955 	if (offset != 5) {
11956 tcpoptions:
11957 		if (offset < 5) {
11958 			BUMP_MIB(&ip_mib, ipInDiscards);
11959 			goto error;
11960 		}
11961 		/*
11962 		 * There must be TCP options.
11963 		 * Make sure we can grab them.
11964 		 */
11965 		offset <<= 2;
11966 		offset += u1;
11967 		if (len < offset) {
11968 			if (!pullupmsg(mp, offset)) {
11969 				BUMP_MIB(&ip_mib, ipInDiscards);
11970 				goto error;
11971 			}
11972 			ipha = (ipha_t *)mp->b_rptr;
11973 			len = mp->b_wptr - rptr;
11974 		}
11975 	}
11976 
11977 	/* Get the total packet length in len, including headers. */
11978 	if (mp->b_cont) {
11979 multipkttcp:
11980 		len = msgdsize(mp);
11981 	}
11982 
11983 	/*
11984 	 * Check the TCP checksum by pulling together the pseudo-
11985 	 * header checksum, and passing it to ip_csum to be added in
11986 	 * with the TCP datagram.
11987 	 *
11988 	 * Since we are not using the hwcksum if available we must
11989 	 * clear the flag. We may come here via tcppullup or tcpoptions.
11990 	 * If either of these fails along the way the mblk is freed.
11991 	 * If this logic ever changes and mblk is reused to say send
11992 	 * ICMP's back, then this flag may need to be cleared in
11993 	 * other places as well.
11994 	 */
11995 	DB_CKSUMFLAGS(mp) = 0;
11996 
11997 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
11998 
11999 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12000 #ifdef	_BIG_ENDIAN
12001 	u1 += IPPROTO_TCP;
12002 #else
12003 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12004 #endif
12005 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12006 	/*
12007 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12008 	 */
12009 	IP_STAT(ip_in_sw_cksum);
12010 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12011 		BUMP_MIB(&ip_mib, tcpInErrs);
12012 		goto error;
12013 	}
12014 
12015 	IP_STAT(ip_tcp_slow_path);
12016 	goto try_again;
12017 #undef  iphs
12018 #undef  rptr
12019 
12020 error:
12021 	freemsg(first_mp);
12022 slow_done:
12023 	return (NULL);
12024 }
12025 
12026 /* ARGSUSED */
12027 static void
12028 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12029     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12030 {
12031 	conn_t		*connp;
12032 	uint32_t	sum;
12033 	uint32_t	u1;
12034 	ssize_t		len;
12035 	sctp_hdr_t	*sctph;
12036 	zoneid_t	zoneid = ire->ire_zoneid;
12037 	uint32_t	pktsum;
12038 	uint32_t	calcsum;
12039 	uint32_t	ports;
12040 	uint_t		ipif_seqid;
12041 	in6_addr_t	map_src, map_dst;
12042 	ill_t		*ill = (ill_t *)q->q_ptr;
12043 
12044 #define	rptr	((uchar_t *)ipha)
12045 
12046 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12047 
12048 	/* u1 is # words of IP options */
12049 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12050 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12051 
12052 	/* IP options present */
12053 	if (u1 > 0) {
12054 		goto ipoptions;
12055 	} else {
12056 		/* Check the IP header checksum.  */
12057 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12058 			/*
12059 			 * Since there is no SCTP h/w cksum support yet, just
12060 			 * clear the flag.
12061 			 */
12062 			DB_CKSUMFLAGS(mp) = 0;
12063 		} else {
12064 #define	uph	((uint16_t *)ipha)
12065 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12066 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12067 #undef	uph
12068 			/* finish doing IP checksum */
12069 			sum = (sum & 0xFFFF) + (sum >> 16);
12070 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12071 			/*
12072 			 * Don't verify header checksum if this packet
12073 			 * is coming back from AH/ESP as we already did it.
12074 			 */
12075 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12076 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12077 				goto error;
12078 			}
12079 		}
12080 	}
12081 
12082 	/*
12083 	 * Don't verify header checksum if this packet is coming
12084 	 * back from AH/ESP as we already did it.
12085 	 */
12086 	if (!mctl_present) {
12087 		UPDATE_IB_PKT_COUNT(ire);
12088 		ire->ire_last_used_time = lbolt;
12089 	}
12090 
12091 	/* packet part of fragmented IP packet? */
12092 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12093 	if (u1 & (IPH_MF | IPH_OFFSET))
12094 		goto fragmented;
12095 
12096 	/* u1 = IP header length (20 bytes) */
12097 	u1 = IP_SIMPLE_HDR_LENGTH;
12098 
12099 find_sctp_client:
12100 	/* Pullup if we don't have the sctp common header. */
12101 	len = MBLKL(mp);
12102 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12103 		if (mp->b_cont == NULL ||
12104 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12105 			BUMP_MIB(&ip_mib, ipInDiscards);
12106 			goto error;
12107 		}
12108 		ipha = (ipha_t *)mp->b_rptr;
12109 		len = MBLKL(mp);
12110 	}
12111 
12112 	sctph = (sctp_hdr_t *)(rptr + u1);
12113 #ifdef	DEBUG
12114 	if (!skip_sctp_cksum) {
12115 #endif
12116 		pktsum = sctph->sh_chksum;
12117 		sctph->sh_chksum = 0;
12118 		calcsum = sctp_cksum(mp, u1);
12119 		if (calcsum != pktsum) {
12120 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12121 			goto error;
12122 		}
12123 		sctph->sh_chksum = pktsum;
12124 #ifdef	DEBUG	/* skip_sctp_cksum */
12125 	}
12126 #endif
12127 	/* get the ports */
12128 	ports = *(uint32_t *)&sctph->sh_sport;
12129 
12130 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12131 	IRE_REFRELE(ire);
12132 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12133 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12134 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12135 	    zoneid)) == NULL) {
12136 		/* Check for raw socket or OOTB handling */
12137 		goto no_conn;
12138 	}
12139 
12140 	/* Found a client; up it goes */
12141 	BUMP_MIB(&ip_mib, ipInDelivers);
12142 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12143 	return;
12144 
12145 no_conn:
12146 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12147 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12148 	return;
12149 
12150 ipoptions:
12151 	DB_CKSUMFLAGS(mp) = 0;
12152 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12153 		goto slow_done;
12154 
12155 	UPDATE_IB_PKT_COUNT(ire);
12156 	ire->ire_last_used_time = lbolt;
12157 
12158 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12159 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12160 fragmented:
12161 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12162 			goto slow_done;
12163 		/*
12164 		 * Make sure that first_mp points back to mp as
12165 		 * the mp we came in with could have changed in
12166 		 * ip_rput_fragment().
12167 		 */
12168 		ASSERT(!mctl_present);
12169 		ipha = (ipha_t *)mp->b_rptr;
12170 		first_mp = mp;
12171 	}
12172 
12173 	/* Now we have a complete datagram, destined for this machine. */
12174 	u1 = IPH_HDR_LENGTH(ipha);
12175 	goto find_sctp_client;
12176 #undef  iphs
12177 #undef  rptr
12178 
12179 error:
12180 	freemsg(first_mp);
12181 slow_done:
12182 	IRE_REFRELE(ire);
12183 }
12184 
12185 #define	VER_BITS	0xF0
12186 #define	VERSION_6	0x60
12187 
12188 static boolean_t
12189 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12190     ipaddr_t *dstp)
12191 {
12192 	uint_t	opt_len;
12193 	ipha_t *ipha;
12194 	ssize_t len;
12195 	uint_t	pkt_len;
12196 
12197 	IP_STAT(ip_ipoptions);
12198 	ipha = *iphapp;
12199 
12200 #define	rptr    ((uchar_t *)ipha)
12201 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12202 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12203 		BUMP_MIB(&ip_mib, ipInIPv6);
12204 		freemsg(mp);
12205 		return (B_FALSE);
12206 	}
12207 
12208 	/* multiple mblk or too short */
12209 	pkt_len = ntohs(ipha->ipha_length);
12210 
12211 	/* Get the number of words of IP options in the IP header. */
12212 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12213 	if (opt_len) {
12214 		/* IP Options present!  Validate and process. */
12215 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12216 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12217 			goto done;
12218 		}
12219 		/*
12220 		 * Recompute complete header length and make sure we
12221 		 * have access to all of it.
12222 		 */
12223 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12224 		if (len > (mp->b_wptr - rptr)) {
12225 			if (len > pkt_len) {
12226 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12227 				goto done;
12228 			}
12229 			if (!pullupmsg(mp, len)) {
12230 				BUMP_MIB(&ip_mib, ipInDiscards);
12231 				goto done;
12232 			}
12233 			ipha = (ipha_t *)mp->b_rptr;
12234 		}
12235 		/*
12236 		 * Go off to ip_rput_options which returns the next hop
12237 		 * destination address, which may have been affected
12238 		 * by source routing.
12239 		 */
12240 		IP_STAT(ip_opt);
12241 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12242 			return (B_FALSE);
12243 		}
12244 	}
12245 	*iphapp = ipha;
12246 	return (B_TRUE);
12247 done:
12248 	/* clear b_prev - used by ip_mroute_decap */
12249 	mp->b_prev = NULL;
12250 	freemsg(mp);
12251 	return (B_FALSE);
12252 #undef  rptr
12253 }
12254 
12255 /*
12256  * Deal with the fact that there is no ire for the destination.
12257  * The incoming ill (in_ill) is passed in to ip_newroute only
12258  * in the case of packets coming from mobile ip forward tunnel.
12259  * It must be null otherwise.
12260  */
12261 static void
12262 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12263     ipaddr_t dst)
12264 {
12265 	ipha_t	*ipha;
12266 	ill_t	*ill;
12267 
12268 	ipha = (ipha_t *)mp->b_rptr;
12269 	ill = (ill_t *)q->q_ptr;
12270 
12271 	ASSERT(ill != NULL);
12272 	/*
12273 	 * No IRE for this destination, so it can't be for us.
12274 	 * Unless we are forwarding, drop the packet.
12275 	 * We have to let source routed packets through
12276 	 * since we don't yet know if they are 'ping -l'
12277 	 * packets i.e. if they will go out over the
12278 	 * same interface as they came in on.
12279 	 */
12280 	if (ll_multicast) {
12281 		freemsg(mp);
12282 		return;
12283 	}
12284 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12285 		BUMP_MIB(&ip_mib, ipForwProhibits);
12286 		freemsg(mp);
12287 		return;
12288 	}
12289 
12290 	/* Check for Martian addresses */
12291 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12292 		freemsg(mp);
12293 		return;
12294 	}
12295 
12296 	/* Mark this packet as having originated externally */
12297 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12298 
12299 	/*
12300 	 * Clear the indication that this may have a hardware checksum
12301 	 * as we are not using it
12302 	 */
12303 	DB_CKSUMFLAGS(mp) = 0;
12304 
12305 	/*
12306 	 * Now hand the packet to ip_newroute.
12307 	 */
12308 	ip_newroute(q, mp, dst, in_ill, NULL);
12309 }
12310 
12311 /*
12312  * check ip header length and align it.
12313  */
12314 static boolean_t
12315 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12316 {
12317 	ssize_t len;
12318 	ill_t *ill;
12319 	ipha_t	*ipha;
12320 
12321 	len = MBLKL(mp);
12322 
12323 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12324 		if (!OK_32PTR(mp->b_rptr))
12325 			IP_STAT(ip_notaligned1);
12326 		else
12327 			IP_STAT(ip_notaligned2);
12328 		/* Guard against bogus device drivers */
12329 		if (len < 0) {
12330 			/* clear b_prev - used by ip_mroute_decap */
12331 			mp->b_prev = NULL;
12332 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12333 			freemsg(mp);
12334 			return (B_FALSE);
12335 		}
12336 
12337 		if (ip_rput_pullups++ == 0) {
12338 			ill = (ill_t *)q->q_ptr;
12339 			ipha = (ipha_t *)mp->b_rptr;
12340 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12341 			    "ip_check_and_align_header: %s forced us to "
12342 			    " pullup pkt, hdr len %ld, hdr addr %p",
12343 			    ill->ill_name, len, ipha);
12344 		}
12345 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12346 			/* clear b_prev - used by ip_mroute_decap */
12347 			mp->b_prev = NULL;
12348 			BUMP_MIB(&ip_mib, ipInDiscards);
12349 			freemsg(mp);
12350 			return (B_FALSE);
12351 		}
12352 	}
12353 	return (B_TRUE);
12354 }
12355 
12356 static boolean_t
12357 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12358 {
12359 	ill_group_t	*ill_group;
12360 	ill_group_t	*ire_group;
12361 	queue_t 	*q;
12362 	ill_t		*ire_ill;
12363 	uint_t		ill_ifindex;
12364 
12365 	q = *qp;
12366 	/*
12367 	 * We need to check to make sure the packet came in
12368 	 * on the queue associated with the destination IRE.
12369 	 * Note that for multicast packets and broadcast packets sent to
12370 	 * a broadcast address which is shared between multiple interfaces
12371 	 * we should not do this since we just got a random broadcast ire.
12372 	 */
12373 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12374 		boolean_t check_multi = B_TRUE;
12375 
12376 		/*
12377 		 * This packet came in on an interface other than the
12378 		 * one associated with the destination address.
12379 		 * "Gateway" it to the appropriate interface here.
12380 		 * As long as the ills belong to the same group,
12381 		 * we don't consider them to arriving on the wrong
12382 		 * interface. Thus, when the switch is doing inbound
12383 		 * load spreading, we won't drop packets when we
12384 		 * are doing strict multihoming checks. Note, the
12385 		 * same holds true for 'usesrc groups' where the
12386 		 * destination address may belong to another interface
12387 		 * to allow multipathing to happen
12388 		 */
12389 		ill_group = ill->ill_group;
12390 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12391 		ill_ifindex = ill->ill_usesrc_ifindex;
12392 		ire_group = ire_ill->ill_group;
12393 
12394 		/*
12395 		 * If it's part of the same IPMP group, or if it's a legal
12396 		 * address on the 'usesrc' interface, then bypass strict
12397 		 * checks.
12398 		 */
12399 		if (ill_group != NULL && ill_group == ire_group) {
12400 			check_multi = B_FALSE;
12401 		} else if (ill_ifindex != 0 &&
12402 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12403 			check_multi = B_FALSE;
12404 		}
12405 
12406 		if (check_multi &&
12407 		    ip_strict_dst_multihoming &&
12408 		    ((ill->ill_flags &
12409 		    ire->ire_ipif->ipif_ill->ill_flags &
12410 		    ILLF_ROUTER) == 0)) {
12411 			/* Drop packet */
12412 			BUMP_MIB(&ip_mib, ipForwProhibits);
12413 			freemsg(mp);
12414 			ire_refrele(ire);
12415 			return (B_TRUE);
12416 		}
12417 
12418 		/*
12419 		 * Change the queue (for non-virtual destination network
12420 		 * interfaces) and ip_rput_local will be called with the right
12421 		 * queue
12422 		 */
12423 		q = ire->ire_rfq;
12424 	}
12425 	/* Must be broadcast.  We'll take it. */
12426 	*qp = q;
12427 	return (B_FALSE);
12428 }
12429 
12430 static void
12431 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12432     ill_t *ill, int ll_multicast)
12433 {
12434 	ill_group_t	*ill_group;
12435 	ill_group_t	*ire_group;
12436 	queue_t	*dev_q;
12437 
12438 	ASSERT(ire->ire_stq != NULL);
12439 	if (ll_multicast != 0)
12440 		goto drop_pkt;
12441 
12442 	if (ip_no_forward(ipha, ill))
12443 		goto drop_pkt;
12444 
12445 	ill_group = ill->ill_group;
12446 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12447 	/*
12448 	 * Check if we want to forward this one at this time.
12449 	 * We allow source routed packets on a host provided that
12450 	 * they go out the same interface or same interface group
12451 	 * as they came in on.
12452 	 *
12453 	 * XXX To be quicker, we may wish to not chase pointers to
12454 	 * get the ILLF_ROUTER flag and instead store the
12455 	 * forwarding policy in the ire.  An unfortunate
12456 	 * side-effect of that would be requiring an ire flush
12457 	 * whenever the ILLF_ROUTER flag changes.
12458 	 */
12459 	if (((ill->ill_flags &
12460 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12461 	    ILLF_ROUTER) == 0) &&
12462 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12463 	    (ill_group != NULL && ill_group == ire_group)))) {
12464 		BUMP_MIB(&ip_mib, ipForwProhibits);
12465 		if (ip_source_routed(ipha)) {
12466 			q = WR(q);
12467 			/*
12468 			 * Clear the indication that this may have
12469 			 * hardware checksum as we are not using it.
12470 			 */
12471 			DB_CKSUMFLAGS(mp) = 0;
12472 			icmp_unreachable(q, mp,
12473 			    ICMP_SOURCE_ROUTE_FAILED);
12474 			ire_refrele(ire);
12475 			return;
12476 		}
12477 		goto drop_pkt;
12478 	}
12479 
12480 	/* Packet is being forwarded. Turning off hwcksum flag. */
12481 	DB_CKSUMFLAGS(mp) = 0;
12482 	if (ip_g_send_redirects) {
12483 		/*
12484 		 * Check whether the incoming interface and outgoing
12485 		 * interface is part of the same group. If so,
12486 		 * send redirects.
12487 		 *
12488 		 * Check the source address to see if it originated
12489 		 * on the same logical subnet it is going back out on.
12490 		 * If so, we should be able to send it a redirect.
12491 		 * Avoid sending a redirect if the destination
12492 		 * is directly connected (gw_addr == 0),
12493 		 * or if the packet was source routed out this
12494 		 * interface.
12495 		 */
12496 		ipaddr_t src;
12497 		mblk_t	*mp1;
12498 		ire_t	*src_ire = NULL;
12499 
12500 		/*
12501 		 * Check whether ire_rfq and q are from the same ill
12502 		 * or if they are not same, they at least belong
12503 		 * to the same group. If so, send redirects.
12504 		 */
12505 		if ((ire->ire_rfq == q ||
12506 		    (ill_group != NULL && ill_group == ire_group)) &&
12507 		    (ire->ire_gateway_addr != 0) &&
12508 		    !ip_source_routed(ipha)) {
12509 
12510 			src = ipha->ipha_src;
12511 			src_ire = ire_ftable_lookup(src, 0, 0,
12512 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12513 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12514 
12515 			if (src_ire != NULL) {
12516 				/*
12517 				 * The source is directly connected.
12518 				 * Just copy the ip header (which is
12519 				 * in the first mblk)
12520 				 */
12521 				mp1 = copyb(mp);
12522 				if (mp1 != NULL) {
12523 					icmp_send_redirect(WR(q), mp1,
12524 					    ire->ire_gateway_addr);
12525 				}
12526 				ire_refrele(src_ire);
12527 			}
12528 		}
12529 	}
12530 
12531 	dev_q = ire->ire_stq->q_next;
12532 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12533 		BUMP_MIB(&ip_mib, ipInDiscards);
12534 		freemsg(mp);
12535 		ire_refrele(ire);
12536 		return;
12537 	}
12538 
12539 	ip_rput_forward(ire, ipha, mp, ill);
12540 	IRE_REFRELE(ire);
12541 	return;
12542 
12543 drop_pkt:
12544 	ire_refrele(ire);
12545 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12546 	freemsg(mp);
12547 }
12548 
12549 static boolean_t
12550 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12551     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12552 {
12553 	queue_t		*q;
12554 	ire_t		*ire;
12555 	uint16_t	hcksumflags;
12556 
12557 	q = *qp;
12558 	ire = *irep;
12559 
12560 	/*
12561 	 * Clear the indication that this may have hardware
12562 	 * checksum as we are not using it for forwarding.
12563 	 */
12564 	hcksumflags = DB_CKSUMFLAGS(mp);
12565 	DB_CKSUMFLAGS(mp) = 0;
12566 
12567 	/*
12568 	 * Directed broadcast forwarding: if the packet came in over a
12569 	 * different interface then it is routed out over we can forward it.
12570 	 */
12571 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12572 		ire_refrele(ire);
12573 		freemsg(mp);
12574 		BUMP_MIB(&ip_mib, ipInDiscards);
12575 		return (B_TRUE);
12576 	}
12577 	/*
12578 	 * For multicast we have set dst to be INADDR_BROADCAST
12579 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12580 	 * only for broadcast packets.
12581 	 */
12582 	if (!CLASSD(ipha->ipha_dst)) {
12583 		ire_t *new_ire;
12584 		ipif_t *ipif;
12585 		/*
12586 		 * For ill groups, as the switch duplicates broadcasts
12587 		 * across all the ports, we need to filter out and
12588 		 * send up only one copy. There is one copy for every
12589 		 * broadcast address on each ill. Thus, we look for a
12590 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12591 		 * later to see whether this ill is eligible to receive
12592 		 * them or not. ill_nominate_bcast_rcv() nominates only
12593 		 * one set of IREs for receiving.
12594 		 */
12595 
12596 		ipif = ipif_get_next_ipif(NULL, ill);
12597 		if (ipif == NULL) {
12598 			ire_refrele(ire);
12599 			freemsg(mp);
12600 			BUMP_MIB(&ip_mib, ipInDiscards);
12601 			return (B_TRUE);
12602 		}
12603 		new_ire = ire_ctable_lookup(dst, 0, 0,
12604 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12605 		ipif_refrele(ipif);
12606 
12607 		if (new_ire != NULL) {
12608 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12609 				ire_refrele(ire);
12610 				ire_refrele(new_ire);
12611 				freemsg(mp);
12612 				BUMP_MIB(&ip_mib, ipInDiscards);
12613 				return (B_TRUE);
12614 			}
12615 			/*
12616 			 * In the special case of multirouted broadcast
12617 			 * packets, we unconditionally need to "gateway"
12618 			 * them to the appropriate interface here.
12619 			 * In the normal case, this cannot happen, because
12620 			 * there is no broadcast IRE tagged with the
12621 			 * RTF_MULTIRT flag.
12622 			 */
12623 			if (new_ire->ire_flags & RTF_MULTIRT) {
12624 				ire_refrele(new_ire);
12625 				if (ire->ire_rfq != NULL) {
12626 					q = ire->ire_rfq;
12627 					*qp = q;
12628 				}
12629 			} else {
12630 				ire_refrele(ire);
12631 				ire = new_ire;
12632 			}
12633 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12634 			if (!ip_g_forward_directed_bcast) {
12635 				/*
12636 				 * Free the message if
12637 				 * ip_g_forward_directed_bcast is turned
12638 				 * off for non-local broadcast.
12639 				 */
12640 				ire_refrele(ire);
12641 				freemsg(mp);
12642 				BUMP_MIB(&ip_mib, ipInDiscards);
12643 				return (B_TRUE);
12644 			}
12645 		} else {
12646 			/*
12647 			 * This CGTP packet successfully passed the
12648 			 * CGTP filter, but the related CGTP
12649 			 * broadcast IRE has not been found,
12650 			 * meaning that the redundant ipif is
12651 			 * probably down. However, if we discarded
12652 			 * this packet, its duplicate would be
12653 			 * filtered out by the CGTP filter so none
12654 			 * of them would get through. So we keep
12655 			 * going with this one.
12656 			 */
12657 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12658 			if (ire->ire_rfq != NULL) {
12659 				q = ire->ire_rfq;
12660 				*qp = q;
12661 			}
12662 		}
12663 	}
12664 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12665 		/*
12666 		 * Verify that there are not more then one
12667 		 * IRE_BROADCAST with this broadcast address which
12668 		 * has ire_stq set.
12669 		 * TODO: simplify, loop over all IRE's
12670 		 */
12671 		ire_t	*ire1;
12672 		int	num_stq = 0;
12673 		mblk_t	*mp1;
12674 
12675 		/* Find the first one with ire_stq set */
12676 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12677 		for (ire1 = ire; ire1 &&
12678 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12679 		    ire1 = ire1->ire_next)
12680 			;
12681 		if (ire1) {
12682 			ire_refrele(ire);
12683 			ire = ire1;
12684 			IRE_REFHOLD(ire);
12685 		}
12686 
12687 		/* Check if there are additional ones with stq set */
12688 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12689 			if (ire->ire_addr != ire1->ire_addr)
12690 				break;
12691 			if (ire1->ire_stq) {
12692 				num_stq++;
12693 				break;
12694 			}
12695 		}
12696 		rw_exit(&ire->ire_bucket->irb_lock);
12697 		if (num_stq == 1 && ire->ire_stq != NULL) {
12698 			ip1dbg(("ip_rput_process_broadcast: directed "
12699 			    "broadcast to 0x%x\n",
12700 			    ntohl(ire->ire_addr)));
12701 			mp1 = copymsg(mp);
12702 			if (mp1) {
12703 				switch (ipha->ipha_protocol) {
12704 				case IPPROTO_UDP:
12705 					ip_udp_input(q, mp1, ipha, ire, ill);
12706 					break;
12707 				default:
12708 					ip_proto_input(q, mp1, ipha, ire, ill);
12709 					break;
12710 				}
12711 			}
12712 			/*
12713 			 * Adjust ttl to 2 (1+1 - the forward engine
12714 			 * will decrement it by one.
12715 			 */
12716 			if (ip_csum_hdr(ipha)) {
12717 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12718 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12719 				freemsg(mp);
12720 				ire_refrele(ire);
12721 				return (B_TRUE);
12722 			}
12723 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12724 			ipha->ipha_hdr_checksum = 0;
12725 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12726 			ip_rput_process_forward(q, mp, ire, ipha,
12727 			    ill, ll_multicast);
12728 			return (B_TRUE);
12729 		}
12730 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12731 		    ntohl(ire->ire_addr)));
12732 	}
12733 
12734 	*irep = ire;
12735 
12736 	/* Restore any hardware checksum flags */
12737 	DB_CKSUMFLAGS(mp) = hcksumflags;
12738 	return (B_FALSE);
12739 }
12740 
12741 /* ARGSUSED */
12742 static boolean_t
12743 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12744     int *ll_multicast, ipaddr_t *dstp)
12745 {
12746 	/*
12747 	 * Forward packets only if we have joined the allmulti
12748 	 * group on this interface.
12749 	 */
12750 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12751 		int retval;
12752 
12753 		/*
12754 		 * Clear the indication that this may have hardware
12755 		 * checksum as we are not using it.
12756 		 */
12757 		DB_CKSUMFLAGS(mp) = 0;
12758 		retval = ip_mforward(ill, ipha, mp);
12759 		/* ip_mforward updates mib variables if needed */
12760 		/* clear b_prev - used by ip_mroute_decap */
12761 		mp->b_prev = NULL;
12762 
12763 		switch (retval) {
12764 		case 0:
12765 			/*
12766 			 * pkt is okay and arrived on phyint.
12767 			 *
12768 			 * If we are running as a multicast router
12769 			 * we need to see all IGMP and/or PIM packets.
12770 			 */
12771 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12772 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12773 				goto done;
12774 			}
12775 			break;
12776 		case -1:
12777 			/* pkt is mal-formed, toss it */
12778 			goto drop_pkt;
12779 		case 1:
12780 			/* pkt is okay and arrived on a tunnel */
12781 			/*
12782 			 * If we are running a multicast router
12783 			 *  we need to see all igmp packets.
12784 			 */
12785 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12786 				*dstp = INADDR_BROADCAST;
12787 				*ll_multicast = 1;
12788 				return (B_FALSE);
12789 			}
12790 
12791 			goto drop_pkt;
12792 		}
12793 	}
12794 
12795 	ILM_WALKER_HOLD(ill);
12796 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12797 		/*
12798 		 * This might just be caused by the fact that
12799 		 * multiple IP Multicast addresses map to the same
12800 		 * link layer multicast - no need to increment counter!
12801 		 */
12802 		ILM_WALKER_RELE(ill);
12803 		freemsg(mp);
12804 		return (B_TRUE);
12805 	}
12806 	ILM_WALKER_RELE(ill);
12807 done:
12808 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12809 	/*
12810 	 * This assumes the we deliver to all streams for multicast
12811 	 * and broadcast packets.
12812 	 */
12813 	*dstp = INADDR_BROADCAST;
12814 	*ll_multicast = 1;
12815 	return (B_FALSE);
12816 drop_pkt:
12817 	ip2dbg(("ip_rput: drop pkt\n"));
12818 	freemsg(mp);
12819 	return (B_TRUE);
12820 }
12821 
12822 static boolean_t
12823 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12824     int *ll_multicast, mblk_t **mpp)
12825 {
12826 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12827 	boolean_t must_copy = B_FALSE;
12828 	struct iocblk   *iocp;
12829 	ipha_t		*ipha;
12830 
12831 #define	rptr    ((uchar_t *)ipha)
12832 
12833 	first_mp = *first_mpp;
12834 	mp = *mpp;
12835 
12836 	ASSERT(first_mp == mp);
12837 
12838 	/*
12839 	 * if db_ref > 1 then copymsg and free original. Packet may be
12840 	 * changed and do not want other entity who has a reference to this
12841 	 * message to trip over the changes. This is a blind change because
12842 	 * trying to catch all places that might change packet is too
12843 	 * difficult (since it may be a module above this one)
12844 	 *
12845 	 * This corresponds to the non-fast path case. We walk down the full
12846 	 * chain in this case, and check the db_ref count of all the dblks,
12847 	 * and do a copymsg if required. It is possible that the db_ref counts
12848 	 * of the data blocks in the mblk chain can be different.
12849 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12850 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12851 	 * 'snoop' is running.
12852 	 */
12853 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12854 		if (mp1->b_datap->db_ref > 1) {
12855 			must_copy = B_TRUE;
12856 			break;
12857 		}
12858 	}
12859 
12860 	if (must_copy) {
12861 		mp1 = copymsg(mp);
12862 		if (mp1 == NULL) {
12863 			for (mp1 = mp; mp1 != NULL;
12864 			    mp1 = mp1->b_cont) {
12865 				mp1->b_next = NULL;
12866 				mp1->b_prev = NULL;
12867 			}
12868 			freemsg(mp);
12869 			BUMP_MIB(&ip_mib, ipInDiscards);
12870 			return (B_TRUE);
12871 		}
12872 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12873 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12874 			/* Copy b_next - used in M_BREAK messages */
12875 			to_mp->b_next = from_mp->b_next;
12876 			from_mp->b_next = NULL;
12877 			/* Copy b_prev - used by ip_mroute_decap */
12878 			to_mp->b_prev = from_mp->b_prev;
12879 			from_mp->b_prev = NULL;
12880 		}
12881 		*first_mpp = first_mp = mp1;
12882 		freemsg(mp);
12883 		mp = mp1;
12884 		*mpp = mp1;
12885 	}
12886 
12887 	ipha = (ipha_t *)mp->b_rptr;
12888 
12889 	/*
12890 	 * previous code has a case for M_DATA.
12891 	 * We want to check how that happens.
12892 	 */
12893 	ASSERT(first_mp->b_datap->db_type != M_DATA);
12894 	switch (first_mp->b_datap->db_type) {
12895 	case M_PROTO:
12896 	case M_PCPROTO:
12897 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
12898 		    DL_UNITDATA_IND) {
12899 			/* Go handle anything other than data elsewhere. */
12900 			ip_rput_dlpi(q, mp);
12901 			return (B_TRUE);
12902 		}
12903 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
12904 		/* Ditch the DLPI header. */
12905 		mp1 = mp->b_cont;
12906 		ASSERT(first_mp == mp);
12907 		*first_mpp = mp1;
12908 		freeb(mp);
12909 		*mpp = mp1;
12910 		return (B_FALSE);
12911 	case M_BREAK:
12912 		/*
12913 		 * A packet arrives as M_BREAK following a cycle through
12914 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
12915 		 * This is an IP datagram sans lower level header.
12916 		 * M_BREAK are also used to pass back in multicast packets
12917 		 * that are encapsulated with a source route.
12918 		 */
12919 		/* Ditch the M_BREAK mblk */
12920 		mp1 = mp->b_cont;
12921 		ASSERT(first_mp == mp);
12922 		*first_mpp = mp1;
12923 		freeb(mp);
12924 		mp = mp1;
12925 		mp->b_next = NULL;
12926 		*mpp = mp;
12927 		*ll_multicast = 0;
12928 		return (B_FALSE);
12929 	case M_IOCACK:
12930 		ip1dbg(("got iocack "));
12931 		iocp = (struct iocblk *)mp->b_rptr;
12932 		switch (iocp->ioc_cmd) {
12933 		case DL_IOC_HDR_INFO:
12934 			ill = (ill_t *)q->q_ptr;
12935 			ill_fastpath_ack(ill, mp);
12936 			return (B_TRUE);
12937 		case SIOCSTUNPARAM:
12938 		case OSIOCSTUNPARAM:
12939 			/* Go through qwriter_ip */
12940 			break;
12941 		case SIOCGTUNPARAM:
12942 		case OSIOCGTUNPARAM:
12943 			ip_rput_other(NULL, q, mp, NULL);
12944 			return (B_TRUE);
12945 		default:
12946 			putnext(q, mp);
12947 			return (B_TRUE);
12948 		}
12949 		/* FALLTHRU */
12950 	case M_ERROR:
12951 	case M_HANGUP:
12952 		/*
12953 		 * Since this is on the ill stream we unconditionally
12954 		 * bump up the refcount
12955 		 */
12956 		ill_refhold(ill);
12957 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
12958 		    B_FALSE);
12959 		return (B_TRUE);
12960 	case M_CTL:
12961 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
12962 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
12963 			IPHADA_M_CTL)) {
12964 			/*
12965 			 * It's an IPsec accelerated packet.
12966 			 * Make sure that the ill from which we received the
12967 			 * packet has enabled IPsec hardware acceleration.
12968 			 */
12969 			if (!(ill->ill_capabilities &
12970 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
12971 				/* IPsec kstats: bean counter */
12972 				freemsg(mp);
12973 				return (B_TRUE);
12974 			}
12975 
12976 			/*
12977 			 * Make mp point to the mblk following the M_CTL,
12978 			 * then process according to type of mp.
12979 			 * After this processing, first_mp will point to
12980 			 * the data-attributes and mp to the pkt following
12981 			 * the M_CTL.
12982 			 */
12983 			mp = first_mp->b_cont;
12984 			if (mp == NULL) {
12985 				freemsg(first_mp);
12986 				return (B_TRUE);
12987 			}
12988 			/*
12989 			 * A Hardware Accelerated packet can only be M_DATA
12990 			 * ESP or AH packet.
12991 			 */
12992 			if (mp->b_datap->db_type != M_DATA) {
12993 				/* non-M_DATA IPsec accelerated packet */
12994 				IPSECHW_DEBUG(IPSECHW_PKT,
12995 				    ("non-M_DATA IPsec accelerated pkt\n"));
12996 				freemsg(first_mp);
12997 				return (B_TRUE);
12998 			}
12999 			ipha = (ipha_t *)mp->b_rptr;
13000 			if (ipha->ipha_protocol != IPPROTO_AH &&
13001 			    ipha->ipha_protocol != IPPROTO_ESP) {
13002 				IPSECHW_DEBUG(IPSECHW_PKT,
13003 				    ("non-M_DATA IPsec accelerated pkt\n"));
13004 				freemsg(first_mp);
13005 				return (B_TRUE);
13006 			}
13007 			*mpp = mp;
13008 			return (B_FALSE);
13009 		}
13010 		putnext(q, mp);
13011 		return (B_TRUE);
13012 	case M_FLUSH:
13013 		if (*mp->b_rptr & FLUSHW) {
13014 			*mp->b_rptr &= ~FLUSHR;
13015 			qreply(q, mp);
13016 			return (B_TRUE);
13017 		}
13018 		freemsg(mp);
13019 		return (B_TRUE);
13020 	case M_IOCNAK:
13021 		ip1dbg(("got iocnak "));
13022 		iocp = (struct iocblk *)mp->b_rptr;
13023 		switch (iocp->ioc_cmd) {
13024 		case DL_IOC_HDR_INFO:
13025 		case SIOCSTUNPARAM:
13026 		case OSIOCSTUNPARAM:
13027 			/*
13028 			 * Since this is on the ill stream we unconditionally
13029 			 * bump up the refcount
13030 			 */
13031 			ill_refhold(ill);
13032 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13033 			    CUR_OP, B_FALSE);
13034 			return (B_TRUE);
13035 		case SIOCGTUNPARAM:
13036 		case OSIOCGTUNPARAM:
13037 			ip_rput_other(NULL, q, mp, NULL);
13038 			return (B_TRUE);
13039 		default:
13040 			break;
13041 		}
13042 		/* FALLTHRU */
13043 	default:
13044 		putnext(q, mp);
13045 		return (B_TRUE);
13046 	}
13047 }
13048 
13049 /* Read side put procedure.  Packets coming from the wire arrive here. */
13050 void
13051 ip_rput(queue_t *q, mblk_t *mp)
13052 {
13053 	ill_t		*ill;
13054 
13055 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13056 
13057 	ill = (ill_t *)q->q_ptr;
13058 
13059 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13060 		union DL_primitives *dl;
13061 
13062 		/*
13063 		 * Things are opening or closing. Only accept DLPI control
13064 		 * messages. In the open case, the ill->ill_ipif has not yet
13065 		 * been created. In the close case, things hanging off the
13066 		 * ill could have been freed already. In either case it
13067 		 * may not be safe to proceed further.
13068 		 */
13069 
13070 		dl = (union DL_primitives *)mp->b_rptr;
13071 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13072 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13073 			/*
13074 			 * Also SIOC[GS]TUN* ioctls can come here.
13075 			 */
13076 			inet_freemsg(mp);
13077 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13078 			    "ip_input_end: q %p (%S)", q, "uninit");
13079 			return;
13080 		}
13081 	}
13082 
13083 	/*
13084 	 * if db_ref > 1 then copymsg and free original. Packet may be
13085 	 * changed and we do not want the other entity who has a reference to
13086 	 * this message to trip over the changes. This is a blind change because
13087 	 * trying to catch all places that might change the packet is too
13088 	 * difficult.
13089 	 *
13090 	 * This corresponds to the fast path case, where we have a chain of
13091 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13092 	 * in the mblk chain. There doesn't seem to be a reason why a device
13093 	 * driver would send up data with varying db_ref counts in the mblk
13094 	 * chain. In any case the Fast path is a private interface, and our
13095 	 * drivers don't do such a thing. Given the above assumption, there is
13096 	 * no need to walk down the entire mblk chain (which could have a
13097 	 * potential performance problem)
13098 	 */
13099 	if (mp->b_datap->db_ref > 1) {
13100 		mblk_t  *mp1;
13101 		boolean_t adjusted = B_FALSE;
13102 		IP_STAT(ip_db_ref);
13103 
13104 		/*
13105 		 * The IP_RECVSLLA option depends on having the link layer
13106 		 * header. First check that:
13107 		 * a> the underlying device is of type ether, since this
13108 		 * option is currently supported only over ethernet.
13109 		 * b> there is enough room to copy over the link layer header.
13110 		 *
13111 		 * Once the checks are done, adjust rptr so that the link layer
13112 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13113 		 * be returned by some non-ethernet drivers but in this case the
13114 		 * second check will fail.
13115 		 */
13116 		if (ill->ill_type == IFT_ETHER &&
13117 		    (mp->b_rptr - mp->b_datap->db_base) >=
13118 		    sizeof (struct ether_header)) {
13119 			mp->b_rptr -= sizeof (struct ether_header);
13120 			adjusted = B_TRUE;
13121 		}
13122 		mp1 = copymsg(mp);
13123 		if (mp1 == NULL) {
13124 			/* Clear b_next - used in M_BREAK messages */
13125 			mp->b_next = NULL;
13126 			/* clear b_prev - used by ip_mroute_decap */
13127 			mp->b_prev = NULL;
13128 			freemsg(mp);
13129 			BUMP_MIB(&ip_mib, ipInDiscards);
13130 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13131 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13132 			return;
13133 		}
13134 		if (adjusted) {
13135 			/*
13136 			 * Copy is done. Restore the pointer in the _new_ mblk
13137 			 */
13138 			mp1->b_rptr += sizeof (struct ether_header);
13139 		}
13140 		/* Copy b_next - used in M_BREAK messages */
13141 		mp1->b_next = mp->b_next;
13142 		mp->b_next = NULL;
13143 		/* Copy b_prev - used by ip_mroute_decap */
13144 		mp1->b_prev = mp->b_prev;
13145 		mp->b_prev = NULL;
13146 		freemsg(mp);
13147 		mp = mp1;
13148 	}
13149 
13150 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13151 	    "ip_rput_end: q %p (%S)", q, "end");
13152 
13153 	ip_input(ill, NULL, mp, 0);
13154 }
13155 
13156 /*
13157  * Direct read side procedure capable of dealing with chains. GLDv3 based
13158  * drivers call this function directly with mblk chains while STREAMS
13159  * read side procedure ip_rput() calls this for single packet with ip_ring
13160  * set to NULL to process one packet at a time.
13161  *
13162  * The ill will always be valid if this function is called directly from
13163  * the driver.
13164  */
13165 /*ARGSUSED*/
13166 void
13167 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13168 {
13169 	ipaddr_t		dst;
13170 	ire_t			*ire;
13171 	ipha_t			*ipha;
13172 	uint_t			pkt_len;
13173 	ssize_t			len;
13174 	uint_t			opt_len;
13175 	int			ll_multicast;
13176 	int			cgtp_flt_pkt;
13177 	queue_t			*q = ill->ill_rq;
13178 	squeue_t		*curr_sqp = NULL;
13179 	mblk_t 			*head = NULL;
13180 	mblk_t			*tail = NULL;
13181 	mblk_t			*first_mp;
13182 	mblk_t 			*mp;
13183 	int			cnt = 0;
13184 
13185 	ASSERT(mp_chain != NULL);
13186 	ASSERT(ill != NULL);
13187 
13188 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13189 
13190 #define	rptr	((uchar_t *)ipha)
13191 
13192 	while (mp_chain != NULL) {
13193 		first_mp = mp = mp_chain;
13194 		mp_chain = mp_chain->b_next;
13195 		mp->b_next = NULL;
13196 		ll_multicast = 0;
13197 		ire = NULL;
13198 
13199 		/*
13200 		 * ip_input fast path
13201 		 */
13202 
13203 		/* mblk type is not M_DATA */
13204 		if (mp->b_datap->db_type != M_DATA) {
13205 			if (ip_rput_process_notdata(q, &first_mp, ill,
13206 			    &ll_multicast, &mp))
13207 				continue;
13208 		}
13209 
13210 		ASSERT(mp->b_datap->db_type == M_DATA);
13211 		ASSERT(mp->b_datap->db_ref == 1);
13212 
13213 		/*
13214 		 * Invoke the CGTP (multirouting) filtering module to process
13215 		 * the incoming packet. Packets identified as duplicates
13216 		 * must be discarded. Filtering is active only if the
13217 		 * the ip_cgtp_filter ndd variable is non-zero.
13218 		 */
13219 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13220 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13221 			cgtp_flt_pkt =
13222 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13223 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13224 				freemsg(first_mp);
13225 				continue;
13226 			}
13227 		}
13228 
13229 		ipha = (ipha_t *)mp->b_rptr;
13230 		len = mp->b_wptr - rptr;
13231 
13232 		BUMP_MIB(&ip_mib, ipInReceives);
13233 
13234 		/*
13235 		 * IP header ptr not aligned?
13236 		 * OR IP header not complete in first mblk
13237 		 */
13238 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13239 			if (!ip_check_and_align_header(q, mp))
13240 				continue;
13241 			ipha = (ipha_t *)mp->b_rptr;
13242 			len = mp->b_wptr - rptr;
13243 		}
13244 
13245 		/* multiple mblk or too short */
13246 		pkt_len = ntohs(ipha->ipha_length);
13247 		len -= pkt_len;
13248 		if (len != 0) {
13249 			/*
13250 			 * Make sure we have data length consistent
13251 			 * with the IP header.
13252 			 */
13253 			if (mp->b_cont == NULL) {
13254 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13255 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13256 					ip2dbg(("ip_input: drop pkt\n"));
13257 					freemsg(mp);
13258 					continue;
13259 				}
13260 				mp->b_wptr = rptr + pkt_len;
13261 			} else if (len += msgdsize(mp->b_cont)) {
13262 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13263 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13264 					ip2dbg(("ip_input: drop pkt\n"));
13265 					freemsg(mp);
13266 					continue;
13267 				}
13268 				(void) adjmsg(mp, -len);
13269 				IP_STAT(ip_multimblk3);
13270 			}
13271 		}
13272 
13273 		if (ip_loopback_src_or_dst(ipha, ill)) {
13274 			ip2dbg(("ip_input: drop pkt\n"));
13275 			freemsg(mp);
13276 			continue;
13277 		}
13278 
13279 		opt_len = ipha->ipha_version_and_hdr_length -
13280 		    IP_SIMPLE_HDR_VERSION;
13281 		/* IP version bad or there are IP options */
13282 		if (opt_len) {
13283 			if (len != 0)
13284 				IP_STAT(ip_multimblk4);
13285 			else
13286 				IP_STAT(ip_ipoptions);
13287 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13288 				continue;
13289 		} else {
13290 			dst = ipha->ipha_dst;
13291 		}
13292 
13293 		/*
13294 		 * If rsvpd is running, let RSVP daemon handle its processing
13295 		 * and forwarding of RSVP multicast/unicast packets.
13296 		 * If rsvpd is not running but mrouted is running, RSVP
13297 		 * multicast packets are forwarded as multicast traffic
13298 		 * and RSVP unicast packets are forwarded by unicast router.
13299 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13300 		 * packets are not forwarded, but the unicast packets are
13301 		 * forwarded like unicast traffic.
13302 		 */
13303 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13304 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13305 			/* RSVP packet and rsvpd running. Treat as ours */
13306 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13307 			/*
13308 			 * This assumes that we deliver to all streams for
13309 			 * multicast and broadcast packets.
13310 			 * We have to force ll_multicast to 1 to handle the
13311 			 * M_DATA messages passed in from ip_mroute_decap.
13312 			 */
13313 			dst = INADDR_BROADCAST;
13314 			ll_multicast = 1;
13315 		} else if (CLASSD(dst)) {
13316 			/* packet is multicast */
13317 			mp->b_next = NULL;
13318 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13319 			    &ll_multicast, &dst))
13320 				continue;
13321 		}
13322 
13323 
13324 		/*
13325 		 * Check if the packet is coming from the Mobile IP
13326 		 * forward tunnel interface
13327 		 */
13328 		if (ill->ill_srcif_refcnt > 0) {
13329 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13330 			    NULL, ill, MATCH_IRE_TYPE);
13331 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13332 			    ire->ire_ipif->ipif_net_type ==
13333 			    IRE_IF_RESOLVER) {
13334 				/* We need to resolve the link layer info */
13335 				ire_refrele(ire);
13336 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13337 				    ll_multicast, dst);
13338 				continue;
13339 			}
13340 		}
13341 
13342 		if (ire == NULL)
13343 			ire = ire_cache_lookup(dst, ALL_ZONES);
13344 
13345 		/*
13346 		 * If mipagent is running and reverse tunnel is created as per
13347 		 * mobile node request, then any packet coming through the
13348 		 * incoming interface from the mobile-node, should be reverse
13349 		 * tunneled to it's home agent except those that are destined
13350 		 * to foreign agent only.
13351 		 * This needs source address based ire lookup. The routing
13352 		 * entries for source address based lookup are only created by
13353 		 * mipagent program only when a reverse tunnel is created.
13354 		 * Reference : RFC2002, RFC2344
13355 		 */
13356 		if (ill->ill_mrtun_refcnt > 0) {
13357 			ipaddr_t	srcaddr;
13358 			ire_t		*tmp_ire;
13359 
13360 			tmp_ire = ire;	/* Save, we might need it later */
13361 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13362 			    ire->ire_type != IRE_BROADCAST)) {
13363 				srcaddr = ipha->ipha_src;
13364 				ire = ire_mrtun_lookup(srcaddr, ill);
13365 				if (ire != NULL) {
13366 					/*
13367 					 * Should not be getting iphada packet
13368 					 * here. we should only get those for
13369 					 * IRE_LOCAL traffic, excluded above.
13370 					 * Fail-safe (drop packet) in the event
13371 					 * hardware is misbehaving.
13372 					 */
13373 					if (first_mp != mp) {
13374 						/* IPsec KSTATS: beancount me */
13375 						freemsg(first_mp);
13376 					} else {
13377 						/*
13378 						 * This packet must be forwarded
13379 						 * to Reverse Tunnel
13380 						 */
13381 						ip_mrtun_forward(ire, ill, mp);
13382 					}
13383 					ire_refrele(ire);
13384 					if (tmp_ire != NULL)
13385 						ire_refrele(tmp_ire);
13386 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13387 					    "ip_input_end: q %p (%S)",
13388 					    q, "uninit");
13389 					continue;
13390 				}
13391 			}
13392 			/*
13393 			 * If this packet is from a non-mobilenode  or a
13394 			 * mobile-node which does not request reverse
13395 			 * tunnel service
13396 			 */
13397 			ire = tmp_ire;
13398 		}
13399 
13400 
13401 		/*
13402 		 * If we reach here that means the incoming packet satisfies
13403 		 * one of the following conditions:
13404 		 *   - packet is from a mobile node which does not request
13405 		 *	reverse tunnel
13406 		 *   - packet is from a non-mobile node, which is the most
13407 		 *	common case
13408 		 *   - packet is from a reverse tunnel enabled mobile node
13409 		 *	and destined to foreign agent only
13410 		 */
13411 
13412 		if (ire == NULL) {
13413 			/*
13414 			 * No IRE for this destination, so it can't be for us.
13415 			 * Unless we are forwarding, drop the packet.
13416 			 * We have to let source routed packets through
13417 			 * since we don't yet know if they are 'ping -l'
13418 			 * packets i.e. if they will go out over the
13419 			 * same interface as they came in on.
13420 			 */
13421 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13422 			continue;
13423 		}
13424 
13425 		/*
13426 		 * Broadcast IRE may indicate either broadcast or
13427 		 * multicast packet
13428 		 */
13429 		if (ire->ire_type == IRE_BROADCAST) {
13430 			/*
13431 			 * Skip broadcast checks if packet is UDP multicast;
13432 			 * we'd rather not enter ip_rput_process_broadcast()
13433 			 * unless the packet is broadcast for real, since
13434 			 * that routine is a no-op for multicast.
13435 			 */
13436 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
13437 			    !CLASSD(ipha->ipha_dst)) &&
13438 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13439 			    dst, cgtp_flt_pkt, ll_multicast)) {
13440 				continue;
13441 			}
13442 		} else if (ire->ire_stq != NULL) {
13443 			/* fowarding? */
13444 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13445 			    ll_multicast);
13446 			continue;
13447 		}
13448 
13449 		/* packet not for us */
13450 		if (ire->ire_rfq != q) {
13451 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13452 				continue;
13453 			}
13454 		}
13455 
13456 		switch (ipha->ipha_protocol) {
13457 		case IPPROTO_TCP:
13458 			ASSERT(first_mp == mp);
13459 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13460 				mp, 0, q, ip_ring)) != NULL) {
13461 				if (curr_sqp == NULL) {
13462 					curr_sqp = GET_SQUEUE(mp);
13463 					ASSERT(cnt == 0);
13464 					cnt++;
13465 					head = tail = mp;
13466 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13467 					ASSERT(tail != NULL);
13468 					cnt++;
13469 					tail->b_next = mp;
13470 					tail = mp;
13471 				} else {
13472 					/*
13473 					 * A different squeue. Send the
13474 					 * chain for the previous squeue on
13475 					 * its way. This shouldn't happen
13476 					 * often unless interrupt binding
13477 					 * changes.
13478 					 */
13479 					IP_STAT(ip_input_multi_squeue);
13480 					squeue_enter_chain(curr_sqp, head,
13481 					    tail, cnt, SQTAG_IP_INPUT);
13482 					curr_sqp = GET_SQUEUE(mp);
13483 					head = mp;
13484 					tail = mp;
13485 					cnt = 1;
13486 				}
13487 			}
13488 			IRE_REFRELE(ire);
13489 			continue;
13490 		case IPPROTO_UDP:
13491 			ASSERT(first_mp == mp);
13492 			ip_udp_input(q, mp, ipha, ire, ill);
13493 			IRE_REFRELE(ire);
13494 			continue;
13495 		case IPPROTO_SCTP:
13496 			ASSERT(first_mp == mp);
13497 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13498 			    q, dst);
13499 			continue;
13500 		default:
13501 			ip_proto_input(q, first_mp, ipha, ire, ill);
13502 			IRE_REFRELE(ire);
13503 			continue;
13504 		}
13505 	}
13506 
13507 	if (head != NULL)
13508 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13509 
13510 	/*
13511 	 * This code is there just to make netperf/ttcp look good.
13512 	 *
13513 	 * Its possible that after being in polling mode (and having cleared
13514 	 * the backlog), squeues have turned the interrupt frequency higher
13515 	 * to improve latency at the expense of more CPU utilization (less
13516 	 * packets per interrupts or more number of interrupts). Workloads
13517 	 * like ttcp/netperf do manage to tickle polling once in a while
13518 	 * but for the remaining time, stay in higher interrupt mode since
13519 	 * their packet arrival rate is pretty uniform and this shows up
13520 	 * as higher CPU utilization. Since people care about CPU utilization
13521 	 * while running netperf/ttcp, turn the interrupt frequency back to
13522 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13523 	 */
13524 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13525 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13526 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13527 			ip_ring->rr_blank(ip_ring->rr_handle,
13528 			    ip_ring->rr_normal_blank_time,
13529 			    ip_ring->rr_normal_pkt_cnt);
13530 		}
13531 	}
13532 
13533 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13534 	    "ip_input_end: q %p (%S)", q, "end");
13535 #undef	rptr
13536 }
13537 
13538 static void
13539 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13540     t_uscalar_t err)
13541 {
13542 	if (dl_err == DL_SYSERR) {
13543 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13544 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13545 		    ill->ill_name, dlpi_prim_str(prim), err);
13546 		return;
13547 	}
13548 
13549 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13550 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13551 	    dlpi_err_str(dl_err));
13552 }
13553 
13554 /*
13555  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13556  * than DL_UNITDATA_IND messages. If we need to process this message
13557  * exclusively, we call qwriter_ip, in which case we also need to call
13558  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13559  */
13560 void
13561 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13562 {
13563 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13564 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13565 	ill_t		*ill;
13566 
13567 	ip1dbg(("ip_rput_dlpi"));
13568 	ill = (ill_t *)q->q_ptr;
13569 	switch (dloa->dl_primitive) {
13570 	case DL_ERROR_ACK:
13571 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13572 		    "%s (0x%x), unix %u\n", ill->ill_name,
13573 		    dlpi_prim_str(dlea->dl_error_primitive),
13574 		    dlea->dl_error_primitive,
13575 		    dlpi_err_str(dlea->dl_errno),
13576 		    dlea->dl_errno,
13577 		    dlea->dl_unix_errno));
13578 		switch (dlea->dl_error_primitive) {
13579 		case DL_NOTIFY_REQ:
13580 		case DL_UNBIND_REQ:
13581 		case DL_ATTACH_REQ:
13582 		case DL_DETACH_REQ:
13583 		case DL_INFO_REQ:
13584 		case DL_BIND_REQ:
13585 		case DL_ENABMULTI_REQ:
13586 		case DL_PHYS_ADDR_REQ:
13587 		case DL_CAPABILITY_REQ:
13588 		case DL_CONTROL_REQ:
13589 			/*
13590 			 * Refhold the ill to match qwriter_ip which does a
13591 			 * refrele. Since this is on the ill stream we
13592 			 * unconditionally bump up the refcount without
13593 			 * checking for ILL_CAN_LOOKUP
13594 			 */
13595 			ill_refhold(ill);
13596 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13597 			    CUR_OP, B_FALSE);
13598 			return;
13599 		case DL_DISABMULTI_REQ:
13600 			freemsg(mp);	/* Don't want to pass this up */
13601 			return;
13602 		default:
13603 			break;
13604 		}
13605 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13606 		    dlea->dl_errno, dlea->dl_unix_errno);
13607 		freemsg(mp);
13608 		return;
13609 	case DL_INFO_ACK:
13610 	case DL_BIND_ACK:
13611 	case DL_PHYS_ADDR_ACK:
13612 	case DL_NOTIFY_ACK:
13613 	case DL_CAPABILITY_ACK:
13614 	case DL_CONTROL_ACK:
13615 		/*
13616 		 * Refhold the ill to match qwriter_ip which does a refrele
13617 		 * Since this is on the ill stream we unconditionally
13618 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13619 		 */
13620 		ill_refhold(ill);
13621 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13622 		    CUR_OP, B_FALSE);
13623 		return;
13624 	case DL_NOTIFY_IND:
13625 		ill_refhold(ill);
13626 		/*
13627 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13628 		 * relation to the current ioctl in progress (if any). Hence we
13629 		 * pass in NEW_OP in this case.
13630 		 */
13631 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13632 		    NEW_OP, B_FALSE);
13633 		return;
13634 	case DL_OK_ACK:
13635 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13636 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13637 		switch (dloa->dl_correct_primitive) {
13638 		case DL_UNBIND_REQ:
13639 			mutex_enter(&ill->ill_lock);
13640 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13641 			cv_signal(&ill->ill_cv);
13642 			mutex_exit(&ill->ill_lock);
13643 			/* FALLTHRU */
13644 		case DL_ATTACH_REQ:
13645 		case DL_DETACH_REQ:
13646 			/*
13647 			 * Refhold the ill to match qwriter_ip which does a
13648 			 * refrele. Since this is on the ill stream we
13649 			 * unconditionally bump up the refcount
13650 			 */
13651 			ill_refhold(ill);
13652 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13653 			    CUR_OP, B_FALSE);
13654 			return;
13655 		case DL_ENABMULTI_REQ:
13656 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13657 				ill->ill_dlpi_multicast_state = IDMS_OK;
13658 			break;
13659 
13660 		}
13661 		break;
13662 	default:
13663 		break;
13664 	}
13665 	freemsg(mp);
13666 }
13667 
13668 /*
13669  * Handling of DLPI messages that require exclusive access to the ipsq.
13670  *
13671  * Need to do ill_pending_mp_release on ioctl completion, which could
13672  * happen here. (along with mi_copy_done)
13673  */
13674 /* ARGSUSED */
13675 static void
13676 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13677 {
13678 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13679 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13680 	int		err = 0;
13681 	ill_t		*ill;
13682 	ipif_t		*ipif = NULL;
13683 	mblk_t		*mp1 = NULL;
13684 	conn_t		*connp = NULL;
13685 	t_uscalar_t	physaddr_req;
13686 	mblk_t		*mp_hw;
13687 	union DL_primitives *dlp;
13688 	boolean_t	success;
13689 	boolean_t	ioctl_aborted = B_FALSE;
13690 	boolean_t	log = B_TRUE;
13691 
13692 	ip1dbg(("ip_rput_dlpi_writer .."));
13693 	ill = (ill_t *)q->q_ptr;
13694 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13695 
13696 	ASSERT(IAM_WRITER_ILL(ill));
13697 
13698 	/*
13699 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13700 	 * both are null or non-null. However we can assert that only
13701 	 * after grabbing the ipsq_lock. So we don't make any assertion
13702 	 * here and in other places in the code.
13703 	 */
13704 	ipif = ipsq->ipsq_pending_ipif;
13705 	/*
13706 	 * The current ioctl could have been aborted by the user and a new
13707 	 * ioctl to bring up another ill could have started. We could still
13708 	 * get a response from the driver later.
13709 	 */
13710 	if (ipif != NULL && ipif->ipif_ill != ill)
13711 		ioctl_aborted = B_TRUE;
13712 
13713 	switch (dloa->dl_primitive) {
13714 	case DL_ERROR_ACK:
13715 		switch (dlea->dl_error_primitive) {
13716 		case DL_UNBIND_REQ:
13717 		case DL_ATTACH_REQ:
13718 		case DL_DETACH_REQ:
13719 		case DL_INFO_REQ:
13720 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13721 			break;
13722 		case DL_NOTIFY_REQ:
13723 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13724 			log = B_FALSE;
13725 			break;
13726 		case DL_PHYS_ADDR_REQ:
13727 			/*
13728 			 * For IPv6 only, there are two additional
13729 			 * phys_addr_req's sent to the driver to get the
13730 			 * IPv6 token and lla. This allows IP to acquire
13731 			 * the hardware address format for a given interface
13732 			 * without having built in knowledge of the hardware
13733 			 * address. ill_phys_addr_pend keeps track of the last
13734 			 * DL_PAR sent so we know which response we are
13735 			 * dealing with. ill_dlpi_done will update
13736 			 * ill_phys_addr_pend when it sends the next req.
13737 			 * We don't complete the IOCTL until all three DL_PARs
13738 			 * have been attempted, so set *_len to 0 and break.
13739 			 */
13740 			physaddr_req = ill->ill_phys_addr_pend;
13741 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13742 			if (physaddr_req == DL_IPV6_TOKEN) {
13743 				ill->ill_token_length = 0;
13744 				log = B_FALSE;
13745 				break;
13746 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13747 				ill->ill_nd_lla_len = 0;
13748 				log = B_FALSE;
13749 				break;
13750 			}
13751 			/*
13752 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13753 			 * We presumably have an IOCTL hanging out waiting
13754 			 * for completion. Find it and complete the IOCTL
13755 			 * with the error noted.
13756 			 * However, ill_dl_phys was called on an ill queue
13757 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13758 			 * set. But the ioctl is known to be pending on ill_wq.
13759 			 */
13760 			if (!ill->ill_ifname_pending)
13761 				break;
13762 			ill->ill_ifname_pending = 0;
13763 			if (!ioctl_aborted)
13764 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13765 			if (mp1 != NULL) {
13766 				/*
13767 				 * This operation (SIOCSLIFNAME) must have
13768 				 * happened on the ill. Assert there is no conn
13769 				 */
13770 				ASSERT(connp == NULL);
13771 				q = ill->ill_wq;
13772 			}
13773 			break;
13774 		case DL_BIND_REQ:
13775 			ill_dlpi_done(ill, DL_BIND_REQ);
13776 			if (ill->ill_ifname_pending)
13777 				break;
13778 			/*
13779 			 * Something went wrong with the bind.  We presumably
13780 			 * have an IOCTL hanging out waiting for completion.
13781 			 * Find it, take down the interface that was coming
13782 			 * up, and complete the IOCTL with the error noted.
13783 			 */
13784 			if (!ioctl_aborted)
13785 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13786 			if (mp1 != NULL) {
13787 				/*
13788 				 * This operation (SIOCSLIFFLAGS) must have
13789 				 * happened from a conn.
13790 				 */
13791 				ASSERT(connp != NULL);
13792 				q = CONNP_TO_WQ(connp);
13793 				if (ill->ill_move_in_progress) {
13794 					ILL_CLEAR_MOVE(ill);
13795 				}
13796 				(void) ipif_down(ipif, NULL, NULL);
13797 				/* error is set below the switch */
13798 			}
13799 			break;
13800 		case DL_ENABMULTI_REQ:
13801 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13802 
13803 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13804 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13805 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13806 				ipif_t *ipif;
13807 
13808 				log = B_FALSE;
13809 				printf("ip: joining multicasts failed (%d)"
13810 				    " on %s - will use link layer "
13811 				    "broadcasts for multicast\n",
13812 				    dlea->dl_errno, ill->ill_name);
13813 
13814 				/*
13815 				 * Set up the multicast mapping alone.
13816 				 * writer, so ok to access ill->ill_ipif
13817 				 * without any lock.
13818 				 */
13819 				ipif = ill->ill_ipif;
13820 				mutex_enter(&ill->ill_phyint->phyint_lock);
13821 				ill->ill_phyint->phyint_flags |=
13822 				    PHYI_MULTI_BCAST;
13823 				mutex_exit(&ill->ill_phyint->phyint_lock);
13824 
13825 				if (!ill->ill_isv6) {
13826 					(void) ipif_arp_setup_multicast(ipif,
13827 					    NULL);
13828 				} else {
13829 					(void) ipif_ndp_setup_multicast(ipif,
13830 					    NULL);
13831 				}
13832 			}
13833 			freemsg(mp);	/* Don't want to pass this up */
13834 			return;
13835 		case DL_CAPABILITY_REQ:
13836 		case DL_CONTROL_REQ:
13837 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13838 			    "DL_CAPABILITY/CONTROL REQ\n"));
13839 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13840 			ill->ill_capab_state = IDMS_FAILED;
13841 			freemsg(mp);
13842 			return;
13843 		}
13844 		/*
13845 		 * Note the error for IOCTL completion (mp1 is set when
13846 		 * ready to complete ioctl). If ill_ifname_pending_err is
13847 		 * set, an error occured during plumbing (ill_ifname_pending),
13848 		 * so we want to report that error.
13849 		 *
13850 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13851 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13852 		 * expected to get errack'd if the driver doesn't support
13853 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13854 		 * if these error conditions are encountered.
13855 		 */
13856 		if (mp1 != NULL) {
13857 			if (ill->ill_ifname_pending_err != 0)  {
13858 				err = ill->ill_ifname_pending_err;
13859 				ill->ill_ifname_pending_err = 0;
13860 			} else {
13861 				err = dlea->dl_unix_errno ?
13862 				    dlea->dl_unix_errno : ENXIO;
13863 			}
13864 		/*
13865 		 * If we're plumbing an interface and an error hasn't already
13866 		 * been saved, set ill_ifname_pending_err to the error passed
13867 		 * up. Ignore the error if log is B_FALSE (see comment above).
13868 		 */
13869 		} else if (log && ill->ill_ifname_pending &&
13870 		    ill->ill_ifname_pending_err == 0) {
13871 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13872 			dlea->dl_unix_errno : ENXIO;
13873 		}
13874 
13875 		if (log)
13876 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13877 			    dlea->dl_errno, dlea->dl_unix_errno);
13878 		break;
13879 	case DL_CAPABILITY_ACK: {
13880 		boolean_t reneg_flag = B_FALSE;
13881 		/* Call a routine to handle this one. */
13882 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13883 		/*
13884 		 * Check if the ACK is due to renegotiation case since we
13885 		 * will need to send a new CAPABILITY_REQ later.
13886 		 */
13887 		if (ill->ill_capab_state == IDMS_RENEG) {
13888 			/* This is the ack for a renogiation case */
13889 			reneg_flag = B_TRUE;
13890 			ill->ill_capab_state = IDMS_UNKNOWN;
13891 		}
13892 		ill_capability_ack(ill, mp);
13893 		if (reneg_flag)
13894 			ill_capability_probe(ill);
13895 		break;
13896 	}
13897 	case DL_CONTROL_ACK:
13898 		/* We treat all of these as "fire and forget" */
13899 		ill_dlpi_done(ill, DL_CONTROL_REQ);
13900 		break;
13901 	case DL_INFO_ACK:
13902 		/* Call a routine to handle this one. */
13903 		ill_dlpi_done(ill, DL_INFO_REQ);
13904 		ip_ll_subnet_defaults(ill, mp);
13905 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
13906 		return;
13907 	case DL_BIND_ACK:
13908 		/*
13909 		 * We should have an IOCTL waiting on this unless
13910 		 * sent by ill_dl_phys, in which case just return
13911 		 */
13912 		ill_dlpi_done(ill, DL_BIND_REQ);
13913 		if (ill->ill_ifname_pending)
13914 			break;
13915 
13916 		if (!ioctl_aborted)
13917 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
13918 		if (mp1 == NULL)
13919 			break;
13920 		ASSERT(connp != NULL);
13921 		q = CONNP_TO_WQ(connp);
13922 
13923 		/*
13924 		 * We are exclusive. So nothing can change even after
13925 		 * we get the pending mp. If need be we can put it back
13926 		 * and restart, as in calling ipif_arp_up()  below.
13927 		 */
13928 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
13929 
13930 		mutex_enter(&ill->ill_lock);
13931 		ill->ill_dl_up = 1;
13932 		mutex_exit(&ill->ill_lock);
13933 
13934 		/*
13935 		 * Now bring up the resolver, when that is
13936 		 * done we'll create IREs and we are done.
13937 		 */
13938 		if (ill->ill_isv6) {
13939 			/*
13940 			 * v6 interfaces.
13941 			 * Unlike ARP which has to do another bind
13942 			 * and attach, once we get here we are
13943 			 * done withh NDP. Except in the case of
13944 			 * ILLF_XRESOLV, in which case we send an
13945 			 * AR_INTERFACE_UP to the external resolver.
13946 			 * If all goes well, the ioctl will complete
13947 			 * in ip_rput(). If there's an error, we
13948 			 * complete it here.
13949 			 */
13950 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
13951 			    B_FALSE);
13952 			if (err == 0) {
13953 				if (ill->ill_flags & ILLF_XRESOLV) {
13954 					mutex_enter(&connp->conn_lock);
13955 					mutex_enter(&ill->ill_lock);
13956 					success = ipsq_pending_mp_add(
13957 					    connp, ipif, q, mp1, 0);
13958 					mutex_exit(&ill->ill_lock);
13959 					mutex_exit(&connp->conn_lock);
13960 					if (success) {
13961 						err = ipif_resolver_up(ipif,
13962 						    B_FALSE);
13963 						if (err == EINPROGRESS) {
13964 							freemsg(mp);
13965 							return;
13966 						}
13967 						ASSERT(err != 0);
13968 						mp1 = ipsq_pending_mp_get(ipsq,
13969 						    &connp);
13970 						ASSERT(mp1 != NULL);
13971 					} else {
13972 						/* conn has started closing */
13973 						err = EINTR;
13974 					}
13975 				} else { /* Non XRESOLV interface */
13976 					err = ipif_up_done_v6(ipif);
13977 				}
13978 			}
13979 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
13980 			/*
13981 			 * ARP and other v4 external resolvers.
13982 			 * Leave the pending mblk intact so that
13983 			 * the ioctl completes in ip_rput().
13984 			 */
13985 			mutex_enter(&connp->conn_lock);
13986 			mutex_enter(&ill->ill_lock);
13987 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
13988 			mutex_exit(&ill->ill_lock);
13989 			mutex_exit(&connp->conn_lock);
13990 			if (success) {
13991 				err = ipif_resolver_up(ipif, B_FALSE);
13992 				if (err == EINPROGRESS) {
13993 					freemsg(mp);
13994 					return;
13995 				}
13996 				ASSERT(err != 0);
13997 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13998 			} else {
13999 				/* The conn has started closing */
14000 				err = EINTR;
14001 			}
14002 		} else {
14003 			/*
14004 			 * This one is complete. Reply to pending ioctl.
14005 			 */
14006 			err = ipif_up_done(ipif);
14007 		}
14008 
14009 		if ((err == 0) && (ill->ill_up_ipifs)) {
14010 			err = ill_up_ipifs(ill, q, mp1);
14011 			if (err == EINPROGRESS) {
14012 				freemsg(mp);
14013 				return;
14014 			}
14015 		}
14016 
14017 		if (ill->ill_up_ipifs) {
14018 			ill_group_cleanup(ill);
14019 		}
14020 
14021 		break;
14022 	case DL_NOTIFY_IND: {
14023 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14024 		ire_t *ire;
14025 		boolean_t need_ire_walk_v4 = B_FALSE;
14026 		boolean_t need_ire_walk_v6 = B_FALSE;
14027 
14028 		/*
14029 		 * Change the address everywhere we need to.
14030 		 * What we're getting here is a link-level addr or phys addr.
14031 		 * The new addr is at notify + notify->dl_addr_offset
14032 		 * The address length is notify->dl_addr_length;
14033 		 */
14034 		switch (notify->dl_notification) {
14035 		case DL_NOTE_PHYS_ADDR:
14036 			mp_hw = copyb(mp);
14037 			if (mp_hw == NULL) {
14038 				err = ENOMEM;
14039 				break;
14040 			}
14041 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14042 			/*
14043 			 * We currently don't support changing
14044 			 * the token via DL_NOTIFY_IND.
14045 			 * When we do support it, we have to consider
14046 			 * what the implications are with respect to
14047 			 * the token and the link local address.
14048 			 */
14049 			mutex_enter(&ill->ill_lock);
14050 			if (dlp->notify_ind.dl_data ==
14051 			    DL_IPV6_LINK_LAYER_ADDR) {
14052 				if (ill->ill_nd_lla_mp != NULL)
14053 					freemsg(ill->ill_nd_lla_mp);
14054 				ill->ill_nd_lla_mp = mp_hw;
14055 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14056 				    dlp->notify_ind.dl_addr_offset;
14057 				ill->ill_nd_lla_len =
14058 				    dlp->notify_ind.dl_addr_length -
14059 				    ABS(ill->ill_sap_length);
14060 				mutex_exit(&ill->ill_lock);
14061 				break;
14062 			} else if (dlp->notify_ind.dl_data ==
14063 			    DL_CURR_PHYS_ADDR) {
14064 				if (ill->ill_phys_addr_mp != NULL)
14065 					freemsg(ill->ill_phys_addr_mp);
14066 				ill->ill_phys_addr_mp = mp_hw;
14067 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14068 				    dlp->notify_ind.dl_addr_offset;
14069 				ill->ill_phys_addr_length =
14070 				    dlp->notify_ind.dl_addr_length -
14071 				    ABS(ill->ill_sap_length);
14072 				if (ill->ill_isv6 &&
14073 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14074 					if (ill->ill_nd_lla_mp != NULL)
14075 						freemsg(ill->ill_nd_lla_mp);
14076 					ill->ill_nd_lla_mp = copyb(mp_hw);
14077 					ill->ill_nd_lla = (uchar_t *)
14078 					    ill->ill_nd_lla_mp->b_rptr +
14079 					    dlp->notify_ind.dl_addr_offset;
14080 					ill->ill_nd_lla_len =
14081 					    ill->ill_phys_addr_length;
14082 				}
14083 			}
14084 			mutex_exit(&ill->ill_lock);
14085 			/*
14086 			 * Send out gratuitous arp request for our new
14087 			 * hardware address.
14088 			 */
14089 			for (ipif = ill->ill_ipif; ipif != NULL;
14090 			    ipif = ipif->ipif_next) {
14091 				if (!(ipif->ipif_flags & IPIF_UP))
14092 					continue;
14093 				if (ill->ill_isv6) {
14094 					ipif_ndp_down(ipif);
14095 					/*
14096 					 * Set B_TRUE to enable
14097 					 * ipif_ndp_up() to send out
14098 					 * unsolicited advertisements.
14099 					 */
14100 					err = ipif_ndp_up(ipif,
14101 					    &ipif->ipif_v6lcl_addr,
14102 					    B_TRUE);
14103 					if (err) {
14104 						ip1dbg((
14105 						    "ip_rput_dlpi_writer: "
14106 						    "Failed to update ndp "
14107 						    "err %d\n", err));
14108 					}
14109 				} else {
14110 					/*
14111 					 * IPv4 ARP case
14112 					 *
14113 					 * Set B_TRUE, as we only want
14114 					 * ipif_resolver_up to send an
14115 					 * AR_ENTRY_ADD request up to
14116 					 * ARP.
14117 					 */
14118 					err = ipif_resolver_up(ipif,
14119 					    B_TRUE);
14120 					if (err) {
14121 						ip1dbg((
14122 						    "ip_rput_dlpi_writer: "
14123 						    "Failed to update arp "
14124 						    "err %d\n", err));
14125 					}
14126 				}
14127 			}
14128 			/*
14129 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14130 			 * case so that all old fastpath information can be
14131 			 * purged from IRE caches.
14132 			 */
14133 		/* FALLTHRU */
14134 		case DL_NOTE_FASTPATH_FLUSH:
14135 			/*
14136 			 * Any fastpath probe sent henceforth will get the
14137 			 * new fp mp. So we first delete any ires that are
14138 			 * waiting for the fastpath. Then walk all ires and
14139 			 * delete the ire or delete the fp mp. In the case of
14140 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14141 			 * recreate the ire's without going through a complex
14142 			 * ipif up/down dance. So we don't delete the ire
14143 			 * itself, but just the ire_fp_mp for these 2 ire's
14144 			 * In the case of the other ire's we delete the ire's
14145 			 * themselves. Access to ire_fp_mp is completely
14146 			 * protected by ire_lock for IRE_MIPRTUN and
14147 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14148 			 * other cases for performance.
14149 			 */
14150 			if (ill->ill_isv6) {
14151 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14152 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14153 				    NULL);
14154 			} else {
14155 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14156 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14157 				    IRE_CACHE | IRE_BROADCAST,
14158 				    ire_fastpath_flush, NULL, ill);
14159 				mutex_enter(&ire_mrtun_lock);
14160 				if (ire_mrtun_count != 0) {
14161 					mutex_exit(&ire_mrtun_lock);
14162 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14163 					    IRE_MIPRTUN, ire_fastpath_flush,
14164 					    NULL, ill);
14165 				} else {
14166 					mutex_exit(&ire_mrtun_lock);
14167 				}
14168 			}
14169 			break;
14170 		case DL_NOTE_SDU_SIZE:
14171 			/*
14172 			 * Change the MTU size of the interface, of all
14173 			 * attached ipif's, and of all relevant ire's.  The
14174 			 * new value's a uint32_t at notify->dl_data.
14175 			 * Mtu change Vs. new ire creation - protocol below.
14176 			 *
14177 			 * a Mark the ipif as IPIF_CHANGING.
14178 			 * b Set the new mtu in the ipif.
14179 			 * c Change the ire_max_frag on all affected ires
14180 			 * d Unmark the IPIF_CHANGING
14181 			 *
14182 			 * To see how the protocol works, assume an interface
14183 			 * route is also being added simultaneously by
14184 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14185 			 * the ire. If the ire is created before step a,
14186 			 * it will be cleaned up by step c. If the ire is
14187 			 * created after step d, it will see the new value of
14188 			 * ipif_mtu. Any attempt to create the ire between
14189 			 * steps a to d will fail because of the IPIF_CHANGING
14190 			 * flag. Note that ire_create() is passed a pointer to
14191 			 * the ipif_mtu, and not the value. During ire_add
14192 			 * under the bucket lock, the ire_max_frag of the
14193 			 * new ire being created is set from the ipif/ire from
14194 			 * which it is being derived.
14195 			 */
14196 			mutex_enter(&ill->ill_lock);
14197 			ill->ill_max_frag = (uint_t)notify->dl_data;
14198 
14199 			/*
14200 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14201 			 * leave it alone
14202 			 */
14203 			if (ill->ill_mtu_userspecified) {
14204 				mutex_exit(&ill->ill_lock);
14205 				break;
14206 			}
14207 			ill->ill_max_mtu = ill->ill_max_frag;
14208 			if (ill->ill_isv6) {
14209 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14210 					ill->ill_max_mtu = IPV6_MIN_MTU;
14211 			} else {
14212 				if (ill->ill_max_mtu < IP_MIN_MTU)
14213 					ill->ill_max_mtu = IP_MIN_MTU;
14214 			}
14215 			for (ipif = ill->ill_ipif; ipif != NULL;
14216 			    ipif = ipif->ipif_next) {
14217 				/*
14218 				 * Don't override the mtu if the user
14219 				 * has explicitly set it.
14220 				 */
14221 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14222 					continue;
14223 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14224 				if (ipif->ipif_isv6)
14225 					ire = ipif_to_ire_v6(ipif);
14226 				else
14227 					ire = ipif_to_ire(ipif);
14228 				if (ire != NULL) {
14229 					ire->ire_max_frag = ipif->ipif_mtu;
14230 					ire_refrele(ire);
14231 				}
14232 				if (ipif->ipif_flags & IPIF_UP) {
14233 					if (ill->ill_isv6)
14234 						need_ire_walk_v6 = B_TRUE;
14235 					else
14236 						need_ire_walk_v4 = B_TRUE;
14237 				}
14238 			}
14239 			mutex_exit(&ill->ill_lock);
14240 			if (need_ire_walk_v4)
14241 				ire_walk_v4(ill_mtu_change, (char *)ill,
14242 				    ALL_ZONES);
14243 			if (need_ire_walk_v6)
14244 				ire_walk_v6(ill_mtu_change, (char *)ill,
14245 				    ALL_ZONES);
14246 			break;
14247 		case DL_NOTE_LINK_UP:
14248 		case DL_NOTE_LINK_DOWN: {
14249 			/*
14250 			 * We are writer. ill / phyint / ipsq assocs stable.
14251 			 * The RUNNING flag reflects the state of the link.
14252 			 */
14253 			phyint_t *phyint = ill->ill_phyint;
14254 			uint64_t new_phyint_flags;
14255 			boolean_t changed = B_FALSE;
14256 
14257 			mutex_enter(&phyint->phyint_lock);
14258 			new_phyint_flags =
14259 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14260 			    phyint->phyint_flags | PHYI_RUNNING :
14261 			    phyint->phyint_flags & ~PHYI_RUNNING;
14262 			if (new_phyint_flags != phyint->phyint_flags) {
14263 				phyint->phyint_flags = new_phyint_flags;
14264 				changed = B_TRUE;
14265 			}
14266 			mutex_exit(&phyint->phyint_lock);
14267 			/*
14268 			 * If the flags have changed, send a message to
14269 			 * the routing socket.
14270 			 */
14271 			if (changed) {
14272 				if (phyint->phyint_illv4 != NULL) {
14273 					ip_rts_ifmsg(
14274 					    phyint->phyint_illv4->ill_ipif);
14275 				}
14276 				if (phyint->phyint_illv6 != NULL) {
14277 					ip_rts_ifmsg(
14278 					    phyint->phyint_illv6->ill_ipif);
14279 				}
14280 			}
14281 			break;
14282 		}
14283 		case DL_NOTE_PROMISC_ON_PHYS:
14284 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14285 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14286 			mutex_enter(&ill->ill_lock);
14287 			ill->ill_promisc_on_phys = B_TRUE;
14288 			mutex_exit(&ill->ill_lock);
14289 			break;
14290 		case DL_NOTE_PROMISC_OFF_PHYS:
14291 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14292 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14293 			mutex_enter(&ill->ill_lock);
14294 			ill->ill_promisc_on_phys = B_FALSE;
14295 			mutex_exit(&ill->ill_lock);
14296 			break;
14297 		case DL_NOTE_CAPAB_RENEG:
14298 			/*
14299 			 * Something changed on the driver side.
14300 			 * It wants us to renegotiate the capabilities
14301 			 * on this ill. The most likely cause is the
14302 			 * aggregation interface under us where a
14303 			 * port got added or went away.
14304 			 *
14305 			 * We reset the capabilities and set the
14306 			 * state to IDMS_RENG so that when the ack
14307 			 * comes back, we can start the
14308 			 * renegotiation process.
14309 			 */
14310 			ill_capability_reset(ill);
14311 			ill->ill_capab_state = IDMS_RENEG;
14312 			break;
14313 		default:
14314 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14315 			    "type 0x%x for DL_NOTIFY_IND\n",
14316 			    notify->dl_notification));
14317 			break;
14318 		}
14319 
14320 		/*
14321 		 * As this is an asynchronous operation, we
14322 		 * should not call ill_dlpi_done
14323 		 */
14324 		break;
14325 	}
14326 	case DL_NOTIFY_ACK:
14327 		/*
14328 		 * Don't really need to check for what notifications
14329 		 * are supported; we'll process what gets sent upstream,
14330 		 * and we know it'll be something we support changing
14331 		 * based on our DL_NOTIFY_REQ.
14332 		 */
14333 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14334 		break;
14335 	case DL_PHYS_ADDR_ACK: {
14336 		/*
14337 		 * We should have an IOCTL waiting on this when request
14338 		 * sent by ill_dl_phys.
14339 		 * However, ill_dl_phys was called on an ill queue (from
14340 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14341 		 * ioctl is known to be pending on ill_wq.
14342 		 * There are two additional phys_addr_req's sent to the
14343 		 * driver to get the token and lla. ill_phys_addr_pend
14344 		 * keeps track of the last one sent so we know which
14345 		 * response we are dealing with. ill_dlpi_done will
14346 		 * update ill_phys_addr_pend when it sends the next req.
14347 		 * We don't complete the IOCTL until all three DL_PARs
14348 		 * have been attempted.
14349 		 *
14350 		 * We don't need any lock to update ill_nd_lla* fields,
14351 		 * since the ill is not yet up, We grab the lock just
14352 		 * for uniformity with other code that accesses ill_nd_lla.
14353 		 */
14354 		physaddr_req = ill->ill_phys_addr_pend;
14355 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14356 		if (physaddr_req == DL_IPV6_TOKEN ||
14357 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14358 			if (physaddr_req == DL_IPV6_TOKEN) {
14359 				/*
14360 				 * bcopy to low-order bits of ill_token
14361 				 *
14362 				 * XXX Temporary hack - currently,
14363 				 * all known tokens are 64 bits,
14364 				 * so I'll cheat for the moment.
14365 				 */
14366 				dlp = (union DL_primitives *)mp->b_rptr;
14367 
14368 				mutex_enter(&ill->ill_lock);
14369 				bcopy((uchar_t *)(mp->b_rptr +
14370 				dlp->physaddr_ack.dl_addr_offset),
14371 				(void *)&ill->ill_token.s6_addr32[2],
14372 				dlp->physaddr_ack.dl_addr_length);
14373 				ill->ill_token_length =
14374 					dlp->physaddr_ack.dl_addr_length;
14375 				mutex_exit(&ill->ill_lock);
14376 			} else {
14377 				ASSERT(ill->ill_nd_lla_mp == NULL);
14378 				mp_hw = copyb(mp);
14379 				if (mp_hw == NULL) {
14380 					err = ENOMEM;
14381 					break;
14382 				}
14383 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14384 				mutex_enter(&ill->ill_lock);
14385 				ill->ill_nd_lla_mp = mp_hw;
14386 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14387 				dlp->physaddr_ack.dl_addr_offset;
14388 				ill->ill_nd_lla_len =
14389 					dlp->physaddr_ack.dl_addr_length;
14390 				mutex_exit(&ill->ill_lock);
14391 			}
14392 			break;
14393 		}
14394 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14395 		ASSERT(ill->ill_phys_addr_mp == NULL);
14396 		if (!ill->ill_ifname_pending)
14397 			break;
14398 		ill->ill_ifname_pending = 0;
14399 		if (!ioctl_aborted)
14400 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14401 		if (mp1 != NULL) {
14402 			ASSERT(connp == NULL);
14403 			q = ill->ill_wq;
14404 		}
14405 		/*
14406 		 * If any error acks received during the plumbing sequence,
14407 		 * ill_ifname_pending_err will be set. Break out and send up
14408 		 * the error to the pending ioctl.
14409 		 */
14410 		if (ill->ill_ifname_pending_err != 0) {
14411 			err = ill->ill_ifname_pending_err;
14412 			ill->ill_ifname_pending_err = 0;
14413 			break;
14414 		}
14415 		/*
14416 		 * Get the interface token.  If the zeroth interface
14417 		 * address is zero then set the address to the link local
14418 		 * address
14419 		 */
14420 		mp_hw = copyb(mp);
14421 		if (mp_hw == NULL) {
14422 			err = ENOMEM;
14423 			break;
14424 		}
14425 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14426 		ill->ill_phys_addr_mp = mp_hw;
14427 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14428 				dlp->physaddr_ack.dl_addr_offset;
14429 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14430 		    ill->ill_phys_addr_length == 0 ||
14431 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14432 			/*
14433 			 * Compatibility: atun driver returns a length of 0.
14434 			 * ipdptp has an ill_phys_addr_length of zero(from
14435 			 * DL_BIND_ACK) but a non-zero length here.
14436 			 * ipd has an ill_phys_addr_length of 4(from
14437 			 * DL_BIND_ACK) but a non-zero length here.
14438 			 */
14439 			ill->ill_phys_addr = NULL;
14440 		} else if (dlp->physaddr_ack.dl_addr_length !=
14441 		    ill->ill_phys_addr_length) {
14442 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14443 			    "Address length mismatch %d %d\n",
14444 			    dlp->physaddr_ack.dl_addr_length,
14445 			    ill->ill_phys_addr_length));
14446 			err = EINVAL;
14447 			break;
14448 		}
14449 		mutex_enter(&ill->ill_lock);
14450 		if (ill->ill_nd_lla_mp == NULL) {
14451 			ill->ill_nd_lla_mp = copyb(mp_hw);
14452 			if (ill->ill_nd_lla_mp == NULL) {
14453 				err = ENOMEM;
14454 				mutex_exit(&ill->ill_lock);
14455 				break;
14456 			}
14457 			ill->ill_nd_lla =
14458 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14459 			    dlp->physaddr_ack.dl_addr_offset;
14460 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14461 		}
14462 		mutex_exit(&ill->ill_lock);
14463 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14464 			(void) ill_setdefaulttoken(ill);
14465 
14466 		/*
14467 		 * If the ill zero interface has a zero address assign
14468 		 * it the proper link local address.
14469 		 */
14470 		ASSERT(ill->ill_ipif->ipif_id == 0);
14471 		if (ipif != NULL &&
14472 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14473 			(void) ipif_setlinklocal(ipif);
14474 		break;
14475 	}
14476 	case DL_OK_ACK:
14477 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14478 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14479 		    dloa->dl_correct_primitive));
14480 		switch (dloa->dl_correct_primitive) {
14481 		case DL_UNBIND_REQ:
14482 		case DL_ATTACH_REQ:
14483 		case DL_DETACH_REQ:
14484 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14485 			break;
14486 		}
14487 		break;
14488 	default:
14489 		break;
14490 	}
14491 
14492 	freemsg(mp);
14493 	if (mp1) {
14494 		struct iocblk *iocp;
14495 		int mode;
14496 
14497 		/*
14498 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14499 		 * SIOCSLIFNAME do a copyout.
14500 		 */
14501 		iocp = (struct iocblk *)mp1->b_rptr;
14502 
14503 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14504 		    iocp->ioc_cmd == SIOCSLIFNAME)
14505 			mode = COPYOUT;
14506 		else
14507 			mode = NO_COPYOUT;
14508 		/*
14509 		 * The ioctl must complete now without EINPROGRESS
14510 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14511 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14512 		 * stuck for ever in the ipsq.
14513 		 */
14514 		ASSERT(err != EINPROGRESS);
14515 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14516 
14517 	}
14518 }
14519 
14520 /*
14521  * ip_rput_other is called by ip_rput to handle messages modifying the global
14522  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14523  */
14524 /* ARGSUSED */
14525 void
14526 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14527 {
14528 	ill_t		*ill;
14529 	struct iocblk	*iocp;
14530 	mblk_t		*mp1;
14531 	conn_t		*connp = NULL;
14532 
14533 	ip1dbg(("ip_rput_other "));
14534 	ill = (ill_t *)q->q_ptr;
14535 	/*
14536 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14537 	 * in which case ipsq is NULL.
14538 	 */
14539 	if (ipsq != NULL) {
14540 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14541 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14542 	}
14543 
14544 	switch (mp->b_datap->db_type) {
14545 	case M_ERROR:
14546 	case M_HANGUP:
14547 		/*
14548 		 * The device has a problem.  We force the ILL down.  It can
14549 		 * be brought up again manually using SIOCSIFFLAGS (via
14550 		 * ifconfig or equivalent).
14551 		 */
14552 		ASSERT(ipsq != NULL);
14553 		if (mp->b_rptr < mp->b_wptr)
14554 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14555 		if (ill->ill_error == 0)
14556 			ill->ill_error = ENXIO;
14557 		if (!ill_down_start(q, mp))
14558 			return;
14559 		ipif_all_down_tail(ipsq, q, mp, NULL);
14560 		break;
14561 	case M_IOCACK:
14562 		iocp = (struct iocblk *)mp->b_rptr;
14563 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14564 		switch (iocp->ioc_cmd) {
14565 		case SIOCSTUNPARAM:
14566 		case OSIOCSTUNPARAM:
14567 			ASSERT(ipsq != NULL);
14568 			/*
14569 			 * Finish socket ioctl passed through to tun.
14570 			 * We should have an IOCTL waiting on this.
14571 			 */
14572 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14573 			if (ill->ill_isv6) {
14574 				struct iftun_req *ta;
14575 
14576 				/*
14577 				 * if a source or destination is
14578 				 * being set, try and set the link
14579 				 * local address for the tunnel
14580 				 */
14581 				ta = (struct iftun_req *)mp->b_cont->
14582 				    b_cont->b_rptr;
14583 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14584 					ipif_set_tun_llink(ill, ta);
14585 				}
14586 
14587 			}
14588 			if (mp1 != NULL) {
14589 				/*
14590 				 * Now copy back the b_next/b_prev used by
14591 				 * mi code for the mi_copy* functions.
14592 				 * See ip_sioctl_tunparam() for the reason.
14593 				 * Also protect against missing b_cont.
14594 				 */
14595 				if (mp->b_cont != NULL) {
14596 					mp->b_cont->b_next =
14597 					    mp1->b_cont->b_next;
14598 					mp->b_cont->b_prev =
14599 					    mp1->b_cont->b_prev;
14600 				}
14601 				inet_freemsg(mp1);
14602 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14603 				ASSERT(connp != NULL);
14604 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14605 				    iocp->ioc_error, NO_COPYOUT,
14606 				    ipsq->ipsq_current_ipif, ipsq);
14607 			} else {
14608 				ASSERT(connp == NULL);
14609 				putnext(q, mp);
14610 			}
14611 			break;
14612 		case SIOCGTUNPARAM:
14613 		case OSIOCGTUNPARAM:
14614 			/*
14615 			 * This is really M_IOCDATA from the tunnel driver.
14616 			 * convert back and complete the ioctl.
14617 			 * We should have an IOCTL waiting on this.
14618 			 */
14619 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14620 			if (mp1) {
14621 				/*
14622 				 * Now copy back the b_next/b_prev used by
14623 				 * mi code for the mi_copy* functions.
14624 				 * See ip_sioctl_tunparam() for the reason.
14625 				 * Also protect against missing b_cont.
14626 				 */
14627 				if (mp->b_cont != NULL) {
14628 					mp->b_cont->b_next =
14629 					    mp1->b_cont->b_next;
14630 					mp->b_cont->b_prev =
14631 					    mp1->b_cont->b_prev;
14632 				}
14633 				inet_freemsg(mp1);
14634 				if (iocp->ioc_error == 0)
14635 					mp->b_datap->db_type = M_IOCDATA;
14636 				ASSERT(connp != NULL);
14637 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14638 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14639 			} else {
14640 				ASSERT(connp == NULL);
14641 				putnext(q, mp);
14642 			}
14643 			break;
14644 		default:
14645 			break;
14646 		}
14647 		break;
14648 	case M_IOCNAK:
14649 		iocp = (struct iocblk *)mp->b_rptr;
14650 
14651 		switch (iocp->ioc_cmd) {
14652 		int mode;
14653 		ipif_t	*ipif;
14654 
14655 		case DL_IOC_HDR_INFO:
14656 			/*
14657 			 * If this was the first attempt turn of the
14658 			 * fastpath probing.
14659 			 */
14660 			mutex_enter(&ill->ill_lock);
14661 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14662 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14663 				mutex_exit(&ill->ill_lock);
14664 				ill_fastpath_nack(ill);
14665 				ip1dbg(("ip_rput: DLPI fastpath off on "
14666 				    "interface %s\n",
14667 				    ill->ill_name));
14668 			} else {
14669 				mutex_exit(&ill->ill_lock);
14670 			}
14671 			freemsg(mp);
14672 			break;
14673 		case SIOCSTUNPARAM:
14674 		case OSIOCSTUNPARAM:
14675 			ASSERT(ipsq != NULL);
14676 			/*
14677 			 * Finish socket ioctl passed through to tun
14678 			 * We should have an IOCTL waiting on this.
14679 			 */
14680 			/* FALLTHRU */
14681 		case SIOCGTUNPARAM:
14682 		case OSIOCGTUNPARAM:
14683 			/*
14684 			 * This is really M_IOCDATA from the tunnel driver.
14685 			 * convert back and complete the ioctl.
14686 			 * We should have an IOCTL waiting on this.
14687 			 */
14688 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14689 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14690 				mp1 = ill_pending_mp_get(ill, &connp,
14691 				    iocp->ioc_id);
14692 				mode = COPYOUT;
14693 				ipsq = NULL;
14694 				ipif = NULL;
14695 			} else {
14696 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14697 				mode = NO_COPYOUT;
14698 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14699 				ipif = ipsq->ipsq_current_ipif;
14700 			}
14701 			if (mp1 != NULL) {
14702 				/*
14703 				 * Now copy back the b_next/b_prev used by
14704 				 * mi code for the mi_copy* functions.
14705 				 * See ip_sioctl_tunparam() for the reason.
14706 				 * Also protect against missing b_cont.
14707 				 */
14708 				if (mp->b_cont != NULL) {
14709 					mp->b_cont->b_next =
14710 					    mp1->b_cont->b_next;
14711 					mp->b_cont->b_prev =
14712 					    mp1->b_cont->b_prev;
14713 				}
14714 				inet_freemsg(mp1);
14715 				if (iocp->ioc_error == 0)
14716 					iocp->ioc_error = EINVAL;
14717 				ASSERT(connp != NULL);
14718 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14719 				    iocp->ioc_error, mode, ipif, ipsq);
14720 			} else {
14721 				ASSERT(connp == NULL);
14722 				putnext(q, mp);
14723 			}
14724 			break;
14725 		default:
14726 			break;
14727 		}
14728 	default:
14729 		break;
14730 	}
14731 }
14732 
14733 /*
14734  * NOTE : This function does not ire_refrele the ire argument passed in.
14735  *
14736  * IPQoS notes
14737  * IP policy is invoked twice for a forwarded packet, once on the read side
14738  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14739  * enabled. An additional parameter, in_ill, has been added for this purpose.
14740  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14741  * because ip_mroute drops this information.
14742  *
14743  */
14744 void
14745 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14746 {
14747 	uint32_t	pkt_len;
14748 	queue_t	*q;
14749 	uint32_t	sum;
14750 #define	rptr	((uchar_t *)ipha)
14751 	uint32_t	max_frag;
14752 	uint32_t	ill_index;
14753 
14754 	/* Get the ill_index of the incoming ILL */
14755 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14756 
14757 	/* Initiate Read side IPPF processing */
14758 	if (IPP_ENABLED(IPP_FWD_IN)) {
14759 		ip_process(IPP_FWD_IN, &mp, ill_index);
14760 		if (mp == NULL) {
14761 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14762 			    "during IPPF processing\n"));
14763 			return;
14764 		}
14765 	}
14766 	pkt_len = ntohs(ipha->ipha_length);
14767 
14768 	/* Adjust the checksum to reflect the ttl decrement. */
14769 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14770 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14771 
14772 	if (ipha->ipha_ttl-- <= 1) {
14773 		if (ip_csum_hdr(ipha)) {
14774 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14775 			goto drop_pkt;
14776 		}
14777 		/*
14778 		 * Note: ire_stq this will be NULL for multicast
14779 		 * datagrams using the long path through arp (the IRE
14780 		 * is not an IRE_CACHE). This should not cause
14781 		 * problems since we don't generate ICMP errors for
14782 		 * multicast packets.
14783 		 */
14784 		q = ire->ire_stq;
14785 		if (q)
14786 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14787 		else
14788 			freemsg(mp);
14789 		return;
14790 	}
14791 
14792 	/*
14793 	 * Don't forward if the interface is down
14794 	 */
14795 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14796 		BUMP_MIB(&ip_mib, ipInDiscards);
14797 		goto drop_pkt;
14798 	}
14799 
14800 	/* Get the ill_index of the outgoing ILL */
14801 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14802 
14803 	/* Check if there are options to update */
14804 	if (!IS_SIMPLE_IPH(ipha)) {
14805 		if (ip_csum_hdr(ipha)) {
14806 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14807 			goto drop_pkt;
14808 		}
14809 		if (ip_rput_forward_options(mp, ipha, ire)) {
14810 			return;
14811 		}
14812 
14813 		ipha->ipha_hdr_checksum = 0;
14814 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14815 	}
14816 	max_frag = ire->ire_max_frag;
14817 	if (pkt_len > max_frag) {
14818 		/*
14819 		 * It needs fragging on its way out.  We haven't
14820 		 * verified the header checksum yet.  Since we
14821 		 * are going to put a surely good checksum in the
14822 		 * outgoing header, we have to make sure that it
14823 		 * was good coming in.
14824 		 */
14825 		if (ip_csum_hdr(ipha)) {
14826 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14827 			goto drop_pkt;
14828 		}
14829 		/* Initiate Write side IPPF processing */
14830 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14831 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14832 			if (mp == NULL) {
14833 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14834 				    " during IPPF processing\n"));
14835 				return;
14836 			}
14837 		}
14838 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14839 		return;
14840 	}
14841 
14842 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14843 	if (mp == NULL) {
14844 		BUMP_MIB(&ip_mib, ipInDiscards);
14845 		return;
14846 	}
14847 
14848 	q = ire->ire_stq;
14849 	UPDATE_IB_PKT_COUNT(ire);
14850 	ire->ire_last_used_time = lbolt;
14851 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14852 	putnext(q, mp);
14853 	return;
14854 
14855 drop_pkt:;
14856 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14857 	freemsg(mp);
14858 #undef	rptr
14859 }
14860 
14861 void
14862 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14863 {
14864 	ire_t	*ire;
14865 
14866 	ASSERT(!ipif->ipif_isv6);
14867 	/*
14868 	 * Find an IRE which matches the destination and the outgoing
14869 	 * queue in the cache table. All we need is an IRE_CACHE which
14870 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14871 	 * then it is enough to have some IRE_CACHE in the group.
14872 	 */
14873 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14874 		dst = ipif->ipif_pp_dst_addr;
14875 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14876 	    MATCH_IRE_ILL_GROUP);
14877 	if (!ire) {
14878 		/*
14879 		 * Mark this packet to make it be delivered to
14880 		 * ip_rput_forward after the new ire has been
14881 		 * created.
14882 		 */
14883 		mp->b_prev = NULL;
14884 		mp->b_next = mp;
14885 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14886 		    NULL, 0);
14887 	} else {
14888 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14889 		IRE_REFRELE(ire);
14890 	}
14891 }
14892 
14893 /* Update any source route, record route or timestamp options */
14894 static int
14895 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
14896 {
14897 	ipoptp_t	opts;
14898 	uchar_t		*opt;
14899 	uint8_t		optval;
14900 	uint8_t		optlen;
14901 	ipaddr_t	dst;
14902 	uint32_t	ts;
14903 	ire_t		*dst_ire = NULL;
14904 	ire_t		*tmp_ire = NULL;
14905 	timestruc_t	now;
14906 
14907 	ip2dbg(("ip_rput_forward_options\n"));
14908 	dst = ipha->ipha_dst;
14909 	for (optval = ipoptp_first(&opts, ipha);
14910 	    optval != IPOPT_EOL;
14911 	    optval = ipoptp_next(&opts)) {
14912 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
14913 		opt = opts.ipoptp_cur;
14914 		optlen = opts.ipoptp_len;
14915 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
14916 		    optval, opts.ipoptp_len));
14917 		switch (optval) {
14918 			uint32_t off;
14919 		case IPOPT_SSRR:
14920 		case IPOPT_LSRR:
14921 			/* Check if adminstratively disabled */
14922 			if (!ip_forward_src_routed) {
14923 				BUMP_MIB(&ip_mib, ipForwProhibits);
14924 				if (ire->ire_stq)
14925 					icmp_unreachable(ire->ire_stq, mp,
14926 					    ICMP_SOURCE_ROUTE_FAILED);
14927 				else {
14928 					ip0dbg(("ip_rput_forward_options: "
14929 					    "unable to send unreach\n"));
14930 					freemsg(mp);
14931 				}
14932 				return (-1);
14933 			}
14934 
14935 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14936 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14937 			if (dst_ire == NULL) {
14938 				/*
14939 				 * Must be partial since ip_rput_options
14940 				 * checked for strict.
14941 				 */
14942 				break;
14943 			}
14944 			off = opt[IPOPT_OFFSET];
14945 			off--;
14946 		redo_srr:
14947 			if (optlen < IP_ADDR_LEN ||
14948 			    off > optlen - IP_ADDR_LEN) {
14949 				/* End of source route */
14950 				ip1dbg((
14951 				    "ip_rput_forward_options: end of SR\n"));
14952 				ire_refrele(dst_ire);
14953 				break;
14954 			}
14955 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14956 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14957 			    IP_ADDR_LEN);
14958 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
14959 			    ntohl(dst)));
14960 
14961 			/*
14962 			 * Check if our address is present more than
14963 			 * once as consecutive hops in source route.
14964 			 */
14965 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14966 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14967 			if (tmp_ire != NULL) {
14968 				ire_refrele(tmp_ire);
14969 				off += IP_ADDR_LEN;
14970 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14971 				goto redo_srr;
14972 			}
14973 			ipha->ipha_dst = dst;
14974 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14975 			ire_refrele(dst_ire);
14976 			break;
14977 		case IPOPT_RR:
14978 			off = opt[IPOPT_OFFSET];
14979 			off--;
14980 			if (optlen < IP_ADDR_LEN ||
14981 			    off > optlen - IP_ADDR_LEN) {
14982 				/* No more room - ignore */
14983 				ip1dbg((
14984 				    "ip_rput_forward_options: end of RR\n"));
14985 				break;
14986 			}
14987 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14988 			    IP_ADDR_LEN);
14989 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14990 			break;
14991 		case IPOPT_TS:
14992 			/* Insert timestamp if there is room */
14993 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14994 			case IPOPT_TS_TSONLY:
14995 				off = IPOPT_TS_TIMELEN;
14996 				break;
14997 			case IPOPT_TS_PRESPEC:
14998 			case IPOPT_TS_PRESPEC_RFC791:
14999 				/* Verify that the address matched */
15000 				off = opt[IPOPT_OFFSET] - 1;
15001 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15002 				dst_ire = ire_ctable_lookup(dst, 0,
15003 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
15004 				if (dst_ire == NULL) {
15005 					/* Not for us */
15006 					break;
15007 				}
15008 				ire_refrele(dst_ire);
15009 				/* FALLTHRU */
15010 			case IPOPT_TS_TSANDADDR:
15011 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15012 				break;
15013 			default:
15014 				/*
15015 				 * ip_*put_options should have already
15016 				 * dropped this packet.
15017 				 */
15018 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15019 				    "unknown IT - bug in ip_rput_options?\n");
15020 				return (0);	/* Keep "lint" happy */
15021 			}
15022 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15023 				/* Increase overflow counter */
15024 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15025 				opt[IPOPT_POS_OV_FLG] =
15026 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15027 				    (off << 4));
15028 				break;
15029 			}
15030 			off = opt[IPOPT_OFFSET] - 1;
15031 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15032 			case IPOPT_TS_PRESPEC:
15033 			case IPOPT_TS_PRESPEC_RFC791:
15034 			case IPOPT_TS_TSANDADDR:
15035 				bcopy(&ire->ire_src_addr,
15036 				    (char *)opt + off, IP_ADDR_LEN);
15037 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15038 				/* FALLTHRU */
15039 			case IPOPT_TS_TSONLY:
15040 				off = opt[IPOPT_OFFSET] - 1;
15041 				/* Compute # of milliseconds since midnight */
15042 				gethrestime(&now);
15043 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15044 				    now.tv_nsec / (NANOSEC / MILLISEC);
15045 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15046 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15047 				break;
15048 			}
15049 			break;
15050 		}
15051 	}
15052 	return (0);
15053 }
15054 
15055 /*
15056  * This is called after processing at least one of AH/ESP headers.
15057  *
15058  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15059  * the actual, physical interface on which the packet was received,
15060  * but, when ip_strict_dst_multihoming is set to 1, could be the
15061  * interface which had the ipha_dst configured when the packet went
15062  * through ip_rput. The ill_index corresponding to the recv_ill
15063  * is saved in ipsec_in_rill_index
15064  */
15065 void
15066 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15067 {
15068 	mblk_t *mp;
15069 	ipaddr_t dst;
15070 	in6_addr_t *v6dstp;
15071 	ipha_t *ipha;
15072 	ip6_t *ip6h;
15073 	ipsec_in_t *ii;
15074 	boolean_t ill_need_rele = B_FALSE;
15075 	boolean_t rill_need_rele = B_FALSE;
15076 	boolean_t ire_need_rele = B_FALSE;
15077 
15078 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15079 	ASSERT(ii->ipsec_in_ill_index != 0);
15080 
15081 	mp = ipsec_mp->b_cont;
15082 	ASSERT(mp != NULL);
15083 
15084 
15085 	if (ill == NULL) {
15086 		ASSERT(recv_ill == NULL);
15087 		/*
15088 		 * We need to get the original queue on which ip_rput_local
15089 		 * or ip_rput_data_v6 was called.
15090 		 */
15091 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15092 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15093 		ill_need_rele = B_TRUE;
15094 
15095 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15096 			recv_ill = ill_lookup_on_ifindex(
15097 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15098 			    NULL, NULL, NULL, NULL);
15099 			rill_need_rele = B_TRUE;
15100 		} else {
15101 			recv_ill = ill;
15102 		}
15103 
15104 		if ((ill == NULL) || (recv_ill == NULL)) {
15105 			ip0dbg(("ip_fanout_proto_again: interface "
15106 			    "disappeared\n"));
15107 			if (ill != NULL)
15108 				ill_refrele(ill);
15109 			if (recv_ill != NULL)
15110 				ill_refrele(recv_ill);
15111 			freemsg(ipsec_mp);
15112 			return;
15113 		}
15114 	}
15115 
15116 	ASSERT(ill != NULL && recv_ill != NULL);
15117 
15118 	if (mp->b_datap->db_type == M_CTL) {
15119 		/*
15120 		 * AH/ESP is returning the ICMP message after
15121 		 * removing their headers. Fanout again till
15122 		 * it gets to the right protocol.
15123 		 */
15124 		if (ii->ipsec_in_v4) {
15125 			icmph_t *icmph;
15126 			int iph_hdr_length;
15127 			int hdr_length;
15128 
15129 			ipha = (ipha_t *)mp->b_rptr;
15130 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15131 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15132 			ipha = (ipha_t *)&icmph[1];
15133 			hdr_length = IPH_HDR_LENGTH(ipha);
15134 			/*
15135 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15136 			 * Reset the type to M_DATA.
15137 			 */
15138 			mp->b_datap->db_type = M_DATA;
15139 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15140 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15141 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15142 		} else {
15143 			icmp6_t *icmp6;
15144 			int hdr_length;
15145 
15146 			ip6h = (ip6_t *)mp->b_rptr;
15147 			/* Don't call hdr_length_v6() unless you have to. */
15148 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15149 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15150 			else
15151 				hdr_length = IPV6_HDR_LEN;
15152 
15153 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15154 			/*
15155 			 * icmp_inbound_error_fanout_v6 may need to do
15156 			 * pullupmsg.  Reset the type to M_DATA.
15157 			 */
15158 			mp->b_datap->db_type = M_DATA;
15159 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15160 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15161 		}
15162 		if (ill_need_rele)
15163 			ill_refrele(ill);
15164 		if (rill_need_rele)
15165 			ill_refrele(recv_ill);
15166 		return;
15167 	}
15168 
15169 	if (ii->ipsec_in_v4) {
15170 		ipha = (ipha_t *)mp->b_rptr;
15171 		dst = ipha->ipha_dst;
15172 		if (CLASSD(dst)) {
15173 			/*
15174 			 * Multicast has to be delivered to all streams.
15175 			 */
15176 			dst = INADDR_BROADCAST;
15177 		}
15178 
15179 		if (ire == NULL) {
15180 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15181 			if (ire == NULL) {
15182 				if (ill_need_rele)
15183 					ill_refrele(ill);
15184 				if (rill_need_rele)
15185 					ill_refrele(recv_ill);
15186 				ip1dbg(("ip_fanout_proto_again: "
15187 				    "IRE not found"));
15188 				freemsg(ipsec_mp);
15189 				return;
15190 			}
15191 			ire_need_rele = B_TRUE;
15192 		}
15193 
15194 		switch (ipha->ipha_protocol) {
15195 			case IPPROTO_UDP:
15196 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15197 				    recv_ill);
15198 				if (ire_need_rele)
15199 					ire_refrele(ire);
15200 				break;
15201 			case IPPROTO_TCP:
15202 				if (!ire_need_rele)
15203 					IRE_REFHOLD(ire);
15204 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15205 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15206 				IRE_REFRELE(ire);
15207 				if (mp != NULL)
15208 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15209 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15210 				break;
15211 			case IPPROTO_SCTP:
15212 				if (!ire_need_rele)
15213 					IRE_REFHOLD(ire);
15214 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15215 				    ipsec_mp, 0, ill->ill_rq, dst);
15216 				break;
15217 			default:
15218 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15219 				    recv_ill);
15220 				if (ire_need_rele)
15221 					ire_refrele(ire);
15222 				break;
15223 		}
15224 	} else {
15225 		uint32_t rput_flags = 0;
15226 
15227 		ip6h = (ip6_t *)mp->b_rptr;
15228 		v6dstp = &ip6h->ip6_dst;
15229 		/*
15230 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15231 		 * address.
15232 		 *
15233 		 * Currently, we don't store that state in the IPSEC_IN
15234 		 * message, and we may need to.
15235 		 */
15236 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15237 		    IP6_IN_LLMCAST : 0);
15238 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15239 		    NULL);
15240 	}
15241 	if (ill_need_rele)
15242 		ill_refrele(ill);
15243 	if (rill_need_rele)
15244 		ill_refrele(recv_ill);
15245 }
15246 
15247 /*
15248  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15249  * returns 'true' if there are still fragments left on the queue, in
15250  * which case we restart the timer.
15251  */
15252 void
15253 ill_frag_timer(void *arg)
15254 {
15255 	ill_t	*ill = (ill_t *)arg;
15256 	boolean_t frag_pending;
15257 
15258 	mutex_enter(&ill->ill_lock);
15259 	ASSERT(!ill->ill_fragtimer_executing);
15260 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15261 		ill->ill_frag_timer_id = 0;
15262 		mutex_exit(&ill->ill_lock);
15263 		return;
15264 	}
15265 	ill->ill_fragtimer_executing = 1;
15266 	mutex_exit(&ill->ill_lock);
15267 
15268 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15269 
15270 	/*
15271 	 * Restart the timer, if we have fragments pending or if someone
15272 	 * wanted us to be scheduled again.
15273 	 */
15274 	mutex_enter(&ill->ill_lock);
15275 	ill->ill_fragtimer_executing = 0;
15276 	ill->ill_frag_timer_id = 0;
15277 	if (frag_pending || ill->ill_fragtimer_needrestart)
15278 		ill_frag_timer_start(ill);
15279 	mutex_exit(&ill->ill_lock);
15280 }
15281 
15282 void
15283 ill_frag_timer_start(ill_t *ill)
15284 {
15285 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15286 
15287 	/* If the ill is closing or opening don't proceed */
15288 	if (ill->ill_state_flags & ILL_CONDEMNED)
15289 		return;
15290 
15291 	if (ill->ill_fragtimer_executing) {
15292 		/*
15293 		 * ill_frag_timer is currently executing. Just record the
15294 		 * the fact that we want the timer to be restarted.
15295 		 * ill_frag_timer will post a timeout before it returns,
15296 		 * ensuring it will be called again.
15297 		 */
15298 		ill->ill_fragtimer_needrestart = 1;
15299 		return;
15300 	}
15301 
15302 	if (ill->ill_frag_timer_id == 0) {
15303 		/*
15304 		 * The timer is neither running nor is the timeout handler
15305 		 * executing. Post a timeout so that ill_frag_timer will be
15306 		 * called
15307 		 */
15308 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15309 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15310 		ill->ill_fragtimer_needrestart = 0;
15311 	}
15312 }
15313 
15314 /*
15315  * This routine is needed for loopback when forwarding multicasts.
15316  *
15317  * IPQoS Notes:
15318  * IPPF processing is done in fanout routines.
15319  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15320  * processing for IPSec packets is done when it comes back in clear.
15321  * NOTE : The callers of this function need to do the ire_refrele for the
15322  *	  ire that is being passed in.
15323  */
15324 void
15325 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15326     ill_t *recv_ill)
15327 {
15328 	ill_t	*ill = (ill_t *)q->q_ptr;
15329 	uint32_t	sum;
15330 	uint32_t	u1;
15331 	uint32_t	u2;
15332 	int		hdr_length;
15333 	boolean_t	mctl_present;
15334 	mblk_t		*first_mp = mp;
15335 	mblk_t		*hada_mp = NULL;
15336 	ipha_t		*inner_ipha;
15337 
15338 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15339 	    "ip_rput_locl_start: q %p", q);
15340 
15341 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15342 
15343 
15344 #define	rptr	((uchar_t *)ipha)
15345 #define	iphs	((uint16_t *)ipha)
15346 
15347 	/*
15348 	 * no UDP or TCP packet should come here anymore.
15349 	 */
15350 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15351 	    (ipha->ipha_protocol != IPPROTO_UDP));
15352 
15353 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15354 	if (mctl_present &&
15355 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15356 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15357 
15358 		/*
15359 		 * It's an IPsec accelerated packet.
15360 		 * Keep a pointer to the data attributes around until
15361 		 * we allocate the ipsec_info_t.
15362 		 */
15363 		IPSECHW_DEBUG(IPSECHW_PKT,
15364 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15365 		hada_mp = first_mp;
15366 		hada_mp->b_cont = NULL;
15367 		/*
15368 		 * Since it is accelerated, it comes directly from
15369 		 * the ill and the data attributes is followed by
15370 		 * the packet data.
15371 		 */
15372 		ASSERT(mp->b_datap->db_type != M_CTL);
15373 		first_mp = mp;
15374 		mctl_present = B_FALSE;
15375 	}
15376 
15377 	/*
15378 	 * IF M_CTL is not present, then ipsec_in_is_secure
15379 	 * should return B_TRUE. There is a case where loopback
15380 	 * packets has an M_CTL in the front with all the
15381 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15382 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15383 	 * packets never comes here, it is safe to ASSERT the
15384 	 * following.
15385 	 */
15386 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15387 
15388 
15389 	/* u1 is # words of IP options */
15390 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15391 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15392 
15393 	if (u1) {
15394 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15395 			if (hada_mp != NULL)
15396 				freemsg(hada_mp);
15397 			return;
15398 		}
15399 	} else {
15400 		/* Check the IP header checksum.  */
15401 #define	uph	((uint16_t *)ipha)
15402 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15403 		    uph[6] + uph[7] + uph[8] + uph[9];
15404 #undef  uph
15405 		/* finish doing IP checksum */
15406 		sum = (sum & 0xFFFF) + (sum >> 16);
15407 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15408 		/*
15409 		 * Don't verify header checksum if this packet is coming
15410 		 * back from AH/ESP as we already did it.
15411 		 */
15412 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15413 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15414 			goto drop_pkt;
15415 		}
15416 	}
15417 
15418 	/*
15419 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15420 	 * might be called more than once for secure packets, count only
15421 	 * the first time.
15422 	 */
15423 	if (!mctl_present) {
15424 		UPDATE_IB_PKT_COUNT(ire);
15425 		ire->ire_last_used_time = lbolt;
15426 	}
15427 
15428 	/* Check for fragmentation offset. */
15429 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15430 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15431 	if (u1) {
15432 		/*
15433 		 * We re-assemble fragments before we do the AH/ESP
15434 		 * processing. Thus, M_CTL should not be present
15435 		 * while we are re-assembling.
15436 		 */
15437 		ASSERT(!mctl_present);
15438 		ASSERT(first_mp == mp);
15439 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
15440 			return;
15441 		}
15442 		/*
15443 		 * Make sure that first_mp points back to mp as
15444 		 * the mp we came in with could have changed in
15445 		 * ip_rput_fragment().
15446 		 */
15447 		ipha = (ipha_t *)mp->b_rptr;
15448 		first_mp = mp;
15449 	}
15450 
15451 	/*
15452 	 * Clear hardware checksumming flag as it is currently only
15453 	 * used by TCP and UDP.
15454 	 */
15455 	DB_CKSUMFLAGS(mp) = 0;
15456 
15457 	/* Now we have a complete datagram, destined for this machine. */
15458 	u1 = IPH_HDR_LENGTH(ipha);
15459 	switch (ipha->ipha_protocol) {
15460 	case IPPROTO_ICMP: {
15461 		ire_t		*ire_zone;
15462 		ilm_t		*ilm;
15463 		mblk_t		*mp1;
15464 		zoneid_t	last_zoneid;
15465 
15466 		if (CLASSD(ipha->ipha_dst) &&
15467 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15468 			ASSERT(ire->ire_type == IRE_BROADCAST);
15469 			/*
15470 			 * In the multicast case, applications may have joined
15471 			 * the group from different zones, so we need to deliver
15472 			 * the packet to each of them. Loop through the
15473 			 * multicast memberships structures (ilm) on the receive
15474 			 * ill and send a copy of the packet up each matching
15475 			 * one. However, we don't do this for multicasts sent on
15476 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15477 			 * they must stay in the sender's zone.
15478 			 *
15479 			 * ilm_add_v6() ensures that ilms in the same zone are
15480 			 * contiguous in the ill_ilm list. We use this property
15481 			 * to avoid sending duplicates needed when two
15482 			 * applications in the same zone join the same group on
15483 			 * different logical interfaces: we ignore the ilm if
15484 			 * its zoneid is the same as the last matching one.
15485 			 * In addition, the sending of the packet for
15486 			 * ire_zoneid is delayed until all of the other ilms
15487 			 * have been exhausted.
15488 			 */
15489 			last_zoneid = -1;
15490 			ILM_WALKER_HOLD(recv_ill);
15491 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15492 			    ilm = ilm->ilm_next) {
15493 				if ((ilm->ilm_flags & ILM_DELETED) ||
15494 				    ipha->ipha_dst != ilm->ilm_addr ||
15495 				    ilm->ilm_zoneid == last_zoneid ||
15496 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15497 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15498 					continue;
15499 				mp1 = ip_copymsg(first_mp);
15500 				if (mp1 == NULL)
15501 					continue;
15502 				icmp_inbound(q, mp1, B_TRUE, ill,
15503 				    0, sum, mctl_present, B_TRUE,
15504 				    recv_ill, ilm->ilm_zoneid);
15505 				last_zoneid = ilm->ilm_zoneid;
15506 			}
15507 			ILM_WALKER_RELE(recv_ill);
15508 		} else if (ire->ire_type == IRE_BROADCAST) {
15509 			/*
15510 			 * In the broadcast case, there may be many zones
15511 			 * which need a copy of the packet delivered to them.
15512 			 * There is one IRE_BROADCAST per broadcast address
15513 			 * and per zone; we walk those using a helper function.
15514 			 * In addition, the sending of the packet for ire is
15515 			 * delayed until all of the other ires have been
15516 			 * processed.
15517 			 */
15518 			IRB_REFHOLD(ire->ire_bucket);
15519 			ire_zone = NULL;
15520 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15521 			    ire)) != NULL) {
15522 				mp1 = ip_copymsg(first_mp);
15523 				if (mp1 == NULL)
15524 					continue;
15525 
15526 				UPDATE_IB_PKT_COUNT(ire_zone);
15527 				ire_zone->ire_last_used_time = lbolt;
15528 				icmp_inbound(q, mp1, B_TRUE, ill,
15529 				    0, sum, mctl_present, B_TRUE,
15530 				    recv_ill, ire_zone->ire_zoneid);
15531 			}
15532 			IRB_REFRELE(ire->ire_bucket);
15533 		}
15534 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15535 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15536 		    ire->ire_zoneid);
15537 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15538 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15539 		return;
15540 	}
15541 	case IPPROTO_IGMP:
15542 		/*
15543 		 * If we are not willing to accept IGMP packets in clear,
15544 		 * then check with global policy.
15545 		 */
15546 		if (igmp_accept_clear_messages == 0) {
15547 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15548 			    ipha, NULL, mctl_present);
15549 			if (first_mp == NULL)
15550 				return;
15551 		}
15552 		if (igmp_input(q, mp, ill)) {
15553 			/* Bad packet - discarded by igmp_input */
15554 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15555 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15556 			if (mctl_present)
15557 				freeb(first_mp);
15558 			return;
15559 		}
15560 		/*
15561 		 * igmp_input() may have pulled up the message so ipha needs to
15562 		 * be reinitialized.
15563 		 */
15564 		ipha = (ipha_t *)mp->b_rptr;
15565 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15566 			/* No user-level listener for IGMP packets */
15567 			goto drop_pkt;
15568 		}
15569 		/* deliver to local raw users */
15570 		break;
15571 	case IPPROTO_PIM:
15572 		/*
15573 		 * If we are not willing to accept PIM packets in clear,
15574 		 * then check with global policy.
15575 		 */
15576 		if (pim_accept_clear_messages == 0) {
15577 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15578 			    ipha, NULL, mctl_present);
15579 			if (first_mp == NULL)
15580 				return;
15581 		}
15582 		if (pim_input(q, mp) != 0) {
15583 			/* Bad packet - discarded by pim_input */
15584 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15585 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15586 			if (mctl_present)
15587 				freeb(first_mp);
15588 			return;
15589 		}
15590 
15591 		/*
15592 		 * pim_input() may have pulled up the message so ipha needs to
15593 		 * be reinitialized.
15594 		 */
15595 		ipha = (ipha_t *)mp->b_rptr;
15596 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15597 			/* No user-level listener for PIM packets */
15598 			goto drop_pkt;
15599 		}
15600 		/* deliver to local raw users */
15601 		break;
15602 	case IPPROTO_ENCAP:
15603 		/*
15604 		 * Handle self-encapsulated packets (IP-in-IP where
15605 		 * the inner addresses == the outer addresses).
15606 		 */
15607 		hdr_length = IPH_HDR_LENGTH(ipha);
15608 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15609 		    mp->b_wptr) {
15610 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15611 			    sizeof (ipha_t) - mp->b_rptr)) {
15612 				BUMP_MIB(&ip_mib, ipInDiscards);
15613 				freemsg(first_mp);
15614 				return;
15615 			}
15616 			ipha = (ipha_t *)mp->b_rptr;
15617 		}
15618 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15619 		/*
15620 		 * Check the sanity of the inner IP header.
15621 		 */
15622 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15623 			BUMP_MIB(&ip_mib, ipInDiscards);
15624 			freemsg(first_mp);
15625 			return;
15626 		}
15627 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15628 			BUMP_MIB(&ip_mib, ipInDiscards);
15629 			freemsg(first_mp);
15630 			return;
15631 		}
15632 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15633 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15634 			ipsec_in_t *ii;
15635 
15636 			/*
15637 			 * Self-encapsulated tunnel packet. Remove
15638 			 * the outer IP header and fanout again.
15639 			 * We also need to make sure that the inner
15640 			 * header is pulled up until options.
15641 			 */
15642 			mp->b_rptr = (uchar_t *)inner_ipha;
15643 			ipha = inner_ipha;
15644 			hdr_length = IPH_HDR_LENGTH(ipha);
15645 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15646 				if (!pullupmsg(mp, (uchar_t *)ipha +
15647 				    + hdr_length - mp->b_rptr)) {
15648 					freemsg(first_mp);
15649 					return;
15650 				}
15651 				ipha = (ipha_t *)mp->b_rptr;
15652 			}
15653 			if (!mctl_present) {
15654 				ASSERT(first_mp == mp);
15655 				/*
15656 				 * This means that somebody is sending
15657 				 * Self-encapsualted packets without AH/ESP.
15658 				 * If AH/ESP was present, we would have already
15659 				 * allocated the first_mp.
15660 				 */
15661 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15662 				    NULL) {
15663 					ip1dbg(("ip_proto_input: IPSEC_IN "
15664 					    "allocation failure.\n"));
15665 					BUMP_MIB(&ip_mib, ipInDiscards);
15666 					freemsg(mp);
15667 					return;
15668 				}
15669 				first_mp->b_cont = mp;
15670 			}
15671 			/*
15672 			 * We generally store the ill_index if we need to
15673 			 * do IPSEC processing as we lose the ill queue when
15674 			 * we come back. But in this case, we never should
15675 			 * have to store the ill_index here as it should have
15676 			 * been stored previously when we processed the
15677 			 * AH/ESP header in this routine or for non-ipsec
15678 			 * cases, we still have the queue. But for some bad
15679 			 * packets from the wire, we can get to IPSEC after
15680 			 * this and we better store the index for that case.
15681 			 */
15682 			ill = (ill_t *)q->q_ptr;
15683 			ii = (ipsec_in_t *)first_mp->b_rptr;
15684 			ii->ipsec_in_ill_index =
15685 			    ill->ill_phyint->phyint_ifindex;
15686 			ii->ipsec_in_rill_index =
15687 			    recv_ill->ill_phyint->phyint_ifindex;
15688 			if (ii->ipsec_in_decaps) {
15689 				/*
15690 				 * This packet is self-encapsulated multiple
15691 				 * times. We don't want to recurse infinitely.
15692 				 * To keep it simple, drop the packet.
15693 				 */
15694 				BUMP_MIB(&ip_mib, ipInDiscards);
15695 				freemsg(first_mp);
15696 				return;
15697 			}
15698 			ii->ipsec_in_decaps = B_TRUE;
15699 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15700 			return;
15701 		}
15702 		break;
15703 	case IPPROTO_AH:
15704 	case IPPROTO_ESP: {
15705 		/*
15706 		 * Fast path for AH/ESP. If this is the first time
15707 		 * we are sending a datagram to AH/ESP, allocate
15708 		 * a IPSEC_IN message and prepend it. Otherwise,
15709 		 * just fanout.
15710 		 */
15711 
15712 		int ipsec_rc;
15713 		ipsec_in_t *ii;
15714 
15715 		IP_STAT(ipsec_proto_ahesp);
15716 		if (!mctl_present) {
15717 			ASSERT(first_mp == mp);
15718 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15719 				ip1dbg(("ip_proto_input: IPSEC_IN "
15720 				    "allocation failure.\n"));
15721 				freemsg(hada_mp); /* okay ifnull */
15722 				BUMP_MIB(&ip_mib, ipInDiscards);
15723 				freemsg(mp);
15724 				return;
15725 			}
15726 			/*
15727 			 * Store the ill_index so that when we come back
15728 			 * from IPSEC we ride on the same queue.
15729 			 */
15730 			ill = (ill_t *)q->q_ptr;
15731 			ii = (ipsec_in_t *)first_mp->b_rptr;
15732 			ii->ipsec_in_ill_index =
15733 			    ill->ill_phyint->phyint_ifindex;
15734 			ii->ipsec_in_rill_index =
15735 			    recv_ill->ill_phyint->phyint_ifindex;
15736 			first_mp->b_cont = mp;
15737 			/*
15738 			 * Cache hardware acceleration info.
15739 			 */
15740 			if (hada_mp != NULL) {
15741 				IPSECHW_DEBUG(IPSECHW_PKT,
15742 				    ("ip_rput_local: caching data attr.\n"));
15743 				ii->ipsec_in_accelerated = B_TRUE;
15744 				ii->ipsec_in_da = hada_mp;
15745 				hada_mp = NULL;
15746 			}
15747 		} else {
15748 			ii = (ipsec_in_t *)first_mp->b_rptr;
15749 		}
15750 
15751 		if (!ipsec_loaded()) {
15752 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15753 			    ire->ire_zoneid);
15754 			return;
15755 		}
15756 
15757 		/* select inbound SA and have IPsec process the pkt */
15758 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15759 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15760 			if (esph == NULL)
15761 				return;
15762 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15763 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15764 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15765 			    first_mp, esph);
15766 		} else {
15767 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15768 			if (ah == NULL)
15769 				return;
15770 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15771 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15772 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15773 			    first_mp, ah);
15774 		}
15775 
15776 		switch (ipsec_rc) {
15777 		case IPSEC_STATUS_SUCCESS:
15778 			break;
15779 		case IPSEC_STATUS_FAILED:
15780 			BUMP_MIB(&ip_mib, ipInDiscards);
15781 			/* FALLTHRU */
15782 		case IPSEC_STATUS_PENDING:
15783 			return;
15784 		}
15785 		/* we're done with IPsec processing, send it up */
15786 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15787 		return;
15788 	}
15789 	default:
15790 		break;
15791 	}
15792 	/*
15793 	 * Handle protocols with which IP is less intimate.  There
15794 	 * can be more than one stream bound to a particular
15795 	 * protocol.  When this is the case, each one gets a copy
15796 	 * of any incoming packets.
15797 	 */
15798 	ip_fanout_proto(q, first_mp, ill, ipha,
15799 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15800 	    B_TRUE, recv_ill, ire->ire_zoneid);
15801 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15802 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15803 	return;
15804 
15805 drop_pkt:
15806 	freemsg(first_mp);
15807 	if (hada_mp != NULL)
15808 		freeb(hada_mp);
15809 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15810 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15811 #undef	rptr
15812 #undef  iphs
15813 
15814 }
15815 
15816 /*
15817  * Update any source route, record route or timestamp options.
15818  * Check that we are at end of strict source route.
15819  * The options have already been checked for sanity in ip_rput_options().
15820  */
15821 static boolean_t
15822 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15823 {
15824 	ipoptp_t	opts;
15825 	uchar_t		*opt;
15826 	uint8_t		optval;
15827 	uint8_t		optlen;
15828 	ipaddr_t	dst;
15829 	uint32_t	ts;
15830 	ire_t		*dst_ire;
15831 	timestruc_t	now;
15832 
15833 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15834 
15835 	ip2dbg(("ip_rput_local_options\n"));
15836 
15837 	for (optval = ipoptp_first(&opts, ipha);
15838 	    optval != IPOPT_EOL;
15839 	    optval = ipoptp_next(&opts)) {
15840 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15841 		opt = opts.ipoptp_cur;
15842 		optlen = opts.ipoptp_len;
15843 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15844 		    optval, optlen));
15845 		switch (optval) {
15846 			uint32_t off;
15847 		case IPOPT_SSRR:
15848 		case IPOPT_LSRR:
15849 			off = opt[IPOPT_OFFSET];
15850 			off--;
15851 			if (optlen < IP_ADDR_LEN ||
15852 			    off > optlen - IP_ADDR_LEN) {
15853 				/* End of source route */
15854 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15855 				break;
15856 			}
15857 			/*
15858 			 * This will only happen if two consecutive entries
15859 			 * in the source route contains our address or if
15860 			 * it is a packet with a loose source route which
15861 			 * reaches us before consuming the whole source route
15862 			 */
15863 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15864 			if (optval == IPOPT_SSRR) {
15865 				goto bad_src_route;
15866 			}
15867 			/*
15868 			 * Hack: instead of dropping the packet truncate the
15869 			 * source route to what has been used by filling the
15870 			 * rest with IPOPT_NOP.
15871 			 */
15872 			opt[IPOPT_OLEN] = (uint8_t)off;
15873 			while (off < optlen) {
15874 				opt[off++] = IPOPT_NOP;
15875 			}
15876 			break;
15877 		case IPOPT_RR:
15878 			off = opt[IPOPT_OFFSET];
15879 			off--;
15880 			if (optlen < IP_ADDR_LEN ||
15881 			    off > optlen - IP_ADDR_LEN) {
15882 				/* No more room - ignore */
15883 				ip1dbg((
15884 				    "ip_rput_local_options: end of RR\n"));
15885 				break;
15886 			}
15887 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15888 			    IP_ADDR_LEN);
15889 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15890 			break;
15891 		case IPOPT_TS:
15892 			/* Insert timestamp if there is romm */
15893 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15894 			case IPOPT_TS_TSONLY:
15895 				off = IPOPT_TS_TIMELEN;
15896 				break;
15897 			case IPOPT_TS_PRESPEC:
15898 			case IPOPT_TS_PRESPEC_RFC791:
15899 				/* Verify that the address matched */
15900 				off = opt[IPOPT_OFFSET] - 1;
15901 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15902 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15903 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15904 				if (dst_ire == NULL) {
15905 					/* Not for us */
15906 					break;
15907 				}
15908 				ire_refrele(dst_ire);
15909 				/* FALLTHRU */
15910 			case IPOPT_TS_TSANDADDR:
15911 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15912 				break;
15913 			default:
15914 				/*
15915 				 * ip_*put_options should have already
15916 				 * dropped this packet.
15917 				 */
15918 				cmn_err(CE_PANIC, "ip_rput_local_options: "
15919 				    "unknown IT - bug in ip_rput_options?\n");
15920 				return (B_TRUE);	/* Keep "lint" happy */
15921 			}
15922 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15923 				/* Increase overflow counter */
15924 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15925 				opt[IPOPT_POS_OV_FLG] =
15926 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15927 				    (off << 4));
15928 				break;
15929 			}
15930 			off = opt[IPOPT_OFFSET] - 1;
15931 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15932 			case IPOPT_TS_PRESPEC:
15933 			case IPOPT_TS_PRESPEC_RFC791:
15934 			case IPOPT_TS_TSANDADDR:
15935 				bcopy(&ire->ire_src_addr, (char *)opt + off,
15936 				    IP_ADDR_LEN);
15937 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15938 				/* FALLTHRU */
15939 			case IPOPT_TS_TSONLY:
15940 				off = opt[IPOPT_OFFSET] - 1;
15941 				/* Compute # of milliseconds since midnight */
15942 				gethrestime(&now);
15943 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15944 				    now.tv_nsec / (NANOSEC / MILLISEC);
15945 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15946 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15947 				break;
15948 			}
15949 			break;
15950 		}
15951 	}
15952 	return (B_TRUE);
15953 
15954 bad_src_route:
15955 	q = WR(q);
15956 	/* make sure we clear any indication of a hardware checksum */
15957 	DB_CKSUMFLAGS(mp) = 0;
15958 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
15959 	return (B_FALSE);
15960 
15961 }
15962 
15963 /*
15964  * Process IP options in an inbound packet.  If an option affects the
15965  * effective destination address, return the next hop address via dstp.
15966  * Returns -1 if something fails in which case an ICMP error has been sent
15967  * and mp freed.
15968  */
15969 static int
15970 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
15971 {
15972 	ipoptp_t	opts;
15973 	uchar_t		*opt;
15974 	uint8_t		optval;
15975 	uint8_t		optlen;
15976 	ipaddr_t	dst;
15977 	intptr_t	code = 0;
15978 	ire_t		*ire = NULL;
15979 
15980 	ip2dbg(("ip_rput_options\n"));
15981 	dst = ipha->ipha_dst;
15982 	for (optval = ipoptp_first(&opts, ipha);
15983 	    optval != IPOPT_EOL;
15984 	    optval = ipoptp_next(&opts)) {
15985 		opt = opts.ipoptp_cur;
15986 		optlen = opts.ipoptp_len;
15987 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
15988 		    optval, optlen));
15989 		/*
15990 		 * Note: we need to verify the checksum before we
15991 		 * modify anything thus this routine only extracts the next
15992 		 * hop dst from any source route.
15993 		 */
15994 		switch (optval) {
15995 			uint32_t off;
15996 		case IPOPT_SSRR:
15997 		case IPOPT_LSRR:
15998 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15999 			    ALL_ZONES, MATCH_IRE_TYPE);
16000 			if (ire == NULL) {
16001 				if (optval == IPOPT_SSRR) {
16002 					ip1dbg(("ip_rput_options: not next"
16003 					    " strict source route 0x%x\n",
16004 					    ntohl(dst)));
16005 					code = (char *)&ipha->ipha_dst -
16006 					    (char *)ipha;
16007 					goto param_prob; /* RouterReq's */
16008 				}
16009 				ip2dbg(("ip_rput_options: "
16010 				    "not next source route 0x%x\n",
16011 				    ntohl(dst)));
16012 				break;
16013 			}
16014 			ire_refrele(ire);
16015 
16016 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16017 				ip1dbg((
16018 				    "ip_rput_options: bad option offset\n"));
16019 				code = (char *)&opt[IPOPT_OLEN] -
16020 				    (char *)ipha;
16021 				goto param_prob;
16022 			}
16023 			off = opt[IPOPT_OFFSET];
16024 			off--;
16025 		redo_srr:
16026 			if (optlen < IP_ADDR_LEN ||
16027 			    off > optlen - IP_ADDR_LEN) {
16028 				/* End of source route */
16029 				ip1dbg(("ip_rput_options: end of SR\n"));
16030 				break;
16031 			}
16032 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16033 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16034 			    ntohl(dst)));
16035 
16036 			/*
16037 			 * Check if our address is present more than
16038 			 * once as consecutive hops in source route.
16039 			 * XXX verify per-interface ip_forwarding
16040 			 * for source route?
16041 			 */
16042 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16043 			    ALL_ZONES, MATCH_IRE_TYPE);
16044 
16045 			if (ire != NULL) {
16046 				ire_refrele(ire);
16047 				off += IP_ADDR_LEN;
16048 				goto redo_srr;
16049 			}
16050 
16051 			if (dst == htonl(INADDR_LOOPBACK)) {
16052 				ip1dbg(("ip_rput_options: loopback addr in "
16053 				    "source route!\n"));
16054 				goto bad_src_route;
16055 			}
16056 			/*
16057 			 * For strict: verify that dst is directly
16058 			 * reachable.
16059 			 */
16060 			if (optval == IPOPT_SSRR) {
16061 				ire = ire_ftable_lookup(dst, 0, 0,
16062 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16063 				    MATCH_IRE_TYPE);
16064 				if (ire == NULL) {
16065 					ip1dbg(("ip_rput_options: SSRR not "
16066 					    "directly reachable: 0x%x\n",
16067 					    ntohl(dst)));
16068 					goto bad_src_route;
16069 				}
16070 				ire_refrele(ire);
16071 			}
16072 			/*
16073 			 * Defer update of the offset and the record route
16074 			 * until the packet is forwarded.
16075 			 */
16076 			break;
16077 		case IPOPT_RR:
16078 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16079 				ip1dbg((
16080 				    "ip_rput_options: bad option offset\n"));
16081 				code = (char *)&opt[IPOPT_OLEN] -
16082 				    (char *)ipha;
16083 				goto param_prob;
16084 			}
16085 			break;
16086 		case IPOPT_TS:
16087 			/*
16088 			 * Verify that length >= 5 and that there is either
16089 			 * room for another timestamp or that the overflow
16090 			 * counter is not maxed out.
16091 			 */
16092 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16093 			if (optlen < IPOPT_MINLEN_IT) {
16094 				goto param_prob;
16095 			}
16096 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16097 				ip1dbg((
16098 				    "ip_rput_options: bad option offset\n"));
16099 				code = (char *)&opt[IPOPT_OFFSET] -
16100 				    (char *)ipha;
16101 				goto param_prob;
16102 			}
16103 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16104 			case IPOPT_TS_TSONLY:
16105 				off = IPOPT_TS_TIMELEN;
16106 				break;
16107 			case IPOPT_TS_TSANDADDR:
16108 			case IPOPT_TS_PRESPEC:
16109 			case IPOPT_TS_PRESPEC_RFC791:
16110 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16111 				break;
16112 			default:
16113 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16114 				    (char *)ipha;
16115 				goto param_prob;
16116 			}
16117 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16118 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16119 				/*
16120 				 * No room and the overflow counter is 15
16121 				 * already.
16122 				 */
16123 				goto param_prob;
16124 			}
16125 			break;
16126 		}
16127 	}
16128 
16129 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16130 		*dstp = dst;
16131 		return (0);
16132 	}
16133 
16134 	ip1dbg(("ip_rput_options: error processing IP options."));
16135 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16136 
16137 param_prob:
16138 	q = WR(q);
16139 	/* make sure we clear any indication of a hardware checksum */
16140 	DB_CKSUMFLAGS(mp) = 0;
16141 	icmp_param_problem(q, mp, (uint8_t)code);
16142 	return (-1);
16143 
16144 bad_src_route:
16145 	q = WR(q);
16146 	/* make sure we clear any indication of a hardware checksum */
16147 	DB_CKSUMFLAGS(mp) = 0;
16148 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16149 	return (-1);
16150 }
16151 
16152 /*
16153  * IP & ICMP info in >=14 msg's ...
16154  *  - ip fixed part (mib2_ip_t)
16155  *  - icmp fixed part (mib2_icmp_t)
16156  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16157  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16158  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16159  *  - ip multicast membership (ip_member_t)
16160  *  - ip multicast source filtering (ip_grpsrc_t)
16161  *  - igmp fixed part (struct igmpstat)
16162  *  - multicast routing stats (struct mrtstat)
16163  *  - multicast routing vifs (array of struct vifctl)
16164  *  - multicast routing routes (array of struct mfcctl)
16165  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16166  *					One per ill plus one generic
16167  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16168  *					One per ill plus one generic
16169  *  - ipv6RouteEntry			all IPv6 IREs
16170  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16171  *  - ipv6AddrEntry			all IPv6 ipifs
16172  *  - ipv6 multicast membership (ipv6_member_t)
16173  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16174  *
16175  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16176  * already present.
16177  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16178  * already filled in by caller.
16179  * Return value of 0 indicates that no messages were sent and caller
16180  * should free mpctl.
16181  */
16182 int
16183 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16184 {
16185 
16186 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16187 		return (0);
16188 	}
16189 
16190 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16191 		return (1);
16192 	}
16193 
16194 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16195 		return (1);
16196 	}
16197 
16198 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16199 		return (1);
16200 	}
16201 
16202 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16203 		return (1);
16204 	}
16205 
16206 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16207 		return (1);
16208 	}
16209 
16210 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16211 		return (1);
16212 	}
16213 
16214 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16215 		return (1);
16216 	}
16217 
16218 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16219 		return (1);
16220 	}
16221 
16222 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16223 		return (1);
16224 	}
16225 
16226 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16227 		return (1);
16228 	}
16229 
16230 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16231 		return (1);
16232 	}
16233 
16234 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16235 		return (1);
16236 	}
16237 
16238 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16239 		return (1);
16240 	}
16241 
16242 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16243 		return (1);
16244 	}
16245 
16246 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16247 		return (1);
16248 	}
16249 
16250 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16251 		return (1);
16252 	}
16253 
16254 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16255 		return (1);
16256 	}
16257 	freemsg(mpctl);
16258 	return (1);
16259 }
16260 
16261 
16262 /* Get global IPv4 statistics */
16263 static mblk_t *
16264 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16265 {
16266 	struct opthdr		*optp;
16267 	mblk_t			*mp2ctl;
16268 
16269 	/*
16270 	 * make a copy of the original message
16271 	 */
16272 	mp2ctl = copymsg(mpctl);
16273 
16274 	/* fixed length IP structure... */
16275 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16276 	optp->level = MIB2_IP;
16277 	optp->name = 0;
16278 	SET_MIB(ip_mib.ipForwarding,
16279 	    (WE_ARE_FORWARDING ? 1 : 2));
16280 	SET_MIB(ip_mib.ipDefaultTTL,
16281 	    (uint32_t)ip_def_ttl);
16282 	SET_MIB(ip_mib.ipReasmTimeout,
16283 	    ip_g_frag_timeout);
16284 	SET_MIB(ip_mib.ipAddrEntrySize,
16285 	    sizeof (mib2_ipAddrEntry_t));
16286 	SET_MIB(ip_mib.ipRouteEntrySize,
16287 	    sizeof (mib2_ipRouteEntry_t));
16288 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16289 	    sizeof (mib2_ipNetToMediaEntry_t));
16290 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16291 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16292 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16293 	    (int)sizeof (ip_mib))) {
16294 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16295 		    (uint_t)sizeof (ip_mib)));
16296 	}
16297 
16298 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16299 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16300 	    (int)optp->level, (int)optp->name, (int)optp->len));
16301 	qreply(q, mpctl);
16302 	return (mp2ctl);
16303 }
16304 
16305 /* Global IPv4 ICMP statistics */
16306 static mblk_t *
16307 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16308 {
16309 	struct opthdr		*optp;
16310 	mblk_t			*mp2ctl;
16311 
16312 	/*
16313 	 * Make a copy of the original message
16314 	 */
16315 	mp2ctl = copymsg(mpctl);
16316 
16317 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16318 	optp->level = MIB2_ICMP;
16319 	optp->name = 0;
16320 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16321 	    (int)sizeof (icmp_mib))) {
16322 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16323 		    (uint_t)sizeof (icmp_mib)));
16324 	}
16325 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16326 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16327 	    (int)optp->level, (int)optp->name, (int)optp->len));
16328 	qreply(q, mpctl);
16329 	return (mp2ctl);
16330 }
16331 
16332 /* Global IPv4 IGMP statistics */
16333 static mblk_t *
16334 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16335 {
16336 	struct opthdr		*optp;
16337 	mblk_t			*mp2ctl;
16338 
16339 	/*
16340 	 * make a copy of the original message
16341 	 */
16342 	mp2ctl = copymsg(mpctl);
16343 
16344 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16345 	optp->level = EXPER_IGMP;
16346 	optp->name = 0;
16347 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16348 	    (int)sizeof (igmpstat))) {
16349 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16350 		    (uint_t)sizeof (igmpstat)));
16351 	}
16352 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16353 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16354 	    (int)optp->level, (int)optp->name, (int)optp->len));
16355 	qreply(q, mpctl);
16356 	return (mp2ctl);
16357 }
16358 
16359 /* Global IPv4 Multicast Routing statistics */
16360 static mblk_t *
16361 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16362 {
16363 	struct opthdr		*optp;
16364 	mblk_t			*mp2ctl;
16365 
16366 	/*
16367 	 * make a copy of the original message
16368 	 */
16369 	mp2ctl = copymsg(mpctl);
16370 
16371 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16372 	optp->level = EXPER_DVMRP;
16373 	optp->name = 0;
16374 	if (!ip_mroute_stats(mpctl->b_cont)) {
16375 		ip0dbg(("ip_mroute_stats: failed\n"));
16376 	}
16377 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16378 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16379 	    (int)optp->level, (int)optp->name, (int)optp->len));
16380 	qreply(q, mpctl);
16381 	return (mp2ctl);
16382 }
16383 
16384 /* IPv4 address information */
16385 static mblk_t *
16386 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16387 {
16388 	struct opthdr		*optp;
16389 	mblk_t			*mp2ctl;
16390 	mblk_t			*mp_tail = NULL;
16391 	ill_t			*ill;
16392 	ipif_t			*ipif;
16393 	uint_t			bitval;
16394 	mib2_ipAddrEntry_t	mae;
16395 	zoneid_t		zoneid;
16396 	ill_walk_context_t ctx;
16397 
16398 	/*
16399 	 * make a copy of the original message
16400 	 */
16401 	mp2ctl = copymsg(mpctl);
16402 
16403 	/* ipAddrEntryTable */
16404 
16405 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16406 	optp->level = MIB2_IP;
16407 	optp->name = MIB2_IP_ADDR;
16408 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16409 
16410 	rw_enter(&ill_g_lock, RW_READER);
16411 	ill = ILL_START_WALK_V4(&ctx);
16412 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16413 		for (ipif = ill->ill_ipif; ipif != NULL;
16414 		    ipif = ipif->ipif_next) {
16415 			if (ipif->ipif_zoneid != zoneid)
16416 				continue;
16417 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16418 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16419 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16420 
16421 			(void) ipif_get_name(ipif,
16422 			    mae.ipAdEntIfIndex.o_bytes,
16423 			    OCTET_LENGTH);
16424 			mae.ipAdEntIfIndex.o_length =
16425 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16426 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16427 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16428 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16429 			mae.ipAdEntInfo.ae_subnet_len =
16430 			    ip_mask_to_plen(ipif->ipif_net_mask);
16431 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16432 			for (bitval = 1;
16433 			    bitval &&
16434 			    !(bitval & ipif->ipif_brd_addr);
16435 			    bitval <<= 1)
16436 				noop;
16437 			mae.ipAdEntBcastAddr = bitval;
16438 			mae.ipAdEntReasmMaxSize = 65535;
16439 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16440 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16441 			mae.ipAdEntInfo.ae_broadcast_addr =
16442 			    ipif->ipif_brd_addr;
16443 			mae.ipAdEntInfo.ae_pp_dst_addr =
16444 			    ipif->ipif_pp_dst_addr;
16445 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16446 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16447 
16448 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16449 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16450 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16451 				    "allocate %u bytes\n",
16452 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16453 			}
16454 		}
16455 	}
16456 	rw_exit(&ill_g_lock);
16457 
16458 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16459 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16460 	    (int)optp->level, (int)optp->name, (int)optp->len));
16461 	qreply(q, mpctl);
16462 	return (mp2ctl);
16463 }
16464 
16465 /* IPv6 address information */
16466 static mblk_t *
16467 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16468 {
16469 	struct opthdr		*optp;
16470 	mblk_t			*mp2ctl;
16471 	mblk_t			*mp_tail = NULL;
16472 	ill_t			*ill;
16473 	ipif_t			*ipif;
16474 	mib2_ipv6AddrEntry_t	mae6;
16475 	zoneid_t		zoneid;
16476 	ill_walk_context_t	ctx;
16477 
16478 	/*
16479 	 * make a copy of the original message
16480 	 */
16481 	mp2ctl = copymsg(mpctl);
16482 
16483 	/* ipv6AddrEntryTable */
16484 
16485 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16486 	optp->level = MIB2_IP6;
16487 	optp->name = MIB2_IP6_ADDR;
16488 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16489 
16490 	rw_enter(&ill_g_lock, RW_READER);
16491 	ill = ILL_START_WALK_V6(&ctx);
16492 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16493 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16494 			if (ipif->ipif_zoneid != zoneid)
16495 				continue;
16496 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16497 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16498 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16499 
16500 			(void) ipif_get_name(ipif,
16501 			    mae6.ipv6AddrIfIndex.o_bytes,
16502 			    OCTET_LENGTH);
16503 			mae6.ipv6AddrIfIndex.o_length =
16504 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16505 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16506 			mae6.ipv6AddrPfxLength =
16507 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16508 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16509 			mae6.ipv6AddrInfo.ae_subnet_len =
16510 			    mae6.ipv6AddrPfxLength;
16511 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16512 
16513 			/* Type: stateless(1), stateful(2), unknown(3) */
16514 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16515 				mae6.ipv6AddrType = 1;
16516 			else
16517 				mae6.ipv6AddrType = 2;
16518 			/* Anycast: true(1), false(2) */
16519 			if (ipif->ipif_flags & IPIF_ANYCAST)
16520 				mae6.ipv6AddrAnycastFlag = 1;
16521 			else
16522 				mae6.ipv6AddrAnycastFlag = 2;
16523 
16524 			/*
16525 			 * Address status: preferred(1), deprecated(2),
16526 			 * invalid(3), inaccessible(4), unknown(5)
16527 			 */
16528 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16529 				mae6.ipv6AddrStatus = 3;
16530 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16531 				mae6.ipv6AddrStatus = 2;
16532 			else
16533 				mae6.ipv6AddrStatus = 1;
16534 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16535 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16536 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16537 						ipif->ipif_v6pp_dst_addr;
16538 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16539 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16540 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16541 				(char *)&mae6,
16542 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16543 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16544 				    "allocate %u bytes\n",
16545 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16546 			}
16547 		}
16548 	}
16549 	rw_exit(&ill_g_lock);
16550 
16551 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16552 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16553 	    (int)optp->level, (int)optp->name, (int)optp->len));
16554 	qreply(q, mpctl);
16555 	return (mp2ctl);
16556 }
16557 
16558 /* IPv4 multicast group membership. */
16559 static mblk_t *
16560 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16561 {
16562 	struct opthdr		*optp;
16563 	mblk_t			*mp2ctl;
16564 	ill_t			*ill;
16565 	ipif_t			*ipif;
16566 	ilm_t			*ilm;
16567 	ip_member_t		ipm;
16568 	mblk_t			*mp_tail = NULL;
16569 	ill_walk_context_t	ctx;
16570 	zoneid_t		zoneid;
16571 
16572 	/*
16573 	 * make a copy of the original message
16574 	 */
16575 	mp2ctl = copymsg(mpctl);
16576 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16577 
16578 	/* ipGroupMember table */
16579 	optp = (struct opthdr *)&mpctl->b_rptr[
16580 	    sizeof (struct T_optmgmt_ack)];
16581 	optp->level = MIB2_IP;
16582 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16583 
16584 	rw_enter(&ill_g_lock, RW_READER);
16585 	ill = ILL_START_WALK_V4(&ctx);
16586 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16587 		ILM_WALKER_HOLD(ill);
16588 		for (ipif = ill->ill_ipif; ipif != NULL;
16589 		    ipif = ipif->ipif_next) {
16590 			if (ipif->ipif_zoneid != zoneid)
16591 				continue;	/* not this zone */
16592 			(void) ipif_get_name(ipif,
16593 			    ipm.ipGroupMemberIfIndex.o_bytes,
16594 			    OCTET_LENGTH);
16595 			ipm.ipGroupMemberIfIndex.o_length =
16596 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16597 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16598 				ASSERT(ilm->ilm_ipif != NULL);
16599 				ASSERT(ilm->ilm_ill == NULL);
16600 				if (ilm->ilm_ipif != ipif)
16601 					continue;
16602 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16603 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16604 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16605 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16606 				    (char *)&ipm, (int)sizeof (ipm))) {
16607 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16608 					    "failed to allocate %u bytes\n",
16609 						(uint_t)sizeof (ipm)));
16610 				}
16611 			}
16612 		}
16613 		ILM_WALKER_RELE(ill);
16614 	}
16615 	rw_exit(&ill_g_lock);
16616 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16617 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16618 	    (int)optp->level, (int)optp->name, (int)optp->len));
16619 	qreply(q, mpctl);
16620 	return (mp2ctl);
16621 }
16622 
16623 /* IPv6 multicast group membership. */
16624 static mblk_t *
16625 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16626 {
16627 	struct opthdr		*optp;
16628 	mblk_t			*mp2ctl;
16629 	ill_t			*ill;
16630 	ilm_t			*ilm;
16631 	ipv6_member_t		ipm6;
16632 	mblk_t			*mp_tail = NULL;
16633 	ill_walk_context_t	ctx;
16634 	zoneid_t		zoneid;
16635 
16636 	/*
16637 	 * make a copy of the original message
16638 	 */
16639 	mp2ctl = copymsg(mpctl);
16640 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16641 
16642 	/* ip6GroupMember table */
16643 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16644 	optp->level = MIB2_IP6;
16645 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16646 
16647 	rw_enter(&ill_g_lock, RW_READER);
16648 	ill = ILL_START_WALK_V6(&ctx);
16649 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16650 		ILM_WALKER_HOLD(ill);
16651 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16652 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16653 			ASSERT(ilm->ilm_ipif == NULL);
16654 			ASSERT(ilm->ilm_ill != NULL);
16655 			if (ilm->ilm_zoneid != zoneid)
16656 				continue;	/* not this zone */
16657 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16658 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16659 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16660 			if (!snmp_append_data2(mpctl->b_cont,
16661 			    &mp_tail,
16662 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16663 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16664 				    "failed to allocate %u bytes\n",
16665 				    (uint_t)sizeof (ipm6)));
16666 			}
16667 		}
16668 		ILM_WALKER_RELE(ill);
16669 	}
16670 	rw_exit(&ill_g_lock);
16671 
16672 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16673 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16674 	    (int)optp->level, (int)optp->name, (int)optp->len));
16675 	qreply(q, mpctl);
16676 	return (mp2ctl);
16677 }
16678 
16679 /* IP multicast filtered sources */
16680 static mblk_t *
16681 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16682 {
16683 	struct opthdr		*optp;
16684 	mblk_t			*mp2ctl;
16685 	ill_t			*ill;
16686 	ipif_t			*ipif;
16687 	ilm_t			*ilm;
16688 	ip_grpsrc_t		ips;
16689 	mblk_t			*mp_tail = NULL;
16690 	ill_walk_context_t	ctx;
16691 	zoneid_t		zoneid;
16692 	int			i;
16693 	slist_t			*sl;
16694 
16695 	/*
16696 	 * make a copy of the original message
16697 	 */
16698 	mp2ctl = copymsg(mpctl);
16699 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16700 
16701 	/* ipGroupSource table */
16702 	optp = (struct opthdr *)&mpctl->b_rptr[
16703 	    sizeof (struct T_optmgmt_ack)];
16704 	optp->level = MIB2_IP;
16705 	optp->name = EXPER_IP_GROUP_SOURCES;
16706 
16707 	rw_enter(&ill_g_lock, RW_READER);
16708 	ill = ILL_START_WALK_V4(&ctx);
16709 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16710 		ILM_WALKER_HOLD(ill);
16711 		for (ipif = ill->ill_ipif; ipif != NULL;
16712 		    ipif = ipif->ipif_next) {
16713 			if (ipif->ipif_zoneid != zoneid)
16714 				continue;	/* not this zone */
16715 			(void) ipif_get_name(ipif,
16716 			    ips.ipGroupSourceIfIndex.o_bytes,
16717 			    OCTET_LENGTH);
16718 			ips.ipGroupSourceIfIndex.o_length =
16719 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16720 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16721 				ASSERT(ilm->ilm_ipif != NULL);
16722 				ASSERT(ilm->ilm_ill == NULL);
16723 				sl = ilm->ilm_filter;
16724 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16725 					continue;
16726 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16727 				for (i = 0; i < sl->sl_numsrc; i++) {
16728 					if (!IN6_IS_ADDR_V4MAPPED(
16729 					    &sl->sl_addr[i]))
16730 						continue;
16731 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16732 					    ips.ipGroupSourceAddress);
16733 					if (snmp_append_data2(mpctl->b_cont,
16734 					    &mp_tail, (char *)&ips,
16735 					    (int)sizeof (ips)) == 0) {
16736 						ip1dbg(("ip_snmp_get_mib2_"
16737 						    "ip_group_src: failed to "
16738 						    "allocate %u bytes\n",
16739 						    (uint_t)sizeof (ips)));
16740 					}
16741 				}
16742 			}
16743 		}
16744 		ILM_WALKER_RELE(ill);
16745 	}
16746 	rw_exit(&ill_g_lock);
16747 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16748 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16749 	    (int)optp->level, (int)optp->name, (int)optp->len));
16750 	qreply(q, mpctl);
16751 	return (mp2ctl);
16752 }
16753 
16754 /* IPv6 multicast filtered sources. */
16755 static mblk_t *
16756 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16757 {
16758 	struct opthdr		*optp;
16759 	mblk_t			*mp2ctl;
16760 	ill_t			*ill;
16761 	ilm_t			*ilm;
16762 	ipv6_grpsrc_t		ips6;
16763 	mblk_t			*mp_tail = NULL;
16764 	ill_walk_context_t	ctx;
16765 	zoneid_t		zoneid;
16766 	int			i;
16767 	slist_t			*sl;
16768 
16769 	/*
16770 	 * make a copy of the original message
16771 	 */
16772 	mp2ctl = copymsg(mpctl);
16773 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16774 
16775 	/* ip6GroupMember table */
16776 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16777 	optp->level = MIB2_IP6;
16778 	optp->name = EXPER_IP6_GROUP_SOURCES;
16779 
16780 	rw_enter(&ill_g_lock, RW_READER);
16781 	ill = ILL_START_WALK_V6(&ctx);
16782 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16783 		ILM_WALKER_HOLD(ill);
16784 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16785 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16786 			ASSERT(ilm->ilm_ipif == NULL);
16787 			ASSERT(ilm->ilm_ill != NULL);
16788 			sl = ilm->ilm_filter;
16789 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16790 				continue;
16791 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16792 			for (i = 0; i < sl->sl_numsrc; i++) {
16793 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16794 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16795 				    (char *)&ips6, (int)sizeof (ips6))) {
16796 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16797 					    "group_src: failed to allocate "
16798 					    "%u bytes\n",
16799 					    (uint_t)sizeof (ips6)));
16800 				}
16801 			}
16802 		}
16803 		ILM_WALKER_RELE(ill);
16804 	}
16805 	rw_exit(&ill_g_lock);
16806 
16807 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16808 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16809 	    (int)optp->level, (int)optp->name, (int)optp->len));
16810 	qreply(q, mpctl);
16811 	return (mp2ctl);
16812 }
16813 
16814 /* Multicast routing virtual interface table. */
16815 static mblk_t *
16816 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16817 {
16818 	struct opthdr		*optp;
16819 	mblk_t			*mp2ctl;
16820 
16821 	/*
16822 	 * make a copy of the original message
16823 	 */
16824 	mp2ctl = copymsg(mpctl);
16825 
16826 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16827 	optp->level = EXPER_DVMRP;
16828 	optp->name = EXPER_DVMRP_VIF;
16829 	if (!ip_mroute_vif(mpctl->b_cont)) {
16830 		ip0dbg(("ip_mroute_vif: failed\n"));
16831 	}
16832 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16833 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16834 	    (int)optp->level, (int)optp->name, (int)optp->len));
16835 	qreply(q, mpctl);
16836 	return (mp2ctl);
16837 }
16838 
16839 /* Multicast routing table. */
16840 static mblk_t *
16841 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16842 {
16843 	struct opthdr		*optp;
16844 	mblk_t			*mp2ctl;
16845 
16846 	/*
16847 	 * make a copy of the original message
16848 	 */
16849 	mp2ctl = copymsg(mpctl);
16850 
16851 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16852 	optp->level = EXPER_DVMRP;
16853 	optp->name = EXPER_DVMRP_MRT;
16854 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16855 		ip0dbg(("ip_mroute_mrt: failed\n"));
16856 	}
16857 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16858 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16859 	    (int)optp->level, (int)optp->name, (int)optp->len));
16860 	qreply(q, mpctl);
16861 	return (mp2ctl);
16862 }
16863 
16864 /*
16865  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16866  * in one IRE walk.
16867  */
16868 static mblk_t *
16869 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16870 {
16871 	struct opthdr		*optp;
16872 	mblk_t			*mp2ctl;	/* Returned */
16873 	mblk_t			*mp3ctl;	/* nettomedia */
16874 	/*
16875 	 * We need two listptrs, for ipRouteEntryTable and
16876 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16877 	 */
16878 	listptr_t		re_ntme_v4[2];
16879 	zoneid_t		zoneid;
16880 
16881 	/*
16882 	 * make a copy of the original message
16883 	 */
16884 	mp2ctl = copymsg(mpctl);
16885 	mp3ctl = copymsg(mpctl);
16886 	if (mp3ctl == NULL) {
16887 		freemsg(mp2ctl);
16888 		freemsg(mpctl);
16889 		return (NULL);
16890 	}
16891 
16892 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
16893 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
16894 	/*
16895 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16896 	 * proper values when called.
16897 	 */
16898 	re_ntme_v4[0].lp_tail = NULL;
16899 	re_ntme_v4[1].lp_tail = NULL;
16900 
16901 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16902 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
16903 	if (zoneid == GLOBAL_ZONEID) {
16904 		/*
16905 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
16906 		 * the sys_net_config privilege, it can only run in the global
16907 		 * zone, so we don't display these IREs in the other zones.
16908 		 */
16909 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
16910 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
16911 		    NULL);
16912 	}
16913 
16914 	/* ipRouteEntryTable in mpctl */
16915 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16916 	optp->level = MIB2_IP;
16917 	optp->name = MIB2_IP_ROUTE;
16918 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
16919 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16920 	    (int)optp->level, (int)optp->name, (int)optp->len));
16921 	qreply(q, mpctl);
16922 
16923 	/* ipNetToMediaEntryTable in mp3ctl */
16924 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16925 	optp->level = MIB2_IP;
16926 	optp->name = MIB2_IP_MEDIA;
16927 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
16928 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16929 	    (int)optp->level, (int)optp->name, (int)optp->len));
16930 	qreply(q, mp3ctl);
16931 	return (mp2ctl);
16932 }
16933 
16934 /*
16935  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
16936  * in one IRE walk.
16937  */
16938 static mblk_t *
16939 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
16940 {
16941 	struct opthdr		*optp;
16942 	mblk_t			*mp2ctl;	/* Returned */
16943 	mblk_t			*mp3ctl;	/* nettomedia */
16944 	listptr_t		re_ntme_v6;
16945 	zoneid_t		zoneid;
16946 
16947 	/*
16948 	 * make a copy of the original message
16949 	 */
16950 	mp2ctl = copymsg(mpctl);
16951 	mp3ctl = copymsg(mpctl);
16952 	if (mp3ctl == NULL) {
16953 		freemsg(mp2ctl);
16954 		freemsg(mpctl);
16955 		return (NULL);
16956 	}
16957 
16958 	/*
16959 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16960 	 * proper values when called.  ipv6RouteEntryTable in is placed
16961 	 * in mpctl.
16962 	 */
16963 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
16964 	re_ntme_v6.lp_tail = NULL;
16965 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16966 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
16967 
16968 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16969 	optp->level = MIB2_IP6;
16970 	optp->name = MIB2_IP6_ROUTE;
16971 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16972 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16973 	    (int)optp->level, (int)optp->name, (int)optp->len));
16974 	qreply(q, mpctl);
16975 
16976 	/* ipv6NetToMediaEntryTable in mp3ctl */
16977 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
16978 	re_ntme_v6.lp_tail = NULL;
16979 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
16980 
16981 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16982 	optp->level = MIB2_IP6;
16983 	optp->name = MIB2_IP6_MEDIA;
16984 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16985 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16986 	    (int)optp->level, (int)optp->name, (int)optp->len));
16987 	qreply(q, mp3ctl);
16988 	return (mp2ctl);
16989 }
16990 
16991 /*
16992  * ICMPv6 mib: One per ill
16993  */
16994 static mblk_t *
16995 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
16996 {
16997 	struct opthdr		*optp;
16998 	mblk_t			*mp2ctl;
16999 	ill_t			*ill;
17000 	ill_walk_context_t	ctx;
17001 	mblk_t			*mp_tail = NULL;
17002 
17003 	/*
17004 	 * Make a copy of the original message
17005 	 */
17006 	mp2ctl = copymsg(mpctl);
17007 
17008 	/* fixed length IPv6 structure ... */
17009 
17010 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17011 	optp->level = MIB2_IP6;
17012 	optp->name = 0;
17013 	/* Include "unknown interface" ip6_mib */
17014 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17015 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17016 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17017 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17018 	    sizeof (mib2_ipv6IfStatsEntry_t));
17019 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17020 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17021 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17022 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17023 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17024 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17025 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17026 	    (int)sizeof (ip6_mib))) {
17027 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17028 		    (uint_t)sizeof (ip6_mib)));
17029 	}
17030 
17031 	rw_enter(&ill_g_lock, RW_READER);
17032 	ill = ILL_START_WALK_V6(&ctx);
17033 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17034 		ill->ill_ip6_mib->ipv6IfIndex =
17035 		    ill->ill_phyint->phyint_ifindex;
17036 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17037 		    ipv6_forward ? 1 : 2);
17038 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17039 		    ill->ill_max_hops);
17040 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17041 		    sizeof (mib2_ipv6IfStatsEntry_t));
17042 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17043 		    sizeof (mib2_ipv6AddrEntry_t));
17044 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17045 		    sizeof (mib2_ipv6RouteEntry_t));
17046 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17047 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17048 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17049 		    sizeof (ipv6_member_t));
17050 
17051 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17052 		    (char *)ill->ill_ip6_mib,
17053 		    (int)sizeof (*ill->ill_ip6_mib))) {
17054 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17055 				"%u bytes\n",
17056 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17057 		}
17058 	}
17059 	rw_exit(&ill_g_lock);
17060 
17061 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17062 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17063 	    (int)optp->level, (int)optp->name, (int)optp->len));
17064 	qreply(q, mpctl);
17065 	return (mp2ctl);
17066 }
17067 
17068 /*
17069  * ICMPv6 mib: One per ill
17070  */
17071 static mblk_t *
17072 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17073 {
17074 	struct opthdr		*optp;
17075 	mblk_t			*mp2ctl;
17076 	ill_t			*ill;
17077 	ill_walk_context_t	ctx;
17078 	mblk_t			*mp_tail = NULL;
17079 	/*
17080 	 * Make a copy of the original message
17081 	 */
17082 	mp2ctl = copymsg(mpctl);
17083 
17084 	/* fixed length ICMPv6 structure ... */
17085 
17086 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17087 	optp->level = MIB2_ICMP6;
17088 	optp->name = 0;
17089 	/* Include "unknown interface" icmp6_mib */
17090 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17091 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17092 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17093 	    (int)sizeof (icmp6_mib))) {
17094 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17095 		    (uint_t)sizeof (icmp6_mib)));
17096 	}
17097 
17098 	rw_enter(&ill_g_lock, RW_READER);
17099 	ill = ILL_START_WALK_V6(&ctx);
17100 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17101 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17102 		    ill->ill_phyint->phyint_ifindex;
17103 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17104 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17105 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17106 		    (char *)ill->ill_icmp6_mib,
17107 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17108 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17109 			    "%u bytes\n",
17110 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17111 		}
17112 	}
17113 	rw_exit(&ill_g_lock);
17114 
17115 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17116 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17117 	    (int)optp->level, (int)optp->name, (int)optp->len));
17118 	qreply(q, mpctl);
17119 	return (mp2ctl);
17120 }
17121 
17122 /*
17123  * ire_walk routine to create both ipRouteEntryTable and
17124  * ipNetToMediaEntryTable in one IRE walk
17125  */
17126 static void
17127 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17128 {
17129 	ill_t				*ill;
17130 	ipif_t				*ipif;
17131 	mblk_t				*llmp;
17132 	dl_unitdata_req_t		*dlup;
17133 	mib2_ipRouteEntry_t		re;
17134 	mib2_ipNetToMediaEntry_t	ntme;
17135 	ipaddr_t			gw_addr;
17136 
17137 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17138 
17139 	/*
17140 	 * Return all IRE types for route table... let caller pick and choose
17141 	 */
17142 	re.ipRouteDest = ire->ire_addr;
17143 	ipif = ire->ire_ipif;
17144 	re.ipRouteIfIndex.o_length = 0;
17145 	if (ire->ire_type == IRE_CACHE) {
17146 		ill = (ill_t *)ire->ire_stq->q_ptr;
17147 		re.ipRouteIfIndex.o_length =
17148 		    ill->ill_name_length == 0 ? 0 :
17149 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17150 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17151 		    re.ipRouteIfIndex.o_length);
17152 	} else if (ipif != NULL) {
17153 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17154 		    OCTET_LENGTH);
17155 		re.ipRouteIfIndex.o_length =
17156 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17157 	}
17158 	re.ipRouteMetric1 = -1;
17159 	re.ipRouteMetric2 = -1;
17160 	re.ipRouteMetric3 = -1;
17161 	re.ipRouteMetric4 = -1;
17162 
17163 	gw_addr = ire->ire_gateway_addr;
17164 
17165 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17166 		re.ipRouteNextHop = ire->ire_src_addr;
17167 	else
17168 		re.ipRouteNextHop = gw_addr;
17169 	/* indirect(4), direct(3), or invalid(2) */
17170 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17171 		re.ipRouteType = 2;
17172 	else
17173 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17174 	re.ipRouteProto = -1;
17175 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17176 	re.ipRouteMask = ire->ire_mask;
17177 	re.ipRouteMetric5 = -1;
17178 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17179 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17180 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17181 	llmp = ire->ire_dlureq_mp;
17182 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17183 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17184 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17185 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17186 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17187 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17188 	re.ipRouteInfo.re_in_ill.o_length = 0;
17189 	if (ire->ire_in_ill != NULL) {
17190 		re.ipRouteInfo.re_in_ill.o_length =
17191 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17192 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17193 		bcopy(ire->ire_in_ill->ill_name,
17194 		    re.ipRouteInfo.re_in_ill.o_bytes,
17195 		    re.ipRouteInfo.re_in_ill.o_length);
17196 	}
17197 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17198 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17199 	    (char *)&re, (int)sizeof (re))) {
17200 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17201 		    (uint_t)sizeof (re)));
17202 	}
17203 
17204 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17205 		return;
17206 	/*
17207 	 * only IRE_CACHE entries that are for a directly connected subnet
17208 	 * get appended to net -> phys addr table
17209 	 * (others in arp)
17210 	 */
17211 	ntme.ipNetToMediaIfIndex.o_length = 0;
17212 	ill = ire_to_ill(ire);
17213 	ASSERT(ill != NULL);
17214 	ntme.ipNetToMediaIfIndex.o_length =
17215 	    ill->ill_name_length == 0 ? 0 :
17216 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17217 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17218 		    ntme.ipNetToMediaIfIndex.o_length);
17219 
17220 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17221 	if (llmp) {
17222 		uchar_t *addr;
17223 
17224 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17225 		/* Remove sap from  address */
17226 		if (ill->ill_sap_length < 0)
17227 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17228 		else
17229 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17230 			    ill->ill_sap_length;
17231 
17232 		ntme.ipNetToMediaPhysAddress.o_length =
17233 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17234 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17235 		    ntme.ipNetToMediaPhysAddress.o_length);
17236 	}
17237 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17238 	/* assume dynamic (may be changed in arp) */
17239 	ntme.ipNetToMediaType = 3;
17240 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17241 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17242 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17243 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17244 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17245 	    (char *)&ntme, (int)sizeof (ntme))) {
17246 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17247 		    (uint_t)sizeof (ntme)));
17248 	}
17249 }
17250 
17251 /*
17252  * ire_walk routine to create ipv6RouteEntryTable.
17253  */
17254 static void
17255 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17256 {
17257 	ill_t				*ill;
17258 	ipif_t				*ipif;
17259 	mib2_ipv6RouteEntry_t		re;
17260 	in6_addr_t			gw_addr_v6;
17261 
17262 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17263 
17264 	/*
17265 	 * Return all IRE types for route table... let caller pick and choose
17266 	 */
17267 	re.ipv6RouteDest = ire->ire_addr_v6;
17268 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17269 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17270 	re.ipv6RouteIfIndex.o_length = 0;
17271 	ipif = ire->ire_ipif;
17272 	if (ire->ire_type == IRE_CACHE) {
17273 		ill = (ill_t *)ire->ire_stq->q_ptr;
17274 		re.ipv6RouteIfIndex.o_length =
17275 		    ill->ill_name_length == 0 ? 0 :
17276 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17277 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17278 		    re.ipv6RouteIfIndex.o_length);
17279 	} else if (ipif != NULL) {
17280 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17281 		    OCTET_LENGTH);
17282 		re.ipv6RouteIfIndex.o_length =
17283 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17284 	}
17285 
17286 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17287 
17288 	mutex_enter(&ire->ire_lock);
17289 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17290 	mutex_exit(&ire->ire_lock);
17291 
17292 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17293 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17294 	else
17295 		re.ipv6RouteNextHop = gw_addr_v6;
17296 
17297 	/* remote(4), local(3), or discard(2) */
17298 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17299 		re.ipv6RouteType = 2;
17300 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17301 		re.ipv6RouteType = 3;
17302 	else
17303 		re.ipv6RouteType = 4;
17304 
17305 	re.ipv6RouteProtocol		= -1;
17306 	re.ipv6RoutePolicy		= 0;
17307 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17308 	re.ipv6RouteNextHopRDI		= 0;
17309 	re.ipv6RouteWeight		= 0;
17310 	re.ipv6RouteMetric		= 0;
17311 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17312 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17313 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17314 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17315 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17316 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17317 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17318 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17319 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17320 
17321 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17322 	    (char *)&re, (int)sizeof (re))) {
17323 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17324 		    (uint_t)sizeof (re)));
17325 	}
17326 }
17327 
17328 /*
17329  * ndp_walk routine to create ipv6NetToMediaEntryTable
17330  */
17331 static int
17332 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17333 {
17334 	ill_t				*ill;
17335 	mib2_ipv6NetToMediaEntry_t	ntme;
17336 	dl_unitdata_req_t		*dl;
17337 
17338 	ill = nce->nce_ill;
17339 	ASSERT(ill->ill_isv6);
17340 
17341 	/*
17342 	 * Neighbor cache entry attached to IRE with on-link
17343 	 * destination.
17344 	 */
17345 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17346 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17347 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17348 	    (nce->nce_res_mp != NULL)) {
17349 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17350 		ntme.ipv6NetToMediaPhysAddress.o_length =
17351 		    dl->dl_dest_addr_length;
17352 	} else {
17353 		ntme.ipv6NetToMediaPhysAddress.o_length =
17354 		    ill->ill_phys_addr_length;
17355 	}
17356 	if (nce->nce_res_mp != NULL) {
17357 		bcopy((char *)nce->nce_res_mp->b_rptr +
17358 		    NCE_LL_ADDR_OFFSET(ill),
17359 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17360 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17361 	} else {
17362 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17363 		    ill->ill_phys_addr_length);
17364 	}
17365 	/*
17366 	 * Note: Returns ND_* states. Should be:
17367 	 * reachable(1), stale(2), delay(3), probe(4),
17368 	 * invalid(5), unknown(6)
17369 	 */
17370 	ntme.ipv6NetToMediaState = nce->nce_state;
17371 	ntme.ipv6NetToMediaLastUpdated = 0;
17372 
17373 	/* other(1), dynamic(2), static(3), local(4) */
17374 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17375 		ntme.ipv6NetToMediaType = 4;
17376 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17377 		ntme.ipv6NetToMediaType = 1;
17378 	} else {
17379 		ntme.ipv6NetToMediaType = 2;
17380 	}
17381 
17382 	if (!snmp_append_data2(re_ntme->lp_head,
17383 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17384 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17385 		    (uint_t)sizeof (ntme)));
17386 	}
17387 	return (0);
17388 }
17389 
17390 /*
17391  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17392  */
17393 /* ARGSUSED */
17394 int
17395 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17396 {
17397 	switch (level) {
17398 	case MIB2_IP:
17399 	case MIB2_ICMP:
17400 		switch (name) {
17401 		default:
17402 			break;
17403 		}
17404 		return (1);
17405 	default:
17406 		return (1);
17407 	}
17408 }
17409 
17410 /*
17411  * Called before the options are updated to check if this packet will
17412  * be source routed from here.
17413  * This routine assumes that the options are well formed i.e. that they
17414  * have already been checked.
17415  */
17416 static boolean_t
17417 ip_source_routed(ipha_t *ipha)
17418 {
17419 	ipoptp_t	opts;
17420 	uchar_t		*opt;
17421 	uint8_t		optval;
17422 	uint8_t		optlen;
17423 	ipaddr_t	dst;
17424 	ire_t		*ire;
17425 
17426 	if (IS_SIMPLE_IPH(ipha)) {
17427 		ip2dbg(("not source routed\n"));
17428 		return (B_FALSE);
17429 	}
17430 	dst = ipha->ipha_dst;
17431 	for (optval = ipoptp_first(&opts, ipha);
17432 	    optval != IPOPT_EOL;
17433 	    optval = ipoptp_next(&opts)) {
17434 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17435 		opt = opts.ipoptp_cur;
17436 		optlen = opts.ipoptp_len;
17437 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17438 		    optval, optlen));
17439 		switch (optval) {
17440 			uint32_t off;
17441 		case IPOPT_SSRR:
17442 		case IPOPT_LSRR:
17443 			/*
17444 			 * If dst is one of our addresses and there are some
17445 			 * entries left in the source route return (true).
17446 			 */
17447 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17448 			    ALL_ZONES, MATCH_IRE_TYPE);
17449 			if (ire == NULL) {
17450 				ip2dbg(("ip_source_routed: not next"
17451 				    " source route 0x%x\n",
17452 				    ntohl(dst)));
17453 				return (B_FALSE);
17454 			}
17455 			ire_refrele(ire);
17456 			off = opt[IPOPT_OFFSET];
17457 			off--;
17458 			if (optlen < IP_ADDR_LEN ||
17459 			    off > optlen - IP_ADDR_LEN) {
17460 				/* End of source route */
17461 				ip1dbg(("ip_source_routed: end of SR\n"));
17462 				return (B_FALSE);
17463 			}
17464 			return (B_TRUE);
17465 		}
17466 	}
17467 	ip2dbg(("not source routed\n"));
17468 	return (B_FALSE);
17469 }
17470 
17471 /*
17472  * Check if the packet contains any source route.
17473  */
17474 static boolean_t
17475 ip_source_route_included(ipha_t *ipha)
17476 {
17477 	ipoptp_t	opts;
17478 	uint8_t		optval;
17479 
17480 	if (IS_SIMPLE_IPH(ipha))
17481 		return (B_FALSE);
17482 	for (optval = ipoptp_first(&opts, ipha);
17483 	    optval != IPOPT_EOL;
17484 	    optval = ipoptp_next(&opts)) {
17485 		switch (optval) {
17486 		case IPOPT_SSRR:
17487 		case IPOPT_LSRR:
17488 			return (B_TRUE);
17489 		}
17490 	}
17491 	return (B_FALSE);
17492 }
17493 
17494 /*
17495  * Called when the IRE expiration timer fires.
17496  */
17497 /* ARGSUSED */
17498 void
17499 ip_trash_timer_expire(void *args)
17500 {
17501 	int	flush_flag = 0;
17502 
17503 	/*
17504 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17505 	 * This lock makes sure that a new invocation of this function
17506 	 * that occurs due to an almost immediate timer firing will not
17507 	 * progress beyond this point until the current invocation is done
17508 	 */
17509 	mutex_enter(&ip_trash_timer_lock);
17510 	ip_ire_expire_id = 0;
17511 	mutex_exit(&ip_trash_timer_lock);
17512 
17513 	/* Periodic timer */
17514 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17515 		/*
17516 		 * Remove all IRE_CACHE entries since they might
17517 		 * contain arp information.
17518 		 */
17519 		flush_flag |= FLUSH_ARP_TIME;
17520 		ip_ire_arp_time_elapsed = 0;
17521 		IP_STAT(ip_ire_arp_timer_expired);
17522 	}
17523 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17524 		/* Remove all redirects */
17525 		flush_flag |= FLUSH_REDIRECT_TIME;
17526 		ip_ire_rd_time_elapsed = 0;
17527 		IP_STAT(ip_ire_redirect_timer_expired);
17528 	}
17529 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17530 		/* Increase path mtu */
17531 		flush_flag |= FLUSH_MTU_TIME;
17532 		ip_ire_pmtu_time_elapsed = 0;
17533 		IP_STAT(ip_ire_pmtu_timer_expired);
17534 	}
17535 	if (flush_flag != 0) {
17536 		/* Walk all IPv4 IRE's and update them */
17537 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17538 		    ALL_ZONES);
17539 	}
17540 	if (flush_flag & FLUSH_MTU_TIME) {
17541 		/*
17542 		 * Walk all IPv6 IRE's and update them
17543 		 * Note that ARP and redirect timers are not
17544 		 * needed since NUD handles stale entries.
17545 		 */
17546 		flush_flag = FLUSH_MTU_TIME;
17547 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17548 		    ALL_ZONES);
17549 	}
17550 
17551 	ip_ire_arp_time_elapsed += ip_timer_interval;
17552 	ip_ire_rd_time_elapsed += ip_timer_interval;
17553 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17554 
17555 	/*
17556 	 * Hold the lock to serialize timeout calls and prevent
17557 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17558 	 * for the timer to fire and a new invocation of this function
17559 	 * to start before the return value of timeout has been stored
17560 	 * in ip_ire_expire_id by the current invocation.
17561 	 */
17562 	mutex_enter(&ip_trash_timer_lock);
17563 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17564 	    MSEC_TO_TICK(ip_timer_interval));
17565 	mutex_exit(&ip_trash_timer_lock);
17566 }
17567 
17568 /*
17569  * Called by the memory allocator subsystem directly, when the system
17570  * is running low on memory.
17571  */
17572 /* ARGSUSED */
17573 void
17574 ip_trash_ire_reclaim(void *args)
17575 {
17576 	ire_cache_count_t icc;
17577 	ire_cache_reclaim_t icr;
17578 	ncc_cache_count_t ncc;
17579 	nce_cache_reclaim_t ncr;
17580 	uint_t delete_cnt;
17581 	/*
17582 	 * Memory reclaim call back.
17583 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17584 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17585 	 * entries, determine what fraction to free for
17586 	 * each category of IRE_CACHE entries giving absolute priority
17587 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17588 	 * entry will be freed unless all offlink entries are freed).
17589 	 */
17590 	icc.icc_total = 0;
17591 	icc.icc_unused = 0;
17592 	icc.icc_offlink = 0;
17593 	icc.icc_pmtu = 0;
17594 	icc.icc_onlink = 0;
17595 	ire_walk(ire_cache_count, (char *)&icc);
17596 
17597 	/*
17598 	 * Free NCEs for IPv6 like the onlink ires.
17599 	 */
17600 	ncc.ncc_total = 0;
17601 	ncc.ncc_host = 0;
17602 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17603 
17604 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17605 	    icc.icc_pmtu + icc.icc_onlink);
17606 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17607 	IP_STAT(ip_trash_ire_reclaim_calls);
17608 	if (delete_cnt == 0)
17609 		return;
17610 	IP_STAT(ip_trash_ire_reclaim_success);
17611 	/* Always delete all unused offlink entries */
17612 	icr.icr_unused = 1;
17613 	if (delete_cnt <= icc.icc_unused) {
17614 		/*
17615 		 * Only need to free unused entries.  In other words,
17616 		 * there are enough unused entries to free to meet our
17617 		 * target number of freed ire cache entries.
17618 		 */
17619 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17620 		ncr.ncr_host = 0;
17621 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17622 		/*
17623 		 * Only need to free unused entries, plus a fraction of offlink
17624 		 * entries.  It follows from the first if statement that
17625 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17626 		 */
17627 		delete_cnt -= icc.icc_unused;
17628 		/* Round up # deleted by truncating fraction */
17629 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17630 		icr.icr_pmtu = icr.icr_onlink = 0;
17631 		ncr.ncr_host = 0;
17632 	} else if (delete_cnt <=
17633 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17634 		/*
17635 		 * Free all unused and offlink entries, plus a fraction of
17636 		 * pmtu entries.  It follows from the previous if statement
17637 		 * that icc_pmtu is non-zero, and that
17638 		 * delete_cnt != icc_unused + icc_offlink.
17639 		 */
17640 		icr.icr_offlink = 1;
17641 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17642 		/* Round up # deleted by truncating fraction */
17643 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17644 		icr.icr_onlink = 0;
17645 		ncr.ncr_host = 0;
17646 	} else {
17647 		/*
17648 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17649 		 * of onlink entries.  If we're here, then we know that
17650 		 * icc_onlink is non-zero, and that
17651 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17652 		 */
17653 		icr.icr_offlink = icr.icr_pmtu = 1;
17654 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17655 		    icc.icc_pmtu;
17656 		/* Round up # deleted by truncating fraction */
17657 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17658 		/* Using the same delete fraction as for onlink IREs */
17659 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17660 	}
17661 #ifdef DEBUG
17662 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17663 	    "fractions %d/%d/%d/%d\n",
17664 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17665 	    icc.icc_unused, icc.icc_offlink,
17666 	    icc.icc_pmtu, icc.icc_onlink,
17667 	    icr.icr_unused, icr.icr_offlink,
17668 	    icr.icr_pmtu, icr.icr_onlink));
17669 #endif
17670 	ire_walk(ire_cache_reclaim, (char *)&icr);
17671 	if (ncr.ncr_host != 0)
17672 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17673 		    (uchar_t *)&ncr);
17674 #ifdef DEBUG
17675 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17676 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17677 	ire_walk(ire_cache_count, (char *)&icc);
17678 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17679 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17680 	    icc.icc_pmtu, icc.icc_onlink));
17681 #endif
17682 }
17683 
17684 /*
17685  * ip_unbind is called when a copy of an unbind request is received from the
17686  * upper level protocol.  We remove this conn from any fanout hash list it is
17687  * on, and zero out the bind information.  No reply is expected up above.
17688  */
17689 mblk_t *
17690 ip_unbind(queue_t *q, mblk_t *mp)
17691 {
17692 	conn_t	*connp = Q_TO_CONN(q);
17693 
17694 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17695 
17696 	ipcl_hash_remove(connp);
17697 
17698 	ASSERT(mp->b_cont == NULL);
17699 	/*
17700 	 * Convert mp into a T_OK_ACK
17701 	 */
17702 	mp = mi_tpi_ok_ack_alloc(mp);
17703 
17704 	/*
17705 	 * should not happen in practice... T_OK_ACK is smaller than the
17706 	 * original message.
17707 	 */
17708 	if (mp == NULL)
17709 		return (NULL);
17710 
17711 	/*
17712 	 * Don't bzero the ports if its TCP since TCP still needs the
17713 	 * lport to remove it from its own bind hash. TCP will do the
17714 	 * cleanup.
17715 	 */
17716 	if (!IPCL_IS_TCP(connp))
17717 		bzero(&connp->u_port, sizeof (connp->u_port));
17718 
17719 	return (mp);
17720 }
17721 
17722 /*
17723  * Write side put procedure.  Outbound data, IOCTLs, responses from
17724  * resolvers, etc, come down through here.
17725  */
17726 void
17727 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17728 {
17729 	conn_t		*connp = NULL;
17730 	queue_t		*q = (queue_t *)arg2;
17731 	ipha_t		*ipha;
17732 #define	rptr	((uchar_t *)ipha)
17733 	ire_t		*ire = NULL;
17734 	ire_t		*sctp_ire = NULL;
17735 	uint32_t	v_hlen_tos_len;
17736 	ipaddr_t	dst;
17737 	mblk_t		*first_mp = NULL;
17738 	boolean_t	mctl_present;
17739 	ipsec_out_t	*io;
17740 	int		match_flags;
17741 	ill_t		*attach_ill = NULL;
17742 					/* Bind to IPIF_NOFAILOVER ill etc. */
17743 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17744 	ipif_t		*dst_ipif;
17745 	boolean_t	multirt_need_resolve = B_FALSE;
17746 	mblk_t		*copy_mp = NULL;
17747 	int		err;
17748 	zoneid_t	zoneid;
17749 	boolean_t	need_decref = B_FALSE;
17750 	boolean_t	ignore_dontroute = B_FALSE;
17751 
17752 #ifdef	_BIG_ENDIAN
17753 #define	V_HLEN	(v_hlen_tos_len >> 24)
17754 #else
17755 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17756 #endif
17757 
17758 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17759 	    "ip_wput_start: q %p", q);
17760 
17761 	/*
17762 	 * ip_wput fast path
17763 	 */
17764 
17765 	/* is packet from ARP ? */
17766 	if (q->q_next != NULL)
17767 		goto qnext;
17768 
17769 	connp = (conn_t *)arg;
17770 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17771 
17772 	/* is queue flow controlled? */
17773 	if ((q->q_first != NULL || connp->conn_draining) &&
17774 	    (caller == IP_WPUT)) {
17775 		ASSERT(!need_decref);
17776 		(void) putq(q, mp);
17777 		return;
17778 	}
17779 
17780 	/* Multidata transmit? */
17781 	if (DB_TYPE(mp) == M_MULTIDATA) {
17782 		/*
17783 		 * We should never get here, since all Multidata messages
17784 		 * originating from tcp should have been directed over to
17785 		 * tcp_multisend() in the first place.
17786 		 */
17787 		BUMP_MIB(&ip_mib, ipOutDiscards);
17788 		freemsg(mp);
17789 		return;
17790 	} else if (DB_TYPE(mp) != M_DATA)
17791 		goto notdata;
17792 	if (mp->b_flag & MSGHASREF) {
17793 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17794 		mp->b_flag &= ~MSGHASREF;
17795 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17796 		need_decref = B_TRUE;
17797 	}
17798 	ipha = (ipha_t *)mp->b_rptr;
17799 
17800 	/* is IP header non-aligned or mblk smaller than basic IP header */
17801 #ifndef SAFETY_BEFORE_SPEED
17802 	if (!OK_32PTR(rptr) ||
17803 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17804 		goto hdrtoosmall;
17805 #endif
17806 
17807 	/*
17808 	 * If there is a policy, try to attach an ipsec_out in
17809 	 * the front. At the end, first_mp either points to a
17810 	 * M_DATA message or IPSEC_OUT message linked to a
17811 	 * M_DATA message. We have to do it now as we might
17812 	 * lose the "conn" if we go through ip_newroute.
17813 	 */
17814 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17815 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17816 		    ipha->ipha_protocol)) == NULL)) {
17817 			if (need_decref)
17818 				CONN_DEC_REF(connp);
17819 			return;
17820 		} else {
17821 			ASSERT(mp->b_datap->db_type == M_CTL);
17822 			first_mp = mp;
17823 			mp = mp->b_cont;
17824 			mctl_present = B_TRUE;
17825 		}
17826 	} else {
17827 		first_mp = mp;
17828 		mctl_present = B_FALSE;
17829 	}
17830 
17831 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17832 
17833 	/* is wrong version or IP options present */
17834 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17835 		goto version_hdrlen_check;
17836 	dst = ipha->ipha_dst;
17837 
17838 	if (connp->conn_nofailover_ill != NULL) {
17839 		attach_ill = conn_get_held_ill(connp,
17840 		    &connp->conn_nofailover_ill, &err);
17841 		if (err == ILL_LOOKUP_FAILED) {
17842 			if (need_decref)
17843 				CONN_DEC_REF(connp);
17844 			freemsg(first_mp);
17845 			return;
17846 		}
17847 	}
17848 
17849 	/* is packet multicast? */
17850 	if (CLASSD(dst))
17851 		goto multicast;
17852 
17853 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL)) {
17854 		/*
17855 		 * If the destination is a broadcast or a loopback
17856 		 * address, both SO_DONTROUTE and IP_XMIT_IF go
17857 		 * through the standard path. But in the case of local
17858 		 * destination only SO_DONTROUTE goes through the
17859 		 * standard path not IP_XMIT_IF.
17860 		 */
17861 		ire = ire_cache_lookup(dst, zoneid);
17862 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17863 		    (ire->ire_type != IRE_LOOPBACK))) {
17864 
17865 			if ((connp->conn_dontroute) && (ire != NULL) &&
17866 				(ire->ire_type == IRE_LOCAL))
17867 				goto standard_path;
17868 
17869 			if (ire != NULL) {
17870 				ire_refrele(ire);
17871 				/* No more access to ire */
17872 				ire = NULL;
17873 			}
17874 			/*
17875 			 * bypass routing checks and go directly to
17876 			 * interface.
17877 			 */
17878 			if (connp->conn_dontroute)
17879 				goto dontroute;
17880 
17881 			/*
17882 			 * If IP_XMIT_IF socket option is set,
17883 			 * then we allow unicast and multicast
17884 			 * packets to go through the ill. It is
17885 			 * quite possible that the destination
17886 			 * is not in the ire cache table and we
17887 			 * do not want to go to ip_newroute()
17888 			 * instead we call ip_newroute_ipif.
17889 			 */
17890 			xmit_ill = conn_get_held_ill(connp,
17891 			    &connp->conn_xmit_if_ill, &err);
17892 			if (err == ILL_LOOKUP_FAILED) {
17893 				if (attach_ill != NULL)
17894 					ill_refrele(attach_ill);
17895 				if (need_decref)
17896 					CONN_DEC_REF(connp);
17897 				freemsg(first_mp);
17898 				return;
17899 			}
17900 			goto send_from_ill;
17901 		}
17902 standard_path:
17903 		/* Must be a broadcast, a loopback or a local ire */
17904 		if (ire != NULL) {
17905 			ire_refrele(ire);
17906 			/* No more access to ire */
17907 			ire = NULL;
17908 		}
17909 	}
17910 
17911 	if (attach_ill != NULL)
17912 		goto send_from_ill;
17913 
17914 	/*
17915 	 * We cache IRE_CACHEs to avoid lookups. We don't do
17916 	 * this for the tcp global queue and listen end point
17917 	 * as it does not really have a real destination to
17918 	 * talk to.  This is also true for SCTP.
17919 	 */
17920 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
17921 	    !connp->conn_fully_bound) {
17922 		ire = ire_cache_lookup(dst, zoneid);
17923 		if (ire == NULL)
17924 			goto noirefound;
17925 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17926 		    "ip_wput_end: q %p (%S)", q, "end");
17927 
17928 		/*
17929 		 * Check if the ire has the RTF_MULTIRT flag, inherited
17930 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17931 		 */
17932 		if (ire->ire_flags & RTF_MULTIRT) {
17933 
17934 			/*
17935 			 * Force the TTL of multirouted packets if required.
17936 			 * The TTL of such packets is bounded by the
17937 			 * ip_multirt_ttl ndd variable.
17938 			 */
17939 			if ((ip_multirt_ttl > 0) &&
17940 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
17941 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
17942 				    "(was %d), dst 0x%08x\n",
17943 				    ip_multirt_ttl, ipha->ipha_ttl,
17944 				    ntohl(ire->ire_addr)));
17945 				ipha->ipha_ttl = ip_multirt_ttl;
17946 			}
17947 			/*
17948 			 * We look at this point if there are pending
17949 			 * unresolved routes. ire_multirt_resolvable()
17950 			 * checks in O(n) that all IRE_OFFSUBNET ire
17951 			 * entries for the packet's destination and
17952 			 * flagged RTF_MULTIRT are currently resolved.
17953 			 * If some remain unresolved, we make a copy
17954 			 * of the current message. It will be used
17955 			 * to initiate additional route resolutions.
17956 			 */
17957 			multirt_need_resolve =
17958 			    ire_multirt_need_resolve(ire->ire_addr);
17959 			ip2dbg(("ip_wput[TCP]: ire %p, "
17960 			    "multirt_need_resolve %d, first_mp %p\n",
17961 			    (void *)ire, multirt_need_resolve,
17962 			    (void *)first_mp));
17963 			if (multirt_need_resolve) {
17964 				copy_mp = copymsg(first_mp);
17965 				if (copy_mp != NULL) {
17966 					MULTIRT_DEBUG_TAG(copy_mp);
17967 				}
17968 			}
17969 		}
17970 
17971 		ip_wput_ire(q, first_mp, ire, connp, caller);
17972 
17973 		/*
17974 		 * Try to resolve another multiroute if
17975 		 * ire_multirt_need_resolve() deemed it necessary.
17976 		 */
17977 		if (copy_mp != NULL) {
17978 			ip_newroute(q, copy_mp, dst, NULL, connp);
17979 		}
17980 		if (need_decref)
17981 			CONN_DEC_REF(connp);
17982 		return;
17983 	}
17984 
17985 	/*
17986 	 * Access to conn_ire_cache. (protected by conn_lock)
17987 	 *
17988 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
17989 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
17990 	 * send a packet or two with the IRE_CACHE that is going away.
17991 	 * Access to the ire requires an ire refhold on the ire prior to
17992 	 * its use since an interface unplumb thread may delete the cached
17993 	 * ire and release the refhold at any time.
17994 	 *
17995 	 * Caching an ire in the conn_ire_cache
17996 	 *
17997 	 * o Caching an ire pointer in the conn requires a strict check for
17998 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
17999 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18000 	 * in the conn is done after making sure under the bucket lock that the
18001 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18002 	 * caching an ire after the unplumb thread has cleaned up the conn.
18003 	 * If the conn does not send a packet subsequently the unplumb thread
18004 	 * will be hanging waiting for the ire count to drop to zero.
18005 	 *
18006 	 * o We also need to atomically test for a null conn_ire_cache and
18007 	 * set the conn_ire_cache under the the protection of the conn_lock
18008 	 * to avoid races among concurrent threads trying to simultaneously
18009 	 * cache an ire in the conn_ire_cache.
18010 	 */
18011 	mutex_enter(&connp->conn_lock);
18012 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18013 
18014 	if (ire != NULL && ire->ire_addr == dst &&
18015 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18016 
18017 		IRE_REFHOLD(ire);
18018 		mutex_exit(&connp->conn_lock);
18019 
18020 	} else {
18021 		boolean_t cached = B_FALSE;
18022 		connp->conn_ire_cache = NULL;
18023 		mutex_exit(&connp->conn_lock);
18024 		/* Release the old ire */
18025 		if (ire != NULL && sctp_ire == NULL)
18026 			IRE_REFRELE_NOTR(ire);
18027 
18028 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
18029 		if (ire == NULL)
18030 			goto noirefound;
18031 		IRE_REFHOLD_NOTR(ire);
18032 
18033 		mutex_enter(&connp->conn_lock);
18034 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18035 		    connp->conn_ire_cache == NULL) {
18036 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18037 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18038 				connp->conn_ire_cache = ire;
18039 				cached = B_TRUE;
18040 			}
18041 			rw_exit(&ire->ire_bucket->irb_lock);
18042 		}
18043 		mutex_exit(&connp->conn_lock);
18044 
18045 		/*
18046 		 * We can continue to use the ire but since it was
18047 		 * not cached, we should drop the extra reference.
18048 		 */
18049 		if (!cached)
18050 			IRE_REFRELE_NOTR(ire);
18051 	}
18052 
18053 
18054 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18055 	    "ip_wput_end: q %p (%S)", q, "end");
18056 
18057 	/*
18058 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18059 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18060 	 */
18061 	if (ire->ire_flags & RTF_MULTIRT) {
18062 
18063 		/*
18064 		 * Force the TTL of multirouted packets if required.
18065 		 * The TTL of such packets is bounded by the
18066 		 * ip_multirt_ttl ndd variable.
18067 		 */
18068 		if ((ip_multirt_ttl > 0) &&
18069 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18070 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18071 			    "(was %d), dst 0x%08x\n",
18072 			    ip_multirt_ttl, ipha->ipha_ttl,
18073 			    ntohl(ire->ire_addr)));
18074 			ipha->ipha_ttl = ip_multirt_ttl;
18075 		}
18076 
18077 		/*
18078 		 * At this point, we check to see if there are any pending
18079 		 * unresolved routes. ire_multirt_resolvable()
18080 		 * checks in O(n) that all IRE_OFFSUBNET ire
18081 		 * entries for the packet's destination and
18082 		 * flagged RTF_MULTIRT are currently resolved.
18083 		 * If some remain unresolved, we make a copy
18084 		 * of the current message. It will be used
18085 		 * to initiate additional route resolutions.
18086 		 */
18087 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18088 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18089 		    "multirt_need_resolve %d, first_mp %p\n",
18090 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18091 		if (multirt_need_resolve) {
18092 			copy_mp = copymsg(first_mp);
18093 			if (copy_mp != NULL) {
18094 				MULTIRT_DEBUG_TAG(copy_mp);
18095 			}
18096 		}
18097 	}
18098 
18099 	ip_wput_ire(q, first_mp, ire, connp, caller);
18100 
18101 	/*
18102 	 * Try to resolve another multiroute if
18103 	 * ire_multirt_resolvable() deemed it necessary
18104 	 */
18105 	if (copy_mp != NULL) {
18106 		ip_newroute(q, copy_mp, dst, NULL, connp);
18107 	}
18108 	if (need_decref)
18109 		CONN_DEC_REF(connp);
18110 	return;
18111 
18112 qnext:
18113 	/*
18114 	 * Upper Level Protocols pass down complete IP datagrams
18115 	 * as M_DATA messages.	Everything else is a sideshow.
18116 	 *
18117 	 * 1) We could be re-entering ip_wput because of ip_neworute
18118 	 *    in which case we could have a IPSEC_OUT message. We
18119 	 *    need to pass through ip_wput like other datagrams and
18120 	 *    hence cannot branch to ip_wput_nondata.
18121 	 *
18122 	 * 2) ARP, AH, ESP, and other clients who are on the module
18123 	 *    instance of IP stream, give us something to deal with.
18124 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18125 	 *
18126 	 * 3) ICMP replies also could come here.
18127 	 */
18128 	if (DB_TYPE(mp) != M_DATA) {
18129 	    notdata:
18130 		if (DB_TYPE(mp) == M_CTL) {
18131 			/*
18132 			 * M_CTL messages are used by ARP, AH and ESP to
18133 			 * communicate with IP. We deal with IPSEC_IN and
18134 			 * IPSEC_OUT here. ip_wput_nondata handles other
18135 			 * cases.
18136 			 */
18137 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18138 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18139 				first_mp = mp->b_cont;
18140 				first_mp->b_flag &= ~MSGHASREF;
18141 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18142 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18143 				CONN_DEC_REF(connp);
18144 				connp = NULL;
18145 			}
18146 			if (ii->ipsec_info_type == IPSEC_IN) {
18147 				/*
18148 				 * Either this message goes back to
18149 				 * IPSEC for further processing or to
18150 				 * ULP after policy checks.
18151 				 */
18152 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18153 				return;
18154 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18155 				io = (ipsec_out_t *)ii;
18156 				if (io->ipsec_out_proc_begin) {
18157 					/*
18158 					 * IPSEC processing has already started.
18159 					 * Complete it.
18160 					 * IPQoS notes: We don't care what is
18161 					 * in ipsec_out_ill_index since this
18162 					 * won't be processed for IPQoS policies
18163 					 * in ipsec_out_process.
18164 					 */
18165 					ipsec_out_process(q, mp, NULL,
18166 					    io->ipsec_out_ill_index);
18167 					return;
18168 				} else {
18169 					connp = (q->q_next != NULL) ?
18170 					    NULL : Q_TO_CONN(q);
18171 					first_mp = mp;
18172 					mp = mp->b_cont;
18173 					mctl_present = B_TRUE;
18174 				}
18175 				zoneid = io->ipsec_out_zoneid;
18176 				ASSERT(zoneid != ALL_ZONES);
18177 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18178 				/*
18179 				 * It's an IPsec control message requesting
18180 				 * an SADB update to be sent to the IPsec
18181 				 * hardware acceleration capable ills.
18182 				 */
18183 				ipsec_ctl_t *ipsec_ctl =
18184 				    (ipsec_ctl_t *)mp->b_rptr;
18185 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18186 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18187 				mblk_t *cmp = mp->b_cont;
18188 
18189 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18190 				ASSERT(cmp != NULL);
18191 
18192 				freeb(mp);
18193 				ill_ipsec_capab_send_all(satype, cmp, sa);
18194 				return;
18195 			} else {
18196 				/*
18197 				 * This must be ARP.
18198 				 */
18199 				ip_wput_nondata(NULL, q, mp, NULL);
18200 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18201 				    "ip_wput_end: q %p (%S)", q, "nondata");
18202 				return;
18203 			}
18204 		} else {
18205 			/*
18206 			 * This must be non-(ARP/AH/ESP) messages.
18207 			 */
18208 			ASSERT(!need_decref);
18209 			ip_wput_nondata(NULL, q, mp, NULL);
18210 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18211 			    "ip_wput_end: q %p (%S)", q, "nondata");
18212 			return;
18213 		}
18214 	} else {
18215 		first_mp = mp;
18216 		mctl_present = B_FALSE;
18217 	}
18218 
18219 	ASSERT(first_mp != NULL);
18220 	/*
18221 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18222 	 * to make sure that this packet goes out on the same interface it
18223 	 * came in. We handle that here.
18224 	 */
18225 	if (mctl_present) {
18226 		uint_t ifindex;
18227 
18228 		io = (ipsec_out_t *)first_mp->b_rptr;
18229 		if (io->ipsec_out_attach_if ||
18230 		    io->ipsec_out_xmit_if) {
18231 			ill_t	*ill;
18232 
18233 			ASSERT(io->ipsec_out_ill_index != 0);
18234 			ifindex = io->ipsec_out_ill_index;
18235 			ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18236 			    NULL, NULL, NULL, NULL);
18237 			/*
18238 			 * ipsec_out_xmit_if bit is used to tell
18239 			 * ip_wput to use the ill to send outgoing data
18240 			 * as we have no conn when data comes from ICMP
18241 			 * error msg routines. Currently this feature is
18242 			 * only used by ip_mrtun_forward routine.
18243 			 */
18244 			if (io->ipsec_out_xmit_if) {
18245 				xmit_ill = ill;
18246 				if (xmit_ill == NULL) {
18247 					ip1dbg(("ip_wput: bad ifindex for"
18248 					    "xmit_ill %d\n", ifindex));
18249 					freemsg(first_mp);
18250 					BUMP_MIB(&ip_mib, ipOutDiscards);
18251 					ASSERT(!need_decref);
18252 					return;
18253 				}
18254 				/* Free up the ipsec_out_t mblk */
18255 				ASSERT(first_mp->b_cont == mp);
18256 				first_mp->b_cont = NULL;
18257 				freeb(first_mp);
18258 				/* Just send the IP header+ICMP+data */
18259 				first_mp = mp;
18260 				ipha = (ipha_t *)mp->b_rptr;
18261 				dst = ipha->ipha_dst;
18262 				goto send_from_ill;
18263 
18264 			} else {
18265 				attach_ill = ill;
18266 			}
18267 
18268 			if (attach_ill == NULL) {
18269 				ASSERT(xmit_ill == NULL);
18270 				ip1dbg(("ip_wput : bad ifindex for "
18271 				    "(BIND TO IPIF_NOFAILOVER) %d\n", ifindex));
18272 				freemsg(first_mp);
18273 				BUMP_MIB(&ip_mib, ipOutDiscards);
18274 				ASSERT(!need_decref);
18275 				return;
18276 			}
18277 		}
18278 	}
18279 
18280 	ASSERT(xmit_ill == NULL);
18281 
18282 	/* We have a complete IP datagram heading outbound. */
18283 	ipha = (ipha_t *)mp->b_rptr;
18284 
18285 #ifndef SPEED_BEFORE_SAFETY
18286 	/*
18287 	 * Make sure we have a full-word aligned message and that at least
18288 	 * a simple IP header is accessible in the first message.  If not,
18289 	 * try a pullup.
18290 	 */
18291 	if (!OK_32PTR(rptr) ||
18292 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18293 	    hdrtoosmall:
18294 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18295 			BUMP_MIB(&ip_mib, ipOutDiscards);
18296 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18297 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18298 			if (first_mp == NULL)
18299 				first_mp = mp;
18300 			goto drop_pkt;
18301 		}
18302 		ipha = (ipha_t *)mp->b_rptr;
18303 		if (first_mp == NULL) {
18304 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18305 			/*
18306 			 * If we got here because of "goto hdrtoosmall"
18307 			 * We need to attach a IPSEC_OUT.
18308 			 */
18309 			if (connp->conn_out_enforce_policy) {
18310 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18311 				    NULL, ipha->ipha_protocol)) == NULL)) {
18312 					if (need_decref)
18313 						CONN_DEC_REF(connp);
18314 					return;
18315 				} else {
18316 					ASSERT(mp->b_datap->db_type == M_CTL);
18317 					first_mp = mp;
18318 					mp = mp->b_cont;
18319 					mctl_present = B_TRUE;
18320 				}
18321 			} else {
18322 				first_mp = mp;
18323 				mctl_present = B_FALSE;
18324 			}
18325 		}
18326 	}
18327 #endif
18328 
18329 	/* Most of the code below is written for speed, not readability */
18330 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18331 
18332 	/*
18333 	 * If ip_newroute() fails, we're going to need a full
18334 	 * header for the icmp wraparound.
18335 	 */
18336 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18337 		uint_t	v_hlen;
18338 	    version_hdrlen_check:
18339 		ASSERT(first_mp != NULL);
18340 		v_hlen = V_HLEN;
18341 		/*
18342 		 * siphon off IPv6 packets coming down from transport
18343 		 * layer modules here.
18344 		 * Note: high-order bit carries NUD reachability confirmation
18345 		 */
18346 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18347 			/*
18348 			 * XXX implement a IPv4 and IPv6 packet counter per
18349 			 * conn and switch when ratio exceeds e.g. 10:1
18350 			 */
18351 #ifdef notyet
18352 			if (q->q_next == NULL) /* Avoid ill queue */
18353 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18354 #endif
18355 			BUMP_MIB(&ip_mib, ipOutIPv6);
18356 			ASSERT(xmit_ill == NULL);
18357 			if (attach_ill != NULL)
18358 				ill_refrele(attach_ill);
18359 			if (need_decref)
18360 				mp->b_flag |= MSGHASREF;
18361 			(void) ip_output_v6(connp, first_mp, q, caller);
18362 			return;
18363 		}
18364 
18365 		if ((v_hlen >> 4) != IP_VERSION) {
18366 			BUMP_MIB(&ip_mib, ipOutDiscards);
18367 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18368 			    "ip_wput_end: q %p (%S)", q, "badvers");
18369 			goto drop_pkt;
18370 		}
18371 		/*
18372 		 * Is the header length at least 20 bytes?
18373 		 *
18374 		 * Are there enough bytes accessible in the header?  If
18375 		 * not, try a pullup.
18376 		 */
18377 		v_hlen &= 0xF;
18378 		v_hlen <<= 2;
18379 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18380 			BUMP_MIB(&ip_mib, ipOutDiscards);
18381 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18382 			    "ip_wput_end: q %p (%S)", q, "badlen");
18383 			goto drop_pkt;
18384 		}
18385 		if (v_hlen > (mp->b_wptr - rptr)) {
18386 			if (!pullupmsg(mp, v_hlen)) {
18387 				BUMP_MIB(&ip_mib, ipOutDiscards);
18388 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18389 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18390 				goto drop_pkt;
18391 			}
18392 			ipha = (ipha_t *)mp->b_rptr;
18393 		}
18394 		/*
18395 		 * Move first entry from any source route into ipha_dst and
18396 		 * verify the options
18397 		 */
18398 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18399 			ASSERT(xmit_ill == NULL);
18400 			if (attach_ill != NULL)
18401 				ill_refrele(attach_ill);
18402 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18403 			    "ip_wput_end: q %p (%S)", q, "badopts");
18404 			if (need_decref)
18405 				CONN_DEC_REF(connp);
18406 			return;
18407 		}
18408 	}
18409 	dst = ipha->ipha_dst;
18410 
18411 	/*
18412 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18413 	 * we have to run the packet through ip_newroute which will take
18414 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18415 	 * a resolver, or assigning a default gateway, etc.
18416 	 */
18417 	if (CLASSD(dst)) {
18418 		ipif_t	*ipif;
18419 		uint32_t setsrc = 0;
18420 
18421 	    multicast:
18422 		ASSERT(first_mp != NULL);
18423 		ASSERT(xmit_ill == NULL);
18424 		ip2dbg(("ip_wput: CLASSD\n"));
18425 		if (connp == NULL) {
18426 			/*
18427 			 * Use the first good ipif on the ill.
18428 			 * XXX Should this ever happen? (Appears
18429 			 * to show up with just ppp and no ethernet due
18430 			 * to in.rdisc.)
18431 			 * However, ire_send should be able to
18432 			 * call ip_wput_ire directly.
18433 			 *
18434 			 * XXX Also, this can happen for ICMP and other packets
18435 			 * with multicast source addresses.  Perhaps we should
18436 			 * fix things so that we drop the packet in question,
18437 			 * but for now, just run with it.
18438 			 */
18439 			ill_t *ill = (ill_t *)q->q_ptr;
18440 
18441 			/*
18442 			 * Don't honor attach_if for this case. If ill
18443 			 * is part of the group, ipif could belong to
18444 			 * any ill and we cannot maintain attach_ill
18445 			 * and ipif_ill same anymore and the assert
18446 			 * below would fail.
18447 			 */
18448 			if (mctl_present) {
18449 				io->ipsec_out_ill_index = 0;
18450 				io->ipsec_out_attach_if = B_FALSE;
18451 				ASSERT(attach_ill != NULL);
18452 				ill_refrele(attach_ill);
18453 				attach_ill = NULL;
18454 			}
18455 
18456 			ASSERT(attach_ill == NULL);
18457 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18458 			if (ipif == NULL) {
18459 				if (need_decref)
18460 					CONN_DEC_REF(connp);
18461 				freemsg(first_mp);
18462 				return;
18463 			}
18464 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18465 			    ntohl(dst), ill->ill_name));
18466 		} else {
18467 			/*
18468 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18469 			 * IP_XMIT_IF is honoured.
18470 			 * Block comment above this function explains the
18471 			 * locking mechanism used here
18472 			 */
18473 			xmit_ill = conn_get_held_ill(connp,
18474 			    &connp->conn_xmit_if_ill, &err);
18475 			if (err == ILL_LOOKUP_FAILED) {
18476 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18477 				goto drop_pkt;
18478 			}
18479 			if (xmit_ill == NULL) {
18480 				ipif = conn_get_held_ipif(connp,
18481 				    &connp->conn_multicast_ipif, &err);
18482 				if (err == IPIF_LOOKUP_FAILED) {
18483 					ip1dbg(("ip_wput: No ipif for "
18484 					    "multicast\n"));
18485 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18486 					goto drop_pkt;
18487 				}
18488 			}
18489 			if (xmit_ill != NULL) {
18490 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18491 				if (ipif == NULL) {
18492 					ip1dbg(("ip_wput: No ipif for "
18493 					    "IP_XMIT_IF\n"));
18494 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18495 					goto drop_pkt;
18496 				}
18497 			} else if (ipif == NULL || ipif->ipif_isv6) {
18498 				/*
18499 				 * We must do this ipif determination here
18500 				 * else we could pass through ip_newroute
18501 				 * and come back here without the conn context.
18502 				 *
18503 				 * Note: we do late binding i.e. we bind to
18504 				 * the interface when the first packet is sent.
18505 				 * For performance reasons we do not rebind on
18506 				 * each packet but keep the binding until the
18507 				 * next IP_MULTICAST_IF option.
18508 				 *
18509 				 * conn_multicast_{ipif,ill} are shared between
18510 				 * IPv4 and IPv6 and AF_INET6 sockets can
18511 				 * send both IPv4 and IPv6 packets. Hence
18512 				 * we have to check that "isv6" matches above.
18513 				 */
18514 				if (ipif != NULL)
18515 					ipif_refrele(ipif);
18516 				ipif = ipif_lookup_group(dst, zoneid);
18517 				if (ipif == NULL) {
18518 					ip1dbg(("ip_wput: No ipif for "
18519 					    "multicast\n"));
18520 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18521 					goto drop_pkt;
18522 				}
18523 				err = conn_set_held_ipif(connp,
18524 				    &connp->conn_multicast_ipif, ipif);
18525 				if (err == IPIF_LOOKUP_FAILED) {
18526 					ipif_refrele(ipif);
18527 					ip1dbg(("ip_wput: No ipif for "
18528 					    "multicast\n"));
18529 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18530 					goto drop_pkt;
18531 				}
18532 			}
18533 		}
18534 		ASSERT(!ipif->ipif_isv6);
18535 		/*
18536 		 * As we may lose the conn by the time we reach ip_wput_ire,
18537 		 * we copy conn_multicast_loop and conn_dontroute on to an
18538 		 * ipsec_out. In case if this datagram goes out secure,
18539 		 * we need the ill_index also. Copy that also into the
18540 		 * ipsec_out.
18541 		 */
18542 		if (mctl_present) {
18543 			io = (ipsec_out_t *)first_mp->b_rptr;
18544 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18545 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18546 		} else {
18547 			ASSERT(mp == first_mp);
18548 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18549 			    BPRI_HI)) == NULL) {
18550 				ipif_refrele(ipif);
18551 				first_mp = mp;
18552 				goto drop_pkt;
18553 			}
18554 			first_mp->b_datap->db_type = M_CTL;
18555 			first_mp->b_wptr += sizeof (ipsec_info_t);
18556 			/* ipsec_out_secure is B_FALSE now */
18557 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18558 			io = (ipsec_out_t *)first_mp->b_rptr;
18559 			io->ipsec_out_type = IPSEC_OUT;
18560 			io->ipsec_out_len = sizeof (ipsec_out_t);
18561 			io->ipsec_out_use_global_policy = B_TRUE;
18562 			first_mp->b_cont = mp;
18563 			mctl_present = B_TRUE;
18564 		}
18565 		if (attach_ill != NULL) {
18566 			ASSERT(attach_ill == ipif->ipif_ill);
18567 			match_flags = MATCH_IRE_ILL;
18568 
18569 			/*
18570 			 * Check if we need an ire that will not be
18571 			 * looked up by anybody else i.e. HIDDEN.
18572 			 */
18573 			if (ill_is_probeonly(attach_ill)) {
18574 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18575 			}
18576 			io->ipsec_out_ill_index =
18577 			    attach_ill->ill_phyint->phyint_ifindex;
18578 			io->ipsec_out_attach_if = B_TRUE;
18579 		} else {
18580 			match_flags = MATCH_IRE_ILL_GROUP;
18581 			io->ipsec_out_ill_index =
18582 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18583 		}
18584 		if (connp != NULL) {
18585 			io->ipsec_out_multicast_loop =
18586 			    connp->conn_multicast_loop;
18587 			io->ipsec_out_dontroute = connp->conn_dontroute;
18588 			io->ipsec_out_zoneid = connp->conn_zoneid;
18589 		}
18590 		/*
18591 		 * If the application uses IP_MULTICAST_IF with
18592 		 * different logical addresses of the same ILL, we
18593 		 * need to make sure that the soruce address of
18594 		 * the packet matches the logical IP address used
18595 		 * in the option. We do it by initializing ipha_src
18596 		 * here. This should keep IPSEC also happy as
18597 		 * when we return from IPSEC processing, we don't
18598 		 * have to worry about getting the right address on
18599 		 * the packet. Thus it is sufficient to look for
18600 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18601 		 * MATCH_IRE_IPIF.
18602 		 *
18603 		 * NOTE : We need to do it for non-secure case also as
18604 		 * this might go out secure if there is a global policy
18605 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18606 		 * address, the source should be initialized already and
18607 		 * hence we won't be initializing here.
18608 		 *
18609 		 * As we do not have the ire yet, it is possible that
18610 		 * we set the source address here and then later discover
18611 		 * that the ire implies the source address to be assigned
18612 		 * through the RTF_SETSRC flag.
18613 		 * In that case, the setsrc variable will remind us
18614 		 * that overwritting the source address by the one
18615 		 * of the RTF_SETSRC-flagged ire is allowed.
18616 		 */
18617 		if (ipha->ipha_src == INADDR_ANY &&
18618 		    (connp == NULL || !connp->conn_unspec_src)) {
18619 			ipha->ipha_src = ipif->ipif_src_addr;
18620 			setsrc = RTF_SETSRC;
18621 		}
18622 		/*
18623 		 * Find an IRE which matches the destination and the outgoing
18624 		 * queue (i.e. the outgoing interface.)
18625 		 * For loopback use a unicast IP address for
18626 		 * the ire lookup.
18627 		 */
18628 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18629 		    PHYI_LOOPBACK) {
18630 			dst = ipif->ipif_lcl_addr;
18631 		}
18632 		/*
18633 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18634 		 * We don't need to lookup ire in ctable as the packet
18635 		 * needs to be sent to the destination through the specified
18636 		 * ill irrespective of ires in the cache table.
18637 		 */
18638 		ire = NULL;
18639 		if (xmit_ill == NULL) {
18640 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18641 			    zoneid, match_flags);
18642 		}
18643 
18644 		/*
18645 		 * refrele attach_ill as its not needed anymore.
18646 		 */
18647 		if (attach_ill != NULL) {
18648 			ill_refrele(attach_ill);
18649 			attach_ill = NULL;
18650 		}
18651 
18652 		if (ire == NULL) {
18653 			/*
18654 			 * Multicast loopback and multicast forwarding is
18655 			 * done in ip_wput_ire.
18656 			 *
18657 			 * Mark this packet to make it be delivered to
18658 			 * ip_wput_ire after the new ire has been
18659 			 * created.
18660 			 *
18661 			 * The call to ip_newroute_ipif takes into account
18662 			 * the setsrc reminder. In any case, we take care
18663 			 * of the RTF_MULTIRT flag.
18664 			 */
18665 			mp->b_prev = mp->b_next = NULL;
18666 			if (xmit_ill == NULL ||
18667 			    xmit_ill->ill_ipif_up_count > 0) {
18668 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18669 				    setsrc | RTF_MULTIRT);
18670 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18671 				    "ip_wput_end: q %p (%S)", q, "noire");
18672 			} else {
18673 				freemsg(first_mp);
18674 			}
18675 			ipif_refrele(ipif);
18676 			if (xmit_ill != NULL)
18677 				ill_refrele(xmit_ill);
18678 			if (need_decref)
18679 				CONN_DEC_REF(connp);
18680 			return;
18681 		}
18682 
18683 		ipif_refrele(ipif);
18684 		ipif = NULL;
18685 		ASSERT(xmit_ill == NULL);
18686 
18687 		/*
18688 		 * Honor the RTF_SETSRC flag for multicast packets,
18689 		 * if allowed by the setsrc reminder.
18690 		 */
18691 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18692 			ipha->ipha_src = ire->ire_src_addr;
18693 		}
18694 
18695 		/*
18696 		 * Unconditionally force the TTL to 1 for
18697 		 * multirouted multicast packets:
18698 		 * multirouted multicast should not cross
18699 		 * multicast routers.
18700 		 */
18701 		if (ire->ire_flags & RTF_MULTIRT) {
18702 			if (ipha->ipha_ttl > 1) {
18703 				ip2dbg(("ip_wput: forcing multicast "
18704 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18705 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18706 				ipha->ipha_ttl = 1;
18707 			}
18708 		}
18709 	} else {
18710 		ire = ire_cache_lookup(dst, zoneid);
18711 		if ((ire != NULL) && (ire->ire_type &
18712 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18713 			ignore_dontroute = B_TRUE;
18714 		}
18715 		if (ire != NULL) {
18716 			ire_refrele(ire);
18717 			ire = NULL;
18718 		}
18719 		/*
18720 		 * Guard against coming in from arp in which case conn is NULL.
18721 		 * Also guard against non M_DATA with dontroute set but
18722 		 * destined to local, loopback or broadcast addresses.
18723 		 */
18724 		if (connp != NULL && connp->conn_dontroute &&
18725 		    !ignore_dontroute) {
18726 dontroute:
18727 			/*
18728 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18729 			 * routing protocols from seeing false direct
18730 			 * connectivity.
18731 			 */
18732 			ipha->ipha_ttl = 1;
18733 			/*
18734 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18735 			 * along with SO_DONTROUTE, higher precedence is
18736 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18737 			 */
18738 			if (connp->conn_xmit_if_ill == NULL) {
18739 				/* If suitable ipif not found, drop packet */
18740 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18741 				if (dst_ipif == NULL) {
18742 					ip1dbg(("ip_wput: no route for "
18743 					    "dst using SO_DONTROUTE\n"));
18744 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18745 					mp->b_prev = mp->b_next = NULL;
18746 					if (first_mp == NULL)
18747 						first_mp = mp;
18748 					goto drop_pkt;
18749 				} else {
18750 					/*
18751 					 * If suitable ipif has been found, set
18752 					 * xmit_ill to the corresponding
18753 					 * ipif_ill because we'll be following
18754 					 * the IP_XMIT_IF logic.
18755 					 */
18756 					ASSERT(xmit_ill == NULL);
18757 					xmit_ill = dst_ipif->ipif_ill;
18758 					mutex_enter(&xmit_ill->ill_lock);
18759 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18760 						mutex_exit(&xmit_ill->ill_lock);
18761 						xmit_ill = NULL;
18762 						ipif_refrele(dst_ipif);
18763 						ip1dbg(("ip_wput: no route for"
18764 						    " dst using"
18765 						    " SO_DONTROUTE\n"));
18766 						BUMP_MIB(&ip_mib,
18767 						    ipOutNoRoutes);
18768 						mp->b_prev = mp->b_next = NULL;
18769 						if (first_mp == NULL)
18770 							first_mp = mp;
18771 						goto drop_pkt;
18772 					}
18773 					ill_refhold_locked(xmit_ill);
18774 					mutex_exit(&xmit_ill->ill_lock);
18775 					ipif_refrele(dst_ipif);
18776 				}
18777 			}
18778 
18779 		}
18780 		/*
18781 		 * If we are bound to IPIF_NOFAILOVER address, look for
18782 		 * an IRE_CACHE matching the ill.
18783 		 */
18784 send_from_ill:
18785 		if (attach_ill != NULL) {
18786 			ipif_t	*attach_ipif;
18787 
18788 			match_flags = MATCH_IRE_ILL;
18789 
18790 			/*
18791 			 * Check if we need an ire that will not be
18792 			 * looked up by anybody else i.e. HIDDEN.
18793 			 */
18794 			if (ill_is_probeonly(attach_ill)) {
18795 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18796 			}
18797 
18798 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18799 			if (attach_ipif == NULL) {
18800 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18801 				goto drop_pkt;
18802 			}
18803 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18804 			    zoneid, match_flags);
18805 			ipif_refrele(attach_ipif);
18806 		} else if (xmit_ill != NULL || (connp != NULL &&
18807 			    connp->conn_xmit_if_ill != NULL)) {
18808 			/*
18809 			 * Mark this packet as originated locally
18810 			 */
18811 			mp->b_prev = mp->b_next = NULL;
18812 			/*
18813 			 * xmit_ill could be NULL if SO_DONTROUTE
18814 			 * is also set.
18815 			 */
18816 			if (xmit_ill == NULL) {
18817 				xmit_ill = conn_get_held_ill(connp,
18818 				    &connp->conn_xmit_if_ill, &err);
18819 				if (err == ILL_LOOKUP_FAILED) {
18820 					if (need_decref)
18821 						CONN_DEC_REF(connp);
18822 					freemsg(first_mp);
18823 					return;
18824 				}
18825 				if (xmit_ill == NULL) {
18826 					if (connp->conn_dontroute)
18827 						goto dontroute;
18828 					goto send_from_ill;
18829 				}
18830 			}
18831 			/*
18832 			 * could be SO_DONTROUTE case also.
18833 			 * check at least one interface is UP as
18834 			 * spcified by this ILL, and then call
18835 			 * ip_newroute_ipif()
18836 			 */
18837 			if (xmit_ill->ill_ipif_up_count > 0) {
18838 				ipif_t *ipif;
18839 
18840 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18841 				if (ipif != NULL) {
18842 					ip_newroute_ipif(q, first_mp, ipif,
18843 					    dst, connp, 0);
18844 					ipif_refrele(ipif);
18845 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18846 				}
18847 			} else {
18848 				freemsg(first_mp);
18849 			}
18850 			ill_refrele(xmit_ill);
18851 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18852 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18853 			if (need_decref)
18854 				CONN_DEC_REF(connp);
18855 			return;
18856 		} else {
18857 			ire = ire_cache_lookup(dst, zoneid);
18858 		}
18859 		if (!ire) {
18860 			/*
18861 			 * Make sure we don't load spread if this
18862 			 * is IPIF_NOFAILOVER case.
18863 			 */
18864 			if (attach_ill != NULL) {
18865 				if (mctl_present) {
18866 					io = (ipsec_out_t *)first_mp->b_rptr;
18867 					ASSERT(first_mp->b_datap->db_type ==
18868 					    M_CTL);
18869 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
18870 				} else {
18871 					ASSERT(mp == first_mp);
18872 					first_mp = allocb(
18873 					    sizeof (ipsec_info_t), BPRI_HI);
18874 					if (first_mp == NULL) {
18875 						first_mp = mp;
18876 						goto drop_pkt;
18877 					}
18878 					first_mp->b_datap->db_type = M_CTL;
18879 					first_mp->b_wptr +=
18880 					    sizeof (ipsec_info_t);
18881 					/* ipsec_out_secure is B_FALSE now */
18882 					bzero(first_mp->b_rptr,
18883 					    sizeof (ipsec_info_t));
18884 					io = (ipsec_out_t *)first_mp->b_rptr;
18885 					io->ipsec_out_type = IPSEC_OUT;
18886 					io->ipsec_out_len =
18887 					    sizeof (ipsec_out_t);
18888 					io->ipsec_out_use_global_policy =
18889 					    B_TRUE;
18890 					first_mp->b_cont = mp;
18891 					mctl_present = B_TRUE;
18892 				}
18893 				io->ipsec_out_ill_index = attach_ill->
18894 				    ill_phyint->phyint_ifindex;
18895 				io->ipsec_out_attach_if = B_TRUE;
18896 			}
18897 noirefound:
18898 			/*
18899 			 * Mark this packet as having originated on
18900 			 * this machine.  This will be noted in
18901 			 * ire_add_then_send, which needs to know
18902 			 * whether to run it back through ip_wput or
18903 			 * ip_rput following successful resolution.
18904 			 */
18905 			mp->b_prev = NULL;
18906 			mp->b_next = NULL;
18907 			ip_newroute(q, first_mp, dst, NULL, connp);
18908 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18909 			    "ip_wput_end: q %p (%S)", q, "newroute");
18910 			if (attach_ill != NULL)
18911 				ill_refrele(attach_ill);
18912 			if (xmit_ill != NULL)
18913 				ill_refrele(xmit_ill);
18914 			if (need_decref)
18915 				CONN_DEC_REF(connp);
18916 			return;
18917 		}
18918 	}
18919 
18920 	/* We now know where we are going with it. */
18921 
18922 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18923 	    "ip_wput_end: q %p (%S)", q, "end");
18924 
18925 	/*
18926 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18927 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
18928 	 */
18929 	if (ire->ire_flags & RTF_MULTIRT) {
18930 		/*
18931 		 * Force the TTL of multirouted packets if required.
18932 		 * The TTL of such packets is bounded by the
18933 		 * ip_multirt_ttl ndd variable.
18934 		 */
18935 		if ((ip_multirt_ttl > 0) &&
18936 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18937 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18938 			    "(was %d), dst 0x%08x\n",
18939 			    ip_multirt_ttl, ipha->ipha_ttl,
18940 			    ntohl(ire->ire_addr)));
18941 			ipha->ipha_ttl = ip_multirt_ttl;
18942 		}
18943 		/*
18944 		 * At this point, we check to see if there are any pending
18945 		 * unresolved routes. ire_multirt_resolvable()
18946 		 * checks in O(n) that all IRE_OFFSUBNET ire
18947 		 * entries for the packet's destination and
18948 		 * flagged RTF_MULTIRT are currently resolved.
18949 		 * If some remain unresolved, we make a copy
18950 		 * of the current message. It will be used
18951 		 * to initiate additional route resolutions.
18952 		 */
18953 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18954 		ip2dbg(("ip_wput[noirefound]: ire %p, "
18955 		    "multirt_need_resolve %d, first_mp %p\n",
18956 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18957 		if (multirt_need_resolve) {
18958 			copy_mp = copymsg(first_mp);
18959 			if (copy_mp != NULL) {
18960 				MULTIRT_DEBUG_TAG(copy_mp);
18961 			}
18962 		}
18963 	}
18964 
18965 	ip_wput_ire(q, first_mp, ire, connp, caller);
18966 	/*
18967 	 * Try to resolve another multiroute if
18968 	 * ire_multirt_resolvable() deemed it necessary.
18969 	 * At this point, we need to distinguish
18970 	 * multicasts from other packets. For multicasts,
18971 	 * we call ip_newroute_ipif() and request that both
18972 	 * multirouting and setsrc flags are checked.
18973 	 */
18974 	if (copy_mp != NULL) {
18975 		if (CLASSD(dst)) {
18976 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
18977 			if (ipif) {
18978 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
18979 				    RTF_SETSRC | RTF_MULTIRT);
18980 				ipif_refrele(ipif);
18981 			} else {
18982 				MULTIRT_DEBUG_UNTAG(copy_mp);
18983 				freemsg(copy_mp);
18984 				copy_mp = NULL;
18985 			}
18986 		} else {
18987 			ip_newroute(q, copy_mp, dst, NULL, connp);
18988 		}
18989 	}
18990 	if (attach_ill != NULL)
18991 		ill_refrele(attach_ill);
18992 	if (xmit_ill != NULL)
18993 		ill_refrele(xmit_ill);
18994 	if (need_decref)
18995 		CONN_DEC_REF(connp);
18996 	return;
18997 
18998 drop_pkt:
18999 	ip1dbg(("ip_wput: dropped packet\n"));
19000 	if (ire != NULL)
19001 		ire_refrele(ire);
19002 	if (need_decref)
19003 		CONN_DEC_REF(connp);
19004 	freemsg(first_mp);
19005 	if (attach_ill != NULL)
19006 		ill_refrele(attach_ill);
19007 	if (xmit_ill != NULL)
19008 		ill_refrele(xmit_ill);
19009 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19010 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19011 }
19012 
19013 void
19014 ip_wput(queue_t *q, mblk_t *mp)
19015 {
19016 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19017 }
19018 
19019 /*
19020  *
19021  * The following rules must be observed when accessing any ipif or ill
19022  * that has been cached in the conn. Typically conn_nofailover_ill,
19023  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19024  *
19025  * Access: The ipif or ill pointed to from the conn can be accessed under
19026  * the protection of the conn_lock or after it has been refheld under the
19027  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19028  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19029  * The reason for this is that a concurrent unplumb could actually be
19030  * cleaning up these cached pointers by walking the conns and might have
19031  * finished cleaning up the conn in question. The macros check that an
19032  * unplumb has not yet started on the ipif or ill.
19033  *
19034  * Caching: An ipif or ill pointer may be cached in the conn only after
19035  * making sure that an unplumb has not started. So the caching is done
19036  * while holding both the conn_lock and the ill_lock and after using the
19037  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
19038  * flag before starting the cleanup of conns.
19039  *
19040  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
19041  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
19042  * or a reference to the ipif or a reference to an ire that references the
19043  * ipif. An ipif does not change its ill except for failover/failback. Since
19044  * failover/failback happens only after bringing down the ipif and making sure
19045  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
19046  * the above holds.
19047  */
19048 ipif_t *
19049 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
19050 {
19051 	ipif_t	*ipif;
19052 	ill_t	*ill;
19053 
19054 	*err = 0;
19055 	rw_enter(&ill_g_lock, RW_READER);
19056 	mutex_enter(&connp->conn_lock);
19057 	ipif = *ipifp;
19058 	if (ipif != NULL) {
19059 		ill = ipif->ipif_ill;
19060 		mutex_enter(&ill->ill_lock);
19061 		if (IPIF_CAN_LOOKUP(ipif)) {
19062 			ipif_refhold_locked(ipif);
19063 			mutex_exit(&ill->ill_lock);
19064 			mutex_exit(&connp->conn_lock);
19065 			rw_exit(&ill_g_lock);
19066 			return (ipif);
19067 		} else {
19068 			*err = IPIF_LOOKUP_FAILED;
19069 		}
19070 		mutex_exit(&ill->ill_lock);
19071 	}
19072 	mutex_exit(&connp->conn_lock);
19073 	rw_exit(&ill_g_lock);
19074 	return (NULL);
19075 }
19076 
19077 ill_t *
19078 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
19079 {
19080 	ill_t	*ill;
19081 
19082 	*err = 0;
19083 	mutex_enter(&connp->conn_lock);
19084 	ill = *illp;
19085 	if (ill != NULL) {
19086 		mutex_enter(&ill->ill_lock);
19087 		if (ILL_CAN_LOOKUP(ill)) {
19088 			ill_refhold_locked(ill);
19089 			mutex_exit(&ill->ill_lock);
19090 			mutex_exit(&connp->conn_lock);
19091 			return (ill);
19092 		} else {
19093 			*err = ILL_LOOKUP_FAILED;
19094 		}
19095 		mutex_exit(&ill->ill_lock);
19096 	}
19097 	mutex_exit(&connp->conn_lock);
19098 	return (NULL);
19099 }
19100 
19101 static int
19102 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
19103 {
19104 	ill_t	*ill;
19105 
19106 	ill = ipif->ipif_ill;
19107 	mutex_enter(&connp->conn_lock);
19108 	mutex_enter(&ill->ill_lock);
19109 	if (IPIF_CAN_LOOKUP(ipif)) {
19110 		*ipifp = ipif;
19111 		mutex_exit(&ill->ill_lock);
19112 		mutex_exit(&connp->conn_lock);
19113 		return (0);
19114 	}
19115 	mutex_exit(&ill->ill_lock);
19116 	mutex_exit(&connp->conn_lock);
19117 	return (IPIF_LOOKUP_FAILED);
19118 }
19119 
19120 /*
19121  * This is called if the outbound datagram needs fragmentation.
19122  *
19123  * NOTE : This function does not ire_refrele the ire argument passed in.
19124  */
19125 static void
19126 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19127 {
19128 	ipha_t		*ipha;
19129 	mblk_t		*mp;
19130 	uint32_t	v_hlen_tos_len;
19131 	uint32_t	max_frag;
19132 	uint32_t	frag_flag;
19133 	boolean_t	dont_use;
19134 
19135 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19136 		mp = ipsec_mp->b_cont;
19137 	} else {
19138 		mp = ipsec_mp;
19139 	}
19140 
19141 	ipha = (ipha_t *)mp->b_rptr;
19142 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19143 
19144 #ifdef	_BIG_ENDIAN
19145 #define	V_HLEN	(v_hlen_tos_len >> 24)
19146 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19147 #else
19148 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19149 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19150 #endif
19151 
19152 #ifndef SPEED_BEFORE_SAFETY
19153 	/*
19154 	 * Check that ipha_length is consistent with
19155 	 * the mblk length
19156 	 */
19157 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19158 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19159 		    LENGTH, msgdsize(mp)));
19160 		freemsg(ipsec_mp);
19161 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19162 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19163 		    "packet length mismatch");
19164 		return;
19165 	}
19166 #endif
19167 	/*
19168 	 * Don't use frag_flag if pre-built packet or source
19169 	 * routed or if multicast (since multicast packets do not solicit
19170 	 * ICMP "packet too big" messages). Get the values of
19171 	 * max_frag and frag_flag atomically by acquiring the
19172 	 * ire_lock.
19173 	 */
19174 	mutex_enter(&ire->ire_lock);
19175 	max_frag = ire->ire_max_frag;
19176 	frag_flag = ire->ire_frag_flag;
19177 	mutex_exit(&ire->ire_lock);
19178 
19179 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19180 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19181 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19182 
19183 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19184 	    (dont_use ? 0 : frag_flag));
19185 }
19186 
19187 /*
19188  * Used for deciding the MSS size for the upper layer. Thus
19189  * we need to check the outbound policy values in the conn.
19190  */
19191 int
19192 conn_ipsec_length(conn_t *connp)
19193 {
19194 	ipsec_latch_t *ipl;
19195 
19196 	ipl = connp->conn_latch;
19197 	if (ipl == NULL)
19198 		return (0);
19199 
19200 	if (ipl->ipl_out_policy == NULL)
19201 		return (0);
19202 
19203 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19204 }
19205 
19206 /*
19207  * Returns an estimate of the IPSEC headers size. This is used if
19208  * we don't want to call into IPSEC to get the exact size.
19209  */
19210 int
19211 ipsec_out_extra_length(mblk_t *ipsec_mp)
19212 {
19213 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19214 	ipsec_action_t *a;
19215 
19216 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19217 	if (!io->ipsec_out_secure)
19218 		return (0);
19219 
19220 	a = io->ipsec_out_act;
19221 
19222 	if (a == NULL) {
19223 		ASSERT(io->ipsec_out_policy != NULL);
19224 		a = io->ipsec_out_policy->ipsp_act;
19225 	}
19226 	ASSERT(a != NULL);
19227 
19228 	return (a->ipa_ovhd);
19229 }
19230 
19231 /*
19232  * Returns an estimate of the IPSEC headers size. This is used if
19233  * we don't want to call into IPSEC to get the exact size.
19234  */
19235 int
19236 ipsec_in_extra_length(mblk_t *ipsec_mp)
19237 {
19238 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19239 	ipsec_action_t *a;
19240 
19241 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19242 
19243 	a = ii->ipsec_in_action;
19244 	return (a == NULL ? 0 : a->ipa_ovhd);
19245 }
19246 
19247 /*
19248  * If there are any source route options, return the true final
19249  * destination. Otherwise, return the destination.
19250  */
19251 ipaddr_t
19252 ip_get_dst(ipha_t *ipha)
19253 {
19254 	ipoptp_t	opts;
19255 	uchar_t		*opt;
19256 	uint8_t		optval;
19257 	uint8_t		optlen;
19258 	ipaddr_t	dst;
19259 	uint32_t off;
19260 
19261 	dst = ipha->ipha_dst;
19262 
19263 	if (IS_SIMPLE_IPH(ipha))
19264 		return (dst);
19265 
19266 	for (optval = ipoptp_first(&opts, ipha);
19267 	    optval != IPOPT_EOL;
19268 	    optval = ipoptp_next(&opts)) {
19269 		opt = opts.ipoptp_cur;
19270 		optlen = opts.ipoptp_len;
19271 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19272 		switch (optval) {
19273 		case IPOPT_SSRR:
19274 		case IPOPT_LSRR:
19275 			off = opt[IPOPT_OFFSET];
19276 			/*
19277 			 * If one of the conditions is true, it means
19278 			 * end of options and dst already has the right
19279 			 * value.
19280 			 */
19281 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19282 				off = optlen - IP_ADDR_LEN;
19283 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19284 			}
19285 			return (dst);
19286 		default:
19287 			break;
19288 		}
19289 	}
19290 
19291 	return (dst);
19292 }
19293 
19294 mblk_t *
19295 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19296     conn_t *connp, boolean_t unspec_src)
19297 {
19298 	ipsec_out_t	*io;
19299 	mblk_t		*first_mp;
19300 	boolean_t policy_present;
19301 
19302 	first_mp = mp;
19303 	if (mp->b_datap->db_type == M_CTL) {
19304 		io = (ipsec_out_t *)first_mp->b_rptr;
19305 		/*
19306 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19307 		 *
19308 		 * 1) There is per-socket policy (including cached global
19309 		 *    policy).
19310 		 * 2) There is no per-socket policy, but it is
19311 		 *    a multicast packet that needs to go out
19312 		 *    on a specific interface. This is the case
19313 		 *    where (ip_wput and ip_wput_multicast) attaches
19314 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19315 		 *
19316 		 * In case (2) we check with global policy to
19317 		 * see if there is a match and set the ill_index
19318 		 * appropriately so that we can lookup the ire
19319 		 * properly in ip_wput_ipsec_out.
19320 		 */
19321 
19322 		/*
19323 		 * ipsec_out_use_global_policy is set to B_FALSE
19324 		 * in ipsec_in_to_out(). Refer to that function for
19325 		 * details.
19326 		 */
19327 		if ((io->ipsec_out_latch == NULL) &&
19328 		    (io->ipsec_out_use_global_policy)) {
19329 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19330 			    ire, connp, unspec_src));
19331 		}
19332 		if (!io->ipsec_out_secure) {
19333 			/*
19334 			 * If this is not a secure packet, drop
19335 			 * the IPSEC_OUT mp and treat it as a clear
19336 			 * packet. This happens when we are sending
19337 			 * a ICMP reply back to a clear packet. See
19338 			 * ipsec_in_to_out() for details.
19339 			 */
19340 			mp = first_mp->b_cont;
19341 			freeb(first_mp);
19342 		}
19343 		return (mp);
19344 	}
19345 	/*
19346 	 * See whether we need to attach a global policy here. We
19347 	 * don't depend on the conn (as it could be null) for deciding
19348 	 * what policy this datagram should go through because it
19349 	 * should have happened in ip_wput if there was some
19350 	 * policy. This normally happens for connections which are not
19351 	 * fully bound preventing us from caching policies in
19352 	 * ip_bind. Packets coming from the TCP listener/global queue
19353 	 * - which are non-hard_bound - could also be affected by
19354 	 * applying policy here.
19355 	 *
19356 	 * If this packet is coming from tcp global queue or listener,
19357 	 * we will be applying policy here.  This may not be *right*
19358 	 * if these packets are coming from the detached connection as
19359 	 * it could have gone in clear before. This happens only if a
19360 	 * TCP connection started when there is no policy and somebody
19361 	 * added policy before it became detached. Thus packets of the
19362 	 * detached connection could go out secure and the other end
19363 	 * would drop it because it will be expecting in clear. The
19364 	 * converse is not true i.e if somebody starts a TCP
19365 	 * connection and deletes the policy, all the packets will
19366 	 * still go out with the policy that existed before deleting
19367 	 * because ip_unbind sends up policy information which is used
19368 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19369 	 * TCP to attach a dummy IPSEC_OUT and set
19370 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19371 	 * affect performance for normal cases, we are not doing it.
19372 	 * Thus, set policy before starting any TCP connections.
19373 	 *
19374 	 * NOTE - We might apply policy even for a hard bound connection
19375 	 * - for which we cached policy in ip_bind - if somebody added
19376 	 * global policy after we inherited the policy in ip_bind.
19377 	 * This means that the packets that were going out in clear
19378 	 * previously would start going secure and hence get dropped
19379 	 * on the other side. To fix this, TCP attaches a dummy
19380 	 * ipsec_out and make sure that we don't apply global policy.
19381 	 */
19382 	if (ipha != NULL)
19383 		policy_present = ipsec_outbound_v4_policy_present;
19384 	else
19385 		policy_present = ipsec_outbound_v6_policy_present;
19386 	if (!policy_present)
19387 		return (mp);
19388 
19389 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19390 }
19391 
19392 ire_t *
19393 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19394 {
19395 	ipaddr_t addr;
19396 	ire_t *save_ire;
19397 	irb_t *irb;
19398 	ill_group_t *illgrp;
19399 	int	err;
19400 
19401 	save_ire = ire;
19402 	addr = ire->ire_addr;
19403 
19404 	ASSERT(ire->ire_type == IRE_BROADCAST);
19405 
19406 	illgrp = connp->conn_outgoing_ill->ill_group;
19407 	if (illgrp == NULL) {
19408 		*conn_outgoing_ill = conn_get_held_ill(connp,
19409 		    &connp->conn_outgoing_ill, &err);
19410 		if (err == ILL_LOOKUP_FAILED) {
19411 			ire_refrele(save_ire);
19412 			return (NULL);
19413 		}
19414 		return (save_ire);
19415 	}
19416 	/*
19417 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19418 	 * If it is part of the group, we need to send on the ire
19419 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19420 	 * to this group. This is okay as IP_BOUND_IF really means
19421 	 * any ill in the group. We depend on the fact that the
19422 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19423 	 * if such an ire exists. This is possible only if you have
19424 	 * at least one ill in the group that has not failed.
19425 	 *
19426 	 * First get to the ire that matches the address and group.
19427 	 *
19428 	 * We don't look for an ire with a matching zoneid because a given zone
19429 	 * won't always have broadcast ires on all ills in the group.
19430 	 */
19431 	irb = ire->ire_bucket;
19432 	rw_enter(&irb->irb_lock, RW_READER);
19433 	if (ire->ire_marks & IRE_MARK_NORECV) {
19434 		/*
19435 		 * If the current zone only has an ire broadcast for this
19436 		 * address marked NORECV, the ire we want is ahead in the
19437 		 * bucket, so we look it up deliberately ignoring the zoneid.
19438 		 */
19439 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19440 			if (ire->ire_addr != addr)
19441 				continue;
19442 			/* skip over deleted ires */
19443 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19444 				continue;
19445 		}
19446 	}
19447 	while (ire != NULL) {
19448 		/*
19449 		 * If a new interface is coming up, we could end up
19450 		 * seeing the loopback ire and the non-loopback ire
19451 		 * may not have been added yet. So check for ire_stq
19452 		 */
19453 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19454 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19455 			break;
19456 		}
19457 		ire = ire->ire_next;
19458 	}
19459 	if (ire != NULL && ire->ire_addr == addr &&
19460 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19461 		IRE_REFHOLD(ire);
19462 		rw_exit(&irb->irb_lock);
19463 		ire_refrele(save_ire);
19464 		*conn_outgoing_ill = ire_to_ill(ire);
19465 		/*
19466 		 * Refhold the ill to make the conn_outgoing_ill
19467 		 * independent of the ire. ip_wput_ire goes in a loop
19468 		 * and may refrele the ire. Since we have an ire at this
19469 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19470 		 */
19471 		ill_refhold(*conn_outgoing_ill);
19472 		return (ire);
19473 	}
19474 	rw_exit(&irb->irb_lock);
19475 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19476 	/*
19477 	 * If we can't find a suitable ire, return the original ire.
19478 	 */
19479 	return (save_ire);
19480 }
19481 
19482 /*
19483  * This function does the ire_refrele of the ire passed in as the
19484  * argument. As this function looks up more ires i.e broadcast ires,
19485  * it needs to REFRELE them. Currently, for simplicity we don't
19486  * differentiate the one passed in and looked up here. We always
19487  * REFRELE.
19488  * IPQoS Notes:
19489  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19490  * IPSec packets are done in ipsec_out_process.
19491  *
19492  */
19493 void
19494 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19495 {
19496 	ipha_t		*ipha;
19497 #define	rptr	((uchar_t *)ipha)
19498 	mblk_t		*mp1;
19499 	queue_t		*stq;
19500 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19501 	uint32_t	v_hlen_tos_len;
19502 	uint32_t	ttl_protocol;
19503 	ipaddr_t	src;
19504 	ipaddr_t	dst;
19505 	uint32_t	cksum;
19506 	ipaddr_t	orig_src;
19507 	ire_t		*ire1;
19508 	mblk_t		*next_mp;
19509 	uint_t		hlen;
19510 	uint16_t	*up;
19511 	uint32_t	max_frag = ire->ire_max_frag;
19512 	ill_t		*ill = ire_to_ill(ire);
19513 	int		clusterwide;
19514 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19515 	int		ipsec_len;
19516 	mblk_t		*first_mp;
19517 	ipsec_out_t	*io;
19518 	boolean_t	conn_dontroute;		/* conn value for multicast */
19519 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19520 	boolean_t	multicast_forward;	/* Should we forward ? */
19521 	boolean_t	unspec_src;
19522 	ill_t		*conn_outgoing_ill = NULL;
19523 	ill_t		*ire_ill;
19524 	ill_t		*ire1_ill;
19525 	uint32_t 	ill_index = 0;
19526 	boolean_t	multirt_send = B_FALSE;
19527 	int		err;
19528 	zoneid_t	zoneid;
19529 
19530 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19531 	    "ip_wput_ire_start: q %p", q);
19532 
19533 	multicast_forward = B_FALSE;
19534 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19535 
19536 	if (ire->ire_flags & RTF_MULTIRT) {
19537 		/*
19538 		 * Multirouting case. The bucket where ire is stored
19539 		 * probably holds other RTF_MULTIRT flagged ire
19540 		 * to the destination. In this call to ip_wput_ire,
19541 		 * we attempt to send the packet through all
19542 		 * those ires. Thus, we first ensure that ire is the
19543 		 * first RTF_MULTIRT ire in the bucket,
19544 		 * before walking the ire list.
19545 		 */
19546 		ire_t *first_ire;
19547 		irb_t *irb = ire->ire_bucket;
19548 		ASSERT(irb != NULL);
19549 
19550 		/* Make sure we do not omit any multiroute ire. */
19551 		IRB_REFHOLD(irb);
19552 		for (first_ire = irb->irb_ire;
19553 		    first_ire != NULL;
19554 		    first_ire = first_ire->ire_next) {
19555 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19556 			    (first_ire->ire_addr == ire->ire_addr) &&
19557 			    !(first_ire->ire_marks &
19558 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19559 				break;
19560 		}
19561 
19562 		if ((first_ire != NULL) && (first_ire != ire)) {
19563 			IRE_REFHOLD(first_ire);
19564 			ire_refrele(ire);
19565 			ire = first_ire;
19566 			ill = ire_to_ill(ire);
19567 		}
19568 		IRB_REFRELE(irb);
19569 	}
19570 
19571 	/*
19572 	 * conn_outgoing_ill is used only in the broadcast loop.
19573 	 * for performance we don't grab the mutexs in the fastpath
19574 	 */
19575 	if ((connp != NULL) &&
19576 	    (connp->conn_xmit_if_ill == NULL) &&
19577 	    (ire->ire_type == IRE_BROADCAST) &&
19578 	    ((connp->conn_nofailover_ill != NULL) ||
19579 	    (connp->conn_outgoing_ill != NULL))) {
19580 		/*
19581 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19582 		 * option. So, see if this endpoint is bound to a
19583 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19584 		 * that if the interface is failed, we will still send
19585 		 * the packet on the same ill which is what we want.
19586 		 */
19587 		conn_outgoing_ill = conn_get_held_ill(connp,
19588 		    &connp->conn_nofailover_ill, &err);
19589 		if (err == ILL_LOOKUP_FAILED) {
19590 			ire_refrele(ire);
19591 			freemsg(mp);
19592 			return;
19593 		}
19594 		if (conn_outgoing_ill == NULL) {
19595 			/*
19596 			 * Choose a good ill in the group to send the
19597 			 * packets on.
19598 			 */
19599 			ire = conn_set_outgoing_ill(connp, ire,
19600 			    &conn_outgoing_ill);
19601 			if (ire == NULL) {
19602 				freemsg(mp);
19603 				return;
19604 			}
19605 		}
19606 	}
19607 
19608 	if (mp->b_datap->db_type != M_CTL) {
19609 		ipha = (ipha_t *)mp->b_rptr;
19610 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19611 	} else {
19612 		io = (ipsec_out_t *)mp->b_rptr;
19613 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19614 		zoneid = io->ipsec_out_zoneid;
19615 		ASSERT(zoneid != ALL_ZONES);
19616 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19617 		dst = ipha->ipha_dst;
19618 		/*
19619 		 * For the multicast case, ipsec_out carries conn_dontroute and
19620 		 * conn_multicast_loop as conn may not be available here. We
19621 		 * need this for multicast loopback and forwarding which is done
19622 		 * later in the code.
19623 		 */
19624 		if (CLASSD(dst)) {
19625 			conn_dontroute = io->ipsec_out_dontroute;
19626 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19627 			/*
19628 			 * If conn_dontroute is not set or conn_multicast_loop
19629 			 * is set, we need to do forwarding/loopback. For
19630 			 * datagrams from ip_wput_multicast, conn_dontroute is
19631 			 * set to B_TRUE and conn_multicast_loop is set to
19632 			 * B_FALSE so that we neither do forwarding nor
19633 			 * loopback.
19634 			 */
19635 			if (!conn_dontroute || conn_multicast_loop)
19636 				multicast_forward = B_TRUE;
19637 		}
19638 	}
19639 
19640 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19641 		/*
19642 		 * When a zone sends a packet to another zone, we try to deliver
19643 		 * the packet under the same conditions as if the destination
19644 		 * was a real node on the network. To do so, we look for a
19645 		 * matching route in the forwarding table.
19646 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19647 		 * ip_newroute() does.
19648 		 */
19649 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19650 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19651 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19652 		if (src_ire != NULL &&
19653 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19654 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19655 				ipha->ipha_src = src_ire->ire_src_addr;
19656 			ire_refrele(src_ire);
19657 		} else {
19658 			ire_refrele(ire);
19659 			if (conn_outgoing_ill != NULL)
19660 				ill_refrele(conn_outgoing_ill);
19661 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19662 			if (src_ire != NULL) {
19663 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19664 					ire_refrele(src_ire);
19665 					freemsg(mp);
19666 					return;
19667 				}
19668 				ire_refrele(src_ire);
19669 			}
19670 			if (ip_hdr_complete(ipha, zoneid)) {
19671 				/* Failed */
19672 				freemsg(mp);
19673 				return;
19674 			}
19675 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19676 			return;
19677 		}
19678 	}
19679 
19680 	if (mp->b_datap->db_type == M_CTL ||
19681 	    ipsec_outbound_v4_policy_present) {
19682 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19683 		    unspec_src);
19684 		if (mp == NULL) {
19685 			ire_refrele(ire);
19686 			if (conn_outgoing_ill != NULL)
19687 				ill_refrele(conn_outgoing_ill);
19688 			return;
19689 		}
19690 	}
19691 
19692 	first_mp = mp;
19693 	ipsec_len = 0;
19694 
19695 	if (first_mp->b_datap->db_type == M_CTL) {
19696 		io = (ipsec_out_t *)first_mp->b_rptr;
19697 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19698 		mp = first_mp->b_cont;
19699 		ipsec_len = ipsec_out_extra_length(first_mp);
19700 		ASSERT(ipsec_len >= 0);
19701 		zoneid = io->ipsec_out_zoneid;
19702 		ASSERT(zoneid != ALL_ZONES);
19703 
19704 		/*
19705 		 * Drop M_CTL here if IPsec processing is not needed.
19706 		 * (Non-IPsec use of M_CTL extracted any information it
19707 		 * needed above).
19708 		 */
19709 		if (ipsec_len == 0) {
19710 			freeb(first_mp);
19711 			first_mp = mp;
19712 		}
19713 	}
19714 
19715 	/*
19716 	 * Fast path for ip_wput_ire
19717 	 */
19718 
19719 	ipha = (ipha_t *)mp->b_rptr;
19720 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19721 	dst = ipha->ipha_dst;
19722 
19723 	/*
19724 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19725 	 * if the socket is a SOCK_RAW type. The transport checksum should
19726 	 * be provided in the pre-built packet, so we don't need to compute it.
19727 	 * Also, other application set flags, like DF, should not be altered.
19728 	 * Other transport MUST pass down zero.
19729 	 */
19730 	ip_hdr_included = ipha->ipha_ident;
19731 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19732 
19733 	if (CLASSD(dst)) {
19734 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19735 		    ntohl(dst),
19736 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19737 		    ntohl(ire->ire_addr)));
19738 	}
19739 
19740 /* Macros to extract header fields from data already in registers */
19741 #ifdef	_BIG_ENDIAN
19742 #define	V_HLEN	(v_hlen_tos_len >> 24)
19743 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19744 #define	PROTO	(ttl_protocol & 0xFF)
19745 #else
19746 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19747 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19748 #define	PROTO	(ttl_protocol >> 8)
19749 #endif
19750 
19751 
19752 	orig_src = src = ipha->ipha_src;
19753 	/* (The loop back to "another" is explained down below.) */
19754 another:;
19755 	/*
19756 	 * Assign an ident value for this packet.  We assign idents on
19757 	 * a per destination basis out of the IRE.  There could be
19758 	 * other threads targeting the same destination, so we have to
19759 	 * arrange for a atomic increment.  Note that we use a 32-bit
19760 	 * atomic add because it has better performance than its
19761 	 * 16-bit sibling.
19762 	 *
19763 	 * If running in cluster mode and if the source address
19764 	 * belongs to a replicated service then vector through
19765 	 * cl_inet_ipident vector to allocate ip identifier
19766 	 * NOTE: This is a contract private interface with the
19767 	 * clustering group.
19768 	 */
19769 	clusterwide = 0;
19770 	if (cl_inet_ipident) {
19771 		ASSERT(cl_inet_isclusterwide);
19772 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19773 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19774 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19775 			    AF_INET, (uint8_t *)(uintptr_t)src,
19776 			    (uint8_t *)(uintptr_t)dst);
19777 			clusterwide = 1;
19778 		}
19779 	}
19780 	if (!clusterwide) {
19781 		ipha->ipha_ident =
19782 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19783 	}
19784 
19785 #ifndef _BIG_ENDIAN
19786 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19787 #endif
19788 
19789 	/*
19790 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19791 	 * This is needed to obey conn_unspec_src when packets go through
19792 	 * ip_newroute + arp.
19793 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19794 	 */
19795 	if (src == INADDR_ANY && !unspec_src) {
19796 		/*
19797 		 * Assign the appropriate source address from the IRE if none
19798 		 * was specified.
19799 		 */
19800 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19801 
19802 		/*
19803 		 * With IP multipathing, broadcast packets are sent on the ire
19804 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19805 		 * the group. However, this ire might not be in the same zone so
19806 		 * we can't always use its source address. We look for a
19807 		 * broadcast ire in the same group and in the right zone.
19808 		 */
19809 		if (ire->ire_type == IRE_BROADCAST &&
19810 		    ire->ire_zoneid != zoneid) {
19811 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19812 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19813 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19814 			if (src_ire != NULL) {
19815 				src = src_ire->ire_src_addr;
19816 				ire_refrele(src_ire);
19817 			} else {
19818 				ire_refrele(ire);
19819 				if (conn_outgoing_ill != NULL)
19820 					ill_refrele(conn_outgoing_ill);
19821 				freemsg(first_mp);
19822 				BUMP_MIB(&ip_mib, ipOutDiscards);
19823 				return;
19824 			}
19825 		} else {
19826 			src = ire->ire_src_addr;
19827 		}
19828 
19829 		if (connp == NULL) {
19830 			ip1dbg(("ip_wput_ire: no connp and no src "
19831 			    "address for dst 0x%x, using src 0x%x\n",
19832 			    ntohl(dst),
19833 			    ntohl(src)));
19834 		}
19835 		ipha->ipha_src = src;
19836 	}
19837 	stq = ire->ire_stq;
19838 
19839 	/*
19840 	 * We only allow ire chains for broadcasts since there will
19841 	 * be multiple IRE_CACHE entries for the same multicast
19842 	 * address (one per ipif).
19843 	 */
19844 	next_mp = NULL;
19845 
19846 	/* broadcast packet */
19847 	if (ire->ire_type == IRE_BROADCAST)
19848 		goto broadcast;
19849 
19850 	/* loopback ? */
19851 	if (stq == NULL)
19852 		goto nullstq;
19853 
19854 	/* The ill_index for outbound ILL */
19855 	ill_index = Q_TO_INDEX(stq);
19856 
19857 	BUMP_MIB(&ip_mib, ipOutRequests);
19858 	ttl_protocol = ((uint16_t *)ipha)[4];
19859 
19860 	/* pseudo checksum (do it in parts for IP header checksum) */
19861 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19862 
19863 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
19864 		queue_t *dev_q = stq->q_next;
19865 
19866 		/* flow controlled */
19867 		if ((dev_q->q_next || dev_q->q_first) &&
19868 		    !canput(dev_q))
19869 			goto blocked;
19870 		if ((PROTO == IPPROTO_UDP) &&
19871 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
19872 			hlen = (V_HLEN & 0xF) << 2;
19873 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
19874 			if (*up != 0) {
19875 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
19876 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
19877 				/* Software checksum? */
19878 				if (DB_CKSUMFLAGS(mp) == 0) {
19879 					IP_STAT(ip_out_sw_cksum);
19880 					IP_STAT_UPDATE(
19881 					    ip_udp_out_sw_cksum_bytes,
19882 					    LENGTH - hlen);
19883 				}
19884 			}
19885 		}
19886 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
19887 		hlen = (V_HLEN & 0xF) << 2;
19888 		if (PROTO == IPPROTO_TCP) {
19889 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
19890 			/*
19891 			 * The packet header is processed once and for all, even
19892 			 * in the multirouting case. We disable hardware
19893 			 * checksum if the packet is multirouted, as it will be
19894 			 * replicated via several interfaces, and not all of
19895 			 * them may have this capability.
19896 			 */
19897 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
19898 			    LENGTH, max_frag, ipsec_len, cksum);
19899 			/* Software checksum? */
19900 			if (DB_CKSUMFLAGS(mp) == 0) {
19901 				IP_STAT(ip_out_sw_cksum);
19902 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
19903 				    LENGTH - hlen);
19904 			}
19905 		} else {
19906 			sctp_hdr_t	*sctph;
19907 
19908 			ASSERT(PROTO == IPPROTO_SCTP);
19909 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
19910 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
19911 			/*
19912 			 * Zero out the checksum field to ensure proper
19913 			 * checksum calculation.
19914 			 */
19915 			sctph->sh_chksum = 0;
19916 #ifdef	DEBUG
19917 			if (!skip_sctp_cksum)
19918 #endif
19919 				sctph->sh_chksum = sctp_cksum(mp, hlen);
19920 		}
19921 	}
19922 
19923 	/*
19924 	 * If this is a multicast packet and originated from ip_wput
19925 	 * we need to do loopback and forwarding checks. If it comes
19926 	 * from ip_wput_multicast, we SHOULD not do this.
19927 	 */
19928 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
19929 
19930 	/* checksum */
19931 	cksum += ttl_protocol;
19932 
19933 	/* fragment the packet */
19934 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
19935 		goto fragmentit;
19936 	/*
19937 	 * Don't use frag_flag if packet is pre-built or source
19938 	 * routed or if multicast (since multicast packets do
19939 	 * not solicit ICMP "packet too big" messages).
19940 	 */
19941 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
19942 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
19943 	    !ip_source_route_included(ipha)) &&
19944 	    !CLASSD(ipha->ipha_dst))
19945 		ipha->ipha_fragment_offset_and_flags |=
19946 		    htons(ire->ire_frag_flag);
19947 
19948 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19949 		/* calculate IP header checksum */
19950 		cksum += ipha->ipha_ident;
19951 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
19952 		cksum += ipha->ipha_fragment_offset_and_flags;
19953 
19954 		/* IP options present */
19955 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
19956 		if (hlen)
19957 			goto checksumoptions;
19958 
19959 		/* calculate hdr checksum */
19960 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
19961 		cksum = ~(cksum + (cksum >> 16));
19962 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
19963 	}
19964 	if (ipsec_len != 0) {
19965 		/*
19966 		 * We will do the rest of the processing after
19967 		 * we come back from IPSEC in ip_wput_ipsec_out().
19968 		 */
19969 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
19970 
19971 		io = (ipsec_out_t *)first_mp->b_rptr;
19972 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
19973 				ill_phyint->phyint_ifindex;
19974 
19975 		ipsec_out_process(q, first_mp, ire, ill_index);
19976 		ire_refrele(ire);
19977 		if (conn_outgoing_ill != NULL)
19978 			ill_refrele(conn_outgoing_ill);
19979 		return;
19980 	}
19981 
19982 	/*
19983 	 * In most cases, the emission loop below is entered only
19984 	 * once. Only in the case where the ire holds the
19985 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
19986 	 * flagged ires in the bucket, and send the packet
19987 	 * through all crossed RTF_MULTIRT routes.
19988 	 */
19989 	if (ire->ire_flags & RTF_MULTIRT) {
19990 		multirt_send = B_TRUE;
19991 	}
19992 	do {
19993 		if (multirt_send) {
19994 			irb_t *irb;
19995 			/*
19996 			 * We are in a multiple send case, need to get
19997 			 * the next ire and make a duplicate of the packet.
19998 			 * ire1 holds here the next ire to process in the
19999 			 * bucket. If multirouting is expected,
20000 			 * any non-RTF_MULTIRT ire that has the
20001 			 * right destination address is ignored.
20002 			 */
20003 			irb = ire->ire_bucket;
20004 			ASSERT(irb != NULL);
20005 
20006 			IRB_REFHOLD(irb);
20007 			for (ire1 = ire->ire_next;
20008 			    ire1 != NULL;
20009 			    ire1 = ire1->ire_next) {
20010 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20011 					continue;
20012 				if (ire1->ire_addr != ire->ire_addr)
20013 					continue;
20014 				if (ire1->ire_marks &
20015 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20016 					continue;
20017 
20018 				/* Got one */
20019 				IRE_REFHOLD(ire1);
20020 				break;
20021 			}
20022 			IRB_REFRELE(irb);
20023 
20024 			if (ire1 != NULL) {
20025 				next_mp = copyb(mp);
20026 				if ((next_mp == NULL) ||
20027 				    ((mp->b_cont != NULL) &&
20028 				    ((next_mp->b_cont =
20029 				    dupmsg(mp->b_cont)) == NULL))) {
20030 					freemsg(next_mp);
20031 					next_mp = NULL;
20032 					ire_refrele(ire1);
20033 					ire1 = NULL;
20034 				}
20035 			}
20036 
20037 			/* Last multiroute ire; don't loop anymore. */
20038 			if (ire1 == NULL) {
20039 				multirt_send = B_FALSE;
20040 			}
20041 		}
20042 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20043 		if (mp == NULL) {
20044 			BUMP_MIB(&ip_mib, ipOutDiscards);
20045 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20046 			    "during IPPF processing\n"));
20047 			ire_refrele(ire);
20048 			if (next_mp != NULL) {
20049 				freemsg(next_mp);
20050 				ire_refrele(ire1);
20051 			}
20052 			if (conn_outgoing_ill != NULL)
20053 				ill_refrele(conn_outgoing_ill);
20054 			return;
20055 		}
20056 		UPDATE_OB_PKT_COUNT(ire);
20057 		ire->ire_last_used_time = lbolt;
20058 
20059 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20060 		    "ip_wput_ire_end: q %p (%S)",
20061 		    q, "last copy out");
20062 		putnext(stq, mp);
20063 		IRE_REFRELE(ire);
20064 
20065 		if (multirt_send) {
20066 			ASSERT(ire1);
20067 			/*
20068 			 * Proceed with the next RTF_MULTIRT ire,
20069 			 * Also set up the send-to queue accordingly.
20070 			 */
20071 			ire = ire1;
20072 			ire1 = NULL;
20073 			stq = ire->ire_stq;
20074 			mp = next_mp;
20075 			next_mp = NULL;
20076 			ipha = (ipha_t *)mp->b_rptr;
20077 			ill_index = Q_TO_INDEX(stq);
20078 		}
20079 	} while (multirt_send);
20080 	if (conn_outgoing_ill != NULL)
20081 		ill_refrele(conn_outgoing_ill);
20082 	return;
20083 
20084 	/*
20085 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20086 	 */
20087 broadcast:
20088 	{
20089 		/*
20090 		 * Avoid broadcast storms by setting the ttl to 1
20091 		 * for broadcasts. This parameter can be set
20092 		 * via ndd, so make sure that for the SO_DONTROUTE
20093 		 * case that ipha_ttl is always set to 1.
20094 		 * In the event that we are replying to incoming
20095 		 * ICMP packets, conn could be NULL.
20096 		 */
20097 		if ((connp != NULL) && connp->conn_dontroute)
20098 			ipha->ipha_ttl = 1;
20099 		else
20100 			ipha->ipha_ttl = ip_broadcast_ttl;
20101 
20102 		/*
20103 		 * Note that we are not doing a IRB_REFHOLD here.
20104 		 * Actually we don't care if the list changes i.e
20105 		 * if somebody deletes an IRE from the list while
20106 		 * we drop the lock, the next time we come around
20107 		 * ire_next will be NULL and hence we won't send
20108 		 * out multiple copies which is fine.
20109 		 */
20110 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20111 		ire1 = ire->ire_next;
20112 		if (conn_outgoing_ill != NULL) {
20113 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20114 				ASSERT(ire1 == ire->ire_next);
20115 				if (ire1 != NULL && ire1->ire_addr == dst) {
20116 					ire_refrele(ire);
20117 					ire = ire1;
20118 					IRE_REFHOLD(ire);
20119 					ire1 = ire->ire_next;
20120 					continue;
20121 				}
20122 				rw_exit(&ire->ire_bucket->irb_lock);
20123 				/* Did not find a matching ill */
20124 				ip1dbg(("ip_wput_ire: broadcast with no "
20125 				    "matching IP_BOUND_IF ill %s\n",
20126 				    conn_outgoing_ill->ill_name));
20127 				freemsg(first_mp);
20128 				if (ire != NULL)
20129 					ire_refrele(ire);
20130 				ill_refrele(conn_outgoing_ill);
20131 				return;
20132 			}
20133 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20134 			/*
20135 			 * If the next IRE has the same address and is not one
20136 			 * of the two copies that we need to send, try to see
20137 			 * whether this copy should be sent at all. This
20138 			 * assumes that we insert loopbacks first and then
20139 			 * non-loopbacks. This is acheived by inserting the
20140 			 * loopback always before non-loopback.
20141 			 * This is used to send a single copy of a broadcast
20142 			 * packet out all physical interfaces that have an
20143 			 * matching IRE_BROADCAST while also looping
20144 			 * back one copy (to ip_wput_local) for each
20145 			 * matching physical interface. However, we avoid
20146 			 * sending packets out different logical that match by
20147 			 * having ipif_up/ipif_down supress duplicate
20148 			 * IRE_BROADCASTS.
20149 			 *
20150 			 * This feature is currently used to get broadcasts
20151 			 * sent to multiple interfaces, when the broadcast
20152 			 * address being used applies to multiple interfaces.
20153 			 * For example, a whole net broadcast will be
20154 			 * replicated on every connected subnet of
20155 			 * the target net.
20156 			 *
20157 			 * Each zone has its own set of IRE_BROADCASTs, so that
20158 			 * we're able to distribute inbound packets to multiple
20159 			 * zones who share a broadcast address. We avoid looping
20160 			 * back outbound packets in different zones but on the
20161 			 * same ill, as the application would see duplicates.
20162 			 *
20163 			 * If the interfaces are part of the same group,
20164 			 * we would want to send only one copy out for
20165 			 * whole group.
20166 			 *
20167 			 * This logic assumes that ire_add_v4() groups the
20168 			 * IRE_BROADCAST entries so that those with the same
20169 			 * ire_addr and ill_group are kept together.
20170 			 */
20171 			ire_ill = ire->ire_ipif->ipif_ill;
20172 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20173 				if (ire_ill->ill_group != NULL &&
20174 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20175 					/*
20176 					 * If the current zone only has an ire
20177 					 * broadcast for this address marked
20178 					 * NORECV, the ire we want is ahead in
20179 					 * the bucket, so we look it up
20180 					 * deliberately ignoring the zoneid.
20181 					 */
20182 					for (ire1 = ire->ire_bucket->irb_ire;
20183 					    ire1 != NULL;
20184 					    ire1 = ire1->ire_next) {
20185 						ire1_ill =
20186 						    ire1->ire_ipif->ipif_ill;
20187 						if (ire1->ire_addr != dst)
20188 							continue;
20189 						/* skip over the current ire */
20190 						if (ire1 == ire)
20191 							continue;
20192 						/* skip over deleted ires */
20193 						if (ire1->ire_marks &
20194 						    IRE_MARK_CONDEMNED)
20195 							continue;
20196 						/*
20197 						 * non-loopback ire in our
20198 						 * group: use it for the next
20199 						 * pass in the loop
20200 						 */
20201 						if (ire1->ire_stq != NULL &&
20202 						    ire1_ill->ill_group ==
20203 						    ire_ill->ill_group)
20204 							break;
20205 					}
20206 				}
20207 			} else {
20208 				while (ire1 != NULL && ire1->ire_addr == dst) {
20209 					ire1_ill = ire1->ire_ipif->ipif_ill;
20210 					/*
20211 					 * We can have two broadcast ires on the
20212 					 * same ill in different zones; here
20213 					 * we'll send a copy of the packet on
20214 					 * each ill and the fanout code will
20215 					 * call conn_wantpacket() to check that
20216 					 * the zone has the broadcast address
20217 					 * configured on the ill. If the two
20218 					 * ires are in the same group we only
20219 					 * send one copy up.
20220 					 */
20221 					if (ire1_ill != ire_ill &&
20222 					    (ire1_ill->ill_group == NULL ||
20223 					    ire_ill->ill_group == NULL ||
20224 					    ire1_ill->ill_group !=
20225 					    ire_ill->ill_group)) {
20226 						break;
20227 					}
20228 					ire1 = ire1->ire_next;
20229 				}
20230 			}
20231 		}
20232 		ASSERT(multirt_send == B_FALSE);
20233 		if (ire1 != NULL && ire1->ire_addr == dst) {
20234 			if ((ire->ire_flags & RTF_MULTIRT) &&
20235 			    (ire1->ire_flags & RTF_MULTIRT)) {
20236 				/*
20237 				 * We are in the multirouting case.
20238 				 * The message must be sent at least
20239 				 * on both ires. These ires have been
20240 				 * inserted AFTER the standard ones
20241 				 * in ip_rt_add(). There are thus no
20242 				 * other ire entries for the destination
20243 				 * address in the rest of the bucket
20244 				 * that do not have the RTF_MULTIRT
20245 				 * flag. We don't process a copy
20246 				 * of the message here. This will be
20247 				 * done in the final sending loop.
20248 				 */
20249 				multirt_send = B_TRUE;
20250 			} else {
20251 				next_mp = ip_copymsg(first_mp);
20252 				if (next_mp != NULL)
20253 					IRE_REFHOLD(ire1);
20254 			}
20255 		}
20256 		rw_exit(&ire->ire_bucket->irb_lock);
20257 	}
20258 
20259 	if (stq) {
20260 		/*
20261 		 * A non-NULL send-to queue means this packet is going
20262 		 * out of this machine.
20263 		 */
20264 
20265 		BUMP_MIB(&ip_mib, ipOutRequests);
20266 		ttl_protocol = ((uint16_t *)ipha)[4];
20267 		/*
20268 		 * We accumulate the pseudo header checksum in cksum.
20269 		 * This is pretty hairy code, so watch close.  One
20270 		 * thing to keep in mind is that UDP and TCP have
20271 		 * stored their respective datagram lengths in their
20272 		 * checksum fields.  This lines things up real nice.
20273 		 */
20274 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20275 		    (src >> 16) + (src & 0xFFFF);
20276 		/*
20277 		 * We assume the udp checksum field contains the
20278 		 * length, so to compute the pseudo header checksum,
20279 		 * all we need is the protocol number and src/dst.
20280 		 */
20281 		/* Provide the checksums for UDP and TCP. */
20282 		if ((PROTO == IPPROTO_TCP) &&
20283 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20284 			/* hlen gets the number of uchar_ts in the IP header */
20285 			hlen = (V_HLEN & 0xF) << 2;
20286 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20287 			IP_STAT(ip_out_sw_cksum);
20288 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20289 			    LENGTH - hlen);
20290 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20291 			if (*up == 0)
20292 				*up = 0xFFFF;
20293 		} else if (PROTO == IPPROTO_SCTP &&
20294 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20295 			sctp_hdr_t	*sctph;
20296 
20297 			hlen = (V_HLEN & 0xF) << 2;
20298 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20299 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20300 			sctph->sh_chksum = 0;
20301 #ifdef	DEBUG
20302 			if (!skip_sctp_cksum)
20303 #endif
20304 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20305 		} else {
20306 			queue_t *dev_q = stq->q_next;
20307 
20308 			if ((dev_q->q_next || dev_q->q_first) &&
20309 			    !canput(dev_q)) {
20310 			    blocked:
20311 				ipha->ipha_ident = ip_hdr_included;
20312 				/*
20313 				 * If we don't have a conn to apply
20314 				 * backpressure, free the message.
20315 				 * In the ire_send path, we don't know
20316 				 * the position to requeue the packet. Rather
20317 				 * than reorder packets, we just drop this
20318 				 * packet.
20319 				 */
20320 				if (ip_output_queue && connp != NULL &&
20321 				    caller != IRE_SEND) {
20322 					if (caller == IP_WSRV) {
20323 						connp->conn_did_putbq = 1;
20324 						(void) putbq(connp->conn_wq,
20325 						    first_mp);
20326 						conn_drain_insert(connp);
20327 						/*
20328 						 * This is the service thread,
20329 						 * and the queue is already
20330 						 * noenabled. The check for
20331 						 * canput and the putbq is not
20332 						 * atomic. So we need to check
20333 						 * again.
20334 						 */
20335 						if (canput(stq->q_next))
20336 							connp->conn_did_putbq
20337 							    = 0;
20338 						IP_STAT(ip_conn_flputbq);
20339 					} else {
20340 						/*
20341 						 * We are not the service proc.
20342 						 * ip_wsrv will be scheduled or
20343 						 * is already running.
20344 						 */
20345 						(void) putq(connp->conn_wq,
20346 						    first_mp);
20347 					}
20348 				} else {
20349 					BUMP_MIB(&ip_mib, ipOutDiscards);
20350 					freemsg(first_mp);
20351 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20352 					    "ip_wput_ire_end: q %p (%S)",
20353 					    q, "discard");
20354 				}
20355 				ire_refrele(ire);
20356 				if (next_mp) {
20357 					ire_refrele(ire1);
20358 					freemsg(next_mp);
20359 				}
20360 				if (conn_outgoing_ill != NULL)
20361 					ill_refrele(conn_outgoing_ill);
20362 				return;
20363 			}
20364 			if ((PROTO == IPPROTO_UDP) &&
20365 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20366 				/*
20367 				 * hlen gets the number of uchar_ts in the
20368 				 * IP header
20369 				 */
20370 				hlen = (V_HLEN & 0xF) << 2;
20371 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20372 				max_frag = ire->ire_max_frag;
20373 				if (*up != 0) {
20374 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
20375 					    up, PROTO, hlen, LENGTH, max_frag,
20376 					    ipsec_len, cksum);
20377 					/* Software checksum? */
20378 					if (DB_CKSUMFLAGS(mp) == 0) {
20379 						IP_STAT(ip_out_sw_cksum);
20380 						IP_STAT_UPDATE(
20381 						    ip_udp_out_sw_cksum_bytes,
20382 						    LENGTH - hlen);
20383 					}
20384 				}
20385 			}
20386 		}
20387 		/*
20388 		 * Need to do this even when fragmenting. The local
20389 		 * loopback can be done without computing checksums
20390 		 * but forwarding out other interface must be done
20391 		 * after the IP checksum (and ULP checksums) have been
20392 		 * computed.
20393 		 *
20394 		 * NOTE : multicast_forward is set only if this packet
20395 		 * originated from ip_wput. For packets originating from
20396 		 * ip_wput_multicast, it is not set.
20397 		 */
20398 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20399 		    multi_loopback:
20400 			ip2dbg(("ip_wput: multicast, loop %d\n",
20401 			    conn_multicast_loop));
20402 
20403 			/*  Forget header checksum offload */
20404 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
20405 
20406 			/*
20407 			 * Local loopback of multicasts?  Check the
20408 			 * ill.
20409 			 *
20410 			 * Note that the loopback function will not come
20411 			 * in through ip_rput - it will only do the
20412 			 * client fanout thus we need to do an mforward
20413 			 * as well.  The is different from the BSD
20414 			 * logic.
20415 			 */
20416 			if (ill != NULL) {
20417 				ilm_t	*ilm;
20418 
20419 				ILM_WALKER_HOLD(ill);
20420 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20421 				    ALL_ZONES);
20422 				ILM_WALKER_RELE(ill);
20423 				if (ilm != NULL) {
20424 					/*
20425 					 * Pass along the virtual output q.
20426 					 * ip_wput_local() will distribute the
20427 					 * packet to all the matching zones,
20428 					 * except the sending zone when
20429 					 * IP_MULTICAST_LOOP is false.
20430 					 */
20431 					ip_multicast_loopback(q, ill, first_mp,
20432 					    conn_multicast_loop ? 0 :
20433 					    IP_FF_NO_MCAST_LOOP, zoneid);
20434 				}
20435 			}
20436 			if (ipha->ipha_ttl == 0) {
20437 				/*
20438 				 * 0 => only to this host i.e. we are
20439 				 * done. We are also done if this was the
20440 				 * loopback interface since it is sufficient
20441 				 * to loopback one copy of a multicast packet.
20442 				 */
20443 				freemsg(first_mp);
20444 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20445 				    "ip_wput_ire_end: q %p (%S)",
20446 				    q, "loopback");
20447 				ire_refrele(ire);
20448 				if (conn_outgoing_ill != NULL)
20449 					ill_refrele(conn_outgoing_ill);
20450 				return;
20451 			}
20452 			/*
20453 			 * ILLF_MULTICAST is checked in ip_newroute
20454 			 * i.e. we don't need to check it here since
20455 			 * all IRE_CACHEs come from ip_newroute.
20456 			 * For multicast traffic, SO_DONTROUTE is interpreted
20457 			 * to mean only send the packet out the interface
20458 			 * (optionally specified with IP_MULTICAST_IF)
20459 			 * and do not forward it out additional interfaces.
20460 			 * RSVP and the rsvp daemon is an example of a
20461 			 * protocol and user level process that
20462 			 * handles it's own routing. Hence, it uses the
20463 			 * SO_DONTROUTE option to accomplish this.
20464 			 */
20465 
20466 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20467 				/* Unconditionally redo the checksum */
20468 				ipha->ipha_hdr_checksum = 0;
20469 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20470 
20471 				/*
20472 				 * If this needs to go out secure, we need
20473 				 * to wait till we finish the IPSEC
20474 				 * processing.
20475 				 */
20476 				if (ipsec_len == 0 &&
20477 				    ip_mforward(ill, ipha, mp)) {
20478 					freemsg(first_mp);
20479 					ip1dbg(("ip_wput: mforward failed\n"));
20480 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20481 					    "ip_wput_ire_end: q %p (%S)",
20482 					    q, "mforward failed");
20483 					ire_refrele(ire);
20484 					if (conn_outgoing_ill != NULL)
20485 						ill_refrele(conn_outgoing_ill);
20486 					return;
20487 				}
20488 			}
20489 		}
20490 		max_frag = ire->ire_max_frag;
20491 		cksum += ttl_protocol;
20492 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
20493 			/* No fragmentation required for this one. */
20494 			/*
20495 			 * Don't use frag_flag if packet is pre-built or source
20496 			 * routed or if multicast (since multicast packets do
20497 			 * not solicit ICMP "packet too big" messages).
20498 			 */
20499 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20500 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20501 			    !ip_source_route_included(ipha)) &&
20502 			    !CLASSD(ipha->ipha_dst))
20503 				ipha->ipha_fragment_offset_and_flags |=
20504 				    htons(ire->ire_frag_flag);
20505 
20506 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20507 				/* Complete the IP header checksum. */
20508 				cksum += ipha->ipha_ident;
20509 				cksum += (v_hlen_tos_len >> 16)+
20510 				    (v_hlen_tos_len & 0xFFFF);
20511 				cksum += ipha->ipha_fragment_offset_and_flags;
20512 				hlen = (V_HLEN & 0xF) -
20513 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20514 				if (hlen) {
20515 				    checksumoptions:
20516 					/*
20517 					 * Account for the IP Options in the IP
20518 					 * header checksum.
20519 					 */
20520 					up = (uint16_t *)(rptr+
20521 					    IP_SIMPLE_HDR_LENGTH);
20522 					do {
20523 						cksum += up[0];
20524 						cksum += up[1];
20525 						up += 2;
20526 					} while (--hlen);
20527 				}
20528 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20529 				cksum = ~(cksum + (cksum >> 16));
20530 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
20531 			}
20532 			if (ipsec_len != 0) {
20533 				ipsec_out_process(q, first_mp, ire, ill_index);
20534 				if (!next_mp) {
20535 					ire_refrele(ire);
20536 					if (conn_outgoing_ill != NULL)
20537 						ill_refrele(conn_outgoing_ill);
20538 					return;
20539 				}
20540 				goto next;
20541 			}
20542 
20543 			/*
20544 			 * multirt_send has already been handled
20545 			 * for broadcast, but not yet for multicast
20546 			 * or IP options.
20547 			 */
20548 			if (next_mp == NULL) {
20549 				if (ire->ire_flags & RTF_MULTIRT) {
20550 					multirt_send = B_TRUE;
20551 				}
20552 			}
20553 
20554 			/*
20555 			 * In most cases, the emission loop below is
20556 			 * entered only once. Only in the case where
20557 			 * the ire holds the RTF_MULTIRT flag, do we loop
20558 			 * to process all RTF_MULTIRT ires in the bucket,
20559 			 * and send the packet through all crossed
20560 			 * RTF_MULTIRT routes.
20561 			 */
20562 			do {
20563 				if (multirt_send) {
20564 					irb_t *irb;
20565 
20566 					irb = ire->ire_bucket;
20567 					ASSERT(irb != NULL);
20568 					/*
20569 					 * We are in a multiple send case,
20570 					 * need to get the next IRE and make
20571 					 * a duplicate of the packet.
20572 					 */
20573 					IRB_REFHOLD(irb);
20574 					for (ire1 = ire->ire_next;
20575 					    ire1 != NULL;
20576 					    ire1 = ire1->ire_next) {
20577 						if (!(ire1->ire_flags &
20578 						    RTF_MULTIRT))
20579 							continue;
20580 						if (ire1->ire_addr !=
20581 						    ire->ire_addr)
20582 							continue;
20583 						if (ire1->ire_marks &
20584 						    (IRE_MARK_CONDEMNED|
20585 							IRE_MARK_HIDDEN))
20586 							continue;
20587 
20588 						/* Got one */
20589 						IRE_REFHOLD(ire1);
20590 						break;
20591 					}
20592 					IRB_REFRELE(irb);
20593 
20594 					if (ire1 != NULL) {
20595 						next_mp = copyb(mp);
20596 						if ((next_mp == NULL) ||
20597 						    ((mp->b_cont != NULL) &&
20598 						    ((next_mp->b_cont =
20599 						    dupmsg(mp->b_cont))
20600 						    == NULL))) {
20601 							freemsg(next_mp);
20602 							next_mp = NULL;
20603 							ire_refrele(ire1);
20604 							ire1 = NULL;
20605 						}
20606 					}
20607 
20608 					/*
20609 					 * Last multiroute ire; don't loop
20610 					 * anymore. The emission is over
20611 					 * and next_mp is NULL.
20612 					 */
20613 					if (ire1 == NULL) {
20614 						multirt_send = B_FALSE;
20615 					}
20616 				}
20617 
20618 			noprepend:
20619 				ASSERT(ipsec_len == 0);
20620 				mp1 = ip_wput_attach_llhdr(mp, ire,
20621 				    IPP_LOCAL_OUT, ill_index);
20622 				if (mp1 == NULL) {
20623 					BUMP_MIB(&ip_mib, ipOutDiscards);
20624 					if (next_mp) {
20625 						freemsg(next_mp);
20626 						ire_refrele(ire1);
20627 					}
20628 					ire_refrele(ire);
20629 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20630 					    "ip_wput_ire_end: q %p (%S)",
20631 					    q, "discard MDATA");
20632 					if (conn_outgoing_ill != NULL)
20633 						ill_refrele(conn_outgoing_ill);
20634 					return;
20635 				}
20636 				UPDATE_OB_PKT_COUNT(ire);
20637 				ire->ire_last_used_time = lbolt;
20638 
20639 				if (multirt_send) {
20640 					/*
20641 					 * We are in a multiple send case,
20642 					 * need to re-enter the sending loop
20643 					 * using the next ire.
20644 					 */
20645 					putnext(stq, mp1);
20646 					ire_refrele(ire);
20647 					ire = ire1;
20648 					stq = ire->ire_stq;
20649 					mp = next_mp;
20650 					next_mp = NULL;
20651 					ipha = (ipha_t *)mp->b_rptr;
20652 					ill_index = Q_TO_INDEX(stq);
20653 				}
20654 			} while (multirt_send);
20655 
20656 			if (!next_mp) {
20657 				/*
20658 				 * Last copy going out (the ultra-common
20659 				 * case).  Note that we intentionally replicate
20660 				 * the putnext rather than calling it before
20661 				 * the next_mp check in hopes of a little
20662 				 * tail-call action out of the compiler.
20663 				 */
20664 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20665 				    "ip_wput_ire_end: q %p (%S)",
20666 				    q, "last copy out(1)");
20667 				putnext(stq, mp1);
20668 				ire_refrele(ire);
20669 				if (conn_outgoing_ill != NULL)
20670 					ill_refrele(conn_outgoing_ill);
20671 				return;
20672 			}
20673 			/* More copies going out below. */
20674 			putnext(stq, mp1);
20675 		} else {
20676 			int offset;
20677 		    fragmentit:
20678 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20679 			/*
20680 			 * If this would generate a icmp_frag_needed message,
20681 			 * we need to handle it before we do the IPSEC
20682 			 * processing. Otherwise, we need to strip the IPSEC
20683 			 * headers before we send up the message to the ULPs
20684 			 * which becomes messy and difficult.
20685 			 */
20686 			if (ipsec_len != 0) {
20687 				if ((max_frag < (unsigned int)(LENGTH +
20688 				    ipsec_len)) && (offset & IPH_DF)) {
20689 
20690 					BUMP_MIB(&ip_mib, ipFragFails);
20691 					ipha->ipha_hdr_checksum = 0;
20692 					ipha->ipha_hdr_checksum =
20693 					    (uint16_t)ip_csum_hdr(ipha);
20694 					icmp_frag_needed(ire->ire_stq, first_mp,
20695 					    max_frag);
20696 					if (!next_mp) {
20697 						ire_refrele(ire);
20698 						if (conn_outgoing_ill != NULL) {
20699 							ill_refrele(
20700 							    conn_outgoing_ill);
20701 						}
20702 						return;
20703 					}
20704 				} else {
20705 					/*
20706 					 * This won't cause a icmp_frag_needed
20707 					 * message. to be gnerated. Send it on
20708 					 * the wire. Note that this could still
20709 					 * cause fragmentation and all we
20710 					 * do is the generation of the message
20711 					 * to the ULP if needed before IPSEC.
20712 					 */
20713 					if (!next_mp) {
20714 						ipsec_out_process(q, first_mp,
20715 						    ire, ill_index);
20716 						TRACE_2(TR_FAC_IP,
20717 						    TR_IP_WPUT_IRE_END,
20718 						    "ip_wput_ire_end: q %p "
20719 						    "(%S)", q,
20720 						    "last ipsec_out_process");
20721 						ire_refrele(ire);
20722 						if (conn_outgoing_ill != NULL) {
20723 							ill_refrele(
20724 							    conn_outgoing_ill);
20725 						}
20726 						return;
20727 					}
20728 					ipsec_out_process(q, first_mp,
20729 					    ire, ill_index);
20730 				}
20731 			} else {
20732 				/* Initiate IPPF processing */
20733 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20734 					ip_process(IPP_LOCAL_OUT, &mp,
20735 					    ill_index);
20736 					if (mp == NULL) {
20737 						BUMP_MIB(&ip_mib,
20738 						    ipOutDiscards);
20739 						if (next_mp != NULL) {
20740 							freemsg(next_mp);
20741 							ire_refrele(ire1);
20742 						}
20743 						ire_refrele(ire);
20744 						TRACE_2(TR_FAC_IP,
20745 						    TR_IP_WPUT_IRE_END,
20746 						    "ip_wput_ire: q %p (%S)",
20747 						    q, "discard MDATA");
20748 						if (conn_outgoing_ill != NULL) {
20749 							ill_refrele(
20750 							    conn_outgoing_ill);
20751 						}
20752 						return;
20753 					}
20754 				}
20755 				if (!next_mp) {
20756 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20757 					    "ip_wput_ire_end: q %p (%S)",
20758 					    q, "last fragmentation");
20759 					ip_wput_ire_fragmentit(mp, ire);
20760 					ire_refrele(ire);
20761 					if (conn_outgoing_ill != NULL)
20762 						ill_refrele(conn_outgoing_ill);
20763 					return;
20764 				}
20765 				ip_wput_ire_fragmentit(mp, ire);
20766 			}
20767 		}
20768 	} else {
20769 	    nullstq:
20770 		/* A NULL stq means the destination address is local. */
20771 		UPDATE_OB_PKT_COUNT(ire);
20772 		ire->ire_last_used_time = lbolt;
20773 		ASSERT(ire->ire_ipif != NULL);
20774 		if (!next_mp) {
20775 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20776 			    "ip_wput_ire_end: q %p (%S)",
20777 			    q, "local address");
20778 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20779 			    first_mp, ire, 0, ire->ire_zoneid);
20780 			ire_refrele(ire);
20781 			if (conn_outgoing_ill != NULL)
20782 				ill_refrele(conn_outgoing_ill);
20783 			return;
20784 		}
20785 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20786 		    ire, 0, ire->ire_zoneid);
20787 	}
20788 next:
20789 	/*
20790 	 * More copies going out to additional interfaces.
20791 	 * ire1 has already been held. We don't need the
20792 	 * "ire" anymore.
20793 	 */
20794 	ire_refrele(ire);
20795 	ire = ire1;
20796 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20797 	mp = next_mp;
20798 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20799 	ill = ire_to_ill(ire);
20800 	first_mp = mp;
20801 	if (ipsec_len != 0) {
20802 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20803 		mp = mp->b_cont;
20804 	}
20805 	dst = ire->ire_addr;
20806 	ipha = (ipha_t *)mp->b_rptr;
20807 	/*
20808 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20809 	 * Restore ipha_ident "no checksum" flag.
20810 	 */
20811 	src = orig_src;
20812 	ipha->ipha_ident = ip_hdr_included;
20813 	goto another;
20814 
20815 #undef	rptr
20816 #undef	Q_TO_INDEX
20817 }
20818 
20819 /*
20820  * Routine to allocate a message that is used to notify the ULP about MDT.
20821  * The caller may provide a pointer to the link-layer MDT capabilities,
20822  * or NULL if MDT is to be disabled on the stream.
20823  */
20824 mblk_t *
20825 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20826 {
20827 	mblk_t *mp;
20828 	ip_mdt_info_t *mdti;
20829 	ill_mdt_capab_t *idst;
20830 
20831 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20832 		DB_TYPE(mp) = M_CTL;
20833 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20834 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20835 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20836 		idst = &(mdti->mdt_capab);
20837 
20838 		/*
20839 		 * If the caller provides us with the capability, copy
20840 		 * it over into our notification message; otherwise
20841 		 * we zero out the capability portion.
20842 		 */
20843 		if (isrc != NULL)
20844 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20845 		else
20846 			bzero((caddr_t)idst, sizeof (*idst));
20847 	}
20848 	return (mp);
20849 }
20850 
20851 /*
20852  * Routine which determines whether MDT can be enabled on the destination
20853  * IRE and IPC combination, and if so, allocates and returns the MDT
20854  * notification mblk that may be used by ULP.  We also check if we need to
20855  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
20856  * MDT usage in the past have been lifted.  This gets called during IP
20857  * and ULP binding.
20858  */
20859 mblk_t *
20860 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
20861     ill_mdt_capab_t *mdt_cap)
20862 {
20863 	mblk_t *mp;
20864 	boolean_t rc = B_FALSE;
20865 
20866 	ASSERT(dst_ire != NULL);
20867 	ASSERT(connp != NULL);
20868 	ASSERT(mdt_cap != NULL);
20869 
20870 	/*
20871 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
20872 	 * Multidata, which is handled in tcp_multisend().  This
20873 	 * is the reason why we do all these checks here, to ensure
20874 	 * that we don't enable Multidata for the cases which we
20875 	 * can't handle at the moment.
20876 	 */
20877 	do {
20878 		/* Only do TCP at the moment */
20879 		if (connp->conn_ulp != IPPROTO_TCP)
20880 			break;
20881 
20882 		/*
20883 		 * IPSEC outbound policy present?  Note that we get here
20884 		 * after calling ipsec_conn_cache_policy() where the global
20885 		 * policy checking is performed.  conn_latch will be
20886 		 * non-NULL as long as there's a policy defined,
20887 		 * i.e. conn_out_enforce_policy may be NULL in such case
20888 		 * when the connection is non-secure, and hence we check
20889 		 * further if the latch refers to an outbound policy.
20890 		 */
20891 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
20892 			break;
20893 
20894 		/* CGTP (multiroute) is enabled? */
20895 		if (dst_ire->ire_flags & RTF_MULTIRT)
20896 			break;
20897 
20898 		/* Outbound IPQoS enabled? */
20899 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20900 			/*
20901 			 * In this case, we disable MDT for this and all
20902 			 * future connections going over the interface.
20903 			 */
20904 			mdt_cap->ill_mdt_on = 0;
20905 			break;
20906 		}
20907 
20908 		/* socket option(s) present? */
20909 		if (!CONN_IS_MD_FASTPATH(connp))
20910 			break;
20911 
20912 		rc = B_TRUE;
20913 	/* CONSTCOND */
20914 	} while (0);
20915 
20916 	/* Remember the result */
20917 	connp->conn_mdt_ok = rc;
20918 
20919 	if (!rc)
20920 		return (NULL);
20921 	else if (!mdt_cap->ill_mdt_on) {
20922 		/*
20923 		 * If MDT has been previously turned off in the past, and we
20924 		 * currently can do MDT (due to IPQoS policy removal, etc.)
20925 		 * then enable it for this interface.
20926 		 */
20927 		mdt_cap->ill_mdt_on = 1;
20928 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
20929 		    "interface %s\n", ill_name));
20930 	}
20931 
20932 	/* Allocate the MDT info mblk */
20933 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
20934 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
20935 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
20936 		return (NULL);
20937 	}
20938 	return (mp);
20939 }
20940 
20941 /*
20942  * Create destination address attribute, and fill it with the physical
20943  * destination address and SAP taken from the template DL_UNITDATA_REQ
20944  * message block.
20945  */
20946 boolean_t
20947 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
20948 {
20949 	dl_unitdata_req_t *dlurp;
20950 	pattr_t *pa;
20951 	pattrinfo_t pa_info;
20952 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
20953 	uint_t das_len, das_off;
20954 
20955 	ASSERT(dlmp != NULL);
20956 
20957 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
20958 	das_len = dlurp->dl_dest_addr_length;
20959 	das_off = dlurp->dl_dest_addr_offset;
20960 
20961 	pa_info.type = PATTR_DSTADDRSAP;
20962 	pa_info.len = sizeof (**das) + das_len - 1;
20963 
20964 	/* create and associate the attribute */
20965 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20966 	if (pa != NULL) {
20967 		ASSERT(*das != NULL);
20968 		(*das)->addr_is_group = 0;
20969 		(*das)->addr_len = (uint8_t)das_len;
20970 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
20971 	}
20972 
20973 	return (pa != NULL);
20974 }
20975 
20976 /*
20977  * Create hardware checksum attribute and fill it with the values passed.
20978  */
20979 boolean_t
20980 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
20981     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
20982 {
20983 	pattr_t *pa;
20984 	pattrinfo_t pa_info;
20985 
20986 	ASSERT(mmd != NULL);
20987 
20988 	pa_info.type = PATTR_HCKSUM;
20989 	pa_info.len = sizeof (pattr_hcksum_t);
20990 
20991 	/* create and associate the attribute */
20992 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20993 	if (pa != NULL) {
20994 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
20995 
20996 		hck->hcksum_start_offset = start_offset;
20997 		hck->hcksum_stuff_offset = stuff_offset;
20998 		hck->hcksum_end_offset = end_offset;
20999 		hck->hcksum_flags = flags;
21000 	}
21001 	return (pa != NULL);
21002 }
21003 
21004 /*
21005  * Create zerocopy attribute and fill it with the specified flags
21006  */
21007 boolean_t
21008 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21009 {
21010 	pattr_t *pa;
21011 	pattrinfo_t pa_info;
21012 
21013 	ASSERT(mmd != NULL);
21014 	pa_info.type = PATTR_ZCOPY;
21015 	pa_info.len = sizeof (pattr_zcopy_t);
21016 
21017 	/* create and associate the attribute */
21018 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21019 	if (pa != NULL) {
21020 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21021 
21022 		zcopy->zcopy_flags = flags;
21023 	}
21024 	return (pa != NULL);
21025 }
21026 
21027 /*
21028  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21029  * block chain. We could rewrite to handle arbitrary message block chains but
21030  * that would make the code complicated and slow. Right now there three
21031  * restrictions:
21032  *
21033  *   1. The first message block must contain the complete IP header and
21034  *	at least 1 byte of payload data.
21035  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
21036  *	so that we can use a single Multidata message.
21037  *   3. No frag must be distributed over two or more message blocks so
21038  *	that we don't need more than two packet descriptors per frag.
21039  *
21040  * The above restrictions allow us to support userland applications (which
21041  * will send down a single message block) and NFS over UDP (which will
21042  * send down a chain of at most three message blocks).
21043  *
21044  * We also don't use MDT for payloads with less than or equal to
21045  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
21046  */
21047 boolean_t
21048 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
21049 {
21050 	int	blocks;
21051 	ssize_t	total, missing, size;
21052 
21053 	ASSERT(mp != NULL);
21054 	ASSERT(hdr_len > 0);
21055 
21056 	size = MBLKL(mp) - hdr_len;
21057 	if (size <= 0)
21058 		return (B_FALSE);
21059 
21060 	/* The first mblk contains the header and some payload. */
21061 	blocks = 1;
21062 	total = size;
21063 	size %= len;
21064 	missing = (size == 0) ? 0 : (len - size);
21065 	mp = mp->b_cont;
21066 
21067 	while (mp != NULL) {
21068 		/*
21069 		 * Give up if we encounter a zero length message block.
21070 		 * In practice, this should rarely happen and therefore
21071 		 * not worth the trouble of freeing and re-linking the
21072 		 * mblk from the chain to handle such case.
21073 		 */
21074 		if ((size = MBLKL(mp)) == 0)
21075 			return (B_FALSE);
21076 
21077 		/* Too many payload buffers for a single Multidata message? */
21078 		if (++blocks > MULTIDATA_MAX_PBUFS)
21079 			return (B_FALSE);
21080 
21081 		total += size;
21082 		/* Is a frag distributed over two or more message blocks? */
21083 		if (missing > size)
21084 			return (B_FALSE);
21085 		size -= missing;
21086 
21087 		size %= len;
21088 		missing = (size == 0) ? 0 : (len - size);
21089 
21090 		mp = mp->b_cont;
21091 	}
21092 
21093 	return (total > ip_wput_frag_mdt_min);
21094 }
21095 
21096 /*
21097  * Outbound IPv4 fragmentation routine using MDT.
21098  */
21099 static void
21100 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
21101     uint32_t frag_flag, int offset)
21102 {
21103 	ipha_t		*ipha_orig;
21104 	int		i1, ip_data_end;
21105 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
21106 	mblk_t		*hdr_mp, *md_mp = NULL;
21107 	unsigned char	*hdr_ptr, *pld_ptr;
21108 	multidata_t	*mmd;
21109 	ip_pdescinfo_t	pdi;
21110 
21111 	ASSERT(DB_TYPE(mp) == M_DATA);
21112 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
21113 
21114 	ipha_orig = (ipha_t *)mp->b_rptr;
21115 	mp->b_rptr += sizeof (ipha_t);
21116 
21117 	/* Calculate how many packets we will send out */
21118 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
21119 	pkts = (i1 + len - 1) / len;
21120 	ASSERT(pkts > 1);
21121 
21122 	/* Allocate a message block which will hold all the IP Headers. */
21123 	wroff = ip_wroff_extra;
21124 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
21125 
21126 	i1 = pkts * hdr_chunk_len;
21127 	/*
21128 	 * Create the header buffer, Multidata and destination address
21129 	 * and SAP attribute that should be associated with it.
21130 	 */
21131 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
21132 	    ((hdr_mp->b_wptr += i1),
21133 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
21134 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
21135 		freemsg(mp);
21136 		if (md_mp == NULL) {
21137 			freemsg(hdr_mp);
21138 		} else {
21139 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
21140 			freemsg(md_mp);
21141 		}
21142 		IP_STAT(ip_frag_mdt_allocfail);
21143 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
21144 		return;
21145 	}
21146 	IP_STAT(ip_frag_mdt_allocd);
21147 
21148 	/*
21149 	 * Add a payload buffer to the Multidata; this operation must not
21150 	 * fail, or otherwise our logic in this routine is broken.  There
21151 	 * is no memory allocation done by the routine, so any returned
21152 	 * failure simply tells us that we've done something wrong.
21153 	 *
21154 	 * A failure tells us that either we're adding the same payload
21155 	 * buffer more than once, or we're trying to add more buffers than
21156 	 * allowed.  None of the above cases should happen, and we panic
21157 	 * because either there's horrible heap corruption, and/or
21158 	 * programming mistake.
21159 	 */
21160 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21161 		goto pbuf_panic;
21162 
21163 	hdr_ptr = hdr_mp->b_rptr;
21164 	pld_ptr = mp->b_rptr;
21165 
21166 	/* Establish the ending byte offset, based on the starting offset. */
21167 	offset <<= 3;
21168 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
21169 	    IP_SIMPLE_HDR_LENGTH;
21170 
21171 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
21172 
21173 	while (pld_ptr < mp->b_wptr) {
21174 		ipha_t		*ipha;
21175 		uint16_t	offset_and_flags;
21176 		uint16_t	ip_len;
21177 		int		error;
21178 
21179 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
21180 		ipha = (ipha_t *)(hdr_ptr + wroff);
21181 		ASSERT(OK_32PTR(ipha));
21182 		*ipha = *ipha_orig;
21183 
21184 		if (ip_data_end - offset > len) {
21185 			offset_and_flags = IPH_MF;
21186 		} else {
21187 			/*
21188 			 * Last frag. Set len to the length of this last piece.
21189 			 */
21190 			len = ip_data_end - offset;
21191 			/* A frag of a frag might have IPH_MF non-zero */
21192 			offset_and_flags =
21193 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21194 			    IPH_MF;
21195 		}
21196 		offset_and_flags |= (uint16_t)(offset >> 3);
21197 		offset_and_flags |= (uint16_t)frag_flag;
21198 		/* Store the offset and flags in the IP header. */
21199 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21200 
21201 		/* Store the length in the IP header. */
21202 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
21203 		ipha->ipha_length = htons(ip_len);
21204 
21205 		/*
21206 		 * Set the IP header checksum.  Note that mp is just
21207 		 * the header, so this is easy to pass to ip_csum.
21208 		 */
21209 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21210 
21211 		/*
21212 		 * Record offset and size of header and data of the next packet
21213 		 * in the multidata message.
21214 		 */
21215 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
21216 		PDESC_PLD_INIT(&pdi);
21217 		i1 = MIN(mp->b_wptr - pld_ptr, len);
21218 		ASSERT(i1 > 0);
21219 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
21220 		if (i1 == len) {
21221 			pld_ptr += len;
21222 		} else {
21223 			i1 = len - i1;
21224 			mp = mp->b_cont;
21225 			ASSERT(mp != NULL);
21226 			ASSERT(MBLKL(mp) >= i1);
21227 			/*
21228 			 * Attach the next payload message block to the
21229 			 * multidata message.
21230 			 */
21231 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21232 				goto pbuf_panic;
21233 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
21234 			pld_ptr = mp->b_rptr + i1;
21235 		}
21236 
21237 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
21238 		    KM_NOSLEEP)) == NULL) {
21239 			/*
21240 			 * Any failure other than ENOMEM indicates that we
21241 			 * have passed in invalid pdesc info or parameters
21242 			 * to mmd_addpdesc, which must not happen.
21243 			 *
21244 			 * EINVAL is a result of failure on boundary checks
21245 			 * against the pdesc info contents.  It should not
21246 			 * happen, and we panic because either there's
21247 			 * horrible heap corruption, and/or programming
21248 			 * mistake.
21249 			 */
21250 			if (error != ENOMEM) {
21251 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
21252 				    "pdesc logic error detected for "
21253 				    "mmd %p pinfo %p (%d)\n",
21254 				    (void *)mmd, (void *)&pdi, error);
21255 				/* NOTREACHED */
21256 			}
21257 			IP_STAT(ip_frag_mdt_addpdescfail);
21258 			/* Free unattached payload message blocks as well */
21259 			md_mp->b_cont = mp->b_cont;
21260 			goto free_mmd;
21261 		}
21262 
21263 		/* Advance fragment offset. */
21264 		offset += len;
21265 
21266 		/* Advance to location for next header in the buffer. */
21267 		hdr_ptr += hdr_chunk_len;
21268 
21269 		/* Did we reach the next payload message block? */
21270 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
21271 			mp = mp->b_cont;
21272 			/*
21273 			 * Attach the next message block with payload
21274 			 * data to the multidata message.
21275 			 */
21276 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21277 				goto pbuf_panic;
21278 			pld_ptr = mp->b_rptr;
21279 		}
21280 	}
21281 
21282 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
21283 	ASSERT(mp->b_wptr == pld_ptr);
21284 
21285 	/* Update IP statistics */
21286 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
21287 	BUMP_MIB(&ip_mib, ipFragOKs);
21288 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
21289 
21290 	if (pkt_type == OB_PKT) {
21291 		ire->ire_ob_pkt_count += pkts;
21292 		if (ire->ire_ipif != NULL)
21293 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
21294 	} else {
21295 		/*
21296 		 * The type is IB_PKT in the forwarding path and in
21297 		 * the mobile IP case when the packet is being reverse-
21298 		 * tunneled to the home agent.
21299 		 */
21300 		ire->ire_ib_pkt_count += pkts;
21301 		ASSERT(!IRE_IS_LOCAL(ire));
21302 		if (ire->ire_type & IRE_BROADCAST)
21303 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
21304 		else
21305 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
21306 	}
21307 	ire->ire_last_used_time = lbolt;
21308 	/* Send it down */
21309 	putnext(ire->ire_stq, md_mp);
21310 	return;
21311 
21312 pbuf_panic:
21313 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
21314 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
21315 	    pbuf_idx);
21316 	/* NOTREACHED */
21317 }
21318 
21319 /*
21320  * Outbound IP fragmentation routine.
21321  *
21322  * NOTE : This routine does not ire_refrele the ire that is passed in
21323  * as the argument.
21324  */
21325 static void
21326 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21327     uint32_t frag_flag)
21328 {
21329 	int		i1;
21330 	mblk_t		*ll_hdr_mp;
21331 	int 		ll_hdr_len;
21332 	int		hdr_len;
21333 	mblk_t		*hdr_mp;
21334 	ipha_t		*ipha;
21335 	int		ip_data_end;
21336 	int		len;
21337 	mblk_t		*mp = mp_orig;
21338 	int		offset;
21339 	queue_t		*q;
21340 	uint32_t	v_hlen_tos_len;
21341 	mblk_t		*first_mp;
21342 	boolean_t	mctl_present;
21343 	ill_t		*ill;
21344 	mblk_t		*xmit_mp;
21345 	mblk_t		*carve_mp;
21346 	ire_t		*ire1 = NULL;
21347 	ire_t		*save_ire = NULL;
21348 	mblk_t  	*next_mp = NULL;
21349 	boolean_t	last_frag = B_FALSE;
21350 	boolean_t	multirt_send = B_FALSE;
21351 	ire_t		*first_ire = NULL;
21352 	irb_t		*irb = NULL;
21353 
21354 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21355 	    "ip_wput_frag_start:");
21356 
21357 	if (mp->b_datap->db_type == M_CTL) {
21358 		first_mp = mp;
21359 		mp_orig = mp = mp->b_cont;
21360 		mctl_present = B_TRUE;
21361 	} else {
21362 		first_mp = mp;
21363 		mctl_present = B_FALSE;
21364 	}
21365 
21366 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
21367 	ipha = (ipha_t *)mp->b_rptr;
21368 
21369 	/*
21370 	 * If the Don't Fragment flag is on, generate an ICMP destination
21371 	 * unreachable, fragmentation needed.
21372 	 */
21373 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21374 	if (offset & IPH_DF) {
21375 		BUMP_MIB(&ip_mib, ipFragFails);
21376 		/*
21377 		 * Need to compute hdr checksum if called from ip_wput_ire.
21378 		 * Note that ip_rput_forward verifies the checksum before
21379 		 * calling this routine so in that case this is a noop.
21380 		 */
21381 		ipha->ipha_hdr_checksum = 0;
21382 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21383 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21384 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21385 		    "ip_wput_frag_end:(%S)",
21386 		    "don't fragment");
21387 		return;
21388 	}
21389 	if (mctl_present)
21390 		freeb(first_mp);
21391 	/*
21392 	 * Establish the starting offset.  May not be zero if we are fragging
21393 	 * a fragment that is being forwarded.
21394 	 */
21395 	offset = offset & IPH_OFFSET;
21396 
21397 	/* TODO why is this test needed? */
21398 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21399 	if (((max_frag - LENGTH) & ~7) < 8) {
21400 		/* TODO: notify ulp somehow */
21401 		BUMP_MIB(&ip_mib, ipFragFails);
21402 		freemsg(mp);
21403 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21404 		    "ip_wput_frag_end:(%S)",
21405 		    "len < 8");
21406 		return;
21407 	}
21408 
21409 	hdr_len = (V_HLEN & 0xF) << 2;
21410 
21411 	ipha->ipha_hdr_checksum = 0;
21412 
21413 	/*
21414 	 * Establish the number of bytes maximum per frag, after putting
21415 	 * in the header.
21416 	 */
21417 	len = (max_frag - hdr_len) & ~7;
21418 
21419 	/* Check if we can use MDT to send out the frags. */
21420 	ASSERT(!IRE_IS_LOCAL(ire));
21421 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
21422 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
21423 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
21424 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
21425 		ASSERT(ill->ill_mdt_capab != NULL);
21426 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21427 			/*
21428 			 * If MDT has been previously turned off in the past,
21429 			 * and we currently can do MDT (due to IPQoS policy
21430 			 * removal, etc.) then enable it for this interface.
21431 			 */
21432 			ill->ill_mdt_capab->ill_mdt_on = 1;
21433 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
21434 			    ill->ill_name));
21435 		}
21436 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
21437 		    offset);
21438 		return;
21439 	}
21440 
21441 	/* Get a copy of the header for the trailing frags */
21442 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21443 	if (!hdr_mp) {
21444 		BUMP_MIB(&ip_mib, ipOutDiscards);
21445 		freemsg(mp);
21446 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21447 		    "ip_wput_frag_end:(%S)",
21448 		    "couldn't copy hdr");
21449 		return;
21450 	}
21451 
21452 	/* Store the starting offset, with the MoreFrags flag. */
21453 	i1 = offset | IPH_MF | frag_flag;
21454 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21455 
21456 	/* Establish the ending byte offset, based on the starting offset. */
21457 	offset <<= 3;
21458 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21459 
21460 	/* Store the length of the first fragment in the IP header. */
21461 	i1 = len + hdr_len;
21462 	ASSERT(i1 <= IP_MAXPACKET);
21463 	ipha->ipha_length = htons((uint16_t)i1);
21464 
21465 	/*
21466 	 * Compute the IP header checksum for the first frag.  We have to
21467 	 * watch out that we stop at the end of the header.
21468 	 */
21469 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21470 
21471 	/*
21472 	 * Now carve off the first frag.  Note that this will include the
21473 	 * original IP header.
21474 	 */
21475 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21476 		BUMP_MIB(&ip_mib, ipOutDiscards);
21477 		freeb(hdr_mp);
21478 		freemsg(mp_orig);
21479 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21480 		    "ip_wput_frag_end:(%S)",
21481 		    "couldn't carve first");
21482 		return;
21483 	}
21484 
21485 	/*
21486 	 * Multirouting case. Each fragment is replicated
21487 	 * via all non-condemned RTF_MULTIRT routes
21488 	 * currently resolved.
21489 	 * We ensure that first_ire is the first RTF_MULTIRT
21490 	 * ire in the bucket.
21491 	 */
21492 	if (ire->ire_flags & RTF_MULTIRT) {
21493 		irb = ire->ire_bucket;
21494 		ASSERT(irb != NULL);
21495 
21496 		multirt_send = B_TRUE;
21497 
21498 		/* Make sure we do not omit any multiroute ire. */
21499 		IRB_REFHOLD(irb);
21500 		for (first_ire = irb->irb_ire;
21501 		    first_ire != NULL;
21502 		    first_ire = first_ire->ire_next) {
21503 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21504 			    (first_ire->ire_addr == ire->ire_addr) &&
21505 			    !(first_ire->ire_marks &
21506 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21507 				break;
21508 		}
21509 
21510 		if (first_ire != NULL) {
21511 			if (first_ire != ire) {
21512 				IRE_REFHOLD(first_ire);
21513 				/*
21514 				 * Do not release the ire passed in
21515 				 * as the argument.
21516 				 */
21517 				ire = first_ire;
21518 			} else {
21519 				first_ire = NULL;
21520 			}
21521 		}
21522 		IRB_REFRELE(irb);
21523 
21524 		/*
21525 		 * Save the first ire; we will need to restore it
21526 		 * for the trailing frags.
21527 		 * We REFHOLD save_ire, as each iterated ire will be
21528 		 * REFRELEd.
21529 		 */
21530 		save_ire = ire;
21531 		IRE_REFHOLD(save_ire);
21532 	}
21533 
21534 	/*
21535 	 * First fragment emission loop.
21536 	 * In most cases, the emission loop below is entered only
21537 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21538 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21539 	 * bucket, and send the fragment through all crossed
21540 	 * RTF_MULTIRT routes.
21541 	 */
21542 	do {
21543 		if (ire->ire_flags & RTF_MULTIRT) {
21544 			/*
21545 			 * We are in a multiple send case, need to get
21546 			 * the next ire and make a copy of the packet.
21547 			 * ire1 holds here the next ire to process in the
21548 			 * bucket. If multirouting is expected,
21549 			 * any non-RTF_MULTIRT ire that has the
21550 			 * right destination address is ignored.
21551 			 *
21552 			 * We have to take into account the MTU of
21553 			 * each walked ire. max_frag is set by the
21554 			 * the caller and generally refers to
21555 			 * the primary ire entry. Here we ensure that
21556 			 * no route with a lower MTU will be used, as
21557 			 * fragments are carved once for all ires,
21558 			 * then replicated.
21559 			 */
21560 			ASSERT(irb != NULL);
21561 			IRB_REFHOLD(irb);
21562 			for (ire1 = ire->ire_next;
21563 			    ire1 != NULL;
21564 			    ire1 = ire1->ire_next) {
21565 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21566 					continue;
21567 				if (ire1->ire_addr != ire->ire_addr)
21568 					continue;
21569 				if (ire1->ire_marks &
21570 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21571 					continue;
21572 				/*
21573 				 * Ensure we do not exceed the MTU
21574 				 * of the next route.
21575 				 */
21576 				if (ire1->ire_max_frag < max_frag) {
21577 					ip_multirt_bad_mtu(ire1, max_frag);
21578 					continue;
21579 				}
21580 
21581 				/* Got one. */
21582 				IRE_REFHOLD(ire1);
21583 				break;
21584 			}
21585 			IRB_REFRELE(irb);
21586 
21587 			if (ire1 != NULL) {
21588 				next_mp = copyb(mp);
21589 				if ((next_mp == NULL) ||
21590 				    ((mp->b_cont != NULL) &&
21591 				    ((next_mp->b_cont =
21592 				    dupmsg(mp->b_cont)) == NULL))) {
21593 					freemsg(next_mp);
21594 					next_mp = NULL;
21595 					ire_refrele(ire1);
21596 					ire1 = NULL;
21597 				}
21598 			}
21599 
21600 			/* Last multiroute ire; don't loop anymore. */
21601 			if (ire1 == NULL) {
21602 				multirt_send = B_FALSE;
21603 			}
21604 		}
21605 
21606 		ll_hdr_len = 0;
21607 		LOCK_IRE_FP_MP(ire);
21608 		ll_hdr_mp = ire->ire_fp_mp;
21609 		if (ll_hdr_mp != NULL) {
21610 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21611 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21612 		} else {
21613 			ll_hdr_mp = ire->ire_dlureq_mp;
21614 		}
21615 
21616 		/* If there is a transmit header, get a copy for this frag. */
21617 		/*
21618 		 * TODO: should check db_ref before calling ip_carve_mp since
21619 		 * it might give us a dup.
21620 		 */
21621 		if (!ll_hdr_mp) {
21622 			/* No xmit header. */
21623 			xmit_mp = mp;
21624 		} else if (mp->b_datap->db_ref == 1 &&
21625 		    ll_hdr_len != 0 &&
21626 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21627 			/* M_DATA fastpath */
21628 			mp->b_rptr -= ll_hdr_len;
21629 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21630 			xmit_mp = mp;
21631 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21632 			UNLOCK_IRE_FP_MP(ire);
21633 			BUMP_MIB(&ip_mib, ipOutDiscards);
21634 			freeb(hdr_mp);
21635 			freemsg(mp);
21636 			freemsg(mp_orig);
21637 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21638 			    "ip_wput_frag_end:(%S)",
21639 			    "discard");
21640 
21641 			if (multirt_send) {
21642 				ASSERT(ire1);
21643 				ASSERT(next_mp);
21644 
21645 				freemsg(next_mp);
21646 				ire_refrele(ire1);
21647 			}
21648 			if (save_ire != NULL)
21649 				IRE_REFRELE(save_ire);
21650 
21651 			if (first_ire != NULL)
21652 				ire_refrele(first_ire);
21653 			return;
21654 		} else {
21655 			xmit_mp->b_cont = mp;
21656 			/* Get priority marking, if any. */
21657 			if (DB_TYPE(xmit_mp) == M_DATA)
21658 				xmit_mp->b_band = mp->b_band;
21659 		}
21660 		UNLOCK_IRE_FP_MP(ire);
21661 		q = ire->ire_stq;
21662 		BUMP_MIB(&ip_mib, ipFragCreates);
21663 		putnext(q, xmit_mp);
21664 		if (pkt_type != OB_PKT) {
21665 			/*
21666 			 * Update the packet count of trailing
21667 			 * RTF_MULTIRT ires.
21668 			 */
21669 			UPDATE_OB_PKT_COUNT(ire);
21670 		}
21671 
21672 		if (multirt_send) {
21673 			/*
21674 			 * We are in a multiple send case; look for
21675 			 * the next ire and re-enter the loop.
21676 			 */
21677 			ASSERT(ire1);
21678 			ASSERT(next_mp);
21679 			/* REFRELE the current ire before looping */
21680 			ire_refrele(ire);
21681 			ire = ire1;
21682 			ire1 = NULL;
21683 			mp = next_mp;
21684 			next_mp = NULL;
21685 		}
21686 	} while (multirt_send);
21687 
21688 	ASSERT(ire1 == NULL);
21689 
21690 	/* Restore the original ire; we need it for the trailing frags */
21691 	if (save_ire != NULL) {
21692 		/* REFRELE the last iterated ire */
21693 		ire_refrele(ire);
21694 		/* save_ire has been REFHOLDed */
21695 		ire = save_ire;
21696 		save_ire = NULL;
21697 		q = ire->ire_stq;
21698 	}
21699 
21700 	if (pkt_type == OB_PKT) {
21701 		UPDATE_OB_PKT_COUNT(ire);
21702 	} else {
21703 		UPDATE_IB_PKT_COUNT(ire);
21704 	}
21705 
21706 	/* Advance the offset to the second frag starting point. */
21707 	offset += len;
21708 	/*
21709 	 * Update hdr_len from the copied header - there might be less options
21710 	 * in the later fragments.
21711 	 */
21712 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21713 	/* Loop until done. */
21714 	for (;;) {
21715 		uint16_t	offset_and_flags;
21716 		uint16_t	ip_len;
21717 
21718 		if (ip_data_end - offset > len) {
21719 			/*
21720 			 * Carve off the appropriate amount from the original
21721 			 * datagram.
21722 			 */
21723 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21724 				mp = NULL;
21725 				break;
21726 			}
21727 			/*
21728 			 * More frags after this one.  Get another copy
21729 			 * of the header.
21730 			 */
21731 			if (carve_mp->b_datap->db_ref == 1 &&
21732 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21733 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21734 				/* Inline IP header */
21735 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21736 				    hdr_mp->b_rptr;
21737 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21738 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21739 				mp = carve_mp;
21740 			} else {
21741 				if (!(mp = copyb(hdr_mp))) {
21742 					freemsg(carve_mp);
21743 					break;
21744 				}
21745 				/* Get priority marking, if any. */
21746 				mp->b_band = carve_mp->b_band;
21747 				mp->b_cont = carve_mp;
21748 			}
21749 			ipha = (ipha_t *)mp->b_rptr;
21750 			offset_and_flags = IPH_MF;
21751 		} else {
21752 			/*
21753 			 * Last frag.  Consume the header. Set len to
21754 			 * the length of this last piece.
21755 			 */
21756 			len = ip_data_end - offset;
21757 
21758 			/*
21759 			 * Carve off the appropriate amount from the original
21760 			 * datagram.
21761 			 */
21762 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21763 				mp = NULL;
21764 				break;
21765 			}
21766 			if (carve_mp->b_datap->db_ref == 1 &&
21767 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21768 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21769 				/* Inline IP header */
21770 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21771 				    hdr_mp->b_rptr;
21772 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21773 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21774 				mp = carve_mp;
21775 				freeb(hdr_mp);
21776 				hdr_mp = mp;
21777 			} else {
21778 				mp = hdr_mp;
21779 				/* Get priority marking, if any. */
21780 				mp->b_band = carve_mp->b_band;
21781 				mp->b_cont = carve_mp;
21782 			}
21783 			ipha = (ipha_t *)mp->b_rptr;
21784 			/* A frag of a frag might have IPH_MF non-zero */
21785 			offset_and_flags =
21786 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21787 			    IPH_MF;
21788 		}
21789 		offset_and_flags |= (uint16_t)(offset >> 3);
21790 		offset_and_flags |= (uint16_t)frag_flag;
21791 		/* Store the offset and flags in the IP header. */
21792 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21793 
21794 		/* Store the length in the IP header. */
21795 		ip_len = (uint16_t)(len + hdr_len);
21796 		ipha->ipha_length = htons(ip_len);
21797 
21798 		/*
21799 		 * Set the IP header checksum.	Note that mp is just
21800 		 * the header, so this is easy to pass to ip_csum.
21801 		 */
21802 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21803 
21804 		/* Attach a transmit header, if any, and ship it. */
21805 		if (pkt_type == OB_PKT) {
21806 			UPDATE_OB_PKT_COUNT(ire);
21807 		} else {
21808 			UPDATE_IB_PKT_COUNT(ire);
21809 		}
21810 
21811 		if (ire->ire_flags & RTF_MULTIRT) {
21812 			irb = ire->ire_bucket;
21813 			ASSERT(irb != NULL);
21814 
21815 			multirt_send = B_TRUE;
21816 
21817 			/*
21818 			 * Save the original ire; we will need to restore it
21819 			 * for the tailing frags.
21820 			 */
21821 			save_ire = ire;
21822 			IRE_REFHOLD(save_ire);
21823 		}
21824 		/*
21825 		 * Emission loop for this fragment, similar
21826 		 * to what is done for the first fragment.
21827 		 */
21828 		do {
21829 			if (multirt_send) {
21830 				/*
21831 				 * We are in a multiple send case, need to get
21832 				 * the next ire and make a copy of the packet.
21833 				 */
21834 				ASSERT(irb != NULL);
21835 				IRB_REFHOLD(irb);
21836 				for (ire1 = ire->ire_next;
21837 				    ire1 != NULL;
21838 				    ire1 = ire1->ire_next) {
21839 					if (!(ire1->ire_flags & RTF_MULTIRT))
21840 						continue;
21841 					if (ire1->ire_addr != ire->ire_addr)
21842 						continue;
21843 					if (ire1->ire_marks &
21844 					    (IRE_MARK_CONDEMNED|
21845 						IRE_MARK_HIDDEN))
21846 						continue;
21847 					/*
21848 					 * Ensure we do not exceed the MTU
21849 					 * of the next route.
21850 					 */
21851 					if (ire1->ire_max_frag < max_frag) {
21852 						ip_multirt_bad_mtu(ire1,
21853 						    max_frag);
21854 						continue;
21855 					}
21856 
21857 					/* Got one. */
21858 					IRE_REFHOLD(ire1);
21859 					break;
21860 				}
21861 				IRB_REFRELE(irb);
21862 
21863 				if (ire1 != NULL) {
21864 					next_mp = copyb(mp);
21865 					if ((next_mp == NULL) ||
21866 					    ((mp->b_cont != NULL) &&
21867 					    ((next_mp->b_cont =
21868 					    dupmsg(mp->b_cont)) == NULL))) {
21869 						freemsg(next_mp);
21870 						next_mp = NULL;
21871 						ire_refrele(ire1);
21872 						ire1 = NULL;
21873 					}
21874 				}
21875 
21876 				/* Last multiroute ire; don't loop anymore. */
21877 				if (ire1 == NULL) {
21878 					multirt_send = B_FALSE;
21879 				}
21880 			}
21881 
21882 			/* Update transmit header */
21883 			ll_hdr_len = 0;
21884 			LOCK_IRE_FP_MP(ire);
21885 			ll_hdr_mp = ire->ire_fp_mp;
21886 			if (ll_hdr_mp != NULL) {
21887 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21888 				ll_hdr_len = MBLKL(ll_hdr_mp);
21889 			} else {
21890 				ll_hdr_mp = ire->ire_dlureq_mp;
21891 			}
21892 
21893 			if (!ll_hdr_mp) {
21894 				xmit_mp = mp;
21895 			} else if (mp->b_datap->db_ref == 1 &&
21896 			    ll_hdr_len != 0 &&
21897 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21898 				/* M_DATA fastpath */
21899 				mp->b_rptr -= ll_hdr_len;
21900 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
21901 				    ll_hdr_len);
21902 				xmit_mp = mp;
21903 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
21904 				xmit_mp->b_cont = mp;
21905 				/* Get priority marking, if any. */
21906 				if (DB_TYPE(xmit_mp) == M_DATA)
21907 					xmit_mp->b_band = mp->b_band;
21908 			} else {
21909 				/*
21910 				 * Exit both the replication and
21911 				 * fragmentation loops.
21912 				 */
21913 				UNLOCK_IRE_FP_MP(ire);
21914 				goto drop_pkt;
21915 			}
21916 			UNLOCK_IRE_FP_MP(ire);
21917 			BUMP_MIB(&ip_mib, ipFragCreates);
21918 			putnext(q, xmit_mp);
21919 
21920 			if (pkt_type != OB_PKT) {
21921 				/*
21922 				 * Update the packet count of trailing
21923 				 * RTF_MULTIRT ires.
21924 				 */
21925 				UPDATE_OB_PKT_COUNT(ire);
21926 			}
21927 
21928 			/* All done if we just consumed the hdr_mp. */
21929 			if (mp == hdr_mp) {
21930 				last_frag = B_TRUE;
21931 			}
21932 
21933 			if (multirt_send) {
21934 				/*
21935 				 * We are in a multiple send case; look for
21936 				 * the next ire and re-enter the loop.
21937 				 */
21938 				ASSERT(ire1);
21939 				ASSERT(next_mp);
21940 				/* REFRELE the current ire before looping */
21941 				ire_refrele(ire);
21942 				ire = ire1;
21943 				ire1 = NULL;
21944 				q = ire->ire_stq;
21945 				mp = next_mp;
21946 				next_mp = NULL;
21947 			}
21948 		} while (multirt_send);
21949 		/*
21950 		 * Restore the original ire; we need it for the
21951 		 * trailing frags
21952 		 */
21953 		if (save_ire != NULL) {
21954 			ASSERT(ire1 == NULL);
21955 			/* REFRELE the last iterated ire */
21956 			ire_refrele(ire);
21957 			/* save_ire has been REFHOLDed */
21958 			ire = save_ire;
21959 			q = ire->ire_stq;
21960 			save_ire = NULL;
21961 		}
21962 
21963 		if (last_frag) {
21964 			BUMP_MIB(&ip_mib, ipFragOKs);
21965 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21966 			    "ip_wput_frag_end:(%S)",
21967 			    "consumed hdr_mp");
21968 
21969 			if (first_ire != NULL)
21970 				ire_refrele(first_ire);
21971 			return;
21972 		}
21973 		/* Otherwise, advance and loop. */
21974 		offset += len;
21975 	}
21976 
21977 drop_pkt:
21978 	/* Clean up following allocation failure. */
21979 	BUMP_MIB(&ip_mib, ipOutDiscards);
21980 	freemsg(mp);
21981 	if (mp != hdr_mp)
21982 		freeb(hdr_mp);
21983 	if (mp != mp_orig)
21984 		freemsg(mp_orig);
21985 
21986 	if (save_ire != NULL)
21987 		IRE_REFRELE(save_ire);
21988 	if (first_ire != NULL)
21989 		ire_refrele(first_ire);
21990 
21991 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21992 	    "ip_wput_frag_end:(%S)",
21993 	    "end--alloc failure");
21994 }
21995 
21996 /*
21997  * Copy the header plus those options which have the copy bit set
21998  */
21999 static mblk_t *
22000 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22001 {
22002 	mblk_t	*mp;
22003 	uchar_t	*up;
22004 
22005 	/*
22006 	 * Quick check if we need to look for options without the copy bit
22007 	 * set
22008 	 */
22009 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22010 	if (!mp)
22011 		return (mp);
22012 	mp->b_rptr += ip_wroff_extra;
22013 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22014 		bcopy(rptr, mp->b_rptr, hdr_len);
22015 		mp->b_wptr += hdr_len + ip_wroff_extra;
22016 		return (mp);
22017 	}
22018 	up  = mp->b_rptr;
22019 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22020 	up += IP_SIMPLE_HDR_LENGTH;
22021 	rptr += IP_SIMPLE_HDR_LENGTH;
22022 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22023 	while (hdr_len > 0) {
22024 		uint32_t optval;
22025 		uint32_t optlen;
22026 
22027 		optval = *rptr;
22028 		if (optval == IPOPT_EOL)
22029 			break;
22030 		if (optval == IPOPT_NOP)
22031 			optlen = 1;
22032 		else
22033 			optlen = rptr[1];
22034 		if (optval & IPOPT_COPY) {
22035 			bcopy(rptr, up, optlen);
22036 			up += optlen;
22037 		}
22038 		rptr += optlen;
22039 		hdr_len -= optlen;
22040 	}
22041 	/*
22042 	 * Make sure that we drop an even number of words by filling
22043 	 * with EOL to the next word boundary.
22044 	 */
22045 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
22046 	    hdr_len & 0x3; hdr_len++)
22047 		*up++ = IPOPT_EOL;
22048 	mp->b_wptr = up;
22049 	/* Update header length */
22050 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
22051 	return (mp);
22052 }
22053 
22054 /*
22055  * Delivery to local recipients including fanout to multiple recipients.
22056  * Does not do checksumming of UDP/TCP.
22057  * Note: q should be the read side queue for either the ill or conn.
22058  * Note: rq should be the read side q for the lower (ill) stream.
22059  * We don't send packets to IPPF processing, thus the last argument
22060  * to all the fanout calls are B_FALSE.
22061  */
22062 void
22063 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
22064     int fanout_flags, zoneid_t zoneid)
22065 {
22066 	uint32_t	protocol;
22067 	mblk_t		*first_mp;
22068 	boolean_t	mctl_present;
22069 	int		ire_type;
22070 #define	rptr	((uchar_t *)ipha)
22071 
22072 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
22073 	    "ip_wput_local_start: q %p", q);
22074 
22075 	if (ire != NULL) {
22076 		ire_type = ire->ire_type;
22077 	} else {
22078 		/*
22079 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
22080 		 * packet is not multicast, we can't tell the ire type.
22081 		 */
22082 		ASSERT(CLASSD(ipha->ipha_dst));
22083 		ire_type = IRE_BROADCAST;
22084 	}
22085 
22086 	first_mp = mp;
22087 	if (first_mp->b_datap->db_type == M_CTL) {
22088 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
22089 		if (!io->ipsec_out_secure) {
22090 			/*
22091 			 * This ipsec_out_t was allocated in ip_wput
22092 			 * for multicast packets to store the ill_index.
22093 			 * As this is being delivered locally, we don't
22094 			 * need this anymore.
22095 			 */
22096 			mp = first_mp->b_cont;
22097 			freeb(first_mp);
22098 			first_mp = mp;
22099 			mctl_present = B_FALSE;
22100 		} else {
22101 			mctl_present = B_TRUE;
22102 			mp = first_mp->b_cont;
22103 			ASSERT(mp != NULL);
22104 			ipsec_out_to_in(first_mp);
22105 		}
22106 	} else {
22107 		mctl_present = B_FALSE;
22108 	}
22109 
22110 	loopback_packets++;
22111 
22112 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
22113 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
22114 	if (!IS_SIMPLE_IPH(ipha)) {
22115 		ip_wput_local_options(ipha);
22116 	}
22117 
22118 	protocol = ipha->ipha_protocol;
22119 	switch (protocol) {
22120 	case IPPROTO_ICMP: {
22121 		ire_t		*ire_zone;
22122 		ilm_t		*ilm;
22123 		mblk_t		*mp1;
22124 		zoneid_t	last_zoneid;
22125 
22126 		if (CLASSD(ipha->ipha_dst) &&
22127 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
22128 			ASSERT(ire_type == IRE_BROADCAST);
22129 			/*
22130 			 * In the multicast case, applications may have joined
22131 			 * the group from different zones, so we need to deliver
22132 			 * the packet to each of them. Loop through the
22133 			 * multicast memberships structures (ilm) on the receive
22134 			 * ill and send a copy of the packet up each matching
22135 			 * one. However, we don't do this for multicasts sent on
22136 			 * the loopback interface (PHYI_LOOPBACK flag set) as
22137 			 * they must stay in the sender's zone.
22138 			 *
22139 			 * ilm_add_v6() ensures that ilms in the same zone are
22140 			 * contiguous in the ill_ilm list. We use this property
22141 			 * to avoid sending duplicates needed when two
22142 			 * applications in the same zone join the same group on
22143 			 * different logical interfaces: we ignore the ilm if
22144 			 * its zoneid is the same as the last matching one.
22145 			 * In addition, the sending of the packet for
22146 			 * ire_zoneid is delayed until all of the other ilms
22147 			 * have been exhausted.
22148 			 */
22149 			last_zoneid = -1;
22150 			ILM_WALKER_HOLD(ill);
22151 			for (ilm = ill->ill_ilm; ilm != NULL;
22152 			    ilm = ilm->ilm_next) {
22153 				if ((ilm->ilm_flags & ILM_DELETED) ||
22154 				    ipha->ipha_dst != ilm->ilm_addr ||
22155 				    ilm->ilm_zoneid == last_zoneid ||
22156 				    ilm->ilm_zoneid == zoneid ||
22157 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
22158 					continue;
22159 				mp1 = ip_copymsg(first_mp);
22160 				if (mp1 == NULL)
22161 					continue;
22162 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22163 				    mctl_present, B_FALSE, ill,
22164 				    ilm->ilm_zoneid);
22165 				last_zoneid = ilm->ilm_zoneid;
22166 			}
22167 			ILM_WALKER_RELE(ill);
22168 			/*
22169 			 * Loopback case: the sending endpoint has
22170 			 * IP_MULTICAST_LOOP disabled, therefore we don't
22171 			 * dispatch the multicast packet to the sending zone.
22172 			 */
22173 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
22174 				freemsg(first_mp);
22175 				return;
22176 			}
22177 		} else if (ire_type == IRE_BROADCAST) {
22178 			/*
22179 			 * In the broadcast case, there may be many zones
22180 			 * which need a copy of the packet delivered to them.
22181 			 * There is one IRE_BROADCAST per broadcast address
22182 			 * and per zone; we walk those using a helper function.
22183 			 * In addition, the sending of the packet for zoneid is
22184 			 * delayed until all of the other ires have been
22185 			 * processed.
22186 			 */
22187 			IRB_REFHOLD(ire->ire_bucket);
22188 			ire_zone = NULL;
22189 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
22190 			    ire)) != NULL) {
22191 				mp1 = ip_copymsg(first_mp);
22192 				if (mp1 == NULL)
22193 					continue;
22194 
22195 				UPDATE_IB_PKT_COUNT(ire_zone);
22196 				ire_zone->ire_last_used_time = lbolt;
22197 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22198 				    mctl_present, B_FALSE, ill,
22199 				    ire_zone->ire_zoneid);
22200 			}
22201 			IRB_REFRELE(ire->ire_bucket);
22202 		}
22203 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
22204 		    0, mctl_present, B_FALSE, ill, zoneid);
22205 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22206 		    "ip_wput_local_end: q %p (%S)",
22207 		    q, "icmp");
22208 		return;
22209 	}
22210 	case IPPROTO_IGMP:
22211 		if (igmp_input(q, mp, ill)) {
22212 			/* Bad packet - discarded by igmp_input */
22213 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22214 			    "ip_wput_local_end: q %p (%S)",
22215 			    q, "igmp_input--bad packet");
22216 			if (mctl_present)
22217 				freeb(first_mp);
22218 			return;
22219 		}
22220 		/*
22221 		 * igmp_input() may have pulled up the message so ipha needs to
22222 		 * be reinitialized.
22223 		 */
22224 		ipha = (ipha_t *)mp->b_rptr;
22225 		/* deliver to local raw users */
22226 		break;
22227 	case IPPROTO_ENCAP:
22228 		/*
22229 		 * This case is covered by either ip_fanout_proto, or by
22230 		 * the above security processing for self-tunneled packets.
22231 		 */
22232 		break;
22233 	case IPPROTO_UDP: {
22234 		uint16_t	*up;
22235 		uint32_t	ports;
22236 
22237 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
22238 		    UDP_PORTS_OFFSET);
22239 		/* Force a 'valid' checksum. */
22240 		up[3] = 0;
22241 
22242 		ports = *(uint32_t *)up;
22243 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
22244 		    (ire_type == IRE_BROADCAST),
22245 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22246 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
22247 		    ill, zoneid);
22248 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22249 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
22250 		return;
22251 	}
22252 	case IPPROTO_TCP: {
22253 
22254 		/*
22255 		 * For TCP, discard broadcast packets.
22256 		 */
22257 		if ((ushort_t)ire_type == IRE_BROADCAST) {
22258 			freemsg(first_mp);
22259 			BUMP_MIB(&ip_mib, ipInDiscards);
22260 			return;
22261 		}
22262 
22263 		if (mp->b_datap->db_type == M_DATA) {
22264 			/*
22265 			 * M_DATA mblk, so init mblk (chain) for no struio().
22266 			 */
22267 			mblk_t	*mp1 = mp;
22268 
22269 			do
22270 				mp1->b_datap->db_struioflag = 0;
22271 			while ((mp1 = mp1->b_cont) != NULL);
22272 		}
22273 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
22274 		    <= mp->b_wptr);
22275 		ip_fanout_tcp(q, first_mp, ill, ipha,
22276 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22277 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
22278 		    mctl_present, B_FALSE, zoneid);
22279 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22280 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
22281 		return;
22282 	}
22283 	case IPPROTO_SCTP:
22284 	{
22285 		uint32_t	ports;
22286 
22287 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
22288 		ip_fanout_sctp(first_mp, ill, ipha, ports,
22289 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22290 		    IP_FF_IP6INFO,
22291 		    mctl_present, B_FALSE, 0, zoneid);
22292 		return;
22293 	}
22294 
22295 	default:
22296 		break;
22297 	}
22298 	/*
22299 	 * Find a client for some other protocol.  We give
22300 	 * copies to multiple clients, if more than one is
22301 	 * bound.
22302 	 */
22303 	ip_fanout_proto(q, first_mp, ill, ipha,
22304 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
22305 	    mctl_present, B_FALSE, ill, zoneid);
22306 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22307 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
22308 #undef	rptr
22309 }
22310 
22311 /*
22312  * Update any source route, record route, or timestamp options.
22313  * Check that we are at end of strict source route.
22314  * The options have been sanity checked by ip_wput_options().
22315  */
22316 static void
22317 ip_wput_local_options(ipha_t *ipha)
22318 {
22319 	ipoptp_t	opts;
22320 	uchar_t		*opt;
22321 	uint8_t		optval;
22322 	uint8_t		optlen;
22323 	ipaddr_t	dst;
22324 	uint32_t	ts;
22325 	ire_t		*ire;
22326 	timestruc_t	now;
22327 
22328 	ip2dbg(("ip_wput_local_options\n"));
22329 	for (optval = ipoptp_first(&opts, ipha);
22330 	    optval != IPOPT_EOL;
22331 	    optval = ipoptp_next(&opts)) {
22332 		opt = opts.ipoptp_cur;
22333 		optlen = opts.ipoptp_len;
22334 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22335 		switch (optval) {
22336 			uint32_t off;
22337 		case IPOPT_SSRR:
22338 		case IPOPT_LSRR:
22339 			off = opt[IPOPT_OFFSET];
22340 			off--;
22341 			if (optlen < IP_ADDR_LEN ||
22342 			    off > optlen - IP_ADDR_LEN) {
22343 				/* End of source route */
22344 				break;
22345 			}
22346 			/*
22347 			 * This will only happen if two consecutive entries
22348 			 * in the source route contains our address or if
22349 			 * it is a packet with a loose source route which
22350 			 * reaches us before consuming the whole source route
22351 			 */
22352 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22353 			if (optval == IPOPT_SSRR) {
22354 				return;
22355 			}
22356 			/*
22357 			 * Hack: instead of dropping the packet truncate the
22358 			 * source route to what has been used by filling the
22359 			 * rest with IPOPT_NOP.
22360 			 */
22361 			opt[IPOPT_OLEN] = (uint8_t)off;
22362 			while (off < optlen) {
22363 				opt[off++] = IPOPT_NOP;
22364 			}
22365 			break;
22366 		case IPOPT_RR:
22367 			off = opt[IPOPT_OFFSET];
22368 			off--;
22369 			if (optlen < IP_ADDR_LEN ||
22370 			    off > optlen - IP_ADDR_LEN) {
22371 				/* No more room - ignore */
22372 				ip1dbg((
22373 				    "ip_wput_forward_options: end of RR\n"));
22374 				break;
22375 			}
22376 			dst = htonl(INADDR_LOOPBACK);
22377 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22378 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22379 			break;
22380 		case IPOPT_TS:
22381 			/* Insert timestamp if there is romm */
22382 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22383 			case IPOPT_TS_TSONLY:
22384 				off = IPOPT_TS_TIMELEN;
22385 				break;
22386 			case IPOPT_TS_PRESPEC:
22387 			case IPOPT_TS_PRESPEC_RFC791:
22388 				/* Verify that the address matched */
22389 				off = opt[IPOPT_OFFSET] - 1;
22390 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22391 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22392 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22393 				if (ire == NULL) {
22394 					/* Not for us */
22395 					break;
22396 				}
22397 				ire_refrele(ire);
22398 				/* FALLTHRU */
22399 			case IPOPT_TS_TSANDADDR:
22400 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22401 				break;
22402 			default:
22403 				/*
22404 				 * ip_*put_options should have already
22405 				 * dropped this packet.
22406 				 */
22407 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22408 				    "unknown IT - bug in ip_wput_options?\n");
22409 				return;	/* Keep "lint" happy */
22410 			}
22411 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22412 				/* Increase overflow counter */
22413 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22414 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22415 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22416 				    (off << 4);
22417 				break;
22418 			}
22419 			off = opt[IPOPT_OFFSET] - 1;
22420 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22421 			case IPOPT_TS_PRESPEC:
22422 			case IPOPT_TS_PRESPEC_RFC791:
22423 			case IPOPT_TS_TSANDADDR:
22424 				dst = htonl(INADDR_LOOPBACK);
22425 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22426 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22427 				/* FALLTHRU */
22428 			case IPOPT_TS_TSONLY:
22429 				off = opt[IPOPT_OFFSET] - 1;
22430 				/* Compute # of milliseconds since midnight */
22431 				gethrestime(&now);
22432 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22433 				    now.tv_nsec / (NANOSEC / MILLISEC);
22434 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22435 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22436 				break;
22437 			}
22438 			break;
22439 		}
22440 	}
22441 }
22442 
22443 /*
22444  * Send out a multicast packet on interface ipif.
22445  * The sender does not have an conn.
22446  * Caller verifies that this isn't a PHYI_LOOPBACK.
22447  */
22448 void
22449 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22450 {
22451 	ipha_t	*ipha;
22452 	ire_t	*ire;
22453 	ipaddr_t	dst;
22454 	mblk_t		*first_mp;
22455 
22456 	/* igmp_sendpkt always allocates a ipsec_out_t */
22457 	ASSERT(mp->b_datap->db_type == M_CTL);
22458 	ASSERT(!ipif->ipif_isv6);
22459 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22460 
22461 	first_mp = mp;
22462 	mp = first_mp->b_cont;
22463 	ASSERT(mp->b_datap->db_type == M_DATA);
22464 	ipha = (ipha_t *)mp->b_rptr;
22465 
22466 	/*
22467 	 * Find an IRE which matches the destination and the outgoing
22468 	 * queue (i.e. the outgoing interface.)
22469 	 */
22470 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22471 		dst = ipif->ipif_pp_dst_addr;
22472 	else
22473 		dst = ipha->ipha_dst;
22474 	/*
22475 	 * The source address has already been initialized by the
22476 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22477 	 * be sufficient rather than MATCH_IRE_IPIF.
22478 	 *
22479 	 * This function is used for sending IGMP packets. We need
22480 	 * to make sure that we send the packet out of the interface
22481 	 * (ipif->ipif_ill) where we joined the group. This is to
22482 	 * prevent from switches doing IGMP snooping to send us multicast
22483 	 * packets for a given group on the interface we have joined.
22484 	 * If we can't find an ire, igmp_sendpkt has already initialized
22485 	 * ipsec_out_attach_if so that this will not be load spread in
22486 	 * ip_newroute_ipif.
22487 	 */
22488 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22489 	if (!ire) {
22490 		/*
22491 		 * Mark this packet to make it be delivered to
22492 		 * ip_wput_ire after the new ire has been
22493 		 * created.
22494 		 */
22495 		mp->b_prev = NULL;
22496 		mp->b_next = NULL;
22497 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22498 		return;
22499 	}
22500 
22501 	/*
22502 	 * Honor the RTF_SETSRC flag; this is the only case
22503 	 * where we force this addr whatever the current src addr is,
22504 	 * because this address is set by igmp_sendpkt(), and
22505 	 * cannot be specified by any user.
22506 	 */
22507 	if (ire->ire_flags & RTF_SETSRC) {
22508 		ipha->ipha_src = ire->ire_src_addr;
22509 	}
22510 
22511 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22512 }
22513 
22514 /*
22515  * NOTE : This function does not ire_refrele the ire argument passed in.
22516  *
22517  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22518  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22519  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22520  * the ire_lock to access the ire_fp_mp in this case.
22521  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22522  * prepending a fastpath message IPQoS processing must precede it, we also set
22523  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22524  * (IPQoS might have set the b_band for CoS marking).
22525  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22526  * must follow it so that IPQoS can mark the dl_priority field for CoS
22527  * marking, if needed.
22528  */
22529 static mblk_t *
22530 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22531 {
22532 	uint_t	hlen;
22533 	ipha_t *ipha;
22534 	mblk_t *mp1;
22535 	boolean_t qos_done = B_FALSE;
22536 	uchar_t	*ll_hdr;
22537 
22538 #define	rptr	((uchar_t *)ipha)
22539 
22540 	ipha = (ipha_t *)mp->b_rptr;
22541 	hlen = 0;
22542 	LOCK_IRE_FP_MP(ire);
22543 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22544 		ASSERT(DB_TYPE(mp1) == M_DATA);
22545 		/* Initiate IPPF processing */
22546 		if ((proc != 0) && IPP_ENABLED(proc)) {
22547 			UNLOCK_IRE_FP_MP(ire);
22548 			ip_process(proc, &mp, ill_index);
22549 			if (mp == NULL)
22550 				return (NULL);
22551 
22552 			ipha = (ipha_t *)mp->b_rptr;
22553 			LOCK_IRE_FP_MP(ire);
22554 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22555 				qos_done = B_TRUE;
22556 				goto no_fp_mp;
22557 			}
22558 			ASSERT(DB_TYPE(mp1) == M_DATA);
22559 		}
22560 		hlen = MBLKL(mp1);
22561 		/*
22562 		 * Check if we have enough room to prepend fastpath
22563 		 * header
22564 		 */
22565 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22566 			ll_hdr = rptr - hlen;
22567 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22568 			/* XXX ipha is not aligned here */
22569 			ipha = (ipha_t *)(rptr - hlen);
22570 			/*
22571 			 * Set the b_rptr to the start of the link layer
22572 			 * header
22573 			 */
22574 			mp->b_rptr = rptr;
22575 			mp1 = mp;
22576 		} else {
22577 			mp1 = copyb(mp1);
22578 			if (mp1 == NULL)
22579 				goto unlock_err;
22580 			mp1->b_band = mp->b_band;
22581 			mp1->b_cont = mp;
22582 			/*
22583 			 * XXX disable ICK_VALID and compute checksum
22584 			 * here; can happen if ire_fp_mp changes and
22585 			 * it can't be copied now due to insufficient
22586 			 * space. (unlikely, fp mp can change, but it
22587 			 * does not increase in length)
22588 			 */
22589 		}
22590 		UNLOCK_IRE_FP_MP(ire);
22591 	} else {
22592 no_fp_mp:
22593 		mp1 = copyb(ire->ire_dlureq_mp);
22594 		if (mp1 == NULL) {
22595 unlock_err:
22596 			UNLOCK_IRE_FP_MP(ire);
22597 			freemsg(mp);
22598 			return (NULL);
22599 		}
22600 		UNLOCK_IRE_FP_MP(ire);
22601 		mp1->b_cont = mp;
22602 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22603 			ip_process(proc, &mp1, ill_index);
22604 			if (mp1 == NULL)
22605 				return (NULL);
22606 		}
22607 	}
22608 	return (mp1);
22609 #undef rptr
22610 }
22611 
22612 /*
22613  * Finish the outbound IPsec processing for an IPv6 packet. This function
22614  * is called from ipsec_out_process() if the IPsec packet was processed
22615  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22616  * asynchronously.
22617  */
22618 void
22619 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22620     ire_t *ire_arg)
22621 {
22622 	in6_addr_t *v6dstp;
22623 	ire_t *ire;
22624 	mblk_t *mp;
22625 	uint_t	ill_index;
22626 	ipsec_out_t *io;
22627 	boolean_t attach_if, hwaccel;
22628 	uint32_t flags = IP6_NO_IPPOLICY;
22629 	int match_flags;
22630 	zoneid_t zoneid;
22631 	boolean_t ill_need_rele = B_FALSE;
22632 	boolean_t ire_need_rele = B_FALSE;
22633 
22634 	mp = ipsec_mp->b_cont;
22635 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22636 	ill_index = io->ipsec_out_ill_index;
22637 	if (io->ipsec_out_reachable) {
22638 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22639 	}
22640 	attach_if = io->ipsec_out_attach_if;
22641 	hwaccel = io->ipsec_out_accelerated;
22642 	zoneid = io->ipsec_out_zoneid;
22643 	ASSERT(zoneid != ALL_ZONES);
22644 	match_flags = MATCH_IRE_ILL_GROUP;
22645 	/* Multicast addresses should have non-zero ill_index. */
22646 	v6dstp = &ip6h->ip6_dst;
22647 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22648 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22649 	ASSERT(!attach_if || ill_index != 0);
22650 	if (ill_index != 0) {
22651 		if (ill == NULL) {
22652 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22653 			    B_TRUE);
22654 
22655 			/* Failure case frees things for us. */
22656 			if (ill == NULL)
22657 				return;
22658 
22659 			ill_need_rele = B_TRUE;
22660 		}
22661 		/*
22662 		 * If this packet needs to go out on a particular interface
22663 		 * honor it.
22664 		 */
22665 		if (attach_if) {
22666 			match_flags = MATCH_IRE_ILL;
22667 
22668 			/*
22669 			 * Check if we need an ire that will not be
22670 			 * looked up by anybody else i.e. HIDDEN.
22671 			 */
22672 			if (ill_is_probeonly(ill)) {
22673 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22674 			}
22675 		}
22676 	}
22677 	ASSERT(mp != NULL);
22678 
22679 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22680 		boolean_t unspec_src;
22681 		ipif_t	*ipif;
22682 
22683 		/*
22684 		 * Use the ill_index to get the right ill.
22685 		 */
22686 		unspec_src = io->ipsec_out_unspec_src;
22687 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22688 		if (ipif == NULL) {
22689 			if (ill_need_rele)
22690 				ill_refrele(ill);
22691 			freemsg(ipsec_mp);
22692 			return;
22693 		}
22694 
22695 		if (ire_arg != NULL) {
22696 			ire = ire_arg;
22697 		} else {
22698 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22699 			    zoneid, match_flags);
22700 			ire_need_rele = B_TRUE;
22701 		}
22702 		if (ire != NULL) {
22703 			ipif_refrele(ipif);
22704 			/*
22705 			 * XXX Do the multicast forwarding now, as the IPSEC
22706 			 * processing has been done.
22707 			 */
22708 			goto send;
22709 		}
22710 
22711 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22712 		mp->b_prev = NULL;
22713 		mp->b_next = NULL;
22714 
22715 		/*
22716 		 * If the IPsec packet was processed asynchronously,
22717 		 * drop it now.
22718 		 */
22719 		if (q == NULL) {
22720 			if (ill_need_rele)
22721 				ill_refrele(ill);
22722 			freemsg(ipsec_mp);
22723 			return;
22724 		}
22725 
22726 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22727 		    unspec_src, zoneid);
22728 		ipif_refrele(ipif);
22729 	} else {
22730 		if (attach_if) {
22731 			ipif_t	*ipif;
22732 
22733 			ipif = ipif_get_next_ipif(NULL, ill);
22734 			if (ipif == NULL) {
22735 				if (ill_need_rele)
22736 					ill_refrele(ill);
22737 				freemsg(ipsec_mp);
22738 				return;
22739 			}
22740 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22741 			    zoneid, match_flags);
22742 			ire_need_rele = B_TRUE;
22743 			ipif_refrele(ipif);
22744 		} else {
22745 			if (ire_arg != NULL) {
22746 				ire = ire_arg;
22747 			} else {
22748 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22749 				ire_need_rele = B_TRUE;
22750 			}
22751 		}
22752 		if (ire != NULL)
22753 			goto send;
22754 		/*
22755 		 * ire disappeared underneath.
22756 		 *
22757 		 * What we need to do here is the ip_newroute
22758 		 * logic to get the ire without doing the IPSEC
22759 		 * processing. Follow the same old path. But this
22760 		 * time, ip_wput or ire_add_then_send will call us
22761 		 * directly as all the IPSEC operations are done.
22762 		 */
22763 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22764 		mp->b_prev = NULL;
22765 		mp->b_next = NULL;
22766 
22767 		/*
22768 		 * If the IPsec packet was processed asynchronously,
22769 		 * drop it now.
22770 		 */
22771 		if (q == NULL) {
22772 			if (ill_need_rele)
22773 				ill_refrele(ill);
22774 			freemsg(ipsec_mp);
22775 			return;
22776 		}
22777 
22778 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22779 		    zoneid);
22780 	}
22781 	if (ill != NULL && ill_need_rele)
22782 		ill_refrele(ill);
22783 	return;
22784 send:
22785 	if (ill != NULL && ill_need_rele)
22786 		ill_refrele(ill);
22787 
22788 	/* Local delivery */
22789 	if (ire->ire_stq == NULL) {
22790 		ASSERT(q != NULL);
22791 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22792 		    ire, 0);
22793 		if (ire_need_rele)
22794 			ire_refrele(ire);
22795 		return;
22796 	}
22797 	/*
22798 	 * Everything is done. Send it out on the wire.
22799 	 * We force the insertion of a fragment header using the
22800 	 * IPH_FRAG_HDR flag in two cases:
22801 	 * - after reception of an ICMPv6 "packet too big" message
22802 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22803 	 * - for multirouted IPv6 packets, so that the receiver can
22804 	 *   discard duplicates according to their fragment identifier
22805 	 */
22806 	/* XXX fix flow control problems. */
22807 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22808 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22809 		if (hwaccel) {
22810 			/*
22811 			 * hardware acceleration does not handle these
22812 			 * "slow path" cases.
22813 			 */
22814 			/* IPsec KSTATS: should bump bean counter here. */
22815 			if (ire_need_rele)
22816 				ire_refrele(ire);
22817 			freemsg(ipsec_mp);
22818 			return;
22819 		}
22820 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22821 		    (mp->b_cont ? msgdsize(mp) :
22822 		    mp->b_wptr - (uchar_t *)ip6h)) {
22823 			/* IPsec KSTATS: should bump bean counter here. */
22824 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22825 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22826 			    msgdsize(mp)));
22827 			if (ire_need_rele)
22828 				ire_refrele(ire);
22829 			freemsg(ipsec_mp);
22830 			return;
22831 		}
22832 		ASSERT(mp->b_prev == NULL);
22833 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22834 		    ntohs(ip6h->ip6_plen) +
22835 		    IPV6_HDR_LEN, ire->ire_max_frag));
22836 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22837 		    ire->ire_max_frag);
22838 	} else {
22839 		UPDATE_OB_PKT_COUNT(ire);
22840 		ire->ire_last_used_time = lbolt;
22841 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22842 	}
22843 	if (ire_need_rele)
22844 		ire_refrele(ire);
22845 	freeb(ipsec_mp);
22846 }
22847 
22848 void
22849 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
22850 {
22851 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
22852 	da_ipsec_t *hada;	/* data attributes */
22853 	ill_t *ill = (ill_t *)q->q_ptr;
22854 
22855 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
22856 
22857 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
22858 		/* IPsec KSTATS: Bump lose counter here! */
22859 		freemsg(mp);
22860 		return;
22861 	}
22862 
22863 	/*
22864 	 * It's an IPsec packet that must be
22865 	 * accelerated by the Provider, and the
22866 	 * outbound ill is IPsec acceleration capable.
22867 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
22868 	 * to the ill.
22869 	 * IPsec KSTATS: should bump packet counter here.
22870 	 */
22871 
22872 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
22873 	if (hada_mp == NULL) {
22874 		/* IPsec KSTATS: should bump packet counter here. */
22875 		freemsg(mp);
22876 		return;
22877 	}
22878 
22879 	hada_mp->b_datap->db_type = M_CTL;
22880 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
22881 	hada_mp->b_cont = mp;
22882 
22883 	hada = (da_ipsec_t *)hada_mp->b_rptr;
22884 	bzero(hada, sizeof (da_ipsec_t));
22885 	hada->da_type = IPHADA_M_CTL;
22886 
22887 	putnext(q, hada_mp);
22888 }
22889 
22890 /*
22891  * Finish the outbound IPsec processing. This function is called from
22892  * ipsec_out_process() if the IPsec packet was processed
22893  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22894  * asynchronously.
22895  */
22896 void
22897 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
22898     ire_t *ire_arg)
22899 {
22900 	uint32_t v_hlen_tos_len;
22901 	ipaddr_t	dst;
22902 	ipif_t	*ipif = NULL;
22903 	ire_t *ire;
22904 	ire_t *ire1 = NULL;
22905 	mblk_t *next_mp = NULL;
22906 	uint32_t max_frag;
22907 	boolean_t multirt_send = B_FALSE;
22908 	mblk_t *mp;
22909 	mblk_t *mp1;
22910 	uint_t	ill_index;
22911 	ipsec_out_t *io;
22912 	boolean_t attach_if;
22913 	int match_flags, offset;
22914 	irb_t *irb = NULL;
22915 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
22916 	zoneid_t zoneid;
22917 	uint32_t cksum;
22918 	uint16_t *up;
22919 #ifdef	_BIG_ENDIAN
22920 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22921 #else
22922 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22923 #endif
22924 
22925 	mp = ipsec_mp->b_cont;
22926 	ASSERT(mp != NULL);
22927 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22928 	dst = ipha->ipha_dst;
22929 
22930 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22931 	ill_index = io->ipsec_out_ill_index;
22932 	attach_if = io->ipsec_out_attach_if;
22933 	zoneid = io->ipsec_out_zoneid;
22934 	ASSERT(zoneid != ALL_ZONES);
22935 	match_flags = MATCH_IRE_ILL_GROUP;
22936 	if (ill_index != 0) {
22937 		if (ill == NULL) {
22938 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
22939 			    ill_index, B_FALSE);
22940 
22941 			/* Failure case frees things for us. */
22942 			if (ill == NULL)
22943 				return;
22944 
22945 			ill_need_rele = B_TRUE;
22946 		}
22947 		/*
22948 		 * If this packet needs to go out on a particular interface
22949 		 * honor it.
22950 		 */
22951 		if (attach_if) {
22952 			match_flags = MATCH_IRE_ILL;
22953 
22954 			/*
22955 			 * Check if we need an ire that will not be
22956 			 * looked up by anybody else i.e. HIDDEN.
22957 			 */
22958 			if (ill_is_probeonly(ill)) {
22959 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22960 			}
22961 		}
22962 	}
22963 
22964 	if (CLASSD(dst)) {
22965 		boolean_t conn_dontroute;
22966 		/*
22967 		 * Use the ill_index to get the right ipif.
22968 		 */
22969 		conn_dontroute = io->ipsec_out_dontroute;
22970 		if (ill_index == 0)
22971 			ipif = ipif_lookup_group(dst, zoneid);
22972 		else
22973 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22974 		if (ipif == NULL) {
22975 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
22976 			    " multicast\n"));
22977 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
22978 			freemsg(ipsec_mp);
22979 			goto done;
22980 		}
22981 		/*
22982 		 * ipha_src has already been intialized with the
22983 		 * value of the ipif in ip_wput. All we need now is
22984 		 * an ire to send this downstream.
22985 		 */
22986 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
22987 		if (ire != NULL) {
22988 			ill_t *ill1;
22989 			/*
22990 			 * Do the multicast forwarding now, as the IPSEC
22991 			 * processing has been done.
22992 			 */
22993 			if (ip_g_mrouter && !conn_dontroute &&
22994 			    (ill1 = ire_to_ill(ire))) {
22995 				if (ip_mforward(ill1, ipha, mp)) {
22996 					freemsg(ipsec_mp);
22997 					ip1dbg(("ip_wput_ipsec_out: mforward "
22998 					    "failed\n"));
22999 					ire_refrele(ire);
23000 					goto done;
23001 				}
23002 			}
23003 			goto send;
23004 		}
23005 
23006 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23007 		mp->b_prev = NULL;
23008 		mp->b_next = NULL;
23009 
23010 		/*
23011 		 * If the IPsec packet was processed asynchronously,
23012 		 * drop it now.
23013 		 */
23014 		if (q == NULL) {
23015 			freemsg(ipsec_mp);
23016 			goto done;
23017 		}
23018 
23019 		/*
23020 		 * We may be using a wrong ipif to create the ire.
23021 		 * But it is okay as the source address is assigned
23022 		 * for the packet already. Next outbound packet would
23023 		 * create the IRE with the right IPIF in ip_wput.
23024 		 *
23025 		 * Also handle RTF_MULTIRT routes.
23026 		 */
23027 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
23028 	} else {
23029 		if (attach_if) {
23030 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
23031 			    zoneid, match_flags);
23032 		} else {
23033 			if (ire_arg != NULL) {
23034 				ire = ire_arg;
23035 				ire_need_rele = B_FALSE;
23036 			} else {
23037 				ire = ire_cache_lookup(dst, zoneid);
23038 			}
23039 		}
23040 		if (ire != NULL) {
23041 			goto send;
23042 		}
23043 
23044 		/*
23045 		 * ire disappeared underneath.
23046 		 *
23047 		 * What we need to do here is the ip_newroute
23048 		 * logic to get the ire without doing the IPSEC
23049 		 * processing. Follow the same old path. But this
23050 		 * time, ip_wput or ire_add_then_put will call us
23051 		 * directly as all the IPSEC operations are done.
23052 		 */
23053 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
23054 		mp->b_prev = NULL;
23055 		mp->b_next = NULL;
23056 
23057 		/*
23058 		 * If the IPsec packet was processed asynchronously,
23059 		 * drop it now.
23060 		 */
23061 		if (q == NULL) {
23062 			freemsg(ipsec_mp);
23063 			goto done;
23064 		}
23065 
23066 		/*
23067 		 * Since we're going through ip_newroute() again, we
23068 		 * need to make sure we don't:
23069 		 *
23070 		 *	1.) Trigger the ASSERT() with the ipha_ident
23071 		 *	    overloading.
23072 		 *	2.) Redo transport-layer checksumming, since we've
23073 		 *	    already done all that to get this far.
23074 		 *
23075 		 * The easiest way not do either of the above is to set
23076 		 * the ipha_ident field to IP_HDR_INCLUDED.
23077 		 */
23078 		ipha->ipha_ident = IP_HDR_INCLUDED;
23079 		ip_newroute(q, ipsec_mp, dst, NULL,
23080 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
23081 	}
23082 	goto done;
23083 send:
23084 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
23085 		/*
23086 		 * ESP NAT-Traversal packet.
23087 		 *
23088 		 * Just do software checksum for now.
23089 		 */
23090 
23091 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
23092 		IP_STAT(ip_out_sw_cksum);
23093 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
23094 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
23095 #define	iphs	((uint16_t *)ipha)
23096 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
23097 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
23098 		    IP_SIMPLE_HDR_LENGTH);
23099 #undef iphs
23100 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
23101 			cksum = 0xFFFF;
23102 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
23103 			if (mp1->b_wptr - mp1->b_rptr >=
23104 			    offset + sizeof (uint16_t)) {
23105 				up = (uint16_t *)(mp1->b_rptr + offset);
23106 				*up = cksum;
23107 				break;	/* out of for loop */
23108 			} else {
23109 				offset -= (mp->b_wptr - mp->b_rptr);
23110 			}
23111 	} /* Otherwise, just keep the all-zero checksum. */
23112 
23113 	if (ire->ire_stq == NULL) {
23114 		/*
23115 		 * Loopbacks go through ip_wput_local except for one case.
23116 		 * We come here if we generate a icmp_frag_needed message
23117 		 * after IPSEC processing is over. When this function calls
23118 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
23119 		 * icmp_frag_needed. The message generated comes back here
23120 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
23121 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
23122 		 * source address as it is usually set in ip_wput_ire. As
23123 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
23124 		 * and we end up here. We can't enter ip_wput_ire once the
23125 		 * IPSEC processing is over and hence we need to do it here.
23126 		 */
23127 		ASSERT(q != NULL);
23128 		UPDATE_OB_PKT_COUNT(ire);
23129 		ire->ire_last_used_time = lbolt;
23130 		if (ipha->ipha_src == 0)
23131 			ipha->ipha_src = ire->ire_src_addr;
23132 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
23133 		    ire, 0, zoneid);
23134 		if (ire_need_rele)
23135 			ire_refrele(ire);
23136 		goto done;
23137 	}
23138 
23139 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
23140 		/*
23141 		 * We are through with IPSEC processing.
23142 		 * Fragment this and send it on the wire.
23143 		 */
23144 		if (io->ipsec_out_accelerated) {
23145 			/*
23146 			 * The packet has been accelerated but must
23147 			 * be fragmented. This should not happen
23148 			 * since AH and ESP must not accelerate
23149 			 * packets that need fragmentation, however
23150 			 * the configuration could have changed
23151 			 * since the AH or ESP processing.
23152 			 * Drop packet.
23153 			 * IPsec KSTATS: bump bean counter here.
23154 			 */
23155 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
23156 			    "fragmented accelerated packet!\n"));
23157 			freemsg(ipsec_mp);
23158 		} else {
23159 			ip_wput_ire_fragmentit(ipsec_mp, ire);
23160 		}
23161 		if (ire_need_rele)
23162 			ire_refrele(ire);
23163 		goto done;
23164 	}
23165 
23166 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
23167 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
23168 	    (void *)ire->ire_ipif, (void *)ipif));
23169 
23170 	/*
23171 	 * Multiroute the secured packet, unless IPsec really
23172 	 * requires the packet to go out only through a particular
23173 	 * interface.
23174 	 */
23175 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
23176 		ire_t *first_ire;
23177 		irb = ire->ire_bucket;
23178 		ASSERT(irb != NULL);
23179 		/*
23180 		 * This ire has been looked up as the one that
23181 		 * goes through the given ipif;
23182 		 * make sure we do not omit any other multiroute ire
23183 		 * that may be present in the bucket before this one.
23184 		 */
23185 		IRB_REFHOLD(irb);
23186 		for (first_ire = irb->irb_ire;
23187 		    first_ire != NULL;
23188 		    first_ire = first_ire->ire_next) {
23189 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23190 			    (first_ire->ire_addr == ire->ire_addr) &&
23191 			    !(first_ire->ire_marks &
23192 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23193 				break;
23194 		}
23195 
23196 		if ((first_ire != NULL) && (first_ire != ire)) {
23197 			/*
23198 			 * Don't change the ire if the packet must
23199 			 * be fragmented if sent via this new one.
23200 			 */
23201 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
23202 				IRE_REFHOLD(first_ire);
23203 				if (ire_need_rele)
23204 					ire_refrele(ire);
23205 				else
23206 					ire_need_rele = B_TRUE;
23207 				ire = first_ire;
23208 			}
23209 		}
23210 		IRB_REFRELE(irb);
23211 
23212 		multirt_send = B_TRUE;
23213 		max_frag = ire->ire_max_frag;
23214 	} else {
23215 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
23216 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
23217 			    "flag, attach_if %d\n", attach_if));
23218 		}
23219 	}
23220 
23221 	/*
23222 	 * In most cases, the emission loop below is entered only once.
23223 	 * Only in the case where the ire holds the RTF_MULTIRT
23224 	 * flag, we loop to process all RTF_MULTIRT ires in the
23225 	 * bucket, and send the packet through all crossed
23226 	 * RTF_MULTIRT routes.
23227 	 */
23228 	do {
23229 		if (multirt_send) {
23230 			/*
23231 			 * ire1 holds here the next ire to process in the
23232 			 * bucket. If multirouting is expected,
23233 			 * any non-RTF_MULTIRT ire that has the
23234 			 * right destination address is ignored.
23235 			 */
23236 			ASSERT(irb != NULL);
23237 			IRB_REFHOLD(irb);
23238 			for (ire1 = ire->ire_next;
23239 			    ire1 != NULL;
23240 			    ire1 = ire1->ire_next) {
23241 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23242 					continue;
23243 				if (ire1->ire_addr != ire->ire_addr)
23244 					continue;
23245 				if (ire1->ire_marks &
23246 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23247 					continue;
23248 				/* No loopback here */
23249 				if (ire1->ire_stq == NULL)
23250 					continue;
23251 				/*
23252 				 * Ensure we do not exceed the MTU
23253 				 * of the next route.
23254 				 */
23255 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
23256 					ip_multirt_bad_mtu(ire1, max_frag);
23257 					continue;
23258 				}
23259 
23260 				IRE_REFHOLD(ire1);
23261 				break;
23262 			}
23263 			IRB_REFRELE(irb);
23264 			if (ire1 != NULL) {
23265 				/*
23266 				 * We are in a multiple send case, need to
23267 				 * make a copy of the packet.
23268 				 */
23269 				next_mp = copymsg(ipsec_mp);
23270 				if (next_mp == NULL) {
23271 					ire_refrele(ire1);
23272 					ire1 = NULL;
23273 				}
23274 			}
23275 		}
23276 
23277 		/* Everything is done. Send it out on the wire */
23278 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
23279 		if (mp1 == NULL) {
23280 			BUMP_MIB(&ip_mib, ipOutDiscards);
23281 			freemsg(ipsec_mp);
23282 			if (ire_need_rele)
23283 				ire_refrele(ire);
23284 			if (ire1 != NULL) {
23285 				ire_refrele(ire1);
23286 				freemsg(next_mp);
23287 			}
23288 			goto done;
23289 		}
23290 		UPDATE_OB_PKT_COUNT(ire);
23291 		ire->ire_last_used_time = lbolt;
23292 		if (!io->ipsec_out_accelerated) {
23293 			putnext(ire->ire_stq, mp1);
23294 		} else {
23295 			/*
23296 			 * Safety Pup says: make sure this is going to
23297 			 * the right interface!
23298 			 */
23299 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
23300 			int ifindex = ill1->ill_phyint->phyint_ifindex;
23301 
23302 			if (ifindex != io->ipsec_out_capab_ill_index) {
23303 				/* IPsec kstats: bump lose counter */
23304 				freemsg(mp1);
23305 			} else {
23306 				ipsec_hw_putnext(ire->ire_stq, mp1);
23307 			}
23308 		}
23309 
23310 		freeb(ipsec_mp);
23311 		if (ire_need_rele)
23312 			ire_refrele(ire);
23313 
23314 		if (ire1 != NULL) {
23315 			ire = ire1;
23316 			ire_need_rele = B_TRUE;
23317 			ASSERT(next_mp);
23318 			ipsec_mp = next_mp;
23319 			mp = ipsec_mp->b_cont;
23320 			ire1 = NULL;
23321 			next_mp = NULL;
23322 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
23323 		} else {
23324 			multirt_send = B_FALSE;
23325 		}
23326 	} while (multirt_send);
23327 done:
23328 	if (ill != NULL && ill_need_rele)
23329 		ill_refrele(ill);
23330 	if (ipif != NULL)
23331 		ipif_refrele(ipif);
23332 }
23333 
23334 /*
23335  * Get the ill corresponding to the specified ire, and compare its
23336  * capabilities with the protocol and algorithms specified by the
23337  * the SA obtained from ipsec_out. If they match, annotate the
23338  * ipsec_out structure to indicate that the packet needs acceleration.
23339  *
23340  *
23341  * A packet is eligible for outbound hardware acceleration if the
23342  * following conditions are satisfied:
23343  *
23344  * 1. the packet will not be fragmented
23345  * 2. the provider supports the algorithm
23346  * 3. there is no pending control message being exchanged
23347  * 4. snoop is not attached
23348  * 5. the destination address is not a broadcast or multicast address.
23349  *
23350  * Rationale:
23351  *	- Hardware drivers do not support fragmentation with
23352  *	  the current interface.
23353  *	- snoop, multicast, and broadcast may result in exposure of
23354  *	  a cleartext datagram.
23355  * We check all five of these conditions here.
23356  *
23357  * XXX would like to nuke "ire_t *" parameter here; problem is that
23358  * IRE is only way to figure out if a v4 address is a broadcast and
23359  * thus ineligible for acceleration...
23360  */
23361 static void
23362 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23363 {
23364 	ipsec_out_t *io;
23365 	mblk_t *data_mp;
23366 	uint_t plen, overhead;
23367 
23368 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23369 		return;
23370 
23371 	if (ill == NULL)
23372 		return;
23373 
23374 	/*
23375 	 * Destination address is a broadcast or multicast.  Punt.
23376 	 */
23377 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23378 	    IRE_LOCAL)))
23379 		return;
23380 
23381 	data_mp = ipsec_mp->b_cont;
23382 
23383 	if (ill->ill_isv6) {
23384 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23385 
23386 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23387 			return;
23388 
23389 		plen = ip6h->ip6_plen;
23390 	} else {
23391 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23392 
23393 		if (CLASSD(ipha->ipha_dst))
23394 			return;
23395 
23396 		plen = ipha->ipha_length;
23397 	}
23398 	/*
23399 	 * Is there a pending DLPI control message being exchanged
23400 	 * between IP/IPsec and the DLS Provider? If there is, it
23401 	 * could be a SADB update, and the state of the DLS Provider
23402 	 * SADB might not be in sync with the SADB maintained by
23403 	 * IPsec. To avoid dropping packets or using the wrong keying
23404 	 * material, we do not accelerate this packet.
23405 	 */
23406 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23407 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23408 		    "ill_dlpi_pending! don't accelerate packet\n"));
23409 		return;
23410 	}
23411 
23412 	/*
23413 	 * Is the Provider in promiscous mode? If it does, we don't
23414 	 * accelerate the packet since it will bounce back up to the
23415 	 * listeners in the clear.
23416 	 */
23417 	if (ill->ill_promisc_on_phys) {
23418 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23419 		    "ill in promiscous mode, don't accelerate packet\n"));
23420 		return;
23421 	}
23422 
23423 	/*
23424 	 * Will the packet require fragmentation?
23425 	 */
23426 
23427 	/*
23428 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23429 	 * as is used elsewhere.
23430 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23431 	 *	+ 2-byte trailer
23432 	 */
23433 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23434 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23435 
23436 	if ((plen + overhead) > ill->ill_max_mtu)
23437 		return;
23438 
23439 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23440 
23441 	/*
23442 	 * Can the ill accelerate this IPsec protocol and algorithm
23443 	 * specified by the SA?
23444 	 */
23445 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23446 	    ill->ill_isv6, sa)) {
23447 		return;
23448 	}
23449 
23450 	/*
23451 	 * Tell AH or ESP that the outbound ill is capable of
23452 	 * accelerating this packet.
23453 	 */
23454 	io->ipsec_out_is_capab_ill = B_TRUE;
23455 }
23456 
23457 /*
23458  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23459  *
23460  * If this function returns B_TRUE, the requested SA's have been filled
23461  * into the ipsec_out_*_sa pointers.
23462  *
23463  * If the function returns B_FALSE, the packet has been "consumed", most
23464  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23465  *
23466  * The SA references created by the protocol-specific "select"
23467  * function will be released when the ipsec_mp is freed, thanks to the
23468  * ipsec_out_free destructor -- see spd.c.
23469  */
23470 static boolean_t
23471 ipsec_out_select_sa(mblk_t *ipsec_mp)
23472 {
23473 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23474 	ipsec_out_t *io;
23475 	ipsec_policy_t *pp;
23476 	ipsec_action_t *ap;
23477 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23478 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23479 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23480 
23481 	if (!io->ipsec_out_secure) {
23482 		/*
23483 		 * We came here by mistake.
23484 		 * Don't bother with ipsec processing
23485 		 * We should "discourage" this path in the future.
23486 		 */
23487 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23488 		return (B_FALSE);
23489 	}
23490 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23491 	ASSERT((io->ipsec_out_policy != NULL) ||
23492 	    (io->ipsec_out_act != NULL));
23493 
23494 	ASSERT(io->ipsec_out_failed == B_FALSE);
23495 
23496 	/*
23497 	 * IPSEC processing has started.
23498 	 */
23499 	io->ipsec_out_proc_begin = B_TRUE;
23500 	ap = io->ipsec_out_act;
23501 	if (ap == NULL) {
23502 		pp = io->ipsec_out_policy;
23503 		ASSERT(pp != NULL);
23504 		ap = pp->ipsp_act;
23505 		ASSERT(ap != NULL);
23506 	}
23507 
23508 	/*
23509 	 * We have an action.  now, let's select SA's.
23510 	 * (In the future, we can cache this in the conn_t..)
23511 	 */
23512 	if (ap->ipa_want_esp) {
23513 		if (io->ipsec_out_esp_sa == NULL) {
23514 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23515 			    IPPROTO_ESP);
23516 		}
23517 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23518 	}
23519 
23520 	if (ap->ipa_want_ah) {
23521 		if (io->ipsec_out_ah_sa == NULL) {
23522 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23523 			    IPPROTO_AH);
23524 		}
23525 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23526 		/*
23527 		 * The ESP and AH processing order needs to be preserved
23528 		 * when both protocols are required (ESP should be applied
23529 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23530 		 * when both ESP and AH are required, and an AH ACQUIRE
23531 		 * is needed.
23532 		 */
23533 		if (ap->ipa_want_esp && need_ah_acquire)
23534 			need_esp_acquire = B_TRUE;
23535 	}
23536 
23537 	/*
23538 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23539 	 * Release SAs that got referenced, but will not be used until we
23540 	 * acquire _all_ of the SAs we need.
23541 	 */
23542 	if (need_ah_acquire || need_esp_acquire) {
23543 		if (io->ipsec_out_ah_sa != NULL) {
23544 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23545 			io->ipsec_out_ah_sa = NULL;
23546 		}
23547 		if (io->ipsec_out_esp_sa != NULL) {
23548 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23549 			io->ipsec_out_esp_sa = NULL;
23550 		}
23551 
23552 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23553 		return (B_FALSE);
23554 	}
23555 
23556 	return (B_TRUE);
23557 }
23558 
23559 /*
23560  * Process an IPSEC_OUT message and see what you can
23561  * do with it.
23562  * IPQoS Notes:
23563  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23564  * IPSec.
23565  * XXX would like to nuke ire_t.
23566  * XXX ill_index better be "real"
23567  */
23568 void
23569 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23570 {
23571 	ipsec_out_t *io;
23572 	ipsec_policy_t *pp;
23573 	ipsec_action_t *ap;
23574 	ipha_t *ipha;
23575 	ip6_t *ip6h;
23576 	mblk_t *mp;
23577 	ill_t *ill;
23578 	zoneid_t zoneid;
23579 	ipsec_status_t ipsec_rc;
23580 	boolean_t ill_need_rele = B_FALSE;
23581 
23582 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23583 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23584 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23585 	mp = ipsec_mp->b_cont;
23586 
23587 	/*
23588 	 * Initiate IPPF processing. We do it here to account for packets
23589 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23590 	 * We can check for ipsec_out_proc_begin even for such packets, as
23591 	 * they will always be false (asserted below).
23592 	 */
23593 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23594 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23595 		    io->ipsec_out_ill_index : ill_index);
23596 		if (mp == NULL) {
23597 			ip2dbg(("ipsec_out_process: packet dropped "\
23598 			    "during IPPF processing\n"));
23599 			freeb(ipsec_mp);
23600 			BUMP_MIB(&ip_mib, ipOutDiscards);
23601 			return;
23602 		}
23603 	}
23604 
23605 	if (!io->ipsec_out_secure) {
23606 		/*
23607 		 * We came here by mistake.
23608 		 * Don't bother with ipsec processing
23609 		 * Should "discourage" this path in the future.
23610 		 */
23611 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23612 		goto done;
23613 	}
23614 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23615 	ASSERT((io->ipsec_out_policy != NULL) ||
23616 	    (io->ipsec_out_act != NULL));
23617 	ASSERT(io->ipsec_out_failed == B_FALSE);
23618 
23619 	if (!ipsec_loaded()) {
23620 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23621 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23622 			BUMP_MIB(&ip_mib, ipOutDiscards);
23623 		} else {
23624 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23625 		}
23626 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23627 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23628 		return;
23629 	}
23630 
23631 	/*
23632 	 * IPSEC processing has started.
23633 	 */
23634 	io->ipsec_out_proc_begin = B_TRUE;
23635 	ap = io->ipsec_out_act;
23636 	if (ap == NULL) {
23637 		pp = io->ipsec_out_policy;
23638 		ASSERT(pp != NULL);
23639 		ap = pp->ipsp_act;
23640 		ASSERT(ap != NULL);
23641 	}
23642 
23643 	/*
23644 	 * Save the outbound ill index. When the packet comes back
23645 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23646 	 * before sending it the accelerated packet.
23647 	 */
23648 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23649 		int ifindex;
23650 		ill = ire_to_ill(ire);
23651 		ifindex = ill->ill_phyint->phyint_ifindex;
23652 		io->ipsec_out_capab_ill_index = ifindex;
23653 	}
23654 
23655 	/*
23656 	 * The order of processing is first insert a IP header if needed.
23657 	 * Then insert the ESP header and then the AH header.
23658 	 */
23659 	if ((io->ipsec_out_se_done == B_FALSE) &&
23660 	    (ap->ipa_want_se)) {
23661 		/*
23662 		 * First get the outer IP header before sending
23663 		 * it to ESP.
23664 		 */
23665 		ipha_t *oipha, *iipha;
23666 		mblk_t *outer_mp, *inner_mp;
23667 
23668 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23669 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23670 			    "ipsec_out_process: "
23671 			    "Self-Encapsulation failed: Out of memory\n");
23672 			freemsg(ipsec_mp);
23673 			BUMP_MIB(&ip_mib, ipOutDiscards);
23674 			return;
23675 		}
23676 		inner_mp = ipsec_mp->b_cont;
23677 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23678 		oipha = (ipha_t *)outer_mp->b_rptr;
23679 		iipha = (ipha_t *)inner_mp->b_rptr;
23680 		*oipha = *iipha;
23681 		outer_mp->b_wptr += sizeof (ipha_t);
23682 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23683 		    sizeof (ipha_t));
23684 		oipha->ipha_protocol = IPPROTO_ENCAP;
23685 		oipha->ipha_version_and_hdr_length =
23686 		    IP_SIMPLE_HDR_VERSION;
23687 		oipha->ipha_hdr_checksum = 0;
23688 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23689 		outer_mp->b_cont = inner_mp;
23690 		ipsec_mp->b_cont = outer_mp;
23691 
23692 		io->ipsec_out_se_done = B_TRUE;
23693 		io->ipsec_out_encaps = B_TRUE;
23694 	}
23695 
23696 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23697 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23698 	    !ipsec_out_select_sa(ipsec_mp))
23699 		return;
23700 
23701 	/*
23702 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23703 	 * to do the heavy lifting.
23704 	 */
23705 	zoneid = io->ipsec_out_zoneid;
23706 	ASSERT(zoneid != ALL_ZONES);
23707 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23708 		ASSERT(io->ipsec_out_esp_sa != NULL);
23709 		io->ipsec_out_esp_done = B_TRUE;
23710 		/*
23711 		 * Note that since hw accel can only apply one transform,
23712 		 * not two, we skip hw accel for ESP if we also have AH
23713 		 * This is an design limitation of the interface
23714 		 * which should be revisited.
23715 		 */
23716 		ASSERT(ire != NULL);
23717 		if (io->ipsec_out_ah_sa == NULL) {
23718 			ill = (ill_t *)ire->ire_stq->q_ptr;
23719 			ipsec_out_is_accelerated(ipsec_mp,
23720 			    io->ipsec_out_esp_sa, ill, ire);
23721 		}
23722 
23723 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23724 		switch (ipsec_rc) {
23725 		case IPSEC_STATUS_SUCCESS:
23726 			break;
23727 		case IPSEC_STATUS_FAILED:
23728 			BUMP_MIB(&ip_mib, ipOutDiscards);
23729 			/* FALLTHRU */
23730 		case IPSEC_STATUS_PENDING:
23731 			return;
23732 		}
23733 	}
23734 
23735 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23736 		ASSERT(io->ipsec_out_ah_sa != NULL);
23737 		io->ipsec_out_ah_done = B_TRUE;
23738 		if (ire == NULL) {
23739 			int idx = io->ipsec_out_capab_ill_index;
23740 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23741 			    NULL, NULL, NULL, NULL);
23742 			ill_need_rele = B_TRUE;
23743 		} else {
23744 			ill = (ill_t *)ire->ire_stq->q_ptr;
23745 		}
23746 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23747 		    ire);
23748 
23749 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23750 		switch (ipsec_rc) {
23751 		case IPSEC_STATUS_SUCCESS:
23752 			break;
23753 		case IPSEC_STATUS_FAILED:
23754 			BUMP_MIB(&ip_mib, ipOutDiscards);
23755 			/* FALLTHRU */
23756 		case IPSEC_STATUS_PENDING:
23757 			if (ill != NULL && ill_need_rele)
23758 				ill_refrele(ill);
23759 			return;
23760 		}
23761 	}
23762 	/*
23763 	 * We are done with IPSEC processing. Send it over
23764 	 * the wire.
23765 	 */
23766 done:
23767 	mp = ipsec_mp->b_cont;
23768 	ipha = (ipha_t *)mp->b_rptr;
23769 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23770 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23771 	} else {
23772 		ip6h = (ip6_t *)ipha;
23773 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23774 	}
23775 	if (ill != NULL && ill_need_rele)
23776 		ill_refrele(ill);
23777 }
23778 
23779 /* ARGSUSED */
23780 void
23781 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23782 {
23783 	opt_restart_t	*or;
23784 	int	err;
23785 	conn_t	*connp;
23786 
23787 	ASSERT(CONN_Q(q));
23788 	connp = Q_TO_CONN(q);
23789 
23790 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23791 	or = (opt_restart_t *)first_mp->b_rptr;
23792 	/*
23793 	 * We don't need to pass any credentials here since this is just
23794 	 * a restart. The credentials are passed in when svr4_optcom_req
23795 	 * is called the first time (from ip_wput_nondata).
23796 	 */
23797 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23798 		err = svr4_optcom_req(q, first_mp, NULL,
23799 		    &ip_opt_obj);
23800 	} else {
23801 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23802 		err = tpi_optcom_req(q, first_mp, NULL,
23803 		    &ip_opt_obj);
23804 	}
23805 	if (err != EINPROGRESS) {
23806 		/* operation is done */
23807 		CONN_OPER_PENDING_DONE(connp);
23808 	}
23809 }
23810 
23811 /*
23812  * ioctls that go through a down/up sequence may need to wait for the down
23813  * to complete. This involves waiting for the ire and ipif refcnts to go down
23814  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23815  */
23816 /* ARGSUSED */
23817 void
23818 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23819 {
23820 	struct iocblk *iocp;
23821 	mblk_t *mp1;
23822 	ipif_t	*ipif;
23823 	ip_ioctl_cmd_t *ipip;
23824 	int err;
23825 	sin_t	*sin;
23826 	struct lifreq *lifr;
23827 	struct ifreq *ifr;
23828 
23829 	iocp = (struct iocblk *)mp->b_rptr;
23830 	ASSERT(ipsq != NULL);
23831 	/* Existence of mp1 verified in ip_wput_nondata */
23832 	mp1 = mp->b_cont->b_cont;
23833 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23834 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23835 		ill_t *ill;
23836 		/*
23837 		 * Special case where ipsq_current_ipif may not be set.
23838 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23839 		 * ill could also have become part of a ipmp group in the
23840 		 * process, we are here as were not able to complete the
23841 		 * operation in ipif_set_values because we could not become
23842 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23843 		 * will not be set so we need to set it.
23844 		 */
23845 		ill = (ill_t *)q->q_ptr;
23846 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23847 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23848 	}
23849 
23850 	ipif = ipsq->ipsq_current_ipif;
23851 	ASSERT(ipif != NULL);
23852 	if (ipip->ipi_cmd_type == IF_CMD) {
23853 		/* This a old style SIOC[GS]IF* command */
23854 		ifr = (struct ifreq *)mp1->b_rptr;
23855 		sin = (sin_t *)&ifr->ifr_addr;
23856 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
23857 		/* This a new style SIOC[GS]LIF* command */
23858 		lifr = (struct lifreq *)mp1->b_rptr;
23859 		sin = (sin_t *)&lifr->lifr_addr;
23860 	} else {
23861 		sin = NULL;
23862 	}
23863 
23864 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
23865 	    (void *)mp1->b_rptr);
23866 
23867 	/* SIOCLIFREMOVEIF could have removed the ipif */
23868 	ip_ioctl_finish(q, mp, err,
23869 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23870 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
23871 }
23872 
23873 /*
23874  * ioctl processing
23875  *
23876  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
23877  * the ioctl command in the ioctl tables and determines the copyin data size
23878  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
23879  * size.
23880  *
23881  * ioctl processing then continues when the M_IOCDATA makes its way down.
23882  * Now the ioctl is looked up again in the ioctl table, and its properties are
23883  * extracted. The associated 'conn' is then refheld till the end of the ioctl
23884  * and the general ioctl processing function ip_process_ioctl is called.
23885  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
23886  * so goes thru the serialization primitive ipsq_try_enter. Then the
23887  * appropriate function to handle the ioctl is called based on the entry in
23888  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
23889  * which also refreleases the 'conn' that was refheld at the start of the
23890  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
23891  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
23892  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
23893  *
23894  * Many exclusive ioctls go thru an internal down up sequence as part of
23895  * the operation. For example an attempt to change the IP address of an
23896  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
23897  * does all the cleanup such as deleting all ires that use this address.
23898  * Then we need to wait till all references to the interface go away.
23899  */
23900 void
23901 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
23902 {
23903 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
23904 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
23905 	cmd_info_t ci;
23906 	int err;
23907 	boolean_t entered_ipsq = B_FALSE;
23908 
23909 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
23910 
23911 	if (ipip == NULL)
23912 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23913 
23914 	/*
23915 	 * SIOCLIFADDIF needs to go thru a special path since the
23916 	 * ill may not exist yet. This happens in the case of lo0
23917 	 * which is created using this ioctl.
23918 	 */
23919 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
23920 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
23921 		ip_ioctl_finish(q, mp, err,
23922 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23923 		    NULL, NULL);
23924 		return;
23925 	}
23926 
23927 	ci.ci_ipif = NULL;
23928 	switch (ipip->ipi_cmd_type) {
23929 	case IF_CMD:
23930 	case LIF_CMD:
23931 		/*
23932 		 * ioctls that pass in a [l]ifreq appear here.
23933 		 * ip_extract_lifreq_cmn returns a refheld ipif in
23934 		 * ci.ci_ipif
23935 		 */
23936 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
23937 		    ipip->ipi_flags, &ci, ip_process_ioctl);
23938 		if (err != 0) {
23939 			ip_ioctl_finish(q, mp, err,
23940 			    ipip->ipi_flags & IPI_GET_CMD ?
23941 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23942 			return;
23943 		}
23944 		ASSERT(ci.ci_ipif != NULL);
23945 		break;
23946 
23947 	case TUN_CMD:
23948 		/*
23949 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
23950 		 * a refheld ipif in ci.ci_ipif
23951 		 */
23952 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
23953 		if (err != 0) {
23954 			ip_ioctl_finish(q, mp, err,
23955 			    ipip->ipi_flags & IPI_GET_CMD ?
23956 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23957 			return;
23958 		}
23959 		ASSERT(ci.ci_ipif != NULL);
23960 		break;
23961 
23962 	case MISC_CMD:
23963 		/*
23964 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
23965 		 * For eg. SIOCGLIFCONF will appear here.
23966 		 */
23967 		switch (ipip->ipi_cmd) {
23968 		case IF_UNITSEL:
23969 			/* ioctl comes down the ill */
23970 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
23971 			ipif_refhold(ci.ci_ipif);
23972 			break;
23973 		case SIOCGMSFILTER:
23974 		case SIOCSMSFILTER:
23975 		case SIOCGIPMSFILTER:
23976 		case SIOCSIPMSFILTER:
23977 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
23978 			    ip_process_ioctl);
23979 			if (err != 0) {
23980 				ip_ioctl_finish(q, mp, err,
23981 				    ipip->ipi_flags & IPI_GET_CMD ?
23982 				    COPYOUT : NO_COPYOUT, NULL, NULL);
23983 				return;
23984 			}
23985 			break;
23986 		}
23987 		err = 0;
23988 		ci.ci_sin = NULL;
23989 		ci.ci_sin6 = NULL;
23990 		ci.ci_lifr = NULL;
23991 		break;
23992 	}
23993 
23994 	/*
23995 	 * If ipsq is non-null, we are already being called exclusively
23996 	 */
23997 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
23998 	if (!(ipip->ipi_flags & IPI_WR)) {
23999 		/*
24000 		 * A return value of EINPROGRESS means the ioctl is
24001 		 * either queued and waiting for some reason or has
24002 		 * already completed.
24003 		 */
24004 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24005 		    ci.ci_lifr);
24006 		if (ci.ci_ipif != NULL)
24007 			ipif_refrele(ci.ci_ipif);
24008 		ip_ioctl_finish(q, mp, err,
24009 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24010 		    NULL, NULL);
24011 		return;
24012 	}
24013 
24014 	ASSERT(ci.ci_ipif != NULL);
24015 
24016 	if (ipsq == NULL) {
24017 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
24018 		    ip_process_ioctl, NEW_OP, B_TRUE);
24019 		entered_ipsq = B_TRUE;
24020 	}
24021 	/*
24022 	 * Release the ipif so that ipif_down and friends that wait for
24023 	 * references to go away are not misled about the current ipif_refcnt
24024 	 * values. We are writer so we can access the ipif even after releasing
24025 	 * the ipif.
24026 	 */
24027 	ipif_refrele(ci.ci_ipif);
24028 	if (ipsq == NULL)
24029 		return;
24030 
24031 	mutex_enter(&ipsq->ipsq_lock);
24032 	ASSERT(ipsq->ipsq_current_ipif == NULL);
24033 	ipsq->ipsq_current_ipif = ci.ci_ipif;
24034 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24035 	mutex_exit(&ipsq->ipsq_lock);
24036 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
24037 	/*
24038 	 * For most set ioctls that come here, this serves as a single point
24039 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
24040 	 * be any new references to the ipif. This helps functions that go
24041 	 * through this path and end up trying to wait for the refcnts
24042 	 * associated with the ipif to go down to zero. Some exceptions are
24043 	 * Failover, Failback, and Groupname commands that operate on more than
24044 	 * just the ci.ci_ipif. These commands internally determine the
24045 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
24046 	 * flags on that set. Another exception is the Removeif command that
24047 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
24048 	 * ipif to operate on.
24049 	 */
24050 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
24051 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
24052 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
24053 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
24054 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
24055 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
24056 
24057 	/*
24058 	 * A return value of EINPROGRESS means the ioctl is
24059 	 * either queued and waiting for some reason or has
24060 	 * already completed.
24061 	 */
24062 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24063 	    ci.ci_lifr);
24064 
24065 	/* SIOCLIFREMOVEIF could have removed the ipif */
24066 	ip_ioctl_finish(q, mp, err,
24067 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24068 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
24069 
24070 	if (entered_ipsq)
24071 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
24072 }
24073 
24074 /*
24075  * Complete the ioctl. Typically ioctls use the mi package and need to
24076  * do mi_copyout/mi_copy_done.
24077  */
24078 void
24079 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
24080     ipif_t *ipif, ipsq_t *ipsq)
24081 {
24082 	conn_t	*connp = NULL;
24083 
24084 	if (err == EINPROGRESS)
24085 		return;
24086 
24087 	if (CONN_Q(q)) {
24088 		connp = Q_TO_CONN(q);
24089 		ASSERT(connp->conn_ref >= 2);
24090 	}
24091 
24092 	switch (mode) {
24093 	case COPYOUT:
24094 		if (err == 0)
24095 			mi_copyout(q, mp);
24096 		else
24097 			mi_copy_done(q, mp, err);
24098 		break;
24099 
24100 	case NO_COPYOUT:
24101 		mi_copy_done(q, mp, err);
24102 		break;
24103 
24104 	default:
24105 		/* An ioctl aborted through a conn close would take this path */
24106 		break;
24107 	}
24108 
24109 	/*
24110 	 * The refhold placed at the start of the ioctl is released here.
24111 	 */
24112 	if (connp != NULL)
24113 		CONN_OPER_PENDING_DONE(connp);
24114 
24115 	/*
24116 	 * If the ioctl were an exclusive ioctl it would have set
24117 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
24118 	 */
24119 	if (ipif != NULL) {
24120 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
24121 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
24122 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
24123 	}
24124 
24125 	/*
24126 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
24127 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
24128 	 * entering the ipsq
24129 	 */
24130 	if (ipsq != NULL) {
24131 		mutex_enter(&ipsq->ipsq_lock);
24132 		ipsq->ipsq_current_ipif = NULL;
24133 		mutex_exit(&ipsq->ipsq_lock);
24134 	}
24135 }
24136 
24137 /*
24138  * This is called from ip_wput_nondata to resume a deferred TCP bind.
24139  */
24140 /* ARGSUSED */
24141 void
24142 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
24143 {
24144 	conn_t *connp = arg;
24145 	tcp_t	*tcp;
24146 
24147 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
24148 	tcp = connp->conn_tcp;
24149 
24150 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
24151 		freemsg(mp);
24152 	else
24153 		tcp_rput_other(tcp, mp);
24154 	CONN_OPER_PENDING_DONE(connp);
24155 }
24156 
24157 /* Called from ip_wput for all non data messages */
24158 /* ARGSUSED */
24159 void
24160 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24161 {
24162 	mblk_t		*mp1;
24163 	ire_t		*ire;
24164 	ill_t		*ill;
24165 	struct iocblk	*iocp;
24166 	ip_ioctl_cmd_t	*ipip;
24167 	cred_t		*cr;
24168 	conn_t		*connp = NULL;
24169 	int		cmd, err;
24170 
24171 	if (CONN_Q(q))
24172 		connp = Q_TO_CONN(q);
24173 
24174 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
24175 
24176 	/* Check if it is a queue to /dev/sctp. */
24177 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
24178 	    connp->conn_rq == NULL) {
24179 		sctp_wput(q, mp);
24180 		return;
24181 	}
24182 
24183 	switch (DB_TYPE(mp)) {
24184 	case M_IOCTL:
24185 		/*
24186 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
24187 		 * will arrange to copy in associated control structures.
24188 		 */
24189 		ip_sioctl_copyin_setup(q, mp);
24190 		return;
24191 	case M_IOCDATA:
24192 		/*
24193 		 * Ensure that this is associated with one of our trans-
24194 		 * parent ioctls.  If it's not ours, discard it if we're
24195 		 * running as a driver, or pass it on if we're a module.
24196 		 */
24197 		iocp = (struct iocblk *)mp->b_rptr;
24198 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24199 		if (ipip == NULL) {
24200 			if (q->q_next == NULL) {
24201 				goto nak;
24202 			} else {
24203 				putnext(q, mp);
24204 			}
24205 			return;
24206 		} else if ((q->q_next != NULL) &&
24207 		    !(ipip->ipi_flags & IPI_MODOK)) {
24208 			/*
24209 			 * the ioctl is one we recognise, but is not
24210 			 * consumed by IP as a module, pass M_IOCDATA
24211 			 * for processing downstream, but only for
24212 			 * common Streams ioctls.
24213 			 */
24214 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
24215 				putnext(q, mp);
24216 				return;
24217 			} else {
24218 				goto nak;
24219 			}
24220 		}
24221 
24222 		/* IOCTL continuation following copyin or copyout. */
24223 		if (mi_copy_state(q, mp, NULL) == -1) {
24224 			/*
24225 			 * The copy operation failed.  mi_copy_state already
24226 			 * cleaned up, so we're out of here.
24227 			 */
24228 			return;
24229 		}
24230 		/*
24231 		 * If we just completed a copy in, we become writer and
24232 		 * continue processing in ip_sioctl_copyin_done.  If it
24233 		 * was a copy out, we call mi_copyout again.  If there is
24234 		 * nothing more to copy out, it will complete the IOCTL.
24235 		 */
24236 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
24237 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
24238 				mi_copy_done(q, mp, EPROTO);
24239 				return;
24240 			}
24241 			/*
24242 			 * Check for cases that need more copying.  A return
24243 			 * value of 0 means a second copyin has been started,
24244 			 * so we return; a return value of 1 means no more
24245 			 * copying is needed, so we continue.
24246 			 */
24247 			cmd = iocp->ioc_cmd;
24248 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
24249 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
24250 			    MI_COPY_COUNT(mp) == 1) {
24251 				if (ip_copyin_msfilter(q, mp) == 0)
24252 					return;
24253 			}
24254 			/*
24255 			 * Refhold the conn, till the ioctl completes. This is
24256 			 * needed in case the ioctl ends up in the pending mp
24257 			 * list. Every mp in the ill_pending_mp list and
24258 			 * the ipsq_pending_mp must have a refhold on the conn
24259 			 * to resume processing. The refhold is released when
24260 			 * the ioctl completes. (normally or abnormally)
24261 			 * In all cases ip_ioctl_finish is called to finish
24262 			 * the ioctl.
24263 			 */
24264 			if (connp != NULL) {
24265 				/* This is not a reentry */
24266 				ASSERT(ipsq == NULL);
24267 				CONN_INC_REF(connp);
24268 			} else {
24269 				if (!(ipip->ipi_flags & IPI_MODOK)) {
24270 					mi_copy_done(q, mp, EINVAL);
24271 					return;
24272 				}
24273 			}
24274 
24275 			ip_process_ioctl(ipsq, q, mp, ipip);
24276 
24277 		} else {
24278 			mi_copyout(q, mp);
24279 		}
24280 		return;
24281 nak:
24282 		iocp->ioc_error = EINVAL;
24283 		mp->b_datap->db_type = M_IOCNAK;
24284 		iocp->ioc_count = 0;
24285 		qreply(q, mp);
24286 		return;
24287 
24288 	case M_IOCNAK:
24289 		/*
24290 		 * The only way we could get here is if a resolver didn't like
24291 		 * an IOCTL we sent it.	 This shouldn't happen.
24292 		 */
24293 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
24294 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
24295 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
24296 		freemsg(mp);
24297 		return;
24298 	case M_IOCACK:
24299 		/* Finish socket ioctls passed through to ARP. */
24300 		ip_sioctl_iocack(q, mp);
24301 		return;
24302 	case M_FLUSH:
24303 		if (*mp->b_rptr & FLUSHW)
24304 			flushq(q, FLUSHALL);
24305 		if (q->q_next) {
24306 			/*
24307 			 * M_FLUSH is sent up to IP by some drivers during
24308 			 * unbind. ip_rput has already replied to it. We are
24309 			 * here for the M_FLUSH that we originated in IP
24310 			 * before sending the unbind request to the driver.
24311 			 * Just free it as we don't queue packets in IP
24312 			 * on the write side of the device instance.
24313 			 */
24314 			freemsg(mp);
24315 			return;
24316 		}
24317 		if (*mp->b_rptr & FLUSHR) {
24318 			*mp->b_rptr &= ~FLUSHW;
24319 			qreply(q, mp);
24320 			return;
24321 		}
24322 		freemsg(mp);
24323 		return;
24324 	case IRE_DB_REQ_TYPE:
24325 		/* An Upper Level Protocol wants a copy of an IRE. */
24326 		ip_ire_req(q, mp);
24327 		return;
24328 	case M_CTL:
24329 		/* M_CTL messages are used by ARP to tell us things. */
24330 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
24331 			break;
24332 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
24333 		case AR_ENTRY_SQUERY:
24334 			ip_wput_ctl(q, mp);
24335 			return;
24336 		case AR_CLIENT_NOTIFY:
24337 			ip_arp_news(q, mp);
24338 			return;
24339 		case AR_DLPIOP_DONE:
24340 			ASSERT(q->q_next != NULL);
24341 			ill = (ill_t *)q->q_ptr;
24342 			/* qwriter_ip releases the refhold */
24343 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24344 			ill_refhold(ill);
24345 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24346 			    CUR_OP, B_FALSE);
24347 			return;
24348 		case AR_ARP_CLOSING:
24349 			/*
24350 			 * ARP (above us) is closing. If no ARP bringup is
24351 			 * currently pending, ack the message so that ARP
24352 			 * can complete its close. Also mark ill_arp_closing
24353 			 * so that new ARP bringups will fail. If any
24354 			 * ARP bringup is currently in progress, we will
24355 			 * ack this when the current ARP bringup completes.
24356 			 */
24357 			ASSERT(q->q_next != NULL);
24358 			ill = (ill_t *)q->q_ptr;
24359 			mutex_enter(&ill->ill_lock);
24360 			ill->ill_arp_closing = 1;
24361 			if (!ill->ill_arp_bringup_pending) {
24362 				mutex_exit(&ill->ill_lock);
24363 				qreply(q, mp);
24364 			} else {
24365 				mutex_exit(&ill->ill_lock);
24366 				freemsg(mp);
24367 			}
24368 			return;
24369 		default:
24370 			break;
24371 		}
24372 		break;
24373 	case M_PROTO:
24374 	case M_PCPROTO:
24375 		/*
24376 		 * The only PROTO messages we expect are ULP binds and
24377 		 * copies of option negotiation acknowledgements.
24378 		 */
24379 		switch (((union T_primitives *)mp->b_rptr)->type) {
24380 		case O_T_BIND_REQ:
24381 		case T_BIND_REQ: {
24382 			/* Request can get queued in bind */
24383 			ASSERT(connp != NULL);
24384 			/*
24385 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
24386 			 * instead of going through this path.  We only get
24387 			 * here in the following cases:
24388 			 *
24389 			 * a. Bind retries, where ipsq is non-NULL.
24390 			 * b. T_BIND_REQ is issued from non TCP/UDP
24391 			 *    transport, e.g. icmp for raw socket,
24392 			 *    in which case ipsq will be NULL.
24393 			 */
24394 			ASSERT(ipsq != NULL ||
24395 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
24396 
24397 			/* Don't increment refcnt if this is a re-entry */
24398 			if (ipsq == NULL)
24399 				CONN_INC_REF(connp);
24400 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
24401 			    connp, NULL) : ip_bind_v4(q, mp, connp);
24402 			if (mp == NULL)
24403 				return;
24404 			if (IPCL_IS_TCP(connp)) {
24405 				/*
24406 				 * In the case of TCP endpoint we
24407 				 * come here only for bind retries
24408 				 */
24409 				ASSERT(ipsq != NULL);
24410 				CONN_INC_REF(connp);
24411 				squeue_fill(connp->conn_sqp, mp,
24412 				    ip_resume_tcp_bind, connp,
24413 				    SQTAG_BIND_RETRY);
24414 				return;
24415 			} else if (IPCL_IS_UDP(connp)) {
24416 				/*
24417 				 * In the case of UDP endpoint we
24418 				 * come here only for bind retries
24419 				 */
24420 				ASSERT(ipsq != NULL);
24421 				udp_resume_bind(connp, mp);
24422 				return;
24423 			}
24424 			qreply(q, mp);
24425 			CONN_OPER_PENDING_DONE(connp);
24426 			return;
24427 		}
24428 		case T_SVR4_OPTMGMT_REQ:
24429 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24430 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24431 
24432 			ASSERT(connp != NULL);
24433 			if (!snmpcom_req(q, mp, ip_snmp_set,
24434 			    ip_snmp_get, cr)) {
24435 				/*
24436 				 * Call svr4_optcom_req so that it can
24437 				 * generate the ack. We don't come here
24438 				 * if this operation is being restarted.
24439 				 * ip_restart_optmgmt will drop the conn ref.
24440 				 * In the case of ipsec option after the ipsec
24441 				 * load is complete conn_restart_ipsec_waiter
24442 				 * drops the conn ref.
24443 				 */
24444 				ASSERT(ipsq == NULL);
24445 				CONN_INC_REF(connp);
24446 				if (ip_check_for_ipsec_opt(q, mp))
24447 					return;
24448 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24449 				if (err != EINPROGRESS) {
24450 					/* Operation is done */
24451 					CONN_OPER_PENDING_DONE(connp);
24452 				}
24453 			}
24454 			return;
24455 		case T_OPTMGMT_REQ:
24456 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24457 			/*
24458 			 * Note: No snmpcom_req support through new
24459 			 * T_OPTMGMT_REQ.
24460 			 * Call tpi_optcom_req so that it can
24461 			 * generate the ack.
24462 			 */
24463 			ASSERT(connp != NULL);
24464 			ASSERT(ipsq == NULL);
24465 			/*
24466 			 * We don't come here for restart. ip_restart_optmgmt
24467 			 * will drop the conn ref. In the case of ipsec option
24468 			 * after the ipsec load is complete
24469 			 * conn_restart_ipsec_waiter drops the conn ref.
24470 			 */
24471 			CONN_INC_REF(connp);
24472 			if (ip_check_for_ipsec_opt(q, mp))
24473 				return;
24474 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24475 			if (err != EINPROGRESS) {
24476 				/* Operation is done */
24477 				CONN_OPER_PENDING_DONE(connp);
24478 			}
24479 			return;
24480 		case T_UNBIND_REQ:
24481 			mp = ip_unbind(q, mp);
24482 			qreply(q, mp);
24483 			return;
24484 		default:
24485 			/*
24486 			 * Have to drop any DLPI messages coming down from
24487 			 * arp (such as an info_req which would cause ip
24488 			 * to receive an extra info_ack if it was passed
24489 			 * through.
24490 			 */
24491 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24492 			    (int)*(uint_t *)mp->b_rptr));
24493 			freemsg(mp);
24494 			return;
24495 		}
24496 		/* NOTREACHED */
24497 	case IRE_DB_TYPE: {
24498 		nce_t		*nce;
24499 		ill_t		*ill;
24500 		in6_addr_t	gw_addr_v6;
24501 
24502 
24503 		/*
24504 		 * This is a response back from a resolver.  It
24505 		 * consists of a message chain containing:
24506 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24507 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24508 		 * The LL_HDR_MBLK is the DLPI header to use to get
24509 		 * the attached packet, and subsequent ones for the
24510 		 * same destination, transmitted.
24511 		 */
24512 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24513 			break;
24514 		/*
24515 		 * First, check to make sure the resolution succeeded.
24516 		 * If it failed, the second mblk will be empty.
24517 		 * If it is, free the chain, dropping the packet.
24518 		 * (We must ire_delete the ire; that frees the ire mblk)
24519 		 * We're doing this now to support PVCs for ATM; it's
24520 		 * a partial xresolv implementation. When we fully implement
24521 		 * xresolv interfaces, instead of freeing everything here
24522 		 * we'll initiate neighbor discovery.
24523 		 *
24524 		 * For v4 (ARP and other external resolvers) the resolver
24525 		 * frees the message, so no check is needed. This check
24526 		 * is required, though, for a full xresolve implementation.
24527 		 * Including this code here now both shows how external
24528 		 * resolvers can NACK a resolution request using an
24529 		 * existing design that has no specific provisions for NACKs,
24530 		 * and also takes into account that the current non-ARP
24531 		 * external resolver has been coded to use this method of
24532 		 * NACKing for all IPv6 (xresolv) cases,
24533 		 * whether our xresolv implementation is complete or not.
24534 		 *
24535 		 */
24536 		ire = (ire_t *)mp->b_rptr;
24537 		ill = ire_to_ill(ire);
24538 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24539 		if (mp1->b_rptr == mp1->b_wptr) {
24540 			if (ire->ire_ipversion == IPV6_VERSION) {
24541 				/*
24542 				 * XRESOLV interface.
24543 				 */
24544 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24545 				mutex_enter(&ire->ire_lock);
24546 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24547 				mutex_exit(&ire->ire_lock);
24548 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24549 					nce = ndp_lookup(ill,
24550 					    &ire->ire_addr_v6, B_FALSE);
24551 				} else {
24552 					nce = ndp_lookup(ill, &gw_addr_v6,
24553 					    B_FALSE);
24554 				}
24555 				if (nce != NULL) {
24556 					nce_resolv_failed(nce);
24557 					ndp_delete(nce);
24558 					NCE_REFRELE(nce);
24559 				}
24560 			}
24561 			mp->b_cont = NULL;
24562 			freemsg(mp1);		/* frees the pkt as well */
24563 			ire_delete((ire_t *)mp->b_rptr);
24564 			return;
24565 		}
24566 		/*
24567 		 * Split them into IRE_MBLK and pkt and feed it into
24568 		 * ire_add_then_send. Then in ire_add_then_send
24569 		 * the IRE will be added, and then the packet will be
24570 		 * run back through ip_wput. This time it will make
24571 		 * it to the wire.
24572 		 */
24573 		mp->b_cont = NULL;
24574 		mp = mp1->b_cont;		/* now, mp points to pkt */
24575 		mp1->b_cont = NULL;
24576 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24577 		if (ire->ire_ipversion == IPV6_VERSION) {
24578 			/*
24579 			 * XRESOLV interface. Find the nce and put a copy
24580 			 * of the dl_unitdata_req in nce_res_mp
24581 			 */
24582 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24583 			mutex_enter(&ire->ire_lock);
24584 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24585 			mutex_exit(&ire->ire_lock);
24586 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24587 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24588 				    B_FALSE);
24589 			} else {
24590 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24591 			}
24592 			if (nce != NULL) {
24593 				/*
24594 				 * We have to protect nce_res_mp here
24595 				 * from being accessed by other threads
24596 				 * while we change the mblk pointer.
24597 				 * Other functions will also lock the nce when
24598 				 * accessing nce_res_mp.
24599 				 *
24600 				 * The reason we change the mblk pointer
24601 				 * here rather than copying the resolved address
24602 				 * into the template is that, unlike with
24603 				 * ethernet, we have no guarantee that the
24604 				 * resolved address length will be
24605 				 * smaller than or equal to the lla length
24606 				 * with which the template was allocated,
24607 				 * (for ethernet, they're equal)
24608 				 * so we have to use the actual resolved
24609 				 * address mblk - which holds the real
24610 				 * dl_unitdata_req with the resolved address.
24611 				 *
24612 				 * Doing this is the same behavior as was
24613 				 * previously used in the v4 ARP case.
24614 				 */
24615 				mutex_enter(&nce->nce_lock);
24616 				if (nce->nce_res_mp != NULL)
24617 					freemsg(nce->nce_res_mp);
24618 				nce->nce_res_mp = mp1;
24619 				mutex_exit(&nce->nce_lock);
24620 				/*
24621 				 * We do a fastpath probe here because
24622 				 * we have resolved the address without
24623 				 * using Neighbor Discovery.
24624 				 * In the non-XRESOLV v6 case, the fastpath
24625 				 * probe is done right after neighbor
24626 				 * discovery completes.
24627 				 */
24628 				if (nce->nce_res_mp != NULL) {
24629 					int res;
24630 					nce_fastpath_list_add(nce);
24631 					res = ill_fastpath_probe(ill,
24632 					    nce->nce_res_mp);
24633 					if (res != 0 && res != EAGAIN)
24634 						nce_fastpath_list_delete(nce);
24635 				}
24636 
24637 				ire_add_then_send(q, ire, mp);
24638 				/*
24639 				 * Now we have to clean out any packets
24640 				 * that may have been queued on the nce
24641 				 * while it was waiting for address resolution
24642 				 * to complete.
24643 				 */
24644 				mutex_enter(&nce->nce_lock);
24645 				mp1 = nce->nce_qd_mp;
24646 				nce->nce_qd_mp = NULL;
24647 				mutex_exit(&nce->nce_lock);
24648 				while (mp1 != NULL) {
24649 					mblk_t *nxt_mp;
24650 					queue_t *fwdq = NULL;
24651 					ill_t   *inbound_ill;
24652 					uint_t ifindex;
24653 
24654 					nxt_mp = mp1->b_next;
24655 					mp1->b_next = NULL;
24656 					/*
24657 					 * Retrieve ifindex stored in
24658 					 * ip_rput_data_v6()
24659 					 */
24660 					ifindex =
24661 					    (uint_t)(uintptr_t)mp1->b_prev;
24662 					inbound_ill =
24663 						ill_lookup_on_ifindex(ifindex,
24664 						    B_TRUE, NULL, NULL, NULL,
24665 						    NULL);
24666 					mp1->b_prev = NULL;
24667 					if (inbound_ill != NULL)
24668 						fwdq = inbound_ill->ill_rq;
24669 
24670 					if (fwdq != NULL) {
24671 						put(fwdq, mp1);
24672 						ill_refrele(inbound_ill);
24673 					} else
24674 						put(WR(ill->ill_rq), mp1);
24675 					mp1 = nxt_mp;
24676 				}
24677 				NCE_REFRELE(nce);
24678 			} else {	/* nce is NULL; clean up */
24679 				ire_delete(ire);
24680 				freemsg(mp);
24681 				freemsg(mp1);
24682 				return;
24683 			}
24684 		} else {
24685 			ire->ire_dlureq_mp = mp1;
24686 			ire_add_then_send(q, ire, mp);
24687 		}
24688 		return;	/* All is well, the packet has been sent. */
24689 	}
24690 	default:
24691 		break;
24692 	}
24693 	if (q->q_next) {
24694 		putnext(q, mp);
24695 	} else
24696 		freemsg(mp);
24697 }
24698 
24699 /*
24700  * Process IP options in an outbound packet.  Modify the destination if there
24701  * is a source route option.
24702  * Returns non-zero if something fails in which case an ICMP error has been
24703  * sent and mp freed.
24704  */
24705 static int
24706 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24707     boolean_t mctl_present, zoneid_t zoneid)
24708 {
24709 	ipoptp_t	opts;
24710 	uchar_t		*opt;
24711 	uint8_t		optval;
24712 	uint8_t		optlen;
24713 	ipaddr_t	dst;
24714 	intptr_t	code = 0;
24715 	mblk_t		*mp;
24716 	ire_t		*ire = NULL;
24717 
24718 	ip2dbg(("ip_wput_options\n"));
24719 	mp = ipsec_mp;
24720 	if (mctl_present) {
24721 		mp = ipsec_mp->b_cont;
24722 	}
24723 
24724 	dst = ipha->ipha_dst;
24725 	for (optval = ipoptp_first(&opts, ipha);
24726 	    optval != IPOPT_EOL;
24727 	    optval = ipoptp_next(&opts)) {
24728 		opt = opts.ipoptp_cur;
24729 		optlen = opts.ipoptp_len;
24730 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24731 		    optval, optlen));
24732 		switch (optval) {
24733 			uint32_t off;
24734 		case IPOPT_SSRR:
24735 		case IPOPT_LSRR:
24736 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24737 				ip1dbg((
24738 				    "ip_wput_options: bad option offset\n"));
24739 				code = (char *)&opt[IPOPT_OLEN] -
24740 				    (char *)ipha;
24741 				goto param_prob;
24742 			}
24743 			off = opt[IPOPT_OFFSET];
24744 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24745 			    ntohl(dst)));
24746 			/*
24747 			 * For strict: verify that dst is directly
24748 			 * reachable.
24749 			 */
24750 			if (optval == IPOPT_SSRR) {
24751 				ire = ire_ftable_lookup(dst, 0, 0,
24752 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24753 				    MATCH_IRE_TYPE);
24754 				if (ire == NULL) {
24755 					ip1dbg(("ip_wput_options: SSRR not"
24756 					    " directly reachable: 0x%x\n",
24757 					    ntohl(dst)));
24758 					goto bad_src_route;
24759 				}
24760 				ire_refrele(ire);
24761 			}
24762 			break;
24763 		case IPOPT_RR:
24764 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24765 				ip1dbg((
24766 				    "ip_wput_options: bad option offset\n"));
24767 				code = (char *)&opt[IPOPT_OLEN] -
24768 				    (char *)ipha;
24769 				goto param_prob;
24770 			}
24771 			break;
24772 		case IPOPT_TS:
24773 			/*
24774 			 * Verify that length >=5 and that there is either
24775 			 * room for another timestamp or that the overflow
24776 			 * counter is not maxed out.
24777 			 */
24778 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24779 			if (optlen < IPOPT_MINLEN_IT) {
24780 				goto param_prob;
24781 			}
24782 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24783 				ip1dbg((
24784 				    "ip_wput_options: bad option offset\n"));
24785 				code = (char *)&opt[IPOPT_OFFSET] -
24786 				    (char *)ipha;
24787 				goto param_prob;
24788 			}
24789 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24790 			case IPOPT_TS_TSONLY:
24791 				off = IPOPT_TS_TIMELEN;
24792 				break;
24793 			case IPOPT_TS_TSANDADDR:
24794 			case IPOPT_TS_PRESPEC:
24795 			case IPOPT_TS_PRESPEC_RFC791:
24796 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24797 				break;
24798 			default:
24799 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24800 				    (char *)ipha;
24801 				goto param_prob;
24802 			}
24803 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24804 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24805 				/*
24806 				 * No room and the overflow counter is 15
24807 				 * already.
24808 				 */
24809 				goto param_prob;
24810 			}
24811 			break;
24812 		}
24813 	}
24814 
24815 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24816 		return (0);
24817 
24818 	ip1dbg(("ip_wput_options: error processing IP options."));
24819 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24820 
24821 param_prob:
24822 	/*
24823 	 * Since ip_wput() isn't close to finished, we fill
24824 	 * in enough of the header for credible error reporting.
24825 	 */
24826 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24827 		/* Failed */
24828 		freemsg(ipsec_mp);
24829 		return (-1);
24830 	}
24831 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24832 	return (-1);
24833 
24834 bad_src_route:
24835 	/*
24836 	 * Since ip_wput() isn't close to finished, we fill
24837 	 * in enough of the header for credible error reporting.
24838 	 */
24839 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24840 		/* Failed */
24841 		freemsg(ipsec_mp);
24842 		return (-1);
24843 	}
24844 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24845 	return (-1);
24846 }
24847 
24848 /*
24849  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
24850  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
24851  * thru /etc/system.
24852  */
24853 #define	CONN_MAXDRAINCNT	64
24854 
24855 static void
24856 conn_drain_init(void)
24857 {
24858 	int i;
24859 
24860 	conn_drain_list_cnt = conn_drain_nthreads;
24861 
24862 	if ((conn_drain_list_cnt == 0) ||
24863 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
24864 		/*
24865 		 * Default value of the number of drainers is the
24866 		 * number of cpus, subject to maximum of 8 drainers.
24867 		 */
24868 		if (boot_max_ncpus != -1)
24869 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
24870 		else
24871 			conn_drain_list_cnt = MIN(max_ncpus, 8);
24872 	}
24873 
24874 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
24875 	    KM_SLEEP);
24876 
24877 	for (i = 0; i < conn_drain_list_cnt; i++) {
24878 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
24879 		    MUTEX_DEFAULT, NULL);
24880 	}
24881 }
24882 
24883 static void
24884 conn_drain_fini(void)
24885 {
24886 	int i;
24887 
24888 	for (i = 0; i < conn_drain_list_cnt; i++)
24889 		mutex_destroy(&conn_drain_list[i].idl_lock);
24890 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
24891 	conn_drain_list = NULL;
24892 }
24893 
24894 /*
24895  * Note: For an overview of how flowcontrol is handled in IP please see the
24896  * IP Flowcontrol notes at the top of this file.
24897  *
24898  * Flow control has blocked us from proceeding. Insert the given conn in one
24899  * of the conn drain lists. These conn wq's will be qenabled later on when
24900  * STREAMS flow control does a backenable. conn_walk_drain will enable
24901  * the first conn in each of these drain lists. Each of these qenabled conns
24902  * in turn enables the next in the list, after it runs, or when it closes,
24903  * thus sustaining the drain process.
24904  *
24905  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
24906  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
24907  * running at any time, on a given conn, since there can be only 1 service proc
24908  * running on a queue at any time.
24909  */
24910 void
24911 conn_drain_insert(conn_t *connp)
24912 {
24913 	idl_t	*idl;
24914 	uint_t	index;
24915 
24916 	mutex_enter(&connp->conn_lock);
24917 	if (connp->conn_state_flags & CONN_CLOSING) {
24918 		/*
24919 		 * The conn is closing as a result of which CONN_CLOSING
24920 		 * is set. Return.
24921 		 */
24922 		mutex_exit(&connp->conn_lock);
24923 		return;
24924 	} else if (connp->conn_idl == NULL) {
24925 		/*
24926 		 * Assign the next drain list round robin. We dont' use
24927 		 * a lock, and thus it may not be strictly round robin.
24928 		 * Atomicity of load/stores is enough to make sure that
24929 		 * conn_drain_list_index is always within bounds.
24930 		 */
24931 		index = conn_drain_list_index;
24932 		ASSERT(index < conn_drain_list_cnt);
24933 		connp->conn_idl = &conn_drain_list[index];
24934 		index++;
24935 		if (index == conn_drain_list_cnt)
24936 			index = 0;
24937 		conn_drain_list_index = index;
24938 	}
24939 	mutex_exit(&connp->conn_lock);
24940 
24941 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24942 	if ((connp->conn_drain_prev != NULL) ||
24943 	    (connp->conn_state_flags & CONN_CLOSING)) {
24944 		/*
24945 		 * The conn is already in the drain list, OR
24946 		 * the conn is closing. We need to check again for
24947 		 * the closing case again since close can happen
24948 		 * after we drop the conn_lock, and before we
24949 		 * acquire the CONN_DRAIN_LIST_LOCK.
24950 		 */
24951 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24952 		return;
24953 	} else {
24954 		idl = connp->conn_idl;
24955 	}
24956 
24957 	/*
24958 	 * The conn is not in the drain list. Insert it at the
24959 	 * tail of the drain list. The drain list is circular
24960 	 * and doubly linked. idl_conn points to the 1st element
24961 	 * in the list.
24962 	 */
24963 	if (idl->idl_conn == NULL) {
24964 		idl->idl_conn = connp;
24965 		connp->conn_drain_next = connp;
24966 		connp->conn_drain_prev = connp;
24967 	} else {
24968 		conn_t *head = idl->idl_conn;
24969 
24970 		connp->conn_drain_next = head;
24971 		connp->conn_drain_prev = head->conn_drain_prev;
24972 		head->conn_drain_prev->conn_drain_next = connp;
24973 		head->conn_drain_prev = connp;
24974 	}
24975 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24976 }
24977 
24978 /*
24979  * This conn is closing, and we are called from ip_close. OR
24980  * This conn has been serviced by ip_wsrv, and we need to do the tail
24981  * processing.
24982  * If this conn is part of the drain list, we may need to sustain the drain
24983  * process by qenabling the next conn in the drain list. We may also need to
24984  * remove this conn from the list, if it is done.
24985  */
24986 static void
24987 conn_drain_tail(conn_t *connp, boolean_t closing)
24988 {
24989 	idl_t *idl;
24990 
24991 	/*
24992 	 * connp->conn_idl is stable at this point, and no lock is needed
24993 	 * to check it. If we are called from ip_close, close has already
24994 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
24995 	 * called us only because conn_idl is non-null. If we are called thru
24996 	 * service, conn_idl could be null, but it cannot change because
24997 	 * service is single-threaded per queue, and there cannot be another
24998 	 * instance of service trying to call conn_drain_insert on this conn
24999 	 * now.
25000 	 */
25001 	ASSERT(!closing || (connp->conn_idl != NULL));
25002 
25003 	/*
25004 	 * If connp->conn_idl is null, the conn has not been inserted into any
25005 	 * drain list even once since creation of the conn. Just return.
25006 	 */
25007 	if (connp->conn_idl == NULL)
25008 		return;
25009 
25010 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25011 
25012 	if (connp->conn_drain_prev == NULL) {
25013 		/* This conn is currently not in the drain list.  */
25014 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25015 		return;
25016 	}
25017 	idl = connp->conn_idl;
25018 	if (idl->idl_conn_draining == connp) {
25019 		/*
25020 		 * This conn is the current drainer. If this is the last conn
25021 		 * in the drain list, we need to do more checks, in the 'if'
25022 		 * below. Otherwwise we need to just qenable the next conn,
25023 		 * to sustain the draining, and is handled in the 'else'
25024 		 * below.
25025 		 */
25026 		if (connp->conn_drain_next == idl->idl_conn) {
25027 			/*
25028 			 * This conn is the last in this list. This round
25029 			 * of draining is complete. If idl_repeat is set,
25030 			 * it means another flow enabling has happened from
25031 			 * the driver/streams and we need to another round
25032 			 * of draining.
25033 			 * If there are more than 2 conns in the drain list,
25034 			 * do a left rotate by 1, so that all conns except the
25035 			 * conn at the head move towards the head by 1, and the
25036 			 * the conn at the head goes to the tail. This attempts
25037 			 * a more even share for all queues that are being
25038 			 * drained.
25039 			 */
25040 			if ((connp->conn_drain_next != connp) &&
25041 			    (idl->idl_conn->conn_drain_next != connp)) {
25042 				idl->idl_conn = idl->idl_conn->conn_drain_next;
25043 			}
25044 			if (idl->idl_repeat) {
25045 				qenable(idl->idl_conn->conn_wq);
25046 				idl->idl_conn_draining = idl->idl_conn;
25047 				idl->idl_repeat = 0;
25048 			} else {
25049 				idl->idl_conn_draining = NULL;
25050 			}
25051 		} else {
25052 			/*
25053 			 * If the next queue that we are now qenable'ing,
25054 			 * is closing, it will remove itself from this list
25055 			 * and qenable the subsequent queue in ip_close().
25056 			 * Serialization is acheived thru idl_lock.
25057 			 */
25058 			qenable(connp->conn_drain_next->conn_wq);
25059 			idl->idl_conn_draining = connp->conn_drain_next;
25060 		}
25061 	}
25062 	if (!connp->conn_did_putbq || closing) {
25063 		/*
25064 		 * Remove ourself from the drain list, if we did not do
25065 		 * a putbq, or if the conn is closing.
25066 		 * Note: It is possible that q->q_first is non-null. It means
25067 		 * that these messages landed after we did a enableok() in
25068 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
25069 		 * service them.
25070 		 */
25071 		if (connp->conn_drain_next == connp) {
25072 			/* Singleton in the list */
25073 			ASSERT(connp->conn_drain_prev == connp);
25074 			idl->idl_conn = NULL;
25075 			idl->idl_conn_draining = NULL;
25076 		} else {
25077 			connp->conn_drain_prev->conn_drain_next =
25078 			    connp->conn_drain_next;
25079 			connp->conn_drain_next->conn_drain_prev =
25080 			    connp->conn_drain_prev;
25081 			if (idl->idl_conn == connp)
25082 				idl->idl_conn = connp->conn_drain_next;
25083 			ASSERT(idl->idl_conn_draining != connp);
25084 
25085 		}
25086 		connp->conn_drain_next = NULL;
25087 		connp->conn_drain_prev = NULL;
25088 	}
25089 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25090 }
25091 
25092 /*
25093  * Write service routine. Shared perimeter entry point.
25094  * ip_wsrv can be called in any of the following ways.
25095  * 1. The device queue's messages has fallen below the low water mark
25096  *    and STREAMS has backenabled the ill_wq. We walk thru all the
25097  *    the drain lists and backenable the first conn in each list.
25098  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
25099  *    qenabled non-tcp upper layers. We start dequeing messages and call
25100  *    ip_wput for each message.
25101  */
25102 
25103 void
25104 ip_wsrv(queue_t *q)
25105 {
25106 	conn_t	*connp;
25107 	ill_t	*ill;
25108 	mblk_t	*mp;
25109 
25110 	if (q->q_next) {
25111 		ill = (ill_t *)q->q_ptr;
25112 		if (ill->ill_state_flags == 0) {
25113 			/*
25114 			 * The device flow control has opened up.
25115 			 * Walk through conn drain lists and qenable the
25116 			 * first conn in each list. This makes sense only
25117 			 * if the stream is fully plumbed and setup.
25118 			 * Hence the if check above.
25119 			 */
25120 			ip1dbg(("ip_wsrv: walking\n"));
25121 			conn_walk_drain();
25122 		}
25123 		return;
25124 	}
25125 
25126 	connp = Q_TO_CONN(q);
25127 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
25128 
25129 	/*
25130 	 * 1. Set conn_draining flag to signal that service is active.
25131 	 *
25132 	 * 2. ip_output determines whether it has been called from service,
25133 	 *    based on the last parameter. If it is IP_WSRV it concludes it
25134 	 *    has been called from service.
25135 	 *
25136 	 * 3. Message ordering is preserved by the following logic.
25137 	 *    i. A directly called ip_output (i.e. not thru service) will queue
25138 	 *    the message at the tail, if conn_draining is set (i.e. service
25139 	 *    is running) or if q->q_first is non-null.
25140 	 *
25141 	 *    ii. If ip_output is called from service, and if ip_output cannot
25142 	 *    putnext due to flow control, it does a putbq.
25143 	 *
25144 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
25145 	 *    (causing an infinite loop).
25146 	 */
25147 	ASSERT(!connp->conn_did_putbq);
25148 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
25149 		connp->conn_draining = 1;
25150 		noenable(q);
25151 		while ((mp = getq(q)) != NULL) {
25152 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
25153 			if (connp->conn_did_putbq) {
25154 				/* ip_wput did a putbq */
25155 				break;
25156 			}
25157 		}
25158 		/*
25159 		 * At this point, a thread coming down from top, calling
25160 		 * ip_wput, may end up queueing the message. We have not yet
25161 		 * enabled the queue, so ip_wsrv won't be called again.
25162 		 * To avoid this race, check q->q_first again (in the loop)
25163 		 * If the other thread queued the message before we call
25164 		 * enableok(), we will catch it in the q->q_first check.
25165 		 * If the other thread queues the message after we call
25166 		 * enableok(), ip_wsrv will be called again by STREAMS.
25167 		 */
25168 		connp->conn_draining = 0;
25169 		enableok(q);
25170 	}
25171 
25172 	/* Enable the next conn for draining */
25173 	conn_drain_tail(connp, B_FALSE);
25174 
25175 	connp->conn_did_putbq = 0;
25176 }
25177 
25178 /*
25179  * Walk the list of all conn's calling the function provided with the
25180  * specified argument for each.	 Note that this only walks conn's that
25181  * have been bound.
25182  * Applies to both IPv4 and IPv6.
25183  */
25184 static void
25185 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
25186 {
25187 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
25188 	    func, arg, zoneid);
25189 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
25190 	    func, arg, zoneid);
25191 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
25192 	    func, arg, zoneid);
25193 	conn_walk_fanout_table(ipcl_proto_fanout,
25194 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
25195 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
25196 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
25197 }
25198 
25199 /*
25200  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
25201  * of conns that need to be drained, check if drain is already in progress.
25202  * If so set the idl_repeat bit, indicating that the last conn in the list
25203  * needs to reinitiate the drain once again, for the list. If drain is not
25204  * in progress for the list, initiate the draining, by qenabling the 1st
25205  * conn in the list. The drain is self-sustaining, each qenabled conn will
25206  * in turn qenable the next conn, when it is done/blocked/closing.
25207  */
25208 static void
25209 conn_walk_drain(void)
25210 {
25211 	int i;
25212 	idl_t *idl;
25213 
25214 	IP_STAT(ip_conn_walk_drain);
25215 
25216 	for (i = 0; i < conn_drain_list_cnt; i++) {
25217 		idl = &conn_drain_list[i];
25218 		mutex_enter(&idl->idl_lock);
25219 		if (idl->idl_conn == NULL) {
25220 			mutex_exit(&idl->idl_lock);
25221 			continue;
25222 		}
25223 		/*
25224 		 * If this list is not being drained currently by
25225 		 * an ip_wsrv thread, start the process.
25226 		 */
25227 		if (idl->idl_conn_draining == NULL) {
25228 			ASSERT(idl->idl_repeat == 0);
25229 			qenable(idl->idl_conn->conn_wq);
25230 			idl->idl_conn_draining = idl->idl_conn;
25231 		} else {
25232 			idl->idl_repeat = 1;
25233 		}
25234 		mutex_exit(&idl->idl_lock);
25235 	}
25236 }
25237 
25238 /*
25239  * Walk an conn hash table of `count' buckets, calling func for each entry.
25240  */
25241 static void
25242 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
25243     zoneid_t zoneid)
25244 {
25245 	conn_t	*connp;
25246 
25247 	while (count-- > 0) {
25248 		mutex_enter(&connfp->connf_lock);
25249 		for (connp = connfp->connf_head; connp != NULL;
25250 		    connp = connp->conn_next) {
25251 			if (zoneid == GLOBAL_ZONEID ||
25252 			    zoneid == connp->conn_zoneid) {
25253 				CONN_INC_REF(connp);
25254 				mutex_exit(&connfp->connf_lock);
25255 				(*func)(connp, arg);
25256 				mutex_enter(&connfp->connf_lock);
25257 				CONN_DEC_REF(connp);
25258 			}
25259 		}
25260 		mutex_exit(&connfp->connf_lock);
25261 		connfp++;
25262 	}
25263 }
25264 
25265 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
25266 static void
25267 conn_report1(conn_t *connp, void *mp)
25268 {
25269 	char	buf1[INET6_ADDRSTRLEN];
25270 	char	buf2[INET6_ADDRSTRLEN];
25271 	uint_t	print_len, buf_len;
25272 
25273 	ASSERT(connp != NULL);
25274 
25275 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
25276 	if (buf_len <= 0)
25277 		return;
25278 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
25279 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
25280 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
25281 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
25282 	    "%5d %s/%05d %s/%05d\n",
25283 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
25284 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
25285 	    buf1, connp->conn_lport,
25286 	    buf2, connp->conn_fport);
25287 	if (print_len < buf_len) {
25288 		((mblk_t *)mp)->b_wptr += print_len;
25289 	} else {
25290 		((mblk_t *)mp)->b_wptr += buf_len;
25291 	}
25292 }
25293 
25294 /*
25295  * Named Dispatch routine to produce a formatted report on all conns
25296  * that are listed in one of the fanout tables.
25297  * This report is accessed by using the ndd utility to "get" ND variable
25298  * "ip_conn_status".
25299  */
25300 /* ARGSUSED */
25301 static int
25302 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
25303 {
25304 	(void) mi_mpprintf(mp,
25305 	    "CONN      " MI_COL_HDRPAD_STR
25306 	    "rfq      " MI_COL_HDRPAD_STR
25307 	    "stq      " MI_COL_HDRPAD_STR
25308 	    " zone local                 remote");
25309 
25310 	/*
25311 	 * Because of the ndd constraint, at most we can have 64K buffer
25312 	 * to put in all conn info.  So to be more efficient, just
25313 	 * allocate a 64K buffer here, assuming we need that large buffer.
25314 	 * This should be OK as only privileged processes can do ndd /dev/ip.
25315 	 */
25316 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
25317 		/* The following may work even if we cannot get a large buf. */
25318 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
25319 		return (0);
25320 	}
25321 
25322 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
25323 	return (0);
25324 }
25325 
25326 /*
25327  * Determine if the ill and multicast aspects of that packets
25328  * "matches" the conn.
25329  */
25330 boolean_t
25331 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
25332     zoneid_t zoneid)
25333 {
25334 	ill_t *in_ill;
25335 	boolean_t found;
25336 	ipif_t *ipif;
25337 	ire_t *ire;
25338 	ipaddr_t dst, src;
25339 
25340 	dst = ipha->ipha_dst;
25341 	src = ipha->ipha_src;
25342 
25343 	/*
25344 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
25345 	 * unicast, broadcast and multicast reception to
25346 	 * conn_incoming_ill. conn_wantpacket itself is called
25347 	 * only for BROADCAST and multicast.
25348 	 *
25349 	 * 1) ip_rput supresses duplicate broadcasts if the ill
25350 	 *    is part of a group. Hence, we should be receiving
25351 	 *    just one copy of broadcast for the whole group.
25352 	 *    Thus, if it is part of the group the packet could
25353 	 *    come on any ill of the group and hence we need a
25354 	 *    match on the group. Otherwise, match on ill should
25355 	 *    be sufficient.
25356 	 *
25357 	 * 2) ip_rput does not suppress duplicate multicast packets.
25358 	 *    If there are two interfaces in a ill group and we have
25359 	 *    2 applications (conns) joined a multicast group G on
25360 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25361 	 *    will give us two packets because we join G on both the
25362 	 *    interfaces rather than nominating just one interface
25363 	 *    for receiving multicast like broadcast above. So,
25364 	 *    we have to call ilg_lookup_ill to filter out duplicate
25365 	 *    copies, if ill is part of a group.
25366 	 */
25367 	in_ill = connp->conn_incoming_ill;
25368 	if (in_ill != NULL) {
25369 		if (in_ill->ill_group == NULL) {
25370 			if (in_ill != ill)
25371 				return (B_FALSE);
25372 		} else if (in_ill->ill_group != ill->ill_group) {
25373 			return (B_FALSE);
25374 		}
25375 	}
25376 
25377 	if (!CLASSD(dst)) {
25378 		if (connp->conn_zoneid == zoneid)
25379 			return (B_TRUE);
25380 		/*
25381 		 * The conn is in a different zone; we need to check that this
25382 		 * broadcast address is configured in the application's zone and
25383 		 * on one ill in the group.
25384 		 */
25385 		ipif = ipif_get_next_ipif(NULL, ill);
25386 		if (ipif == NULL)
25387 			return (B_FALSE);
25388 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25389 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25390 		ipif_refrele(ipif);
25391 		if (ire != NULL) {
25392 			ire_refrele(ire);
25393 			return (B_TRUE);
25394 		} else {
25395 			return (B_FALSE);
25396 		}
25397 	}
25398 
25399 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25400 	    connp->conn_zoneid == zoneid) {
25401 		/*
25402 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25403 		 * disabled, therefore we don't dispatch the multicast packet to
25404 		 * the sending zone.
25405 		 */
25406 		return (B_FALSE);
25407 	}
25408 
25409 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25410 	    connp->conn_zoneid != zoneid) {
25411 		/*
25412 		 * Multicast packet on the loopback interface: we only match
25413 		 * conns who joined the group in the specified zone.
25414 		 */
25415 		return (B_FALSE);
25416 	}
25417 
25418 	if (connp->conn_multi_router) {
25419 		/* multicast packet and multicast router socket: send up */
25420 		return (B_TRUE);
25421 	}
25422 
25423 	mutex_enter(&connp->conn_lock);
25424 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25425 	mutex_exit(&connp->conn_lock);
25426 	return (found);
25427 }
25428 
25429 /*
25430  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25431  */
25432 /* ARGSUSED */
25433 static void
25434 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25435 {
25436 	ill_t *ill = (ill_t *)q->q_ptr;
25437 	mblk_t	*mp1, *mp2;
25438 	ipif_t  *ipif;
25439 	int err = 0;
25440 	conn_t *connp = NULL;
25441 	ipsq_t	*ipsq;
25442 	arc_t	*arc;
25443 
25444 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25445 
25446 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25447 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25448 
25449 	ASSERT(IAM_WRITER_ILL(ill));
25450 	mp2 = mp->b_cont;
25451 	mp->b_cont = NULL;
25452 
25453 	/*
25454 	 * We have now received the arp bringup completion message
25455 	 * from ARP. Mark the arp bringup as done. Also if the arp
25456 	 * stream has already started closing, send up the AR_ARP_CLOSING
25457 	 * ack now since ARP is waiting in close for this ack.
25458 	 */
25459 	mutex_enter(&ill->ill_lock);
25460 	ill->ill_arp_bringup_pending = 0;
25461 	if (ill->ill_arp_closing) {
25462 		mutex_exit(&ill->ill_lock);
25463 		/* Let's reuse the mp for sending the ack */
25464 		arc = (arc_t *)mp->b_rptr;
25465 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25466 		arc->arc_cmd = AR_ARP_CLOSING;
25467 		qreply(q, mp);
25468 	} else {
25469 		mutex_exit(&ill->ill_lock);
25470 		freeb(mp);
25471 	}
25472 
25473 	/* We should have an IOCTL waiting on this. */
25474 	ipsq = ill->ill_phyint->phyint_ipsq;
25475 	ipif = ipsq->ipsq_pending_ipif;
25476 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25477 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25478 	if (mp1 == NULL) {
25479 		/* bringup was aborted by the user */
25480 		freemsg(mp2);
25481 		return;
25482 	}
25483 	ASSERT(connp != NULL);
25484 	q = CONNP_TO_WQ(connp);
25485 	/*
25486 	 * If the DL_BIND_REQ fails, it is noted
25487 	 * in arc_name_offset.
25488 	 */
25489 	err = *((int *)mp2->b_rptr);
25490 	if (err == 0) {
25491 		if (ipif->ipif_isv6) {
25492 			if ((err = ipif_up_done_v6(ipif)) != 0)
25493 				ip0dbg(("ip_arp_done: init failed\n"));
25494 		} else {
25495 			if ((err = ipif_up_done(ipif)) != 0)
25496 				ip0dbg(("ip_arp_done: init failed\n"));
25497 		}
25498 	} else {
25499 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25500 	}
25501 
25502 	freemsg(mp2);
25503 
25504 	if ((err == 0) && (ill->ill_up_ipifs)) {
25505 		err = ill_up_ipifs(ill, q, mp1);
25506 		if (err == EINPROGRESS)
25507 			return;
25508 	}
25509 
25510 	if (ill->ill_up_ipifs) {
25511 		ill_group_cleanup(ill);
25512 	}
25513 
25514 	/*
25515 	 * The ioctl must complete now without EINPROGRESS
25516 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25517 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25518 	 * stuck for ever in the ipsq.
25519 	 */
25520 	ASSERT(err != EINPROGRESS);
25521 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25522 }
25523 
25524 /* Allocate the private structure */
25525 static int
25526 ip_priv_alloc(void **bufp)
25527 {
25528 	void	*buf;
25529 
25530 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25531 		return (ENOMEM);
25532 
25533 	*bufp = buf;
25534 	return (0);
25535 }
25536 
25537 /* Function to delete the private structure */
25538 void
25539 ip_priv_free(void *buf)
25540 {
25541 	ASSERT(buf != NULL);
25542 	kmem_free(buf, sizeof (ip_priv_t));
25543 }
25544 
25545 /*
25546  * The entry point for IPPF processing.
25547  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25548  * routine just returns.
25549  *
25550  * When called, ip_process generates an ipp_packet_t structure
25551  * which holds the state information for this packet and invokes the
25552  * the classifier (via ipp_packet_process). The classification, depending on
25553  * configured filters, results in a list of actions for this packet. Invoking
25554  * an action may cause the packet to be dropped, in which case the resulting
25555  * mblk (*mpp) is NULL. proc indicates the callout position for
25556  * this packet and ill_index is the interface this packet on or will leave
25557  * on (inbound and outbound resp.).
25558  */
25559 void
25560 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25561 {
25562 	mblk_t		*mp;
25563 	ip_priv_t	*priv;
25564 	ipp_action_id_t	aid;
25565 	int		rc = 0;
25566 	ipp_packet_t	*pp;
25567 #define	IP_CLASS	"ip"
25568 
25569 	/* If the classifier is not loaded, return  */
25570 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25571 		return;
25572 	}
25573 
25574 	mp = *mpp;
25575 	ASSERT(mp != NULL);
25576 
25577 	/* Allocate the packet structure */
25578 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25579 	if (rc != 0) {
25580 		*mpp = NULL;
25581 		freemsg(mp);
25582 		return;
25583 	}
25584 
25585 	/* Allocate the private structure */
25586 	rc = ip_priv_alloc((void **)&priv);
25587 	if (rc != 0) {
25588 		*mpp = NULL;
25589 		freemsg(mp);
25590 		ipp_packet_free(pp);
25591 		return;
25592 	}
25593 	priv->proc = proc;
25594 	priv->ill_index = ill_index;
25595 	ipp_packet_set_private(pp, priv, ip_priv_free);
25596 	ipp_packet_set_data(pp, mp);
25597 
25598 	/* Invoke the classifier */
25599 	rc = ipp_packet_process(&pp);
25600 	if (pp != NULL) {
25601 		mp = ipp_packet_get_data(pp);
25602 		ipp_packet_free(pp);
25603 		if (rc != 0) {
25604 			freemsg(mp);
25605 			*mpp = NULL;
25606 		}
25607 	} else {
25608 		*mpp = NULL;
25609 	}
25610 #undef	IP_CLASS
25611 }
25612 
25613 /*
25614  * Propagate a multicast group membership operation (add/drop) on
25615  * all the interfaces crossed by the related multirt routes.
25616  * The call is considered successful if the operation succeeds
25617  * on at least one interface.
25618  */
25619 static int
25620 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25621     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25622     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25623     mblk_t *first_mp)
25624 {
25625 	ire_t		*ire_gw;
25626 	irb_t		*irb;
25627 	int		error = 0;
25628 	opt_restart_t	*or;
25629 
25630 	irb = ire->ire_bucket;
25631 	ASSERT(irb != NULL);
25632 
25633 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25634 
25635 	or = (opt_restart_t *)first_mp->b_rptr;
25636 	IRB_REFHOLD(irb);
25637 	for (; ire != NULL; ire = ire->ire_next) {
25638 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25639 			continue;
25640 		if (ire->ire_addr != group)
25641 			continue;
25642 
25643 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25644 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25645 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25646 		/* No resolver exists for the gateway; skip this ire. */
25647 		if (ire_gw == NULL)
25648 			continue;
25649 
25650 		/*
25651 		 * This function can return EINPROGRESS. If so the operation
25652 		 * will be restarted from ip_restart_optmgmt which will
25653 		 * call ip_opt_set and option processing will restart for
25654 		 * this option. So we may end up calling 'fn' more than once.
25655 		 * This requires that 'fn' is idempotent except for the
25656 		 * return value. The operation is considered a success if
25657 		 * it succeeds at least once on any one interface.
25658 		 */
25659 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25660 		    NULL, fmode, src, first_mp);
25661 		if (error == 0)
25662 			or->or_private = CGTP_MCAST_SUCCESS;
25663 
25664 		if (ip_debug > 0) {
25665 			ulong_t	off;
25666 			char	*ksym;
25667 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25668 			ip2dbg(("ip_multirt_apply_membership: "
25669 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25670 			    "error %d [success %u]\n",
25671 			    ksym ? ksym : "?",
25672 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25673 			    error, or->or_private));
25674 		}
25675 
25676 		ire_refrele(ire_gw);
25677 		if (error == EINPROGRESS) {
25678 			IRB_REFRELE(irb);
25679 			return (error);
25680 		}
25681 	}
25682 	IRB_REFRELE(irb);
25683 	/*
25684 	 * Consider the call as successful if we succeeded on at least
25685 	 * one interface. Otherwise, return the last encountered error.
25686 	 */
25687 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25688 }
25689 
25690 
25691 /*
25692  * Issue a warning regarding a route crossing an interface with an
25693  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25694  * amount of time is logged.
25695  */
25696 static void
25697 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25698 {
25699 	hrtime_t	current = gethrtime();
25700 	char		buf[16];
25701 
25702 	/* Convert interval in ms to hrtime in ns */
25703 	if (multirt_bad_mtu_last_time +
25704 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25705 	    current) {
25706 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25707 		    "to %s, incorrect MTU %u (expected %u)\n",
25708 		    ip_dot_addr(ire->ire_addr, buf),
25709 		    ire->ire_max_frag, max_frag);
25710 
25711 		multirt_bad_mtu_last_time = current;
25712 	}
25713 }
25714 
25715 
25716 /*
25717  * Get the CGTP (multirouting) filtering status.
25718  * If 0, the CGTP hooks are transparent.
25719  */
25720 /* ARGSUSED */
25721 static int
25722 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25723 {
25724 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25725 
25726 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25727 	return (0);
25728 }
25729 
25730 
25731 /*
25732  * Set the CGTP (multirouting) filtering status.
25733  * If the status is changed from active to transparent
25734  * or from transparent to active, forward the new status
25735  * to the filtering module (if loaded).
25736  */
25737 /* ARGSUSED */
25738 static int
25739 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25740     cred_t *ioc_cr)
25741 {
25742 	long		new_value;
25743 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25744 
25745 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25746 	    new_value < 0 || new_value > 1) {
25747 		return (EINVAL);
25748 	}
25749 
25750 	/*
25751 	 * Do not enable CGTP filtering - thus preventing the hooks
25752 	 * from being invoked - if the version number of the
25753 	 * filtering module hooks does not match.
25754 	 */
25755 	if ((ip_cgtp_filter_ops != NULL) &&
25756 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25757 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25758 		    "(module hooks version %d, expecting %d)\n",
25759 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25760 		return (ENOTSUP);
25761 	}
25762 
25763 	if ((!*ip_cgtp_filter_value) && new_value) {
25764 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25765 		    ip_cgtp_filter_ops == NULL ?
25766 		    " (module not loaded)" : "");
25767 	}
25768 	if (*ip_cgtp_filter_value && (!new_value)) {
25769 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25770 		    ip_cgtp_filter_ops == NULL ?
25771 		    " (module not loaded)" : "");
25772 	}
25773 
25774 	if (ip_cgtp_filter_ops != NULL) {
25775 		int	res;
25776 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25777 			return (res);
25778 		}
25779 	}
25780 
25781 	*ip_cgtp_filter_value = (boolean_t)new_value;
25782 
25783 	return (0);
25784 }
25785 
25786 
25787 /*
25788  * Return the expected CGTP hooks version number.
25789  */
25790 int
25791 ip_cgtp_filter_supported(void)
25792 {
25793 	return (ip_cgtp_filter_rev);
25794 }
25795 
25796 
25797 /*
25798  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25799  * or by invoking this function. In the first case, the version number
25800  * of the registered structure is checked at hooks activation time
25801  * in ip_cgtp_filter_set().
25802  */
25803 int
25804 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25805 {
25806 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25807 		return (ENOTSUP);
25808 
25809 	ip_cgtp_filter_ops = ops;
25810 	return (0);
25811 }
25812 
25813 static squeue_func_t
25814 ip_squeue_switch(int val)
25815 {
25816 	squeue_func_t rval = squeue_fill;
25817 
25818 	switch (val) {
25819 	case IP_SQUEUE_ENTER_NODRAIN:
25820 		rval = squeue_enter_nodrain;
25821 		break;
25822 	case IP_SQUEUE_ENTER:
25823 		rval = squeue_enter;
25824 		break;
25825 	default:
25826 		break;
25827 	}
25828 	return (rval);
25829 }
25830 
25831 /* ARGSUSED */
25832 static int
25833 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25834     caddr_t addr, cred_t *cr)
25835 {
25836 	int *v = (int *)addr;
25837 	long new_value;
25838 
25839 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25840 		return (EINVAL);
25841 
25842 	ip_input_proc = ip_squeue_switch(new_value);
25843 	*v = new_value;
25844 	return (0);
25845 }
25846 
25847 /* ARGSUSED */
25848 static int
25849 ip_fanout_set(queue_t *q, mblk_t *mp, char *value,
25850     caddr_t addr, cred_t *cr)
25851 {
25852 	int *v = (int *)addr;
25853 	long new_value;
25854 
25855 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25856 		return (EINVAL);
25857 
25858 	*v = new_value;
25859 	return (0);
25860 }
25861 
25862 
25863 static void
25864 ip_kstat_init(void)
25865 {
25866 	ip_named_kstat_t template = {
25867 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
25868 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
25869 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
25870 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
25871 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
25872 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
25873 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
25874 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
25875 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
25876 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
25877 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
25878 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
25879 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
25880 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
25881 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
25882 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
25883 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
25884 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
25885 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
25886 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
25887 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
25888 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
25889 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
25890 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
25891 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
25892 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
25893 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
25894 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
25895 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
25896 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
25897 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
25898 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
25899 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
25900 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
25901 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
25902 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
25903 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
25904 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
25905 	};
25906 
25907 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
25908 					NUM_OF_FIELDS(ip_named_kstat_t),
25909 					0);
25910 	if (!ip_mibkp)
25911 		return;
25912 
25913 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
25914 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
25915 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
25916 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
25917 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
25918 
25919 	template.netToMediaEntrySize.value.i32 =
25920 		sizeof (mib2_ipNetToMediaEntry_t);
25921 
25922 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
25923 
25924 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
25925 
25926 	ip_mibkp->ks_update = ip_kstat_update;
25927 
25928 	kstat_install(ip_mibkp);
25929 }
25930 
25931 static void
25932 ip_kstat_fini(void)
25933 {
25934 
25935 	if (ip_mibkp != NULL) {
25936 		kstat_delete(ip_mibkp);
25937 		ip_mibkp = NULL;
25938 	}
25939 }
25940 
25941 static int
25942 ip_kstat_update(kstat_t *kp, int rw)
25943 {
25944 	ip_named_kstat_t *ipkp;
25945 
25946 	if (!kp || !kp->ks_data)
25947 		return (EIO);
25948 
25949 	if (rw == KSTAT_WRITE)
25950 		return (EACCES);
25951 
25952 	ipkp = (ip_named_kstat_t *)kp->ks_data;
25953 
25954 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
25955 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
25956 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
25957 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
25958 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
25959 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
25960 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
25961 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
25962 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
25963 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
25964 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
25965 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
25966 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
25967 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
25968 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
25969 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
25970 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
25971 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
25972 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
25973 
25974 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
25975 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
25976 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
25977 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
25978 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
25979 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
25980 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
25981 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
25982 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
25983 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
25984 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
25985 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
25986 
25987 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
25988 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
25989 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
25990 
25991 	return (0);
25992 }
25993 
25994 static void
25995 icmp_kstat_init(void)
25996 {
25997 	icmp_named_kstat_t template = {
25998 		{ "inMsgs",		KSTAT_DATA_UINT32 },
25999 		{ "inErrors",		KSTAT_DATA_UINT32 },
26000 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
26001 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
26002 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
26003 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
26004 		{ "inRedirects",	KSTAT_DATA_UINT32 },
26005 		{ "inEchos",		KSTAT_DATA_UINT32 },
26006 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
26007 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
26008 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
26009 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
26010 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
26011 		{ "outMsgs",		KSTAT_DATA_UINT32 },
26012 		{ "outErrors",		KSTAT_DATA_UINT32 },
26013 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
26014 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
26015 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
26016 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
26017 		{ "outRedirects",	KSTAT_DATA_UINT32 },
26018 		{ "outEchos",		KSTAT_DATA_UINT32 },
26019 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
26020 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
26021 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
26022 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
26023 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
26024 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
26025 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
26026 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
26027 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
26028 		{ "outDrops",		KSTAT_DATA_UINT32 },
26029 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
26030 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
26031 	};
26032 
26033 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
26034 					NUM_OF_FIELDS(icmp_named_kstat_t),
26035 					0);
26036 	if (icmp_mibkp == NULL)
26037 		return;
26038 
26039 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
26040 
26041 	icmp_mibkp->ks_update = icmp_kstat_update;
26042 
26043 	kstat_install(icmp_mibkp);
26044 }
26045 
26046 static void
26047 icmp_kstat_fini(void)
26048 {
26049 
26050 	if (icmp_mibkp != NULL) {
26051 		kstat_delete(icmp_mibkp);
26052 		icmp_mibkp = NULL;
26053 	}
26054 }
26055 
26056 static int
26057 icmp_kstat_update(kstat_t *kp, int rw)
26058 {
26059 	icmp_named_kstat_t *icmpkp;
26060 
26061 	if ((kp == NULL) || (kp->ks_data == NULL))
26062 		return (EIO);
26063 
26064 	if (rw == KSTAT_WRITE)
26065 		return (EACCES);
26066 
26067 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
26068 
26069 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
26070 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
26071 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
26072 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
26073 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
26074 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
26075 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
26076 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
26077 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
26078 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
26079 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
26080 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
26081 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
26082 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
26083 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
26084 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
26085 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
26086 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
26087 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
26088 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
26089 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
26090 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
26091 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
26092 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
26093 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
26094 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
26095 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
26096 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
26097 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
26098 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
26099 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
26100 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
26101 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
26102 
26103 	return (0);
26104 }
26105 
26106 /*
26107  * This is the fanout function for raw socket opened for SCTP.  Note
26108  * that it is called after SCTP checks that there is no socket which
26109  * wants a packet.  Then before SCTP handles this out of the blue packet,
26110  * this function is called to see if there is any raw socket for SCTP.
26111  * If there is and it is bound to the correct address, the packet will
26112  * be sent to that socket.  Note that only one raw socket can be bound to
26113  * a port.  This is assured in ipcl_sctp_hash_insert();
26114  */
26115 void
26116 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
26117     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
26118     uint_t ipif_seqid, zoneid_t zoneid)
26119 {
26120 	conn_t		*connp;
26121 	queue_t		*rq;
26122 	mblk_t		*first_mp;
26123 	boolean_t	secure;
26124 	ip6_t		*ip6h;
26125 
26126 	first_mp = mp;
26127 	if (mctl_present) {
26128 		mp = first_mp->b_cont;
26129 		secure = ipsec_in_is_secure(first_mp);
26130 		ASSERT(mp != NULL);
26131 	} else {
26132 		secure = B_FALSE;
26133 	}
26134 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
26135 
26136 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
26137 	if (connp == NULL) {
26138 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
26139 		    mctl_present);
26140 		return;
26141 	}
26142 	rq = connp->conn_rq;
26143 	if (!canputnext(rq)) {
26144 		CONN_DEC_REF(connp);
26145 		BUMP_MIB(&ip_mib, rawipInOverflows);
26146 		freemsg(first_mp);
26147 		return;
26148 	}
26149 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
26150 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
26151 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
26152 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
26153 		if (first_mp == NULL) {
26154 			CONN_DEC_REF(connp);
26155 			return;
26156 		}
26157 	}
26158 	/*
26159 	 * We probably should not send M_CTL message up to
26160 	 * raw socket.
26161 	 */
26162 	if (mctl_present)
26163 		freeb(first_mp);
26164 
26165 	/* Initiate IPPF processing here if needed. */
26166 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
26167 	    (!isv4 && IP6_IN_IPP(flags))) {
26168 		ip_process(IPP_LOCAL_IN, &mp,
26169 		    recv_ill->ill_phyint->phyint_ifindex);
26170 		if (mp == NULL) {
26171 			CONN_DEC_REF(connp);
26172 			return;
26173 		}
26174 	}
26175 
26176 	if (connp->conn_recvif || connp->conn_recvslla ||
26177 	    ((connp->conn_ipv6_recvpktinfo ||
26178 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
26179 	    (flags & IP_FF_IP6INFO))) {
26180 		int in_flags = 0;
26181 
26182 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
26183 			in_flags = IPF_RECVIF;
26184 		}
26185 		if (connp->conn_recvslla) {
26186 			in_flags |= IPF_RECVSLLA;
26187 		}
26188 		if (isv4) {
26189 			mp = ip_add_info(mp, recv_ill, in_flags);
26190 		} else {
26191 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
26192 			if (mp == NULL) {
26193 				CONN_DEC_REF(connp);
26194 				return;
26195 			}
26196 		}
26197 	}
26198 
26199 	BUMP_MIB(&ip_mib, ipInDelivers);
26200 	/*
26201 	 * We are sending the IPSEC_IN message also up. Refer
26202 	 * to comments above this function.
26203 	 */
26204 	putnext(rq, mp);
26205 	CONN_DEC_REF(connp);
26206 }
26207 
26208 /*
26209  * Martian Address Filtering [RFC 1812, Section 5.3.7]
26210  */
26211 static boolean_t
26212 ip_no_forward(ipha_t *ipha, ill_t *ill)
26213 {
26214 	ipaddr_t ip_src, ip_dst;
26215 	ire_t *src_ire = NULL;
26216 
26217 	ip_src = ntohl(ipha->ipha_src);
26218 	ip_dst = ntohl(ipha->ipha_dst);
26219 
26220 	if (ip_dst == INADDR_ANY)
26221 		goto dont_forward;
26222 
26223 	if (IN_CLASSD(ip_src))
26224 		goto dont_forward;
26225 
26226 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
26227 		goto dont_forward;
26228 
26229 	if (IN_BADCLASS(ip_dst))
26230 		goto dont_forward;
26231 
26232 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
26233 	    ALL_ZONES, MATCH_IRE_TYPE);
26234 	if (src_ire != NULL) {
26235 		ire_refrele(src_ire);
26236 		goto dont_forward;
26237 	}
26238 
26239 	return (B_FALSE);
26240 
26241 dont_forward:
26242 	if (ip_debug > 2) {
26243 		printf("ip_no_forward: dropping packet received on %s\n",
26244 		    ill->ill_name);
26245 		pr_addr_dbg("ip_no_forward: from src %s\n",
26246 		    AF_INET, &ipha->ipha_src);
26247 		pr_addr_dbg("ip_no_forward: to dst %s\n",
26248 		    AF_INET, &ipha->ipha_dst);
26249 	}
26250 	BUMP_MIB(&ip_mib, ipForwProhibits);
26251 	return (B_TRUE);
26252 }
26253 
26254 static boolean_t
26255 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
26256 {
26257 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
26258 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
26259 		if (ip_debug > 2) {
26260 			if (ill != NULL) {
26261 				printf("ip_loopback_src_or_dst: "
26262 				    "dropping packet received on %s\n",
26263 				    ill->ill_name);
26264 			} else {
26265 				printf("ip_loopback_src_or_dst: "
26266 				    "dropping packet\n");
26267 			}
26268 
26269 			pr_addr_dbg(
26270 			    "ip_loopback_src_or_dst: from src %s\n",
26271 			    AF_INET, &ipha->ipha_src);
26272 			pr_addr_dbg(
26273 			    "ip_loopback_src_or_dst: to dst %s\n",
26274 			    AF_INET, &ipha->ipha_dst);
26275 		}
26276 
26277 		BUMP_MIB(&ip_mib, ipInAddrErrors);
26278 		return (B_TRUE);
26279 	}
26280 	return (B_FALSE);
26281 }
26282