xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 29e362da24db33a6650152985ef5626b4e6a810f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/socket.h>
54 #include <sys/vtrace.h>
55 #include <sys/isa_defs.h>
56 #include <net/if.h>
57 #include <net/if_arp.h>
58 #include <net/route.h>
59 #include <sys/sockio.h>
60 #include <netinet/in.h>
61 #include <net/if_dl.h>
62 
63 #include <inet/common.h>
64 #include <inet/mi.h>
65 #include <inet/mib2.h>
66 #include <inet/nd.h>
67 #include <inet/arp.h>
68 #include <inet/snmpcom.h>
69 #include <inet/kstatcom.h>
70 
71 #include <netinet/igmp_var.h>
72 #include <netinet/ip6.h>
73 #include <netinet/icmp6.h>
74 #include <netinet/sctp.h>
75 
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip6_asp.h>
80 #include <inet/tcp.h>
81 #include <inet/tcp_impl.h>
82 #include <inet/ip_multi.h>
83 #include <inet/ip_if.h>
84 #include <inet/ip_ire.h>
85 #include <inet/ip_rts.h>
86 #include <inet/optcom.h>
87 #include <inet/ip_ndp.h>
88 #include <inet/ip_listutils.h>
89 #include <netinet/igmp.h>
90 #include <netinet/ip_mroute.h>
91 #include <inet/ipp_common.h>
92 
93 #include <net/pfkeyv2.h>
94 #include <inet/ipsec_info.h>
95 #include <inet/sadb.h>
96 #include <inet/ipsec_impl.h>
97 #include <sys/iphada.h>
98 #include <inet/tun.h>
99 #include <inet/ipdrop.h>
100 
101 #include <sys/ethernet.h>
102 #include <net/if_types.h>
103 #include <sys/cpuvar.h>
104 
105 #include <ipp/ipp.h>
106 #include <ipp/ipp_impl.h>
107 #include <ipp/ipgpc/ipgpc.h>
108 
109 #include <sys/multidata.h>
110 #include <sys/pattr.h>
111 
112 #include <inet/ipclassifier.h>
113 #include <inet/sctp_ip.h>
114 #include <inet/udp_impl.h>
115 
116 /*
117  * Values for squeue switch:
118  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
119  * IP_SQUEUE_ENTER: squeue_enter
120  * IP_SQUEUE_FILL: squeue_fill
121  */
122 int ip_squeue_enter = 2;
123 squeue_func_t ip_input_proc;
124 /*
125  * IP statistics.
126  */
127 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
128 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
129 
130 typedef struct ip_stat {
131 	kstat_named_t	ipsec_fanout_proto;
132 	kstat_named_t	ip_udp_fannorm;
133 	kstat_named_t	ip_udp_fanmb;
134 	kstat_named_t	ip_udp_fanothers;
135 	kstat_named_t	ip_udp_fast_path;
136 	kstat_named_t	ip_udp_slow_path;
137 	kstat_named_t	ip_udp_input_err;
138 	kstat_named_t	ip_tcppullup;
139 	kstat_named_t	ip_tcpoptions;
140 	kstat_named_t	ip_multipkttcp;
141 	kstat_named_t	ip_tcp_fast_path;
142 	kstat_named_t	ip_tcp_slow_path;
143 	kstat_named_t	ip_tcp_input_error;
144 	kstat_named_t	ip_db_ref;
145 	kstat_named_t	ip_notaligned1;
146 	kstat_named_t	ip_notaligned2;
147 	kstat_named_t	ip_multimblk3;
148 	kstat_named_t	ip_multimblk4;
149 	kstat_named_t	ip_ipoptions;
150 	kstat_named_t	ip_classify_fail;
151 	kstat_named_t	ip_opt;
152 	kstat_named_t	ip_udp_rput_local;
153 	kstat_named_t	ipsec_proto_ahesp;
154 	kstat_named_t	ip_conn_flputbq;
155 	kstat_named_t	ip_conn_walk_drain;
156 	kstat_named_t   ip_out_sw_cksum;
157 	kstat_named_t   ip_in_sw_cksum;
158 	kstat_named_t   ip_trash_ire_reclaim_calls;
159 	kstat_named_t   ip_trash_ire_reclaim_success;
160 	kstat_named_t   ip_ire_arp_timer_expired;
161 	kstat_named_t   ip_ire_redirect_timer_expired;
162 	kstat_named_t	ip_ire_pmtu_timer_expired;
163 	kstat_named_t	ip_input_multi_squeue;
164 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
165 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
166 	kstat_named_t	ip_tcp_in_sw_cksum_err;
167 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
168 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
169 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
170 	kstat_named_t	ip_udp_in_sw_cksum_err;
171 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
172 	kstat_named_t	ip_frag_mdt_pkt_out;
173 	kstat_named_t	ip_frag_mdt_discarded;
174 	kstat_named_t	ip_frag_mdt_allocfail;
175 	kstat_named_t	ip_frag_mdt_addpdescfail;
176 	kstat_named_t	ip_frag_mdt_allocd;
177 } ip_stat_t;
178 
179 static ip_stat_t ip_statistics = {
180 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
181 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
182 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
183 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
184 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
185 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
186 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
187 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
188 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
189 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
190 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
191 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
192 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
193 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
194 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
195 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
196 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
197 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
198 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
199 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
200 	{ "ip_opt",				KSTAT_DATA_UINT64 },
201 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
202 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
203 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
204 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
205 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
206 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
207 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
208 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
209 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
210 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
211 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
212 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
213 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
214 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
215 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
216 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
217 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
218 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
219 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
220 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
221 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
222 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
223 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
224 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
225 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
226 };
227 
228 static kstat_t *ip_kstat;
229 
230 #define	TCP6 "tcp6"
231 #define	TCP "tcp"
232 #define	SCTP "sctp"
233 #define	SCTP6 "sctp6"
234 
235 major_t TCP6_MAJ;
236 major_t TCP_MAJ;
237 major_t SCTP_MAJ;
238 major_t SCTP6_MAJ;
239 
240 int ip_poll_normal_ms = 100;
241 int ip_poll_normal_ticks = 0;
242 
243 /*
244  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
245  */
246 
247 struct listptr_s {
248 	mblk_t	*lp_head;	/* pointer to the head of the list */
249 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
250 };
251 
252 typedef struct listptr_s listptr_t;
253 
254 /*
255  * Cluster specific hooks. These should be NULL when booted as a non-cluster
256  */
257 
258 /*
259  * Hook functions to enable cluster networking
260  * On non-clustered systems these vectors must always be NULL.
261  *
262  * Hook function to Check ip specified ip address is a shared ip address
263  * in the cluster
264  *
265  */
266 int (*cl_inet_isclusterwide)(uint8_t protocol,
267     sa_family_t addr_family, uint8_t *laddrp) = NULL;
268 
269 /*
270  * Hook function to generate cluster wide ip fragment identifier
271  */
272 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
273     uint8_t *laddrp, uint8_t *faddrp) = NULL;
274 
275 /*
276  * Synchronization notes:
277  *
278  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
279  * MT level protection given by STREAMS. IP uses a combination of its own
280  * internal serialization mechanism and standard Solaris locking techniques.
281  * The internal serialization is per phyint (no IPMP) or per IPMP group.
282  * This is used to serialize plumbing operations, IPMP operations, certain
283  * multicast operations, most set ioctls, igmp/mld timers etc.
284  *
285  * Plumbing is a long sequence of operations involving message
286  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
287  * involved in plumbing operations. A natural model is to serialize these
288  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
289  * parallel without any interference. But various set ioctls on hme0 are best
290  * serialized. However if the system uses IPMP, the operations are easier if
291  * they are serialized on a per IPMP group basis since IPMP operations
292  * happen across ill's of a group. Thus the lowest common denominator is to
293  * serialize most set ioctls, multicast join/leave operations, IPMP operations
294  * igmp/mld timer operations, and processing of DLPI control messages received
295  * from drivers on a per IPMP group basis. If the system does not employ
296  * IPMP the serialization is on a per phyint basis. This serialization is
297  * provided by the ipsq_t and primitives operating on this. Details can
298  * be found in ip_if.c above the core primitives operating on ipsq_t.
299  *
300  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
301  * Simiarly lookup of an ire by a thread also returns a refheld ire.
302  * In addition ipif's and ill's referenced by the ire are also indirectly
303  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
304  * the ipif's address or netmask change as long as an ipif is refheld
305  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
306  * address of an ipif has to go through the ipsq_t. This ensures that only
307  * 1 such exclusive operation proceeds at any time on the ipif. It then
308  * deletes all ires associated with this ipif, and waits for all refcnts
309  * associated with this ipif to come down to zero. The address is changed
310  * only after the ipif has been quiesced. Then the ipif is brought up again.
311  * More details are described above the comment in ip_sioctl_flags.
312  *
313  * Packet processing is based mostly on IREs and are fully multi-threaded
314  * using standard Solaris MT techniques.
315  *
316  * There are explicit locks in IP to handle:
317  * - The ip_g_head list maintained by mi_open_link() and friends.
318  *
319  * - The reassembly data structures (one lock per hash bucket)
320  *
321  * - conn_lock is meant to protect conn_t fields. The fields actually
322  *   protected by conn_lock are documented in the conn_t definition.
323  *
324  * - ire_lock to protect some of the fields of the ire, IRE tables
325  *   (one lock per hash bucket). Refer to ip_ire.c for details.
326  *
327  * - ndp_g_lock and nce_lock for protecting NCEs.
328  *
329  * - ill_lock protects fields of the ill and ipif. Details in ip.h
330  *
331  * - ill_g_lock: This is a global reader/writer lock. Protects the following
332  *	* The AVL tree based global multi list of all ills.
333  *	* The linked list of all ipifs of an ill
334  *	* The <ill-ipsq> mapping
335  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
336  *	* The illgroup list threaded by ill_group_next.
337  *	* <ill-phyint> association
338  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
339  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
340  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
341  *   will all have to hold the ill_g_lock as writer for the actual duration
342  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
343  *   may be found in the IPMP section.
344  *
345  * - ill_lock:  This is a per ill mutex.
346  *   It protects some members of the ill and is documented below.
347  *   It also protects the <ill-ipsq> mapping
348  *   It also protects the illgroup list threaded by ill_group_next.
349  *   It also protects the <ill-phyint> assoc.
350  *   It also protects the list of ipifs hanging off the ill.
351  *
352  * - ipsq_lock: This is a per ipsq_t mutex lock.
353  *   This protects all the other members of the ipsq struct except
354  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
355  *
356  * - illgrp_lock: This is a per ill_group mutex lock.
357  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
358  *   which dictates which is the next ill in an ill_group that is to be chosen
359  *   for sending outgoing packets, through creation of an IRE_CACHE that
360  *   references this ill.
361  *
362  * - phyint_lock: This is a per phyint mutex lock. Protects just the
363  *   phyint_flags
364  *
365  * - ip_g_nd_lock: This is a global reader/writer lock.
366  *   Any call to nd_load to load a new parameter to the ND table must hold the
367  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
368  *   as reader.
369  *
370  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
371  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
372  *   uniqueness check also done atomically.
373  *
374  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
375  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
376  *   as a writer when adding or deleting elements from these lists, and
377  *   as a reader when walking these lists to send a SADB update to the
378  *   IPsec capable ills.
379  *
380  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
381  *   group list linked by ill_usesrc_grp_next. It also protects the
382  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
383  *   group is being added or deleted.  This lock is taken as a reader when
384  *   walking the list/group(eg: to get the number of members in a usesrc group).
385  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
386  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
387  *   example, it is not necessary to take this lock in the initial portion
388  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
389  *   ip_sioctl_flags since the these operations are executed exclusively and
390  *   that ensures that the "usesrc group state" cannot change. The "usesrc
391  *   group state" change can happen only in the latter part of
392  *   ip_sioctl_slifusesrc and in ill_delete.
393  *
394  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
395  *
396  * To change the <ill-phyint> association, the ill_g_lock must be held
397  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
398  * must be held.
399  *
400  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
401  * and the ill_lock of the ill in question must be held.
402  *
403  * To change the <ill-illgroup> association the ill_g_lock must be held as
404  * writer and the ill_lock of the ill in question must be held.
405  *
406  * To add or delete an ipif from the list of ipifs hanging off the ill,
407  * ill_g_lock (writer) and ill_lock must be held and the thread must be
408  * a writer on the associated ipsq,.
409  *
410  * To add or delete an ill to the system, the ill_g_lock must be held as
411  * writer and the thread must be a writer on the associated ipsq.
412  *
413  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
414  * must be a writer on the associated ipsq.
415  *
416  * Lock hierarchy
417  *
418  * Some lock hierarchy scenarios are listed below.
419  *
420  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
421  * ill_g_lock -> illgrp_lock -> ill_lock
422  * ill_g_lock -> ill_lock(s) -> phyint_lock
423  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
424  * ill_g_lock -> ip_addr_avail_lock
425  * conn_lock -> irb_lock -> ill_lock -> ire_lock
426  * ipsa_lock -> ill_g_lock -> ill_lock
427  * ill_g_lock -> ip_g_nd_lock
428  * irb_lock -> ill_lock -> ire_mrtun_lock
429  * irb_lock -> ill_lock -> ire_srcif_table_lock
430  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
431  * ipsec_capab_ills_lock -> ipsa_lock
432  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
433  *
434  * When more than 1 ill lock is needed to be held, all ill lock addresses
435  * are sorted on address and locked starting from highest addressed lock
436  * downward.
437  *
438  * IPSEC notes :
439  *
440  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
441  * in front of the actual packet. For outbound datagrams, the M_CTL
442  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
443  * information used by the IPSEC code for applying the right level of
444  * protection. The information initialized by IP in the ipsec_out_t
445  * is determined by the per-socket policy or global policy in the system.
446  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
447  * ipsec_info.h) which starts out with nothing in it. It gets filled
448  * with the right information if it goes through the AH/ESP code, which
449  * happens if the incoming packet is secure. The information initialized
450  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
451  * the policy requirements needed by per-socket policy or global policy
452  * is met or not.
453  *
454  * If there is both per-socket policy (set using setsockopt) and there
455  * is also global policy match for the 5 tuples of the socket,
456  * ipsec_override_policy() makes the decision of which one to use.
457  *
458  * For fully connected sockets i.e dst, src [addr, port] is known,
459  * conn_policy_cached is set indicating that policy has been cached.
460  * conn_in_enforce_policy may or may not be set depending on whether
461  * there is a global policy match or per-socket policy match.
462  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
463  * Once the right policy is set on the conn_t, policy cannot change for
464  * this socket. This makes life simpler for TCP (UDP ?) where
465  * re-transmissions go out with the same policy. For symmetry, policy
466  * is cached for fully connected UDP sockets also. Thus if policy is cached,
467  * it also implies that policy is latched i.e policy cannot change
468  * on these sockets. As we have the right policy on the conn, we don't
469  * have to lookup global policy for every outbound and inbound datagram
470  * and thus serving as an optimization. Note that a global policy change
471  * does not affect fully connected sockets if they have policy. If fully
472  * connected sockets did not have any policy associated with it, global
473  * policy change may affect them.
474  *
475  * IP Flow control notes:
476  *
477  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
478  * cannot be sent down to the driver by IP, because of a canput failure, IP
479  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
480  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
481  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
482  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
483  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
484  * the queued messages, and removes the conn from the drain list, if all
485  * messages were drained. It also qenables the next conn in the drain list to
486  * continue the drain process.
487  *
488  * In reality the drain list is not a single list, but a configurable number
489  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
490  * list. If the ip_wsrv of the next qenabled conn does not run, because the
491  * stream closes, ip_close takes responsibility to qenable the next conn in
492  * the drain list. The directly called ip_wput path always does a putq, if
493  * it cannot putnext. Thus synchronization problems are handled between
494  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
495  * functions that manipulate this drain list. Furthermore conn_drain_insert
496  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
497  * running on a queue at any time. conn_drain_tail can be simultaneously called
498  * from both ip_wsrv and ip_close.
499  *
500  * IPQOS notes:
501  *
502  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
503  * and IPQoS modules. IPPF includes hooks in IP at different control points
504  * (callout positions) which direct packets to IPQoS modules for policy
505  * processing. Policies, if present, are global.
506  *
507  * The callout positions are located in the following paths:
508  *		o local_in (packets destined for this host)
509  *		o local_out (packets orginating from this host )
510  *		o fwd_in  (packets forwarded by this m/c - inbound)
511  *		o fwd_out (packets forwarded by this m/c - outbound)
512  * Hooks at these callout points can be enabled/disabled using the ndd variable
513  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
514  * By default all the callout positions are enabled.
515  *
516  * Outbound (local_out)
517  * Hooks are placed in ip_wput_ire and ipsec_out_process.
518  *
519  * Inbound (local_in)
520  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
521  * TCP and UDP fanout routines.
522  *
523  * Forwarding (in and out)
524  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
525  *
526  * IP Policy Framework processing (IPPF processing)
527  * Policy processing for a packet is initiated by ip_process, which ascertains
528  * that the classifier (ipgpc) is loaded and configured, failing which the
529  * packet resumes normal processing in IP. If the clasifier is present, the
530  * packet is acted upon by one or more IPQoS modules (action instances), per
531  * filters configured in ipgpc and resumes normal IP processing thereafter.
532  * An action instance can drop a packet in course of its processing.
533  *
534  * A boolean variable, ip_policy, is used in all the fanout routines that can
535  * invoke ip_process for a packet. This variable indicates if the packet should
536  * to be sent for policy processing. The variable is set to B_TRUE by default,
537  * i.e. when the routines are invoked in the normal ip procesing path for a
538  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
539  * ip_policy is set to B_FALSE for all the routines called in these two
540  * functions because, in the former case,  we don't process loopback traffic
541  * currently while in the latter, the packets have already been processed in
542  * icmp_inbound.
543  *
544  * Zones notes:
545  *
546  * The partitioning rules for networking are as follows:
547  * 1) Packets coming from a zone must have a source address belonging to that
548  * zone.
549  * 2) Packets coming from a zone can only be sent on a physical interface on
550  * which the zone has an IP address.
551  * 3) Between two zones on the same machine, packet delivery is only allowed if
552  * there's a matching route for the destination and zone in the forwarding
553  * table.
554  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
555  * different zones can bind to the same port with the wildcard address
556  * (INADDR_ANY).
557  *
558  * The granularity of interface partitioning is at the logical interface level.
559  * Therefore, every zone has its own IP addresses, and incoming packets can be
560  * attributed to a zone unambiguously. A logical interface is placed into a zone
561  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
562  * structure. Rule (1) is implemented by modifying the source address selection
563  * algorithm so that the list of eligible addresses is filtered based on the
564  * sending process zone.
565  *
566  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
567  * across all zones, depending on their type. Here is the break-up:
568  *
569  * IRE type				Shared/exclusive
570  * --------				----------------
571  * IRE_BROADCAST			Exclusive
572  * IRE_DEFAULT (default routes)		Shared (*)
573  * IRE_LOCAL				Exclusive
574  * IRE_LOOPBACK				Exclusive
575  * IRE_PREFIX (net routes)		Shared (*)
576  * IRE_CACHE				Exclusive
577  * IRE_IF_NORESOLVER (interface routes)	Exclusive
578  * IRE_IF_RESOLVER (interface routes)	Exclusive
579  * IRE_HOST (host routes)		Shared (*)
580  *
581  * (*) A zone can only use a default or off-subnet route if the gateway is
582  * directly reachable from the zone, that is, if the gateway's address matches
583  * one of the zone's logical interfaces.
584  *
585  * Multiple zones can share a common broadcast address; typically all zones
586  * share the 255.255.255.255 address. Incoming as well as locally originated
587  * broadcast packets must be dispatched to all the zones on the broadcast
588  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
589  * since some zones may not be on the 10.16.72/24 network. To handle this, each
590  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
591  * sent to every zone that has an IRE_BROADCAST entry for the destination
592  * address on the input ill, see conn_wantpacket().
593  *
594  * Applications in different zones can join the same multicast group address.
595  * For IPv4, group memberships are per-logical interface, so they're already
596  * inherently part of a zone. For IPv6, group memberships are per-physical
597  * interface, so we distinguish IPv6 group memberships based on group address,
598  * interface and zoneid. In both cases, received multicast packets are sent to
599  * every zone for which a group membership entry exists. On IPv6 we need to
600  * check that the target zone still has an address on the receiving physical
601  * interface; it could have been removed since the application issued the
602  * IPV6_JOIN_GROUP.
603  */
604 
605 /*
606  * Squeue Fanout flags:
607  *	0: No fanout.
608  *	1: Fanout across all squeues
609  */
610 boolean_t	ip_squeue_fanout = 0;
611 
612 /*
613  * Maximum dups allowed per packet.
614  */
615 uint_t ip_max_frag_dups = 10;
616 
617 #define	IS_SIMPLE_IPH(ipha)						\
618 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
619 
620 /* RFC1122 Conformance */
621 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
622 
623 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
624 
625 /* Leave room for ip_newroute to tack on the src and target addresses */
626 #define	OK_RESOLVER_MP(mp)						\
627 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
628 
629 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
630 
631 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
632 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
633 
634 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
635 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
636     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
637 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
638 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
639 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
640 		    ill_t *, zoneid_t);
641 static void	icmp_options_update(ipha_t *);
642 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
643 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
644 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
645 static void	icmp_redirect(mblk_t *);
646 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
647 
648 static void	ip_arp_news(queue_t *, mblk_t *);
649 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
650 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
651 char		*ip_dot_addr(ipaddr_t, char *);
652 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
653 int		ip_close(queue_t *, int);
654 static char	*ip_dot_saddr(uchar_t *, char *);
655 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
656 		    boolean_t, boolean_t, ill_t *, zoneid_t);
657 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
658 		    boolean_t, boolean_t, zoneid_t);
659 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
660 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
661 static void	ip_lrput(queue_t *, mblk_t *);
662 ipaddr_t	ip_massage_options(ipha_t *);
663 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
664 ipaddr_t	ip_net_mask(ipaddr_t);
665 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
666 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
667 		    conn_t *, uint32_t);
668 static int	ip_hdr_complete(ipha_t *, zoneid_t);
669 char		*ip_nv_lookup(nv_t *, int);
670 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
671 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
672 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
673 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
674 			    size_t);
675 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
676 void	ip_rput(queue_t *, mblk_t *);
677 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
678 		    void *dummy_arg);
679 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
680 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
681 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
682 			    ire_t *);
683 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
684 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
685 		    uint16_t *);
686 int		ip_snmp_get(queue_t *, mblk_t *);
687 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
689 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
690 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
691 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
692 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
693 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
694 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
695 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
696 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
698 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
699 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
700 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
701 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
703 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
704 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
705 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
706 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
707 static boolean_t	ip_source_routed(ipha_t *);
708 static boolean_t	ip_source_route_included(ipha_t *);
709 
710 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
711 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
712 static void	ip_wput_local_options(ipha_t *);
713 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
714     zoneid_t);
715 
716 static void	conn_drain_init(void);
717 static void	conn_drain_fini(void);
718 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(void);
721 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
722     zoneid_t);
723 
724 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
725     zoneid_t);
726 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
727     void *dummy_arg);
728 
729 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
730 
731 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
732     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
733     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
734 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
735 
736 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
737 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
738     caddr_t, cred_t *);
739 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
740     caddr_t cp, cred_t *cr);
741 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
742     cred_t *);
743 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static squeue_func_t ip_squeue_switch(int);
748 
749 static void	ip_kstat_init(void);
750 static void	ip_kstat_fini(void);
751 static int	ip_kstat_update(kstat_t *kp, int rw);
752 static void	icmp_kstat_init(void);
753 static void	icmp_kstat_fini(void);
754 static int	icmp_kstat_update(kstat_t *kp, int rw);
755 
756 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
757 
758 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
759 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
760 
761 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
762     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
763 
764 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
765 
766 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
767 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
768 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
769 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
770 
771 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
772 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
773 
774 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
775 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
776 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
777 
778 /* How long, in seconds, we allow frags to hang around. */
779 #define	IP_FRAG_TIMEOUT	60
780 
781 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
782 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
783 
784 /*
785  * Threshold which determines whether MDT should be used when
786  * generating IP fragments; payload size must be greater than
787  * this threshold for MDT to take place.
788  */
789 #define	IP_WPUT_FRAG_MDT_MIN	32768
790 
791 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
792 
793 /* Protected by ip_mi_lock */
794 static void	*ip_g_head;		/* Instance Data List Head */
795 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
796 
797 /* Only modified during _init and _fini thus no locking is needed. */
798 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
799 
800 
801 static long ip_rput_pullups;
802 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
803 
804 vmem_t *ip_minor_arena;
805 
806 /*
807  * MIB-2 stuff for SNMP (both IP and ICMP)
808  */
809 mib2_ip_t	ip_mib;
810 mib2_icmp_t	icmp_mib;
811 
812 #ifdef DEBUG
813 uint32_t ipsechw_debug = 0;
814 #endif
815 
816 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
817 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
818 
819 uint_t	loopback_packets = 0;
820 
821 /*
822  * Multirouting/CGTP stuff
823  */
824 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
825 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
826 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
827 /* Interval (in ms) between consecutive 'bad MTU' warnings */
828 hrtime_t ip_multirt_log_interval = 1000;
829 /* Time since last warning issued. */
830 static hrtime_t	multirt_bad_mtu_last_time = 0;
831 
832 kmutex_t ip_trash_timer_lock;
833 krwlock_t ip_g_nd_lock;
834 
835 /*
836  * XXX following really should only be in a header. Would need more
837  * header and .c clean up first.
838  */
839 extern optdb_obj_t	ip_opt_obj;
840 
841 ulong_t ip_squeue_enter_unbound = 0;
842 
843 /*
844  * Named Dispatch Parameter Table.
845  * All of these are alterable, within the min/max values given, at run time.
846  */
847 static ipparam_t	lcl_param_arr[] = {
848 	/* min	max	value	name */
849 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
850 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
851 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
852 	{  0,	1,	0,	"ip_respond_to_timestamp"},
853 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
854 	{  0,	1,	1,	"ip_send_redirects"},
855 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
856 	{  0,	10,	0,	"ip_debug"},
857 	{  0,	10,	0,	"ip_mrtdebug"},
858 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
859 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
860 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
861 	{  1,	255,	255,	"ip_def_ttl" },
862 	{  0,	1,	0,	"ip_forward_src_routed"},
863 	{  0,	256,	32,	"ip_wroff_extra" },
864 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
865 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
866 	{  0,	1,	1,	"ip_path_mtu_discovery" },
867 	{  0,	240,	30,	"ip_ignore_delete_time" },
868 	{  0,	1,	0,	"ip_ignore_redirect" },
869 	{  0,	1,	1,	"ip_output_queue" },
870 	{  1,	254,	1,	"ip_broadcast_ttl" },
871 	{  0,	99999,	100,	"ip_icmp_err_interval" },
872 	{  1,	99999,	10,	"ip_icmp_err_burst" },
873 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
874 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
875 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
876 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
877 	{  0,	1,	1,	"icmp_accept_clear_messages" },
878 	{  0,	1,	1,	"igmp_accept_clear_messages" },
879 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
880 				"ip_ndp_delay_first_probe_time"},
881 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
882 				"ip_ndp_max_unicast_solicit"},
883 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
884 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
885 	{  0,	1,	0,	"ip6_forward_src_routed"},
886 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
887 	{  0,	1,	1,	"ip6_send_redirects"},
888 	{  0,	1,	0,	"ip6_ignore_redirect" },
889 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
890 
891 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
892 
893 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
894 
895 	{  0,	1,	1,	"pim_accept_clear_messages" },
896 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
897 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
898 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
899 	{  0,	15,	0,	"ip_policy_mask" },
900 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
901 	{  0,	255,	1,	"ip_multirt_ttl" },
902 	{  0,	1,	1,	"ip_multidata_outbound" },
903 #ifdef DEBUG
904 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
905 #endif
906 };
907 
908 ipparam_t	*ip_param_arr = lcl_param_arr;
909 
910 /* Extended NDP table */
911 static ipndp_t	lcl_ndp_arr[] = {
912 	/* getf			setf		data			name */
913 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
914 	    "ip_forwarding" },
915 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
916 	    "ip6_forwarding" },
917 	{  ip_ill_report,	NULL,		NULL,
918 	    "ip_ill_status" },
919 	{  ip_ipif_report,	NULL,		NULL,
920 	    "ip_ipif_status" },
921 	{  ip_ire_report,	NULL,		NULL,
922 	    "ipv4_ire_status" },
923 	{  ip_ire_report_mrtun,	NULL,		NULL,
924 	    "ipv4_mrtun_ire_status" },
925 	{  ip_ire_report_srcif,	NULL,		NULL,
926 	    "ipv4_srcif_ire_status" },
927 	{  ip_ire_report_v6,	NULL,		NULL,
928 	    "ipv6_ire_status" },
929 	{  ip_conn_report,	NULL,		NULL,
930 	    "ip_conn_status" },
931 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
932 	    "ip_rput_pullups" },
933 	{  ndp_report,		NULL,		NULL,
934 	    "ip_ndp_cache_report" },
935 	{  ip_srcid_report,	NULL,		NULL,
936 	    "ip_srcid_status" },
937 	{ ip_param_generic_get, ip_squeue_profile_set,
938 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
939 	{ ip_param_generic_get, ip_squeue_bind_set,
940 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
941 	{ ip_param_generic_get, ip_input_proc_set,
942 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
943 	{ ip_param_generic_get, ip_int_set,
944 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
945 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
946 	    "ip_cgtp_filter" },
947 	{ ip_param_generic_get, ip_int_set,
948 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
949 };
950 
951 /*
952  * ip_g_forward controls IP forwarding.  It takes two values:
953  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
954  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
955  *
956  * RFC1122 says there must be a configuration switch to control forwarding,
957  * but that the default MUST be to not forward packets ever.  Implicit
958  * control based on configuration of multiple interfaces MUST NOT be
959  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
960  * and, in fact, it was the default.  That capability is now provided in the
961  * /etc/rc2.d/S69inet script.
962  */
963 int ip_g_forward = IP_FORWARD_DEFAULT;
964 
965 /* It also has an IPv6 counterpart. */
966 
967 int ipv6_forward = IP_FORWARD_DEFAULT;
968 
969 /* Following line is external, and in ip.h.  Normally marked with * *. */
970 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
971 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
972 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
973 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
974 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
975 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
976 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
977 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
978 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
979 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
980 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
981 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
982 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
983 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
984 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
985 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
986 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
987 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
988 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
989 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
990 #define	ip_output_queue			ip_param_arr[20].ip_param_value
991 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
992 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
993 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
994 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
995 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
996 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
997 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
998 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
999 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
1000 
1001 /* IPv6 configuration knobs */
1002 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1003 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1004 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1005 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1006 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1007 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1008 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1009 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1010 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1011 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1012 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1013 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1014 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1015 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1016 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1017 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1018 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1019 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1020 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1021 #ifdef DEBUG
1022 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1023 #else
1024 #define	ipv6_drop_inbound_icmpv6	0
1025 #endif
1026 
1027 
1028 /*
1029  * Table of IP ioctls encoding the various properties of the ioctl and
1030  * indexed based on the last byte of the ioctl command. Occasionally there
1031  * is a clash, and there is more than 1 ioctl with the same last byte.
1032  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1033  * ioctls are encoded in the misc table. An entry in the ndx table is
1034  * retrieved by indexing on the last byte of the ioctl command and comparing
1035  * the ioctl command with the value in the ndx table. In the event of a
1036  * mismatch the misc table is then searched sequentially for the desired
1037  * ioctl command.
1038  *
1039  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1040  */
1041 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1042 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 
1053 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1054 			MISC_CMD, ip_siocaddrt, NULL },
1055 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1056 			MISC_CMD, ip_siocdelrt, NULL },
1057 
1058 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1059 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1060 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1061 			IF_CMD, ip_sioctl_get_addr, NULL },
1062 
1063 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1064 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1065 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1066 			IPI_GET_CMD | IPI_REPL,
1067 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1068 
1069 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1070 			IPI_PRIV | IPI_WR | IPI_REPL,
1071 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1072 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1073 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1074 			IF_CMD, ip_sioctl_get_flags, NULL },
1075 
1076 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* copyin size cannot be coded for SIOCGIFCONF */
1080 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1081 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1082 
1083 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1084 			IF_CMD, ip_sioctl_mtu, NULL },
1085 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_mtu, NULL },
1087 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1088 			IPI_GET_CMD | IPI_REPL,
1089 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1090 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1091 			IF_CMD, ip_sioctl_brdaddr, NULL },
1092 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1093 			IPI_GET_CMD | IPI_REPL,
1094 			IF_CMD, ip_sioctl_get_netmask, NULL },
1095 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1096 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1097 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1098 			IPI_GET_CMD | IPI_REPL,
1099 			IF_CMD, ip_sioctl_get_metric, NULL },
1100 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1101 			IF_CMD, ip_sioctl_metric, NULL },
1102 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 
1104 	/* See 166-168 below for extended SIOC*XARP ioctls */
1105 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1106 			MISC_CMD, ip_sioctl_arp, NULL },
1107 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1108 			MISC_CMD, ip_sioctl_arp, NULL },
1109 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1110 			MISC_CMD, ip_sioctl_arp, NULL },
1111 
1112 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 
1134 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1135 			MISC_CMD, if_unitsel, if_unitsel_restart },
1136 
1137 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 
1156 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1157 			IPI_PRIV | IPI_WR | IPI_MODOK,
1158 			IF_CMD, ip_sioctl_sifname, NULL },
1159 
1160 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 
1174 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1175 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1176 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1177 			IF_CMD, ip_sioctl_get_muxid, NULL },
1178 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			IF_CMD, ip_sioctl_muxid, NULL },
1181 
1182 	/* Both if and lif variants share same func */
1183 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1184 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1185 	/* Both if and lif variants share same func */
1186 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1187 			IPI_PRIV | IPI_WR | IPI_REPL,
1188 			IF_CMD, ip_sioctl_slifindex, NULL },
1189 
1190 	/* copyin size cannot be coded for SIOCGIFCONF */
1191 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1192 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1193 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 
1211 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1212 			IPI_PRIV | IPI_WR | IPI_REPL,
1213 			LIF_CMD, ip_sioctl_removeif,
1214 			ip_sioctl_removeif_restart },
1215 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1216 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1217 			LIF_CMD, ip_sioctl_addif, NULL },
1218 #define	SIOCLIFADDR_NDX 112
1219 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1220 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1221 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1222 			IPI_GET_CMD | IPI_REPL,
1223 			LIF_CMD, ip_sioctl_get_addr, NULL },
1224 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1225 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1226 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1227 			IPI_GET_CMD | IPI_REPL,
1228 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1229 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1230 			IPI_PRIV | IPI_WR | IPI_REPL,
1231 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1232 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1233 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_get_flags, NULL },
1235 
1236 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 
1239 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1240 			ip_sioctl_get_lifconf, NULL },
1241 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1242 			LIF_CMD, ip_sioctl_mtu, NULL },
1243 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1244 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1245 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1248 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1250 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1253 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1255 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1256 			IPI_GET_CMD | IPI_REPL,
1257 			LIF_CMD, ip_sioctl_get_metric, NULL },
1258 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1259 			LIF_CMD, ip_sioctl_metric, NULL },
1260 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1261 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1262 			LIF_CMD, ip_sioctl_slifname,
1263 			ip_sioctl_slifname_restart },
1264 
1265 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1266 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1267 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1268 			IPI_GET_CMD | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1270 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1271 			IPI_PRIV | IPI_WR | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_muxid, NULL },
1273 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1274 			IPI_GET_CMD | IPI_REPL,
1275 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1276 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1277 			IPI_PRIV | IPI_WR | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_slifindex, 0 },
1279 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1280 			LIF_CMD, ip_sioctl_token, NULL },
1281 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1282 			IPI_GET_CMD | IPI_REPL,
1283 			LIF_CMD, ip_sioctl_get_token, NULL },
1284 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1286 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1287 			IPI_GET_CMD | IPI_REPL,
1288 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1289 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1290 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1291 
1292 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1293 			IPI_GET_CMD | IPI_REPL,
1294 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1295 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1296 			LIF_CMD, ip_siocdelndp_v6, NULL },
1297 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1298 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1299 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1300 			LIF_CMD, ip_siocsetndp_v6, NULL },
1301 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1302 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1303 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1304 			MISC_CMD, ip_sioctl_tonlink, NULL },
1305 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1306 			MISC_CMD, ip_sioctl_tmysite, NULL },
1307 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1308 			TUN_CMD, ip_sioctl_tunparam, NULL },
1309 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1310 			IPI_PRIV | IPI_WR,
1311 			TUN_CMD, ip_sioctl_tunparam, NULL },
1312 
1313 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1314 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1315 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1316 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1317 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1318 
1319 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1320 			IPI_PRIV | IPI_WR | IPI_REPL,
1321 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1322 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1323 			IPI_PRIV | IPI_WR | IPI_REPL,
1324 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1325 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1326 			IPI_PRIV | IPI_WR,
1327 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1328 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1329 			IPI_GET_CMD | IPI_REPL,
1330 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1331 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1332 			IPI_GET_CMD | IPI_REPL,
1333 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1334 
1335 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1336 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1337 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1338 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1339 
1340 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1341 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1342 
1343 	/* These are handled in ip_sioctl_copyin_setup itself */
1344 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1345 			MISC_CMD, NULL, NULL },
1346 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1347 			MISC_CMD, NULL, NULL },
1348 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1349 
1350 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1351 			ip_sioctl_get_lifconf, NULL },
1352 
1353 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1354 			MISC_CMD, ip_sioctl_xarp, NULL },
1355 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1356 			MISC_CMD, ip_sioctl_xarp, NULL },
1357 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1358 			MISC_CMD, ip_sioctl_xarp, NULL },
1359 
1360 	/* SIOCPOPSOCKFS is not handled by IP */
1361 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1362 
1363 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1364 			IPI_GET_CMD | IPI_REPL,
1365 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1366 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1367 			IPI_PRIV | IPI_WR | IPI_REPL,
1368 			LIF_CMD, ip_sioctl_slifzone,
1369 			ip_sioctl_slifzone_restart },
1370 	/* 172-174 are SCTP ioctls and not handled by IP */
1371 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1372 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1373 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1374 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1375 			IPI_GET_CMD, LIF_CMD,
1376 			ip_sioctl_get_lifusesrc, 0 },
1377 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1378 			IPI_PRIV | IPI_WR,
1379 			LIF_CMD, ip_sioctl_slifusesrc,
1380 			NULL },
1381 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1382 			ip_sioctl_get_lifsrcof, NULL },
1383 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1384 			MISC_CMD, ip_sioctl_msfilter, NULL },
1385 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1386 			MISC_CMD, ip_sioctl_msfilter, NULL },
1387 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1388 			MISC_CMD, ip_sioctl_msfilter, NULL },
1389 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1390 			MISC_CMD, ip_sioctl_msfilter, NULL },
1391 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1392 			ip_sioctl_set_ipmpfailback, NULL }
1393 };
1394 
1395 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1396 
1397 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1398 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1399 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1400 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1401 		TUN_CMD, ip_sioctl_tunparam, NULL },
1402 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1403 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1404 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1405 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1406 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1407 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1408 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1409 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1410 		MISC_CMD, mrt_ioctl},
1411 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1412 		MISC_CMD, mrt_ioctl},
1413 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1414 		MISC_CMD, mrt_ioctl}
1415 };
1416 
1417 int ip_misc_ioctl_count =
1418     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1419 
1420 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1421 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1422 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1423 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1424 					/* Settable in /etc/system */
1425 
1426 /* Defined in ip_ire.c */
1427 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1428 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1429 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1430 
1431 static nv_t	ire_nv_arr[] = {
1432 	{ IRE_BROADCAST, "BROADCAST" },
1433 	{ IRE_LOCAL, "LOCAL" },
1434 	{ IRE_LOOPBACK, "LOOPBACK" },
1435 	{ IRE_CACHE, "CACHE" },
1436 	{ IRE_DEFAULT, "DEFAULT" },
1437 	{ IRE_PREFIX, "PREFIX" },
1438 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1439 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1440 	{ IRE_HOST, "HOST" },
1441 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1442 	{ 0 }
1443 };
1444 
1445 nv_t	*ire_nv_tbl = ire_nv_arr;
1446 
1447 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1448 extern krwlock_t ipsec_capab_ills_lock;
1449 
1450 /* Packet dropper for IP IPsec processing failures */
1451 ipdropper_t ip_dropper;
1452 
1453 /* Simple ICMP IP Header Template */
1454 static ipha_t icmp_ipha = {
1455 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1456 };
1457 
1458 struct module_info ip_mod_info = {
1459 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1460 };
1461 
1462 static struct qinit rinit = {
1463 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1464 	&ip_mod_info
1465 };
1466 
1467 static struct qinit winit = {
1468 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1469 	&ip_mod_info
1470 };
1471 
1472 static struct qinit lrinit = {
1473 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1474 	&ip_mod_info
1475 };
1476 
1477 static struct qinit lwinit = {
1478 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1479 	&ip_mod_info
1480 };
1481 
1482 struct streamtab ipinfo = {
1483 	&rinit, &winit, &lrinit, &lwinit
1484 };
1485 
1486 #ifdef	DEBUG
1487 static boolean_t skip_sctp_cksum = B_FALSE;
1488 #endif
1489 /*
1490  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1491  */
1492 mblk_t *
1493 ip_copymsg(mblk_t *mp)
1494 {
1495 	mblk_t *nmp;
1496 	ipsec_info_t *in;
1497 
1498 	if (mp->b_datap->db_type != M_CTL)
1499 		return (copymsg(mp));
1500 
1501 	in = (ipsec_info_t *)mp->b_rptr;
1502 
1503 	/*
1504 	 * Note that M_CTL is also used for delivering ICMP error messages
1505 	 * upstream to transport layers.
1506 	 */
1507 	if (in->ipsec_info_type != IPSEC_OUT &&
1508 	    in->ipsec_info_type != IPSEC_IN)
1509 		return (copymsg(mp));
1510 
1511 	nmp = copymsg(mp->b_cont);
1512 
1513 	if (in->ipsec_info_type == IPSEC_OUT)
1514 		return (ipsec_out_tag(mp, nmp));
1515 	else
1516 		return (ipsec_in_tag(mp, nmp));
1517 }
1518 
1519 /* Generate an ICMP fragmentation needed message. */
1520 static void
1521 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1522 {
1523 	icmph_t	icmph;
1524 	mblk_t *first_mp;
1525 	boolean_t mctl_present;
1526 
1527 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1528 
1529 	if (!(mp = icmp_pkt_err_ok(mp))) {
1530 		if (mctl_present)
1531 			freeb(first_mp);
1532 		return;
1533 	}
1534 
1535 	bzero(&icmph, sizeof (icmph_t));
1536 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1537 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1538 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1539 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1540 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1541 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1542 }
1543 
1544 /*
1545  * icmp_inbound deals with ICMP messages in the following ways.
1546  *
1547  * 1) It needs to send a reply back and possibly delivering it
1548  *    to the "interested" upper clients.
1549  * 2) It needs to send it to the upper clients only.
1550  * 3) It needs to change some values in IP only.
1551  * 4) It needs to change some values in IP and upper layers e.g TCP.
1552  *
1553  * We need to accomodate icmp messages coming in clear until we get
1554  * everything secure from the wire. If icmp_accept_clear_messages
1555  * is zero we check with the global policy and act accordingly. If
1556  * it is non-zero, we accept the message without any checks. But
1557  * *this does not mean* that this will be delivered to the upper
1558  * clients. By accepting we might send replies back, change our MTU
1559  * value etc. but delivery to the ULP/clients depends on their policy
1560  * dispositions.
1561  *
1562  * We handle the above 4 cases in the context of IPSEC in the
1563  * following way :
1564  *
1565  * 1) Send the reply back in the same way as the request came in.
1566  *    If it came in encrypted, it goes out encrypted. If it came in
1567  *    clear, it goes out in clear. Thus, this will prevent chosen
1568  *    plain text attack.
1569  * 2) The client may or may not expect things to come in secure.
1570  *    If it comes in secure, the policy constraints are checked
1571  *    before delivering it to the upper layers. If it comes in
1572  *    clear, ipsec_inbound_accept_clear will decide whether to
1573  *    accept this in clear or not. In both the cases, if the returned
1574  *    message (IP header + 8 bytes) that caused the icmp message has
1575  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1576  *    sending up. If there are only 8 bytes of returned message, then
1577  *    upper client will not be notified.
1578  * 3) Check with global policy to see whether it matches the constaints.
1579  *    But this will be done only if icmp_accept_messages_in_clear is
1580  *    zero.
1581  * 4) If we need to change both in IP and ULP, then the decision taken
1582  *    while affecting the values in IP and while delivering up to TCP
1583  *    should be the same.
1584  *
1585  * 	There are two cases.
1586  *
1587  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1588  *	   failed), we will not deliver it to the ULP, even though they
1589  *	   are *willing* to accept in *clear*. This is fine as our global
1590  *	   disposition to icmp messages asks us reject the datagram.
1591  *
1592  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1593  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1594  *	   to deliver it to ULP (policy failed), it can lead to
1595  *	   consistency problems. The cases known at this time are
1596  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1597  *	   values :
1598  *
1599  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1600  *	     and Upper layer rejects. Then the communication will
1601  *	     come to a stop. This is solved by making similar decisions
1602  *	     at both levels. Currently, when we are unable to deliver
1603  *	     to the Upper Layer (due to policy failures) while IP has
1604  *	     adjusted ire_max_frag, the next outbound datagram would
1605  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1606  *	     will be with the right level of protection. Thus the right
1607  *	     value will be communicated even if we are not able to
1608  *	     communicate when we get from the wire initially. But this
1609  *	     assumes there would be at least one outbound datagram after
1610  *	     IP has adjusted its ire_max_frag value. To make things
1611  *	     simpler, we accept in clear after the validation of
1612  *	     AH/ESP headers.
1613  *
1614  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1615  *	     upper layer depending on the level of protection the upper
1616  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1617  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1618  *	     should be accepted in clear when the Upper layer expects secure.
1619  *	     Thus the communication may get aborted by some bad ICMP
1620  *	     packets.
1621  *
1622  * IPQoS Notes:
1623  * The only instance when a packet is sent for processing is when there
1624  * isn't an ICMP client and if we are interested in it.
1625  * If there is a client, IPPF processing will take place in the
1626  * ip_fanout_proto routine.
1627  *
1628  * Zones notes:
1629  * The packet is only processed in the context of the specified zone: typically
1630  * only this zone will reply to an echo request, and only interested clients in
1631  * this zone will receive a copy of the packet. This means that the caller must
1632  * call icmp_inbound() for each relevant zone.
1633  */
1634 static void
1635 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1636     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1637     ill_t *recv_ill, zoneid_t zoneid)
1638 {
1639 	icmph_t	*icmph;
1640 	ipha_t	*ipha;
1641 	int	iph_hdr_length;
1642 	int	hdr_length;
1643 	boolean_t	interested;
1644 	uint32_t	ts;
1645 	uchar_t	*wptr;
1646 	ipif_t	*ipif;
1647 	mblk_t *first_mp;
1648 	ipsec_in_t *ii;
1649 	ire_t *src_ire;
1650 	boolean_t onlink;
1651 	timestruc_t now;
1652 	uint32_t ill_index;
1653 
1654 	ASSERT(ill != NULL);
1655 
1656 	first_mp = mp;
1657 	if (mctl_present) {
1658 		mp = first_mp->b_cont;
1659 		ASSERT(mp != NULL);
1660 	}
1661 
1662 	ipha = (ipha_t *)mp->b_rptr;
1663 	if (icmp_accept_clear_messages == 0) {
1664 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1665 		    ipha, NULL, mctl_present);
1666 		if (first_mp == NULL)
1667 			return;
1668 	}
1669 	/*
1670 	 * We have accepted the ICMP message. It means that we will
1671 	 * respond to the packet if needed. It may not be delivered
1672 	 * to the upper client depending on the policy constraints
1673 	 * and the disposition in ipsec_inbound_accept_clear.
1674 	 */
1675 
1676 	ASSERT(ill != NULL);
1677 
1678 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1679 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1680 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1681 		/* Last chance to get real. */
1682 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1683 			BUMP_MIB(&icmp_mib, icmpInErrors);
1684 			freemsg(first_mp);
1685 			return;
1686 		}
1687 		/* Refresh iph following the pullup. */
1688 		ipha = (ipha_t *)mp->b_rptr;
1689 	}
1690 	/* ICMP header checksum, including checksum field, should be zero. */
1691 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1692 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1693 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1694 		freemsg(first_mp);
1695 		return;
1696 	}
1697 	/* The IP header will always be a multiple of four bytes */
1698 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1699 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1700 	    icmph->icmph_code));
1701 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1702 	/* We will set "interested" to "true" if we want a copy */
1703 	interested = B_FALSE;
1704 	switch (icmph->icmph_type) {
1705 	case ICMP_ECHO_REPLY:
1706 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1707 		break;
1708 	case ICMP_DEST_UNREACHABLE:
1709 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1710 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1711 		interested = B_TRUE;	/* Pass up to transport */
1712 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1713 		break;
1714 	case ICMP_SOURCE_QUENCH:
1715 		interested = B_TRUE;	/* Pass up to transport */
1716 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1717 		break;
1718 	case ICMP_REDIRECT:
1719 		if (!ip_ignore_redirect)
1720 			interested = B_TRUE;
1721 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1722 		break;
1723 	case ICMP_ECHO_REQUEST:
1724 		/*
1725 		 * Whether to respond to echo requests that come in as IP
1726 		 * broadcasts or as IP multicast is subject to debate
1727 		 * (what isn't?).  We aim to please, you pick it.
1728 		 * Default is do it.
1729 		 */
1730 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1731 			/* unicast: always respond */
1732 			interested = B_TRUE;
1733 		} else if (CLASSD(ipha->ipha_dst)) {
1734 			/* multicast: respond based on tunable */
1735 			interested = ip_g_resp_to_echo_mcast;
1736 		} else if (broadcast) {
1737 			/* broadcast: respond based on tunable */
1738 			interested = ip_g_resp_to_echo_bcast;
1739 		}
1740 		BUMP_MIB(&icmp_mib, icmpInEchos);
1741 		break;
1742 	case ICMP_ROUTER_ADVERTISEMENT:
1743 	case ICMP_ROUTER_SOLICITATION:
1744 		break;
1745 	case ICMP_TIME_EXCEEDED:
1746 		interested = B_TRUE;	/* Pass up to transport */
1747 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1748 		break;
1749 	case ICMP_PARAM_PROBLEM:
1750 		interested = B_TRUE;	/* Pass up to transport */
1751 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1752 		break;
1753 	case ICMP_TIME_STAMP_REQUEST:
1754 		/* Response to Time Stamp Requests is local policy. */
1755 		if (ip_g_resp_to_timestamp &&
1756 		    /* So is whether to respond if it was an IP broadcast. */
1757 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1758 			int tstamp_len = 3 * sizeof (uint32_t);
1759 
1760 			if (wptr +  tstamp_len > mp->b_wptr) {
1761 				if (!pullupmsg(mp, wptr + tstamp_len -
1762 				    mp->b_rptr)) {
1763 					BUMP_MIB(&ip_mib, ipInDiscards);
1764 					freemsg(first_mp);
1765 					return;
1766 				}
1767 				/* Refresh ipha following the pullup. */
1768 				ipha = (ipha_t *)mp->b_rptr;
1769 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1770 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1771 			}
1772 			interested = B_TRUE;
1773 		}
1774 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1775 		break;
1776 	case ICMP_TIME_STAMP_REPLY:
1777 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1778 		break;
1779 	case ICMP_INFO_REQUEST:
1780 		/* Per RFC 1122 3.2.2.7, ignore this. */
1781 	case ICMP_INFO_REPLY:
1782 		break;
1783 	case ICMP_ADDRESS_MASK_REQUEST:
1784 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1785 		    /* TODO m_pullup of complete header? */
1786 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1787 			interested = B_TRUE;
1788 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1789 		break;
1790 	case ICMP_ADDRESS_MASK_REPLY:
1791 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1792 		break;
1793 	default:
1794 		interested = B_TRUE;	/* Pass up to transport */
1795 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1796 		break;
1797 	}
1798 	/* See if there is an ICMP client. */
1799 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1800 		/* If there is an ICMP client and we want one too, copy it. */
1801 		mblk_t *first_mp1;
1802 
1803 		if (!interested) {
1804 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1805 			    ip_policy, recv_ill, zoneid);
1806 			return;
1807 		}
1808 		first_mp1 = ip_copymsg(first_mp);
1809 		if (first_mp1 != NULL) {
1810 			ip_fanout_proto(q, first_mp1, ill, ipha,
1811 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1812 		}
1813 	} else if (!interested) {
1814 		freemsg(first_mp);
1815 		return;
1816 	} else {
1817 		/*
1818 		 * Initiate policy processing for this packet if ip_policy
1819 		 * is true.
1820 		 */
1821 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1822 			ill_index = ill->ill_phyint->phyint_ifindex;
1823 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1824 			if (mp == NULL) {
1825 				if (mctl_present) {
1826 					freeb(first_mp);
1827 				}
1828 				BUMP_MIB(&icmp_mib, icmpInErrors);
1829 				return;
1830 			}
1831 		}
1832 	}
1833 	/* We want to do something with it. */
1834 	/* Check db_ref to make sure we can modify the packet. */
1835 	if (mp->b_datap->db_ref > 1) {
1836 		mblk_t	*first_mp1;
1837 
1838 		first_mp1 = ip_copymsg(first_mp);
1839 		freemsg(first_mp);
1840 		if (!first_mp1) {
1841 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1842 			return;
1843 		}
1844 		first_mp = first_mp1;
1845 		if (mctl_present) {
1846 			mp = first_mp->b_cont;
1847 			ASSERT(mp != NULL);
1848 		} else {
1849 			mp = first_mp;
1850 		}
1851 		ipha = (ipha_t *)mp->b_rptr;
1852 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1853 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1854 	}
1855 	switch (icmph->icmph_type) {
1856 	case ICMP_ADDRESS_MASK_REQUEST:
1857 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1858 		if (ipif == NULL) {
1859 			freemsg(first_mp);
1860 			return;
1861 		}
1862 		/*
1863 		 * outging interface must be IPv4
1864 		 */
1865 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1866 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1867 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1868 		ipif_refrele(ipif);
1869 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1870 		break;
1871 	case ICMP_ECHO_REQUEST:
1872 		icmph->icmph_type = ICMP_ECHO_REPLY;
1873 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1874 		break;
1875 	case ICMP_TIME_STAMP_REQUEST: {
1876 		uint32_t *tsp;
1877 
1878 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1879 		tsp = (uint32_t *)wptr;
1880 		tsp++;		/* Skip past 'originate time' */
1881 		/* Compute # of milliseconds since midnight */
1882 		gethrestime(&now);
1883 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1884 		    now.tv_nsec / (NANOSEC / MILLISEC);
1885 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1886 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1887 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1888 		break;
1889 	}
1890 	default:
1891 		ipha = (ipha_t *)&icmph[1];
1892 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1893 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1894 				BUMP_MIB(&ip_mib, ipInDiscards);
1895 				freemsg(first_mp);
1896 				return;
1897 			}
1898 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1899 			ipha = (ipha_t *)&icmph[1];
1900 		}
1901 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1902 			BUMP_MIB(&ip_mib, ipInDiscards);
1903 			freemsg(first_mp);
1904 			return;
1905 		}
1906 		hdr_length = IPH_HDR_LENGTH(ipha);
1907 		if (hdr_length < sizeof (ipha_t)) {
1908 			BUMP_MIB(&ip_mib, ipInDiscards);
1909 			freemsg(first_mp);
1910 			return;
1911 		}
1912 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1913 			if (!pullupmsg(mp,
1914 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1915 				BUMP_MIB(&ip_mib, ipInDiscards);
1916 				freemsg(first_mp);
1917 				return;
1918 			}
1919 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1920 			ipha = (ipha_t *)&icmph[1];
1921 		}
1922 		switch (icmph->icmph_type) {
1923 		case ICMP_REDIRECT:
1924 			/*
1925 			 * As there is no upper client to deliver, we don't
1926 			 * need the first_mp any more.
1927 			 */
1928 			if (mctl_present) {
1929 				freeb(first_mp);
1930 			}
1931 			icmp_redirect(mp);
1932 			return;
1933 		case ICMP_DEST_UNREACHABLE:
1934 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1935 				if (!icmp_inbound_too_big(icmph, ipha)) {
1936 					freemsg(first_mp);
1937 					return;
1938 				}
1939 			}
1940 			/* FALLTHRU */
1941 		default :
1942 			/*
1943 			 * IPQoS notes: Since we have already done IPQoS
1944 			 * processing we don't want to do it again in
1945 			 * the fanout routines called by
1946 			 * icmp_inbound_error_fanout, hence the last
1947 			 * argument, ip_policy, is B_FALSE.
1948 			 */
1949 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1950 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1951 			    B_FALSE, recv_ill, zoneid);
1952 		}
1953 		return;
1954 	}
1955 	/* Send out an ICMP packet */
1956 	icmph->icmph_checksum = 0;
1957 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1958 	if (icmph->icmph_checksum == 0)
1959 		icmph->icmph_checksum = 0xFFFF;
1960 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1961 		ipif_t	*ipif_chosen;
1962 		/*
1963 		 * Make it look like it was directed to us, so we don't look
1964 		 * like a fool with a broadcast or multicast source address.
1965 		 */
1966 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1967 		/*
1968 		 * Make sure that we haven't grabbed an interface that's DOWN.
1969 		 */
1970 		if (ipif != NULL) {
1971 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1972 			    ipha->ipha_src, zoneid);
1973 			if (ipif_chosen != NULL) {
1974 				ipif_refrele(ipif);
1975 				ipif = ipif_chosen;
1976 			}
1977 		}
1978 		if (ipif == NULL) {
1979 			ip0dbg(("icmp_inbound: "
1980 			    "No source for broadcast/multicast:\n"
1981 			    "\tsrc 0x%x dst 0x%x ill %p "
1982 			    "ipif_lcl_addr 0x%x\n",
1983 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1984 			    (void *)ill,
1985 			    ill->ill_ipif->ipif_lcl_addr));
1986 			freemsg(first_mp);
1987 			return;
1988 		}
1989 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1990 		ipha->ipha_dst = ipif->ipif_src_addr;
1991 		ipif_refrele(ipif);
1992 	}
1993 	/* Reset time to live. */
1994 	ipha->ipha_ttl = ip_def_ttl;
1995 	{
1996 		/* Swap source and destination addresses */
1997 		ipaddr_t tmp;
1998 
1999 		tmp = ipha->ipha_src;
2000 		ipha->ipha_src = ipha->ipha_dst;
2001 		ipha->ipha_dst = tmp;
2002 	}
2003 	ipha->ipha_ident = 0;
2004 	if (!IS_SIMPLE_IPH(ipha))
2005 		icmp_options_update(ipha);
2006 
2007 	/*
2008 	 * ICMP echo replies should go out on the same interface
2009 	 * the request came on as probes used by in.mpathd for detecting
2010 	 * NIC failures are ECHO packets. We turn-off load spreading
2011 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2012 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2013 	 * function. This is in turn handled by ip_wput and ip_newroute
2014 	 * to make sure that the packet goes out on the interface it came
2015 	 * in on. If we don't turnoff load spreading, the packets might get
2016 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2017 	 * to go out and in.mpathd would wrongly detect a failure or
2018 	 * mis-detect a NIC failure for link failure. As load spreading
2019 	 * can happen only if ill_group is not NULL, we do only for
2020 	 * that case and this does not affect the normal case.
2021 	 *
2022 	 * We turn off load spreading only on echo packets that came from
2023 	 * on-link hosts. If the interface route has been deleted, this will
2024 	 * not be enforced as we can't do much. For off-link hosts, as the
2025 	 * default routes in IPv4 does not typically have an ire_ipif
2026 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2027 	 * Moreover, expecting a default route through this interface may
2028 	 * not be correct. We use ipha_dst because of the swap above.
2029 	 */
2030 	onlink = B_FALSE;
2031 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2032 		/*
2033 		 * First, we need to make sure that it is not one of our
2034 		 * local addresses. If we set onlink when it is one of
2035 		 * our local addresses, we will end up creating IRE_CACHES
2036 		 * for one of our local addresses. Then, we will never
2037 		 * accept packets for them afterwards.
2038 		 */
2039 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2040 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2041 		if (src_ire == NULL) {
2042 			ipif = ipif_get_next_ipif(NULL, ill);
2043 			if (ipif == NULL) {
2044 				BUMP_MIB(&ip_mib, ipInDiscards);
2045 				freemsg(mp);
2046 				return;
2047 			}
2048 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2049 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2050 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2051 			ipif_refrele(ipif);
2052 			if (src_ire != NULL) {
2053 				onlink = B_TRUE;
2054 				ire_refrele(src_ire);
2055 			}
2056 		} else {
2057 			ire_refrele(src_ire);
2058 		}
2059 	}
2060 	if (!mctl_present) {
2061 		/*
2062 		 * This packet should go out the same way as it
2063 		 * came in i.e in clear. To make sure that global
2064 		 * policy will not be applied to this in ip_wput_ire,
2065 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2066 		 */
2067 		ASSERT(first_mp == mp);
2068 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2069 			BUMP_MIB(&ip_mib, ipInDiscards);
2070 			freemsg(mp);
2071 			return;
2072 		}
2073 		ii = (ipsec_in_t *)first_mp->b_rptr;
2074 
2075 		/* This is not a secure packet */
2076 		ii->ipsec_in_secure = B_FALSE;
2077 		if (onlink) {
2078 			ii->ipsec_in_attach_if = B_TRUE;
2079 			ii->ipsec_in_ill_index =
2080 			    ill->ill_phyint->phyint_ifindex;
2081 			ii->ipsec_in_rill_index =
2082 			    recv_ill->ill_phyint->phyint_ifindex;
2083 		}
2084 		first_mp->b_cont = mp;
2085 	} else if (onlink) {
2086 		ii = (ipsec_in_t *)first_mp->b_rptr;
2087 		ii->ipsec_in_attach_if = B_TRUE;
2088 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2089 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2090 	} else {
2091 		ii = (ipsec_in_t *)first_mp->b_rptr;
2092 	}
2093 	ii->ipsec_in_zoneid = zoneid;
2094 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2095 		BUMP_MIB(&ip_mib, ipInDiscards);
2096 		return;
2097 	}
2098 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2099 	put(WR(q), first_mp);
2100 }
2101 
2102 /* Table from RFC 1191 */
2103 static int icmp_frag_size_table[] =
2104 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2105 
2106 /*
2107  * Process received ICMP Packet too big.
2108  * After updating any IRE it does the fanout to any matching transport streams.
2109  * Assumes the message has been pulled up till the IP header that caused
2110  * the error.
2111  *
2112  * Returns B_FALSE on failure and B_TRUE on success.
2113  */
2114 static boolean_t
2115 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2116 {
2117 	ire_t	*ire, *first_ire;
2118 	int	mtu;
2119 	int	hdr_length;
2120 
2121 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2122 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2123 
2124 	hdr_length = IPH_HDR_LENGTH(ipha);
2125 
2126 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2127 	    ALL_ZONES, MATCH_IRE_TYPE);
2128 
2129 	if (!first_ire) {
2130 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2131 		    ntohl(ipha->ipha_dst)));
2132 		return (B_FALSE);
2133 	}
2134 	/* Drop if the original packet contained a source route */
2135 	if (ip_source_route_included(ipha)) {
2136 		ire_refrele(first_ire);
2137 		return (B_FALSE);
2138 	}
2139 	/* Check for MTU discovery advice as described in RFC 1191 */
2140 	mtu = ntohs(icmph->icmph_du_mtu);
2141 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2142 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2143 	    ire = ire->ire_next) {
2144 		mutex_enter(&ire->ire_lock);
2145 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2146 			/* Reduce the IRE max frag value as advised. */
2147 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2148 			ip1dbg(("Received mtu from router: %d\n", mtu));
2149 		} else {
2150 			uint32_t length;
2151 			int	i;
2152 
2153 			/*
2154 			 * Use the table from RFC 1191 to figure out
2155 			 * the next "plateau" based on the length in
2156 			 * the original IP packet.
2157 			 */
2158 			length = ntohs(ipha->ipha_length);
2159 			if (ire->ire_max_frag <= length &&
2160 			    ire->ire_max_frag >= length - hdr_length) {
2161 				/*
2162 				 * Handle broken BSD 4.2 systems that
2163 				 * return the wrong iph_length in ICMP
2164 				 * errors.
2165 				 */
2166 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2167 				    length, ire->ire_max_frag));
2168 				length -= hdr_length;
2169 			}
2170 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2171 				if (length > icmp_frag_size_table[i])
2172 					break;
2173 			}
2174 			if (i == A_CNT(icmp_frag_size_table)) {
2175 				/* Smaller than 68! */
2176 				ip1dbg(("Too big for packet size %d\n",
2177 				    length));
2178 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2179 				ire->ire_frag_flag = 0;
2180 			} else {
2181 				mtu = icmp_frag_size_table[i];
2182 				ip1dbg(("Calculated mtu %d, packet size %d, "
2183 				    "before %d", mtu, length,
2184 				    ire->ire_max_frag));
2185 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2186 				ip1dbg((", after %d\n", ire->ire_max_frag));
2187 			}
2188 			/* Record the new max frag size for the ULP. */
2189 			icmph->icmph_du_zero = 0;
2190 			icmph->icmph_du_mtu =
2191 			    htons((uint16_t)ire->ire_max_frag);
2192 		}
2193 		mutex_exit(&ire->ire_lock);
2194 	}
2195 	rw_exit(&first_ire->ire_bucket->irb_lock);
2196 	ire_refrele(first_ire);
2197 	return (B_TRUE);
2198 }
2199 
2200 /*
2201  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2202  * calls this function.
2203  */
2204 static mblk_t *
2205 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2206 {
2207 	ipha_t *ipha;
2208 	icmph_t *icmph;
2209 	ipha_t *in_ipha;
2210 	int length;
2211 
2212 	ASSERT(mp->b_datap->db_type == M_DATA);
2213 
2214 	/*
2215 	 * For Self-encapsulated packets, we added an extra IP header
2216 	 * without the options. Inner IP header is the one from which
2217 	 * the outer IP header was formed. Thus, we need to remove the
2218 	 * outer IP header. To do this, we pullup the whole message
2219 	 * and overlay whatever follows the outer IP header over the
2220 	 * outer IP header.
2221 	 */
2222 
2223 	if (!pullupmsg(mp, -1)) {
2224 		BUMP_MIB(&ip_mib, ipInDiscards);
2225 		return (NULL);
2226 	}
2227 
2228 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2229 	ipha = (ipha_t *)&icmph[1];
2230 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2231 
2232 	/*
2233 	 * The length that we want to overlay is following the inner
2234 	 * IP header. Subtracting the IP header + icmp header + outer
2235 	 * IP header's length should give us the length that we want to
2236 	 * overlay.
2237 	 */
2238 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2239 	    hdr_length;
2240 	/*
2241 	 * Overlay whatever follows the inner header over the
2242 	 * outer header.
2243 	 */
2244 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2245 
2246 	/* Set the wptr to account for the outer header */
2247 	mp->b_wptr -= hdr_length;
2248 	return (mp);
2249 }
2250 
2251 /*
2252  * Try to pass the ICMP message upstream in case the ULP cares.
2253  *
2254  * If the packet that caused the ICMP error is secure, we send
2255  * it to AH/ESP to make sure that the attached packet has a
2256  * valid association. ipha in the code below points to the
2257  * IP header of the packet that caused the error.
2258  *
2259  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2260  * in the context of IPSEC. Normally we tell the upper layer
2261  * whenever we send the ire (including ip_bind), the IPSEC header
2262  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2263  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2264  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2265  * same thing. As TCP has the IPSEC options size that needs to be
2266  * adjusted, we just pass the MTU unchanged.
2267  *
2268  * IFN could have been generated locally or by some router.
2269  *
2270  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2271  *	    This happens because IP adjusted its value of MTU on an
2272  *	    earlier IFN message and could not tell the upper layer,
2273  *	    the new adjusted value of MTU e.g. Packet was encrypted
2274  *	    or there was not enough information to fanout to upper
2275  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2276  *	    generates the IFN, where IPSEC processing has *not* been
2277  *	    done.
2278  *
2279  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2280  *	    could have generated this. This happens because ire_max_frag
2281  *	    value in IP was set to a new value, while the IPSEC processing
2282  *	    was being done and after we made the fragmentation check in
2283  *	    ip_wput_ire. Thus on return from IPSEC processing,
2284  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2285  *	    and generates the IFN. As IPSEC processing is over, we fanout
2286  *	    to AH/ESP to remove the header.
2287  *
2288  *	    In both these cases, ipsec_in_loopback will be set indicating
2289  *	    that IFN was generated locally.
2290  *
2291  * ROUTER : IFN could be secure or non-secure.
2292  *
2293  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2294  *	      packet in error has AH/ESP headers to validate the AH/ESP
2295  *	      headers. AH/ESP will verify whether there is a valid SA or
2296  *	      not and send it back. We will fanout again if we have more
2297  *	      data in the packet.
2298  *
2299  *	      If the packet in error does not have AH/ESP, we handle it
2300  *	      like any other case.
2301  *
2302  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2303  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2304  *	      for validation. AH/ESP will verify whether there is a
2305  *	      valid SA or not and send it back. We will fanout again if
2306  *	      we have more data in the packet.
2307  *
2308  *	      If the packet in error does not have AH/ESP, we handle it
2309  *	      like any other case.
2310  */
2311 static void
2312 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2313     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2314     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2315     zoneid_t zoneid)
2316 {
2317 	uint16_t *up;	/* Pointer to ports in ULP header */
2318 	uint32_t ports;	/* reversed ports for fanout */
2319 	ipha_t ripha;	/* With reversed addresses */
2320 	mblk_t *first_mp;
2321 	ipsec_in_t *ii;
2322 	tcph_t	*tcph;
2323 	conn_t	*connp;
2324 
2325 	first_mp = mp;
2326 	if (mctl_present) {
2327 		mp = first_mp->b_cont;
2328 		ASSERT(mp != NULL);
2329 
2330 		ii = (ipsec_in_t *)first_mp->b_rptr;
2331 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2332 	} else {
2333 		ii = NULL;
2334 	}
2335 
2336 	switch (ipha->ipha_protocol) {
2337 	case IPPROTO_UDP:
2338 		/*
2339 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2340 		 * transport header.
2341 		 */
2342 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2343 		    mp->b_wptr) {
2344 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2345 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2346 				BUMP_MIB(&ip_mib, ipInDiscards);
2347 				goto drop_pkt;
2348 			}
2349 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2350 			ipha = (ipha_t *)&icmph[1];
2351 		}
2352 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2353 
2354 		/*
2355 		 * Attempt to find a client stream based on port.
2356 		 * Note that we do a reverse lookup since the header is
2357 		 * in the form we sent it out.
2358 		 * The ripha header is only used for the IP_UDP_MATCH and we
2359 		 * only set the src and dst addresses and protocol.
2360 		 */
2361 		ripha.ipha_src = ipha->ipha_dst;
2362 		ripha.ipha_dst = ipha->ipha_src;
2363 		ripha.ipha_protocol = ipha->ipha_protocol;
2364 		((uint16_t *)&ports)[0] = up[1];
2365 		((uint16_t *)&ports)[1] = up[0];
2366 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2367 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2368 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2369 		    icmph->icmph_type, icmph->icmph_code));
2370 
2371 		/* Have to change db_type after any pullupmsg */
2372 		DB_TYPE(mp) = M_CTL;
2373 
2374 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2375 		    mctl_present, ip_policy, recv_ill, zoneid);
2376 		return;
2377 
2378 	case IPPROTO_TCP:
2379 		/*
2380 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2381 		 * transport header.
2382 		 */
2383 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2384 		    mp->b_wptr) {
2385 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2386 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2387 				BUMP_MIB(&ip_mib, ipInDiscards);
2388 				goto drop_pkt;
2389 			}
2390 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2391 			ipha = (ipha_t *)&icmph[1];
2392 		}
2393 		/*
2394 		 * Find a TCP client stream for this packet.
2395 		 * Note that we do a reverse lookup since the header is
2396 		 * in the form we sent it out.
2397 		 */
2398 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2399 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2400 		if (connp == NULL) {
2401 			BUMP_MIB(&ip_mib, ipInDiscards);
2402 			goto drop_pkt;
2403 		}
2404 
2405 		/* Have to change db_type after any pullupmsg */
2406 		DB_TYPE(mp) = M_CTL;
2407 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2408 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2409 		return;
2410 
2411 	case IPPROTO_SCTP:
2412 		/*
2413 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2414 		 * transport header.
2415 		 */
2416 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2417 		    mp->b_wptr) {
2418 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2419 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2420 				BUMP_MIB(&ip_mib, ipInDiscards);
2421 				goto drop_pkt;
2422 			}
2423 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2424 			ipha = (ipha_t *)&icmph[1];
2425 		}
2426 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2427 		/*
2428 		 * Find a SCTP client stream for this packet.
2429 		 * Note that we do a reverse lookup since the header is
2430 		 * in the form we sent it out.
2431 		 * The ripha header is only used for the matching and we
2432 		 * only set the src and dst addresses, protocol, and version.
2433 		 */
2434 		ripha.ipha_src = ipha->ipha_dst;
2435 		ripha.ipha_dst = ipha->ipha_src;
2436 		ripha.ipha_protocol = ipha->ipha_protocol;
2437 		ripha.ipha_version_and_hdr_length =
2438 		    ipha->ipha_version_and_hdr_length;
2439 		((uint16_t *)&ports)[0] = up[1];
2440 		((uint16_t *)&ports)[1] = up[0];
2441 
2442 		/* Have to change db_type after any pullupmsg */
2443 		DB_TYPE(mp) = M_CTL;
2444 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2445 		    mctl_present, ip_policy, 0, zoneid);
2446 		return;
2447 
2448 	case IPPROTO_ESP:
2449 	case IPPROTO_AH: {
2450 		int ipsec_rc;
2451 
2452 		/*
2453 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2454 		 * We will re-use the IPSEC_IN if it is already present as
2455 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2456 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2457 		 * one and attach it in the front.
2458 		 */
2459 		if (ii != NULL) {
2460 			/*
2461 			 * ip_fanout_proto_again converts the ICMP errors
2462 			 * that come back from AH/ESP to M_DATA so that
2463 			 * if it is non-AH/ESP and we do a pullupmsg in
2464 			 * this function, it would work. Convert it back
2465 			 * to M_CTL before we send up as this is a ICMP
2466 			 * error. This could have been generated locally or
2467 			 * by some router. Validate the inner IPSEC
2468 			 * headers.
2469 			 *
2470 			 * NOTE : ill_index is used by ip_fanout_proto_again
2471 			 * to locate the ill.
2472 			 */
2473 			ASSERT(ill != NULL);
2474 			ii->ipsec_in_ill_index =
2475 			    ill->ill_phyint->phyint_ifindex;
2476 			ii->ipsec_in_rill_index =
2477 			    recv_ill->ill_phyint->phyint_ifindex;
2478 			DB_TYPE(first_mp->b_cont) = M_CTL;
2479 		} else {
2480 			/*
2481 			 * IPSEC_IN is not present. We attach a ipsec_in
2482 			 * message and send up to IPSEC for validating
2483 			 * and removing the IPSEC headers. Clear
2484 			 * ipsec_in_secure so that when we return
2485 			 * from IPSEC, we don't mistakenly think that this
2486 			 * is a secure packet came from the network.
2487 			 *
2488 			 * NOTE : ill_index is used by ip_fanout_proto_again
2489 			 * to locate the ill.
2490 			 */
2491 			ASSERT(first_mp == mp);
2492 			first_mp = ipsec_in_alloc(B_TRUE);
2493 			if (first_mp == NULL) {
2494 				freemsg(mp);
2495 				BUMP_MIB(&ip_mib, ipInDiscards);
2496 				return;
2497 			}
2498 			ii = (ipsec_in_t *)first_mp->b_rptr;
2499 
2500 			/* This is not a secure packet */
2501 			ii->ipsec_in_secure = B_FALSE;
2502 			first_mp->b_cont = mp;
2503 			DB_TYPE(mp) = M_CTL;
2504 			ASSERT(ill != NULL);
2505 			ii->ipsec_in_ill_index =
2506 			    ill->ill_phyint->phyint_ifindex;
2507 			ii->ipsec_in_rill_index =
2508 			    recv_ill->ill_phyint->phyint_ifindex;
2509 		}
2510 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2511 
2512 		if (!ipsec_loaded()) {
2513 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2514 			return;
2515 		}
2516 
2517 		if (ipha->ipha_protocol == IPPROTO_ESP)
2518 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2519 		else
2520 			ipsec_rc = ipsecah_icmp_error(first_mp);
2521 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2522 			return;
2523 
2524 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2525 		return;
2526 	}
2527 	default:
2528 		/*
2529 		 * The ripha header is only used for the lookup and we
2530 		 * only set the src and dst addresses and protocol.
2531 		 */
2532 		ripha.ipha_src = ipha->ipha_dst;
2533 		ripha.ipha_dst = ipha->ipha_src;
2534 		ripha.ipha_protocol = ipha->ipha_protocol;
2535 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2536 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2537 		    ntohl(ipha->ipha_dst),
2538 		    icmph->icmph_type, icmph->icmph_code));
2539 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2540 			ipha_t *in_ipha;
2541 
2542 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2543 			    mp->b_wptr) {
2544 				if (!pullupmsg(mp, (uchar_t *)ipha +
2545 				    hdr_length + sizeof (ipha_t) -
2546 				    mp->b_rptr)) {
2547 
2548 					BUMP_MIB(&ip_mib, ipInDiscards);
2549 					goto drop_pkt;
2550 				}
2551 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2552 				ipha = (ipha_t *)&icmph[1];
2553 			}
2554 			/*
2555 			 * Caller has verified that length has to be
2556 			 * at least the size of IP header.
2557 			 */
2558 			ASSERT(hdr_length >= sizeof (ipha_t));
2559 			/*
2560 			 * Check the sanity of the inner IP header like
2561 			 * we did for the outer header.
2562 			 */
2563 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2564 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2565 				BUMP_MIB(&ip_mib, ipInDiscards);
2566 				goto drop_pkt;
2567 			}
2568 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2569 				BUMP_MIB(&ip_mib, ipInDiscards);
2570 				goto drop_pkt;
2571 			}
2572 			/* Check for Self-encapsulated tunnels */
2573 			if (in_ipha->ipha_src == ipha->ipha_src &&
2574 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2575 
2576 				mp = icmp_inbound_self_encap_error(mp,
2577 				    iph_hdr_length, hdr_length);
2578 				if (mp == NULL)
2579 					goto drop_pkt;
2580 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2581 				ipha = (ipha_t *)&icmph[1];
2582 				hdr_length = IPH_HDR_LENGTH(ipha);
2583 				/*
2584 				 * The packet in error is self-encapsualted.
2585 				 * And we are finding it further encapsulated
2586 				 * which we could not have possibly generated.
2587 				 */
2588 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2589 					BUMP_MIB(&ip_mib, ipInDiscards);
2590 					goto drop_pkt;
2591 				}
2592 				icmp_inbound_error_fanout(q, ill, first_mp,
2593 				    icmph, ipha, iph_hdr_length, hdr_length,
2594 				    mctl_present, ip_policy, recv_ill, zoneid);
2595 				return;
2596 			}
2597 		}
2598 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2599 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2600 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2601 		    ii != NULL &&
2602 		    ii->ipsec_in_loopback &&
2603 		    ii->ipsec_in_secure) {
2604 			/*
2605 			 * For IP tunnels that get a looped-back
2606 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2607 			 * reported new MTU to take into account the IPsec
2608 			 * headers protecting this configured tunnel.
2609 			 *
2610 			 * This allows the tunnel module (tun.c) to blindly
2611 			 * accept the MTU reported in an ICMP "too big"
2612 			 * message.
2613 			 *
2614 			 * Non-looped back ICMP messages will just be
2615 			 * handled by the security protocols (if needed),
2616 			 * and the first subsequent packet will hit this
2617 			 * path.
2618 			 */
2619 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2620 			    ipsec_in_extra_length(first_mp));
2621 		}
2622 		/* Have to change db_type after any pullupmsg */
2623 		DB_TYPE(mp) = M_CTL;
2624 
2625 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2626 		    ip_policy, recv_ill, zoneid);
2627 		return;
2628 	}
2629 	/* NOTREACHED */
2630 drop_pkt:;
2631 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2632 	freemsg(first_mp);
2633 }
2634 
2635 /*
2636  * Common IP options parser.
2637  *
2638  * Setup routine: fill in *optp with options-parsing state, then
2639  * tail-call ipoptp_next to return the first option.
2640  */
2641 uint8_t
2642 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2643 {
2644 	uint32_t totallen; /* total length of all options */
2645 
2646 	totallen = ipha->ipha_version_and_hdr_length -
2647 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2648 	totallen <<= 2;
2649 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2650 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2651 	optp->ipoptp_flags = 0;
2652 	return (ipoptp_next(optp));
2653 }
2654 
2655 /*
2656  * Common IP options parser: extract next option.
2657  */
2658 uint8_t
2659 ipoptp_next(ipoptp_t *optp)
2660 {
2661 	uint8_t *end = optp->ipoptp_end;
2662 	uint8_t *cur = optp->ipoptp_next;
2663 	uint8_t opt, len, pointer;
2664 
2665 	/*
2666 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2667 	 * has been corrupted.
2668 	 */
2669 	ASSERT(cur <= end);
2670 
2671 	if (cur == end)
2672 		return (IPOPT_EOL);
2673 
2674 	opt = cur[IPOPT_OPTVAL];
2675 
2676 	/*
2677 	 * Skip any NOP options.
2678 	 */
2679 	while (opt == IPOPT_NOP) {
2680 		cur++;
2681 		if (cur == end)
2682 			return (IPOPT_EOL);
2683 		opt = cur[IPOPT_OPTVAL];
2684 	}
2685 
2686 	if (opt == IPOPT_EOL)
2687 		return (IPOPT_EOL);
2688 
2689 	/*
2690 	 * Option requiring a length.
2691 	 */
2692 	if ((cur + 1) >= end) {
2693 		optp->ipoptp_flags |= IPOPTP_ERROR;
2694 		return (IPOPT_EOL);
2695 	}
2696 	len = cur[IPOPT_OLEN];
2697 	if (len < 2) {
2698 		optp->ipoptp_flags |= IPOPTP_ERROR;
2699 		return (IPOPT_EOL);
2700 	}
2701 	optp->ipoptp_cur = cur;
2702 	optp->ipoptp_len = len;
2703 	optp->ipoptp_next = cur + len;
2704 	if (cur + len > end) {
2705 		optp->ipoptp_flags |= IPOPTP_ERROR;
2706 		return (IPOPT_EOL);
2707 	}
2708 
2709 	/*
2710 	 * For the options which require a pointer field, make sure
2711 	 * its there, and make sure it points to either something
2712 	 * inside this option, or the end of the option.
2713 	 */
2714 	switch (opt) {
2715 	case IPOPT_RR:
2716 	case IPOPT_TS:
2717 	case IPOPT_LSRR:
2718 	case IPOPT_SSRR:
2719 		if (len <= IPOPT_OFFSET) {
2720 			optp->ipoptp_flags |= IPOPTP_ERROR;
2721 			return (opt);
2722 		}
2723 		pointer = cur[IPOPT_OFFSET];
2724 		if (pointer - 1 > len) {
2725 			optp->ipoptp_flags |= IPOPTP_ERROR;
2726 			return (opt);
2727 		}
2728 		break;
2729 	}
2730 
2731 	/*
2732 	 * Sanity check the pointer field based on the type of the
2733 	 * option.
2734 	 */
2735 	switch (opt) {
2736 	case IPOPT_RR:
2737 	case IPOPT_SSRR:
2738 	case IPOPT_LSRR:
2739 		if (pointer < IPOPT_MINOFF_SR)
2740 			optp->ipoptp_flags |= IPOPTP_ERROR;
2741 		break;
2742 	case IPOPT_TS:
2743 		if (pointer < IPOPT_MINOFF_IT)
2744 			optp->ipoptp_flags |= IPOPTP_ERROR;
2745 		/*
2746 		 * Note that the Internet Timestamp option also
2747 		 * contains two four bit fields (the Overflow field,
2748 		 * and the Flag field), which follow the pointer
2749 		 * field.  We don't need to check that these fields
2750 		 * fall within the length of the option because this
2751 		 * was implicitely done above.  We've checked that the
2752 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2753 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2754 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2755 		 */
2756 		ASSERT(len > IPOPT_POS_OV_FLG);
2757 		break;
2758 	}
2759 
2760 	return (opt);
2761 }
2762 
2763 /*
2764  * Update any record route or timestamp options to include this host.
2765  * Reverse any source route option.
2766  * This routine assumes that the options are well formed i.e. that they
2767  * have already been checked.
2768  */
2769 static void
2770 icmp_options_update(ipha_t *ipha)
2771 {
2772 	ipoptp_t	opts;
2773 	uchar_t		*opt;
2774 	uint8_t		optval;
2775 	ipaddr_t	src;		/* Our local address */
2776 	ipaddr_t	dst;
2777 
2778 	ip2dbg(("icmp_options_update\n"));
2779 	src = ipha->ipha_src;
2780 	dst = ipha->ipha_dst;
2781 
2782 	for (optval = ipoptp_first(&opts, ipha);
2783 	    optval != IPOPT_EOL;
2784 	    optval = ipoptp_next(&opts)) {
2785 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2786 		opt = opts.ipoptp_cur;
2787 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2788 		    optval, opts.ipoptp_len));
2789 		switch (optval) {
2790 			int off1, off2;
2791 		case IPOPT_SSRR:
2792 		case IPOPT_LSRR:
2793 			/*
2794 			 * Reverse the source route.  The first entry
2795 			 * should be the next to last one in the current
2796 			 * source route (the last entry is our address).
2797 			 * The last entry should be the final destination.
2798 			 */
2799 			off1 = IPOPT_MINOFF_SR - 1;
2800 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2801 			if (off2 < 0) {
2802 				/* No entries in source route */
2803 				ip1dbg((
2804 				    "icmp_options_update: bad src route\n"));
2805 				break;
2806 			}
2807 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2808 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2809 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2810 			off2 -= IP_ADDR_LEN;
2811 
2812 			while (off1 < off2) {
2813 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2814 				bcopy((char *)opt + off2, (char *)opt + off1,
2815 				    IP_ADDR_LEN);
2816 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2817 				off1 += IP_ADDR_LEN;
2818 				off2 -= IP_ADDR_LEN;
2819 			}
2820 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2821 			break;
2822 		}
2823 	}
2824 }
2825 
2826 /*
2827  * Process received ICMP Redirect messages.
2828  */
2829 /* ARGSUSED */
2830 static void
2831 icmp_redirect(mblk_t *mp)
2832 {
2833 	ipha_t	*ipha;
2834 	int	iph_hdr_length;
2835 	icmph_t	*icmph;
2836 	ipha_t	*ipha_err;
2837 	ire_t	*ire;
2838 	ire_t	*prev_ire;
2839 	ire_t	*save_ire;
2840 	ipaddr_t  src, dst, gateway;
2841 	iulp_t	ulp_info = { 0 };
2842 	int	error;
2843 
2844 	ipha = (ipha_t *)mp->b_rptr;
2845 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2846 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2847 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2848 		BUMP_MIB(&icmp_mib, icmpInErrors);
2849 		freemsg(mp);
2850 		return;
2851 	}
2852 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2853 	ipha_err = (ipha_t *)&icmph[1];
2854 	src = ipha->ipha_src;
2855 	dst = ipha_err->ipha_dst;
2856 	gateway = icmph->icmph_rd_gateway;
2857 	/* Make sure the new gateway is reachable somehow. */
2858 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2859 	    ALL_ZONES, MATCH_IRE_TYPE);
2860 	/*
2861 	 * Make sure we had a route for the dest in question and that
2862 	 * that route was pointing to the old gateway (the source of the
2863 	 * redirect packet.)
2864 	 */
2865 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2866 	    MATCH_IRE_GW);
2867 	/*
2868 	 * Check that
2869 	 *	the redirect was not from ourselves
2870 	 *	the new gateway and the old gateway are directly reachable
2871 	 */
2872 	if (!prev_ire ||
2873 	    !ire ||
2874 	    ire->ire_type == IRE_LOCAL) {
2875 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2876 		freemsg(mp);
2877 		if (ire != NULL)
2878 			ire_refrele(ire);
2879 		if (prev_ire != NULL)
2880 			ire_refrele(prev_ire);
2881 		return;
2882 	}
2883 
2884 	/*
2885 	 * Should we use the old ULP info to create the new gateway?  From
2886 	 * a user's perspective, we should inherit the info so that it
2887 	 * is a "smooth" transition.  If we do not do that, then new
2888 	 * connections going thru the new gateway will have no route metrics,
2889 	 * which is counter-intuitive to user.  From a network point of
2890 	 * view, this may or may not make sense even though the new gateway
2891 	 * is still directly connected to us so the route metrics should not
2892 	 * change much.
2893 	 *
2894 	 * But if the old ire_uinfo is not initialized, we do another
2895 	 * recursive lookup on the dest using the new gateway.  There may
2896 	 * be a route to that.  If so, use it to initialize the redirect
2897 	 * route.
2898 	 */
2899 	if (prev_ire->ire_uinfo.iulp_set) {
2900 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2901 	} else {
2902 		ire_t *tmp_ire;
2903 		ire_t *sire;
2904 
2905 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2906 		    ALL_ZONES, 0,
2907 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2908 		if (sire != NULL) {
2909 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2910 			/*
2911 			 * If sire != NULL, ire_ftable_lookup() should not
2912 			 * return a NULL value.
2913 			 */
2914 			ASSERT(tmp_ire != NULL);
2915 			ire_refrele(tmp_ire);
2916 			ire_refrele(sire);
2917 		} else if (tmp_ire != NULL) {
2918 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2919 			    sizeof (iulp_t));
2920 			ire_refrele(tmp_ire);
2921 		}
2922 	}
2923 	if (prev_ire->ire_type == IRE_CACHE)
2924 		ire_delete(prev_ire);
2925 	ire_refrele(prev_ire);
2926 	/*
2927 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2928 	 * require TOS routing
2929 	 */
2930 	switch (icmph->icmph_code) {
2931 	case 0:
2932 	case 1:
2933 		/* TODO: TOS specificity for cases 2 and 3 */
2934 	case 2:
2935 	case 3:
2936 		break;
2937 	default:
2938 		freemsg(mp);
2939 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2940 		ire_refrele(ire);
2941 		return;
2942 	}
2943 	/*
2944 	 * Create a Route Association.  This will allow us to remember that
2945 	 * someone we believe told us to use the particular gateway.
2946 	 */
2947 	save_ire = ire;
2948 	ire = ire_create(
2949 		(uchar_t *)&dst,			/* dest addr */
2950 		(uchar_t *)&ip_g_all_ones,		/* mask */
2951 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2952 		(uchar_t *)&gateway,			/* gateway addr */
2953 		NULL,					/* no in_srcaddr */
2954 		&save_ire->ire_max_frag,		/* max frag */
2955 		NULL,					/* Fast Path header */
2956 		NULL,					/* no rfq */
2957 		NULL,					/* no stq */
2958 		IRE_HOST_REDIRECT,
2959 		NULL,
2960 		NULL,
2961 		NULL,
2962 		0,
2963 		0,
2964 		0,
2965 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2966 		&ulp_info);
2967 
2968 	if (ire == NULL) {
2969 		freemsg(mp);
2970 		ire_refrele(save_ire);
2971 		return;
2972 	}
2973 	error = ire_add(&ire, NULL, NULL, NULL);
2974 	ire_refrele(save_ire);
2975 	if (error == 0) {
2976 		ire_refrele(ire);		/* Held in ire_add_v4 */
2977 		/* tell routing sockets that we received a redirect */
2978 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2979 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2980 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2981 	}
2982 
2983 	/*
2984 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2985 	 * This together with the added IRE has the effect of
2986 	 * modifying an existing redirect.
2987 	 */
2988 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2989 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2990 	if (prev_ire) {
2991 		ire_delete(prev_ire);
2992 		ire_refrele(prev_ire);
2993 	}
2994 
2995 	freemsg(mp);
2996 }
2997 
2998 /*
2999  * Generate an ICMP parameter problem message.
3000  */
3001 static void
3002 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3003 {
3004 	icmph_t	icmph;
3005 	boolean_t mctl_present;
3006 	mblk_t *first_mp;
3007 
3008 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3009 
3010 	if (!(mp = icmp_pkt_err_ok(mp))) {
3011 		if (mctl_present)
3012 			freeb(first_mp);
3013 		return;
3014 	}
3015 
3016 	bzero(&icmph, sizeof (icmph_t));
3017 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3018 	icmph.icmph_pp_ptr = ptr;
3019 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3020 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3021 }
3022 
3023 /*
3024  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3025  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3026  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3027  * an icmp error packet can be sent.
3028  * Assigns an appropriate source address to the packet. If ipha_dst is
3029  * one of our addresses use it for source. Otherwise pick a source based
3030  * on a route lookup back to ipha_src.
3031  * Note that ipha_src must be set here since the
3032  * packet is likely to arrive on an ill queue in ip_wput() which will
3033  * not set a source address.
3034  */
3035 static void
3036 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3037     boolean_t mctl_present)
3038 {
3039 	ipaddr_t dst;
3040 	icmph_t	*icmph;
3041 	ipha_t	*ipha;
3042 	uint_t	len_needed;
3043 	size_t	msg_len;
3044 	mblk_t	*mp1;
3045 	ipaddr_t src;
3046 	ire_t	*ire;
3047 	mblk_t *ipsec_mp;
3048 	ipsec_out_t	*io = NULL;
3049 	boolean_t xmit_if_on = B_FALSE;
3050 	zoneid_t	zoneid;
3051 
3052 	if (mctl_present) {
3053 		/*
3054 		 * If it is :
3055 		 *
3056 		 * 1) a IPSEC_OUT, then this is caused by outbound
3057 		 *    datagram originating on this host. IPSEC processing
3058 		 *    may or may not have been done. Refer to comments above
3059 		 *    icmp_inbound_error_fanout for details.
3060 		 *
3061 		 * 2) a IPSEC_IN if we are generating a icmp_message
3062 		 *    for an incoming datagram destined for us i.e called
3063 		 *    from ip_fanout_send_icmp.
3064 		 */
3065 		ipsec_info_t *in;
3066 		ipsec_mp = mp;
3067 		mp = ipsec_mp->b_cont;
3068 
3069 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3070 		ipha = (ipha_t *)mp->b_rptr;
3071 
3072 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3073 		    in->ipsec_info_type == IPSEC_IN);
3074 
3075 		if (in->ipsec_info_type == IPSEC_IN) {
3076 			/*
3077 			 * Convert the IPSEC_IN to IPSEC_OUT.
3078 			 */
3079 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3080 				BUMP_MIB(&ip_mib, ipOutDiscards);
3081 				return;
3082 			}
3083 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3084 		} else {
3085 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3086 			io = (ipsec_out_t *)in;
3087 			if (io->ipsec_out_xmit_if)
3088 				xmit_if_on = B_TRUE;
3089 			/*
3090 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3091 			 * ire lookup.
3092 			 */
3093 			io->ipsec_out_proc_begin = B_FALSE;
3094 		}
3095 		zoneid = io->ipsec_out_zoneid;
3096 		ASSERT(zoneid != ALL_ZONES);
3097 	} else {
3098 		/*
3099 		 * This is in clear. The icmp message we are building
3100 		 * here should go out in clear.
3101 		 *
3102 		 * Pardon the convolution of it all, but it's easier to
3103 		 * allocate a "use cleartext" IPSEC_IN message and convert
3104 		 * it than it is to allocate a new one.
3105 		 */
3106 		ipsec_in_t *ii;
3107 		ASSERT(DB_TYPE(mp) == M_DATA);
3108 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3109 			freemsg(mp);
3110 			BUMP_MIB(&ip_mib, ipOutDiscards);
3111 			return;
3112 		}
3113 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3114 
3115 		/* This is not a secure packet */
3116 		ii->ipsec_in_secure = B_FALSE;
3117 		if (CONN_Q(q)) {
3118 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3119 		} else {
3120 			zoneid = GLOBAL_ZONEID;
3121 		}
3122 		ii->ipsec_in_zoneid = zoneid;
3123 		ipsec_mp->b_cont = mp;
3124 		ipha = (ipha_t *)mp->b_rptr;
3125 		/*
3126 		 * Convert the IPSEC_IN to IPSEC_OUT.
3127 		 */
3128 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3129 			BUMP_MIB(&ip_mib, ipOutDiscards);
3130 			return;
3131 		}
3132 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3133 	}
3134 
3135 	/* Remember our eventual destination */
3136 	dst = ipha->ipha_src;
3137 
3138 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3139 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3140 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3141 		src = ipha->ipha_dst;
3142 	} else if (!xmit_if_on) {
3143 		if (ire != NULL)
3144 			ire_refrele(ire);
3145 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3146 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3147 		if (ire == NULL) {
3148 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3149 			freemsg(ipsec_mp);
3150 			return;
3151 		}
3152 		src = ire->ire_src_addr;
3153 	} else {
3154 		ipif_t	*ipif = NULL;
3155 		ill_t	*ill;
3156 		/*
3157 		 * This must be an ICMP error coming from
3158 		 * ip_mrtun_forward(). The src addr should
3159 		 * be equal to the IP-addr of the outgoing
3160 		 * interface.
3161 		 */
3162 		if (io == NULL) {
3163 			/* This is not a IPSEC_OUT type control msg */
3164 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3165 			freemsg(ipsec_mp);
3166 			return;
3167 		}
3168 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3169 		    NULL, NULL, NULL, NULL);
3170 		if (ill != NULL) {
3171 			ipif = ipif_get_next_ipif(NULL, ill);
3172 			ill_refrele(ill);
3173 		}
3174 		if (ipif == NULL) {
3175 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3176 			freemsg(ipsec_mp);
3177 			return;
3178 		}
3179 		src = ipif->ipif_src_addr;
3180 		ipif_refrele(ipif);
3181 	}
3182 
3183 	if (ire != NULL)
3184 		ire_refrele(ire);
3185 
3186 	/*
3187 	 * Check if we can send back more then 8 bytes in addition
3188 	 * to the IP header. We will include as much as 64 bytes.
3189 	 */
3190 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3191 	msg_len = msgdsize(mp);
3192 	if (msg_len > len_needed) {
3193 		(void) adjmsg(mp, len_needed - msg_len);
3194 		msg_len = len_needed;
3195 	}
3196 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3197 	if (!mp1) {
3198 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3199 		freemsg(ipsec_mp);
3200 		return;
3201 	}
3202 	mp1->b_cont = mp;
3203 	mp = mp1;
3204 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3205 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3206 	    io->ipsec_out_type == IPSEC_OUT);
3207 	ipsec_mp->b_cont = mp;
3208 
3209 	/*
3210 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3211 	 * node generates be accepted in peace by all on-host destinations.
3212 	 * If we do NOT assume that all on-host destinations trust
3213 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3214 	 * (Look for ipsec_out_icmp_loopback).
3215 	 */
3216 	io->ipsec_out_icmp_loopback = B_TRUE;
3217 
3218 	ipha = (ipha_t *)mp->b_rptr;
3219 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3220 	*ipha = icmp_ipha;
3221 	ipha->ipha_src = src;
3222 	ipha->ipha_dst = dst;
3223 	ipha->ipha_ttl = ip_def_ttl;
3224 	msg_len += sizeof (icmp_ipha) + len;
3225 	if (msg_len > IP_MAXPACKET) {
3226 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3227 		msg_len = IP_MAXPACKET;
3228 	}
3229 	ipha->ipha_length = htons((uint16_t)msg_len);
3230 	icmph = (icmph_t *)&ipha[1];
3231 	bcopy(stuff, icmph, len);
3232 	icmph->icmph_checksum = 0;
3233 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3234 	if (icmph->icmph_checksum == 0)
3235 		icmph->icmph_checksum = 0xFFFF;
3236 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3237 	put(q, ipsec_mp);
3238 }
3239 
3240 /*
3241  * Determine if an ICMP error packet can be sent given the rate limit.
3242  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3243  * in milliseconds) and a burst size. Burst size number of packets can
3244  * be sent arbitrarely closely spaced.
3245  * The state is tracked using two variables to implement an approximate
3246  * token bucket filter:
3247  *	icmp_pkt_err_last - lbolt value when the last burst started
3248  *	icmp_pkt_err_sent - number of packets sent in current burst
3249  */
3250 boolean_t
3251 icmp_err_rate_limit(void)
3252 {
3253 	clock_t now = TICK_TO_MSEC(lbolt);
3254 	uint_t refilled; /* Number of packets refilled in tbf since last */
3255 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3256 
3257 	if (err_interval == 0)
3258 		return (B_FALSE);
3259 
3260 	if (icmp_pkt_err_last > now) {
3261 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3262 		icmp_pkt_err_last = 0;
3263 		icmp_pkt_err_sent = 0;
3264 	}
3265 	/*
3266 	 * If we are in a burst update the token bucket filter.
3267 	 * Update the "last" time to be close to "now" but make sure
3268 	 * we don't loose precision.
3269 	 */
3270 	if (icmp_pkt_err_sent != 0) {
3271 		refilled = (now - icmp_pkt_err_last)/err_interval;
3272 		if (refilled > icmp_pkt_err_sent) {
3273 			icmp_pkt_err_sent = 0;
3274 		} else {
3275 			icmp_pkt_err_sent -= refilled;
3276 			icmp_pkt_err_last += refilled * err_interval;
3277 		}
3278 	}
3279 	if (icmp_pkt_err_sent == 0) {
3280 		/* Start of new burst */
3281 		icmp_pkt_err_last = now;
3282 	}
3283 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3284 		icmp_pkt_err_sent++;
3285 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3286 		    icmp_pkt_err_sent));
3287 		return (B_FALSE);
3288 	}
3289 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3290 	return (B_TRUE);
3291 }
3292 
3293 /*
3294  * Check if it is ok to send an IPv4 ICMP error packet in
3295  * response to the IPv4 packet in mp.
3296  * Free the message and return null if no
3297  * ICMP error packet should be sent.
3298  */
3299 static mblk_t *
3300 icmp_pkt_err_ok(mblk_t *mp)
3301 {
3302 	icmph_t	*icmph;
3303 	ipha_t	*ipha;
3304 	uint_t	len_needed;
3305 	ire_t	*src_ire;
3306 	ire_t	*dst_ire;
3307 
3308 	if (!mp)
3309 		return (NULL);
3310 	ipha = (ipha_t *)mp->b_rptr;
3311 	if (ip_csum_hdr(ipha)) {
3312 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3313 		freemsg(mp);
3314 		return (NULL);
3315 	}
3316 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3317 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3318 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3319 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3320 	if (src_ire != NULL || dst_ire != NULL ||
3321 	    CLASSD(ipha->ipha_dst) ||
3322 	    CLASSD(ipha->ipha_src) ||
3323 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3324 		/* Note: only errors to the fragment with offset 0 */
3325 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3326 		freemsg(mp);
3327 		if (src_ire != NULL)
3328 			ire_refrele(src_ire);
3329 		if (dst_ire != NULL)
3330 			ire_refrele(dst_ire);
3331 		return (NULL);
3332 	}
3333 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3334 		/*
3335 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3336 		 * errors in response to any ICMP errors.
3337 		 */
3338 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3339 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3340 			if (!pullupmsg(mp, len_needed)) {
3341 				BUMP_MIB(&icmp_mib, icmpInErrors);
3342 				freemsg(mp);
3343 				return (NULL);
3344 			}
3345 			ipha = (ipha_t *)mp->b_rptr;
3346 		}
3347 		icmph = (icmph_t *)
3348 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3349 		switch (icmph->icmph_type) {
3350 		case ICMP_DEST_UNREACHABLE:
3351 		case ICMP_SOURCE_QUENCH:
3352 		case ICMP_TIME_EXCEEDED:
3353 		case ICMP_PARAM_PROBLEM:
3354 		case ICMP_REDIRECT:
3355 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3356 			freemsg(mp);
3357 			return (NULL);
3358 		default:
3359 			break;
3360 		}
3361 	}
3362 	if (icmp_err_rate_limit()) {
3363 		/*
3364 		 * Only send ICMP error packets every so often.
3365 		 * This should be done on a per port/source basis,
3366 		 * but for now this will suffice.
3367 		 */
3368 		freemsg(mp);
3369 		return (NULL);
3370 	}
3371 	return (mp);
3372 }
3373 
3374 /*
3375  * Generate an ICMP redirect message.
3376  */
3377 static void
3378 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3379 {
3380 	icmph_t	icmph;
3381 
3382 	/*
3383 	 * We are called from ip_rput where we could
3384 	 * not have attached an IPSEC_IN.
3385 	 */
3386 	ASSERT(mp->b_datap->db_type == M_DATA);
3387 
3388 	if (!(mp = icmp_pkt_err_ok(mp))) {
3389 		return;
3390 	}
3391 
3392 	bzero(&icmph, sizeof (icmph_t));
3393 	icmph.icmph_type = ICMP_REDIRECT;
3394 	icmph.icmph_code = 1;
3395 	icmph.icmph_rd_gateway = gateway;
3396 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3397 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3398 }
3399 
3400 /*
3401  * Generate an ICMP time exceeded message.
3402  */
3403 void
3404 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3405 {
3406 	icmph_t	icmph;
3407 	boolean_t mctl_present;
3408 	mblk_t *first_mp;
3409 
3410 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3411 
3412 	if (!(mp = icmp_pkt_err_ok(mp))) {
3413 		if (mctl_present)
3414 			freeb(first_mp);
3415 		return;
3416 	}
3417 
3418 	bzero(&icmph, sizeof (icmph_t));
3419 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3420 	icmph.icmph_code = code;
3421 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3422 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3423 }
3424 
3425 /*
3426  * Generate an ICMP unreachable message.
3427  */
3428 void
3429 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3430 {
3431 	icmph_t	icmph;
3432 	mblk_t *first_mp;
3433 	boolean_t mctl_present;
3434 
3435 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3436 
3437 	if (!(mp = icmp_pkt_err_ok(mp))) {
3438 		if (mctl_present)
3439 			freeb(first_mp);
3440 		return;
3441 	}
3442 
3443 	bzero(&icmph, sizeof (icmph_t));
3444 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3445 	icmph.icmph_code = code;
3446 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3447 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3448 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3449 }
3450 
3451 /*
3452  * News from ARP.  ARP sends notification of interesting events down
3453  * to its clients using M_CTL messages with the interesting ARP packet
3454  * attached via b_cont.
3455  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3456  * queue as opposed to ARP sending the message to all the clients, i.e. all
3457  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3458  * table if a cache IRE is found to delete all the entries for the address in
3459  * the packet.
3460  */
3461 static void
3462 ip_arp_news(queue_t *q, mblk_t *mp)
3463 {
3464 	arcn_t		*arcn;
3465 	arh_t		*arh;
3466 	char		*cp1;
3467 	uchar_t		*cp2;
3468 	ire_t		*ire = NULL;
3469 	int		i1;
3470 	char		hbuf[128];
3471 	char		sbuf[16];
3472 	ipaddr_t	src;
3473 	in6_addr_t	v6src;
3474 	boolean_t	isv6 = B_FALSE;
3475 
3476 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3477 		if (q->q_next) {
3478 			putnext(q, mp);
3479 		} else
3480 			freemsg(mp);
3481 		return;
3482 	}
3483 	arh = (arh_t *)mp->b_cont->b_rptr;
3484 	/* Is it one we are interested in? */
3485 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3486 		isv6 = B_TRUE;
3487 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3488 		    IPV6_ADDR_LEN);
3489 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3490 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3491 		    IP_ADDR_LEN);
3492 	} else {
3493 		freemsg(mp);
3494 		return;
3495 	}
3496 
3497 	arcn = (arcn_t *)mp->b_rptr;
3498 	switch (arcn->arcn_code) {
3499 	case AR_CN_BOGON:
3500 		/*
3501 		 * Someone is sending ARP packets with a source protocol
3502 		 * address which we have published.  Either they are
3503 		 * pretending to be us, or we have been asked to proxy
3504 		 * for a machine that can do fine for itself, or two
3505 		 * different machines are providing proxy service for the
3506 		 * same protocol address, or something.  We try and do
3507 		 * something appropriate here.
3508 		 */
3509 		cp2 = (uchar_t *)&arh[1];
3510 		cp1 = hbuf;
3511 		*cp1 = '\0';
3512 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3513 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3514 		if (cp1 != hbuf)
3515 			cp1[-1] = '\0';
3516 		(void) ip_dot_addr(src, sbuf);
3517 		if (isv6)
3518 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3519 		else
3520 			ire = ire_cache_lookup(src, ALL_ZONES);
3521 
3522 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3523 			cmn_err(CE_WARN,
3524 			    "IP: Hardware address '%s' trying"
3525 			    " to be our address %s!",
3526 			    hbuf, sbuf);
3527 		} else {
3528 			cmn_err(CE_WARN,
3529 			    "IP: Proxy ARP problem?  "
3530 			    "Hardware address '%s' thinks it is %s",
3531 			    hbuf, sbuf);
3532 		}
3533 		if (ire != NULL)
3534 			ire_refrele(ire);
3535 		break;
3536 	case AR_CN_ANNOUNCE:
3537 		if (isv6) {
3538 			/*
3539 			 * For XRESOLV interfaces.
3540 			 * Delete the IRE cache entry and NCE for this
3541 			 * v6 address
3542 			 */
3543 			ip_ire_clookup_and_delete_v6(&v6src);
3544 			/*
3545 			 * If v6src is a non-zero, it's a router address
3546 			 * as below. Do the same sort of thing to clean
3547 			 * out off-net IRE_CACHE entries that go through
3548 			 * the router.
3549 			 */
3550 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3551 				ire_walk_v6(ire_delete_cache_gw_v6,
3552 				    (char *)&v6src, ALL_ZONES);
3553 			}
3554 			break;
3555 		}
3556 		/*
3557 		 * ARP gives us a copy of any broadcast packet with identical
3558 		 * sender and receiver protocol address, in
3559 		 * case we want to intuit something from it.  Such a packet
3560 		 * usually means that a machine has just come up on the net.
3561 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3562 		 * immediately pick up the rare case of a host changing
3563 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3564 		 *
3565 		 * The address in "src" may be an entry for a router.
3566 		 * (Default router, or non-default router.)  If
3567 		 * that's true, then any off-net IRE_CACHE entries
3568 		 * that go through the router with address "src"
3569 		 * must be clobbered.  Use ire_walk to achieve this
3570 		 * goal.
3571 		 *
3572 		 * It should be possible to determine if the address
3573 		 * in src is or is not for a router.  This way,
3574 		 * the ire_walk() isn't called all of the time here.
3575 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3576 		 * as it would remove all IRE_CACHE entries for onlink
3577 		 * destinations. All onlink destinations have
3578 		 * ire_gateway_addr == 0.
3579 		 */
3580 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3581 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3582 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3583 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3584 			    ALL_ZONES);
3585 		}
3586 		/* From ire_ftable_lookup */
3587 		if (ire != NULL)
3588 			ire_refrele(ire);
3589 		break;
3590 	default:
3591 		if (ire != NULL)
3592 			ire_refrele(ire);
3593 		break;
3594 	}
3595 	freemsg(mp);
3596 }
3597 
3598 /*
3599  * Create a mblk suitable for carrying the interface index and/or source link
3600  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3601  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3602  * application.
3603  */
3604 mblk_t *
3605 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3606 {
3607 	mblk_t		*mp;
3608 	in_pktinfo_t	*pinfo;
3609 	ipha_t *ipha;
3610 	struct ether_header *pether;
3611 
3612 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3613 	if (mp == NULL) {
3614 		ip1dbg(("ip_add_info: allocation failure.\n"));
3615 		return (data_mp);
3616 	}
3617 
3618 	ipha	= (ipha_t *)data_mp->b_rptr;
3619 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3620 	bzero(pinfo, sizeof (in_pktinfo_t));
3621 	pinfo->in_pkt_flags = (uchar_t)flags;
3622 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3623 
3624 	if (flags & IPF_RECVIF)
3625 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3626 
3627 	pether = (struct ether_header *)((char *)ipha
3628 	    - sizeof (struct ether_header));
3629 	/*
3630 	 * Make sure the interface is an ethernet type, since this option
3631 	 * is currently supported only on this type of interface. Also make
3632 	 * sure we are pointing correctly above db_base.
3633 	 */
3634 
3635 	if ((flags & IPF_RECVSLLA) &&
3636 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3637 	    (ill->ill_type == IFT_ETHER) &&
3638 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3639 
3640 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3641 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3642 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3643 	} else {
3644 		/*
3645 		 * Clear the bit. Indicate to upper layer that IP is not
3646 		 * sending this ancillary info.
3647 		 */
3648 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3649 	}
3650 
3651 	mp->b_datap->db_type = M_CTL;
3652 	mp->b_wptr += sizeof (in_pktinfo_t);
3653 	mp->b_cont = data_mp;
3654 
3655 	return (mp);
3656 }
3657 
3658 /*
3659  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3660  * part of the bind request.
3661  */
3662 
3663 boolean_t
3664 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3665 {
3666 	ipsec_in_t *ii;
3667 
3668 	ASSERT(policy_mp != NULL);
3669 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3670 
3671 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3672 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3673 
3674 	connp->conn_policy = ii->ipsec_in_policy;
3675 	ii->ipsec_in_policy = NULL;
3676 
3677 	if (ii->ipsec_in_action != NULL) {
3678 		if (connp->conn_latch == NULL) {
3679 			connp->conn_latch = iplatch_create();
3680 			if (connp->conn_latch == NULL)
3681 				return (B_FALSE);
3682 		}
3683 		ipsec_latch_inbound(connp->conn_latch, ii);
3684 	}
3685 	return (B_TRUE);
3686 }
3687 
3688 /*
3689  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3690  * and to arrange for power-fanout assist.  The ULP is identified by
3691  * adding a single byte at the end of the original bind message.
3692  * A ULP other than UDP or TCP that wishes to be recognized passes
3693  * down a bind with a zero length address.
3694  *
3695  * The binding works as follows:
3696  * - A zero byte address means just bind to the protocol.
3697  * - A four byte address is treated as a request to validate
3698  *   that the address is a valid local address, appropriate for
3699  *   an application to bind to. This does not affect any fanout
3700  *   information in IP.
3701  * - A sizeof sin_t byte address is used to bind to only the local address
3702  *   and port.
3703  * - A sizeof ipa_conn_t byte address contains complete fanout information
3704  *   consisting of local and remote addresses and ports.  In
3705  *   this case, the addresses are both validated as appropriate
3706  *   for this operation, and, if so, the information is retained
3707  *   for use in the inbound fanout.
3708  *
3709  * The ULP (except in the zero-length bind) can append an
3710  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3711  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3712  * a copy of the source or destination IRE (source for local bind;
3713  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3714  * policy information contained should be copied on to the conn.
3715  *
3716  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3717  */
3718 mblk_t *
3719 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3720 {
3721 	ssize_t		len;
3722 	struct T_bind_req	*tbr;
3723 	sin_t		*sin;
3724 	ipa_conn_t	*ac;
3725 	uchar_t		*ucp;
3726 	mblk_t		*mp1;
3727 	boolean_t	ire_requested;
3728 	boolean_t	ipsec_policy_set = B_FALSE;
3729 	int		error = 0;
3730 	int		protocol;
3731 	ipa_conn_x_t	*acx;
3732 
3733 	ASSERT(!connp->conn_af_isv6);
3734 	connp->conn_pkt_isv6 = B_FALSE;
3735 
3736 	len = MBLKL(mp);
3737 	if (len < (sizeof (*tbr) + 1)) {
3738 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3739 		    "ip_bind: bogus msg, len %ld", len);
3740 		/* XXX: Need to return something better */
3741 		goto bad_addr;
3742 	}
3743 	/* Back up and extract the protocol identifier. */
3744 	mp->b_wptr--;
3745 	protocol = *mp->b_wptr & 0xFF;
3746 	tbr = (struct T_bind_req *)mp->b_rptr;
3747 	/* Reset the message type in preparation for shipping it back. */
3748 	DB_TYPE(mp) = M_PCPROTO;
3749 
3750 	connp->conn_ulp = (uint8_t)protocol;
3751 
3752 	/*
3753 	 * Check for a zero length address.  This is from a protocol that
3754 	 * wants to register to receive all packets of its type.
3755 	 */
3756 	if (tbr->ADDR_length == 0) {
3757 		/*
3758 		 * These protocols are now intercepted in ip_bind_v6().
3759 		 * Reject protocol-level binds here for now.
3760 		 *
3761 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3762 		 * so that the protocol type cannot be SCTP.
3763 		 */
3764 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3765 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3766 			goto bad_addr;
3767 		}
3768 
3769 		/* No hash here really.  The table is big enough. */
3770 		connp->conn_srcv6 = ipv6_all_zeros;
3771 
3772 		ipcl_proto_insert(connp, protocol);
3773 
3774 		tbr->PRIM_type = T_BIND_ACK;
3775 		return (mp);
3776 	}
3777 
3778 	/* Extract the address pointer from the message. */
3779 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3780 	    tbr->ADDR_length);
3781 	if (ucp == NULL) {
3782 		ip1dbg(("ip_bind: no address\n"));
3783 		goto bad_addr;
3784 	}
3785 	if (!OK_32PTR(ucp)) {
3786 		ip1dbg(("ip_bind: unaligned address\n"));
3787 		goto bad_addr;
3788 	}
3789 	/*
3790 	 * Check for trailing mps.
3791 	 */
3792 
3793 	mp1 = mp->b_cont;
3794 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
3795 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
3796 
3797 	switch (tbr->ADDR_length) {
3798 	default:
3799 		ip1dbg(("ip_bind: bad address length %d\n",
3800 		    (int)tbr->ADDR_length));
3801 		goto bad_addr;
3802 
3803 	case IP_ADDR_LEN:
3804 		/* Verification of local address only */
3805 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3806 		    ire_requested, ipsec_policy_set, B_FALSE);
3807 		break;
3808 
3809 	case sizeof (sin_t):
3810 		sin = (sin_t *)ucp;
3811 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3812 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3813 		if (protocol == IPPROTO_TCP)
3814 			connp->conn_recv = tcp_conn_request;
3815 		break;
3816 
3817 	case sizeof (ipa_conn_t):
3818 		ac = (ipa_conn_t *)ucp;
3819 		/* For raw socket, the local port is not set. */
3820 		if (ac->ac_lport == 0)
3821 			ac->ac_lport = connp->conn_lport;
3822 		/* Always verify destination reachability. */
3823 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3824 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3825 		    ipsec_policy_set, B_TRUE, B_TRUE);
3826 		if (protocol == IPPROTO_TCP)
3827 			connp->conn_recv = tcp_input;
3828 		break;
3829 
3830 	case sizeof (ipa_conn_x_t):
3831 		acx = (ipa_conn_x_t *)ucp;
3832 		/*
3833 		 * Whether or not to verify destination reachability depends
3834 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3835 		 */
3836 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3837 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3838 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3839 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3840 		if (protocol == IPPROTO_TCP)
3841 			connp->conn_recv = tcp_input;
3842 		break;
3843 	}
3844 	if (error == EINPROGRESS)
3845 		return (NULL);
3846 	else if (error != 0)
3847 		goto bad_addr;
3848 	/*
3849 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3850 	 * We can't do this in ip_bind_insert_ire because the policy
3851 	 * may not have been inherited at that point in time and hence
3852 	 * conn_out_enforce_policy may not be set.
3853 	 */
3854 	mp1 = mp->b_cont;
3855 	if (ire_requested && connp->conn_out_enforce_policy &&
3856 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3857 		ire_t *ire = (ire_t *)mp1->b_rptr;
3858 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3859 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3860 	}
3861 
3862 	/* Send it home. */
3863 	mp->b_datap->db_type = M_PCPROTO;
3864 	tbr->PRIM_type = T_BIND_ACK;
3865 	return (mp);
3866 
3867 bad_addr:
3868 	/*
3869 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3870 	 * a unix errno.
3871 	 */
3872 	if (error > 0)
3873 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3874 	else
3875 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3876 	return (mp);
3877 }
3878 
3879 /*
3880  * Here address is verified to be a valid local address.
3881  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3882  * address is also considered a valid local address.
3883  * In the case of a broadcast/multicast address, however, the
3884  * upper protocol is expected to reset the src address
3885  * to 0 if it sees a IRE_BROADCAST type returned so that
3886  * no packets are emitted with broadcast/multicast address as
3887  * source address (that violates hosts requirements RFC1122)
3888  * The addresses valid for bind are:
3889  *	(1) - INADDR_ANY (0)
3890  *	(2) - IP address of an UP interface
3891  *	(3) - IP address of a DOWN interface
3892  *	(4) - valid local IP broadcast addresses. In this case
3893  *	the conn will only receive packets destined to
3894  *	the specified broadcast address.
3895  *	(5) - a multicast address. In this case
3896  *	the conn will only receive packets destined to
3897  *	the specified multicast address. Note: the
3898  *	application still has to issue an
3899  *	IP_ADD_MEMBERSHIP socket option.
3900  *
3901  * On error, return -1 for TBADADDR otherwise pass the
3902  * errno with TSYSERR reply.
3903  *
3904  * In all the above cases, the bound address must be valid in the current zone.
3905  * When the address is loopback, multicast or broadcast, there might be many
3906  * matching IREs so bind has to look up based on the zone.
3907  */
3908 int
3909 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3910     boolean_t ire_requested, boolean_t ipsec_policy_set,
3911     boolean_t fanout_insert)
3912 {
3913 	int		error = 0;
3914 	ire_t		*src_ire;
3915 	mblk_t		*policy_mp;
3916 	ipif_t		*ipif;
3917 	zoneid_t	zoneid;
3918 
3919 	if (ipsec_policy_set) {
3920 		policy_mp = mp->b_cont;
3921 	}
3922 
3923 	/*
3924 	 * If it was previously connected, conn_fully_bound would have
3925 	 * been set.
3926 	 */
3927 	connp->conn_fully_bound = B_FALSE;
3928 
3929 	src_ire = NULL;
3930 	ipif = NULL;
3931 
3932 	zoneid = connp->conn_zoneid;
3933 
3934 	if (src_addr) {
3935 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3936 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3937 		/*
3938 		 * If an address other than 0.0.0.0 is requested,
3939 		 * we verify that it is a valid address for bind
3940 		 * Note: Following code is in if-else-if form for
3941 		 * readability compared to a condition check.
3942 		 */
3943 		/* LINTED - statement has no consequent */
3944 		if (IRE_IS_LOCAL(src_ire)) {
3945 			/*
3946 			 * (2) Bind to address of local UP interface
3947 			 */
3948 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3949 			/*
3950 			 * (4) Bind to broadcast address
3951 			 * Note: permitted only from transports that
3952 			 * request IRE
3953 			 */
3954 			if (!ire_requested)
3955 				error = EADDRNOTAVAIL;
3956 		} else {
3957 			/*
3958 			 * (3) Bind to address of local DOWN interface
3959 			 * (ipif_lookup_addr() looks up all interfaces
3960 			 * but we do not get here for UP interfaces
3961 			 * - case (2) above)
3962 			 * We put the protocol byte back into the mblk
3963 			 * since we may come back via ip_wput_nondata()
3964 			 * later with this mblk if ipif_lookup_addr chooses
3965 			 * to defer processing.
3966 			 */
3967 			*mp->b_wptr++ = (char)connp->conn_ulp;
3968 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3969 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3970 			    &error)) != NULL) {
3971 				ipif_refrele(ipif);
3972 			} else if (error == EINPROGRESS) {
3973 				if (src_ire != NULL)
3974 					ire_refrele(src_ire);
3975 				return (EINPROGRESS);
3976 			} else if (CLASSD(src_addr)) {
3977 				error = 0;
3978 				if (src_ire != NULL)
3979 					ire_refrele(src_ire);
3980 				/*
3981 				 * (5) bind to multicast address.
3982 				 * Fake out the IRE returned to upper
3983 				 * layer to be a broadcast IRE.
3984 				 */
3985 				src_ire = ire_ctable_lookup(
3986 				    INADDR_BROADCAST, INADDR_ANY,
3987 				    IRE_BROADCAST, NULL, zoneid,
3988 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3989 				if (src_ire == NULL || !ire_requested)
3990 					error = EADDRNOTAVAIL;
3991 			} else {
3992 				/*
3993 				 * Not a valid address for bind
3994 				 */
3995 				error = EADDRNOTAVAIL;
3996 			}
3997 			/*
3998 			 * Just to keep it consistent with the processing in
3999 			 * ip_bind_v4()
4000 			 */
4001 			mp->b_wptr--;
4002 		}
4003 		if (error) {
4004 			/* Red Alert!  Attempting to be a bogon! */
4005 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4006 			    ntohl(src_addr)));
4007 			goto bad_addr;
4008 		}
4009 	}
4010 
4011 	/*
4012 	 * Allow setting new policies. For example, disconnects come
4013 	 * down as ipa_t bind. As we would have set conn_policy_cached
4014 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4015 	 * can change after the disconnect.
4016 	 */
4017 	connp->conn_policy_cached = B_FALSE;
4018 
4019 	/*
4020 	 * If not fanout_insert this was just an address verification
4021 	 */
4022 	if (fanout_insert) {
4023 		/*
4024 		 * The addresses have been verified. Time to insert in
4025 		 * the correct fanout list.
4026 		 */
4027 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4028 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4029 		connp->conn_lport = lport;
4030 		connp->conn_fport = 0;
4031 		/*
4032 		 * Do we need to add a check to reject Multicast packets
4033 		 */
4034 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4035 	}
4036 done:
4037 	if (error == 0) {
4038 		if (ire_requested) {
4039 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4040 				error = -1;
4041 				/* Falls through to bad_addr */
4042 			}
4043 		} else if (ipsec_policy_set) {
4044 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4045 				error = -1;
4046 				/* Falls through to bad_addr */
4047 			}
4048 		}
4049 	}
4050 bad_addr:
4051 	if (src_ire != NULL)
4052 		IRE_REFRELE(src_ire);
4053 	if (ipsec_policy_set) {
4054 		ASSERT(policy_mp == mp->b_cont);
4055 		ASSERT(policy_mp != NULL);
4056 		freeb(policy_mp);
4057 		/*
4058 		 * As of now assume that nothing else accompanies
4059 		 * IPSEC_POLICY_SET.
4060 		 */
4061 		mp->b_cont = NULL;
4062 	}
4063 	return (error);
4064 }
4065 
4066 /*
4067  * Verify that both the source and destination addresses
4068  * are valid.  If verify_dst is false, then the destination address may be
4069  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4070  * destination reachability, while tunnels do not.
4071  * Note that we allow connect to broadcast and multicast
4072  * addresses when ire_requested is set. Thus the ULP
4073  * has to check for IRE_BROADCAST and multicast.
4074  *
4075  * Returns zero if ok.
4076  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4077  * (for use with TSYSERR reply).
4078  */
4079 int
4080 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4081     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4082     boolean_t ire_requested, boolean_t ipsec_policy_set,
4083     boolean_t fanout_insert, boolean_t verify_dst)
4084 {
4085 	ire_t		*src_ire;
4086 	ire_t		*dst_ire;
4087 	int		error = 0;
4088 	int 		protocol;
4089 	mblk_t		*policy_mp;
4090 	ire_t		*sire = NULL;
4091 	ire_t		*md_dst_ire = NULL;
4092 	ill_t		*md_ill = NULL;
4093 	zoneid_t	zoneid;
4094 	ipaddr_t	src_addr = *src_addrp;
4095 
4096 	src_ire = dst_ire = NULL;
4097 	protocol = *mp->b_wptr & 0xFF;
4098 
4099 	/*
4100 	 * If we never got a disconnect before, clear it now.
4101 	 */
4102 	connp->conn_fully_bound = B_FALSE;
4103 
4104 	if (ipsec_policy_set) {
4105 		policy_mp = mp->b_cont;
4106 	}
4107 
4108 	zoneid = connp->conn_zoneid;
4109 
4110 	if (CLASSD(dst_addr)) {
4111 		/* Pick up an IRE_BROADCAST */
4112 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4113 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4114 		    MATCH_IRE_RJ_BHOLE));
4115 	} else {
4116 		/*
4117 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4118 		 * and onlink ipif is not found set ENETUNREACH error.
4119 		 */
4120 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4121 			ipif_t *ipif;
4122 
4123 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4124 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4125 			if (ipif == NULL) {
4126 				error = ENETUNREACH;
4127 				goto bad_addr;
4128 			}
4129 			ipif_refrele(ipif);
4130 		}
4131 
4132 		if (connp->conn_nexthop_set) {
4133 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4134 			    0, 0, NULL, NULL, zoneid, 0);
4135 		} else {
4136 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4137 			    &sire, zoneid,
4138 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4139 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4140 		}
4141 	}
4142 	/*
4143 	 * dst_ire can't be a broadcast when not ire_requested.
4144 	 * We also prevent ire's with src address INADDR_ANY to
4145 	 * be used, which are created temporarily for
4146 	 * sending out packets from endpoints that have
4147 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4148 	 * reachable.  If verify_dst is false, the destination needn't be
4149 	 * reachable.
4150 	 *
4151 	 * If we match on a reject or black hole, then we've got a
4152 	 * local failure.  May as well fail out the connect() attempt,
4153 	 * since it's never going to succeed.
4154 	 */
4155 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4156 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4157 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4158 		/*
4159 		 * If we're verifying destination reachability, we always want
4160 		 * to complain here.
4161 		 *
4162 		 * If we're not verifying destination reachability but the
4163 		 * destination has a route, we still want to fail on the
4164 		 * temporary address and broadcast address tests.
4165 		 */
4166 		if (verify_dst || (dst_ire != NULL)) {
4167 			if (ip_debug > 2) {
4168 				pr_addr_dbg("ip_bind_connected: bad connected "
4169 				    "dst %s\n", AF_INET, &dst_addr);
4170 			}
4171 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4172 				error = ENETUNREACH;
4173 			else
4174 				error = EHOSTUNREACH;
4175 			goto bad_addr;
4176 		}
4177 	}
4178 	/*
4179 	 * If the app does a connect(), it means that it will most likely
4180 	 * send more than 1 packet to the destination.  It makes sense
4181 	 * to clear the temporary flag.
4182 	 */
4183 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4184 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4185 		irb_t *irb = dst_ire->ire_bucket;
4186 
4187 		rw_enter(&irb->irb_lock, RW_WRITER);
4188 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4189 		irb->irb_tmp_ire_cnt--;
4190 		rw_exit(&irb->irb_lock);
4191 	}
4192 
4193 	/*
4194 	 * See if we should notify ULP about MDT; we do this whether or not
4195 	 * ire_requested is TRUE, in order to handle active connects; MDT
4196 	 * eligibility tests for passive connects are handled separately
4197 	 * through tcp_adapt_ire().  We do this before the source address
4198 	 * selection, because dst_ire may change after a call to
4199 	 * ipif_select_source().  This is a best-effort check, as the
4200 	 * packet for this connection may not actually go through
4201 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4202 	 * calling ip_newroute().  This is why we further check on the
4203 	 * IRE during Multidata packet transmission in tcp_multisend().
4204 	 */
4205 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4206 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4207 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4208 	    ILL_MDT_CAPABLE(md_ill)) {
4209 		md_dst_ire = dst_ire;
4210 		IRE_REFHOLD(md_dst_ire);
4211 	}
4212 
4213 	if (dst_ire != NULL &&
4214 	    dst_ire->ire_type == IRE_LOCAL &&
4215 	    dst_ire->ire_zoneid != zoneid) {
4216 		/*
4217 		 * If the IRE belongs to a different zone, look for a matching
4218 		 * route in the forwarding table and use the source address from
4219 		 * that route.
4220 		 */
4221 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4222 		    zoneid, 0,
4223 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4224 		    MATCH_IRE_RJ_BHOLE);
4225 		if (src_ire == NULL) {
4226 			error = EHOSTUNREACH;
4227 			goto bad_addr;
4228 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4229 			if (!(src_ire->ire_type & IRE_HOST))
4230 				error = ENETUNREACH;
4231 			else
4232 				error = EHOSTUNREACH;
4233 			goto bad_addr;
4234 		}
4235 		if (src_addr == INADDR_ANY)
4236 			src_addr = src_ire->ire_src_addr;
4237 		ire_refrele(src_ire);
4238 		src_ire = NULL;
4239 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4240 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4241 			src_addr = sire->ire_src_addr;
4242 			ire_refrele(dst_ire);
4243 			dst_ire = sire;
4244 			sire = NULL;
4245 		} else {
4246 			/*
4247 			 * Pick a source address so that a proper inbound
4248 			 * load spreading would happen.
4249 			 */
4250 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4251 			ipif_t *src_ipif = NULL;
4252 			ire_t *ipif_ire;
4253 
4254 			/*
4255 			 * Supply a local source address such that inbound
4256 			 * load spreading happens.
4257 			 *
4258 			 * Determine the best source address on this ill for
4259 			 * the destination.
4260 			 *
4261 			 * 1) For broadcast, we should return a broadcast ire
4262 			 *    found above so that upper layers know that the
4263 			 *    destination address is a broadcast address.
4264 			 *
4265 			 * 2) If this is part of a group, select a better
4266 			 *    source address so that better inbound load
4267 			 *    balancing happens. Do the same if the ipif
4268 			 *    is DEPRECATED.
4269 			 *
4270 			 * 3) If the outgoing interface is part of a usesrc
4271 			 *    group, then try selecting a source address from
4272 			 *    the usesrc ILL.
4273 			 */
4274 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4275 			    ((dst_ill->ill_group != NULL) ||
4276 			    (dst_ire->ire_ipif->ipif_flags &
4277 			    IPIF_DEPRECATED) ||
4278 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4279 				/*
4280 				 * If the destination is reachable via a
4281 				 * given gateway, the selected source address
4282 				 * should be in the same subnet as the gateway.
4283 				 * Otherwise, the destination is not reachable.
4284 				 *
4285 				 * If there are no interfaces on the same subnet
4286 				 * as the destination, ipif_select_source gives
4287 				 * first non-deprecated interface which might be
4288 				 * on a different subnet than the gateway.
4289 				 * This is not desirable. Hence pass the dst_ire
4290 				 * source address to ipif_select_source.
4291 				 * It is sure that the destination is reachable
4292 				 * with the dst_ire source address subnet.
4293 				 * So passing dst_ire source address to
4294 				 * ipif_select_source will make sure that the
4295 				 * selected source will be on the same subnet
4296 				 * as dst_ire source address.
4297 				 */
4298 				ipaddr_t saddr =
4299 				    dst_ire->ire_ipif->ipif_src_addr;
4300 				src_ipif = ipif_select_source(dst_ill,
4301 				    saddr, zoneid);
4302 				if (src_ipif != NULL) {
4303 					if (IS_VNI(src_ipif->ipif_ill)) {
4304 						/*
4305 						 * For VNI there is no
4306 						 * interface route
4307 						 */
4308 						src_addr =
4309 						    src_ipif->ipif_src_addr;
4310 					} else {
4311 						ipif_ire =
4312 						    ipif_to_ire(src_ipif);
4313 						if (ipif_ire != NULL) {
4314 							IRE_REFRELE(dst_ire);
4315 							dst_ire = ipif_ire;
4316 						}
4317 						src_addr =
4318 						    dst_ire->ire_src_addr;
4319 					}
4320 					ipif_refrele(src_ipif);
4321 				} else {
4322 					src_addr = dst_ire->ire_src_addr;
4323 				}
4324 			} else {
4325 				src_addr = dst_ire->ire_src_addr;
4326 			}
4327 		}
4328 	}
4329 
4330 	/*
4331 	 * We do ire_route_lookup() here (and not
4332 	 * interface lookup as we assert that
4333 	 * src_addr should only come from an
4334 	 * UP interface for hard binding.
4335 	 */
4336 	ASSERT(src_ire == NULL);
4337 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4338 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4339 	/* src_ire must be a local|loopback */
4340 	if (!IRE_IS_LOCAL(src_ire)) {
4341 		if (ip_debug > 2) {
4342 			pr_addr_dbg("ip_bind_connected: bad connected "
4343 			    "src %s\n", AF_INET, &src_addr);
4344 		}
4345 		error = EADDRNOTAVAIL;
4346 		goto bad_addr;
4347 	}
4348 
4349 	/*
4350 	 * If the source address is a loopback address, the
4351 	 * destination had best be local or multicast.
4352 	 * The transports that can't handle multicast will reject
4353 	 * those addresses.
4354 	 */
4355 	if (src_ire->ire_type == IRE_LOOPBACK &&
4356 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4357 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4358 		error = -1;
4359 		goto bad_addr;
4360 	}
4361 
4362 	/*
4363 	 * Allow setting new policies. For example, disconnects come
4364 	 * down as ipa_t bind. As we would have set conn_policy_cached
4365 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4366 	 * can change after the disconnect.
4367 	 */
4368 	connp->conn_policy_cached = B_FALSE;
4369 
4370 	/*
4371 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4372 	 * can handle their passed-in conn's.
4373 	 */
4374 
4375 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4376 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4377 	connp->conn_lport = lport;
4378 	connp->conn_fport = fport;
4379 	*src_addrp = src_addr;
4380 
4381 	ASSERT(!(ipsec_policy_set && ire_requested));
4382 	if (ire_requested) {
4383 		iulp_t *ulp_info = NULL;
4384 
4385 		/*
4386 		 * Note that sire will not be NULL if this is an off-link
4387 		 * connection and there is not cache for that dest yet.
4388 		 *
4389 		 * XXX Because of an existing bug, if there are multiple
4390 		 * default routes, the IRE returned now may not be the actual
4391 		 * default route used (default routes are chosen in a
4392 		 * round robin fashion).  So if the metrics for different
4393 		 * default routes are different, we may return the wrong
4394 		 * metrics.  This will not be a problem if the existing
4395 		 * bug is fixed.
4396 		 */
4397 		if (sire != NULL) {
4398 			ulp_info = &(sire->ire_uinfo);
4399 		}
4400 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4401 			error = -1;
4402 			goto bad_addr;
4403 		}
4404 	} else if (ipsec_policy_set) {
4405 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4406 			error = -1;
4407 			goto bad_addr;
4408 		}
4409 	}
4410 
4411 	/*
4412 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4413 	 * we'll cache that.  If we don't, we'll inherit global policy.
4414 	 *
4415 	 * We can't insert until the conn reflects the policy. Note that
4416 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4417 	 * connections where we don't have a policy. This is to prevent
4418 	 * global policy lookups in the inbound path.
4419 	 *
4420 	 * If we insert before we set conn_policy_cached,
4421 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4422 	 * because global policy cound be non-empty. We normally call
4423 	 * ipsec_check_policy() for conn_policy_cached connections only if
4424 	 * ipc_in_enforce_policy is set. But in this case,
4425 	 * conn_policy_cached can get set anytime since we made the
4426 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4427 	 * called, which will make the above assumption false.  Thus, we
4428 	 * need to insert after we set conn_policy_cached.
4429 	 */
4430 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4431 		goto bad_addr;
4432 
4433 	if (fanout_insert) {
4434 		/*
4435 		 * The addresses have been verified. Time to insert in
4436 		 * the correct fanout list.
4437 		 */
4438 		error = ipcl_conn_insert(connp, protocol, src_addr,
4439 		    dst_addr, connp->conn_ports);
4440 	}
4441 
4442 	if (error == 0) {
4443 		connp->conn_fully_bound = B_TRUE;
4444 		/*
4445 		 * Our initial checks for MDT have passed; the IRE is not
4446 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4447 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4448 		 * ip_mdinfo_return(), which performs further checks
4449 		 * against them and upon success, returns the MDT info
4450 		 * mblk which we will attach to the bind acknowledgment.
4451 		 */
4452 		if (md_dst_ire != NULL) {
4453 			mblk_t *mdinfo_mp;
4454 
4455 			ASSERT(md_ill != NULL);
4456 			ASSERT(md_ill->ill_mdt_capab != NULL);
4457 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4458 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4459 				linkb(mp, mdinfo_mp);
4460 		}
4461 	}
4462 bad_addr:
4463 	if (ipsec_policy_set) {
4464 		ASSERT(policy_mp == mp->b_cont);
4465 		ASSERT(policy_mp != NULL);
4466 		freeb(policy_mp);
4467 		/*
4468 		 * As of now assume that nothing else accompanies
4469 		 * IPSEC_POLICY_SET.
4470 		 */
4471 		mp->b_cont = NULL;
4472 	}
4473 	if (src_ire != NULL)
4474 		IRE_REFRELE(src_ire);
4475 	if (dst_ire != NULL)
4476 		IRE_REFRELE(dst_ire);
4477 	if (sire != NULL)
4478 		IRE_REFRELE(sire);
4479 	if (md_dst_ire != NULL)
4480 		IRE_REFRELE(md_dst_ire);
4481 	return (error);
4482 }
4483 
4484 /*
4485  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4486  * Prefers dst_ire over src_ire.
4487  */
4488 static boolean_t
4489 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4490 {
4491 	mblk_t	*mp1;
4492 	ire_t *ret_ire = NULL;
4493 
4494 	mp1 = mp->b_cont;
4495 	ASSERT(mp1 != NULL);
4496 
4497 	if (ire != NULL) {
4498 		/*
4499 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4500 		 * appended mblk. Its <upper protocol>'s
4501 		 * job to make sure there is room.
4502 		 */
4503 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4504 			return (0);
4505 
4506 		mp1->b_datap->db_type = IRE_DB_TYPE;
4507 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4508 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4509 		ret_ire = (ire_t *)mp1->b_rptr;
4510 		/*
4511 		 * Pass the latest setting of the ip_path_mtu_discovery and
4512 		 * copy the ulp info if any.
4513 		 */
4514 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4515 		    IPH_DF : 0;
4516 		if (ulp_info != NULL) {
4517 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4518 			    sizeof (iulp_t));
4519 		}
4520 		ret_ire->ire_mp = mp1;
4521 	} else {
4522 		/*
4523 		 * No IRE was found. Remove IRE mblk.
4524 		 */
4525 		mp->b_cont = mp1->b_cont;
4526 		freeb(mp1);
4527 	}
4528 
4529 	return (1);
4530 }
4531 
4532 /*
4533  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4534  * the final piece where we don't.  Return a pointer to the first mblk in the
4535  * result, and update the pointer to the next mblk to chew on.  If anything
4536  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4537  * NULL pointer.
4538  */
4539 mblk_t *
4540 ip_carve_mp(mblk_t **mpp, ssize_t len)
4541 {
4542 	mblk_t	*mp0;
4543 	mblk_t	*mp1;
4544 	mblk_t	*mp2;
4545 
4546 	if (!len || !mpp || !(mp0 = *mpp))
4547 		return (NULL);
4548 	/* If we aren't going to consume the first mblk, we need a dup. */
4549 	if (mp0->b_wptr - mp0->b_rptr > len) {
4550 		mp1 = dupb(mp0);
4551 		if (mp1) {
4552 			/* Partition the data between the two mblks. */
4553 			mp1->b_wptr = mp1->b_rptr + len;
4554 			mp0->b_rptr = mp1->b_wptr;
4555 			/*
4556 			 * after adjustments if mblk not consumed is now
4557 			 * unaligned, try to align it. If this fails free
4558 			 * all messages and let upper layer recover.
4559 			 */
4560 			if (!OK_32PTR(mp0->b_rptr)) {
4561 				if (!pullupmsg(mp0, -1)) {
4562 					freemsg(mp0);
4563 					freemsg(mp1);
4564 					*mpp = NULL;
4565 					return (NULL);
4566 				}
4567 			}
4568 		}
4569 		return (mp1);
4570 	}
4571 	/* Eat through as many mblks as we need to get len bytes. */
4572 	len -= mp0->b_wptr - mp0->b_rptr;
4573 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4574 		if (mp2->b_wptr - mp2->b_rptr > len) {
4575 			/*
4576 			 * We won't consume the entire last mblk.  Like
4577 			 * above, dup and partition it.
4578 			 */
4579 			mp1->b_cont = dupb(mp2);
4580 			mp1 = mp1->b_cont;
4581 			if (!mp1) {
4582 				/*
4583 				 * Trouble.  Rather than go to a lot of
4584 				 * trouble to clean up, we free the messages.
4585 				 * This won't be any worse than losing it on
4586 				 * the wire.
4587 				 */
4588 				freemsg(mp0);
4589 				freemsg(mp2);
4590 				*mpp = NULL;
4591 				return (NULL);
4592 			}
4593 			mp1->b_wptr = mp1->b_rptr + len;
4594 			mp2->b_rptr = mp1->b_wptr;
4595 			/*
4596 			 * after adjustments if mblk not consumed is now
4597 			 * unaligned, try to align it. If this fails free
4598 			 * all messages and let upper layer recover.
4599 			 */
4600 			if (!OK_32PTR(mp2->b_rptr)) {
4601 				if (!pullupmsg(mp2, -1)) {
4602 					freemsg(mp0);
4603 					freemsg(mp2);
4604 					*mpp = NULL;
4605 					return (NULL);
4606 				}
4607 			}
4608 			*mpp = mp2;
4609 			return (mp0);
4610 		}
4611 		/* Decrement len by the amount we just got. */
4612 		len -= mp2->b_wptr - mp2->b_rptr;
4613 	}
4614 	/*
4615 	 * len should be reduced to zero now.  If not our caller has
4616 	 * screwed up.
4617 	 */
4618 	if (len) {
4619 		/* Shouldn't happen! */
4620 		freemsg(mp0);
4621 		*mpp = NULL;
4622 		return (NULL);
4623 	}
4624 	/*
4625 	 * We consumed up to exactly the end of an mblk.  Detach the part
4626 	 * we are returning from the rest of the chain.
4627 	 */
4628 	mp1->b_cont = NULL;
4629 	*mpp = mp2;
4630 	return (mp0);
4631 }
4632 
4633 /* The ill stream is being unplumbed. Called from ip_close */
4634 int
4635 ip_modclose(ill_t *ill)
4636 {
4637 
4638 	boolean_t success;
4639 	ipsq_t	*ipsq;
4640 	ipif_t	*ipif;
4641 	queue_t	*q = ill->ill_rq;
4642 
4643 	/*
4644 	 * Forcibly enter the ipsq after some delay. This is to take
4645 	 * care of the case when some ioctl does not complete because
4646 	 * we sent a control message to the driver and it did not
4647 	 * send us a reply. We want to be able to at least unplumb
4648 	 * and replumb rather than force the user to reboot the system.
4649 	 */
4650 	success = ipsq_enter(ill, B_FALSE);
4651 
4652 	/*
4653 	 * Open/close/push/pop is guaranteed to be single threaded
4654 	 * per stream by STREAMS. FS guarantees that all references
4655 	 * from top are gone before close is called. So there can't
4656 	 * be another close thread that has set CONDEMNED on this ill.
4657 	 * and cause ipsq_enter to return failure.
4658 	 */
4659 	ASSERT(success);
4660 	ipsq = ill->ill_phyint->phyint_ipsq;
4661 
4662 	/*
4663 	 * Mark it condemned. No new reference will be made to this ill.
4664 	 * Lookup functions will return an error. Threads that try to
4665 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4666 	 * that the refcnt will drop down to zero.
4667 	 */
4668 	mutex_enter(&ill->ill_lock);
4669 	ill->ill_state_flags |= ILL_CONDEMNED;
4670 	for (ipif = ill->ill_ipif; ipif != NULL;
4671 	    ipif = ipif->ipif_next) {
4672 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4673 	}
4674 	/*
4675 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4676 	 * returns  error if ILL_CONDEMNED is set
4677 	 */
4678 	cv_broadcast(&ill->ill_cv);
4679 	mutex_exit(&ill->ill_lock);
4680 
4681 	/*
4682 	 * Shut down fragmentation reassembly.
4683 	 * ill_frag_timer won't start a timer again.
4684 	 * Now cancel any existing timer
4685 	 */
4686 	(void) untimeout(ill->ill_frag_timer_id);
4687 	(void) ill_frag_timeout(ill, 0);
4688 
4689 	/*
4690 	 * If MOVE was in progress, clear the
4691 	 * move_in_progress fields also.
4692 	 */
4693 	if (ill->ill_move_in_progress) {
4694 		ILL_CLEAR_MOVE(ill);
4695 	}
4696 
4697 	/*
4698 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4699 	 * this ill. Then wait for the refcnts to drop to zero.
4700 	 * ill_is_quiescent checks whether the ill is really quiescent.
4701 	 * Then make sure that threads that are waiting to enter the
4702 	 * ipsq have seen the error returned by ipsq_enter and have
4703 	 * gone away. Then we call ill_delete_tail which does the
4704 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4705 	 */
4706 	ill_delete(ill);
4707 	mutex_enter(&ill->ill_lock);
4708 	while (!ill_is_quiescent(ill))
4709 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4710 	while (ill->ill_waiters)
4711 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4712 
4713 	mutex_exit(&ill->ill_lock);
4714 
4715 	/* qprocsoff is called in ill_delete_tail */
4716 	ill_delete_tail(ill);
4717 
4718 	/*
4719 	 * Walk through all upper (conn) streams and qenable
4720 	 * those that have queued data.
4721 	 * close synchronization needs this to
4722 	 * be done to ensure that all upper layers blocked
4723 	 * due to flow control to the closing device
4724 	 * get unblocked.
4725 	 */
4726 	ip1dbg(("ip_wsrv: walking\n"));
4727 	conn_walk_drain();
4728 
4729 	mutex_enter(&ip_mi_lock);
4730 	mi_close_unlink(&ip_g_head, (IDP)ill);
4731 	mutex_exit(&ip_mi_lock);
4732 
4733 	/*
4734 	 * credp could be null if the open didn't succeed and ip_modopen
4735 	 * itself calls ip_close.
4736 	 */
4737 	if (ill->ill_credp != NULL)
4738 		crfree(ill->ill_credp);
4739 
4740 	mi_close_free((IDP)ill);
4741 	q->q_ptr = WR(q)->q_ptr = NULL;
4742 
4743 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4744 
4745 	return (0);
4746 }
4747 
4748 /*
4749  * This is called as part of close() for both IP and UDP
4750  * in order to quiesce the conn.
4751  */
4752 void
4753 ip_quiesce_conn(conn_t *connp)
4754 {
4755 	boolean_t	drain_cleanup_reqd = B_FALSE;
4756 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4757 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4758 
4759 	ASSERT(!IPCL_IS_TCP(connp));
4760 
4761 	/*
4762 	 * Mark the conn as closing, and this conn must not be
4763 	 * inserted in future into any list. Eg. conn_drain_insert(),
4764 	 * won't insert this conn into the conn_drain_list.
4765 	 * Similarly ill_pending_mp_add() will not add any mp to
4766 	 * the pending mp list, after this conn has started closing.
4767 	 *
4768 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4769 	 * cannot get set henceforth.
4770 	 */
4771 	mutex_enter(&connp->conn_lock);
4772 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4773 	connp->conn_state_flags |= CONN_CLOSING;
4774 	if (connp->conn_idl != NULL)
4775 		drain_cleanup_reqd = B_TRUE;
4776 	if (connp->conn_oper_pending_ill != NULL)
4777 		conn_ioctl_cleanup_reqd = B_TRUE;
4778 	if (connp->conn_ilg_inuse != 0)
4779 		ilg_cleanup_reqd = B_TRUE;
4780 	mutex_exit(&connp->conn_lock);
4781 
4782 	if (IPCL_IS_UDP(connp))
4783 		udp_quiesce_conn(connp);
4784 
4785 	if (conn_ioctl_cleanup_reqd)
4786 		conn_ioctl_cleanup(connp);
4787 
4788 	/*
4789 	 * Remove this conn from any fanout list it is on.
4790 	 * and then wait for any threads currently operating
4791 	 * on this endpoint to finish
4792 	 */
4793 	ipcl_hash_remove(connp);
4794 
4795 	/*
4796 	 * Remove this conn from the drain list, and do
4797 	 * any other cleanup that may be required.
4798 	 * (Only non-tcp streams may have a non-null conn_idl.
4799 	 * TCP streams are never flow controlled, and
4800 	 * conn_idl will be null)
4801 	 */
4802 	if (drain_cleanup_reqd)
4803 		conn_drain_tail(connp, B_TRUE);
4804 
4805 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4806 		(void) ip_mrouter_done(NULL);
4807 
4808 	if (ilg_cleanup_reqd)
4809 		ilg_delete_all(connp);
4810 
4811 	conn_delete_ire(connp, NULL);
4812 
4813 	/*
4814 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4815 	 * callers from write side can't be there now because close
4816 	 * is in progress. The only other caller is ipcl_walk
4817 	 * which checks for the condemned flag.
4818 	 */
4819 	mutex_enter(&connp->conn_lock);
4820 	connp->conn_state_flags |= CONN_CONDEMNED;
4821 	while (connp->conn_ref != 1)
4822 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4823 	connp->conn_state_flags |= CONN_QUIESCED;
4824 	mutex_exit(&connp->conn_lock);
4825 }
4826 
4827 /* ARGSUSED */
4828 int
4829 ip_close(queue_t *q, int flags)
4830 {
4831 	conn_t		*connp;
4832 
4833 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4834 
4835 	/*
4836 	 * Call the appropriate delete routine depending on whether this is
4837 	 * a module or device.
4838 	 */
4839 	if (WR(q)->q_next != NULL) {
4840 		/* This is a module close */
4841 		return (ip_modclose((ill_t *)q->q_ptr));
4842 	}
4843 
4844 	connp = q->q_ptr;
4845 	ip_quiesce_conn(connp);
4846 
4847 	qprocsoff(q);
4848 
4849 	/*
4850 	 * Now we are truly single threaded on this stream, and can
4851 	 * delete the things hanging off the connp, and finally the connp.
4852 	 * We removed this connp from the fanout list, it cannot be
4853 	 * accessed thru the fanouts, and we already waited for the
4854 	 * conn_ref to drop to 0. We are already in close, so
4855 	 * there cannot be any other thread from the top. qprocsoff
4856 	 * has completed, and service has completed or won't run in
4857 	 * future.
4858 	 */
4859 	ASSERT(connp->conn_ref == 1);
4860 
4861 	/*
4862 	 * A conn which was previously marked as IPCL_UDP cannot
4863 	 * retain the flag because it would have been cleared by
4864 	 * udp_close().
4865 	 */
4866 	ASSERT(!IPCL_IS_UDP(connp));
4867 
4868 	if (connp->conn_latch != NULL) {
4869 		IPLATCH_REFRELE(connp->conn_latch);
4870 		connp->conn_latch = NULL;
4871 	}
4872 	if (connp->conn_policy != NULL) {
4873 		IPPH_REFRELE(connp->conn_policy);
4874 		connp->conn_policy = NULL;
4875 	}
4876 	if (connp->conn_ipsec_opt_mp != NULL) {
4877 		freemsg(connp->conn_ipsec_opt_mp);
4878 		connp->conn_ipsec_opt_mp = NULL;
4879 	}
4880 	if (connp->conn_cred != NULL) {
4881 		crfree(connp->conn_cred);
4882 		connp->conn_cred = NULL;
4883 	}
4884 
4885 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4886 
4887 	connp->conn_ref--;
4888 	ipcl_conn_destroy(connp);
4889 
4890 	q->q_ptr = WR(q)->q_ptr = NULL;
4891 	return (0);
4892 }
4893 
4894 int
4895 ip_snmpmod_close(queue_t *q)
4896 {
4897 	conn_t *connp = Q_TO_CONN(q);
4898 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4899 
4900 	qprocsoff(q);
4901 
4902 	if (connp->conn_flags & IPCL_UDPMOD)
4903 		udp_close_free(connp);
4904 
4905 	if (connp->conn_cred != NULL) {
4906 		crfree(connp->conn_cred);
4907 		connp->conn_cred = NULL;
4908 	}
4909 	CONN_DEC_REF(connp);
4910 	q->q_ptr = WR(q)->q_ptr = NULL;
4911 	return (0);
4912 }
4913 
4914 /*
4915  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
4916  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
4917  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
4918  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
4919  * queues as we never enqueue messages there and we don't handle any ioctls.
4920  * Everything else is freed.
4921  */
4922 void
4923 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
4924 {
4925 	conn_t	*connp = q->q_ptr;
4926 	pfi_t	setfn;
4927 	pfi_t	getfn;
4928 
4929 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4930 
4931 	switch (DB_TYPE(mp)) {
4932 	case M_PROTO:
4933 	case M_PCPROTO:
4934 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
4935 		    ((((union T_primitives *)mp->b_rptr)->type ==
4936 			T_SVR4_OPTMGMT_REQ) ||
4937 		    (((union T_primitives *)mp->b_rptr)->type ==
4938 			T_OPTMGMT_REQ))) {
4939 			/*
4940 			 * This is the only TPI primitive supported. Its
4941 			 * handling does not require tcp_t, but it does require
4942 			 * conn_t to check permissions.
4943 			 */
4944 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
4945 
4946 			if (connp->conn_flags & IPCL_TCPMOD) {
4947 				setfn = tcp_snmp_set;
4948 				getfn = tcp_snmp_get;
4949 			} else {
4950 				setfn = udp_snmp_set;
4951 				getfn = udp_snmp_get;
4952 			}
4953 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
4954 				freemsg(mp);
4955 				return;
4956 			}
4957 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
4958 		    != NULL)
4959 			qreply(q, mp);
4960 		break;
4961 	case M_FLUSH:
4962 	case M_IOCTL:
4963 		putnext(q, mp);
4964 		break;
4965 	default:
4966 		freemsg(mp);
4967 		break;
4968 	}
4969 }
4970 
4971 /* Return the IP checksum for the IP header at "iph". */
4972 uint16_t
4973 ip_csum_hdr(ipha_t *ipha)
4974 {
4975 	uint16_t	*uph;
4976 	uint32_t	sum;
4977 	int		opt_len;
4978 
4979 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4980 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4981 	uph = (uint16_t *)ipha;
4982 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4983 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4984 	if (opt_len > 0) {
4985 		do {
4986 			sum += uph[10];
4987 			sum += uph[11];
4988 			uph += 2;
4989 		} while (--opt_len);
4990 	}
4991 	sum = (sum & 0xFFFF) + (sum >> 16);
4992 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4993 	if (sum == 0xffff)
4994 		sum = 0;
4995 	return ((uint16_t)sum);
4996 }
4997 
4998 void
4999 ip_ddi_destroy(void)
5000 {
5001 	tcp_ddi_destroy();
5002 	sctp_ddi_destroy();
5003 	ipsec_loader_destroy();
5004 	ipsec_policy_destroy();
5005 	ipsec_kstat_destroy();
5006 	nd_free(&ip_g_nd);
5007 	mutex_destroy(&igmp_timer_lock);
5008 	mutex_destroy(&mld_timer_lock);
5009 	mutex_destroy(&igmp_slowtimeout_lock);
5010 	mutex_destroy(&mld_slowtimeout_lock);
5011 	mutex_destroy(&ip_mi_lock);
5012 	mutex_destroy(&rts_clients.connf_lock);
5013 	ip_ire_fini();
5014 	ip6_asp_free();
5015 	conn_drain_fini();
5016 	ipcl_destroy();
5017 	inet_minor_destroy(ip_minor_arena);
5018 	icmp_kstat_fini();
5019 	ip_kstat_fini();
5020 	rw_destroy(&ipsec_capab_ills_lock);
5021 	rw_destroy(&ill_g_usesrc_lock);
5022 	ip_drop_unregister(&ip_dropper);
5023 }
5024 
5025 
5026 void
5027 ip_ddi_init(void)
5028 {
5029 	TCP6_MAJ = ddi_name_to_major(TCP6);
5030 	TCP_MAJ	= ddi_name_to_major(TCP);
5031 	SCTP_MAJ = ddi_name_to_major(SCTP);
5032 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5033 
5034 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5035 
5036 	/* IP's IPsec code calls the packet dropper */
5037 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5038 
5039 	if (!ip_g_nd) {
5040 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5041 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5042 			nd_free(&ip_g_nd);
5043 		}
5044 	}
5045 
5046 	ipsec_loader_init();
5047 	ipsec_policy_init();
5048 	ipsec_kstat_init();
5049 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5050 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5051 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5052 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5053 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5054 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5055 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5056 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5057 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5058 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5059 
5060 	/*
5061 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5062 	 * initial devices: ip, ip6, tcp, tcp6.
5063 	 */
5064 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5065 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5066 		cmn_err(CE_PANIC,
5067 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5068 	}
5069 
5070 	ipcl_init();
5071 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5072 	ip_ire_init();
5073 	ip6_asp_init();
5074 	ipif_init();
5075 	conn_drain_init();
5076 	tcp_ddi_init();
5077 	sctp_ddi_init();
5078 
5079 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5080 
5081 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5082 		"net", KSTAT_TYPE_NAMED,
5083 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5084 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5085 		ip_kstat->ks_data = &ip_statistics;
5086 		kstat_install(ip_kstat);
5087 	}
5088 	ip_kstat_init();
5089 	ip6_kstat_init();
5090 	icmp_kstat_init();
5091 
5092 	ipsec_loader_start();
5093 }
5094 
5095 /*
5096  * Allocate and initialize a DLPI template of the specified length.  (May be
5097  * called as writer.)
5098  */
5099 mblk_t *
5100 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5101 {
5102 	mblk_t	*mp;
5103 
5104 	mp = allocb(len, BPRI_MED);
5105 	if (!mp)
5106 		return (NULL);
5107 
5108 	/*
5109 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5110 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5111 	 * that other DLPI are M_PROTO.
5112 	 */
5113 	if (prim == DL_INFO_REQ) {
5114 		mp->b_datap->db_type = M_PCPROTO;
5115 	} else {
5116 		mp->b_datap->db_type = M_PROTO;
5117 	}
5118 
5119 	mp->b_wptr = mp->b_rptr + len;
5120 	bzero(mp->b_rptr, len);
5121 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5122 	return (mp);
5123 }
5124 
5125 const char *
5126 dlpi_prim_str(int prim)
5127 {
5128 	switch (prim) {
5129 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5130 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5131 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5132 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5133 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5134 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5135 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5136 	case DL_OK_ACK:		return ("DL_OK_ACK");
5137 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5138 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5139 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5140 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5141 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5142 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5143 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5144 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5145 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5146 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5147 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5148 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5149 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5150 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5151 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5152 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5153 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5154 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5155 	default:		return ("<unknown primitive>");
5156 	}
5157 }
5158 
5159 const char *
5160 dlpi_err_str(int err)
5161 {
5162 	switch (err) {
5163 	case DL_ACCESS:		return ("DL_ACCESS");
5164 	case DL_BADADDR:	return ("DL_BADADDR");
5165 	case DL_BADCORR:	return ("DL_BADCORR");
5166 	case DL_BADDATA:	return ("DL_BADDATA");
5167 	case DL_BADPPA:		return ("DL_BADPPA");
5168 	case DL_BADPRIM:	return ("DL_BADPRIM");
5169 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5170 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5171 	case DL_BADSAP:		return ("DL_BADSAP");
5172 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5173 	case DL_BOUND:		return ("DL_BOUND");
5174 	case DL_INITFAILED:	return ("DL_INITFAILED");
5175 	case DL_NOADDR:		return ("DL_NOADDR");
5176 	case DL_NOTINIT:	return ("DL_NOTINIT");
5177 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5178 	case DL_SYSERR:		return ("DL_SYSERR");
5179 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5180 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5181 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5182 	case DL_TOOMANY:	return ("DL_TOOMANY");
5183 	case DL_NOTENAB:	return ("DL_NOTENAB");
5184 	case DL_BUSY:		return ("DL_BUSY");
5185 	case DL_NOAUTO:		return ("DL_NOAUTO");
5186 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5187 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5188 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5189 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5190 	case DL_PENDING:	return ("DL_PENDING");
5191 	default:		return ("<unknown error>");
5192 	}
5193 }
5194 
5195 /*
5196  * Debug formatting routine.  Returns a character string representation of the
5197  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5198  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5199  */
5200 char *
5201 ip_dot_addr(ipaddr_t addr, char *buf)
5202 {
5203 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5204 }
5205 
5206 /*
5207  * Debug formatting routine.  Returns a character string representation of the
5208  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5209  * as a pointer.  The "xxx" parts including left zero padding so the final
5210  * string will fit easily in tables.  It would be nice to take a padding
5211  * length argument instead.
5212  */
5213 static char *
5214 ip_dot_saddr(uchar_t *addr, char *buf)
5215 {
5216 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5217 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5218 	return (buf);
5219 }
5220 
5221 /*
5222  * Send an ICMP error after patching up the packet appropriately.  Returns
5223  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5224  */
5225 static boolean_t
5226 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5227     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5228 {
5229 	ipha_t *ipha;
5230 	mblk_t *first_mp;
5231 	boolean_t secure;
5232 	unsigned char db_type;
5233 
5234 	first_mp = mp;
5235 	if (mctl_present) {
5236 		mp = mp->b_cont;
5237 		secure = ipsec_in_is_secure(first_mp);
5238 		ASSERT(mp != NULL);
5239 	} else {
5240 		/*
5241 		 * If this is an ICMP error being reported - which goes
5242 		 * up as M_CTLs, we need to convert them to M_DATA till
5243 		 * we finish checking with global policy because
5244 		 * ipsec_check_global_policy() assumes M_DATA as clear
5245 		 * and M_CTL as secure.
5246 		 */
5247 		db_type = DB_TYPE(mp);
5248 		DB_TYPE(mp) = M_DATA;
5249 		secure = B_FALSE;
5250 	}
5251 	/*
5252 	 * We are generating an icmp error for some inbound packet.
5253 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5254 	 * Before we generate an error, check with global policy
5255 	 * to see whether this is allowed to enter the system. As
5256 	 * there is no "conn", we are checking with global policy.
5257 	 */
5258 	ipha = (ipha_t *)mp->b_rptr;
5259 	if (secure || ipsec_inbound_v4_policy_present) {
5260 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5261 		    ipha, NULL, mctl_present);
5262 		if (first_mp == NULL)
5263 			return (B_FALSE);
5264 	}
5265 
5266 	if (!mctl_present)
5267 		DB_TYPE(mp) = db_type;
5268 
5269 	if (flags & IP_FF_SEND_ICMP) {
5270 		if (flags & IP_FF_HDR_COMPLETE) {
5271 			if (ip_hdr_complete(ipha, zoneid)) {
5272 				freemsg(first_mp);
5273 				return (B_TRUE);
5274 			}
5275 		}
5276 		if (flags & IP_FF_CKSUM) {
5277 			/*
5278 			 * Have to correct checksum since
5279 			 * the packet might have been
5280 			 * fragmented and the reassembly code in ip_rput
5281 			 * does not restore the IP checksum.
5282 			 */
5283 			ipha->ipha_hdr_checksum = 0;
5284 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5285 		}
5286 		switch (icmp_type) {
5287 		case ICMP_DEST_UNREACHABLE:
5288 			icmp_unreachable(WR(q), first_mp, icmp_code);
5289 			break;
5290 		default:
5291 			freemsg(first_mp);
5292 			break;
5293 		}
5294 	} else {
5295 		freemsg(first_mp);
5296 		return (B_FALSE);
5297 	}
5298 
5299 	return (B_TRUE);
5300 }
5301 
5302 #ifdef DEBUG
5303 /*
5304  * Copy the header into the IPSEC_IN message.
5305  */
5306 static void
5307 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5308 {
5309 	mblk_t *data_mp = ipsec_mp->b_cont;
5310 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5311 	ipha_t *ipha;
5312 
5313 	if (ii->ipsec_in_type != IPSEC_IN)
5314 		return;
5315 	ASSERT(data_mp != NULL);
5316 
5317 	ipha = (ipha_t *)data_mp->b_rptr;
5318 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5319 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5320 	    sizeof (ipha_t) : sizeof (ip6_t));
5321 }
5322 #else
5323 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5324 #endif	/* DEBUG */
5325 
5326 /*
5327  * Used to send an ICMP error message when a packet is received for
5328  * a protocol that is not supported. The mblk passed as argument
5329  * is consumed by this function.
5330  */
5331 void
5332 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5333 {
5334 	mblk_t *mp;
5335 	ipha_t *ipha;
5336 	ill_t *ill;
5337 	ipsec_in_t *ii;
5338 
5339 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5340 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5341 
5342 	mp = ipsec_mp->b_cont;
5343 	ipsec_mp->b_cont = NULL;
5344 	ipha = (ipha_t *)mp->b_rptr;
5345 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5346 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5347 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5348 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5349 		}
5350 	} else {
5351 		/* Get ill from index in ipsec_in_t. */
5352 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5353 		    B_TRUE, NULL, NULL, NULL, NULL);
5354 		if (ill != NULL) {
5355 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5356 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5357 			    0, B_FALSE, zoneid)) {
5358 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5359 			}
5360 
5361 			ill_refrele(ill);
5362 		} else { /* re-link for the freemsg() below. */
5363 			ipsec_mp->b_cont = mp;
5364 		}
5365 	}
5366 
5367 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5368 	freemsg(ipsec_mp);
5369 }
5370 
5371 /*
5372  * See if the inbound datagram has had IPsec processing applied to it.
5373  */
5374 boolean_t
5375 ipsec_in_is_secure(mblk_t *ipsec_mp)
5376 {
5377 	ipsec_in_t *ii;
5378 
5379 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5380 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5381 
5382 	if (ii->ipsec_in_loopback) {
5383 		return (ii->ipsec_in_secure);
5384 	} else {
5385 		return (ii->ipsec_in_ah_sa != NULL ||
5386 		    ii->ipsec_in_esp_sa != NULL ||
5387 		    ii->ipsec_in_decaps);
5388 	}
5389 }
5390 
5391 /*
5392  * Handle protocols with which IP is less intimate.  There
5393  * can be more than one stream bound to a particular
5394  * protocol.  When this is the case, normally each one gets a copy
5395  * of any incoming packets.
5396  *
5397  * IPSEC NOTE :
5398  *
5399  * Don't allow a secure packet going up a non-secure connection.
5400  * We don't allow this because
5401  *
5402  * 1) Reply might go out in clear which will be dropped at
5403  *    the sending side.
5404  * 2) If the reply goes out in clear it will give the
5405  *    adversary enough information for getting the key in
5406  *    most of the cases.
5407  *
5408  * Moreover getting a secure packet when we expect clear
5409  * implies that SA's were added without checking for
5410  * policy on both ends. This should not happen once ISAKMP
5411  * is used to negotiate SAs as SAs will be added only after
5412  * verifying the policy.
5413  *
5414  * NOTE : If the packet was tunneled and not multicast we only send
5415  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5416  * back to delivering packets to AF_INET6 raw sockets.
5417  *
5418  * IPQoS Notes:
5419  * Once we have determined the client, invoke IPPF processing.
5420  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5421  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5422  * ip_policy will be false.
5423  *
5424  * Zones notes:
5425  * Currently only applications in the global zone can create raw sockets for
5426  * protocols other than ICMP. So unlike the broadcast / multicast case of
5427  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5428  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5429  */
5430 static void
5431 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5432     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5433     zoneid_t zoneid)
5434 {
5435 	queue_t	*rq;
5436 	mblk_t	*mp1, *first_mp1;
5437 	uint_t	protocol = ipha->ipha_protocol;
5438 	ipaddr_t dst;
5439 	boolean_t one_only;
5440 	mblk_t *first_mp = mp;
5441 	boolean_t secure;
5442 	uint32_t ill_index;
5443 	conn_t	*connp, *first_connp, *next_connp;
5444 	connf_t	*connfp;
5445 
5446 	if (mctl_present) {
5447 		mp = first_mp->b_cont;
5448 		secure = ipsec_in_is_secure(first_mp);
5449 		ASSERT(mp != NULL);
5450 	} else {
5451 		secure = B_FALSE;
5452 	}
5453 	dst = ipha->ipha_dst;
5454 	/*
5455 	 * If the packet was tunneled and not multicast we only send to it
5456 	 * the first match.
5457 	 */
5458 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5459 	    !CLASSD(dst));
5460 
5461 	connfp = &ipcl_proto_fanout[protocol];
5462 	mutex_enter(&connfp->connf_lock);
5463 	connp = connfp->connf_head;
5464 	for (connp = connfp->connf_head; connp != NULL;
5465 		connp = connp->conn_next) {
5466 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5467 			break;
5468 	}
5469 
5470 	if (connp == NULL || connp->conn_upq == NULL) {
5471 		/*
5472 		 * No one bound to these addresses.  Is
5473 		 * there a client that wants all
5474 		 * unclaimed datagrams?
5475 		 */
5476 		mutex_exit(&connfp->connf_lock);
5477 		/*
5478 		 * Check for IPPROTO_ENCAP...
5479 		 */
5480 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5481 			/*
5482 			 * XXX If an IPsec mblk is here on a multicast
5483 			 * tunnel (using ip_mroute stuff), what should
5484 			 * I do?
5485 			 *
5486 			 * For now, just free the IPsec mblk before
5487 			 * passing it up to the multicast routing
5488 			 * stuff.
5489 			 *
5490 			 * BTW,  If I match a configured IP-in-IP
5491 			 * tunnel, ip_mroute_decap will never be
5492 			 * called.
5493 			 */
5494 			if (mp != first_mp)
5495 				freeb(first_mp);
5496 			ip_mroute_decap(q, mp);
5497 		} else {
5498 			/*
5499 			 * Otherwise send an ICMP protocol unreachable.
5500 			 */
5501 			if (ip_fanout_send_icmp(q, first_mp, flags,
5502 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5503 			    mctl_present, zoneid)) {
5504 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5505 			}
5506 		}
5507 		return;
5508 	}
5509 	CONN_INC_REF(connp);
5510 	first_connp = connp;
5511 
5512 	/*
5513 	 * Only send message to one tunnel driver by immediately
5514 	 * terminating the loop.
5515 	 */
5516 	connp = one_only ? NULL : connp->conn_next;
5517 
5518 	for (;;) {
5519 		while (connp != NULL) {
5520 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5521 			    flags, zoneid))
5522 				break;
5523 			connp = connp->conn_next;
5524 		}
5525 
5526 		/*
5527 		 * Copy the packet.
5528 		 */
5529 		if (connp == NULL || connp->conn_upq == NULL ||
5530 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5531 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5532 			/*
5533 			 * No more interested clients or memory
5534 			 * allocation failed
5535 			 */
5536 			connp = first_connp;
5537 			break;
5538 		}
5539 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5540 		CONN_INC_REF(connp);
5541 		mutex_exit(&connfp->connf_lock);
5542 		rq = connp->conn_rq;
5543 		if (!canputnext(rq)) {
5544 			if (flags & IP_FF_RAWIP) {
5545 				BUMP_MIB(&ip_mib, rawipInOverflows);
5546 			} else {
5547 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5548 			}
5549 
5550 			freemsg(first_mp1);
5551 		} else {
5552 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5553 				first_mp1 = ipsec_check_inbound_policy
5554 				    (first_mp1, connp, ipha, NULL,
5555 				    mctl_present);
5556 			}
5557 			if (first_mp1 != NULL) {
5558 				/*
5559 				 * ip_fanout_proto also gets called from
5560 				 * icmp_inbound_error_fanout, in which case
5561 				 * the msg type is M_CTL.  Don't add info
5562 				 * in this case for the time being. In future
5563 				 * when there is a need for knowing the
5564 				 * inbound iface index for ICMP error msgs,
5565 				 * then this can be changed.
5566 				 */
5567 				if ((connp->conn_recvif != 0) &&
5568 				    (mp->b_datap->db_type != M_CTL)) {
5569 					/*
5570 					 * the actual data will be
5571 					 * contained in b_cont upon
5572 					 * successful return of the
5573 					 * following call else
5574 					 * original mblk is returned
5575 					 */
5576 					ASSERT(recv_ill != NULL);
5577 					mp1 = ip_add_info(mp1, recv_ill,
5578 						IPF_RECVIF);
5579 				}
5580 				BUMP_MIB(&ip_mib, ipInDelivers);
5581 				if (mctl_present)
5582 					freeb(first_mp1);
5583 				putnext(rq, mp1);
5584 			}
5585 		}
5586 		mutex_enter(&connfp->connf_lock);
5587 		/* Follow the next pointer before releasing the conn. */
5588 		next_connp = connp->conn_next;
5589 		CONN_DEC_REF(connp);
5590 		connp = next_connp;
5591 	}
5592 
5593 	/* Last one.  Send it upstream. */
5594 	mutex_exit(&connfp->connf_lock);
5595 
5596 	/*
5597 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5598 	 * will be set to false.
5599 	 */
5600 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5601 		ill_index = ill->ill_phyint->phyint_ifindex;
5602 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5603 		if (mp == NULL) {
5604 			CONN_DEC_REF(connp);
5605 			if (mctl_present) {
5606 				freeb(first_mp);
5607 			}
5608 			return;
5609 		}
5610 	}
5611 
5612 	rq = connp->conn_rq;
5613 	if (!canputnext(rq)) {
5614 		if (flags & IP_FF_RAWIP) {
5615 			BUMP_MIB(&ip_mib, rawipInOverflows);
5616 		} else {
5617 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5618 		}
5619 
5620 		freemsg(first_mp);
5621 	} else {
5622 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5623 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5624 			    ipha, NULL, mctl_present);
5625 		}
5626 		if (first_mp != NULL) {
5627 			/*
5628 			 * ip_fanout_proto also gets called
5629 			 * from icmp_inbound_error_fanout, in
5630 			 * which case the msg type is M_CTL.
5631 			 * Don't add info in this case for time
5632 			 * being. In future when there is a
5633 			 * need for knowing the inbound iface
5634 			 * index for ICMP error msgs, then this
5635 			 * can be changed
5636 			 */
5637 			if ((connp->conn_recvif != 0) &&
5638 			    (mp->b_datap->db_type != M_CTL)) {
5639 				/*
5640 				 * the actual data will be contained in
5641 				 * b_cont upon successful return
5642 				 * of the following call else original
5643 				 * mblk is returned
5644 				 */
5645 				ASSERT(recv_ill != NULL);
5646 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5647 			}
5648 			BUMP_MIB(&ip_mib, ipInDelivers);
5649 			putnext(rq, mp);
5650 			if (mctl_present)
5651 				freeb(first_mp);
5652 		}
5653 	}
5654 	CONN_DEC_REF(connp);
5655 }
5656 
5657 /*
5658  * Fanout for TCP packets
5659  * The caller puts <fport, lport> in the ports parameter.
5660  *
5661  * IPQoS Notes
5662  * Before sending it to the client, invoke IPPF processing.
5663  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5664  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5665  * ip_policy is false.
5666  */
5667 static void
5668 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5669     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5670 {
5671 	mblk_t  *first_mp;
5672 	boolean_t secure;
5673 	uint32_t ill_index;
5674 	int	ip_hdr_len;
5675 	tcph_t	*tcph;
5676 	boolean_t syn_present = B_FALSE;
5677 	conn_t	*connp;
5678 
5679 	first_mp = mp;
5680 	if (mctl_present) {
5681 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5682 		mp = first_mp->b_cont;
5683 		secure = ipsec_in_is_secure(first_mp);
5684 		ASSERT(mp != NULL);
5685 	} else {
5686 		secure = B_FALSE;
5687 	}
5688 
5689 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5690 
5691 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5692 	    NULL) {
5693 		/*
5694 		 * No connected connection or listener. Send a
5695 		 * TH_RST via tcp_xmit_listeners_reset.
5696 		 */
5697 
5698 		/* Initiate IPPf processing, if needed. */
5699 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5700 			uint32_t ill_index;
5701 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5702 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5703 			if (first_mp == NULL)
5704 				return;
5705 		}
5706 		BUMP_MIB(&ip_mib, ipInDelivers);
5707 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5708 		return;
5709 	}
5710 
5711 	/*
5712 	 * Allocate the SYN for the TCP connection here itself
5713 	 */
5714 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5715 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5716 		if (IPCL_IS_TCP(connp)) {
5717 			squeue_t *sqp;
5718 
5719 			/*
5720 			 * For fused tcp loopback, assign the eager's
5721 			 * squeue to be that of the active connect's.
5722 			 * Note that we don't check for IP_FF_LOOPBACK
5723 			 * here since this routine gets called only
5724 			 * for loopback (unlike the IPv6 counterpart).
5725 			 */
5726 			ASSERT(Q_TO_CONN(q) != NULL);
5727 			if (do_tcp_fusion &&
5728 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5729 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
5730 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
5731 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
5732 				sqp = Q_TO_CONN(q)->conn_sqp;
5733 			} else {
5734 				sqp = IP_SQUEUE_GET(lbolt);
5735 			}
5736 
5737 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5738 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
5739 			syn_present = B_TRUE;
5740 		}
5741 	}
5742 
5743 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5744 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5745 		if ((flags & TH_RST) || (flags & TH_URG)) {
5746 			CONN_DEC_REF(connp);
5747 			freemsg(first_mp);
5748 			return;
5749 		}
5750 		if (flags & TH_ACK) {
5751 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5752 			CONN_DEC_REF(connp);
5753 			return;
5754 		}
5755 
5756 		CONN_DEC_REF(connp);
5757 		freemsg(first_mp);
5758 		return;
5759 	}
5760 
5761 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5762 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5763 		    NULL, mctl_present);
5764 		if (first_mp == NULL) {
5765 			CONN_DEC_REF(connp);
5766 			return;
5767 		}
5768 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5769 			ASSERT(syn_present);
5770 			if (mctl_present) {
5771 				ASSERT(first_mp != mp);
5772 				first_mp->b_datap->db_struioflag |=
5773 				    STRUIO_POLICY;
5774 			} else {
5775 				ASSERT(first_mp == mp);
5776 				mp->b_datap->db_struioflag &=
5777 				    ~STRUIO_EAGER;
5778 				mp->b_datap->db_struioflag |=
5779 				    STRUIO_POLICY;
5780 			}
5781 		} else {
5782 			/*
5783 			 * Discard first_mp early since we're dealing with a
5784 			 * fully-connected conn_t and tcp doesn't do policy in
5785 			 * this case.
5786 			 */
5787 			if (mctl_present) {
5788 				freeb(first_mp);
5789 				mctl_present = B_FALSE;
5790 			}
5791 			first_mp = mp;
5792 		}
5793 	}
5794 
5795 	/*
5796 	 * Initiate policy processing here if needed. If we get here from
5797 	 * icmp_inbound_error_fanout, ip_policy is false.
5798 	 */
5799 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5800 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5801 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5802 		if (mp == NULL) {
5803 			CONN_DEC_REF(connp);
5804 			if (mctl_present)
5805 				freeb(first_mp);
5806 			return;
5807 		} else if (mctl_present) {
5808 			ASSERT(first_mp != mp);
5809 			first_mp->b_cont = mp;
5810 		} else {
5811 			first_mp = mp;
5812 		}
5813 	}
5814 
5815 
5816 
5817 	/* Handle IPv6 socket options. */
5818 	if (!syn_present &&
5819 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5820 		/* Add header */
5821 		ASSERT(recv_ill != NULL);
5822 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5823 		if (mp == NULL) {
5824 			CONN_DEC_REF(connp);
5825 			if (mctl_present)
5826 				freeb(first_mp);
5827 			return;
5828 		} else if (mctl_present) {
5829 			/*
5830 			 * ip_add_info might return a new mp.
5831 			 */
5832 			ASSERT(first_mp != mp);
5833 			first_mp->b_cont = mp;
5834 		} else {
5835 			first_mp = mp;
5836 		}
5837 	}
5838 
5839 	BUMP_MIB(&ip_mib, ipInDelivers);
5840 	if (IPCL_IS_TCP(connp)) {
5841 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5842 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5843 	} else {
5844 		putnext(connp->conn_rq, first_mp);
5845 		CONN_DEC_REF(connp);
5846 	}
5847 }
5848 
5849 /*
5850  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5851  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5852  * Caller is responsible for dropping references to the conn, and freeing
5853  * first_mp.
5854  *
5855  * IPQoS Notes
5856  * Before sending it to the client, invoke IPPF processing. Policy processing
5857  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5858  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5859  * ip_wput_local, ip_policy is false.
5860  */
5861 static void
5862 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5863     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5864     boolean_t ip_policy)
5865 {
5866 	boolean_t	mctl_present = (first_mp != NULL);
5867 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5868 	uint32_t	ill_index;
5869 
5870 	if (mctl_present)
5871 		first_mp->b_cont = mp;
5872 	else
5873 		first_mp = mp;
5874 
5875 	if (CONN_UDP_FLOWCTLD(connp)) {
5876 		BUMP_MIB(&ip_mib, udpInOverflows);
5877 		freemsg(first_mp);
5878 		return;
5879 	}
5880 
5881 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5882 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5883 		    NULL, mctl_present);
5884 		if (first_mp == NULL)
5885 			return;	/* Freed by ipsec_check_inbound_policy(). */
5886 	}
5887 	if (mctl_present)
5888 		freeb(first_mp);
5889 
5890 	if (connp->conn_recvif)
5891 		in_flags = IPF_RECVIF;
5892 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5893 		in_flags |= IPF_RECVSLLA;
5894 
5895 	/* Handle IPv6 options. */
5896 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5897 		in_flags |= IPF_RECVIF;
5898 
5899 	/*
5900 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5901 	 * freed if the packet is dropped. The caller will do so.
5902 	 */
5903 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5904 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5905 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5906 		if (mp == NULL) {
5907 			return;
5908 		}
5909 	}
5910 	if ((in_flags != 0) &&
5911 	    (mp->b_datap->db_type != M_CTL)) {
5912 		/*
5913 		 * The actual data will be contained in b_cont
5914 		 * upon successful return of the following call
5915 		 * else original mblk is returned
5916 		 */
5917 		ASSERT(recv_ill != NULL);
5918 		mp = ip_add_info(mp, recv_ill, in_flags);
5919 	}
5920 	BUMP_MIB(&ip_mib, ipInDelivers);
5921 
5922 	/* Send it upstream */
5923 	CONN_UDP_RECV(connp, mp);
5924 }
5925 
5926 /*
5927  * Fanout for UDP packets.
5928  * The caller puts <fport, lport> in the ports parameter.
5929  *
5930  * If SO_REUSEADDR is set all multicast and broadcast packets
5931  * will be delivered to all streams bound to the same port.
5932  *
5933  * Zones notes:
5934  * Multicast and broadcast packets will be distributed to streams in all zones.
5935  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5936  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5937  * packets. To maintain this behavior with multiple zones, the conns are grouped
5938  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5939  * each zone. If unset, all the following conns in the same zone are skipped.
5940  */
5941 static void
5942 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5943     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5944     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5945 {
5946 	uint32_t	dstport, srcport;
5947 	ipaddr_t	dst;
5948 	mblk_t		*first_mp;
5949 	boolean_t	secure;
5950 	in6_addr_t	v6src;
5951 	conn_t		*connp;
5952 	connf_t		*connfp;
5953 	conn_t		*first_connp;
5954 	conn_t		*next_connp;
5955 	mblk_t		*mp1, *first_mp1;
5956 	ipaddr_t	src;
5957 	zoneid_t	last_zoneid;
5958 	boolean_t	reuseaddr;
5959 
5960 	first_mp = mp;
5961 	if (mctl_present) {
5962 		mp = first_mp->b_cont;
5963 		first_mp->b_cont = NULL;
5964 		secure = ipsec_in_is_secure(first_mp);
5965 		ASSERT(mp != NULL);
5966 	} else {
5967 		first_mp = NULL;
5968 		secure = B_FALSE;
5969 	}
5970 
5971 	/* Extract ports in net byte order */
5972 	dstport = htons(ntohl(ports) & 0xFFFF);
5973 	srcport = htons(ntohl(ports) >> 16);
5974 	dst = ipha->ipha_dst;
5975 	src = ipha->ipha_src;
5976 
5977 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5978 	mutex_enter(&connfp->connf_lock);
5979 	connp = connfp->connf_head;
5980 	if (!broadcast && !CLASSD(dst)) {
5981 		/*
5982 		 * Not broadcast or multicast. Send to the one (first)
5983 		 * client we find. No need to check conn_wantpacket()
5984 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5985 		 * IPv4 unicast packets.
5986 		 */
5987 		while ((connp != NULL) &&
5988 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5989 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5990 			connp = connp->conn_next;
5991 		}
5992 
5993 		if (connp == NULL || connp->conn_upq == NULL)
5994 			goto notfound;
5995 		CONN_INC_REF(connp);
5996 		mutex_exit(&connfp->connf_lock);
5997 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5998 		    recv_ill, ip_policy);
5999 		IP_STAT(ip_udp_fannorm);
6000 		CONN_DEC_REF(connp);
6001 		return;
6002 	}
6003 
6004 	/*
6005 	 * Broadcast and multicast case
6006 	 *
6007 	 * Need to check conn_wantpacket().
6008 	 * If SO_REUSEADDR has been set on the first we send the
6009 	 * packet to all clients that have joined the group and
6010 	 * match the port.
6011 	 */
6012 
6013 	while (connp != NULL) {
6014 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6015 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6016 			break;
6017 		connp = connp->conn_next;
6018 	}
6019 
6020 	if (connp == NULL || connp->conn_upq == NULL)
6021 		goto notfound;
6022 
6023 	first_connp = connp;
6024 	/*
6025 	 * When SO_REUSEADDR is not set, send the packet only to the first
6026 	 * matching connection in its zone by keeping track of the zoneid.
6027 	 */
6028 	reuseaddr = first_connp->conn_reuseaddr;
6029 	last_zoneid = first_connp->conn_zoneid;
6030 
6031 	CONN_INC_REF(connp);
6032 	connp = connp->conn_next;
6033 	for (;;) {
6034 		while (connp != NULL) {
6035 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6036 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6037 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6038 				break;
6039 			connp = connp->conn_next;
6040 		}
6041 		/*
6042 		 * Just copy the data part alone. The mctl part is
6043 		 * needed just for verifying policy and it is never
6044 		 * sent up.
6045 		 */
6046 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6047 		    ((mp1 = copymsg(mp)) == NULL))) {
6048 			/*
6049 			 * No more interested clients or memory
6050 			 * allocation failed
6051 			 */
6052 			connp = first_connp;
6053 			break;
6054 		}
6055 		if (connp->conn_zoneid != last_zoneid) {
6056 			/*
6057 			 * Update the zoneid so that the packet isn't sent to
6058 			 * any more conns in the same zone unless SO_REUSEADDR
6059 			 * is set.
6060 			 */
6061 			reuseaddr = connp->conn_reuseaddr;
6062 			last_zoneid = connp->conn_zoneid;
6063 		}
6064 		if (first_mp != NULL) {
6065 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6066 			    ipsec_info_type == IPSEC_IN);
6067 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6068 			if (first_mp1 == NULL) {
6069 				freemsg(mp1);
6070 				connp = first_connp;
6071 				break;
6072 			}
6073 		} else {
6074 			first_mp1 = NULL;
6075 		}
6076 		CONN_INC_REF(connp);
6077 		mutex_exit(&connfp->connf_lock);
6078 		/*
6079 		 * IPQoS notes: We don't send the packet for policy
6080 		 * processing here, will do it for the last one (below).
6081 		 * i.e. we do it per-packet now, but if we do policy
6082 		 * processing per-conn, then we would need to do it
6083 		 * here too.
6084 		 */
6085 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6086 		    ipha, flags, recv_ill, B_FALSE);
6087 		mutex_enter(&connfp->connf_lock);
6088 		/* Follow the next pointer before releasing the conn. */
6089 		next_connp = connp->conn_next;
6090 		IP_STAT(ip_udp_fanmb);
6091 		CONN_DEC_REF(connp);
6092 		connp = next_connp;
6093 	}
6094 
6095 	/* Last one.  Send it upstream. */
6096 	mutex_exit(&connfp->connf_lock);
6097 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6098 	    ip_policy);
6099 	IP_STAT(ip_udp_fanmb);
6100 	CONN_DEC_REF(connp);
6101 	return;
6102 
6103 notfound:
6104 
6105 	mutex_exit(&connfp->connf_lock);
6106 	IP_STAT(ip_udp_fanothers);
6107 	/*
6108 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6109 	 * have already been matched above, since they live in the IPv4
6110 	 * fanout tables. This implies we only need to
6111 	 * check for IPv6 in6addr_any endpoints here.
6112 	 * Thus we compare using ipv6_all_zeros instead of the destination
6113 	 * address, except for the multicast group membership lookup which
6114 	 * uses the IPv4 destination.
6115 	 */
6116 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6117 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6118 	mutex_enter(&connfp->connf_lock);
6119 	connp = connfp->connf_head;
6120 	if (!broadcast && !CLASSD(dst)) {
6121 		while (connp != NULL) {
6122 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6123 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6124 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6125 			    !connp->conn_ipv6_v6only)
6126 				break;
6127 			connp = connp->conn_next;
6128 		}
6129 
6130 		if (connp == NULL || connp->conn_upq == NULL) {
6131 			/*
6132 			 * No one bound to this port.  Is
6133 			 * there a client that wants all
6134 			 * unclaimed datagrams?
6135 			 */
6136 			mutex_exit(&connfp->connf_lock);
6137 
6138 			if (mctl_present)
6139 				first_mp->b_cont = mp;
6140 			else
6141 				first_mp = mp;
6142 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6143 				ip_fanout_proto(q, first_mp, ill, ipha,
6144 				    flags | IP_FF_RAWIP, mctl_present,
6145 				    ip_policy, recv_ill, zoneid);
6146 			} else {
6147 				if (ip_fanout_send_icmp(q, first_mp, flags,
6148 				    ICMP_DEST_UNREACHABLE,
6149 				    ICMP_PORT_UNREACHABLE,
6150 				    mctl_present, zoneid)) {
6151 					BUMP_MIB(&ip_mib, udpNoPorts);
6152 				}
6153 			}
6154 			return;
6155 		}
6156 		CONN_INC_REF(connp);
6157 		mutex_exit(&connfp->connf_lock);
6158 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6159 		    recv_ill, ip_policy);
6160 		CONN_DEC_REF(connp);
6161 		return;
6162 	}
6163 	/*
6164 	 * IPv4 multicast packet being delivered to an AF_INET6
6165 	 * in6addr_any endpoint.
6166 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6167 	 * and not conn_wantpacket_v6() since any multicast membership is
6168 	 * for an IPv4-mapped multicast address.
6169 	 * The packet is sent to all clients in all zones that have joined the
6170 	 * group and match the port.
6171 	 */
6172 	while (connp != NULL) {
6173 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6174 		    srcport, v6src) &&
6175 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6176 			break;
6177 		connp = connp->conn_next;
6178 	}
6179 
6180 	if (connp == NULL || connp->conn_upq == NULL) {
6181 		/*
6182 		 * No one bound to this port.  Is
6183 		 * there a client that wants all
6184 		 * unclaimed datagrams?
6185 		 */
6186 		mutex_exit(&connfp->connf_lock);
6187 
6188 		if (mctl_present)
6189 			first_mp->b_cont = mp;
6190 		else
6191 			first_mp = mp;
6192 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6193 			ip_fanout_proto(q, first_mp, ill, ipha,
6194 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6195 			    recv_ill, zoneid);
6196 		} else {
6197 			/*
6198 			 * We used to attempt to send an icmp error here, but
6199 			 * since this is known to be a multicast packet
6200 			 * and we don't send icmp errors in response to
6201 			 * multicast, just drop the packet and give up sooner.
6202 			 */
6203 			BUMP_MIB(&ip_mib, udpNoPorts);
6204 			freemsg(first_mp);
6205 		}
6206 		return;
6207 	}
6208 
6209 	first_connp = connp;
6210 
6211 	CONN_INC_REF(connp);
6212 	connp = connp->conn_next;
6213 	for (;;) {
6214 		while (connp != NULL) {
6215 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6216 			    ipv6_all_zeros, srcport, v6src) &&
6217 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6218 				break;
6219 			connp = connp->conn_next;
6220 		}
6221 		/*
6222 		 * Just copy the data part alone. The mctl part is
6223 		 * needed just for verifying policy and it is never
6224 		 * sent up.
6225 		 */
6226 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6227 		    ((mp1 = copymsg(mp)) == NULL))) {
6228 			/*
6229 			 * No more intested clients or memory
6230 			 * allocation failed
6231 			 */
6232 			connp = first_connp;
6233 			break;
6234 		}
6235 		if (first_mp != NULL) {
6236 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6237 			    ipsec_info_type == IPSEC_IN);
6238 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6239 			if (first_mp1 == NULL) {
6240 				freemsg(mp1);
6241 				connp = first_connp;
6242 				break;
6243 			}
6244 		} else {
6245 			first_mp1 = NULL;
6246 		}
6247 		CONN_INC_REF(connp);
6248 		mutex_exit(&connfp->connf_lock);
6249 		/*
6250 		 * IPQoS notes: We don't send the packet for policy
6251 		 * processing here, will do it for the last one (below).
6252 		 * i.e. we do it per-packet now, but if we do policy
6253 		 * processing per-conn, then we would need to do it
6254 		 * here too.
6255 		 */
6256 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6257 		    ipha, flags, recv_ill, B_FALSE);
6258 		mutex_enter(&connfp->connf_lock);
6259 		/* Follow the next pointer before releasing the conn. */
6260 		next_connp = connp->conn_next;
6261 		CONN_DEC_REF(connp);
6262 		connp = next_connp;
6263 	}
6264 
6265 	/* Last one.  Send it upstream. */
6266 	mutex_exit(&connfp->connf_lock);
6267 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6268 	    ip_policy);
6269 	CONN_DEC_REF(connp);
6270 }
6271 
6272 /*
6273  * Complete the ip_wput header so that it
6274  * is possible to generate ICMP
6275  * errors.
6276  */
6277 static int
6278 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6279 {
6280 	ire_t *ire;
6281 
6282 	if (ipha->ipha_src == INADDR_ANY) {
6283 		ire = ire_lookup_local(zoneid);
6284 		if (ire == NULL) {
6285 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6286 			return (1);
6287 		}
6288 		ipha->ipha_src = ire->ire_addr;
6289 		ire_refrele(ire);
6290 	}
6291 	ipha->ipha_ttl = ip_def_ttl;
6292 	ipha->ipha_hdr_checksum = 0;
6293 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6294 	return (0);
6295 }
6296 
6297 /*
6298  * Nobody should be sending
6299  * packets up this stream
6300  */
6301 static void
6302 ip_lrput(queue_t *q, mblk_t *mp)
6303 {
6304 	mblk_t *mp1;
6305 
6306 	switch (mp->b_datap->db_type) {
6307 	case M_FLUSH:
6308 		/* Turn around */
6309 		if (*mp->b_rptr & FLUSHW) {
6310 			*mp->b_rptr &= ~FLUSHR;
6311 			qreply(q, mp);
6312 			return;
6313 		}
6314 		break;
6315 	}
6316 	/* Could receive messages that passed through ar_rput */
6317 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6318 		mp1->b_prev = mp1->b_next = NULL;
6319 	freemsg(mp);
6320 }
6321 
6322 /* Nobody should be sending packets down this stream */
6323 /* ARGSUSED */
6324 void
6325 ip_lwput(queue_t *q, mblk_t *mp)
6326 {
6327 	freemsg(mp);
6328 }
6329 
6330 /*
6331  * Move the first hop in any source route to ipha_dst and remove that part of
6332  * the source route.  Called by other protocols.  Errors in option formatting
6333  * are ignored - will be handled by ip_wput_options Return the final
6334  * destination (either ipha_dst or the last entry in a source route.)
6335  */
6336 ipaddr_t
6337 ip_massage_options(ipha_t *ipha)
6338 {
6339 	ipoptp_t	opts;
6340 	uchar_t		*opt;
6341 	uint8_t		optval;
6342 	uint8_t		optlen;
6343 	ipaddr_t	dst;
6344 	int		i;
6345 	ire_t		*ire;
6346 
6347 	ip2dbg(("ip_massage_options\n"));
6348 	dst = ipha->ipha_dst;
6349 	for (optval = ipoptp_first(&opts, ipha);
6350 	    optval != IPOPT_EOL;
6351 	    optval = ipoptp_next(&opts)) {
6352 		opt = opts.ipoptp_cur;
6353 		switch (optval) {
6354 			uint8_t off;
6355 		case IPOPT_SSRR:
6356 		case IPOPT_LSRR:
6357 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6358 				ip1dbg(("ip_massage_options: bad src route\n"));
6359 				break;
6360 			}
6361 			optlen = opts.ipoptp_len;
6362 			off = opt[IPOPT_OFFSET];
6363 			off--;
6364 		redo_srr:
6365 			if (optlen < IP_ADDR_LEN ||
6366 			    off > optlen - IP_ADDR_LEN) {
6367 				/* End of source route */
6368 				ip1dbg(("ip_massage_options: end of SR\n"));
6369 				break;
6370 			}
6371 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6372 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6373 			    ntohl(dst)));
6374 			/*
6375 			 * Check if our address is present more than
6376 			 * once as consecutive hops in source route.
6377 			 * XXX verify per-interface ip_forwarding
6378 			 * for source route?
6379 			 */
6380 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6381 			    ALL_ZONES, MATCH_IRE_TYPE);
6382 			if (ire != NULL) {
6383 				ire_refrele(ire);
6384 				off += IP_ADDR_LEN;
6385 				goto redo_srr;
6386 			}
6387 			if (dst == htonl(INADDR_LOOPBACK)) {
6388 				ip1dbg(("ip_massage_options: loopback addr in "
6389 				    "source route!\n"));
6390 				break;
6391 			}
6392 			/*
6393 			 * Update ipha_dst to be the first hop and remove the
6394 			 * first hop from the source route (by overwriting
6395 			 * part of the option with NOP options).
6396 			 */
6397 			ipha->ipha_dst = dst;
6398 			/* Put the last entry in dst */
6399 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6400 			    3;
6401 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6402 
6403 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6404 			    ntohl(dst)));
6405 			/* Move down and overwrite */
6406 			opt[IP_ADDR_LEN] = opt[0];
6407 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6408 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6409 			for (i = 0; i < IP_ADDR_LEN; i++)
6410 				opt[i] = IPOPT_NOP;
6411 			break;
6412 		}
6413 	}
6414 	return (dst);
6415 }
6416 
6417 /*
6418  * This function's job is to forward data to the reverse tunnel (FA->HA)
6419  * after doing a few checks. It is assumed that the incoming interface
6420  * of the packet is always different than the outgoing interface and the
6421  * ire_type of the found ire has to be a non-resolver type.
6422  *
6423  * IPQoS notes
6424  * IP policy is invoked twice for a forwarded packet, once on the read side
6425  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6426  * enabled.
6427  */
6428 static void
6429 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6430 {
6431 	ipha_t		*ipha;
6432 	queue_t		*q;
6433 	uint32_t 	pkt_len;
6434 #define	rptr    ((uchar_t *)ipha)
6435 	uint32_t 	sum;
6436 	uint32_t 	max_frag;
6437 	mblk_t		*first_mp;
6438 	uint32_t	ill_index;
6439 
6440 	ASSERT(ire != NULL);
6441 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6442 	ASSERT(ire->ire_stq != NULL);
6443 
6444 	/* Initiate read side IPPF processing */
6445 	if (IPP_ENABLED(IPP_FWD_IN)) {
6446 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6447 		ip_process(IPP_FWD_IN, &mp, ill_index);
6448 		if (mp == NULL) {
6449 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6450 			    "dropped during IPPF processing\n"));
6451 			return;
6452 		}
6453 	}
6454 
6455 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6456 		ILLF_ROUTER) == 0) ||
6457 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6458 		BUMP_MIB(&ip_mib, ipForwProhibits);
6459 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6460 		    "forwarding is not turned on\n"));
6461 		goto drop_pkt;
6462 	}
6463 
6464 	/*
6465 	 * Don't forward if the interface is down
6466 	 */
6467 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6468 		BUMP_MIB(&ip_mib, ipInDiscards);
6469 		goto drop_pkt;
6470 	}
6471 
6472 	ipha = (ipha_t *)mp->b_rptr;
6473 	pkt_len = ntohs(ipha->ipha_length);
6474 	/* Adjust the checksum to reflect the ttl decrement. */
6475 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6476 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6477 	if (ipha->ipha_ttl-- <= 1) {
6478 		if (ip_csum_hdr(ipha)) {
6479 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6480 			goto drop_pkt;
6481 		}
6482 		q = ire->ire_stq;
6483 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6484 		    BPRI_HI)) == NULL) {
6485 			goto drop_pkt;
6486 		}
6487 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6488 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6489 
6490 		return;
6491 	}
6492 
6493 	/* Get the ill_index of the ILL */
6494 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6495 
6496 	/*
6497 	 * ip_mrtun_forward is only used by foreign agent to reverse
6498 	 * tunnel the incoming packet. So it does not do any option
6499 	 * processing for source routing.
6500 	 */
6501 	max_frag = ire->ire_max_frag;
6502 	if (pkt_len > max_frag) {
6503 		/*
6504 		 * It needs fragging on its way out.  We haven't
6505 		 * verified the header checksum yet.  Since we
6506 		 * are going to put a surely good checksum in the
6507 		 * outgoing header, we have to make sure that it
6508 		 * was good coming in.
6509 		 */
6510 		if (ip_csum_hdr(ipha)) {
6511 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6512 			goto drop_pkt;
6513 		}
6514 
6515 		/* Initiate write side IPPF processing */
6516 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6517 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6518 			if (mp == NULL) {
6519 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6520 				    "dropped/deferred during ip policy "\
6521 				    "processing\n"));
6522 				return;
6523 			}
6524 		}
6525 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6526 		    BPRI_HI)) == NULL) {
6527 			goto drop_pkt;
6528 		}
6529 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6530 		mp = first_mp;
6531 
6532 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6533 		return;
6534 	}
6535 
6536 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6537 
6538 	ASSERT(ire->ire_ipif != NULL);
6539 
6540 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6541 	if (mp == NULL) {
6542 		BUMP_MIB(&ip_mib, ipInDiscards);
6543 		return;
6544 	}
6545 
6546 	/* Now send the packet to the tunnel interface */
6547 	q = ire->ire_stq;
6548 	UPDATE_IB_PKT_COUNT(ire);
6549 	ire->ire_last_used_time = lbolt;
6550 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6551 	putnext(q, mp);
6552 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6553 	return;
6554 
6555 drop_pkt:;
6556 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6557 	freemsg(mp);
6558 #undef	rptr
6559 }
6560 
6561 /*
6562  * Fills the ipsec_out_t data structure with appropriate fields and
6563  * prepends it to mp which contains the IP hdr + data that was meant
6564  * to be forwarded. Please note that ipsec_out_info data structure
6565  * is used here to communicate the outgoing ill path at ip_wput()
6566  * for the ICMP error packet. This has nothing to do with ipsec IP
6567  * security. ipsec_out_t is really used to pass the info to the module
6568  * IP where this information cannot be extracted from conn.
6569  * This functions is called by ip_mrtun_forward().
6570  */
6571 void
6572 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6573 {
6574 	ipsec_out_t	*io;
6575 
6576 	ASSERT(xmit_ill != NULL);
6577 	first_mp->b_datap->db_type = M_CTL;
6578 	first_mp->b_wptr += sizeof (ipsec_info_t);
6579 	/*
6580 	 * This is to pass info to ip_wput in absence of conn.
6581 	 * ipsec_out_secure will be B_FALSE because of this.
6582 	 * Thus ipsec_out_secure being B_FALSE indicates that
6583 	 * this is not IPSEC security related information.
6584 	 */
6585 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6586 	io = (ipsec_out_t *)first_mp->b_rptr;
6587 	io->ipsec_out_type = IPSEC_OUT;
6588 	io->ipsec_out_len = sizeof (ipsec_out_t);
6589 	first_mp->b_cont = mp;
6590 	io->ipsec_out_ill_index =
6591 	    xmit_ill->ill_phyint->phyint_ifindex;
6592 	io->ipsec_out_xmit_if = B_TRUE;
6593 }
6594 
6595 /*
6596  * Return the network mask
6597  * associated with the specified address.
6598  */
6599 ipaddr_t
6600 ip_net_mask(ipaddr_t addr)
6601 {
6602 	uchar_t	*up = (uchar_t *)&addr;
6603 	ipaddr_t mask = 0;
6604 	uchar_t	*maskp = (uchar_t *)&mask;
6605 
6606 #if defined(__i386) || defined(__amd64)
6607 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6608 #endif
6609 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6610 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6611 #endif
6612 	if (CLASSD(addr)) {
6613 		maskp[0] = 0xF0;
6614 		return (mask);
6615 	}
6616 	if (addr == 0)
6617 		return (0);
6618 	maskp[0] = 0xFF;
6619 	if ((up[0] & 0x80) == 0)
6620 		return (mask);
6621 
6622 	maskp[1] = 0xFF;
6623 	if ((up[0] & 0xC0) == 0x80)
6624 		return (mask);
6625 
6626 	maskp[2] = 0xFF;
6627 	if ((up[0] & 0xE0) == 0xC0)
6628 		return (mask);
6629 
6630 	/* Must be experimental or multicast, indicate as much */
6631 	return ((ipaddr_t)0);
6632 }
6633 
6634 /*
6635  * Select an ill for the packet by considering load spreading across
6636  * a different ill in the group if dst_ill is part of some group.
6637  */
6638 static ill_t *
6639 ip_newroute_get_dst_ill(ill_t *dst_ill)
6640 {
6641 	ill_t *ill;
6642 
6643 	/*
6644 	 * We schedule irrespective of whether the source address is
6645 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6646 	 */
6647 	ill = illgrp_scheduler(dst_ill);
6648 	if (ill == NULL)
6649 		return (NULL);
6650 
6651 	/*
6652 	 * For groups with names ip_sioctl_groupname ensures that all
6653 	 * ills are of same type. For groups without names, ifgrp_insert
6654 	 * ensures this.
6655 	 */
6656 	ASSERT(dst_ill->ill_type == ill->ill_type);
6657 
6658 	return (ill);
6659 }
6660 
6661 /*
6662  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6663  */
6664 ill_t *
6665 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6666 {
6667 	ill_t *ret_ill;
6668 
6669 	ASSERT(ifindex != 0);
6670 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6671 	if (ret_ill == NULL ||
6672 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6673 		if (isv6) {
6674 			if (ill != NULL) {
6675 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6676 			} else {
6677 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6678 			}
6679 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6680 			    "bad ifindex %d.\n", ifindex));
6681 		} else {
6682 			BUMP_MIB(&ip_mib, ipOutDiscards);
6683 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6684 			    "bad ifindex %d.\n", ifindex));
6685 		}
6686 		if (ret_ill != NULL)
6687 			ill_refrele(ret_ill);
6688 		freemsg(first_mp);
6689 		return (NULL);
6690 	}
6691 
6692 	return (ret_ill);
6693 }
6694 
6695 /*
6696  * IPv4 -
6697  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6698  * out a packet to a destination address for which we do not have specific
6699  * (or sufficient) routing information.
6700  *
6701  * NOTE : These are the scopes of some of the variables that point at IRE,
6702  *	  which needs to be followed while making any future modifications
6703  *	  to avoid memory leaks.
6704  *
6705  *	- ire and sire are the entries looked up initially by
6706  *	  ire_ftable_lookup.
6707  *	- ipif_ire is used to hold the interface ire associated with
6708  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6709  *	  it before branching out to error paths.
6710  *	- save_ire is initialized before ire_create, so that ire returned
6711  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6712  *	  before breaking out of the switch.
6713  *
6714  *	Thus on failures, we have to REFRELE only ire and sire, if they
6715  *	are not NULL.
6716  */
6717 void
6718 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6719 {
6720 	areq_t	*areq;
6721 	ipaddr_t gw = 0;
6722 	ire_t	*ire = NULL;
6723 	mblk_t	*res_mp;
6724 	ipaddr_t *addrp;
6725 	ipaddr_t nexthop_addr;
6726 	ipif_t  *src_ipif = NULL;
6727 	ill_t	*dst_ill = NULL;
6728 	ipha_t  *ipha;
6729 	ire_t	*sire = NULL;
6730 	mblk_t	*first_mp;
6731 	ire_t	*save_ire;
6732 	mblk_t	*dlureq_mp;
6733 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6734 	ushort_t ire_marks = 0;
6735 	boolean_t mctl_present;
6736 	ipsec_out_t *io;
6737 	mblk_t	*saved_mp;
6738 	ire_t	*first_sire = NULL;
6739 	mblk_t	*copy_mp = NULL;
6740 	mblk_t	*xmit_mp = NULL;
6741 	ipaddr_t save_dst;
6742 	uint32_t multirt_flags =
6743 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6744 	boolean_t multirt_is_resolvable;
6745 	boolean_t multirt_resolve_next;
6746 	boolean_t do_attach_ill = B_FALSE;
6747 	boolean_t ip_nexthop = B_FALSE;
6748 	zoneid_t zoneid;
6749 
6750 	if (ip_debug > 2) {
6751 		/* ip1dbg */
6752 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6753 	}
6754 
6755 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6756 	if (mctl_present) {
6757 		io = (ipsec_out_t *)first_mp->b_rptr;
6758 		zoneid = io->ipsec_out_zoneid;
6759 		ASSERT(zoneid != ALL_ZONES);
6760 	} else if (connp != NULL) {
6761 		zoneid = connp->conn_zoneid;
6762 	} else {
6763 		zoneid = GLOBAL_ZONEID;
6764 	}
6765 
6766 	ipha = (ipha_t *)mp->b_rptr;
6767 
6768 	/* All multicast lookups come through ip_newroute_ipif() */
6769 	if (CLASSD(dst)) {
6770 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6771 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6772 		freemsg(first_mp);
6773 		return;
6774 	}
6775 
6776 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6777 		goto icmp_err_ret;
6778 	}
6779 
6780 	if (mctl_present && io->ipsec_out_attach_if) {
6781 		/* ip_grab_attach_ill returns a held ill */
6782 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6783 		    io->ipsec_out_ill_index, B_FALSE);
6784 
6785 		/* Failure case frees things for us. */
6786 		if (attach_ill == NULL)
6787 			return;
6788 
6789 		/*
6790 		 * Check if we need an ire that will not be
6791 		 * looked up by anybody else i.e. HIDDEN.
6792 		 */
6793 		if (ill_is_probeonly(attach_ill))
6794 			ire_marks = IRE_MARK_HIDDEN;
6795 	}
6796 	if (mctl_present && io->ipsec_out_ip_nexthop) {
6797 		ip_nexthop = B_TRUE;
6798 		nexthop_addr = io->ipsec_out_nexthop_addr;
6799 	}
6800 	/*
6801 	 * If this IRE is created for forwarding or it is not for
6802 	 * traffic for congestion controlled protocols, mark it as temporary.
6803 	 */
6804 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6805 		ire_marks |= IRE_MARK_TEMPORARY;
6806 
6807 	/*
6808 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6809 	 * chain until it gets the most specific information available.
6810 	 * For example, we know that there is no IRE_CACHE for this dest,
6811 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6812 	 * ire_ftable_lookup will look up the gateway, etc.
6813 	 * Check if in_ill != NULL. If it is true, the packet must be
6814 	 * from an incoming interface where RTA_SRCIFP is set.
6815 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6816 	 * to the destination, of equal netmask length in the forward table,
6817 	 * will be recursively explored. If no information is available
6818 	 * for the final gateway of that route, we force the returned ire
6819 	 * to be equal to sire using MATCH_IRE_PARENT.
6820 	 * At least, in this case we have a starting point (in the buckets)
6821 	 * to look for other routes to the destination in the forward table.
6822 	 * This is actually used only for multirouting, where a list
6823 	 * of routes has to be processed in sequence.
6824 	 */
6825 	if (in_ill != NULL) {
6826 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6827 		    in_ill, MATCH_IRE_TYPE);
6828 	} else if (ip_nexthop) {
6829 		/*
6830 		 * The first time we come here, we look for an IRE_INTERFACE
6831 		 * entry for the specified nexthop, set the dst to be the
6832 		 * nexthop address and create an IRE_CACHE entry for the
6833 		 * nexthop. The next time around, we are able to find an
6834 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
6835 		 * nexthop address and create an IRE_CACHE entry for the
6836 		 * destination address via the specified nexthop.
6837 		 */
6838 		ire = ire_cache_lookup(nexthop_addr, zoneid);
6839 		if (ire != NULL) {
6840 			gw = nexthop_addr;
6841 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
6842 		} else {
6843 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
6844 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
6845 			    MATCH_IRE_TYPE);
6846 			if (ire != NULL) {
6847 				dst = nexthop_addr;
6848 			}
6849 		}
6850 	} else if (attach_ill == NULL) {
6851 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6852 		    NULL, &sire, zoneid, 0,
6853 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6854 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6855 	} else {
6856 		/*
6857 		 * attach_ill is set only for communicating with
6858 		 * on-link hosts. So, don't look for DEFAULT.
6859 		 */
6860 		ipif_t	*attach_ipif;
6861 
6862 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6863 		if (attach_ipif == NULL) {
6864 			ill_refrele(attach_ill);
6865 			goto icmp_err_ret;
6866 		}
6867 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6868 		    &sire, zoneid, 0,
6869 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6870 		ipif_refrele(attach_ipif);
6871 	}
6872 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6873 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6874 
6875 	/*
6876 	 * This loop is run only once in most cases.
6877 	 * We loop to resolve further routes only when the destination
6878 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6879 	 */
6880 	do {
6881 		/* Clear the previous iteration's values */
6882 		if (src_ipif != NULL) {
6883 			ipif_refrele(src_ipif);
6884 			src_ipif = NULL;
6885 		}
6886 		if (dst_ill != NULL) {
6887 			ill_refrele(dst_ill);
6888 			dst_ill = NULL;
6889 		}
6890 
6891 		multirt_resolve_next = B_FALSE;
6892 		/*
6893 		 * We check if packets have to be multirouted.
6894 		 * In this case, given the current <ire, sire> couple,
6895 		 * we look for the next suitable <ire, sire>.
6896 		 * This check is done in ire_multirt_lookup(),
6897 		 * which applies various criteria to find the next route
6898 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6899 		 * unchanged if it detects it has not been tried yet.
6900 		 */
6901 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6902 			ip3dbg(("ip_newroute: starting next_resolution "
6903 			    "with first_mp %p, tag %d\n",
6904 			    (void *)first_mp,
6905 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6906 
6907 			ASSERT(sire != NULL);
6908 			multirt_is_resolvable =
6909 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6910 
6911 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6912 			    "ire %p, sire %p\n",
6913 			    multirt_is_resolvable,
6914 			    (void *)ire, (void *)sire));
6915 
6916 			if (!multirt_is_resolvable) {
6917 				/*
6918 				 * No more multirt route to resolve; give up
6919 				 * (all routes resolved or no more
6920 				 * resolvable routes).
6921 				 */
6922 				if (ire != NULL) {
6923 					ire_refrele(ire);
6924 					ire = NULL;
6925 				}
6926 			} else {
6927 				ASSERT(sire != NULL);
6928 				ASSERT(ire != NULL);
6929 				/*
6930 				 * We simply use first_sire as a flag that
6931 				 * indicates if a resolvable multirt route
6932 				 * has already been found.
6933 				 * If it is not the case, we may have to send
6934 				 * an ICMP error to report that the
6935 				 * destination is unreachable.
6936 				 * We do not IRE_REFHOLD first_sire.
6937 				 */
6938 				if (first_sire == NULL) {
6939 					first_sire = sire;
6940 				}
6941 			}
6942 		}
6943 		if (ire == NULL) {
6944 			if (ip_debug > 3) {
6945 				/* ip2dbg */
6946 				pr_addr_dbg("ip_newroute: "
6947 				    "can't resolve %s\n", AF_INET, &dst);
6948 			}
6949 			ip3dbg(("ip_newroute: "
6950 			    "ire %p, sire %p, first_sire %p\n",
6951 			    (void *)ire, (void *)sire, (void *)first_sire));
6952 
6953 			if (sire != NULL) {
6954 				ire_refrele(sire);
6955 				sire = NULL;
6956 			}
6957 
6958 			if (first_sire != NULL) {
6959 				/*
6960 				 * At least one multirt route has been found
6961 				 * in the same call to ip_newroute();
6962 				 * there is no need to report an ICMP error.
6963 				 * first_sire was not IRE_REFHOLDed.
6964 				 */
6965 				MULTIRT_DEBUG_UNTAG(first_mp);
6966 				freemsg(first_mp);
6967 				return;
6968 			}
6969 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6970 			    RTA_DST);
6971 			if (attach_ill != NULL)
6972 				ill_refrele(attach_ill);
6973 			goto icmp_err_ret;
6974 		}
6975 
6976 		/*
6977 		 * When RTA_SRCIFP is used to add a route, then an interface
6978 		 * route is added in the source interface's routing table.
6979 		 * If the outgoing interface of this route is of type
6980 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6981 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6982 		 * first used for forwarding packet, ip_newroute() is called
6983 		 * to resolve the hardware address of the outgoing ipif.
6984 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6985 		 * source interface based table. We only come here if the
6986 		 * outgoing interface is a resolver interface and we don't
6987 		 * have the ire_dlureq_mp information yet.
6988 		 * If in_ill is not null that means it is called from
6989 		 * ip_rput.
6990 		 */
6991 
6992 		ASSERT(ire->ire_in_ill == NULL ||
6993 		    (ire->ire_type == IRE_IF_RESOLVER &&
6994 		    ire->ire_dlureq_mp == NULL));
6995 
6996 		/*
6997 		 * Verify that the returned IRE does not have either
6998 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6999 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7000 		 */
7001 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7002 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7003 			if (attach_ill != NULL)
7004 				ill_refrele(attach_ill);
7005 			goto icmp_err_ret;
7006 		}
7007 		/*
7008 		 * Increment the ire_ob_pkt_count field for ire if it is an
7009 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7010 		 * increment the same for the parent IRE, sire, if it is some
7011 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7012 		 * and HOST_REDIRECT).
7013 		 */
7014 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7015 			UPDATE_OB_PKT_COUNT(ire);
7016 			ire->ire_last_used_time = lbolt;
7017 		}
7018 
7019 		if (sire != NULL) {
7020 			gw = sire->ire_gateway_addr;
7021 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7022 			    IRE_INTERFACE)) == 0);
7023 			UPDATE_OB_PKT_COUNT(sire);
7024 			sire->ire_last_used_time = lbolt;
7025 		}
7026 		/*
7027 		 * We have a route to reach the destination.
7028 		 *
7029 		 * 1) If the interface is part of ill group, try to get a new
7030 		 *    ill taking load spreading into account.
7031 		 *
7032 		 * 2) After selecting the ill, get a source address that
7033 		 *    might create good inbound load spreading.
7034 		 *    ipif_select_source does this for us.
7035 		 *
7036 		 * If the application specified the ill (ifindex), we still
7037 		 * load spread. Only if the packets needs to go out
7038 		 * specifically on a given ill e.g. binding to
7039 		 * IPIF_NOFAILOVER address, then we don't try to use a
7040 		 * different ill for load spreading.
7041 		 */
7042 		if (attach_ill == NULL) {
7043 			/*
7044 			 * Don't perform outbound load spreading in the
7045 			 * case of an RTF_MULTIRT route, as we actually
7046 			 * typically want to replicate outgoing packets
7047 			 * through particular interfaces.
7048 			 */
7049 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7050 				dst_ill = ire->ire_ipif->ipif_ill;
7051 				/* for uniformity */
7052 				ill_refhold(dst_ill);
7053 			} else {
7054 				/*
7055 				 * If we are here trying to create an IRE_CACHE
7056 				 * for an offlink destination and have the
7057 				 * IRE_CACHE for the next hop and the latter is
7058 				 * using virtual IP source address selection i.e
7059 				 * it's ire->ire_ipif is pointing to a virtual
7060 				 * network interface (vni) then
7061 				 * ip_newroute_get_dst_ll() will return the vni
7062 				 * interface as the dst_ill. Since the vni is
7063 				 * virtual i.e not associated with any physical
7064 				 * interface, it cannot be the dst_ill, hence
7065 				 * in such a case call ip_newroute_get_dst_ll()
7066 				 * with the stq_ill instead of the ire_ipif ILL.
7067 				 * The function returns a refheld ill.
7068 				 */
7069 				if ((ire->ire_type == IRE_CACHE) &&
7070 				    IS_VNI(ire->ire_ipif->ipif_ill))
7071 					dst_ill = ip_newroute_get_dst_ill(
7072 						ire->ire_stq->q_ptr);
7073 				else
7074 					dst_ill = ip_newroute_get_dst_ill(
7075 						ire->ire_ipif->ipif_ill);
7076 			}
7077 			if (dst_ill == NULL) {
7078 				if (ip_debug > 2) {
7079 					pr_addr_dbg("ip_newroute: "
7080 					    "no dst ill for dst"
7081 					    " %s\n", AF_INET, &dst);
7082 				}
7083 				goto icmp_err_ret;
7084 			}
7085 		} else {
7086 			dst_ill = ire->ire_ipif->ipif_ill;
7087 			/* for uniformity */
7088 			ill_refhold(dst_ill);
7089 			/*
7090 			 * We should have found a route matching ill as we
7091 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7092 			 * Rather than asserting, when there is a mismatch,
7093 			 * we just drop the packet.
7094 			 */
7095 			if (dst_ill != attach_ill) {
7096 				ip0dbg(("ip_newroute: Packet dropped as "
7097 				    "IPIF_NOFAILOVER ill is %s, "
7098 				    "ire->ire_ipif->ipif_ill is %s\n",
7099 				    attach_ill->ill_name,
7100 				    dst_ill->ill_name));
7101 				ill_refrele(attach_ill);
7102 				goto icmp_err_ret;
7103 			}
7104 		}
7105 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7106 		if (attach_ill != NULL) {
7107 			ill_refrele(attach_ill);
7108 			attach_ill = NULL;
7109 			do_attach_ill = B_TRUE;
7110 		}
7111 		ASSERT(dst_ill != NULL);
7112 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7113 
7114 		/*
7115 		 * Pick the best source address from dst_ill.
7116 		 *
7117 		 * 1) If it is part of a multipathing group, we would
7118 		 *    like to spread the inbound packets across different
7119 		 *    interfaces. ipif_select_source picks a random source
7120 		 *    across the different ills in the group.
7121 		 *
7122 		 * 2) If it is not part of a multipathing group, we try
7123 		 *    to pick the source address from the destination
7124 		 *    route. Clustering assumes that when we have multiple
7125 		 *    prefixes hosted on an interface, the prefix of the
7126 		 *    source address matches the prefix of the destination
7127 		 *    route. We do this only if the address is not
7128 		 *    DEPRECATED.
7129 		 *
7130 		 * 3) If the conn is in a different zone than the ire, we
7131 		 *    need to pick a source address from the right zone.
7132 		 *
7133 		 * NOTE : If we hit case (1) above, the prefix of the source
7134 		 *	  address picked may not match the prefix of the
7135 		 *	  destination routes prefix as ipif_select_source
7136 		 *	  does not look at "dst" while picking a source
7137 		 *	  address.
7138 		 *	  If we want the same behavior as (2), we will need
7139 		 *	  to change the behavior of ipif_select_source.
7140 		 */
7141 		ASSERT(src_ipif == NULL);
7142 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7143 			/*
7144 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7145 			 * Check that the ipif matching the requested source
7146 			 * address still exists.
7147 			 */
7148 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7149 			    zoneid, NULL, NULL, NULL, NULL);
7150 		}
7151 		if (src_ipif == NULL) {
7152 			ire_marks |= IRE_MARK_USESRC_CHECK;
7153 			if ((dst_ill->ill_group != NULL) ||
7154 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7155 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
7156 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7157 				/*
7158 				 * If the destination is reachable via a
7159 				 * given gateway, the selected source address
7160 				 * should be in the same subnet as the gateway.
7161 				 * Otherwise, the destination is not reachable.
7162 				 *
7163 				 * If there are no interfaces on the same subnet
7164 				 * as the destination, ipif_select_source gives
7165 				 * first non-deprecated interface which might be
7166 				 * on a different subnet than the gateway.
7167 				 * This is not desirable. Hence pass the dst_ire
7168 				 * source address to ipif_select_source.
7169 				 * It is sure that the destination is reachable
7170 				 * with the dst_ire source address subnet.
7171 				 * So passing dst_ire source address to
7172 				 * ipif_select_source will make sure that the
7173 				 * selected source will be on the same subnet
7174 				 * as dst_ire source address.
7175 				 */
7176 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7177 				src_ipif = ipif_select_source(dst_ill, saddr,
7178 				    zoneid);
7179 				if (src_ipif == NULL) {
7180 					if (ip_debug > 2) {
7181 						pr_addr_dbg("ip_newroute: "
7182 						    "no src for dst %s ",
7183 						    AF_INET, &dst);
7184 						printf("through interface %s\n",
7185 						    dst_ill->ill_name);
7186 					}
7187 					goto icmp_err_ret;
7188 				}
7189 			} else {
7190 				src_ipif = ire->ire_ipif;
7191 				ASSERT(src_ipif != NULL);
7192 				/* hold src_ipif for uniformity */
7193 				ipif_refhold(src_ipif);
7194 			}
7195 		}
7196 
7197 		/*
7198 		 * Assign a source address while we have the conn.
7199 		 * We can't have ip_wput_ire pick a source address when the
7200 		 * packet returns from arp since we need to look at
7201 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7202 		 * going through arp.
7203 		 *
7204 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7205 		 *	  it uses ip6i to store this information.
7206 		 */
7207 		if (ipha->ipha_src == INADDR_ANY &&
7208 		    (connp == NULL || !connp->conn_unspec_src)) {
7209 			ipha->ipha_src = src_ipif->ipif_src_addr;
7210 		}
7211 		if (ip_debug > 3) {
7212 			/* ip2dbg */
7213 			pr_addr_dbg("ip_newroute: first hop %s\n",
7214 			    AF_INET, &gw);
7215 		}
7216 		ip2dbg(("\tire type %s (%d)\n",
7217 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7218 
7219 		/*
7220 		 * The TTL of multirouted packets is bounded by the
7221 		 * ip_multirt_ttl ndd variable.
7222 		 */
7223 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7224 			/* Force TTL of multirouted packets */
7225 			if ((ip_multirt_ttl > 0) &&
7226 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7227 				ip2dbg(("ip_newroute: forcing multirt TTL "
7228 				    "to %d (was %d), dst 0x%08x\n",
7229 				    ip_multirt_ttl, ipha->ipha_ttl,
7230 				    ntohl(sire->ire_addr)));
7231 				ipha->ipha_ttl = ip_multirt_ttl;
7232 			}
7233 		}
7234 		/*
7235 		 * At this point in ip_newroute(), ire is either the
7236 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7237 		 * destination or an IRE_INTERFACE type that should be used
7238 		 * to resolve an on-subnet destination or an on-subnet
7239 		 * next-hop gateway.
7240 		 *
7241 		 * In the IRE_CACHE case, we have the following :
7242 		 *
7243 		 * 1) src_ipif - used for getting a source address.
7244 		 *
7245 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7246 		 *    means packets using this IRE_CACHE will go out on
7247 		 *    dst_ill.
7248 		 *
7249 		 * 3) The IRE sire will point to the prefix that is the
7250 		 *    longest  matching route for the destination. These
7251 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7252 		 *    and IRE_HOST_REDIRECT.
7253 		 *
7254 		 *    The newly created IRE_CACHE entry for the off-subnet
7255 		 *    destination is tied to both the prefix route and the
7256 		 *    interface route used to resolve the next-hop gateway
7257 		 *    via the ire_phandle and ire_ihandle fields,
7258 		 *    respectively.
7259 		 *
7260 		 * In the IRE_INTERFACE case, we have the following :
7261 		 *
7262 		 * 1) src_ipif - used for getting a source address.
7263 		 *
7264 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7265 		 *    means packets using the IRE_CACHE that we will build
7266 		 *    here will go out on dst_ill.
7267 		 *
7268 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7269 		 *    to be created will only be tied to the IRE_INTERFACE
7270 		 *    that was derived from the ire_ihandle field.
7271 		 *
7272 		 *    If sire is non-NULL, it means the destination is
7273 		 *    off-link and we will first create the IRE_CACHE for the
7274 		 *    gateway. Next time through ip_newroute, we will create
7275 		 *    the IRE_CACHE for the final destination as described
7276 		 *    above.
7277 		 *
7278 		 * In both cases, after the current resolution has been
7279 		 * completed (or possibly initialised, in the IRE_INTERFACE
7280 		 * case), the loop may be re-entered to attempt the resolution
7281 		 * of another RTF_MULTIRT route.
7282 		 *
7283 		 * When an IRE_CACHE entry for the off-subnet destination is
7284 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7285 		 * for further processing in emission loops.
7286 		 */
7287 		save_ire = ire;
7288 		switch (ire->ire_type) {
7289 		case IRE_CACHE: {
7290 			ire_t	*ipif_ire;
7291 			mblk_t	*ire_fp_mp;
7292 
7293 			if (gw == 0)
7294 				gw = ire->ire_gateway_addr;
7295 			/*
7296 			 * We need 3 ire's to create a new cache ire for an
7297 			 * off-link destination from the cache ire of the
7298 			 * gateway.
7299 			 *
7300 			 *	1. The prefix ire 'sire' (Note that this does
7301 			 *	   not apply to the conn_nexthop_set case)
7302 			 *	2. The cache ire of the gateway 'ire'
7303 			 *	3. The interface ire 'ipif_ire'
7304 			 *
7305 			 * We have (1) and (2). We lookup (3) below.
7306 			 *
7307 			 * If there is no interface route to the gateway,
7308 			 * it is a race condition, where we found the cache
7309 			 * but the interface route has been deleted.
7310 			 */
7311 			if (ip_nexthop) {
7312 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7313 			} else {
7314 				ipif_ire =
7315 				    ire_ihandle_lookup_offlink(ire, sire);
7316 			}
7317 			if (ipif_ire == NULL) {
7318 				ip1dbg(("ip_newroute: "
7319 				    "ire_ihandle_lookup_offlink failed\n"));
7320 				goto icmp_err_ret;
7321 			}
7322 			/*
7323 			 * XXX We are using the same dlureq_mp
7324 			 * (DL_UNITDATA_REQ) though the save_ire is not
7325 			 * pointing at the same ill.
7326 			 * This is incorrect. We need to send it up to the
7327 			 * resolver to get the right dlureq_mp. For ethernets
7328 			 * this may be okay (ill_type == DL_ETHER).
7329 			 */
7330 			dlureq_mp = save_ire->ire_dlureq_mp;
7331 			ire_fp_mp = NULL;
7332 			/*
7333 			 * save_ire's ire_fp_mp can't change since it is
7334 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7335 			 * LOCK_IRE_FP_MP does not do any useful work in
7336 			 * the case of IRE_CACHE. So we don't use it below.
7337 			 */
7338 			if (save_ire->ire_stq == dst_ill->ill_wq)
7339 				ire_fp_mp = save_ire->ire_fp_mp;
7340 
7341 			ire = ire_create(
7342 			    (uchar_t *)&dst,		/* dest address */
7343 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7344 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7345 			    (uchar_t *)&gw,		/* gateway address */
7346 			    NULL,
7347 			    &save_ire->ire_max_frag,
7348 			    ire_fp_mp,			/* Fast Path header */
7349 			    dst_ill->ill_rq,		/* recv-from queue */
7350 			    dst_ill->ill_wq,		/* send-to queue */
7351 			    IRE_CACHE,			/* IRE type */
7352 			    save_ire->ire_dlureq_mp,
7353 			    src_ipif,
7354 			    in_ill,			/* incoming ill */
7355 			    (sire != NULL) ?
7356 				sire->ire_mask : 0, 	/* Parent mask */
7357 			    (sire != NULL) ?
7358 				sire->ire_phandle : 0,  /* Parent handle */
7359 			    ipif_ire->ire_ihandle,	/* Interface handle */
7360 			    (sire != NULL) ? (sire->ire_flags &
7361 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7362 			    (sire != NULL) ?
7363 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo));
7364 
7365 			if (ire == NULL) {
7366 				ire_refrele(ipif_ire);
7367 				ire_refrele(save_ire);
7368 				break;
7369 			}
7370 			ire->ire_marks |= ire_marks;
7371 
7372 			/*
7373 			 * Prevent sire and ipif_ire from getting deleted.
7374 			 * The newly created ire is tied to both of them via
7375 			 * the phandle and ihandle respectively.
7376 			 */
7377 			if (sire != NULL) {
7378 				IRB_REFHOLD(sire->ire_bucket);
7379 				/* Has it been removed already ? */
7380 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7381 					IRB_REFRELE(sire->ire_bucket);
7382 					ire_refrele(ipif_ire);
7383 					ire_refrele(save_ire);
7384 					break;
7385 				}
7386 			}
7387 
7388 			IRB_REFHOLD(ipif_ire->ire_bucket);
7389 			/* Has it been removed already ? */
7390 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7391 				IRB_REFRELE(ipif_ire->ire_bucket);
7392 				if (sire != NULL)
7393 					IRB_REFRELE(sire->ire_bucket);
7394 				ire_refrele(ipif_ire);
7395 				ire_refrele(save_ire);
7396 				break;
7397 			}
7398 
7399 			xmit_mp = first_mp;
7400 			/*
7401 			 * In the case of multirouting, a copy
7402 			 * of the packet is done before its sending.
7403 			 * The copy is used to attempt another
7404 			 * route resolution, in a next loop.
7405 			 */
7406 			if (ire->ire_flags & RTF_MULTIRT) {
7407 				copy_mp = copymsg(first_mp);
7408 				if (copy_mp != NULL) {
7409 					xmit_mp = copy_mp;
7410 					MULTIRT_DEBUG_TAG(first_mp);
7411 				}
7412 			}
7413 			ire_add_then_send(q, ire, xmit_mp);
7414 			ire_refrele(save_ire);
7415 
7416 			/* Assert that sire is not deleted yet. */
7417 			if (sire != NULL) {
7418 				ASSERT(sire->ire_ptpn != NULL);
7419 				IRB_REFRELE(sire->ire_bucket);
7420 			}
7421 
7422 			/* Assert that ipif_ire is not deleted yet. */
7423 			ASSERT(ipif_ire->ire_ptpn != NULL);
7424 			IRB_REFRELE(ipif_ire->ire_bucket);
7425 			ire_refrele(ipif_ire);
7426 
7427 			/*
7428 			 * If copy_mp is not NULL, multirouting was
7429 			 * requested. We loop to initiate a next
7430 			 * route resolution attempt, starting from sire.
7431 			 */
7432 			if (copy_mp != NULL) {
7433 				/*
7434 				 * Search for the next unresolved
7435 				 * multirt route.
7436 				 */
7437 				copy_mp = NULL;
7438 				ipif_ire = NULL;
7439 				ire = NULL;
7440 				multirt_resolve_next = B_TRUE;
7441 				continue;
7442 			}
7443 			if (sire != NULL)
7444 				ire_refrele(sire);
7445 			ipif_refrele(src_ipif);
7446 			ill_refrele(dst_ill);
7447 			return;
7448 		}
7449 		case IRE_IF_NORESOLVER: {
7450 			/*
7451 			 * We have what we need to build an IRE_CACHE.
7452 			 *
7453 			 * Create a new dlureq_mp with the IP gateway address
7454 			 * in destination address in the DLPI hdr if the
7455 			 * physical length is exactly 4 bytes.
7456 			 */
7457 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7458 				uchar_t *addr;
7459 
7460 				if (gw)
7461 					addr = (uchar_t *)&gw;
7462 				else
7463 					addr = (uchar_t *)&dst;
7464 
7465 				dlureq_mp = ill_dlur_gen(addr,
7466 				    dst_ill->ill_phys_addr_length,
7467 				    dst_ill->ill_sap,
7468 				    dst_ill->ill_sap_length);
7469 			} else {
7470 				dlureq_mp = ire->ire_dlureq_mp;
7471 			}
7472 
7473 			if (dlureq_mp == NULL) {
7474 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7475 				break;
7476 			}
7477 
7478 			ire = ire_create(
7479 			    (uchar_t *)&dst,		/* dest address */
7480 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7481 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7482 			    (uchar_t *)&gw,		/* gateway address */
7483 			    NULL,
7484 			    &save_ire->ire_max_frag,
7485 			    NULL,			/* Fast Path header */
7486 			    dst_ill->ill_rq,		/* recv-from queue */
7487 			    dst_ill->ill_wq,		/* send-to queue */
7488 			    IRE_CACHE,
7489 			    dlureq_mp,
7490 			    src_ipif,
7491 			    in_ill,			/* Incoming ill */
7492 			    save_ire->ire_mask,		/* Parent mask */
7493 			    (sire != NULL) ?		/* Parent handle */
7494 				sire->ire_phandle : 0,
7495 			    save_ire->ire_ihandle,	/* Interface handle */
7496 			    (sire != NULL) ? sire->ire_flags &
7497 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7498 			    &(save_ire->ire_uinfo));
7499 
7500 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7501 				freeb(dlureq_mp);
7502 
7503 			if (ire == NULL) {
7504 				ire_refrele(save_ire);
7505 				break;
7506 			}
7507 
7508 			ire->ire_marks |= ire_marks;
7509 
7510 			/* Prevent save_ire from getting deleted */
7511 			IRB_REFHOLD(save_ire->ire_bucket);
7512 			/* Has it been removed already ? */
7513 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7514 				IRB_REFRELE(save_ire->ire_bucket);
7515 				ire_refrele(save_ire);
7516 				break;
7517 			}
7518 
7519 			/*
7520 			 * In the case of multirouting, a copy
7521 			 * of the packet is made before it is sent.
7522 			 * The copy is used in the next
7523 			 * loop to attempt another resolution.
7524 			 */
7525 			xmit_mp = first_mp;
7526 			if ((sire != NULL) &&
7527 			    (sire->ire_flags & RTF_MULTIRT)) {
7528 				copy_mp = copymsg(first_mp);
7529 				if (copy_mp != NULL) {
7530 					xmit_mp = copy_mp;
7531 					MULTIRT_DEBUG_TAG(first_mp);
7532 				}
7533 			}
7534 			ire_add_then_send(q, ire, xmit_mp);
7535 
7536 			/* Assert that it is not deleted yet. */
7537 			ASSERT(save_ire->ire_ptpn != NULL);
7538 			IRB_REFRELE(save_ire->ire_bucket);
7539 			ire_refrele(save_ire);
7540 
7541 			if (copy_mp != NULL) {
7542 				/*
7543 				 * If we found a (no)resolver, we ignore any
7544 				 * trailing top priority IRE_CACHE in further
7545 				 * loops. This ensures that we do not omit any
7546 				 * (no)resolver.
7547 				 * This IRE_CACHE, if any, will be processed
7548 				 * by another thread entering ip_newroute().
7549 				 * IRE_CACHE entries, if any, will be processed
7550 				 * by another thread entering ip_newroute(),
7551 				 * (upon resolver response, for instance).
7552 				 * This aims to force parallel multirt
7553 				 * resolutions as soon as a packet must be sent.
7554 				 * In the best case, after the tx of only one
7555 				 * packet, all reachable routes are resolved.
7556 				 * Otherwise, the resolution of all RTF_MULTIRT
7557 				 * routes would require several emissions.
7558 				 */
7559 				multirt_flags &= ~MULTIRT_CACHEGW;
7560 
7561 				/*
7562 				 * Search for the next unresolved multirt
7563 				 * route.
7564 				 */
7565 				copy_mp = NULL;
7566 				save_ire = NULL;
7567 				ire = NULL;
7568 				multirt_resolve_next = B_TRUE;
7569 				continue;
7570 			}
7571 
7572 			/*
7573 			 * Don't need sire anymore
7574 			 */
7575 			if (sire != NULL)
7576 				ire_refrele(sire);
7577 
7578 			ipif_refrele(src_ipif);
7579 			ill_refrele(dst_ill);
7580 			return;
7581 		}
7582 		case IRE_IF_RESOLVER:
7583 			/*
7584 			 * We can't build an IRE_CACHE yet, but at least we
7585 			 * found a resolver that can help.
7586 			 */
7587 			res_mp = dst_ill->ill_resolver_mp;
7588 			if (!OK_RESOLVER_MP(res_mp))
7589 				break;
7590 			/*
7591 			 * To be at this point in the code with a non-zero gw
7592 			 * means that dst is reachable through a gateway that
7593 			 * we have never resolved.  By changing dst to the gw
7594 			 * addr we resolve the gateway first.
7595 			 * When ire_add_then_send() tries to put the IP dg
7596 			 * to dst, it will reenter ip_newroute() at which
7597 			 * time we will find the IRE_CACHE for the gw and
7598 			 * create another IRE_CACHE in case IRE_CACHE above.
7599 			 */
7600 			if (gw != INADDR_ANY) {
7601 				/*
7602 				 * The source ipif that was determined above was
7603 				 * relative to the destination address, not the
7604 				 * gateway's. If src_ipif was not taken out of
7605 				 * the IRE_IF_RESOLVER entry, we'll need to call
7606 				 * ipif_select_source() again.
7607 				 */
7608 				if (src_ipif != ire->ire_ipif) {
7609 					ipif_refrele(src_ipif);
7610 					src_ipif = ipif_select_source(dst_ill,
7611 					    gw, zoneid);
7612 					if (src_ipif == NULL) {
7613 						if (ip_debug > 2) {
7614 							pr_addr_dbg(
7615 							    "ip_newroute: no "
7616 							    "src for gw %s ",
7617 							    AF_INET, &gw);
7618 							printf("through "
7619 							    "interface %s\n",
7620 							    dst_ill->ill_name);
7621 						}
7622 						goto icmp_err_ret;
7623 					}
7624 				}
7625 				save_dst = dst;
7626 				dst = gw;
7627 				gw = INADDR_ANY;
7628 			}
7629 			/*
7630 			 * We obtain a partial IRE_CACHE which we will pass
7631 			 * along with the resolver query.  When the response
7632 			 * comes back it will be there ready for us to add.
7633 			 * The ire_max_frag is atomically set under the
7634 			 * irebucket lock in ire_add_v[46].
7635 			 */
7636 			ire = ire_create_mp(
7637 			    (uchar_t *)&dst,		/* dest address */
7638 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7639 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7640 			    (uchar_t *)&gw,		/* gateway address */
7641 			    NULL,			/* no in_src_addr */
7642 			    NULL,			/* ire_max_frag */
7643 			    NULL,			/* Fast Path header */
7644 			    dst_ill->ill_rq,		/* recv-from queue */
7645 			    dst_ill->ill_wq,		/* send-to queue */
7646 			    IRE_CACHE,
7647 			    res_mp,
7648 			    src_ipif,			/* Interface ipif */
7649 			    in_ill,			/* Incoming ILL */
7650 			    save_ire->ire_mask,		/* Parent mask */
7651 			    0,
7652 			    save_ire->ire_ihandle,	/* Interface handle */
7653 			    0,				/* flags if any */
7654 			    &(save_ire->ire_uinfo));
7655 
7656 			if (ire == NULL) {
7657 				ire_refrele(save_ire);
7658 				break;
7659 			}
7660 
7661 			if ((sire != NULL) &&
7662 			    (sire->ire_flags & RTF_MULTIRT)) {
7663 				copy_mp = copymsg(first_mp);
7664 				if (copy_mp != NULL)
7665 					MULTIRT_DEBUG_TAG(copy_mp);
7666 			}
7667 
7668 			ire->ire_marks |= ire_marks;
7669 
7670 			/*
7671 			 * Construct message chain for the resolver
7672 			 * of the form:
7673 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7674 			 * Packet could contain a IPSEC_OUT mp.
7675 			 *
7676 			 * NOTE : ire will be added later when the response
7677 			 * comes back from ARP. If the response does not
7678 			 * come back, ARP frees the packet. For this reason,
7679 			 * we can't REFHOLD the bucket of save_ire to prevent
7680 			 * deletions. We may not be able to REFRELE the bucket
7681 			 * if the response never comes back. Thus, before
7682 			 * adding the ire, ire_add_v4 will make sure that the
7683 			 * interface route does not get deleted. This is the
7684 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7685 			 * where we can always prevent deletions because of
7686 			 * the synchronous nature of adding IRES i.e
7687 			 * ire_add_then_send is called after creating the IRE.
7688 			 */
7689 			ASSERT(ire->ire_mp != NULL);
7690 			ire->ire_mp->b_cont = first_mp;
7691 			/* Have saved_mp handy, for cleanup if canput fails */
7692 			saved_mp = mp;
7693 			mp = ire->ire_dlureq_mp;
7694 			ASSERT(mp != NULL);
7695 			ire->ire_dlureq_mp = NULL;
7696 			linkb(mp, ire->ire_mp);
7697 
7698 
7699 			/*
7700 			 * Fill in the source and dest addrs for the resolver.
7701 			 * NOTE: this depends on memory layouts imposed by
7702 			 * ill_init().
7703 			 */
7704 			areq = (areq_t *)mp->b_rptr;
7705 			addrp = (ipaddr_t *)((char *)areq +
7706 			    areq->areq_sender_addr_offset);
7707 			if (do_attach_ill) {
7708 				/*
7709 				 * This is bind to no failover case.
7710 				 * arp packet also must go out on attach_ill.
7711 				 */
7712 				ASSERT(ipha->ipha_src != NULL);
7713 				*addrp = ipha->ipha_src;
7714 			} else {
7715 				*addrp = save_ire->ire_src_addr;
7716 			}
7717 
7718 			ire_refrele(save_ire);
7719 			addrp = (ipaddr_t *)((char *)areq +
7720 			    areq->areq_target_addr_offset);
7721 			*addrp = dst;
7722 			/* Up to the resolver. */
7723 			if (canputnext(dst_ill->ill_rq)) {
7724 				putnext(dst_ill->ill_rq, mp);
7725 				ire = NULL;
7726 				if (copy_mp != NULL) {
7727 					/*
7728 					 * If we found a resolver, we ignore
7729 					 * any trailing top priority IRE_CACHE
7730 					 * in the further loops. This ensures
7731 					 * that we do not omit any resolver.
7732 					 * IRE_CACHE entries, if any, will be
7733 					 * processed next time we enter
7734 					 * ip_newroute().
7735 					 */
7736 					multirt_flags &= ~MULTIRT_CACHEGW;
7737 					/*
7738 					 * Search for the next unresolved
7739 					 * multirt route.
7740 					 */
7741 					first_mp = copy_mp;
7742 					copy_mp = NULL;
7743 					/* Prepare the next resolution loop. */
7744 					mp = first_mp;
7745 					EXTRACT_PKT_MP(mp, first_mp,
7746 					    mctl_present);
7747 					if (mctl_present)
7748 						io = (ipsec_out_t *)
7749 						    first_mp->b_rptr;
7750 					ipha = (ipha_t *)mp->b_rptr;
7751 
7752 					ASSERT(sire != NULL);
7753 
7754 					dst = save_dst;
7755 					multirt_resolve_next = B_TRUE;
7756 					continue;
7757 				}
7758 
7759 				if (sire != NULL)
7760 					ire_refrele(sire);
7761 
7762 				/*
7763 				 * The response will come back in ip_wput
7764 				 * with db_type IRE_DB_TYPE.
7765 				 */
7766 				ipif_refrele(src_ipif);
7767 				ill_refrele(dst_ill);
7768 				return;
7769 			} else {
7770 				/* Prepare for cleanup */
7771 				ire->ire_dlureq_mp = mp;
7772 				mp->b_cont = NULL;
7773 				ire_delete(ire);
7774 				mp = saved_mp;
7775 				ire = NULL;
7776 				if (copy_mp != NULL) {
7777 					MULTIRT_DEBUG_UNTAG(copy_mp);
7778 					freemsg(copy_mp);
7779 					copy_mp = NULL;
7780 				}
7781 				break;
7782 			}
7783 		default:
7784 			break;
7785 		}
7786 	} while (multirt_resolve_next);
7787 
7788 	ip1dbg(("ip_newroute: dropped\n"));
7789 	/* Did this packet originate externally? */
7790 	if (mp->b_prev) {
7791 		mp->b_next = NULL;
7792 		mp->b_prev = NULL;
7793 		BUMP_MIB(&ip_mib, ipInDiscards);
7794 	} else {
7795 		BUMP_MIB(&ip_mib, ipOutDiscards);
7796 	}
7797 	ASSERT(copy_mp == NULL);
7798 	MULTIRT_DEBUG_UNTAG(first_mp);
7799 	freemsg(first_mp);
7800 	if (ire != NULL)
7801 		ire_refrele(ire);
7802 	if (sire != NULL)
7803 		ire_refrele(sire);
7804 	if (src_ipif != NULL)
7805 		ipif_refrele(src_ipif);
7806 	if (dst_ill != NULL)
7807 		ill_refrele(dst_ill);
7808 	return;
7809 
7810 icmp_err_ret:
7811 	ip1dbg(("ip_newroute: no route\n"));
7812 	if (src_ipif != NULL)
7813 		ipif_refrele(src_ipif);
7814 	if (dst_ill != NULL)
7815 		ill_refrele(dst_ill);
7816 	if (sire != NULL)
7817 		ire_refrele(sire);
7818 	/* Did this packet originate externally? */
7819 	if (mp->b_prev) {
7820 		mp->b_next = NULL;
7821 		mp->b_prev = NULL;
7822 		/* XXX ipInNoRoutes */
7823 		q = WR(q);
7824 	} else {
7825 		/*
7826 		 * Since ip_wput() isn't close to finished, we fill
7827 		 * in enough of the header for credible error reporting.
7828 		 */
7829 		if (ip_hdr_complete(ipha, zoneid)) {
7830 			/* Failed */
7831 			MULTIRT_DEBUG_UNTAG(first_mp);
7832 			freemsg(first_mp);
7833 			if (ire != NULL)
7834 				ire_refrele(ire);
7835 			return;
7836 		}
7837 	}
7838 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7839 
7840 	/*
7841 	 * At this point we will have ire only if RTF_BLACKHOLE
7842 	 * or RTF_REJECT flags are set on the IRE. It will not
7843 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7844 	 */
7845 	if (ire != NULL) {
7846 		if (ire->ire_flags & RTF_BLACKHOLE) {
7847 			ire_refrele(ire);
7848 			MULTIRT_DEBUG_UNTAG(first_mp);
7849 			freemsg(first_mp);
7850 			return;
7851 		}
7852 		ire_refrele(ire);
7853 	}
7854 	if (ip_source_routed(ipha)) {
7855 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7856 		return;
7857 	}
7858 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7859 }
7860 
7861 /*
7862  * IPv4 -
7863  * ip_newroute_ipif is called by ip_wput_multicast and
7864  * ip_rput_forward_multicast whenever we need to send
7865  * out a packet to a destination address for which we do not have specific
7866  * routing information. It is used when the packet will be sent out
7867  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7868  * socket option is set or icmp error message wants to go out on a particular
7869  * interface for a unicast packet.
7870  *
7871  * In most cases, the destination address is resolved thanks to the ipif
7872  * intrinsic resolver. However, there are some cases where the call to
7873  * ip_newroute_ipif must take into account the potential presence of
7874  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7875  * that uses the interface. This is specified through flags,
7876  * which can be a combination of:
7877  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7878  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7879  *   and flags. Additionally, the packet source address has to be set to
7880  *   the specified address. The caller is thus expected to set this flag
7881  *   if the packet has no specific source address yet.
7882  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7883  *   flag, the resulting ire will inherit the flag. All unresolved routes
7884  *   to the destination must be explored in the same call to
7885  *   ip_newroute_ipif().
7886  */
7887 static void
7888 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7889     conn_t *connp, uint32_t flags)
7890 {
7891 	areq_t	*areq;
7892 	ire_t	*ire = NULL;
7893 	mblk_t	*res_mp;
7894 	ipaddr_t *addrp;
7895 	mblk_t *first_mp;
7896 	ire_t	*save_ire = NULL;
7897 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7898 	ipif_t	*src_ipif = NULL;
7899 	ushort_t ire_marks = 0;
7900 	ill_t	*dst_ill = NULL;
7901 	boolean_t mctl_present;
7902 	ipsec_out_t *io;
7903 	ipha_t *ipha;
7904 	int	ihandle = 0;
7905 	mblk_t	*saved_mp;
7906 	ire_t   *fire = NULL;
7907 	mblk_t  *copy_mp = NULL;
7908 	boolean_t multirt_resolve_next;
7909 	ipaddr_t ipha_dst;
7910 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7911 
7912 	/*
7913 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7914 	 * here for uniformity
7915 	 */
7916 	ipif_refhold(ipif);
7917 
7918 	/*
7919 	 * This loop is run only once in most cases.
7920 	 * We loop to resolve further routes only when the destination
7921 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7922 	 */
7923 	do {
7924 		if (dst_ill != NULL) {
7925 			ill_refrele(dst_ill);
7926 			dst_ill = NULL;
7927 		}
7928 		if (src_ipif != NULL) {
7929 			ipif_refrele(src_ipif);
7930 			src_ipif = NULL;
7931 		}
7932 		multirt_resolve_next = B_FALSE;
7933 
7934 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7935 		    ipif->ipif_ill->ill_name));
7936 
7937 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7938 		if (mctl_present)
7939 			io = (ipsec_out_t *)first_mp->b_rptr;
7940 
7941 		ipha = (ipha_t *)mp->b_rptr;
7942 
7943 		/*
7944 		 * Save the packet destination address, we may need it after
7945 		 * the packet has been consumed.
7946 		 */
7947 		ipha_dst = ipha->ipha_dst;
7948 
7949 		/*
7950 		 * If the interface is a pt-pt interface we look for an
7951 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7952 		 * local_address and the pt-pt destination address. Otherwise
7953 		 * we just match the local address.
7954 		 * NOTE: dst could be different than ipha->ipha_dst in case
7955 		 * of sending igmp multicast packets over a point-to-point
7956 		 * connection.
7957 		 * Thus we must be careful enough to check ipha_dst to be a
7958 		 * multicast address, otherwise it will take xmit_if path for
7959 		 * multicast packets resulting into kernel stack overflow by
7960 		 * repeated calls to ip_newroute_ipif from ire_send().
7961 		 */
7962 		if (CLASSD(ipha_dst) &&
7963 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7964 			goto err_ret;
7965 		}
7966 
7967 		/*
7968 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7969 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7970 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7971 		 * propagate its flags to the new ire.
7972 		 */
7973 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7974 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7975 			ip2dbg(("ip_newroute_ipif: "
7976 			    "ipif_lookup_multi_ire("
7977 			    "ipif %p, dst %08x) = fire %p\n",
7978 			    (void *)ipif, ntohl(dst), (void *)fire));
7979 		}
7980 
7981 		if (mctl_present && io->ipsec_out_attach_if) {
7982 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7983 			    io->ipsec_out_ill_index, B_FALSE);
7984 
7985 			/* Failure case frees things for us. */
7986 			if (attach_ill == NULL) {
7987 				ipif_refrele(ipif);
7988 				if (fire != NULL)
7989 					ire_refrele(fire);
7990 				return;
7991 			}
7992 
7993 			/*
7994 			 * Check if we need an ire that will not be
7995 			 * looked up by anybody else i.e. HIDDEN.
7996 			 */
7997 			if (ill_is_probeonly(attach_ill)) {
7998 				ire_marks = IRE_MARK_HIDDEN;
7999 			}
8000 			/*
8001 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8002 			 * case.
8003 			 */
8004 			dst_ill = ipif->ipif_ill;
8005 			/* attach_ill has been refheld by ip_grab_attach_ill */
8006 			ASSERT(dst_ill == attach_ill);
8007 		} else {
8008 			/*
8009 			 * If this is set by IP_XMIT_IF, then make sure that
8010 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8011 			 * specified ill.
8012 			 */
8013 			ASSERT((connp == NULL) ||
8014 			    (connp->conn_xmit_if_ill == NULL) ||
8015 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8016 			/*
8017 			 * If the interface belongs to an interface group,
8018 			 * make sure the next possible interface in the group
8019 			 * is used.  This encourages load spreading among
8020 			 * peers in an interface group.
8021 			 * Note: load spreading is disabled for RTF_MULTIRT
8022 			 * routes.
8023 			 */
8024 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8025 			    (fire->ire_flags & RTF_MULTIRT)) {
8026 				/*
8027 				 * Don't perform outbound load spreading
8028 				 * in the case of an RTF_MULTIRT issued route,
8029 				 * we actually typically want to replicate
8030 				 * outgoing packets through particular
8031 				 * interfaces.
8032 				 */
8033 				dst_ill = ipif->ipif_ill;
8034 				ill_refhold(dst_ill);
8035 			} else {
8036 				dst_ill = ip_newroute_get_dst_ill(
8037 				    ipif->ipif_ill);
8038 			}
8039 			if (dst_ill == NULL) {
8040 				if (ip_debug > 2) {
8041 					pr_addr_dbg("ip_newroute_ipif: "
8042 					    "no dst ill for dst %s\n",
8043 					    AF_INET, &dst);
8044 				}
8045 				goto err_ret;
8046 			}
8047 		}
8048 
8049 		/*
8050 		 * Pick a source address preferring non-deprecated ones.
8051 		 * Unlike ip_newroute, we don't do any source address
8052 		 * selection here since for multicast it really does not help
8053 		 * in inbound load spreading as in the unicast case.
8054 		 */
8055 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8056 		    (fire->ire_flags & RTF_SETSRC)) {
8057 			/*
8058 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8059 			 * on that interface. This ire has RTF_SETSRC flag, so
8060 			 * the source address of the packet must be changed.
8061 			 * Check that the ipif matching the requested source
8062 			 * address still exists.
8063 			 */
8064 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8065 			    zoneid, NULL, NULL, NULL, NULL);
8066 		}
8067 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8068 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
8069 		    (src_ipif == NULL)) {
8070 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8071 			if (src_ipif == NULL) {
8072 				if (ip_debug > 2) {
8073 					/* ip1dbg */
8074 					pr_addr_dbg("ip_newroute_ipif: "
8075 					    "no src for dst %s",
8076 					    AF_INET, &dst);
8077 				}
8078 				ip1dbg((" through interface %s\n",
8079 				    dst_ill->ill_name));
8080 				goto err_ret;
8081 			}
8082 			ipif_refrele(ipif);
8083 			ipif = src_ipif;
8084 			ipif_refhold(ipif);
8085 		}
8086 		if (src_ipif == NULL) {
8087 			src_ipif = ipif;
8088 			ipif_refhold(src_ipif);
8089 		}
8090 
8091 		/*
8092 		 * Assign a source address while we have the conn.
8093 		 * We can't have ip_wput_ire pick a source address when the
8094 		 * packet returns from arp since conn_unspec_src might be set
8095 		 * and we loose the conn when going through arp.
8096 		 */
8097 		if (ipha->ipha_src == INADDR_ANY &&
8098 		    (connp == NULL || !connp->conn_unspec_src)) {
8099 			ipha->ipha_src = src_ipif->ipif_src_addr;
8100 		}
8101 
8102 		/*
8103 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8104 		 * interface does not have an interface ire.
8105 		 * Example: Thousands of mobileip PPP interfaces to mobile
8106 		 * nodes. We don't want to create interface ires because
8107 		 * packets from other mobile nodes must not take the route
8108 		 * via interface ires to the visiting mobile node without
8109 		 * going through the home agent, in absence of mobileip
8110 		 * route optimization.
8111 		 */
8112 		if (CLASSD(ipha_dst) && (connp == NULL ||
8113 		    connp->conn_xmit_if_ill == NULL)) {
8114 			/* ipif_to_ire returns an held ire */
8115 			ire = ipif_to_ire(ipif);
8116 			if (ire == NULL)
8117 				goto err_ret;
8118 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8119 				goto err_ret;
8120 			/*
8121 			 * ihandle is needed when the ire is added to
8122 			 * cache table.
8123 			 */
8124 			save_ire = ire;
8125 			ihandle = save_ire->ire_ihandle;
8126 
8127 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8128 			    "flags %04x\n",
8129 			    (void *)ire, (void *)ipif, flags));
8130 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8131 			    (fire->ire_flags & RTF_MULTIRT)) {
8132 				/*
8133 				 * As requested by flags, an IRE_OFFSUBNET was
8134 				 * looked up on that interface. This ire has
8135 				 * RTF_MULTIRT flag, so the resolution loop will
8136 				 * be re-entered to resolve additional routes on
8137 				 * other interfaces. For that purpose, a copy of
8138 				 * the packet is performed at this point.
8139 				 */
8140 				fire->ire_last_used_time = lbolt;
8141 				copy_mp = copymsg(first_mp);
8142 				if (copy_mp) {
8143 					MULTIRT_DEBUG_TAG(copy_mp);
8144 				}
8145 			}
8146 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8147 			    (fire->ire_flags & RTF_SETSRC)) {
8148 				/*
8149 				 * As requested by flags, an IRE_OFFSUBET was
8150 				 * looked up on that interface. This ire has
8151 				 * RTF_SETSRC flag, so the source address of the
8152 				 * packet must be changed.
8153 				 */
8154 				ipha->ipha_src = fire->ire_src_addr;
8155 			}
8156 		} else {
8157 			ASSERT((connp == NULL) ||
8158 			    (connp->conn_xmit_if_ill != NULL) ||
8159 			    (connp->conn_dontroute));
8160 			/*
8161 			 * The only ways we can come here are:
8162 			 * 1) IP_XMIT_IF socket option is set
8163 			 * 2) ICMP error message generated from
8164 			 *    ip_mrtun_forward() routine and it needs
8165 			 *    to go through the specified ill.
8166 			 * 3) SO_DONTROUTE socket option is set
8167 			 * In all cases, the new ire will not be added
8168 			 * into cache table.
8169 			 */
8170 			ire_marks |= IRE_MARK_NOADD;
8171 		}
8172 
8173 		switch (ipif->ipif_net_type) {
8174 		case IRE_IF_NORESOLVER: {
8175 			/* We have what we need to build an IRE_CACHE. */
8176 			mblk_t	*dlureq_mp;
8177 
8178 			/*
8179 			 * Create a new dlureq_mp with the
8180 			 * IP gateway address as destination address in the
8181 			 * DLPI hdr if the physical length is exactly 4 bytes.
8182 			 */
8183 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8184 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8185 				    dst_ill->ill_phys_addr_length,
8186 				    dst_ill->ill_sap,
8187 				    dst_ill->ill_sap_length);
8188 			} else {
8189 				/* use the value set in ip_ll_subnet_defaults */
8190 				dlureq_mp = ill_dlur_gen(NULL,
8191 				    dst_ill->ill_phys_addr_length,
8192 				    dst_ill->ill_sap,
8193 				    dst_ill->ill_sap_length);
8194 			}
8195 
8196 			if (dlureq_mp == NULL)
8197 				break;
8198 			/*
8199 			 * The new ire inherits the IRE_OFFSUBNET flags
8200 			 * and source address, if this was requested.
8201 			 */
8202 			ire = ire_create(
8203 			    (uchar_t *)&dst,		/* dest address */
8204 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8205 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8206 			    NULL,			/* gateway address */
8207 			    NULL,
8208 			    &ipif->ipif_mtu,
8209 			    NULL,			/* Fast Path header */
8210 			    dst_ill->ill_rq,		/* recv-from queue */
8211 			    dst_ill->ill_wq,		/* send-to queue */
8212 			    IRE_CACHE,
8213 			    dlureq_mp,
8214 			    src_ipif,
8215 			    NULL,
8216 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8217 			    (fire != NULL) ?		/* Parent handle */
8218 				fire->ire_phandle : 0,
8219 			    ihandle,			/* Interface handle */
8220 			    (fire != NULL) ?
8221 				(fire->ire_flags &
8222 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8223 			    (save_ire == NULL ? &ire_uinfo_null :
8224 				&save_ire->ire_uinfo));
8225 
8226 			freeb(dlureq_mp);
8227 
8228 			if (ire == NULL) {
8229 				if (save_ire != NULL)
8230 					ire_refrele(save_ire);
8231 				break;
8232 			}
8233 
8234 			ire->ire_marks |= ire_marks;
8235 
8236 			/*
8237 			 * If IRE_MARK_NOADD is set then we need to convert
8238 			 * the max_fragp to a useable value now. This is
8239 			 * normally done in ire_add_v[46].
8240 			 */
8241 			if (ire->ire_marks & IRE_MARK_NOADD) {
8242 				uint_t  max_frag;
8243 
8244 				max_frag = *ire->ire_max_fragp;
8245 				ire->ire_max_fragp = NULL;
8246 				ire->ire_max_frag = max_frag;
8247 			}
8248 
8249 			/* Prevent save_ire from getting deleted */
8250 			if (save_ire != NULL) {
8251 				IRB_REFHOLD(save_ire->ire_bucket);
8252 				/* Has it been removed already ? */
8253 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8254 					IRB_REFRELE(save_ire->ire_bucket);
8255 					ire_refrele(save_ire);
8256 					break;
8257 				}
8258 			}
8259 
8260 			ire_add_then_send(q, ire, first_mp);
8261 
8262 			/* Assert that save_ire is not deleted yet. */
8263 			if (save_ire != NULL) {
8264 				ASSERT(save_ire->ire_ptpn != NULL);
8265 				IRB_REFRELE(save_ire->ire_bucket);
8266 				ire_refrele(save_ire);
8267 				save_ire = NULL;
8268 			}
8269 			if (fire != NULL) {
8270 				ire_refrele(fire);
8271 				fire = NULL;
8272 			}
8273 
8274 			/*
8275 			 * the resolution loop is re-entered if this
8276 			 * was requested through flags and if we
8277 			 * actually are in a multirouting case.
8278 			 */
8279 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8280 				boolean_t need_resolve =
8281 				    ire_multirt_need_resolve(ipha_dst);
8282 				if (!need_resolve) {
8283 					MULTIRT_DEBUG_UNTAG(copy_mp);
8284 					freemsg(copy_mp);
8285 					copy_mp = NULL;
8286 				} else {
8287 					/*
8288 					 * ipif_lookup_group() calls
8289 					 * ire_lookup_multi() that uses
8290 					 * ire_ftable_lookup() to find
8291 					 * an IRE_INTERFACE for the group.
8292 					 * In the multirt case,
8293 					 * ire_lookup_multi() then invokes
8294 					 * ire_multirt_lookup() to find
8295 					 * the next resolvable ire.
8296 					 * As a result, we obtain an new
8297 					 * interface, derived from the
8298 					 * next ire.
8299 					 */
8300 					ipif_refrele(ipif);
8301 					ipif = ipif_lookup_group(ipha_dst,
8302 					    zoneid);
8303 					ip2dbg(("ip_newroute_ipif: "
8304 					    "multirt dst %08x, ipif %p\n",
8305 					    htonl(dst), (void *)ipif));
8306 					if (ipif != NULL) {
8307 						mp = copy_mp;
8308 						copy_mp = NULL;
8309 						multirt_resolve_next = B_TRUE;
8310 						continue;
8311 					} else {
8312 						freemsg(copy_mp);
8313 					}
8314 				}
8315 			}
8316 			if (ipif != NULL)
8317 				ipif_refrele(ipif);
8318 			ill_refrele(dst_ill);
8319 			ipif_refrele(src_ipif);
8320 			return;
8321 		}
8322 		case IRE_IF_RESOLVER:
8323 			/*
8324 			 * We can't build an IRE_CACHE yet, but at least
8325 			 * we found a resolver that can help.
8326 			 */
8327 			res_mp = dst_ill->ill_resolver_mp;
8328 			if (!OK_RESOLVER_MP(res_mp))
8329 				break;
8330 
8331 			/*
8332 			 * We obtain a partial IRE_CACHE which we will pass
8333 			 * along with the resolver query.  When the response
8334 			 * comes back it will be there ready for us to add.
8335 			 * The new ire inherits the IRE_OFFSUBNET flags
8336 			 * and source address, if this was requested.
8337 			 * The ire_max_frag is atomically set under the
8338 			 * irebucket lock in ire_add_v[46]. Only in the
8339 			 * case of IRE_MARK_NOADD, we set it here itself.
8340 			 */
8341 			ire = ire_create_mp(
8342 			    (uchar_t *)&dst,		/* dest address */
8343 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8344 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8345 			    NULL,			/* gateway address */
8346 			    NULL,			/* no in_src_addr */
8347 			    (ire_marks & IRE_MARK_NOADD) ?
8348 				ipif->ipif_mtu : 0,	/* max_frag */
8349 			    NULL,			/* Fast path header */
8350 			    dst_ill->ill_rq,		/* recv-from queue */
8351 			    dst_ill->ill_wq,		/* send-to queue */
8352 			    IRE_CACHE,
8353 			    res_mp,
8354 			    src_ipif,
8355 			    NULL,
8356 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8357 			    (fire != NULL) ?		/* Parent handle */
8358 				fire->ire_phandle : 0,
8359 			    ihandle,			/* Interface handle */
8360 			    (fire != NULL) ?		/* flags if any */
8361 				(fire->ire_flags &
8362 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8363 			    (save_ire == NULL ? &ire_uinfo_null :
8364 				&save_ire->ire_uinfo));
8365 
8366 			if (save_ire != NULL) {
8367 				ire_refrele(save_ire);
8368 				save_ire = NULL;
8369 			}
8370 			if (ire == NULL)
8371 				break;
8372 
8373 			ire->ire_marks |= ire_marks;
8374 			/*
8375 			 * Construct message chain for the resolver of the
8376 			 * form:
8377 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8378 			 *
8379 			 * NOTE : ire will be added later when the response
8380 			 * comes back from ARP. If the response does not
8381 			 * come back, ARP frees the packet. For this reason,
8382 			 * we can't REFHOLD the bucket of save_ire to prevent
8383 			 * deletions. We may not be able to REFRELE the
8384 			 * bucket if the response never comes back.
8385 			 * Thus, before adding the ire, ire_add_v4 will make
8386 			 * sure that the interface route does not get deleted.
8387 			 * This is the only case unlike ip_newroute_v6,
8388 			 * ip_newroute_ipif_v6 where we can always prevent
8389 			 * deletions because ire_add_then_send is called after
8390 			 * creating the IRE.
8391 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8392 			 * does not add this IRE into the IRE CACHE.
8393 			 */
8394 			ASSERT(ire->ire_mp != NULL);
8395 			ire->ire_mp->b_cont = first_mp;
8396 			/* Have saved_mp handy, for cleanup if canput fails */
8397 			saved_mp = mp;
8398 			mp = ire->ire_dlureq_mp;
8399 			ASSERT(mp != NULL);
8400 			ire->ire_dlureq_mp = NULL;
8401 			linkb(mp, ire->ire_mp);
8402 
8403 			/*
8404 			 * Fill in the source and dest addrs for the resolver.
8405 			 * NOTE: this depends on memory layouts imposed by
8406 			 * ill_init().
8407 			 */
8408 			areq = (areq_t *)mp->b_rptr;
8409 			addrp = (ipaddr_t *)((char *)areq +
8410 			    areq->areq_sender_addr_offset);
8411 			*addrp = ire->ire_src_addr;
8412 			addrp = (ipaddr_t *)((char *)areq +
8413 			    areq->areq_target_addr_offset);
8414 			*addrp = dst;
8415 			/* Up to the resolver. */
8416 			if (canputnext(dst_ill->ill_rq)) {
8417 				putnext(dst_ill->ill_rq, mp);
8418 				/*
8419 				 * The response will come back in ip_wput
8420 				 * with db_type IRE_DB_TYPE.
8421 				 */
8422 			} else {
8423 				ire->ire_dlureq_mp = mp;
8424 				mp->b_cont = NULL;
8425 				ire_delete(ire);
8426 				saved_mp->b_next = NULL;
8427 				saved_mp->b_prev = NULL;
8428 				freemsg(first_mp);
8429 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8430 			}
8431 
8432 			if (fire != NULL) {
8433 				ire_refrele(fire);
8434 				fire = NULL;
8435 			}
8436 
8437 
8438 			/*
8439 			 * The resolution loop is re-entered if this was
8440 			 * requested through flags and we actually are
8441 			 * in a multirouting case.
8442 			 */
8443 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8444 				boolean_t need_resolve =
8445 				    ire_multirt_need_resolve(ipha_dst);
8446 				if (!need_resolve) {
8447 					MULTIRT_DEBUG_UNTAG(copy_mp);
8448 					freemsg(copy_mp);
8449 					copy_mp = NULL;
8450 				} else {
8451 					/*
8452 					 * ipif_lookup_group() calls
8453 					 * ire_lookup_multi() that uses
8454 					 * ire_ftable_lookup() to find
8455 					 * an IRE_INTERFACE for the group.
8456 					 * In the multirt case,
8457 					 * ire_lookup_multi() then invokes
8458 					 * ire_multirt_lookup() to find
8459 					 * the next resolvable ire.
8460 					 * As a result, we obtain an new
8461 					 * interface, derived from the
8462 					 * next ire.
8463 					 */
8464 					ipif_refrele(ipif);
8465 					ipif = ipif_lookup_group(ipha_dst,
8466 					    zoneid);
8467 					if (ipif != NULL) {
8468 						mp = copy_mp;
8469 						copy_mp = NULL;
8470 						multirt_resolve_next = B_TRUE;
8471 						continue;
8472 					} else {
8473 						freemsg(copy_mp);
8474 					}
8475 				}
8476 			}
8477 			if (ipif != NULL)
8478 				ipif_refrele(ipif);
8479 			ill_refrele(dst_ill);
8480 			ipif_refrele(src_ipif);
8481 			return;
8482 		default:
8483 			break;
8484 		}
8485 	} while (multirt_resolve_next);
8486 
8487 err_ret:
8488 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8489 	if (fire != NULL)
8490 		ire_refrele(fire);
8491 	ipif_refrele(ipif);
8492 	/* Did this packet originate externally? */
8493 	if (dst_ill != NULL)
8494 		ill_refrele(dst_ill);
8495 	if (src_ipif != NULL)
8496 		ipif_refrele(src_ipif);
8497 	if (mp->b_prev || mp->b_next) {
8498 		mp->b_next = NULL;
8499 		mp->b_prev = NULL;
8500 	} else {
8501 		/*
8502 		 * Since ip_wput() isn't close to finished, we fill
8503 		 * in enough of the header for credible error reporting.
8504 		 */
8505 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8506 			/* Failed */
8507 			freemsg(first_mp);
8508 			if (ire != NULL)
8509 				ire_refrele(ire);
8510 			return;
8511 		}
8512 	}
8513 	/*
8514 	 * At this point we will have ire only if RTF_BLACKHOLE
8515 	 * or RTF_REJECT flags are set on the IRE. It will not
8516 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8517 	 */
8518 	if (ire != NULL) {
8519 		if (ire->ire_flags & RTF_BLACKHOLE) {
8520 			ire_refrele(ire);
8521 			freemsg(first_mp);
8522 			return;
8523 		}
8524 		ire_refrele(ire);
8525 	}
8526 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8527 }
8528 
8529 /* Name/Value Table Lookup Routine */
8530 char *
8531 ip_nv_lookup(nv_t *nv, int value)
8532 {
8533 	if (!nv)
8534 		return (NULL);
8535 	for (; nv->nv_name; nv++) {
8536 		if (nv->nv_value == value)
8537 			return (nv->nv_name);
8538 	}
8539 	return ("unknown");
8540 }
8541 
8542 /*
8543  * one day it can be patched to 1 from /etc/system for machines that have few
8544  * fast network interfaces feeding multiple cpus.
8545  */
8546 int ill_stream_putlocks = 0;
8547 
8548 /*
8549  * This is a module open, i.e. this is a control stream for access
8550  * to a DLPI device.  We allocate an ill_t as the instance data in
8551  * this case.
8552  */
8553 int
8554 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8555 {
8556 	uint32_t mem_cnt;
8557 	uint32_t cpu_cnt;
8558 	uint32_t min_cnt;
8559 	pgcnt_t mem_avail;
8560 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8561 	ill_t	*ill;
8562 	int	err;
8563 
8564 	/*
8565 	 * Prevent unprivileged processes from pushing IP so that
8566 	 * they can't send raw IP.
8567 	 */
8568 	if (secpolicy_net_rawaccess(credp) != 0)
8569 		return (EPERM);
8570 
8571 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8572 	q->q_ptr = WR(q)->q_ptr = ill;
8573 
8574 	/*
8575 	 * ill_init initializes the ill fields and then sends down
8576 	 * down a DL_INFO_REQ after calling qprocson.
8577 	 */
8578 	err = ill_init(q, ill);
8579 	if (err != 0) {
8580 		mi_free(ill);
8581 		q->q_ptr = NULL;
8582 		WR(q)->q_ptr = NULL;
8583 		return (err);
8584 	}
8585 
8586 	/* ill_init initializes the ipsq marking this thread as writer */
8587 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8588 	/* Wait for the DL_INFO_ACK */
8589 	mutex_enter(&ill->ill_lock);
8590 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8591 		/*
8592 		 * Return value of 0 indicates a pending signal.
8593 		 */
8594 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8595 		if (err == 0) {
8596 			mutex_exit(&ill->ill_lock);
8597 			(void) ip_close(q, 0);
8598 			return (EINTR);
8599 		}
8600 	}
8601 	mutex_exit(&ill->ill_lock);
8602 
8603 	/*
8604 	 * ip_rput_other could have set an error  in ill_error on
8605 	 * receipt of M_ERROR.
8606 	 */
8607 
8608 	err = ill->ill_error;
8609 	if (err != 0) {
8610 		(void) ip_close(q, 0);
8611 		return (err);
8612 	}
8613 
8614 	/*
8615 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8616 	 * size and the cpu speed of the machine. This is upper
8617 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8618 	 * and is lower bounded by the compile time value of
8619 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8620 	 * ip6_ire_max_bucket_cnt.
8621 	 */
8622 	mem_avail = kmem_avail();
8623 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8624 	    ip_cache_table_size / sizeof (ire_t);
8625 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8626 
8627 	min_cnt = MIN(cpu_cnt, mem_cnt);
8628 	if (min_cnt < ip_ire_min_bucket_cnt)
8629 		min_cnt = ip_ire_min_bucket_cnt;
8630 	if (ip_ire_max_bucket_cnt > min_cnt) {
8631 		ip_ire_max_bucket_cnt = min_cnt;
8632 	}
8633 
8634 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8635 	    ip6_cache_table_size / sizeof (ire_t);
8636 	min_cnt = MIN(cpu_cnt, mem_cnt);
8637 	if (min_cnt < ip6_ire_min_bucket_cnt)
8638 		min_cnt = ip6_ire_min_bucket_cnt;
8639 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8640 		ip6_ire_max_bucket_cnt = min_cnt;
8641 	}
8642 
8643 	ill->ill_credp = credp;
8644 	crhold(credp);
8645 
8646 	mutex_enter(&ip_mi_lock);
8647 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8648 	mutex_exit(&ip_mi_lock);
8649 	if (err) {
8650 		(void) ip_close(q, 0);
8651 		return (err);
8652 	}
8653 	return (0);
8654 }
8655 
8656 /* IP open routine. */
8657 int
8658 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8659 {
8660 	conn_t 		*connp;
8661 	major_t		maj;
8662 
8663 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8664 
8665 	/* Allow reopen. */
8666 	if (q->q_ptr != NULL)
8667 		return (0);
8668 
8669 	if (sflag & MODOPEN) {
8670 		/* This is a module open */
8671 		return (ip_modopen(q, devp, flag, sflag, credp));
8672 	}
8673 
8674 	/*
8675 	 * We are opening as a device. This is an IP client stream, and we
8676 	 * allocate an conn_t as the instance data.
8677 	 */
8678 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8679 	connp->conn_upq = q;
8680 	q->q_ptr = WR(q)->q_ptr = connp;
8681 
8682 	if (flag & SO_SOCKSTR)
8683 		connp->conn_flags |= IPCL_SOCKET;
8684 
8685 	/* Minor tells us which /dev entry was opened */
8686 	if (geteminor(*devp) == IPV6_MINOR) {
8687 		connp->conn_flags |= IPCL_ISV6;
8688 		connp->conn_af_isv6 = B_TRUE;
8689 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8690 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8691 	} else {
8692 		connp->conn_af_isv6 = B_FALSE;
8693 		connp->conn_pkt_isv6 = B_FALSE;
8694 	}
8695 
8696 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
8697 		q->q_ptr = WR(q)->q_ptr = NULL;
8698 		CONN_DEC_REF(connp);
8699 		return (EBUSY);
8700 	}
8701 
8702 	maj = getemajor(*devp);
8703 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8704 
8705 	/*
8706 	 * connp->conn_cred is crfree()ed in ip_close().
8707 	 */
8708 	connp->conn_cred = credp;
8709 	crhold(connp->conn_cred);
8710 
8711 	connp->conn_zoneid = getzoneid();
8712 
8713 	/*
8714 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8715 	 * administrative ops.  In these cases, we just need a normal conn_t
8716 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8717 	 * an error will be returned.
8718 	 */
8719 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8720 		connp->conn_rq = q;
8721 		connp->conn_wq = WR(q);
8722 	} else {
8723 		connp->conn_ulp = IPPROTO_SCTP;
8724 		connp->conn_rq = connp->conn_wq = NULL;
8725 	}
8726 	/* Non-zero default values */
8727 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8728 
8729 	/*
8730 	 * Make the conn globally visible to walkers
8731 	 */
8732 	mutex_enter(&connp->conn_lock);
8733 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8734 	mutex_exit(&connp->conn_lock);
8735 	ASSERT(connp->conn_ref == 1);
8736 
8737 	qprocson(q);
8738 
8739 	return (0);
8740 }
8741 
8742 /*
8743  * Change q_qinfo based on the value of isv6.
8744  * This can not called on an ill queue.
8745  * Note that there is no race since either q_qinfo works for conn queues - it
8746  * is just an optimization to enter the best wput routine directly.
8747  */
8748 void
8749 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8750 {
8751 	ASSERT(q->q_flag & QREADR);
8752 	ASSERT(WR(q)->q_next == NULL);
8753 	ASSERT(q->q_ptr != NULL);
8754 
8755 	if (minor == IPV6_MINOR)  {
8756 		if (bump_mib)
8757 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8758 		q->q_qinfo = &rinit_ipv6;
8759 		WR(q)->q_qinfo = &winit_ipv6;
8760 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8761 	} else {
8762 		if (bump_mib)
8763 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8764 		q->q_qinfo = &rinit;
8765 		WR(q)->q_qinfo = &winit;
8766 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8767 	}
8768 
8769 }
8770 
8771 /*
8772  * See if IPsec needs loading because of the options in mp.
8773  */
8774 static boolean_t
8775 ipsec_opt_present(mblk_t *mp)
8776 {
8777 	uint8_t *optcp, *next_optcp, *opt_endcp;
8778 	struct opthdr *opt;
8779 	struct T_opthdr *topt;
8780 	int opthdr_len;
8781 	t_uscalar_t optname, optlevel;
8782 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8783 	ipsec_req_t *ipsr;
8784 
8785 	/*
8786 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8787 	 * return TRUE.
8788 	 */
8789 
8790 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8791 	opt_endcp = optcp + tor->OPT_length;
8792 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8793 		opthdr_len = sizeof (struct T_opthdr);
8794 	} else {		/* O_OPTMGMT_REQ */
8795 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8796 		opthdr_len = sizeof (struct opthdr);
8797 	}
8798 	for (; optcp < opt_endcp; optcp = next_optcp) {
8799 		if (optcp + opthdr_len > opt_endcp)
8800 			return (B_FALSE);	/* Not enough option header. */
8801 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8802 			topt = (struct T_opthdr *)optcp;
8803 			optlevel = topt->level;
8804 			optname = topt->name;
8805 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8806 		} else {
8807 			opt = (struct opthdr *)optcp;
8808 			optlevel = opt->level;
8809 			optname = opt->name;
8810 			next_optcp = optcp + opthdr_len +
8811 			    _TPI_ALIGN_OPT(opt->len);
8812 		}
8813 		if ((next_optcp < optcp) || /* wraparound pointer space */
8814 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8815 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8816 			return (B_FALSE); /* bad option buffer */
8817 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8818 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8819 			/*
8820 			 * Check to see if it's an all-bypass or all-zeroes
8821 			 * IPsec request.  Don't bother loading IPsec if
8822 			 * the socket doesn't want to use it.  (A good example
8823 			 * is a bypass request.)
8824 			 *
8825 			 * Basically, if any of the non-NEVER bits are set,
8826 			 * load IPsec.
8827 			 */
8828 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8829 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8830 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8831 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8832 			    != 0)
8833 				return (B_TRUE);
8834 		}
8835 	}
8836 	return (B_FALSE);
8837 }
8838 
8839 /*
8840  * If conn is is waiting for ipsec to finish loading, kick it.
8841  */
8842 /* ARGSUSED */
8843 static void
8844 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8845 {
8846 	t_scalar_t	optreq_prim;
8847 	mblk_t		*mp;
8848 	cred_t		*cr;
8849 	int		err = 0;
8850 
8851 	/*
8852 	 * This function is called, after ipsec loading is complete.
8853 	 * Since IP checks exclusively and atomically (i.e it prevents
8854 	 * ipsec load from completing until ip_optcom_req completes)
8855 	 * whether ipsec load is complete, there cannot be a race with IP
8856 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8857 	 */
8858 	mutex_enter(&connp->conn_lock);
8859 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8860 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8861 		mp = connp->conn_ipsec_opt_mp;
8862 		connp->conn_ipsec_opt_mp = NULL;
8863 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8864 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8865 		mutex_exit(&connp->conn_lock);
8866 
8867 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8868 
8869 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8870 		if (optreq_prim == T_OPTMGMT_REQ) {
8871 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8872 			    &ip_opt_obj);
8873 		} else {
8874 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8875 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8876 			    &ip_opt_obj);
8877 		}
8878 		if (err != EINPROGRESS)
8879 			CONN_OPER_PENDING_DONE(connp);
8880 		return;
8881 	}
8882 	mutex_exit(&connp->conn_lock);
8883 }
8884 
8885 /*
8886  * Called from the ipsec_loader thread, outside any perimeter, to tell
8887  * ip qenable any of the queues waiting for the ipsec loader to
8888  * complete.
8889  *
8890  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8891  * are done with this lock held, so it's guaranteed that none of the
8892  * links will change along the way.
8893  */
8894 void
8895 ip_ipsec_load_complete()
8896 {
8897 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8898 }
8899 
8900 /*
8901  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8902  * determines the grp on which it has to become exclusive, queues the mp
8903  * and sq draining restarts the optmgmt
8904  */
8905 static boolean_t
8906 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8907 {
8908 	conn_t *connp;
8909 
8910 	/*
8911 	 * Take IPsec requests and treat them special.
8912 	 */
8913 	if (ipsec_opt_present(mp)) {
8914 		/* First check if IPsec is loaded. */
8915 		mutex_enter(&ipsec_loader_lock);
8916 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8917 			mutex_exit(&ipsec_loader_lock);
8918 			return (B_FALSE);
8919 		}
8920 		connp = Q_TO_CONN(q);
8921 		mutex_enter(&connp->conn_lock);
8922 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8923 
8924 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8925 		connp->conn_ipsec_opt_mp = mp;
8926 		mutex_exit(&connp->conn_lock);
8927 		mutex_exit(&ipsec_loader_lock);
8928 
8929 		ipsec_loader_loadnow();
8930 		return (B_TRUE);
8931 	}
8932 	return (B_FALSE);
8933 }
8934 
8935 /*
8936  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8937  * all of them are copied to the conn_t. If the req is "zero", the policy is
8938  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8939  * fields.
8940  * We keep only the latest setting of the policy and thus policy setting
8941  * is not incremental/cumulative.
8942  *
8943  * Requests to set policies with multiple alternative actions will
8944  * go through a different API.
8945  */
8946 int
8947 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8948 {
8949 	uint_t ah_req = 0;
8950 	uint_t esp_req = 0;
8951 	uint_t se_req = 0;
8952 	ipsec_selkey_t sel;
8953 	ipsec_act_t *actp = NULL;
8954 	uint_t nact;
8955 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8956 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8957 	ipsec_policy_root_t *pr;
8958 	ipsec_policy_head_t *ph;
8959 	int fam;
8960 	boolean_t is_pol_reset;
8961 	int error = 0;
8962 
8963 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8964 
8965 	/*
8966 	 * The IP_SEC_OPT option does not allow variable length parameters,
8967 	 * hence a request cannot be NULL.
8968 	 */
8969 	if (req == NULL)
8970 		return (EINVAL);
8971 
8972 	ah_req = req->ipsr_ah_req;
8973 	esp_req = req->ipsr_esp_req;
8974 	se_req = req->ipsr_self_encap_req;
8975 
8976 	/*
8977 	 * Are we dealing with a request to reset the policy (i.e.
8978 	 * zero requests).
8979 	 */
8980 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8981 	    (esp_req & REQ_MASK) == 0 &&
8982 	    (se_req & REQ_MASK) == 0);
8983 
8984 	if (!is_pol_reset) {
8985 		/*
8986 		 * If we couldn't load IPsec, fail with "protocol
8987 		 * not supported".
8988 		 * IPsec may not have been loaded for a request with zero
8989 		 * policies, so we don't fail in this case.
8990 		 */
8991 		mutex_enter(&ipsec_loader_lock);
8992 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8993 			mutex_exit(&ipsec_loader_lock);
8994 			return (EPROTONOSUPPORT);
8995 		}
8996 		mutex_exit(&ipsec_loader_lock);
8997 
8998 		/*
8999 		 * Test for valid requests. Invalid algorithms
9000 		 * need to be tested by IPSEC code because new
9001 		 * algorithms can be added dynamically.
9002 		 */
9003 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9004 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9005 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9006 			return (EINVAL);
9007 		}
9008 
9009 		/*
9010 		 * Only privileged users can issue these
9011 		 * requests.
9012 		 */
9013 		if (((ah_req & IPSEC_PREF_NEVER) ||
9014 		    (esp_req & IPSEC_PREF_NEVER) ||
9015 		    (se_req & IPSEC_PREF_NEVER)) &&
9016 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9017 			return (EPERM);
9018 		}
9019 
9020 		/*
9021 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9022 		 * are mutually exclusive.
9023 		 */
9024 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9025 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9026 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9027 			/* Both of them are set */
9028 			return (EINVAL);
9029 		}
9030 	}
9031 
9032 	mutex_enter(&connp->conn_lock);
9033 
9034 	/*
9035 	 * If we have already cached policies in ip_bind_connected*(), don't
9036 	 * let them change now. We cache policies for connections
9037 	 * whose src,dst [addr, port] is known.  The exception to this is
9038 	 * tunnels.  Tunnels are allowed to change policies after having
9039 	 * become fully bound.
9040 	 */
9041 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9042 		mutex_exit(&connp->conn_lock);
9043 		return (EINVAL);
9044 	}
9045 
9046 	/*
9047 	 * We have a zero policies, reset the connection policy if already
9048 	 * set. This will cause the connection to inherit the
9049 	 * global policy, if any.
9050 	 */
9051 	if (is_pol_reset) {
9052 		if (connp->conn_policy != NULL) {
9053 			IPPH_REFRELE(connp->conn_policy);
9054 			connp->conn_policy = NULL;
9055 		}
9056 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9057 		connp->conn_in_enforce_policy = B_FALSE;
9058 		connp->conn_out_enforce_policy = B_FALSE;
9059 		mutex_exit(&connp->conn_lock);
9060 		return (0);
9061 	}
9062 
9063 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9064 	if (ph == NULL)
9065 		goto enomem;
9066 
9067 	ipsec_actvec_from_req(req, &actp, &nact);
9068 	if (actp == NULL)
9069 		goto enomem;
9070 
9071 	/*
9072 	 * Always allocate IPv4 policy entries, since they can also
9073 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9074 	 */
9075 	bzero(&sel, sizeof (sel));
9076 	sel.ipsl_valid = IPSL_IPV4;
9077 
9078 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9079 	if (pin4 == NULL)
9080 		goto enomem;
9081 
9082 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9083 	if (pout4 == NULL)
9084 		goto enomem;
9085 
9086 	if (connp->conn_pkt_isv6) {
9087 		/*
9088 		 * We're looking at a v6 socket, also allocate the
9089 		 * v6-specific entries...
9090 		 */
9091 		sel.ipsl_valid = IPSL_IPV6;
9092 		pin6 = ipsec_policy_create(&sel, actp, nact,
9093 		    IPSEC_PRIO_SOCKET);
9094 		if (pin6 == NULL)
9095 			goto enomem;
9096 
9097 		pout6 = ipsec_policy_create(&sel, actp, nact,
9098 		    IPSEC_PRIO_SOCKET);
9099 		if (pout6 == NULL)
9100 			goto enomem;
9101 
9102 		/*
9103 		 * .. and file them away in the right place.
9104 		 */
9105 		fam = IPSEC_AF_V6;
9106 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9107 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9108 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9109 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9110 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9111 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9112 	}
9113 
9114 	ipsec_actvec_free(actp, nact);
9115 
9116 	/*
9117 	 * File the v4 policies.
9118 	 */
9119 	fam = IPSEC_AF_V4;
9120 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9121 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9122 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9123 
9124 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9125 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9126 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9127 
9128 	/*
9129 	 * If the requests need security, set enforce_policy.
9130 	 * If the requests are IPSEC_PREF_NEVER, one should
9131 	 * still set conn_out_enforce_policy so that an ipsec_out
9132 	 * gets attached in ip_wput. This is needed so that
9133 	 * for connections that we don't cache policy in ip_bind,
9134 	 * if global policy matches in ip_wput_attach_policy, we
9135 	 * don't wrongly inherit global policy. Similarly, we need
9136 	 * to set conn_in_enforce_policy also so that we don't verify
9137 	 * policy wrongly.
9138 	 */
9139 	if ((ah_req & REQ_MASK) != 0 ||
9140 	    (esp_req & REQ_MASK) != 0 ||
9141 	    (se_req & REQ_MASK) != 0) {
9142 		connp->conn_in_enforce_policy = B_TRUE;
9143 		connp->conn_out_enforce_policy = B_TRUE;
9144 		connp->conn_flags |= IPCL_CHECK_POLICY;
9145 	}
9146 
9147 	/*
9148 	 * Tunnels are allowed to set policy after having been fully bound.
9149 	 * If that's the case, cache policy here.
9150 	 */
9151 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9152 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9153 
9154 	mutex_exit(&connp->conn_lock);
9155 	return (error);
9156 #undef REQ_MASK
9157 
9158 	/*
9159 	 * Common memory-allocation-failure exit path.
9160 	 */
9161 enomem:
9162 	mutex_exit(&connp->conn_lock);
9163 	if (actp != NULL)
9164 		ipsec_actvec_free(actp, nact);
9165 	if (pin4 != NULL)
9166 		IPPOL_REFRELE(pin4);
9167 	if (pout4 != NULL)
9168 		IPPOL_REFRELE(pout4);
9169 	if (pin6 != NULL)
9170 		IPPOL_REFRELE(pin6);
9171 	if (pout6 != NULL)
9172 		IPPOL_REFRELE(pout6);
9173 	return (ENOMEM);
9174 }
9175 
9176 /*
9177  * Only for options that pass in an IP addr. Currently only V4 options
9178  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9179  * So this function assumes level is IPPROTO_IP
9180  */
9181 int
9182 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9183     mblk_t *first_mp)
9184 {
9185 	ipif_t *ipif = NULL;
9186 	int error;
9187 	ill_t *ill;
9188 
9189 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9190 
9191 	if (addr != INADDR_ANY || checkonly) {
9192 		ASSERT(connp != NULL);
9193 		if (option == IP_NEXTHOP) {
9194 			ipif =
9195 			    ipif_lookup_onlink_addr(addr, connp->conn_zoneid);
9196 		} else {
9197 			ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9198 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9199 			    &error);
9200 		}
9201 		if (ipif == NULL) {
9202 			if (error == EINPROGRESS)
9203 				return (error);
9204 			else if ((option == IP_MULTICAST_IF) ||
9205 			    (option == IP_NEXTHOP))
9206 				return (EHOSTUNREACH);
9207 			else
9208 				return (EINVAL);
9209 		} else if (checkonly) {
9210 			if (option == IP_MULTICAST_IF) {
9211 				ill = ipif->ipif_ill;
9212 				/* not supported by the virtual network iface */
9213 				if (IS_VNI(ill)) {
9214 					ipif_refrele(ipif);
9215 					return (EINVAL);
9216 				}
9217 			}
9218 			ipif_refrele(ipif);
9219 			return (0);
9220 		}
9221 		ill = ipif->ipif_ill;
9222 		mutex_enter(&connp->conn_lock);
9223 		mutex_enter(&ill->ill_lock);
9224 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9225 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9226 			mutex_exit(&ill->ill_lock);
9227 			mutex_exit(&connp->conn_lock);
9228 			ipif_refrele(ipif);
9229 			return (option == IP_MULTICAST_IF ?
9230 			    EHOSTUNREACH : EINVAL);
9231 		}
9232 	} else {
9233 		mutex_enter(&connp->conn_lock);
9234 	}
9235 
9236 	/* None of the options below are supported on the VNI */
9237 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9238 		mutex_exit(&ill->ill_lock);
9239 		mutex_exit(&connp->conn_lock);
9240 		ipif_refrele(ipif);
9241 		return (EINVAL);
9242 	}
9243 
9244 	switch (option) {
9245 	case IP_DONTFAILOVER_IF:
9246 		/*
9247 		 * This option is used by in.mpathd to ensure
9248 		 * that IPMP probe packets only go out on the
9249 		 * test interfaces. in.mpathd sets this option
9250 		 * on the non-failover interfaces.
9251 		 * For backward compatibility, this option
9252 		 * implicitly sets IP_MULTICAST_IF, as used
9253 		 * be done in bind(), so that ip_wput gets
9254 		 * this ipif to send mcast packets.
9255 		 */
9256 		if (ipif != NULL) {
9257 			ASSERT(addr != INADDR_ANY);
9258 			connp->conn_nofailover_ill = ipif->ipif_ill;
9259 			connp->conn_multicast_ipif = ipif;
9260 		} else {
9261 			ASSERT(addr == INADDR_ANY);
9262 			connp->conn_nofailover_ill = NULL;
9263 			connp->conn_multicast_ipif = NULL;
9264 		}
9265 		break;
9266 
9267 	case IP_MULTICAST_IF:
9268 		connp->conn_multicast_ipif = ipif;
9269 		break;
9270 	case IP_NEXTHOP:
9271 		connp->conn_nexthop_v4 = addr;
9272 		connp->conn_nexthop_set = B_TRUE;
9273 		break;
9274 	}
9275 
9276 	if (ipif != NULL) {
9277 		mutex_exit(&ill->ill_lock);
9278 		mutex_exit(&connp->conn_lock);
9279 		ipif_refrele(ipif);
9280 		return (0);
9281 	}
9282 	mutex_exit(&connp->conn_lock);
9283 	/* We succeded in cleared the option */
9284 	return (0);
9285 }
9286 
9287 /*
9288  * For options that pass in an ifindex specifying the ill. V6 options always
9289  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9290  */
9291 int
9292 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9293     int level, int option, mblk_t *first_mp)
9294 {
9295 	ill_t *ill = NULL;
9296 	int error = 0;
9297 
9298 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9299 	if (ifindex != 0) {
9300 		ASSERT(connp != NULL);
9301 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9302 		    first_mp, ip_restart_optmgmt, &error);
9303 		if (ill != NULL) {
9304 			if (checkonly) {
9305 				/* not supported by the virtual network iface */
9306 				if (IS_VNI(ill)) {
9307 					ill_refrele(ill);
9308 					return (EINVAL);
9309 				}
9310 				ill_refrele(ill);
9311 				return (0);
9312 			}
9313 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9314 			    0, NULL)) {
9315 				ill_refrele(ill);
9316 				ill = NULL;
9317 				mutex_enter(&connp->conn_lock);
9318 				goto setit;
9319 			}
9320 			mutex_enter(&connp->conn_lock);
9321 			mutex_enter(&ill->ill_lock);
9322 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9323 				mutex_exit(&ill->ill_lock);
9324 				mutex_exit(&connp->conn_lock);
9325 				ill_refrele(ill);
9326 				ill = NULL;
9327 				mutex_enter(&connp->conn_lock);
9328 			}
9329 			goto setit;
9330 		} else if (error == EINPROGRESS) {
9331 			return (error);
9332 		} else {
9333 			error = 0;
9334 		}
9335 	}
9336 	mutex_enter(&connp->conn_lock);
9337 setit:
9338 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9339 
9340 	/*
9341 	 * The options below assume that the ILL (if any) transmits and/or
9342 	 * receives traffic. Neither of which is true for the virtual network
9343 	 * interface, so fail setting these on a VNI.
9344 	 */
9345 	if (IS_VNI(ill)) {
9346 		ASSERT(ill != NULL);
9347 		mutex_exit(&ill->ill_lock);
9348 		mutex_exit(&connp->conn_lock);
9349 		ill_refrele(ill);
9350 		return (EINVAL);
9351 	}
9352 
9353 	if (level == IPPROTO_IP) {
9354 		switch (option) {
9355 		case IP_BOUND_IF:
9356 			connp->conn_incoming_ill = ill;
9357 			connp->conn_outgoing_ill = ill;
9358 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9359 			    0 : ifindex;
9360 			break;
9361 
9362 		case IP_XMIT_IF:
9363 			/*
9364 			 * Similar to IP_BOUND_IF, but this only
9365 			 * determines the outgoing interface for
9366 			 * unicast packets. Also no IRE_CACHE entry
9367 			 * is added for the destination of the
9368 			 * outgoing packets. This feature is needed
9369 			 * for mobile IP.
9370 			 */
9371 			connp->conn_xmit_if_ill = ill;
9372 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9373 			    0 : ifindex;
9374 			break;
9375 
9376 		case IP_MULTICAST_IF:
9377 			/*
9378 			 * This option is an internal special. The socket
9379 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9380 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9381 			 * specifies an ifindex and we try first on V6 ill's.
9382 			 * If we don't find one, we they try using on v4 ill's
9383 			 * intenally and we come here.
9384 			 */
9385 			if (!checkonly && ill != NULL) {
9386 				ipif_t	*ipif;
9387 				ipif = ill->ill_ipif;
9388 
9389 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9390 					mutex_exit(&ill->ill_lock);
9391 					mutex_exit(&connp->conn_lock);
9392 					ill_refrele(ill);
9393 					ill = NULL;
9394 					mutex_enter(&connp->conn_lock);
9395 				} else {
9396 					connp->conn_multicast_ipif = ipif;
9397 				}
9398 			}
9399 			break;
9400 		}
9401 	} else {
9402 		switch (option) {
9403 		case IPV6_BOUND_IF:
9404 			connp->conn_incoming_ill = ill;
9405 			connp->conn_outgoing_ill = ill;
9406 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9407 			    0 : ifindex;
9408 			break;
9409 
9410 		case IPV6_BOUND_PIF:
9411 			/*
9412 			 * Limit all transmit to this ill.
9413 			 * Unlike IPV6_BOUND_IF, using this option
9414 			 * prevents load spreading and failover from
9415 			 * happening when the interface is part of the
9416 			 * group. That's why we don't need to remember
9417 			 * the ifindex in orig_bound_ifindex as in
9418 			 * IPV6_BOUND_IF.
9419 			 */
9420 			connp->conn_outgoing_pill = ill;
9421 			break;
9422 
9423 		case IPV6_DONTFAILOVER_IF:
9424 			/*
9425 			 * This option is used by in.mpathd to ensure
9426 			 * that IPMP probe packets only go out on the
9427 			 * test interfaces. in.mpathd sets this option
9428 			 * on the non-failover interfaces.
9429 			 */
9430 			connp->conn_nofailover_ill = ill;
9431 			/*
9432 			 * For backward compatibility, this option
9433 			 * implicitly sets ip_multicast_ill as used in
9434 			 * IP_MULTICAST_IF so that ip_wput gets
9435 			 * this ipif to send mcast packets.
9436 			 */
9437 			connp->conn_multicast_ill = ill;
9438 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9439 			    0 : ifindex;
9440 			break;
9441 
9442 		case IPV6_MULTICAST_IF:
9443 			/*
9444 			 * Set conn_multicast_ill to be the IPv6 ill.
9445 			 * Set conn_multicast_ipif to be an IPv4 ipif
9446 			 * for ifindex to make IPv4 mapped addresses
9447 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9448 			 * Even if no IPv6 ill exists for the ifindex
9449 			 * we need to check for an IPv4 ifindex in order
9450 			 * for this to work with mapped addresses. In that
9451 			 * case only set conn_multicast_ipif.
9452 			 */
9453 			if (!checkonly) {
9454 				if (ifindex == 0) {
9455 					connp->conn_multicast_ill = NULL;
9456 					connp->conn_orig_multicast_ifindex = 0;
9457 					connp->conn_multicast_ipif = NULL;
9458 				} else if (ill != NULL) {
9459 					connp->conn_multicast_ill = ill;
9460 					connp->conn_orig_multicast_ifindex =
9461 					    ifindex;
9462 				}
9463 			}
9464 			break;
9465 		}
9466 	}
9467 
9468 	if (ill != NULL) {
9469 		mutex_exit(&ill->ill_lock);
9470 		mutex_exit(&connp->conn_lock);
9471 		ill_refrele(ill);
9472 		return (0);
9473 	}
9474 	mutex_exit(&connp->conn_lock);
9475 	/*
9476 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9477 	 * locate the ill and could not set the option (ifindex != 0)
9478 	 */
9479 	return (ifindex == 0 ? 0 : EINVAL);
9480 }
9481 
9482 /* This routine sets socket options. */
9483 /* ARGSUSED */
9484 int
9485 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9486     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9487     void *dummy, cred_t *cr, mblk_t *first_mp)
9488 {
9489 	int		*i1 = (int *)invalp;
9490 	conn_t		*connp = Q_TO_CONN(q);
9491 	int		error = 0;
9492 	boolean_t	checkonly;
9493 	ire_t		*ire;
9494 	boolean_t	found;
9495 
9496 	switch (optset_context) {
9497 
9498 	case SETFN_OPTCOM_CHECKONLY:
9499 		checkonly = B_TRUE;
9500 		/*
9501 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9502 		 * inlen != 0 implies value supplied and
9503 		 * 	we have to "pretend" to set it.
9504 		 * inlen == 0 implies that there is no
9505 		 * 	value part in T_CHECK request and just validation
9506 		 * done elsewhere should be enough, we just return here.
9507 		 */
9508 		if (inlen == 0) {
9509 			*outlenp = 0;
9510 			return (0);
9511 		}
9512 		break;
9513 	case SETFN_OPTCOM_NEGOTIATE:
9514 	case SETFN_UD_NEGOTIATE:
9515 	case SETFN_CONN_NEGOTIATE:
9516 		checkonly = B_FALSE;
9517 		break;
9518 	default:
9519 		/*
9520 		 * We should never get here
9521 		 */
9522 		*outlenp = 0;
9523 		return (EINVAL);
9524 	}
9525 
9526 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9527 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9528 
9529 	/*
9530 	 * For fixed length options, no sanity check
9531 	 * of passed in length is done. It is assumed *_optcom_req()
9532 	 * routines do the right thing.
9533 	 */
9534 
9535 	switch (level) {
9536 	case SOL_SOCKET:
9537 		/*
9538 		 * conn_lock protects the bitfields, and is used to
9539 		 * set the fields atomically.
9540 		 */
9541 		switch (name) {
9542 		case SO_BROADCAST:
9543 			if (!checkonly) {
9544 				/* TODO: use value someplace? */
9545 				mutex_enter(&connp->conn_lock);
9546 				connp->conn_broadcast = *i1 ? 1 : 0;
9547 				mutex_exit(&connp->conn_lock);
9548 			}
9549 			break;	/* goto sizeof (int) option return */
9550 		case SO_USELOOPBACK:
9551 			if (!checkonly) {
9552 				/* TODO: use value someplace? */
9553 				mutex_enter(&connp->conn_lock);
9554 				connp->conn_loopback = *i1 ? 1 : 0;
9555 				mutex_exit(&connp->conn_lock);
9556 			}
9557 			break;	/* goto sizeof (int) option return */
9558 		case SO_DONTROUTE:
9559 			if (!checkonly) {
9560 				mutex_enter(&connp->conn_lock);
9561 				connp->conn_dontroute = *i1 ? 1 : 0;
9562 				mutex_exit(&connp->conn_lock);
9563 			}
9564 			break;	/* goto sizeof (int) option return */
9565 		case SO_REUSEADDR:
9566 			if (!checkonly) {
9567 				mutex_enter(&connp->conn_lock);
9568 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9569 				mutex_exit(&connp->conn_lock);
9570 			}
9571 			break;	/* goto sizeof (int) option return */
9572 		case SO_PROTOTYPE:
9573 			if (!checkonly) {
9574 				mutex_enter(&connp->conn_lock);
9575 				connp->conn_proto = *i1;
9576 				mutex_exit(&connp->conn_lock);
9577 			}
9578 			break;	/* goto sizeof (int) option return */
9579 		default:
9580 			/*
9581 			 * "soft" error (negative)
9582 			 * option not handled at this level
9583 			 * Note: Do not modify *outlenp
9584 			 */
9585 			return (-EINVAL);
9586 		}
9587 		break;
9588 	case IPPROTO_IP:
9589 		switch (name) {
9590 		case IP_NEXTHOP:
9591 		case IP_MULTICAST_IF:
9592 		case IP_DONTFAILOVER_IF: {
9593 			ipaddr_t addr = *i1;
9594 
9595 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9596 			    first_mp);
9597 			if (error != 0)
9598 				return (error);
9599 			break;	/* goto sizeof (int) option return */
9600 		}
9601 
9602 		case IP_MULTICAST_TTL:
9603 			/* Recorded in transport above IP */
9604 			*outvalp = *invalp;
9605 			*outlenp = sizeof (uchar_t);
9606 			return (0);
9607 		case IP_MULTICAST_LOOP:
9608 			if (!checkonly) {
9609 				mutex_enter(&connp->conn_lock);
9610 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9611 				mutex_exit(&connp->conn_lock);
9612 			}
9613 			*outvalp = *invalp;
9614 			*outlenp = sizeof (uchar_t);
9615 			return (0);
9616 		case IP_ADD_MEMBERSHIP:
9617 		case MCAST_JOIN_GROUP:
9618 		case IP_DROP_MEMBERSHIP:
9619 		case MCAST_LEAVE_GROUP: {
9620 			struct ip_mreq *mreqp;
9621 			struct group_req *greqp;
9622 			ire_t *ire;
9623 			boolean_t done = B_FALSE;
9624 			ipaddr_t group, ifaddr;
9625 			struct sockaddr_in *sin;
9626 			uint32_t *ifindexp;
9627 			boolean_t mcast_opt = B_TRUE;
9628 			mcast_record_t fmode;
9629 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9630 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9631 
9632 			switch (name) {
9633 			case IP_ADD_MEMBERSHIP:
9634 				mcast_opt = B_FALSE;
9635 				/* FALLTHRU */
9636 			case MCAST_JOIN_GROUP:
9637 				fmode = MODE_IS_EXCLUDE;
9638 				optfn = ip_opt_add_group;
9639 				break;
9640 
9641 			case IP_DROP_MEMBERSHIP:
9642 				mcast_opt = B_FALSE;
9643 				/* FALLTHRU */
9644 			case MCAST_LEAVE_GROUP:
9645 				fmode = MODE_IS_INCLUDE;
9646 				optfn = ip_opt_delete_group;
9647 				break;
9648 			}
9649 
9650 			if (mcast_opt) {
9651 				greqp = (struct group_req *)i1;
9652 				sin = (struct sockaddr_in *)&greqp->gr_group;
9653 				if (sin->sin_family != AF_INET) {
9654 					*outlenp = 0;
9655 					return (ENOPROTOOPT);
9656 				}
9657 				group = (ipaddr_t)sin->sin_addr.s_addr;
9658 				ifaddr = INADDR_ANY;
9659 				ifindexp = &greqp->gr_interface;
9660 			} else {
9661 				mreqp = (struct ip_mreq *)i1;
9662 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9663 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9664 				ifindexp = NULL;
9665 			}
9666 
9667 			/*
9668 			 * In the multirouting case, we need to replicate
9669 			 * the request on all interfaces that will take part
9670 			 * in replication.  We do so because multirouting is
9671 			 * reflective, thus we will probably receive multi-
9672 			 * casts on those interfaces.
9673 			 * The ip_multirt_apply_membership() succeeds if the
9674 			 * operation succeeds on at least one interface.
9675 			 */
9676 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9677 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9678 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9679 			if (ire != NULL) {
9680 				if (ire->ire_flags & RTF_MULTIRT) {
9681 					error = ip_multirt_apply_membership(
9682 					    optfn, ire, connp, checkonly, group,
9683 					    fmode, INADDR_ANY, first_mp);
9684 					done = B_TRUE;
9685 				}
9686 				ire_refrele(ire);
9687 			}
9688 			if (!done) {
9689 				error = optfn(connp, checkonly, group, ifaddr,
9690 				    ifindexp, fmode, INADDR_ANY, first_mp);
9691 			}
9692 			if (error) {
9693 				/*
9694 				 * EINPROGRESS is a soft error, needs retry
9695 				 * so don't make *outlenp zero.
9696 				 */
9697 				if (error != EINPROGRESS)
9698 					*outlenp = 0;
9699 				return (error);
9700 			}
9701 			/* OK return - copy input buffer into output buffer */
9702 			if (invalp != outvalp) {
9703 				/* don't trust bcopy for identical src/dst */
9704 				bcopy(invalp, outvalp, inlen);
9705 			}
9706 			*outlenp = inlen;
9707 			return (0);
9708 		}
9709 		case IP_BLOCK_SOURCE:
9710 		case IP_UNBLOCK_SOURCE:
9711 		case IP_ADD_SOURCE_MEMBERSHIP:
9712 		case IP_DROP_SOURCE_MEMBERSHIP:
9713 		case MCAST_BLOCK_SOURCE:
9714 		case MCAST_UNBLOCK_SOURCE:
9715 		case MCAST_JOIN_SOURCE_GROUP:
9716 		case MCAST_LEAVE_SOURCE_GROUP: {
9717 			struct ip_mreq_source *imreqp;
9718 			struct group_source_req *gsreqp;
9719 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9720 			uint32_t ifindex = 0;
9721 			mcast_record_t fmode;
9722 			struct sockaddr_in *sin;
9723 			ire_t *ire;
9724 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9725 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9726 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9727 
9728 			switch (name) {
9729 			case IP_BLOCK_SOURCE:
9730 				mcast_opt = B_FALSE;
9731 				/* FALLTHRU */
9732 			case MCAST_BLOCK_SOURCE:
9733 				fmode = MODE_IS_EXCLUDE;
9734 				optfn = ip_opt_add_group;
9735 				break;
9736 
9737 			case IP_UNBLOCK_SOURCE:
9738 				mcast_opt = B_FALSE;
9739 				/* FALLTHRU */
9740 			case MCAST_UNBLOCK_SOURCE:
9741 				fmode = MODE_IS_EXCLUDE;
9742 				optfn = ip_opt_delete_group;
9743 				break;
9744 
9745 			case IP_ADD_SOURCE_MEMBERSHIP:
9746 				mcast_opt = B_FALSE;
9747 				/* FALLTHRU */
9748 			case MCAST_JOIN_SOURCE_GROUP:
9749 				fmode = MODE_IS_INCLUDE;
9750 				optfn = ip_opt_add_group;
9751 				break;
9752 
9753 			case IP_DROP_SOURCE_MEMBERSHIP:
9754 				mcast_opt = B_FALSE;
9755 				/* FALLTHRU */
9756 			case MCAST_LEAVE_SOURCE_GROUP:
9757 				fmode = MODE_IS_INCLUDE;
9758 				optfn = ip_opt_delete_group;
9759 				break;
9760 			}
9761 
9762 			if (mcast_opt) {
9763 				gsreqp = (struct group_source_req *)i1;
9764 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9765 					*outlenp = 0;
9766 					return (ENOPROTOOPT);
9767 				}
9768 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9769 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9770 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9771 				src = (ipaddr_t)sin->sin_addr.s_addr;
9772 				ifindex = gsreqp->gsr_interface;
9773 			} else {
9774 				imreqp = (struct ip_mreq_source *)i1;
9775 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9776 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9777 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9778 			}
9779 
9780 			/*
9781 			 * In the multirouting case, we need to replicate
9782 			 * the request as noted in the mcast cases above.
9783 			 */
9784 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9785 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9786 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9787 			if (ire != NULL) {
9788 				if (ire->ire_flags & RTF_MULTIRT) {
9789 					error = ip_multirt_apply_membership(
9790 					    optfn, ire, connp, checkonly, grp,
9791 					    fmode, src, first_mp);
9792 					done = B_TRUE;
9793 				}
9794 				ire_refrele(ire);
9795 			}
9796 			if (!done) {
9797 				error = optfn(connp, checkonly, grp, ifaddr,
9798 				    &ifindex, fmode, src, first_mp);
9799 			}
9800 			if (error != 0) {
9801 				/*
9802 				 * EINPROGRESS is a soft error, needs retry
9803 				 * so don't make *outlenp zero.
9804 				 */
9805 				if (error != EINPROGRESS)
9806 					*outlenp = 0;
9807 				return (error);
9808 			}
9809 			/* OK return - copy input buffer into output buffer */
9810 			if (invalp != outvalp) {
9811 				bcopy(invalp, outvalp, inlen);
9812 			}
9813 			*outlenp = inlen;
9814 			return (0);
9815 		}
9816 		case IP_SEC_OPT:
9817 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9818 			if (error != 0) {
9819 				*outlenp = 0;
9820 				return (error);
9821 			}
9822 			break;
9823 		case IP_HDRINCL:
9824 		case IP_OPTIONS:
9825 		case T_IP_OPTIONS:
9826 		case IP_TOS:
9827 		case T_IP_TOS:
9828 		case IP_TTL:
9829 		case IP_RECVDSTADDR:
9830 		case IP_RECVOPTS:
9831 			/* OK return - copy input buffer into output buffer */
9832 			if (invalp != outvalp) {
9833 				/* don't trust bcopy for identical src/dst */
9834 				bcopy(invalp, outvalp, inlen);
9835 			}
9836 			*outlenp = inlen;
9837 			return (0);
9838 		case IP_RECVIF:
9839 			/* Retrieve the inbound interface index */
9840 			if (!checkonly) {
9841 				mutex_enter(&connp->conn_lock);
9842 				connp->conn_recvif = *i1 ? 1 : 0;
9843 				mutex_exit(&connp->conn_lock);
9844 			}
9845 			break;	/* goto sizeof (int) option return */
9846 		case IP_RECVSLLA:
9847 			/* Retrieve the source link layer address */
9848 			if (!checkonly) {
9849 				mutex_enter(&connp->conn_lock);
9850 				connp->conn_recvslla = *i1 ? 1 : 0;
9851 				mutex_exit(&connp->conn_lock);
9852 			}
9853 			break;	/* goto sizeof (int) option return */
9854 		case MRT_INIT:
9855 		case MRT_DONE:
9856 		case MRT_ADD_VIF:
9857 		case MRT_DEL_VIF:
9858 		case MRT_ADD_MFC:
9859 		case MRT_DEL_MFC:
9860 		case MRT_ASSERT:
9861 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9862 				*outlenp = 0;
9863 				return (error);
9864 			}
9865 			error = ip_mrouter_set((int)name, q, checkonly,
9866 			    (uchar_t *)invalp, inlen, first_mp);
9867 			if (error) {
9868 				*outlenp = 0;
9869 				return (error);
9870 			}
9871 			/* OK return - copy input buffer into output buffer */
9872 			if (invalp != outvalp) {
9873 				/* don't trust bcopy for identical src/dst */
9874 				bcopy(invalp, outvalp, inlen);
9875 			}
9876 			*outlenp = inlen;
9877 			return (0);
9878 		case IP_BOUND_IF:
9879 		case IP_XMIT_IF:
9880 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9881 			    level, name, first_mp);
9882 			if (error != 0)
9883 				return (error);
9884 			break; 		/* goto sizeof (int) option return */
9885 
9886 		case IP_UNSPEC_SRC:
9887 			/* Allow sending with a zero source address */
9888 			if (!checkonly) {
9889 				mutex_enter(&connp->conn_lock);
9890 				connp->conn_unspec_src = *i1 ? 1 : 0;
9891 				mutex_exit(&connp->conn_lock);
9892 			}
9893 			break;	/* goto sizeof (int) option return */
9894 		default:
9895 			/*
9896 			 * "soft" error (negative)
9897 			 * option not handled at this level
9898 			 * Note: Do not modify *outlenp
9899 			 */
9900 			return (-EINVAL);
9901 		}
9902 		break;
9903 	case IPPROTO_IPV6:
9904 		switch (name) {
9905 		case IPV6_BOUND_IF:
9906 		case IPV6_BOUND_PIF:
9907 		case IPV6_DONTFAILOVER_IF:
9908 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9909 			    level, name, first_mp);
9910 			if (error != 0)
9911 				return (error);
9912 			break; 		/* goto sizeof (int) option return */
9913 
9914 		case IPV6_MULTICAST_IF:
9915 			/*
9916 			 * The only possible errors are EINPROGRESS and
9917 			 * EINVAL. EINPROGRESS will be restarted and is not
9918 			 * a hard error. We call this option on both V4 and V6
9919 			 * If both return EINVAL, then this call returns
9920 			 * EINVAL. If at least one of them succeeds we
9921 			 * return success.
9922 			 */
9923 			found = B_FALSE;
9924 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9925 			    level, name, first_mp);
9926 			if (error == EINPROGRESS)
9927 				return (error);
9928 			if (error == 0)
9929 				found = B_TRUE;
9930 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9931 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9932 			if (error == 0)
9933 				found = B_TRUE;
9934 			if (!found)
9935 				return (error);
9936 			break; 		/* goto sizeof (int) option return */
9937 
9938 		case IPV6_MULTICAST_HOPS:
9939 			/* Recorded in transport above IP */
9940 			break;	/* goto sizeof (int) option return */
9941 		case IPV6_MULTICAST_LOOP:
9942 			if (!checkonly) {
9943 				mutex_enter(&connp->conn_lock);
9944 				connp->conn_multicast_loop = *i1;
9945 				mutex_exit(&connp->conn_lock);
9946 			}
9947 			break;	/* goto sizeof (int) option return */
9948 		case IPV6_JOIN_GROUP:
9949 		case MCAST_JOIN_GROUP:
9950 		case IPV6_LEAVE_GROUP:
9951 		case MCAST_LEAVE_GROUP: {
9952 			struct ipv6_mreq *ip_mreqp;
9953 			struct group_req *greqp;
9954 			ire_t *ire;
9955 			boolean_t done = B_FALSE;
9956 			in6_addr_t groupv6;
9957 			uint32_t ifindex;
9958 			boolean_t mcast_opt = B_TRUE;
9959 			mcast_record_t fmode;
9960 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9961 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9962 
9963 			switch (name) {
9964 			case IPV6_JOIN_GROUP:
9965 				mcast_opt = B_FALSE;
9966 				/* FALLTHRU */
9967 			case MCAST_JOIN_GROUP:
9968 				fmode = MODE_IS_EXCLUDE;
9969 				optfn = ip_opt_add_group_v6;
9970 				break;
9971 
9972 			case IPV6_LEAVE_GROUP:
9973 				mcast_opt = B_FALSE;
9974 				/* FALLTHRU */
9975 			case MCAST_LEAVE_GROUP:
9976 				fmode = MODE_IS_INCLUDE;
9977 				optfn = ip_opt_delete_group_v6;
9978 				break;
9979 			}
9980 
9981 			if (mcast_opt) {
9982 				struct sockaddr_in *sin;
9983 				struct sockaddr_in6 *sin6;
9984 				greqp = (struct group_req *)i1;
9985 				if (greqp->gr_group.ss_family == AF_INET) {
9986 					sin = (struct sockaddr_in *)
9987 					    &(greqp->gr_group);
9988 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9989 					    &groupv6);
9990 				} else {
9991 					sin6 = (struct sockaddr_in6 *)
9992 					    &(greqp->gr_group);
9993 					groupv6 = sin6->sin6_addr;
9994 				}
9995 				ifindex = greqp->gr_interface;
9996 			} else {
9997 				ip_mreqp = (struct ipv6_mreq *)i1;
9998 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9999 				ifindex = ip_mreqp->ipv6mr_interface;
10000 			}
10001 			/*
10002 			 * In the multirouting case, we need to replicate
10003 			 * the request on all interfaces that will take part
10004 			 * in replication.  We do so because multirouting is
10005 			 * reflective, thus we will probably receive multi-
10006 			 * casts on those interfaces.
10007 			 * The ip_multirt_apply_membership_v6() succeeds if
10008 			 * the operation succeeds on at least one interface.
10009 			 */
10010 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10011 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10012 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10013 			if (ire != NULL) {
10014 				if (ire->ire_flags & RTF_MULTIRT) {
10015 					error = ip_multirt_apply_membership_v6(
10016 					    optfn, ire, connp, checkonly,
10017 					    &groupv6, fmode, &ipv6_all_zeros,
10018 					    first_mp);
10019 					done = B_TRUE;
10020 				}
10021 				ire_refrele(ire);
10022 			}
10023 			if (!done) {
10024 				error = optfn(connp, checkonly, &groupv6,
10025 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10026 			}
10027 			if (error) {
10028 				/*
10029 				 * EINPROGRESS is a soft error, needs retry
10030 				 * so don't make *outlenp zero.
10031 				 */
10032 				if (error != EINPROGRESS)
10033 					*outlenp = 0;
10034 				return (error);
10035 			}
10036 			/* OK return - copy input buffer into output buffer */
10037 			if (invalp != outvalp) {
10038 				/* don't trust bcopy for identical src/dst */
10039 				bcopy(invalp, outvalp, inlen);
10040 			}
10041 			*outlenp = inlen;
10042 			return (0);
10043 		}
10044 		case MCAST_BLOCK_SOURCE:
10045 		case MCAST_UNBLOCK_SOURCE:
10046 		case MCAST_JOIN_SOURCE_GROUP:
10047 		case MCAST_LEAVE_SOURCE_GROUP: {
10048 			struct group_source_req *gsreqp;
10049 			in6_addr_t v6grp, v6src;
10050 			uint32_t ifindex;
10051 			mcast_record_t fmode;
10052 			ire_t *ire;
10053 			boolean_t done = B_FALSE;
10054 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10055 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10056 
10057 			switch (name) {
10058 			case MCAST_BLOCK_SOURCE:
10059 				fmode = MODE_IS_EXCLUDE;
10060 				optfn = ip_opt_add_group_v6;
10061 				break;
10062 			case MCAST_UNBLOCK_SOURCE:
10063 				fmode = MODE_IS_EXCLUDE;
10064 				optfn = ip_opt_delete_group_v6;
10065 				break;
10066 			case MCAST_JOIN_SOURCE_GROUP:
10067 				fmode = MODE_IS_INCLUDE;
10068 				optfn = ip_opt_add_group_v6;
10069 				break;
10070 			case MCAST_LEAVE_SOURCE_GROUP:
10071 				fmode = MODE_IS_INCLUDE;
10072 				optfn = ip_opt_delete_group_v6;
10073 				break;
10074 			}
10075 
10076 			gsreqp = (struct group_source_req *)i1;
10077 			ifindex = gsreqp->gsr_interface;
10078 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10079 				struct sockaddr_in *s;
10080 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10081 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10082 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10083 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10084 			} else {
10085 				struct sockaddr_in6 *s6;
10086 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10087 				v6grp = s6->sin6_addr;
10088 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10089 				v6src = s6->sin6_addr;
10090 			}
10091 
10092 			/*
10093 			 * In the multirouting case, we need to replicate
10094 			 * the request as noted in the mcast cases above.
10095 			 */
10096 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10097 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10098 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10099 			if (ire != NULL) {
10100 				if (ire->ire_flags & RTF_MULTIRT) {
10101 					error = ip_multirt_apply_membership_v6(
10102 					    optfn, ire, connp, checkonly,
10103 					    &v6grp, fmode, &v6src, first_mp);
10104 					done = B_TRUE;
10105 				}
10106 				ire_refrele(ire);
10107 			}
10108 			if (!done) {
10109 				error = optfn(connp, checkonly, &v6grp,
10110 				    ifindex, fmode, &v6src, first_mp);
10111 			}
10112 			if (error != 0) {
10113 				/*
10114 				 * EINPROGRESS is a soft error, needs retry
10115 				 * so don't make *outlenp zero.
10116 				 */
10117 				if (error != EINPROGRESS)
10118 					*outlenp = 0;
10119 				return (error);
10120 			}
10121 			/* OK return - copy input buffer into output buffer */
10122 			if (invalp != outvalp) {
10123 				bcopy(invalp, outvalp, inlen);
10124 			}
10125 			*outlenp = inlen;
10126 			return (0);
10127 		}
10128 		case IPV6_UNICAST_HOPS:
10129 			/* Recorded in transport above IP */
10130 			break;	/* goto sizeof (int) option return */
10131 		case IPV6_UNSPEC_SRC:
10132 			/* Allow sending with a zero source address */
10133 			if (!checkonly) {
10134 				mutex_enter(&connp->conn_lock);
10135 				connp->conn_unspec_src = *i1 ? 1 : 0;
10136 				mutex_exit(&connp->conn_lock);
10137 			}
10138 			break;	/* goto sizeof (int) option return */
10139 		case IPV6_RECVPKTINFO:
10140 			if (!checkonly) {
10141 				mutex_enter(&connp->conn_lock);
10142 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10143 				mutex_exit(&connp->conn_lock);
10144 			}
10145 			break;	/* goto sizeof (int) option return */
10146 		case IPV6_RECVTCLASS:
10147 			if (!checkonly) {
10148 				if (*i1 < 0 || *i1 > 1) {
10149 					return (EINVAL);
10150 				}
10151 				mutex_enter(&connp->conn_lock);
10152 				connp->conn_ipv6_recvtclass = *i1;
10153 				mutex_exit(&connp->conn_lock);
10154 			}
10155 			break;
10156 		case IPV6_RECVPATHMTU:
10157 			if (!checkonly) {
10158 				if (*i1 < 0 || *i1 > 1) {
10159 					return (EINVAL);
10160 				}
10161 				mutex_enter(&connp->conn_lock);
10162 				connp->conn_ipv6_recvpathmtu = *i1;
10163 				mutex_exit(&connp->conn_lock);
10164 			}
10165 			break;
10166 		case IPV6_RECVHOPLIMIT:
10167 			if (!checkonly) {
10168 				mutex_enter(&connp->conn_lock);
10169 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10170 				mutex_exit(&connp->conn_lock);
10171 			}
10172 			break;	/* goto sizeof (int) option return */
10173 		case IPV6_RECVHOPOPTS:
10174 			if (!checkonly) {
10175 				mutex_enter(&connp->conn_lock);
10176 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10177 				mutex_exit(&connp->conn_lock);
10178 			}
10179 			break;	/* goto sizeof (int) option return */
10180 		case IPV6_RECVDSTOPTS:
10181 			if (!checkonly) {
10182 				mutex_enter(&connp->conn_lock);
10183 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10184 				mutex_exit(&connp->conn_lock);
10185 			}
10186 			break;	/* goto sizeof (int) option return */
10187 		case IPV6_RECVRTHDR:
10188 			if (!checkonly) {
10189 				mutex_enter(&connp->conn_lock);
10190 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10191 				mutex_exit(&connp->conn_lock);
10192 			}
10193 			break;	/* goto sizeof (int) option return */
10194 		case IPV6_RECVRTHDRDSTOPTS:
10195 			if (!checkonly) {
10196 				mutex_enter(&connp->conn_lock);
10197 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10198 				mutex_exit(&connp->conn_lock);
10199 			}
10200 			break;	/* goto sizeof (int) option return */
10201 		case IPV6_PKTINFO:
10202 			if (inlen == 0)
10203 				return (-EINVAL);	/* clearing option */
10204 			error = ip6_set_pktinfo(cr, connp,
10205 			    (struct in6_pktinfo *)invalp, first_mp);
10206 			if (error != 0)
10207 				*outlenp = 0;
10208 			else
10209 				*outlenp = inlen;
10210 			return (error);
10211 		case IPV6_NEXTHOP: {
10212 			struct sockaddr_in6 *sin6;
10213 
10214 			/* Verify that the nexthop is reachable */
10215 			if (inlen == 0)
10216 				return (-EINVAL);	/* clearing option */
10217 
10218 			sin6 = (struct sockaddr_in6 *)invalp;
10219 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10220 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10221 			    MATCH_IRE_DEFAULT);
10222 
10223 			if (ire == NULL) {
10224 				*outlenp = 0;
10225 				return (EHOSTUNREACH);
10226 			}
10227 			ire_refrele(ire);
10228 			return (-EINVAL);
10229 		}
10230 		case IPV6_SEC_OPT:
10231 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10232 			if (error != 0) {
10233 				*outlenp = 0;
10234 				return (error);
10235 			}
10236 			break;
10237 		case IPV6_SRC_PREFERENCES: {
10238 			/*
10239 			 * This is implemented strictly in the ip module
10240 			 * (here and in tcp_opt_*() to accomodate tcp
10241 			 * sockets).  Modules above ip pass this option
10242 			 * down here since ip is the only one that needs to
10243 			 * be aware of source address preferences.
10244 			 *
10245 			 * This socket option only affects connected
10246 			 * sockets that haven't already bound to a specific
10247 			 * IPv6 address.  In other words, sockets that
10248 			 * don't call bind() with an address other than the
10249 			 * unspecified address and that call connect().
10250 			 * ip_bind_connected_v6() passes these preferences
10251 			 * to the ipif_select_source_v6() function.
10252 			 */
10253 			if (inlen != sizeof (uint32_t))
10254 				return (EINVAL);
10255 			error = ip6_set_src_preferences(connp,
10256 			    *(uint32_t *)invalp);
10257 			if (error != 0) {
10258 				*outlenp = 0;
10259 				return (error);
10260 			} else {
10261 				*outlenp = sizeof (uint32_t);
10262 			}
10263 			break;
10264 		}
10265 		case IPV6_V6ONLY:
10266 			if (*i1 < 0 || *i1 > 1) {
10267 				return (EINVAL);
10268 			}
10269 			mutex_enter(&connp->conn_lock);
10270 			connp->conn_ipv6_v6only = *i1;
10271 			mutex_exit(&connp->conn_lock);
10272 			break;
10273 		default:
10274 			return (-EINVAL);
10275 		}
10276 		break;
10277 	default:
10278 		/*
10279 		 * "soft" error (negative)
10280 		 * option not handled at this level
10281 		 * Note: Do not modify *outlenp
10282 		 */
10283 		return (-EINVAL);
10284 	}
10285 	/*
10286 	 * Common case of return from an option that is sizeof (int)
10287 	 */
10288 	*(int *)outvalp = *i1;
10289 	*outlenp = sizeof (int);
10290 	return (0);
10291 }
10292 
10293 /*
10294  * This routine gets default values of certain options whose default
10295  * values are maintained by protocol specific code
10296  */
10297 /* ARGSUSED */
10298 int
10299 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10300 {
10301 	int *i1 = (int *)ptr;
10302 
10303 	switch (level) {
10304 	case IPPROTO_IP:
10305 		switch (name) {
10306 		case IP_MULTICAST_TTL:
10307 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10308 			return (sizeof (uchar_t));
10309 		case IP_MULTICAST_LOOP:
10310 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10311 			return (sizeof (uchar_t));
10312 		default:
10313 			return (-1);
10314 		}
10315 	case IPPROTO_IPV6:
10316 		switch (name) {
10317 		case IPV6_UNICAST_HOPS:
10318 			*i1 = ipv6_def_hops;
10319 			return (sizeof (int));
10320 		case IPV6_MULTICAST_HOPS:
10321 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10322 			return (sizeof (int));
10323 		case IPV6_MULTICAST_LOOP:
10324 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10325 			return (sizeof (int));
10326 		case IPV6_V6ONLY:
10327 			*i1 = 1;
10328 			return (sizeof (int));
10329 		default:
10330 			return (-1);
10331 		}
10332 	default:
10333 		return (-1);
10334 	}
10335 	/* NOTREACHED */
10336 }
10337 
10338 /*
10339  * Given a destination address and a pointer to where to put the information
10340  * this routine fills in the mtuinfo.
10341  */
10342 int
10343 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10344     struct ip6_mtuinfo *mtuinfo)
10345 {
10346 	ire_t *ire;
10347 
10348 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10349 		return (-1);
10350 
10351 	bzero(mtuinfo, sizeof (*mtuinfo));
10352 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10353 	mtuinfo->ip6m_addr.sin6_port = port;
10354 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10355 
10356 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10357 	if (ire != NULL) {
10358 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10359 		ire_refrele(ire);
10360 	} else {
10361 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10362 	}
10363 	return (sizeof (struct ip6_mtuinfo));
10364 }
10365 
10366 /*
10367  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10368  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10369  * isn't.  This doesn't matter as the error checking is done properly for the
10370  * other MRT options coming in through ip_opt_set.
10371  */
10372 int
10373 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10374 {
10375 	conn_t		*connp = Q_TO_CONN(q);
10376 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10377 
10378 	switch (level) {
10379 	case IPPROTO_IP:
10380 		switch (name) {
10381 		case MRT_VERSION:
10382 		case MRT_ASSERT:
10383 			(void) ip_mrouter_get(name, q, ptr);
10384 			return (sizeof (int));
10385 		case IP_SEC_OPT:
10386 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10387 		case IP_NEXTHOP:
10388 			if (connp->conn_nexthop_set) {
10389 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10390 				return (sizeof (ipaddr_t));
10391 			} else
10392 				return (0);
10393 		default:
10394 			break;
10395 		}
10396 		break;
10397 	case IPPROTO_IPV6:
10398 		switch (name) {
10399 		case IPV6_SEC_OPT:
10400 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10401 		case IPV6_SRC_PREFERENCES: {
10402 			return (ip6_get_src_preferences(connp,
10403 			    (uint32_t *)ptr));
10404 		}
10405 		case IPV6_V6ONLY:
10406 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10407 			return (sizeof (int));
10408 		case IPV6_PATHMTU:
10409 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10410 				(struct ip6_mtuinfo *)ptr));
10411 		default:
10412 			break;
10413 		}
10414 		break;
10415 	default:
10416 		break;
10417 	}
10418 	return (-1);
10419 }
10420 
10421 /* Named Dispatch routine to get a current value out of our parameter table. */
10422 /* ARGSUSED */
10423 static int
10424 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10425 {
10426 	ipparam_t *ippa = (ipparam_t *)cp;
10427 
10428 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10429 	return (0);
10430 }
10431 
10432 /* ARGSUSED */
10433 static int
10434 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10435 {
10436 
10437 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10438 	return (0);
10439 }
10440 
10441 /*
10442  * Set ip{,6}_forwarding values.  This means walking through all of the
10443  * ill's and toggling their forwarding values.
10444  */
10445 /* ARGSUSED */
10446 static int
10447 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10448 {
10449 	long new_value;
10450 	int *forwarding_value = (int *)cp;
10451 	ill_t *walker;
10452 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10453 	ill_walk_context_t ctx;
10454 
10455 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10456 	    new_value < 0 || new_value > 1) {
10457 		return (EINVAL);
10458 	}
10459 
10460 	*forwarding_value = new_value;
10461 
10462 	/*
10463 	 * Regardless of the current value of ip_forwarding, set all per-ill
10464 	 * values of ip_forwarding to the value being set.
10465 	 *
10466 	 * Bring all the ill's up to date with the new global value.
10467 	 */
10468 	rw_enter(&ill_g_lock, RW_READER);
10469 
10470 	if (isv6)
10471 		walker = ILL_START_WALK_V6(&ctx);
10472 	else
10473 		walker = ILL_START_WALK_V4(&ctx);
10474 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10475 		(void) ill_forward_set(q, mp, (new_value != 0),
10476 		    (caddr_t)walker);
10477 	}
10478 	rw_exit(&ill_g_lock);
10479 
10480 	return (0);
10481 }
10482 
10483 /*
10484  * Walk through the param array specified registering each element with the
10485  * Named Dispatch handler. This is called only during init. So it is ok
10486  * not to acquire any locks
10487  */
10488 static boolean_t
10489 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10490     ipndp_t *ipnd, size_t ipnd_cnt)
10491 {
10492 	for (; ippa_cnt-- > 0; ippa++) {
10493 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10494 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10495 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10496 				nd_free(&ip_g_nd);
10497 				return (B_FALSE);
10498 			}
10499 		}
10500 	}
10501 
10502 	for (; ipnd_cnt-- > 0; ipnd++) {
10503 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10504 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10505 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10506 			    ipnd->ip_ndp_data)) {
10507 				nd_free(&ip_g_nd);
10508 				return (B_FALSE);
10509 			}
10510 		}
10511 	}
10512 
10513 	return (B_TRUE);
10514 }
10515 
10516 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10517 /* ARGSUSED */
10518 static int
10519 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10520 {
10521 	long		new_value;
10522 	ipparam_t	*ippa = (ipparam_t *)cp;
10523 
10524 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10525 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10526 		return (EINVAL);
10527 	}
10528 	ippa->ip_param_value = new_value;
10529 	return (0);
10530 }
10531 
10532 /*
10533  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10534  * When an ipf is passed here for the first time, if
10535  * we already have in-order fragments on the queue, we convert from the fast-
10536  * path reassembly scheme to the hard-case scheme.  From then on, additional
10537  * fragments are reassembled here.  We keep track of the start and end offsets
10538  * of each piece, and the number of holes in the chain.  When the hole count
10539  * goes to zero, we are done!
10540  *
10541  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10542  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10543  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10544  * after the call to ip_reassemble().
10545  */
10546 int
10547 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10548     size_t msg_len)
10549 {
10550 	uint_t	end;
10551 	mblk_t	*next_mp;
10552 	mblk_t	*mp1;
10553 	uint_t	offset;
10554 	boolean_t incr_dups = B_TRUE;
10555 	boolean_t offset_zero_seen = B_FALSE;
10556 	boolean_t pkt_boundary_checked = B_FALSE;
10557 
10558 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10559 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10560 
10561 	/* Add in byte count */
10562 	ipf->ipf_count += msg_len;
10563 	if (ipf->ipf_end) {
10564 		/*
10565 		 * We were part way through in-order reassembly, but now there
10566 		 * is a hole.  We walk through messages already queued, and
10567 		 * mark them for hard case reassembly.  We know that up till
10568 		 * now they were in order starting from offset zero.
10569 		 */
10570 		offset = 0;
10571 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10572 			IP_REASS_SET_START(mp1, offset);
10573 			if (offset == 0) {
10574 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10575 				offset = -ipf->ipf_nf_hdr_len;
10576 			}
10577 			offset += mp1->b_wptr - mp1->b_rptr;
10578 			IP_REASS_SET_END(mp1, offset);
10579 		}
10580 		/* One hole at the end. */
10581 		ipf->ipf_hole_cnt = 1;
10582 		/* Brand it as a hard case, forever. */
10583 		ipf->ipf_end = 0;
10584 	}
10585 	/* Walk through all the new pieces. */
10586 	do {
10587 		end = start + (mp->b_wptr - mp->b_rptr);
10588 		/*
10589 		 * If start is 0, decrease 'end' only for the first mblk of
10590 		 * the fragment. Otherwise 'end' can get wrong value in the
10591 		 * second pass of the loop if first mblk is exactly the
10592 		 * size of ipf_nf_hdr_len.
10593 		 */
10594 		if (start == 0 && !offset_zero_seen) {
10595 			/* First segment */
10596 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10597 			end -= ipf->ipf_nf_hdr_len;
10598 			offset_zero_seen = B_TRUE;
10599 		}
10600 		next_mp = mp->b_cont;
10601 		/*
10602 		 * We are checking to see if there is any interesing data
10603 		 * to process.  If there isn't and the mblk isn't the
10604 		 * one which carries the unfragmentable header then we
10605 		 * drop it.  It's possible to have just the unfragmentable
10606 		 * header come through without any data.  That needs to be
10607 		 * saved.
10608 		 *
10609 		 * If the assert at the top of this function holds then the
10610 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10611 		 * is infrequently traveled enough that the test is left in
10612 		 * to protect against future code changes which break that
10613 		 * invariant.
10614 		 */
10615 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10616 			/* Empty.  Blast it. */
10617 			IP_REASS_SET_START(mp, 0);
10618 			IP_REASS_SET_END(mp, 0);
10619 			/*
10620 			 * If the ipf points to the mblk we are about to free,
10621 			 * update ipf to point to the next mblk (or NULL
10622 			 * if none).
10623 			 */
10624 			if (ipf->ipf_mp->b_cont == mp)
10625 				ipf->ipf_mp->b_cont = next_mp;
10626 			freeb(mp);
10627 			continue;
10628 		}
10629 		mp->b_cont = NULL;
10630 		IP_REASS_SET_START(mp, start);
10631 		IP_REASS_SET_END(mp, end);
10632 		if (!ipf->ipf_tail_mp) {
10633 			ipf->ipf_tail_mp = mp;
10634 			ipf->ipf_mp->b_cont = mp;
10635 			if (start == 0 || !more) {
10636 				ipf->ipf_hole_cnt = 1;
10637 				/*
10638 				 * if the first fragment comes in more than one
10639 				 * mblk, this loop will be executed for each
10640 				 * mblk. Need to adjust hole count so exiting
10641 				 * this routine will leave hole count at 1.
10642 				 */
10643 				if (next_mp)
10644 					ipf->ipf_hole_cnt++;
10645 			} else
10646 				ipf->ipf_hole_cnt = 2;
10647 			continue;
10648 		} else if (ipf->ipf_last_frag_seen && !more &&
10649 			    !pkt_boundary_checked) {
10650 			/*
10651 			 * We check datagram boundary only if this fragment
10652 			 * claims to be the last fragment and we have seen a
10653 			 * last fragment in the past too. We do this only
10654 			 * once for a given fragment.
10655 			 *
10656 			 * start cannot be 0 here as fragments with start=0
10657 			 * and MF=0 gets handled as a complete packet. These
10658 			 * fragments should not reach here.
10659 			 */
10660 
10661 			if (start + msgdsize(mp) !=
10662 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10663 				/*
10664 				 * We have two fragments both of which claim
10665 				 * to be the last fragment but gives conflicting
10666 				 * information about the whole datagram size.
10667 				 * Something fishy is going on. Drop the
10668 				 * fragment and free up the reassembly list.
10669 				 */
10670 				return (IP_REASS_FAILED);
10671 			}
10672 
10673 			/*
10674 			 * We shouldn't come to this code block again for this
10675 			 * particular fragment.
10676 			 */
10677 			pkt_boundary_checked = B_TRUE;
10678 		}
10679 
10680 		/* New stuff at or beyond tail? */
10681 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10682 		if (start >= offset) {
10683 			if (ipf->ipf_last_frag_seen) {
10684 				/* current fragment is beyond last fragment */
10685 				return (IP_REASS_FAILED);
10686 			}
10687 			/* Link it on end. */
10688 			ipf->ipf_tail_mp->b_cont = mp;
10689 			ipf->ipf_tail_mp = mp;
10690 			if (more) {
10691 				if (start != offset)
10692 					ipf->ipf_hole_cnt++;
10693 			} else if (start == offset && next_mp == NULL)
10694 					ipf->ipf_hole_cnt--;
10695 			continue;
10696 		}
10697 		mp1 = ipf->ipf_mp->b_cont;
10698 		offset = IP_REASS_START(mp1);
10699 		/* New stuff at the front? */
10700 		if (start < offset) {
10701 			if (start == 0) {
10702 				if (end >= offset) {
10703 					/* Nailed the hole at the begining. */
10704 					ipf->ipf_hole_cnt--;
10705 				}
10706 			} else if (end < offset) {
10707 				/*
10708 				 * A hole, stuff, and a hole where there used
10709 				 * to be just a hole.
10710 				 */
10711 				ipf->ipf_hole_cnt++;
10712 			}
10713 			mp->b_cont = mp1;
10714 			/* Check for overlap. */
10715 			while (end > offset) {
10716 				if (end < IP_REASS_END(mp1)) {
10717 					mp->b_wptr -= end - offset;
10718 					IP_REASS_SET_END(mp, offset);
10719 					if (ill->ill_isv6) {
10720 						BUMP_MIB(ill->ill_ip6_mib,
10721 						    ipv6ReasmPartDups);
10722 					} else {
10723 						BUMP_MIB(&ip_mib,
10724 						    ipReasmPartDups);
10725 					}
10726 					break;
10727 				}
10728 				/* Did we cover another hole? */
10729 				if ((mp1->b_cont &&
10730 				    IP_REASS_END(mp1) !=
10731 				    IP_REASS_START(mp1->b_cont) &&
10732 				    end >= IP_REASS_START(mp1->b_cont)) ||
10733 				    (!ipf->ipf_last_frag_seen && !more)) {
10734 					ipf->ipf_hole_cnt--;
10735 				}
10736 				/* Clip out mp1. */
10737 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10738 					/*
10739 					 * After clipping out mp1, this guy
10740 					 * is now hanging off the end.
10741 					 */
10742 					ipf->ipf_tail_mp = mp;
10743 				}
10744 				IP_REASS_SET_START(mp1, 0);
10745 				IP_REASS_SET_END(mp1, 0);
10746 				/* Subtract byte count */
10747 				ipf->ipf_count -= mp1->b_datap->db_lim -
10748 				    mp1->b_datap->db_base;
10749 				freeb(mp1);
10750 				if (ill->ill_isv6) {
10751 					BUMP_MIB(ill->ill_ip6_mib,
10752 					    ipv6ReasmPartDups);
10753 				} else {
10754 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10755 				}
10756 				mp1 = mp->b_cont;
10757 				if (!mp1)
10758 					break;
10759 				offset = IP_REASS_START(mp1);
10760 			}
10761 			ipf->ipf_mp->b_cont = mp;
10762 			continue;
10763 		}
10764 		/*
10765 		 * The new piece starts somewhere between the start of the head
10766 		 * and before the end of the tail.
10767 		 */
10768 		for (; mp1; mp1 = mp1->b_cont) {
10769 			offset = IP_REASS_END(mp1);
10770 			if (start < offset) {
10771 				if (end <= offset) {
10772 					/* Nothing new. */
10773 					IP_REASS_SET_START(mp, 0);
10774 					IP_REASS_SET_END(mp, 0);
10775 					/* Subtract byte count */
10776 					ipf->ipf_count -= mp->b_datap->db_lim -
10777 					    mp->b_datap->db_base;
10778 					if (incr_dups) {
10779 						ipf->ipf_num_dups++;
10780 						incr_dups = B_FALSE;
10781 					}
10782 					freeb(mp);
10783 					if (ill->ill_isv6) {
10784 						BUMP_MIB(ill->ill_ip6_mib,
10785 						    ipv6ReasmDuplicates);
10786 					} else {
10787 						BUMP_MIB(&ip_mib,
10788 						    ipReasmDuplicates);
10789 					}
10790 					break;
10791 				}
10792 				/*
10793 				 * Trim redundant stuff off beginning of new
10794 				 * piece.
10795 				 */
10796 				IP_REASS_SET_START(mp, offset);
10797 				mp->b_rptr += offset - start;
10798 				if (ill->ill_isv6) {
10799 					BUMP_MIB(ill->ill_ip6_mib,
10800 					    ipv6ReasmPartDups);
10801 				} else {
10802 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10803 				}
10804 				start = offset;
10805 				if (!mp1->b_cont) {
10806 					/*
10807 					 * After trimming, this guy is now
10808 					 * hanging off the end.
10809 					 */
10810 					mp1->b_cont = mp;
10811 					ipf->ipf_tail_mp = mp;
10812 					if (!more) {
10813 						ipf->ipf_hole_cnt--;
10814 					}
10815 					break;
10816 				}
10817 			}
10818 			if (start >= IP_REASS_START(mp1->b_cont))
10819 				continue;
10820 			/* Fill a hole */
10821 			if (start > offset)
10822 				ipf->ipf_hole_cnt++;
10823 			mp->b_cont = mp1->b_cont;
10824 			mp1->b_cont = mp;
10825 			mp1 = mp->b_cont;
10826 			offset = IP_REASS_START(mp1);
10827 			if (end >= offset) {
10828 				ipf->ipf_hole_cnt--;
10829 				/* Check for overlap. */
10830 				while (end > offset) {
10831 					if (end < IP_REASS_END(mp1)) {
10832 						mp->b_wptr -= end - offset;
10833 						IP_REASS_SET_END(mp, offset);
10834 						/*
10835 						 * TODO we might bump
10836 						 * this up twice if there is
10837 						 * overlap at both ends.
10838 						 */
10839 						if (ill->ill_isv6) {
10840 							BUMP_MIB(
10841 							    ill->ill_ip6_mib,
10842 							    ipv6ReasmPartDups);
10843 						} else {
10844 							BUMP_MIB(&ip_mib,
10845 							    ipReasmPartDups);
10846 						}
10847 						break;
10848 					}
10849 					/* Did we cover another hole? */
10850 					if ((mp1->b_cont &&
10851 					    IP_REASS_END(mp1)
10852 					    != IP_REASS_START(mp1->b_cont) &&
10853 					    end >=
10854 					    IP_REASS_START(mp1->b_cont)) ||
10855 					    (!ipf->ipf_last_frag_seen &&
10856 					    !more)) {
10857 						ipf->ipf_hole_cnt--;
10858 					}
10859 					/* Clip out mp1. */
10860 					if ((mp->b_cont = mp1->b_cont) ==
10861 					    NULL) {
10862 						/*
10863 						 * After clipping out mp1,
10864 						 * this guy is now hanging
10865 						 * off the end.
10866 						 */
10867 						ipf->ipf_tail_mp = mp;
10868 					}
10869 					IP_REASS_SET_START(mp1, 0);
10870 					IP_REASS_SET_END(mp1, 0);
10871 					/* Subtract byte count */
10872 					ipf->ipf_count -=
10873 					    mp1->b_datap->db_lim -
10874 					    mp1->b_datap->db_base;
10875 					freeb(mp1);
10876 					if (ill->ill_isv6) {
10877 						BUMP_MIB(ill->ill_ip6_mib,
10878 						    ipv6ReasmPartDups);
10879 					} else {
10880 						BUMP_MIB(&ip_mib,
10881 						    ipReasmPartDups);
10882 					}
10883 					mp1 = mp->b_cont;
10884 					if (!mp1)
10885 						break;
10886 					offset = IP_REASS_START(mp1);
10887 				}
10888 			}
10889 			break;
10890 		}
10891 	} while (start = end, mp = next_mp);
10892 
10893 	/* Fragment just processed could be the last one. Remember this fact */
10894 	if (!more)
10895 		ipf->ipf_last_frag_seen = B_TRUE;
10896 
10897 	/* Still got holes? */
10898 	if (ipf->ipf_hole_cnt)
10899 		return (IP_REASS_PARTIAL);
10900 	/* Clean up overloaded fields to avoid upstream disasters. */
10901 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10902 		IP_REASS_SET_START(mp1, 0);
10903 		IP_REASS_SET_END(mp1, 0);
10904 	}
10905 	return (IP_REASS_COMPLETE);
10906 }
10907 
10908 /*
10909  * ipsec processing for the fast path, used for input UDP Packets
10910  */
10911 static boolean_t
10912 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10913     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10914 {
10915 	uint32_t	ill_index;
10916 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10917 
10918 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10919 	/* The ill_index of the incoming ILL */
10920 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10921 
10922 	/* pass packet up to the transport */
10923 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10924 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10925 		    NULL, mctl_present);
10926 		if (*first_mpp == NULL) {
10927 			return (B_FALSE);
10928 		}
10929 	}
10930 
10931 	/* Initiate IPPF processing for fastpath UDP */
10932 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10933 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10934 		if (*mpp == NULL) {
10935 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10936 			    "deferred/dropped during IPPF processing\n"));
10937 			return (B_FALSE);
10938 		}
10939 	}
10940 	/*
10941 	 * We make the checks as below since we are in the fast path
10942 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10943 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10944 	 */
10945 	if (connp->conn_recvif || connp->conn_recvslla ||
10946 	    connp->conn_ipv6_recvpktinfo) {
10947 		if (connp->conn_recvif ||
10948 		    connp->conn_ipv6_recvpktinfo) {
10949 			in_flags = IPF_RECVIF;
10950 		}
10951 		if (connp->conn_recvslla) {
10952 			in_flags |= IPF_RECVSLLA;
10953 		}
10954 		/*
10955 		 * since in_flags are being set ill will be
10956 		 * referenced in ip_add_info, so it better not
10957 		 * be NULL.
10958 		 */
10959 		/*
10960 		 * the actual data will be contained in b_cont
10961 		 * upon successful return of the following call.
10962 		 * If the call fails then the original mblk is
10963 		 * returned.
10964 		 */
10965 		*mpp = ip_add_info(*mpp, ill, in_flags);
10966 	}
10967 
10968 	return (B_TRUE);
10969 }
10970 
10971 /*
10972  * Fragmentation reassembly.  Each ILL has a hash table for
10973  * queuing packets undergoing reassembly for all IPIFs
10974  * associated with the ILL.  The hash is based on the packet
10975  * IP ident field.  The ILL frag hash table was allocated
10976  * as a timer block at the time the ILL was created.  Whenever
10977  * there is anything on the reassembly queue, the timer will
10978  * be running.  Returns B_TRUE if successful else B_FALSE;
10979  * frees mp on failure.
10980  */
10981 static boolean_t
10982 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
10983     uint32_t *cksum_val, uint16_t *cksum_flags)
10984 {
10985 	uint32_t	frag_offset_flags;
10986 	ill_t		*ill = (ill_t *)q->q_ptr;
10987 	mblk_t		*mp = *mpp;
10988 	mblk_t		*t_mp;
10989 	ipaddr_t	dst;
10990 	uint8_t		proto = ipha->ipha_protocol;
10991 	uint32_t	sum_val;
10992 	uint16_t	sum_flags;
10993 	ipf_t		*ipf;
10994 	ipf_t		**ipfp;
10995 	ipfb_t		*ipfb;
10996 	uint16_t	ident;
10997 	uint32_t	offset;
10998 	ipaddr_t	src;
10999 	uint_t		hdr_length;
11000 	uint32_t	end;
11001 	mblk_t		*mp1;
11002 	mblk_t		*tail_mp;
11003 	size_t		count;
11004 	size_t		msg_len;
11005 	uint8_t		ecn_info = 0;
11006 	uint32_t	packet_size;
11007 	boolean_t	pruned = B_FALSE;
11008 
11009 	if (cksum_val != NULL)
11010 		*cksum_val = 0;
11011 	if (cksum_flags != NULL)
11012 		*cksum_flags = 0;
11013 
11014 	/*
11015 	 * Drop the fragmented as early as possible, if
11016 	 * we don't have resource(s) to re-assemble.
11017 	 */
11018 	if (ip_reass_queue_bytes == 0) {
11019 		freemsg(mp);
11020 		return (B_FALSE);
11021 	}
11022 
11023 	/* Check for fragmentation offset; return if there's none */
11024 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11025 	    (IPH_MF | IPH_OFFSET)) == 0)
11026 		return (B_TRUE);
11027 
11028 	/*
11029 	 * We utilize hardware computed checksum info only for UDP since
11030 	 * IP fragmentation is a normal occurence for the protocol.  In
11031 	 * addition, checksum offload support for IP fragments carrying
11032 	 * UDP payload is commonly implemented across network adapters.
11033 	 */
11034 	ASSERT(ill != NULL);
11035 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11036 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11037 		mblk_t *mp1 = mp->b_cont;
11038 		int32_t len;
11039 
11040 		/* Record checksum information from the packet */
11041 		sum_val = (uint32_t)DB_CKSUM16(mp);
11042 		sum_flags = DB_CKSUMFLAGS(mp);
11043 
11044 		/* IP payload offset from beginning of mblk */
11045 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11046 
11047 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11048 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11049 		    offset >= DB_CKSUMSTART(mp) &&
11050 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11051 			uint32_t adj;
11052 			/*
11053 			 * Partial checksum has been calculated by hardware
11054 			 * and attached to the packet; in addition, any
11055 			 * prepended extraneous data is even byte aligned.
11056 			 * If any such data exists, we adjust the checksum;
11057 			 * this would also handle any postpended data.
11058 			 */
11059 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11060 			    mp, mp1, len, adj);
11061 
11062 			/* One's complement subtract extraneous checksum */
11063 			if (adj >= sum_val)
11064 				sum_val = ~(adj - sum_val) & 0xFFFF;
11065 			else
11066 				sum_val -= adj;
11067 		}
11068 	} else {
11069 		sum_val = 0;
11070 		sum_flags = 0;
11071 	}
11072 
11073 	/* Clear hardware checksumming flag */
11074 	DB_CKSUMFLAGS(mp) = 0;
11075 
11076 	ident = ipha->ipha_ident;
11077 	offset = (frag_offset_flags << 3) & 0xFFFF;
11078 	src = ipha->ipha_src;
11079 	dst = ipha->ipha_dst;
11080 	hdr_length = IPH_HDR_LENGTH(ipha);
11081 	end = ntohs(ipha->ipha_length) - hdr_length;
11082 
11083 	/* If end == 0 then we have a packet with no data, so just free it */
11084 	if (end == 0) {
11085 		freemsg(mp);
11086 		return (B_FALSE);
11087 	}
11088 
11089 	/* Record the ECN field info. */
11090 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11091 	if (offset != 0) {
11092 		/*
11093 		 * If this isn't the first piece, strip the header, and
11094 		 * add the offset to the end value.
11095 		 */
11096 		mp->b_rptr += hdr_length;
11097 		end += offset;
11098 	}
11099 
11100 	msg_len = MBLKSIZE(mp);
11101 	tail_mp = mp;
11102 	while (tail_mp->b_cont != NULL) {
11103 		tail_mp = tail_mp->b_cont;
11104 		msg_len += MBLKSIZE(tail_mp);
11105 	}
11106 
11107 	/* If the reassembly list for this ILL will get too big, prune it */
11108 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11109 	    ip_reass_queue_bytes) {
11110 		ill_frag_prune(ill,
11111 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11112 		    (ip_reass_queue_bytes - msg_len));
11113 		pruned = B_TRUE;
11114 	}
11115 
11116 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11117 	mutex_enter(&ipfb->ipfb_lock);
11118 
11119 	ipfp = &ipfb->ipfb_ipf;
11120 	/* Try to find an existing fragment queue for this packet. */
11121 	for (;;) {
11122 		ipf = ipfp[0];
11123 		if (ipf != NULL) {
11124 			/*
11125 			 * It has to match on ident and src/dst address.
11126 			 */
11127 			if (ipf->ipf_ident == ident &&
11128 			    ipf->ipf_src == src &&
11129 			    ipf->ipf_dst == dst &&
11130 			    ipf->ipf_protocol == proto) {
11131 				/*
11132 				 * If we have received too many
11133 				 * duplicate fragments for this packet
11134 				 * free it.
11135 				 */
11136 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11137 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11138 					freemsg(mp);
11139 					mutex_exit(&ipfb->ipfb_lock);
11140 					return (B_FALSE);
11141 				}
11142 				/* Found it. */
11143 				break;
11144 			}
11145 			ipfp = &ipf->ipf_hash_next;
11146 			continue;
11147 		}
11148 
11149 		/*
11150 		 * If we pruned the list, do we want to store this new
11151 		 * fragment?. We apply an optimization here based on the
11152 		 * fact that most fragments will be received in order.
11153 		 * So if the offset of this incoming fragment is zero,
11154 		 * it is the first fragment of a new packet. We will
11155 		 * keep it.  Otherwise drop the fragment, as we have
11156 		 * probably pruned the packet already (since the
11157 		 * packet cannot be found).
11158 		 */
11159 		if (pruned && offset != 0) {
11160 			mutex_exit(&ipfb->ipfb_lock);
11161 			freemsg(mp);
11162 			return (B_FALSE);
11163 		}
11164 
11165 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11166 			/*
11167 			 * Too many fragmented packets in this hash
11168 			 * bucket. Free the oldest.
11169 			 */
11170 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11171 		}
11172 
11173 		/* New guy.  Allocate a frag message. */
11174 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11175 		if (mp1 == NULL) {
11176 			BUMP_MIB(&ip_mib, ipInDiscards);
11177 			freemsg(mp);
11178 reass_done:
11179 			mutex_exit(&ipfb->ipfb_lock);
11180 			return (B_FALSE);
11181 		}
11182 
11183 
11184 		BUMP_MIB(&ip_mib, ipReasmReqds);
11185 		mp1->b_cont = mp;
11186 
11187 		/* Initialize the fragment header. */
11188 		ipf = (ipf_t *)mp1->b_rptr;
11189 		ipf->ipf_mp = mp1;
11190 		ipf->ipf_ptphn = ipfp;
11191 		ipfp[0] = ipf;
11192 		ipf->ipf_hash_next = NULL;
11193 		ipf->ipf_ident = ident;
11194 		ipf->ipf_protocol = proto;
11195 		ipf->ipf_src = src;
11196 		ipf->ipf_dst = dst;
11197 		ipf->ipf_nf_hdr_len = 0;
11198 		/* Record reassembly start time. */
11199 		ipf->ipf_timestamp = gethrestime_sec();
11200 		/* Record ipf generation and account for frag header */
11201 		ipf->ipf_gen = ill->ill_ipf_gen++;
11202 		ipf->ipf_count = MBLKSIZE(mp1);
11203 		ipf->ipf_last_frag_seen = B_FALSE;
11204 		ipf->ipf_ecn = ecn_info;
11205 		ipf->ipf_num_dups = 0;
11206 		ipfb->ipfb_frag_pkts++;
11207 		ipf->ipf_checksum = 0;
11208 		ipf->ipf_checksum_flags = 0;
11209 
11210 		/* Store checksum value in fragment header */
11211 		if (sum_flags != 0) {
11212 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11213 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11214 			ipf->ipf_checksum = sum_val;
11215 			ipf->ipf_checksum_flags = sum_flags;
11216 		}
11217 
11218 		/*
11219 		 * We handle reassembly two ways.  In the easy case,
11220 		 * where all the fragments show up in order, we do
11221 		 * minimal bookkeeping, and just clip new pieces on
11222 		 * the end.  If we ever see a hole, then we go off
11223 		 * to ip_reassemble which has to mark the pieces and
11224 		 * keep track of the number of holes, etc.  Obviously,
11225 		 * the point of having both mechanisms is so we can
11226 		 * handle the easy case as efficiently as possible.
11227 		 */
11228 		if (offset == 0) {
11229 			/* Easy case, in-order reassembly so far. */
11230 			ipf->ipf_count += msg_len;
11231 			ipf->ipf_tail_mp = tail_mp;
11232 			/*
11233 			 * Keep track of next expected offset in
11234 			 * ipf_end.
11235 			 */
11236 			ipf->ipf_end = end;
11237 			ipf->ipf_nf_hdr_len = hdr_length;
11238 		} else {
11239 			/* Hard case, hole at the beginning. */
11240 			ipf->ipf_tail_mp = NULL;
11241 			/*
11242 			 * ipf_end == 0 means that we have given up
11243 			 * on easy reassembly.
11244 			 */
11245 			ipf->ipf_end = 0;
11246 
11247 			/* Forget checksum offload from now on */
11248 			ipf->ipf_checksum_flags = 0;
11249 
11250 			/*
11251 			 * ipf_hole_cnt is set by ip_reassemble.
11252 			 * ipf_count is updated by ip_reassemble.
11253 			 * No need to check for return value here
11254 			 * as we don't expect reassembly to complete
11255 			 * or fail for the first fragment itself.
11256 			 */
11257 			(void) ip_reassemble(mp, ipf,
11258 			    (frag_offset_flags & IPH_OFFSET) << 3,
11259 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11260 		}
11261 		/* Update per ipfb and ill byte counts */
11262 		ipfb->ipfb_count += ipf->ipf_count;
11263 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11264 		ill->ill_frag_count += ipf->ipf_count;
11265 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11266 		/* If the frag timer wasn't already going, start it. */
11267 		mutex_enter(&ill->ill_lock);
11268 		ill_frag_timer_start(ill);
11269 		mutex_exit(&ill->ill_lock);
11270 		goto reass_done;
11271 	}
11272 
11273 	/*
11274 	 * If the packet's flag has changed (it could be coming up
11275 	 * from an interface different than the previous, therefore
11276 	 * possibly different checksum capability), then forget about
11277 	 * any stored checksum states.  Otherwise add the value to
11278 	 * the existing one stored in the fragment header.
11279 	 */
11280 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11281 		sum_val += ipf->ipf_checksum;
11282 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11283 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11284 		ipf->ipf_checksum = sum_val;
11285 	} else if (ipf->ipf_checksum_flags != 0) {
11286 		/* Forget checksum offload from now on */
11287 		ipf->ipf_checksum_flags = 0;
11288 	}
11289 
11290 	/*
11291 	 * We have a new piece of a datagram which is already being
11292 	 * reassembled.  Update the ECN info if all IP fragments
11293 	 * are ECN capable.  If there is one which is not, clear
11294 	 * all the info.  If there is at least one which has CE
11295 	 * code point, IP needs to report that up to transport.
11296 	 */
11297 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11298 		if (ecn_info == IPH_ECN_CE)
11299 			ipf->ipf_ecn = IPH_ECN_CE;
11300 	} else {
11301 		ipf->ipf_ecn = IPH_ECN_NECT;
11302 	}
11303 	if (offset && ipf->ipf_end == offset) {
11304 		/* The new fragment fits at the end */
11305 		ipf->ipf_tail_mp->b_cont = mp;
11306 		/* Update the byte count */
11307 		ipf->ipf_count += msg_len;
11308 		/* Update per ipfb and ill byte counts */
11309 		ipfb->ipfb_count += msg_len;
11310 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11311 		ill->ill_frag_count += msg_len;
11312 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11313 		if (frag_offset_flags & IPH_MF) {
11314 			/* More to come. */
11315 			ipf->ipf_end = end;
11316 			ipf->ipf_tail_mp = tail_mp;
11317 			goto reass_done;
11318 		}
11319 	} else {
11320 		/* Go do the hard cases. */
11321 		int ret;
11322 
11323 		if (offset == 0)
11324 			ipf->ipf_nf_hdr_len = hdr_length;
11325 
11326 		/* Save current byte count */
11327 		count = ipf->ipf_count;
11328 		ret = ip_reassemble(mp, ipf,
11329 		    (frag_offset_flags & IPH_OFFSET) << 3,
11330 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11331 		/* Count of bytes added and subtracted (freeb()ed) */
11332 		count = ipf->ipf_count - count;
11333 		if (count) {
11334 			/* Update per ipfb and ill byte counts */
11335 			ipfb->ipfb_count += count;
11336 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11337 			ill->ill_frag_count += count;
11338 			ASSERT(ill->ill_frag_count > 0);
11339 		}
11340 		if (ret == IP_REASS_PARTIAL) {
11341 			goto reass_done;
11342 		} else if (ret == IP_REASS_FAILED) {
11343 			/* Reassembly failed. Free up all resources */
11344 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11345 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11346 				IP_REASS_SET_START(t_mp, 0);
11347 				IP_REASS_SET_END(t_mp, 0);
11348 			}
11349 			freemsg(mp);
11350 			goto reass_done;
11351 		}
11352 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11353 	}
11354 	/*
11355 	 * We have completed reassembly.  Unhook the frag header from
11356 	 * the reassembly list.
11357 	 *
11358 	 * Before we free the frag header, record the ECN info
11359 	 * to report back to the transport.
11360 	 */
11361 	ecn_info = ipf->ipf_ecn;
11362 	BUMP_MIB(&ip_mib, ipReasmOKs);
11363 	ipfp = ipf->ipf_ptphn;
11364 
11365 	/* We need to supply these to caller */
11366 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11367 		sum_val = ipf->ipf_checksum;
11368 	else
11369 		sum_val = 0;
11370 
11371 	mp1 = ipf->ipf_mp;
11372 	count = ipf->ipf_count;
11373 	ipf = ipf->ipf_hash_next;
11374 	if (ipf != NULL)
11375 		ipf->ipf_ptphn = ipfp;
11376 	ipfp[0] = ipf;
11377 	ill->ill_frag_count -= count;
11378 	ASSERT(ipfb->ipfb_count >= count);
11379 	ipfb->ipfb_count -= count;
11380 	ipfb->ipfb_frag_pkts--;
11381 	mutex_exit(&ipfb->ipfb_lock);
11382 	/* Ditch the frag header. */
11383 	mp = mp1->b_cont;
11384 
11385 	freeb(mp1);
11386 
11387 	/* Restore original IP length in header. */
11388 	packet_size = (uint32_t)msgdsize(mp);
11389 	if (packet_size > IP_MAXPACKET) {
11390 		freemsg(mp);
11391 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11392 		return (B_FALSE);
11393 	}
11394 
11395 	if (DB_REF(mp) > 1) {
11396 		mblk_t *mp2 = copymsg(mp);
11397 
11398 		freemsg(mp);
11399 		if (mp2 == NULL) {
11400 			BUMP_MIB(&ip_mib, ipInDiscards);
11401 			return (B_FALSE);
11402 		}
11403 		mp = mp2;
11404 	}
11405 	ipha = (ipha_t *)mp->b_rptr;
11406 
11407 	ipha->ipha_length = htons((uint16_t)packet_size);
11408 	/* We're now complete, zip the frag state */
11409 	ipha->ipha_fragment_offset_and_flags = 0;
11410 	/* Record the ECN info. */
11411 	ipha->ipha_type_of_service &= 0xFC;
11412 	ipha->ipha_type_of_service |= ecn_info;
11413 	*mpp = mp;
11414 
11415 	/* Reassembly is successful; return checksum information if needed */
11416 	if (cksum_val != NULL)
11417 		*cksum_val = sum_val;
11418 	if (cksum_flags != NULL)
11419 		*cksum_flags = sum_flags;
11420 
11421 	return (B_TRUE);
11422 }
11423 
11424 /*
11425  * Perform ip header check sum update local options.
11426  * return B_TRUE if all is well, else return B_FALSE and release
11427  * the mp. caller is responsible for decrementing ire ref cnt.
11428  */
11429 static boolean_t
11430 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11431 {
11432 	mblk_t		*first_mp;
11433 	boolean_t	mctl_present;
11434 	uint16_t	sum;
11435 
11436 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11437 	/*
11438 	 * Don't do the checksum if it has gone through AH/ESP
11439 	 * processing.
11440 	 */
11441 	if (!mctl_present) {
11442 		sum = ip_csum_hdr(ipha);
11443 		if (sum != 0) {
11444 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11445 			freemsg(first_mp);
11446 			return (B_FALSE);
11447 		}
11448 	}
11449 
11450 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11451 		if (mctl_present)
11452 			freeb(first_mp);
11453 		return (B_FALSE);
11454 	}
11455 
11456 	return (B_TRUE);
11457 }
11458 
11459 /*
11460  * All udp packet are delivered to the local host via this routine.
11461  */
11462 void
11463 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11464     ill_t *recv_ill)
11465 {
11466 	uint32_t	sum;
11467 	uint32_t	u1;
11468 	boolean_t	mctl_present;
11469 	conn_t		*connp;
11470 	mblk_t		*first_mp;
11471 	uint16_t	*up;
11472 	ill_t		*ill = (ill_t *)q->q_ptr;
11473 	uint16_t	reass_hck_flags = 0;
11474 
11475 #define	rptr    ((uchar_t *)ipha)
11476 
11477 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11478 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11479 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11480 
11481 	/*
11482 	 * FAST PATH for udp packets
11483 	 */
11484 
11485 	/* u1 is # words of IP options */
11486 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11487 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11488 
11489 	/* IP options present */
11490 	if (u1 != 0)
11491 		goto ipoptions;
11492 
11493 	/* Check the IP header checksum.  */
11494 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11495 		/* Clear the IP header h/w cksum flag */
11496 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11497 	} else {
11498 #define	uph	((uint16_t *)ipha)
11499 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11500 		    uph[6] + uph[7] + uph[8] + uph[9];
11501 #undef	uph
11502 		/* finish doing IP checksum */
11503 		sum = (sum & 0xFFFF) + (sum >> 16);
11504 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11505 		/*
11506 		 * Don't verify header checksum if this packet is coming
11507 		 * back from AH/ESP as we already did it.
11508 		 */
11509 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
11510 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11511 			freemsg(first_mp);
11512 			return;
11513 		}
11514 	}
11515 
11516 	/*
11517 	 * Count for SNMP of inbound packets for ire.
11518 	 * if mctl is present this might be a secure packet and
11519 	 * has already been counted for in ip_proto_input().
11520 	 */
11521 	if (!mctl_present) {
11522 		UPDATE_IB_PKT_COUNT(ire);
11523 		ire->ire_last_used_time = lbolt;
11524 	}
11525 
11526 	/* packet part of fragmented IP packet? */
11527 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11528 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11529 		goto fragmented;
11530 	}
11531 
11532 	/* u1 = IP header length (20 bytes) */
11533 	u1 = IP_SIMPLE_HDR_LENGTH;
11534 
11535 	/* packet does not contain complete IP & UDP headers */
11536 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11537 		goto udppullup;
11538 
11539 	/* up points to UDP header */
11540 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11541 #define	iphs    ((uint16_t *)ipha)
11542 
11543 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11544 	if (up[3] != 0) {
11545 		mblk_t *mp1 = mp->b_cont;
11546 		boolean_t cksum_err;
11547 		uint16_t hck_flags = 0;
11548 
11549 		/* Pseudo-header checksum */
11550 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11551 		    iphs[9] + up[2];
11552 
11553 		/*
11554 		 * Revert to software checksum calculation if the interface
11555 		 * isn't capable of checksum offload or if IPsec is present.
11556 		 */
11557 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11558 			hck_flags = DB_CKSUMFLAGS(mp);
11559 
11560 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11561 			IP_STAT(ip_in_sw_cksum);
11562 
11563 		IP_CKSUM_RECV(hck_flags, u1,
11564 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11565 		    (int32_t)((uchar_t *)up - rptr),
11566 		    mp, mp1, cksum_err);
11567 
11568 		if (cksum_err) {
11569 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11570 
11571 			if (hck_flags & HCK_FULLCKSUM)
11572 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11573 			else if (hck_flags & HCK_PARTIALCKSUM)
11574 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11575 			else
11576 				IP_STAT(ip_udp_in_sw_cksum_err);
11577 
11578 			freemsg(first_mp);
11579 			return;
11580 		}
11581 	}
11582 
11583 	/* Non-fragmented broadcast or multicast packet? */
11584 	if (ire->ire_type == IRE_BROADCAST)
11585 		goto udpslowpath;
11586 
11587 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11588 	    ire->ire_zoneid)) != NULL) {
11589 		ASSERT(connp->conn_upq != NULL);
11590 		IP_STAT(ip_udp_fast_path);
11591 
11592 		if (CONN_UDP_FLOWCTLD(connp)) {
11593 			freemsg(mp);
11594 			BUMP_MIB(&ip_mib, udpInOverflows);
11595 		} else {
11596 			if (!mctl_present) {
11597 				BUMP_MIB(&ip_mib, ipInDelivers);
11598 			}
11599 			/*
11600 			 * mp and first_mp can change.
11601 			 */
11602 			if (ip_udp_check(q, connp, recv_ill,
11603 			    ipha, &mp, &first_mp, mctl_present)) {
11604 				/* Send it upstream */
11605 				CONN_UDP_RECV(connp, mp);
11606 			}
11607 		}
11608 		/*
11609 		 * freeb() cannot deal with null mblk being passed
11610 		 * in and first_mp can be set to null in the call
11611 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11612 		 */
11613 		if (mctl_present && first_mp != NULL) {
11614 			freeb(first_mp);
11615 		}
11616 		CONN_DEC_REF(connp);
11617 		return;
11618 	}
11619 
11620 	/*
11621 	 * if we got here we know the packet is not fragmented and
11622 	 * has no options. The classifier could not find a conn_t and
11623 	 * most likely its an icmp packet so send it through slow path.
11624 	 */
11625 
11626 	goto udpslowpath;
11627 
11628 ipoptions:
11629 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11630 		goto slow_done;
11631 	}
11632 
11633 	UPDATE_IB_PKT_COUNT(ire);
11634 	ire->ire_last_used_time = lbolt;
11635 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11636 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11637 fragmented:
11638 		/*
11639 		 * "sum" and "reass_hck_flags" are non-zero if the
11640 		 * reassembled packet has a valid hardware computed
11641 		 * checksum information associated with it.
11642 		 */
11643 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
11644 			goto slow_done;
11645 		/*
11646 		 * Make sure that first_mp points back to mp as
11647 		 * the mp we came in with could have changed in
11648 		 * ip_rput_fragment().
11649 		 */
11650 		ASSERT(!mctl_present);
11651 		ipha = (ipha_t *)mp->b_rptr;
11652 		first_mp = mp;
11653 	}
11654 
11655 	/* Now we have a complete datagram, destined for this machine. */
11656 	u1 = IPH_HDR_LENGTH(ipha);
11657 	/* Pull up the UDP header, if necessary. */
11658 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
11659 udppullup:
11660 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11661 			BUMP_MIB(&ip_mib, ipInDiscards);
11662 			freemsg(first_mp);
11663 			goto slow_done;
11664 		}
11665 		ipha = (ipha_t *)mp->b_rptr;
11666 	}
11667 
11668 	/*
11669 	 * Validate the checksum for the reassembled packet; for the
11670 	 * pullup case we calculate the payload checksum in software.
11671 	 */
11672 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11673 	if (up[3] != 0) {
11674 		boolean_t cksum_err;
11675 
11676 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11677 			IP_STAT(ip_in_sw_cksum);
11678 
11679 		IP_CKSUM_RECV_REASS(reass_hck_flags,
11680 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11681 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11682 		    iphs[9] + up[2], sum, cksum_err);
11683 
11684 		if (cksum_err) {
11685 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11686 
11687 			if (reass_hck_flags & HCK_FULLCKSUM)
11688 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11689 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
11690 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11691 			else
11692 				IP_STAT(ip_udp_in_sw_cksum_err);
11693 
11694 			freemsg(first_mp);
11695 			goto slow_done;
11696 		}
11697 	}
11698 udpslowpath:
11699 
11700 	/* Clear hardware checksum flag to be safe */
11701 	DB_CKSUMFLAGS(mp) = 0;
11702 
11703 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
11704 	    (ire->ire_type == IRE_BROADCAST),
11705 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11706 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11707 
11708 slow_done:
11709 	IP_STAT(ip_udp_slow_path);
11710 	return;
11711 
11712 #undef  iphs
11713 #undef  rptr
11714 }
11715 
11716 /* ARGSUSED */
11717 static mblk_t *
11718 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11719     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11720     ill_rx_ring_t *ill_ring)
11721 {
11722 	conn_t		*connp;
11723 	uint32_t	sum;
11724 	uint32_t	u1;
11725 	uint16_t	*up;
11726 	int		offset;
11727 	ssize_t		len;
11728 	mblk_t		*mp1;
11729 	boolean_t	syn_present = B_FALSE;
11730 	tcph_t		*tcph;
11731 	uint_t		ip_hdr_len;
11732 	ill_t		*ill = (ill_t *)q->q_ptr;
11733 	zoneid_t	zoneid = ire->ire_zoneid;
11734 	boolean_t	cksum_err;
11735 	uint16_t	hck_flags = 0;
11736 
11737 #define	rptr	((uchar_t *)ipha)
11738 
11739 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11740 
11741 	/*
11742 	 * FAST PATH for tcp packets
11743 	 */
11744 
11745 	/* u1 is # words of IP options */
11746 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11747 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11748 
11749 	/* IP options present */
11750 	if (u1) {
11751 		goto ipoptions;
11752 	} else {
11753 		/* Check the IP header checksum.  */
11754 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11755 			/* Clear the IP header h/w cksum flag */
11756 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11757 		} else {
11758 #define	uph	((uint16_t *)ipha)
11759 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11760 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11761 #undef	uph
11762 			/* finish doing IP checksum */
11763 			sum = (sum & 0xFFFF) + (sum >> 16);
11764 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11765 			/*
11766 			 * Don't verify header checksum if this packet
11767 			 * is coming back from AH/ESP as we already did it.
11768 			 */
11769 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11770 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11771 				goto error;
11772 			}
11773 		}
11774 	}
11775 
11776 	if (!mctl_present) {
11777 		UPDATE_IB_PKT_COUNT(ire);
11778 		ire->ire_last_used_time = lbolt;
11779 	}
11780 
11781 	/* packet part of fragmented IP packet? */
11782 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11783 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11784 		goto fragmented;
11785 	}
11786 
11787 	/* u1 = IP header length (20 bytes) */
11788 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11789 
11790 	/* does packet contain IP+TCP headers? */
11791 	len = mp->b_wptr - rptr;
11792 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11793 		IP_STAT(ip_tcppullup);
11794 		goto tcppullup;
11795 	}
11796 
11797 	/* TCP options present? */
11798 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11799 
11800 	/*
11801 	 * If options need to be pulled up, then goto tcpoptions.
11802 	 * otherwise we are still in the fast path
11803 	 */
11804 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11805 		IP_STAT(ip_tcpoptions);
11806 		goto tcpoptions;
11807 	}
11808 
11809 	/* multiple mblks of tcp data? */
11810 	if ((mp1 = mp->b_cont) != NULL) {
11811 		/* more then two? */
11812 		if (mp1->b_cont != NULL) {
11813 			IP_STAT(ip_multipkttcp);
11814 			goto multipkttcp;
11815 		}
11816 		len += mp1->b_wptr - mp1->b_rptr;
11817 	}
11818 
11819 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11820 
11821 	/* part of pseudo checksum */
11822 
11823 	/* TCP datagram length */
11824 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11825 
11826 #define	iphs    ((uint16_t *)ipha)
11827 
11828 #ifdef	_BIG_ENDIAN
11829 	u1 += IPPROTO_TCP;
11830 #else
11831 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11832 #endif
11833 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11834 
11835 	/*
11836 	 * Revert to software checksum calculation if the interface
11837 	 * isn't capable of checksum offload or if IPsec is present.
11838 	 */
11839 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11840 		hck_flags = DB_CKSUMFLAGS(mp);
11841 
11842 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11843 		IP_STAT(ip_in_sw_cksum);
11844 
11845 	IP_CKSUM_RECV(hck_flags, u1,
11846 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11847 	    (int32_t)((uchar_t *)up - rptr),
11848 	    mp, mp1, cksum_err);
11849 
11850 	if (cksum_err) {
11851 		BUMP_MIB(&ip_mib, tcpInErrs);
11852 
11853 		if (hck_flags & HCK_FULLCKSUM)
11854 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
11855 		else if (hck_flags & HCK_PARTIALCKSUM)
11856 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
11857 		else
11858 			IP_STAT(ip_tcp_in_sw_cksum_err);
11859 
11860 		goto error;
11861 	}
11862 
11863 try_again:
11864 
11865 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11866 	    NULL) {
11867 		/* Send the TH_RST */
11868 		goto no_conn;
11869 	}
11870 
11871 	/*
11872 	 * TCP FAST PATH for AF_INET socket.
11873 	 *
11874 	 * TCP fast path to avoid extra work. An AF_INET socket type
11875 	 * does not have facility to receive extra information via
11876 	 * ip_process or ip_add_info. Also, when the connection was
11877 	 * established, we made a check if this connection is impacted
11878 	 * by any global IPSec policy or per connection policy (a
11879 	 * policy that comes in effect later will not apply to this
11880 	 * connection). Since all this can be determined at the
11881 	 * connection establishment time, a quick check of flags
11882 	 * can avoid extra work.
11883 	 */
11884 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11885 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11886 		ASSERT(first_mp == mp);
11887 		SET_SQUEUE(mp, tcp_rput_data, connp);
11888 		return (mp);
11889 	}
11890 
11891 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11892 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11893 		if (IPCL_IS_TCP(connp)) {
11894 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11895 			DB_CKSUMSTART(mp) =
11896 			    (intptr_t)ip_squeue_get(ill_ring);
11897 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11898 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11899 				SET_SQUEUE(mp, connp->conn_recv, connp);
11900 				return (mp);
11901 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11902 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11903 				ip_squeue_enter_unbound++;
11904 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11905 				    connp);
11906 				return (mp);
11907 			}
11908 			syn_present = B_TRUE;
11909 		}
11910 
11911 	}
11912 
11913 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11914 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11915 
11916 		/* No need to send this packet to TCP */
11917 		if ((flags & TH_RST) || (flags & TH_URG)) {
11918 			CONN_DEC_REF(connp);
11919 			freemsg(first_mp);
11920 			return (NULL);
11921 		}
11922 		if (flags & TH_ACK) {
11923 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11924 			CONN_DEC_REF(connp);
11925 			return (NULL);
11926 		}
11927 
11928 		CONN_DEC_REF(connp);
11929 		freemsg(first_mp);
11930 		return (NULL);
11931 	}
11932 
11933 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11934 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11935 		    ipha, NULL, mctl_present);
11936 		if (first_mp == NULL) {
11937 			CONN_DEC_REF(connp);
11938 			return (NULL);
11939 		}
11940 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11941 			ASSERT(syn_present);
11942 			if (mctl_present) {
11943 				ASSERT(first_mp != mp);
11944 				first_mp->b_datap->db_struioflag |=
11945 				    STRUIO_POLICY;
11946 			} else {
11947 				ASSERT(first_mp == mp);
11948 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11949 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11950 			}
11951 		} else {
11952 			/*
11953 			 * Discard first_mp early since we're dealing with a
11954 			 * fully-connected conn_t and tcp doesn't do policy in
11955 			 * this case.
11956 			 */
11957 			if (mctl_present) {
11958 				freeb(first_mp);
11959 				mctl_present = B_FALSE;
11960 			}
11961 			first_mp = mp;
11962 		}
11963 	}
11964 
11965 	/* Initiate IPPF processing for fastpath */
11966 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11967 		uint32_t	ill_index;
11968 
11969 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11970 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11971 		if (mp == NULL) {
11972 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11973 			    "deferred/dropped during IPPF processing\n"));
11974 			CONN_DEC_REF(connp);
11975 			if (mctl_present)
11976 				freeb(first_mp);
11977 			return (NULL);
11978 		} else if (mctl_present) {
11979 			/*
11980 			 * ip_process might return a new mp.
11981 			 */
11982 			ASSERT(first_mp != mp);
11983 			first_mp->b_cont = mp;
11984 		} else {
11985 			first_mp = mp;
11986 		}
11987 
11988 	}
11989 
11990 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11991 		mp = ip_add_info(mp, recv_ill, flags);
11992 		if (mp == NULL) {
11993 			CONN_DEC_REF(connp);
11994 			if (mctl_present)
11995 				freeb(first_mp);
11996 			return (NULL);
11997 		} else if (mctl_present) {
11998 			/*
11999 			 * ip_add_info might return a new mp.
12000 			 */
12001 			ASSERT(first_mp != mp);
12002 			first_mp->b_cont = mp;
12003 		} else {
12004 			first_mp = mp;
12005 		}
12006 	}
12007 
12008 	if (IPCL_IS_TCP(connp)) {
12009 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12010 		return (first_mp);
12011 	} else {
12012 		putnext(connp->conn_rq, first_mp);
12013 		CONN_DEC_REF(connp);
12014 		return (NULL);
12015 	}
12016 
12017 no_conn:
12018 	/* Initiate IPPf processing, if needed. */
12019 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12020 		uint32_t ill_index;
12021 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12022 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12023 		if (first_mp == NULL) {
12024 			return (NULL);
12025 		}
12026 	}
12027 	BUMP_MIB(&ip_mib, ipInDelivers);
12028 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12029 	return (NULL);
12030 ipoptions:
12031 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12032 		goto slow_done;
12033 	}
12034 
12035 	UPDATE_IB_PKT_COUNT(ire);
12036 	ire->ire_last_used_time = lbolt;
12037 
12038 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12039 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12040 fragmented:
12041 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12042 			if (mctl_present)
12043 				freeb(first_mp);
12044 			goto slow_done;
12045 		}
12046 		/*
12047 		 * Make sure that first_mp points back to mp as
12048 		 * the mp we came in with could have changed in
12049 		 * ip_rput_fragment().
12050 		 */
12051 		ASSERT(!mctl_present);
12052 		ipha = (ipha_t *)mp->b_rptr;
12053 		first_mp = mp;
12054 	}
12055 
12056 tcp_slow:
12057 	/* Now we have a complete datagram, destined for this machine. */
12058 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12059 
12060 	len = mp->b_wptr - mp->b_rptr;
12061 	/* Pull up a minimal TCP header, if necessary. */
12062 	if (len < (u1 + 20)) {
12063 tcppullup:
12064 		if (!pullupmsg(mp, u1 + 20)) {
12065 			BUMP_MIB(&ip_mib, ipInDiscards);
12066 			goto error;
12067 		}
12068 		ipha = (ipha_t *)mp->b_rptr;
12069 		len = mp->b_wptr - mp->b_rptr;
12070 	}
12071 
12072 	/*
12073 	 * Extract the offset field from the TCP header.  As usual, we
12074 	 * try to help the compiler more than the reader.
12075 	 */
12076 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12077 	if (offset != 5) {
12078 tcpoptions:
12079 		if (offset < 5) {
12080 			BUMP_MIB(&ip_mib, ipInDiscards);
12081 			goto error;
12082 		}
12083 		/*
12084 		 * There must be TCP options.
12085 		 * Make sure we can grab them.
12086 		 */
12087 		offset <<= 2;
12088 		offset += u1;
12089 		if (len < offset) {
12090 			if (!pullupmsg(mp, offset)) {
12091 				BUMP_MIB(&ip_mib, ipInDiscards);
12092 				goto error;
12093 			}
12094 			ipha = (ipha_t *)mp->b_rptr;
12095 			len = mp->b_wptr - rptr;
12096 		}
12097 	}
12098 
12099 	/* Get the total packet length in len, including headers. */
12100 	if (mp->b_cont) {
12101 multipkttcp:
12102 		len = msgdsize(mp);
12103 	}
12104 
12105 	/*
12106 	 * Check the TCP checksum by pulling together the pseudo-
12107 	 * header checksum, and passing it to ip_csum to be added in
12108 	 * with the TCP datagram.
12109 	 *
12110 	 * Since we are not using the hwcksum if available we must
12111 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12112 	 * If either of these fails along the way the mblk is freed.
12113 	 * If this logic ever changes and mblk is reused to say send
12114 	 * ICMP's back, then this flag may need to be cleared in
12115 	 * other places as well.
12116 	 */
12117 	DB_CKSUMFLAGS(mp) = 0;
12118 
12119 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12120 
12121 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12122 #ifdef	_BIG_ENDIAN
12123 	u1 += IPPROTO_TCP;
12124 #else
12125 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12126 #endif
12127 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12128 	/*
12129 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12130 	 */
12131 	IP_STAT(ip_in_sw_cksum);
12132 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12133 		BUMP_MIB(&ip_mib, tcpInErrs);
12134 		goto error;
12135 	}
12136 
12137 	IP_STAT(ip_tcp_slow_path);
12138 	goto try_again;
12139 #undef  iphs
12140 #undef  rptr
12141 
12142 error:
12143 	freemsg(first_mp);
12144 slow_done:
12145 	return (NULL);
12146 }
12147 
12148 /* ARGSUSED */
12149 static void
12150 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12151     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12152 {
12153 	conn_t		*connp;
12154 	uint32_t	sum;
12155 	uint32_t	u1;
12156 	ssize_t		len;
12157 	sctp_hdr_t	*sctph;
12158 	zoneid_t	zoneid = ire->ire_zoneid;
12159 	uint32_t	pktsum;
12160 	uint32_t	calcsum;
12161 	uint32_t	ports;
12162 	uint_t		ipif_seqid;
12163 	in6_addr_t	map_src, map_dst;
12164 	ill_t		*ill = (ill_t *)q->q_ptr;
12165 
12166 #define	rptr	((uchar_t *)ipha)
12167 
12168 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12169 
12170 	/* u1 is # words of IP options */
12171 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12172 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12173 
12174 	/* IP options present */
12175 	if (u1 > 0) {
12176 		goto ipoptions;
12177 	} else {
12178 		/* Check the IP header checksum.  */
12179 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12180 			/*
12181 			 * Since there is no SCTP h/w cksum support yet, just
12182 			 * clear the flag.
12183 			 */
12184 			DB_CKSUMFLAGS(mp) = 0;
12185 		} else {
12186 #define	uph	((uint16_t *)ipha)
12187 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12188 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12189 #undef	uph
12190 			/* finish doing IP checksum */
12191 			sum = (sum & 0xFFFF) + (sum >> 16);
12192 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12193 			/*
12194 			 * Don't verify header checksum if this packet
12195 			 * is coming back from AH/ESP as we already did it.
12196 			 */
12197 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12198 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12199 				goto error;
12200 			}
12201 		}
12202 	}
12203 
12204 	/*
12205 	 * Don't verify header checksum if this packet is coming
12206 	 * back from AH/ESP as we already did it.
12207 	 */
12208 	if (!mctl_present) {
12209 		UPDATE_IB_PKT_COUNT(ire);
12210 		ire->ire_last_used_time = lbolt;
12211 	}
12212 
12213 	/* packet part of fragmented IP packet? */
12214 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12215 	if (u1 & (IPH_MF | IPH_OFFSET))
12216 		goto fragmented;
12217 
12218 	/* u1 = IP header length (20 bytes) */
12219 	u1 = IP_SIMPLE_HDR_LENGTH;
12220 
12221 find_sctp_client:
12222 	/* Pullup if we don't have the sctp common header. */
12223 	len = MBLKL(mp);
12224 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12225 		if (mp->b_cont == NULL ||
12226 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12227 			BUMP_MIB(&ip_mib, ipInDiscards);
12228 			goto error;
12229 		}
12230 		ipha = (ipha_t *)mp->b_rptr;
12231 		len = MBLKL(mp);
12232 	}
12233 
12234 	sctph = (sctp_hdr_t *)(rptr + u1);
12235 #ifdef	DEBUG
12236 	if (!skip_sctp_cksum) {
12237 #endif
12238 		pktsum = sctph->sh_chksum;
12239 		sctph->sh_chksum = 0;
12240 		calcsum = sctp_cksum(mp, u1);
12241 		if (calcsum != pktsum) {
12242 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12243 			goto error;
12244 		}
12245 		sctph->sh_chksum = pktsum;
12246 #ifdef	DEBUG	/* skip_sctp_cksum */
12247 	}
12248 #endif
12249 	/* get the ports */
12250 	ports = *(uint32_t *)&sctph->sh_sport;
12251 
12252 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12253 	IRE_REFRELE(ire);
12254 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12255 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12256 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12257 	    zoneid)) == NULL) {
12258 		/* Check for raw socket or OOTB handling */
12259 		goto no_conn;
12260 	}
12261 
12262 	/* Found a client; up it goes */
12263 	BUMP_MIB(&ip_mib, ipInDelivers);
12264 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12265 	return;
12266 
12267 no_conn:
12268 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12269 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12270 	return;
12271 
12272 ipoptions:
12273 	DB_CKSUMFLAGS(mp) = 0;
12274 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12275 		goto slow_done;
12276 
12277 	UPDATE_IB_PKT_COUNT(ire);
12278 	ire->ire_last_used_time = lbolt;
12279 
12280 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12281 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12282 fragmented:
12283 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12284 			goto slow_done;
12285 		/*
12286 		 * Make sure that first_mp points back to mp as
12287 		 * the mp we came in with could have changed in
12288 		 * ip_rput_fragment().
12289 		 */
12290 		ASSERT(!mctl_present);
12291 		ipha = (ipha_t *)mp->b_rptr;
12292 		first_mp = mp;
12293 	}
12294 
12295 	/* Now we have a complete datagram, destined for this machine. */
12296 	u1 = IPH_HDR_LENGTH(ipha);
12297 	goto find_sctp_client;
12298 #undef  iphs
12299 #undef  rptr
12300 
12301 error:
12302 	freemsg(first_mp);
12303 slow_done:
12304 	IRE_REFRELE(ire);
12305 }
12306 
12307 #define	VER_BITS	0xF0
12308 #define	VERSION_6	0x60
12309 
12310 static boolean_t
12311 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12312     ipaddr_t *dstp)
12313 {
12314 	uint_t	opt_len;
12315 	ipha_t *ipha;
12316 	ssize_t len;
12317 	uint_t	pkt_len;
12318 
12319 	IP_STAT(ip_ipoptions);
12320 	ipha = *iphapp;
12321 
12322 #define	rptr    ((uchar_t *)ipha)
12323 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12324 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12325 		BUMP_MIB(&ip_mib, ipInIPv6);
12326 		freemsg(mp);
12327 		return (B_FALSE);
12328 	}
12329 
12330 	/* multiple mblk or too short */
12331 	pkt_len = ntohs(ipha->ipha_length);
12332 
12333 	/* Get the number of words of IP options in the IP header. */
12334 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12335 	if (opt_len) {
12336 		/* IP Options present!  Validate and process. */
12337 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12338 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12339 			goto done;
12340 		}
12341 		/*
12342 		 * Recompute complete header length and make sure we
12343 		 * have access to all of it.
12344 		 */
12345 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12346 		if (len > (mp->b_wptr - rptr)) {
12347 			if (len > pkt_len) {
12348 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12349 				goto done;
12350 			}
12351 			if (!pullupmsg(mp, len)) {
12352 				BUMP_MIB(&ip_mib, ipInDiscards);
12353 				goto done;
12354 			}
12355 			ipha = (ipha_t *)mp->b_rptr;
12356 		}
12357 		/*
12358 		 * Go off to ip_rput_options which returns the next hop
12359 		 * destination address, which may have been affected
12360 		 * by source routing.
12361 		 */
12362 		IP_STAT(ip_opt);
12363 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12364 			return (B_FALSE);
12365 		}
12366 	}
12367 	*iphapp = ipha;
12368 	return (B_TRUE);
12369 done:
12370 	/* clear b_prev - used by ip_mroute_decap */
12371 	mp->b_prev = NULL;
12372 	freemsg(mp);
12373 	return (B_FALSE);
12374 #undef  rptr
12375 }
12376 
12377 /*
12378  * Deal with the fact that there is no ire for the destination.
12379  * The incoming ill (in_ill) is passed in to ip_newroute only
12380  * in the case of packets coming from mobile ip forward tunnel.
12381  * It must be null otherwise.
12382  */
12383 static void
12384 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12385     ipaddr_t dst)
12386 {
12387 	ipha_t	*ipha;
12388 	ill_t	*ill;
12389 
12390 	ipha = (ipha_t *)mp->b_rptr;
12391 	ill = (ill_t *)q->q_ptr;
12392 
12393 	ASSERT(ill != NULL);
12394 	/*
12395 	 * No IRE for this destination, so it can't be for us.
12396 	 * Unless we are forwarding, drop the packet.
12397 	 * We have to let source routed packets through
12398 	 * since we don't yet know if they are 'ping -l'
12399 	 * packets i.e. if they will go out over the
12400 	 * same interface as they came in on.
12401 	 */
12402 	if (ll_multicast) {
12403 		freemsg(mp);
12404 		return;
12405 	}
12406 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12407 		BUMP_MIB(&ip_mib, ipForwProhibits);
12408 		freemsg(mp);
12409 		return;
12410 	}
12411 
12412 	/* Check for Martian addresses */
12413 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12414 		freemsg(mp);
12415 		return;
12416 	}
12417 
12418 	/* Mark this packet as having originated externally */
12419 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12420 
12421 	/*
12422 	 * Clear the indication that this may have a hardware checksum
12423 	 * as we are not using it
12424 	 */
12425 	DB_CKSUMFLAGS(mp) = 0;
12426 
12427 	/*
12428 	 * Now hand the packet to ip_newroute.
12429 	 */
12430 	ip_newroute(q, mp, dst, in_ill, NULL);
12431 }
12432 
12433 /*
12434  * check ip header length and align it.
12435  */
12436 static boolean_t
12437 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12438 {
12439 	ssize_t len;
12440 	ill_t *ill;
12441 	ipha_t	*ipha;
12442 
12443 	len = MBLKL(mp);
12444 
12445 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12446 		if (!OK_32PTR(mp->b_rptr))
12447 			IP_STAT(ip_notaligned1);
12448 		else
12449 			IP_STAT(ip_notaligned2);
12450 		/* Guard against bogus device drivers */
12451 		if (len < 0) {
12452 			/* clear b_prev - used by ip_mroute_decap */
12453 			mp->b_prev = NULL;
12454 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12455 			freemsg(mp);
12456 			return (B_FALSE);
12457 		}
12458 
12459 		if (ip_rput_pullups++ == 0) {
12460 			ill = (ill_t *)q->q_ptr;
12461 			ipha = (ipha_t *)mp->b_rptr;
12462 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12463 			    "ip_check_and_align_header: %s forced us to "
12464 			    " pullup pkt, hdr len %ld, hdr addr %p",
12465 			    ill->ill_name, len, ipha);
12466 		}
12467 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12468 			/* clear b_prev - used by ip_mroute_decap */
12469 			mp->b_prev = NULL;
12470 			BUMP_MIB(&ip_mib, ipInDiscards);
12471 			freemsg(mp);
12472 			return (B_FALSE);
12473 		}
12474 	}
12475 	return (B_TRUE);
12476 }
12477 
12478 static boolean_t
12479 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12480 {
12481 	ill_group_t	*ill_group;
12482 	ill_group_t	*ire_group;
12483 	queue_t 	*q;
12484 	ill_t		*ire_ill;
12485 	uint_t		ill_ifindex;
12486 
12487 	q = *qp;
12488 	/*
12489 	 * We need to check to make sure the packet came in
12490 	 * on the queue associated with the destination IRE.
12491 	 * Note that for multicast packets and broadcast packets sent to
12492 	 * a broadcast address which is shared between multiple interfaces
12493 	 * we should not do this since we just got a random broadcast ire.
12494 	 */
12495 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12496 		boolean_t check_multi = B_TRUE;
12497 
12498 		/*
12499 		 * This packet came in on an interface other than the
12500 		 * one associated with the destination address.
12501 		 * "Gateway" it to the appropriate interface here.
12502 		 * As long as the ills belong to the same group,
12503 		 * we don't consider them to arriving on the wrong
12504 		 * interface. Thus, when the switch is doing inbound
12505 		 * load spreading, we won't drop packets when we
12506 		 * are doing strict multihoming checks. Note, the
12507 		 * same holds true for 'usesrc groups' where the
12508 		 * destination address may belong to another interface
12509 		 * to allow multipathing to happen
12510 		 */
12511 		ill_group = ill->ill_group;
12512 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12513 		ill_ifindex = ill->ill_usesrc_ifindex;
12514 		ire_group = ire_ill->ill_group;
12515 
12516 		/*
12517 		 * If it's part of the same IPMP group, or if it's a legal
12518 		 * address on the 'usesrc' interface, then bypass strict
12519 		 * checks.
12520 		 */
12521 		if (ill_group != NULL && ill_group == ire_group) {
12522 			check_multi = B_FALSE;
12523 		} else if (ill_ifindex != 0 &&
12524 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12525 			check_multi = B_FALSE;
12526 		}
12527 
12528 		if (check_multi &&
12529 		    ip_strict_dst_multihoming &&
12530 		    ((ill->ill_flags &
12531 		    ire->ire_ipif->ipif_ill->ill_flags &
12532 		    ILLF_ROUTER) == 0)) {
12533 			/* Drop packet */
12534 			BUMP_MIB(&ip_mib, ipForwProhibits);
12535 			freemsg(mp);
12536 			ire_refrele(ire);
12537 			return (B_TRUE);
12538 		}
12539 
12540 		/*
12541 		 * Change the queue (for non-virtual destination network
12542 		 * interfaces) and ip_rput_local will be called with the right
12543 		 * queue
12544 		 */
12545 		q = ire->ire_rfq;
12546 	}
12547 	/* Must be broadcast.  We'll take it. */
12548 	*qp = q;
12549 	return (B_FALSE);
12550 }
12551 
12552 static void
12553 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12554     ill_t *ill, int ll_multicast)
12555 {
12556 	ill_group_t	*ill_group;
12557 	ill_group_t	*ire_group;
12558 	queue_t	*dev_q;
12559 
12560 	ASSERT(ire->ire_stq != NULL);
12561 	if (ll_multicast != 0)
12562 		goto drop_pkt;
12563 
12564 	if (ip_no_forward(ipha, ill))
12565 		goto drop_pkt;
12566 
12567 	ill_group = ill->ill_group;
12568 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12569 	/*
12570 	 * Check if we want to forward this one at this time.
12571 	 * We allow source routed packets on a host provided that
12572 	 * they go out the same interface or same interface group
12573 	 * as they came in on.
12574 	 *
12575 	 * XXX To be quicker, we may wish to not chase pointers to
12576 	 * get the ILLF_ROUTER flag and instead store the
12577 	 * forwarding policy in the ire.  An unfortunate
12578 	 * side-effect of that would be requiring an ire flush
12579 	 * whenever the ILLF_ROUTER flag changes.
12580 	 */
12581 	if (((ill->ill_flags &
12582 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12583 	    ILLF_ROUTER) == 0) &&
12584 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12585 	    (ill_group != NULL && ill_group == ire_group)))) {
12586 		BUMP_MIB(&ip_mib, ipForwProhibits);
12587 		if (ip_source_routed(ipha)) {
12588 			q = WR(q);
12589 			/*
12590 			 * Clear the indication that this may have
12591 			 * hardware checksum as we are not using it.
12592 			 */
12593 			DB_CKSUMFLAGS(mp) = 0;
12594 			icmp_unreachable(q, mp,
12595 			    ICMP_SOURCE_ROUTE_FAILED);
12596 			ire_refrele(ire);
12597 			return;
12598 		}
12599 		goto drop_pkt;
12600 	}
12601 
12602 	/* Packet is being forwarded. Turning off hwcksum flag. */
12603 	DB_CKSUMFLAGS(mp) = 0;
12604 	if (ip_g_send_redirects) {
12605 		/*
12606 		 * Check whether the incoming interface and outgoing
12607 		 * interface is part of the same group. If so,
12608 		 * send redirects.
12609 		 *
12610 		 * Check the source address to see if it originated
12611 		 * on the same logical subnet it is going back out on.
12612 		 * If so, we should be able to send it a redirect.
12613 		 * Avoid sending a redirect if the destination
12614 		 * is directly connected (gw_addr == 0),
12615 		 * or if the packet was source routed out this
12616 		 * interface.
12617 		 */
12618 		ipaddr_t src;
12619 		mblk_t	*mp1;
12620 		ire_t	*src_ire = NULL;
12621 
12622 		/*
12623 		 * Check whether ire_rfq and q are from the same ill
12624 		 * or if they are not same, they at least belong
12625 		 * to the same group. If so, send redirects.
12626 		 */
12627 		if ((ire->ire_rfq == q ||
12628 		    (ill_group != NULL && ill_group == ire_group)) &&
12629 		    (ire->ire_gateway_addr != 0) &&
12630 		    !ip_source_routed(ipha)) {
12631 
12632 			src = ipha->ipha_src;
12633 			src_ire = ire_ftable_lookup(src, 0, 0,
12634 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12635 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12636 
12637 			if (src_ire != NULL) {
12638 				/*
12639 				 * The source is directly connected.
12640 				 * Just copy the ip header (which is
12641 				 * in the first mblk)
12642 				 */
12643 				mp1 = copyb(mp);
12644 				if (mp1 != NULL) {
12645 					icmp_send_redirect(WR(q), mp1,
12646 					    ire->ire_gateway_addr);
12647 				}
12648 				ire_refrele(src_ire);
12649 			}
12650 		}
12651 	}
12652 
12653 	dev_q = ire->ire_stq->q_next;
12654 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12655 		BUMP_MIB(&ip_mib, ipInDiscards);
12656 		freemsg(mp);
12657 		ire_refrele(ire);
12658 		return;
12659 	}
12660 
12661 	ip_rput_forward(ire, ipha, mp, ill);
12662 	IRE_REFRELE(ire);
12663 	return;
12664 
12665 drop_pkt:
12666 	ire_refrele(ire);
12667 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12668 	freemsg(mp);
12669 }
12670 
12671 static boolean_t
12672 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12673     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12674 {
12675 	queue_t		*q;
12676 	ire_t		*ire;
12677 	uint16_t	hcksumflags;
12678 
12679 	q = *qp;
12680 	ire = *irep;
12681 
12682 	/*
12683 	 * Clear the indication that this may have hardware
12684 	 * checksum as we are not using it for forwarding.
12685 	 */
12686 	hcksumflags = DB_CKSUMFLAGS(mp);
12687 	DB_CKSUMFLAGS(mp) = 0;
12688 
12689 	/*
12690 	 * Directed broadcast forwarding: if the packet came in over a
12691 	 * different interface then it is routed out over we can forward it.
12692 	 */
12693 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12694 		ire_refrele(ire);
12695 		freemsg(mp);
12696 		BUMP_MIB(&ip_mib, ipInDiscards);
12697 		return (B_TRUE);
12698 	}
12699 	/*
12700 	 * For multicast we have set dst to be INADDR_BROADCAST
12701 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12702 	 * only for broadcast packets.
12703 	 */
12704 	if (!CLASSD(ipha->ipha_dst)) {
12705 		ire_t *new_ire;
12706 		ipif_t *ipif;
12707 		/*
12708 		 * For ill groups, as the switch duplicates broadcasts
12709 		 * across all the ports, we need to filter out and
12710 		 * send up only one copy. There is one copy for every
12711 		 * broadcast address on each ill. Thus, we look for a
12712 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12713 		 * later to see whether this ill is eligible to receive
12714 		 * them or not. ill_nominate_bcast_rcv() nominates only
12715 		 * one set of IREs for receiving.
12716 		 */
12717 
12718 		ipif = ipif_get_next_ipif(NULL, ill);
12719 		if (ipif == NULL) {
12720 			ire_refrele(ire);
12721 			freemsg(mp);
12722 			BUMP_MIB(&ip_mib, ipInDiscards);
12723 			return (B_TRUE);
12724 		}
12725 		new_ire = ire_ctable_lookup(dst, 0, 0,
12726 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12727 		ipif_refrele(ipif);
12728 
12729 		if (new_ire != NULL) {
12730 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12731 				ire_refrele(ire);
12732 				ire_refrele(new_ire);
12733 				freemsg(mp);
12734 				BUMP_MIB(&ip_mib, ipInDiscards);
12735 				return (B_TRUE);
12736 			}
12737 			/*
12738 			 * In the special case of multirouted broadcast
12739 			 * packets, we unconditionally need to "gateway"
12740 			 * them to the appropriate interface here.
12741 			 * In the normal case, this cannot happen, because
12742 			 * there is no broadcast IRE tagged with the
12743 			 * RTF_MULTIRT flag.
12744 			 */
12745 			if (new_ire->ire_flags & RTF_MULTIRT) {
12746 				ire_refrele(new_ire);
12747 				if (ire->ire_rfq != NULL) {
12748 					q = ire->ire_rfq;
12749 					*qp = q;
12750 				}
12751 			} else {
12752 				ire_refrele(ire);
12753 				ire = new_ire;
12754 			}
12755 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12756 			if (!ip_g_forward_directed_bcast) {
12757 				/*
12758 				 * Free the message if
12759 				 * ip_g_forward_directed_bcast is turned
12760 				 * off for non-local broadcast.
12761 				 */
12762 				ire_refrele(ire);
12763 				freemsg(mp);
12764 				BUMP_MIB(&ip_mib, ipInDiscards);
12765 				return (B_TRUE);
12766 			}
12767 		} else {
12768 			/*
12769 			 * This CGTP packet successfully passed the
12770 			 * CGTP filter, but the related CGTP
12771 			 * broadcast IRE has not been found,
12772 			 * meaning that the redundant ipif is
12773 			 * probably down. However, if we discarded
12774 			 * this packet, its duplicate would be
12775 			 * filtered out by the CGTP filter so none
12776 			 * of them would get through. So we keep
12777 			 * going with this one.
12778 			 */
12779 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12780 			if (ire->ire_rfq != NULL) {
12781 				q = ire->ire_rfq;
12782 				*qp = q;
12783 			}
12784 		}
12785 	}
12786 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12787 		/*
12788 		 * Verify that there are not more then one
12789 		 * IRE_BROADCAST with this broadcast address which
12790 		 * has ire_stq set.
12791 		 * TODO: simplify, loop over all IRE's
12792 		 */
12793 		ire_t	*ire1;
12794 		int	num_stq = 0;
12795 		mblk_t	*mp1;
12796 
12797 		/* Find the first one with ire_stq set */
12798 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12799 		for (ire1 = ire; ire1 &&
12800 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12801 		    ire1 = ire1->ire_next)
12802 			;
12803 		if (ire1) {
12804 			ire_refrele(ire);
12805 			ire = ire1;
12806 			IRE_REFHOLD(ire);
12807 		}
12808 
12809 		/* Check if there are additional ones with stq set */
12810 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12811 			if (ire->ire_addr != ire1->ire_addr)
12812 				break;
12813 			if (ire1->ire_stq) {
12814 				num_stq++;
12815 				break;
12816 			}
12817 		}
12818 		rw_exit(&ire->ire_bucket->irb_lock);
12819 		if (num_stq == 1 && ire->ire_stq != NULL) {
12820 			ip1dbg(("ip_rput_process_broadcast: directed "
12821 			    "broadcast to 0x%x\n",
12822 			    ntohl(ire->ire_addr)));
12823 			mp1 = copymsg(mp);
12824 			if (mp1) {
12825 				switch (ipha->ipha_protocol) {
12826 				case IPPROTO_UDP:
12827 					ip_udp_input(q, mp1, ipha, ire, ill);
12828 					break;
12829 				default:
12830 					ip_proto_input(q, mp1, ipha, ire, ill);
12831 					break;
12832 				}
12833 			}
12834 			/*
12835 			 * Adjust ttl to 2 (1+1 - the forward engine
12836 			 * will decrement it by one.
12837 			 */
12838 			if (ip_csum_hdr(ipha)) {
12839 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12840 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12841 				freemsg(mp);
12842 				ire_refrele(ire);
12843 				return (B_TRUE);
12844 			}
12845 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12846 			ipha->ipha_hdr_checksum = 0;
12847 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12848 			ip_rput_process_forward(q, mp, ire, ipha,
12849 			    ill, ll_multicast);
12850 			return (B_TRUE);
12851 		}
12852 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12853 		    ntohl(ire->ire_addr)));
12854 	}
12855 
12856 	*irep = ire;
12857 
12858 	/* Restore any hardware checksum flags */
12859 	DB_CKSUMFLAGS(mp) = hcksumflags;
12860 	return (B_FALSE);
12861 }
12862 
12863 /* ARGSUSED */
12864 static boolean_t
12865 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12866     int *ll_multicast, ipaddr_t *dstp)
12867 {
12868 	/*
12869 	 * Forward packets only if we have joined the allmulti
12870 	 * group on this interface.
12871 	 */
12872 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12873 		int retval;
12874 
12875 		/*
12876 		 * Clear the indication that this may have hardware
12877 		 * checksum as we are not using it.
12878 		 */
12879 		DB_CKSUMFLAGS(mp) = 0;
12880 		retval = ip_mforward(ill, ipha, mp);
12881 		/* ip_mforward updates mib variables if needed */
12882 		/* clear b_prev - used by ip_mroute_decap */
12883 		mp->b_prev = NULL;
12884 
12885 		switch (retval) {
12886 		case 0:
12887 			/*
12888 			 * pkt is okay and arrived on phyint.
12889 			 *
12890 			 * If we are running as a multicast router
12891 			 * we need to see all IGMP and/or PIM packets.
12892 			 */
12893 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12894 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12895 				goto done;
12896 			}
12897 			break;
12898 		case -1:
12899 			/* pkt is mal-formed, toss it */
12900 			goto drop_pkt;
12901 		case 1:
12902 			/* pkt is okay and arrived on a tunnel */
12903 			/*
12904 			 * If we are running a multicast router
12905 			 *  we need to see all igmp packets.
12906 			 */
12907 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12908 				*dstp = INADDR_BROADCAST;
12909 				*ll_multicast = 1;
12910 				return (B_FALSE);
12911 			}
12912 
12913 			goto drop_pkt;
12914 		}
12915 	}
12916 
12917 	ILM_WALKER_HOLD(ill);
12918 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12919 		/*
12920 		 * This might just be caused by the fact that
12921 		 * multiple IP Multicast addresses map to the same
12922 		 * link layer multicast - no need to increment counter!
12923 		 */
12924 		ILM_WALKER_RELE(ill);
12925 		freemsg(mp);
12926 		return (B_TRUE);
12927 	}
12928 	ILM_WALKER_RELE(ill);
12929 done:
12930 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12931 	/*
12932 	 * This assumes the we deliver to all streams for multicast
12933 	 * and broadcast packets.
12934 	 */
12935 	*dstp = INADDR_BROADCAST;
12936 	*ll_multicast = 1;
12937 	return (B_FALSE);
12938 drop_pkt:
12939 	ip2dbg(("ip_rput: drop pkt\n"));
12940 	freemsg(mp);
12941 	return (B_TRUE);
12942 }
12943 
12944 static boolean_t
12945 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12946     int *ll_multicast, mblk_t **mpp)
12947 {
12948 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12949 	boolean_t must_copy = B_FALSE;
12950 	struct iocblk   *iocp;
12951 	ipha_t		*ipha;
12952 
12953 #define	rptr    ((uchar_t *)ipha)
12954 
12955 	first_mp = *first_mpp;
12956 	mp = *mpp;
12957 
12958 	ASSERT(first_mp == mp);
12959 
12960 	/*
12961 	 * if db_ref > 1 then copymsg and free original. Packet may be
12962 	 * changed and do not want other entity who has a reference to this
12963 	 * message to trip over the changes. This is a blind change because
12964 	 * trying to catch all places that might change packet is too
12965 	 * difficult (since it may be a module above this one)
12966 	 *
12967 	 * This corresponds to the non-fast path case. We walk down the full
12968 	 * chain in this case, and check the db_ref count of all the dblks,
12969 	 * and do a copymsg if required. It is possible that the db_ref counts
12970 	 * of the data blocks in the mblk chain can be different.
12971 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12972 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12973 	 * 'snoop' is running.
12974 	 */
12975 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12976 		if (mp1->b_datap->db_ref > 1) {
12977 			must_copy = B_TRUE;
12978 			break;
12979 		}
12980 	}
12981 
12982 	if (must_copy) {
12983 		mp1 = copymsg(mp);
12984 		if (mp1 == NULL) {
12985 			for (mp1 = mp; mp1 != NULL;
12986 			    mp1 = mp1->b_cont) {
12987 				mp1->b_next = NULL;
12988 				mp1->b_prev = NULL;
12989 			}
12990 			freemsg(mp);
12991 			BUMP_MIB(&ip_mib, ipInDiscards);
12992 			return (B_TRUE);
12993 		}
12994 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12995 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12996 			/* Copy b_next - used in M_BREAK messages */
12997 			to_mp->b_next = from_mp->b_next;
12998 			from_mp->b_next = NULL;
12999 			/* Copy b_prev - used by ip_mroute_decap */
13000 			to_mp->b_prev = from_mp->b_prev;
13001 			from_mp->b_prev = NULL;
13002 		}
13003 		*first_mpp = first_mp = mp1;
13004 		freemsg(mp);
13005 		mp = mp1;
13006 		*mpp = mp1;
13007 	}
13008 
13009 	ipha = (ipha_t *)mp->b_rptr;
13010 
13011 	/*
13012 	 * previous code has a case for M_DATA.
13013 	 * We want to check how that happens.
13014 	 */
13015 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13016 	switch (first_mp->b_datap->db_type) {
13017 	case M_PROTO:
13018 	case M_PCPROTO:
13019 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13020 		    DL_UNITDATA_IND) {
13021 			/* Go handle anything other than data elsewhere. */
13022 			ip_rput_dlpi(q, mp);
13023 			return (B_TRUE);
13024 		}
13025 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13026 		/* Ditch the DLPI header. */
13027 		mp1 = mp->b_cont;
13028 		ASSERT(first_mp == mp);
13029 		*first_mpp = mp1;
13030 		freeb(mp);
13031 		*mpp = mp1;
13032 		return (B_FALSE);
13033 	case M_BREAK:
13034 		/*
13035 		 * A packet arrives as M_BREAK following a cycle through
13036 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13037 		 * This is an IP datagram sans lower level header.
13038 		 * M_BREAK are also used to pass back in multicast packets
13039 		 * that are encapsulated with a source route.
13040 		 */
13041 		/* Ditch the M_BREAK mblk */
13042 		mp1 = mp->b_cont;
13043 		ASSERT(first_mp == mp);
13044 		*first_mpp = mp1;
13045 		freeb(mp);
13046 		mp = mp1;
13047 		mp->b_next = NULL;
13048 		*mpp = mp;
13049 		*ll_multicast = 0;
13050 		return (B_FALSE);
13051 	case M_IOCACK:
13052 		ip1dbg(("got iocack "));
13053 		iocp = (struct iocblk *)mp->b_rptr;
13054 		switch (iocp->ioc_cmd) {
13055 		case DL_IOC_HDR_INFO:
13056 			ill = (ill_t *)q->q_ptr;
13057 			ill_fastpath_ack(ill, mp);
13058 			return (B_TRUE);
13059 		case SIOCSTUNPARAM:
13060 		case OSIOCSTUNPARAM:
13061 			/* Go through qwriter_ip */
13062 			break;
13063 		case SIOCGTUNPARAM:
13064 		case OSIOCGTUNPARAM:
13065 			ip_rput_other(NULL, q, mp, NULL);
13066 			return (B_TRUE);
13067 		default:
13068 			putnext(q, mp);
13069 			return (B_TRUE);
13070 		}
13071 		/* FALLTHRU */
13072 	case M_ERROR:
13073 	case M_HANGUP:
13074 		/*
13075 		 * Since this is on the ill stream we unconditionally
13076 		 * bump up the refcount
13077 		 */
13078 		ill_refhold(ill);
13079 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13080 		    B_FALSE);
13081 		return (B_TRUE);
13082 	case M_CTL:
13083 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13084 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13085 			IPHADA_M_CTL)) {
13086 			/*
13087 			 * It's an IPsec accelerated packet.
13088 			 * Make sure that the ill from which we received the
13089 			 * packet has enabled IPsec hardware acceleration.
13090 			 */
13091 			if (!(ill->ill_capabilities &
13092 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13093 				/* IPsec kstats: bean counter */
13094 				freemsg(mp);
13095 				return (B_TRUE);
13096 			}
13097 
13098 			/*
13099 			 * Make mp point to the mblk following the M_CTL,
13100 			 * then process according to type of mp.
13101 			 * After this processing, first_mp will point to
13102 			 * the data-attributes and mp to the pkt following
13103 			 * the M_CTL.
13104 			 */
13105 			mp = first_mp->b_cont;
13106 			if (mp == NULL) {
13107 				freemsg(first_mp);
13108 				return (B_TRUE);
13109 			}
13110 			/*
13111 			 * A Hardware Accelerated packet can only be M_DATA
13112 			 * ESP or AH packet.
13113 			 */
13114 			if (mp->b_datap->db_type != M_DATA) {
13115 				/* non-M_DATA IPsec accelerated packet */
13116 				IPSECHW_DEBUG(IPSECHW_PKT,
13117 				    ("non-M_DATA IPsec accelerated pkt\n"));
13118 				freemsg(first_mp);
13119 				return (B_TRUE);
13120 			}
13121 			ipha = (ipha_t *)mp->b_rptr;
13122 			if (ipha->ipha_protocol != IPPROTO_AH &&
13123 			    ipha->ipha_protocol != IPPROTO_ESP) {
13124 				IPSECHW_DEBUG(IPSECHW_PKT,
13125 				    ("non-M_DATA IPsec accelerated pkt\n"));
13126 				freemsg(first_mp);
13127 				return (B_TRUE);
13128 			}
13129 			*mpp = mp;
13130 			return (B_FALSE);
13131 		}
13132 		putnext(q, mp);
13133 		return (B_TRUE);
13134 	case M_FLUSH:
13135 		if (*mp->b_rptr & FLUSHW) {
13136 			*mp->b_rptr &= ~FLUSHR;
13137 			qreply(q, mp);
13138 			return (B_TRUE);
13139 		}
13140 		freemsg(mp);
13141 		return (B_TRUE);
13142 	case M_IOCNAK:
13143 		ip1dbg(("got iocnak "));
13144 		iocp = (struct iocblk *)mp->b_rptr;
13145 		switch (iocp->ioc_cmd) {
13146 		case DL_IOC_HDR_INFO:
13147 		case SIOCSTUNPARAM:
13148 		case OSIOCSTUNPARAM:
13149 			/*
13150 			 * Since this is on the ill stream we unconditionally
13151 			 * bump up the refcount
13152 			 */
13153 			ill_refhold(ill);
13154 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13155 			    CUR_OP, B_FALSE);
13156 			return (B_TRUE);
13157 		case SIOCGTUNPARAM:
13158 		case OSIOCGTUNPARAM:
13159 			ip_rput_other(NULL, q, mp, NULL);
13160 			return (B_TRUE);
13161 		default:
13162 			break;
13163 		}
13164 		/* FALLTHRU */
13165 	default:
13166 		putnext(q, mp);
13167 		return (B_TRUE);
13168 	}
13169 }
13170 
13171 /* Read side put procedure.  Packets coming from the wire arrive here. */
13172 void
13173 ip_rput(queue_t *q, mblk_t *mp)
13174 {
13175 	ill_t		*ill;
13176 
13177 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13178 
13179 	ill = (ill_t *)q->q_ptr;
13180 
13181 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13182 		union DL_primitives *dl;
13183 
13184 		/*
13185 		 * Things are opening or closing. Only accept DLPI control
13186 		 * messages. In the open case, the ill->ill_ipif has not yet
13187 		 * been created. In the close case, things hanging off the
13188 		 * ill could have been freed already. In either case it
13189 		 * may not be safe to proceed further.
13190 		 */
13191 
13192 		dl = (union DL_primitives *)mp->b_rptr;
13193 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13194 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13195 			/*
13196 			 * Also SIOC[GS]TUN* ioctls can come here.
13197 			 */
13198 			inet_freemsg(mp);
13199 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13200 			    "ip_input_end: q %p (%S)", q, "uninit");
13201 			return;
13202 		}
13203 	}
13204 
13205 	/*
13206 	 * if db_ref > 1 then copymsg and free original. Packet may be
13207 	 * changed and we do not want the other entity who has a reference to
13208 	 * this message to trip over the changes. This is a blind change because
13209 	 * trying to catch all places that might change the packet is too
13210 	 * difficult.
13211 	 *
13212 	 * This corresponds to the fast path case, where we have a chain of
13213 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13214 	 * in the mblk chain. There doesn't seem to be a reason why a device
13215 	 * driver would send up data with varying db_ref counts in the mblk
13216 	 * chain. In any case the Fast path is a private interface, and our
13217 	 * drivers don't do such a thing. Given the above assumption, there is
13218 	 * no need to walk down the entire mblk chain (which could have a
13219 	 * potential performance problem)
13220 	 */
13221 	if (mp->b_datap->db_ref > 1) {
13222 		mblk_t  *mp1;
13223 		boolean_t adjusted = B_FALSE;
13224 		IP_STAT(ip_db_ref);
13225 
13226 		/*
13227 		 * The IP_RECVSLLA option depends on having the link layer
13228 		 * header. First check that:
13229 		 * a> the underlying device is of type ether, since this
13230 		 * option is currently supported only over ethernet.
13231 		 * b> there is enough room to copy over the link layer header.
13232 		 *
13233 		 * Once the checks are done, adjust rptr so that the link layer
13234 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13235 		 * be returned by some non-ethernet drivers but in this case the
13236 		 * second check will fail.
13237 		 */
13238 		if (ill->ill_type == IFT_ETHER &&
13239 		    (mp->b_rptr - mp->b_datap->db_base) >=
13240 		    sizeof (struct ether_header)) {
13241 			mp->b_rptr -= sizeof (struct ether_header);
13242 			adjusted = B_TRUE;
13243 		}
13244 		mp1 = copymsg(mp);
13245 		if (mp1 == NULL) {
13246 			/* Clear b_next - used in M_BREAK messages */
13247 			mp->b_next = NULL;
13248 			/* clear b_prev - used by ip_mroute_decap */
13249 			mp->b_prev = NULL;
13250 			freemsg(mp);
13251 			BUMP_MIB(&ip_mib, ipInDiscards);
13252 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13253 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13254 			return;
13255 		}
13256 		if (adjusted) {
13257 			/*
13258 			 * Copy is done. Restore the pointer in the _new_ mblk
13259 			 */
13260 			mp1->b_rptr += sizeof (struct ether_header);
13261 		}
13262 		/* Copy b_next - used in M_BREAK messages */
13263 		mp1->b_next = mp->b_next;
13264 		mp->b_next = NULL;
13265 		/* Copy b_prev - used by ip_mroute_decap */
13266 		mp1->b_prev = mp->b_prev;
13267 		mp->b_prev = NULL;
13268 		freemsg(mp);
13269 		mp = mp1;
13270 	}
13271 
13272 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13273 	    "ip_rput_end: q %p (%S)", q, "end");
13274 
13275 	ip_input(ill, NULL, mp, 0);
13276 }
13277 
13278 /*
13279  * Direct read side procedure capable of dealing with chains. GLDv3 based
13280  * drivers call this function directly with mblk chains while STREAMS
13281  * read side procedure ip_rput() calls this for single packet with ip_ring
13282  * set to NULL to process one packet at a time.
13283  *
13284  * The ill will always be valid if this function is called directly from
13285  * the driver.
13286  */
13287 /*ARGSUSED*/
13288 void
13289 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13290 {
13291 	ipaddr_t		dst;
13292 	ire_t			*ire;
13293 	ipha_t			*ipha;
13294 	uint_t			pkt_len;
13295 	ssize_t			len;
13296 	uint_t			opt_len;
13297 	int			ll_multicast;
13298 	int			cgtp_flt_pkt;
13299 	queue_t			*q = ill->ill_rq;
13300 	squeue_t		*curr_sqp = NULL;
13301 	mblk_t 			*head = NULL;
13302 	mblk_t			*tail = NULL;
13303 	mblk_t			*first_mp;
13304 	mblk_t 			*mp;
13305 	int			cnt = 0;
13306 
13307 	ASSERT(mp_chain != NULL);
13308 	ASSERT(ill != NULL);
13309 
13310 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13311 
13312 #define	rptr	((uchar_t *)ipha)
13313 
13314 	while (mp_chain != NULL) {
13315 		first_mp = mp = mp_chain;
13316 		mp_chain = mp_chain->b_next;
13317 		mp->b_next = NULL;
13318 		ll_multicast = 0;
13319 		ire = NULL;
13320 
13321 		/*
13322 		 * ip_input fast path
13323 		 */
13324 
13325 		/* mblk type is not M_DATA */
13326 		if (mp->b_datap->db_type != M_DATA) {
13327 			if (ip_rput_process_notdata(q, &first_mp, ill,
13328 			    &ll_multicast, &mp))
13329 				continue;
13330 		}
13331 
13332 		ASSERT(mp->b_datap->db_type == M_DATA);
13333 		ASSERT(mp->b_datap->db_ref == 1);
13334 
13335 		/*
13336 		 * Invoke the CGTP (multirouting) filtering module to process
13337 		 * the incoming packet. Packets identified as duplicates
13338 		 * must be discarded. Filtering is active only if the
13339 		 * the ip_cgtp_filter ndd variable is non-zero.
13340 		 */
13341 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13342 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13343 			cgtp_flt_pkt =
13344 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13345 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13346 				freemsg(first_mp);
13347 				continue;
13348 			}
13349 		}
13350 
13351 		ipha = (ipha_t *)mp->b_rptr;
13352 		len = mp->b_wptr - rptr;
13353 
13354 		BUMP_MIB(&ip_mib, ipInReceives);
13355 
13356 		/*
13357 		 * IP header ptr not aligned?
13358 		 * OR IP header not complete in first mblk
13359 		 */
13360 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13361 			if (!ip_check_and_align_header(q, mp))
13362 				continue;
13363 			ipha = (ipha_t *)mp->b_rptr;
13364 			len = mp->b_wptr - rptr;
13365 		}
13366 
13367 		/* multiple mblk or too short */
13368 		pkt_len = ntohs(ipha->ipha_length);
13369 		len -= pkt_len;
13370 		if (len != 0) {
13371 			/*
13372 			 * Make sure we have data length consistent
13373 			 * with the IP header.
13374 			 */
13375 			if (mp->b_cont == NULL) {
13376 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13377 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13378 					ip2dbg(("ip_input: drop pkt\n"));
13379 					freemsg(mp);
13380 					continue;
13381 				}
13382 				mp->b_wptr = rptr + pkt_len;
13383 			} else if (len += msgdsize(mp->b_cont)) {
13384 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13385 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13386 					ip2dbg(("ip_input: drop pkt\n"));
13387 					freemsg(mp);
13388 					continue;
13389 				}
13390 				(void) adjmsg(mp, -len);
13391 				IP_STAT(ip_multimblk3);
13392 			}
13393 		}
13394 
13395 		if (ip_loopback_src_or_dst(ipha, ill)) {
13396 			ip2dbg(("ip_input: drop pkt\n"));
13397 			freemsg(mp);
13398 			continue;
13399 		}
13400 
13401 		opt_len = ipha->ipha_version_and_hdr_length -
13402 		    IP_SIMPLE_HDR_VERSION;
13403 		/* IP version bad or there are IP options */
13404 		if (opt_len) {
13405 			if (len != 0)
13406 				IP_STAT(ip_multimblk4);
13407 			else
13408 				IP_STAT(ip_ipoptions);
13409 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13410 				continue;
13411 		} else {
13412 			dst = ipha->ipha_dst;
13413 		}
13414 
13415 		/*
13416 		 * If rsvpd is running, let RSVP daemon handle its processing
13417 		 * and forwarding of RSVP multicast/unicast packets.
13418 		 * If rsvpd is not running but mrouted is running, RSVP
13419 		 * multicast packets are forwarded as multicast traffic
13420 		 * and RSVP unicast packets are forwarded by unicast router.
13421 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13422 		 * packets are not forwarded, but the unicast packets are
13423 		 * forwarded like unicast traffic.
13424 		 */
13425 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13426 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13427 			/* RSVP packet and rsvpd running. Treat as ours */
13428 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13429 			/*
13430 			 * This assumes that we deliver to all streams for
13431 			 * multicast and broadcast packets.
13432 			 * We have to force ll_multicast to 1 to handle the
13433 			 * M_DATA messages passed in from ip_mroute_decap.
13434 			 */
13435 			dst = INADDR_BROADCAST;
13436 			ll_multicast = 1;
13437 		} else if (CLASSD(dst)) {
13438 			/* packet is multicast */
13439 			mp->b_next = NULL;
13440 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13441 			    &ll_multicast, &dst))
13442 				continue;
13443 		}
13444 
13445 
13446 		/*
13447 		 * Check if the packet is coming from the Mobile IP
13448 		 * forward tunnel interface
13449 		 */
13450 		if (ill->ill_srcif_refcnt > 0) {
13451 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13452 			    NULL, ill, MATCH_IRE_TYPE);
13453 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13454 			    ire->ire_ipif->ipif_net_type ==
13455 			    IRE_IF_RESOLVER) {
13456 				/* We need to resolve the link layer info */
13457 				ire_refrele(ire);
13458 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13459 				    ll_multicast, dst);
13460 				continue;
13461 			}
13462 		}
13463 
13464 		if (ire == NULL)
13465 			ire = ire_cache_lookup(dst, ALL_ZONES);
13466 
13467 		/*
13468 		 * If mipagent is running and reverse tunnel is created as per
13469 		 * mobile node request, then any packet coming through the
13470 		 * incoming interface from the mobile-node, should be reverse
13471 		 * tunneled to it's home agent except those that are destined
13472 		 * to foreign agent only.
13473 		 * This needs source address based ire lookup. The routing
13474 		 * entries for source address based lookup are only created by
13475 		 * mipagent program only when a reverse tunnel is created.
13476 		 * Reference : RFC2002, RFC2344
13477 		 */
13478 		if (ill->ill_mrtun_refcnt > 0) {
13479 			ipaddr_t	srcaddr;
13480 			ire_t		*tmp_ire;
13481 
13482 			tmp_ire = ire;	/* Save, we might need it later */
13483 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13484 			    ire->ire_type != IRE_BROADCAST)) {
13485 				srcaddr = ipha->ipha_src;
13486 				ire = ire_mrtun_lookup(srcaddr, ill);
13487 				if (ire != NULL) {
13488 					/*
13489 					 * Should not be getting iphada packet
13490 					 * here. we should only get those for
13491 					 * IRE_LOCAL traffic, excluded above.
13492 					 * Fail-safe (drop packet) in the event
13493 					 * hardware is misbehaving.
13494 					 */
13495 					if (first_mp != mp) {
13496 						/* IPsec KSTATS: beancount me */
13497 						freemsg(first_mp);
13498 					} else {
13499 						/*
13500 						 * This packet must be forwarded
13501 						 * to Reverse Tunnel
13502 						 */
13503 						ip_mrtun_forward(ire, ill, mp);
13504 					}
13505 					ire_refrele(ire);
13506 					if (tmp_ire != NULL)
13507 						ire_refrele(tmp_ire);
13508 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13509 					    "ip_input_end: q %p (%S)",
13510 					    q, "uninit");
13511 					continue;
13512 				}
13513 			}
13514 			/*
13515 			 * If this packet is from a non-mobilenode  or a
13516 			 * mobile-node which does not request reverse
13517 			 * tunnel service
13518 			 */
13519 			ire = tmp_ire;
13520 		}
13521 
13522 
13523 		/*
13524 		 * If we reach here that means the incoming packet satisfies
13525 		 * one of the following conditions:
13526 		 *   - packet is from a mobile node which does not request
13527 		 *	reverse tunnel
13528 		 *   - packet is from a non-mobile node, which is the most
13529 		 *	common case
13530 		 *   - packet is from a reverse tunnel enabled mobile node
13531 		 *	and destined to foreign agent only
13532 		 */
13533 
13534 		if (ire == NULL) {
13535 			/*
13536 			 * No IRE for this destination, so it can't be for us.
13537 			 * Unless we are forwarding, drop the packet.
13538 			 * We have to let source routed packets through
13539 			 * since we don't yet know if they are 'ping -l'
13540 			 * packets i.e. if they will go out over the
13541 			 * same interface as they came in on.
13542 			 */
13543 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13544 			continue;
13545 		}
13546 
13547 		/*
13548 		 * Broadcast IRE may indicate either broadcast or
13549 		 * multicast packet
13550 		 */
13551 		if (ire->ire_type == IRE_BROADCAST) {
13552 			/*
13553 			 * Skip broadcast checks if packet is UDP multicast;
13554 			 * we'd rather not enter ip_rput_process_broadcast()
13555 			 * unless the packet is broadcast for real, since
13556 			 * that routine is a no-op for multicast.
13557 			 */
13558 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
13559 			    !CLASSD(ipha->ipha_dst)) &&
13560 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13561 			    dst, cgtp_flt_pkt, ll_multicast)) {
13562 				continue;
13563 			}
13564 		} else if (ire->ire_stq != NULL) {
13565 			/* fowarding? */
13566 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13567 			    ll_multicast);
13568 			continue;
13569 		}
13570 
13571 		/* packet not for us */
13572 		if (ire->ire_rfq != q) {
13573 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13574 				continue;
13575 			}
13576 		}
13577 
13578 		switch (ipha->ipha_protocol) {
13579 		case IPPROTO_TCP:
13580 			ASSERT(first_mp == mp);
13581 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13582 				mp, 0, q, ip_ring)) != NULL) {
13583 				if (curr_sqp == NULL) {
13584 					curr_sqp = GET_SQUEUE(mp);
13585 					ASSERT(cnt == 0);
13586 					cnt++;
13587 					head = tail = mp;
13588 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13589 					ASSERT(tail != NULL);
13590 					cnt++;
13591 					tail->b_next = mp;
13592 					tail = mp;
13593 				} else {
13594 					/*
13595 					 * A different squeue. Send the
13596 					 * chain for the previous squeue on
13597 					 * its way. This shouldn't happen
13598 					 * often unless interrupt binding
13599 					 * changes.
13600 					 */
13601 					IP_STAT(ip_input_multi_squeue);
13602 					squeue_enter_chain(curr_sqp, head,
13603 					    tail, cnt, SQTAG_IP_INPUT);
13604 					curr_sqp = GET_SQUEUE(mp);
13605 					head = mp;
13606 					tail = mp;
13607 					cnt = 1;
13608 				}
13609 			}
13610 			IRE_REFRELE(ire);
13611 			continue;
13612 		case IPPROTO_UDP:
13613 			ASSERT(first_mp == mp);
13614 			ip_udp_input(q, mp, ipha, ire, ill);
13615 			IRE_REFRELE(ire);
13616 			continue;
13617 		case IPPROTO_SCTP:
13618 			ASSERT(first_mp == mp);
13619 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13620 			    q, dst);
13621 			continue;
13622 		default:
13623 			ip_proto_input(q, first_mp, ipha, ire, ill);
13624 			IRE_REFRELE(ire);
13625 			continue;
13626 		}
13627 	}
13628 
13629 	if (head != NULL)
13630 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13631 
13632 	/*
13633 	 * This code is there just to make netperf/ttcp look good.
13634 	 *
13635 	 * Its possible that after being in polling mode (and having cleared
13636 	 * the backlog), squeues have turned the interrupt frequency higher
13637 	 * to improve latency at the expense of more CPU utilization (less
13638 	 * packets per interrupts or more number of interrupts). Workloads
13639 	 * like ttcp/netperf do manage to tickle polling once in a while
13640 	 * but for the remaining time, stay in higher interrupt mode since
13641 	 * their packet arrival rate is pretty uniform and this shows up
13642 	 * as higher CPU utilization. Since people care about CPU utilization
13643 	 * while running netperf/ttcp, turn the interrupt frequency back to
13644 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13645 	 */
13646 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13647 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13648 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13649 			ip_ring->rr_blank(ip_ring->rr_handle,
13650 			    ip_ring->rr_normal_blank_time,
13651 			    ip_ring->rr_normal_pkt_cnt);
13652 		}
13653 	}
13654 
13655 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13656 	    "ip_input_end: q %p (%S)", q, "end");
13657 #undef	rptr
13658 }
13659 
13660 static void
13661 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13662     t_uscalar_t err)
13663 {
13664 	if (dl_err == DL_SYSERR) {
13665 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13666 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13667 		    ill->ill_name, dlpi_prim_str(prim), err);
13668 		return;
13669 	}
13670 
13671 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13672 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13673 	    dlpi_err_str(dl_err));
13674 }
13675 
13676 /*
13677  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13678  * than DL_UNITDATA_IND messages. If we need to process this message
13679  * exclusively, we call qwriter_ip, in which case we also need to call
13680  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13681  */
13682 void
13683 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13684 {
13685 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13686 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13687 	ill_t		*ill;
13688 
13689 	ip1dbg(("ip_rput_dlpi"));
13690 	ill = (ill_t *)q->q_ptr;
13691 	switch (dloa->dl_primitive) {
13692 	case DL_ERROR_ACK:
13693 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13694 		    "%s (0x%x), unix %u\n", ill->ill_name,
13695 		    dlpi_prim_str(dlea->dl_error_primitive),
13696 		    dlea->dl_error_primitive,
13697 		    dlpi_err_str(dlea->dl_errno),
13698 		    dlea->dl_errno,
13699 		    dlea->dl_unix_errno));
13700 		switch (dlea->dl_error_primitive) {
13701 		case DL_UNBIND_REQ:
13702 			mutex_enter(&ill->ill_lock);
13703 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
13704 			cv_signal(&ill->ill_cv);
13705 			mutex_exit(&ill->ill_lock);
13706 			/* FALLTHRU */
13707 		case DL_NOTIFY_REQ:
13708 		case DL_ATTACH_REQ:
13709 		case DL_DETACH_REQ:
13710 		case DL_INFO_REQ:
13711 		case DL_BIND_REQ:
13712 		case DL_ENABMULTI_REQ:
13713 		case DL_PHYS_ADDR_REQ:
13714 		case DL_CAPABILITY_REQ:
13715 		case DL_CONTROL_REQ:
13716 			/*
13717 			 * Refhold the ill to match qwriter_ip which does a
13718 			 * refrele. Since this is on the ill stream we
13719 			 * unconditionally bump up the refcount without
13720 			 * checking for ILL_CAN_LOOKUP
13721 			 */
13722 			ill_refhold(ill);
13723 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13724 			    CUR_OP, B_FALSE);
13725 			return;
13726 		case DL_DISABMULTI_REQ:
13727 			freemsg(mp);	/* Don't want to pass this up */
13728 			return;
13729 		default:
13730 			break;
13731 		}
13732 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13733 		    dlea->dl_errno, dlea->dl_unix_errno);
13734 		freemsg(mp);
13735 		return;
13736 	case DL_INFO_ACK:
13737 	case DL_BIND_ACK:
13738 	case DL_PHYS_ADDR_ACK:
13739 	case DL_NOTIFY_ACK:
13740 	case DL_CAPABILITY_ACK:
13741 	case DL_CONTROL_ACK:
13742 		/*
13743 		 * Refhold the ill to match qwriter_ip which does a refrele
13744 		 * Since this is on the ill stream we unconditionally
13745 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13746 		 */
13747 		ill_refhold(ill);
13748 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13749 		    CUR_OP, B_FALSE);
13750 		return;
13751 	case DL_NOTIFY_IND:
13752 		ill_refhold(ill);
13753 		/*
13754 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13755 		 * relation to the current ioctl in progress (if any). Hence we
13756 		 * pass in NEW_OP in this case.
13757 		 */
13758 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13759 		    NEW_OP, B_FALSE);
13760 		return;
13761 	case DL_OK_ACK:
13762 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13763 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13764 		switch (dloa->dl_correct_primitive) {
13765 		case DL_UNBIND_REQ:
13766 			mutex_enter(&ill->ill_lock);
13767 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
13768 			cv_signal(&ill->ill_cv);
13769 			mutex_exit(&ill->ill_lock);
13770 			/* FALLTHRU */
13771 		case DL_ATTACH_REQ:
13772 		case DL_DETACH_REQ:
13773 			/*
13774 			 * Refhold the ill to match qwriter_ip which does a
13775 			 * refrele. Since this is on the ill stream we
13776 			 * unconditionally bump up the refcount
13777 			 */
13778 			ill_refhold(ill);
13779 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13780 			    CUR_OP, B_FALSE);
13781 			return;
13782 		case DL_ENABMULTI_REQ:
13783 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13784 				ill->ill_dlpi_multicast_state = IDMS_OK;
13785 			break;
13786 
13787 		}
13788 		break;
13789 	default:
13790 		break;
13791 	}
13792 	freemsg(mp);
13793 }
13794 
13795 /*
13796  * Handling of DLPI messages that require exclusive access to the ipsq.
13797  *
13798  * Need to do ill_pending_mp_release on ioctl completion, which could
13799  * happen here. (along with mi_copy_done)
13800  */
13801 /* ARGSUSED */
13802 static void
13803 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13804 {
13805 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13806 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13807 	int		err = 0;
13808 	ill_t		*ill;
13809 	ipif_t		*ipif = NULL;
13810 	mblk_t		*mp1 = NULL;
13811 	conn_t		*connp = NULL;
13812 	t_uscalar_t	physaddr_req;
13813 	mblk_t		*mp_hw;
13814 	union DL_primitives *dlp;
13815 	boolean_t	success;
13816 	boolean_t	ioctl_aborted = B_FALSE;
13817 	boolean_t	log = B_TRUE;
13818 
13819 	ip1dbg(("ip_rput_dlpi_writer .."));
13820 	ill = (ill_t *)q->q_ptr;
13821 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13822 
13823 	ASSERT(IAM_WRITER_ILL(ill));
13824 
13825 	/*
13826 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13827 	 * both are null or non-null. However we can assert that only
13828 	 * after grabbing the ipsq_lock. So we don't make any assertion
13829 	 * here and in other places in the code.
13830 	 */
13831 	ipif = ipsq->ipsq_pending_ipif;
13832 	/*
13833 	 * The current ioctl could have been aborted by the user and a new
13834 	 * ioctl to bring up another ill could have started. We could still
13835 	 * get a response from the driver later.
13836 	 */
13837 	if (ipif != NULL && ipif->ipif_ill != ill)
13838 		ioctl_aborted = B_TRUE;
13839 
13840 	switch (dloa->dl_primitive) {
13841 	case DL_ERROR_ACK:
13842 		switch (dlea->dl_error_primitive) {
13843 		case DL_UNBIND_REQ:
13844 		case DL_ATTACH_REQ:
13845 		case DL_DETACH_REQ:
13846 		case DL_INFO_REQ:
13847 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13848 			break;
13849 		case DL_NOTIFY_REQ:
13850 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13851 			log = B_FALSE;
13852 			break;
13853 		case DL_PHYS_ADDR_REQ:
13854 			/*
13855 			 * For IPv6 only, there are two additional
13856 			 * phys_addr_req's sent to the driver to get the
13857 			 * IPv6 token and lla. This allows IP to acquire
13858 			 * the hardware address format for a given interface
13859 			 * without having built in knowledge of the hardware
13860 			 * address. ill_phys_addr_pend keeps track of the last
13861 			 * DL_PAR sent so we know which response we are
13862 			 * dealing with. ill_dlpi_done will update
13863 			 * ill_phys_addr_pend when it sends the next req.
13864 			 * We don't complete the IOCTL until all three DL_PARs
13865 			 * have been attempted, so set *_len to 0 and break.
13866 			 */
13867 			physaddr_req = ill->ill_phys_addr_pend;
13868 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13869 			if (physaddr_req == DL_IPV6_TOKEN) {
13870 				ill->ill_token_length = 0;
13871 				log = B_FALSE;
13872 				break;
13873 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13874 				ill->ill_nd_lla_len = 0;
13875 				log = B_FALSE;
13876 				break;
13877 			}
13878 			/*
13879 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13880 			 * We presumably have an IOCTL hanging out waiting
13881 			 * for completion. Find it and complete the IOCTL
13882 			 * with the error noted.
13883 			 * However, ill_dl_phys was called on an ill queue
13884 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13885 			 * set. But the ioctl is known to be pending on ill_wq.
13886 			 */
13887 			if (!ill->ill_ifname_pending)
13888 				break;
13889 			ill->ill_ifname_pending = 0;
13890 			if (!ioctl_aborted)
13891 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13892 			if (mp1 != NULL) {
13893 				/*
13894 				 * This operation (SIOCSLIFNAME) must have
13895 				 * happened on the ill. Assert there is no conn
13896 				 */
13897 				ASSERT(connp == NULL);
13898 				q = ill->ill_wq;
13899 			}
13900 			break;
13901 		case DL_BIND_REQ:
13902 			ill_dlpi_done(ill, DL_BIND_REQ);
13903 			if (ill->ill_ifname_pending)
13904 				break;
13905 			/*
13906 			 * Something went wrong with the bind.  We presumably
13907 			 * have an IOCTL hanging out waiting for completion.
13908 			 * Find it, take down the interface that was coming
13909 			 * up, and complete the IOCTL with the error noted.
13910 			 */
13911 			if (!ioctl_aborted)
13912 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13913 			if (mp1 != NULL) {
13914 				/*
13915 				 * This operation (SIOCSLIFFLAGS) must have
13916 				 * happened from a conn.
13917 				 */
13918 				ASSERT(connp != NULL);
13919 				q = CONNP_TO_WQ(connp);
13920 				if (ill->ill_move_in_progress) {
13921 					ILL_CLEAR_MOVE(ill);
13922 				}
13923 				(void) ipif_down(ipif, NULL, NULL);
13924 				/* error is set below the switch */
13925 			}
13926 			break;
13927 		case DL_ENABMULTI_REQ:
13928 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13929 
13930 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13931 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13932 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13933 				ipif_t *ipif;
13934 
13935 				log = B_FALSE;
13936 				printf("ip: joining multicasts failed (%d)"
13937 				    " on %s - will use link layer "
13938 				    "broadcasts for multicast\n",
13939 				    dlea->dl_errno, ill->ill_name);
13940 
13941 				/*
13942 				 * Set up the multicast mapping alone.
13943 				 * writer, so ok to access ill->ill_ipif
13944 				 * without any lock.
13945 				 */
13946 				ipif = ill->ill_ipif;
13947 				mutex_enter(&ill->ill_phyint->phyint_lock);
13948 				ill->ill_phyint->phyint_flags |=
13949 				    PHYI_MULTI_BCAST;
13950 				mutex_exit(&ill->ill_phyint->phyint_lock);
13951 
13952 				if (!ill->ill_isv6) {
13953 					(void) ipif_arp_setup_multicast(ipif,
13954 					    NULL);
13955 				} else {
13956 					(void) ipif_ndp_setup_multicast(ipif,
13957 					    NULL);
13958 				}
13959 			}
13960 			freemsg(mp);	/* Don't want to pass this up */
13961 			return;
13962 		case DL_CAPABILITY_REQ:
13963 		case DL_CONTROL_REQ:
13964 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13965 			    "DL_CAPABILITY/CONTROL REQ\n"));
13966 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13967 			ill->ill_capab_state = IDMS_FAILED;
13968 			freemsg(mp);
13969 			return;
13970 		}
13971 		/*
13972 		 * Note the error for IOCTL completion (mp1 is set when
13973 		 * ready to complete ioctl). If ill_ifname_pending_err is
13974 		 * set, an error occured during plumbing (ill_ifname_pending),
13975 		 * so we want to report that error.
13976 		 *
13977 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13978 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13979 		 * expected to get errack'd if the driver doesn't support
13980 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13981 		 * if these error conditions are encountered.
13982 		 */
13983 		if (mp1 != NULL) {
13984 			if (ill->ill_ifname_pending_err != 0)  {
13985 				err = ill->ill_ifname_pending_err;
13986 				ill->ill_ifname_pending_err = 0;
13987 			} else {
13988 				err = dlea->dl_unix_errno ?
13989 				    dlea->dl_unix_errno : ENXIO;
13990 			}
13991 		/*
13992 		 * If we're plumbing an interface and an error hasn't already
13993 		 * been saved, set ill_ifname_pending_err to the error passed
13994 		 * up. Ignore the error if log is B_FALSE (see comment above).
13995 		 */
13996 		} else if (log && ill->ill_ifname_pending &&
13997 		    ill->ill_ifname_pending_err == 0) {
13998 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13999 			dlea->dl_unix_errno : ENXIO;
14000 		}
14001 
14002 		if (log)
14003 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14004 			    dlea->dl_errno, dlea->dl_unix_errno);
14005 		break;
14006 	case DL_CAPABILITY_ACK: {
14007 		boolean_t reneg_flag = B_FALSE;
14008 		/* Call a routine to handle this one. */
14009 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14010 		/*
14011 		 * Check if the ACK is due to renegotiation case since we
14012 		 * will need to send a new CAPABILITY_REQ later.
14013 		 */
14014 		if (ill->ill_capab_state == IDMS_RENEG) {
14015 			/* This is the ack for a renogiation case */
14016 			reneg_flag = B_TRUE;
14017 			ill->ill_capab_state = IDMS_UNKNOWN;
14018 		}
14019 		ill_capability_ack(ill, mp);
14020 		if (reneg_flag)
14021 			ill_capability_probe(ill);
14022 		break;
14023 	}
14024 	case DL_CONTROL_ACK:
14025 		/* We treat all of these as "fire and forget" */
14026 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14027 		break;
14028 	case DL_INFO_ACK:
14029 		/* Call a routine to handle this one. */
14030 		ill_dlpi_done(ill, DL_INFO_REQ);
14031 		ip_ll_subnet_defaults(ill, mp);
14032 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14033 		return;
14034 	case DL_BIND_ACK:
14035 		/*
14036 		 * We should have an IOCTL waiting on this unless
14037 		 * sent by ill_dl_phys, in which case just return
14038 		 */
14039 		ill_dlpi_done(ill, DL_BIND_REQ);
14040 		if (ill->ill_ifname_pending)
14041 			break;
14042 
14043 		if (!ioctl_aborted)
14044 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14045 		if (mp1 == NULL)
14046 			break;
14047 		ASSERT(connp != NULL);
14048 		q = CONNP_TO_WQ(connp);
14049 
14050 		/*
14051 		 * We are exclusive. So nothing can change even after
14052 		 * we get the pending mp. If need be we can put it back
14053 		 * and restart, as in calling ipif_arp_up()  below.
14054 		 */
14055 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14056 
14057 		mutex_enter(&ill->ill_lock);
14058 		ill->ill_dl_up = 1;
14059 		mutex_exit(&ill->ill_lock);
14060 
14061 		/*
14062 		 * Now bring up the resolver, when that is
14063 		 * done we'll create IREs and we are done.
14064 		 */
14065 		if (ill->ill_isv6) {
14066 			/*
14067 			 * v6 interfaces.
14068 			 * Unlike ARP which has to do another bind
14069 			 * and attach, once we get here we are
14070 			 * done withh NDP. Except in the case of
14071 			 * ILLF_XRESOLV, in which case we send an
14072 			 * AR_INTERFACE_UP to the external resolver.
14073 			 * If all goes well, the ioctl will complete
14074 			 * in ip_rput(). If there's an error, we
14075 			 * complete it here.
14076 			 */
14077 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14078 			    B_FALSE);
14079 			if (err == 0) {
14080 				if (ill->ill_flags & ILLF_XRESOLV) {
14081 					mutex_enter(&connp->conn_lock);
14082 					mutex_enter(&ill->ill_lock);
14083 					success = ipsq_pending_mp_add(
14084 					    connp, ipif, q, mp1, 0);
14085 					mutex_exit(&ill->ill_lock);
14086 					mutex_exit(&connp->conn_lock);
14087 					if (success) {
14088 						err = ipif_resolver_up(ipif,
14089 						    B_FALSE);
14090 						if (err == EINPROGRESS) {
14091 							freemsg(mp);
14092 							return;
14093 						}
14094 						ASSERT(err != 0);
14095 						mp1 = ipsq_pending_mp_get(ipsq,
14096 						    &connp);
14097 						ASSERT(mp1 != NULL);
14098 					} else {
14099 						/* conn has started closing */
14100 						err = EINTR;
14101 					}
14102 				} else { /* Non XRESOLV interface */
14103 					err = ipif_up_done_v6(ipif);
14104 				}
14105 			}
14106 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14107 			/*
14108 			 * ARP and other v4 external resolvers.
14109 			 * Leave the pending mblk intact so that
14110 			 * the ioctl completes in ip_rput().
14111 			 */
14112 			mutex_enter(&connp->conn_lock);
14113 			mutex_enter(&ill->ill_lock);
14114 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14115 			mutex_exit(&ill->ill_lock);
14116 			mutex_exit(&connp->conn_lock);
14117 			if (success) {
14118 				err = ipif_resolver_up(ipif, B_FALSE);
14119 				if (err == EINPROGRESS) {
14120 					freemsg(mp);
14121 					return;
14122 				}
14123 				ASSERT(err != 0);
14124 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14125 			} else {
14126 				/* The conn has started closing */
14127 				err = EINTR;
14128 			}
14129 		} else {
14130 			/*
14131 			 * This one is complete. Reply to pending ioctl.
14132 			 */
14133 			err = ipif_up_done(ipif);
14134 		}
14135 
14136 		if ((err == 0) && (ill->ill_up_ipifs)) {
14137 			err = ill_up_ipifs(ill, q, mp1);
14138 			if (err == EINPROGRESS) {
14139 				freemsg(mp);
14140 				return;
14141 			}
14142 		}
14143 
14144 		if (ill->ill_up_ipifs) {
14145 			ill_group_cleanup(ill);
14146 		}
14147 
14148 		break;
14149 	case DL_NOTIFY_IND: {
14150 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14151 		ire_t *ire;
14152 		boolean_t need_ire_walk_v4 = B_FALSE;
14153 		boolean_t need_ire_walk_v6 = B_FALSE;
14154 
14155 		/*
14156 		 * Change the address everywhere we need to.
14157 		 * What we're getting here is a link-level addr or phys addr.
14158 		 * The new addr is at notify + notify->dl_addr_offset
14159 		 * The address length is notify->dl_addr_length;
14160 		 */
14161 		switch (notify->dl_notification) {
14162 		case DL_NOTE_PHYS_ADDR:
14163 			mp_hw = copyb(mp);
14164 			if (mp_hw == NULL) {
14165 				err = ENOMEM;
14166 				break;
14167 			}
14168 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14169 			/*
14170 			 * We currently don't support changing
14171 			 * the token via DL_NOTIFY_IND.
14172 			 * When we do support it, we have to consider
14173 			 * what the implications are with respect to
14174 			 * the token and the link local address.
14175 			 */
14176 			mutex_enter(&ill->ill_lock);
14177 			if (dlp->notify_ind.dl_data ==
14178 			    DL_IPV6_LINK_LAYER_ADDR) {
14179 				if (ill->ill_nd_lla_mp != NULL)
14180 					freemsg(ill->ill_nd_lla_mp);
14181 				ill->ill_nd_lla_mp = mp_hw;
14182 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14183 				    dlp->notify_ind.dl_addr_offset;
14184 				ill->ill_nd_lla_len =
14185 				    dlp->notify_ind.dl_addr_length -
14186 				    ABS(ill->ill_sap_length);
14187 				mutex_exit(&ill->ill_lock);
14188 				break;
14189 			} else if (dlp->notify_ind.dl_data ==
14190 			    DL_CURR_PHYS_ADDR) {
14191 				if (ill->ill_phys_addr_mp != NULL)
14192 					freemsg(ill->ill_phys_addr_mp);
14193 				ill->ill_phys_addr_mp = mp_hw;
14194 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14195 				    dlp->notify_ind.dl_addr_offset;
14196 				ill->ill_phys_addr_length =
14197 				    dlp->notify_ind.dl_addr_length -
14198 				    ABS(ill->ill_sap_length);
14199 				if (ill->ill_isv6 &&
14200 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14201 					if (ill->ill_nd_lla_mp != NULL)
14202 						freemsg(ill->ill_nd_lla_mp);
14203 					ill->ill_nd_lla_mp = copyb(mp_hw);
14204 					ill->ill_nd_lla = (uchar_t *)
14205 					    ill->ill_nd_lla_mp->b_rptr +
14206 					    dlp->notify_ind.dl_addr_offset;
14207 					ill->ill_nd_lla_len =
14208 					    ill->ill_phys_addr_length;
14209 				}
14210 			}
14211 			mutex_exit(&ill->ill_lock);
14212 			/*
14213 			 * Send out gratuitous arp request for our new
14214 			 * hardware address.
14215 			 */
14216 			for (ipif = ill->ill_ipif; ipif != NULL;
14217 			    ipif = ipif->ipif_next) {
14218 				if (!(ipif->ipif_flags & IPIF_UP))
14219 					continue;
14220 				if (ill->ill_isv6) {
14221 					ipif_ndp_down(ipif);
14222 					/*
14223 					 * Set B_TRUE to enable
14224 					 * ipif_ndp_up() to send out
14225 					 * unsolicited advertisements.
14226 					 */
14227 					err = ipif_ndp_up(ipif,
14228 					    &ipif->ipif_v6lcl_addr,
14229 					    B_TRUE);
14230 					if (err) {
14231 						ip1dbg((
14232 						    "ip_rput_dlpi_writer: "
14233 						    "Failed to update ndp "
14234 						    "err %d\n", err));
14235 					}
14236 				} else {
14237 					/*
14238 					 * IPv4 ARP case
14239 					 *
14240 					 * Set B_TRUE, as we only want
14241 					 * ipif_resolver_up to send an
14242 					 * AR_ENTRY_ADD request up to
14243 					 * ARP.
14244 					 */
14245 					err = ipif_resolver_up(ipif,
14246 					    B_TRUE);
14247 					if (err) {
14248 						ip1dbg((
14249 						    "ip_rput_dlpi_writer: "
14250 						    "Failed to update arp "
14251 						    "err %d\n", err));
14252 					}
14253 				}
14254 			}
14255 			/*
14256 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14257 			 * case so that all old fastpath information can be
14258 			 * purged from IRE caches.
14259 			 */
14260 		/* FALLTHRU */
14261 		case DL_NOTE_FASTPATH_FLUSH:
14262 			/*
14263 			 * Any fastpath probe sent henceforth will get the
14264 			 * new fp mp. So we first delete any ires that are
14265 			 * waiting for the fastpath. Then walk all ires and
14266 			 * delete the ire or delete the fp mp. In the case of
14267 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14268 			 * recreate the ire's without going through a complex
14269 			 * ipif up/down dance. So we don't delete the ire
14270 			 * itself, but just the ire_fp_mp for these 2 ire's
14271 			 * In the case of the other ire's we delete the ire's
14272 			 * themselves. Access to ire_fp_mp is completely
14273 			 * protected by ire_lock for IRE_MIPRTUN and
14274 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14275 			 * other cases for performance.
14276 			 */
14277 			if (ill->ill_isv6) {
14278 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14279 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14280 				    NULL);
14281 			} else {
14282 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14283 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14284 				    IRE_CACHE | IRE_BROADCAST,
14285 				    ire_fastpath_flush, NULL, ill);
14286 				mutex_enter(&ire_mrtun_lock);
14287 				if (ire_mrtun_count != 0) {
14288 					mutex_exit(&ire_mrtun_lock);
14289 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14290 					    IRE_MIPRTUN, ire_fastpath_flush,
14291 					    NULL, ill);
14292 				} else {
14293 					mutex_exit(&ire_mrtun_lock);
14294 				}
14295 			}
14296 			break;
14297 		case DL_NOTE_SDU_SIZE:
14298 			/*
14299 			 * Change the MTU size of the interface, of all
14300 			 * attached ipif's, and of all relevant ire's.  The
14301 			 * new value's a uint32_t at notify->dl_data.
14302 			 * Mtu change Vs. new ire creation - protocol below.
14303 			 *
14304 			 * a Mark the ipif as IPIF_CHANGING.
14305 			 * b Set the new mtu in the ipif.
14306 			 * c Change the ire_max_frag on all affected ires
14307 			 * d Unmark the IPIF_CHANGING
14308 			 *
14309 			 * To see how the protocol works, assume an interface
14310 			 * route is also being added simultaneously by
14311 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14312 			 * the ire. If the ire is created before step a,
14313 			 * it will be cleaned up by step c. If the ire is
14314 			 * created after step d, it will see the new value of
14315 			 * ipif_mtu. Any attempt to create the ire between
14316 			 * steps a to d will fail because of the IPIF_CHANGING
14317 			 * flag. Note that ire_create() is passed a pointer to
14318 			 * the ipif_mtu, and not the value. During ire_add
14319 			 * under the bucket lock, the ire_max_frag of the
14320 			 * new ire being created is set from the ipif/ire from
14321 			 * which it is being derived.
14322 			 */
14323 			mutex_enter(&ill->ill_lock);
14324 			ill->ill_max_frag = (uint_t)notify->dl_data;
14325 
14326 			/*
14327 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14328 			 * leave it alone
14329 			 */
14330 			if (ill->ill_mtu_userspecified) {
14331 				mutex_exit(&ill->ill_lock);
14332 				break;
14333 			}
14334 			ill->ill_max_mtu = ill->ill_max_frag;
14335 			if (ill->ill_isv6) {
14336 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14337 					ill->ill_max_mtu = IPV6_MIN_MTU;
14338 			} else {
14339 				if (ill->ill_max_mtu < IP_MIN_MTU)
14340 					ill->ill_max_mtu = IP_MIN_MTU;
14341 			}
14342 			for (ipif = ill->ill_ipif; ipif != NULL;
14343 			    ipif = ipif->ipif_next) {
14344 				/*
14345 				 * Don't override the mtu if the user
14346 				 * has explicitly set it.
14347 				 */
14348 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14349 					continue;
14350 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14351 				if (ipif->ipif_isv6)
14352 					ire = ipif_to_ire_v6(ipif);
14353 				else
14354 					ire = ipif_to_ire(ipif);
14355 				if (ire != NULL) {
14356 					ire->ire_max_frag = ipif->ipif_mtu;
14357 					ire_refrele(ire);
14358 				}
14359 				if (ipif->ipif_flags & IPIF_UP) {
14360 					if (ill->ill_isv6)
14361 						need_ire_walk_v6 = B_TRUE;
14362 					else
14363 						need_ire_walk_v4 = B_TRUE;
14364 				}
14365 			}
14366 			mutex_exit(&ill->ill_lock);
14367 			if (need_ire_walk_v4)
14368 				ire_walk_v4(ill_mtu_change, (char *)ill,
14369 				    ALL_ZONES);
14370 			if (need_ire_walk_v6)
14371 				ire_walk_v6(ill_mtu_change, (char *)ill,
14372 				    ALL_ZONES);
14373 			break;
14374 		case DL_NOTE_LINK_UP:
14375 		case DL_NOTE_LINK_DOWN: {
14376 			/*
14377 			 * We are writer. ill / phyint / ipsq assocs stable.
14378 			 * The RUNNING flag reflects the state of the link.
14379 			 */
14380 			phyint_t *phyint = ill->ill_phyint;
14381 			uint64_t new_phyint_flags;
14382 			boolean_t changed = B_FALSE;
14383 
14384 			mutex_enter(&phyint->phyint_lock);
14385 			new_phyint_flags =
14386 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14387 			    phyint->phyint_flags | PHYI_RUNNING :
14388 			    phyint->phyint_flags & ~PHYI_RUNNING;
14389 			if (new_phyint_flags != phyint->phyint_flags) {
14390 				phyint->phyint_flags = new_phyint_flags;
14391 				changed = B_TRUE;
14392 			}
14393 			mutex_exit(&phyint->phyint_lock);
14394 			/*
14395 			 * If the flags have changed, send a message to
14396 			 * the routing socket.
14397 			 */
14398 			if (changed) {
14399 				if (phyint->phyint_illv4 != NULL) {
14400 					ip_rts_ifmsg(
14401 					    phyint->phyint_illv4->ill_ipif);
14402 				}
14403 				if (phyint->phyint_illv6 != NULL) {
14404 					ip_rts_ifmsg(
14405 					    phyint->phyint_illv6->ill_ipif);
14406 				}
14407 			}
14408 			break;
14409 		}
14410 		case DL_NOTE_PROMISC_ON_PHYS:
14411 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14412 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14413 			mutex_enter(&ill->ill_lock);
14414 			ill->ill_promisc_on_phys = B_TRUE;
14415 			mutex_exit(&ill->ill_lock);
14416 			break;
14417 		case DL_NOTE_PROMISC_OFF_PHYS:
14418 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14419 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14420 			mutex_enter(&ill->ill_lock);
14421 			ill->ill_promisc_on_phys = B_FALSE;
14422 			mutex_exit(&ill->ill_lock);
14423 			break;
14424 		case DL_NOTE_CAPAB_RENEG:
14425 			/*
14426 			 * Something changed on the driver side.
14427 			 * It wants us to renegotiate the capabilities
14428 			 * on this ill. The most likely cause is the
14429 			 * aggregation interface under us where a
14430 			 * port got added or went away.
14431 			 *
14432 			 * We reset the capabilities and set the
14433 			 * state to IDMS_RENG so that when the ack
14434 			 * comes back, we can start the
14435 			 * renegotiation process.
14436 			 */
14437 			ill_capability_reset(ill);
14438 			ill->ill_capab_state = IDMS_RENEG;
14439 			break;
14440 		default:
14441 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14442 			    "type 0x%x for DL_NOTIFY_IND\n",
14443 			    notify->dl_notification));
14444 			break;
14445 		}
14446 
14447 		/*
14448 		 * As this is an asynchronous operation, we
14449 		 * should not call ill_dlpi_done
14450 		 */
14451 		break;
14452 	}
14453 	case DL_NOTIFY_ACK:
14454 		/*
14455 		 * Don't really need to check for what notifications
14456 		 * are supported; we'll process what gets sent upstream,
14457 		 * and we know it'll be something we support changing
14458 		 * based on our DL_NOTIFY_REQ.
14459 		 */
14460 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14461 		break;
14462 	case DL_PHYS_ADDR_ACK: {
14463 		/*
14464 		 * We should have an IOCTL waiting on this when request
14465 		 * sent by ill_dl_phys.
14466 		 * However, ill_dl_phys was called on an ill queue (from
14467 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14468 		 * ioctl is known to be pending on ill_wq.
14469 		 * There are two additional phys_addr_req's sent to the
14470 		 * driver to get the token and lla. ill_phys_addr_pend
14471 		 * keeps track of the last one sent so we know which
14472 		 * response we are dealing with. ill_dlpi_done will
14473 		 * update ill_phys_addr_pend when it sends the next req.
14474 		 * We don't complete the IOCTL until all three DL_PARs
14475 		 * have been attempted.
14476 		 *
14477 		 * We don't need any lock to update ill_nd_lla* fields,
14478 		 * since the ill is not yet up, We grab the lock just
14479 		 * for uniformity with other code that accesses ill_nd_lla.
14480 		 */
14481 		physaddr_req = ill->ill_phys_addr_pend;
14482 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14483 		if (physaddr_req == DL_IPV6_TOKEN ||
14484 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14485 			if (physaddr_req == DL_IPV6_TOKEN) {
14486 				/*
14487 				 * bcopy to low-order bits of ill_token
14488 				 *
14489 				 * XXX Temporary hack - currently,
14490 				 * all known tokens are 64 bits,
14491 				 * so I'll cheat for the moment.
14492 				 */
14493 				dlp = (union DL_primitives *)mp->b_rptr;
14494 
14495 				mutex_enter(&ill->ill_lock);
14496 				bcopy((uchar_t *)(mp->b_rptr +
14497 				dlp->physaddr_ack.dl_addr_offset),
14498 				(void *)&ill->ill_token.s6_addr32[2],
14499 				dlp->physaddr_ack.dl_addr_length);
14500 				ill->ill_token_length =
14501 					dlp->physaddr_ack.dl_addr_length;
14502 				mutex_exit(&ill->ill_lock);
14503 			} else {
14504 				ASSERT(ill->ill_nd_lla_mp == NULL);
14505 				mp_hw = copyb(mp);
14506 				if (mp_hw == NULL) {
14507 					err = ENOMEM;
14508 					break;
14509 				}
14510 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14511 				mutex_enter(&ill->ill_lock);
14512 				ill->ill_nd_lla_mp = mp_hw;
14513 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14514 				dlp->physaddr_ack.dl_addr_offset;
14515 				ill->ill_nd_lla_len =
14516 					dlp->physaddr_ack.dl_addr_length;
14517 				mutex_exit(&ill->ill_lock);
14518 			}
14519 			break;
14520 		}
14521 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14522 		ASSERT(ill->ill_phys_addr_mp == NULL);
14523 		if (!ill->ill_ifname_pending)
14524 			break;
14525 		ill->ill_ifname_pending = 0;
14526 		if (!ioctl_aborted)
14527 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14528 		if (mp1 != NULL) {
14529 			ASSERT(connp == NULL);
14530 			q = ill->ill_wq;
14531 		}
14532 		/*
14533 		 * If any error acks received during the plumbing sequence,
14534 		 * ill_ifname_pending_err will be set. Break out and send up
14535 		 * the error to the pending ioctl.
14536 		 */
14537 		if (ill->ill_ifname_pending_err != 0) {
14538 			err = ill->ill_ifname_pending_err;
14539 			ill->ill_ifname_pending_err = 0;
14540 			break;
14541 		}
14542 		/*
14543 		 * Get the interface token.  If the zeroth interface
14544 		 * address is zero then set the address to the link local
14545 		 * address
14546 		 */
14547 		mp_hw = copyb(mp);
14548 		if (mp_hw == NULL) {
14549 			err = ENOMEM;
14550 			break;
14551 		}
14552 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14553 		ill->ill_phys_addr_mp = mp_hw;
14554 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14555 				dlp->physaddr_ack.dl_addr_offset;
14556 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14557 		    ill->ill_phys_addr_length == 0 ||
14558 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14559 			/*
14560 			 * Compatibility: atun driver returns a length of 0.
14561 			 * ipdptp has an ill_phys_addr_length of zero(from
14562 			 * DL_BIND_ACK) but a non-zero length here.
14563 			 * ipd has an ill_phys_addr_length of 4(from
14564 			 * DL_BIND_ACK) but a non-zero length here.
14565 			 */
14566 			ill->ill_phys_addr = NULL;
14567 		} else if (dlp->physaddr_ack.dl_addr_length !=
14568 		    ill->ill_phys_addr_length) {
14569 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14570 			    "Address length mismatch %d %d\n",
14571 			    dlp->physaddr_ack.dl_addr_length,
14572 			    ill->ill_phys_addr_length));
14573 			err = EINVAL;
14574 			break;
14575 		}
14576 		mutex_enter(&ill->ill_lock);
14577 		if (ill->ill_nd_lla_mp == NULL) {
14578 			ill->ill_nd_lla_mp = copyb(mp_hw);
14579 			if (ill->ill_nd_lla_mp == NULL) {
14580 				err = ENOMEM;
14581 				mutex_exit(&ill->ill_lock);
14582 				break;
14583 			}
14584 			ill->ill_nd_lla =
14585 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14586 			    dlp->physaddr_ack.dl_addr_offset;
14587 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14588 		}
14589 		mutex_exit(&ill->ill_lock);
14590 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14591 			(void) ill_setdefaulttoken(ill);
14592 
14593 		/*
14594 		 * If the ill zero interface has a zero address assign
14595 		 * it the proper link local address.
14596 		 */
14597 		ASSERT(ill->ill_ipif->ipif_id == 0);
14598 		if (ipif != NULL &&
14599 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14600 			(void) ipif_setlinklocal(ipif);
14601 		break;
14602 	}
14603 	case DL_OK_ACK:
14604 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14605 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14606 		    dloa->dl_correct_primitive));
14607 		switch (dloa->dl_correct_primitive) {
14608 		case DL_UNBIND_REQ:
14609 		case DL_ATTACH_REQ:
14610 		case DL_DETACH_REQ:
14611 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14612 			break;
14613 		}
14614 		break;
14615 	default:
14616 		break;
14617 	}
14618 
14619 	freemsg(mp);
14620 	if (mp1) {
14621 		struct iocblk *iocp;
14622 		int mode;
14623 
14624 		/*
14625 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14626 		 * SIOCSLIFNAME do a copyout.
14627 		 */
14628 		iocp = (struct iocblk *)mp1->b_rptr;
14629 
14630 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14631 		    iocp->ioc_cmd == SIOCSLIFNAME)
14632 			mode = COPYOUT;
14633 		else
14634 			mode = NO_COPYOUT;
14635 		/*
14636 		 * The ioctl must complete now without EINPROGRESS
14637 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14638 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14639 		 * stuck for ever in the ipsq.
14640 		 */
14641 		ASSERT(err != EINPROGRESS);
14642 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14643 
14644 	}
14645 }
14646 
14647 /*
14648  * ip_rput_other is called by ip_rput to handle messages modifying the global
14649  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14650  */
14651 /* ARGSUSED */
14652 void
14653 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14654 {
14655 	ill_t		*ill;
14656 	struct iocblk	*iocp;
14657 	mblk_t		*mp1;
14658 	conn_t		*connp = NULL;
14659 
14660 	ip1dbg(("ip_rput_other "));
14661 	ill = (ill_t *)q->q_ptr;
14662 	/*
14663 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14664 	 * in which case ipsq is NULL.
14665 	 */
14666 	if (ipsq != NULL) {
14667 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14668 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14669 	}
14670 
14671 	switch (mp->b_datap->db_type) {
14672 	case M_ERROR:
14673 	case M_HANGUP:
14674 		/*
14675 		 * The device has a problem.  We force the ILL down.  It can
14676 		 * be brought up again manually using SIOCSIFFLAGS (via
14677 		 * ifconfig or equivalent).
14678 		 */
14679 		ASSERT(ipsq != NULL);
14680 		if (mp->b_rptr < mp->b_wptr)
14681 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14682 		if (ill->ill_error == 0)
14683 			ill->ill_error = ENXIO;
14684 		if (!ill_down_start(q, mp))
14685 			return;
14686 		ipif_all_down_tail(ipsq, q, mp, NULL);
14687 		break;
14688 	case M_IOCACK:
14689 		iocp = (struct iocblk *)mp->b_rptr;
14690 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14691 		switch (iocp->ioc_cmd) {
14692 		case SIOCSTUNPARAM:
14693 		case OSIOCSTUNPARAM:
14694 			ASSERT(ipsq != NULL);
14695 			/*
14696 			 * Finish socket ioctl passed through to tun.
14697 			 * We should have an IOCTL waiting on this.
14698 			 */
14699 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14700 			if (ill->ill_isv6) {
14701 				struct iftun_req *ta;
14702 
14703 				/*
14704 				 * if a source or destination is
14705 				 * being set, try and set the link
14706 				 * local address for the tunnel
14707 				 */
14708 				ta = (struct iftun_req *)mp->b_cont->
14709 				    b_cont->b_rptr;
14710 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14711 					ipif_set_tun_llink(ill, ta);
14712 				}
14713 
14714 			}
14715 			if (mp1 != NULL) {
14716 				/*
14717 				 * Now copy back the b_next/b_prev used by
14718 				 * mi code for the mi_copy* functions.
14719 				 * See ip_sioctl_tunparam() for the reason.
14720 				 * Also protect against missing b_cont.
14721 				 */
14722 				if (mp->b_cont != NULL) {
14723 					mp->b_cont->b_next =
14724 					    mp1->b_cont->b_next;
14725 					mp->b_cont->b_prev =
14726 					    mp1->b_cont->b_prev;
14727 				}
14728 				inet_freemsg(mp1);
14729 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14730 				ASSERT(connp != NULL);
14731 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14732 				    iocp->ioc_error, NO_COPYOUT,
14733 				    ipsq->ipsq_current_ipif, ipsq);
14734 			} else {
14735 				ASSERT(connp == NULL);
14736 				putnext(q, mp);
14737 			}
14738 			break;
14739 		case SIOCGTUNPARAM:
14740 		case OSIOCGTUNPARAM:
14741 			/*
14742 			 * This is really M_IOCDATA from the tunnel driver.
14743 			 * convert back and complete the ioctl.
14744 			 * We should have an IOCTL waiting on this.
14745 			 */
14746 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14747 			if (mp1) {
14748 				/*
14749 				 * Now copy back the b_next/b_prev used by
14750 				 * mi code for the mi_copy* functions.
14751 				 * See ip_sioctl_tunparam() for the reason.
14752 				 * Also protect against missing b_cont.
14753 				 */
14754 				if (mp->b_cont != NULL) {
14755 					mp->b_cont->b_next =
14756 					    mp1->b_cont->b_next;
14757 					mp->b_cont->b_prev =
14758 					    mp1->b_cont->b_prev;
14759 				}
14760 				inet_freemsg(mp1);
14761 				if (iocp->ioc_error == 0)
14762 					mp->b_datap->db_type = M_IOCDATA;
14763 				ASSERT(connp != NULL);
14764 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14765 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14766 			} else {
14767 				ASSERT(connp == NULL);
14768 				putnext(q, mp);
14769 			}
14770 			break;
14771 		default:
14772 			break;
14773 		}
14774 		break;
14775 	case M_IOCNAK:
14776 		iocp = (struct iocblk *)mp->b_rptr;
14777 
14778 		switch (iocp->ioc_cmd) {
14779 		int mode;
14780 		ipif_t	*ipif;
14781 
14782 		case DL_IOC_HDR_INFO:
14783 			/*
14784 			 * If this was the first attempt turn of the
14785 			 * fastpath probing.
14786 			 */
14787 			mutex_enter(&ill->ill_lock);
14788 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14789 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14790 				mutex_exit(&ill->ill_lock);
14791 				ill_fastpath_nack(ill);
14792 				ip1dbg(("ip_rput: DLPI fastpath off on "
14793 				    "interface %s\n",
14794 				    ill->ill_name));
14795 			} else {
14796 				mutex_exit(&ill->ill_lock);
14797 			}
14798 			freemsg(mp);
14799 			break;
14800 		case SIOCSTUNPARAM:
14801 		case OSIOCSTUNPARAM:
14802 			ASSERT(ipsq != NULL);
14803 			/*
14804 			 * Finish socket ioctl passed through to tun
14805 			 * We should have an IOCTL waiting on this.
14806 			 */
14807 			/* FALLTHRU */
14808 		case SIOCGTUNPARAM:
14809 		case OSIOCGTUNPARAM:
14810 			/*
14811 			 * This is really M_IOCDATA from the tunnel driver.
14812 			 * convert back and complete the ioctl.
14813 			 * We should have an IOCTL waiting on this.
14814 			 */
14815 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14816 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14817 				mp1 = ill_pending_mp_get(ill, &connp,
14818 				    iocp->ioc_id);
14819 				mode = COPYOUT;
14820 				ipsq = NULL;
14821 				ipif = NULL;
14822 			} else {
14823 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14824 				mode = NO_COPYOUT;
14825 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14826 				ipif = ipsq->ipsq_current_ipif;
14827 			}
14828 			if (mp1 != NULL) {
14829 				/*
14830 				 * Now copy back the b_next/b_prev used by
14831 				 * mi code for the mi_copy* functions.
14832 				 * See ip_sioctl_tunparam() for the reason.
14833 				 * Also protect against missing b_cont.
14834 				 */
14835 				if (mp->b_cont != NULL) {
14836 					mp->b_cont->b_next =
14837 					    mp1->b_cont->b_next;
14838 					mp->b_cont->b_prev =
14839 					    mp1->b_cont->b_prev;
14840 				}
14841 				inet_freemsg(mp1);
14842 				if (iocp->ioc_error == 0)
14843 					iocp->ioc_error = EINVAL;
14844 				ASSERT(connp != NULL);
14845 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14846 				    iocp->ioc_error, mode, ipif, ipsq);
14847 			} else {
14848 				ASSERT(connp == NULL);
14849 				putnext(q, mp);
14850 			}
14851 			break;
14852 		default:
14853 			break;
14854 		}
14855 	default:
14856 		break;
14857 	}
14858 }
14859 
14860 /*
14861  * NOTE : This function does not ire_refrele the ire argument passed in.
14862  *
14863  * IPQoS notes
14864  * IP policy is invoked twice for a forwarded packet, once on the read side
14865  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14866  * enabled. An additional parameter, in_ill, has been added for this purpose.
14867  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14868  * because ip_mroute drops this information.
14869  *
14870  */
14871 void
14872 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14873 {
14874 	uint32_t	pkt_len;
14875 	queue_t	*q;
14876 	uint32_t	sum;
14877 #define	rptr	((uchar_t *)ipha)
14878 	uint32_t	max_frag;
14879 	uint32_t	ill_index;
14880 
14881 	/* Get the ill_index of the incoming ILL */
14882 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14883 
14884 	/* Initiate Read side IPPF processing */
14885 	if (IPP_ENABLED(IPP_FWD_IN)) {
14886 		ip_process(IPP_FWD_IN, &mp, ill_index);
14887 		if (mp == NULL) {
14888 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14889 			    "during IPPF processing\n"));
14890 			return;
14891 		}
14892 	}
14893 	pkt_len = ntohs(ipha->ipha_length);
14894 
14895 	/* Adjust the checksum to reflect the ttl decrement. */
14896 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14897 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14898 
14899 	if (ipha->ipha_ttl-- <= 1) {
14900 		if (ip_csum_hdr(ipha)) {
14901 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14902 			goto drop_pkt;
14903 		}
14904 		/*
14905 		 * Note: ire_stq this will be NULL for multicast
14906 		 * datagrams using the long path through arp (the IRE
14907 		 * is not an IRE_CACHE). This should not cause
14908 		 * problems since we don't generate ICMP errors for
14909 		 * multicast packets.
14910 		 */
14911 		q = ire->ire_stq;
14912 		if (q)
14913 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14914 		else
14915 			freemsg(mp);
14916 		return;
14917 	}
14918 
14919 	/*
14920 	 * Don't forward if the interface is down
14921 	 */
14922 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14923 		BUMP_MIB(&ip_mib, ipInDiscards);
14924 		goto drop_pkt;
14925 	}
14926 
14927 	/* Get the ill_index of the outgoing ILL */
14928 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14929 
14930 	/* Check if there are options to update */
14931 	if (!IS_SIMPLE_IPH(ipha)) {
14932 		if (ip_csum_hdr(ipha)) {
14933 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14934 			goto drop_pkt;
14935 		}
14936 		if (ip_rput_forward_options(mp, ipha, ire)) {
14937 			return;
14938 		}
14939 
14940 		ipha->ipha_hdr_checksum = 0;
14941 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14942 	}
14943 	max_frag = ire->ire_max_frag;
14944 	if (pkt_len > max_frag) {
14945 		/*
14946 		 * It needs fragging on its way out.  We haven't
14947 		 * verified the header checksum yet.  Since we
14948 		 * are going to put a surely good checksum in the
14949 		 * outgoing header, we have to make sure that it
14950 		 * was good coming in.
14951 		 */
14952 		if (ip_csum_hdr(ipha)) {
14953 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14954 			goto drop_pkt;
14955 		}
14956 		/* Initiate Write side IPPF processing */
14957 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14958 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14959 			if (mp == NULL) {
14960 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14961 				    " during IPPF processing\n"));
14962 				return;
14963 			}
14964 		}
14965 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14966 		return;
14967 	}
14968 
14969 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14970 	if (mp == NULL) {
14971 		BUMP_MIB(&ip_mib, ipInDiscards);
14972 		return;
14973 	}
14974 
14975 	q = ire->ire_stq;
14976 	UPDATE_IB_PKT_COUNT(ire);
14977 	ire->ire_last_used_time = lbolt;
14978 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14979 	putnext(q, mp);
14980 	return;
14981 
14982 drop_pkt:;
14983 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14984 	freemsg(mp);
14985 #undef	rptr
14986 }
14987 
14988 void
14989 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14990 {
14991 	ire_t	*ire;
14992 
14993 	ASSERT(!ipif->ipif_isv6);
14994 	/*
14995 	 * Find an IRE which matches the destination and the outgoing
14996 	 * queue in the cache table. All we need is an IRE_CACHE which
14997 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14998 	 * then it is enough to have some IRE_CACHE in the group.
14999 	 */
15000 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15001 		dst = ipif->ipif_pp_dst_addr;
15002 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
15003 	    MATCH_IRE_ILL_GROUP);
15004 	if (!ire) {
15005 		/*
15006 		 * Mark this packet to make it be delivered to
15007 		 * ip_rput_forward after the new ire has been
15008 		 * created.
15009 		 */
15010 		mp->b_prev = NULL;
15011 		mp->b_next = mp;
15012 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15013 		    NULL, 0);
15014 	} else {
15015 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15016 		IRE_REFRELE(ire);
15017 	}
15018 }
15019 
15020 /* Update any source route, record route or timestamp options */
15021 static int
15022 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15023 {
15024 	ipoptp_t	opts;
15025 	uchar_t		*opt;
15026 	uint8_t		optval;
15027 	uint8_t		optlen;
15028 	ipaddr_t	dst;
15029 	uint32_t	ts;
15030 	ire_t		*dst_ire = NULL;
15031 	ire_t		*tmp_ire = NULL;
15032 	timestruc_t	now;
15033 
15034 	ip2dbg(("ip_rput_forward_options\n"));
15035 	dst = ipha->ipha_dst;
15036 	for (optval = ipoptp_first(&opts, ipha);
15037 	    optval != IPOPT_EOL;
15038 	    optval = ipoptp_next(&opts)) {
15039 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15040 		opt = opts.ipoptp_cur;
15041 		optlen = opts.ipoptp_len;
15042 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15043 		    optval, opts.ipoptp_len));
15044 		switch (optval) {
15045 			uint32_t off;
15046 		case IPOPT_SSRR:
15047 		case IPOPT_LSRR:
15048 			/* Check if adminstratively disabled */
15049 			if (!ip_forward_src_routed) {
15050 				BUMP_MIB(&ip_mib, ipForwProhibits);
15051 				if (ire->ire_stq)
15052 					icmp_unreachable(ire->ire_stq, mp,
15053 					    ICMP_SOURCE_ROUTE_FAILED);
15054 				else {
15055 					ip0dbg(("ip_rput_forward_options: "
15056 					    "unable to send unreach\n"));
15057 					freemsg(mp);
15058 				}
15059 				return (-1);
15060 			}
15061 
15062 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15063 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15064 			if (dst_ire == NULL) {
15065 				/*
15066 				 * Must be partial since ip_rput_options
15067 				 * checked for strict.
15068 				 */
15069 				break;
15070 			}
15071 			off = opt[IPOPT_OFFSET];
15072 			off--;
15073 		redo_srr:
15074 			if (optlen < IP_ADDR_LEN ||
15075 			    off > optlen - IP_ADDR_LEN) {
15076 				/* End of source route */
15077 				ip1dbg((
15078 				    "ip_rput_forward_options: end of SR\n"));
15079 				ire_refrele(dst_ire);
15080 				break;
15081 			}
15082 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15083 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15084 			    IP_ADDR_LEN);
15085 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15086 			    ntohl(dst)));
15087 
15088 			/*
15089 			 * Check if our address is present more than
15090 			 * once as consecutive hops in source route.
15091 			 */
15092 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15093 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15094 			if (tmp_ire != NULL) {
15095 				ire_refrele(tmp_ire);
15096 				off += IP_ADDR_LEN;
15097 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15098 				goto redo_srr;
15099 			}
15100 			ipha->ipha_dst = dst;
15101 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15102 			ire_refrele(dst_ire);
15103 			break;
15104 		case IPOPT_RR:
15105 			off = opt[IPOPT_OFFSET];
15106 			off--;
15107 			if (optlen < IP_ADDR_LEN ||
15108 			    off > optlen - IP_ADDR_LEN) {
15109 				/* No more room - ignore */
15110 				ip1dbg((
15111 				    "ip_rput_forward_options: end of RR\n"));
15112 				break;
15113 			}
15114 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15115 			    IP_ADDR_LEN);
15116 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15117 			break;
15118 		case IPOPT_TS:
15119 			/* Insert timestamp if there is room */
15120 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15121 			case IPOPT_TS_TSONLY:
15122 				off = IPOPT_TS_TIMELEN;
15123 				break;
15124 			case IPOPT_TS_PRESPEC:
15125 			case IPOPT_TS_PRESPEC_RFC791:
15126 				/* Verify that the address matched */
15127 				off = opt[IPOPT_OFFSET] - 1;
15128 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15129 				dst_ire = ire_ctable_lookup(dst, 0,
15130 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
15131 				if (dst_ire == NULL) {
15132 					/* Not for us */
15133 					break;
15134 				}
15135 				ire_refrele(dst_ire);
15136 				/* FALLTHRU */
15137 			case IPOPT_TS_TSANDADDR:
15138 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15139 				break;
15140 			default:
15141 				/*
15142 				 * ip_*put_options should have already
15143 				 * dropped this packet.
15144 				 */
15145 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15146 				    "unknown IT - bug in ip_rput_options?\n");
15147 				return (0);	/* Keep "lint" happy */
15148 			}
15149 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15150 				/* Increase overflow counter */
15151 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15152 				opt[IPOPT_POS_OV_FLG] =
15153 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15154 				    (off << 4));
15155 				break;
15156 			}
15157 			off = opt[IPOPT_OFFSET] - 1;
15158 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15159 			case IPOPT_TS_PRESPEC:
15160 			case IPOPT_TS_PRESPEC_RFC791:
15161 			case IPOPT_TS_TSANDADDR:
15162 				bcopy(&ire->ire_src_addr,
15163 				    (char *)opt + off, IP_ADDR_LEN);
15164 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15165 				/* FALLTHRU */
15166 			case IPOPT_TS_TSONLY:
15167 				off = opt[IPOPT_OFFSET] - 1;
15168 				/* Compute # of milliseconds since midnight */
15169 				gethrestime(&now);
15170 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15171 				    now.tv_nsec / (NANOSEC / MILLISEC);
15172 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15173 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15174 				break;
15175 			}
15176 			break;
15177 		}
15178 	}
15179 	return (0);
15180 }
15181 
15182 /*
15183  * This is called after processing at least one of AH/ESP headers.
15184  *
15185  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15186  * the actual, physical interface on which the packet was received,
15187  * but, when ip_strict_dst_multihoming is set to 1, could be the
15188  * interface which had the ipha_dst configured when the packet went
15189  * through ip_rput. The ill_index corresponding to the recv_ill
15190  * is saved in ipsec_in_rill_index
15191  */
15192 void
15193 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15194 {
15195 	mblk_t *mp;
15196 	ipaddr_t dst;
15197 	in6_addr_t *v6dstp;
15198 	ipha_t *ipha;
15199 	ip6_t *ip6h;
15200 	ipsec_in_t *ii;
15201 	boolean_t ill_need_rele = B_FALSE;
15202 	boolean_t rill_need_rele = B_FALSE;
15203 	boolean_t ire_need_rele = B_FALSE;
15204 
15205 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15206 	ASSERT(ii->ipsec_in_ill_index != 0);
15207 
15208 	mp = ipsec_mp->b_cont;
15209 	ASSERT(mp != NULL);
15210 
15211 
15212 	if (ill == NULL) {
15213 		ASSERT(recv_ill == NULL);
15214 		/*
15215 		 * We need to get the original queue on which ip_rput_local
15216 		 * or ip_rput_data_v6 was called.
15217 		 */
15218 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15219 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15220 		ill_need_rele = B_TRUE;
15221 
15222 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15223 			recv_ill = ill_lookup_on_ifindex(
15224 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15225 			    NULL, NULL, NULL, NULL);
15226 			rill_need_rele = B_TRUE;
15227 		} else {
15228 			recv_ill = ill;
15229 		}
15230 
15231 		if ((ill == NULL) || (recv_ill == NULL)) {
15232 			ip0dbg(("ip_fanout_proto_again: interface "
15233 			    "disappeared\n"));
15234 			if (ill != NULL)
15235 				ill_refrele(ill);
15236 			if (recv_ill != NULL)
15237 				ill_refrele(recv_ill);
15238 			freemsg(ipsec_mp);
15239 			return;
15240 		}
15241 	}
15242 
15243 	ASSERT(ill != NULL && recv_ill != NULL);
15244 
15245 	if (mp->b_datap->db_type == M_CTL) {
15246 		/*
15247 		 * AH/ESP is returning the ICMP message after
15248 		 * removing their headers. Fanout again till
15249 		 * it gets to the right protocol.
15250 		 */
15251 		if (ii->ipsec_in_v4) {
15252 			icmph_t *icmph;
15253 			int iph_hdr_length;
15254 			int hdr_length;
15255 
15256 			ipha = (ipha_t *)mp->b_rptr;
15257 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15258 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15259 			ipha = (ipha_t *)&icmph[1];
15260 			hdr_length = IPH_HDR_LENGTH(ipha);
15261 			/*
15262 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15263 			 * Reset the type to M_DATA.
15264 			 */
15265 			mp->b_datap->db_type = M_DATA;
15266 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15267 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15268 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15269 		} else {
15270 			icmp6_t *icmp6;
15271 			int hdr_length;
15272 
15273 			ip6h = (ip6_t *)mp->b_rptr;
15274 			/* Don't call hdr_length_v6() unless you have to. */
15275 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15276 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15277 			else
15278 				hdr_length = IPV6_HDR_LEN;
15279 
15280 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15281 			/*
15282 			 * icmp_inbound_error_fanout_v6 may need to do
15283 			 * pullupmsg.  Reset the type to M_DATA.
15284 			 */
15285 			mp->b_datap->db_type = M_DATA;
15286 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15287 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15288 		}
15289 		if (ill_need_rele)
15290 			ill_refrele(ill);
15291 		if (rill_need_rele)
15292 			ill_refrele(recv_ill);
15293 		return;
15294 	}
15295 
15296 	if (ii->ipsec_in_v4) {
15297 		ipha = (ipha_t *)mp->b_rptr;
15298 		dst = ipha->ipha_dst;
15299 		if (CLASSD(dst)) {
15300 			/*
15301 			 * Multicast has to be delivered to all streams.
15302 			 */
15303 			dst = INADDR_BROADCAST;
15304 		}
15305 
15306 		if (ire == NULL) {
15307 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15308 			if (ire == NULL) {
15309 				if (ill_need_rele)
15310 					ill_refrele(ill);
15311 				if (rill_need_rele)
15312 					ill_refrele(recv_ill);
15313 				ip1dbg(("ip_fanout_proto_again: "
15314 				    "IRE not found"));
15315 				freemsg(ipsec_mp);
15316 				return;
15317 			}
15318 			ire_need_rele = B_TRUE;
15319 		}
15320 
15321 		switch (ipha->ipha_protocol) {
15322 			case IPPROTO_UDP:
15323 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15324 				    recv_ill);
15325 				if (ire_need_rele)
15326 					ire_refrele(ire);
15327 				break;
15328 			case IPPROTO_TCP:
15329 				if (!ire_need_rele)
15330 					IRE_REFHOLD(ire);
15331 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15332 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15333 				IRE_REFRELE(ire);
15334 				if (mp != NULL)
15335 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15336 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15337 				break;
15338 			case IPPROTO_SCTP:
15339 				if (!ire_need_rele)
15340 					IRE_REFHOLD(ire);
15341 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15342 				    ipsec_mp, 0, ill->ill_rq, dst);
15343 				break;
15344 			default:
15345 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15346 				    recv_ill);
15347 				if (ire_need_rele)
15348 					ire_refrele(ire);
15349 				break;
15350 		}
15351 	} else {
15352 		uint32_t rput_flags = 0;
15353 
15354 		ip6h = (ip6_t *)mp->b_rptr;
15355 		v6dstp = &ip6h->ip6_dst;
15356 		/*
15357 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15358 		 * address.
15359 		 *
15360 		 * Currently, we don't store that state in the IPSEC_IN
15361 		 * message, and we may need to.
15362 		 */
15363 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15364 		    IP6_IN_LLMCAST : 0);
15365 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15366 		    NULL);
15367 	}
15368 	if (ill_need_rele)
15369 		ill_refrele(ill);
15370 	if (rill_need_rele)
15371 		ill_refrele(recv_ill);
15372 }
15373 
15374 /*
15375  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15376  * returns 'true' if there are still fragments left on the queue, in
15377  * which case we restart the timer.
15378  */
15379 void
15380 ill_frag_timer(void *arg)
15381 {
15382 	ill_t	*ill = (ill_t *)arg;
15383 	boolean_t frag_pending;
15384 
15385 	mutex_enter(&ill->ill_lock);
15386 	ASSERT(!ill->ill_fragtimer_executing);
15387 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15388 		ill->ill_frag_timer_id = 0;
15389 		mutex_exit(&ill->ill_lock);
15390 		return;
15391 	}
15392 	ill->ill_fragtimer_executing = 1;
15393 	mutex_exit(&ill->ill_lock);
15394 
15395 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15396 
15397 	/*
15398 	 * Restart the timer, if we have fragments pending or if someone
15399 	 * wanted us to be scheduled again.
15400 	 */
15401 	mutex_enter(&ill->ill_lock);
15402 	ill->ill_fragtimer_executing = 0;
15403 	ill->ill_frag_timer_id = 0;
15404 	if (frag_pending || ill->ill_fragtimer_needrestart)
15405 		ill_frag_timer_start(ill);
15406 	mutex_exit(&ill->ill_lock);
15407 }
15408 
15409 void
15410 ill_frag_timer_start(ill_t *ill)
15411 {
15412 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15413 
15414 	/* If the ill is closing or opening don't proceed */
15415 	if (ill->ill_state_flags & ILL_CONDEMNED)
15416 		return;
15417 
15418 	if (ill->ill_fragtimer_executing) {
15419 		/*
15420 		 * ill_frag_timer is currently executing. Just record the
15421 		 * the fact that we want the timer to be restarted.
15422 		 * ill_frag_timer will post a timeout before it returns,
15423 		 * ensuring it will be called again.
15424 		 */
15425 		ill->ill_fragtimer_needrestart = 1;
15426 		return;
15427 	}
15428 
15429 	if (ill->ill_frag_timer_id == 0) {
15430 		/*
15431 		 * The timer is neither running nor is the timeout handler
15432 		 * executing. Post a timeout so that ill_frag_timer will be
15433 		 * called
15434 		 */
15435 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15436 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15437 		ill->ill_fragtimer_needrestart = 0;
15438 	}
15439 }
15440 
15441 /*
15442  * This routine is needed for loopback when forwarding multicasts.
15443  *
15444  * IPQoS Notes:
15445  * IPPF processing is done in fanout routines.
15446  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15447  * processing for IPSec packets is done when it comes back in clear.
15448  * NOTE : The callers of this function need to do the ire_refrele for the
15449  *	  ire that is being passed in.
15450  */
15451 void
15452 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15453     ill_t *recv_ill)
15454 {
15455 	ill_t	*ill = (ill_t *)q->q_ptr;
15456 	uint32_t	sum;
15457 	uint32_t	u1;
15458 	uint32_t	u2;
15459 	int		hdr_length;
15460 	boolean_t	mctl_present;
15461 	mblk_t		*first_mp = mp;
15462 	mblk_t		*hada_mp = NULL;
15463 	ipha_t		*inner_ipha;
15464 
15465 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15466 	    "ip_rput_locl_start: q %p", q);
15467 
15468 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15469 
15470 
15471 #define	rptr	((uchar_t *)ipha)
15472 #define	iphs	((uint16_t *)ipha)
15473 
15474 	/*
15475 	 * no UDP or TCP packet should come here anymore.
15476 	 */
15477 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15478 	    (ipha->ipha_protocol != IPPROTO_UDP));
15479 
15480 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15481 	if (mctl_present &&
15482 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15483 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15484 
15485 		/*
15486 		 * It's an IPsec accelerated packet.
15487 		 * Keep a pointer to the data attributes around until
15488 		 * we allocate the ipsec_info_t.
15489 		 */
15490 		IPSECHW_DEBUG(IPSECHW_PKT,
15491 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15492 		hada_mp = first_mp;
15493 		hada_mp->b_cont = NULL;
15494 		/*
15495 		 * Since it is accelerated, it comes directly from
15496 		 * the ill and the data attributes is followed by
15497 		 * the packet data.
15498 		 */
15499 		ASSERT(mp->b_datap->db_type != M_CTL);
15500 		first_mp = mp;
15501 		mctl_present = B_FALSE;
15502 	}
15503 
15504 	/*
15505 	 * IF M_CTL is not present, then ipsec_in_is_secure
15506 	 * should return B_TRUE. There is a case where loopback
15507 	 * packets has an M_CTL in the front with all the
15508 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15509 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15510 	 * packets never comes here, it is safe to ASSERT the
15511 	 * following.
15512 	 */
15513 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15514 
15515 
15516 	/* u1 is # words of IP options */
15517 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15518 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15519 
15520 	if (u1) {
15521 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15522 			if (hada_mp != NULL)
15523 				freemsg(hada_mp);
15524 			return;
15525 		}
15526 	} else {
15527 		/* Check the IP header checksum.  */
15528 #define	uph	((uint16_t *)ipha)
15529 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15530 		    uph[6] + uph[7] + uph[8] + uph[9];
15531 #undef  uph
15532 		/* finish doing IP checksum */
15533 		sum = (sum & 0xFFFF) + (sum >> 16);
15534 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15535 		/*
15536 		 * Don't verify header checksum if this packet is coming
15537 		 * back from AH/ESP as we already did it.
15538 		 */
15539 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15540 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15541 			goto drop_pkt;
15542 		}
15543 	}
15544 
15545 	/*
15546 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15547 	 * might be called more than once for secure packets, count only
15548 	 * the first time.
15549 	 */
15550 	if (!mctl_present) {
15551 		UPDATE_IB_PKT_COUNT(ire);
15552 		ire->ire_last_used_time = lbolt;
15553 	}
15554 
15555 	/* Check for fragmentation offset. */
15556 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15557 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15558 	if (u1) {
15559 		/*
15560 		 * We re-assemble fragments before we do the AH/ESP
15561 		 * processing. Thus, M_CTL should not be present
15562 		 * while we are re-assembling.
15563 		 */
15564 		ASSERT(!mctl_present);
15565 		ASSERT(first_mp == mp);
15566 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
15567 			return;
15568 		}
15569 		/*
15570 		 * Make sure that first_mp points back to mp as
15571 		 * the mp we came in with could have changed in
15572 		 * ip_rput_fragment().
15573 		 */
15574 		ipha = (ipha_t *)mp->b_rptr;
15575 		first_mp = mp;
15576 	}
15577 
15578 	/*
15579 	 * Clear hardware checksumming flag as it is currently only
15580 	 * used by TCP and UDP.
15581 	 */
15582 	DB_CKSUMFLAGS(mp) = 0;
15583 
15584 	/* Now we have a complete datagram, destined for this machine. */
15585 	u1 = IPH_HDR_LENGTH(ipha);
15586 	switch (ipha->ipha_protocol) {
15587 	case IPPROTO_ICMP: {
15588 		ire_t		*ire_zone;
15589 		ilm_t		*ilm;
15590 		mblk_t		*mp1;
15591 		zoneid_t	last_zoneid;
15592 
15593 		if (CLASSD(ipha->ipha_dst) &&
15594 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15595 			ASSERT(ire->ire_type == IRE_BROADCAST);
15596 			/*
15597 			 * In the multicast case, applications may have joined
15598 			 * the group from different zones, so we need to deliver
15599 			 * the packet to each of them. Loop through the
15600 			 * multicast memberships structures (ilm) on the receive
15601 			 * ill and send a copy of the packet up each matching
15602 			 * one. However, we don't do this for multicasts sent on
15603 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15604 			 * they must stay in the sender's zone.
15605 			 *
15606 			 * ilm_add_v6() ensures that ilms in the same zone are
15607 			 * contiguous in the ill_ilm list. We use this property
15608 			 * to avoid sending duplicates needed when two
15609 			 * applications in the same zone join the same group on
15610 			 * different logical interfaces: we ignore the ilm if
15611 			 * its zoneid is the same as the last matching one.
15612 			 * In addition, the sending of the packet for
15613 			 * ire_zoneid is delayed until all of the other ilms
15614 			 * have been exhausted.
15615 			 */
15616 			last_zoneid = -1;
15617 			ILM_WALKER_HOLD(recv_ill);
15618 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15619 			    ilm = ilm->ilm_next) {
15620 				if ((ilm->ilm_flags & ILM_DELETED) ||
15621 				    ipha->ipha_dst != ilm->ilm_addr ||
15622 				    ilm->ilm_zoneid == last_zoneid ||
15623 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15624 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15625 					continue;
15626 				mp1 = ip_copymsg(first_mp);
15627 				if (mp1 == NULL)
15628 					continue;
15629 				icmp_inbound(q, mp1, B_TRUE, ill,
15630 				    0, sum, mctl_present, B_TRUE,
15631 				    recv_ill, ilm->ilm_zoneid);
15632 				last_zoneid = ilm->ilm_zoneid;
15633 			}
15634 			ILM_WALKER_RELE(recv_ill);
15635 		} else if (ire->ire_type == IRE_BROADCAST) {
15636 			/*
15637 			 * In the broadcast case, there may be many zones
15638 			 * which need a copy of the packet delivered to them.
15639 			 * There is one IRE_BROADCAST per broadcast address
15640 			 * and per zone; we walk those using a helper function.
15641 			 * In addition, the sending of the packet for ire is
15642 			 * delayed until all of the other ires have been
15643 			 * processed.
15644 			 */
15645 			IRB_REFHOLD(ire->ire_bucket);
15646 			ire_zone = NULL;
15647 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15648 			    ire)) != NULL) {
15649 				mp1 = ip_copymsg(first_mp);
15650 				if (mp1 == NULL)
15651 					continue;
15652 
15653 				UPDATE_IB_PKT_COUNT(ire_zone);
15654 				ire_zone->ire_last_used_time = lbolt;
15655 				icmp_inbound(q, mp1, B_TRUE, ill,
15656 				    0, sum, mctl_present, B_TRUE,
15657 				    recv_ill, ire_zone->ire_zoneid);
15658 			}
15659 			IRB_REFRELE(ire->ire_bucket);
15660 		}
15661 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15662 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15663 		    ire->ire_zoneid);
15664 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15665 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15666 		return;
15667 	}
15668 	case IPPROTO_IGMP:
15669 		/*
15670 		 * If we are not willing to accept IGMP packets in clear,
15671 		 * then check with global policy.
15672 		 */
15673 		if (igmp_accept_clear_messages == 0) {
15674 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15675 			    ipha, NULL, mctl_present);
15676 			if (first_mp == NULL)
15677 				return;
15678 		}
15679 		if (igmp_input(q, mp, ill)) {
15680 			/* Bad packet - discarded by igmp_input */
15681 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15682 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15683 			if (mctl_present)
15684 				freeb(first_mp);
15685 			return;
15686 		}
15687 		/*
15688 		 * igmp_input() may have pulled up the message so ipha needs to
15689 		 * be reinitialized.
15690 		 */
15691 		ipha = (ipha_t *)mp->b_rptr;
15692 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15693 			/* No user-level listener for IGMP packets */
15694 			goto drop_pkt;
15695 		}
15696 		/* deliver to local raw users */
15697 		break;
15698 	case IPPROTO_PIM:
15699 		/*
15700 		 * If we are not willing to accept PIM packets in clear,
15701 		 * then check with global policy.
15702 		 */
15703 		if (pim_accept_clear_messages == 0) {
15704 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15705 			    ipha, NULL, mctl_present);
15706 			if (first_mp == NULL)
15707 				return;
15708 		}
15709 		if (pim_input(q, mp) != 0) {
15710 			/* Bad packet - discarded by pim_input */
15711 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15712 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15713 			if (mctl_present)
15714 				freeb(first_mp);
15715 			return;
15716 		}
15717 
15718 		/*
15719 		 * pim_input() may have pulled up the message so ipha needs to
15720 		 * be reinitialized.
15721 		 */
15722 		ipha = (ipha_t *)mp->b_rptr;
15723 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15724 			/* No user-level listener for PIM packets */
15725 			goto drop_pkt;
15726 		}
15727 		/* deliver to local raw users */
15728 		break;
15729 	case IPPROTO_ENCAP:
15730 		/*
15731 		 * Handle self-encapsulated packets (IP-in-IP where
15732 		 * the inner addresses == the outer addresses).
15733 		 */
15734 		hdr_length = IPH_HDR_LENGTH(ipha);
15735 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15736 		    mp->b_wptr) {
15737 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15738 			    sizeof (ipha_t) - mp->b_rptr)) {
15739 				BUMP_MIB(&ip_mib, ipInDiscards);
15740 				freemsg(first_mp);
15741 				return;
15742 			}
15743 			ipha = (ipha_t *)mp->b_rptr;
15744 		}
15745 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15746 		/*
15747 		 * Check the sanity of the inner IP header.
15748 		 */
15749 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15750 			BUMP_MIB(&ip_mib, ipInDiscards);
15751 			freemsg(first_mp);
15752 			return;
15753 		}
15754 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15755 			BUMP_MIB(&ip_mib, ipInDiscards);
15756 			freemsg(first_mp);
15757 			return;
15758 		}
15759 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15760 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15761 			ipsec_in_t *ii;
15762 
15763 			/*
15764 			 * Self-encapsulated tunnel packet. Remove
15765 			 * the outer IP header and fanout again.
15766 			 * We also need to make sure that the inner
15767 			 * header is pulled up until options.
15768 			 */
15769 			mp->b_rptr = (uchar_t *)inner_ipha;
15770 			ipha = inner_ipha;
15771 			hdr_length = IPH_HDR_LENGTH(ipha);
15772 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15773 				if (!pullupmsg(mp, (uchar_t *)ipha +
15774 				    + hdr_length - mp->b_rptr)) {
15775 					freemsg(first_mp);
15776 					return;
15777 				}
15778 				ipha = (ipha_t *)mp->b_rptr;
15779 			}
15780 			if (!mctl_present) {
15781 				ASSERT(first_mp == mp);
15782 				/*
15783 				 * This means that somebody is sending
15784 				 * Self-encapsualted packets without AH/ESP.
15785 				 * If AH/ESP was present, we would have already
15786 				 * allocated the first_mp.
15787 				 */
15788 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15789 				    NULL) {
15790 					ip1dbg(("ip_proto_input: IPSEC_IN "
15791 					    "allocation failure.\n"));
15792 					BUMP_MIB(&ip_mib, ipInDiscards);
15793 					freemsg(mp);
15794 					return;
15795 				}
15796 				first_mp->b_cont = mp;
15797 			}
15798 			/*
15799 			 * We generally store the ill_index if we need to
15800 			 * do IPSEC processing as we lose the ill queue when
15801 			 * we come back. But in this case, we never should
15802 			 * have to store the ill_index here as it should have
15803 			 * been stored previously when we processed the
15804 			 * AH/ESP header in this routine or for non-ipsec
15805 			 * cases, we still have the queue. But for some bad
15806 			 * packets from the wire, we can get to IPSEC after
15807 			 * this and we better store the index for that case.
15808 			 */
15809 			ill = (ill_t *)q->q_ptr;
15810 			ii = (ipsec_in_t *)first_mp->b_rptr;
15811 			ii->ipsec_in_ill_index =
15812 			    ill->ill_phyint->phyint_ifindex;
15813 			ii->ipsec_in_rill_index =
15814 			    recv_ill->ill_phyint->phyint_ifindex;
15815 			if (ii->ipsec_in_decaps) {
15816 				/*
15817 				 * This packet is self-encapsulated multiple
15818 				 * times. We don't want to recurse infinitely.
15819 				 * To keep it simple, drop the packet.
15820 				 */
15821 				BUMP_MIB(&ip_mib, ipInDiscards);
15822 				freemsg(first_mp);
15823 				return;
15824 			}
15825 			ii->ipsec_in_decaps = B_TRUE;
15826 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15827 			return;
15828 		}
15829 		break;
15830 	case IPPROTO_AH:
15831 	case IPPROTO_ESP: {
15832 		/*
15833 		 * Fast path for AH/ESP. If this is the first time
15834 		 * we are sending a datagram to AH/ESP, allocate
15835 		 * a IPSEC_IN message and prepend it. Otherwise,
15836 		 * just fanout.
15837 		 */
15838 
15839 		int ipsec_rc;
15840 		ipsec_in_t *ii;
15841 
15842 		IP_STAT(ipsec_proto_ahesp);
15843 		if (!mctl_present) {
15844 			ASSERT(first_mp == mp);
15845 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15846 				ip1dbg(("ip_proto_input: IPSEC_IN "
15847 				    "allocation failure.\n"));
15848 				freemsg(hada_mp); /* okay ifnull */
15849 				BUMP_MIB(&ip_mib, ipInDiscards);
15850 				freemsg(mp);
15851 				return;
15852 			}
15853 			/*
15854 			 * Store the ill_index so that when we come back
15855 			 * from IPSEC we ride on the same queue.
15856 			 */
15857 			ill = (ill_t *)q->q_ptr;
15858 			ii = (ipsec_in_t *)first_mp->b_rptr;
15859 			ii->ipsec_in_ill_index =
15860 			    ill->ill_phyint->phyint_ifindex;
15861 			ii->ipsec_in_rill_index =
15862 			    recv_ill->ill_phyint->phyint_ifindex;
15863 			first_mp->b_cont = mp;
15864 			/*
15865 			 * Cache hardware acceleration info.
15866 			 */
15867 			if (hada_mp != NULL) {
15868 				IPSECHW_DEBUG(IPSECHW_PKT,
15869 				    ("ip_rput_local: caching data attr.\n"));
15870 				ii->ipsec_in_accelerated = B_TRUE;
15871 				ii->ipsec_in_da = hada_mp;
15872 				hada_mp = NULL;
15873 			}
15874 		} else {
15875 			ii = (ipsec_in_t *)first_mp->b_rptr;
15876 		}
15877 
15878 		if (!ipsec_loaded()) {
15879 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15880 			    ire->ire_zoneid);
15881 			return;
15882 		}
15883 
15884 		/* select inbound SA and have IPsec process the pkt */
15885 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15886 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15887 			if (esph == NULL)
15888 				return;
15889 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15890 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15891 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15892 			    first_mp, esph);
15893 		} else {
15894 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15895 			if (ah == NULL)
15896 				return;
15897 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15898 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15899 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15900 			    first_mp, ah);
15901 		}
15902 
15903 		switch (ipsec_rc) {
15904 		case IPSEC_STATUS_SUCCESS:
15905 			break;
15906 		case IPSEC_STATUS_FAILED:
15907 			BUMP_MIB(&ip_mib, ipInDiscards);
15908 			/* FALLTHRU */
15909 		case IPSEC_STATUS_PENDING:
15910 			return;
15911 		}
15912 		/* we're done with IPsec processing, send it up */
15913 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15914 		return;
15915 	}
15916 	default:
15917 		break;
15918 	}
15919 	/*
15920 	 * Handle protocols with which IP is less intimate.  There
15921 	 * can be more than one stream bound to a particular
15922 	 * protocol.  When this is the case, each one gets a copy
15923 	 * of any incoming packets.
15924 	 */
15925 	ip_fanout_proto(q, first_mp, ill, ipha,
15926 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15927 	    B_TRUE, recv_ill, ire->ire_zoneid);
15928 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15929 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15930 	return;
15931 
15932 drop_pkt:
15933 	freemsg(first_mp);
15934 	if (hada_mp != NULL)
15935 		freeb(hada_mp);
15936 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15937 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15938 #undef	rptr
15939 #undef  iphs
15940 
15941 }
15942 
15943 /*
15944  * Update any source route, record route or timestamp options.
15945  * Check that we are at end of strict source route.
15946  * The options have already been checked for sanity in ip_rput_options().
15947  */
15948 static boolean_t
15949 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15950 {
15951 	ipoptp_t	opts;
15952 	uchar_t		*opt;
15953 	uint8_t		optval;
15954 	uint8_t		optlen;
15955 	ipaddr_t	dst;
15956 	uint32_t	ts;
15957 	ire_t		*dst_ire;
15958 	timestruc_t	now;
15959 
15960 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15961 
15962 	ip2dbg(("ip_rput_local_options\n"));
15963 
15964 	for (optval = ipoptp_first(&opts, ipha);
15965 	    optval != IPOPT_EOL;
15966 	    optval = ipoptp_next(&opts)) {
15967 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15968 		opt = opts.ipoptp_cur;
15969 		optlen = opts.ipoptp_len;
15970 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15971 		    optval, optlen));
15972 		switch (optval) {
15973 			uint32_t off;
15974 		case IPOPT_SSRR:
15975 		case IPOPT_LSRR:
15976 			off = opt[IPOPT_OFFSET];
15977 			off--;
15978 			if (optlen < IP_ADDR_LEN ||
15979 			    off > optlen - IP_ADDR_LEN) {
15980 				/* End of source route */
15981 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15982 				break;
15983 			}
15984 			/*
15985 			 * This will only happen if two consecutive entries
15986 			 * in the source route contains our address or if
15987 			 * it is a packet with a loose source route which
15988 			 * reaches us before consuming the whole source route
15989 			 */
15990 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15991 			if (optval == IPOPT_SSRR) {
15992 				goto bad_src_route;
15993 			}
15994 			/*
15995 			 * Hack: instead of dropping the packet truncate the
15996 			 * source route to what has been used by filling the
15997 			 * rest with IPOPT_NOP.
15998 			 */
15999 			opt[IPOPT_OLEN] = (uint8_t)off;
16000 			while (off < optlen) {
16001 				opt[off++] = IPOPT_NOP;
16002 			}
16003 			break;
16004 		case IPOPT_RR:
16005 			off = opt[IPOPT_OFFSET];
16006 			off--;
16007 			if (optlen < IP_ADDR_LEN ||
16008 			    off > optlen - IP_ADDR_LEN) {
16009 				/* No more room - ignore */
16010 				ip1dbg((
16011 				    "ip_rput_local_options: end of RR\n"));
16012 				break;
16013 			}
16014 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16015 			    IP_ADDR_LEN);
16016 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16017 			break;
16018 		case IPOPT_TS:
16019 			/* Insert timestamp if there is romm */
16020 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16021 			case IPOPT_TS_TSONLY:
16022 				off = IPOPT_TS_TIMELEN;
16023 				break;
16024 			case IPOPT_TS_PRESPEC:
16025 			case IPOPT_TS_PRESPEC_RFC791:
16026 				/* Verify that the address matched */
16027 				off = opt[IPOPT_OFFSET] - 1;
16028 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16029 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16030 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
16031 				if (dst_ire == NULL) {
16032 					/* Not for us */
16033 					break;
16034 				}
16035 				ire_refrele(dst_ire);
16036 				/* FALLTHRU */
16037 			case IPOPT_TS_TSANDADDR:
16038 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16039 				break;
16040 			default:
16041 				/*
16042 				 * ip_*put_options should have already
16043 				 * dropped this packet.
16044 				 */
16045 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16046 				    "unknown IT - bug in ip_rput_options?\n");
16047 				return (B_TRUE);	/* Keep "lint" happy */
16048 			}
16049 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16050 				/* Increase overflow counter */
16051 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16052 				opt[IPOPT_POS_OV_FLG] =
16053 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16054 				    (off << 4));
16055 				break;
16056 			}
16057 			off = opt[IPOPT_OFFSET] - 1;
16058 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16059 			case IPOPT_TS_PRESPEC:
16060 			case IPOPT_TS_PRESPEC_RFC791:
16061 			case IPOPT_TS_TSANDADDR:
16062 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16063 				    IP_ADDR_LEN);
16064 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16065 				/* FALLTHRU */
16066 			case IPOPT_TS_TSONLY:
16067 				off = opt[IPOPT_OFFSET] - 1;
16068 				/* Compute # of milliseconds since midnight */
16069 				gethrestime(&now);
16070 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16071 				    now.tv_nsec / (NANOSEC / MILLISEC);
16072 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16073 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16074 				break;
16075 			}
16076 			break;
16077 		}
16078 	}
16079 	return (B_TRUE);
16080 
16081 bad_src_route:
16082 	q = WR(q);
16083 	/* make sure we clear any indication of a hardware checksum */
16084 	DB_CKSUMFLAGS(mp) = 0;
16085 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16086 	return (B_FALSE);
16087 
16088 }
16089 
16090 /*
16091  * Process IP options in an inbound packet.  If an option affects the
16092  * effective destination address, return the next hop address via dstp.
16093  * Returns -1 if something fails in which case an ICMP error has been sent
16094  * and mp freed.
16095  */
16096 static int
16097 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16098 {
16099 	ipoptp_t	opts;
16100 	uchar_t		*opt;
16101 	uint8_t		optval;
16102 	uint8_t		optlen;
16103 	ipaddr_t	dst;
16104 	intptr_t	code = 0;
16105 	ire_t		*ire = NULL;
16106 
16107 	ip2dbg(("ip_rput_options\n"));
16108 	dst = ipha->ipha_dst;
16109 	for (optval = ipoptp_first(&opts, ipha);
16110 	    optval != IPOPT_EOL;
16111 	    optval = ipoptp_next(&opts)) {
16112 		opt = opts.ipoptp_cur;
16113 		optlen = opts.ipoptp_len;
16114 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16115 		    optval, optlen));
16116 		/*
16117 		 * Note: we need to verify the checksum before we
16118 		 * modify anything thus this routine only extracts the next
16119 		 * hop dst from any source route.
16120 		 */
16121 		switch (optval) {
16122 			uint32_t off;
16123 		case IPOPT_SSRR:
16124 		case IPOPT_LSRR:
16125 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16126 			    ALL_ZONES, MATCH_IRE_TYPE);
16127 			if (ire == NULL) {
16128 				if (optval == IPOPT_SSRR) {
16129 					ip1dbg(("ip_rput_options: not next"
16130 					    " strict source route 0x%x\n",
16131 					    ntohl(dst)));
16132 					code = (char *)&ipha->ipha_dst -
16133 					    (char *)ipha;
16134 					goto param_prob; /* RouterReq's */
16135 				}
16136 				ip2dbg(("ip_rput_options: "
16137 				    "not next source route 0x%x\n",
16138 				    ntohl(dst)));
16139 				break;
16140 			}
16141 			ire_refrele(ire);
16142 
16143 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16144 				ip1dbg((
16145 				    "ip_rput_options: bad option offset\n"));
16146 				code = (char *)&opt[IPOPT_OLEN] -
16147 				    (char *)ipha;
16148 				goto param_prob;
16149 			}
16150 			off = opt[IPOPT_OFFSET];
16151 			off--;
16152 		redo_srr:
16153 			if (optlen < IP_ADDR_LEN ||
16154 			    off > optlen - IP_ADDR_LEN) {
16155 				/* End of source route */
16156 				ip1dbg(("ip_rput_options: end of SR\n"));
16157 				break;
16158 			}
16159 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16160 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16161 			    ntohl(dst)));
16162 
16163 			/*
16164 			 * Check if our address is present more than
16165 			 * once as consecutive hops in source route.
16166 			 * XXX verify per-interface ip_forwarding
16167 			 * for source route?
16168 			 */
16169 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16170 			    ALL_ZONES, MATCH_IRE_TYPE);
16171 
16172 			if (ire != NULL) {
16173 				ire_refrele(ire);
16174 				off += IP_ADDR_LEN;
16175 				goto redo_srr;
16176 			}
16177 
16178 			if (dst == htonl(INADDR_LOOPBACK)) {
16179 				ip1dbg(("ip_rput_options: loopback addr in "
16180 				    "source route!\n"));
16181 				goto bad_src_route;
16182 			}
16183 			/*
16184 			 * For strict: verify that dst is directly
16185 			 * reachable.
16186 			 */
16187 			if (optval == IPOPT_SSRR) {
16188 				ire = ire_ftable_lookup(dst, 0, 0,
16189 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16190 				    MATCH_IRE_TYPE);
16191 				if (ire == NULL) {
16192 					ip1dbg(("ip_rput_options: SSRR not "
16193 					    "directly reachable: 0x%x\n",
16194 					    ntohl(dst)));
16195 					goto bad_src_route;
16196 				}
16197 				ire_refrele(ire);
16198 			}
16199 			/*
16200 			 * Defer update of the offset and the record route
16201 			 * until the packet is forwarded.
16202 			 */
16203 			break;
16204 		case IPOPT_RR:
16205 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16206 				ip1dbg((
16207 				    "ip_rput_options: bad option offset\n"));
16208 				code = (char *)&opt[IPOPT_OLEN] -
16209 				    (char *)ipha;
16210 				goto param_prob;
16211 			}
16212 			break;
16213 		case IPOPT_TS:
16214 			/*
16215 			 * Verify that length >= 5 and that there is either
16216 			 * room for another timestamp or that the overflow
16217 			 * counter is not maxed out.
16218 			 */
16219 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16220 			if (optlen < IPOPT_MINLEN_IT) {
16221 				goto param_prob;
16222 			}
16223 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16224 				ip1dbg((
16225 				    "ip_rput_options: bad option offset\n"));
16226 				code = (char *)&opt[IPOPT_OFFSET] -
16227 				    (char *)ipha;
16228 				goto param_prob;
16229 			}
16230 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16231 			case IPOPT_TS_TSONLY:
16232 				off = IPOPT_TS_TIMELEN;
16233 				break;
16234 			case IPOPT_TS_TSANDADDR:
16235 			case IPOPT_TS_PRESPEC:
16236 			case IPOPT_TS_PRESPEC_RFC791:
16237 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16238 				break;
16239 			default:
16240 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16241 				    (char *)ipha;
16242 				goto param_prob;
16243 			}
16244 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16245 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16246 				/*
16247 				 * No room and the overflow counter is 15
16248 				 * already.
16249 				 */
16250 				goto param_prob;
16251 			}
16252 			break;
16253 		}
16254 	}
16255 
16256 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16257 		*dstp = dst;
16258 		return (0);
16259 	}
16260 
16261 	ip1dbg(("ip_rput_options: error processing IP options."));
16262 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16263 
16264 param_prob:
16265 	q = WR(q);
16266 	/* make sure we clear any indication of a hardware checksum */
16267 	DB_CKSUMFLAGS(mp) = 0;
16268 	icmp_param_problem(q, mp, (uint8_t)code);
16269 	return (-1);
16270 
16271 bad_src_route:
16272 	q = WR(q);
16273 	/* make sure we clear any indication of a hardware checksum */
16274 	DB_CKSUMFLAGS(mp) = 0;
16275 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16276 	return (-1);
16277 }
16278 
16279 /*
16280  * IP & ICMP info in >=14 msg's ...
16281  *  - ip fixed part (mib2_ip_t)
16282  *  - icmp fixed part (mib2_icmp_t)
16283  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16284  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16285  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16286  *  - ip multicast membership (ip_member_t)
16287  *  - ip multicast source filtering (ip_grpsrc_t)
16288  *  - igmp fixed part (struct igmpstat)
16289  *  - multicast routing stats (struct mrtstat)
16290  *  - multicast routing vifs (array of struct vifctl)
16291  *  - multicast routing routes (array of struct mfcctl)
16292  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16293  *					One per ill plus one generic
16294  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16295  *					One per ill plus one generic
16296  *  - ipv6RouteEntry			all IPv6 IREs
16297  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16298  *  - ipv6AddrEntry			all IPv6 ipifs
16299  *  - ipv6 multicast membership (ipv6_member_t)
16300  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16301  *
16302  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16303  * already present.
16304  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16305  * already filled in by caller.
16306  * Return value of 0 indicates that no messages were sent and caller
16307  * should free mpctl.
16308  */
16309 int
16310 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16311 {
16312 
16313 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16314 		return (0);
16315 	}
16316 
16317 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16318 		return (1);
16319 	}
16320 
16321 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16322 		return (1);
16323 	}
16324 
16325 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16326 		return (1);
16327 	}
16328 
16329 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16330 		return (1);
16331 	}
16332 
16333 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16334 		return (1);
16335 	}
16336 
16337 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16338 		return (1);
16339 	}
16340 
16341 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16342 		return (1);
16343 	}
16344 
16345 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16346 		return (1);
16347 	}
16348 
16349 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16350 		return (1);
16351 	}
16352 
16353 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16354 		return (1);
16355 	}
16356 
16357 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16358 		return (1);
16359 	}
16360 
16361 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16362 		return (1);
16363 	}
16364 
16365 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16366 		return (1);
16367 	}
16368 
16369 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16370 		return (1);
16371 	}
16372 
16373 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16374 		return (1);
16375 	}
16376 
16377 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16378 		return (1);
16379 	}
16380 
16381 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16382 		return (1);
16383 	}
16384 	freemsg(mpctl);
16385 	return (1);
16386 }
16387 
16388 
16389 /* Get global IPv4 statistics */
16390 static mblk_t *
16391 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16392 {
16393 	struct opthdr		*optp;
16394 	mblk_t			*mp2ctl;
16395 
16396 	/*
16397 	 * make a copy of the original message
16398 	 */
16399 	mp2ctl = copymsg(mpctl);
16400 
16401 	/* fixed length IP structure... */
16402 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16403 	optp->level = MIB2_IP;
16404 	optp->name = 0;
16405 	SET_MIB(ip_mib.ipForwarding,
16406 	    (WE_ARE_FORWARDING ? 1 : 2));
16407 	SET_MIB(ip_mib.ipDefaultTTL,
16408 	    (uint32_t)ip_def_ttl);
16409 	SET_MIB(ip_mib.ipReasmTimeout,
16410 	    ip_g_frag_timeout);
16411 	SET_MIB(ip_mib.ipAddrEntrySize,
16412 	    sizeof (mib2_ipAddrEntry_t));
16413 	SET_MIB(ip_mib.ipRouteEntrySize,
16414 	    sizeof (mib2_ipRouteEntry_t));
16415 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16416 	    sizeof (mib2_ipNetToMediaEntry_t));
16417 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16418 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16419 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16420 	    (int)sizeof (ip_mib))) {
16421 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16422 		    (uint_t)sizeof (ip_mib)));
16423 	}
16424 
16425 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16426 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16427 	    (int)optp->level, (int)optp->name, (int)optp->len));
16428 	qreply(q, mpctl);
16429 	return (mp2ctl);
16430 }
16431 
16432 /* Global IPv4 ICMP statistics */
16433 static mblk_t *
16434 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16435 {
16436 	struct opthdr		*optp;
16437 	mblk_t			*mp2ctl;
16438 
16439 	/*
16440 	 * Make a copy of the original message
16441 	 */
16442 	mp2ctl = copymsg(mpctl);
16443 
16444 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16445 	optp->level = MIB2_ICMP;
16446 	optp->name = 0;
16447 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16448 	    (int)sizeof (icmp_mib))) {
16449 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16450 		    (uint_t)sizeof (icmp_mib)));
16451 	}
16452 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16453 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16454 	    (int)optp->level, (int)optp->name, (int)optp->len));
16455 	qreply(q, mpctl);
16456 	return (mp2ctl);
16457 }
16458 
16459 /* Global IPv4 IGMP statistics */
16460 static mblk_t *
16461 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16462 {
16463 	struct opthdr		*optp;
16464 	mblk_t			*mp2ctl;
16465 
16466 	/*
16467 	 * make a copy of the original message
16468 	 */
16469 	mp2ctl = copymsg(mpctl);
16470 
16471 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16472 	optp->level = EXPER_IGMP;
16473 	optp->name = 0;
16474 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16475 	    (int)sizeof (igmpstat))) {
16476 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16477 		    (uint_t)sizeof (igmpstat)));
16478 	}
16479 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16480 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16481 	    (int)optp->level, (int)optp->name, (int)optp->len));
16482 	qreply(q, mpctl);
16483 	return (mp2ctl);
16484 }
16485 
16486 /* Global IPv4 Multicast Routing statistics */
16487 static mblk_t *
16488 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16489 {
16490 	struct opthdr		*optp;
16491 	mblk_t			*mp2ctl;
16492 
16493 	/*
16494 	 * make a copy of the original message
16495 	 */
16496 	mp2ctl = copymsg(mpctl);
16497 
16498 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16499 	optp->level = EXPER_DVMRP;
16500 	optp->name = 0;
16501 	if (!ip_mroute_stats(mpctl->b_cont)) {
16502 		ip0dbg(("ip_mroute_stats: failed\n"));
16503 	}
16504 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16505 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16506 	    (int)optp->level, (int)optp->name, (int)optp->len));
16507 	qreply(q, mpctl);
16508 	return (mp2ctl);
16509 }
16510 
16511 /* IPv4 address information */
16512 static mblk_t *
16513 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16514 {
16515 	struct opthdr		*optp;
16516 	mblk_t			*mp2ctl;
16517 	mblk_t			*mp_tail = NULL;
16518 	ill_t			*ill;
16519 	ipif_t			*ipif;
16520 	uint_t			bitval;
16521 	mib2_ipAddrEntry_t	mae;
16522 	zoneid_t		zoneid;
16523 	ill_walk_context_t ctx;
16524 
16525 	/*
16526 	 * make a copy of the original message
16527 	 */
16528 	mp2ctl = copymsg(mpctl);
16529 
16530 	/* ipAddrEntryTable */
16531 
16532 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16533 	optp->level = MIB2_IP;
16534 	optp->name = MIB2_IP_ADDR;
16535 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16536 
16537 	rw_enter(&ill_g_lock, RW_READER);
16538 	ill = ILL_START_WALK_V4(&ctx);
16539 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16540 		for (ipif = ill->ill_ipif; ipif != NULL;
16541 		    ipif = ipif->ipif_next) {
16542 			if (ipif->ipif_zoneid != zoneid)
16543 				continue;
16544 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16545 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16546 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16547 
16548 			(void) ipif_get_name(ipif,
16549 			    mae.ipAdEntIfIndex.o_bytes,
16550 			    OCTET_LENGTH);
16551 			mae.ipAdEntIfIndex.o_length =
16552 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16553 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16554 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16555 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16556 			mae.ipAdEntInfo.ae_subnet_len =
16557 			    ip_mask_to_plen(ipif->ipif_net_mask);
16558 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16559 			for (bitval = 1;
16560 			    bitval &&
16561 			    !(bitval & ipif->ipif_brd_addr);
16562 			    bitval <<= 1)
16563 				noop;
16564 			mae.ipAdEntBcastAddr = bitval;
16565 			mae.ipAdEntReasmMaxSize = 65535;
16566 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16567 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16568 			mae.ipAdEntInfo.ae_broadcast_addr =
16569 			    ipif->ipif_brd_addr;
16570 			mae.ipAdEntInfo.ae_pp_dst_addr =
16571 			    ipif->ipif_pp_dst_addr;
16572 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16573 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16574 
16575 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16576 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16577 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16578 				    "allocate %u bytes\n",
16579 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16580 			}
16581 		}
16582 	}
16583 	rw_exit(&ill_g_lock);
16584 
16585 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16586 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16587 	    (int)optp->level, (int)optp->name, (int)optp->len));
16588 	qreply(q, mpctl);
16589 	return (mp2ctl);
16590 }
16591 
16592 /* IPv6 address information */
16593 static mblk_t *
16594 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16595 {
16596 	struct opthdr		*optp;
16597 	mblk_t			*mp2ctl;
16598 	mblk_t			*mp_tail = NULL;
16599 	ill_t			*ill;
16600 	ipif_t			*ipif;
16601 	mib2_ipv6AddrEntry_t	mae6;
16602 	zoneid_t		zoneid;
16603 	ill_walk_context_t	ctx;
16604 
16605 	/*
16606 	 * make a copy of the original message
16607 	 */
16608 	mp2ctl = copymsg(mpctl);
16609 
16610 	/* ipv6AddrEntryTable */
16611 
16612 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16613 	optp->level = MIB2_IP6;
16614 	optp->name = MIB2_IP6_ADDR;
16615 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16616 
16617 	rw_enter(&ill_g_lock, RW_READER);
16618 	ill = ILL_START_WALK_V6(&ctx);
16619 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16620 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16621 			if (ipif->ipif_zoneid != zoneid)
16622 				continue;
16623 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16624 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16625 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16626 
16627 			(void) ipif_get_name(ipif,
16628 			    mae6.ipv6AddrIfIndex.o_bytes,
16629 			    OCTET_LENGTH);
16630 			mae6.ipv6AddrIfIndex.o_length =
16631 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16632 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16633 			mae6.ipv6AddrPfxLength =
16634 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16635 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16636 			mae6.ipv6AddrInfo.ae_subnet_len =
16637 			    mae6.ipv6AddrPfxLength;
16638 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16639 
16640 			/* Type: stateless(1), stateful(2), unknown(3) */
16641 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16642 				mae6.ipv6AddrType = 1;
16643 			else
16644 				mae6.ipv6AddrType = 2;
16645 			/* Anycast: true(1), false(2) */
16646 			if (ipif->ipif_flags & IPIF_ANYCAST)
16647 				mae6.ipv6AddrAnycastFlag = 1;
16648 			else
16649 				mae6.ipv6AddrAnycastFlag = 2;
16650 
16651 			/*
16652 			 * Address status: preferred(1), deprecated(2),
16653 			 * invalid(3), inaccessible(4), unknown(5)
16654 			 */
16655 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16656 				mae6.ipv6AddrStatus = 3;
16657 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16658 				mae6.ipv6AddrStatus = 2;
16659 			else
16660 				mae6.ipv6AddrStatus = 1;
16661 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16662 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16663 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16664 						ipif->ipif_v6pp_dst_addr;
16665 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16666 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16667 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16668 				(char *)&mae6,
16669 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16670 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16671 				    "allocate %u bytes\n",
16672 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16673 			}
16674 		}
16675 	}
16676 	rw_exit(&ill_g_lock);
16677 
16678 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16679 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16680 	    (int)optp->level, (int)optp->name, (int)optp->len));
16681 	qreply(q, mpctl);
16682 	return (mp2ctl);
16683 }
16684 
16685 /* IPv4 multicast group membership. */
16686 static mblk_t *
16687 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16688 {
16689 	struct opthdr		*optp;
16690 	mblk_t			*mp2ctl;
16691 	ill_t			*ill;
16692 	ipif_t			*ipif;
16693 	ilm_t			*ilm;
16694 	ip_member_t		ipm;
16695 	mblk_t			*mp_tail = NULL;
16696 	ill_walk_context_t	ctx;
16697 	zoneid_t		zoneid;
16698 
16699 	/*
16700 	 * make a copy of the original message
16701 	 */
16702 	mp2ctl = copymsg(mpctl);
16703 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16704 
16705 	/* ipGroupMember table */
16706 	optp = (struct opthdr *)&mpctl->b_rptr[
16707 	    sizeof (struct T_optmgmt_ack)];
16708 	optp->level = MIB2_IP;
16709 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16710 
16711 	rw_enter(&ill_g_lock, RW_READER);
16712 	ill = ILL_START_WALK_V4(&ctx);
16713 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16714 		ILM_WALKER_HOLD(ill);
16715 		for (ipif = ill->ill_ipif; ipif != NULL;
16716 		    ipif = ipif->ipif_next) {
16717 			if (ipif->ipif_zoneid != zoneid)
16718 				continue;	/* not this zone */
16719 			(void) ipif_get_name(ipif,
16720 			    ipm.ipGroupMemberIfIndex.o_bytes,
16721 			    OCTET_LENGTH);
16722 			ipm.ipGroupMemberIfIndex.o_length =
16723 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16724 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16725 				ASSERT(ilm->ilm_ipif != NULL);
16726 				ASSERT(ilm->ilm_ill == NULL);
16727 				if (ilm->ilm_ipif != ipif)
16728 					continue;
16729 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16730 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16731 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16732 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16733 				    (char *)&ipm, (int)sizeof (ipm))) {
16734 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16735 					    "failed to allocate %u bytes\n",
16736 						(uint_t)sizeof (ipm)));
16737 				}
16738 			}
16739 		}
16740 		ILM_WALKER_RELE(ill);
16741 	}
16742 	rw_exit(&ill_g_lock);
16743 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16744 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16745 	    (int)optp->level, (int)optp->name, (int)optp->len));
16746 	qreply(q, mpctl);
16747 	return (mp2ctl);
16748 }
16749 
16750 /* IPv6 multicast group membership. */
16751 static mblk_t *
16752 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16753 {
16754 	struct opthdr		*optp;
16755 	mblk_t			*mp2ctl;
16756 	ill_t			*ill;
16757 	ilm_t			*ilm;
16758 	ipv6_member_t		ipm6;
16759 	mblk_t			*mp_tail = NULL;
16760 	ill_walk_context_t	ctx;
16761 	zoneid_t		zoneid;
16762 
16763 	/*
16764 	 * make a copy of the original message
16765 	 */
16766 	mp2ctl = copymsg(mpctl);
16767 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16768 
16769 	/* ip6GroupMember table */
16770 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16771 	optp->level = MIB2_IP6;
16772 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16773 
16774 	rw_enter(&ill_g_lock, RW_READER);
16775 	ill = ILL_START_WALK_V6(&ctx);
16776 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16777 		ILM_WALKER_HOLD(ill);
16778 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16779 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16780 			ASSERT(ilm->ilm_ipif == NULL);
16781 			ASSERT(ilm->ilm_ill != NULL);
16782 			if (ilm->ilm_zoneid != zoneid)
16783 				continue;	/* not this zone */
16784 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16785 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16786 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16787 			if (!snmp_append_data2(mpctl->b_cont,
16788 			    &mp_tail,
16789 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16790 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16791 				    "failed to allocate %u bytes\n",
16792 				    (uint_t)sizeof (ipm6)));
16793 			}
16794 		}
16795 		ILM_WALKER_RELE(ill);
16796 	}
16797 	rw_exit(&ill_g_lock);
16798 
16799 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16800 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16801 	    (int)optp->level, (int)optp->name, (int)optp->len));
16802 	qreply(q, mpctl);
16803 	return (mp2ctl);
16804 }
16805 
16806 /* IP multicast filtered sources */
16807 static mblk_t *
16808 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16809 {
16810 	struct opthdr		*optp;
16811 	mblk_t			*mp2ctl;
16812 	ill_t			*ill;
16813 	ipif_t			*ipif;
16814 	ilm_t			*ilm;
16815 	ip_grpsrc_t		ips;
16816 	mblk_t			*mp_tail = NULL;
16817 	ill_walk_context_t	ctx;
16818 	zoneid_t		zoneid;
16819 	int			i;
16820 	slist_t			*sl;
16821 
16822 	/*
16823 	 * make a copy of the original message
16824 	 */
16825 	mp2ctl = copymsg(mpctl);
16826 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16827 
16828 	/* ipGroupSource table */
16829 	optp = (struct opthdr *)&mpctl->b_rptr[
16830 	    sizeof (struct T_optmgmt_ack)];
16831 	optp->level = MIB2_IP;
16832 	optp->name = EXPER_IP_GROUP_SOURCES;
16833 
16834 	rw_enter(&ill_g_lock, RW_READER);
16835 	ill = ILL_START_WALK_V4(&ctx);
16836 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16837 		ILM_WALKER_HOLD(ill);
16838 		for (ipif = ill->ill_ipif; ipif != NULL;
16839 		    ipif = ipif->ipif_next) {
16840 			if (ipif->ipif_zoneid != zoneid)
16841 				continue;	/* not this zone */
16842 			(void) ipif_get_name(ipif,
16843 			    ips.ipGroupSourceIfIndex.o_bytes,
16844 			    OCTET_LENGTH);
16845 			ips.ipGroupSourceIfIndex.o_length =
16846 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16847 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16848 				ASSERT(ilm->ilm_ipif != NULL);
16849 				ASSERT(ilm->ilm_ill == NULL);
16850 				sl = ilm->ilm_filter;
16851 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16852 					continue;
16853 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16854 				for (i = 0; i < sl->sl_numsrc; i++) {
16855 					if (!IN6_IS_ADDR_V4MAPPED(
16856 					    &sl->sl_addr[i]))
16857 						continue;
16858 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16859 					    ips.ipGroupSourceAddress);
16860 					if (snmp_append_data2(mpctl->b_cont,
16861 					    &mp_tail, (char *)&ips,
16862 					    (int)sizeof (ips)) == 0) {
16863 						ip1dbg(("ip_snmp_get_mib2_"
16864 						    "ip_group_src: failed to "
16865 						    "allocate %u bytes\n",
16866 						    (uint_t)sizeof (ips)));
16867 					}
16868 				}
16869 			}
16870 		}
16871 		ILM_WALKER_RELE(ill);
16872 	}
16873 	rw_exit(&ill_g_lock);
16874 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16875 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16876 	    (int)optp->level, (int)optp->name, (int)optp->len));
16877 	qreply(q, mpctl);
16878 	return (mp2ctl);
16879 }
16880 
16881 /* IPv6 multicast filtered sources. */
16882 static mblk_t *
16883 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16884 {
16885 	struct opthdr		*optp;
16886 	mblk_t			*mp2ctl;
16887 	ill_t			*ill;
16888 	ilm_t			*ilm;
16889 	ipv6_grpsrc_t		ips6;
16890 	mblk_t			*mp_tail = NULL;
16891 	ill_walk_context_t	ctx;
16892 	zoneid_t		zoneid;
16893 	int			i;
16894 	slist_t			*sl;
16895 
16896 	/*
16897 	 * make a copy of the original message
16898 	 */
16899 	mp2ctl = copymsg(mpctl);
16900 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16901 
16902 	/* ip6GroupMember table */
16903 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16904 	optp->level = MIB2_IP6;
16905 	optp->name = EXPER_IP6_GROUP_SOURCES;
16906 
16907 	rw_enter(&ill_g_lock, RW_READER);
16908 	ill = ILL_START_WALK_V6(&ctx);
16909 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16910 		ILM_WALKER_HOLD(ill);
16911 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16912 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16913 			ASSERT(ilm->ilm_ipif == NULL);
16914 			ASSERT(ilm->ilm_ill != NULL);
16915 			sl = ilm->ilm_filter;
16916 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16917 				continue;
16918 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16919 			for (i = 0; i < sl->sl_numsrc; i++) {
16920 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16921 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16922 				    (char *)&ips6, (int)sizeof (ips6))) {
16923 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16924 					    "group_src: failed to allocate "
16925 					    "%u bytes\n",
16926 					    (uint_t)sizeof (ips6)));
16927 				}
16928 			}
16929 		}
16930 		ILM_WALKER_RELE(ill);
16931 	}
16932 	rw_exit(&ill_g_lock);
16933 
16934 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16935 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16936 	    (int)optp->level, (int)optp->name, (int)optp->len));
16937 	qreply(q, mpctl);
16938 	return (mp2ctl);
16939 }
16940 
16941 /* Multicast routing virtual interface table. */
16942 static mblk_t *
16943 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16944 {
16945 	struct opthdr		*optp;
16946 	mblk_t			*mp2ctl;
16947 
16948 	/*
16949 	 * make a copy of the original message
16950 	 */
16951 	mp2ctl = copymsg(mpctl);
16952 
16953 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16954 	optp->level = EXPER_DVMRP;
16955 	optp->name = EXPER_DVMRP_VIF;
16956 	if (!ip_mroute_vif(mpctl->b_cont)) {
16957 		ip0dbg(("ip_mroute_vif: failed\n"));
16958 	}
16959 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16960 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16961 	    (int)optp->level, (int)optp->name, (int)optp->len));
16962 	qreply(q, mpctl);
16963 	return (mp2ctl);
16964 }
16965 
16966 /* Multicast routing table. */
16967 static mblk_t *
16968 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16969 {
16970 	struct opthdr		*optp;
16971 	mblk_t			*mp2ctl;
16972 
16973 	/*
16974 	 * make a copy of the original message
16975 	 */
16976 	mp2ctl = copymsg(mpctl);
16977 
16978 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16979 	optp->level = EXPER_DVMRP;
16980 	optp->name = EXPER_DVMRP_MRT;
16981 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16982 		ip0dbg(("ip_mroute_mrt: failed\n"));
16983 	}
16984 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16985 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16986 	    (int)optp->level, (int)optp->name, (int)optp->len));
16987 	qreply(q, mpctl);
16988 	return (mp2ctl);
16989 }
16990 
16991 /*
16992  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16993  * in one IRE walk.
16994  */
16995 static mblk_t *
16996 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16997 {
16998 	struct opthdr		*optp;
16999 	mblk_t			*mp2ctl;	/* Returned */
17000 	mblk_t			*mp3ctl;	/* nettomedia */
17001 	/*
17002 	 * We need two listptrs, for ipRouteEntryTable and
17003 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
17004 	 */
17005 	listptr_t		re_ntme_v4[2];
17006 	zoneid_t		zoneid;
17007 
17008 	/*
17009 	 * make a copy of the original message
17010 	 */
17011 	mp2ctl = copymsg(mpctl);
17012 	mp3ctl = copymsg(mpctl);
17013 	if (mp3ctl == NULL) {
17014 		freemsg(mp2ctl);
17015 		freemsg(mpctl);
17016 		return (NULL);
17017 	}
17018 
17019 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
17020 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
17021 	/*
17022 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17023 	 * proper values when called.
17024 	 */
17025 	re_ntme_v4[0].lp_tail = NULL;
17026 	re_ntme_v4[1].lp_tail = NULL;
17027 
17028 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17029 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
17030 	if (zoneid == GLOBAL_ZONEID) {
17031 		/*
17032 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17033 		 * the sys_net_config privilege, it can only run in the global
17034 		 * zone, so we don't display these IREs in the other zones.
17035 		 */
17036 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
17037 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
17038 		    NULL);
17039 	}
17040 
17041 	/* ipRouteEntryTable in mpctl */
17042 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17043 	optp->level = MIB2_IP;
17044 	optp->name = MIB2_IP_ROUTE;
17045 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
17046 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17047 	    (int)optp->level, (int)optp->name, (int)optp->len));
17048 	qreply(q, mpctl);
17049 
17050 	/* ipNetToMediaEntryTable in mp3ctl */
17051 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17052 	optp->level = MIB2_IP;
17053 	optp->name = MIB2_IP_MEDIA;
17054 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
17055 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17056 	    (int)optp->level, (int)optp->name, (int)optp->len));
17057 	qreply(q, mp3ctl);
17058 	return (mp2ctl);
17059 }
17060 
17061 /*
17062  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
17063  * in one IRE walk.
17064  */
17065 static mblk_t *
17066 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17067 {
17068 	struct opthdr		*optp;
17069 	mblk_t			*mp2ctl;	/* Returned */
17070 	mblk_t			*mp3ctl;	/* nettomedia */
17071 	listptr_t		re_ntme_v6;
17072 	zoneid_t		zoneid;
17073 
17074 	/*
17075 	 * make a copy of the original message
17076 	 */
17077 	mp2ctl = copymsg(mpctl);
17078 	mp3ctl = copymsg(mpctl);
17079 	if (mp3ctl == NULL) {
17080 		freemsg(mp2ctl);
17081 		freemsg(mpctl);
17082 		return (NULL);
17083 	}
17084 
17085 	/*
17086 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17087 	 * proper values when called.  ipv6RouteEntryTable in is placed
17088 	 * in mpctl.
17089 	 */
17090 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
17091 	re_ntme_v6.lp_tail = NULL;
17092 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17093 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
17094 
17095 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17096 	optp->level = MIB2_IP6;
17097 	optp->name = MIB2_IP6_ROUTE;
17098 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17099 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17100 	    (int)optp->level, (int)optp->name, (int)optp->len));
17101 	qreply(q, mpctl);
17102 
17103 	/* ipv6NetToMediaEntryTable in mp3ctl */
17104 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
17105 	re_ntme_v6.lp_tail = NULL;
17106 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
17107 
17108 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17109 	optp->level = MIB2_IP6;
17110 	optp->name = MIB2_IP6_MEDIA;
17111 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17112 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17113 	    (int)optp->level, (int)optp->name, (int)optp->len));
17114 	qreply(q, mp3ctl);
17115 	return (mp2ctl);
17116 }
17117 
17118 /*
17119  * ICMPv6 mib: One per ill
17120  */
17121 static mblk_t *
17122 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17123 {
17124 	struct opthdr		*optp;
17125 	mblk_t			*mp2ctl;
17126 	ill_t			*ill;
17127 	ill_walk_context_t	ctx;
17128 	mblk_t			*mp_tail = NULL;
17129 
17130 	/*
17131 	 * Make a copy of the original message
17132 	 */
17133 	mp2ctl = copymsg(mpctl);
17134 
17135 	/* fixed length IPv6 structure ... */
17136 
17137 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17138 	optp->level = MIB2_IP6;
17139 	optp->name = 0;
17140 	/* Include "unknown interface" ip6_mib */
17141 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17142 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17143 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17144 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17145 	    sizeof (mib2_ipv6IfStatsEntry_t));
17146 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17147 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17148 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17149 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17150 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17151 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17152 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17153 	    (int)sizeof (ip6_mib))) {
17154 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17155 		    (uint_t)sizeof (ip6_mib)));
17156 	}
17157 
17158 	rw_enter(&ill_g_lock, RW_READER);
17159 	ill = ILL_START_WALK_V6(&ctx);
17160 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17161 		ill->ill_ip6_mib->ipv6IfIndex =
17162 		    ill->ill_phyint->phyint_ifindex;
17163 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17164 		    ipv6_forward ? 1 : 2);
17165 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17166 		    ill->ill_max_hops);
17167 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17168 		    sizeof (mib2_ipv6IfStatsEntry_t));
17169 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17170 		    sizeof (mib2_ipv6AddrEntry_t));
17171 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17172 		    sizeof (mib2_ipv6RouteEntry_t));
17173 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17174 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17175 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17176 		    sizeof (ipv6_member_t));
17177 
17178 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17179 		    (char *)ill->ill_ip6_mib,
17180 		    (int)sizeof (*ill->ill_ip6_mib))) {
17181 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17182 				"%u bytes\n",
17183 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17184 		}
17185 	}
17186 	rw_exit(&ill_g_lock);
17187 
17188 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17189 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17190 	    (int)optp->level, (int)optp->name, (int)optp->len));
17191 	qreply(q, mpctl);
17192 	return (mp2ctl);
17193 }
17194 
17195 /*
17196  * ICMPv6 mib: One per ill
17197  */
17198 static mblk_t *
17199 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17200 {
17201 	struct opthdr		*optp;
17202 	mblk_t			*mp2ctl;
17203 	ill_t			*ill;
17204 	ill_walk_context_t	ctx;
17205 	mblk_t			*mp_tail = NULL;
17206 	/*
17207 	 * Make a copy of the original message
17208 	 */
17209 	mp2ctl = copymsg(mpctl);
17210 
17211 	/* fixed length ICMPv6 structure ... */
17212 
17213 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17214 	optp->level = MIB2_ICMP6;
17215 	optp->name = 0;
17216 	/* Include "unknown interface" icmp6_mib */
17217 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17218 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17219 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17220 	    (int)sizeof (icmp6_mib))) {
17221 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17222 		    (uint_t)sizeof (icmp6_mib)));
17223 	}
17224 
17225 	rw_enter(&ill_g_lock, RW_READER);
17226 	ill = ILL_START_WALK_V6(&ctx);
17227 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17228 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17229 		    ill->ill_phyint->phyint_ifindex;
17230 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17231 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17232 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17233 		    (char *)ill->ill_icmp6_mib,
17234 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17235 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17236 			    "%u bytes\n",
17237 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17238 		}
17239 	}
17240 	rw_exit(&ill_g_lock);
17241 
17242 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17243 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17244 	    (int)optp->level, (int)optp->name, (int)optp->len));
17245 	qreply(q, mpctl);
17246 	return (mp2ctl);
17247 }
17248 
17249 /*
17250  * ire_walk routine to create both ipRouteEntryTable and
17251  * ipNetToMediaEntryTable in one IRE walk
17252  */
17253 static void
17254 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17255 {
17256 	ill_t				*ill;
17257 	ipif_t				*ipif;
17258 	mblk_t				*llmp;
17259 	dl_unitdata_req_t		*dlup;
17260 	mib2_ipRouteEntry_t		re;
17261 	mib2_ipNetToMediaEntry_t	ntme;
17262 	ipaddr_t			gw_addr;
17263 
17264 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17265 
17266 	/*
17267 	 * Return all IRE types for route table... let caller pick and choose
17268 	 */
17269 	re.ipRouteDest = ire->ire_addr;
17270 	ipif = ire->ire_ipif;
17271 	re.ipRouteIfIndex.o_length = 0;
17272 	if (ire->ire_type == IRE_CACHE) {
17273 		ill = (ill_t *)ire->ire_stq->q_ptr;
17274 		re.ipRouteIfIndex.o_length =
17275 		    ill->ill_name_length == 0 ? 0 :
17276 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17277 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17278 		    re.ipRouteIfIndex.o_length);
17279 	} else if (ipif != NULL) {
17280 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17281 		    OCTET_LENGTH);
17282 		re.ipRouteIfIndex.o_length =
17283 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17284 	}
17285 	re.ipRouteMetric1 = -1;
17286 	re.ipRouteMetric2 = -1;
17287 	re.ipRouteMetric3 = -1;
17288 	re.ipRouteMetric4 = -1;
17289 
17290 	gw_addr = ire->ire_gateway_addr;
17291 
17292 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17293 		re.ipRouteNextHop = ire->ire_src_addr;
17294 	else
17295 		re.ipRouteNextHop = gw_addr;
17296 	/* indirect(4), direct(3), or invalid(2) */
17297 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17298 		re.ipRouteType = 2;
17299 	else
17300 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17301 	re.ipRouteProto = -1;
17302 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17303 	re.ipRouteMask = ire->ire_mask;
17304 	re.ipRouteMetric5 = -1;
17305 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17306 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17307 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17308 	llmp = ire->ire_dlureq_mp;
17309 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17310 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17311 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17312 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17313 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17314 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17315 	re.ipRouteInfo.re_in_ill.o_length = 0;
17316 	if (ire->ire_in_ill != NULL) {
17317 		re.ipRouteInfo.re_in_ill.o_length =
17318 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17319 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17320 		bcopy(ire->ire_in_ill->ill_name,
17321 		    re.ipRouteInfo.re_in_ill.o_bytes,
17322 		    re.ipRouteInfo.re_in_ill.o_length);
17323 	}
17324 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17325 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17326 	    (char *)&re, (int)sizeof (re))) {
17327 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17328 		    (uint_t)sizeof (re)));
17329 	}
17330 
17331 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17332 		return;
17333 	/*
17334 	 * only IRE_CACHE entries that are for a directly connected subnet
17335 	 * get appended to net -> phys addr table
17336 	 * (others in arp)
17337 	 */
17338 	ntme.ipNetToMediaIfIndex.o_length = 0;
17339 	ill = ire_to_ill(ire);
17340 	ASSERT(ill != NULL);
17341 	ntme.ipNetToMediaIfIndex.o_length =
17342 	    ill->ill_name_length == 0 ? 0 :
17343 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17344 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17345 		    ntme.ipNetToMediaIfIndex.o_length);
17346 
17347 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17348 	if (llmp) {
17349 		uchar_t *addr;
17350 
17351 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17352 		/* Remove sap from  address */
17353 		if (ill->ill_sap_length < 0)
17354 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17355 		else
17356 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17357 			    ill->ill_sap_length;
17358 
17359 		ntme.ipNetToMediaPhysAddress.o_length =
17360 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17361 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17362 		    ntme.ipNetToMediaPhysAddress.o_length);
17363 	}
17364 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17365 	/* assume dynamic (may be changed in arp) */
17366 	ntme.ipNetToMediaType = 3;
17367 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17368 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17369 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17370 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17371 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17372 	    (char *)&ntme, (int)sizeof (ntme))) {
17373 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17374 		    (uint_t)sizeof (ntme)));
17375 	}
17376 }
17377 
17378 /*
17379  * ire_walk routine to create ipv6RouteEntryTable.
17380  */
17381 static void
17382 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17383 {
17384 	ill_t				*ill;
17385 	ipif_t				*ipif;
17386 	mib2_ipv6RouteEntry_t		re;
17387 	in6_addr_t			gw_addr_v6;
17388 
17389 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17390 
17391 	/*
17392 	 * Return all IRE types for route table... let caller pick and choose
17393 	 */
17394 	re.ipv6RouteDest = ire->ire_addr_v6;
17395 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17396 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17397 	re.ipv6RouteIfIndex.o_length = 0;
17398 	ipif = ire->ire_ipif;
17399 	if (ire->ire_type == IRE_CACHE) {
17400 		ill = (ill_t *)ire->ire_stq->q_ptr;
17401 		re.ipv6RouteIfIndex.o_length =
17402 		    ill->ill_name_length == 0 ? 0 :
17403 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17404 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17405 		    re.ipv6RouteIfIndex.o_length);
17406 	} else if (ipif != NULL) {
17407 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17408 		    OCTET_LENGTH);
17409 		re.ipv6RouteIfIndex.o_length =
17410 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17411 	}
17412 
17413 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17414 
17415 	mutex_enter(&ire->ire_lock);
17416 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17417 	mutex_exit(&ire->ire_lock);
17418 
17419 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17420 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17421 	else
17422 		re.ipv6RouteNextHop = gw_addr_v6;
17423 
17424 	/* remote(4), local(3), or discard(2) */
17425 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17426 		re.ipv6RouteType = 2;
17427 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17428 		re.ipv6RouteType = 3;
17429 	else
17430 		re.ipv6RouteType = 4;
17431 
17432 	re.ipv6RouteProtocol		= -1;
17433 	re.ipv6RoutePolicy		= 0;
17434 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17435 	re.ipv6RouteNextHopRDI		= 0;
17436 	re.ipv6RouteWeight		= 0;
17437 	re.ipv6RouteMetric		= 0;
17438 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17439 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17440 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17441 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17442 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17443 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17444 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17445 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17446 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17447 
17448 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17449 	    (char *)&re, (int)sizeof (re))) {
17450 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17451 		    (uint_t)sizeof (re)));
17452 	}
17453 }
17454 
17455 /*
17456  * ndp_walk routine to create ipv6NetToMediaEntryTable
17457  */
17458 static int
17459 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17460 {
17461 	ill_t				*ill;
17462 	mib2_ipv6NetToMediaEntry_t	ntme;
17463 	dl_unitdata_req_t		*dl;
17464 
17465 	ill = nce->nce_ill;
17466 	ASSERT(ill->ill_isv6);
17467 
17468 	/*
17469 	 * Neighbor cache entry attached to IRE with on-link
17470 	 * destination.
17471 	 */
17472 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17473 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17474 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17475 	    (nce->nce_res_mp != NULL)) {
17476 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17477 		ntme.ipv6NetToMediaPhysAddress.o_length =
17478 		    dl->dl_dest_addr_length;
17479 	} else {
17480 		ntme.ipv6NetToMediaPhysAddress.o_length =
17481 		    ill->ill_phys_addr_length;
17482 	}
17483 	if (nce->nce_res_mp != NULL) {
17484 		bcopy((char *)nce->nce_res_mp->b_rptr +
17485 		    NCE_LL_ADDR_OFFSET(ill),
17486 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17487 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17488 	} else {
17489 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17490 		    ill->ill_phys_addr_length);
17491 	}
17492 	/*
17493 	 * Note: Returns ND_* states. Should be:
17494 	 * reachable(1), stale(2), delay(3), probe(4),
17495 	 * invalid(5), unknown(6)
17496 	 */
17497 	ntme.ipv6NetToMediaState = nce->nce_state;
17498 	ntme.ipv6NetToMediaLastUpdated = 0;
17499 
17500 	/* other(1), dynamic(2), static(3), local(4) */
17501 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17502 		ntme.ipv6NetToMediaType = 4;
17503 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17504 		ntme.ipv6NetToMediaType = 1;
17505 	} else {
17506 		ntme.ipv6NetToMediaType = 2;
17507 	}
17508 
17509 	if (!snmp_append_data2(re_ntme->lp_head,
17510 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17511 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17512 		    (uint_t)sizeof (ntme)));
17513 	}
17514 	return (0);
17515 }
17516 
17517 /*
17518  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17519  */
17520 /* ARGSUSED */
17521 int
17522 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17523 {
17524 	switch (level) {
17525 	case MIB2_IP:
17526 	case MIB2_ICMP:
17527 		switch (name) {
17528 		default:
17529 			break;
17530 		}
17531 		return (1);
17532 	default:
17533 		return (1);
17534 	}
17535 }
17536 
17537 /*
17538  * Called before the options are updated to check if this packet will
17539  * be source routed from here.
17540  * This routine assumes that the options are well formed i.e. that they
17541  * have already been checked.
17542  */
17543 static boolean_t
17544 ip_source_routed(ipha_t *ipha)
17545 {
17546 	ipoptp_t	opts;
17547 	uchar_t		*opt;
17548 	uint8_t		optval;
17549 	uint8_t		optlen;
17550 	ipaddr_t	dst;
17551 	ire_t		*ire;
17552 
17553 	if (IS_SIMPLE_IPH(ipha)) {
17554 		ip2dbg(("not source routed\n"));
17555 		return (B_FALSE);
17556 	}
17557 	dst = ipha->ipha_dst;
17558 	for (optval = ipoptp_first(&opts, ipha);
17559 	    optval != IPOPT_EOL;
17560 	    optval = ipoptp_next(&opts)) {
17561 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17562 		opt = opts.ipoptp_cur;
17563 		optlen = opts.ipoptp_len;
17564 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17565 		    optval, optlen));
17566 		switch (optval) {
17567 			uint32_t off;
17568 		case IPOPT_SSRR:
17569 		case IPOPT_LSRR:
17570 			/*
17571 			 * If dst is one of our addresses and there are some
17572 			 * entries left in the source route return (true).
17573 			 */
17574 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17575 			    ALL_ZONES, MATCH_IRE_TYPE);
17576 			if (ire == NULL) {
17577 				ip2dbg(("ip_source_routed: not next"
17578 				    " source route 0x%x\n",
17579 				    ntohl(dst)));
17580 				return (B_FALSE);
17581 			}
17582 			ire_refrele(ire);
17583 			off = opt[IPOPT_OFFSET];
17584 			off--;
17585 			if (optlen < IP_ADDR_LEN ||
17586 			    off > optlen - IP_ADDR_LEN) {
17587 				/* End of source route */
17588 				ip1dbg(("ip_source_routed: end of SR\n"));
17589 				return (B_FALSE);
17590 			}
17591 			return (B_TRUE);
17592 		}
17593 	}
17594 	ip2dbg(("not source routed\n"));
17595 	return (B_FALSE);
17596 }
17597 
17598 /*
17599  * Check if the packet contains any source route.
17600  */
17601 static boolean_t
17602 ip_source_route_included(ipha_t *ipha)
17603 {
17604 	ipoptp_t	opts;
17605 	uint8_t		optval;
17606 
17607 	if (IS_SIMPLE_IPH(ipha))
17608 		return (B_FALSE);
17609 	for (optval = ipoptp_first(&opts, ipha);
17610 	    optval != IPOPT_EOL;
17611 	    optval = ipoptp_next(&opts)) {
17612 		switch (optval) {
17613 		case IPOPT_SSRR:
17614 		case IPOPT_LSRR:
17615 			return (B_TRUE);
17616 		}
17617 	}
17618 	return (B_FALSE);
17619 }
17620 
17621 /*
17622  * Called when the IRE expiration timer fires.
17623  */
17624 /* ARGSUSED */
17625 void
17626 ip_trash_timer_expire(void *args)
17627 {
17628 	int	flush_flag = 0;
17629 
17630 	/*
17631 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17632 	 * This lock makes sure that a new invocation of this function
17633 	 * that occurs due to an almost immediate timer firing will not
17634 	 * progress beyond this point until the current invocation is done
17635 	 */
17636 	mutex_enter(&ip_trash_timer_lock);
17637 	ip_ire_expire_id = 0;
17638 	mutex_exit(&ip_trash_timer_lock);
17639 
17640 	/* Periodic timer */
17641 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17642 		/*
17643 		 * Remove all IRE_CACHE entries since they might
17644 		 * contain arp information.
17645 		 */
17646 		flush_flag |= FLUSH_ARP_TIME;
17647 		ip_ire_arp_time_elapsed = 0;
17648 		IP_STAT(ip_ire_arp_timer_expired);
17649 	}
17650 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17651 		/* Remove all redirects */
17652 		flush_flag |= FLUSH_REDIRECT_TIME;
17653 		ip_ire_rd_time_elapsed = 0;
17654 		IP_STAT(ip_ire_redirect_timer_expired);
17655 	}
17656 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17657 		/* Increase path mtu */
17658 		flush_flag |= FLUSH_MTU_TIME;
17659 		ip_ire_pmtu_time_elapsed = 0;
17660 		IP_STAT(ip_ire_pmtu_timer_expired);
17661 	}
17662 	if (flush_flag != 0) {
17663 		/* Walk all IPv4 IRE's and update them */
17664 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17665 		    ALL_ZONES);
17666 	}
17667 	if (flush_flag & FLUSH_MTU_TIME) {
17668 		/*
17669 		 * Walk all IPv6 IRE's and update them
17670 		 * Note that ARP and redirect timers are not
17671 		 * needed since NUD handles stale entries.
17672 		 */
17673 		flush_flag = FLUSH_MTU_TIME;
17674 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17675 		    ALL_ZONES);
17676 	}
17677 
17678 	ip_ire_arp_time_elapsed += ip_timer_interval;
17679 	ip_ire_rd_time_elapsed += ip_timer_interval;
17680 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17681 
17682 	/*
17683 	 * Hold the lock to serialize timeout calls and prevent
17684 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17685 	 * for the timer to fire and a new invocation of this function
17686 	 * to start before the return value of timeout has been stored
17687 	 * in ip_ire_expire_id by the current invocation.
17688 	 */
17689 	mutex_enter(&ip_trash_timer_lock);
17690 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17691 	    MSEC_TO_TICK(ip_timer_interval));
17692 	mutex_exit(&ip_trash_timer_lock);
17693 }
17694 
17695 /*
17696  * Called by the memory allocator subsystem directly, when the system
17697  * is running low on memory.
17698  */
17699 /* ARGSUSED */
17700 void
17701 ip_trash_ire_reclaim(void *args)
17702 {
17703 	ire_cache_count_t icc;
17704 	ire_cache_reclaim_t icr;
17705 	ncc_cache_count_t ncc;
17706 	nce_cache_reclaim_t ncr;
17707 	uint_t delete_cnt;
17708 	/*
17709 	 * Memory reclaim call back.
17710 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17711 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17712 	 * entries, determine what fraction to free for
17713 	 * each category of IRE_CACHE entries giving absolute priority
17714 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17715 	 * entry will be freed unless all offlink entries are freed).
17716 	 */
17717 	icc.icc_total = 0;
17718 	icc.icc_unused = 0;
17719 	icc.icc_offlink = 0;
17720 	icc.icc_pmtu = 0;
17721 	icc.icc_onlink = 0;
17722 	ire_walk(ire_cache_count, (char *)&icc);
17723 
17724 	/*
17725 	 * Free NCEs for IPv6 like the onlink ires.
17726 	 */
17727 	ncc.ncc_total = 0;
17728 	ncc.ncc_host = 0;
17729 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17730 
17731 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17732 	    icc.icc_pmtu + icc.icc_onlink);
17733 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17734 	IP_STAT(ip_trash_ire_reclaim_calls);
17735 	if (delete_cnt == 0)
17736 		return;
17737 	IP_STAT(ip_trash_ire_reclaim_success);
17738 	/* Always delete all unused offlink entries */
17739 	icr.icr_unused = 1;
17740 	if (delete_cnt <= icc.icc_unused) {
17741 		/*
17742 		 * Only need to free unused entries.  In other words,
17743 		 * there are enough unused entries to free to meet our
17744 		 * target number of freed ire cache entries.
17745 		 */
17746 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17747 		ncr.ncr_host = 0;
17748 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17749 		/*
17750 		 * Only need to free unused entries, plus a fraction of offlink
17751 		 * entries.  It follows from the first if statement that
17752 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17753 		 */
17754 		delete_cnt -= icc.icc_unused;
17755 		/* Round up # deleted by truncating fraction */
17756 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17757 		icr.icr_pmtu = icr.icr_onlink = 0;
17758 		ncr.ncr_host = 0;
17759 	} else if (delete_cnt <=
17760 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17761 		/*
17762 		 * Free all unused and offlink entries, plus a fraction of
17763 		 * pmtu entries.  It follows from the previous if statement
17764 		 * that icc_pmtu is non-zero, and that
17765 		 * delete_cnt != icc_unused + icc_offlink.
17766 		 */
17767 		icr.icr_offlink = 1;
17768 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17769 		/* Round up # deleted by truncating fraction */
17770 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17771 		icr.icr_onlink = 0;
17772 		ncr.ncr_host = 0;
17773 	} else {
17774 		/*
17775 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17776 		 * of onlink entries.  If we're here, then we know that
17777 		 * icc_onlink is non-zero, and that
17778 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17779 		 */
17780 		icr.icr_offlink = icr.icr_pmtu = 1;
17781 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17782 		    icc.icc_pmtu;
17783 		/* Round up # deleted by truncating fraction */
17784 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17785 		/* Using the same delete fraction as for onlink IREs */
17786 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17787 	}
17788 #ifdef DEBUG
17789 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17790 	    "fractions %d/%d/%d/%d\n",
17791 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17792 	    icc.icc_unused, icc.icc_offlink,
17793 	    icc.icc_pmtu, icc.icc_onlink,
17794 	    icr.icr_unused, icr.icr_offlink,
17795 	    icr.icr_pmtu, icr.icr_onlink));
17796 #endif
17797 	ire_walk(ire_cache_reclaim, (char *)&icr);
17798 	if (ncr.ncr_host != 0)
17799 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17800 		    (uchar_t *)&ncr);
17801 #ifdef DEBUG
17802 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17803 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17804 	ire_walk(ire_cache_count, (char *)&icc);
17805 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17806 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17807 	    icc.icc_pmtu, icc.icc_onlink));
17808 #endif
17809 }
17810 
17811 /*
17812  * ip_unbind is called when a copy of an unbind request is received from the
17813  * upper level protocol.  We remove this conn from any fanout hash list it is
17814  * on, and zero out the bind information.  No reply is expected up above.
17815  */
17816 mblk_t *
17817 ip_unbind(queue_t *q, mblk_t *mp)
17818 {
17819 	conn_t	*connp = Q_TO_CONN(q);
17820 
17821 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17822 
17823 	ipcl_hash_remove(connp);
17824 
17825 	ASSERT(mp->b_cont == NULL);
17826 	/*
17827 	 * Convert mp into a T_OK_ACK
17828 	 */
17829 	mp = mi_tpi_ok_ack_alloc(mp);
17830 
17831 	/*
17832 	 * should not happen in practice... T_OK_ACK is smaller than the
17833 	 * original message.
17834 	 */
17835 	if (mp == NULL)
17836 		return (NULL);
17837 
17838 	/*
17839 	 * Don't bzero the ports if its TCP since TCP still needs the
17840 	 * lport to remove it from its own bind hash. TCP will do the
17841 	 * cleanup.
17842 	 */
17843 	if (!IPCL_IS_TCP(connp))
17844 		bzero(&connp->u_port, sizeof (connp->u_port));
17845 
17846 	return (mp);
17847 }
17848 
17849 /*
17850  * Write side put procedure.  Outbound data, IOCTLs, responses from
17851  * resolvers, etc, come down through here.
17852  */
17853 void
17854 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17855 {
17856 	conn_t		*connp = NULL;
17857 	queue_t		*q = (queue_t *)arg2;
17858 	ipha_t		*ipha;
17859 #define	rptr	((uchar_t *)ipha)
17860 	ire_t		*ire = NULL;
17861 	ire_t		*sctp_ire = NULL;
17862 	uint32_t	v_hlen_tos_len;
17863 	ipaddr_t	dst;
17864 	mblk_t		*first_mp = NULL;
17865 	boolean_t	mctl_present;
17866 	ipsec_out_t	*io;
17867 	int		match_flags;
17868 	ill_t		*attach_ill = NULL;
17869 					/* Bind to IPIF_NOFAILOVER ill etc. */
17870 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17871 	ipif_t		*dst_ipif;
17872 	boolean_t	multirt_need_resolve = B_FALSE;
17873 	mblk_t		*copy_mp = NULL;
17874 	int		err;
17875 	zoneid_t	zoneid;
17876 	boolean_t	need_decref = B_FALSE;
17877 	boolean_t	ignore_dontroute = B_FALSE;
17878 	boolean_t	ignore_nexthop = B_FALSE;
17879 	boolean_t	ip_nexthop = B_FALSE;
17880 	ipaddr_t	nexthop_addr;
17881 
17882 #ifdef	_BIG_ENDIAN
17883 #define	V_HLEN	(v_hlen_tos_len >> 24)
17884 #else
17885 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17886 #endif
17887 
17888 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17889 	    "ip_wput_start: q %p", q);
17890 
17891 	/*
17892 	 * ip_wput fast path
17893 	 */
17894 
17895 	/* is packet from ARP ? */
17896 	if (q->q_next != NULL)
17897 		goto qnext;
17898 
17899 	connp = (conn_t *)arg;
17900 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17901 
17902 	/* is queue flow controlled? */
17903 	if ((q->q_first != NULL || connp->conn_draining) &&
17904 	    (caller == IP_WPUT)) {
17905 		ASSERT(!need_decref);
17906 		(void) putq(q, mp);
17907 		return;
17908 	}
17909 
17910 	/* Multidata transmit? */
17911 	if (DB_TYPE(mp) == M_MULTIDATA) {
17912 		/*
17913 		 * We should never get here, since all Multidata messages
17914 		 * originating from tcp should have been directed over to
17915 		 * tcp_multisend() in the first place.
17916 		 */
17917 		BUMP_MIB(&ip_mib, ipOutDiscards);
17918 		freemsg(mp);
17919 		return;
17920 	} else if (DB_TYPE(mp) != M_DATA)
17921 		goto notdata;
17922 	if (mp->b_flag & MSGHASREF) {
17923 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17924 		mp->b_flag &= ~MSGHASREF;
17925 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17926 		need_decref = B_TRUE;
17927 	}
17928 	ipha = (ipha_t *)mp->b_rptr;
17929 
17930 	/* is IP header non-aligned or mblk smaller than basic IP header */
17931 #ifndef SAFETY_BEFORE_SPEED
17932 	if (!OK_32PTR(rptr) ||
17933 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17934 		goto hdrtoosmall;
17935 #endif
17936 
17937 	/*
17938 	 * If there is a policy, try to attach an ipsec_out in
17939 	 * the front. At the end, first_mp either points to a
17940 	 * M_DATA message or IPSEC_OUT message linked to a
17941 	 * M_DATA message. We have to do it now as we might
17942 	 * lose the "conn" if we go through ip_newroute.
17943 	 */
17944 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17945 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17946 		    ipha->ipha_protocol)) == NULL)) {
17947 			if (need_decref)
17948 				CONN_DEC_REF(connp);
17949 			return;
17950 		} else {
17951 			ASSERT(mp->b_datap->db_type == M_CTL);
17952 			first_mp = mp;
17953 			mp = mp->b_cont;
17954 			mctl_present = B_TRUE;
17955 		}
17956 	} else {
17957 		first_mp = mp;
17958 		mctl_present = B_FALSE;
17959 	}
17960 
17961 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17962 
17963 	/* is wrong version or IP options present */
17964 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17965 		goto version_hdrlen_check;
17966 	dst = ipha->ipha_dst;
17967 
17968 	if (connp->conn_nofailover_ill != NULL) {
17969 		attach_ill = conn_get_held_ill(connp,
17970 		    &connp->conn_nofailover_ill, &err);
17971 		if (err == ILL_LOOKUP_FAILED) {
17972 			if (need_decref)
17973 				CONN_DEC_REF(connp);
17974 			freemsg(first_mp);
17975 			return;
17976 		}
17977 	}
17978 
17979 	/* is packet multicast? */
17980 	if (CLASSD(dst))
17981 		goto multicast;
17982 
17983 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
17984 	    (connp->conn_nexthop_set)) {
17985 		/*
17986 		 * If the destination is a broadcast or a loopback
17987 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
17988 		 * through the standard path. But in the case of local
17989 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
17990 		 * the standard path not IP_XMIT_IF.
17991 		 */
17992 		ire = ire_cache_lookup(dst, zoneid);
17993 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17994 		    (ire->ire_type != IRE_LOOPBACK))) {
17995 			if ((connp->conn_dontroute ||
17996 			    connp->conn_nexthop_set) && (ire != NULL) &&
17997 			    (ire->ire_type == IRE_LOCAL))
17998 				goto standard_path;
17999 
18000 			if (ire != NULL) {
18001 				ire_refrele(ire);
18002 				/* No more access to ire */
18003 				ire = NULL;
18004 			}
18005 			/*
18006 			 * bypass routing checks and go directly to
18007 			 * interface.
18008 			 */
18009 			if (connp->conn_dontroute) {
18010 				goto dontroute;
18011 			} else if (connp->conn_nexthop_set) {
18012 				ip_nexthop = B_TRUE;
18013 				nexthop_addr = connp->conn_nexthop_v4;
18014 				goto send_from_ill;
18015 			}
18016 
18017 			/*
18018 			 * If IP_XMIT_IF socket option is set,
18019 			 * then we allow unicast and multicast
18020 			 * packets to go through the ill. It is
18021 			 * quite possible that the destination
18022 			 * is not in the ire cache table and we
18023 			 * do not want to go to ip_newroute()
18024 			 * instead we call ip_newroute_ipif.
18025 			 */
18026 			xmit_ill = conn_get_held_ill(connp,
18027 			    &connp->conn_xmit_if_ill, &err);
18028 			if (err == ILL_LOOKUP_FAILED) {
18029 				if (attach_ill != NULL)
18030 					ill_refrele(attach_ill);
18031 				if (need_decref)
18032 					CONN_DEC_REF(connp);
18033 				freemsg(first_mp);
18034 				return;
18035 			}
18036 			goto send_from_ill;
18037 		}
18038 standard_path:
18039 		/* Must be a broadcast, a loopback or a local ire */
18040 		if (ire != NULL) {
18041 			ire_refrele(ire);
18042 			/* No more access to ire */
18043 			ire = NULL;
18044 		}
18045 	}
18046 
18047 	if (attach_ill != NULL)
18048 		goto send_from_ill;
18049 
18050 	/*
18051 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18052 	 * this for the tcp global queue and listen end point
18053 	 * as it does not really have a real destination to
18054 	 * talk to.  This is also true for SCTP.
18055 	 */
18056 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18057 	    !connp->conn_fully_bound) {
18058 		ire = ire_cache_lookup(dst, zoneid);
18059 		if (ire == NULL)
18060 			goto noirefound;
18061 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18062 		    "ip_wput_end: q %p (%S)", q, "end");
18063 
18064 		/*
18065 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18066 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18067 		 */
18068 		if (ire->ire_flags & RTF_MULTIRT) {
18069 
18070 			/*
18071 			 * Force the TTL of multirouted packets if required.
18072 			 * The TTL of such packets is bounded by the
18073 			 * ip_multirt_ttl ndd variable.
18074 			 */
18075 			if ((ip_multirt_ttl > 0) &&
18076 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18077 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18078 				    "(was %d), dst 0x%08x\n",
18079 				    ip_multirt_ttl, ipha->ipha_ttl,
18080 				    ntohl(ire->ire_addr)));
18081 				ipha->ipha_ttl = ip_multirt_ttl;
18082 			}
18083 			/*
18084 			 * We look at this point if there are pending
18085 			 * unresolved routes. ire_multirt_resolvable()
18086 			 * checks in O(n) that all IRE_OFFSUBNET ire
18087 			 * entries for the packet's destination and
18088 			 * flagged RTF_MULTIRT are currently resolved.
18089 			 * If some remain unresolved, we make a copy
18090 			 * of the current message. It will be used
18091 			 * to initiate additional route resolutions.
18092 			 */
18093 			multirt_need_resolve =
18094 			    ire_multirt_need_resolve(ire->ire_addr);
18095 			ip2dbg(("ip_wput[TCP]: ire %p, "
18096 			    "multirt_need_resolve %d, first_mp %p\n",
18097 			    (void *)ire, multirt_need_resolve,
18098 			    (void *)first_mp));
18099 			if (multirt_need_resolve) {
18100 				copy_mp = copymsg(first_mp);
18101 				if (copy_mp != NULL) {
18102 					MULTIRT_DEBUG_TAG(copy_mp);
18103 				}
18104 			}
18105 		}
18106 
18107 		ip_wput_ire(q, first_mp, ire, connp, caller);
18108 
18109 		/*
18110 		 * Try to resolve another multiroute if
18111 		 * ire_multirt_need_resolve() deemed it necessary.
18112 		 */
18113 		if (copy_mp != NULL) {
18114 			ip_newroute(q, copy_mp, dst, NULL, connp);
18115 		}
18116 		if (need_decref)
18117 			CONN_DEC_REF(connp);
18118 		return;
18119 	}
18120 
18121 	/*
18122 	 * Access to conn_ire_cache. (protected by conn_lock)
18123 	 *
18124 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18125 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18126 	 * send a packet or two with the IRE_CACHE that is going away.
18127 	 * Access to the ire requires an ire refhold on the ire prior to
18128 	 * its use since an interface unplumb thread may delete the cached
18129 	 * ire and release the refhold at any time.
18130 	 *
18131 	 * Caching an ire in the conn_ire_cache
18132 	 *
18133 	 * o Caching an ire pointer in the conn requires a strict check for
18134 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18135 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18136 	 * in the conn is done after making sure under the bucket lock that the
18137 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18138 	 * caching an ire after the unplumb thread has cleaned up the conn.
18139 	 * If the conn does not send a packet subsequently the unplumb thread
18140 	 * will be hanging waiting for the ire count to drop to zero.
18141 	 *
18142 	 * o We also need to atomically test for a null conn_ire_cache and
18143 	 * set the conn_ire_cache under the the protection of the conn_lock
18144 	 * to avoid races among concurrent threads trying to simultaneously
18145 	 * cache an ire in the conn_ire_cache.
18146 	 */
18147 	mutex_enter(&connp->conn_lock);
18148 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18149 
18150 	if (ire != NULL && ire->ire_addr == dst &&
18151 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18152 
18153 		IRE_REFHOLD(ire);
18154 		mutex_exit(&connp->conn_lock);
18155 
18156 	} else {
18157 		boolean_t cached = B_FALSE;
18158 		connp->conn_ire_cache = NULL;
18159 		mutex_exit(&connp->conn_lock);
18160 		/* Release the old ire */
18161 		if (ire != NULL && sctp_ire == NULL)
18162 			IRE_REFRELE_NOTR(ire);
18163 
18164 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
18165 		if (ire == NULL)
18166 			goto noirefound;
18167 		IRE_REFHOLD_NOTR(ire);
18168 
18169 		mutex_enter(&connp->conn_lock);
18170 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18171 		    connp->conn_ire_cache == NULL) {
18172 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18173 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18174 				connp->conn_ire_cache = ire;
18175 				cached = B_TRUE;
18176 			}
18177 			rw_exit(&ire->ire_bucket->irb_lock);
18178 		}
18179 		mutex_exit(&connp->conn_lock);
18180 
18181 		/*
18182 		 * We can continue to use the ire but since it was
18183 		 * not cached, we should drop the extra reference.
18184 		 */
18185 		if (!cached)
18186 			IRE_REFRELE_NOTR(ire);
18187 	}
18188 
18189 
18190 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18191 	    "ip_wput_end: q %p (%S)", q, "end");
18192 
18193 	/*
18194 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18195 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18196 	 */
18197 	if (ire->ire_flags & RTF_MULTIRT) {
18198 
18199 		/*
18200 		 * Force the TTL of multirouted packets if required.
18201 		 * The TTL of such packets is bounded by the
18202 		 * ip_multirt_ttl ndd variable.
18203 		 */
18204 		if ((ip_multirt_ttl > 0) &&
18205 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18206 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18207 			    "(was %d), dst 0x%08x\n",
18208 			    ip_multirt_ttl, ipha->ipha_ttl,
18209 			    ntohl(ire->ire_addr)));
18210 			ipha->ipha_ttl = ip_multirt_ttl;
18211 		}
18212 
18213 		/*
18214 		 * At this point, we check to see if there are any pending
18215 		 * unresolved routes. ire_multirt_resolvable()
18216 		 * checks in O(n) that all IRE_OFFSUBNET ire
18217 		 * entries for the packet's destination and
18218 		 * flagged RTF_MULTIRT are currently resolved.
18219 		 * If some remain unresolved, we make a copy
18220 		 * of the current message. It will be used
18221 		 * to initiate additional route resolutions.
18222 		 */
18223 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18224 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18225 		    "multirt_need_resolve %d, first_mp %p\n",
18226 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18227 		if (multirt_need_resolve) {
18228 			copy_mp = copymsg(first_mp);
18229 			if (copy_mp != NULL) {
18230 				MULTIRT_DEBUG_TAG(copy_mp);
18231 			}
18232 		}
18233 	}
18234 
18235 	ip_wput_ire(q, first_mp, ire, connp, caller);
18236 
18237 	/*
18238 	 * Try to resolve another multiroute if
18239 	 * ire_multirt_resolvable() deemed it necessary
18240 	 */
18241 	if (copy_mp != NULL) {
18242 		ip_newroute(q, copy_mp, dst, NULL, connp);
18243 	}
18244 	if (need_decref)
18245 		CONN_DEC_REF(connp);
18246 	return;
18247 
18248 qnext:
18249 	/*
18250 	 * Upper Level Protocols pass down complete IP datagrams
18251 	 * as M_DATA messages.	Everything else is a sideshow.
18252 	 *
18253 	 * 1) We could be re-entering ip_wput because of ip_neworute
18254 	 *    in which case we could have a IPSEC_OUT message. We
18255 	 *    need to pass through ip_wput like other datagrams and
18256 	 *    hence cannot branch to ip_wput_nondata.
18257 	 *
18258 	 * 2) ARP, AH, ESP, and other clients who are on the module
18259 	 *    instance of IP stream, give us something to deal with.
18260 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18261 	 *
18262 	 * 3) ICMP replies also could come here.
18263 	 */
18264 	if (DB_TYPE(mp) != M_DATA) {
18265 	    notdata:
18266 		if (DB_TYPE(mp) == M_CTL) {
18267 			/*
18268 			 * M_CTL messages are used by ARP, AH and ESP to
18269 			 * communicate with IP. We deal with IPSEC_IN and
18270 			 * IPSEC_OUT here. ip_wput_nondata handles other
18271 			 * cases.
18272 			 */
18273 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18274 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18275 				first_mp = mp->b_cont;
18276 				first_mp->b_flag &= ~MSGHASREF;
18277 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18278 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18279 				CONN_DEC_REF(connp);
18280 				connp = NULL;
18281 			}
18282 			if (ii->ipsec_info_type == IPSEC_IN) {
18283 				/*
18284 				 * Either this message goes back to
18285 				 * IPSEC for further processing or to
18286 				 * ULP after policy checks.
18287 				 */
18288 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18289 				return;
18290 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18291 				io = (ipsec_out_t *)ii;
18292 				if (io->ipsec_out_proc_begin) {
18293 					/*
18294 					 * IPSEC processing has already started.
18295 					 * Complete it.
18296 					 * IPQoS notes: We don't care what is
18297 					 * in ipsec_out_ill_index since this
18298 					 * won't be processed for IPQoS policies
18299 					 * in ipsec_out_process.
18300 					 */
18301 					ipsec_out_process(q, mp, NULL,
18302 					    io->ipsec_out_ill_index);
18303 					return;
18304 				} else {
18305 					connp = (q->q_next != NULL) ?
18306 					    NULL : Q_TO_CONN(q);
18307 					first_mp = mp;
18308 					mp = mp->b_cont;
18309 					mctl_present = B_TRUE;
18310 				}
18311 				zoneid = io->ipsec_out_zoneid;
18312 				ASSERT(zoneid != ALL_ZONES);
18313 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18314 				/*
18315 				 * It's an IPsec control message requesting
18316 				 * an SADB update to be sent to the IPsec
18317 				 * hardware acceleration capable ills.
18318 				 */
18319 				ipsec_ctl_t *ipsec_ctl =
18320 				    (ipsec_ctl_t *)mp->b_rptr;
18321 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18322 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18323 				mblk_t *cmp = mp->b_cont;
18324 
18325 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18326 				ASSERT(cmp != NULL);
18327 
18328 				freeb(mp);
18329 				ill_ipsec_capab_send_all(satype, cmp, sa);
18330 				return;
18331 			} else {
18332 				/*
18333 				 * This must be ARP.
18334 				 */
18335 				ip_wput_nondata(NULL, q, mp, NULL);
18336 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18337 				    "ip_wput_end: q %p (%S)", q, "nondata");
18338 				return;
18339 			}
18340 		} else {
18341 			/*
18342 			 * This must be non-(ARP/AH/ESP) messages.
18343 			 */
18344 			ASSERT(!need_decref);
18345 			ip_wput_nondata(NULL, q, mp, NULL);
18346 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18347 			    "ip_wput_end: q %p (%S)", q, "nondata");
18348 			return;
18349 		}
18350 	} else {
18351 		first_mp = mp;
18352 		mctl_present = B_FALSE;
18353 	}
18354 
18355 	ASSERT(first_mp != NULL);
18356 	/*
18357 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18358 	 * to make sure that this packet goes out on the same interface it
18359 	 * came in. We handle that here.
18360 	 */
18361 	if (mctl_present) {
18362 		uint_t ifindex;
18363 
18364 		io = (ipsec_out_t *)first_mp->b_rptr;
18365 		if (io->ipsec_out_attach_if ||
18366 		    io->ipsec_out_xmit_if ||
18367 		    io->ipsec_out_ip_nexthop) {
18368 			ill_t	*ill;
18369 
18370 			/*
18371 			 * We may have lost the conn context if we are
18372 			 * coming here from ip_newroute(). Copy the
18373 			 * nexthop information.
18374 			 */
18375 			if (io->ipsec_out_ip_nexthop) {
18376 				ip_nexthop = B_TRUE;
18377 				nexthop_addr = io->ipsec_out_nexthop_addr;
18378 
18379 				ipha = (ipha_t *)mp->b_rptr;
18380 				dst = ipha->ipha_dst;
18381 				goto send_from_ill;
18382 			} else {
18383 				ASSERT(io->ipsec_out_ill_index != 0);
18384 				ifindex = io->ipsec_out_ill_index;
18385 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18386 				    NULL, NULL, NULL, NULL);
18387 				/*
18388 				 * ipsec_out_xmit_if bit is used to tell
18389 				 * ip_wput to use the ill to send outgoing data
18390 				 * as we have no conn when data comes from ICMP
18391 				 * error msg routines. Currently this feature is
18392 				 * only used by ip_mrtun_forward routine.
18393 				 */
18394 				if (io->ipsec_out_xmit_if) {
18395 					xmit_ill = ill;
18396 					if (xmit_ill == NULL) {
18397 						ip1dbg(("ip_output:bad ifindex "
18398 						    "for xmit_ill %d\n",
18399 						    ifindex));
18400 						freemsg(first_mp);
18401 						BUMP_MIB(&ip_mib,
18402 						    ipOutDiscards);
18403 						ASSERT(!need_decref);
18404 						return;
18405 					}
18406 					/* Free up the ipsec_out_t mblk */
18407 					ASSERT(first_mp->b_cont == mp);
18408 					first_mp->b_cont = NULL;
18409 					freeb(first_mp);
18410 					/* Just send the IP header+ICMP+data */
18411 					first_mp = mp;
18412 					ipha = (ipha_t *)mp->b_rptr;
18413 					dst = ipha->ipha_dst;
18414 					goto send_from_ill;
18415 				} else {
18416 					attach_ill = ill;
18417 				}
18418 
18419 				if (attach_ill == NULL) {
18420 					ASSERT(xmit_ill == NULL);
18421 					ip1dbg(("ip_output: bad ifindex for "
18422 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
18423 					    ifindex));
18424 					freemsg(first_mp);
18425 					BUMP_MIB(&ip_mib, ipOutDiscards);
18426 					ASSERT(!need_decref);
18427 					return;
18428 				}
18429 			}
18430 		}
18431 	}
18432 
18433 	ASSERT(xmit_ill == NULL);
18434 
18435 	/* We have a complete IP datagram heading outbound. */
18436 	ipha = (ipha_t *)mp->b_rptr;
18437 
18438 #ifndef SPEED_BEFORE_SAFETY
18439 	/*
18440 	 * Make sure we have a full-word aligned message and that at least
18441 	 * a simple IP header is accessible in the first message.  If not,
18442 	 * try a pullup.
18443 	 */
18444 	if (!OK_32PTR(rptr) ||
18445 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18446 	    hdrtoosmall:
18447 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18448 			BUMP_MIB(&ip_mib, ipOutDiscards);
18449 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18450 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18451 			if (first_mp == NULL)
18452 				first_mp = mp;
18453 			goto drop_pkt;
18454 		}
18455 		ipha = (ipha_t *)mp->b_rptr;
18456 		if (first_mp == NULL) {
18457 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18458 			/*
18459 			 * If we got here because of "goto hdrtoosmall"
18460 			 * We need to attach a IPSEC_OUT.
18461 			 */
18462 			if (connp->conn_out_enforce_policy) {
18463 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18464 				    NULL, ipha->ipha_protocol)) == NULL)) {
18465 					if (need_decref)
18466 						CONN_DEC_REF(connp);
18467 					return;
18468 				} else {
18469 					ASSERT(mp->b_datap->db_type == M_CTL);
18470 					first_mp = mp;
18471 					mp = mp->b_cont;
18472 					mctl_present = B_TRUE;
18473 				}
18474 			} else {
18475 				first_mp = mp;
18476 				mctl_present = B_FALSE;
18477 			}
18478 		}
18479 	}
18480 #endif
18481 
18482 	/* Most of the code below is written for speed, not readability */
18483 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18484 
18485 	/*
18486 	 * If ip_newroute() fails, we're going to need a full
18487 	 * header for the icmp wraparound.
18488 	 */
18489 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18490 		uint_t	v_hlen;
18491 	    version_hdrlen_check:
18492 		ASSERT(first_mp != NULL);
18493 		v_hlen = V_HLEN;
18494 		/*
18495 		 * siphon off IPv6 packets coming down from transport
18496 		 * layer modules here.
18497 		 * Note: high-order bit carries NUD reachability confirmation
18498 		 */
18499 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18500 			/*
18501 			 * XXX implement a IPv4 and IPv6 packet counter per
18502 			 * conn and switch when ratio exceeds e.g. 10:1
18503 			 */
18504 #ifdef notyet
18505 			if (q->q_next == NULL) /* Avoid ill queue */
18506 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18507 #endif
18508 			BUMP_MIB(&ip_mib, ipOutIPv6);
18509 			ASSERT(xmit_ill == NULL);
18510 			if (attach_ill != NULL)
18511 				ill_refrele(attach_ill);
18512 			if (need_decref)
18513 				mp->b_flag |= MSGHASREF;
18514 			(void) ip_output_v6(connp, first_mp, q, caller);
18515 			return;
18516 		}
18517 
18518 		if ((v_hlen >> 4) != IP_VERSION) {
18519 			BUMP_MIB(&ip_mib, ipOutDiscards);
18520 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18521 			    "ip_wput_end: q %p (%S)", q, "badvers");
18522 			goto drop_pkt;
18523 		}
18524 		/*
18525 		 * Is the header length at least 20 bytes?
18526 		 *
18527 		 * Are there enough bytes accessible in the header?  If
18528 		 * not, try a pullup.
18529 		 */
18530 		v_hlen &= 0xF;
18531 		v_hlen <<= 2;
18532 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18533 			BUMP_MIB(&ip_mib, ipOutDiscards);
18534 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18535 			    "ip_wput_end: q %p (%S)", q, "badlen");
18536 			goto drop_pkt;
18537 		}
18538 		if (v_hlen > (mp->b_wptr - rptr)) {
18539 			if (!pullupmsg(mp, v_hlen)) {
18540 				BUMP_MIB(&ip_mib, ipOutDiscards);
18541 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18542 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18543 				goto drop_pkt;
18544 			}
18545 			ipha = (ipha_t *)mp->b_rptr;
18546 		}
18547 		/*
18548 		 * Move first entry from any source route into ipha_dst and
18549 		 * verify the options
18550 		 */
18551 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18552 			ASSERT(xmit_ill == NULL);
18553 			if (attach_ill != NULL)
18554 				ill_refrele(attach_ill);
18555 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18556 			    "ip_wput_end: q %p (%S)", q, "badopts");
18557 			if (need_decref)
18558 				CONN_DEC_REF(connp);
18559 			return;
18560 		}
18561 	}
18562 	dst = ipha->ipha_dst;
18563 
18564 	/*
18565 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18566 	 * we have to run the packet through ip_newroute which will take
18567 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18568 	 * a resolver, or assigning a default gateway, etc.
18569 	 */
18570 	if (CLASSD(dst)) {
18571 		ipif_t	*ipif;
18572 		uint32_t setsrc = 0;
18573 
18574 	    multicast:
18575 		ASSERT(first_mp != NULL);
18576 		ASSERT(xmit_ill == NULL);
18577 		ip2dbg(("ip_wput: CLASSD\n"));
18578 		if (connp == NULL) {
18579 			/*
18580 			 * Use the first good ipif on the ill.
18581 			 * XXX Should this ever happen? (Appears
18582 			 * to show up with just ppp and no ethernet due
18583 			 * to in.rdisc.)
18584 			 * However, ire_send should be able to
18585 			 * call ip_wput_ire directly.
18586 			 *
18587 			 * XXX Also, this can happen for ICMP and other packets
18588 			 * with multicast source addresses.  Perhaps we should
18589 			 * fix things so that we drop the packet in question,
18590 			 * but for now, just run with it.
18591 			 */
18592 			ill_t *ill = (ill_t *)q->q_ptr;
18593 
18594 			/*
18595 			 * Don't honor attach_if for this case. If ill
18596 			 * is part of the group, ipif could belong to
18597 			 * any ill and we cannot maintain attach_ill
18598 			 * and ipif_ill same anymore and the assert
18599 			 * below would fail.
18600 			 */
18601 			if (mctl_present) {
18602 				io->ipsec_out_ill_index = 0;
18603 				io->ipsec_out_attach_if = B_FALSE;
18604 				ASSERT(attach_ill != NULL);
18605 				ill_refrele(attach_ill);
18606 				attach_ill = NULL;
18607 			}
18608 
18609 			ASSERT(attach_ill == NULL);
18610 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18611 			if (ipif == NULL) {
18612 				if (need_decref)
18613 					CONN_DEC_REF(connp);
18614 				freemsg(first_mp);
18615 				return;
18616 			}
18617 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18618 			    ntohl(dst), ill->ill_name));
18619 		} else {
18620 			/*
18621 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18622 			 * IP_XMIT_IF is honoured.
18623 			 * Block comment above this function explains the
18624 			 * locking mechanism used here
18625 			 */
18626 			xmit_ill = conn_get_held_ill(connp,
18627 			    &connp->conn_xmit_if_ill, &err);
18628 			if (err == ILL_LOOKUP_FAILED) {
18629 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18630 				goto drop_pkt;
18631 			}
18632 			if (xmit_ill == NULL) {
18633 				ipif = conn_get_held_ipif(connp,
18634 				    &connp->conn_multicast_ipif, &err);
18635 				if (err == IPIF_LOOKUP_FAILED) {
18636 					ip1dbg(("ip_wput: No ipif for "
18637 					    "multicast\n"));
18638 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18639 					goto drop_pkt;
18640 				}
18641 			}
18642 			if (xmit_ill != NULL) {
18643 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18644 				if (ipif == NULL) {
18645 					ip1dbg(("ip_wput: No ipif for "
18646 					    "IP_XMIT_IF\n"));
18647 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18648 					goto drop_pkt;
18649 				}
18650 			} else if (ipif == NULL || ipif->ipif_isv6) {
18651 				/*
18652 				 * We must do this ipif determination here
18653 				 * else we could pass through ip_newroute
18654 				 * and come back here without the conn context.
18655 				 *
18656 				 * Note: we do late binding i.e. we bind to
18657 				 * the interface when the first packet is sent.
18658 				 * For performance reasons we do not rebind on
18659 				 * each packet but keep the binding until the
18660 				 * next IP_MULTICAST_IF option.
18661 				 *
18662 				 * conn_multicast_{ipif,ill} are shared between
18663 				 * IPv4 and IPv6 and AF_INET6 sockets can
18664 				 * send both IPv4 and IPv6 packets. Hence
18665 				 * we have to check that "isv6" matches above.
18666 				 */
18667 				if (ipif != NULL)
18668 					ipif_refrele(ipif);
18669 				ipif = ipif_lookup_group(dst, zoneid);
18670 				if (ipif == NULL) {
18671 					ip1dbg(("ip_wput: No ipif for "
18672 					    "multicast\n"));
18673 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18674 					goto drop_pkt;
18675 				}
18676 				err = conn_set_held_ipif(connp,
18677 				    &connp->conn_multicast_ipif, ipif);
18678 				if (err == IPIF_LOOKUP_FAILED) {
18679 					ipif_refrele(ipif);
18680 					ip1dbg(("ip_wput: No ipif for "
18681 					    "multicast\n"));
18682 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18683 					goto drop_pkt;
18684 				}
18685 			}
18686 		}
18687 		ASSERT(!ipif->ipif_isv6);
18688 		/*
18689 		 * As we may lose the conn by the time we reach ip_wput_ire,
18690 		 * we copy conn_multicast_loop and conn_dontroute on to an
18691 		 * ipsec_out. In case if this datagram goes out secure,
18692 		 * we need the ill_index also. Copy that also into the
18693 		 * ipsec_out.
18694 		 */
18695 		if (mctl_present) {
18696 			io = (ipsec_out_t *)first_mp->b_rptr;
18697 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18698 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18699 		} else {
18700 			ASSERT(mp == first_mp);
18701 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18702 			    BPRI_HI)) == NULL) {
18703 				ipif_refrele(ipif);
18704 				first_mp = mp;
18705 				goto drop_pkt;
18706 			}
18707 			first_mp->b_datap->db_type = M_CTL;
18708 			first_mp->b_wptr += sizeof (ipsec_info_t);
18709 			/* ipsec_out_secure is B_FALSE now */
18710 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18711 			io = (ipsec_out_t *)first_mp->b_rptr;
18712 			io->ipsec_out_type = IPSEC_OUT;
18713 			io->ipsec_out_len = sizeof (ipsec_out_t);
18714 			io->ipsec_out_use_global_policy = B_TRUE;
18715 			first_mp->b_cont = mp;
18716 			mctl_present = B_TRUE;
18717 		}
18718 		if (attach_ill != NULL) {
18719 			ASSERT(attach_ill == ipif->ipif_ill);
18720 			match_flags = MATCH_IRE_ILL;
18721 
18722 			/*
18723 			 * Check if we need an ire that will not be
18724 			 * looked up by anybody else i.e. HIDDEN.
18725 			 */
18726 			if (ill_is_probeonly(attach_ill)) {
18727 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18728 			}
18729 			io->ipsec_out_ill_index =
18730 			    attach_ill->ill_phyint->phyint_ifindex;
18731 			io->ipsec_out_attach_if = B_TRUE;
18732 		} else {
18733 			match_flags = MATCH_IRE_ILL_GROUP;
18734 			io->ipsec_out_ill_index =
18735 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18736 		}
18737 		if (connp != NULL) {
18738 			io->ipsec_out_multicast_loop =
18739 			    connp->conn_multicast_loop;
18740 			io->ipsec_out_dontroute = connp->conn_dontroute;
18741 			io->ipsec_out_zoneid = connp->conn_zoneid;
18742 		}
18743 		/*
18744 		 * If the application uses IP_MULTICAST_IF with
18745 		 * different logical addresses of the same ILL, we
18746 		 * need to make sure that the soruce address of
18747 		 * the packet matches the logical IP address used
18748 		 * in the option. We do it by initializing ipha_src
18749 		 * here. This should keep IPSEC also happy as
18750 		 * when we return from IPSEC processing, we don't
18751 		 * have to worry about getting the right address on
18752 		 * the packet. Thus it is sufficient to look for
18753 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18754 		 * MATCH_IRE_IPIF.
18755 		 *
18756 		 * NOTE : We need to do it for non-secure case also as
18757 		 * this might go out secure if there is a global policy
18758 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18759 		 * address, the source should be initialized already and
18760 		 * hence we won't be initializing here.
18761 		 *
18762 		 * As we do not have the ire yet, it is possible that
18763 		 * we set the source address here and then later discover
18764 		 * that the ire implies the source address to be assigned
18765 		 * through the RTF_SETSRC flag.
18766 		 * In that case, the setsrc variable will remind us
18767 		 * that overwritting the source address by the one
18768 		 * of the RTF_SETSRC-flagged ire is allowed.
18769 		 */
18770 		if (ipha->ipha_src == INADDR_ANY &&
18771 		    (connp == NULL || !connp->conn_unspec_src)) {
18772 			ipha->ipha_src = ipif->ipif_src_addr;
18773 			setsrc = RTF_SETSRC;
18774 		}
18775 		/*
18776 		 * Find an IRE which matches the destination and the outgoing
18777 		 * queue (i.e. the outgoing interface.)
18778 		 * For loopback use a unicast IP address for
18779 		 * the ire lookup.
18780 		 */
18781 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18782 		    PHYI_LOOPBACK) {
18783 			dst = ipif->ipif_lcl_addr;
18784 		}
18785 		/*
18786 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18787 		 * We don't need to lookup ire in ctable as the packet
18788 		 * needs to be sent to the destination through the specified
18789 		 * ill irrespective of ires in the cache table.
18790 		 */
18791 		ire = NULL;
18792 		if (xmit_ill == NULL) {
18793 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18794 			    zoneid, match_flags);
18795 		}
18796 
18797 		/*
18798 		 * refrele attach_ill as its not needed anymore.
18799 		 */
18800 		if (attach_ill != NULL) {
18801 			ill_refrele(attach_ill);
18802 			attach_ill = NULL;
18803 		}
18804 
18805 		if (ire == NULL) {
18806 			/*
18807 			 * Multicast loopback and multicast forwarding is
18808 			 * done in ip_wput_ire.
18809 			 *
18810 			 * Mark this packet to make it be delivered to
18811 			 * ip_wput_ire after the new ire has been
18812 			 * created.
18813 			 *
18814 			 * The call to ip_newroute_ipif takes into account
18815 			 * the setsrc reminder. In any case, we take care
18816 			 * of the RTF_MULTIRT flag.
18817 			 */
18818 			mp->b_prev = mp->b_next = NULL;
18819 			if (xmit_ill == NULL ||
18820 			    xmit_ill->ill_ipif_up_count > 0) {
18821 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18822 				    setsrc | RTF_MULTIRT);
18823 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18824 				    "ip_wput_end: q %p (%S)", q, "noire");
18825 			} else {
18826 				freemsg(first_mp);
18827 			}
18828 			ipif_refrele(ipif);
18829 			if (xmit_ill != NULL)
18830 				ill_refrele(xmit_ill);
18831 			if (need_decref)
18832 				CONN_DEC_REF(connp);
18833 			return;
18834 		}
18835 
18836 		ipif_refrele(ipif);
18837 		ipif = NULL;
18838 		ASSERT(xmit_ill == NULL);
18839 
18840 		/*
18841 		 * Honor the RTF_SETSRC flag for multicast packets,
18842 		 * if allowed by the setsrc reminder.
18843 		 */
18844 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18845 			ipha->ipha_src = ire->ire_src_addr;
18846 		}
18847 
18848 		/*
18849 		 * Unconditionally force the TTL to 1 for
18850 		 * multirouted multicast packets:
18851 		 * multirouted multicast should not cross
18852 		 * multicast routers.
18853 		 */
18854 		if (ire->ire_flags & RTF_MULTIRT) {
18855 			if (ipha->ipha_ttl > 1) {
18856 				ip2dbg(("ip_wput: forcing multicast "
18857 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18858 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18859 				ipha->ipha_ttl = 1;
18860 			}
18861 		}
18862 	} else {
18863 		ire = ire_cache_lookup(dst, zoneid);
18864 		if ((ire != NULL) && (ire->ire_type &
18865 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18866 			ignore_dontroute = B_TRUE;
18867 			ignore_nexthop = B_TRUE;
18868 		}
18869 		if (ire != NULL) {
18870 			ire_refrele(ire);
18871 			ire = NULL;
18872 		}
18873 		/*
18874 		 * Guard against coming in from arp in which case conn is NULL.
18875 		 * Also guard against non M_DATA with dontroute set but
18876 		 * destined to local, loopback or broadcast addresses.
18877 		 */
18878 		if (connp != NULL && connp->conn_dontroute &&
18879 		    !ignore_dontroute) {
18880 dontroute:
18881 			/*
18882 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18883 			 * routing protocols from seeing false direct
18884 			 * connectivity.
18885 			 */
18886 			ipha->ipha_ttl = 1;
18887 			/*
18888 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18889 			 * along with SO_DONTROUTE, higher precedence is
18890 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18891 			 */
18892 			if (connp->conn_xmit_if_ill == NULL) {
18893 				/* If suitable ipif not found, drop packet */
18894 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18895 				if (dst_ipif == NULL) {
18896 					ip1dbg(("ip_wput: no route for "
18897 					    "dst using SO_DONTROUTE\n"));
18898 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18899 					mp->b_prev = mp->b_next = NULL;
18900 					if (first_mp == NULL)
18901 						first_mp = mp;
18902 					goto drop_pkt;
18903 				} else {
18904 					/*
18905 					 * If suitable ipif has been found, set
18906 					 * xmit_ill to the corresponding
18907 					 * ipif_ill because we'll be following
18908 					 * the IP_XMIT_IF logic.
18909 					 */
18910 					ASSERT(xmit_ill == NULL);
18911 					xmit_ill = dst_ipif->ipif_ill;
18912 					mutex_enter(&xmit_ill->ill_lock);
18913 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18914 						mutex_exit(&xmit_ill->ill_lock);
18915 						xmit_ill = NULL;
18916 						ipif_refrele(dst_ipif);
18917 						ip1dbg(("ip_wput: no route for"
18918 						    " dst using"
18919 						    " SO_DONTROUTE\n"));
18920 						BUMP_MIB(&ip_mib,
18921 						    ipOutNoRoutes);
18922 						mp->b_prev = mp->b_next = NULL;
18923 						if (first_mp == NULL)
18924 							first_mp = mp;
18925 						goto drop_pkt;
18926 					}
18927 					ill_refhold_locked(xmit_ill);
18928 					mutex_exit(&xmit_ill->ill_lock);
18929 					ipif_refrele(dst_ipif);
18930 				}
18931 			}
18932 
18933 		}
18934 		/*
18935 		 * If we are bound to IPIF_NOFAILOVER address, look for
18936 		 * an IRE_CACHE matching the ill.
18937 		 */
18938 send_from_ill:
18939 		if (attach_ill != NULL) {
18940 			ipif_t	*attach_ipif;
18941 
18942 			match_flags = MATCH_IRE_ILL;
18943 
18944 			/*
18945 			 * Check if we need an ire that will not be
18946 			 * looked up by anybody else i.e. HIDDEN.
18947 			 */
18948 			if (ill_is_probeonly(attach_ill)) {
18949 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18950 			}
18951 
18952 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18953 			if (attach_ipif == NULL) {
18954 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18955 				goto drop_pkt;
18956 			}
18957 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18958 			    zoneid, match_flags);
18959 			ipif_refrele(attach_ipif);
18960 		} else if (xmit_ill != NULL || (connp != NULL &&
18961 			    connp->conn_xmit_if_ill != NULL)) {
18962 			/*
18963 			 * Mark this packet as originated locally
18964 			 */
18965 			mp->b_prev = mp->b_next = NULL;
18966 			/*
18967 			 * xmit_ill could be NULL if SO_DONTROUTE
18968 			 * is also set.
18969 			 */
18970 			if (xmit_ill == NULL) {
18971 				xmit_ill = conn_get_held_ill(connp,
18972 				    &connp->conn_xmit_if_ill, &err);
18973 				if (err == ILL_LOOKUP_FAILED) {
18974 					if (need_decref)
18975 						CONN_DEC_REF(connp);
18976 					freemsg(first_mp);
18977 					return;
18978 				}
18979 				if (xmit_ill == NULL) {
18980 					if (connp->conn_dontroute)
18981 						goto dontroute;
18982 					goto send_from_ill;
18983 				}
18984 			}
18985 			/*
18986 			 * could be SO_DONTROUTE case also.
18987 			 * check at least one interface is UP as
18988 			 * spcified by this ILL, and then call
18989 			 * ip_newroute_ipif()
18990 			 */
18991 			if (xmit_ill->ill_ipif_up_count > 0) {
18992 				ipif_t *ipif;
18993 
18994 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18995 				if (ipif != NULL) {
18996 					ip_newroute_ipif(q, first_mp, ipif,
18997 					    dst, connp, 0);
18998 					ipif_refrele(ipif);
18999 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19000 				}
19001 			} else {
19002 				freemsg(first_mp);
19003 			}
19004 			ill_refrele(xmit_ill);
19005 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19006 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19007 			if (need_decref)
19008 				CONN_DEC_REF(connp);
19009 			return;
19010 		} else if (ip_nexthop || (connp != NULL &&
19011 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19012 			if (!ip_nexthop) {
19013 				ip_nexthop = B_TRUE;
19014 				nexthop_addr = connp->conn_nexthop_v4;
19015 			}
19016 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19017 			    MATCH_IRE_GW;
19018 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19019 			    NULL, zoneid, match_flags);
19020 		} else {
19021 			ire = ire_cache_lookup(dst, zoneid);
19022 		}
19023 		if (!ire) {
19024 			/*
19025 			 * Make sure we don't load spread if this
19026 			 * is IPIF_NOFAILOVER case.
19027 			 */
19028 			if ((attach_ill != NULL) ||
19029 			    (ip_nexthop && !ignore_nexthop)) {
19030 				if (mctl_present) {
19031 					io = (ipsec_out_t *)first_mp->b_rptr;
19032 					ASSERT(first_mp->b_datap->db_type ==
19033 					    M_CTL);
19034 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19035 				} else {
19036 					ASSERT(mp == first_mp);
19037 					first_mp = allocb(
19038 					    sizeof (ipsec_info_t), BPRI_HI);
19039 					if (first_mp == NULL) {
19040 						first_mp = mp;
19041 						goto drop_pkt;
19042 					}
19043 					first_mp->b_datap->db_type = M_CTL;
19044 					first_mp->b_wptr +=
19045 					    sizeof (ipsec_info_t);
19046 					/* ipsec_out_secure is B_FALSE now */
19047 					bzero(first_mp->b_rptr,
19048 					    sizeof (ipsec_info_t));
19049 					io = (ipsec_out_t *)first_mp->b_rptr;
19050 					io->ipsec_out_type = IPSEC_OUT;
19051 					io->ipsec_out_len =
19052 					    sizeof (ipsec_out_t);
19053 					io->ipsec_out_use_global_policy =
19054 					    B_TRUE;
19055 					first_mp->b_cont = mp;
19056 					mctl_present = B_TRUE;
19057 				}
19058 				if (attach_ill != NULL) {
19059 					io->ipsec_out_ill_index = attach_ill->
19060 					    ill_phyint->phyint_ifindex;
19061 					io->ipsec_out_attach_if = B_TRUE;
19062 				} else {
19063 					io->ipsec_out_ip_nexthop = ip_nexthop;
19064 					io->ipsec_out_nexthop_addr =
19065 					    nexthop_addr;
19066 				}
19067 			}
19068 noirefound:
19069 			/*
19070 			 * Mark this packet as having originated on
19071 			 * this machine.  This will be noted in
19072 			 * ire_add_then_send, which needs to know
19073 			 * whether to run it back through ip_wput or
19074 			 * ip_rput following successful resolution.
19075 			 */
19076 			mp->b_prev = NULL;
19077 			mp->b_next = NULL;
19078 			ip_newroute(q, first_mp, dst, NULL, connp);
19079 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19080 			    "ip_wput_end: q %p (%S)", q, "newroute");
19081 			if (attach_ill != NULL)
19082 				ill_refrele(attach_ill);
19083 			if (xmit_ill != NULL)
19084 				ill_refrele(xmit_ill);
19085 			if (need_decref)
19086 				CONN_DEC_REF(connp);
19087 			return;
19088 		}
19089 	}
19090 
19091 	/* We now know where we are going with it. */
19092 
19093 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19094 	    "ip_wput_end: q %p (%S)", q, "end");
19095 
19096 	/*
19097 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19098 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19099 	 */
19100 	if (ire->ire_flags & RTF_MULTIRT) {
19101 		/*
19102 		 * Force the TTL of multirouted packets if required.
19103 		 * The TTL of such packets is bounded by the
19104 		 * ip_multirt_ttl ndd variable.
19105 		 */
19106 		if ((ip_multirt_ttl > 0) &&
19107 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19108 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19109 			    "(was %d), dst 0x%08x\n",
19110 			    ip_multirt_ttl, ipha->ipha_ttl,
19111 			    ntohl(ire->ire_addr)));
19112 			ipha->ipha_ttl = ip_multirt_ttl;
19113 		}
19114 		/*
19115 		 * At this point, we check to see if there are any pending
19116 		 * unresolved routes. ire_multirt_resolvable()
19117 		 * checks in O(n) that all IRE_OFFSUBNET ire
19118 		 * entries for the packet's destination and
19119 		 * flagged RTF_MULTIRT are currently resolved.
19120 		 * If some remain unresolved, we make a copy
19121 		 * of the current message. It will be used
19122 		 * to initiate additional route resolutions.
19123 		 */
19124 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
19125 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19126 		    "multirt_need_resolve %d, first_mp %p\n",
19127 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19128 		if (multirt_need_resolve) {
19129 			copy_mp = copymsg(first_mp);
19130 			if (copy_mp != NULL) {
19131 				MULTIRT_DEBUG_TAG(copy_mp);
19132 			}
19133 		}
19134 	}
19135 
19136 	ip_wput_ire(q, first_mp, ire, connp, caller);
19137 	/*
19138 	 * Try to resolve another multiroute if
19139 	 * ire_multirt_resolvable() deemed it necessary.
19140 	 * At this point, we need to distinguish
19141 	 * multicasts from other packets. For multicasts,
19142 	 * we call ip_newroute_ipif() and request that both
19143 	 * multirouting and setsrc flags are checked.
19144 	 */
19145 	if (copy_mp != NULL) {
19146 		if (CLASSD(dst)) {
19147 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19148 			if (ipif) {
19149 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19150 				    RTF_SETSRC | RTF_MULTIRT);
19151 				ipif_refrele(ipif);
19152 			} else {
19153 				MULTIRT_DEBUG_UNTAG(copy_mp);
19154 				freemsg(copy_mp);
19155 				copy_mp = NULL;
19156 			}
19157 		} else {
19158 			ip_newroute(q, copy_mp, dst, NULL, connp);
19159 		}
19160 	}
19161 	if (attach_ill != NULL)
19162 		ill_refrele(attach_ill);
19163 	if (xmit_ill != NULL)
19164 		ill_refrele(xmit_ill);
19165 	if (need_decref)
19166 		CONN_DEC_REF(connp);
19167 	return;
19168 
19169 drop_pkt:
19170 	ip1dbg(("ip_wput: dropped packet\n"));
19171 	if (ire != NULL)
19172 		ire_refrele(ire);
19173 	if (need_decref)
19174 		CONN_DEC_REF(connp);
19175 	freemsg(first_mp);
19176 	if (attach_ill != NULL)
19177 		ill_refrele(attach_ill);
19178 	if (xmit_ill != NULL)
19179 		ill_refrele(xmit_ill);
19180 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19181 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19182 }
19183 
19184 void
19185 ip_wput(queue_t *q, mblk_t *mp)
19186 {
19187 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19188 }
19189 
19190 /*
19191  *
19192  * The following rules must be observed when accessing any ipif or ill
19193  * that has been cached in the conn. Typically conn_nofailover_ill,
19194  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19195  *
19196  * Access: The ipif or ill pointed to from the conn can be accessed under
19197  * the protection of the conn_lock or after it has been refheld under the
19198  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19199  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19200  * The reason for this is that a concurrent unplumb could actually be
19201  * cleaning up these cached pointers by walking the conns and might have
19202  * finished cleaning up the conn in question. The macros check that an
19203  * unplumb has not yet started on the ipif or ill.
19204  *
19205  * Caching: An ipif or ill pointer may be cached in the conn only after
19206  * making sure that an unplumb has not started. So the caching is done
19207  * while holding both the conn_lock and the ill_lock and after using the
19208  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
19209  * flag before starting the cleanup of conns.
19210  *
19211  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
19212  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
19213  * or a reference to the ipif or a reference to an ire that references the
19214  * ipif. An ipif does not change its ill except for failover/failback. Since
19215  * failover/failback happens only after bringing down the ipif and making sure
19216  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
19217  * the above holds.
19218  */
19219 ipif_t *
19220 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
19221 {
19222 	ipif_t	*ipif;
19223 	ill_t	*ill;
19224 
19225 	*err = 0;
19226 	rw_enter(&ill_g_lock, RW_READER);
19227 	mutex_enter(&connp->conn_lock);
19228 	ipif = *ipifp;
19229 	if (ipif != NULL) {
19230 		ill = ipif->ipif_ill;
19231 		mutex_enter(&ill->ill_lock);
19232 		if (IPIF_CAN_LOOKUP(ipif)) {
19233 			ipif_refhold_locked(ipif);
19234 			mutex_exit(&ill->ill_lock);
19235 			mutex_exit(&connp->conn_lock);
19236 			rw_exit(&ill_g_lock);
19237 			return (ipif);
19238 		} else {
19239 			*err = IPIF_LOOKUP_FAILED;
19240 		}
19241 		mutex_exit(&ill->ill_lock);
19242 	}
19243 	mutex_exit(&connp->conn_lock);
19244 	rw_exit(&ill_g_lock);
19245 	return (NULL);
19246 }
19247 
19248 ill_t *
19249 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
19250 {
19251 	ill_t	*ill;
19252 
19253 	*err = 0;
19254 	mutex_enter(&connp->conn_lock);
19255 	ill = *illp;
19256 	if (ill != NULL) {
19257 		mutex_enter(&ill->ill_lock);
19258 		if (ILL_CAN_LOOKUP(ill)) {
19259 			ill_refhold_locked(ill);
19260 			mutex_exit(&ill->ill_lock);
19261 			mutex_exit(&connp->conn_lock);
19262 			return (ill);
19263 		} else {
19264 			*err = ILL_LOOKUP_FAILED;
19265 		}
19266 		mutex_exit(&ill->ill_lock);
19267 	}
19268 	mutex_exit(&connp->conn_lock);
19269 	return (NULL);
19270 }
19271 
19272 static int
19273 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
19274 {
19275 	ill_t	*ill;
19276 
19277 	ill = ipif->ipif_ill;
19278 	mutex_enter(&connp->conn_lock);
19279 	mutex_enter(&ill->ill_lock);
19280 	if (IPIF_CAN_LOOKUP(ipif)) {
19281 		*ipifp = ipif;
19282 		mutex_exit(&ill->ill_lock);
19283 		mutex_exit(&connp->conn_lock);
19284 		return (0);
19285 	}
19286 	mutex_exit(&ill->ill_lock);
19287 	mutex_exit(&connp->conn_lock);
19288 	return (IPIF_LOOKUP_FAILED);
19289 }
19290 
19291 /*
19292  * This is called if the outbound datagram needs fragmentation.
19293  *
19294  * NOTE : This function does not ire_refrele the ire argument passed in.
19295  */
19296 static void
19297 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19298 {
19299 	ipha_t		*ipha;
19300 	mblk_t		*mp;
19301 	uint32_t	v_hlen_tos_len;
19302 	uint32_t	max_frag;
19303 	uint32_t	frag_flag;
19304 	boolean_t	dont_use;
19305 
19306 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19307 		mp = ipsec_mp->b_cont;
19308 	} else {
19309 		mp = ipsec_mp;
19310 	}
19311 
19312 	ipha = (ipha_t *)mp->b_rptr;
19313 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19314 
19315 #ifdef	_BIG_ENDIAN
19316 #define	V_HLEN	(v_hlen_tos_len >> 24)
19317 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19318 #else
19319 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19320 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19321 #endif
19322 
19323 #ifndef SPEED_BEFORE_SAFETY
19324 	/*
19325 	 * Check that ipha_length is consistent with
19326 	 * the mblk length
19327 	 */
19328 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19329 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19330 		    LENGTH, msgdsize(mp)));
19331 		freemsg(ipsec_mp);
19332 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19333 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19334 		    "packet length mismatch");
19335 		return;
19336 	}
19337 #endif
19338 	/*
19339 	 * Don't use frag_flag if pre-built packet or source
19340 	 * routed or if multicast (since multicast packets do not solicit
19341 	 * ICMP "packet too big" messages). Get the values of
19342 	 * max_frag and frag_flag atomically by acquiring the
19343 	 * ire_lock.
19344 	 */
19345 	mutex_enter(&ire->ire_lock);
19346 	max_frag = ire->ire_max_frag;
19347 	frag_flag = ire->ire_frag_flag;
19348 	mutex_exit(&ire->ire_lock);
19349 
19350 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19351 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19352 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19353 
19354 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19355 	    (dont_use ? 0 : frag_flag));
19356 }
19357 
19358 /*
19359  * Used for deciding the MSS size for the upper layer. Thus
19360  * we need to check the outbound policy values in the conn.
19361  */
19362 int
19363 conn_ipsec_length(conn_t *connp)
19364 {
19365 	ipsec_latch_t *ipl;
19366 
19367 	ipl = connp->conn_latch;
19368 	if (ipl == NULL)
19369 		return (0);
19370 
19371 	if (ipl->ipl_out_policy == NULL)
19372 		return (0);
19373 
19374 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19375 }
19376 
19377 /*
19378  * Returns an estimate of the IPSEC headers size. This is used if
19379  * we don't want to call into IPSEC to get the exact size.
19380  */
19381 int
19382 ipsec_out_extra_length(mblk_t *ipsec_mp)
19383 {
19384 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19385 	ipsec_action_t *a;
19386 
19387 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19388 	if (!io->ipsec_out_secure)
19389 		return (0);
19390 
19391 	a = io->ipsec_out_act;
19392 
19393 	if (a == NULL) {
19394 		ASSERT(io->ipsec_out_policy != NULL);
19395 		a = io->ipsec_out_policy->ipsp_act;
19396 	}
19397 	ASSERT(a != NULL);
19398 
19399 	return (a->ipa_ovhd);
19400 }
19401 
19402 /*
19403  * Returns an estimate of the IPSEC headers size. This is used if
19404  * we don't want to call into IPSEC to get the exact size.
19405  */
19406 int
19407 ipsec_in_extra_length(mblk_t *ipsec_mp)
19408 {
19409 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19410 	ipsec_action_t *a;
19411 
19412 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19413 
19414 	a = ii->ipsec_in_action;
19415 	return (a == NULL ? 0 : a->ipa_ovhd);
19416 }
19417 
19418 /*
19419  * If there are any source route options, return the true final
19420  * destination. Otherwise, return the destination.
19421  */
19422 ipaddr_t
19423 ip_get_dst(ipha_t *ipha)
19424 {
19425 	ipoptp_t	opts;
19426 	uchar_t		*opt;
19427 	uint8_t		optval;
19428 	uint8_t		optlen;
19429 	ipaddr_t	dst;
19430 	uint32_t off;
19431 
19432 	dst = ipha->ipha_dst;
19433 
19434 	if (IS_SIMPLE_IPH(ipha))
19435 		return (dst);
19436 
19437 	for (optval = ipoptp_first(&opts, ipha);
19438 	    optval != IPOPT_EOL;
19439 	    optval = ipoptp_next(&opts)) {
19440 		opt = opts.ipoptp_cur;
19441 		optlen = opts.ipoptp_len;
19442 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19443 		switch (optval) {
19444 		case IPOPT_SSRR:
19445 		case IPOPT_LSRR:
19446 			off = opt[IPOPT_OFFSET];
19447 			/*
19448 			 * If one of the conditions is true, it means
19449 			 * end of options and dst already has the right
19450 			 * value.
19451 			 */
19452 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19453 				off = optlen - IP_ADDR_LEN;
19454 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19455 			}
19456 			return (dst);
19457 		default:
19458 			break;
19459 		}
19460 	}
19461 
19462 	return (dst);
19463 }
19464 
19465 mblk_t *
19466 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19467     conn_t *connp, boolean_t unspec_src)
19468 {
19469 	ipsec_out_t	*io;
19470 	mblk_t		*first_mp;
19471 	boolean_t policy_present;
19472 
19473 	first_mp = mp;
19474 	if (mp->b_datap->db_type == M_CTL) {
19475 		io = (ipsec_out_t *)first_mp->b_rptr;
19476 		/*
19477 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19478 		 *
19479 		 * 1) There is per-socket policy (including cached global
19480 		 *    policy).
19481 		 * 2) There is no per-socket policy, but it is
19482 		 *    a multicast packet that needs to go out
19483 		 *    on a specific interface. This is the case
19484 		 *    where (ip_wput and ip_wput_multicast) attaches
19485 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19486 		 *
19487 		 * In case (2) we check with global policy to
19488 		 * see if there is a match and set the ill_index
19489 		 * appropriately so that we can lookup the ire
19490 		 * properly in ip_wput_ipsec_out.
19491 		 */
19492 
19493 		/*
19494 		 * ipsec_out_use_global_policy is set to B_FALSE
19495 		 * in ipsec_in_to_out(). Refer to that function for
19496 		 * details.
19497 		 */
19498 		if ((io->ipsec_out_latch == NULL) &&
19499 		    (io->ipsec_out_use_global_policy)) {
19500 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19501 			    ire, connp, unspec_src));
19502 		}
19503 		if (!io->ipsec_out_secure) {
19504 			/*
19505 			 * If this is not a secure packet, drop
19506 			 * the IPSEC_OUT mp and treat it as a clear
19507 			 * packet. This happens when we are sending
19508 			 * a ICMP reply back to a clear packet. See
19509 			 * ipsec_in_to_out() for details.
19510 			 */
19511 			mp = first_mp->b_cont;
19512 			freeb(first_mp);
19513 		}
19514 		return (mp);
19515 	}
19516 	/*
19517 	 * See whether we need to attach a global policy here. We
19518 	 * don't depend on the conn (as it could be null) for deciding
19519 	 * what policy this datagram should go through because it
19520 	 * should have happened in ip_wput if there was some
19521 	 * policy. This normally happens for connections which are not
19522 	 * fully bound preventing us from caching policies in
19523 	 * ip_bind. Packets coming from the TCP listener/global queue
19524 	 * - which are non-hard_bound - could also be affected by
19525 	 * applying policy here.
19526 	 *
19527 	 * If this packet is coming from tcp global queue or listener,
19528 	 * we will be applying policy here.  This may not be *right*
19529 	 * if these packets are coming from the detached connection as
19530 	 * it could have gone in clear before. This happens only if a
19531 	 * TCP connection started when there is no policy and somebody
19532 	 * added policy before it became detached. Thus packets of the
19533 	 * detached connection could go out secure and the other end
19534 	 * would drop it because it will be expecting in clear. The
19535 	 * converse is not true i.e if somebody starts a TCP
19536 	 * connection and deletes the policy, all the packets will
19537 	 * still go out with the policy that existed before deleting
19538 	 * because ip_unbind sends up policy information which is used
19539 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19540 	 * TCP to attach a dummy IPSEC_OUT and set
19541 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19542 	 * affect performance for normal cases, we are not doing it.
19543 	 * Thus, set policy before starting any TCP connections.
19544 	 *
19545 	 * NOTE - We might apply policy even for a hard bound connection
19546 	 * - for which we cached policy in ip_bind - if somebody added
19547 	 * global policy after we inherited the policy in ip_bind.
19548 	 * This means that the packets that were going out in clear
19549 	 * previously would start going secure and hence get dropped
19550 	 * on the other side. To fix this, TCP attaches a dummy
19551 	 * ipsec_out and make sure that we don't apply global policy.
19552 	 */
19553 	if (ipha != NULL)
19554 		policy_present = ipsec_outbound_v4_policy_present;
19555 	else
19556 		policy_present = ipsec_outbound_v6_policy_present;
19557 	if (!policy_present)
19558 		return (mp);
19559 
19560 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19561 }
19562 
19563 ire_t *
19564 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19565 {
19566 	ipaddr_t addr;
19567 	ire_t *save_ire;
19568 	irb_t *irb;
19569 	ill_group_t *illgrp;
19570 	int	err;
19571 
19572 	save_ire = ire;
19573 	addr = ire->ire_addr;
19574 
19575 	ASSERT(ire->ire_type == IRE_BROADCAST);
19576 
19577 	illgrp = connp->conn_outgoing_ill->ill_group;
19578 	if (illgrp == NULL) {
19579 		*conn_outgoing_ill = conn_get_held_ill(connp,
19580 		    &connp->conn_outgoing_ill, &err);
19581 		if (err == ILL_LOOKUP_FAILED) {
19582 			ire_refrele(save_ire);
19583 			return (NULL);
19584 		}
19585 		return (save_ire);
19586 	}
19587 	/*
19588 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19589 	 * If it is part of the group, we need to send on the ire
19590 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19591 	 * to this group. This is okay as IP_BOUND_IF really means
19592 	 * any ill in the group. We depend on the fact that the
19593 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19594 	 * if such an ire exists. This is possible only if you have
19595 	 * at least one ill in the group that has not failed.
19596 	 *
19597 	 * First get to the ire that matches the address and group.
19598 	 *
19599 	 * We don't look for an ire with a matching zoneid because a given zone
19600 	 * won't always have broadcast ires on all ills in the group.
19601 	 */
19602 	irb = ire->ire_bucket;
19603 	rw_enter(&irb->irb_lock, RW_READER);
19604 	if (ire->ire_marks & IRE_MARK_NORECV) {
19605 		/*
19606 		 * If the current zone only has an ire broadcast for this
19607 		 * address marked NORECV, the ire we want is ahead in the
19608 		 * bucket, so we look it up deliberately ignoring the zoneid.
19609 		 */
19610 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19611 			if (ire->ire_addr != addr)
19612 				continue;
19613 			/* skip over deleted ires */
19614 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19615 				continue;
19616 		}
19617 	}
19618 	while (ire != NULL) {
19619 		/*
19620 		 * If a new interface is coming up, we could end up
19621 		 * seeing the loopback ire and the non-loopback ire
19622 		 * may not have been added yet. So check for ire_stq
19623 		 */
19624 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19625 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19626 			break;
19627 		}
19628 		ire = ire->ire_next;
19629 	}
19630 	if (ire != NULL && ire->ire_addr == addr &&
19631 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19632 		IRE_REFHOLD(ire);
19633 		rw_exit(&irb->irb_lock);
19634 		ire_refrele(save_ire);
19635 		*conn_outgoing_ill = ire_to_ill(ire);
19636 		/*
19637 		 * Refhold the ill to make the conn_outgoing_ill
19638 		 * independent of the ire. ip_wput_ire goes in a loop
19639 		 * and may refrele the ire. Since we have an ire at this
19640 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19641 		 */
19642 		ill_refhold(*conn_outgoing_ill);
19643 		return (ire);
19644 	}
19645 	rw_exit(&irb->irb_lock);
19646 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19647 	/*
19648 	 * If we can't find a suitable ire, return the original ire.
19649 	 */
19650 	return (save_ire);
19651 }
19652 
19653 /*
19654  * This function does the ire_refrele of the ire passed in as the
19655  * argument. As this function looks up more ires i.e broadcast ires,
19656  * it needs to REFRELE them. Currently, for simplicity we don't
19657  * differentiate the one passed in and looked up here. We always
19658  * REFRELE.
19659  * IPQoS Notes:
19660  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19661  * IPSec packets are done in ipsec_out_process.
19662  *
19663  */
19664 void
19665 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19666 {
19667 	ipha_t		*ipha;
19668 #define	rptr	((uchar_t *)ipha)
19669 	mblk_t		*mp1;
19670 	queue_t		*stq;
19671 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19672 	uint32_t	v_hlen_tos_len;
19673 	uint32_t	ttl_protocol;
19674 	ipaddr_t	src;
19675 	ipaddr_t	dst;
19676 	uint32_t	cksum;
19677 	ipaddr_t	orig_src;
19678 	ire_t		*ire1;
19679 	mblk_t		*next_mp;
19680 	uint_t		hlen;
19681 	uint16_t	*up;
19682 	uint32_t	max_frag = ire->ire_max_frag;
19683 	ill_t		*ill = ire_to_ill(ire);
19684 	int		clusterwide;
19685 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19686 	int		ipsec_len;
19687 	mblk_t		*first_mp;
19688 	ipsec_out_t	*io;
19689 	boolean_t	conn_dontroute;		/* conn value for multicast */
19690 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19691 	boolean_t	multicast_forward;	/* Should we forward ? */
19692 	boolean_t	unspec_src;
19693 	ill_t		*conn_outgoing_ill = NULL;
19694 	ill_t		*ire_ill;
19695 	ill_t		*ire1_ill;
19696 	uint32_t 	ill_index = 0;
19697 	boolean_t	multirt_send = B_FALSE;
19698 	int		err;
19699 	zoneid_t	zoneid;
19700 
19701 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19702 	    "ip_wput_ire_start: q %p", q);
19703 
19704 	multicast_forward = B_FALSE;
19705 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19706 
19707 	if (ire->ire_flags & RTF_MULTIRT) {
19708 		/*
19709 		 * Multirouting case. The bucket where ire is stored
19710 		 * probably holds other RTF_MULTIRT flagged ire
19711 		 * to the destination. In this call to ip_wput_ire,
19712 		 * we attempt to send the packet through all
19713 		 * those ires. Thus, we first ensure that ire is the
19714 		 * first RTF_MULTIRT ire in the bucket,
19715 		 * before walking the ire list.
19716 		 */
19717 		ire_t *first_ire;
19718 		irb_t *irb = ire->ire_bucket;
19719 		ASSERT(irb != NULL);
19720 
19721 		/* Make sure we do not omit any multiroute ire. */
19722 		IRB_REFHOLD(irb);
19723 		for (first_ire = irb->irb_ire;
19724 		    first_ire != NULL;
19725 		    first_ire = first_ire->ire_next) {
19726 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19727 			    (first_ire->ire_addr == ire->ire_addr) &&
19728 			    !(first_ire->ire_marks &
19729 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19730 				break;
19731 		}
19732 
19733 		if ((first_ire != NULL) && (first_ire != ire)) {
19734 			IRE_REFHOLD(first_ire);
19735 			ire_refrele(ire);
19736 			ire = first_ire;
19737 			ill = ire_to_ill(ire);
19738 		}
19739 		IRB_REFRELE(irb);
19740 	}
19741 
19742 	/*
19743 	 * conn_outgoing_ill is used only in the broadcast loop.
19744 	 * for performance we don't grab the mutexs in the fastpath
19745 	 */
19746 	if ((connp != NULL) &&
19747 	    (connp->conn_xmit_if_ill == NULL) &&
19748 	    (ire->ire_type == IRE_BROADCAST) &&
19749 	    ((connp->conn_nofailover_ill != NULL) ||
19750 	    (connp->conn_outgoing_ill != NULL))) {
19751 		/*
19752 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19753 		 * option. So, see if this endpoint is bound to a
19754 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19755 		 * that if the interface is failed, we will still send
19756 		 * the packet on the same ill which is what we want.
19757 		 */
19758 		conn_outgoing_ill = conn_get_held_ill(connp,
19759 		    &connp->conn_nofailover_ill, &err);
19760 		if (err == ILL_LOOKUP_FAILED) {
19761 			ire_refrele(ire);
19762 			freemsg(mp);
19763 			return;
19764 		}
19765 		if (conn_outgoing_ill == NULL) {
19766 			/*
19767 			 * Choose a good ill in the group to send the
19768 			 * packets on.
19769 			 */
19770 			ire = conn_set_outgoing_ill(connp, ire,
19771 			    &conn_outgoing_ill);
19772 			if (ire == NULL) {
19773 				freemsg(mp);
19774 				return;
19775 			}
19776 		}
19777 	}
19778 
19779 	if (mp->b_datap->db_type != M_CTL) {
19780 		ipha = (ipha_t *)mp->b_rptr;
19781 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19782 	} else {
19783 		io = (ipsec_out_t *)mp->b_rptr;
19784 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19785 		zoneid = io->ipsec_out_zoneid;
19786 		ASSERT(zoneid != ALL_ZONES);
19787 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19788 		dst = ipha->ipha_dst;
19789 		/*
19790 		 * For the multicast case, ipsec_out carries conn_dontroute and
19791 		 * conn_multicast_loop as conn may not be available here. We
19792 		 * need this for multicast loopback and forwarding which is done
19793 		 * later in the code.
19794 		 */
19795 		if (CLASSD(dst)) {
19796 			conn_dontroute = io->ipsec_out_dontroute;
19797 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19798 			/*
19799 			 * If conn_dontroute is not set or conn_multicast_loop
19800 			 * is set, we need to do forwarding/loopback. For
19801 			 * datagrams from ip_wput_multicast, conn_dontroute is
19802 			 * set to B_TRUE and conn_multicast_loop is set to
19803 			 * B_FALSE so that we neither do forwarding nor
19804 			 * loopback.
19805 			 */
19806 			if (!conn_dontroute || conn_multicast_loop)
19807 				multicast_forward = B_TRUE;
19808 		}
19809 	}
19810 
19811 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19812 		/*
19813 		 * When a zone sends a packet to another zone, we try to deliver
19814 		 * the packet under the same conditions as if the destination
19815 		 * was a real node on the network. To do so, we look for a
19816 		 * matching route in the forwarding table.
19817 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19818 		 * ip_newroute() does.
19819 		 */
19820 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19821 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19822 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19823 		if (src_ire != NULL &&
19824 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19825 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19826 				ipha->ipha_src = src_ire->ire_src_addr;
19827 			ire_refrele(src_ire);
19828 		} else {
19829 			ire_refrele(ire);
19830 			if (conn_outgoing_ill != NULL)
19831 				ill_refrele(conn_outgoing_ill);
19832 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19833 			if (src_ire != NULL) {
19834 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19835 					ire_refrele(src_ire);
19836 					freemsg(mp);
19837 					return;
19838 				}
19839 				ire_refrele(src_ire);
19840 			}
19841 			if (ip_hdr_complete(ipha, zoneid)) {
19842 				/* Failed */
19843 				freemsg(mp);
19844 				return;
19845 			}
19846 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19847 			return;
19848 		}
19849 	}
19850 
19851 	if (mp->b_datap->db_type == M_CTL ||
19852 	    ipsec_outbound_v4_policy_present) {
19853 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19854 		    unspec_src);
19855 		if (mp == NULL) {
19856 			ire_refrele(ire);
19857 			if (conn_outgoing_ill != NULL)
19858 				ill_refrele(conn_outgoing_ill);
19859 			return;
19860 		}
19861 	}
19862 
19863 	first_mp = mp;
19864 	ipsec_len = 0;
19865 
19866 	if (first_mp->b_datap->db_type == M_CTL) {
19867 		io = (ipsec_out_t *)first_mp->b_rptr;
19868 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19869 		mp = first_mp->b_cont;
19870 		ipsec_len = ipsec_out_extra_length(first_mp);
19871 		ASSERT(ipsec_len >= 0);
19872 		zoneid = io->ipsec_out_zoneid;
19873 		ASSERT(zoneid != ALL_ZONES);
19874 
19875 		/*
19876 		 * Drop M_CTL here if IPsec processing is not needed.
19877 		 * (Non-IPsec use of M_CTL extracted any information it
19878 		 * needed above).
19879 		 */
19880 		if (ipsec_len == 0) {
19881 			freeb(first_mp);
19882 			first_mp = mp;
19883 		}
19884 	}
19885 
19886 	/*
19887 	 * Fast path for ip_wput_ire
19888 	 */
19889 
19890 	ipha = (ipha_t *)mp->b_rptr;
19891 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19892 	dst = ipha->ipha_dst;
19893 
19894 	/*
19895 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19896 	 * if the socket is a SOCK_RAW type. The transport checksum should
19897 	 * be provided in the pre-built packet, so we don't need to compute it.
19898 	 * Also, other application set flags, like DF, should not be altered.
19899 	 * Other transport MUST pass down zero.
19900 	 */
19901 	ip_hdr_included = ipha->ipha_ident;
19902 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19903 
19904 	if (CLASSD(dst)) {
19905 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19906 		    ntohl(dst),
19907 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19908 		    ntohl(ire->ire_addr)));
19909 	}
19910 
19911 /* Macros to extract header fields from data already in registers */
19912 #ifdef	_BIG_ENDIAN
19913 #define	V_HLEN	(v_hlen_tos_len >> 24)
19914 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19915 #define	PROTO	(ttl_protocol & 0xFF)
19916 #else
19917 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19918 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19919 #define	PROTO	(ttl_protocol >> 8)
19920 #endif
19921 
19922 
19923 	orig_src = src = ipha->ipha_src;
19924 	/* (The loop back to "another" is explained down below.) */
19925 another:;
19926 	/*
19927 	 * Assign an ident value for this packet.  We assign idents on
19928 	 * a per destination basis out of the IRE.  There could be
19929 	 * other threads targeting the same destination, so we have to
19930 	 * arrange for a atomic increment.  Note that we use a 32-bit
19931 	 * atomic add because it has better performance than its
19932 	 * 16-bit sibling.
19933 	 *
19934 	 * If running in cluster mode and if the source address
19935 	 * belongs to a replicated service then vector through
19936 	 * cl_inet_ipident vector to allocate ip identifier
19937 	 * NOTE: This is a contract private interface with the
19938 	 * clustering group.
19939 	 */
19940 	clusterwide = 0;
19941 	if (cl_inet_ipident) {
19942 		ASSERT(cl_inet_isclusterwide);
19943 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19944 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19945 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19946 			    AF_INET, (uint8_t *)(uintptr_t)src,
19947 			    (uint8_t *)(uintptr_t)dst);
19948 			clusterwide = 1;
19949 		}
19950 	}
19951 	if (!clusterwide) {
19952 		ipha->ipha_ident =
19953 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19954 	}
19955 
19956 #ifndef _BIG_ENDIAN
19957 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19958 #endif
19959 
19960 	/*
19961 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19962 	 * This is needed to obey conn_unspec_src when packets go through
19963 	 * ip_newroute + arp.
19964 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19965 	 */
19966 	if (src == INADDR_ANY && !unspec_src) {
19967 		/*
19968 		 * Assign the appropriate source address from the IRE if none
19969 		 * was specified.
19970 		 */
19971 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19972 
19973 		/*
19974 		 * With IP multipathing, broadcast packets are sent on the ire
19975 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19976 		 * the group. However, this ire might not be in the same zone so
19977 		 * we can't always use its source address. We look for a
19978 		 * broadcast ire in the same group and in the right zone.
19979 		 */
19980 		if (ire->ire_type == IRE_BROADCAST &&
19981 		    ire->ire_zoneid != zoneid) {
19982 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19983 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19984 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19985 			if (src_ire != NULL) {
19986 				src = src_ire->ire_src_addr;
19987 				ire_refrele(src_ire);
19988 			} else {
19989 				ire_refrele(ire);
19990 				if (conn_outgoing_ill != NULL)
19991 					ill_refrele(conn_outgoing_ill);
19992 				freemsg(first_mp);
19993 				BUMP_MIB(&ip_mib, ipOutDiscards);
19994 				return;
19995 			}
19996 		} else {
19997 			src = ire->ire_src_addr;
19998 		}
19999 
20000 		if (connp == NULL) {
20001 			ip1dbg(("ip_wput_ire: no connp and no src "
20002 			    "address for dst 0x%x, using src 0x%x\n",
20003 			    ntohl(dst),
20004 			    ntohl(src)));
20005 		}
20006 		ipha->ipha_src = src;
20007 	}
20008 	stq = ire->ire_stq;
20009 
20010 	/*
20011 	 * We only allow ire chains for broadcasts since there will
20012 	 * be multiple IRE_CACHE entries for the same multicast
20013 	 * address (one per ipif).
20014 	 */
20015 	next_mp = NULL;
20016 
20017 	/* broadcast packet */
20018 	if (ire->ire_type == IRE_BROADCAST)
20019 		goto broadcast;
20020 
20021 	/* loopback ? */
20022 	if (stq == NULL)
20023 		goto nullstq;
20024 
20025 	/* The ill_index for outbound ILL */
20026 	ill_index = Q_TO_INDEX(stq);
20027 
20028 	BUMP_MIB(&ip_mib, ipOutRequests);
20029 	ttl_protocol = ((uint16_t *)ipha)[4];
20030 
20031 	/* pseudo checksum (do it in parts for IP header checksum) */
20032 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20033 
20034 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20035 		queue_t *dev_q = stq->q_next;
20036 
20037 		/* flow controlled */
20038 		if ((dev_q->q_next || dev_q->q_first) &&
20039 		    !canput(dev_q))
20040 			goto blocked;
20041 		if ((PROTO == IPPROTO_UDP) &&
20042 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20043 			hlen = (V_HLEN & 0xF) << 2;
20044 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20045 			if (*up != 0) {
20046 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20047 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20048 				/* Software checksum? */
20049 				if (DB_CKSUMFLAGS(mp) == 0) {
20050 					IP_STAT(ip_out_sw_cksum);
20051 					IP_STAT_UPDATE(
20052 					    ip_udp_out_sw_cksum_bytes,
20053 					    LENGTH - hlen);
20054 				}
20055 			}
20056 		}
20057 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20058 		hlen = (V_HLEN & 0xF) << 2;
20059 		if (PROTO == IPPROTO_TCP) {
20060 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20061 			/*
20062 			 * The packet header is processed once and for all, even
20063 			 * in the multirouting case. We disable hardware
20064 			 * checksum if the packet is multirouted, as it will be
20065 			 * replicated via several interfaces, and not all of
20066 			 * them may have this capability.
20067 			 */
20068 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20069 			    LENGTH, max_frag, ipsec_len, cksum);
20070 			/* Software checksum? */
20071 			if (DB_CKSUMFLAGS(mp) == 0) {
20072 				IP_STAT(ip_out_sw_cksum);
20073 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20074 				    LENGTH - hlen);
20075 			}
20076 		} else {
20077 			sctp_hdr_t	*sctph;
20078 
20079 			ASSERT(PROTO == IPPROTO_SCTP);
20080 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20081 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20082 			/*
20083 			 * Zero out the checksum field to ensure proper
20084 			 * checksum calculation.
20085 			 */
20086 			sctph->sh_chksum = 0;
20087 #ifdef	DEBUG
20088 			if (!skip_sctp_cksum)
20089 #endif
20090 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20091 		}
20092 	}
20093 
20094 	/*
20095 	 * If this is a multicast packet and originated from ip_wput
20096 	 * we need to do loopback and forwarding checks. If it comes
20097 	 * from ip_wput_multicast, we SHOULD not do this.
20098 	 */
20099 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20100 
20101 	/* checksum */
20102 	cksum += ttl_protocol;
20103 
20104 	/* fragment the packet */
20105 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20106 		goto fragmentit;
20107 	/*
20108 	 * Don't use frag_flag if packet is pre-built or source
20109 	 * routed or if multicast (since multicast packets do
20110 	 * not solicit ICMP "packet too big" messages).
20111 	 */
20112 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20113 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20114 	    !ip_source_route_included(ipha)) &&
20115 	    !CLASSD(ipha->ipha_dst))
20116 		ipha->ipha_fragment_offset_and_flags |=
20117 		    htons(ire->ire_frag_flag);
20118 
20119 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20120 		/* calculate IP header checksum */
20121 		cksum += ipha->ipha_ident;
20122 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20123 		cksum += ipha->ipha_fragment_offset_and_flags;
20124 
20125 		/* IP options present */
20126 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20127 		if (hlen)
20128 			goto checksumoptions;
20129 
20130 		/* calculate hdr checksum */
20131 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20132 		cksum = ~(cksum + (cksum >> 16));
20133 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20134 	}
20135 	if (ipsec_len != 0) {
20136 		/*
20137 		 * We will do the rest of the processing after
20138 		 * we come back from IPSEC in ip_wput_ipsec_out().
20139 		 */
20140 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20141 
20142 		io = (ipsec_out_t *)first_mp->b_rptr;
20143 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20144 				ill_phyint->phyint_ifindex;
20145 
20146 		ipsec_out_process(q, first_mp, ire, ill_index);
20147 		ire_refrele(ire);
20148 		if (conn_outgoing_ill != NULL)
20149 			ill_refrele(conn_outgoing_ill);
20150 		return;
20151 	}
20152 
20153 	/*
20154 	 * In most cases, the emission loop below is entered only
20155 	 * once. Only in the case where the ire holds the
20156 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20157 	 * flagged ires in the bucket, and send the packet
20158 	 * through all crossed RTF_MULTIRT routes.
20159 	 */
20160 	if (ire->ire_flags & RTF_MULTIRT) {
20161 		multirt_send = B_TRUE;
20162 	}
20163 	do {
20164 		if (multirt_send) {
20165 			irb_t *irb;
20166 			/*
20167 			 * We are in a multiple send case, need to get
20168 			 * the next ire and make a duplicate of the packet.
20169 			 * ire1 holds here the next ire to process in the
20170 			 * bucket. If multirouting is expected,
20171 			 * any non-RTF_MULTIRT ire that has the
20172 			 * right destination address is ignored.
20173 			 */
20174 			irb = ire->ire_bucket;
20175 			ASSERT(irb != NULL);
20176 
20177 			IRB_REFHOLD(irb);
20178 			for (ire1 = ire->ire_next;
20179 			    ire1 != NULL;
20180 			    ire1 = ire1->ire_next) {
20181 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20182 					continue;
20183 				if (ire1->ire_addr != ire->ire_addr)
20184 					continue;
20185 				if (ire1->ire_marks &
20186 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20187 					continue;
20188 
20189 				/* Got one */
20190 				IRE_REFHOLD(ire1);
20191 				break;
20192 			}
20193 			IRB_REFRELE(irb);
20194 
20195 			if (ire1 != NULL) {
20196 				next_mp = copyb(mp);
20197 				if ((next_mp == NULL) ||
20198 				    ((mp->b_cont != NULL) &&
20199 				    ((next_mp->b_cont =
20200 				    dupmsg(mp->b_cont)) == NULL))) {
20201 					freemsg(next_mp);
20202 					next_mp = NULL;
20203 					ire_refrele(ire1);
20204 					ire1 = NULL;
20205 				}
20206 			}
20207 
20208 			/* Last multiroute ire; don't loop anymore. */
20209 			if (ire1 == NULL) {
20210 				multirt_send = B_FALSE;
20211 			}
20212 		}
20213 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20214 		if (mp == NULL) {
20215 			BUMP_MIB(&ip_mib, ipOutDiscards);
20216 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20217 			    "during IPPF processing\n"));
20218 			ire_refrele(ire);
20219 			if (next_mp != NULL) {
20220 				freemsg(next_mp);
20221 				ire_refrele(ire1);
20222 			}
20223 			if (conn_outgoing_ill != NULL)
20224 				ill_refrele(conn_outgoing_ill);
20225 			return;
20226 		}
20227 		UPDATE_OB_PKT_COUNT(ire);
20228 		ire->ire_last_used_time = lbolt;
20229 
20230 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20231 		    "ip_wput_ire_end: q %p (%S)",
20232 		    q, "last copy out");
20233 		putnext(stq, mp);
20234 		IRE_REFRELE(ire);
20235 
20236 		if (multirt_send) {
20237 			ASSERT(ire1);
20238 			/*
20239 			 * Proceed with the next RTF_MULTIRT ire,
20240 			 * Also set up the send-to queue accordingly.
20241 			 */
20242 			ire = ire1;
20243 			ire1 = NULL;
20244 			stq = ire->ire_stq;
20245 			mp = next_mp;
20246 			next_mp = NULL;
20247 			ipha = (ipha_t *)mp->b_rptr;
20248 			ill_index = Q_TO_INDEX(stq);
20249 		}
20250 	} while (multirt_send);
20251 	if (conn_outgoing_ill != NULL)
20252 		ill_refrele(conn_outgoing_ill);
20253 	return;
20254 
20255 	/*
20256 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20257 	 */
20258 broadcast:
20259 	{
20260 		/*
20261 		 * Avoid broadcast storms by setting the ttl to 1
20262 		 * for broadcasts. This parameter can be set
20263 		 * via ndd, so make sure that for the SO_DONTROUTE
20264 		 * case that ipha_ttl is always set to 1.
20265 		 * In the event that we are replying to incoming
20266 		 * ICMP packets, conn could be NULL.
20267 		 */
20268 		if ((connp != NULL) && connp->conn_dontroute)
20269 			ipha->ipha_ttl = 1;
20270 		else
20271 			ipha->ipha_ttl = ip_broadcast_ttl;
20272 
20273 		/*
20274 		 * Note that we are not doing a IRB_REFHOLD here.
20275 		 * Actually we don't care if the list changes i.e
20276 		 * if somebody deletes an IRE from the list while
20277 		 * we drop the lock, the next time we come around
20278 		 * ire_next will be NULL and hence we won't send
20279 		 * out multiple copies which is fine.
20280 		 */
20281 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20282 		ire1 = ire->ire_next;
20283 		if (conn_outgoing_ill != NULL) {
20284 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20285 				ASSERT(ire1 == ire->ire_next);
20286 				if (ire1 != NULL && ire1->ire_addr == dst) {
20287 					ire_refrele(ire);
20288 					ire = ire1;
20289 					IRE_REFHOLD(ire);
20290 					ire1 = ire->ire_next;
20291 					continue;
20292 				}
20293 				rw_exit(&ire->ire_bucket->irb_lock);
20294 				/* Did not find a matching ill */
20295 				ip1dbg(("ip_wput_ire: broadcast with no "
20296 				    "matching IP_BOUND_IF ill %s\n",
20297 				    conn_outgoing_ill->ill_name));
20298 				freemsg(first_mp);
20299 				if (ire != NULL)
20300 					ire_refrele(ire);
20301 				ill_refrele(conn_outgoing_ill);
20302 				return;
20303 			}
20304 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20305 			/*
20306 			 * If the next IRE has the same address and is not one
20307 			 * of the two copies that we need to send, try to see
20308 			 * whether this copy should be sent at all. This
20309 			 * assumes that we insert loopbacks first and then
20310 			 * non-loopbacks. This is acheived by inserting the
20311 			 * loopback always before non-loopback.
20312 			 * This is used to send a single copy of a broadcast
20313 			 * packet out all physical interfaces that have an
20314 			 * matching IRE_BROADCAST while also looping
20315 			 * back one copy (to ip_wput_local) for each
20316 			 * matching physical interface. However, we avoid
20317 			 * sending packets out different logical that match by
20318 			 * having ipif_up/ipif_down supress duplicate
20319 			 * IRE_BROADCASTS.
20320 			 *
20321 			 * This feature is currently used to get broadcasts
20322 			 * sent to multiple interfaces, when the broadcast
20323 			 * address being used applies to multiple interfaces.
20324 			 * For example, a whole net broadcast will be
20325 			 * replicated on every connected subnet of
20326 			 * the target net.
20327 			 *
20328 			 * Each zone has its own set of IRE_BROADCASTs, so that
20329 			 * we're able to distribute inbound packets to multiple
20330 			 * zones who share a broadcast address. We avoid looping
20331 			 * back outbound packets in different zones but on the
20332 			 * same ill, as the application would see duplicates.
20333 			 *
20334 			 * If the interfaces are part of the same group,
20335 			 * we would want to send only one copy out for
20336 			 * whole group.
20337 			 *
20338 			 * This logic assumes that ire_add_v4() groups the
20339 			 * IRE_BROADCAST entries so that those with the same
20340 			 * ire_addr and ill_group are kept together.
20341 			 */
20342 			ire_ill = ire->ire_ipif->ipif_ill;
20343 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20344 				if (ire_ill->ill_group != NULL &&
20345 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20346 					/*
20347 					 * If the current zone only has an ire
20348 					 * broadcast for this address marked
20349 					 * NORECV, the ire we want is ahead in
20350 					 * the bucket, so we look it up
20351 					 * deliberately ignoring the zoneid.
20352 					 */
20353 					for (ire1 = ire->ire_bucket->irb_ire;
20354 					    ire1 != NULL;
20355 					    ire1 = ire1->ire_next) {
20356 						ire1_ill =
20357 						    ire1->ire_ipif->ipif_ill;
20358 						if (ire1->ire_addr != dst)
20359 							continue;
20360 						/* skip over the current ire */
20361 						if (ire1 == ire)
20362 							continue;
20363 						/* skip over deleted ires */
20364 						if (ire1->ire_marks &
20365 						    IRE_MARK_CONDEMNED)
20366 							continue;
20367 						/*
20368 						 * non-loopback ire in our
20369 						 * group: use it for the next
20370 						 * pass in the loop
20371 						 */
20372 						if (ire1->ire_stq != NULL &&
20373 						    ire1_ill->ill_group ==
20374 						    ire_ill->ill_group)
20375 							break;
20376 					}
20377 				}
20378 			} else {
20379 				while (ire1 != NULL && ire1->ire_addr == dst) {
20380 					ire1_ill = ire1->ire_ipif->ipif_ill;
20381 					/*
20382 					 * We can have two broadcast ires on the
20383 					 * same ill in different zones; here
20384 					 * we'll send a copy of the packet on
20385 					 * each ill and the fanout code will
20386 					 * call conn_wantpacket() to check that
20387 					 * the zone has the broadcast address
20388 					 * configured on the ill. If the two
20389 					 * ires are in the same group we only
20390 					 * send one copy up.
20391 					 */
20392 					if (ire1_ill != ire_ill &&
20393 					    (ire1_ill->ill_group == NULL ||
20394 					    ire_ill->ill_group == NULL ||
20395 					    ire1_ill->ill_group !=
20396 					    ire_ill->ill_group)) {
20397 						break;
20398 					}
20399 					ire1 = ire1->ire_next;
20400 				}
20401 			}
20402 		}
20403 		ASSERT(multirt_send == B_FALSE);
20404 		if (ire1 != NULL && ire1->ire_addr == dst) {
20405 			if ((ire->ire_flags & RTF_MULTIRT) &&
20406 			    (ire1->ire_flags & RTF_MULTIRT)) {
20407 				/*
20408 				 * We are in the multirouting case.
20409 				 * The message must be sent at least
20410 				 * on both ires. These ires have been
20411 				 * inserted AFTER the standard ones
20412 				 * in ip_rt_add(). There are thus no
20413 				 * other ire entries for the destination
20414 				 * address in the rest of the bucket
20415 				 * that do not have the RTF_MULTIRT
20416 				 * flag. We don't process a copy
20417 				 * of the message here. This will be
20418 				 * done in the final sending loop.
20419 				 */
20420 				multirt_send = B_TRUE;
20421 			} else {
20422 				next_mp = ip_copymsg(first_mp);
20423 				if (next_mp != NULL)
20424 					IRE_REFHOLD(ire1);
20425 			}
20426 		}
20427 		rw_exit(&ire->ire_bucket->irb_lock);
20428 	}
20429 
20430 	if (stq) {
20431 		/*
20432 		 * A non-NULL send-to queue means this packet is going
20433 		 * out of this machine.
20434 		 */
20435 
20436 		BUMP_MIB(&ip_mib, ipOutRequests);
20437 		ttl_protocol = ((uint16_t *)ipha)[4];
20438 		/*
20439 		 * We accumulate the pseudo header checksum in cksum.
20440 		 * This is pretty hairy code, so watch close.  One
20441 		 * thing to keep in mind is that UDP and TCP have
20442 		 * stored their respective datagram lengths in their
20443 		 * checksum fields.  This lines things up real nice.
20444 		 */
20445 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20446 		    (src >> 16) + (src & 0xFFFF);
20447 		/*
20448 		 * We assume the udp checksum field contains the
20449 		 * length, so to compute the pseudo header checksum,
20450 		 * all we need is the protocol number and src/dst.
20451 		 */
20452 		/* Provide the checksums for UDP and TCP. */
20453 		if ((PROTO == IPPROTO_TCP) &&
20454 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20455 			/* hlen gets the number of uchar_ts in the IP header */
20456 			hlen = (V_HLEN & 0xF) << 2;
20457 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20458 			IP_STAT(ip_out_sw_cksum);
20459 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20460 			    LENGTH - hlen);
20461 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20462 			if (*up == 0)
20463 				*up = 0xFFFF;
20464 		} else if (PROTO == IPPROTO_SCTP &&
20465 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20466 			sctp_hdr_t	*sctph;
20467 
20468 			hlen = (V_HLEN & 0xF) << 2;
20469 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20470 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20471 			sctph->sh_chksum = 0;
20472 #ifdef	DEBUG
20473 			if (!skip_sctp_cksum)
20474 #endif
20475 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20476 		} else {
20477 			queue_t *dev_q = stq->q_next;
20478 
20479 			if ((dev_q->q_next || dev_q->q_first) &&
20480 			    !canput(dev_q)) {
20481 			    blocked:
20482 				ipha->ipha_ident = ip_hdr_included;
20483 				/*
20484 				 * If we don't have a conn to apply
20485 				 * backpressure, free the message.
20486 				 * In the ire_send path, we don't know
20487 				 * the position to requeue the packet. Rather
20488 				 * than reorder packets, we just drop this
20489 				 * packet.
20490 				 */
20491 				if (ip_output_queue && connp != NULL &&
20492 				    caller != IRE_SEND) {
20493 					if (caller == IP_WSRV) {
20494 						connp->conn_did_putbq = 1;
20495 						(void) putbq(connp->conn_wq,
20496 						    first_mp);
20497 						conn_drain_insert(connp);
20498 						/*
20499 						 * This is the service thread,
20500 						 * and the queue is already
20501 						 * noenabled. The check for
20502 						 * canput and the putbq is not
20503 						 * atomic. So we need to check
20504 						 * again.
20505 						 */
20506 						if (canput(stq->q_next))
20507 							connp->conn_did_putbq
20508 							    = 0;
20509 						IP_STAT(ip_conn_flputbq);
20510 					} else {
20511 						/*
20512 						 * We are not the service proc.
20513 						 * ip_wsrv will be scheduled or
20514 						 * is already running.
20515 						 */
20516 						(void) putq(connp->conn_wq,
20517 						    first_mp);
20518 					}
20519 				} else {
20520 					BUMP_MIB(&ip_mib, ipOutDiscards);
20521 					freemsg(first_mp);
20522 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20523 					    "ip_wput_ire_end: q %p (%S)",
20524 					    q, "discard");
20525 				}
20526 				ire_refrele(ire);
20527 				if (next_mp) {
20528 					ire_refrele(ire1);
20529 					freemsg(next_mp);
20530 				}
20531 				if (conn_outgoing_ill != NULL)
20532 					ill_refrele(conn_outgoing_ill);
20533 				return;
20534 			}
20535 			if ((PROTO == IPPROTO_UDP) &&
20536 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20537 				/*
20538 				 * hlen gets the number of uchar_ts in the
20539 				 * IP header
20540 				 */
20541 				hlen = (V_HLEN & 0xF) << 2;
20542 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20543 				max_frag = ire->ire_max_frag;
20544 				if (*up != 0) {
20545 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
20546 					    up, PROTO, hlen, LENGTH, max_frag,
20547 					    ipsec_len, cksum);
20548 					/* Software checksum? */
20549 					if (DB_CKSUMFLAGS(mp) == 0) {
20550 						IP_STAT(ip_out_sw_cksum);
20551 						IP_STAT_UPDATE(
20552 						    ip_udp_out_sw_cksum_bytes,
20553 						    LENGTH - hlen);
20554 					}
20555 				}
20556 			}
20557 		}
20558 		/*
20559 		 * Need to do this even when fragmenting. The local
20560 		 * loopback can be done without computing checksums
20561 		 * but forwarding out other interface must be done
20562 		 * after the IP checksum (and ULP checksums) have been
20563 		 * computed.
20564 		 *
20565 		 * NOTE : multicast_forward is set only if this packet
20566 		 * originated from ip_wput. For packets originating from
20567 		 * ip_wput_multicast, it is not set.
20568 		 */
20569 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20570 		    multi_loopback:
20571 			ip2dbg(("ip_wput: multicast, loop %d\n",
20572 			    conn_multicast_loop));
20573 
20574 			/*  Forget header checksum offload */
20575 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
20576 
20577 			/*
20578 			 * Local loopback of multicasts?  Check the
20579 			 * ill.
20580 			 *
20581 			 * Note that the loopback function will not come
20582 			 * in through ip_rput - it will only do the
20583 			 * client fanout thus we need to do an mforward
20584 			 * as well.  The is different from the BSD
20585 			 * logic.
20586 			 */
20587 			if (ill != NULL) {
20588 				ilm_t	*ilm;
20589 
20590 				ILM_WALKER_HOLD(ill);
20591 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20592 				    ALL_ZONES);
20593 				ILM_WALKER_RELE(ill);
20594 				if (ilm != NULL) {
20595 					/*
20596 					 * Pass along the virtual output q.
20597 					 * ip_wput_local() will distribute the
20598 					 * packet to all the matching zones,
20599 					 * except the sending zone when
20600 					 * IP_MULTICAST_LOOP is false.
20601 					 */
20602 					ip_multicast_loopback(q, ill, first_mp,
20603 					    conn_multicast_loop ? 0 :
20604 					    IP_FF_NO_MCAST_LOOP, zoneid);
20605 				}
20606 			}
20607 			if (ipha->ipha_ttl == 0) {
20608 				/*
20609 				 * 0 => only to this host i.e. we are
20610 				 * done. We are also done if this was the
20611 				 * loopback interface since it is sufficient
20612 				 * to loopback one copy of a multicast packet.
20613 				 */
20614 				freemsg(first_mp);
20615 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20616 				    "ip_wput_ire_end: q %p (%S)",
20617 				    q, "loopback");
20618 				ire_refrele(ire);
20619 				if (conn_outgoing_ill != NULL)
20620 					ill_refrele(conn_outgoing_ill);
20621 				return;
20622 			}
20623 			/*
20624 			 * ILLF_MULTICAST is checked in ip_newroute
20625 			 * i.e. we don't need to check it here since
20626 			 * all IRE_CACHEs come from ip_newroute.
20627 			 * For multicast traffic, SO_DONTROUTE is interpreted
20628 			 * to mean only send the packet out the interface
20629 			 * (optionally specified with IP_MULTICAST_IF)
20630 			 * and do not forward it out additional interfaces.
20631 			 * RSVP and the rsvp daemon is an example of a
20632 			 * protocol and user level process that
20633 			 * handles it's own routing. Hence, it uses the
20634 			 * SO_DONTROUTE option to accomplish this.
20635 			 */
20636 
20637 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20638 				/* Unconditionally redo the checksum */
20639 				ipha->ipha_hdr_checksum = 0;
20640 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20641 
20642 				/*
20643 				 * If this needs to go out secure, we need
20644 				 * to wait till we finish the IPSEC
20645 				 * processing.
20646 				 */
20647 				if (ipsec_len == 0 &&
20648 				    ip_mforward(ill, ipha, mp)) {
20649 					freemsg(first_mp);
20650 					ip1dbg(("ip_wput: mforward failed\n"));
20651 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20652 					    "ip_wput_ire_end: q %p (%S)",
20653 					    q, "mforward failed");
20654 					ire_refrele(ire);
20655 					if (conn_outgoing_ill != NULL)
20656 						ill_refrele(conn_outgoing_ill);
20657 					return;
20658 				}
20659 			}
20660 		}
20661 		max_frag = ire->ire_max_frag;
20662 		cksum += ttl_protocol;
20663 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
20664 			/* No fragmentation required for this one. */
20665 			/*
20666 			 * Don't use frag_flag if packet is pre-built or source
20667 			 * routed or if multicast (since multicast packets do
20668 			 * not solicit ICMP "packet too big" messages).
20669 			 */
20670 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20671 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20672 			    !ip_source_route_included(ipha)) &&
20673 			    !CLASSD(ipha->ipha_dst))
20674 				ipha->ipha_fragment_offset_and_flags |=
20675 				    htons(ire->ire_frag_flag);
20676 
20677 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20678 				/* Complete the IP header checksum. */
20679 				cksum += ipha->ipha_ident;
20680 				cksum += (v_hlen_tos_len >> 16)+
20681 				    (v_hlen_tos_len & 0xFFFF);
20682 				cksum += ipha->ipha_fragment_offset_and_flags;
20683 				hlen = (V_HLEN & 0xF) -
20684 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20685 				if (hlen) {
20686 				    checksumoptions:
20687 					/*
20688 					 * Account for the IP Options in the IP
20689 					 * header checksum.
20690 					 */
20691 					up = (uint16_t *)(rptr+
20692 					    IP_SIMPLE_HDR_LENGTH);
20693 					do {
20694 						cksum += up[0];
20695 						cksum += up[1];
20696 						up += 2;
20697 					} while (--hlen);
20698 				}
20699 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20700 				cksum = ~(cksum + (cksum >> 16));
20701 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
20702 			}
20703 			if (ipsec_len != 0) {
20704 				ipsec_out_process(q, first_mp, ire, ill_index);
20705 				if (!next_mp) {
20706 					ire_refrele(ire);
20707 					if (conn_outgoing_ill != NULL)
20708 						ill_refrele(conn_outgoing_ill);
20709 					return;
20710 				}
20711 				goto next;
20712 			}
20713 
20714 			/*
20715 			 * multirt_send has already been handled
20716 			 * for broadcast, but not yet for multicast
20717 			 * or IP options.
20718 			 */
20719 			if (next_mp == NULL) {
20720 				if (ire->ire_flags & RTF_MULTIRT) {
20721 					multirt_send = B_TRUE;
20722 				}
20723 			}
20724 
20725 			/*
20726 			 * In most cases, the emission loop below is
20727 			 * entered only once. Only in the case where
20728 			 * the ire holds the RTF_MULTIRT flag, do we loop
20729 			 * to process all RTF_MULTIRT ires in the bucket,
20730 			 * and send the packet through all crossed
20731 			 * RTF_MULTIRT routes.
20732 			 */
20733 			do {
20734 				if (multirt_send) {
20735 					irb_t *irb;
20736 
20737 					irb = ire->ire_bucket;
20738 					ASSERT(irb != NULL);
20739 					/*
20740 					 * We are in a multiple send case,
20741 					 * need to get the next IRE and make
20742 					 * a duplicate of the packet.
20743 					 */
20744 					IRB_REFHOLD(irb);
20745 					for (ire1 = ire->ire_next;
20746 					    ire1 != NULL;
20747 					    ire1 = ire1->ire_next) {
20748 						if (!(ire1->ire_flags &
20749 						    RTF_MULTIRT))
20750 							continue;
20751 						if (ire1->ire_addr !=
20752 						    ire->ire_addr)
20753 							continue;
20754 						if (ire1->ire_marks &
20755 						    (IRE_MARK_CONDEMNED|
20756 							IRE_MARK_HIDDEN))
20757 							continue;
20758 
20759 						/* Got one */
20760 						IRE_REFHOLD(ire1);
20761 						break;
20762 					}
20763 					IRB_REFRELE(irb);
20764 
20765 					if (ire1 != NULL) {
20766 						next_mp = copyb(mp);
20767 						if ((next_mp == NULL) ||
20768 						    ((mp->b_cont != NULL) &&
20769 						    ((next_mp->b_cont =
20770 						    dupmsg(mp->b_cont))
20771 						    == NULL))) {
20772 							freemsg(next_mp);
20773 							next_mp = NULL;
20774 							ire_refrele(ire1);
20775 							ire1 = NULL;
20776 						}
20777 					}
20778 
20779 					/*
20780 					 * Last multiroute ire; don't loop
20781 					 * anymore. The emission is over
20782 					 * and next_mp is NULL.
20783 					 */
20784 					if (ire1 == NULL) {
20785 						multirt_send = B_FALSE;
20786 					}
20787 				}
20788 
20789 			noprepend:
20790 				ASSERT(ipsec_len == 0);
20791 				mp1 = ip_wput_attach_llhdr(mp, ire,
20792 				    IPP_LOCAL_OUT, ill_index);
20793 				if (mp1 == NULL) {
20794 					BUMP_MIB(&ip_mib, ipOutDiscards);
20795 					if (next_mp) {
20796 						freemsg(next_mp);
20797 						ire_refrele(ire1);
20798 					}
20799 					ire_refrele(ire);
20800 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20801 					    "ip_wput_ire_end: q %p (%S)",
20802 					    q, "discard MDATA");
20803 					if (conn_outgoing_ill != NULL)
20804 						ill_refrele(conn_outgoing_ill);
20805 					return;
20806 				}
20807 				UPDATE_OB_PKT_COUNT(ire);
20808 				ire->ire_last_used_time = lbolt;
20809 
20810 				if (multirt_send) {
20811 					/*
20812 					 * We are in a multiple send case,
20813 					 * need to re-enter the sending loop
20814 					 * using the next ire.
20815 					 */
20816 					putnext(stq, mp1);
20817 					ire_refrele(ire);
20818 					ire = ire1;
20819 					stq = ire->ire_stq;
20820 					mp = next_mp;
20821 					next_mp = NULL;
20822 					ipha = (ipha_t *)mp->b_rptr;
20823 					ill_index = Q_TO_INDEX(stq);
20824 				}
20825 			} while (multirt_send);
20826 
20827 			if (!next_mp) {
20828 				/*
20829 				 * Last copy going out (the ultra-common
20830 				 * case).  Note that we intentionally replicate
20831 				 * the putnext rather than calling it before
20832 				 * the next_mp check in hopes of a little
20833 				 * tail-call action out of the compiler.
20834 				 */
20835 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20836 				    "ip_wput_ire_end: q %p (%S)",
20837 				    q, "last copy out(1)");
20838 				putnext(stq, mp1);
20839 				ire_refrele(ire);
20840 				if (conn_outgoing_ill != NULL)
20841 					ill_refrele(conn_outgoing_ill);
20842 				return;
20843 			}
20844 			/* More copies going out below. */
20845 			putnext(stq, mp1);
20846 		} else {
20847 			int offset;
20848 		    fragmentit:
20849 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20850 			/*
20851 			 * If this would generate a icmp_frag_needed message,
20852 			 * we need to handle it before we do the IPSEC
20853 			 * processing. Otherwise, we need to strip the IPSEC
20854 			 * headers before we send up the message to the ULPs
20855 			 * which becomes messy and difficult.
20856 			 */
20857 			if (ipsec_len != 0) {
20858 				if ((max_frag < (unsigned int)(LENGTH +
20859 				    ipsec_len)) && (offset & IPH_DF)) {
20860 
20861 					BUMP_MIB(&ip_mib, ipFragFails);
20862 					ipha->ipha_hdr_checksum = 0;
20863 					ipha->ipha_hdr_checksum =
20864 					    (uint16_t)ip_csum_hdr(ipha);
20865 					icmp_frag_needed(ire->ire_stq, first_mp,
20866 					    max_frag);
20867 					if (!next_mp) {
20868 						ire_refrele(ire);
20869 						if (conn_outgoing_ill != NULL) {
20870 							ill_refrele(
20871 							    conn_outgoing_ill);
20872 						}
20873 						return;
20874 					}
20875 				} else {
20876 					/*
20877 					 * This won't cause a icmp_frag_needed
20878 					 * message. to be gnerated. Send it on
20879 					 * the wire. Note that this could still
20880 					 * cause fragmentation and all we
20881 					 * do is the generation of the message
20882 					 * to the ULP if needed before IPSEC.
20883 					 */
20884 					if (!next_mp) {
20885 						ipsec_out_process(q, first_mp,
20886 						    ire, ill_index);
20887 						TRACE_2(TR_FAC_IP,
20888 						    TR_IP_WPUT_IRE_END,
20889 						    "ip_wput_ire_end: q %p "
20890 						    "(%S)", q,
20891 						    "last ipsec_out_process");
20892 						ire_refrele(ire);
20893 						if (conn_outgoing_ill != NULL) {
20894 							ill_refrele(
20895 							    conn_outgoing_ill);
20896 						}
20897 						return;
20898 					}
20899 					ipsec_out_process(q, first_mp,
20900 					    ire, ill_index);
20901 				}
20902 			} else {
20903 				/* Initiate IPPF processing */
20904 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20905 					ip_process(IPP_LOCAL_OUT, &mp,
20906 					    ill_index);
20907 					if (mp == NULL) {
20908 						BUMP_MIB(&ip_mib,
20909 						    ipOutDiscards);
20910 						if (next_mp != NULL) {
20911 							freemsg(next_mp);
20912 							ire_refrele(ire1);
20913 						}
20914 						ire_refrele(ire);
20915 						TRACE_2(TR_FAC_IP,
20916 						    TR_IP_WPUT_IRE_END,
20917 						    "ip_wput_ire: q %p (%S)",
20918 						    q, "discard MDATA");
20919 						if (conn_outgoing_ill != NULL) {
20920 							ill_refrele(
20921 							    conn_outgoing_ill);
20922 						}
20923 						return;
20924 					}
20925 				}
20926 				if (!next_mp) {
20927 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20928 					    "ip_wput_ire_end: q %p (%S)",
20929 					    q, "last fragmentation");
20930 					ip_wput_ire_fragmentit(mp, ire);
20931 					ire_refrele(ire);
20932 					if (conn_outgoing_ill != NULL)
20933 						ill_refrele(conn_outgoing_ill);
20934 					return;
20935 				}
20936 				ip_wput_ire_fragmentit(mp, ire);
20937 			}
20938 		}
20939 	} else {
20940 	    nullstq:
20941 		/* A NULL stq means the destination address is local. */
20942 		UPDATE_OB_PKT_COUNT(ire);
20943 		ire->ire_last_used_time = lbolt;
20944 		ASSERT(ire->ire_ipif != NULL);
20945 		if (!next_mp) {
20946 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20947 			    "ip_wput_ire_end: q %p (%S)",
20948 			    q, "local address");
20949 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20950 			    first_mp, ire, 0, ire->ire_zoneid);
20951 			ire_refrele(ire);
20952 			if (conn_outgoing_ill != NULL)
20953 				ill_refrele(conn_outgoing_ill);
20954 			return;
20955 		}
20956 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20957 		    ire, 0, ire->ire_zoneid);
20958 	}
20959 next:
20960 	/*
20961 	 * More copies going out to additional interfaces.
20962 	 * ire1 has already been held. We don't need the
20963 	 * "ire" anymore.
20964 	 */
20965 	ire_refrele(ire);
20966 	ire = ire1;
20967 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20968 	mp = next_mp;
20969 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20970 	ill = ire_to_ill(ire);
20971 	first_mp = mp;
20972 	if (ipsec_len != 0) {
20973 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20974 		mp = mp->b_cont;
20975 	}
20976 	dst = ire->ire_addr;
20977 	ipha = (ipha_t *)mp->b_rptr;
20978 	/*
20979 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20980 	 * Restore ipha_ident "no checksum" flag.
20981 	 */
20982 	src = orig_src;
20983 	ipha->ipha_ident = ip_hdr_included;
20984 	goto another;
20985 
20986 #undef	rptr
20987 #undef	Q_TO_INDEX
20988 }
20989 
20990 /*
20991  * Routine to allocate a message that is used to notify the ULP about MDT.
20992  * The caller may provide a pointer to the link-layer MDT capabilities,
20993  * or NULL if MDT is to be disabled on the stream.
20994  */
20995 mblk_t *
20996 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20997 {
20998 	mblk_t *mp;
20999 	ip_mdt_info_t *mdti;
21000 	ill_mdt_capab_t *idst;
21001 
21002 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21003 		DB_TYPE(mp) = M_CTL;
21004 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21005 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21006 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21007 		idst = &(mdti->mdt_capab);
21008 
21009 		/*
21010 		 * If the caller provides us with the capability, copy
21011 		 * it over into our notification message; otherwise
21012 		 * we zero out the capability portion.
21013 		 */
21014 		if (isrc != NULL)
21015 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21016 		else
21017 			bzero((caddr_t)idst, sizeof (*idst));
21018 	}
21019 	return (mp);
21020 }
21021 
21022 /*
21023  * Routine which determines whether MDT can be enabled on the destination
21024  * IRE and IPC combination, and if so, allocates and returns the MDT
21025  * notification mblk that may be used by ULP.  We also check if we need to
21026  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21027  * MDT usage in the past have been lifted.  This gets called during IP
21028  * and ULP binding.
21029  */
21030 mblk_t *
21031 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21032     ill_mdt_capab_t *mdt_cap)
21033 {
21034 	mblk_t *mp;
21035 	boolean_t rc = B_FALSE;
21036 
21037 	ASSERT(dst_ire != NULL);
21038 	ASSERT(connp != NULL);
21039 	ASSERT(mdt_cap != NULL);
21040 
21041 	/*
21042 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21043 	 * Multidata, which is handled in tcp_multisend().  This
21044 	 * is the reason why we do all these checks here, to ensure
21045 	 * that we don't enable Multidata for the cases which we
21046 	 * can't handle at the moment.
21047 	 */
21048 	do {
21049 		/* Only do TCP at the moment */
21050 		if (connp->conn_ulp != IPPROTO_TCP)
21051 			break;
21052 
21053 		/*
21054 		 * IPSEC outbound policy present?  Note that we get here
21055 		 * after calling ipsec_conn_cache_policy() where the global
21056 		 * policy checking is performed.  conn_latch will be
21057 		 * non-NULL as long as there's a policy defined,
21058 		 * i.e. conn_out_enforce_policy may be NULL in such case
21059 		 * when the connection is non-secure, and hence we check
21060 		 * further if the latch refers to an outbound policy.
21061 		 */
21062 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21063 			break;
21064 
21065 		/* CGTP (multiroute) is enabled? */
21066 		if (dst_ire->ire_flags & RTF_MULTIRT)
21067 			break;
21068 
21069 		/* Outbound IPQoS enabled? */
21070 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21071 			/*
21072 			 * In this case, we disable MDT for this and all
21073 			 * future connections going over the interface.
21074 			 */
21075 			mdt_cap->ill_mdt_on = 0;
21076 			break;
21077 		}
21078 
21079 		/* socket option(s) present? */
21080 		if (!CONN_IS_MD_FASTPATH(connp))
21081 			break;
21082 
21083 		rc = B_TRUE;
21084 	/* CONSTCOND */
21085 	} while (0);
21086 
21087 	/* Remember the result */
21088 	connp->conn_mdt_ok = rc;
21089 
21090 	if (!rc)
21091 		return (NULL);
21092 	else if (!mdt_cap->ill_mdt_on) {
21093 		/*
21094 		 * If MDT has been previously turned off in the past, and we
21095 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21096 		 * then enable it for this interface.
21097 		 */
21098 		mdt_cap->ill_mdt_on = 1;
21099 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21100 		    "interface %s\n", ill_name));
21101 	}
21102 
21103 	/* Allocate the MDT info mblk */
21104 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21105 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21106 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21107 		return (NULL);
21108 	}
21109 	return (mp);
21110 }
21111 
21112 /*
21113  * Create destination address attribute, and fill it with the physical
21114  * destination address and SAP taken from the template DL_UNITDATA_REQ
21115  * message block.
21116  */
21117 boolean_t
21118 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21119 {
21120 	dl_unitdata_req_t *dlurp;
21121 	pattr_t *pa;
21122 	pattrinfo_t pa_info;
21123 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21124 	uint_t das_len, das_off;
21125 
21126 	ASSERT(dlmp != NULL);
21127 
21128 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21129 	das_len = dlurp->dl_dest_addr_length;
21130 	das_off = dlurp->dl_dest_addr_offset;
21131 
21132 	pa_info.type = PATTR_DSTADDRSAP;
21133 	pa_info.len = sizeof (**das) + das_len - 1;
21134 
21135 	/* create and associate the attribute */
21136 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21137 	if (pa != NULL) {
21138 		ASSERT(*das != NULL);
21139 		(*das)->addr_is_group = 0;
21140 		(*das)->addr_len = (uint8_t)das_len;
21141 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21142 	}
21143 
21144 	return (pa != NULL);
21145 }
21146 
21147 /*
21148  * Create hardware checksum attribute and fill it with the values passed.
21149  */
21150 boolean_t
21151 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21152     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21153 {
21154 	pattr_t *pa;
21155 	pattrinfo_t pa_info;
21156 
21157 	ASSERT(mmd != NULL);
21158 
21159 	pa_info.type = PATTR_HCKSUM;
21160 	pa_info.len = sizeof (pattr_hcksum_t);
21161 
21162 	/* create and associate the attribute */
21163 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21164 	if (pa != NULL) {
21165 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21166 
21167 		hck->hcksum_start_offset = start_offset;
21168 		hck->hcksum_stuff_offset = stuff_offset;
21169 		hck->hcksum_end_offset = end_offset;
21170 		hck->hcksum_flags = flags;
21171 	}
21172 	return (pa != NULL);
21173 }
21174 
21175 /*
21176  * Create zerocopy attribute and fill it with the specified flags
21177  */
21178 boolean_t
21179 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21180 {
21181 	pattr_t *pa;
21182 	pattrinfo_t pa_info;
21183 
21184 	ASSERT(mmd != NULL);
21185 	pa_info.type = PATTR_ZCOPY;
21186 	pa_info.len = sizeof (pattr_zcopy_t);
21187 
21188 	/* create and associate the attribute */
21189 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21190 	if (pa != NULL) {
21191 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21192 
21193 		zcopy->zcopy_flags = flags;
21194 	}
21195 	return (pa != NULL);
21196 }
21197 
21198 /*
21199  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21200  * block chain. We could rewrite to handle arbitrary message block chains but
21201  * that would make the code complicated and slow. Right now there three
21202  * restrictions:
21203  *
21204  *   1. The first message block must contain the complete IP header and
21205  *	at least 1 byte of payload data.
21206  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
21207  *	so that we can use a single Multidata message.
21208  *   3. No frag must be distributed over two or more message blocks so
21209  *	that we don't need more than two packet descriptors per frag.
21210  *
21211  * The above restrictions allow us to support userland applications (which
21212  * will send down a single message block) and NFS over UDP (which will
21213  * send down a chain of at most three message blocks).
21214  *
21215  * We also don't use MDT for payloads with less than or equal to
21216  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
21217  */
21218 boolean_t
21219 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
21220 {
21221 	int	blocks;
21222 	ssize_t	total, missing, size;
21223 
21224 	ASSERT(mp != NULL);
21225 	ASSERT(hdr_len > 0);
21226 
21227 	size = MBLKL(mp) - hdr_len;
21228 	if (size <= 0)
21229 		return (B_FALSE);
21230 
21231 	/* The first mblk contains the header and some payload. */
21232 	blocks = 1;
21233 	total = size;
21234 	size %= len;
21235 	missing = (size == 0) ? 0 : (len - size);
21236 	mp = mp->b_cont;
21237 
21238 	while (mp != NULL) {
21239 		/*
21240 		 * Give up if we encounter a zero length message block.
21241 		 * In practice, this should rarely happen and therefore
21242 		 * not worth the trouble of freeing and re-linking the
21243 		 * mblk from the chain to handle such case.
21244 		 */
21245 		if ((size = MBLKL(mp)) == 0)
21246 			return (B_FALSE);
21247 
21248 		/* Too many payload buffers for a single Multidata message? */
21249 		if (++blocks > MULTIDATA_MAX_PBUFS)
21250 			return (B_FALSE);
21251 
21252 		total += size;
21253 		/* Is a frag distributed over two or more message blocks? */
21254 		if (missing > size)
21255 			return (B_FALSE);
21256 		size -= missing;
21257 
21258 		size %= len;
21259 		missing = (size == 0) ? 0 : (len - size);
21260 
21261 		mp = mp->b_cont;
21262 	}
21263 
21264 	return (total > ip_wput_frag_mdt_min);
21265 }
21266 
21267 /*
21268  * Outbound IPv4 fragmentation routine using MDT.
21269  */
21270 static void
21271 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
21272     uint32_t frag_flag, int offset)
21273 {
21274 	ipha_t		*ipha_orig;
21275 	int		i1, ip_data_end;
21276 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
21277 	mblk_t		*hdr_mp, *md_mp = NULL;
21278 	unsigned char	*hdr_ptr, *pld_ptr;
21279 	multidata_t	*mmd;
21280 	ip_pdescinfo_t	pdi;
21281 
21282 	ASSERT(DB_TYPE(mp) == M_DATA);
21283 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
21284 
21285 	ipha_orig = (ipha_t *)mp->b_rptr;
21286 	mp->b_rptr += sizeof (ipha_t);
21287 
21288 	/* Calculate how many packets we will send out */
21289 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
21290 	pkts = (i1 + len - 1) / len;
21291 	ASSERT(pkts > 1);
21292 
21293 	/* Allocate a message block which will hold all the IP Headers. */
21294 	wroff = ip_wroff_extra;
21295 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
21296 
21297 	i1 = pkts * hdr_chunk_len;
21298 	/*
21299 	 * Create the header buffer, Multidata and destination address
21300 	 * and SAP attribute that should be associated with it.
21301 	 */
21302 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
21303 	    ((hdr_mp->b_wptr += i1),
21304 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
21305 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
21306 		freemsg(mp);
21307 		if (md_mp == NULL) {
21308 			freemsg(hdr_mp);
21309 		} else {
21310 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
21311 			freemsg(md_mp);
21312 		}
21313 		IP_STAT(ip_frag_mdt_allocfail);
21314 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
21315 		return;
21316 	}
21317 	IP_STAT(ip_frag_mdt_allocd);
21318 
21319 	/*
21320 	 * Add a payload buffer to the Multidata; this operation must not
21321 	 * fail, or otherwise our logic in this routine is broken.  There
21322 	 * is no memory allocation done by the routine, so any returned
21323 	 * failure simply tells us that we've done something wrong.
21324 	 *
21325 	 * A failure tells us that either we're adding the same payload
21326 	 * buffer more than once, or we're trying to add more buffers than
21327 	 * allowed.  None of the above cases should happen, and we panic
21328 	 * because either there's horrible heap corruption, and/or
21329 	 * programming mistake.
21330 	 */
21331 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21332 		goto pbuf_panic;
21333 
21334 	hdr_ptr = hdr_mp->b_rptr;
21335 	pld_ptr = mp->b_rptr;
21336 
21337 	/* Establish the ending byte offset, based on the starting offset. */
21338 	offset <<= 3;
21339 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
21340 	    IP_SIMPLE_HDR_LENGTH;
21341 
21342 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
21343 
21344 	while (pld_ptr < mp->b_wptr) {
21345 		ipha_t		*ipha;
21346 		uint16_t	offset_and_flags;
21347 		uint16_t	ip_len;
21348 		int		error;
21349 
21350 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
21351 		ipha = (ipha_t *)(hdr_ptr + wroff);
21352 		ASSERT(OK_32PTR(ipha));
21353 		*ipha = *ipha_orig;
21354 
21355 		if (ip_data_end - offset > len) {
21356 			offset_and_flags = IPH_MF;
21357 		} else {
21358 			/*
21359 			 * Last frag. Set len to the length of this last piece.
21360 			 */
21361 			len = ip_data_end - offset;
21362 			/* A frag of a frag might have IPH_MF non-zero */
21363 			offset_and_flags =
21364 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21365 			    IPH_MF;
21366 		}
21367 		offset_and_flags |= (uint16_t)(offset >> 3);
21368 		offset_and_flags |= (uint16_t)frag_flag;
21369 		/* Store the offset and flags in the IP header. */
21370 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21371 
21372 		/* Store the length in the IP header. */
21373 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
21374 		ipha->ipha_length = htons(ip_len);
21375 
21376 		/*
21377 		 * Set the IP header checksum.  Note that mp is just
21378 		 * the header, so this is easy to pass to ip_csum.
21379 		 */
21380 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21381 
21382 		/*
21383 		 * Record offset and size of header and data of the next packet
21384 		 * in the multidata message.
21385 		 */
21386 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
21387 		PDESC_PLD_INIT(&pdi);
21388 		i1 = MIN(mp->b_wptr - pld_ptr, len);
21389 		ASSERT(i1 > 0);
21390 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
21391 		if (i1 == len) {
21392 			pld_ptr += len;
21393 		} else {
21394 			i1 = len - i1;
21395 			mp = mp->b_cont;
21396 			ASSERT(mp != NULL);
21397 			ASSERT(MBLKL(mp) >= i1);
21398 			/*
21399 			 * Attach the next payload message block to the
21400 			 * multidata message.
21401 			 */
21402 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21403 				goto pbuf_panic;
21404 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
21405 			pld_ptr = mp->b_rptr + i1;
21406 		}
21407 
21408 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
21409 		    KM_NOSLEEP)) == NULL) {
21410 			/*
21411 			 * Any failure other than ENOMEM indicates that we
21412 			 * have passed in invalid pdesc info or parameters
21413 			 * to mmd_addpdesc, which must not happen.
21414 			 *
21415 			 * EINVAL is a result of failure on boundary checks
21416 			 * against the pdesc info contents.  It should not
21417 			 * happen, and we panic because either there's
21418 			 * horrible heap corruption, and/or programming
21419 			 * mistake.
21420 			 */
21421 			if (error != ENOMEM) {
21422 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
21423 				    "pdesc logic error detected for "
21424 				    "mmd %p pinfo %p (%d)\n",
21425 				    (void *)mmd, (void *)&pdi, error);
21426 				/* NOTREACHED */
21427 			}
21428 			IP_STAT(ip_frag_mdt_addpdescfail);
21429 			/* Free unattached payload message blocks as well */
21430 			md_mp->b_cont = mp->b_cont;
21431 			goto free_mmd;
21432 		}
21433 
21434 		/* Advance fragment offset. */
21435 		offset += len;
21436 
21437 		/* Advance to location for next header in the buffer. */
21438 		hdr_ptr += hdr_chunk_len;
21439 
21440 		/* Did we reach the next payload message block? */
21441 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
21442 			mp = mp->b_cont;
21443 			/*
21444 			 * Attach the next message block with payload
21445 			 * data to the multidata message.
21446 			 */
21447 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21448 				goto pbuf_panic;
21449 			pld_ptr = mp->b_rptr;
21450 		}
21451 	}
21452 
21453 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
21454 	ASSERT(mp->b_wptr == pld_ptr);
21455 
21456 	/* Update IP statistics */
21457 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
21458 	BUMP_MIB(&ip_mib, ipFragOKs);
21459 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
21460 
21461 	if (pkt_type == OB_PKT) {
21462 		ire->ire_ob_pkt_count += pkts;
21463 		if (ire->ire_ipif != NULL)
21464 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
21465 	} else {
21466 		/*
21467 		 * The type is IB_PKT in the forwarding path and in
21468 		 * the mobile IP case when the packet is being reverse-
21469 		 * tunneled to the home agent.
21470 		 */
21471 		ire->ire_ib_pkt_count += pkts;
21472 		ASSERT(!IRE_IS_LOCAL(ire));
21473 		if (ire->ire_type & IRE_BROADCAST)
21474 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
21475 		else
21476 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
21477 	}
21478 	ire->ire_last_used_time = lbolt;
21479 	/* Send it down */
21480 	putnext(ire->ire_stq, md_mp);
21481 	return;
21482 
21483 pbuf_panic:
21484 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
21485 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
21486 	    pbuf_idx);
21487 	/* NOTREACHED */
21488 }
21489 
21490 /*
21491  * Outbound IP fragmentation routine.
21492  *
21493  * NOTE : This routine does not ire_refrele the ire that is passed in
21494  * as the argument.
21495  */
21496 static void
21497 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21498     uint32_t frag_flag)
21499 {
21500 	int		i1;
21501 	mblk_t		*ll_hdr_mp;
21502 	int 		ll_hdr_len;
21503 	int		hdr_len;
21504 	mblk_t		*hdr_mp;
21505 	ipha_t		*ipha;
21506 	int		ip_data_end;
21507 	int		len;
21508 	mblk_t		*mp = mp_orig;
21509 	int		offset;
21510 	queue_t		*q;
21511 	uint32_t	v_hlen_tos_len;
21512 	mblk_t		*first_mp;
21513 	boolean_t	mctl_present;
21514 	ill_t		*ill;
21515 	mblk_t		*xmit_mp;
21516 	mblk_t		*carve_mp;
21517 	ire_t		*ire1 = NULL;
21518 	ire_t		*save_ire = NULL;
21519 	mblk_t  	*next_mp = NULL;
21520 	boolean_t	last_frag = B_FALSE;
21521 	boolean_t	multirt_send = B_FALSE;
21522 	ire_t		*first_ire = NULL;
21523 	irb_t		*irb = NULL;
21524 
21525 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21526 	    "ip_wput_frag_start:");
21527 
21528 	if (mp->b_datap->db_type == M_CTL) {
21529 		first_mp = mp;
21530 		mp_orig = mp = mp->b_cont;
21531 		mctl_present = B_TRUE;
21532 	} else {
21533 		first_mp = mp;
21534 		mctl_present = B_FALSE;
21535 	}
21536 
21537 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
21538 	ipha = (ipha_t *)mp->b_rptr;
21539 
21540 	/*
21541 	 * If the Don't Fragment flag is on, generate an ICMP destination
21542 	 * unreachable, fragmentation needed.
21543 	 */
21544 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21545 	if (offset & IPH_DF) {
21546 		BUMP_MIB(&ip_mib, ipFragFails);
21547 		/*
21548 		 * Need to compute hdr checksum if called from ip_wput_ire.
21549 		 * Note that ip_rput_forward verifies the checksum before
21550 		 * calling this routine so in that case this is a noop.
21551 		 */
21552 		ipha->ipha_hdr_checksum = 0;
21553 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21554 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21555 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21556 		    "ip_wput_frag_end:(%S)",
21557 		    "don't fragment");
21558 		return;
21559 	}
21560 	if (mctl_present)
21561 		freeb(first_mp);
21562 	/*
21563 	 * Establish the starting offset.  May not be zero if we are fragging
21564 	 * a fragment that is being forwarded.
21565 	 */
21566 	offset = offset & IPH_OFFSET;
21567 
21568 	/* TODO why is this test needed? */
21569 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21570 	if (((max_frag - LENGTH) & ~7) < 8) {
21571 		/* TODO: notify ulp somehow */
21572 		BUMP_MIB(&ip_mib, ipFragFails);
21573 		freemsg(mp);
21574 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21575 		    "ip_wput_frag_end:(%S)",
21576 		    "len < 8");
21577 		return;
21578 	}
21579 
21580 	hdr_len = (V_HLEN & 0xF) << 2;
21581 
21582 	ipha->ipha_hdr_checksum = 0;
21583 
21584 	/*
21585 	 * Establish the number of bytes maximum per frag, after putting
21586 	 * in the header.
21587 	 */
21588 	len = (max_frag - hdr_len) & ~7;
21589 
21590 	/* Check if we can use MDT to send out the frags. */
21591 	ASSERT(!IRE_IS_LOCAL(ire));
21592 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
21593 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
21594 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
21595 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
21596 		ASSERT(ill->ill_mdt_capab != NULL);
21597 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21598 			/*
21599 			 * If MDT has been previously turned off in the past,
21600 			 * and we currently can do MDT (due to IPQoS policy
21601 			 * removal, etc.) then enable it for this interface.
21602 			 */
21603 			ill->ill_mdt_capab->ill_mdt_on = 1;
21604 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
21605 			    ill->ill_name));
21606 		}
21607 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
21608 		    offset);
21609 		return;
21610 	}
21611 
21612 	/* Get a copy of the header for the trailing frags */
21613 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21614 	if (!hdr_mp) {
21615 		BUMP_MIB(&ip_mib, ipOutDiscards);
21616 		freemsg(mp);
21617 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21618 		    "ip_wput_frag_end:(%S)",
21619 		    "couldn't copy hdr");
21620 		return;
21621 	}
21622 
21623 	/* Store the starting offset, with the MoreFrags flag. */
21624 	i1 = offset | IPH_MF | frag_flag;
21625 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21626 
21627 	/* Establish the ending byte offset, based on the starting offset. */
21628 	offset <<= 3;
21629 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21630 
21631 	/* Store the length of the first fragment in the IP header. */
21632 	i1 = len + hdr_len;
21633 	ASSERT(i1 <= IP_MAXPACKET);
21634 	ipha->ipha_length = htons((uint16_t)i1);
21635 
21636 	/*
21637 	 * Compute the IP header checksum for the first frag.  We have to
21638 	 * watch out that we stop at the end of the header.
21639 	 */
21640 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21641 
21642 	/*
21643 	 * Now carve off the first frag.  Note that this will include the
21644 	 * original IP header.
21645 	 */
21646 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21647 		BUMP_MIB(&ip_mib, ipOutDiscards);
21648 		freeb(hdr_mp);
21649 		freemsg(mp_orig);
21650 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21651 		    "ip_wput_frag_end:(%S)",
21652 		    "couldn't carve first");
21653 		return;
21654 	}
21655 
21656 	/*
21657 	 * Multirouting case. Each fragment is replicated
21658 	 * via all non-condemned RTF_MULTIRT routes
21659 	 * currently resolved.
21660 	 * We ensure that first_ire is the first RTF_MULTIRT
21661 	 * ire in the bucket.
21662 	 */
21663 	if (ire->ire_flags & RTF_MULTIRT) {
21664 		irb = ire->ire_bucket;
21665 		ASSERT(irb != NULL);
21666 
21667 		multirt_send = B_TRUE;
21668 
21669 		/* Make sure we do not omit any multiroute ire. */
21670 		IRB_REFHOLD(irb);
21671 		for (first_ire = irb->irb_ire;
21672 		    first_ire != NULL;
21673 		    first_ire = first_ire->ire_next) {
21674 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21675 			    (first_ire->ire_addr == ire->ire_addr) &&
21676 			    !(first_ire->ire_marks &
21677 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21678 				break;
21679 		}
21680 
21681 		if (first_ire != NULL) {
21682 			if (first_ire != ire) {
21683 				IRE_REFHOLD(first_ire);
21684 				/*
21685 				 * Do not release the ire passed in
21686 				 * as the argument.
21687 				 */
21688 				ire = first_ire;
21689 			} else {
21690 				first_ire = NULL;
21691 			}
21692 		}
21693 		IRB_REFRELE(irb);
21694 
21695 		/*
21696 		 * Save the first ire; we will need to restore it
21697 		 * for the trailing frags.
21698 		 * We REFHOLD save_ire, as each iterated ire will be
21699 		 * REFRELEd.
21700 		 */
21701 		save_ire = ire;
21702 		IRE_REFHOLD(save_ire);
21703 	}
21704 
21705 	/*
21706 	 * First fragment emission loop.
21707 	 * In most cases, the emission loop below is entered only
21708 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21709 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21710 	 * bucket, and send the fragment through all crossed
21711 	 * RTF_MULTIRT routes.
21712 	 */
21713 	do {
21714 		if (ire->ire_flags & RTF_MULTIRT) {
21715 			/*
21716 			 * We are in a multiple send case, need to get
21717 			 * the next ire and make a copy of the packet.
21718 			 * ire1 holds here the next ire to process in the
21719 			 * bucket. If multirouting is expected,
21720 			 * any non-RTF_MULTIRT ire that has the
21721 			 * right destination address is ignored.
21722 			 *
21723 			 * We have to take into account the MTU of
21724 			 * each walked ire. max_frag is set by the
21725 			 * the caller and generally refers to
21726 			 * the primary ire entry. Here we ensure that
21727 			 * no route with a lower MTU will be used, as
21728 			 * fragments are carved once for all ires,
21729 			 * then replicated.
21730 			 */
21731 			ASSERT(irb != NULL);
21732 			IRB_REFHOLD(irb);
21733 			for (ire1 = ire->ire_next;
21734 			    ire1 != NULL;
21735 			    ire1 = ire1->ire_next) {
21736 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21737 					continue;
21738 				if (ire1->ire_addr != ire->ire_addr)
21739 					continue;
21740 				if (ire1->ire_marks &
21741 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21742 					continue;
21743 				/*
21744 				 * Ensure we do not exceed the MTU
21745 				 * of the next route.
21746 				 */
21747 				if (ire1->ire_max_frag < max_frag) {
21748 					ip_multirt_bad_mtu(ire1, max_frag);
21749 					continue;
21750 				}
21751 
21752 				/* Got one. */
21753 				IRE_REFHOLD(ire1);
21754 				break;
21755 			}
21756 			IRB_REFRELE(irb);
21757 
21758 			if (ire1 != NULL) {
21759 				next_mp = copyb(mp);
21760 				if ((next_mp == NULL) ||
21761 				    ((mp->b_cont != NULL) &&
21762 				    ((next_mp->b_cont =
21763 				    dupmsg(mp->b_cont)) == NULL))) {
21764 					freemsg(next_mp);
21765 					next_mp = NULL;
21766 					ire_refrele(ire1);
21767 					ire1 = NULL;
21768 				}
21769 			}
21770 
21771 			/* Last multiroute ire; don't loop anymore. */
21772 			if (ire1 == NULL) {
21773 				multirt_send = B_FALSE;
21774 			}
21775 		}
21776 
21777 		ll_hdr_len = 0;
21778 		LOCK_IRE_FP_MP(ire);
21779 		ll_hdr_mp = ire->ire_fp_mp;
21780 		if (ll_hdr_mp != NULL) {
21781 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21782 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21783 		} else {
21784 			ll_hdr_mp = ire->ire_dlureq_mp;
21785 		}
21786 
21787 		/* If there is a transmit header, get a copy for this frag. */
21788 		/*
21789 		 * TODO: should check db_ref before calling ip_carve_mp since
21790 		 * it might give us a dup.
21791 		 */
21792 		if (!ll_hdr_mp) {
21793 			/* No xmit header. */
21794 			xmit_mp = mp;
21795 		} else if (mp->b_datap->db_ref == 1 &&
21796 		    ll_hdr_len != 0 &&
21797 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21798 			/* M_DATA fastpath */
21799 			mp->b_rptr -= ll_hdr_len;
21800 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21801 			xmit_mp = mp;
21802 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21803 			UNLOCK_IRE_FP_MP(ire);
21804 			BUMP_MIB(&ip_mib, ipOutDiscards);
21805 			freeb(hdr_mp);
21806 			freemsg(mp);
21807 			freemsg(mp_orig);
21808 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21809 			    "ip_wput_frag_end:(%S)",
21810 			    "discard");
21811 
21812 			if (multirt_send) {
21813 				ASSERT(ire1);
21814 				ASSERT(next_mp);
21815 
21816 				freemsg(next_mp);
21817 				ire_refrele(ire1);
21818 			}
21819 			if (save_ire != NULL)
21820 				IRE_REFRELE(save_ire);
21821 
21822 			if (first_ire != NULL)
21823 				ire_refrele(first_ire);
21824 			return;
21825 		} else {
21826 			xmit_mp->b_cont = mp;
21827 			/* Get priority marking, if any. */
21828 			if (DB_TYPE(xmit_mp) == M_DATA)
21829 				xmit_mp->b_band = mp->b_band;
21830 		}
21831 		UNLOCK_IRE_FP_MP(ire);
21832 		q = ire->ire_stq;
21833 		BUMP_MIB(&ip_mib, ipFragCreates);
21834 		putnext(q, xmit_mp);
21835 		if (pkt_type != OB_PKT) {
21836 			/*
21837 			 * Update the packet count of trailing
21838 			 * RTF_MULTIRT ires.
21839 			 */
21840 			UPDATE_OB_PKT_COUNT(ire);
21841 		}
21842 
21843 		if (multirt_send) {
21844 			/*
21845 			 * We are in a multiple send case; look for
21846 			 * the next ire and re-enter the loop.
21847 			 */
21848 			ASSERT(ire1);
21849 			ASSERT(next_mp);
21850 			/* REFRELE the current ire before looping */
21851 			ire_refrele(ire);
21852 			ire = ire1;
21853 			ire1 = NULL;
21854 			mp = next_mp;
21855 			next_mp = NULL;
21856 		}
21857 	} while (multirt_send);
21858 
21859 	ASSERT(ire1 == NULL);
21860 
21861 	/* Restore the original ire; we need it for the trailing frags */
21862 	if (save_ire != NULL) {
21863 		/* REFRELE the last iterated ire */
21864 		ire_refrele(ire);
21865 		/* save_ire has been REFHOLDed */
21866 		ire = save_ire;
21867 		save_ire = NULL;
21868 		q = ire->ire_stq;
21869 	}
21870 
21871 	if (pkt_type == OB_PKT) {
21872 		UPDATE_OB_PKT_COUNT(ire);
21873 	} else {
21874 		UPDATE_IB_PKT_COUNT(ire);
21875 	}
21876 
21877 	/* Advance the offset to the second frag starting point. */
21878 	offset += len;
21879 	/*
21880 	 * Update hdr_len from the copied header - there might be less options
21881 	 * in the later fragments.
21882 	 */
21883 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21884 	/* Loop until done. */
21885 	for (;;) {
21886 		uint16_t	offset_and_flags;
21887 		uint16_t	ip_len;
21888 
21889 		if (ip_data_end - offset > len) {
21890 			/*
21891 			 * Carve off the appropriate amount from the original
21892 			 * datagram.
21893 			 */
21894 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21895 				mp = NULL;
21896 				break;
21897 			}
21898 			/*
21899 			 * More frags after this one.  Get another copy
21900 			 * of the header.
21901 			 */
21902 			if (carve_mp->b_datap->db_ref == 1 &&
21903 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21904 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21905 				/* Inline IP header */
21906 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21907 				    hdr_mp->b_rptr;
21908 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21909 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21910 				mp = carve_mp;
21911 			} else {
21912 				if (!(mp = copyb(hdr_mp))) {
21913 					freemsg(carve_mp);
21914 					break;
21915 				}
21916 				/* Get priority marking, if any. */
21917 				mp->b_band = carve_mp->b_band;
21918 				mp->b_cont = carve_mp;
21919 			}
21920 			ipha = (ipha_t *)mp->b_rptr;
21921 			offset_and_flags = IPH_MF;
21922 		} else {
21923 			/*
21924 			 * Last frag.  Consume the header. Set len to
21925 			 * the length of this last piece.
21926 			 */
21927 			len = ip_data_end - offset;
21928 
21929 			/*
21930 			 * Carve off the appropriate amount from the original
21931 			 * datagram.
21932 			 */
21933 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21934 				mp = NULL;
21935 				break;
21936 			}
21937 			if (carve_mp->b_datap->db_ref == 1 &&
21938 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21939 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21940 				/* Inline IP header */
21941 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21942 				    hdr_mp->b_rptr;
21943 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21944 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21945 				mp = carve_mp;
21946 				freeb(hdr_mp);
21947 				hdr_mp = mp;
21948 			} else {
21949 				mp = hdr_mp;
21950 				/* Get priority marking, if any. */
21951 				mp->b_band = carve_mp->b_band;
21952 				mp->b_cont = carve_mp;
21953 			}
21954 			ipha = (ipha_t *)mp->b_rptr;
21955 			/* A frag of a frag might have IPH_MF non-zero */
21956 			offset_and_flags =
21957 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21958 			    IPH_MF;
21959 		}
21960 		offset_and_flags |= (uint16_t)(offset >> 3);
21961 		offset_and_flags |= (uint16_t)frag_flag;
21962 		/* Store the offset and flags in the IP header. */
21963 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21964 
21965 		/* Store the length in the IP header. */
21966 		ip_len = (uint16_t)(len + hdr_len);
21967 		ipha->ipha_length = htons(ip_len);
21968 
21969 		/*
21970 		 * Set the IP header checksum.	Note that mp is just
21971 		 * the header, so this is easy to pass to ip_csum.
21972 		 */
21973 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21974 
21975 		/* Attach a transmit header, if any, and ship it. */
21976 		if (pkt_type == OB_PKT) {
21977 			UPDATE_OB_PKT_COUNT(ire);
21978 		} else {
21979 			UPDATE_IB_PKT_COUNT(ire);
21980 		}
21981 
21982 		if (ire->ire_flags & RTF_MULTIRT) {
21983 			irb = ire->ire_bucket;
21984 			ASSERT(irb != NULL);
21985 
21986 			multirt_send = B_TRUE;
21987 
21988 			/*
21989 			 * Save the original ire; we will need to restore it
21990 			 * for the tailing frags.
21991 			 */
21992 			save_ire = ire;
21993 			IRE_REFHOLD(save_ire);
21994 		}
21995 		/*
21996 		 * Emission loop for this fragment, similar
21997 		 * to what is done for the first fragment.
21998 		 */
21999 		do {
22000 			if (multirt_send) {
22001 				/*
22002 				 * We are in a multiple send case, need to get
22003 				 * the next ire and make a copy of the packet.
22004 				 */
22005 				ASSERT(irb != NULL);
22006 				IRB_REFHOLD(irb);
22007 				for (ire1 = ire->ire_next;
22008 				    ire1 != NULL;
22009 				    ire1 = ire1->ire_next) {
22010 					if (!(ire1->ire_flags & RTF_MULTIRT))
22011 						continue;
22012 					if (ire1->ire_addr != ire->ire_addr)
22013 						continue;
22014 					if (ire1->ire_marks &
22015 					    (IRE_MARK_CONDEMNED|
22016 						IRE_MARK_HIDDEN))
22017 						continue;
22018 					/*
22019 					 * Ensure we do not exceed the MTU
22020 					 * of the next route.
22021 					 */
22022 					if (ire1->ire_max_frag < max_frag) {
22023 						ip_multirt_bad_mtu(ire1,
22024 						    max_frag);
22025 						continue;
22026 					}
22027 
22028 					/* Got one. */
22029 					IRE_REFHOLD(ire1);
22030 					break;
22031 				}
22032 				IRB_REFRELE(irb);
22033 
22034 				if (ire1 != NULL) {
22035 					next_mp = copyb(mp);
22036 					if ((next_mp == NULL) ||
22037 					    ((mp->b_cont != NULL) &&
22038 					    ((next_mp->b_cont =
22039 					    dupmsg(mp->b_cont)) == NULL))) {
22040 						freemsg(next_mp);
22041 						next_mp = NULL;
22042 						ire_refrele(ire1);
22043 						ire1 = NULL;
22044 					}
22045 				}
22046 
22047 				/* Last multiroute ire; don't loop anymore. */
22048 				if (ire1 == NULL) {
22049 					multirt_send = B_FALSE;
22050 				}
22051 			}
22052 
22053 			/* Update transmit header */
22054 			ll_hdr_len = 0;
22055 			LOCK_IRE_FP_MP(ire);
22056 			ll_hdr_mp = ire->ire_fp_mp;
22057 			if (ll_hdr_mp != NULL) {
22058 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22059 				ll_hdr_len = MBLKL(ll_hdr_mp);
22060 			} else {
22061 				ll_hdr_mp = ire->ire_dlureq_mp;
22062 			}
22063 
22064 			if (!ll_hdr_mp) {
22065 				xmit_mp = mp;
22066 			} else if (mp->b_datap->db_ref == 1 &&
22067 			    ll_hdr_len != 0 &&
22068 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22069 				/* M_DATA fastpath */
22070 				mp->b_rptr -= ll_hdr_len;
22071 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22072 				    ll_hdr_len);
22073 				xmit_mp = mp;
22074 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22075 				xmit_mp->b_cont = mp;
22076 				/* Get priority marking, if any. */
22077 				if (DB_TYPE(xmit_mp) == M_DATA)
22078 					xmit_mp->b_band = mp->b_band;
22079 			} else {
22080 				/*
22081 				 * Exit both the replication and
22082 				 * fragmentation loops.
22083 				 */
22084 				UNLOCK_IRE_FP_MP(ire);
22085 				goto drop_pkt;
22086 			}
22087 			UNLOCK_IRE_FP_MP(ire);
22088 			BUMP_MIB(&ip_mib, ipFragCreates);
22089 			putnext(q, xmit_mp);
22090 
22091 			if (pkt_type != OB_PKT) {
22092 				/*
22093 				 * Update the packet count of trailing
22094 				 * RTF_MULTIRT ires.
22095 				 */
22096 				UPDATE_OB_PKT_COUNT(ire);
22097 			}
22098 
22099 			/* All done if we just consumed the hdr_mp. */
22100 			if (mp == hdr_mp) {
22101 				last_frag = B_TRUE;
22102 			}
22103 
22104 			if (multirt_send) {
22105 				/*
22106 				 * We are in a multiple send case; look for
22107 				 * the next ire and re-enter the loop.
22108 				 */
22109 				ASSERT(ire1);
22110 				ASSERT(next_mp);
22111 				/* REFRELE the current ire before looping */
22112 				ire_refrele(ire);
22113 				ire = ire1;
22114 				ire1 = NULL;
22115 				q = ire->ire_stq;
22116 				mp = next_mp;
22117 				next_mp = NULL;
22118 			}
22119 		} while (multirt_send);
22120 		/*
22121 		 * Restore the original ire; we need it for the
22122 		 * trailing frags
22123 		 */
22124 		if (save_ire != NULL) {
22125 			ASSERT(ire1 == NULL);
22126 			/* REFRELE the last iterated ire */
22127 			ire_refrele(ire);
22128 			/* save_ire has been REFHOLDed */
22129 			ire = save_ire;
22130 			q = ire->ire_stq;
22131 			save_ire = NULL;
22132 		}
22133 
22134 		if (last_frag) {
22135 			BUMP_MIB(&ip_mib, ipFragOKs);
22136 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22137 			    "ip_wput_frag_end:(%S)",
22138 			    "consumed hdr_mp");
22139 
22140 			if (first_ire != NULL)
22141 				ire_refrele(first_ire);
22142 			return;
22143 		}
22144 		/* Otherwise, advance and loop. */
22145 		offset += len;
22146 	}
22147 
22148 drop_pkt:
22149 	/* Clean up following allocation failure. */
22150 	BUMP_MIB(&ip_mib, ipOutDiscards);
22151 	freemsg(mp);
22152 	if (mp != hdr_mp)
22153 		freeb(hdr_mp);
22154 	if (mp != mp_orig)
22155 		freemsg(mp_orig);
22156 
22157 	if (save_ire != NULL)
22158 		IRE_REFRELE(save_ire);
22159 	if (first_ire != NULL)
22160 		ire_refrele(first_ire);
22161 
22162 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22163 	    "ip_wput_frag_end:(%S)",
22164 	    "end--alloc failure");
22165 }
22166 
22167 /*
22168  * Copy the header plus those options which have the copy bit set
22169  */
22170 static mblk_t *
22171 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22172 {
22173 	mblk_t	*mp;
22174 	uchar_t	*up;
22175 
22176 	/*
22177 	 * Quick check if we need to look for options without the copy bit
22178 	 * set
22179 	 */
22180 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22181 	if (!mp)
22182 		return (mp);
22183 	mp->b_rptr += ip_wroff_extra;
22184 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22185 		bcopy(rptr, mp->b_rptr, hdr_len);
22186 		mp->b_wptr += hdr_len + ip_wroff_extra;
22187 		return (mp);
22188 	}
22189 	up  = mp->b_rptr;
22190 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22191 	up += IP_SIMPLE_HDR_LENGTH;
22192 	rptr += IP_SIMPLE_HDR_LENGTH;
22193 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22194 	while (hdr_len > 0) {
22195 		uint32_t optval;
22196 		uint32_t optlen;
22197 
22198 		optval = *rptr;
22199 		if (optval == IPOPT_EOL)
22200 			break;
22201 		if (optval == IPOPT_NOP)
22202 			optlen = 1;
22203 		else
22204 			optlen = rptr[1];
22205 		if (optval & IPOPT_COPY) {
22206 			bcopy(rptr, up, optlen);
22207 			up += optlen;
22208 		}
22209 		rptr += optlen;
22210 		hdr_len -= optlen;
22211 	}
22212 	/*
22213 	 * Make sure that we drop an even number of words by filling
22214 	 * with EOL to the next word boundary.
22215 	 */
22216 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
22217 	    hdr_len & 0x3; hdr_len++)
22218 		*up++ = IPOPT_EOL;
22219 	mp->b_wptr = up;
22220 	/* Update header length */
22221 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
22222 	return (mp);
22223 }
22224 
22225 /*
22226  * Delivery to local recipients including fanout to multiple recipients.
22227  * Does not do checksumming of UDP/TCP.
22228  * Note: q should be the read side queue for either the ill or conn.
22229  * Note: rq should be the read side q for the lower (ill) stream.
22230  * We don't send packets to IPPF processing, thus the last argument
22231  * to all the fanout calls are B_FALSE.
22232  */
22233 void
22234 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
22235     int fanout_flags, zoneid_t zoneid)
22236 {
22237 	uint32_t	protocol;
22238 	mblk_t		*first_mp;
22239 	boolean_t	mctl_present;
22240 	int		ire_type;
22241 #define	rptr	((uchar_t *)ipha)
22242 
22243 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
22244 	    "ip_wput_local_start: q %p", q);
22245 
22246 	if (ire != NULL) {
22247 		ire_type = ire->ire_type;
22248 	} else {
22249 		/*
22250 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
22251 		 * packet is not multicast, we can't tell the ire type.
22252 		 */
22253 		ASSERT(CLASSD(ipha->ipha_dst));
22254 		ire_type = IRE_BROADCAST;
22255 	}
22256 
22257 	first_mp = mp;
22258 	if (first_mp->b_datap->db_type == M_CTL) {
22259 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
22260 		if (!io->ipsec_out_secure) {
22261 			/*
22262 			 * This ipsec_out_t was allocated in ip_wput
22263 			 * for multicast packets to store the ill_index.
22264 			 * As this is being delivered locally, we don't
22265 			 * need this anymore.
22266 			 */
22267 			mp = first_mp->b_cont;
22268 			freeb(first_mp);
22269 			first_mp = mp;
22270 			mctl_present = B_FALSE;
22271 		} else {
22272 			mctl_present = B_TRUE;
22273 			mp = first_mp->b_cont;
22274 			ASSERT(mp != NULL);
22275 			ipsec_out_to_in(first_mp);
22276 		}
22277 	} else {
22278 		mctl_present = B_FALSE;
22279 	}
22280 
22281 	loopback_packets++;
22282 
22283 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
22284 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
22285 	if (!IS_SIMPLE_IPH(ipha)) {
22286 		ip_wput_local_options(ipha);
22287 	}
22288 
22289 	protocol = ipha->ipha_protocol;
22290 	switch (protocol) {
22291 	case IPPROTO_ICMP: {
22292 		ire_t		*ire_zone;
22293 		ilm_t		*ilm;
22294 		mblk_t		*mp1;
22295 		zoneid_t	last_zoneid;
22296 
22297 		if (CLASSD(ipha->ipha_dst) &&
22298 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
22299 			ASSERT(ire_type == IRE_BROADCAST);
22300 			/*
22301 			 * In the multicast case, applications may have joined
22302 			 * the group from different zones, so we need to deliver
22303 			 * the packet to each of them. Loop through the
22304 			 * multicast memberships structures (ilm) on the receive
22305 			 * ill and send a copy of the packet up each matching
22306 			 * one. However, we don't do this for multicasts sent on
22307 			 * the loopback interface (PHYI_LOOPBACK flag set) as
22308 			 * they must stay in the sender's zone.
22309 			 *
22310 			 * ilm_add_v6() ensures that ilms in the same zone are
22311 			 * contiguous in the ill_ilm list. We use this property
22312 			 * to avoid sending duplicates needed when two
22313 			 * applications in the same zone join the same group on
22314 			 * different logical interfaces: we ignore the ilm if
22315 			 * its zoneid is the same as the last matching one.
22316 			 * In addition, the sending of the packet for
22317 			 * ire_zoneid is delayed until all of the other ilms
22318 			 * have been exhausted.
22319 			 */
22320 			last_zoneid = -1;
22321 			ILM_WALKER_HOLD(ill);
22322 			for (ilm = ill->ill_ilm; ilm != NULL;
22323 			    ilm = ilm->ilm_next) {
22324 				if ((ilm->ilm_flags & ILM_DELETED) ||
22325 				    ipha->ipha_dst != ilm->ilm_addr ||
22326 				    ilm->ilm_zoneid == last_zoneid ||
22327 				    ilm->ilm_zoneid == zoneid ||
22328 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
22329 					continue;
22330 				mp1 = ip_copymsg(first_mp);
22331 				if (mp1 == NULL)
22332 					continue;
22333 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22334 				    mctl_present, B_FALSE, ill,
22335 				    ilm->ilm_zoneid);
22336 				last_zoneid = ilm->ilm_zoneid;
22337 			}
22338 			ILM_WALKER_RELE(ill);
22339 			/*
22340 			 * Loopback case: the sending endpoint has
22341 			 * IP_MULTICAST_LOOP disabled, therefore we don't
22342 			 * dispatch the multicast packet to the sending zone.
22343 			 */
22344 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
22345 				freemsg(first_mp);
22346 				return;
22347 			}
22348 		} else if (ire_type == IRE_BROADCAST) {
22349 			/*
22350 			 * In the broadcast case, there may be many zones
22351 			 * which need a copy of the packet delivered to them.
22352 			 * There is one IRE_BROADCAST per broadcast address
22353 			 * and per zone; we walk those using a helper function.
22354 			 * In addition, the sending of the packet for zoneid is
22355 			 * delayed until all of the other ires have been
22356 			 * processed.
22357 			 */
22358 			IRB_REFHOLD(ire->ire_bucket);
22359 			ire_zone = NULL;
22360 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
22361 			    ire)) != NULL) {
22362 				mp1 = ip_copymsg(first_mp);
22363 				if (mp1 == NULL)
22364 					continue;
22365 
22366 				UPDATE_IB_PKT_COUNT(ire_zone);
22367 				ire_zone->ire_last_used_time = lbolt;
22368 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22369 				    mctl_present, B_FALSE, ill,
22370 				    ire_zone->ire_zoneid);
22371 			}
22372 			IRB_REFRELE(ire->ire_bucket);
22373 		}
22374 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
22375 		    0, mctl_present, B_FALSE, ill, zoneid);
22376 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22377 		    "ip_wput_local_end: q %p (%S)",
22378 		    q, "icmp");
22379 		return;
22380 	}
22381 	case IPPROTO_IGMP:
22382 		if (igmp_input(q, mp, ill)) {
22383 			/* Bad packet - discarded by igmp_input */
22384 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22385 			    "ip_wput_local_end: q %p (%S)",
22386 			    q, "igmp_input--bad packet");
22387 			if (mctl_present)
22388 				freeb(first_mp);
22389 			return;
22390 		}
22391 		/*
22392 		 * igmp_input() may have pulled up the message so ipha needs to
22393 		 * be reinitialized.
22394 		 */
22395 		ipha = (ipha_t *)mp->b_rptr;
22396 		/* deliver to local raw users */
22397 		break;
22398 	case IPPROTO_ENCAP:
22399 		/*
22400 		 * This case is covered by either ip_fanout_proto, or by
22401 		 * the above security processing for self-tunneled packets.
22402 		 */
22403 		break;
22404 	case IPPROTO_UDP: {
22405 		uint16_t	*up;
22406 		uint32_t	ports;
22407 
22408 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
22409 		    UDP_PORTS_OFFSET);
22410 		/* Force a 'valid' checksum. */
22411 		up[3] = 0;
22412 
22413 		ports = *(uint32_t *)up;
22414 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
22415 		    (ire_type == IRE_BROADCAST),
22416 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22417 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
22418 		    ill, zoneid);
22419 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22420 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
22421 		return;
22422 	}
22423 	case IPPROTO_TCP: {
22424 
22425 		/*
22426 		 * For TCP, discard broadcast packets.
22427 		 */
22428 		if ((ushort_t)ire_type == IRE_BROADCAST) {
22429 			freemsg(first_mp);
22430 			BUMP_MIB(&ip_mib, ipInDiscards);
22431 			return;
22432 		}
22433 
22434 		if (mp->b_datap->db_type == M_DATA) {
22435 			/*
22436 			 * M_DATA mblk, so init mblk (chain) for no struio().
22437 			 */
22438 			mblk_t	*mp1 = mp;
22439 
22440 			do
22441 				mp1->b_datap->db_struioflag = 0;
22442 			while ((mp1 = mp1->b_cont) != NULL);
22443 		}
22444 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
22445 		    <= mp->b_wptr);
22446 		ip_fanout_tcp(q, first_mp, ill, ipha,
22447 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22448 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
22449 		    mctl_present, B_FALSE, zoneid);
22450 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22451 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
22452 		return;
22453 	}
22454 	case IPPROTO_SCTP:
22455 	{
22456 		uint32_t	ports;
22457 
22458 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
22459 		ip_fanout_sctp(first_mp, ill, ipha, ports,
22460 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22461 		    IP_FF_IP6INFO,
22462 		    mctl_present, B_FALSE, 0, zoneid);
22463 		return;
22464 	}
22465 
22466 	default:
22467 		break;
22468 	}
22469 	/*
22470 	 * Find a client for some other protocol.  We give
22471 	 * copies to multiple clients, if more than one is
22472 	 * bound.
22473 	 */
22474 	ip_fanout_proto(q, first_mp, ill, ipha,
22475 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
22476 	    mctl_present, B_FALSE, ill, zoneid);
22477 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22478 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
22479 #undef	rptr
22480 }
22481 
22482 /*
22483  * Update any source route, record route, or timestamp options.
22484  * Check that we are at end of strict source route.
22485  * The options have been sanity checked by ip_wput_options().
22486  */
22487 static void
22488 ip_wput_local_options(ipha_t *ipha)
22489 {
22490 	ipoptp_t	opts;
22491 	uchar_t		*opt;
22492 	uint8_t		optval;
22493 	uint8_t		optlen;
22494 	ipaddr_t	dst;
22495 	uint32_t	ts;
22496 	ire_t		*ire;
22497 	timestruc_t	now;
22498 
22499 	ip2dbg(("ip_wput_local_options\n"));
22500 	for (optval = ipoptp_first(&opts, ipha);
22501 	    optval != IPOPT_EOL;
22502 	    optval = ipoptp_next(&opts)) {
22503 		opt = opts.ipoptp_cur;
22504 		optlen = opts.ipoptp_len;
22505 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22506 		switch (optval) {
22507 			uint32_t off;
22508 		case IPOPT_SSRR:
22509 		case IPOPT_LSRR:
22510 			off = opt[IPOPT_OFFSET];
22511 			off--;
22512 			if (optlen < IP_ADDR_LEN ||
22513 			    off > optlen - IP_ADDR_LEN) {
22514 				/* End of source route */
22515 				break;
22516 			}
22517 			/*
22518 			 * This will only happen if two consecutive entries
22519 			 * in the source route contains our address or if
22520 			 * it is a packet with a loose source route which
22521 			 * reaches us before consuming the whole source route
22522 			 */
22523 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22524 			if (optval == IPOPT_SSRR) {
22525 				return;
22526 			}
22527 			/*
22528 			 * Hack: instead of dropping the packet truncate the
22529 			 * source route to what has been used by filling the
22530 			 * rest with IPOPT_NOP.
22531 			 */
22532 			opt[IPOPT_OLEN] = (uint8_t)off;
22533 			while (off < optlen) {
22534 				opt[off++] = IPOPT_NOP;
22535 			}
22536 			break;
22537 		case IPOPT_RR:
22538 			off = opt[IPOPT_OFFSET];
22539 			off--;
22540 			if (optlen < IP_ADDR_LEN ||
22541 			    off > optlen - IP_ADDR_LEN) {
22542 				/* No more room - ignore */
22543 				ip1dbg((
22544 				    "ip_wput_forward_options: end of RR\n"));
22545 				break;
22546 			}
22547 			dst = htonl(INADDR_LOOPBACK);
22548 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22549 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22550 			break;
22551 		case IPOPT_TS:
22552 			/* Insert timestamp if there is romm */
22553 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22554 			case IPOPT_TS_TSONLY:
22555 				off = IPOPT_TS_TIMELEN;
22556 				break;
22557 			case IPOPT_TS_PRESPEC:
22558 			case IPOPT_TS_PRESPEC_RFC791:
22559 				/* Verify that the address matched */
22560 				off = opt[IPOPT_OFFSET] - 1;
22561 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22562 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22563 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22564 				if (ire == NULL) {
22565 					/* Not for us */
22566 					break;
22567 				}
22568 				ire_refrele(ire);
22569 				/* FALLTHRU */
22570 			case IPOPT_TS_TSANDADDR:
22571 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22572 				break;
22573 			default:
22574 				/*
22575 				 * ip_*put_options should have already
22576 				 * dropped this packet.
22577 				 */
22578 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22579 				    "unknown IT - bug in ip_wput_options?\n");
22580 				return;	/* Keep "lint" happy */
22581 			}
22582 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22583 				/* Increase overflow counter */
22584 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22585 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22586 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22587 				    (off << 4);
22588 				break;
22589 			}
22590 			off = opt[IPOPT_OFFSET] - 1;
22591 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22592 			case IPOPT_TS_PRESPEC:
22593 			case IPOPT_TS_PRESPEC_RFC791:
22594 			case IPOPT_TS_TSANDADDR:
22595 				dst = htonl(INADDR_LOOPBACK);
22596 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22597 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22598 				/* FALLTHRU */
22599 			case IPOPT_TS_TSONLY:
22600 				off = opt[IPOPT_OFFSET] - 1;
22601 				/* Compute # of milliseconds since midnight */
22602 				gethrestime(&now);
22603 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22604 				    now.tv_nsec / (NANOSEC / MILLISEC);
22605 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22606 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22607 				break;
22608 			}
22609 			break;
22610 		}
22611 	}
22612 }
22613 
22614 /*
22615  * Send out a multicast packet on interface ipif.
22616  * The sender does not have an conn.
22617  * Caller verifies that this isn't a PHYI_LOOPBACK.
22618  */
22619 void
22620 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22621 {
22622 	ipha_t	*ipha;
22623 	ire_t	*ire;
22624 	ipaddr_t	dst;
22625 	mblk_t		*first_mp;
22626 
22627 	/* igmp_sendpkt always allocates a ipsec_out_t */
22628 	ASSERT(mp->b_datap->db_type == M_CTL);
22629 	ASSERT(!ipif->ipif_isv6);
22630 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22631 
22632 	first_mp = mp;
22633 	mp = first_mp->b_cont;
22634 	ASSERT(mp->b_datap->db_type == M_DATA);
22635 	ipha = (ipha_t *)mp->b_rptr;
22636 
22637 	/*
22638 	 * Find an IRE which matches the destination and the outgoing
22639 	 * queue (i.e. the outgoing interface.)
22640 	 */
22641 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22642 		dst = ipif->ipif_pp_dst_addr;
22643 	else
22644 		dst = ipha->ipha_dst;
22645 	/*
22646 	 * The source address has already been initialized by the
22647 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22648 	 * be sufficient rather than MATCH_IRE_IPIF.
22649 	 *
22650 	 * This function is used for sending IGMP packets. We need
22651 	 * to make sure that we send the packet out of the interface
22652 	 * (ipif->ipif_ill) where we joined the group. This is to
22653 	 * prevent from switches doing IGMP snooping to send us multicast
22654 	 * packets for a given group on the interface we have joined.
22655 	 * If we can't find an ire, igmp_sendpkt has already initialized
22656 	 * ipsec_out_attach_if so that this will not be load spread in
22657 	 * ip_newroute_ipif.
22658 	 */
22659 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22660 	if (!ire) {
22661 		/*
22662 		 * Mark this packet to make it be delivered to
22663 		 * ip_wput_ire after the new ire has been
22664 		 * created.
22665 		 */
22666 		mp->b_prev = NULL;
22667 		mp->b_next = NULL;
22668 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22669 		return;
22670 	}
22671 
22672 	/*
22673 	 * Honor the RTF_SETSRC flag; this is the only case
22674 	 * where we force this addr whatever the current src addr is,
22675 	 * because this address is set by igmp_sendpkt(), and
22676 	 * cannot be specified by any user.
22677 	 */
22678 	if (ire->ire_flags & RTF_SETSRC) {
22679 		ipha->ipha_src = ire->ire_src_addr;
22680 	}
22681 
22682 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22683 }
22684 
22685 /*
22686  * NOTE : This function does not ire_refrele the ire argument passed in.
22687  *
22688  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22689  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22690  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22691  * the ire_lock to access the ire_fp_mp in this case.
22692  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22693  * prepending a fastpath message IPQoS processing must precede it, we also set
22694  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22695  * (IPQoS might have set the b_band for CoS marking).
22696  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22697  * must follow it so that IPQoS can mark the dl_priority field for CoS
22698  * marking, if needed.
22699  */
22700 static mblk_t *
22701 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22702 {
22703 	uint_t	hlen;
22704 	ipha_t *ipha;
22705 	mblk_t *mp1;
22706 	boolean_t qos_done = B_FALSE;
22707 	uchar_t	*ll_hdr;
22708 
22709 #define	rptr	((uchar_t *)ipha)
22710 
22711 	ipha = (ipha_t *)mp->b_rptr;
22712 	hlen = 0;
22713 	LOCK_IRE_FP_MP(ire);
22714 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22715 		ASSERT(DB_TYPE(mp1) == M_DATA);
22716 		/* Initiate IPPF processing */
22717 		if ((proc != 0) && IPP_ENABLED(proc)) {
22718 			UNLOCK_IRE_FP_MP(ire);
22719 			ip_process(proc, &mp, ill_index);
22720 			if (mp == NULL)
22721 				return (NULL);
22722 
22723 			ipha = (ipha_t *)mp->b_rptr;
22724 			LOCK_IRE_FP_MP(ire);
22725 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22726 				qos_done = B_TRUE;
22727 				goto no_fp_mp;
22728 			}
22729 			ASSERT(DB_TYPE(mp1) == M_DATA);
22730 		}
22731 		hlen = MBLKL(mp1);
22732 		/*
22733 		 * Check if we have enough room to prepend fastpath
22734 		 * header
22735 		 */
22736 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22737 			ll_hdr = rptr - hlen;
22738 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22739 			/* XXX ipha is not aligned here */
22740 			ipha = (ipha_t *)(rptr - hlen);
22741 			/*
22742 			 * Set the b_rptr to the start of the link layer
22743 			 * header
22744 			 */
22745 			mp->b_rptr = rptr;
22746 			mp1 = mp;
22747 		} else {
22748 			mp1 = copyb(mp1);
22749 			if (mp1 == NULL)
22750 				goto unlock_err;
22751 			mp1->b_band = mp->b_band;
22752 			mp1->b_cont = mp;
22753 			/*
22754 			 * XXX disable ICK_VALID and compute checksum
22755 			 * here; can happen if ire_fp_mp changes and
22756 			 * it can't be copied now due to insufficient
22757 			 * space. (unlikely, fp mp can change, but it
22758 			 * does not increase in length)
22759 			 */
22760 		}
22761 		UNLOCK_IRE_FP_MP(ire);
22762 	} else {
22763 no_fp_mp:
22764 		mp1 = copyb(ire->ire_dlureq_mp);
22765 		if (mp1 == NULL) {
22766 unlock_err:
22767 			UNLOCK_IRE_FP_MP(ire);
22768 			freemsg(mp);
22769 			return (NULL);
22770 		}
22771 		UNLOCK_IRE_FP_MP(ire);
22772 		mp1->b_cont = mp;
22773 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22774 			ip_process(proc, &mp1, ill_index);
22775 			if (mp1 == NULL)
22776 				return (NULL);
22777 		}
22778 	}
22779 	return (mp1);
22780 #undef rptr
22781 }
22782 
22783 /*
22784  * Finish the outbound IPsec processing for an IPv6 packet. This function
22785  * is called from ipsec_out_process() if the IPsec packet was processed
22786  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22787  * asynchronously.
22788  */
22789 void
22790 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22791     ire_t *ire_arg)
22792 {
22793 	in6_addr_t *v6dstp;
22794 	ire_t *ire;
22795 	mblk_t *mp;
22796 	uint_t	ill_index;
22797 	ipsec_out_t *io;
22798 	boolean_t attach_if, hwaccel;
22799 	uint32_t flags = IP6_NO_IPPOLICY;
22800 	int match_flags;
22801 	zoneid_t zoneid;
22802 	boolean_t ill_need_rele = B_FALSE;
22803 	boolean_t ire_need_rele = B_FALSE;
22804 
22805 	mp = ipsec_mp->b_cont;
22806 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22807 	ill_index = io->ipsec_out_ill_index;
22808 	if (io->ipsec_out_reachable) {
22809 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22810 	}
22811 	attach_if = io->ipsec_out_attach_if;
22812 	hwaccel = io->ipsec_out_accelerated;
22813 	zoneid = io->ipsec_out_zoneid;
22814 	ASSERT(zoneid != ALL_ZONES);
22815 	match_flags = MATCH_IRE_ILL_GROUP;
22816 	/* Multicast addresses should have non-zero ill_index. */
22817 	v6dstp = &ip6h->ip6_dst;
22818 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22819 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22820 	ASSERT(!attach_if || ill_index != 0);
22821 	if (ill_index != 0) {
22822 		if (ill == NULL) {
22823 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22824 			    B_TRUE);
22825 
22826 			/* Failure case frees things for us. */
22827 			if (ill == NULL)
22828 				return;
22829 
22830 			ill_need_rele = B_TRUE;
22831 		}
22832 		/*
22833 		 * If this packet needs to go out on a particular interface
22834 		 * honor it.
22835 		 */
22836 		if (attach_if) {
22837 			match_flags = MATCH_IRE_ILL;
22838 
22839 			/*
22840 			 * Check if we need an ire that will not be
22841 			 * looked up by anybody else i.e. HIDDEN.
22842 			 */
22843 			if (ill_is_probeonly(ill)) {
22844 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22845 			}
22846 		}
22847 	}
22848 	ASSERT(mp != NULL);
22849 
22850 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22851 		boolean_t unspec_src;
22852 		ipif_t	*ipif;
22853 
22854 		/*
22855 		 * Use the ill_index to get the right ill.
22856 		 */
22857 		unspec_src = io->ipsec_out_unspec_src;
22858 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22859 		if (ipif == NULL) {
22860 			if (ill_need_rele)
22861 				ill_refrele(ill);
22862 			freemsg(ipsec_mp);
22863 			return;
22864 		}
22865 
22866 		if (ire_arg != NULL) {
22867 			ire = ire_arg;
22868 		} else {
22869 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22870 			    zoneid, match_flags);
22871 			ire_need_rele = B_TRUE;
22872 		}
22873 		if (ire != NULL) {
22874 			ipif_refrele(ipif);
22875 			/*
22876 			 * XXX Do the multicast forwarding now, as the IPSEC
22877 			 * processing has been done.
22878 			 */
22879 			goto send;
22880 		}
22881 
22882 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22883 		mp->b_prev = NULL;
22884 		mp->b_next = NULL;
22885 
22886 		/*
22887 		 * If the IPsec packet was processed asynchronously,
22888 		 * drop it now.
22889 		 */
22890 		if (q == NULL) {
22891 			if (ill_need_rele)
22892 				ill_refrele(ill);
22893 			freemsg(ipsec_mp);
22894 			return;
22895 		}
22896 
22897 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22898 		    unspec_src, zoneid);
22899 		ipif_refrele(ipif);
22900 	} else {
22901 		if (attach_if) {
22902 			ipif_t	*ipif;
22903 
22904 			ipif = ipif_get_next_ipif(NULL, ill);
22905 			if (ipif == NULL) {
22906 				if (ill_need_rele)
22907 					ill_refrele(ill);
22908 				freemsg(ipsec_mp);
22909 				return;
22910 			}
22911 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22912 			    zoneid, match_flags);
22913 			ire_need_rele = B_TRUE;
22914 			ipif_refrele(ipif);
22915 		} else {
22916 			if (ire_arg != NULL) {
22917 				ire = ire_arg;
22918 			} else {
22919 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22920 				ire_need_rele = B_TRUE;
22921 			}
22922 		}
22923 		if (ire != NULL)
22924 			goto send;
22925 		/*
22926 		 * ire disappeared underneath.
22927 		 *
22928 		 * What we need to do here is the ip_newroute
22929 		 * logic to get the ire without doing the IPSEC
22930 		 * processing. Follow the same old path. But this
22931 		 * time, ip_wput or ire_add_then_send will call us
22932 		 * directly as all the IPSEC operations are done.
22933 		 */
22934 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22935 		mp->b_prev = NULL;
22936 		mp->b_next = NULL;
22937 
22938 		/*
22939 		 * If the IPsec packet was processed asynchronously,
22940 		 * drop it now.
22941 		 */
22942 		if (q == NULL) {
22943 			if (ill_need_rele)
22944 				ill_refrele(ill);
22945 			freemsg(ipsec_mp);
22946 			return;
22947 		}
22948 
22949 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22950 		    zoneid);
22951 	}
22952 	if (ill != NULL && ill_need_rele)
22953 		ill_refrele(ill);
22954 	return;
22955 send:
22956 	if (ill != NULL && ill_need_rele)
22957 		ill_refrele(ill);
22958 
22959 	/* Local delivery */
22960 	if (ire->ire_stq == NULL) {
22961 		ASSERT(q != NULL);
22962 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22963 		    ire, 0);
22964 		if (ire_need_rele)
22965 			ire_refrele(ire);
22966 		return;
22967 	}
22968 	/*
22969 	 * Everything is done. Send it out on the wire.
22970 	 * We force the insertion of a fragment header using the
22971 	 * IPH_FRAG_HDR flag in two cases:
22972 	 * - after reception of an ICMPv6 "packet too big" message
22973 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22974 	 * - for multirouted IPv6 packets, so that the receiver can
22975 	 *   discard duplicates according to their fragment identifier
22976 	 */
22977 	/* XXX fix flow control problems. */
22978 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22979 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22980 		if (hwaccel) {
22981 			/*
22982 			 * hardware acceleration does not handle these
22983 			 * "slow path" cases.
22984 			 */
22985 			/* IPsec KSTATS: should bump bean counter here. */
22986 			if (ire_need_rele)
22987 				ire_refrele(ire);
22988 			freemsg(ipsec_mp);
22989 			return;
22990 		}
22991 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22992 		    (mp->b_cont ? msgdsize(mp) :
22993 		    mp->b_wptr - (uchar_t *)ip6h)) {
22994 			/* IPsec KSTATS: should bump bean counter here. */
22995 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22996 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22997 			    msgdsize(mp)));
22998 			if (ire_need_rele)
22999 				ire_refrele(ire);
23000 			freemsg(ipsec_mp);
23001 			return;
23002 		}
23003 		ASSERT(mp->b_prev == NULL);
23004 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23005 		    ntohs(ip6h->ip6_plen) +
23006 		    IPV6_HDR_LEN, ire->ire_max_frag));
23007 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23008 		    ire->ire_max_frag);
23009 	} else {
23010 		UPDATE_OB_PKT_COUNT(ire);
23011 		ire->ire_last_used_time = lbolt;
23012 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23013 	}
23014 	if (ire_need_rele)
23015 		ire_refrele(ire);
23016 	freeb(ipsec_mp);
23017 }
23018 
23019 void
23020 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23021 {
23022 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23023 	da_ipsec_t *hada;	/* data attributes */
23024 	ill_t *ill = (ill_t *)q->q_ptr;
23025 
23026 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23027 
23028 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23029 		/* IPsec KSTATS: Bump lose counter here! */
23030 		freemsg(mp);
23031 		return;
23032 	}
23033 
23034 	/*
23035 	 * It's an IPsec packet that must be
23036 	 * accelerated by the Provider, and the
23037 	 * outbound ill is IPsec acceleration capable.
23038 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23039 	 * to the ill.
23040 	 * IPsec KSTATS: should bump packet counter here.
23041 	 */
23042 
23043 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23044 	if (hada_mp == NULL) {
23045 		/* IPsec KSTATS: should bump packet counter here. */
23046 		freemsg(mp);
23047 		return;
23048 	}
23049 
23050 	hada_mp->b_datap->db_type = M_CTL;
23051 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23052 	hada_mp->b_cont = mp;
23053 
23054 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23055 	bzero(hada, sizeof (da_ipsec_t));
23056 	hada->da_type = IPHADA_M_CTL;
23057 
23058 	putnext(q, hada_mp);
23059 }
23060 
23061 /*
23062  * Finish the outbound IPsec processing. This function is called from
23063  * ipsec_out_process() if the IPsec packet was processed
23064  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23065  * asynchronously.
23066  */
23067 void
23068 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23069     ire_t *ire_arg)
23070 {
23071 	uint32_t v_hlen_tos_len;
23072 	ipaddr_t	dst;
23073 	ipif_t	*ipif = NULL;
23074 	ire_t *ire;
23075 	ire_t *ire1 = NULL;
23076 	mblk_t *next_mp = NULL;
23077 	uint32_t max_frag;
23078 	boolean_t multirt_send = B_FALSE;
23079 	mblk_t *mp;
23080 	mblk_t *mp1;
23081 	uint_t	ill_index;
23082 	ipsec_out_t *io;
23083 	boolean_t attach_if;
23084 	int match_flags, offset;
23085 	irb_t *irb = NULL;
23086 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23087 	zoneid_t zoneid;
23088 	uint32_t cksum;
23089 	uint16_t *up;
23090 #ifdef	_BIG_ENDIAN
23091 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23092 #else
23093 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23094 #endif
23095 
23096 	mp = ipsec_mp->b_cont;
23097 	ASSERT(mp != NULL);
23098 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23099 	dst = ipha->ipha_dst;
23100 
23101 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23102 	ill_index = io->ipsec_out_ill_index;
23103 	attach_if = io->ipsec_out_attach_if;
23104 	zoneid = io->ipsec_out_zoneid;
23105 	ASSERT(zoneid != ALL_ZONES);
23106 	match_flags = MATCH_IRE_ILL_GROUP;
23107 	if (ill_index != 0) {
23108 		if (ill == NULL) {
23109 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23110 			    ill_index, B_FALSE);
23111 
23112 			/* Failure case frees things for us. */
23113 			if (ill == NULL)
23114 				return;
23115 
23116 			ill_need_rele = B_TRUE;
23117 		}
23118 		/*
23119 		 * If this packet needs to go out on a particular interface
23120 		 * honor it.
23121 		 */
23122 		if (attach_if) {
23123 			match_flags = MATCH_IRE_ILL;
23124 
23125 			/*
23126 			 * Check if we need an ire that will not be
23127 			 * looked up by anybody else i.e. HIDDEN.
23128 			 */
23129 			if (ill_is_probeonly(ill)) {
23130 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23131 			}
23132 		}
23133 	}
23134 
23135 	if (CLASSD(dst)) {
23136 		boolean_t conn_dontroute;
23137 		/*
23138 		 * Use the ill_index to get the right ipif.
23139 		 */
23140 		conn_dontroute = io->ipsec_out_dontroute;
23141 		if (ill_index == 0)
23142 			ipif = ipif_lookup_group(dst, zoneid);
23143 		else
23144 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23145 		if (ipif == NULL) {
23146 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23147 			    " multicast\n"));
23148 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23149 			freemsg(ipsec_mp);
23150 			goto done;
23151 		}
23152 		/*
23153 		 * ipha_src has already been intialized with the
23154 		 * value of the ipif in ip_wput. All we need now is
23155 		 * an ire to send this downstream.
23156 		 */
23157 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
23158 		if (ire != NULL) {
23159 			ill_t *ill1;
23160 			/*
23161 			 * Do the multicast forwarding now, as the IPSEC
23162 			 * processing has been done.
23163 			 */
23164 			if (ip_g_mrouter && !conn_dontroute &&
23165 			    (ill1 = ire_to_ill(ire))) {
23166 				if (ip_mforward(ill1, ipha, mp)) {
23167 					freemsg(ipsec_mp);
23168 					ip1dbg(("ip_wput_ipsec_out: mforward "
23169 					    "failed\n"));
23170 					ire_refrele(ire);
23171 					goto done;
23172 				}
23173 			}
23174 			goto send;
23175 		}
23176 
23177 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23178 		mp->b_prev = NULL;
23179 		mp->b_next = NULL;
23180 
23181 		/*
23182 		 * If the IPsec packet was processed asynchronously,
23183 		 * drop it now.
23184 		 */
23185 		if (q == NULL) {
23186 			freemsg(ipsec_mp);
23187 			goto done;
23188 		}
23189 
23190 		/*
23191 		 * We may be using a wrong ipif to create the ire.
23192 		 * But it is okay as the source address is assigned
23193 		 * for the packet already. Next outbound packet would
23194 		 * create the IRE with the right IPIF in ip_wput.
23195 		 *
23196 		 * Also handle RTF_MULTIRT routes.
23197 		 */
23198 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
23199 	} else {
23200 		if (attach_if) {
23201 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
23202 			    zoneid, match_flags);
23203 		} else {
23204 			if (ire_arg != NULL) {
23205 				ire = ire_arg;
23206 				ire_need_rele = B_FALSE;
23207 			} else {
23208 				ire = ire_cache_lookup(dst, zoneid);
23209 			}
23210 		}
23211 		if (ire != NULL) {
23212 			goto send;
23213 		}
23214 
23215 		/*
23216 		 * ire disappeared underneath.
23217 		 *
23218 		 * What we need to do here is the ip_newroute
23219 		 * logic to get the ire without doing the IPSEC
23220 		 * processing. Follow the same old path. But this
23221 		 * time, ip_wput or ire_add_then_put will call us
23222 		 * directly as all the IPSEC operations are done.
23223 		 */
23224 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
23225 		mp->b_prev = NULL;
23226 		mp->b_next = NULL;
23227 
23228 		/*
23229 		 * If the IPsec packet was processed asynchronously,
23230 		 * drop it now.
23231 		 */
23232 		if (q == NULL) {
23233 			freemsg(ipsec_mp);
23234 			goto done;
23235 		}
23236 
23237 		/*
23238 		 * Since we're going through ip_newroute() again, we
23239 		 * need to make sure we don't:
23240 		 *
23241 		 *	1.) Trigger the ASSERT() with the ipha_ident
23242 		 *	    overloading.
23243 		 *	2.) Redo transport-layer checksumming, since we've
23244 		 *	    already done all that to get this far.
23245 		 *
23246 		 * The easiest way not do either of the above is to set
23247 		 * the ipha_ident field to IP_HDR_INCLUDED.
23248 		 */
23249 		ipha->ipha_ident = IP_HDR_INCLUDED;
23250 		ip_newroute(q, ipsec_mp, dst, NULL,
23251 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
23252 	}
23253 	goto done;
23254 send:
23255 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
23256 		/*
23257 		 * ESP NAT-Traversal packet.
23258 		 *
23259 		 * Just do software checksum for now.
23260 		 */
23261 
23262 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
23263 		IP_STAT(ip_out_sw_cksum);
23264 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
23265 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
23266 #define	iphs	((uint16_t *)ipha)
23267 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
23268 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
23269 		    IP_SIMPLE_HDR_LENGTH);
23270 #undef iphs
23271 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
23272 			cksum = 0xFFFF;
23273 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
23274 			if (mp1->b_wptr - mp1->b_rptr >=
23275 			    offset + sizeof (uint16_t)) {
23276 				up = (uint16_t *)(mp1->b_rptr + offset);
23277 				*up = cksum;
23278 				break;	/* out of for loop */
23279 			} else {
23280 				offset -= (mp->b_wptr - mp->b_rptr);
23281 			}
23282 	} /* Otherwise, just keep the all-zero checksum. */
23283 
23284 	if (ire->ire_stq == NULL) {
23285 		/*
23286 		 * Loopbacks go through ip_wput_local except for one case.
23287 		 * We come here if we generate a icmp_frag_needed message
23288 		 * after IPSEC processing is over. When this function calls
23289 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
23290 		 * icmp_frag_needed. The message generated comes back here
23291 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
23292 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
23293 		 * source address as it is usually set in ip_wput_ire. As
23294 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
23295 		 * and we end up here. We can't enter ip_wput_ire once the
23296 		 * IPSEC processing is over and hence we need to do it here.
23297 		 */
23298 		ASSERT(q != NULL);
23299 		UPDATE_OB_PKT_COUNT(ire);
23300 		ire->ire_last_used_time = lbolt;
23301 		if (ipha->ipha_src == 0)
23302 			ipha->ipha_src = ire->ire_src_addr;
23303 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
23304 		    ire, 0, zoneid);
23305 		if (ire_need_rele)
23306 			ire_refrele(ire);
23307 		goto done;
23308 	}
23309 
23310 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
23311 		/*
23312 		 * We are through with IPSEC processing.
23313 		 * Fragment this and send it on the wire.
23314 		 */
23315 		if (io->ipsec_out_accelerated) {
23316 			/*
23317 			 * The packet has been accelerated but must
23318 			 * be fragmented. This should not happen
23319 			 * since AH and ESP must not accelerate
23320 			 * packets that need fragmentation, however
23321 			 * the configuration could have changed
23322 			 * since the AH or ESP processing.
23323 			 * Drop packet.
23324 			 * IPsec KSTATS: bump bean counter here.
23325 			 */
23326 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
23327 			    "fragmented accelerated packet!\n"));
23328 			freemsg(ipsec_mp);
23329 		} else {
23330 			ip_wput_ire_fragmentit(ipsec_mp, ire);
23331 		}
23332 		if (ire_need_rele)
23333 			ire_refrele(ire);
23334 		goto done;
23335 	}
23336 
23337 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
23338 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
23339 	    (void *)ire->ire_ipif, (void *)ipif));
23340 
23341 	/*
23342 	 * Multiroute the secured packet, unless IPsec really
23343 	 * requires the packet to go out only through a particular
23344 	 * interface.
23345 	 */
23346 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
23347 		ire_t *first_ire;
23348 		irb = ire->ire_bucket;
23349 		ASSERT(irb != NULL);
23350 		/*
23351 		 * This ire has been looked up as the one that
23352 		 * goes through the given ipif;
23353 		 * make sure we do not omit any other multiroute ire
23354 		 * that may be present in the bucket before this one.
23355 		 */
23356 		IRB_REFHOLD(irb);
23357 		for (first_ire = irb->irb_ire;
23358 		    first_ire != NULL;
23359 		    first_ire = first_ire->ire_next) {
23360 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23361 			    (first_ire->ire_addr == ire->ire_addr) &&
23362 			    !(first_ire->ire_marks &
23363 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23364 				break;
23365 		}
23366 
23367 		if ((first_ire != NULL) && (first_ire != ire)) {
23368 			/*
23369 			 * Don't change the ire if the packet must
23370 			 * be fragmented if sent via this new one.
23371 			 */
23372 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
23373 				IRE_REFHOLD(first_ire);
23374 				if (ire_need_rele)
23375 					ire_refrele(ire);
23376 				else
23377 					ire_need_rele = B_TRUE;
23378 				ire = first_ire;
23379 			}
23380 		}
23381 		IRB_REFRELE(irb);
23382 
23383 		multirt_send = B_TRUE;
23384 		max_frag = ire->ire_max_frag;
23385 	} else {
23386 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
23387 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
23388 			    "flag, attach_if %d\n", attach_if));
23389 		}
23390 	}
23391 
23392 	/*
23393 	 * In most cases, the emission loop below is entered only once.
23394 	 * Only in the case where the ire holds the RTF_MULTIRT
23395 	 * flag, we loop to process all RTF_MULTIRT ires in the
23396 	 * bucket, and send the packet through all crossed
23397 	 * RTF_MULTIRT routes.
23398 	 */
23399 	do {
23400 		if (multirt_send) {
23401 			/*
23402 			 * ire1 holds here the next ire to process in the
23403 			 * bucket. If multirouting is expected,
23404 			 * any non-RTF_MULTIRT ire that has the
23405 			 * right destination address is ignored.
23406 			 */
23407 			ASSERT(irb != NULL);
23408 			IRB_REFHOLD(irb);
23409 			for (ire1 = ire->ire_next;
23410 			    ire1 != NULL;
23411 			    ire1 = ire1->ire_next) {
23412 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23413 					continue;
23414 				if (ire1->ire_addr != ire->ire_addr)
23415 					continue;
23416 				if (ire1->ire_marks &
23417 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23418 					continue;
23419 				/* No loopback here */
23420 				if (ire1->ire_stq == NULL)
23421 					continue;
23422 				/*
23423 				 * Ensure we do not exceed the MTU
23424 				 * of the next route.
23425 				 */
23426 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
23427 					ip_multirt_bad_mtu(ire1, max_frag);
23428 					continue;
23429 				}
23430 
23431 				IRE_REFHOLD(ire1);
23432 				break;
23433 			}
23434 			IRB_REFRELE(irb);
23435 			if (ire1 != NULL) {
23436 				/*
23437 				 * We are in a multiple send case, need to
23438 				 * make a copy of the packet.
23439 				 */
23440 				next_mp = copymsg(ipsec_mp);
23441 				if (next_mp == NULL) {
23442 					ire_refrele(ire1);
23443 					ire1 = NULL;
23444 				}
23445 			}
23446 		}
23447 
23448 		/* Everything is done. Send it out on the wire */
23449 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
23450 		if (mp1 == NULL) {
23451 			BUMP_MIB(&ip_mib, ipOutDiscards);
23452 			freemsg(ipsec_mp);
23453 			if (ire_need_rele)
23454 				ire_refrele(ire);
23455 			if (ire1 != NULL) {
23456 				ire_refrele(ire1);
23457 				freemsg(next_mp);
23458 			}
23459 			goto done;
23460 		}
23461 		UPDATE_OB_PKT_COUNT(ire);
23462 		ire->ire_last_used_time = lbolt;
23463 		if (!io->ipsec_out_accelerated) {
23464 			putnext(ire->ire_stq, mp1);
23465 		} else {
23466 			/*
23467 			 * Safety Pup says: make sure this is going to
23468 			 * the right interface!
23469 			 */
23470 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
23471 			int ifindex = ill1->ill_phyint->phyint_ifindex;
23472 
23473 			if (ifindex != io->ipsec_out_capab_ill_index) {
23474 				/* IPsec kstats: bump lose counter */
23475 				freemsg(mp1);
23476 			} else {
23477 				ipsec_hw_putnext(ire->ire_stq, mp1);
23478 			}
23479 		}
23480 
23481 		freeb(ipsec_mp);
23482 		if (ire_need_rele)
23483 			ire_refrele(ire);
23484 
23485 		if (ire1 != NULL) {
23486 			ire = ire1;
23487 			ire_need_rele = B_TRUE;
23488 			ASSERT(next_mp);
23489 			ipsec_mp = next_mp;
23490 			mp = ipsec_mp->b_cont;
23491 			ire1 = NULL;
23492 			next_mp = NULL;
23493 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
23494 		} else {
23495 			multirt_send = B_FALSE;
23496 		}
23497 	} while (multirt_send);
23498 done:
23499 	if (ill != NULL && ill_need_rele)
23500 		ill_refrele(ill);
23501 	if (ipif != NULL)
23502 		ipif_refrele(ipif);
23503 }
23504 
23505 /*
23506  * Get the ill corresponding to the specified ire, and compare its
23507  * capabilities with the protocol and algorithms specified by the
23508  * the SA obtained from ipsec_out. If they match, annotate the
23509  * ipsec_out structure to indicate that the packet needs acceleration.
23510  *
23511  *
23512  * A packet is eligible for outbound hardware acceleration if the
23513  * following conditions are satisfied:
23514  *
23515  * 1. the packet will not be fragmented
23516  * 2. the provider supports the algorithm
23517  * 3. there is no pending control message being exchanged
23518  * 4. snoop is not attached
23519  * 5. the destination address is not a broadcast or multicast address.
23520  *
23521  * Rationale:
23522  *	- Hardware drivers do not support fragmentation with
23523  *	  the current interface.
23524  *	- snoop, multicast, and broadcast may result in exposure of
23525  *	  a cleartext datagram.
23526  * We check all five of these conditions here.
23527  *
23528  * XXX would like to nuke "ire_t *" parameter here; problem is that
23529  * IRE is only way to figure out if a v4 address is a broadcast and
23530  * thus ineligible for acceleration...
23531  */
23532 static void
23533 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23534 {
23535 	ipsec_out_t *io;
23536 	mblk_t *data_mp;
23537 	uint_t plen, overhead;
23538 
23539 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23540 		return;
23541 
23542 	if (ill == NULL)
23543 		return;
23544 
23545 	/*
23546 	 * Destination address is a broadcast or multicast.  Punt.
23547 	 */
23548 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23549 	    IRE_LOCAL)))
23550 		return;
23551 
23552 	data_mp = ipsec_mp->b_cont;
23553 
23554 	if (ill->ill_isv6) {
23555 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23556 
23557 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23558 			return;
23559 
23560 		plen = ip6h->ip6_plen;
23561 	} else {
23562 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23563 
23564 		if (CLASSD(ipha->ipha_dst))
23565 			return;
23566 
23567 		plen = ipha->ipha_length;
23568 	}
23569 	/*
23570 	 * Is there a pending DLPI control message being exchanged
23571 	 * between IP/IPsec and the DLS Provider? If there is, it
23572 	 * could be a SADB update, and the state of the DLS Provider
23573 	 * SADB might not be in sync with the SADB maintained by
23574 	 * IPsec. To avoid dropping packets or using the wrong keying
23575 	 * material, we do not accelerate this packet.
23576 	 */
23577 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23578 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23579 		    "ill_dlpi_pending! don't accelerate packet\n"));
23580 		return;
23581 	}
23582 
23583 	/*
23584 	 * Is the Provider in promiscous mode? If it does, we don't
23585 	 * accelerate the packet since it will bounce back up to the
23586 	 * listeners in the clear.
23587 	 */
23588 	if (ill->ill_promisc_on_phys) {
23589 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23590 		    "ill in promiscous mode, don't accelerate packet\n"));
23591 		return;
23592 	}
23593 
23594 	/*
23595 	 * Will the packet require fragmentation?
23596 	 */
23597 
23598 	/*
23599 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23600 	 * as is used elsewhere.
23601 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23602 	 *	+ 2-byte trailer
23603 	 */
23604 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23605 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23606 
23607 	if ((plen + overhead) > ill->ill_max_mtu)
23608 		return;
23609 
23610 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23611 
23612 	/*
23613 	 * Can the ill accelerate this IPsec protocol and algorithm
23614 	 * specified by the SA?
23615 	 */
23616 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23617 	    ill->ill_isv6, sa)) {
23618 		return;
23619 	}
23620 
23621 	/*
23622 	 * Tell AH or ESP that the outbound ill is capable of
23623 	 * accelerating this packet.
23624 	 */
23625 	io->ipsec_out_is_capab_ill = B_TRUE;
23626 }
23627 
23628 /*
23629  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23630  *
23631  * If this function returns B_TRUE, the requested SA's have been filled
23632  * into the ipsec_out_*_sa pointers.
23633  *
23634  * If the function returns B_FALSE, the packet has been "consumed", most
23635  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23636  *
23637  * The SA references created by the protocol-specific "select"
23638  * function will be released when the ipsec_mp is freed, thanks to the
23639  * ipsec_out_free destructor -- see spd.c.
23640  */
23641 static boolean_t
23642 ipsec_out_select_sa(mblk_t *ipsec_mp)
23643 {
23644 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23645 	ipsec_out_t *io;
23646 	ipsec_policy_t *pp;
23647 	ipsec_action_t *ap;
23648 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23649 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23650 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23651 
23652 	if (!io->ipsec_out_secure) {
23653 		/*
23654 		 * We came here by mistake.
23655 		 * Don't bother with ipsec processing
23656 		 * We should "discourage" this path in the future.
23657 		 */
23658 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23659 		return (B_FALSE);
23660 	}
23661 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23662 	ASSERT((io->ipsec_out_policy != NULL) ||
23663 	    (io->ipsec_out_act != NULL));
23664 
23665 	ASSERT(io->ipsec_out_failed == B_FALSE);
23666 
23667 	/*
23668 	 * IPSEC processing has started.
23669 	 */
23670 	io->ipsec_out_proc_begin = B_TRUE;
23671 	ap = io->ipsec_out_act;
23672 	if (ap == NULL) {
23673 		pp = io->ipsec_out_policy;
23674 		ASSERT(pp != NULL);
23675 		ap = pp->ipsp_act;
23676 		ASSERT(ap != NULL);
23677 	}
23678 
23679 	/*
23680 	 * We have an action.  now, let's select SA's.
23681 	 * (In the future, we can cache this in the conn_t..)
23682 	 */
23683 	if (ap->ipa_want_esp) {
23684 		if (io->ipsec_out_esp_sa == NULL) {
23685 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23686 			    IPPROTO_ESP);
23687 		}
23688 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23689 	}
23690 
23691 	if (ap->ipa_want_ah) {
23692 		if (io->ipsec_out_ah_sa == NULL) {
23693 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23694 			    IPPROTO_AH);
23695 		}
23696 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23697 		/*
23698 		 * The ESP and AH processing order needs to be preserved
23699 		 * when both protocols are required (ESP should be applied
23700 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23701 		 * when both ESP and AH are required, and an AH ACQUIRE
23702 		 * is needed.
23703 		 */
23704 		if (ap->ipa_want_esp && need_ah_acquire)
23705 			need_esp_acquire = B_TRUE;
23706 	}
23707 
23708 	/*
23709 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23710 	 * Release SAs that got referenced, but will not be used until we
23711 	 * acquire _all_ of the SAs we need.
23712 	 */
23713 	if (need_ah_acquire || need_esp_acquire) {
23714 		if (io->ipsec_out_ah_sa != NULL) {
23715 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23716 			io->ipsec_out_ah_sa = NULL;
23717 		}
23718 		if (io->ipsec_out_esp_sa != NULL) {
23719 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23720 			io->ipsec_out_esp_sa = NULL;
23721 		}
23722 
23723 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23724 		return (B_FALSE);
23725 	}
23726 
23727 	return (B_TRUE);
23728 }
23729 
23730 /*
23731  * Process an IPSEC_OUT message and see what you can
23732  * do with it.
23733  * IPQoS Notes:
23734  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23735  * IPSec.
23736  * XXX would like to nuke ire_t.
23737  * XXX ill_index better be "real"
23738  */
23739 void
23740 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23741 {
23742 	ipsec_out_t *io;
23743 	ipsec_policy_t *pp;
23744 	ipsec_action_t *ap;
23745 	ipha_t *ipha;
23746 	ip6_t *ip6h;
23747 	mblk_t *mp;
23748 	ill_t *ill;
23749 	zoneid_t zoneid;
23750 	ipsec_status_t ipsec_rc;
23751 	boolean_t ill_need_rele = B_FALSE;
23752 
23753 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23754 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23755 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23756 	mp = ipsec_mp->b_cont;
23757 
23758 	/*
23759 	 * Initiate IPPF processing. We do it here to account for packets
23760 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23761 	 * We can check for ipsec_out_proc_begin even for such packets, as
23762 	 * they will always be false (asserted below).
23763 	 */
23764 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23765 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23766 		    io->ipsec_out_ill_index : ill_index);
23767 		if (mp == NULL) {
23768 			ip2dbg(("ipsec_out_process: packet dropped "\
23769 			    "during IPPF processing\n"));
23770 			freeb(ipsec_mp);
23771 			BUMP_MIB(&ip_mib, ipOutDiscards);
23772 			return;
23773 		}
23774 	}
23775 
23776 	if (!io->ipsec_out_secure) {
23777 		/*
23778 		 * We came here by mistake.
23779 		 * Don't bother with ipsec processing
23780 		 * Should "discourage" this path in the future.
23781 		 */
23782 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23783 		goto done;
23784 	}
23785 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23786 	ASSERT((io->ipsec_out_policy != NULL) ||
23787 	    (io->ipsec_out_act != NULL));
23788 	ASSERT(io->ipsec_out_failed == B_FALSE);
23789 
23790 	if (!ipsec_loaded()) {
23791 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23792 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23793 			BUMP_MIB(&ip_mib, ipOutDiscards);
23794 		} else {
23795 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23796 		}
23797 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23798 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23799 		return;
23800 	}
23801 
23802 	/*
23803 	 * IPSEC processing has started.
23804 	 */
23805 	io->ipsec_out_proc_begin = B_TRUE;
23806 	ap = io->ipsec_out_act;
23807 	if (ap == NULL) {
23808 		pp = io->ipsec_out_policy;
23809 		ASSERT(pp != NULL);
23810 		ap = pp->ipsp_act;
23811 		ASSERT(ap != NULL);
23812 	}
23813 
23814 	/*
23815 	 * Save the outbound ill index. When the packet comes back
23816 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23817 	 * before sending it the accelerated packet.
23818 	 */
23819 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23820 		int ifindex;
23821 		ill = ire_to_ill(ire);
23822 		ifindex = ill->ill_phyint->phyint_ifindex;
23823 		io->ipsec_out_capab_ill_index = ifindex;
23824 	}
23825 
23826 	/*
23827 	 * The order of processing is first insert a IP header if needed.
23828 	 * Then insert the ESP header and then the AH header.
23829 	 */
23830 	if ((io->ipsec_out_se_done == B_FALSE) &&
23831 	    (ap->ipa_want_se)) {
23832 		/*
23833 		 * First get the outer IP header before sending
23834 		 * it to ESP.
23835 		 */
23836 		ipha_t *oipha, *iipha;
23837 		mblk_t *outer_mp, *inner_mp;
23838 
23839 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23840 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23841 			    "ipsec_out_process: "
23842 			    "Self-Encapsulation failed: Out of memory\n");
23843 			freemsg(ipsec_mp);
23844 			BUMP_MIB(&ip_mib, ipOutDiscards);
23845 			return;
23846 		}
23847 		inner_mp = ipsec_mp->b_cont;
23848 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23849 		oipha = (ipha_t *)outer_mp->b_rptr;
23850 		iipha = (ipha_t *)inner_mp->b_rptr;
23851 		*oipha = *iipha;
23852 		outer_mp->b_wptr += sizeof (ipha_t);
23853 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23854 		    sizeof (ipha_t));
23855 		oipha->ipha_protocol = IPPROTO_ENCAP;
23856 		oipha->ipha_version_and_hdr_length =
23857 		    IP_SIMPLE_HDR_VERSION;
23858 		oipha->ipha_hdr_checksum = 0;
23859 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23860 		outer_mp->b_cont = inner_mp;
23861 		ipsec_mp->b_cont = outer_mp;
23862 
23863 		io->ipsec_out_se_done = B_TRUE;
23864 		io->ipsec_out_encaps = B_TRUE;
23865 	}
23866 
23867 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23868 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23869 	    !ipsec_out_select_sa(ipsec_mp))
23870 		return;
23871 
23872 	/*
23873 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23874 	 * to do the heavy lifting.
23875 	 */
23876 	zoneid = io->ipsec_out_zoneid;
23877 	ASSERT(zoneid != ALL_ZONES);
23878 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23879 		ASSERT(io->ipsec_out_esp_sa != NULL);
23880 		io->ipsec_out_esp_done = B_TRUE;
23881 		/*
23882 		 * Note that since hw accel can only apply one transform,
23883 		 * not two, we skip hw accel for ESP if we also have AH
23884 		 * This is an design limitation of the interface
23885 		 * which should be revisited.
23886 		 */
23887 		ASSERT(ire != NULL);
23888 		if (io->ipsec_out_ah_sa == NULL) {
23889 			ill = (ill_t *)ire->ire_stq->q_ptr;
23890 			ipsec_out_is_accelerated(ipsec_mp,
23891 			    io->ipsec_out_esp_sa, ill, ire);
23892 		}
23893 
23894 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23895 		switch (ipsec_rc) {
23896 		case IPSEC_STATUS_SUCCESS:
23897 			break;
23898 		case IPSEC_STATUS_FAILED:
23899 			BUMP_MIB(&ip_mib, ipOutDiscards);
23900 			/* FALLTHRU */
23901 		case IPSEC_STATUS_PENDING:
23902 			return;
23903 		}
23904 	}
23905 
23906 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23907 		ASSERT(io->ipsec_out_ah_sa != NULL);
23908 		io->ipsec_out_ah_done = B_TRUE;
23909 		if (ire == NULL) {
23910 			int idx = io->ipsec_out_capab_ill_index;
23911 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23912 			    NULL, NULL, NULL, NULL);
23913 			ill_need_rele = B_TRUE;
23914 		} else {
23915 			ill = (ill_t *)ire->ire_stq->q_ptr;
23916 		}
23917 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23918 		    ire);
23919 
23920 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23921 		switch (ipsec_rc) {
23922 		case IPSEC_STATUS_SUCCESS:
23923 			break;
23924 		case IPSEC_STATUS_FAILED:
23925 			BUMP_MIB(&ip_mib, ipOutDiscards);
23926 			/* FALLTHRU */
23927 		case IPSEC_STATUS_PENDING:
23928 			if (ill != NULL && ill_need_rele)
23929 				ill_refrele(ill);
23930 			return;
23931 		}
23932 	}
23933 	/*
23934 	 * We are done with IPSEC processing. Send it over
23935 	 * the wire.
23936 	 */
23937 done:
23938 	mp = ipsec_mp->b_cont;
23939 	ipha = (ipha_t *)mp->b_rptr;
23940 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23941 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23942 	} else {
23943 		ip6h = (ip6_t *)ipha;
23944 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23945 	}
23946 	if (ill != NULL && ill_need_rele)
23947 		ill_refrele(ill);
23948 }
23949 
23950 /* ARGSUSED */
23951 void
23952 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23953 {
23954 	opt_restart_t	*or;
23955 	int	err;
23956 	conn_t	*connp;
23957 
23958 	ASSERT(CONN_Q(q));
23959 	connp = Q_TO_CONN(q);
23960 
23961 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23962 	or = (opt_restart_t *)first_mp->b_rptr;
23963 	/*
23964 	 * We don't need to pass any credentials here since this is just
23965 	 * a restart. The credentials are passed in when svr4_optcom_req
23966 	 * is called the first time (from ip_wput_nondata).
23967 	 */
23968 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23969 		err = svr4_optcom_req(q, first_mp, NULL,
23970 		    &ip_opt_obj);
23971 	} else {
23972 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23973 		err = tpi_optcom_req(q, first_mp, NULL,
23974 		    &ip_opt_obj);
23975 	}
23976 	if (err != EINPROGRESS) {
23977 		/* operation is done */
23978 		CONN_OPER_PENDING_DONE(connp);
23979 	}
23980 }
23981 
23982 /*
23983  * ioctls that go through a down/up sequence may need to wait for the down
23984  * to complete. This involves waiting for the ire and ipif refcnts to go down
23985  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23986  */
23987 /* ARGSUSED */
23988 void
23989 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23990 {
23991 	struct iocblk *iocp;
23992 	mblk_t *mp1;
23993 	ipif_t	*ipif;
23994 	ip_ioctl_cmd_t *ipip;
23995 	int err;
23996 	sin_t	*sin;
23997 	struct lifreq *lifr;
23998 	struct ifreq *ifr;
23999 
24000 	iocp = (struct iocblk *)mp->b_rptr;
24001 	ASSERT(ipsq != NULL);
24002 	/* Existence of mp1 verified in ip_wput_nondata */
24003 	mp1 = mp->b_cont->b_cont;
24004 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24005 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24006 		ill_t *ill;
24007 		/*
24008 		 * Special case where ipsq_current_ipif may not be set.
24009 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24010 		 * ill could also have become part of a ipmp group in the
24011 		 * process, we are here as were not able to complete the
24012 		 * operation in ipif_set_values because we could not become
24013 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24014 		 * will not be set so we need to set it.
24015 		 */
24016 		ill = (ill_t *)q->q_ptr;
24017 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24018 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24019 	}
24020 
24021 	ipif = ipsq->ipsq_current_ipif;
24022 	ASSERT(ipif != NULL);
24023 	if (ipip->ipi_cmd_type == IF_CMD) {
24024 		/* This a old style SIOC[GS]IF* command */
24025 		ifr = (struct ifreq *)mp1->b_rptr;
24026 		sin = (sin_t *)&ifr->ifr_addr;
24027 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24028 		/* This a new style SIOC[GS]LIF* command */
24029 		lifr = (struct lifreq *)mp1->b_rptr;
24030 		sin = (sin_t *)&lifr->lifr_addr;
24031 	} else {
24032 		sin = NULL;
24033 	}
24034 
24035 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24036 	    (void *)mp1->b_rptr);
24037 
24038 	/* SIOCLIFREMOVEIF could have removed the ipif */
24039 	ip_ioctl_finish(q, mp, err,
24040 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24041 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24042 }
24043 
24044 /*
24045  * ioctl processing
24046  *
24047  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24048  * the ioctl command in the ioctl tables and determines the copyin data size
24049  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24050  * size.
24051  *
24052  * ioctl processing then continues when the M_IOCDATA makes its way down.
24053  * Now the ioctl is looked up again in the ioctl table, and its properties are
24054  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24055  * and the general ioctl processing function ip_process_ioctl is called.
24056  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24057  * so goes thru the serialization primitive ipsq_try_enter. Then the
24058  * appropriate function to handle the ioctl is called based on the entry in
24059  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24060  * which also refreleases the 'conn' that was refheld at the start of the
24061  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24062  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24063  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24064  *
24065  * Many exclusive ioctls go thru an internal down up sequence as part of
24066  * the operation. For example an attempt to change the IP address of an
24067  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24068  * does all the cleanup such as deleting all ires that use this address.
24069  * Then we need to wait till all references to the interface go away.
24070  */
24071 void
24072 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24073 {
24074 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24075 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24076 	cmd_info_t ci;
24077 	int err;
24078 	boolean_t entered_ipsq = B_FALSE;
24079 
24080 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24081 
24082 	if (ipip == NULL)
24083 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24084 
24085 	/*
24086 	 * SIOCLIFADDIF needs to go thru a special path since the
24087 	 * ill may not exist yet. This happens in the case of lo0
24088 	 * which is created using this ioctl.
24089 	 */
24090 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24091 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24092 		ip_ioctl_finish(q, mp, err,
24093 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24094 		    NULL, NULL);
24095 		return;
24096 	}
24097 
24098 	ci.ci_ipif = NULL;
24099 	switch (ipip->ipi_cmd_type) {
24100 	case IF_CMD:
24101 	case LIF_CMD:
24102 		/*
24103 		 * ioctls that pass in a [l]ifreq appear here.
24104 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24105 		 * ci.ci_ipif
24106 		 */
24107 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24108 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24109 		if (err != 0) {
24110 			ip_ioctl_finish(q, mp, err,
24111 			    ipip->ipi_flags & IPI_GET_CMD ?
24112 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24113 			return;
24114 		}
24115 		ASSERT(ci.ci_ipif != NULL);
24116 		break;
24117 
24118 	case TUN_CMD:
24119 		/*
24120 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24121 		 * a refheld ipif in ci.ci_ipif
24122 		 */
24123 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24124 		if (err != 0) {
24125 			ip_ioctl_finish(q, mp, err,
24126 			    ipip->ipi_flags & IPI_GET_CMD ?
24127 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24128 			return;
24129 		}
24130 		ASSERT(ci.ci_ipif != NULL);
24131 		break;
24132 
24133 	case MISC_CMD:
24134 		/*
24135 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24136 		 * For eg. SIOCGLIFCONF will appear here.
24137 		 */
24138 		switch (ipip->ipi_cmd) {
24139 		case IF_UNITSEL:
24140 			/* ioctl comes down the ill */
24141 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24142 			ipif_refhold(ci.ci_ipif);
24143 			break;
24144 		case SIOCGMSFILTER:
24145 		case SIOCSMSFILTER:
24146 		case SIOCGIPMSFILTER:
24147 		case SIOCSIPMSFILTER:
24148 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24149 			    ip_process_ioctl);
24150 			if (err != 0) {
24151 				ip_ioctl_finish(q, mp, err,
24152 				    ipip->ipi_flags & IPI_GET_CMD ?
24153 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24154 				return;
24155 			}
24156 			break;
24157 		}
24158 		err = 0;
24159 		ci.ci_sin = NULL;
24160 		ci.ci_sin6 = NULL;
24161 		ci.ci_lifr = NULL;
24162 		break;
24163 	}
24164 
24165 	/*
24166 	 * If ipsq is non-null, we are already being called exclusively
24167 	 */
24168 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24169 	if (!(ipip->ipi_flags & IPI_WR)) {
24170 		/*
24171 		 * A return value of EINPROGRESS means the ioctl is
24172 		 * either queued and waiting for some reason or has
24173 		 * already completed.
24174 		 */
24175 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24176 		    ci.ci_lifr);
24177 		if (ci.ci_ipif != NULL)
24178 			ipif_refrele(ci.ci_ipif);
24179 		ip_ioctl_finish(q, mp, err,
24180 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24181 		    NULL, NULL);
24182 		return;
24183 	}
24184 
24185 	ASSERT(ci.ci_ipif != NULL);
24186 
24187 	if (ipsq == NULL) {
24188 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
24189 		    ip_process_ioctl, NEW_OP, B_TRUE);
24190 		entered_ipsq = B_TRUE;
24191 	}
24192 	/*
24193 	 * Release the ipif so that ipif_down and friends that wait for
24194 	 * references to go away are not misled about the current ipif_refcnt
24195 	 * values. We are writer so we can access the ipif even after releasing
24196 	 * the ipif.
24197 	 */
24198 	ipif_refrele(ci.ci_ipif);
24199 	if (ipsq == NULL)
24200 		return;
24201 
24202 	mutex_enter(&ipsq->ipsq_lock);
24203 	ASSERT(ipsq->ipsq_current_ipif == NULL);
24204 	ipsq->ipsq_current_ipif = ci.ci_ipif;
24205 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24206 	mutex_exit(&ipsq->ipsq_lock);
24207 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
24208 	/*
24209 	 * For most set ioctls that come here, this serves as a single point
24210 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
24211 	 * be any new references to the ipif. This helps functions that go
24212 	 * through this path and end up trying to wait for the refcnts
24213 	 * associated with the ipif to go down to zero. Some exceptions are
24214 	 * Failover, Failback, and Groupname commands that operate on more than
24215 	 * just the ci.ci_ipif. These commands internally determine the
24216 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
24217 	 * flags on that set. Another exception is the Removeif command that
24218 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
24219 	 * ipif to operate on.
24220 	 */
24221 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
24222 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
24223 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
24224 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
24225 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
24226 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
24227 
24228 	/*
24229 	 * A return value of EINPROGRESS means the ioctl is
24230 	 * either queued and waiting for some reason or has
24231 	 * already completed.
24232 	 */
24233 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24234 	    ci.ci_lifr);
24235 
24236 	/* SIOCLIFREMOVEIF could have removed the ipif */
24237 	ip_ioctl_finish(q, mp, err,
24238 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24239 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
24240 
24241 	if (entered_ipsq)
24242 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
24243 }
24244 
24245 /*
24246  * Complete the ioctl. Typically ioctls use the mi package and need to
24247  * do mi_copyout/mi_copy_done.
24248  */
24249 void
24250 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
24251     ipif_t *ipif, ipsq_t *ipsq)
24252 {
24253 	conn_t	*connp = NULL;
24254 
24255 	if (err == EINPROGRESS)
24256 		return;
24257 
24258 	if (CONN_Q(q)) {
24259 		connp = Q_TO_CONN(q);
24260 		ASSERT(connp->conn_ref >= 2);
24261 	}
24262 
24263 	switch (mode) {
24264 	case COPYOUT:
24265 		if (err == 0)
24266 			mi_copyout(q, mp);
24267 		else
24268 			mi_copy_done(q, mp, err);
24269 		break;
24270 
24271 	case NO_COPYOUT:
24272 		mi_copy_done(q, mp, err);
24273 		break;
24274 
24275 	default:
24276 		/* An ioctl aborted through a conn close would take this path */
24277 		break;
24278 	}
24279 
24280 	/*
24281 	 * The refhold placed at the start of the ioctl is released here.
24282 	 */
24283 	if (connp != NULL)
24284 		CONN_OPER_PENDING_DONE(connp);
24285 
24286 	/*
24287 	 * If the ioctl were an exclusive ioctl it would have set
24288 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
24289 	 */
24290 	if (ipif != NULL) {
24291 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
24292 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
24293 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
24294 	}
24295 
24296 	/*
24297 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
24298 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
24299 	 * entering the ipsq
24300 	 */
24301 	if (ipsq != NULL) {
24302 		mutex_enter(&ipsq->ipsq_lock);
24303 		ipsq->ipsq_current_ipif = NULL;
24304 		mutex_exit(&ipsq->ipsq_lock);
24305 	}
24306 }
24307 
24308 /*
24309  * This is called from ip_wput_nondata to resume a deferred TCP bind.
24310  */
24311 /* ARGSUSED */
24312 void
24313 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
24314 {
24315 	conn_t *connp = arg;
24316 	tcp_t	*tcp;
24317 
24318 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
24319 	tcp = connp->conn_tcp;
24320 
24321 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
24322 		freemsg(mp);
24323 	else
24324 		tcp_rput_other(tcp, mp);
24325 	CONN_OPER_PENDING_DONE(connp);
24326 }
24327 
24328 /* Called from ip_wput for all non data messages */
24329 /* ARGSUSED */
24330 void
24331 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24332 {
24333 	mblk_t		*mp1;
24334 	ire_t		*ire;
24335 	ill_t		*ill;
24336 	struct iocblk	*iocp;
24337 	ip_ioctl_cmd_t	*ipip;
24338 	cred_t		*cr;
24339 	conn_t		*connp = NULL;
24340 	int		cmd, err;
24341 
24342 	if (CONN_Q(q))
24343 		connp = Q_TO_CONN(q);
24344 
24345 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
24346 
24347 	/* Check if it is a queue to /dev/sctp. */
24348 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
24349 	    connp->conn_rq == NULL) {
24350 		sctp_wput(q, mp);
24351 		return;
24352 	}
24353 
24354 	switch (DB_TYPE(mp)) {
24355 	case M_IOCTL:
24356 		/*
24357 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
24358 		 * will arrange to copy in associated control structures.
24359 		 */
24360 		ip_sioctl_copyin_setup(q, mp);
24361 		return;
24362 	case M_IOCDATA:
24363 		/*
24364 		 * Ensure that this is associated with one of our trans-
24365 		 * parent ioctls.  If it's not ours, discard it if we're
24366 		 * running as a driver, or pass it on if we're a module.
24367 		 */
24368 		iocp = (struct iocblk *)mp->b_rptr;
24369 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24370 		if (ipip == NULL) {
24371 			if (q->q_next == NULL) {
24372 				goto nak;
24373 			} else {
24374 				putnext(q, mp);
24375 			}
24376 			return;
24377 		} else if ((q->q_next != NULL) &&
24378 		    !(ipip->ipi_flags & IPI_MODOK)) {
24379 			/*
24380 			 * the ioctl is one we recognise, but is not
24381 			 * consumed by IP as a module, pass M_IOCDATA
24382 			 * for processing downstream, but only for
24383 			 * common Streams ioctls.
24384 			 */
24385 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
24386 				putnext(q, mp);
24387 				return;
24388 			} else {
24389 				goto nak;
24390 			}
24391 		}
24392 
24393 		/* IOCTL continuation following copyin or copyout. */
24394 		if (mi_copy_state(q, mp, NULL) == -1) {
24395 			/*
24396 			 * The copy operation failed.  mi_copy_state already
24397 			 * cleaned up, so we're out of here.
24398 			 */
24399 			return;
24400 		}
24401 		/*
24402 		 * If we just completed a copy in, we become writer and
24403 		 * continue processing in ip_sioctl_copyin_done.  If it
24404 		 * was a copy out, we call mi_copyout again.  If there is
24405 		 * nothing more to copy out, it will complete the IOCTL.
24406 		 */
24407 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
24408 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
24409 				mi_copy_done(q, mp, EPROTO);
24410 				return;
24411 			}
24412 			/*
24413 			 * Check for cases that need more copying.  A return
24414 			 * value of 0 means a second copyin has been started,
24415 			 * so we return; a return value of 1 means no more
24416 			 * copying is needed, so we continue.
24417 			 */
24418 			cmd = iocp->ioc_cmd;
24419 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
24420 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
24421 			    MI_COPY_COUNT(mp) == 1) {
24422 				if (ip_copyin_msfilter(q, mp) == 0)
24423 					return;
24424 			}
24425 			/*
24426 			 * Refhold the conn, till the ioctl completes. This is
24427 			 * needed in case the ioctl ends up in the pending mp
24428 			 * list. Every mp in the ill_pending_mp list and
24429 			 * the ipsq_pending_mp must have a refhold on the conn
24430 			 * to resume processing. The refhold is released when
24431 			 * the ioctl completes. (normally or abnormally)
24432 			 * In all cases ip_ioctl_finish is called to finish
24433 			 * the ioctl.
24434 			 */
24435 			if (connp != NULL) {
24436 				/* This is not a reentry */
24437 				ASSERT(ipsq == NULL);
24438 				CONN_INC_REF(connp);
24439 			} else {
24440 				if (!(ipip->ipi_flags & IPI_MODOK)) {
24441 					mi_copy_done(q, mp, EINVAL);
24442 					return;
24443 				}
24444 			}
24445 
24446 			ip_process_ioctl(ipsq, q, mp, ipip);
24447 
24448 		} else {
24449 			mi_copyout(q, mp);
24450 		}
24451 		return;
24452 nak:
24453 		iocp->ioc_error = EINVAL;
24454 		mp->b_datap->db_type = M_IOCNAK;
24455 		iocp->ioc_count = 0;
24456 		qreply(q, mp);
24457 		return;
24458 
24459 	case M_IOCNAK:
24460 		/*
24461 		 * The only way we could get here is if a resolver didn't like
24462 		 * an IOCTL we sent it.	 This shouldn't happen.
24463 		 */
24464 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
24465 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
24466 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
24467 		freemsg(mp);
24468 		return;
24469 	case M_IOCACK:
24470 		/* Finish socket ioctls passed through to ARP. */
24471 		ip_sioctl_iocack(q, mp);
24472 		return;
24473 	case M_FLUSH:
24474 		if (*mp->b_rptr & FLUSHW)
24475 			flushq(q, FLUSHALL);
24476 		if (q->q_next) {
24477 			/*
24478 			 * M_FLUSH is sent up to IP by some drivers during
24479 			 * unbind. ip_rput has already replied to it. We are
24480 			 * here for the M_FLUSH that we originated in IP
24481 			 * before sending the unbind request to the driver.
24482 			 * Just free it as we don't queue packets in IP
24483 			 * on the write side of the device instance.
24484 			 */
24485 			freemsg(mp);
24486 			return;
24487 		}
24488 		if (*mp->b_rptr & FLUSHR) {
24489 			*mp->b_rptr &= ~FLUSHW;
24490 			qreply(q, mp);
24491 			return;
24492 		}
24493 		freemsg(mp);
24494 		return;
24495 	case IRE_DB_REQ_TYPE:
24496 		/* An Upper Level Protocol wants a copy of an IRE. */
24497 		ip_ire_req(q, mp);
24498 		return;
24499 	case M_CTL:
24500 		/* M_CTL messages are used by ARP to tell us things. */
24501 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
24502 			break;
24503 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
24504 		case AR_ENTRY_SQUERY:
24505 			ip_wput_ctl(q, mp);
24506 			return;
24507 		case AR_CLIENT_NOTIFY:
24508 			ip_arp_news(q, mp);
24509 			return;
24510 		case AR_DLPIOP_DONE:
24511 			ASSERT(q->q_next != NULL);
24512 			ill = (ill_t *)q->q_ptr;
24513 			/* qwriter_ip releases the refhold */
24514 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24515 			ill_refhold(ill);
24516 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24517 			    CUR_OP, B_FALSE);
24518 			return;
24519 		case AR_ARP_CLOSING:
24520 			/*
24521 			 * ARP (above us) is closing. If no ARP bringup is
24522 			 * currently pending, ack the message so that ARP
24523 			 * can complete its close. Also mark ill_arp_closing
24524 			 * so that new ARP bringups will fail. If any
24525 			 * ARP bringup is currently in progress, we will
24526 			 * ack this when the current ARP bringup completes.
24527 			 */
24528 			ASSERT(q->q_next != NULL);
24529 			ill = (ill_t *)q->q_ptr;
24530 			mutex_enter(&ill->ill_lock);
24531 			ill->ill_arp_closing = 1;
24532 			if (!ill->ill_arp_bringup_pending) {
24533 				mutex_exit(&ill->ill_lock);
24534 				qreply(q, mp);
24535 			} else {
24536 				mutex_exit(&ill->ill_lock);
24537 				freemsg(mp);
24538 			}
24539 			return;
24540 		default:
24541 			break;
24542 		}
24543 		break;
24544 	case M_PROTO:
24545 	case M_PCPROTO:
24546 		/*
24547 		 * The only PROTO messages we expect are ULP binds and
24548 		 * copies of option negotiation acknowledgements.
24549 		 */
24550 		switch (((union T_primitives *)mp->b_rptr)->type) {
24551 		case O_T_BIND_REQ:
24552 		case T_BIND_REQ: {
24553 			/* Request can get queued in bind */
24554 			ASSERT(connp != NULL);
24555 			/*
24556 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
24557 			 * instead of going through this path.  We only get
24558 			 * here in the following cases:
24559 			 *
24560 			 * a. Bind retries, where ipsq is non-NULL.
24561 			 * b. T_BIND_REQ is issued from non TCP/UDP
24562 			 *    transport, e.g. icmp for raw socket,
24563 			 *    in which case ipsq will be NULL.
24564 			 */
24565 			ASSERT(ipsq != NULL ||
24566 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
24567 
24568 			/* Don't increment refcnt if this is a re-entry */
24569 			if (ipsq == NULL)
24570 				CONN_INC_REF(connp);
24571 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
24572 			    connp, NULL) : ip_bind_v4(q, mp, connp);
24573 			if (mp == NULL)
24574 				return;
24575 			if (IPCL_IS_TCP(connp)) {
24576 				/*
24577 				 * In the case of TCP endpoint we
24578 				 * come here only for bind retries
24579 				 */
24580 				ASSERT(ipsq != NULL);
24581 				CONN_INC_REF(connp);
24582 				squeue_fill(connp->conn_sqp, mp,
24583 				    ip_resume_tcp_bind, connp,
24584 				    SQTAG_BIND_RETRY);
24585 				return;
24586 			} else if (IPCL_IS_UDP(connp)) {
24587 				/*
24588 				 * In the case of UDP endpoint we
24589 				 * come here only for bind retries
24590 				 */
24591 				ASSERT(ipsq != NULL);
24592 				udp_resume_bind(connp, mp);
24593 				return;
24594 			}
24595 			qreply(q, mp);
24596 			CONN_OPER_PENDING_DONE(connp);
24597 			return;
24598 		}
24599 		case T_SVR4_OPTMGMT_REQ:
24600 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24601 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24602 
24603 			ASSERT(connp != NULL);
24604 			if (!snmpcom_req(q, mp, ip_snmp_set,
24605 			    ip_snmp_get, cr)) {
24606 				/*
24607 				 * Call svr4_optcom_req so that it can
24608 				 * generate the ack. We don't come here
24609 				 * if this operation is being restarted.
24610 				 * ip_restart_optmgmt will drop the conn ref.
24611 				 * In the case of ipsec option after the ipsec
24612 				 * load is complete conn_restart_ipsec_waiter
24613 				 * drops the conn ref.
24614 				 */
24615 				ASSERT(ipsq == NULL);
24616 				CONN_INC_REF(connp);
24617 				if (ip_check_for_ipsec_opt(q, mp))
24618 					return;
24619 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24620 				if (err != EINPROGRESS) {
24621 					/* Operation is done */
24622 					CONN_OPER_PENDING_DONE(connp);
24623 				}
24624 			}
24625 			return;
24626 		case T_OPTMGMT_REQ:
24627 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24628 			/*
24629 			 * Note: No snmpcom_req support through new
24630 			 * T_OPTMGMT_REQ.
24631 			 * Call tpi_optcom_req so that it can
24632 			 * generate the ack.
24633 			 */
24634 			ASSERT(connp != NULL);
24635 			ASSERT(ipsq == NULL);
24636 			/*
24637 			 * We don't come here for restart. ip_restart_optmgmt
24638 			 * will drop the conn ref. In the case of ipsec option
24639 			 * after the ipsec load is complete
24640 			 * conn_restart_ipsec_waiter drops the conn ref.
24641 			 */
24642 			CONN_INC_REF(connp);
24643 			if (ip_check_for_ipsec_opt(q, mp))
24644 				return;
24645 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24646 			if (err != EINPROGRESS) {
24647 				/* Operation is done */
24648 				CONN_OPER_PENDING_DONE(connp);
24649 			}
24650 			return;
24651 		case T_UNBIND_REQ:
24652 			mp = ip_unbind(q, mp);
24653 			qreply(q, mp);
24654 			return;
24655 		default:
24656 			/*
24657 			 * Have to drop any DLPI messages coming down from
24658 			 * arp (such as an info_req which would cause ip
24659 			 * to receive an extra info_ack if it was passed
24660 			 * through.
24661 			 */
24662 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24663 			    (int)*(uint_t *)mp->b_rptr));
24664 			freemsg(mp);
24665 			return;
24666 		}
24667 		/* NOTREACHED */
24668 	case IRE_DB_TYPE: {
24669 		nce_t		*nce;
24670 		ill_t		*ill;
24671 		in6_addr_t	gw_addr_v6;
24672 
24673 
24674 		/*
24675 		 * This is a response back from a resolver.  It
24676 		 * consists of a message chain containing:
24677 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24678 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24679 		 * The LL_HDR_MBLK is the DLPI header to use to get
24680 		 * the attached packet, and subsequent ones for the
24681 		 * same destination, transmitted.
24682 		 */
24683 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24684 			break;
24685 		/*
24686 		 * First, check to make sure the resolution succeeded.
24687 		 * If it failed, the second mblk will be empty.
24688 		 * If it is, free the chain, dropping the packet.
24689 		 * (We must ire_delete the ire; that frees the ire mblk)
24690 		 * We're doing this now to support PVCs for ATM; it's
24691 		 * a partial xresolv implementation. When we fully implement
24692 		 * xresolv interfaces, instead of freeing everything here
24693 		 * we'll initiate neighbor discovery.
24694 		 *
24695 		 * For v4 (ARP and other external resolvers) the resolver
24696 		 * frees the message, so no check is needed. This check
24697 		 * is required, though, for a full xresolve implementation.
24698 		 * Including this code here now both shows how external
24699 		 * resolvers can NACK a resolution request using an
24700 		 * existing design that has no specific provisions for NACKs,
24701 		 * and also takes into account that the current non-ARP
24702 		 * external resolver has been coded to use this method of
24703 		 * NACKing for all IPv6 (xresolv) cases,
24704 		 * whether our xresolv implementation is complete or not.
24705 		 *
24706 		 */
24707 		ire = (ire_t *)mp->b_rptr;
24708 		ill = ire_to_ill(ire);
24709 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24710 		if (mp1->b_rptr == mp1->b_wptr) {
24711 			if (ire->ire_ipversion == IPV6_VERSION) {
24712 				/*
24713 				 * XRESOLV interface.
24714 				 */
24715 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24716 				mutex_enter(&ire->ire_lock);
24717 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24718 				mutex_exit(&ire->ire_lock);
24719 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24720 					nce = ndp_lookup(ill,
24721 					    &ire->ire_addr_v6, B_FALSE);
24722 				} else {
24723 					nce = ndp_lookup(ill, &gw_addr_v6,
24724 					    B_FALSE);
24725 				}
24726 				if (nce != NULL) {
24727 					nce_resolv_failed(nce);
24728 					ndp_delete(nce);
24729 					NCE_REFRELE(nce);
24730 				}
24731 			}
24732 			mp->b_cont = NULL;
24733 			freemsg(mp1);		/* frees the pkt as well */
24734 			ire_delete((ire_t *)mp->b_rptr);
24735 			return;
24736 		}
24737 		/*
24738 		 * Split them into IRE_MBLK and pkt and feed it into
24739 		 * ire_add_then_send. Then in ire_add_then_send
24740 		 * the IRE will be added, and then the packet will be
24741 		 * run back through ip_wput. This time it will make
24742 		 * it to the wire.
24743 		 */
24744 		mp->b_cont = NULL;
24745 		mp = mp1->b_cont;		/* now, mp points to pkt */
24746 		mp1->b_cont = NULL;
24747 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24748 		if (ire->ire_ipversion == IPV6_VERSION) {
24749 			/*
24750 			 * XRESOLV interface. Find the nce and put a copy
24751 			 * of the dl_unitdata_req in nce_res_mp
24752 			 */
24753 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24754 			mutex_enter(&ire->ire_lock);
24755 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24756 			mutex_exit(&ire->ire_lock);
24757 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24758 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24759 				    B_FALSE);
24760 			} else {
24761 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24762 			}
24763 			if (nce != NULL) {
24764 				/*
24765 				 * We have to protect nce_res_mp here
24766 				 * from being accessed by other threads
24767 				 * while we change the mblk pointer.
24768 				 * Other functions will also lock the nce when
24769 				 * accessing nce_res_mp.
24770 				 *
24771 				 * The reason we change the mblk pointer
24772 				 * here rather than copying the resolved address
24773 				 * into the template is that, unlike with
24774 				 * ethernet, we have no guarantee that the
24775 				 * resolved address length will be
24776 				 * smaller than or equal to the lla length
24777 				 * with which the template was allocated,
24778 				 * (for ethernet, they're equal)
24779 				 * so we have to use the actual resolved
24780 				 * address mblk - which holds the real
24781 				 * dl_unitdata_req with the resolved address.
24782 				 *
24783 				 * Doing this is the same behavior as was
24784 				 * previously used in the v4 ARP case.
24785 				 */
24786 				mutex_enter(&nce->nce_lock);
24787 				if (nce->nce_res_mp != NULL)
24788 					freemsg(nce->nce_res_mp);
24789 				nce->nce_res_mp = mp1;
24790 				mutex_exit(&nce->nce_lock);
24791 				/*
24792 				 * We do a fastpath probe here because
24793 				 * we have resolved the address without
24794 				 * using Neighbor Discovery.
24795 				 * In the non-XRESOLV v6 case, the fastpath
24796 				 * probe is done right after neighbor
24797 				 * discovery completes.
24798 				 */
24799 				if (nce->nce_res_mp != NULL) {
24800 					int res;
24801 					nce_fastpath_list_add(nce);
24802 					res = ill_fastpath_probe(ill,
24803 					    nce->nce_res_mp);
24804 					if (res != 0 && res != EAGAIN)
24805 						nce_fastpath_list_delete(nce);
24806 				}
24807 
24808 				ire_add_then_send(q, ire, mp);
24809 				/*
24810 				 * Now we have to clean out any packets
24811 				 * that may have been queued on the nce
24812 				 * while it was waiting for address resolution
24813 				 * to complete.
24814 				 */
24815 				mutex_enter(&nce->nce_lock);
24816 				mp1 = nce->nce_qd_mp;
24817 				nce->nce_qd_mp = NULL;
24818 				mutex_exit(&nce->nce_lock);
24819 				while (mp1 != NULL) {
24820 					mblk_t *nxt_mp;
24821 					queue_t *fwdq = NULL;
24822 					ill_t   *inbound_ill;
24823 					uint_t ifindex;
24824 
24825 					nxt_mp = mp1->b_next;
24826 					mp1->b_next = NULL;
24827 					/*
24828 					 * Retrieve ifindex stored in
24829 					 * ip_rput_data_v6()
24830 					 */
24831 					ifindex =
24832 					    (uint_t)(uintptr_t)mp1->b_prev;
24833 					inbound_ill =
24834 						ill_lookup_on_ifindex(ifindex,
24835 						    B_TRUE, NULL, NULL, NULL,
24836 						    NULL);
24837 					mp1->b_prev = NULL;
24838 					if (inbound_ill != NULL)
24839 						fwdq = inbound_ill->ill_rq;
24840 
24841 					if (fwdq != NULL) {
24842 						put(fwdq, mp1);
24843 						ill_refrele(inbound_ill);
24844 					} else
24845 						put(WR(ill->ill_rq), mp1);
24846 					mp1 = nxt_mp;
24847 				}
24848 				NCE_REFRELE(nce);
24849 			} else {	/* nce is NULL; clean up */
24850 				ire_delete(ire);
24851 				freemsg(mp);
24852 				freemsg(mp1);
24853 				return;
24854 			}
24855 		} else {
24856 			ire->ire_dlureq_mp = mp1;
24857 			ire_add_then_send(q, ire, mp);
24858 		}
24859 		return;	/* All is well, the packet has been sent. */
24860 	}
24861 	default:
24862 		break;
24863 	}
24864 	if (q->q_next) {
24865 		putnext(q, mp);
24866 	} else
24867 		freemsg(mp);
24868 }
24869 
24870 /*
24871  * Process IP options in an outbound packet.  Modify the destination if there
24872  * is a source route option.
24873  * Returns non-zero if something fails in which case an ICMP error has been
24874  * sent and mp freed.
24875  */
24876 static int
24877 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24878     boolean_t mctl_present, zoneid_t zoneid)
24879 {
24880 	ipoptp_t	opts;
24881 	uchar_t		*opt;
24882 	uint8_t		optval;
24883 	uint8_t		optlen;
24884 	ipaddr_t	dst;
24885 	intptr_t	code = 0;
24886 	mblk_t		*mp;
24887 	ire_t		*ire = NULL;
24888 
24889 	ip2dbg(("ip_wput_options\n"));
24890 	mp = ipsec_mp;
24891 	if (mctl_present) {
24892 		mp = ipsec_mp->b_cont;
24893 	}
24894 
24895 	dst = ipha->ipha_dst;
24896 	for (optval = ipoptp_first(&opts, ipha);
24897 	    optval != IPOPT_EOL;
24898 	    optval = ipoptp_next(&opts)) {
24899 		opt = opts.ipoptp_cur;
24900 		optlen = opts.ipoptp_len;
24901 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24902 		    optval, optlen));
24903 		switch (optval) {
24904 			uint32_t off;
24905 		case IPOPT_SSRR:
24906 		case IPOPT_LSRR:
24907 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24908 				ip1dbg((
24909 				    "ip_wput_options: bad option offset\n"));
24910 				code = (char *)&opt[IPOPT_OLEN] -
24911 				    (char *)ipha;
24912 				goto param_prob;
24913 			}
24914 			off = opt[IPOPT_OFFSET];
24915 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24916 			    ntohl(dst)));
24917 			/*
24918 			 * For strict: verify that dst is directly
24919 			 * reachable.
24920 			 */
24921 			if (optval == IPOPT_SSRR) {
24922 				ire = ire_ftable_lookup(dst, 0, 0,
24923 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24924 				    MATCH_IRE_TYPE);
24925 				if (ire == NULL) {
24926 					ip1dbg(("ip_wput_options: SSRR not"
24927 					    " directly reachable: 0x%x\n",
24928 					    ntohl(dst)));
24929 					goto bad_src_route;
24930 				}
24931 				ire_refrele(ire);
24932 			}
24933 			break;
24934 		case IPOPT_RR:
24935 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24936 				ip1dbg((
24937 				    "ip_wput_options: bad option offset\n"));
24938 				code = (char *)&opt[IPOPT_OLEN] -
24939 				    (char *)ipha;
24940 				goto param_prob;
24941 			}
24942 			break;
24943 		case IPOPT_TS:
24944 			/*
24945 			 * Verify that length >=5 and that there is either
24946 			 * room for another timestamp or that the overflow
24947 			 * counter is not maxed out.
24948 			 */
24949 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24950 			if (optlen < IPOPT_MINLEN_IT) {
24951 				goto param_prob;
24952 			}
24953 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24954 				ip1dbg((
24955 				    "ip_wput_options: bad option offset\n"));
24956 				code = (char *)&opt[IPOPT_OFFSET] -
24957 				    (char *)ipha;
24958 				goto param_prob;
24959 			}
24960 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24961 			case IPOPT_TS_TSONLY:
24962 				off = IPOPT_TS_TIMELEN;
24963 				break;
24964 			case IPOPT_TS_TSANDADDR:
24965 			case IPOPT_TS_PRESPEC:
24966 			case IPOPT_TS_PRESPEC_RFC791:
24967 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24968 				break;
24969 			default:
24970 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24971 				    (char *)ipha;
24972 				goto param_prob;
24973 			}
24974 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24975 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24976 				/*
24977 				 * No room and the overflow counter is 15
24978 				 * already.
24979 				 */
24980 				goto param_prob;
24981 			}
24982 			break;
24983 		}
24984 	}
24985 
24986 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24987 		return (0);
24988 
24989 	ip1dbg(("ip_wput_options: error processing IP options."));
24990 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24991 
24992 param_prob:
24993 	/*
24994 	 * Since ip_wput() isn't close to finished, we fill
24995 	 * in enough of the header for credible error reporting.
24996 	 */
24997 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24998 		/* Failed */
24999 		freemsg(ipsec_mp);
25000 		return (-1);
25001 	}
25002 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
25003 	return (-1);
25004 
25005 bad_src_route:
25006 	/*
25007 	 * Since ip_wput() isn't close to finished, we fill
25008 	 * in enough of the header for credible error reporting.
25009 	 */
25010 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25011 		/* Failed */
25012 		freemsg(ipsec_mp);
25013 		return (-1);
25014 	}
25015 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25016 	return (-1);
25017 }
25018 
25019 /*
25020  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25021  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25022  * thru /etc/system.
25023  */
25024 #define	CONN_MAXDRAINCNT	64
25025 
25026 static void
25027 conn_drain_init(void)
25028 {
25029 	int i;
25030 
25031 	conn_drain_list_cnt = conn_drain_nthreads;
25032 
25033 	if ((conn_drain_list_cnt == 0) ||
25034 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25035 		/*
25036 		 * Default value of the number of drainers is the
25037 		 * number of cpus, subject to maximum of 8 drainers.
25038 		 */
25039 		if (boot_max_ncpus != -1)
25040 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25041 		else
25042 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25043 	}
25044 
25045 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25046 	    KM_SLEEP);
25047 
25048 	for (i = 0; i < conn_drain_list_cnt; i++) {
25049 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25050 		    MUTEX_DEFAULT, NULL);
25051 	}
25052 }
25053 
25054 static void
25055 conn_drain_fini(void)
25056 {
25057 	int i;
25058 
25059 	for (i = 0; i < conn_drain_list_cnt; i++)
25060 		mutex_destroy(&conn_drain_list[i].idl_lock);
25061 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25062 	conn_drain_list = NULL;
25063 }
25064 
25065 /*
25066  * Note: For an overview of how flowcontrol is handled in IP please see the
25067  * IP Flowcontrol notes at the top of this file.
25068  *
25069  * Flow control has blocked us from proceeding. Insert the given conn in one
25070  * of the conn drain lists. These conn wq's will be qenabled later on when
25071  * STREAMS flow control does a backenable. conn_walk_drain will enable
25072  * the first conn in each of these drain lists. Each of these qenabled conns
25073  * in turn enables the next in the list, after it runs, or when it closes,
25074  * thus sustaining the drain process.
25075  *
25076  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25077  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25078  * running at any time, on a given conn, since there can be only 1 service proc
25079  * running on a queue at any time.
25080  */
25081 void
25082 conn_drain_insert(conn_t *connp)
25083 {
25084 	idl_t	*idl;
25085 	uint_t	index;
25086 
25087 	mutex_enter(&connp->conn_lock);
25088 	if (connp->conn_state_flags & CONN_CLOSING) {
25089 		/*
25090 		 * The conn is closing as a result of which CONN_CLOSING
25091 		 * is set. Return.
25092 		 */
25093 		mutex_exit(&connp->conn_lock);
25094 		return;
25095 	} else if (connp->conn_idl == NULL) {
25096 		/*
25097 		 * Assign the next drain list round robin. We dont' use
25098 		 * a lock, and thus it may not be strictly round robin.
25099 		 * Atomicity of load/stores is enough to make sure that
25100 		 * conn_drain_list_index is always within bounds.
25101 		 */
25102 		index = conn_drain_list_index;
25103 		ASSERT(index < conn_drain_list_cnt);
25104 		connp->conn_idl = &conn_drain_list[index];
25105 		index++;
25106 		if (index == conn_drain_list_cnt)
25107 			index = 0;
25108 		conn_drain_list_index = index;
25109 	}
25110 	mutex_exit(&connp->conn_lock);
25111 
25112 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25113 	if ((connp->conn_drain_prev != NULL) ||
25114 	    (connp->conn_state_flags & CONN_CLOSING)) {
25115 		/*
25116 		 * The conn is already in the drain list, OR
25117 		 * the conn is closing. We need to check again for
25118 		 * the closing case again since close can happen
25119 		 * after we drop the conn_lock, and before we
25120 		 * acquire the CONN_DRAIN_LIST_LOCK.
25121 		 */
25122 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25123 		return;
25124 	} else {
25125 		idl = connp->conn_idl;
25126 	}
25127 
25128 	/*
25129 	 * The conn is not in the drain list. Insert it at the
25130 	 * tail of the drain list. The drain list is circular
25131 	 * and doubly linked. idl_conn points to the 1st element
25132 	 * in the list.
25133 	 */
25134 	if (idl->idl_conn == NULL) {
25135 		idl->idl_conn = connp;
25136 		connp->conn_drain_next = connp;
25137 		connp->conn_drain_prev = connp;
25138 	} else {
25139 		conn_t *head = idl->idl_conn;
25140 
25141 		connp->conn_drain_next = head;
25142 		connp->conn_drain_prev = head->conn_drain_prev;
25143 		head->conn_drain_prev->conn_drain_next = connp;
25144 		head->conn_drain_prev = connp;
25145 	}
25146 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25147 }
25148 
25149 /*
25150  * This conn is closing, and we are called from ip_close. OR
25151  * This conn has been serviced by ip_wsrv, and we need to do the tail
25152  * processing.
25153  * If this conn is part of the drain list, we may need to sustain the drain
25154  * process by qenabling the next conn in the drain list. We may also need to
25155  * remove this conn from the list, if it is done.
25156  */
25157 static void
25158 conn_drain_tail(conn_t *connp, boolean_t closing)
25159 {
25160 	idl_t *idl;
25161 
25162 	/*
25163 	 * connp->conn_idl is stable at this point, and no lock is needed
25164 	 * to check it. If we are called from ip_close, close has already
25165 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
25166 	 * called us only because conn_idl is non-null. If we are called thru
25167 	 * service, conn_idl could be null, but it cannot change because
25168 	 * service is single-threaded per queue, and there cannot be another
25169 	 * instance of service trying to call conn_drain_insert on this conn
25170 	 * now.
25171 	 */
25172 	ASSERT(!closing || (connp->conn_idl != NULL));
25173 
25174 	/*
25175 	 * If connp->conn_idl is null, the conn has not been inserted into any
25176 	 * drain list even once since creation of the conn. Just return.
25177 	 */
25178 	if (connp->conn_idl == NULL)
25179 		return;
25180 
25181 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25182 
25183 	if (connp->conn_drain_prev == NULL) {
25184 		/* This conn is currently not in the drain list.  */
25185 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25186 		return;
25187 	}
25188 	idl = connp->conn_idl;
25189 	if (idl->idl_conn_draining == connp) {
25190 		/*
25191 		 * This conn is the current drainer. If this is the last conn
25192 		 * in the drain list, we need to do more checks, in the 'if'
25193 		 * below. Otherwwise we need to just qenable the next conn,
25194 		 * to sustain the draining, and is handled in the 'else'
25195 		 * below.
25196 		 */
25197 		if (connp->conn_drain_next == idl->idl_conn) {
25198 			/*
25199 			 * This conn is the last in this list. This round
25200 			 * of draining is complete. If idl_repeat is set,
25201 			 * it means another flow enabling has happened from
25202 			 * the driver/streams and we need to another round
25203 			 * of draining.
25204 			 * If there are more than 2 conns in the drain list,
25205 			 * do a left rotate by 1, so that all conns except the
25206 			 * conn at the head move towards the head by 1, and the
25207 			 * the conn at the head goes to the tail. This attempts
25208 			 * a more even share for all queues that are being
25209 			 * drained.
25210 			 */
25211 			if ((connp->conn_drain_next != connp) &&
25212 			    (idl->idl_conn->conn_drain_next != connp)) {
25213 				idl->idl_conn = idl->idl_conn->conn_drain_next;
25214 			}
25215 			if (idl->idl_repeat) {
25216 				qenable(idl->idl_conn->conn_wq);
25217 				idl->idl_conn_draining = idl->idl_conn;
25218 				idl->idl_repeat = 0;
25219 			} else {
25220 				idl->idl_conn_draining = NULL;
25221 			}
25222 		} else {
25223 			/*
25224 			 * If the next queue that we are now qenable'ing,
25225 			 * is closing, it will remove itself from this list
25226 			 * and qenable the subsequent queue in ip_close().
25227 			 * Serialization is acheived thru idl_lock.
25228 			 */
25229 			qenable(connp->conn_drain_next->conn_wq);
25230 			idl->idl_conn_draining = connp->conn_drain_next;
25231 		}
25232 	}
25233 	if (!connp->conn_did_putbq || closing) {
25234 		/*
25235 		 * Remove ourself from the drain list, if we did not do
25236 		 * a putbq, or if the conn is closing.
25237 		 * Note: It is possible that q->q_first is non-null. It means
25238 		 * that these messages landed after we did a enableok() in
25239 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
25240 		 * service them.
25241 		 */
25242 		if (connp->conn_drain_next == connp) {
25243 			/* Singleton in the list */
25244 			ASSERT(connp->conn_drain_prev == connp);
25245 			idl->idl_conn = NULL;
25246 			idl->idl_conn_draining = NULL;
25247 		} else {
25248 			connp->conn_drain_prev->conn_drain_next =
25249 			    connp->conn_drain_next;
25250 			connp->conn_drain_next->conn_drain_prev =
25251 			    connp->conn_drain_prev;
25252 			if (idl->idl_conn == connp)
25253 				idl->idl_conn = connp->conn_drain_next;
25254 			ASSERT(idl->idl_conn_draining != connp);
25255 
25256 		}
25257 		connp->conn_drain_next = NULL;
25258 		connp->conn_drain_prev = NULL;
25259 	}
25260 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25261 }
25262 
25263 /*
25264  * Write service routine. Shared perimeter entry point.
25265  * ip_wsrv can be called in any of the following ways.
25266  * 1. The device queue's messages has fallen below the low water mark
25267  *    and STREAMS has backenabled the ill_wq. We walk thru all the
25268  *    the drain lists and backenable the first conn in each list.
25269  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
25270  *    qenabled non-tcp upper layers. We start dequeing messages and call
25271  *    ip_wput for each message.
25272  */
25273 
25274 void
25275 ip_wsrv(queue_t *q)
25276 {
25277 	conn_t	*connp;
25278 	ill_t	*ill;
25279 	mblk_t	*mp;
25280 
25281 	if (q->q_next) {
25282 		ill = (ill_t *)q->q_ptr;
25283 		if (ill->ill_state_flags == 0) {
25284 			/*
25285 			 * The device flow control has opened up.
25286 			 * Walk through conn drain lists and qenable the
25287 			 * first conn in each list. This makes sense only
25288 			 * if the stream is fully plumbed and setup.
25289 			 * Hence the if check above.
25290 			 */
25291 			ip1dbg(("ip_wsrv: walking\n"));
25292 			conn_walk_drain();
25293 		}
25294 		return;
25295 	}
25296 
25297 	connp = Q_TO_CONN(q);
25298 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
25299 
25300 	/*
25301 	 * 1. Set conn_draining flag to signal that service is active.
25302 	 *
25303 	 * 2. ip_output determines whether it has been called from service,
25304 	 *    based on the last parameter. If it is IP_WSRV it concludes it
25305 	 *    has been called from service.
25306 	 *
25307 	 * 3. Message ordering is preserved by the following logic.
25308 	 *    i. A directly called ip_output (i.e. not thru service) will queue
25309 	 *    the message at the tail, if conn_draining is set (i.e. service
25310 	 *    is running) or if q->q_first is non-null.
25311 	 *
25312 	 *    ii. If ip_output is called from service, and if ip_output cannot
25313 	 *    putnext due to flow control, it does a putbq.
25314 	 *
25315 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
25316 	 *    (causing an infinite loop).
25317 	 */
25318 	ASSERT(!connp->conn_did_putbq);
25319 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
25320 		connp->conn_draining = 1;
25321 		noenable(q);
25322 		while ((mp = getq(q)) != NULL) {
25323 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
25324 			if (connp->conn_did_putbq) {
25325 				/* ip_wput did a putbq */
25326 				break;
25327 			}
25328 		}
25329 		/*
25330 		 * At this point, a thread coming down from top, calling
25331 		 * ip_wput, may end up queueing the message. We have not yet
25332 		 * enabled the queue, so ip_wsrv won't be called again.
25333 		 * To avoid this race, check q->q_first again (in the loop)
25334 		 * If the other thread queued the message before we call
25335 		 * enableok(), we will catch it in the q->q_first check.
25336 		 * If the other thread queues the message after we call
25337 		 * enableok(), ip_wsrv will be called again by STREAMS.
25338 		 */
25339 		connp->conn_draining = 0;
25340 		enableok(q);
25341 	}
25342 
25343 	/* Enable the next conn for draining */
25344 	conn_drain_tail(connp, B_FALSE);
25345 
25346 	connp->conn_did_putbq = 0;
25347 }
25348 
25349 /*
25350  * Walk the list of all conn's calling the function provided with the
25351  * specified argument for each.	 Note that this only walks conn's that
25352  * have been bound.
25353  * Applies to both IPv4 and IPv6.
25354  */
25355 static void
25356 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
25357 {
25358 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
25359 	    func, arg, zoneid);
25360 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
25361 	    func, arg, zoneid);
25362 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
25363 	    func, arg, zoneid);
25364 	conn_walk_fanout_table(ipcl_proto_fanout,
25365 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
25366 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
25367 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
25368 }
25369 
25370 /*
25371  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
25372  * of conns that need to be drained, check if drain is already in progress.
25373  * If so set the idl_repeat bit, indicating that the last conn in the list
25374  * needs to reinitiate the drain once again, for the list. If drain is not
25375  * in progress for the list, initiate the draining, by qenabling the 1st
25376  * conn in the list. The drain is self-sustaining, each qenabled conn will
25377  * in turn qenable the next conn, when it is done/blocked/closing.
25378  */
25379 static void
25380 conn_walk_drain(void)
25381 {
25382 	int i;
25383 	idl_t *idl;
25384 
25385 	IP_STAT(ip_conn_walk_drain);
25386 
25387 	for (i = 0; i < conn_drain_list_cnt; i++) {
25388 		idl = &conn_drain_list[i];
25389 		mutex_enter(&idl->idl_lock);
25390 		if (idl->idl_conn == NULL) {
25391 			mutex_exit(&idl->idl_lock);
25392 			continue;
25393 		}
25394 		/*
25395 		 * If this list is not being drained currently by
25396 		 * an ip_wsrv thread, start the process.
25397 		 */
25398 		if (idl->idl_conn_draining == NULL) {
25399 			ASSERT(idl->idl_repeat == 0);
25400 			qenable(idl->idl_conn->conn_wq);
25401 			idl->idl_conn_draining = idl->idl_conn;
25402 		} else {
25403 			idl->idl_repeat = 1;
25404 		}
25405 		mutex_exit(&idl->idl_lock);
25406 	}
25407 }
25408 
25409 /*
25410  * Walk an conn hash table of `count' buckets, calling func for each entry.
25411  */
25412 static void
25413 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
25414     zoneid_t zoneid)
25415 {
25416 	conn_t	*connp;
25417 
25418 	while (count-- > 0) {
25419 		mutex_enter(&connfp->connf_lock);
25420 		for (connp = connfp->connf_head; connp != NULL;
25421 		    connp = connp->conn_next) {
25422 			if (zoneid == GLOBAL_ZONEID ||
25423 			    zoneid == connp->conn_zoneid) {
25424 				CONN_INC_REF(connp);
25425 				mutex_exit(&connfp->connf_lock);
25426 				(*func)(connp, arg);
25427 				mutex_enter(&connfp->connf_lock);
25428 				CONN_DEC_REF(connp);
25429 			}
25430 		}
25431 		mutex_exit(&connfp->connf_lock);
25432 		connfp++;
25433 	}
25434 }
25435 
25436 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
25437 static void
25438 conn_report1(conn_t *connp, void *mp)
25439 {
25440 	char	buf1[INET6_ADDRSTRLEN];
25441 	char	buf2[INET6_ADDRSTRLEN];
25442 	uint_t	print_len, buf_len;
25443 
25444 	ASSERT(connp != NULL);
25445 
25446 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
25447 	if (buf_len <= 0)
25448 		return;
25449 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
25450 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
25451 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
25452 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
25453 	    "%5d %s/%05d %s/%05d\n",
25454 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
25455 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
25456 	    buf1, connp->conn_lport,
25457 	    buf2, connp->conn_fport);
25458 	if (print_len < buf_len) {
25459 		((mblk_t *)mp)->b_wptr += print_len;
25460 	} else {
25461 		((mblk_t *)mp)->b_wptr += buf_len;
25462 	}
25463 }
25464 
25465 /*
25466  * Named Dispatch routine to produce a formatted report on all conns
25467  * that are listed in one of the fanout tables.
25468  * This report is accessed by using the ndd utility to "get" ND variable
25469  * "ip_conn_status".
25470  */
25471 /* ARGSUSED */
25472 static int
25473 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
25474 {
25475 	(void) mi_mpprintf(mp,
25476 	    "CONN      " MI_COL_HDRPAD_STR
25477 	    "rfq      " MI_COL_HDRPAD_STR
25478 	    "stq      " MI_COL_HDRPAD_STR
25479 	    " zone local                 remote");
25480 
25481 	/*
25482 	 * Because of the ndd constraint, at most we can have 64K buffer
25483 	 * to put in all conn info.  So to be more efficient, just
25484 	 * allocate a 64K buffer here, assuming we need that large buffer.
25485 	 * This should be OK as only privileged processes can do ndd /dev/ip.
25486 	 */
25487 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
25488 		/* The following may work even if we cannot get a large buf. */
25489 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
25490 		return (0);
25491 	}
25492 
25493 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
25494 	return (0);
25495 }
25496 
25497 /*
25498  * Determine if the ill and multicast aspects of that packets
25499  * "matches" the conn.
25500  */
25501 boolean_t
25502 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
25503     zoneid_t zoneid)
25504 {
25505 	ill_t *in_ill;
25506 	boolean_t found;
25507 	ipif_t *ipif;
25508 	ire_t *ire;
25509 	ipaddr_t dst, src;
25510 
25511 	dst = ipha->ipha_dst;
25512 	src = ipha->ipha_src;
25513 
25514 	/*
25515 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
25516 	 * unicast, broadcast and multicast reception to
25517 	 * conn_incoming_ill. conn_wantpacket itself is called
25518 	 * only for BROADCAST and multicast.
25519 	 *
25520 	 * 1) ip_rput supresses duplicate broadcasts if the ill
25521 	 *    is part of a group. Hence, we should be receiving
25522 	 *    just one copy of broadcast for the whole group.
25523 	 *    Thus, if it is part of the group the packet could
25524 	 *    come on any ill of the group and hence we need a
25525 	 *    match on the group. Otherwise, match on ill should
25526 	 *    be sufficient.
25527 	 *
25528 	 * 2) ip_rput does not suppress duplicate multicast packets.
25529 	 *    If there are two interfaces in a ill group and we have
25530 	 *    2 applications (conns) joined a multicast group G on
25531 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25532 	 *    will give us two packets because we join G on both the
25533 	 *    interfaces rather than nominating just one interface
25534 	 *    for receiving multicast like broadcast above. So,
25535 	 *    we have to call ilg_lookup_ill to filter out duplicate
25536 	 *    copies, if ill is part of a group.
25537 	 */
25538 	in_ill = connp->conn_incoming_ill;
25539 	if (in_ill != NULL) {
25540 		if (in_ill->ill_group == NULL) {
25541 			if (in_ill != ill)
25542 				return (B_FALSE);
25543 		} else if (in_ill->ill_group != ill->ill_group) {
25544 			return (B_FALSE);
25545 		}
25546 	}
25547 
25548 	if (!CLASSD(dst)) {
25549 		if (connp->conn_zoneid == zoneid)
25550 			return (B_TRUE);
25551 		/*
25552 		 * The conn is in a different zone; we need to check that this
25553 		 * broadcast address is configured in the application's zone and
25554 		 * on one ill in the group.
25555 		 */
25556 		ipif = ipif_get_next_ipif(NULL, ill);
25557 		if (ipif == NULL)
25558 			return (B_FALSE);
25559 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25560 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25561 		ipif_refrele(ipif);
25562 		if (ire != NULL) {
25563 			ire_refrele(ire);
25564 			return (B_TRUE);
25565 		} else {
25566 			return (B_FALSE);
25567 		}
25568 	}
25569 
25570 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25571 	    connp->conn_zoneid == zoneid) {
25572 		/*
25573 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25574 		 * disabled, therefore we don't dispatch the multicast packet to
25575 		 * the sending zone.
25576 		 */
25577 		return (B_FALSE);
25578 	}
25579 
25580 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25581 	    connp->conn_zoneid != zoneid) {
25582 		/*
25583 		 * Multicast packet on the loopback interface: we only match
25584 		 * conns who joined the group in the specified zone.
25585 		 */
25586 		return (B_FALSE);
25587 	}
25588 
25589 	if (connp->conn_multi_router) {
25590 		/* multicast packet and multicast router socket: send up */
25591 		return (B_TRUE);
25592 	}
25593 
25594 	mutex_enter(&connp->conn_lock);
25595 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25596 	mutex_exit(&connp->conn_lock);
25597 	return (found);
25598 }
25599 
25600 /*
25601  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25602  */
25603 /* ARGSUSED */
25604 static void
25605 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25606 {
25607 	ill_t *ill = (ill_t *)q->q_ptr;
25608 	mblk_t	*mp1, *mp2;
25609 	ipif_t  *ipif;
25610 	int err = 0;
25611 	conn_t *connp = NULL;
25612 	ipsq_t	*ipsq;
25613 	arc_t	*arc;
25614 
25615 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25616 
25617 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25618 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25619 
25620 	ASSERT(IAM_WRITER_ILL(ill));
25621 	mp2 = mp->b_cont;
25622 	mp->b_cont = NULL;
25623 
25624 	/*
25625 	 * We have now received the arp bringup completion message
25626 	 * from ARP. Mark the arp bringup as done. Also if the arp
25627 	 * stream has already started closing, send up the AR_ARP_CLOSING
25628 	 * ack now since ARP is waiting in close for this ack.
25629 	 */
25630 	mutex_enter(&ill->ill_lock);
25631 	ill->ill_arp_bringup_pending = 0;
25632 	if (ill->ill_arp_closing) {
25633 		mutex_exit(&ill->ill_lock);
25634 		/* Let's reuse the mp for sending the ack */
25635 		arc = (arc_t *)mp->b_rptr;
25636 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25637 		arc->arc_cmd = AR_ARP_CLOSING;
25638 		qreply(q, mp);
25639 	} else {
25640 		mutex_exit(&ill->ill_lock);
25641 		freeb(mp);
25642 	}
25643 
25644 	/* We should have an IOCTL waiting on this. */
25645 	ipsq = ill->ill_phyint->phyint_ipsq;
25646 	ipif = ipsq->ipsq_pending_ipif;
25647 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25648 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25649 	if (mp1 == NULL) {
25650 		/* bringup was aborted by the user */
25651 		freemsg(mp2);
25652 		return;
25653 	}
25654 	ASSERT(connp != NULL);
25655 	q = CONNP_TO_WQ(connp);
25656 	/*
25657 	 * If the DL_BIND_REQ fails, it is noted
25658 	 * in arc_name_offset.
25659 	 */
25660 	err = *((int *)mp2->b_rptr);
25661 	if (err == 0) {
25662 		if (ipif->ipif_isv6) {
25663 			if ((err = ipif_up_done_v6(ipif)) != 0)
25664 				ip0dbg(("ip_arp_done: init failed\n"));
25665 		} else {
25666 			if ((err = ipif_up_done(ipif)) != 0)
25667 				ip0dbg(("ip_arp_done: init failed\n"));
25668 		}
25669 	} else {
25670 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25671 	}
25672 
25673 	freemsg(mp2);
25674 
25675 	if ((err == 0) && (ill->ill_up_ipifs)) {
25676 		err = ill_up_ipifs(ill, q, mp1);
25677 		if (err == EINPROGRESS)
25678 			return;
25679 	}
25680 
25681 	if (ill->ill_up_ipifs) {
25682 		ill_group_cleanup(ill);
25683 	}
25684 
25685 	/*
25686 	 * The ioctl must complete now without EINPROGRESS
25687 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25688 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25689 	 * stuck for ever in the ipsq.
25690 	 */
25691 	ASSERT(err != EINPROGRESS);
25692 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25693 }
25694 
25695 /* Allocate the private structure */
25696 static int
25697 ip_priv_alloc(void **bufp)
25698 {
25699 	void	*buf;
25700 
25701 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25702 		return (ENOMEM);
25703 
25704 	*bufp = buf;
25705 	return (0);
25706 }
25707 
25708 /* Function to delete the private structure */
25709 void
25710 ip_priv_free(void *buf)
25711 {
25712 	ASSERT(buf != NULL);
25713 	kmem_free(buf, sizeof (ip_priv_t));
25714 }
25715 
25716 /*
25717  * The entry point for IPPF processing.
25718  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25719  * routine just returns.
25720  *
25721  * When called, ip_process generates an ipp_packet_t structure
25722  * which holds the state information for this packet and invokes the
25723  * the classifier (via ipp_packet_process). The classification, depending on
25724  * configured filters, results in a list of actions for this packet. Invoking
25725  * an action may cause the packet to be dropped, in which case the resulting
25726  * mblk (*mpp) is NULL. proc indicates the callout position for
25727  * this packet and ill_index is the interface this packet on or will leave
25728  * on (inbound and outbound resp.).
25729  */
25730 void
25731 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25732 {
25733 	mblk_t		*mp;
25734 	ip_priv_t	*priv;
25735 	ipp_action_id_t	aid;
25736 	int		rc = 0;
25737 	ipp_packet_t	*pp;
25738 #define	IP_CLASS	"ip"
25739 
25740 	/* If the classifier is not loaded, return  */
25741 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25742 		return;
25743 	}
25744 
25745 	mp = *mpp;
25746 	ASSERT(mp != NULL);
25747 
25748 	/* Allocate the packet structure */
25749 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25750 	if (rc != 0) {
25751 		*mpp = NULL;
25752 		freemsg(mp);
25753 		return;
25754 	}
25755 
25756 	/* Allocate the private structure */
25757 	rc = ip_priv_alloc((void **)&priv);
25758 	if (rc != 0) {
25759 		*mpp = NULL;
25760 		freemsg(mp);
25761 		ipp_packet_free(pp);
25762 		return;
25763 	}
25764 	priv->proc = proc;
25765 	priv->ill_index = ill_index;
25766 	ipp_packet_set_private(pp, priv, ip_priv_free);
25767 	ipp_packet_set_data(pp, mp);
25768 
25769 	/* Invoke the classifier */
25770 	rc = ipp_packet_process(&pp);
25771 	if (pp != NULL) {
25772 		mp = ipp_packet_get_data(pp);
25773 		ipp_packet_free(pp);
25774 		if (rc != 0) {
25775 			freemsg(mp);
25776 			*mpp = NULL;
25777 		}
25778 	} else {
25779 		*mpp = NULL;
25780 	}
25781 #undef	IP_CLASS
25782 }
25783 
25784 /*
25785  * Propagate a multicast group membership operation (add/drop) on
25786  * all the interfaces crossed by the related multirt routes.
25787  * The call is considered successful if the operation succeeds
25788  * on at least one interface.
25789  */
25790 static int
25791 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25792     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25793     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25794     mblk_t *first_mp)
25795 {
25796 	ire_t		*ire_gw;
25797 	irb_t		*irb;
25798 	int		error = 0;
25799 	opt_restart_t	*or;
25800 
25801 	irb = ire->ire_bucket;
25802 	ASSERT(irb != NULL);
25803 
25804 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25805 
25806 	or = (opt_restart_t *)first_mp->b_rptr;
25807 	IRB_REFHOLD(irb);
25808 	for (; ire != NULL; ire = ire->ire_next) {
25809 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25810 			continue;
25811 		if (ire->ire_addr != group)
25812 			continue;
25813 
25814 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25815 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25816 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25817 		/* No resolver exists for the gateway; skip this ire. */
25818 		if (ire_gw == NULL)
25819 			continue;
25820 
25821 		/*
25822 		 * This function can return EINPROGRESS. If so the operation
25823 		 * will be restarted from ip_restart_optmgmt which will
25824 		 * call ip_opt_set and option processing will restart for
25825 		 * this option. So we may end up calling 'fn' more than once.
25826 		 * This requires that 'fn' is idempotent except for the
25827 		 * return value. The operation is considered a success if
25828 		 * it succeeds at least once on any one interface.
25829 		 */
25830 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25831 		    NULL, fmode, src, first_mp);
25832 		if (error == 0)
25833 			or->or_private = CGTP_MCAST_SUCCESS;
25834 
25835 		if (ip_debug > 0) {
25836 			ulong_t	off;
25837 			char	*ksym;
25838 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25839 			ip2dbg(("ip_multirt_apply_membership: "
25840 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25841 			    "error %d [success %u]\n",
25842 			    ksym ? ksym : "?",
25843 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25844 			    error, or->or_private));
25845 		}
25846 
25847 		ire_refrele(ire_gw);
25848 		if (error == EINPROGRESS) {
25849 			IRB_REFRELE(irb);
25850 			return (error);
25851 		}
25852 	}
25853 	IRB_REFRELE(irb);
25854 	/*
25855 	 * Consider the call as successful if we succeeded on at least
25856 	 * one interface. Otherwise, return the last encountered error.
25857 	 */
25858 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25859 }
25860 
25861 
25862 /*
25863  * Issue a warning regarding a route crossing an interface with an
25864  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25865  * amount of time is logged.
25866  */
25867 static void
25868 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25869 {
25870 	hrtime_t	current = gethrtime();
25871 	char		buf[16];
25872 
25873 	/* Convert interval in ms to hrtime in ns */
25874 	if (multirt_bad_mtu_last_time +
25875 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25876 	    current) {
25877 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25878 		    "to %s, incorrect MTU %u (expected %u)\n",
25879 		    ip_dot_addr(ire->ire_addr, buf),
25880 		    ire->ire_max_frag, max_frag);
25881 
25882 		multirt_bad_mtu_last_time = current;
25883 	}
25884 }
25885 
25886 
25887 /*
25888  * Get the CGTP (multirouting) filtering status.
25889  * If 0, the CGTP hooks are transparent.
25890  */
25891 /* ARGSUSED */
25892 static int
25893 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25894 {
25895 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25896 
25897 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25898 	return (0);
25899 }
25900 
25901 
25902 /*
25903  * Set the CGTP (multirouting) filtering status.
25904  * If the status is changed from active to transparent
25905  * or from transparent to active, forward the new status
25906  * to the filtering module (if loaded).
25907  */
25908 /* ARGSUSED */
25909 static int
25910 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25911     cred_t *ioc_cr)
25912 {
25913 	long		new_value;
25914 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25915 
25916 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25917 	    new_value < 0 || new_value > 1) {
25918 		return (EINVAL);
25919 	}
25920 
25921 	/*
25922 	 * Do not enable CGTP filtering - thus preventing the hooks
25923 	 * from being invoked - if the version number of the
25924 	 * filtering module hooks does not match.
25925 	 */
25926 	if ((ip_cgtp_filter_ops != NULL) &&
25927 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25928 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25929 		    "(module hooks version %d, expecting %d)\n",
25930 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25931 		return (ENOTSUP);
25932 	}
25933 
25934 	if ((!*ip_cgtp_filter_value) && new_value) {
25935 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25936 		    ip_cgtp_filter_ops == NULL ?
25937 		    " (module not loaded)" : "");
25938 	}
25939 	if (*ip_cgtp_filter_value && (!new_value)) {
25940 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25941 		    ip_cgtp_filter_ops == NULL ?
25942 		    " (module not loaded)" : "");
25943 	}
25944 
25945 	if (ip_cgtp_filter_ops != NULL) {
25946 		int	res;
25947 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25948 			return (res);
25949 		}
25950 	}
25951 
25952 	*ip_cgtp_filter_value = (boolean_t)new_value;
25953 
25954 	return (0);
25955 }
25956 
25957 
25958 /*
25959  * Return the expected CGTP hooks version number.
25960  */
25961 int
25962 ip_cgtp_filter_supported(void)
25963 {
25964 	return (ip_cgtp_filter_rev);
25965 }
25966 
25967 
25968 /*
25969  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25970  * or by invoking this function. In the first case, the version number
25971  * of the registered structure is checked at hooks activation time
25972  * in ip_cgtp_filter_set().
25973  */
25974 int
25975 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25976 {
25977 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25978 		return (ENOTSUP);
25979 
25980 	ip_cgtp_filter_ops = ops;
25981 	return (0);
25982 }
25983 
25984 static squeue_func_t
25985 ip_squeue_switch(int val)
25986 {
25987 	squeue_func_t rval = squeue_fill;
25988 
25989 	switch (val) {
25990 	case IP_SQUEUE_ENTER_NODRAIN:
25991 		rval = squeue_enter_nodrain;
25992 		break;
25993 	case IP_SQUEUE_ENTER:
25994 		rval = squeue_enter;
25995 		break;
25996 	default:
25997 		break;
25998 	}
25999 	return (rval);
26000 }
26001 
26002 /* ARGSUSED */
26003 static int
26004 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26005     caddr_t addr, cred_t *cr)
26006 {
26007 	int *v = (int *)addr;
26008 	long new_value;
26009 
26010 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26011 		return (EINVAL);
26012 
26013 	ip_input_proc = ip_squeue_switch(new_value);
26014 	*v = new_value;
26015 	return (0);
26016 }
26017 
26018 /* ARGSUSED */
26019 static int
26020 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26021     caddr_t addr, cred_t *cr)
26022 {
26023 	int *v = (int *)addr;
26024 	long new_value;
26025 
26026 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26027 		return (EINVAL);
26028 
26029 	*v = new_value;
26030 	return (0);
26031 }
26032 
26033 static void
26034 ip_kstat_init(void)
26035 {
26036 	ip_named_kstat_t template = {
26037 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26038 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26039 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26040 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26041 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26042 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26043 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26044 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26045 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26046 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26047 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26048 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26049 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26050 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26051 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26052 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26053 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26054 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26055 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26056 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26057 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26058 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26059 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26060 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26061 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26062 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26063 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26064 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26065 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26066 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26067 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26068 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26069 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26070 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26071 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26072 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26073 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26074 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26075 	};
26076 
26077 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26078 					NUM_OF_FIELDS(ip_named_kstat_t),
26079 					0);
26080 	if (!ip_mibkp)
26081 		return;
26082 
26083 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26084 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26085 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26086 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26087 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26088 
26089 	template.netToMediaEntrySize.value.i32 =
26090 		sizeof (mib2_ipNetToMediaEntry_t);
26091 
26092 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26093 
26094 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26095 
26096 	ip_mibkp->ks_update = ip_kstat_update;
26097 
26098 	kstat_install(ip_mibkp);
26099 }
26100 
26101 static void
26102 ip_kstat_fini(void)
26103 {
26104 
26105 	if (ip_mibkp != NULL) {
26106 		kstat_delete(ip_mibkp);
26107 		ip_mibkp = NULL;
26108 	}
26109 }
26110 
26111 static int
26112 ip_kstat_update(kstat_t *kp, int rw)
26113 {
26114 	ip_named_kstat_t *ipkp;
26115 
26116 	if (!kp || !kp->ks_data)
26117 		return (EIO);
26118 
26119 	if (rw == KSTAT_WRITE)
26120 		return (EACCES);
26121 
26122 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26123 
26124 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26125 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26126 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26127 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26128 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26129 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26130 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26131 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26132 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26133 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26134 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26135 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26136 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26137 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26138 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26139 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26140 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26141 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26142 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26143 
26144 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26145 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26146 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26147 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26148 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26149 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26150 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26151 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26152 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26153 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26154 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26155 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26156 
26157 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
26158 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
26159 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
26160 
26161 	return (0);
26162 }
26163 
26164 static void
26165 icmp_kstat_init(void)
26166 {
26167 	icmp_named_kstat_t template = {
26168 		{ "inMsgs",		KSTAT_DATA_UINT32 },
26169 		{ "inErrors",		KSTAT_DATA_UINT32 },
26170 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
26171 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
26172 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
26173 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
26174 		{ "inRedirects",	KSTAT_DATA_UINT32 },
26175 		{ "inEchos",		KSTAT_DATA_UINT32 },
26176 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
26177 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
26178 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
26179 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
26180 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
26181 		{ "outMsgs",		KSTAT_DATA_UINT32 },
26182 		{ "outErrors",		KSTAT_DATA_UINT32 },
26183 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
26184 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
26185 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
26186 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
26187 		{ "outRedirects",	KSTAT_DATA_UINT32 },
26188 		{ "outEchos",		KSTAT_DATA_UINT32 },
26189 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
26190 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
26191 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
26192 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
26193 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
26194 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
26195 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
26196 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
26197 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
26198 		{ "outDrops",		KSTAT_DATA_UINT32 },
26199 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
26200 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
26201 	};
26202 
26203 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
26204 					NUM_OF_FIELDS(icmp_named_kstat_t),
26205 					0);
26206 	if (icmp_mibkp == NULL)
26207 		return;
26208 
26209 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
26210 
26211 	icmp_mibkp->ks_update = icmp_kstat_update;
26212 
26213 	kstat_install(icmp_mibkp);
26214 }
26215 
26216 static void
26217 icmp_kstat_fini(void)
26218 {
26219 
26220 	if (icmp_mibkp != NULL) {
26221 		kstat_delete(icmp_mibkp);
26222 		icmp_mibkp = NULL;
26223 	}
26224 }
26225 
26226 static int
26227 icmp_kstat_update(kstat_t *kp, int rw)
26228 {
26229 	icmp_named_kstat_t *icmpkp;
26230 
26231 	if ((kp == NULL) || (kp->ks_data == NULL))
26232 		return (EIO);
26233 
26234 	if (rw == KSTAT_WRITE)
26235 		return (EACCES);
26236 
26237 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
26238 
26239 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
26240 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
26241 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
26242 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
26243 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
26244 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
26245 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
26246 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
26247 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
26248 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
26249 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
26250 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
26251 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
26252 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
26253 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
26254 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
26255 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
26256 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
26257 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
26258 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
26259 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
26260 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
26261 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
26262 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
26263 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
26264 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
26265 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
26266 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
26267 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
26268 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
26269 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
26270 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
26271 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
26272 
26273 	return (0);
26274 }
26275 
26276 /*
26277  * This is the fanout function for raw socket opened for SCTP.  Note
26278  * that it is called after SCTP checks that there is no socket which
26279  * wants a packet.  Then before SCTP handles this out of the blue packet,
26280  * this function is called to see if there is any raw socket for SCTP.
26281  * If there is and it is bound to the correct address, the packet will
26282  * be sent to that socket.  Note that only one raw socket can be bound to
26283  * a port.  This is assured in ipcl_sctp_hash_insert();
26284  */
26285 void
26286 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
26287     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
26288     uint_t ipif_seqid, zoneid_t zoneid)
26289 {
26290 	conn_t		*connp;
26291 	queue_t		*rq;
26292 	mblk_t		*first_mp;
26293 	boolean_t	secure;
26294 	ip6_t		*ip6h;
26295 
26296 	first_mp = mp;
26297 	if (mctl_present) {
26298 		mp = first_mp->b_cont;
26299 		secure = ipsec_in_is_secure(first_mp);
26300 		ASSERT(mp != NULL);
26301 	} else {
26302 		secure = B_FALSE;
26303 	}
26304 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
26305 
26306 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
26307 	if (connp == NULL) {
26308 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
26309 		    mctl_present);
26310 		return;
26311 	}
26312 	rq = connp->conn_rq;
26313 	if (!canputnext(rq)) {
26314 		CONN_DEC_REF(connp);
26315 		BUMP_MIB(&ip_mib, rawipInOverflows);
26316 		freemsg(first_mp);
26317 		return;
26318 	}
26319 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
26320 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
26321 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
26322 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
26323 		if (first_mp == NULL) {
26324 			CONN_DEC_REF(connp);
26325 			return;
26326 		}
26327 	}
26328 	/*
26329 	 * We probably should not send M_CTL message up to
26330 	 * raw socket.
26331 	 */
26332 	if (mctl_present)
26333 		freeb(first_mp);
26334 
26335 	/* Initiate IPPF processing here if needed. */
26336 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
26337 	    (!isv4 && IP6_IN_IPP(flags))) {
26338 		ip_process(IPP_LOCAL_IN, &mp,
26339 		    recv_ill->ill_phyint->phyint_ifindex);
26340 		if (mp == NULL) {
26341 			CONN_DEC_REF(connp);
26342 			return;
26343 		}
26344 	}
26345 
26346 	if (connp->conn_recvif || connp->conn_recvslla ||
26347 	    ((connp->conn_ipv6_recvpktinfo ||
26348 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
26349 	    (flags & IP_FF_IP6INFO))) {
26350 		int in_flags = 0;
26351 
26352 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
26353 			in_flags = IPF_RECVIF;
26354 		}
26355 		if (connp->conn_recvslla) {
26356 			in_flags |= IPF_RECVSLLA;
26357 		}
26358 		if (isv4) {
26359 			mp = ip_add_info(mp, recv_ill, in_flags);
26360 		} else {
26361 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
26362 			if (mp == NULL) {
26363 				CONN_DEC_REF(connp);
26364 				return;
26365 			}
26366 		}
26367 	}
26368 
26369 	BUMP_MIB(&ip_mib, ipInDelivers);
26370 	/*
26371 	 * We are sending the IPSEC_IN message also up. Refer
26372 	 * to comments above this function.
26373 	 */
26374 	putnext(rq, mp);
26375 	CONN_DEC_REF(connp);
26376 }
26377 
26378 /*
26379  * Martian Address Filtering [RFC 1812, Section 5.3.7]
26380  */
26381 static boolean_t
26382 ip_no_forward(ipha_t *ipha, ill_t *ill)
26383 {
26384 	ipaddr_t ip_src, ip_dst;
26385 	ire_t *src_ire = NULL;
26386 
26387 	ip_src = ntohl(ipha->ipha_src);
26388 	ip_dst = ntohl(ipha->ipha_dst);
26389 
26390 	if (ip_dst == INADDR_ANY)
26391 		goto dont_forward;
26392 
26393 	if (IN_CLASSD(ip_src))
26394 		goto dont_forward;
26395 
26396 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
26397 		goto dont_forward;
26398 
26399 	if (IN_BADCLASS(ip_dst))
26400 		goto dont_forward;
26401 
26402 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
26403 	    ALL_ZONES, MATCH_IRE_TYPE);
26404 	if (src_ire != NULL) {
26405 		ire_refrele(src_ire);
26406 		goto dont_forward;
26407 	}
26408 
26409 	return (B_FALSE);
26410 
26411 dont_forward:
26412 	if (ip_debug > 2) {
26413 		printf("ip_no_forward: dropping packet received on %s\n",
26414 		    ill->ill_name);
26415 		pr_addr_dbg("ip_no_forward: from src %s\n",
26416 		    AF_INET, &ipha->ipha_src);
26417 		pr_addr_dbg("ip_no_forward: to dst %s\n",
26418 		    AF_INET, &ipha->ipha_dst);
26419 	}
26420 	BUMP_MIB(&ip_mib, ipForwProhibits);
26421 	return (B_TRUE);
26422 }
26423 
26424 static boolean_t
26425 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
26426 {
26427 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
26428 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
26429 		if (ip_debug > 2) {
26430 			if (ill != NULL) {
26431 				printf("ip_loopback_src_or_dst: "
26432 				    "dropping packet received on %s\n",
26433 				    ill->ill_name);
26434 			} else {
26435 				printf("ip_loopback_src_or_dst: "
26436 				    "dropping packet\n");
26437 			}
26438 
26439 			pr_addr_dbg(
26440 			    "ip_loopback_src_or_dst: from src %s\n",
26441 			    AF_INET, &ipha->ipha_src);
26442 			pr_addr_dbg(
26443 			    "ip_loopback_src_or_dst: to dst %s\n",
26444 			    AF_INET, &ipha->ipha_dst);
26445 		}
26446 
26447 		BUMP_MIB(&ip_mib, ipInAddrErrors);
26448 		return (B_TRUE);
26449 	}
26450 	return (B_FALSE);
26451 }
26452