xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision c138f478d2bc94e73ab8f6a084e323bec25e62f5)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_rts.h>
87 #include <inet/optcom.h>
88 #include <inet/ip_ndp.h>
89 #include <inet/ip_listutils.h>
90 #include <netinet/igmp.h>
91 #include <netinet/ip_mroute.h>
92 #include <inet/ipp_common.h>
93 
94 #include <net/pfkeyv2.h>
95 #include <inet/ipsec_info.h>
96 #include <inet/sadb.h>
97 #include <inet/ipsec_impl.h>
98 #include <sys/iphada.h>
99 #include <inet/tun.h>
100 #include <inet/ipdrop.h>
101 
102 #include <sys/ethernet.h>
103 #include <net/if_types.h>
104 #include <sys/cpuvar.h>
105 
106 #include <ipp/ipp.h>
107 #include <ipp/ipp_impl.h>
108 #include <ipp/ipgpc/ipgpc.h>
109 
110 #include <sys/multidata.h>
111 #include <sys/pattr.h>
112 
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/udp_impl.h>
116 
117 /*
118  * Values for squeue switch:
119  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
120  * IP_SQUEUE_ENTER: squeue_enter
121  * IP_SQUEUE_FILL: squeue_fill
122  */
123 int ip_squeue_enter = 2;
124 squeue_func_t ip_input_proc;
125 /*
126  * IP statistics.
127  */
128 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
129 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
130 
131 typedef struct ip_stat {
132 	kstat_named_t	ipsec_fanout_proto;
133 	kstat_named_t	ip_udp_fannorm;
134 	kstat_named_t	ip_udp_fanmb;
135 	kstat_named_t	ip_udp_fanothers;
136 	kstat_named_t	ip_udp_fast_path;
137 	kstat_named_t	ip_udp_slow_path;
138 	kstat_named_t	ip_udp_input_err;
139 	kstat_named_t	ip_tcppullup;
140 	kstat_named_t	ip_tcpoptions;
141 	kstat_named_t	ip_multipkttcp;
142 	kstat_named_t	ip_tcp_fast_path;
143 	kstat_named_t	ip_tcp_slow_path;
144 	kstat_named_t	ip_tcp_input_error;
145 	kstat_named_t	ip_db_ref;
146 	kstat_named_t	ip_notaligned1;
147 	kstat_named_t	ip_notaligned2;
148 	kstat_named_t	ip_multimblk3;
149 	kstat_named_t	ip_multimblk4;
150 	kstat_named_t	ip_ipoptions;
151 	kstat_named_t	ip_classify_fail;
152 	kstat_named_t	ip_opt;
153 	kstat_named_t	ip_udp_rput_local;
154 	kstat_named_t	ipsec_proto_ahesp;
155 	kstat_named_t	ip_conn_flputbq;
156 	kstat_named_t	ip_conn_walk_drain;
157 	kstat_named_t   ip_out_sw_cksum;
158 	kstat_named_t   ip_in_sw_cksum;
159 	kstat_named_t   ip_trash_ire_reclaim_calls;
160 	kstat_named_t   ip_trash_ire_reclaim_success;
161 	kstat_named_t   ip_ire_arp_timer_expired;
162 	kstat_named_t   ip_ire_redirect_timer_expired;
163 	kstat_named_t	ip_ire_pmtu_timer_expired;
164 	kstat_named_t	ip_input_multi_squeue;
165 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
166 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
167 	kstat_named_t	ip_tcp_in_sw_cksum_err;
168 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
169 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
170 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
171 	kstat_named_t	ip_udp_in_sw_cksum_err;
172 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
173 	kstat_named_t	ip_frag_mdt_pkt_out;
174 	kstat_named_t	ip_frag_mdt_discarded;
175 	kstat_named_t	ip_frag_mdt_allocfail;
176 	kstat_named_t	ip_frag_mdt_addpdescfail;
177 	kstat_named_t	ip_frag_mdt_allocd;
178 } ip_stat_t;
179 
180 static ip_stat_t ip_statistics = {
181 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
182 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
183 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
184 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
185 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
186 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
187 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
188 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
189 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
190 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
191 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
192 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
193 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
194 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
195 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
196 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
197 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
198 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
199 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
200 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
201 	{ "ip_opt",				KSTAT_DATA_UINT64 },
202 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
203 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
204 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
205 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
206 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
207 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
208 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
209 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
210 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
211 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
212 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
213 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
214 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
215 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
216 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
217 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
218 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
219 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
220 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
221 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
222 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
223 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
224 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
225 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
226 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
227 };
228 
229 static kstat_t *ip_kstat;
230 
231 #define	TCP6 "tcp6"
232 #define	TCP "tcp"
233 #define	SCTP "sctp"
234 #define	SCTP6 "sctp6"
235 
236 major_t TCP6_MAJ;
237 major_t TCP_MAJ;
238 major_t SCTP_MAJ;
239 major_t SCTP6_MAJ;
240 
241 int ip_poll_normal_ms = 100;
242 int ip_poll_normal_ticks = 0;
243 
244 /*
245  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
246  */
247 
248 struct listptr_s {
249 	mblk_t	*lp_head;	/* pointer to the head of the list */
250 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
251 };
252 
253 typedef struct listptr_s listptr_t;
254 
255 /*
256  * Cluster specific hooks. These should be NULL when booted as a non-cluster
257  */
258 
259 /*
260  * Hook functions to enable cluster networking
261  * On non-clustered systems these vectors must always be NULL.
262  *
263  * Hook function to Check ip specified ip address is a shared ip address
264  * in the cluster
265  *
266  */
267 int (*cl_inet_isclusterwide)(uint8_t protocol,
268     sa_family_t addr_family, uint8_t *laddrp) = NULL;
269 
270 /*
271  * Hook function to generate cluster wide ip fragment identifier
272  */
273 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
274     uint8_t *laddrp, uint8_t *faddrp) = NULL;
275 
276 /*
277  * Synchronization notes:
278  *
279  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
280  * MT level protection given by STREAMS. IP uses a combination of its own
281  * internal serialization mechanism and standard Solaris locking techniques.
282  * The internal serialization is per phyint (no IPMP) or per IPMP group.
283  * This is used to serialize plumbing operations, IPMP operations, certain
284  * multicast operations, most set ioctls, igmp/mld timers etc.
285  *
286  * Plumbing is a long sequence of operations involving message
287  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
288  * involved in plumbing operations. A natural model is to serialize these
289  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
290  * parallel without any interference. But various set ioctls on hme0 are best
291  * serialized. However if the system uses IPMP, the operations are easier if
292  * they are serialized on a per IPMP group basis since IPMP operations
293  * happen across ill's of a group. Thus the lowest common denominator is to
294  * serialize most set ioctls, multicast join/leave operations, IPMP operations
295  * igmp/mld timer operations, and processing of DLPI control messages received
296  * from drivers on a per IPMP group basis. If the system does not employ
297  * IPMP the serialization is on a per phyint basis. This serialization is
298  * provided by the ipsq_t and primitives operating on this. Details can
299  * be found in ip_if.c above the core primitives operating on ipsq_t.
300  *
301  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
302  * Simiarly lookup of an ire by a thread also returns a refheld ire.
303  * In addition ipif's and ill's referenced by the ire are also indirectly
304  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
305  * the ipif's address or netmask change as long as an ipif is refheld
306  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
307  * address of an ipif has to go through the ipsq_t. This ensures that only
308  * 1 such exclusive operation proceeds at any time on the ipif. It then
309  * deletes all ires associated with this ipif, and waits for all refcnts
310  * associated with this ipif to come down to zero. The address is changed
311  * only after the ipif has been quiesced. Then the ipif is brought up again.
312  * More details are described above the comment in ip_sioctl_flags.
313  *
314  * Packet processing is based mostly on IREs and are fully multi-threaded
315  * using standard Solaris MT techniques.
316  *
317  * There are explicit locks in IP to handle:
318  * - The ip_g_head list maintained by mi_open_link() and friends.
319  *
320  * - The reassembly data structures (one lock per hash bucket)
321  *
322  * - conn_lock is meant to protect conn_t fields. The fields actually
323  *   protected by conn_lock are documented in the conn_t definition.
324  *
325  * - ire_lock to protect some of the fields of the ire, IRE tables
326  *   (one lock per hash bucket). Refer to ip_ire.c for details.
327  *
328  * - ndp_g_lock and nce_lock for protecting NCEs.
329  *
330  * - ill_lock protects fields of the ill and ipif. Details in ip.h
331  *
332  * - ill_g_lock: This is a global reader/writer lock. Protects the following
333  *	* The AVL tree based global multi list of all ills.
334  *	* The linked list of all ipifs of an ill
335  *	* The <ill-ipsq> mapping
336  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
337  *	* The illgroup list threaded by ill_group_next.
338  *	* <ill-phyint> association
339  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
340  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
341  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
342  *   will all have to hold the ill_g_lock as writer for the actual duration
343  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
344  *   may be found in the IPMP section.
345  *
346  * - ill_lock:  This is a per ill mutex.
347  *   It protects some members of the ill and is documented below.
348  *   It also protects the <ill-ipsq> mapping
349  *   It also protects the illgroup list threaded by ill_group_next.
350  *   It also protects the <ill-phyint> assoc.
351  *   It also protects the list of ipifs hanging off the ill.
352  *
353  * - ipsq_lock: This is a per ipsq_t mutex lock.
354  *   This protects all the other members of the ipsq struct except
355  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
356  *
357  * - illgrp_lock: This is a per ill_group mutex lock.
358  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
359  *   which dictates which is the next ill in an ill_group that is to be chosen
360  *   for sending outgoing packets, through creation of an IRE_CACHE that
361  *   references this ill.
362  *
363  * - phyint_lock: This is a per phyint mutex lock. Protects just the
364  *   phyint_flags
365  *
366  * - ip_g_nd_lock: This is a global reader/writer lock.
367  *   Any call to nd_load to load a new parameter to the ND table must hold the
368  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
369  *   as reader.
370  *
371  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
372  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
373  *   uniqueness check also done atomically.
374  *
375  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
376  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
377  *   as a writer when adding or deleting elements from these lists, and
378  *   as a reader when walking these lists to send a SADB update to the
379  *   IPsec capable ills.
380  *
381  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
382  *   group list linked by ill_usesrc_grp_next. It also protects the
383  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
384  *   group is being added or deleted.  This lock is taken as a reader when
385  *   walking the list/group(eg: to get the number of members in a usesrc group).
386  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
387  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
388  *   example, it is not necessary to take this lock in the initial portion
389  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
390  *   ip_sioctl_flags since the these operations are executed exclusively and
391  *   that ensures that the "usesrc group state" cannot change. The "usesrc
392  *   group state" change can happen only in the latter part of
393  *   ip_sioctl_slifusesrc and in ill_delete.
394  *
395  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
396  *
397  * To change the <ill-phyint> association, the ill_g_lock must be held
398  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
399  * must be held.
400  *
401  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
402  * and the ill_lock of the ill in question must be held.
403  *
404  * To change the <ill-illgroup> association the ill_g_lock must be held as
405  * writer and the ill_lock of the ill in question must be held.
406  *
407  * To add or delete an ipif from the list of ipifs hanging off the ill,
408  * ill_g_lock (writer) and ill_lock must be held and the thread must be
409  * a writer on the associated ipsq,.
410  *
411  * To add or delete an ill to the system, the ill_g_lock must be held as
412  * writer and the thread must be a writer on the associated ipsq.
413  *
414  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
415  * must be a writer on the associated ipsq.
416  *
417  * Lock hierarchy
418  *
419  * Some lock hierarchy scenarios are listed below.
420  *
421  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
422  * ill_g_lock -> illgrp_lock -> ill_lock
423  * ill_g_lock -> ill_lock(s) -> phyint_lock
424  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
425  * ill_g_lock -> ip_addr_avail_lock
426  * conn_lock -> irb_lock -> ill_lock -> ire_lock
427  * ipsa_lock -> ill_g_lock -> ill_lock
428  * ill_g_lock -> ip_g_nd_lock
429  * irb_lock -> ill_lock -> ire_mrtun_lock
430  * irb_lock -> ill_lock -> ire_srcif_table_lock
431  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
432  * ipsec_capab_ills_lock -> ipsa_lock
433  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
434  *
435  * When more than 1 ill lock is needed to be held, all ill lock addresses
436  * are sorted on address and locked starting from highest addressed lock
437  * downward.
438  *
439  * IPSEC notes :
440  *
441  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
442  * in front of the actual packet. For outbound datagrams, the M_CTL
443  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
444  * information used by the IPSEC code for applying the right level of
445  * protection. The information initialized by IP in the ipsec_out_t
446  * is determined by the per-socket policy or global policy in the system.
447  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
448  * ipsec_info.h) which starts out with nothing in it. It gets filled
449  * with the right information if it goes through the AH/ESP code, which
450  * happens if the incoming packet is secure. The information initialized
451  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
452  * the policy requirements needed by per-socket policy or global policy
453  * is met or not.
454  *
455  * If there is both per-socket policy (set using setsockopt) and there
456  * is also global policy match for the 5 tuples of the socket,
457  * ipsec_override_policy() makes the decision of which one to use.
458  *
459  * For fully connected sockets i.e dst, src [addr, port] is known,
460  * conn_policy_cached is set indicating that policy has been cached.
461  * conn_in_enforce_policy may or may not be set depending on whether
462  * there is a global policy match or per-socket policy match.
463  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
464  * Once the right policy is set on the conn_t, policy cannot change for
465  * this socket. This makes life simpler for TCP (UDP ?) where
466  * re-transmissions go out with the same policy. For symmetry, policy
467  * is cached for fully connected UDP sockets also. Thus if policy is cached,
468  * it also implies that policy is latched i.e policy cannot change
469  * on these sockets. As we have the right policy on the conn, we don't
470  * have to lookup global policy for every outbound and inbound datagram
471  * and thus serving as an optimization. Note that a global policy change
472  * does not affect fully connected sockets if they have policy. If fully
473  * connected sockets did not have any policy associated with it, global
474  * policy change may affect them.
475  *
476  * IP Flow control notes:
477  *
478  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
479  * cannot be sent down to the driver by IP, because of a canput failure, IP
480  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
481  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
482  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
483  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
484  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
485  * the queued messages, and removes the conn from the drain list, if all
486  * messages were drained. It also qenables the next conn in the drain list to
487  * continue the drain process.
488  *
489  * In reality the drain list is not a single list, but a configurable number
490  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
491  * list. If the ip_wsrv of the next qenabled conn does not run, because the
492  * stream closes, ip_close takes responsibility to qenable the next conn in
493  * the drain list. The directly called ip_wput path always does a putq, if
494  * it cannot putnext. Thus synchronization problems are handled between
495  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
496  * functions that manipulate this drain list. Furthermore conn_drain_insert
497  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
498  * running on a queue at any time. conn_drain_tail can be simultaneously called
499  * from both ip_wsrv and ip_close.
500  *
501  * IPQOS notes:
502  *
503  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
504  * and IPQoS modules. IPPF includes hooks in IP at different control points
505  * (callout positions) which direct packets to IPQoS modules for policy
506  * processing. Policies, if present, are global.
507  *
508  * The callout positions are located in the following paths:
509  *		o local_in (packets destined for this host)
510  *		o local_out (packets orginating from this host )
511  *		o fwd_in  (packets forwarded by this m/c - inbound)
512  *		o fwd_out (packets forwarded by this m/c - outbound)
513  * Hooks at these callout points can be enabled/disabled using the ndd variable
514  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
515  * By default all the callout positions are enabled.
516  *
517  * Outbound (local_out)
518  * Hooks are placed in ip_wput_ire and ipsec_out_process.
519  *
520  * Inbound (local_in)
521  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
522  * TCP and UDP fanout routines.
523  *
524  * Forwarding (in and out)
525  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
526  *
527  * IP Policy Framework processing (IPPF processing)
528  * Policy processing for a packet is initiated by ip_process, which ascertains
529  * that the classifier (ipgpc) is loaded and configured, failing which the
530  * packet resumes normal processing in IP. If the clasifier is present, the
531  * packet is acted upon by one or more IPQoS modules (action instances), per
532  * filters configured in ipgpc and resumes normal IP processing thereafter.
533  * An action instance can drop a packet in course of its processing.
534  *
535  * A boolean variable, ip_policy, is used in all the fanout routines that can
536  * invoke ip_process for a packet. This variable indicates if the packet should
537  * to be sent for policy processing. The variable is set to B_TRUE by default,
538  * i.e. when the routines are invoked in the normal ip procesing path for a
539  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
540  * ip_policy is set to B_FALSE for all the routines called in these two
541  * functions because, in the former case,  we don't process loopback traffic
542  * currently while in the latter, the packets have already been processed in
543  * icmp_inbound.
544  *
545  * Zones notes:
546  *
547  * The partitioning rules for networking are as follows:
548  * 1) Packets coming from a zone must have a source address belonging to that
549  * zone.
550  * 2) Packets coming from a zone can only be sent on a physical interface on
551  * which the zone has an IP address.
552  * 3) Between two zones on the same machine, packet delivery is only allowed if
553  * there's a matching route for the destination and zone in the forwarding
554  * table.
555  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
556  * different zones can bind to the same port with the wildcard address
557  * (INADDR_ANY).
558  *
559  * The granularity of interface partitioning is at the logical interface level.
560  * Therefore, every zone has its own IP addresses, and incoming packets can be
561  * attributed to a zone unambiguously. A logical interface is placed into a zone
562  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
563  * structure. Rule (1) is implemented by modifying the source address selection
564  * algorithm so that the list of eligible addresses is filtered based on the
565  * sending process zone.
566  *
567  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
568  * across all zones, depending on their type. Here is the break-up:
569  *
570  * IRE type				Shared/exclusive
571  * --------				----------------
572  * IRE_BROADCAST			Exclusive
573  * IRE_DEFAULT (default routes)		Shared (*)
574  * IRE_LOCAL				Exclusive
575  * IRE_LOOPBACK				Exclusive
576  * IRE_PREFIX (net routes)		Shared (*)
577  * IRE_CACHE				Exclusive
578  * IRE_IF_NORESOLVER (interface routes)	Exclusive
579  * IRE_IF_RESOLVER (interface routes)	Exclusive
580  * IRE_HOST (host routes)		Shared (*)
581  *
582  * (*) A zone can only use a default or off-subnet route if the gateway is
583  * directly reachable from the zone, that is, if the gateway's address matches
584  * one of the zone's logical interfaces.
585  *
586  * Multiple zones can share a common broadcast address; typically all zones
587  * share the 255.255.255.255 address. Incoming as well as locally originated
588  * broadcast packets must be dispatched to all the zones on the broadcast
589  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
590  * since some zones may not be on the 10.16.72/24 network. To handle this, each
591  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
592  * sent to every zone that has an IRE_BROADCAST entry for the destination
593  * address on the input ill, see conn_wantpacket().
594  *
595  * Applications in different zones can join the same multicast group address.
596  * For IPv4, group memberships are per-logical interface, so they're already
597  * inherently part of a zone. For IPv6, group memberships are per-physical
598  * interface, so we distinguish IPv6 group memberships based on group address,
599  * interface and zoneid. In both cases, received multicast packets are sent to
600  * every zone for which a group membership entry exists. On IPv6 we need to
601  * check that the target zone still has an address on the receiving physical
602  * interface; it could have been removed since the application issued the
603  * IPV6_JOIN_GROUP.
604  */
605 
606 /*
607  * Squeue Fanout flags:
608  *	0: No fanout.
609  *	1: Fanout across all squeues
610  */
611 boolean_t	ip_squeue_fanout = 0;
612 
613 /*
614  * Maximum dups allowed per packet.
615  */
616 uint_t ip_max_frag_dups = 10;
617 
618 #define	IS_SIMPLE_IPH(ipha)						\
619 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
620 
621 /* RFC1122 Conformance */
622 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
623 
624 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
625 
626 /* Leave room for ip_newroute to tack on the src and target addresses */
627 #define	OK_RESOLVER_MP(mp)						\
628 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
629 
630 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
631 
632 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
633 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
634 
635 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
636 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
637     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
638 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
639 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
640 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
641 		    ill_t *, zoneid_t);
642 static void	icmp_options_update(ipha_t *);
643 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
644 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
645 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
646 static void	icmp_redirect(mblk_t *);
647 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
648 
649 static void	ip_arp_news(queue_t *, mblk_t *);
650 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
651 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
652 char		*ip_dot_addr(ipaddr_t, char *);
653 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
654 int		ip_close(queue_t *, int);
655 static char	*ip_dot_saddr(uchar_t *, char *);
656 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
657 		    boolean_t, boolean_t, ill_t *, zoneid_t);
658 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
659 		    boolean_t, boolean_t, zoneid_t);
660 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
661 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
662 static void	ip_lrput(queue_t *, mblk_t *);
663 ipaddr_t	ip_massage_options(ipha_t *);
664 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
665 ipaddr_t	ip_net_mask(ipaddr_t);
666 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
667 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
668 		    conn_t *, uint32_t);
669 static int	ip_hdr_complete(ipha_t *, zoneid_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
672 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
673 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
674 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
675 			    size_t);
676 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
677 void	ip_rput(queue_t *, mblk_t *);
678 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
679 		    void *dummy_arg);
680 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
681 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
682 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
683 			    ire_t *);
684 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
685 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
686 		    uint16_t *);
687 int		ip_snmp_get(queue_t *, mblk_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
689 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
690 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
691 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
692 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
693 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
694 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
695 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
696 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
698 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
699 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
700 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
701 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
704 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
705 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 
711 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
712 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
713 static void	ip_wput_local_options(ipha_t *);
714 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
715     zoneid_t);
716 
717 static void	conn_drain_init(void);
718 static void	conn_drain_fini(void);
719 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
720 
721 static void	conn_walk_drain(void);
722 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
723     zoneid_t);
724 
725 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
726     zoneid_t);
727 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
728     void *dummy_arg);
729 
730 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
731 
732 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
733     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
734     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
735 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
736 
737 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
738 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
739     caddr_t, cred_t *);
740 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
741     caddr_t cp, cred_t *cr);
742 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
743     cred_t *);
744 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
745     caddr_t cp, cred_t *cr);
746 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
747     cred_t *);
748 static squeue_func_t ip_squeue_switch(int);
749 
750 static void	ip_kstat_init(void);
751 static void	ip_kstat_fini(void);
752 static int	ip_kstat_update(kstat_t *kp, int rw);
753 static void	icmp_kstat_init(void);
754 static void	icmp_kstat_fini(void);
755 static int	icmp_kstat_update(kstat_t *kp, int rw);
756 
757 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
758 
759 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
760 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
761 
762 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
763     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
764 
765 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
766 
767 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
768 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
769 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
770 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
771 
772 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
773 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
774 
775 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
776 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
777 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
778 
779 /* How long, in seconds, we allow frags to hang around. */
780 #define	IP_FRAG_TIMEOUT	60
781 
782 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
783 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
784 
785 /*
786  * Threshold which determines whether MDT should be used when
787  * generating IP fragments; payload size must be greater than
788  * this threshold for MDT to take place.
789  */
790 #define	IP_WPUT_FRAG_MDT_MIN	32768
791 
792 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
793 
794 /* Protected by ip_mi_lock */
795 static void	*ip_g_head;		/* Instance Data List Head */
796 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
797 
798 /* Only modified during _init and _fini thus no locking is needed. */
799 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
800 
801 
802 static long ip_rput_pullups;
803 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
804 
805 vmem_t *ip_minor_arena;
806 
807 /*
808  * MIB-2 stuff for SNMP (both IP and ICMP)
809  */
810 mib2_ip_t	ip_mib;
811 mib2_icmp_t	icmp_mib;
812 
813 #ifdef DEBUG
814 uint32_t ipsechw_debug = 0;
815 #endif
816 
817 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
818 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
819 
820 uint_t	loopback_packets = 0;
821 
822 /*
823  * Multirouting/CGTP stuff
824  */
825 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
826 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
827 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
828 /* Interval (in ms) between consecutive 'bad MTU' warnings */
829 hrtime_t ip_multirt_log_interval = 1000;
830 /* Time since last warning issued. */
831 static hrtime_t	multirt_bad_mtu_last_time = 0;
832 
833 kmutex_t ip_trash_timer_lock;
834 krwlock_t ip_g_nd_lock;
835 
836 /*
837  * XXX following really should only be in a header. Would need more
838  * header and .c clean up first.
839  */
840 extern optdb_obj_t	ip_opt_obj;
841 
842 ulong_t ip_squeue_enter_unbound = 0;
843 
844 /*
845  * Named Dispatch Parameter Table.
846  * All of these are alterable, within the min/max values given, at run time.
847  */
848 static ipparam_t	lcl_param_arr[] = {
849 	/* min	max	value	name */
850 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
851 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
852 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
853 	{  0,	1,	0,	"ip_respond_to_timestamp"},
854 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
855 	{  0,	1,	1,	"ip_send_redirects"},
856 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
857 	{  0,	10,	0,	"ip_debug"},
858 	{  0,	10,	0,	"ip_mrtdebug"},
859 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
860 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
861 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
862 	{  1,	255,	255,	"ip_def_ttl" },
863 	{  0,	1,	0,	"ip_forward_src_routed"},
864 	{  0,	256,	32,	"ip_wroff_extra" },
865 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
866 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
867 	{  0,	1,	1,	"ip_path_mtu_discovery" },
868 	{  0,	240,	30,	"ip_ignore_delete_time" },
869 	{  0,	1,	0,	"ip_ignore_redirect" },
870 	{  0,	1,	1,	"ip_output_queue" },
871 	{  1,	254,	1,	"ip_broadcast_ttl" },
872 	{  0,	99999,	100,	"ip_icmp_err_interval" },
873 	{  1,	99999,	10,	"ip_icmp_err_burst" },
874 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
875 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
876 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
877 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
878 	{  0,	1,	1,	"icmp_accept_clear_messages" },
879 	{  0,	1,	1,	"igmp_accept_clear_messages" },
880 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
881 				"ip_ndp_delay_first_probe_time"},
882 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
883 				"ip_ndp_max_unicast_solicit"},
884 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
885 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
886 	{  0,	1,	0,	"ip6_forward_src_routed"},
887 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
888 	{  0,	1,	1,	"ip6_send_redirects"},
889 	{  0,	1,	0,	"ip6_ignore_redirect" },
890 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
891 
892 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
893 
894 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
895 
896 	{  0,	1,	1,	"pim_accept_clear_messages" },
897 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
898 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
899 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
900 	{  0,	15,	0,	"ip_policy_mask" },
901 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
902 	{  0,	255,	1,	"ip_multirt_ttl" },
903 	{  0,	1,	1,	"ip_multidata_outbound" },
904 #ifdef DEBUG
905 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
906 #endif
907 };
908 
909 ipparam_t	*ip_param_arr = lcl_param_arr;
910 
911 /* Extended NDP table */
912 static ipndp_t	lcl_ndp_arr[] = {
913 	/* getf			setf		data			name */
914 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
915 	    "ip_forwarding" },
916 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
917 	    "ip6_forwarding" },
918 	{  ip_ill_report,	NULL,		NULL,
919 	    "ip_ill_status" },
920 	{  ip_ipif_report,	NULL,		NULL,
921 	    "ip_ipif_status" },
922 	{  ip_ire_report,	NULL,		NULL,
923 	    "ipv4_ire_status" },
924 	{  ip_ire_report_mrtun,	NULL,		NULL,
925 	    "ipv4_mrtun_ire_status" },
926 	{  ip_ire_report_srcif,	NULL,		NULL,
927 	    "ipv4_srcif_ire_status" },
928 	{  ip_ire_report_v6,	NULL,		NULL,
929 	    "ipv6_ire_status" },
930 	{  ip_conn_report,	NULL,		NULL,
931 	    "ip_conn_status" },
932 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
933 	    "ip_rput_pullups" },
934 	{  ndp_report,		NULL,		NULL,
935 	    "ip_ndp_cache_report" },
936 	{  ip_srcid_report,	NULL,		NULL,
937 	    "ip_srcid_status" },
938 	{ ip_param_generic_get, ip_squeue_profile_set,
939 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
940 	{ ip_param_generic_get, ip_squeue_bind_set,
941 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
942 	{ ip_param_generic_get, ip_input_proc_set,
943 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
944 	{ ip_param_generic_get, ip_int_set,
945 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
946 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
947 	    "ip_cgtp_filter" },
948 	{ ip_param_generic_get, ip_int_set,
949 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
950 };
951 
952 /*
953  * ip_g_forward controls IP forwarding.  It takes two values:
954  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
955  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
956  *
957  * RFC1122 says there must be a configuration switch to control forwarding,
958  * but that the default MUST be to not forward packets ever.  Implicit
959  * control based on configuration of multiple interfaces MUST NOT be
960  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
961  * and, in fact, it was the default.  That capability is now provided in the
962  * /etc/rc2.d/S69inet script.
963  */
964 int ip_g_forward = IP_FORWARD_DEFAULT;
965 
966 /* It also has an IPv6 counterpart. */
967 
968 int ipv6_forward = IP_FORWARD_DEFAULT;
969 
970 /* Following line is external, and in ip.h.  Normally marked with * *. */
971 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
972 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
973 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
974 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
975 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
976 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
977 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
978 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
979 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
980 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
981 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
982 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
983 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
984 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
985 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
986 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
987 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
988 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
989 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
990 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
991 #define	ip_output_queue			ip_param_arr[20].ip_param_value
992 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
993 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
994 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
995 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
996 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
997 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
998 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
999 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
1000 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
1001 
1002 /* IPv6 configuration knobs */
1003 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1004 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1005 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1006 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1007 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1008 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1009 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1010 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1011 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1012 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1013 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1014 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1015 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1016 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1017 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1018 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1019 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1020 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1021 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1022 #ifdef DEBUG
1023 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1024 #else
1025 #define	ipv6_drop_inbound_icmpv6	0
1026 #endif
1027 
1028 
1029 /*
1030  * Table of IP ioctls encoding the various properties of the ioctl and
1031  * indexed based on the last byte of the ioctl command. Occasionally there
1032  * is a clash, and there is more than 1 ioctl with the same last byte.
1033  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1034  * ioctls are encoded in the misc table. An entry in the ndx table is
1035  * retrieved by indexing on the last byte of the ioctl command and comparing
1036  * the ioctl command with the value in the ndx table. In the event of a
1037  * mismatch the misc table is then searched sequentially for the desired
1038  * ioctl command.
1039  *
1040  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1041  */
1042 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1043 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 
1054 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1055 			MISC_CMD, ip_siocaddrt, NULL },
1056 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1057 			MISC_CMD, ip_siocdelrt, NULL },
1058 
1059 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1060 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1061 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1062 			IF_CMD, ip_sioctl_get_addr, NULL },
1063 
1064 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1065 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1066 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1067 			IPI_GET_CMD | IPI_REPL,
1068 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1069 
1070 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1071 			IPI_PRIV | IPI_WR | IPI_REPL,
1072 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1073 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1074 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1075 			IF_CMD, ip_sioctl_get_flags, NULL },
1076 
1077 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 
1080 	/* copyin size cannot be coded for SIOCGIFCONF */
1081 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1082 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1083 
1084 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_mtu, NULL },
1086 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1087 			IF_CMD, ip_sioctl_get_mtu, NULL },
1088 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1089 			IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1091 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1092 			IF_CMD, ip_sioctl_brdaddr, NULL },
1093 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1094 			IPI_GET_CMD | IPI_REPL,
1095 			IF_CMD, ip_sioctl_get_netmask, NULL },
1096 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1097 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1098 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1099 			IPI_GET_CMD | IPI_REPL,
1100 			IF_CMD, ip_sioctl_get_metric, NULL },
1101 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1102 			IF_CMD, ip_sioctl_metric, NULL },
1103 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 
1105 	/* See 166-168 below for extended SIOC*XARP ioctls */
1106 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1107 			MISC_CMD, ip_sioctl_arp, NULL },
1108 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1109 			MISC_CMD, ip_sioctl_arp, NULL },
1110 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1111 			MISC_CMD, ip_sioctl_arp, NULL },
1112 
1113 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1136 			MISC_CMD, if_unitsel, if_unitsel_restart },
1137 
1138 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 
1157 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			IF_CMD, ip_sioctl_sifname, NULL },
1160 
1161 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 
1175 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1176 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1177 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1178 			IF_CMD, ip_sioctl_get_muxid, NULL },
1179 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1180 			IPI_PRIV | IPI_WR | IPI_REPL,
1181 			IF_CMD, ip_sioctl_muxid, NULL },
1182 
1183 	/* Both if and lif variants share same func */
1184 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1185 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1186 	/* Both if and lif variants share same func */
1187 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1188 			IPI_PRIV | IPI_WR | IPI_REPL,
1189 			IF_CMD, ip_sioctl_slifindex, NULL },
1190 
1191 	/* copyin size cannot be coded for SIOCGIFCONF */
1192 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1193 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1194 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 
1212 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1213 			IPI_PRIV | IPI_WR | IPI_REPL,
1214 			LIF_CMD, ip_sioctl_removeif,
1215 			ip_sioctl_removeif_restart },
1216 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1217 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1218 			LIF_CMD, ip_sioctl_addif, NULL },
1219 #define	SIOCLIFADDR_NDX 112
1220 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1221 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1222 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1223 			IPI_GET_CMD | IPI_REPL,
1224 			LIF_CMD, ip_sioctl_get_addr, NULL },
1225 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1227 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1228 			IPI_GET_CMD | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1230 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1233 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_flags, NULL },
1236 
1237 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 
1240 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1241 			ip_sioctl_get_lifconf, NULL },
1242 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_mtu, NULL },
1244 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1245 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1246 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1247 			IPI_GET_CMD | IPI_REPL,
1248 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1249 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1251 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1252 			IPI_GET_CMD | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1254 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1256 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_metric, NULL },
1259 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_metric, NULL },
1261 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1262 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1263 			LIF_CMD, ip_sioctl_slifname,
1264 			ip_sioctl_slifname_restart },
1265 
1266 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1267 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1268 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1269 			IPI_GET_CMD | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1271 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1272 			IPI_PRIV | IPI_WR | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_muxid, NULL },
1274 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1277 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1278 			IPI_PRIV | IPI_WR | IPI_REPL,
1279 			LIF_CMD, ip_sioctl_slifindex, 0 },
1280 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1281 			LIF_CMD, ip_sioctl_token, NULL },
1282 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1283 			IPI_GET_CMD | IPI_REPL,
1284 			LIF_CMD, ip_sioctl_get_token, NULL },
1285 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1286 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1287 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1288 			IPI_GET_CMD | IPI_REPL,
1289 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1290 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1291 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1292 
1293 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1294 			IPI_GET_CMD | IPI_REPL,
1295 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1296 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1297 			LIF_CMD, ip_siocdelndp_v6, NULL },
1298 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1299 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1300 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1301 			LIF_CMD, ip_siocsetndp_v6, NULL },
1302 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1303 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1304 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1305 			MISC_CMD, ip_sioctl_tonlink, NULL },
1306 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1307 			MISC_CMD, ip_sioctl_tmysite, NULL },
1308 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1309 			TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1311 			IPI_PRIV | IPI_WR,
1312 			TUN_CMD, ip_sioctl_tunparam, NULL },
1313 
1314 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1315 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1316 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1317 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1318 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1319 
1320 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1321 			IPI_PRIV | IPI_WR | IPI_REPL,
1322 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1323 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1324 			IPI_PRIV | IPI_WR | IPI_REPL,
1325 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1326 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1327 			IPI_PRIV | IPI_WR,
1328 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1329 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1330 			IPI_GET_CMD | IPI_REPL,
1331 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1332 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1333 			IPI_GET_CMD | IPI_REPL,
1334 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1335 
1336 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1337 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1338 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1339 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1340 
1341 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1342 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1343 
1344 	/* These are handled in ip_sioctl_copyin_setup itself */
1345 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1346 			MISC_CMD, NULL, NULL },
1347 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1348 			MISC_CMD, NULL, NULL },
1349 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1350 
1351 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1352 			ip_sioctl_get_lifconf, NULL },
1353 
1354 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1355 			MISC_CMD, ip_sioctl_xarp, NULL },
1356 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1357 			MISC_CMD, ip_sioctl_xarp, NULL },
1358 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1359 			MISC_CMD, ip_sioctl_xarp, NULL },
1360 
1361 	/* SIOCPOPSOCKFS is not handled by IP */
1362 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1363 
1364 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1365 			IPI_GET_CMD | IPI_REPL,
1366 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1367 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1368 			IPI_PRIV | IPI_WR | IPI_REPL,
1369 			LIF_CMD, ip_sioctl_slifzone,
1370 			ip_sioctl_slifzone_restart },
1371 	/* 172-174 are SCTP ioctls and not handled by IP */
1372 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1373 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1374 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1375 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1376 			IPI_GET_CMD, LIF_CMD,
1377 			ip_sioctl_get_lifusesrc, 0 },
1378 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1379 			IPI_PRIV | IPI_WR,
1380 			LIF_CMD, ip_sioctl_slifusesrc,
1381 			NULL },
1382 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1383 			ip_sioctl_get_lifsrcof, NULL },
1384 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1385 			MISC_CMD, ip_sioctl_msfilter, NULL },
1386 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1387 			MISC_CMD, ip_sioctl_msfilter, NULL },
1388 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1389 			MISC_CMD, ip_sioctl_msfilter, NULL },
1390 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1391 			MISC_CMD, ip_sioctl_msfilter, NULL },
1392 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1393 			ip_sioctl_set_ipmpfailback, NULL }
1394 };
1395 
1396 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1397 
1398 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1399 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1400 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1401 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1402 		TUN_CMD, ip_sioctl_tunparam, NULL },
1403 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1404 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1405 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1406 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1407 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1408 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1409 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1410 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1411 		MISC_CMD, mrt_ioctl},
1412 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1413 		MISC_CMD, mrt_ioctl},
1414 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1415 		MISC_CMD, mrt_ioctl}
1416 };
1417 
1418 int ip_misc_ioctl_count =
1419     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1420 
1421 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1422 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1423 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1424 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1425 					/* Settable in /etc/system */
1426 
1427 /* Defined in ip_ire.c */
1428 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1429 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1430 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1431 
1432 static nv_t	ire_nv_arr[] = {
1433 	{ IRE_BROADCAST, "BROADCAST" },
1434 	{ IRE_LOCAL, "LOCAL" },
1435 	{ IRE_LOOPBACK, "LOOPBACK" },
1436 	{ IRE_CACHE, "CACHE" },
1437 	{ IRE_DEFAULT, "DEFAULT" },
1438 	{ IRE_PREFIX, "PREFIX" },
1439 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1440 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1441 	{ IRE_HOST, "HOST" },
1442 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1443 	{ 0 }
1444 };
1445 
1446 nv_t	*ire_nv_tbl = ire_nv_arr;
1447 
1448 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1449 extern krwlock_t ipsec_capab_ills_lock;
1450 
1451 /* Packet dropper for IP IPsec processing failures */
1452 ipdropper_t ip_dropper;
1453 
1454 /* Simple ICMP IP Header Template */
1455 static ipha_t icmp_ipha = {
1456 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1457 };
1458 
1459 struct module_info ip_mod_info = {
1460 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1461 };
1462 
1463 static struct qinit rinit = {
1464 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1465 	&ip_mod_info
1466 };
1467 
1468 static struct qinit winit = {
1469 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1470 	&ip_mod_info
1471 };
1472 
1473 static struct qinit lrinit = {
1474 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1475 	&ip_mod_info
1476 };
1477 
1478 static struct qinit lwinit = {
1479 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1480 	&ip_mod_info
1481 };
1482 
1483 struct streamtab ipinfo = {
1484 	&rinit, &winit, &lrinit, &lwinit
1485 };
1486 
1487 #ifdef	DEBUG
1488 static boolean_t skip_sctp_cksum = B_FALSE;
1489 #endif
1490 /*
1491  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1492  */
1493 mblk_t *
1494 ip_copymsg(mblk_t *mp)
1495 {
1496 	mblk_t *nmp;
1497 	ipsec_info_t *in;
1498 
1499 	if (mp->b_datap->db_type != M_CTL)
1500 		return (copymsg(mp));
1501 
1502 	in = (ipsec_info_t *)mp->b_rptr;
1503 
1504 	/*
1505 	 * Note that M_CTL is also used for delivering ICMP error messages
1506 	 * upstream to transport layers.
1507 	 */
1508 	if (in->ipsec_info_type != IPSEC_OUT &&
1509 	    in->ipsec_info_type != IPSEC_IN)
1510 		return (copymsg(mp));
1511 
1512 	nmp = copymsg(mp->b_cont);
1513 
1514 	if (in->ipsec_info_type == IPSEC_OUT)
1515 		return (ipsec_out_tag(mp, nmp));
1516 	else
1517 		return (ipsec_in_tag(mp, nmp));
1518 }
1519 
1520 /* Generate an ICMP fragmentation needed message. */
1521 static void
1522 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1523 {
1524 	icmph_t	icmph;
1525 	mblk_t *first_mp;
1526 	boolean_t mctl_present;
1527 
1528 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1529 
1530 	if (!(mp = icmp_pkt_err_ok(mp))) {
1531 		if (mctl_present)
1532 			freeb(first_mp);
1533 		return;
1534 	}
1535 
1536 	bzero(&icmph, sizeof (icmph_t));
1537 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1538 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1539 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1540 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1541 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1542 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1543 }
1544 
1545 /*
1546  * icmp_inbound deals with ICMP messages in the following ways.
1547  *
1548  * 1) It needs to send a reply back and possibly delivering it
1549  *    to the "interested" upper clients.
1550  * 2) It needs to send it to the upper clients only.
1551  * 3) It needs to change some values in IP only.
1552  * 4) It needs to change some values in IP and upper layers e.g TCP.
1553  *
1554  * We need to accomodate icmp messages coming in clear until we get
1555  * everything secure from the wire. If icmp_accept_clear_messages
1556  * is zero we check with the global policy and act accordingly. If
1557  * it is non-zero, we accept the message without any checks. But
1558  * *this does not mean* that this will be delivered to the upper
1559  * clients. By accepting we might send replies back, change our MTU
1560  * value etc. but delivery to the ULP/clients depends on their policy
1561  * dispositions.
1562  *
1563  * We handle the above 4 cases in the context of IPSEC in the
1564  * following way :
1565  *
1566  * 1) Send the reply back in the same way as the request came in.
1567  *    If it came in encrypted, it goes out encrypted. If it came in
1568  *    clear, it goes out in clear. Thus, this will prevent chosen
1569  *    plain text attack.
1570  * 2) The client may or may not expect things to come in secure.
1571  *    If it comes in secure, the policy constraints are checked
1572  *    before delivering it to the upper layers. If it comes in
1573  *    clear, ipsec_inbound_accept_clear will decide whether to
1574  *    accept this in clear or not. In both the cases, if the returned
1575  *    message (IP header + 8 bytes) that caused the icmp message has
1576  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1577  *    sending up. If there are only 8 bytes of returned message, then
1578  *    upper client will not be notified.
1579  * 3) Check with global policy to see whether it matches the constaints.
1580  *    But this will be done only if icmp_accept_messages_in_clear is
1581  *    zero.
1582  * 4) If we need to change both in IP and ULP, then the decision taken
1583  *    while affecting the values in IP and while delivering up to TCP
1584  *    should be the same.
1585  *
1586  * 	There are two cases.
1587  *
1588  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1589  *	   failed), we will not deliver it to the ULP, even though they
1590  *	   are *willing* to accept in *clear*. This is fine as our global
1591  *	   disposition to icmp messages asks us reject the datagram.
1592  *
1593  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1594  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1595  *	   to deliver it to ULP (policy failed), it can lead to
1596  *	   consistency problems. The cases known at this time are
1597  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1598  *	   values :
1599  *
1600  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1601  *	     and Upper layer rejects. Then the communication will
1602  *	     come to a stop. This is solved by making similar decisions
1603  *	     at both levels. Currently, when we are unable to deliver
1604  *	     to the Upper Layer (due to policy failures) while IP has
1605  *	     adjusted ire_max_frag, the next outbound datagram would
1606  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1607  *	     will be with the right level of protection. Thus the right
1608  *	     value will be communicated even if we are not able to
1609  *	     communicate when we get from the wire initially. But this
1610  *	     assumes there would be at least one outbound datagram after
1611  *	     IP has adjusted its ire_max_frag value. To make things
1612  *	     simpler, we accept in clear after the validation of
1613  *	     AH/ESP headers.
1614  *
1615  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1616  *	     upper layer depending on the level of protection the upper
1617  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1618  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1619  *	     should be accepted in clear when the Upper layer expects secure.
1620  *	     Thus the communication may get aborted by some bad ICMP
1621  *	     packets.
1622  *
1623  * IPQoS Notes:
1624  * The only instance when a packet is sent for processing is when there
1625  * isn't an ICMP client and if we are interested in it.
1626  * If there is a client, IPPF processing will take place in the
1627  * ip_fanout_proto routine.
1628  *
1629  * Zones notes:
1630  * The packet is only processed in the context of the specified zone: typically
1631  * only this zone will reply to an echo request, and only interested clients in
1632  * this zone will receive a copy of the packet. This means that the caller must
1633  * call icmp_inbound() for each relevant zone.
1634  */
1635 static void
1636 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1637     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1638     ill_t *recv_ill, zoneid_t zoneid)
1639 {
1640 	icmph_t	*icmph;
1641 	ipha_t	*ipha;
1642 	int	iph_hdr_length;
1643 	int	hdr_length;
1644 	boolean_t	interested;
1645 	uint32_t	ts;
1646 	uchar_t	*wptr;
1647 	ipif_t	*ipif;
1648 	mblk_t *first_mp;
1649 	ipsec_in_t *ii;
1650 	ire_t *src_ire;
1651 	boolean_t onlink;
1652 	timestruc_t now;
1653 	uint32_t ill_index;
1654 
1655 	ASSERT(ill != NULL);
1656 
1657 	first_mp = mp;
1658 	if (mctl_present) {
1659 		mp = first_mp->b_cont;
1660 		ASSERT(mp != NULL);
1661 	}
1662 
1663 	ipha = (ipha_t *)mp->b_rptr;
1664 	if (icmp_accept_clear_messages == 0) {
1665 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1666 		    ipha, NULL, mctl_present);
1667 		if (first_mp == NULL)
1668 			return;
1669 	}
1670 	/*
1671 	 * We have accepted the ICMP message. It means that we will
1672 	 * respond to the packet if needed. It may not be delivered
1673 	 * to the upper client depending on the policy constraints
1674 	 * and the disposition in ipsec_inbound_accept_clear.
1675 	 */
1676 
1677 	ASSERT(ill != NULL);
1678 
1679 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1680 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1681 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1682 		/* Last chance to get real. */
1683 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1684 			BUMP_MIB(&icmp_mib, icmpInErrors);
1685 			freemsg(first_mp);
1686 			return;
1687 		}
1688 		/* Refresh iph following the pullup. */
1689 		ipha = (ipha_t *)mp->b_rptr;
1690 	}
1691 	/* ICMP header checksum, including checksum field, should be zero. */
1692 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1693 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1694 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1695 		freemsg(first_mp);
1696 		return;
1697 	}
1698 	/* The IP header will always be a multiple of four bytes */
1699 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1700 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1701 	    icmph->icmph_code));
1702 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1703 	/* We will set "interested" to "true" if we want a copy */
1704 	interested = B_FALSE;
1705 	switch (icmph->icmph_type) {
1706 	case ICMP_ECHO_REPLY:
1707 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1708 		break;
1709 	case ICMP_DEST_UNREACHABLE:
1710 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1711 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1714 		break;
1715 	case ICMP_SOURCE_QUENCH:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1718 		break;
1719 	case ICMP_REDIRECT:
1720 		if (!ip_ignore_redirect)
1721 			interested = B_TRUE;
1722 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1723 		break;
1724 	case ICMP_ECHO_REQUEST:
1725 		/*
1726 		 * Whether to respond to echo requests that come in as IP
1727 		 * broadcasts or as IP multicast is subject to debate
1728 		 * (what isn't?).  We aim to please, you pick it.
1729 		 * Default is do it.
1730 		 */
1731 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1732 			/* unicast: always respond */
1733 			interested = B_TRUE;
1734 		} else if (CLASSD(ipha->ipha_dst)) {
1735 			/* multicast: respond based on tunable */
1736 			interested = ip_g_resp_to_echo_mcast;
1737 		} else if (broadcast) {
1738 			/* broadcast: respond based on tunable */
1739 			interested = ip_g_resp_to_echo_bcast;
1740 		}
1741 		BUMP_MIB(&icmp_mib, icmpInEchos);
1742 		break;
1743 	case ICMP_ROUTER_ADVERTISEMENT:
1744 	case ICMP_ROUTER_SOLICITATION:
1745 		break;
1746 	case ICMP_TIME_EXCEEDED:
1747 		interested = B_TRUE;	/* Pass up to transport */
1748 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1749 		break;
1750 	case ICMP_PARAM_PROBLEM:
1751 		interested = B_TRUE;	/* Pass up to transport */
1752 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1753 		break;
1754 	case ICMP_TIME_STAMP_REQUEST:
1755 		/* Response to Time Stamp Requests is local policy. */
1756 		if (ip_g_resp_to_timestamp &&
1757 		    /* So is whether to respond if it was an IP broadcast. */
1758 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1759 			int tstamp_len = 3 * sizeof (uint32_t);
1760 
1761 			if (wptr +  tstamp_len > mp->b_wptr) {
1762 				if (!pullupmsg(mp, wptr + tstamp_len -
1763 				    mp->b_rptr)) {
1764 					BUMP_MIB(&ip_mib, ipInDiscards);
1765 					freemsg(first_mp);
1766 					return;
1767 				}
1768 				/* Refresh ipha following the pullup. */
1769 				ipha = (ipha_t *)mp->b_rptr;
1770 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1771 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1772 			}
1773 			interested = B_TRUE;
1774 		}
1775 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1776 		break;
1777 	case ICMP_TIME_STAMP_REPLY:
1778 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1779 		break;
1780 	case ICMP_INFO_REQUEST:
1781 		/* Per RFC 1122 3.2.2.7, ignore this. */
1782 	case ICMP_INFO_REPLY:
1783 		break;
1784 	case ICMP_ADDRESS_MASK_REQUEST:
1785 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1786 		    /* TODO m_pullup of complete header? */
1787 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1788 			interested = B_TRUE;
1789 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1790 		break;
1791 	case ICMP_ADDRESS_MASK_REPLY:
1792 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1793 		break;
1794 	default:
1795 		interested = B_TRUE;	/* Pass up to transport */
1796 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1797 		break;
1798 	}
1799 	/* See if there is an ICMP client. */
1800 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1801 		/* If there is an ICMP client and we want one too, copy it. */
1802 		mblk_t *first_mp1;
1803 
1804 		if (!interested) {
1805 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1806 			    ip_policy, recv_ill, zoneid);
1807 			return;
1808 		}
1809 		first_mp1 = ip_copymsg(first_mp);
1810 		if (first_mp1 != NULL) {
1811 			ip_fanout_proto(q, first_mp1, ill, ipha,
1812 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1813 		}
1814 	} else if (!interested) {
1815 		freemsg(first_mp);
1816 		return;
1817 	} else {
1818 		/*
1819 		 * Initiate policy processing for this packet if ip_policy
1820 		 * is true.
1821 		 */
1822 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1823 			ill_index = ill->ill_phyint->phyint_ifindex;
1824 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1825 			if (mp == NULL) {
1826 				if (mctl_present) {
1827 					freeb(first_mp);
1828 				}
1829 				BUMP_MIB(&icmp_mib, icmpInErrors);
1830 				return;
1831 			}
1832 		}
1833 	}
1834 	/* We want to do something with it. */
1835 	/* Check db_ref to make sure we can modify the packet. */
1836 	if (mp->b_datap->db_ref > 1) {
1837 		mblk_t	*first_mp1;
1838 
1839 		first_mp1 = ip_copymsg(first_mp);
1840 		freemsg(first_mp);
1841 		if (!first_mp1) {
1842 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1843 			return;
1844 		}
1845 		first_mp = first_mp1;
1846 		if (mctl_present) {
1847 			mp = first_mp->b_cont;
1848 			ASSERT(mp != NULL);
1849 		} else {
1850 			mp = first_mp;
1851 		}
1852 		ipha = (ipha_t *)mp->b_rptr;
1853 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1854 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1855 	}
1856 	switch (icmph->icmph_type) {
1857 	case ICMP_ADDRESS_MASK_REQUEST:
1858 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1859 		if (ipif == NULL) {
1860 			freemsg(first_mp);
1861 			return;
1862 		}
1863 		/*
1864 		 * outging interface must be IPv4
1865 		 */
1866 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1867 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1868 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1869 		ipif_refrele(ipif);
1870 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1871 		break;
1872 	case ICMP_ECHO_REQUEST:
1873 		icmph->icmph_type = ICMP_ECHO_REPLY;
1874 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1875 		break;
1876 	case ICMP_TIME_STAMP_REQUEST: {
1877 		uint32_t *tsp;
1878 
1879 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1880 		tsp = (uint32_t *)wptr;
1881 		tsp++;		/* Skip past 'originate time' */
1882 		/* Compute # of milliseconds since midnight */
1883 		gethrestime(&now);
1884 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1885 		    now.tv_nsec / (NANOSEC / MILLISEC);
1886 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1887 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1888 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1889 		break;
1890 	}
1891 	default:
1892 		ipha = (ipha_t *)&icmph[1];
1893 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1894 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1895 				BUMP_MIB(&ip_mib, ipInDiscards);
1896 				freemsg(first_mp);
1897 				return;
1898 			}
1899 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1900 			ipha = (ipha_t *)&icmph[1];
1901 		}
1902 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1903 			BUMP_MIB(&ip_mib, ipInDiscards);
1904 			freemsg(first_mp);
1905 			return;
1906 		}
1907 		hdr_length = IPH_HDR_LENGTH(ipha);
1908 		if (hdr_length < sizeof (ipha_t)) {
1909 			BUMP_MIB(&ip_mib, ipInDiscards);
1910 			freemsg(first_mp);
1911 			return;
1912 		}
1913 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1914 			if (!pullupmsg(mp,
1915 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1916 				BUMP_MIB(&ip_mib, ipInDiscards);
1917 				freemsg(first_mp);
1918 				return;
1919 			}
1920 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1921 			ipha = (ipha_t *)&icmph[1];
1922 		}
1923 		switch (icmph->icmph_type) {
1924 		case ICMP_REDIRECT:
1925 			/*
1926 			 * As there is no upper client to deliver, we don't
1927 			 * need the first_mp any more.
1928 			 */
1929 			if (mctl_present) {
1930 				freeb(first_mp);
1931 			}
1932 			icmp_redirect(mp);
1933 			return;
1934 		case ICMP_DEST_UNREACHABLE:
1935 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1936 				if (!icmp_inbound_too_big(icmph, ipha)) {
1937 					freemsg(first_mp);
1938 					return;
1939 				}
1940 			}
1941 			/* FALLTHRU */
1942 		default :
1943 			/*
1944 			 * IPQoS notes: Since we have already done IPQoS
1945 			 * processing we don't want to do it again in
1946 			 * the fanout routines called by
1947 			 * icmp_inbound_error_fanout, hence the last
1948 			 * argument, ip_policy, is B_FALSE.
1949 			 */
1950 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1951 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1952 			    B_FALSE, recv_ill, zoneid);
1953 		}
1954 		return;
1955 	}
1956 	/* Send out an ICMP packet */
1957 	icmph->icmph_checksum = 0;
1958 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1959 	if (icmph->icmph_checksum == 0)
1960 		icmph->icmph_checksum = 0xFFFF;
1961 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1962 		ipif_t	*ipif_chosen;
1963 		/*
1964 		 * Make it look like it was directed to us, so we don't look
1965 		 * like a fool with a broadcast or multicast source address.
1966 		 */
1967 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1968 		/*
1969 		 * Make sure that we haven't grabbed an interface that's DOWN.
1970 		 */
1971 		if (ipif != NULL) {
1972 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1973 			    ipha->ipha_src, zoneid);
1974 			if (ipif_chosen != NULL) {
1975 				ipif_refrele(ipif);
1976 				ipif = ipif_chosen;
1977 			}
1978 		}
1979 		if (ipif == NULL) {
1980 			ip0dbg(("icmp_inbound: "
1981 			    "No source for broadcast/multicast:\n"
1982 			    "\tsrc 0x%x dst 0x%x ill %p "
1983 			    "ipif_lcl_addr 0x%x\n",
1984 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1985 			    (void *)ill,
1986 			    ill->ill_ipif->ipif_lcl_addr));
1987 			freemsg(first_mp);
1988 			return;
1989 		}
1990 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1991 		ipha->ipha_dst = ipif->ipif_src_addr;
1992 		ipif_refrele(ipif);
1993 	}
1994 	/* Reset time to live. */
1995 	ipha->ipha_ttl = ip_def_ttl;
1996 	{
1997 		/* Swap source and destination addresses */
1998 		ipaddr_t tmp;
1999 
2000 		tmp = ipha->ipha_src;
2001 		ipha->ipha_src = ipha->ipha_dst;
2002 		ipha->ipha_dst = tmp;
2003 	}
2004 	ipha->ipha_ident = 0;
2005 	if (!IS_SIMPLE_IPH(ipha))
2006 		icmp_options_update(ipha);
2007 
2008 	/*
2009 	 * ICMP echo replies should go out on the same interface
2010 	 * the request came on as probes used by in.mpathd for detecting
2011 	 * NIC failures are ECHO packets. We turn-off load spreading
2012 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2013 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2014 	 * function. This is in turn handled by ip_wput and ip_newroute
2015 	 * to make sure that the packet goes out on the interface it came
2016 	 * in on. If we don't turnoff load spreading, the packets might get
2017 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2018 	 * to go out and in.mpathd would wrongly detect a failure or
2019 	 * mis-detect a NIC failure for link failure. As load spreading
2020 	 * can happen only if ill_group is not NULL, we do only for
2021 	 * that case and this does not affect the normal case.
2022 	 *
2023 	 * We turn off load spreading only on echo packets that came from
2024 	 * on-link hosts. If the interface route has been deleted, this will
2025 	 * not be enforced as we can't do much. For off-link hosts, as the
2026 	 * default routes in IPv4 does not typically have an ire_ipif
2027 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2028 	 * Moreover, expecting a default route through this interface may
2029 	 * not be correct. We use ipha_dst because of the swap above.
2030 	 */
2031 	onlink = B_FALSE;
2032 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2033 		/*
2034 		 * First, we need to make sure that it is not one of our
2035 		 * local addresses. If we set onlink when it is one of
2036 		 * our local addresses, we will end up creating IRE_CACHES
2037 		 * for one of our local addresses. Then, we will never
2038 		 * accept packets for them afterwards.
2039 		 */
2040 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2041 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2042 		if (src_ire == NULL) {
2043 			ipif = ipif_get_next_ipif(NULL, ill);
2044 			if (ipif == NULL) {
2045 				BUMP_MIB(&ip_mib, ipInDiscards);
2046 				freemsg(mp);
2047 				return;
2048 			}
2049 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2050 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2051 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2052 			ipif_refrele(ipif);
2053 			if (src_ire != NULL) {
2054 				onlink = B_TRUE;
2055 				ire_refrele(src_ire);
2056 			}
2057 		} else {
2058 			ire_refrele(src_ire);
2059 		}
2060 	}
2061 	if (!mctl_present) {
2062 		/*
2063 		 * This packet should go out the same way as it
2064 		 * came in i.e in clear. To make sure that global
2065 		 * policy will not be applied to this in ip_wput_ire,
2066 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2067 		 */
2068 		ASSERT(first_mp == mp);
2069 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2070 			BUMP_MIB(&ip_mib, ipInDiscards);
2071 			freemsg(mp);
2072 			return;
2073 		}
2074 		ii = (ipsec_in_t *)first_mp->b_rptr;
2075 
2076 		/* This is not a secure packet */
2077 		ii->ipsec_in_secure = B_FALSE;
2078 		if (onlink) {
2079 			ii->ipsec_in_attach_if = B_TRUE;
2080 			ii->ipsec_in_ill_index =
2081 			    ill->ill_phyint->phyint_ifindex;
2082 			ii->ipsec_in_rill_index =
2083 			    recv_ill->ill_phyint->phyint_ifindex;
2084 		}
2085 		first_mp->b_cont = mp;
2086 	} else if (onlink) {
2087 		ii = (ipsec_in_t *)first_mp->b_rptr;
2088 		ii->ipsec_in_attach_if = B_TRUE;
2089 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2090 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2091 	} else {
2092 		ii = (ipsec_in_t *)first_mp->b_rptr;
2093 	}
2094 	ii->ipsec_in_zoneid = zoneid;
2095 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2096 		BUMP_MIB(&ip_mib, ipInDiscards);
2097 		return;
2098 	}
2099 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2100 	put(WR(q), first_mp);
2101 }
2102 
2103 /* Table from RFC 1191 */
2104 static int icmp_frag_size_table[] =
2105 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2106 
2107 /*
2108  * Process received ICMP Packet too big.
2109  * After updating any IRE it does the fanout to any matching transport streams.
2110  * Assumes the message has been pulled up till the IP header that caused
2111  * the error.
2112  *
2113  * Returns B_FALSE on failure and B_TRUE on success.
2114  */
2115 static boolean_t
2116 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2117 {
2118 	ire_t	*ire, *first_ire;
2119 	int	mtu;
2120 	int	hdr_length;
2121 
2122 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2123 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2124 
2125 	hdr_length = IPH_HDR_LENGTH(ipha);
2126 
2127 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2128 	    ALL_ZONES, MATCH_IRE_TYPE);
2129 
2130 	if (!first_ire) {
2131 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2132 		    ntohl(ipha->ipha_dst)));
2133 		return (B_FALSE);
2134 	}
2135 	/* Drop if the original packet contained a source route */
2136 	if (ip_source_route_included(ipha)) {
2137 		ire_refrele(first_ire);
2138 		return (B_FALSE);
2139 	}
2140 	/* Check for MTU discovery advice as described in RFC 1191 */
2141 	mtu = ntohs(icmph->icmph_du_mtu);
2142 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2143 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2144 	    ire = ire->ire_next) {
2145 		mutex_enter(&ire->ire_lock);
2146 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2147 			/* Reduce the IRE max frag value as advised. */
2148 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2149 			ip1dbg(("Received mtu from router: %d\n", mtu));
2150 		} else {
2151 			uint32_t length;
2152 			int	i;
2153 
2154 			/*
2155 			 * Use the table from RFC 1191 to figure out
2156 			 * the next "plateau" based on the length in
2157 			 * the original IP packet.
2158 			 */
2159 			length = ntohs(ipha->ipha_length);
2160 			if (ire->ire_max_frag <= length &&
2161 			    ire->ire_max_frag >= length - hdr_length) {
2162 				/*
2163 				 * Handle broken BSD 4.2 systems that
2164 				 * return the wrong iph_length in ICMP
2165 				 * errors.
2166 				 */
2167 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2168 				    length, ire->ire_max_frag));
2169 				length -= hdr_length;
2170 			}
2171 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2172 				if (length > icmp_frag_size_table[i])
2173 					break;
2174 			}
2175 			if (i == A_CNT(icmp_frag_size_table)) {
2176 				/* Smaller than 68! */
2177 				ip1dbg(("Too big for packet size %d\n",
2178 				    length));
2179 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2180 				ire->ire_frag_flag = 0;
2181 			} else {
2182 				mtu = icmp_frag_size_table[i];
2183 				ip1dbg(("Calculated mtu %d, packet size %d, "
2184 				    "before %d", mtu, length,
2185 				    ire->ire_max_frag));
2186 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2187 				ip1dbg((", after %d\n", ire->ire_max_frag));
2188 			}
2189 			/* Record the new max frag size for the ULP. */
2190 			icmph->icmph_du_zero = 0;
2191 			icmph->icmph_du_mtu =
2192 			    htons((uint16_t)ire->ire_max_frag);
2193 		}
2194 		mutex_exit(&ire->ire_lock);
2195 	}
2196 	rw_exit(&first_ire->ire_bucket->irb_lock);
2197 	ire_refrele(first_ire);
2198 	return (B_TRUE);
2199 }
2200 
2201 /*
2202  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2203  * calls this function.
2204  */
2205 static mblk_t *
2206 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2207 {
2208 	ipha_t *ipha;
2209 	icmph_t *icmph;
2210 	ipha_t *in_ipha;
2211 	int length;
2212 
2213 	ASSERT(mp->b_datap->db_type == M_DATA);
2214 
2215 	/*
2216 	 * For Self-encapsulated packets, we added an extra IP header
2217 	 * without the options. Inner IP header is the one from which
2218 	 * the outer IP header was formed. Thus, we need to remove the
2219 	 * outer IP header. To do this, we pullup the whole message
2220 	 * and overlay whatever follows the outer IP header over the
2221 	 * outer IP header.
2222 	 */
2223 
2224 	if (!pullupmsg(mp, -1)) {
2225 		BUMP_MIB(&ip_mib, ipInDiscards);
2226 		return (NULL);
2227 	}
2228 
2229 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2230 	ipha = (ipha_t *)&icmph[1];
2231 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2232 
2233 	/*
2234 	 * The length that we want to overlay is following the inner
2235 	 * IP header. Subtracting the IP header + icmp header + outer
2236 	 * IP header's length should give us the length that we want to
2237 	 * overlay.
2238 	 */
2239 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2240 	    hdr_length;
2241 	/*
2242 	 * Overlay whatever follows the inner header over the
2243 	 * outer header.
2244 	 */
2245 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2246 
2247 	/* Set the wptr to account for the outer header */
2248 	mp->b_wptr -= hdr_length;
2249 	return (mp);
2250 }
2251 
2252 /*
2253  * Try to pass the ICMP message upstream in case the ULP cares.
2254  *
2255  * If the packet that caused the ICMP error is secure, we send
2256  * it to AH/ESP to make sure that the attached packet has a
2257  * valid association. ipha in the code below points to the
2258  * IP header of the packet that caused the error.
2259  *
2260  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2261  * in the context of IPSEC. Normally we tell the upper layer
2262  * whenever we send the ire (including ip_bind), the IPSEC header
2263  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2264  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2265  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2266  * same thing. As TCP has the IPSEC options size that needs to be
2267  * adjusted, we just pass the MTU unchanged.
2268  *
2269  * IFN could have been generated locally or by some router.
2270  *
2271  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2272  *	    This happens because IP adjusted its value of MTU on an
2273  *	    earlier IFN message and could not tell the upper layer,
2274  *	    the new adjusted value of MTU e.g. Packet was encrypted
2275  *	    or there was not enough information to fanout to upper
2276  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2277  *	    generates the IFN, where IPSEC processing has *not* been
2278  *	    done.
2279  *
2280  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2281  *	    could have generated this. This happens because ire_max_frag
2282  *	    value in IP was set to a new value, while the IPSEC processing
2283  *	    was being done and after we made the fragmentation check in
2284  *	    ip_wput_ire. Thus on return from IPSEC processing,
2285  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2286  *	    and generates the IFN. As IPSEC processing is over, we fanout
2287  *	    to AH/ESP to remove the header.
2288  *
2289  *	    In both these cases, ipsec_in_loopback will be set indicating
2290  *	    that IFN was generated locally.
2291  *
2292  * ROUTER : IFN could be secure or non-secure.
2293  *
2294  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2295  *	      packet in error has AH/ESP headers to validate the AH/ESP
2296  *	      headers. AH/ESP will verify whether there is a valid SA or
2297  *	      not and send it back. We will fanout again if we have more
2298  *	      data in the packet.
2299  *
2300  *	      If the packet in error does not have AH/ESP, we handle it
2301  *	      like any other case.
2302  *
2303  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2304  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2305  *	      for validation. AH/ESP will verify whether there is a
2306  *	      valid SA or not and send it back. We will fanout again if
2307  *	      we have more data in the packet.
2308  *
2309  *	      If the packet in error does not have AH/ESP, we handle it
2310  *	      like any other case.
2311  */
2312 static void
2313 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2314     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2315     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2316     zoneid_t zoneid)
2317 {
2318 	uint16_t *up;	/* Pointer to ports in ULP header */
2319 	uint32_t ports;	/* reversed ports for fanout */
2320 	ipha_t ripha;	/* With reversed addresses */
2321 	mblk_t *first_mp;
2322 	ipsec_in_t *ii;
2323 	tcph_t	*tcph;
2324 	conn_t	*connp;
2325 
2326 	first_mp = mp;
2327 	if (mctl_present) {
2328 		mp = first_mp->b_cont;
2329 		ASSERT(mp != NULL);
2330 
2331 		ii = (ipsec_in_t *)first_mp->b_rptr;
2332 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2333 	} else {
2334 		ii = NULL;
2335 	}
2336 
2337 	switch (ipha->ipha_protocol) {
2338 	case IPPROTO_UDP:
2339 		/*
2340 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2341 		 * transport header.
2342 		 */
2343 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2344 		    mp->b_wptr) {
2345 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2346 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2347 				BUMP_MIB(&ip_mib, ipInDiscards);
2348 				goto drop_pkt;
2349 			}
2350 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2351 			ipha = (ipha_t *)&icmph[1];
2352 		}
2353 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2354 
2355 		/*
2356 		 * Attempt to find a client stream based on port.
2357 		 * Note that we do a reverse lookup since the header is
2358 		 * in the form we sent it out.
2359 		 * The ripha header is only used for the IP_UDP_MATCH and we
2360 		 * only set the src and dst addresses and protocol.
2361 		 */
2362 		ripha.ipha_src = ipha->ipha_dst;
2363 		ripha.ipha_dst = ipha->ipha_src;
2364 		ripha.ipha_protocol = ipha->ipha_protocol;
2365 		((uint16_t *)&ports)[0] = up[1];
2366 		((uint16_t *)&ports)[1] = up[0];
2367 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2368 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2369 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2370 		    icmph->icmph_type, icmph->icmph_code));
2371 
2372 		/* Have to change db_type after any pullupmsg */
2373 		DB_TYPE(mp) = M_CTL;
2374 
2375 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2376 		    mctl_present, ip_policy, recv_ill, zoneid);
2377 		return;
2378 
2379 	case IPPROTO_TCP:
2380 		/*
2381 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2382 		 * transport header.
2383 		 */
2384 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2385 		    mp->b_wptr) {
2386 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2387 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2388 				BUMP_MIB(&ip_mib, ipInDiscards);
2389 				goto drop_pkt;
2390 			}
2391 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2392 			ipha = (ipha_t *)&icmph[1];
2393 		}
2394 		/*
2395 		 * Find a TCP client stream for this packet.
2396 		 * Note that we do a reverse lookup since the header is
2397 		 * in the form we sent it out.
2398 		 */
2399 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2400 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2401 		if (connp == NULL) {
2402 			BUMP_MIB(&ip_mib, ipInDiscards);
2403 			goto drop_pkt;
2404 		}
2405 
2406 		/* Have to change db_type after any pullupmsg */
2407 		DB_TYPE(mp) = M_CTL;
2408 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2409 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2410 		return;
2411 
2412 	case IPPROTO_SCTP:
2413 		/*
2414 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2415 		 * transport header.
2416 		 */
2417 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2418 		    mp->b_wptr) {
2419 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2420 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2421 				BUMP_MIB(&ip_mib, ipInDiscards);
2422 				goto drop_pkt;
2423 			}
2424 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2425 			ipha = (ipha_t *)&icmph[1];
2426 		}
2427 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2428 		/*
2429 		 * Find a SCTP client stream for this packet.
2430 		 * Note that we do a reverse lookup since the header is
2431 		 * in the form we sent it out.
2432 		 * The ripha header is only used for the matching and we
2433 		 * only set the src and dst addresses, protocol, and version.
2434 		 */
2435 		ripha.ipha_src = ipha->ipha_dst;
2436 		ripha.ipha_dst = ipha->ipha_src;
2437 		ripha.ipha_protocol = ipha->ipha_protocol;
2438 		ripha.ipha_version_and_hdr_length =
2439 		    ipha->ipha_version_and_hdr_length;
2440 		((uint16_t *)&ports)[0] = up[1];
2441 		((uint16_t *)&ports)[1] = up[0];
2442 
2443 		/* Have to change db_type after any pullupmsg */
2444 		DB_TYPE(mp) = M_CTL;
2445 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2446 		    mctl_present, ip_policy, 0, zoneid);
2447 		return;
2448 
2449 	case IPPROTO_ESP:
2450 	case IPPROTO_AH: {
2451 		int ipsec_rc;
2452 
2453 		/*
2454 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2455 		 * We will re-use the IPSEC_IN if it is already present as
2456 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2457 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2458 		 * one and attach it in the front.
2459 		 */
2460 		if (ii != NULL) {
2461 			/*
2462 			 * ip_fanout_proto_again converts the ICMP errors
2463 			 * that come back from AH/ESP to M_DATA so that
2464 			 * if it is non-AH/ESP and we do a pullupmsg in
2465 			 * this function, it would work. Convert it back
2466 			 * to M_CTL before we send up as this is a ICMP
2467 			 * error. This could have been generated locally or
2468 			 * by some router. Validate the inner IPSEC
2469 			 * headers.
2470 			 *
2471 			 * NOTE : ill_index is used by ip_fanout_proto_again
2472 			 * to locate the ill.
2473 			 */
2474 			ASSERT(ill != NULL);
2475 			ii->ipsec_in_ill_index =
2476 			    ill->ill_phyint->phyint_ifindex;
2477 			ii->ipsec_in_rill_index =
2478 			    recv_ill->ill_phyint->phyint_ifindex;
2479 			DB_TYPE(first_mp->b_cont) = M_CTL;
2480 		} else {
2481 			/*
2482 			 * IPSEC_IN is not present. We attach a ipsec_in
2483 			 * message and send up to IPSEC for validating
2484 			 * and removing the IPSEC headers. Clear
2485 			 * ipsec_in_secure so that when we return
2486 			 * from IPSEC, we don't mistakenly think that this
2487 			 * is a secure packet came from the network.
2488 			 *
2489 			 * NOTE : ill_index is used by ip_fanout_proto_again
2490 			 * to locate the ill.
2491 			 */
2492 			ASSERT(first_mp == mp);
2493 			first_mp = ipsec_in_alloc(B_TRUE);
2494 			if (first_mp == NULL) {
2495 				freemsg(mp);
2496 				BUMP_MIB(&ip_mib, ipInDiscards);
2497 				return;
2498 			}
2499 			ii = (ipsec_in_t *)first_mp->b_rptr;
2500 
2501 			/* This is not a secure packet */
2502 			ii->ipsec_in_secure = B_FALSE;
2503 			first_mp->b_cont = mp;
2504 			DB_TYPE(mp) = M_CTL;
2505 			ASSERT(ill != NULL);
2506 			ii->ipsec_in_ill_index =
2507 			    ill->ill_phyint->phyint_ifindex;
2508 			ii->ipsec_in_rill_index =
2509 			    recv_ill->ill_phyint->phyint_ifindex;
2510 		}
2511 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2512 
2513 		if (!ipsec_loaded()) {
2514 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2515 			return;
2516 		}
2517 
2518 		if (ipha->ipha_protocol == IPPROTO_ESP)
2519 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2520 		else
2521 			ipsec_rc = ipsecah_icmp_error(first_mp);
2522 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2523 			return;
2524 
2525 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2526 		return;
2527 	}
2528 	default:
2529 		/*
2530 		 * The ripha header is only used for the lookup and we
2531 		 * only set the src and dst addresses and protocol.
2532 		 */
2533 		ripha.ipha_src = ipha->ipha_dst;
2534 		ripha.ipha_dst = ipha->ipha_src;
2535 		ripha.ipha_protocol = ipha->ipha_protocol;
2536 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2537 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2538 		    ntohl(ipha->ipha_dst),
2539 		    icmph->icmph_type, icmph->icmph_code));
2540 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2541 			ipha_t *in_ipha;
2542 
2543 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2544 			    mp->b_wptr) {
2545 				if (!pullupmsg(mp, (uchar_t *)ipha +
2546 				    hdr_length + sizeof (ipha_t) -
2547 				    mp->b_rptr)) {
2548 
2549 					BUMP_MIB(&ip_mib, ipInDiscards);
2550 					goto drop_pkt;
2551 				}
2552 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2553 				ipha = (ipha_t *)&icmph[1];
2554 			}
2555 			/*
2556 			 * Caller has verified that length has to be
2557 			 * at least the size of IP header.
2558 			 */
2559 			ASSERT(hdr_length >= sizeof (ipha_t));
2560 			/*
2561 			 * Check the sanity of the inner IP header like
2562 			 * we did for the outer header.
2563 			 */
2564 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2565 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2566 				BUMP_MIB(&ip_mib, ipInDiscards);
2567 				goto drop_pkt;
2568 			}
2569 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2570 				BUMP_MIB(&ip_mib, ipInDiscards);
2571 				goto drop_pkt;
2572 			}
2573 			/* Check for Self-encapsulated tunnels */
2574 			if (in_ipha->ipha_src == ipha->ipha_src &&
2575 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2576 
2577 				mp = icmp_inbound_self_encap_error(mp,
2578 				    iph_hdr_length, hdr_length);
2579 				if (mp == NULL)
2580 					goto drop_pkt;
2581 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2582 				ipha = (ipha_t *)&icmph[1];
2583 				hdr_length = IPH_HDR_LENGTH(ipha);
2584 				/*
2585 				 * The packet in error is self-encapsualted.
2586 				 * And we are finding it further encapsulated
2587 				 * which we could not have possibly generated.
2588 				 */
2589 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2590 					BUMP_MIB(&ip_mib, ipInDiscards);
2591 					goto drop_pkt;
2592 				}
2593 				icmp_inbound_error_fanout(q, ill, first_mp,
2594 				    icmph, ipha, iph_hdr_length, hdr_length,
2595 				    mctl_present, ip_policy, recv_ill, zoneid);
2596 				return;
2597 			}
2598 		}
2599 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2600 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2601 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2602 		    ii != NULL &&
2603 		    ii->ipsec_in_loopback &&
2604 		    ii->ipsec_in_secure) {
2605 			/*
2606 			 * For IP tunnels that get a looped-back
2607 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2608 			 * reported new MTU to take into account the IPsec
2609 			 * headers protecting this configured tunnel.
2610 			 *
2611 			 * This allows the tunnel module (tun.c) to blindly
2612 			 * accept the MTU reported in an ICMP "too big"
2613 			 * message.
2614 			 *
2615 			 * Non-looped back ICMP messages will just be
2616 			 * handled by the security protocols (if needed),
2617 			 * and the first subsequent packet will hit this
2618 			 * path.
2619 			 */
2620 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2621 			    ipsec_in_extra_length(first_mp));
2622 		}
2623 		/* Have to change db_type after any pullupmsg */
2624 		DB_TYPE(mp) = M_CTL;
2625 
2626 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2627 		    ip_policy, recv_ill, zoneid);
2628 		return;
2629 	}
2630 	/* NOTREACHED */
2631 drop_pkt:;
2632 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2633 	freemsg(first_mp);
2634 }
2635 
2636 /*
2637  * Common IP options parser.
2638  *
2639  * Setup routine: fill in *optp with options-parsing state, then
2640  * tail-call ipoptp_next to return the first option.
2641  */
2642 uint8_t
2643 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2644 {
2645 	uint32_t totallen; /* total length of all options */
2646 
2647 	totallen = ipha->ipha_version_and_hdr_length -
2648 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2649 	totallen <<= 2;
2650 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2651 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2652 	optp->ipoptp_flags = 0;
2653 	return (ipoptp_next(optp));
2654 }
2655 
2656 /*
2657  * Common IP options parser: extract next option.
2658  */
2659 uint8_t
2660 ipoptp_next(ipoptp_t *optp)
2661 {
2662 	uint8_t *end = optp->ipoptp_end;
2663 	uint8_t *cur = optp->ipoptp_next;
2664 	uint8_t opt, len, pointer;
2665 
2666 	/*
2667 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2668 	 * has been corrupted.
2669 	 */
2670 	ASSERT(cur <= end);
2671 
2672 	if (cur == end)
2673 		return (IPOPT_EOL);
2674 
2675 	opt = cur[IPOPT_OPTVAL];
2676 
2677 	/*
2678 	 * Skip any NOP options.
2679 	 */
2680 	while (opt == IPOPT_NOP) {
2681 		cur++;
2682 		if (cur == end)
2683 			return (IPOPT_EOL);
2684 		opt = cur[IPOPT_OPTVAL];
2685 	}
2686 
2687 	if (opt == IPOPT_EOL)
2688 		return (IPOPT_EOL);
2689 
2690 	/*
2691 	 * Option requiring a length.
2692 	 */
2693 	if ((cur + 1) >= end) {
2694 		optp->ipoptp_flags |= IPOPTP_ERROR;
2695 		return (IPOPT_EOL);
2696 	}
2697 	len = cur[IPOPT_OLEN];
2698 	if (len < 2) {
2699 		optp->ipoptp_flags |= IPOPTP_ERROR;
2700 		return (IPOPT_EOL);
2701 	}
2702 	optp->ipoptp_cur = cur;
2703 	optp->ipoptp_len = len;
2704 	optp->ipoptp_next = cur + len;
2705 	if (cur + len > end) {
2706 		optp->ipoptp_flags |= IPOPTP_ERROR;
2707 		return (IPOPT_EOL);
2708 	}
2709 
2710 	/*
2711 	 * For the options which require a pointer field, make sure
2712 	 * its there, and make sure it points to either something
2713 	 * inside this option, or the end of the option.
2714 	 */
2715 	switch (opt) {
2716 	case IPOPT_RR:
2717 	case IPOPT_TS:
2718 	case IPOPT_LSRR:
2719 	case IPOPT_SSRR:
2720 		if (len <= IPOPT_OFFSET) {
2721 			optp->ipoptp_flags |= IPOPTP_ERROR;
2722 			return (opt);
2723 		}
2724 		pointer = cur[IPOPT_OFFSET];
2725 		if (pointer - 1 > len) {
2726 			optp->ipoptp_flags |= IPOPTP_ERROR;
2727 			return (opt);
2728 		}
2729 		break;
2730 	}
2731 
2732 	/*
2733 	 * Sanity check the pointer field based on the type of the
2734 	 * option.
2735 	 */
2736 	switch (opt) {
2737 	case IPOPT_RR:
2738 	case IPOPT_SSRR:
2739 	case IPOPT_LSRR:
2740 		if (pointer < IPOPT_MINOFF_SR)
2741 			optp->ipoptp_flags |= IPOPTP_ERROR;
2742 		break;
2743 	case IPOPT_TS:
2744 		if (pointer < IPOPT_MINOFF_IT)
2745 			optp->ipoptp_flags |= IPOPTP_ERROR;
2746 		/*
2747 		 * Note that the Internet Timestamp option also
2748 		 * contains two four bit fields (the Overflow field,
2749 		 * and the Flag field), which follow the pointer
2750 		 * field.  We don't need to check that these fields
2751 		 * fall within the length of the option because this
2752 		 * was implicitely done above.  We've checked that the
2753 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2754 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2755 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2756 		 */
2757 		ASSERT(len > IPOPT_POS_OV_FLG);
2758 		break;
2759 	}
2760 
2761 	return (opt);
2762 }
2763 
2764 /*
2765  * Update any record route or timestamp options to include this host.
2766  * Reverse any source route option.
2767  * This routine assumes that the options are well formed i.e. that they
2768  * have already been checked.
2769  */
2770 static void
2771 icmp_options_update(ipha_t *ipha)
2772 {
2773 	ipoptp_t	opts;
2774 	uchar_t		*opt;
2775 	uint8_t		optval;
2776 	ipaddr_t	src;		/* Our local address */
2777 	ipaddr_t	dst;
2778 
2779 	ip2dbg(("icmp_options_update\n"));
2780 	src = ipha->ipha_src;
2781 	dst = ipha->ipha_dst;
2782 
2783 	for (optval = ipoptp_first(&opts, ipha);
2784 	    optval != IPOPT_EOL;
2785 	    optval = ipoptp_next(&opts)) {
2786 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2787 		opt = opts.ipoptp_cur;
2788 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2789 		    optval, opts.ipoptp_len));
2790 		switch (optval) {
2791 			int off1, off2;
2792 		case IPOPT_SSRR:
2793 		case IPOPT_LSRR:
2794 			/*
2795 			 * Reverse the source route.  The first entry
2796 			 * should be the next to last one in the current
2797 			 * source route (the last entry is our address).
2798 			 * The last entry should be the final destination.
2799 			 */
2800 			off1 = IPOPT_MINOFF_SR - 1;
2801 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2802 			if (off2 < 0) {
2803 				/* No entries in source route */
2804 				ip1dbg((
2805 				    "icmp_options_update: bad src route\n"));
2806 				break;
2807 			}
2808 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2809 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2810 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2811 			off2 -= IP_ADDR_LEN;
2812 
2813 			while (off1 < off2) {
2814 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2815 				bcopy((char *)opt + off2, (char *)opt + off1,
2816 				    IP_ADDR_LEN);
2817 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2818 				off1 += IP_ADDR_LEN;
2819 				off2 -= IP_ADDR_LEN;
2820 			}
2821 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2822 			break;
2823 		}
2824 	}
2825 }
2826 
2827 /*
2828  * Process received ICMP Redirect messages.
2829  */
2830 /* ARGSUSED */
2831 static void
2832 icmp_redirect(mblk_t *mp)
2833 {
2834 	ipha_t	*ipha;
2835 	int	iph_hdr_length;
2836 	icmph_t	*icmph;
2837 	ipha_t	*ipha_err;
2838 	ire_t	*ire;
2839 	ire_t	*prev_ire;
2840 	ire_t	*save_ire;
2841 	ipaddr_t  src, dst, gateway;
2842 	iulp_t	ulp_info = { 0 };
2843 	int	error;
2844 
2845 	ipha = (ipha_t *)mp->b_rptr;
2846 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2847 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2848 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2849 		BUMP_MIB(&icmp_mib, icmpInErrors);
2850 		freemsg(mp);
2851 		return;
2852 	}
2853 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2854 	ipha_err = (ipha_t *)&icmph[1];
2855 	src = ipha->ipha_src;
2856 	dst = ipha_err->ipha_dst;
2857 	gateway = icmph->icmph_rd_gateway;
2858 	/* Make sure the new gateway is reachable somehow. */
2859 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2860 	    ALL_ZONES, MATCH_IRE_TYPE);
2861 	/*
2862 	 * Make sure we had a route for the dest in question and that
2863 	 * that route was pointing to the old gateway (the source of the
2864 	 * redirect packet.)
2865 	 */
2866 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2867 	    MATCH_IRE_GW);
2868 	/*
2869 	 * Check that
2870 	 *	the redirect was not from ourselves
2871 	 *	the new gateway and the old gateway are directly reachable
2872 	 */
2873 	if (!prev_ire ||
2874 	    !ire ||
2875 	    ire->ire_type == IRE_LOCAL) {
2876 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2877 		freemsg(mp);
2878 		if (ire != NULL)
2879 			ire_refrele(ire);
2880 		if (prev_ire != NULL)
2881 			ire_refrele(prev_ire);
2882 		return;
2883 	}
2884 
2885 	/*
2886 	 * Should we use the old ULP info to create the new gateway?  From
2887 	 * a user's perspective, we should inherit the info so that it
2888 	 * is a "smooth" transition.  If we do not do that, then new
2889 	 * connections going thru the new gateway will have no route metrics,
2890 	 * which is counter-intuitive to user.  From a network point of
2891 	 * view, this may or may not make sense even though the new gateway
2892 	 * is still directly connected to us so the route metrics should not
2893 	 * change much.
2894 	 *
2895 	 * But if the old ire_uinfo is not initialized, we do another
2896 	 * recursive lookup on the dest using the new gateway.  There may
2897 	 * be a route to that.  If so, use it to initialize the redirect
2898 	 * route.
2899 	 */
2900 	if (prev_ire->ire_uinfo.iulp_set) {
2901 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2902 	} else {
2903 		ire_t *tmp_ire;
2904 		ire_t *sire;
2905 
2906 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2907 		    ALL_ZONES, 0,
2908 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2909 		if (sire != NULL) {
2910 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2911 			/*
2912 			 * If sire != NULL, ire_ftable_lookup() should not
2913 			 * return a NULL value.
2914 			 */
2915 			ASSERT(tmp_ire != NULL);
2916 			ire_refrele(tmp_ire);
2917 			ire_refrele(sire);
2918 		} else if (tmp_ire != NULL) {
2919 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2920 			    sizeof (iulp_t));
2921 			ire_refrele(tmp_ire);
2922 		}
2923 	}
2924 	if (prev_ire->ire_type == IRE_CACHE)
2925 		ire_delete(prev_ire);
2926 	ire_refrele(prev_ire);
2927 	/*
2928 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2929 	 * require TOS routing
2930 	 */
2931 	switch (icmph->icmph_code) {
2932 	case 0:
2933 	case 1:
2934 		/* TODO: TOS specificity for cases 2 and 3 */
2935 	case 2:
2936 	case 3:
2937 		break;
2938 	default:
2939 		freemsg(mp);
2940 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2941 		ire_refrele(ire);
2942 		return;
2943 	}
2944 	/*
2945 	 * Create a Route Association.  This will allow us to remember that
2946 	 * someone we believe told us to use the particular gateway.
2947 	 */
2948 	save_ire = ire;
2949 	ire = ire_create(
2950 		(uchar_t *)&dst,			/* dest addr */
2951 		(uchar_t *)&ip_g_all_ones,		/* mask */
2952 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2953 		(uchar_t *)&gateway,			/* gateway addr */
2954 		NULL,					/* no in_srcaddr */
2955 		&save_ire->ire_max_frag,		/* max frag */
2956 		NULL,					/* Fast Path header */
2957 		NULL,					/* no rfq */
2958 		NULL,					/* no stq */
2959 		IRE_HOST_REDIRECT,
2960 		NULL,
2961 		NULL,
2962 		NULL,
2963 		0,
2964 		0,
2965 		0,
2966 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2967 		&ulp_info);
2968 
2969 	if (ire == NULL) {
2970 		freemsg(mp);
2971 		ire_refrele(save_ire);
2972 		return;
2973 	}
2974 	error = ire_add(&ire, NULL, NULL, NULL);
2975 	ire_refrele(save_ire);
2976 	if (error == 0) {
2977 		ire_refrele(ire);		/* Held in ire_add_v4 */
2978 		/* tell routing sockets that we received a redirect */
2979 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2980 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2981 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2982 	}
2983 
2984 	/*
2985 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2986 	 * This together with the added IRE has the effect of
2987 	 * modifying an existing redirect.
2988 	 */
2989 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2990 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2991 	if (prev_ire) {
2992 		ire_delete(prev_ire);
2993 		ire_refrele(prev_ire);
2994 	}
2995 
2996 	freemsg(mp);
2997 }
2998 
2999 /*
3000  * Generate an ICMP parameter problem message.
3001  */
3002 static void
3003 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3004 {
3005 	icmph_t	icmph;
3006 	boolean_t mctl_present;
3007 	mblk_t *first_mp;
3008 
3009 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3010 
3011 	if (!(mp = icmp_pkt_err_ok(mp))) {
3012 		if (mctl_present)
3013 			freeb(first_mp);
3014 		return;
3015 	}
3016 
3017 	bzero(&icmph, sizeof (icmph_t));
3018 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3019 	icmph.icmph_pp_ptr = ptr;
3020 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3021 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3022 }
3023 
3024 /*
3025  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3026  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3027  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3028  * an icmp error packet can be sent.
3029  * Assigns an appropriate source address to the packet. If ipha_dst is
3030  * one of our addresses use it for source. Otherwise pick a source based
3031  * on a route lookup back to ipha_src.
3032  * Note that ipha_src must be set here since the
3033  * packet is likely to arrive on an ill queue in ip_wput() which will
3034  * not set a source address.
3035  */
3036 static void
3037 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3038     boolean_t mctl_present)
3039 {
3040 	ipaddr_t dst;
3041 	icmph_t	*icmph;
3042 	ipha_t	*ipha;
3043 	uint_t	len_needed;
3044 	size_t	msg_len;
3045 	mblk_t	*mp1;
3046 	ipaddr_t src;
3047 	ire_t	*ire;
3048 	mblk_t *ipsec_mp;
3049 	ipsec_out_t	*io = NULL;
3050 	boolean_t xmit_if_on = B_FALSE;
3051 	zoneid_t	zoneid;
3052 
3053 	if (mctl_present) {
3054 		/*
3055 		 * If it is :
3056 		 *
3057 		 * 1) a IPSEC_OUT, then this is caused by outbound
3058 		 *    datagram originating on this host. IPSEC processing
3059 		 *    may or may not have been done. Refer to comments above
3060 		 *    icmp_inbound_error_fanout for details.
3061 		 *
3062 		 * 2) a IPSEC_IN if we are generating a icmp_message
3063 		 *    for an incoming datagram destined for us i.e called
3064 		 *    from ip_fanout_send_icmp.
3065 		 */
3066 		ipsec_info_t *in;
3067 		ipsec_mp = mp;
3068 		mp = ipsec_mp->b_cont;
3069 
3070 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3071 		ipha = (ipha_t *)mp->b_rptr;
3072 
3073 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3074 		    in->ipsec_info_type == IPSEC_IN);
3075 
3076 		if (in->ipsec_info_type == IPSEC_IN) {
3077 			/*
3078 			 * Convert the IPSEC_IN to IPSEC_OUT.
3079 			 */
3080 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3081 				BUMP_MIB(&ip_mib, ipOutDiscards);
3082 				return;
3083 			}
3084 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3085 		} else {
3086 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3087 			io = (ipsec_out_t *)in;
3088 			if (io->ipsec_out_xmit_if)
3089 				xmit_if_on = B_TRUE;
3090 			/*
3091 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3092 			 * ire lookup.
3093 			 */
3094 			io->ipsec_out_proc_begin = B_FALSE;
3095 		}
3096 		zoneid = io->ipsec_out_zoneid;
3097 		ASSERT(zoneid != ALL_ZONES);
3098 	} else {
3099 		/*
3100 		 * This is in clear. The icmp message we are building
3101 		 * here should go out in clear.
3102 		 *
3103 		 * Pardon the convolution of it all, but it's easier to
3104 		 * allocate a "use cleartext" IPSEC_IN message and convert
3105 		 * it than it is to allocate a new one.
3106 		 */
3107 		ipsec_in_t *ii;
3108 		ASSERT(DB_TYPE(mp) == M_DATA);
3109 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3110 			freemsg(mp);
3111 			BUMP_MIB(&ip_mib, ipOutDiscards);
3112 			return;
3113 		}
3114 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3115 
3116 		/* This is not a secure packet */
3117 		ii->ipsec_in_secure = B_FALSE;
3118 		if (CONN_Q(q)) {
3119 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3120 		} else {
3121 			zoneid = GLOBAL_ZONEID;
3122 		}
3123 		ii->ipsec_in_zoneid = zoneid;
3124 		ipsec_mp->b_cont = mp;
3125 		ipha = (ipha_t *)mp->b_rptr;
3126 		/*
3127 		 * Convert the IPSEC_IN to IPSEC_OUT.
3128 		 */
3129 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3130 			BUMP_MIB(&ip_mib, ipOutDiscards);
3131 			return;
3132 		}
3133 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3134 	}
3135 
3136 	/* Remember our eventual destination */
3137 	dst = ipha->ipha_src;
3138 
3139 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3140 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3141 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3142 		src = ipha->ipha_dst;
3143 	} else if (!xmit_if_on) {
3144 		if (ire != NULL)
3145 			ire_refrele(ire);
3146 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3147 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3148 		if (ire == NULL) {
3149 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3150 			freemsg(ipsec_mp);
3151 			return;
3152 		}
3153 		src = ire->ire_src_addr;
3154 	} else {
3155 		ipif_t	*ipif = NULL;
3156 		ill_t	*ill;
3157 		/*
3158 		 * This must be an ICMP error coming from
3159 		 * ip_mrtun_forward(). The src addr should
3160 		 * be equal to the IP-addr of the outgoing
3161 		 * interface.
3162 		 */
3163 		if (io == NULL) {
3164 			/* This is not a IPSEC_OUT type control msg */
3165 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3166 			freemsg(ipsec_mp);
3167 			return;
3168 		}
3169 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3170 		    NULL, NULL, NULL, NULL);
3171 		if (ill != NULL) {
3172 			ipif = ipif_get_next_ipif(NULL, ill);
3173 			ill_refrele(ill);
3174 		}
3175 		if (ipif == NULL) {
3176 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3177 			freemsg(ipsec_mp);
3178 			return;
3179 		}
3180 		src = ipif->ipif_src_addr;
3181 		ipif_refrele(ipif);
3182 	}
3183 
3184 	if (ire != NULL)
3185 		ire_refrele(ire);
3186 
3187 	/*
3188 	 * Check if we can send back more then 8 bytes in addition
3189 	 * to the IP header. We will include as much as 64 bytes.
3190 	 */
3191 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3192 	msg_len = msgdsize(mp);
3193 	if (msg_len > len_needed) {
3194 		(void) adjmsg(mp, len_needed - msg_len);
3195 		msg_len = len_needed;
3196 	}
3197 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3198 	if (!mp1) {
3199 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3200 		freemsg(ipsec_mp);
3201 		return;
3202 	}
3203 	mp1->b_cont = mp;
3204 	mp = mp1;
3205 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3206 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3207 	    io->ipsec_out_type == IPSEC_OUT);
3208 	ipsec_mp->b_cont = mp;
3209 
3210 	/*
3211 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3212 	 * node generates be accepted in peace by all on-host destinations.
3213 	 * If we do NOT assume that all on-host destinations trust
3214 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3215 	 * (Look for ipsec_out_icmp_loopback).
3216 	 */
3217 	io->ipsec_out_icmp_loopback = B_TRUE;
3218 
3219 	ipha = (ipha_t *)mp->b_rptr;
3220 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3221 	*ipha = icmp_ipha;
3222 	ipha->ipha_src = src;
3223 	ipha->ipha_dst = dst;
3224 	ipha->ipha_ttl = ip_def_ttl;
3225 	msg_len += sizeof (icmp_ipha) + len;
3226 	if (msg_len > IP_MAXPACKET) {
3227 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3228 		msg_len = IP_MAXPACKET;
3229 	}
3230 	ipha->ipha_length = htons((uint16_t)msg_len);
3231 	icmph = (icmph_t *)&ipha[1];
3232 	bcopy(stuff, icmph, len);
3233 	icmph->icmph_checksum = 0;
3234 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3235 	if (icmph->icmph_checksum == 0)
3236 		icmph->icmph_checksum = 0xFFFF;
3237 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3238 	put(q, ipsec_mp);
3239 }
3240 
3241 /*
3242  * Determine if an ICMP error packet can be sent given the rate limit.
3243  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3244  * in milliseconds) and a burst size. Burst size number of packets can
3245  * be sent arbitrarely closely spaced.
3246  * The state is tracked using two variables to implement an approximate
3247  * token bucket filter:
3248  *	icmp_pkt_err_last - lbolt value when the last burst started
3249  *	icmp_pkt_err_sent - number of packets sent in current burst
3250  */
3251 boolean_t
3252 icmp_err_rate_limit(void)
3253 {
3254 	clock_t now = TICK_TO_MSEC(lbolt);
3255 	uint_t refilled; /* Number of packets refilled in tbf since last */
3256 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3257 
3258 	if (err_interval == 0)
3259 		return (B_FALSE);
3260 
3261 	if (icmp_pkt_err_last > now) {
3262 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3263 		icmp_pkt_err_last = 0;
3264 		icmp_pkt_err_sent = 0;
3265 	}
3266 	/*
3267 	 * If we are in a burst update the token bucket filter.
3268 	 * Update the "last" time to be close to "now" but make sure
3269 	 * we don't loose precision.
3270 	 */
3271 	if (icmp_pkt_err_sent != 0) {
3272 		refilled = (now - icmp_pkt_err_last)/err_interval;
3273 		if (refilled > icmp_pkt_err_sent) {
3274 			icmp_pkt_err_sent = 0;
3275 		} else {
3276 			icmp_pkt_err_sent -= refilled;
3277 			icmp_pkt_err_last += refilled * err_interval;
3278 		}
3279 	}
3280 	if (icmp_pkt_err_sent == 0) {
3281 		/* Start of new burst */
3282 		icmp_pkt_err_last = now;
3283 	}
3284 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3285 		icmp_pkt_err_sent++;
3286 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3287 		    icmp_pkt_err_sent));
3288 		return (B_FALSE);
3289 	}
3290 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3291 	return (B_TRUE);
3292 }
3293 
3294 /*
3295  * Check if it is ok to send an IPv4 ICMP error packet in
3296  * response to the IPv4 packet in mp.
3297  * Free the message and return null if no
3298  * ICMP error packet should be sent.
3299  */
3300 static mblk_t *
3301 icmp_pkt_err_ok(mblk_t *mp)
3302 {
3303 	icmph_t	*icmph;
3304 	ipha_t	*ipha;
3305 	uint_t	len_needed;
3306 	ire_t	*src_ire;
3307 	ire_t	*dst_ire;
3308 
3309 	if (!mp)
3310 		return (NULL);
3311 	ipha = (ipha_t *)mp->b_rptr;
3312 	if (ip_csum_hdr(ipha)) {
3313 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3314 		freemsg(mp);
3315 		return (NULL);
3316 	}
3317 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3318 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3319 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3320 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3321 	if (src_ire != NULL || dst_ire != NULL ||
3322 	    CLASSD(ipha->ipha_dst) ||
3323 	    CLASSD(ipha->ipha_src) ||
3324 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3325 		/* Note: only errors to the fragment with offset 0 */
3326 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3327 		freemsg(mp);
3328 		if (src_ire != NULL)
3329 			ire_refrele(src_ire);
3330 		if (dst_ire != NULL)
3331 			ire_refrele(dst_ire);
3332 		return (NULL);
3333 	}
3334 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3335 		/*
3336 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3337 		 * errors in response to any ICMP errors.
3338 		 */
3339 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3340 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3341 			if (!pullupmsg(mp, len_needed)) {
3342 				BUMP_MIB(&icmp_mib, icmpInErrors);
3343 				freemsg(mp);
3344 				return (NULL);
3345 			}
3346 			ipha = (ipha_t *)mp->b_rptr;
3347 		}
3348 		icmph = (icmph_t *)
3349 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3350 		switch (icmph->icmph_type) {
3351 		case ICMP_DEST_UNREACHABLE:
3352 		case ICMP_SOURCE_QUENCH:
3353 		case ICMP_TIME_EXCEEDED:
3354 		case ICMP_PARAM_PROBLEM:
3355 		case ICMP_REDIRECT:
3356 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3357 			freemsg(mp);
3358 			return (NULL);
3359 		default:
3360 			break;
3361 		}
3362 	}
3363 	if (icmp_err_rate_limit()) {
3364 		/*
3365 		 * Only send ICMP error packets every so often.
3366 		 * This should be done on a per port/source basis,
3367 		 * but for now this will suffice.
3368 		 */
3369 		freemsg(mp);
3370 		return (NULL);
3371 	}
3372 	return (mp);
3373 }
3374 
3375 /*
3376  * Generate an ICMP redirect message.
3377  */
3378 static void
3379 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3380 {
3381 	icmph_t	icmph;
3382 
3383 	/*
3384 	 * We are called from ip_rput where we could
3385 	 * not have attached an IPSEC_IN.
3386 	 */
3387 	ASSERT(mp->b_datap->db_type == M_DATA);
3388 
3389 	if (!(mp = icmp_pkt_err_ok(mp))) {
3390 		return;
3391 	}
3392 
3393 	bzero(&icmph, sizeof (icmph_t));
3394 	icmph.icmph_type = ICMP_REDIRECT;
3395 	icmph.icmph_code = 1;
3396 	icmph.icmph_rd_gateway = gateway;
3397 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3398 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3399 }
3400 
3401 /*
3402  * Generate an ICMP time exceeded message.
3403  */
3404 void
3405 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3406 {
3407 	icmph_t	icmph;
3408 	boolean_t mctl_present;
3409 	mblk_t *first_mp;
3410 
3411 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3412 
3413 	if (!(mp = icmp_pkt_err_ok(mp))) {
3414 		if (mctl_present)
3415 			freeb(first_mp);
3416 		return;
3417 	}
3418 
3419 	bzero(&icmph, sizeof (icmph_t));
3420 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3421 	icmph.icmph_code = code;
3422 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3423 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3424 }
3425 
3426 /*
3427  * Generate an ICMP unreachable message.
3428  */
3429 void
3430 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3431 {
3432 	icmph_t	icmph;
3433 	mblk_t *first_mp;
3434 	boolean_t mctl_present;
3435 
3436 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3437 
3438 	if (!(mp = icmp_pkt_err_ok(mp))) {
3439 		if (mctl_present)
3440 			freeb(first_mp);
3441 		return;
3442 	}
3443 
3444 	bzero(&icmph, sizeof (icmph_t));
3445 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3446 	icmph.icmph_code = code;
3447 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3448 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3449 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3450 }
3451 
3452 /*
3453  * News from ARP.  ARP sends notification of interesting events down
3454  * to its clients using M_CTL messages with the interesting ARP packet
3455  * attached via b_cont.
3456  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3457  * queue as opposed to ARP sending the message to all the clients, i.e. all
3458  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3459  * table if a cache IRE is found to delete all the entries for the address in
3460  * the packet.
3461  */
3462 static void
3463 ip_arp_news(queue_t *q, mblk_t *mp)
3464 {
3465 	arcn_t		*arcn;
3466 	arh_t		*arh;
3467 	char		*cp1;
3468 	uchar_t		*cp2;
3469 	ire_t		*ire = NULL;
3470 	int		i1;
3471 	char		hbuf[128];
3472 	char		sbuf[16];
3473 	ipaddr_t	src;
3474 	in6_addr_t	v6src;
3475 	boolean_t	isv6 = B_FALSE;
3476 
3477 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3478 		if (q->q_next) {
3479 			putnext(q, mp);
3480 		} else
3481 			freemsg(mp);
3482 		return;
3483 	}
3484 	arh = (arh_t *)mp->b_cont->b_rptr;
3485 	/* Is it one we are interested in? */
3486 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3487 		isv6 = B_TRUE;
3488 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3489 		    IPV6_ADDR_LEN);
3490 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3491 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3492 		    IP_ADDR_LEN);
3493 	} else {
3494 		freemsg(mp);
3495 		return;
3496 	}
3497 
3498 	arcn = (arcn_t *)mp->b_rptr;
3499 	switch (arcn->arcn_code) {
3500 	case AR_CN_BOGON:
3501 		/*
3502 		 * Someone is sending ARP packets with a source protocol
3503 		 * address which we have published.  Either they are
3504 		 * pretending to be us, or we have been asked to proxy
3505 		 * for a machine that can do fine for itself, or two
3506 		 * different machines are providing proxy service for the
3507 		 * same protocol address, or something.  We try and do
3508 		 * something appropriate here.
3509 		 */
3510 		cp2 = (uchar_t *)&arh[1];
3511 		cp1 = hbuf;
3512 		*cp1 = '\0';
3513 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3514 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3515 		if (cp1 != hbuf)
3516 			cp1[-1] = '\0';
3517 		(void) ip_dot_addr(src, sbuf);
3518 		if (isv6)
3519 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3520 		else
3521 			ire = ire_cache_lookup(src, ALL_ZONES);
3522 
3523 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3524 			cmn_err(CE_WARN,
3525 			    "IP: Hardware address '%s' trying"
3526 			    " to be our address %s!",
3527 			    hbuf, sbuf);
3528 		} else {
3529 			cmn_err(CE_WARN,
3530 			    "IP: Proxy ARP problem?  "
3531 			    "Hardware address '%s' thinks it is %s",
3532 			    hbuf, sbuf);
3533 		}
3534 		if (ire != NULL)
3535 			ire_refrele(ire);
3536 		break;
3537 	case AR_CN_ANNOUNCE:
3538 		if (isv6) {
3539 			/*
3540 			 * For XRESOLV interfaces.
3541 			 * Delete the IRE cache entry and NCE for this
3542 			 * v6 address
3543 			 */
3544 			ip_ire_clookup_and_delete_v6(&v6src);
3545 			/*
3546 			 * If v6src is a non-zero, it's a router address
3547 			 * as below. Do the same sort of thing to clean
3548 			 * out off-net IRE_CACHE entries that go through
3549 			 * the router.
3550 			 */
3551 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3552 				ire_walk_v6(ire_delete_cache_gw_v6,
3553 				    (char *)&v6src, ALL_ZONES);
3554 			}
3555 			break;
3556 		}
3557 		/*
3558 		 * ARP gives us a copy of any broadcast packet with identical
3559 		 * sender and receiver protocol address, in
3560 		 * case we want to intuit something from it.  Such a packet
3561 		 * usually means that a machine has just come up on the net.
3562 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3563 		 * immediately pick up the rare case of a host changing
3564 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3565 		 *
3566 		 * The address in "src" may be an entry for a router.
3567 		 * (Default router, or non-default router.)  If
3568 		 * that's true, then any off-net IRE_CACHE entries
3569 		 * that go through the router with address "src"
3570 		 * must be clobbered.  Use ire_walk to achieve this
3571 		 * goal.
3572 		 *
3573 		 * It should be possible to determine if the address
3574 		 * in src is or is not for a router.  This way,
3575 		 * the ire_walk() isn't called all of the time here.
3576 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3577 		 * as it would remove all IRE_CACHE entries for onlink
3578 		 * destinations. All onlink destinations have
3579 		 * ire_gateway_addr == 0.
3580 		 */
3581 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3582 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3583 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3584 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3585 			    ALL_ZONES);
3586 		}
3587 		/* From ire_ftable_lookup */
3588 		if (ire != NULL)
3589 			ire_refrele(ire);
3590 		break;
3591 	default:
3592 		if (ire != NULL)
3593 			ire_refrele(ire);
3594 		break;
3595 	}
3596 	freemsg(mp);
3597 }
3598 
3599 /*
3600  * Create a mblk suitable for carrying the interface index and/or source link
3601  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3602  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3603  * application.
3604  */
3605 mblk_t *
3606 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3607 {
3608 	mblk_t		*mp;
3609 	in_pktinfo_t	*pinfo;
3610 	ipha_t *ipha;
3611 	struct ether_header *pether;
3612 
3613 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3614 	if (mp == NULL) {
3615 		ip1dbg(("ip_add_info: allocation failure.\n"));
3616 		return (data_mp);
3617 	}
3618 
3619 	ipha	= (ipha_t *)data_mp->b_rptr;
3620 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3621 	bzero(pinfo, sizeof (in_pktinfo_t));
3622 	pinfo->in_pkt_flags = (uchar_t)flags;
3623 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3624 
3625 	if (flags & IPF_RECVIF)
3626 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3627 
3628 	pether = (struct ether_header *)((char *)ipha
3629 	    - sizeof (struct ether_header));
3630 	/*
3631 	 * Make sure the interface is an ethernet type, since this option
3632 	 * is currently supported only on this type of interface. Also make
3633 	 * sure we are pointing correctly above db_base.
3634 	 */
3635 
3636 	if ((flags & IPF_RECVSLLA) &&
3637 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3638 	    (ill->ill_type == IFT_ETHER) &&
3639 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3640 
3641 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3642 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3643 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3644 	} else {
3645 		/*
3646 		 * Clear the bit. Indicate to upper layer that IP is not
3647 		 * sending this ancillary info.
3648 		 */
3649 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3650 	}
3651 
3652 	mp->b_datap->db_type = M_CTL;
3653 	mp->b_wptr += sizeof (in_pktinfo_t);
3654 	mp->b_cont = data_mp;
3655 
3656 	return (mp);
3657 }
3658 
3659 /*
3660  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3661  * part of the bind request.
3662  */
3663 
3664 boolean_t
3665 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3666 {
3667 	ipsec_in_t *ii;
3668 
3669 	ASSERT(policy_mp != NULL);
3670 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3671 
3672 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3673 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3674 
3675 	connp->conn_policy = ii->ipsec_in_policy;
3676 	ii->ipsec_in_policy = NULL;
3677 
3678 	if (ii->ipsec_in_action != NULL) {
3679 		if (connp->conn_latch == NULL) {
3680 			connp->conn_latch = iplatch_create();
3681 			if (connp->conn_latch == NULL)
3682 				return (B_FALSE);
3683 		}
3684 		ipsec_latch_inbound(connp->conn_latch, ii);
3685 	}
3686 	return (B_TRUE);
3687 }
3688 
3689 /*
3690  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3691  * and to arrange for power-fanout assist.  The ULP is identified by
3692  * adding a single byte at the end of the original bind message.
3693  * A ULP other than UDP or TCP that wishes to be recognized passes
3694  * down a bind with a zero length address.
3695  *
3696  * The binding works as follows:
3697  * - A zero byte address means just bind to the protocol.
3698  * - A four byte address is treated as a request to validate
3699  *   that the address is a valid local address, appropriate for
3700  *   an application to bind to. This does not affect any fanout
3701  *   information in IP.
3702  * - A sizeof sin_t byte address is used to bind to only the local address
3703  *   and port.
3704  * - A sizeof ipa_conn_t byte address contains complete fanout information
3705  *   consisting of local and remote addresses and ports.  In
3706  *   this case, the addresses are both validated as appropriate
3707  *   for this operation, and, if so, the information is retained
3708  *   for use in the inbound fanout.
3709  *
3710  * The ULP (except in the zero-length bind) can append an
3711  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3712  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3713  * a copy of the source or destination IRE (source for local bind;
3714  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3715  * policy information contained should be copied on to the conn.
3716  *
3717  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3718  */
3719 mblk_t *
3720 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3721 {
3722 	ssize_t		len;
3723 	struct T_bind_req	*tbr;
3724 	sin_t		*sin;
3725 	ipa_conn_t	*ac;
3726 	uchar_t		*ucp;
3727 	mblk_t		*mp1;
3728 	boolean_t	ire_requested;
3729 	boolean_t	ipsec_policy_set = B_FALSE;
3730 	int		error = 0;
3731 	int		protocol;
3732 	ipa_conn_x_t	*acx;
3733 
3734 	ASSERT(!connp->conn_af_isv6);
3735 	connp->conn_pkt_isv6 = B_FALSE;
3736 
3737 	len = MBLKL(mp);
3738 	if (len < (sizeof (*tbr) + 1)) {
3739 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3740 		    "ip_bind: bogus msg, len %ld", len);
3741 		/* XXX: Need to return something better */
3742 		goto bad_addr;
3743 	}
3744 	/* Back up and extract the protocol identifier. */
3745 	mp->b_wptr--;
3746 	protocol = *mp->b_wptr & 0xFF;
3747 	tbr = (struct T_bind_req *)mp->b_rptr;
3748 	/* Reset the message type in preparation for shipping it back. */
3749 	DB_TYPE(mp) = M_PCPROTO;
3750 
3751 	connp->conn_ulp = (uint8_t)protocol;
3752 
3753 	/*
3754 	 * Check for a zero length address.  This is from a protocol that
3755 	 * wants to register to receive all packets of its type.
3756 	 */
3757 	if (tbr->ADDR_length == 0) {
3758 		/*
3759 		 * These protocols are now intercepted in ip_bind_v6().
3760 		 * Reject protocol-level binds here for now.
3761 		 *
3762 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3763 		 * so that the protocol type cannot be SCTP.
3764 		 */
3765 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3766 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3767 			goto bad_addr;
3768 		}
3769 
3770 		/* No hash here really.  The table is big enough. */
3771 		connp->conn_srcv6 = ipv6_all_zeros;
3772 
3773 		ipcl_proto_insert(connp, protocol);
3774 
3775 		tbr->PRIM_type = T_BIND_ACK;
3776 		return (mp);
3777 	}
3778 
3779 	/* Extract the address pointer from the message. */
3780 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3781 	    tbr->ADDR_length);
3782 	if (ucp == NULL) {
3783 		ip1dbg(("ip_bind: no address\n"));
3784 		goto bad_addr;
3785 	}
3786 	if (!OK_32PTR(ucp)) {
3787 		ip1dbg(("ip_bind: unaligned address\n"));
3788 		goto bad_addr;
3789 	}
3790 	/*
3791 	 * Check for trailing mps.
3792 	 */
3793 
3794 	mp1 = mp->b_cont;
3795 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
3796 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
3797 
3798 	switch (tbr->ADDR_length) {
3799 	default:
3800 		ip1dbg(("ip_bind: bad address length %d\n",
3801 		    (int)tbr->ADDR_length));
3802 		goto bad_addr;
3803 
3804 	case IP_ADDR_LEN:
3805 		/* Verification of local address only */
3806 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3807 		    ire_requested, ipsec_policy_set, B_FALSE);
3808 		break;
3809 
3810 	case sizeof (sin_t):
3811 		sin = (sin_t *)ucp;
3812 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3813 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3814 		if (protocol == IPPROTO_TCP)
3815 			connp->conn_recv = tcp_conn_request;
3816 		break;
3817 
3818 	case sizeof (ipa_conn_t):
3819 		ac = (ipa_conn_t *)ucp;
3820 		/* For raw socket, the local port is not set. */
3821 		if (ac->ac_lport == 0)
3822 			ac->ac_lport = connp->conn_lport;
3823 		/* Always verify destination reachability. */
3824 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3825 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3826 		    ipsec_policy_set, B_TRUE, B_TRUE);
3827 		if (protocol == IPPROTO_TCP)
3828 			connp->conn_recv = tcp_input;
3829 		break;
3830 
3831 	case sizeof (ipa_conn_x_t):
3832 		acx = (ipa_conn_x_t *)ucp;
3833 		/*
3834 		 * Whether or not to verify destination reachability depends
3835 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3836 		 */
3837 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3838 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3839 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3840 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3841 		if (protocol == IPPROTO_TCP)
3842 			connp->conn_recv = tcp_input;
3843 		break;
3844 	}
3845 	if (error == EINPROGRESS)
3846 		return (NULL);
3847 	else if (error != 0)
3848 		goto bad_addr;
3849 	/*
3850 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3851 	 * We can't do this in ip_bind_insert_ire because the policy
3852 	 * may not have been inherited at that point in time and hence
3853 	 * conn_out_enforce_policy may not be set.
3854 	 */
3855 	mp1 = mp->b_cont;
3856 	if (ire_requested && connp->conn_out_enforce_policy &&
3857 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3858 		ire_t *ire = (ire_t *)mp1->b_rptr;
3859 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3860 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3861 	}
3862 
3863 	/* Send it home. */
3864 	mp->b_datap->db_type = M_PCPROTO;
3865 	tbr->PRIM_type = T_BIND_ACK;
3866 	return (mp);
3867 
3868 bad_addr:
3869 	/*
3870 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3871 	 * a unix errno.
3872 	 */
3873 	if (error > 0)
3874 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3875 	else
3876 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3877 	return (mp);
3878 }
3879 
3880 /*
3881  * Here address is verified to be a valid local address.
3882  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3883  * address is also considered a valid local address.
3884  * In the case of a broadcast/multicast address, however, the
3885  * upper protocol is expected to reset the src address
3886  * to 0 if it sees a IRE_BROADCAST type returned so that
3887  * no packets are emitted with broadcast/multicast address as
3888  * source address (that violates hosts requirements RFC1122)
3889  * The addresses valid for bind are:
3890  *	(1) - INADDR_ANY (0)
3891  *	(2) - IP address of an UP interface
3892  *	(3) - IP address of a DOWN interface
3893  *	(4) - valid local IP broadcast addresses. In this case
3894  *	the conn will only receive packets destined to
3895  *	the specified broadcast address.
3896  *	(5) - a multicast address. In this case
3897  *	the conn will only receive packets destined to
3898  *	the specified multicast address. Note: the
3899  *	application still has to issue an
3900  *	IP_ADD_MEMBERSHIP socket option.
3901  *
3902  * On error, return -1 for TBADADDR otherwise pass the
3903  * errno with TSYSERR reply.
3904  *
3905  * In all the above cases, the bound address must be valid in the current zone.
3906  * When the address is loopback, multicast or broadcast, there might be many
3907  * matching IREs so bind has to look up based on the zone.
3908  */
3909 int
3910 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3911     boolean_t ire_requested, boolean_t ipsec_policy_set,
3912     boolean_t fanout_insert)
3913 {
3914 	int		error = 0;
3915 	ire_t		*src_ire;
3916 	mblk_t		*policy_mp;
3917 	ipif_t		*ipif;
3918 	zoneid_t	zoneid;
3919 
3920 	if (ipsec_policy_set) {
3921 		policy_mp = mp->b_cont;
3922 	}
3923 
3924 	/*
3925 	 * If it was previously connected, conn_fully_bound would have
3926 	 * been set.
3927 	 */
3928 	connp->conn_fully_bound = B_FALSE;
3929 
3930 	src_ire = NULL;
3931 	ipif = NULL;
3932 
3933 	zoneid = connp->conn_zoneid;
3934 
3935 	if (src_addr) {
3936 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3937 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3938 		/*
3939 		 * If an address other than 0.0.0.0 is requested,
3940 		 * we verify that it is a valid address for bind
3941 		 * Note: Following code is in if-else-if form for
3942 		 * readability compared to a condition check.
3943 		 */
3944 		/* LINTED - statement has no consequent */
3945 		if (IRE_IS_LOCAL(src_ire)) {
3946 			/*
3947 			 * (2) Bind to address of local UP interface
3948 			 */
3949 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3950 			/*
3951 			 * (4) Bind to broadcast address
3952 			 * Note: permitted only from transports that
3953 			 * request IRE
3954 			 */
3955 			if (!ire_requested)
3956 				error = EADDRNOTAVAIL;
3957 		} else {
3958 			/*
3959 			 * (3) Bind to address of local DOWN interface
3960 			 * (ipif_lookup_addr() looks up all interfaces
3961 			 * but we do not get here for UP interfaces
3962 			 * - case (2) above)
3963 			 * We put the protocol byte back into the mblk
3964 			 * since we may come back via ip_wput_nondata()
3965 			 * later with this mblk if ipif_lookup_addr chooses
3966 			 * to defer processing.
3967 			 */
3968 			*mp->b_wptr++ = (char)connp->conn_ulp;
3969 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3970 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3971 			    &error)) != NULL) {
3972 				ipif_refrele(ipif);
3973 			} else if (error == EINPROGRESS) {
3974 				if (src_ire != NULL)
3975 					ire_refrele(src_ire);
3976 				return (EINPROGRESS);
3977 			} else if (CLASSD(src_addr)) {
3978 				error = 0;
3979 				if (src_ire != NULL)
3980 					ire_refrele(src_ire);
3981 				/*
3982 				 * (5) bind to multicast address.
3983 				 * Fake out the IRE returned to upper
3984 				 * layer to be a broadcast IRE.
3985 				 */
3986 				src_ire = ire_ctable_lookup(
3987 				    INADDR_BROADCAST, INADDR_ANY,
3988 				    IRE_BROADCAST, NULL, zoneid,
3989 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3990 				if (src_ire == NULL || !ire_requested)
3991 					error = EADDRNOTAVAIL;
3992 			} else {
3993 				/*
3994 				 * Not a valid address for bind
3995 				 */
3996 				error = EADDRNOTAVAIL;
3997 			}
3998 			/*
3999 			 * Just to keep it consistent with the processing in
4000 			 * ip_bind_v4()
4001 			 */
4002 			mp->b_wptr--;
4003 		}
4004 		if (error) {
4005 			/* Red Alert!  Attempting to be a bogon! */
4006 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4007 			    ntohl(src_addr)));
4008 			goto bad_addr;
4009 		}
4010 	}
4011 
4012 	/*
4013 	 * Allow setting new policies. For example, disconnects come
4014 	 * down as ipa_t bind. As we would have set conn_policy_cached
4015 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4016 	 * can change after the disconnect.
4017 	 */
4018 	connp->conn_policy_cached = B_FALSE;
4019 
4020 	/*
4021 	 * If not fanout_insert this was just an address verification
4022 	 */
4023 	if (fanout_insert) {
4024 		/*
4025 		 * The addresses have been verified. Time to insert in
4026 		 * the correct fanout list.
4027 		 */
4028 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4029 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4030 		connp->conn_lport = lport;
4031 		connp->conn_fport = 0;
4032 		/*
4033 		 * Do we need to add a check to reject Multicast packets
4034 		 */
4035 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4036 	}
4037 done:
4038 	if (error == 0) {
4039 		if (ire_requested) {
4040 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4041 				error = -1;
4042 				/* Falls through to bad_addr */
4043 			}
4044 		} else if (ipsec_policy_set) {
4045 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4046 				error = -1;
4047 				/* Falls through to bad_addr */
4048 			}
4049 		}
4050 	}
4051 bad_addr:
4052 	if (src_ire != NULL)
4053 		IRE_REFRELE(src_ire);
4054 	if (ipsec_policy_set) {
4055 		ASSERT(policy_mp == mp->b_cont);
4056 		ASSERT(policy_mp != NULL);
4057 		freeb(policy_mp);
4058 		/*
4059 		 * As of now assume that nothing else accompanies
4060 		 * IPSEC_POLICY_SET.
4061 		 */
4062 		mp->b_cont = NULL;
4063 	}
4064 	return (error);
4065 }
4066 
4067 /*
4068  * Verify that both the source and destination addresses
4069  * are valid.  If verify_dst is false, then the destination address may be
4070  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4071  * destination reachability, while tunnels do not.
4072  * Note that we allow connect to broadcast and multicast
4073  * addresses when ire_requested is set. Thus the ULP
4074  * has to check for IRE_BROADCAST and multicast.
4075  *
4076  * Returns zero if ok.
4077  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4078  * (for use with TSYSERR reply).
4079  */
4080 int
4081 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4082     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4083     boolean_t ire_requested, boolean_t ipsec_policy_set,
4084     boolean_t fanout_insert, boolean_t verify_dst)
4085 {
4086 	ire_t		*src_ire;
4087 	ire_t		*dst_ire;
4088 	int		error = 0;
4089 	int 		protocol;
4090 	mblk_t		*policy_mp;
4091 	ire_t		*sire = NULL;
4092 	ire_t		*md_dst_ire = NULL;
4093 	ill_t		*md_ill = NULL;
4094 	zoneid_t	zoneid;
4095 	ipaddr_t	src_addr = *src_addrp;
4096 
4097 	src_ire = dst_ire = NULL;
4098 	protocol = *mp->b_wptr & 0xFF;
4099 
4100 	/*
4101 	 * If we never got a disconnect before, clear it now.
4102 	 */
4103 	connp->conn_fully_bound = B_FALSE;
4104 
4105 	if (ipsec_policy_set) {
4106 		policy_mp = mp->b_cont;
4107 	}
4108 
4109 	zoneid = connp->conn_zoneid;
4110 
4111 	if (CLASSD(dst_addr)) {
4112 		/* Pick up an IRE_BROADCAST */
4113 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4114 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4115 		    MATCH_IRE_RJ_BHOLE));
4116 	} else {
4117 		/*
4118 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4119 		 * and onlink ipif is not found set ENETUNREACH error.
4120 		 */
4121 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4122 			ipif_t *ipif;
4123 
4124 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4125 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4126 			if (ipif == NULL) {
4127 				error = ENETUNREACH;
4128 				goto bad_addr;
4129 			}
4130 			ipif_refrele(ipif);
4131 		}
4132 
4133 		if (connp->conn_nexthop_set) {
4134 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4135 			    0, 0, NULL, NULL, zoneid, 0);
4136 		} else {
4137 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4138 			    &sire, zoneid,
4139 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4140 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4141 		}
4142 	}
4143 	/*
4144 	 * dst_ire can't be a broadcast when not ire_requested.
4145 	 * We also prevent ire's with src address INADDR_ANY to
4146 	 * be used, which are created temporarily for
4147 	 * sending out packets from endpoints that have
4148 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4149 	 * reachable.  If verify_dst is false, the destination needn't be
4150 	 * reachable.
4151 	 *
4152 	 * If we match on a reject or black hole, then we've got a
4153 	 * local failure.  May as well fail out the connect() attempt,
4154 	 * since it's never going to succeed.
4155 	 */
4156 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4157 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4158 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4159 		/*
4160 		 * If we're verifying destination reachability, we always want
4161 		 * to complain here.
4162 		 *
4163 		 * If we're not verifying destination reachability but the
4164 		 * destination has a route, we still want to fail on the
4165 		 * temporary address and broadcast address tests.
4166 		 */
4167 		if (verify_dst || (dst_ire != NULL)) {
4168 			if (ip_debug > 2) {
4169 				pr_addr_dbg("ip_bind_connected: bad connected "
4170 				    "dst %s\n", AF_INET, &dst_addr);
4171 			}
4172 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4173 				error = ENETUNREACH;
4174 			else
4175 				error = EHOSTUNREACH;
4176 			goto bad_addr;
4177 		}
4178 	}
4179 	/*
4180 	 * If the app does a connect(), it means that it will most likely
4181 	 * send more than 1 packet to the destination.  It makes sense
4182 	 * to clear the temporary flag.
4183 	 */
4184 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4185 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4186 		irb_t *irb = dst_ire->ire_bucket;
4187 
4188 		rw_enter(&irb->irb_lock, RW_WRITER);
4189 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4190 		irb->irb_tmp_ire_cnt--;
4191 		rw_exit(&irb->irb_lock);
4192 	}
4193 
4194 	/*
4195 	 * See if we should notify ULP about MDT; we do this whether or not
4196 	 * ire_requested is TRUE, in order to handle active connects; MDT
4197 	 * eligibility tests for passive connects are handled separately
4198 	 * through tcp_adapt_ire().  We do this before the source address
4199 	 * selection, because dst_ire may change after a call to
4200 	 * ipif_select_source().  This is a best-effort check, as the
4201 	 * packet for this connection may not actually go through
4202 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4203 	 * calling ip_newroute().  This is why we further check on the
4204 	 * IRE during Multidata packet transmission in tcp_multisend().
4205 	 */
4206 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4207 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4208 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4209 	    ILL_MDT_CAPABLE(md_ill)) {
4210 		md_dst_ire = dst_ire;
4211 		IRE_REFHOLD(md_dst_ire);
4212 	}
4213 
4214 	if (dst_ire != NULL &&
4215 	    dst_ire->ire_type == IRE_LOCAL &&
4216 	    dst_ire->ire_zoneid != zoneid) {
4217 		/*
4218 		 * If the IRE belongs to a different zone, look for a matching
4219 		 * route in the forwarding table and use the source address from
4220 		 * that route.
4221 		 */
4222 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4223 		    zoneid, 0,
4224 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4225 		    MATCH_IRE_RJ_BHOLE);
4226 		if (src_ire == NULL) {
4227 			error = EHOSTUNREACH;
4228 			goto bad_addr;
4229 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4230 			if (!(src_ire->ire_type & IRE_HOST))
4231 				error = ENETUNREACH;
4232 			else
4233 				error = EHOSTUNREACH;
4234 			goto bad_addr;
4235 		}
4236 		if (src_addr == INADDR_ANY)
4237 			src_addr = src_ire->ire_src_addr;
4238 		ire_refrele(src_ire);
4239 		src_ire = NULL;
4240 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4241 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4242 			src_addr = sire->ire_src_addr;
4243 			ire_refrele(dst_ire);
4244 			dst_ire = sire;
4245 			sire = NULL;
4246 		} else {
4247 			/*
4248 			 * Pick a source address so that a proper inbound
4249 			 * load spreading would happen.
4250 			 */
4251 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4252 			ipif_t *src_ipif = NULL;
4253 			ire_t *ipif_ire;
4254 
4255 			/*
4256 			 * Supply a local source address such that inbound
4257 			 * load spreading happens.
4258 			 *
4259 			 * Determine the best source address on this ill for
4260 			 * the destination.
4261 			 *
4262 			 * 1) For broadcast, we should return a broadcast ire
4263 			 *    found above so that upper layers know that the
4264 			 *    destination address is a broadcast address.
4265 			 *
4266 			 * 2) If this is part of a group, select a better
4267 			 *    source address so that better inbound load
4268 			 *    balancing happens. Do the same if the ipif
4269 			 *    is DEPRECATED.
4270 			 *
4271 			 * 3) If the outgoing interface is part of a usesrc
4272 			 *    group, then try selecting a source address from
4273 			 *    the usesrc ILL.
4274 			 */
4275 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4276 			    ((dst_ill->ill_group != NULL) ||
4277 			    (dst_ire->ire_ipif->ipif_flags &
4278 			    IPIF_DEPRECATED) ||
4279 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4280 				/*
4281 				 * If the destination is reachable via a
4282 				 * given gateway, the selected source address
4283 				 * should be in the same subnet as the gateway.
4284 				 * Otherwise, the destination is not reachable.
4285 				 *
4286 				 * If there are no interfaces on the same subnet
4287 				 * as the destination, ipif_select_source gives
4288 				 * first non-deprecated interface which might be
4289 				 * on a different subnet than the gateway.
4290 				 * This is not desirable. Hence pass the dst_ire
4291 				 * source address to ipif_select_source.
4292 				 * It is sure that the destination is reachable
4293 				 * with the dst_ire source address subnet.
4294 				 * So passing dst_ire source address to
4295 				 * ipif_select_source will make sure that the
4296 				 * selected source will be on the same subnet
4297 				 * as dst_ire source address.
4298 				 */
4299 				ipaddr_t saddr =
4300 				    dst_ire->ire_ipif->ipif_src_addr;
4301 				src_ipif = ipif_select_source(dst_ill,
4302 				    saddr, zoneid);
4303 				if (src_ipif != NULL) {
4304 					if (IS_VNI(src_ipif->ipif_ill)) {
4305 						/*
4306 						 * For VNI there is no
4307 						 * interface route
4308 						 */
4309 						src_addr =
4310 						    src_ipif->ipif_src_addr;
4311 					} else {
4312 						ipif_ire =
4313 						    ipif_to_ire(src_ipif);
4314 						if (ipif_ire != NULL) {
4315 							IRE_REFRELE(dst_ire);
4316 							dst_ire = ipif_ire;
4317 						}
4318 						src_addr =
4319 						    dst_ire->ire_src_addr;
4320 					}
4321 					ipif_refrele(src_ipif);
4322 				} else {
4323 					src_addr = dst_ire->ire_src_addr;
4324 				}
4325 			} else {
4326 				src_addr = dst_ire->ire_src_addr;
4327 			}
4328 		}
4329 	}
4330 
4331 	/*
4332 	 * We do ire_route_lookup() here (and not
4333 	 * interface lookup as we assert that
4334 	 * src_addr should only come from an
4335 	 * UP interface for hard binding.
4336 	 */
4337 	ASSERT(src_ire == NULL);
4338 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4339 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4340 	/* src_ire must be a local|loopback */
4341 	if (!IRE_IS_LOCAL(src_ire)) {
4342 		if (ip_debug > 2) {
4343 			pr_addr_dbg("ip_bind_connected: bad connected "
4344 			    "src %s\n", AF_INET, &src_addr);
4345 		}
4346 		error = EADDRNOTAVAIL;
4347 		goto bad_addr;
4348 	}
4349 
4350 	/*
4351 	 * If the source address is a loopback address, the
4352 	 * destination had best be local or multicast.
4353 	 * The transports that can't handle multicast will reject
4354 	 * those addresses.
4355 	 */
4356 	if (src_ire->ire_type == IRE_LOOPBACK &&
4357 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4358 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4359 		error = -1;
4360 		goto bad_addr;
4361 	}
4362 
4363 	/*
4364 	 * Allow setting new policies. For example, disconnects come
4365 	 * down as ipa_t bind. As we would have set conn_policy_cached
4366 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4367 	 * can change after the disconnect.
4368 	 */
4369 	connp->conn_policy_cached = B_FALSE;
4370 
4371 	/*
4372 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4373 	 * can handle their passed-in conn's.
4374 	 */
4375 
4376 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4377 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4378 	connp->conn_lport = lport;
4379 	connp->conn_fport = fport;
4380 	*src_addrp = src_addr;
4381 
4382 	ASSERT(!(ipsec_policy_set && ire_requested));
4383 	if (ire_requested) {
4384 		iulp_t *ulp_info = NULL;
4385 
4386 		/*
4387 		 * Note that sire will not be NULL if this is an off-link
4388 		 * connection and there is not cache for that dest yet.
4389 		 *
4390 		 * XXX Because of an existing bug, if there are multiple
4391 		 * default routes, the IRE returned now may not be the actual
4392 		 * default route used (default routes are chosen in a
4393 		 * round robin fashion).  So if the metrics for different
4394 		 * default routes are different, we may return the wrong
4395 		 * metrics.  This will not be a problem if the existing
4396 		 * bug is fixed.
4397 		 */
4398 		if (sire != NULL) {
4399 			ulp_info = &(sire->ire_uinfo);
4400 		}
4401 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4402 			error = -1;
4403 			goto bad_addr;
4404 		}
4405 	} else if (ipsec_policy_set) {
4406 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4407 			error = -1;
4408 			goto bad_addr;
4409 		}
4410 	}
4411 
4412 	/*
4413 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4414 	 * we'll cache that.  If we don't, we'll inherit global policy.
4415 	 *
4416 	 * We can't insert until the conn reflects the policy. Note that
4417 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4418 	 * connections where we don't have a policy. This is to prevent
4419 	 * global policy lookups in the inbound path.
4420 	 *
4421 	 * If we insert before we set conn_policy_cached,
4422 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4423 	 * because global policy cound be non-empty. We normally call
4424 	 * ipsec_check_policy() for conn_policy_cached connections only if
4425 	 * ipc_in_enforce_policy is set. But in this case,
4426 	 * conn_policy_cached can get set anytime since we made the
4427 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4428 	 * called, which will make the above assumption false.  Thus, we
4429 	 * need to insert after we set conn_policy_cached.
4430 	 */
4431 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4432 		goto bad_addr;
4433 
4434 	if (fanout_insert) {
4435 		/*
4436 		 * The addresses have been verified. Time to insert in
4437 		 * the correct fanout list.
4438 		 */
4439 		error = ipcl_conn_insert(connp, protocol, src_addr,
4440 		    dst_addr, connp->conn_ports);
4441 	}
4442 
4443 	if (error == 0) {
4444 		connp->conn_fully_bound = B_TRUE;
4445 		/*
4446 		 * Our initial checks for MDT have passed; the IRE is not
4447 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4448 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4449 		 * ip_mdinfo_return(), which performs further checks
4450 		 * against them and upon success, returns the MDT info
4451 		 * mblk which we will attach to the bind acknowledgment.
4452 		 */
4453 		if (md_dst_ire != NULL) {
4454 			mblk_t *mdinfo_mp;
4455 
4456 			ASSERT(md_ill != NULL);
4457 			ASSERT(md_ill->ill_mdt_capab != NULL);
4458 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4459 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4460 				linkb(mp, mdinfo_mp);
4461 		}
4462 	}
4463 bad_addr:
4464 	if (ipsec_policy_set) {
4465 		ASSERT(policy_mp == mp->b_cont);
4466 		ASSERT(policy_mp != NULL);
4467 		freeb(policy_mp);
4468 		/*
4469 		 * As of now assume that nothing else accompanies
4470 		 * IPSEC_POLICY_SET.
4471 		 */
4472 		mp->b_cont = NULL;
4473 	}
4474 	if (src_ire != NULL)
4475 		IRE_REFRELE(src_ire);
4476 	if (dst_ire != NULL)
4477 		IRE_REFRELE(dst_ire);
4478 	if (sire != NULL)
4479 		IRE_REFRELE(sire);
4480 	if (md_dst_ire != NULL)
4481 		IRE_REFRELE(md_dst_ire);
4482 	return (error);
4483 }
4484 
4485 /*
4486  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4487  * Prefers dst_ire over src_ire.
4488  */
4489 static boolean_t
4490 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4491 {
4492 	mblk_t	*mp1;
4493 	ire_t *ret_ire = NULL;
4494 
4495 	mp1 = mp->b_cont;
4496 	ASSERT(mp1 != NULL);
4497 
4498 	if (ire != NULL) {
4499 		/*
4500 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4501 		 * appended mblk. Its <upper protocol>'s
4502 		 * job to make sure there is room.
4503 		 */
4504 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4505 			return (0);
4506 
4507 		mp1->b_datap->db_type = IRE_DB_TYPE;
4508 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4509 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4510 		ret_ire = (ire_t *)mp1->b_rptr;
4511 		/*
4512 		 * Pass the latest setting of the ip_path_mtu_discovery and
4513 		 * copy the ulp info if any.
4514 		 */
4515 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4516 		    IPH_DF : 0;
4517 		if (ulp_info != NULL) {
4518 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4519 			    sizeof (iulp_t));
4520 		}
4521 		ret_ire->ire_mp = mp1;
4522 	} else {
4523 		/*
4524 		 * No IRE was found. Remove IRE mblk.
4525 		 */
4526 		mp->b_cont = mp1->b_cont;
4527 		freeb(mp1);
4528 	}
4529 
4530 	return (1);
4531 }
4532 
4533 /*
4534  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4535  * the final piece where we don't.  Return a pointer to the first mblk in the
4536  * result, and update the pointer to the next mblk to chew on.  If anything
4537  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4538  * NULL pointer.
4539  */
4540 mblk_t *
4541 ip_carve_mp(mblk_t **mpp, ssize_t len)
4542 {
4543 	mblk_t	*mp0;
4544 	mblk_t	*mp1;
4545 	mblk_t	*mp2;
4546 
4547 	if (!len || !mpp || !(mp0 = *mpp))
4548 		return (NULL);
4549 	/* If we aren't going to consume the first mblk, we need a dup. */
4550 	if (mp0->b_wptr - mp0->b_rptr > len) {
4551 		mp1 = dupb(mp0);
4552 		if (mp1) {
4553 			/* Partition the data between the two mblks. */
4554 			mp1->b_wptr = mp1->b_rptr + len;
4555 			mp0->b_rptr = mp1->b_wptr;
4556 			/*
4557 			 * after adjustments if mblk not consumed is now
4558 			 * unaligned, try to align it. If this fails free
4559 			 * all messages and let upper layer recover.
4560 			 */
4561 			if (!OK_32PTR(mp0->b_rptr)) {
4562 				if (!pullupmsg(mp0, -1)) {
4563 					freemsg(mp0);
4564 					freemsg(mp1);
4565 					*mpp = NULL;
4566 					return (NULL);
4567 				}
4568 			}
4569 		}
4570 		return (mp1);
4571 	}
4572 	/* Eat through as many mblks as we need to get len bytes. */
4573 	len -= mp0->b_wptr - mp0->b_rptr;
4574 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4575 		if (mp2->b_wptr - mp2->b_rptr > len) {
4576 			/*
4577 			 * We won't consume the entire last mblk.  Like
4578 			 * above, dup and partition it.
4579 			 */
4580 			mp1->b_cont = dupb(mp2);
4581 			mp1 = mp1->b_cont;
4582 			if (!mp1) {
4583 				/*
4584 				 * Trouble.  Rather than go to a lot of
4585 				 * trouble to clean up, we free the messages.
4586 				 * This won't be any worse than losing it on
4587 				 * the wire.
4588 				 */
4589 				freemsg(mp0);
4590 				freemsg(mp2);
4591 				*mpp = NULL;
4592 				return (NULL);
4593 			}
4594 			mp1->b_wptr = mp1->b_rptr + len;
4595 			mp2->b_rptr = mp1->b_wptr;
4596 			/*
4597 			 * after adjustments if mblk not consumed is now
4598 			 * unaligned, try to align it. If this fails free
4599 			 * all messages and let upper layer recover.
4600 			 */
4601 			if (!OK_32PTR(mp2->b_rptr)) {
4602 				if (!pullupmsg(mp2, -1)) {
4603 					freemsg(mp0);
4604 					freemsg(mp2);
4605 					*mpp = NULL;
4606 					return (NULL);
4607 				}
4608 			}
4609 			*mpp = mp2;
4610 			return (mp0);
4611 		}
4612 		/* Decrement len by the amount we just got. */
4613 		len -= mp2->b_wptr - mp2->b_rptr;
4614 	}
4615 	/*
4616 	 * len should be reduced to zero now.  If not our caller has
4617 	 * screwed up.
4618 	 */
4619 	if (len) {
4620 		/* Shouldn't happen! */
4621 		freemsg(mp0);
4622 		*mpp = NULL;
4623 		return (NULL);
4624 	}
4625 	/*
4626 	 * We consumed up to exactly the end of an mblk.  Detach the part
4627 	 * we are returning from the rest of the chain.
4628 	 */
4629 	mp1->b_cont = NULL;
4630 	*mpp = mp2;
4631 	return (mp0);
4632 }
4633 
4634 /* The ill stream is being unplumbed. Called from ip_close */
4635 int
4636 ip_modclose(ill_t *ill)
4637 {
4638 
4639 	boolean_t success;
4640 	ipsq_t	*ipsq;
4641 	ipif_t	*ipif;
4642 	queue_t	*q = ill->ill_rq;
4643 
4644 	/*
4645 	 * Forcibly enter the ipsq after some delay. This is to take
4646 	 * care of the case when some ioctl does not complete because
4647 	 * we sent a control message to the driver and it did not
4648 	 * send us a reply. We want to be able to at least unplumb
4649 	 * and replumb rather than force the user to reboot the system.
4650 	 */
4651 	success = ipsq_enter(ill, B_FALSE);
4652 
4653 	/*
4654 	 * Open/close/push/pop is guaranteed to be single threaded
4655 	 * per stream by STREAMS. FS guarantees that all references
4656 	 * from top are gone before close is called. So there can't
4657 	 * be another close thread that has set CONDEMNED on this ill.
4658 	 * and cause ipsq_enter to return failure.
4659 	 */
4660 	ASSERT(success);
4661 	ipsq = ill->ill_phyint->phyint_ipsq;
4662 
4663 	/*
4664 	 * Mark it condemned. No new reference will be made to this ill.
4665 	 * Lookup functions will return an error. Threads that try to
4666 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4667 	 * that the refcnt will drop down to zero.
4668 	 */
4669 	mutex_enter(&ill->ill_lock);
4670 	ill->ill_state_flags |= ILL_CONDEMNED;
4671 	for (ipif = ill->ill_ipif; ipif != NULL;
4672 	    ipif = ipif->ipif_next) {
4673 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4674 	}
4675 	/*
4676 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4677 	 * returns  error if ILL_CONDEMNED is set
4678 	 */
4679 	cv_broadcast(&ill->ill_cv);
4680 	mutex_exit(&ill->ill_lock);
4681 
4682 	/*
4683 	 * Shut down fragmentation reassembly.
4684 	 * ill_frag_timer won't start a timer again.
4685 	 * Now cancel any existing timer
4686 	 */
4687 	(void) untimeout(ill->ill_frag_timer_id);
4688 	(void) ill_frag_timeout(ill, 0);
4689 
4690 	/*
4691 	 * If MOVE was in progress, clear the
4692 	 * move_in_progress fields also.
4693 	 */
4694 	if (ill->ill_move_in_progress) {
4695 		ILL_CLEAR_MOVE(ill);
4696 	}
4697 
4698 	/*
4699 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4700 	 * this ill. Then wait for the refcnts to drop to zero.
4701 	 * ill_is_quiescent checks whether the ill is really quiescent.
4702 	 * Then make sure that threads that are waiting to enter the
4703 	 * ipsq have seen the error returned by ipsq_enter and have
4704 	 * gone away. Then we call ill_delete_tail which does the
4705 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4706 	 */
4707 	ill_delete(ill);
4708 	mutex_enter(&ill->ill_lock);
4709 	while (!ill_is_quiescent(ill))
4710 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4711 	while (ill->ill_waiters)
4712 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4713 
4714 	mutex_exit(&ill->ill_lock);
4715 
4716 	/* qprocsoff is called in ill_delete_tail */
4717 	ill_delete_tail(ill);
4718 
4719 	/*
4720 	 * Walk through all upper (conn) streams and qenable
4721 	 * those that have queued data.
4722 	 * close synchronization needs this to
4723 	 * be done to ensure that all upper layers blocked
4724 	 * due to flow control to the closing device
4725 	 * get unblocked.
4726 	 */
4727 	ip1dbg(("ip_wsrv: walking\n"));
4728 	conn_walk_drain();
4729 
4730 	mutex_enter(&ip_mi_lock);
4731 	mi_close_unlink(&ip_g_head, (IDP)ill);
4732 	mutex_exit(&ip_mi_lock);
4733 
4734 	/*
4735 	 * credp could be null if the open didn't succeed and ip_modopen
4736 	 * itself calls ip_close.
4737 	 */
4738 	if (ill->ill_credp != NULL)
4739 		crfree(ill->ill_credp);
4740 
4741 	mi_close_free((IDP)ill);
4742 	q->q_ptr = WR(q)->q_ptr = NULL;
4743 
4744 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4745 
4746 	return (0);
4747 }
4748 
4749 /*
4750  * This is called as part of close() for both IP and UDP
4751  * in order to quiesce the conn.
4752  */
4753 void
4754 ip_quiesce_conn(conn_t *connp)
4755 {
4756 	boolean_t	drain_cleanup_reqd = B_FALSE;
4757 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4758 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4759 
4760 	ASSERT(!IPCL_IS_TCP(connp));
4761 
4762 	/*
4763 	 * Mark the conn as closing, and this conn must not be
4764 	 * inserted in future into any list. Eg. conn_drain_insert(),
4765 	 * won't insert this conn into the conn_drain_list.
4766 	 * Similarly ill_pending_mp_add() will not add any mp to
4767 	 * the pending mp list, after this conn has started closing.
4768 	 *
4769 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4770 	 * cannot get set henceforth.
4771 	 */
4772 	mutex_enter(&connp->conn_lock);
4773 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4774 	connp->conn_state_flags |= CONN_CLOSING;
4775 	if (connp->conn_idl != NULL)
4776 		drain_cleanup_reqd = B_TRUE;
4777 	if (connp->conn_oper_pending_ill != NULL)
4778 		conn_ioctl_cleanup_reqd = B_TRUE;
4779 	if (connp->conn_ilg_inuse != 0)
4780 		ilg_cleanup_reqd = B_TRUE;
4781 	mutex_exit(&connp->conn_lock);
4782 
4783 	if (IPCL_IS_UDP(connp))
4784 		udp_quiesce_conn(connp);
4785 
4786 	if (conn_ioctl_cleanup_reqd)
4787 		conn_ioctl_cleanup(connp);
4788 
4789 	/*
4790 	 * Remove this conn from any fanout list it is on.
4791 	 * and then wait for any threads currently operating
4792 	 * on this endpoint to finish
4793 	 */
4794 	ipcl_hash_remove(connp);
4795 
4796 	/*
4797 	 * Remove this conn from the drain list, and do
4798 	 * any other cleanup that may be required.
4799 	 * (Only non-tcp streams may have a non-null conn_idl.
4800 	 * TCP streams are never flow controlled, and
4801 	 * conn_idl will be null)
4802 	 */
4803 	if (drain_cleanup_reqd)
4804 		conn_drain_tail(connp, B_TRUE);
4805 
4806 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4807 		(void) ip_mrouter_done(NULL);
4808 
4809 	if (ilg_cleanup_reqd)
4810 		ilg_delete_all(connp);
4811 
4812 	conn_delete_ire(connp, NULL);
4813 
4814 	/*
4815 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4816 	 * callers from write side can't be there now because close
4817 	 * is in progress. The only other caller is ipcl_walk
4818 	 * which checks for the condemned flag.
4819 	 */
4820 	mutex_enter(&connp->conn_lock);
4821 	connp->conn_state_flags |= CONN_CONDEMNED;
4822 	while (connp->conn_ref != 1)
4823 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4824 	connp->conn_state_flags |= CONN_QUIESCED;
4825 	mutex_exit(&connp->conn_lock);
4826 }
4827 
4828 /* ARGSUSED */
4829 int
4830 ip_close(queue_t *q, int flags)
4831 {
4832 	conn_t		*connp;
4833 
4834 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4835 
4836 	/*
4837 	 * Call the appropriate delete routine depending on whether this is
4838 	 * a module or device.
4839 	 */
4840 	if (WR(q)->q_next != NULL) {
4841 		/* This is a module close */
4842 		return (ip_modclose((ill_t *)q->q_ptr));
4843 	}
4844 
4845 	connp = q->q_ptr;
4846 	ip_quiesce_conn(connp);
4847 
4848 	qprocsoff(q);
4849 
4850 	/*
4851 	 * Now we are truly single threaded on this stream, and can
4852 	 * delete the things hanging off the connp, and finally the connp.
4853 	 * We removed this connp from the fanout list, it cannot be
4854 	 * accessed thru the fanouts, and we already waited for the
4855 	 * conn_ref to drop to 0. We are already in close, so
4856 	 * there cannot be any other thread from the top. qprocsoff
4857 	 * has completed, and service has completed or won't run in
4858 	 * future.
4859 	 */
4860 	ASSERT(connp->conn_ref == 1);
4861 
4862 	/*
4863 	 * A conn which was previously marked as IPCL_UDP cannot
4864 	 * retain the flag because it would have been cleared by
4865 	 * udp_close().
4866 	 */
4867 	ASSERT(!IPCL_IS_UDP(connp));
4868 
4869 	if (connp->conn_latch != NULL) {
4870 		IPLATCH_REFRELE(connp->conn_latch);
4871 		connp->conn_latch = NULL;
4872 	}
4873 	if (connp->conn_policy != NULL) {
4874 		IPPH_REFRELE(connp->conn_policy);
4875 		connp->conn_policy = NULL;
4876 	}
4877 	if (connp->conn_ipsec_opt_mp != NULL) {
4878 		freemsg(connp->conn_ipsec_opt_mp);
4879 		connp->conn_ipsec_opt_mp = NULL;
4880 	}
4881 	if (connp->conn_cred != NULL) {
4882 		crfree(connp->conn_cred);
4883 		connp->conn_cred = NULL;
4884 	}
4885 
4886 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4887 
4888 	connp->conn_ref--;
4889 	ipcl_conn_destroy(connp);
4890 
4891 	q->q_ptr = WR(q)->q_ptr = NULL;
4892 	return (0);
4893 }
4894 
4895 int
4896 ip_snmpmod_close(queue_t *q)
4897 {
4898 	conn_t *connp = Q_TO_CONN(q);
4899 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4900 
4901 	qprocsoff(q);
4902 
4903 	if (connp->conn_flags & IPCL_UDPMOD)
4904 		udp_close_free(connp);
4905 
4906 	if (connp->conn_cred != NULL) {
4907 		crfree(connp->conn_cred);
4908 		connp->conn_cred = NULL;
4909 	}
4910 	CONN_DEC_REF(connp);
4911 	q->q_ptr = WR(q)->q_ptr = NULL;
4912 	return (0);
4913 }
4914 
4915 /*
4916  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
4917  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
4918  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
4919  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
4920  * queues as we never enqueue messages there and we don't handle any ioctls.
4921  * Everything else is freed.
4922  */
4923 void
4924 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
4925 {
4926 	conn_t	*connp = q->q_ptr;
4927 	pfi_t	setfn;
4928 	pfi_t	getfn;
4929 
4930 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4931 
4932 	switch (DB_TYPE(mp)) {
4933 	case M_PROTO:
4934 	case M_PCPROTO:
4935 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
4936 		    ((((union T_primitives *)mp->b_rptr)->type ==
4937 			T_SVR4_OPTMGMT_REQ) ||
4938 		    (((union T_primitives *)mp->b_rptr)->type ==
4939 			T_OPTMGMT_REQ))) {
4940 			/*
4941 			 * This is the only TPI primitive supported. Its
4942 			 * handling does not require tcp_t, but it does require
4943 			 * conn_t to check permissions.
4944 			 */
4945 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
4946 
4947 			if (connp->conn_flags & IPCL_TCPMOD) {
4948 				setfn = tcp_snmp_set;
4949 				getfn = tcp_snmp_get;
4950 			} else {
4951 				setfn = udp_snmp_set;
4952 				getfn = udp_snmp_get;
4953 			}
4954 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
4955 				freemsg(mp);
4956 				return;
4957 			}
4958 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
4959 		    != NULL)
4960 			qreply(q, mp);
4961 		break;
4962 	case M_FLUSH:
4963 	case M_IOCTL:
4964 		putnext(q, mp);
4965 		break;
4966 	default:
4967 		freemsg(mp);
4968 		break;
4969 	}
4970 }
4971 
4972 /* Return the IP checksum for the IP header at "iph". */
4973 uint16_t
4974 ip_csum_hdr(ipha_t *ipha)
4975 {
4976 	uint16_t	*uph;
4977 	uint32_t	sum;
4978 	int		opt_len;
4979 
4980 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4981 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4982 	uph = (uint16_t *)ipha;
4983 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4984 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4985 	if (opt_len > 0) {
4986 		do {
4987 			sum += uph[10];
4988 			sum += uph[11];
4989 			uph += 2;
4990 		} while (--opt_len);
4991 	}
4992 	sum = (sum & 0xFFFF) + (sum >> 16);
4993 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4994 	if (sum == 0xffff)
4995 		sum = 0;
4996 	return ((uint16_t)sum);
4997 }
4998 
4999 void
5000 ip_ddi_destroy(void)
5001 {
5002 	tcp_ddi_destroy();
5003 	sctp_ddi_destroy();
5004 	ipsec_loader_destroy();
5005 	ipsec_policy_destroy();
5006 	ipsec_kstat_destroy();
5007 	nd_free(&ip_g_nd);
5008 	mutex_destroy(&igmp_timer_lock);
5009 	mutex_destroy(&mld_timer_lock);
5010 	mutex_destroy(&igmp_slowtimeout_lock);
5011 	mutex_destroy(&mld_slowtimeout_lock);
5012 	mutex_destroy(&ip_mi_lock);
5013 	mutex_destroy(&rts_clients.connf_lock);
5014 	ip_ire_fini();
5015 	ip6_asp_free();
5016 	conn_drain_fini();
5017 	ipcl_destroy();
5018 	inet_minor_destroy(ip_minor_arena);
5019 	icmp_kstat_fini();
5020 	ip_kstat_fini();
5021 	rw_destroy(&ipsec_capab_ills_lock);
5022 	rw_destroy(&ill_g_usesrc_lock);
5023 	ip_drop_unregister(&ip_dropper);
5024 }
5025 
5026 
5027 void
5028 ip_ddi_init(void)
5029 {
5030 	TCP6_MAJ = ddi_name_to_major(TCP6);
5031 	TCP_MAJ	= ddi_name_to_major(TCP);
5032 	SCTP_MAJ = ddi_name_to_major(SCTP);
5033 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5034 
5035 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5036 
5037 	/* IP's IPsec code calls the packet dropper */
5038 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5039 
5040 	if (!ip_g_nd) {
5041 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5042 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5043 			nd_free(&ip_g_nd);
5044 		}
5045 	}
5046 
5047 	ipsec_loader_init();
5048 	ipsec_policy_init();
5049 	ipsec_kstat_init();
5050 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5051 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5052 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5053 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5054 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5055 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5056 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5057 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5058 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5059 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5060 
5061 	/*
5062 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5063 	 * initial devices: ip, ip6, tcp, tcp6.
5064 	 */
5065 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5066 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5067 		cmn_err(CE_PANIC,
5068 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5069 	}
5070 
5071 	ipcl_init();
5072 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5073 	ip_ire_init();
5074 	ip6_asp_init();
5075 	ipif_init();
5076 	conn_drain_init();
5077 	tcp_ddi_init();
5078 	sctp_ddi_init();
5079 
5080 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5081 
5082 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5083 		"net", KSTAT_TYPE_NAMED,
5084 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5085 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5086 		ip_kstat->ks_data = &ip_statistics;
5087 		kstat_install(ip_kstat);
5088 	}
5089 	ip_kstat_init();
5090 	ip6_kstat_init();
5091 	icmp_kstat_init();
5092 
5093 	ipsec_loader_start();
5094 }
5095 
5096 /*
5097  * Allocate and initialize a DLPI template of the specified length.  (May be
5098  * called as writer.)
5099  */
5100 mblk_t *
5101 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5102 {
5103 	mblk_t	*mp;
5104 
5105 	mp = allocb(len, BPRI_MED);
5106 	if (!mp)
5107 		return (NULL);
5108 
5109 	/*
5110 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5111 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5112 	 * that other DLPI are M_PROTO.
5113 	 */
5114 	if (prim == DL_INFO_REQ) {
5115 		mp->b_datap->db_type = M_PCPROTO;
5116 	} else {
5117 		mp->b_datap->db_type = M_PROTO;
5118 	}
5119 
5120 	mp->b_wptr = mp->b_rptr + len;
5121 	bzero(mp->b_rptr, len);
5122 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5123 	return (mp);
5124 }
5125 
5126 const char *
5127 dlpi_prim_str(int prim)
5128 {
5129 	switch (prim) {
5130 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5131 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5132 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5133 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5134 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5135 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5136 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5137 	case DL_OK_ACK:		return ("DL_OK_ACK");
5138 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5139 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5140 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5141 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5142 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5143 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5144 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5145 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5146 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5147 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5148 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5149 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5150 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5151 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5152 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5153 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5154 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5155 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5156 	default:		return ("<unknown primitive>");
5157 	}
5158 }
5159 
5160 const char *
5161 dlpi_err_str(int err)
5162 {
5163 	switch (err) {
5164 	case DL_ACCESS:		return ("DL_ACCESS");
5165 	case DL_BADADDR:	return ("DL_BADADDR");
5166 	case DL_BADCORR:	return ("DL_BADCORR");
5167 	case DL_BADDATA:	return ("DL_BADDATA");
5168 	case DL_BADPPA:		return ("DL_BADPPA");
5169 	case DL_BADPRIM:	return ("DL_BADPRIM");
5170 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5171 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5172 	case DL_BADSAP:		return ("DL_BADSAP");
5173 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5174 	case DL_BOUND:		return ("DL_BOUND");
5175 	case DL_INITFAILED:	return ("DL_INITFAILED");
5176 	case DL_NOADDR:		return ("DL_NOADDR");
5177 	case DL_NOTINIT:	return ("DL_NOTINIT");
5178 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5179 	case DL_SYSERR:		return ("DL_SYSERR");
5180 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5181 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5182 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5183 	case DL_TOOMANY:	return ("DL_TOOMANY");
5184 	case DL_NOTENAB:	return ("DL_NOTENAB");
5185 	case DL_BUSY:		return ("DL_BUSY");
5186 	case DL_NOAUTO:		return ("DL_NOAUTO");
5187 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5188 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5189 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5190 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5191 	case DL_PENDING:	return ("DL_PENDING");
5192 	default:		return ("<unknown error>");
5193 	}
5194 }
5195 
5196 /*
5197  * Debug formatting routine.  Returns a character string representation of the
5198  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5199  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5200  */
5201 char *
5202 ip_dot_addr(ipaddr_t addr, char *buf)
5203 {
5204 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5205 }
5206 
5207 /*
5208  * Debug formatting routine.  Returns a character string representation of the
5209  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5210  * as a pointer.  The "xxx" parts including left zero padding so the final
5211  * string will fit easily in tables.  It would be nice to take a padding
5212  * length argument instead.
5213  */
5214 static char *
5215 ip_dot_saddr(uchar_t *addr, char *buf)
5216 {
5217 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5218 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5219 	return (buf);
5220 }
5221 
5222 /*
5223  * Send an ICMP error after patching up the packet appropriately.  Returns
5224  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5225  */
5226 static boolean_t
5227 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5228     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5229 {
5230 	ipha_t *ipha;
5231 	mblk_t *first_mp;
5232 	boolean_t secure;
5233 	unsigned char db_type;
5234 
5235 	first_mp = mp;
5236 	if (mctl_present) {
5237 		mp = mp->b_cont;
5238 		secure = ipsec_in_is_secure(first_mp);
5239 		ASSERT(mp != NULL);
5240 	} else {
5241 		/*
5242 		 * If this is an ICMP error being reported - which goes
5243 		 * up as M_CTLs, we need to convert them to M_DATA till
5244 		 * we finish checking with global policy because
5245 		 * ipsec_check_global_policy() assumes M_DATA as clear
5246 		 * and M_CTL as secure.
5247 		 */
5248 		db_type = DB_TYPE(mp);
5249 		DB_TYPE(mp) = M_DATA;
5250 		secure = B_FALSE;
5251 	}
5252 	/*
5253 	 * We are generating an icmp error for some inbound packet.
5254 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5255 	 * Before we generate an error, check with global policy
5256 	 * to see whether this is allowed to enter the system. As
5257 	 * there is no "conn", we are checking with global policy.
5258 	 */
5259 	ipha = (ipha_t *)mp->b_rptr;
5260 	if (secure || ipsec_inbound_v4_policy_present) {
5261 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5262 		    ipha, NULL, mctl_present);
5263 		if (first_mp == NULL)
5264 			return (B_FALSE);
5265 	}
5266 
5267 	if (!mctl_present)
5268 		DB_TYPE(mp) = db_type;
5269 
5270 	if (flags & IP_FF_SEND_ICMP) {
5271 		if (flags & IP_FF_HDR_COMPLETE) {
5272 			if (ip_hdr_complete(ipha, zoneid)) {
5273 				freemsg(first_mp);
5274 				return (B_TRUE);
5275 			}
5276 		}
5277 		if (flags & IP_FF_CKSUM) {
5278 			/*
5279 			 * Have to correct checksum since
5280 			 * the packet might have been
5281 			 * fragmented and the reassembly code in ip_rput
5282 			 * does not restore the IP checksum.
5283 			 */
5284 			ipha->ipha_hdr_checksum = 0;
5285 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5286 		}
5287 		switch (icmp_type) {
5288 		case ICMP_DEST_UNREACHABLE:
5289 			icmp_unreachable(WR(q), first_mp, icmp_code);
5290 			break;
5291 		default:
5292 			freemsg(first_mp);
5293 			break;
5294 		}
5295 	} else {
5296 		freemsg(first_mp);
5297 		return (B_FALSE);
5298 	}
5299 
5300 	return (B_TRUE);
5301 }
5302 
5303 #ifdef DEBUG
5304 /*
5305  * Copy the header into the IPSEC_IN message.
5306  */
5307 static void
5308 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5309 {
5310 	mblk_t *data_mp = ipsec_mp->b_cont;
5311 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5312 	ipha_t *ipha;
5313 
5314 	if (ii->ipsec_in_type != IPSEC_IN)
5315 		return;
5316 	ASSERT(data_mp != NULL);
5317 
5318 	ipha = (ipha_t *)data_mp->b_rptr;
5319 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5320 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5321 	    sizeof (ipha_t) : sizeof (ip6_t));
5322 }
5323 #else
5324 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5325 #endif	/* DEBUG */
5326 
5327 /*
5328  * Used to send an ICMP error message when a packet is received for
5329  * a protocol that is not supported. The mblk passed as argument
5330  * is consumed by this function.
5331  */
5332 void
5333 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5334 {
5335 	mblk_t *mp;
5336 	ipha_t *ipha;
5337 	ill_t *ill;
5338 	ipsec_in_t *ii;
5339 
5340 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5341 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5342 
5343 	mp = ipsec_mp->b_cont;
5344 	ipsec_mp->b_cont = NULL;
5345 	ipha = (ipha_t *)mp->b_rptr;
5346 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5347 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5348 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5349 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5350 		}
5351 	} else {
5352 		/* Get ill from index in ipsec_in_t. */
5353 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5354 		    B_TRUE, NULL, NULL, NULL, NULL);
5355 		if (ill != NULL) {
5356 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5357 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5358 			    0, B_FALSE, zoneid)) {
5359 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5360 			}
5361 
5362 			ill_refrele(ill);
5363 		} else { /* re-link for the freemsg() below. */
5364 			ipsec_mp->b_cont = mp;
5365 		}
5366 	}
5367 
5368 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5369 	freemsg(ipsec_mp);
5370 }
5371 
5372 /*
5373  * See if the inbound datagram has had IPsec processing applied to it.
5374  */
5375 boolean_t
5376 ipsec_in_is_secure(mblk_t *ipsec_mp)
5377 {
5378 	ipsec_in_t *ii;
5379 
5380 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5381 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5382 
5383 	if (ii->ipsec_in_loopback) {
5384 		return (ii->ipsec_in_secure);
5385 	} else {
5386 		return (ii->ipsec_in_ah_sa != NULL ||
5387 		    ii->ipsec_in_esp_sa != NULL ||
5388 		    ii->ipsec_in_decaps);
5389 	}
5390 }
5391 
5392 /*
5393  * Handle protocols with which IP is less intimate.  There
5394  * can be more than one stream bound to a particular
5395  * protocol.  When this is the case, normally each one gets a copy
5396  * of any incoming packets.
5397  *
5398  * IPSEC NOTE :
5399  *
5400  * Don't allow a secure packet going up a non-secure connection.
5401  * We don't allow this because
5402  *
5403  * 1) Reply might go out in clear which will be dropped at
5404  *    the sending side.
5405  * 2) If the reply goes out in clear it will give the
5406  *    adversary enough information for getting the key in
5407  *    most of the cases.
5408  *
5409  * Moreover getting a secure packet when we expect clear
5410  * implies that SA's were added without checking for
5411  * policy on both ends. This should not happen once ISAKMP
5412  * is used to negotiate SAs as SAs will be added only after
5413  * verifying the policy.
5414  *
5415  * NOTE : If the packet was tunneled and not multicast we only send
5416  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5417  * back to delivering packets to AF_INET6 raw sockets.
5418  *
5419  * IPQoS Notes:
5420  * Once we have determined the client, invoke IPPF processing.
5421  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5422  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5423  * ip_policy will be false.
5424  *
5425  * Zones notes:
5426  * Currently only applications in the global zone can create raw sockets for
5427  * protocols other than ICMP. So unlike the broadcast / multicast case of
5428  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5429  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5430  */
5431 static void
5432 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5433     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5434     zoneid_t zoneid)
5435 {
5436 	queue_t	*rq;
5437 	mblk_t	*mp1, *first_mp1;
5438 	uint_t	protocol = ipha->ipha_protocol;
5439 	ipaddr_t dst;
5440 	boolean_t one_only;
5441 	mblk_t *first_mp = mp;
5442 	boolean_t secure;
5443 	uint32_t ill_index;
5444 	conn_t	*connp, *first_connp, *next_connp;
5445 	connf_t	*connfp;
5446 
5447 	if (mctl_present) {
5448 		mp = first_mp->b_cont;
5449 		secure = ipsec_in_is_secure(first_mp);
5450 		ASSERT(mp != NULL);
5451 	} else {
5452 		secure = B_FALSE;
5453 	}
5454 	dst = ipha->ipha_dst;
5455 	/*
5456 	 * If the packet was tunneled and not multicast we only send to it
5457 	 * the first match.
5458 	 */
5459 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5460 	    !CLASSD(dst));
5461 
5462 	connfp = &ipcl_proto_fanout[protocol];
5463 	mutex_enter(&connfp->connf_lock);
5464 	connp = connfp->connf_head;
5465 	for (connp = connfp->connf_head; connp != NULL;
5466 		connp = connp->conn_next) {
5467 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5468 			break;
5469 	}
5470 
5471 	if (connp == NULL || connp->conn_upq == NULL) {
5472 		/*
5473 		 * No one bound to these addresses.  Is
5474 		 * there a client that wants all
5475 		 * unclaimed datagrams?
5476 		 */
5477 		mutex_exit(&connfp->connf_lock);
5478 		/*
5479 		 * Check for IPPROTO_ENCAP...
5480 		 */
5481 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5482 			/*
5483 			 * XXX If an IPsec mblk is here on a multicast
5484 			 * tunnel (using ip_mroute stuff), what should
5485 			 * I do?
5486 			 *
5487 			 * For now, just free the IPsec mblk before
5488 			 * passing it up to the multicast routing
5489 			 * stuff.
5490 			 *
5491 			 * BTW,  If I match a configured IP-in-IP
5492 			 * tunnel, ip_mroute_decap will never be
5493 			 * called.
5494 			 */
5495 			if (mp != first_mp)
5496 				freeb(first_mp);
5497 			ip_mroute_decap(q, mp);
5498 		} else {
5499 			/*
5500 			 * Otherwise send an ICMP protocol unreachable.
5501 			 */
5502 			if (ip_fanout_send_icmp(q, first_mp, flags,
5503 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5504 			    mctl_present, zoneid)) {
5505 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5506 			}
5507 		}
5508 		return;
5509 	}
5510 	CONN_INC_REF(connp);
5511 	first_connp = connp;
5512 
5513 	/*
5514 	 * Only send message to one tunnel driver by immediately
5515 	 * terminating the loop.
5516 	 */
5517 	connp = one_only ? NULL : connp->conn_next;
5518 
5519 	for (;;) {
5520 		while (connp != NULL) {
5521 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5522 			    flags, zoneid))
5523 				break;
5524 			connp = connp->conn_next;
5525 		}
5526 
5527 		/*
5528 		 * Copy the packet.
5529 		 */
5530 		if (connp == NULL || connp->conn_upq == NULL ||
5531 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5532 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5533 			/*
5534 			 * No more interested clients or memory
5535 			 * allocation failed
5536 			 */
5537 			connp = first_connp;
5538 			break;
5539 		}
5540 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5541 		CONN_INC_REF(connp);
5542 		mutex_exit(&connfp->connf_lock);
5543 		rq = connp->conn_rq;
5544 		if (!canputnext(rq)) {
5545 			if (flags & IP_FF_RAWIP) {
5546 				BUMP_MIB(&ip_mib, rawipInOverflows);
5547 			} else {
5548 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5549 			}
5550 
5551 			freemsg(first_mp1);
5552 		} else {
5553 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5554 				first_mp1 = ipsec_check_inbound_policy
5555 				    (first_mp1, connp, ipha, NULL,
5556 				    mctl_present);
5557 			}
5558 			if (first_mp1 != NULL) {
5559 				/*
5560 				 * ip_fanout_proto also gets called from
5561 				 * icmp_inbound_error_fanout, in which case
5562 				 * the msg type is M_CTL.  Don't add info
5563 				 * in this case for the time being. In future
5564 				 * when there is a need for knowing the
5565 				 * inbound iface index for ICMP error msgs,
5566 				 * then this can be changed.
5567 				 */
5568 				if ((connp->conn_recvif != 0) &&
5569 				    (mp->b_datap->db_type != M_CTL)) {
5570 					/*
5571 					 * the actual data will be
5572 					 * contained in b_cont upon
5573 					 * successful return of the
5574 					 * following call else
5575 					 * original mblk is returned
5576 					 */
5577 					ASSERT(recv_ill != NULL);
5578 					mp1 = ip_add_info(mp1, recv_ill,
5579 						IPF_RECVIF);
5580 				}
5581 				BUMP_MIB(&ip_mib, ipInDelivers);
5582 				if (mctl_present)
5583 					freeb(first_mp1);
5584 				putnext(rq, mp1);
5585 			}
5586 		}
5587 		mutex_enter(&connfp->connf_lock);
5588 		/* Follow the next pointer before releasing the conn. */
5589 		next_connp = connp->conn_next;
5590 		CONN_DEC_REF(connp);
5591 		connp = next_connp;
5592 	}
5593 
5594 	/* Last one.  Send it upstream. */
5595 	mutex_exit(&connfp->connf_lock);
5596 
5597 	/*
5598 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5599 	 * will be set to false.
5600 	 */
5601 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5602 		ill_index = ill->ill_phyint->phyint_ifindex;
5603 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5604 		if (mp == NULL) {
5605 			CONN_DEC_REF(connp);
5606 			if (mctl_present) {
5607 				freeb(first_mp);
5608 			}
5609 			return;
5610 		}
5611 	}
5612 
5613 	rq = connp->conn_rq;
5614 	if (!canputnext(rq)) {
5615 		if (flags & IP_FF_RAWIP) {
5616 			BUMP_MIB(&ip_mib, rawipInOverflows);
5617 		} else {
5618 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5619 		}
5620 
5621 		freemsg(first_mp);
5622 	} else {
5623 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5624 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5625 			    ipha, NULL, mctl_present);
5626 		}
5627 		if (first_mp != NULL) {
5628 			/*
5629 			 * ip_fanout_proto also gets called
5630 			 * from icmp_inbound_error_fanout, in
5631 			 * which case the msg type is M_CTL.
5632 			 * Don't add info in this case for time
5633 			 * being. In future when there is a
5634 			 * need for knowing the inbound iface
5635 			 * index for ICMP error msgs, then this
5636 			 * can be changed
5637 			 */
5638 			if ((connp->conn_recvif != 0) &&
5639 			    (mp->b_datap->db_type != M_CTL)) {
5640 				/*
5641 				 * the actual data will be contained in
5642 				 * b_cont upon successful return
5643 				 * of the following call else original
5644 				 * mblk is returned
5645 				 */
5646 				ASSERT(recv_ill != NULL);
5647 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5648 			}
5649 			BUMP_MIB(&ip_mib, ipInDelivers);
5650 			putnext(rq, mp);
5651 			if (mctl_present)
5652 				freeb(first_mp);
5653 		}
5654 	}
5655 	CONN_DEC_REF(connp);
5656 }
5657 
5658 /*
5659  * Fanout for TCP packets
5660  * The caller puts <fport, lport> in the ports parameter.
5661  *
5662  * IPQoS Notes
5663  * Before sending it to the client, invoke IPPF processing.
5664  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5665  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5666  * ip_policy is false.
5667  */
5668 static void
5669 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5670     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5671 {
5672 	mblk_t  *first_mp;
5673 	boolean_t secure;
5674 	uint32_t ill_index;
5675 	int	ip_hdr_len;
5676 	tcph_t	*tcph;
5677 	boolean_t syn_present = B_FALSE;
5678 	conn_t	*connp;
5679 
5680 	first_mp = mp;
5681 	if (mctl_present) {
5682 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5683 		mp = first_mp->b_cont;
5684 		secure = ipsec_in_is_secure(first_mp);
5685 		ASSERT(mp != NULL);
5686 	} else {
5687 		secure = B_FALSE;
5688 	}
5689 
5690 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5691 
5692 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5693 	    NULL) {
5694 		/*
5695 		 * No connected connection or listener. Send a
5696 		 * TH_RST via tcp_xmit_listeners_reset.
5697 		 */
5698 
5699 		/* Initiate IPPf processing, if needed. */
5700 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5701 			uint32_t ill_index;
5702 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5703 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5704 			if (first_mp == NULL)
5705 				return;
5706 		}
5707 		BUMP_MIB(&ip_mib, ipInDelivers);
5708 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5709 		return;
5710 	}
5711 
5712 	/*
5713 	 * Allocate the SYN for the TCP connection here itself
5714 	 */
5715 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5716 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5717 		if (IPCL_IS_TCP(connp)) {
5718 			squeue_t *sqp;
5719 
5720 			/*
5721 			 * For fused tcp loopback, assign the eager's
5722 			 * squeue to be that of the active connect's.
5723 			 * Note that we don't check for IP_FF_LOOPBACK
5724 			 * here since this routine gets called only
5725 			 * for loopback (unlike the IPv6 counterpart).
5726 			 */
5727 			if (do_tcp_fusion &&
5728 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5729 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy) {
5730 				ASSERT(Q_TO_CONN(q) != NULL);
5731 				sqp = Q_TO_CONN(q)->conn_sqp;
5732 			} else {
5733 				sqp = IP_SQUEUE_GET(lbolt);
5734 			}
5735 
5736 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5737 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
5738 			syn_present = B_TRUE;
5739 		}
5740 	}
5741 
5742 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5743 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5744 		if ((flags & TH_RST) || (flags & TH_URG)) {
5745 			CONN_DEC_REF(connp);
5746 			freemsg(first_mp);
5747 			return;
5748 		}
5749 		if (flags & TH_ACK) {
5750 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5751 			CONN_DEC_REF(connp);
5752 			return;
5753 		}
5754 
5755 		CONN_DEC_REF(connp);
5756 		freemsg(first_mp);
5757 		return;
5758 	}
5759 
5760 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5761 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5762 		    NULL, mctl_present);
5763 		if (first_mp == NULL) {
5764 			CONN_DEC_REF(connp);
5765 			return;
5766 		}
5767 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5768 			ASSERT(syn_present);
5769 			if (mctl_present) {
5770 				ASSERT(first_mp != mp);
5771 				first_mp->b_datap->db_struioflag |=
5772 				    STRUIO_POLICY;
5773 			} else {
5774 				ASSERT(first_mp == mp);
5775 				mp->b_datap->db_struioflag &=
5776 				    ~STRUIO_EAGER;
5777 				mp->b_datap->db_struioflag |=
5778 				    STRUIO_POLICY;
5779 			}
5780 		} else {
5781 			/*
5782 			 * Discard first_mp early since we're dealing with a
5783 			 * fully-connected conn_t and tcp doesn't do policy in
5784 			 * this case.
5785 			 */
5786 			if (mctl_present) {
5787 				freeb(first_mp);
5788 				mctl_present = B_FALSE;
5789 			}
5790 			first_mp = mp;
5791 		}
5792 	}
5793 
5794 	/*
5795 	 * Initiate policy processing here if needed. If we get here from
5796 	 * icmp_inbound_error_fanout, ip_policy is false.
5797 	 */
5798 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5799 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5800 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5801 		if (mp == NULL) {
5802 			CONN_DEC_REF(connp);
5803 			if (mctl_present)
5804 				freeb(first_mp);
5805 			return;
5806 		} else if (mctl_present) {
5807 			ASSERT(first_mp != mp);
5808 			first_mp->b_cont = mp;
5809 		} else {
5810 			first_mp = mp;
5811 		}
5812 	}
5813 
5814 
5815 
5816 	/* Handle IPv6 socket options. */
5817 	if (!syn_present &&
5818 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5819 		/* Add header */
5820 		ASSERT(recv_ill != NULL);
5821 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5822 		if (mp == NULL) {
5823 			CONN_DEC_REF(connp);
5824 			if (mctl_present)
5825 				freeb(first_mp);
5826 			return;
5827 		} else if (mctl_present) {
5828 			/*
5829 			 * ip_add_info might return a new mp.
5830 			 */
5831 			ASSERT(first_mp != mp);
5832 			first_mp->b_cont = mp;
5833 		} else {
5834 			first_mp = mp;
5835 		}
5836 	}
5837 
5838 	BUMP_MIB(&ip_mib, ipInDelivers);
5839 	if (IPCL_IS_TCP(connp)) {
5840 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5841 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5842 	} else {
5843 		putnext(connp->conn_rq, first_mp);
5844 		CONN_DEC_REF(connp);
5845 	}
5846 }
5847 
5848 /*
5849  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5850  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5851  * Caller is responsible for dropping references to the conn, and freeing
5852  * first_mp.
5853  *
5854  * IPQoS Notes
5855  * Before sending it to the client, invoke IPPF processing. Policy processing
5856  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5857  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5858  * ip_wput_local, ip_policy is false.
5859  */
5860 static void
5861 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5862     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5863     boolean_t ip_policy)
5864 {
5865 	boolean_t	mctl_present = (first_mp != NULL);
5866 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5867 	uint32_t	ill_index;
5868 
5869 	if (mctl_present)
5870 		first_mp->b_cont = mp;
5871 	else
5872 		first_mp = mp;
5873 
5874 	if (CONN_UDP_FLOWCTLD(connp)) {
5875 		BUMP_MIB(&ip_mib, udpInOverflows);
5876 		freemsg(first_mp);
5877 		return;
5878 	}
5879 
5880 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5881 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5882 		    NULL, mctl_present);
5883 		if (first_mp == NULL)
5884 			return;	/* Freed by ipsec_check_inbound_policy(). */
5885 	}
5886 	if (mctl_present)
5887 		freeb(first_mp);
5888 
5889 	if (connp->conn_recvif)
5890 		in_flags = IPF_RECVIF;
5891 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5892 		in_flags |= IPF_RECVSLLA;
5893 
5894 	/* Handle IPv6 options. */
5895 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5896 		in_flags |= IPF_RECVIF;
5897 
5898 	/*
5899 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5900 	 * freed if the packet is dropped. The caller will do so.
5901 	 */
5902 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5903 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5904 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5905 		if (mp == NULL) {
5906 			return;
5907 		}
5908 	}
5909 	if ((in_flags != 0) &&
5910 	    (mp->b_datap->db_type != M_CTL)) {
5911 		/*
5912 		 * The actual data will be contained in b_cont
5913 		 * upon successful return of the following call
5914 		 * else original mblk is returned
5915 		 */
5916 		ASSERT(recv_ill != NULL);
5917 		mp = ip_add_info(mp, recv_ill, in_flags);
5918 	}
5919 	BUMP_MIB(&ip_mib, ipInDelivers);
5920 
5921 	/* Send it upstream */
5922 	CONN_UDP_RECV(connp, mp);
5923 }
5924 
5925 /*
5926  * Fanout for UDP packets.
5927  * The caller puts <fport, lport> in the ports parameter.
5928  *
5929  * If SO_REUSEADDR is set all multicast and broadcast packets
5930  * will be delivered to all streams bound to the same port.
5931  *
5932  * Zones notes:
5933  * Multicast and broadcast packets will be distributed to streams in all zones.
5934  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5935  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5936  * packets. To maintain this behavior with multiple zones, the conns are grouped
5937  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5938  * each zone. If unset, all the following conns in the same zone are skipped.
5939  */
5940 static void
5941 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5942     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5943     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5944 {
5945 	uint32_t	dstport, srcport;
5946 	ipaddr_t	dst;
5947 	mblk_t		*first_mp;
5948 	boolean_t	secure;
5949 	in6_addr_t	v6src;
5950 	conn_t		*connp;
5951 	connf_t		*connfp;
5952 	conn_t		*first_connp;
5953 	conn_t		*next_connp;
5954 	mblk_t		*mp1, *first_mp1;
5955 	ipaddr_t	src;
5956 	zoneid_t	last_zoneid;
5957 	boolean_t	reuseaddr;
5958 
5959 	first_mp = mp;
5960 	if (mctl_present) {
5961 		mp = first_mp->b_cont;
5962 		first_mp->b_cont = NULL;
5963 		secure = ipsec_in_is_secure(first_mp);
5964 		ASSERT(mp != NULL);
5965 	} else {
5966 		first_mp = NULL;
5967 		secure = B_FALSE;
5968 	}
5969 
5970 	/* Extract ports in net byte order */
5971 	dstport = htons(ntohl(ports) & 0xFFFF);
5972 	srcport = htons(ntohl(ports) >> 16);
5973 	dst = ipha->ipha_dst;
5974 	src = ipha->ipha_src;
5975 
5976 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5977 	mutex_enter(&connfp->connf_lock);
5978 	connp = connfp->connf_head;
5979 	if (!broadcast && !CLASSD(dst)) {
5980 		/*
5981 		 * Not broadcast or multicast. Send to the one (first)
5982 		 * client we find. No need to check conn_wantpacket()
5983 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5984 		 * IPv4 unicast packets.
5985 		 */
5986 		while ((connp != NULL) &&
5987 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5988 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5989 			connp = connp->conn_next;
5990 		}
5991 
5992 		if (connp == NULL || connp->conn_upq == NULL)
5993 			goto notfound;
5994 		CONN_INC_REF(connp);
5995 		mutex_exit(&connfp->connf_lock);
5996 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5997 		    recv_ill, ip_policy);
5998 		IP_STAT(ip_udp_fannorm);
5999 		CONN_DEC_REF(connp);
6000 		return;
6001 	}
6002 
6003 	/*
6004 	 * Broadcast and multicast case
6005 	 *
6006 	 * Need to check conn_wantpacket().
6007 	 * If SO_REUSEADDR has been set on the first we send the
6008 	 * packet to all clients that have joined the group and
6009 	 * match the port.
6010 	 */
6011 
6012 	while (connp != NULL) {
6013 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6014 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6015 			break;
6016 		connp = connp->conn_next;
6017 	}
6018 
6019 	if (connp == NULL || connp->conn_upq == NULL)
6020 		goto notfound;
6021 
6022 	first_connp = connp;
6023 	/*
6024 	 * When SO_REUSEADDR is not set, send the packet only to the first
6025 	 * matching connection in its zone by keeping track of the zoneid.
6026 	 */
6027 	reuseaddr = first_connp->conn_reuseaddr;
6028 	last_zoneid = first_connp->conn_zoneid;
6029 
6030 	CONN_INC_REF(connp);
6031 	connp = connp->conn_next;
6032 	for (;;) {
6033 		while (connp != NULL) {
6034 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6035 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6036 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6037 				break;
6038 			connp = connp->conn_next;
6039 		}
6040 		/*
6041 		 * Just copy the data part alone. The mctl part is
6042 		 * needed just for verifying policy and it is never
6043 		 * sent up.
6044 		 */
6045 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6046 		    ((mp1 = copymsg(mp)) == NULL))) {
6047 			/*
6048 			 * No more interested clients or memory
6049 			 * allocation failed
6050 			 */
6051 			connp = first_connp;
6052 			break;
6053 		}
6054 		if (connp->conn_zoneid != last_zoneid) {
6055 			/*
6056 			 * Update the zoneid so that the packet isn't sent to
6057 			 * any more conns in the same zone unless SO_REUSEADDR
6058 			 * is set.
6059 			 */
6060 			reuseaddr = connp->conn_reuseaddr;
6061 			last_zoneid = connp->conn_zoneid;
6062 		}
6063 		if (first_mp != NULL) {
6064 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6065 			    ipsec_info_type == IPSEC_IN);
6066 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6067 			if (first_mp1 == NULL) {
6068 				freemsg(mp1);
6069 				connp = first_connp;
6070 				break;
6071 			}
6072 		} else {
6073 			first_mp1 = NULL;
6074 		}
6075 		CONN_INC_REF(connp);
6076 		mutex_exit(&connfp->connf_lock);
6077 		/*
6078 		 * IPQoS notes: We don't send the packet for policy
6079 		 * processing here, will do it for the last one (below).
6080 		 * i.e. we do it per-packet now, but if we do policy
6081 		 * processing per-conn, then we would need to do it
6082 		 * here too.
6083 		 */
6084 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6085 		    ipha, flags, recv_ill, B_FALSE);
6086 		mutex_enter(&connfp->connf_lock);
6087 		/* Follow the next pointer before releasing the conn. */
6088 		next_connp = connp->conn_next;
6089 		IP_STAT(ip_udp_fanmb);
6090 		CONN_DEC_REF(connp);
6091 		connp = next_connp;
6092 	}
6093 
6094 	/* Last one.  Send it upstream. */
6095 	mutex_exit(&connfp->connf_lock);
6096 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6097 	    ip_policy);
6098 	IP_STAT(ip_udp_fanmb);
6099 	CONN_DEC_REF(connp);
6100 	return;
6101 
6102 notfound:
6103 
6104 	mutex_exit(&connfp->connf_lock);
6105 	IP_STAT(ip_udp_fanothers);
6106 	/*
6107 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6108 	 * have already been matched above, since they live in the IPv4
6109 	 * fanout tables. This implies we only need to
6110 	 * check for IPv6 in6addr_any endpoints here.
6111 	 * Thus we compare using ipv6_all_zeros instead of the destination
6112 	 * address, except for the multicast group membership lookup which
6113 	 * uses the IPv4 destination.
6114 	 */
6115 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6116 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6117 	mutex_enter(&connfp->connf_lock);
6118 	connp = connfp->connf_head;
6119 	if (!broadcast && !CLASSD(dst)) {
6120 		while (connp != NULL) {
6121 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6122 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6123 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6124 			    !connp->conn_ipv6_v6only)
6125 				break;
6126 			connp = connp->conn_next;
6127 		}
6128 
6129 		if (connp == NULL || connp->conn_upq == NULL) {
6130 			/*
6131 			 * No one bound to this port.  Is
6132 			 * there a client that wants all
6133 			 * unclaimed datagrams?
6134 			 */
6135 			mutex_exit(&connfp->connf_lock);
6136 
6137 			if (mctl_present)
6138 				first_mp->b_cont = mp;
6139 			else
6140 				first_mp = mp;
6141 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6142 				ip_fanout_proto(q, first_mp, ill, ipha,
6143 				    flags | IP_FF_RAWIP, mctl_present,
6144 				    ip_policy, recv_ill, zoneid);
6145 			} else {
6146 				if (ip_fanout_send_icmp(q, first_mp, flags,
6147 				    ICMP_DEST_UNREACHABLE,
6148 				    ICMP_PORT_UNREACHABLE,
6149 				    mctl_present, zoneid)) {
6150 					BUMP_MIB(&ip_mib, udpNoPorts);
6151 				}
6152 			}
6153 			return;
6154 		}
6155 		CONN_INC_REF(connp);
6156 		mutex_exit(&connfp->connf_lock);
6157 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6158 		    recv_ill, ip_policy);
6159 		CONN_DEC_REF(connp);
6160 		return;
6161 	}
6162 	/*
6163 	 * IPv4 multicast packet being delivered to an AF_INET6
6164 	 * in6addr_any endpoint.
6165 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6166 	 * and not conn_wantpacket_v6() since any multicast membership is
6167 	 * for an IPv4-mapped multicast address.
6168 	 * The packet is sent to all clients in all zones that have joined the
6169 	 * group and match the port.
6170 	 */
6171 	while (connp != NULL) {
6172 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6173 		    srcport, v6src) &&
6174 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6175 			break;
6176 		connp = connp->conn_next;
6177 	}
6178 
6179 	if (connp == NULL || connp->conn_upq == NULL) {
6180 		/*
6181 		 * No one bound to this port.  Is
6182 		 * there a client that wants all
6183 		 * unclaimed datagrams?
6184 		 */
6185 		mutex_exit(&connfp->connf_lock);
6186 
6187 		if (mctl_present)
6188 			first_mp->b_cont = mp;
6189 		else
6190 			first_mp = mp;
6191 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6192 			ip_fanout_proto(q, first_mp, ill, ipha,
6193 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6194 			    recv_ill, zoneid);
6195 		} else {
6196 			/*
6197 			 * We used to attempt to send an icmp error here, but
6198 			 * since this is known to be a multicast packet
6199 			 * and we don't send icmp errors in response to
6200 			 * multicast, just drop the packet and give up sooner.
6201 			 */
6202 			BUMP_MIB(&ip_mib, udpNoPorts);
6203 			freemsg(first_mp);
6204 		}
6205 		return;
6206 	}
6207 
6208 	first_connp = connp;
6209 
6210 	CONN_INC_REF(connp);
6211 	connp = connp->conn_next;
6212 	for (;;) {
6213 		while (connp != NULL) {
6214 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6215 			    ipv6_all_zeros, srcport, v6src) &&
6216 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6217 				break;
6218 			connp = connp->conn_next;
6219 		}
6220 		/*
6221 		 * Just copy the data part alone. The mctl part is
6222 		 * needed just for verifying policy and it is never
6223 		 * sent up.
6224 		 */
6225 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6226 		    ((mp1 = copymsg(mp)) == NULL))) {
6227 			/*
6228 			 * No more intested clients or memory
6229 			 * allocation failed
6230 			 */
6231 			connp = first_connp;
6232 			break;
6233 		}
6234 		if (first_mp != NULL) {
6235 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6236 			    ipsec_info_type == IPSEC_IN);
6237 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6238 			if (first_mp1 == NULL) {
6239 				freemsg(mp1);
6240 				connp = first_connp;
6241 				break;
6242 			}
6243 		} else {
6244 			first_mp1 = NULL;
6245 		}
6246 		CONN_INC_REF(connp);
6247 		mutex_exit(&connfp->connf_lock);
6248 		/*
6249 		 * IPQoS notes: We don't send the packet for policy
6250 		 * processing here, will do it for the last one (below).
6251 		 * i.e. we do it per-packet now, but if we do policy
6252 		 * processing per-conn, then we would need to do it
6253 		 * here too.
6254 		 */
6255 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6256 		    ipha, flags, recv_ill, B_FALSE);
6257 		mutex_enter(&connfp->connf_lock);
6258 		/* Follow the next pointer before releasing the conn. */
6259 		next_connp = connp->conn_next;
6260 		CONN_DEC_REF(connp);
6261 		connp = next_connp;
6262 	}
6263 
6264 	/* Last one.  Send it upstream. */
6265 	mutex_exit(&connfp->connf_lock);
6266 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6267 	    ip_policy);
6268 	CONN_DEC_REF(connp);
6269 }
6270 
6271 /*
6272  * Complete the ip_wput header so that it
6273  * is possible to generate ICMP
6274  * errors.
6275  */
6276 static int
6277 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6278 {
6279 	ire_t *ire;
6280 
6281 	if (ipha->ipha_src == INADDR_ANY) {
6282 		ire = ire_lookup_local(zoneid);
6283 		if (ire == NULL) {
6284 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6285 			return (1);
6286 		}
6287 		ipha->ipha_src = ire->ire_addr;
6288 		ire_refrele(ire);
6289 	}
6290 	ipha->ipha_ttl = ip_def_ttl;
6291 	ipha->ipha_hdr_checksum = 0;
6292 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6293 	return (0);
6294 }
6295 
6296 /*
6297  * Nobody should be sending
6298  * packets up this stream
6299  */
6300 static void
6301 ip_lrput(queue_t *q, mblk_t *mp)
6302 {
6303 	mblk_t *mp1;
6304 
6305 	switch (mp->b_datap->db_type) {
6306 	case M_FLUSH:
6307 		/* Turn around */
6308 		if (*mp->b_rptr & FLUSHW) {
6309 			*mp->b_rptr &= ~FLUSHR;
6310 			qreply(q, mp);
6311 			return;
6312 		}
6313 		break;
6314 	}
6315 	/* Could receive messages that passed through ar_rput */
6316 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6317 		mp1->b_prev = mp1->b_next = NULL;
6318 	freemsg(mp);
6319 }
6320 
6321 /* Nobody should be sending packets down this stream */
6322 /* ARGSUSED */
6323 void
6324 ip_lwput(queue_t *q, mblk_t *mp)
6325 {
6326 	freemsg(mp);
6327 }
6328 
6329 /*
6330  * Move the first hop in any source route to ipha_dst and remove that part of
6331  * the source route.  Called by other protocols.  Errors in option formatting
6332  * are ignored - will be handled by ip_wput_options Return the final
6333  * destination (either ipha_dst or the last entry in a source route.)
6334  */
6335 ipaddr_t
6336 ip_massage_options(ipha_t *ipha)
6337 {
6338 	ipoptp_t	opts;
6339 	uchar_t		*opt;
6340 	uint8_t		optval;
6341 	uint8_t		optlen;
6342 	ipaddr_t	dst;
6343 	int		i;
6344 	ire_t		*ire;
6345 
6346 	ip2dbg(("ip_massage_options\n"));
6347 	dst = ipha->ipha_dst;
6348 	for (optval = ipoptp_first(&opts, ipha);
6349 	    optval != IPOPT_EOL;
6350 	    optval = ipoptp_next(&opts)) {
6351 		opt = opts.ipoptp_cur;
6352 		switch (optval) {
6353 			uint8_t off;
6354 		case IPOPT_SSRR:
6355 		case IPOPT_LSRR:
6356 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6357 				ip1dbg(("ip_massage_options: bad src route\n"));
6358 				break;
6359 			}
6360 			optlen = opts.ipoptp_len;
6361 			off = opt[IPOPT_OFFSET];
6362 			off--;
6363 		redo_srr:
6364 			if (optlen < IP_ADDR_LEN ||
6365 			    off > optlen - IP_ADDR_LEN) {
6366 				/* End of source route */
6367 				ip1dbg(("ip_massage_options: end of SR\n"));
6368 				break;
6369 			}
6370 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6371 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6372 			    ntohl(dst)));
6373 			/*
6374 			 * Check if our address is present more than
6375 			 * once as consecutive hops in source route.
6376 			 * XXX verify per-interface ip_forwarding
6377 			 * for source route?
6378 			 */
6379 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6380 			    ALL_ZONES, MATCH_IRE_TYPE);
6381 			if (ire != NULL) {
6382 				ire_refrele(ire);
6383 				off += IP_ADDR_LEN;
6384 				goto redo_srr;
6385 			}
6386 			if (dst == htonl(INADDR_LOOPBACK)) {
6387 				ip1dbg(("ip_massage_options: loopback addr in "
6388 				    "source route!\n"));
6389 				break;
6390 			}
6391 			/*
6392 			 * Update ipha_dst to be the first hop and remove the
6393 			 * first hop from the source route (by overwriting
6394 			 * part of the option with NOP options).
6395 			 */
6396 			ipha->ipha_dst = dst;
6397 			/* Put the last entry in dst */
6398 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6399 			    3;
6400 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6401 
6402 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6403 			    ntohl(dst)));
6404 			/* Move down and overwrite */
6405 			opt[IP_ADDR_LEN] = opt[0];
6406 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6407 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6408 			for (i = 0; i < IP_ADDR_LEN; i++)
6409 				opt[i] = IPOPT_NOP;
6410 			break;
6411 		}
6412 	}
6413 	return (dst);
6414 }
6415 
6416 /*
6417  * This function's job is to forward data to the reverse tunnel (FA->HA)
6418  * after doing a few checks. It is assumed that the incoming interface
6419  * of the packet is always different than the outgoing interface and the
6420  * ire_type of the found ire has to be a non-resolver type.
6421  *
6422  * IPQoS notes
6423  * IP policy is invoked twice for a forwarded packet, once on the read side
6424  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6425  * enabled.
6426  */
6427 static void
6428 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6429 {
6430 	ipha_t		*ipha;
6431 	queue_t		*q;
6432 	uint32_t 	pkt_len;
6433 #define	rptr    ((uchar_t *)ipha)
6434 	uint32_t 	sum;
6435 	uint32_t 	max_frag;
6436 	mblk_t		*first_mp;
6437 	uint32_t	ill_index;
6438 
6439 	ASSERT(ire != NULL);
6440 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6441 	ASSERT(ire->ire_stq != NULL);
6442 
6443 	/* Initiate read side IPPF processing */
6444 	if (IPP_ENABLED(IPP_FWD_IN)) {
6445 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6446 		ip_process(IPP_FWD_IN, &mp, ill_index);
6447 		if (mp == NULL) {
6448 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6449 			    "dropped during IPPF processing\n"));
6450 			return;
6451 		}
6452 	}
6453 
6454 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6455 		ILLF_ROUTER) == 0) ||
6456 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6457 		BUMP_MIB(&ip_mib, ipForwProhibits);
6458 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6459 		    "forwarding is not turned on\n"));
6460 		goto drop_pkt;
6461 	}
6462 
6463 	/*
6464 	 * Don't forward if the interface is down
6465 	 */
6466 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6467 		BUMP_MIB(&ip_mib, ipInDiscards);
6468 		goto drop_pkt;
6469 	}
6470 
6471 	ipha = (ipha_t *)mp->b_rptr;
6472 	pkt_len = ntohs(ipha->ipha_length);
6473 	/* Adjust the checksum to reflect the ttl decrement. */
6474 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6475 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6476 	if (ipha->ipha_ttl-- <= 1) {
6477 		if (ip_csum_hdr(ipha)) {
6478 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6479 			goto drop_pkt;
6480 		}
6481 		q = ire->ire_stq;
6482 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6483 		    BPRI_HI)) == NULL) {
6484 			goto drop_pkt;
6485 		}
6486 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6487 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6488 
6489 		return;
6490 	}
6491 
6492 	/* Get the ill_index of the ILL */
6493 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6494 
6495 	/*
6496 	 * ip_mrtun_forward is only used by foreign agent to reverse
6497 	 * tunnel the incoming packet. So it does not do any option
6498 	 * processing for source routing.
6499 	 */
6500 	max_frag = ire->ire_max_frag;
6501 	if (pkt_len > max_frag) {
6502 		/*
6503 		 * It needs fragging on its way out.  We haven't
6504 		 * verified the header checksum yet.  Since we
6505 		 * are going to put a surely good checksum in the
6506 		 * outgoing header, we have to make sure that it
6507 		 * was good coming in.
6508 		 */
6509 		if (ip_csum_hdr(ipha)) {
6510 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6511 			goto drop_pkt;
6512 		}
6513 
6514 		/* Initiate write side IPPF processing */
6515 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6516 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6517 			if (mp == NULL) {
6518 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6519 				    "dropped/deferred during ip policy "\
6520 				    "processing\n"));
6521 				return;
6522 			}
6523 		}
6524 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6525 		    BPRI_HI)) == NULL) {
6526 			goto drop_pkt;
6527 		}
6528 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6529 		mp = first_mp;
6530 
6531 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6532 		return;
6533 	}
6534 
6535 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6536 
6537 	ASSERT(ire->ire_ipif != NULL);
6538 
6539 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6540 	if (mp == NULL) {
6541 		BUMP_MIB(&ip_mib, ipInDiscards);
6542 		return;
6543 	}
6544 
6545 	/* Now send the packet to the tunnel interface */
6546 	q = ire->ire_stq;
6547 	UPDATE_IB_PKT_COUNT(ire);
6548 	ire->ire_last_used_time = lbolt;
6549 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6550 	putnext(q, mp);
6551 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6552 	return;
6553 
6554 drop_pkt:;
6555 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6556 	freemsg(mp);
6557 #undef	rptr
6558 }
6559 
6560 /*
6561  * Fills the ipsec_out_t data structure with appropriate fields and
6562  * prepends it to mp which contains the IP hdr + data that was meant
6563  * to be forwarded. Please note that ipsec_out_info data structure
6564  * is used here to communicate the outgoing ill path at ip_wput()
6565  * for the ICMP error packet. This has nothing to do with ipsec IP
6566  * security. ipsec_out_t is really used to pass the info to the module
6567  * IP where this information cannot be extracted from conn.
6568  * This functions is called by ip_mrtun_forward().
6569  */
6570 void
6571 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6572 {
6573 	ipsec_out_t	*io;
6574 
6575 	ASSERT(xmit_ill != NULL);
6576 	first_mp->b_datap->db_type = M_CTL;
6577 	first_mp->b_wptr += sizeof (ipsec_info_t);
6578 	/*
6579 	 * This is to pass info to ip_wput in absence of conn.
6580 	 * ipsec_out_secure will be B_FALSE because of this.
6581 	 * Thus ipsec_out_secure being B_FALSE indicates that
6582 	 * this is not IPSEC security related information.
6583 	 */
6584 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6585 	io = (ipsec_out_t *)first_mp->b_rptr;
6586 	io->ipsec_out_type = IPSEC_OUT;
6587 	io->ipsec_out_len = sizeof (ipsec_out_t);
6588 	first_mp->b_cont = mp;
6589 	io->ipsec_out_ill_index =
6590 	    xmit_ill->ill_phyint->phyint_ifindex;
6591 	io->ipsec_out_xmit_if = B_TRUE;
6592 }
6593 
6594 /*
6595  * Return the network mask
6596  * associated with the specified address.
6597  */
6598 ipaddr_t
6599 ip_net_mask(ipaddr_t addr)
6600 {
6601 	uchar_t	*up = (uchar_t *)&addr;
6602 	ipaddr_t mask = 0;
6603 	uchar_t	*maskp = (uchar_t *)&mask;
6604 
6605 #if defined(__i386) || defined(__amd64)
6606 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6607 #endif
6608 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6609 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6610 #endif
6611 	if (CLASSD(addr)) {
6612 		maskp[0] = 0xF0;
6613 		return (mask);
6614 	}
6615 	if (addr == 0)
6616 		return (0);
6617 	maskp[0] = 0xFF;
6618 	if ((up[0] & 0x80) == 0)
6619 		return (mask);
6620 
6621 	maskp[1] = 0xFF;
6622 	if ((up[0] & 0xC0) == 0x80)
6623 		return (mask);
6624 
6625 	maskp[2] = 0xFF;
6626 	if ((up[0] & 0xE0) == 0xC0)
6627 		return (mask);
6628 
6629 	/* Must be experimental or multicast, indicate as much */
6630 	return ((ipaddr_t)0);
6631 }
6632 
6633 /*
6634  * Select an ill for the packet by considering load spreading across
6635  * a different ill in the group if dst_ill is part of some group.
6636  */
6637 static ill_t *
6638 ip_newroute_get_dst_ill(ill_t *dst_ill)
6639 {
6640 	ill_t *ill;
6641 
6642 	/*
6643 	 * We schedule irrespective of whether the source address is
6644 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6645 	 */
6646 	ill = illgrp_scheduler(dst_ill);
6647 	if (ill == NULL)
6648 		return (NULL);
6649 
6650 	/*
6651 	 * For groups with names ip_sioctl_groupname ensures that all
6652 	 * ills are of same type. For groups without names, ifgrp_insert
6653 	 * ensures this.
6654 	 */
6655 	ASSERT(dst_ill->ill_type == ill->ill_type);
6656 
6657 	return (ill);
6658 }
6659 
6660 /*
6661  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6662  */
6663 ill_t *
6664 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6665 {
6666 	ill_t *ret_ill;
6667 
6668 	ASSERT(ifindex != 0);
6669 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6670 	if (ret_ill == NULL ||
6671 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6672 		if (isv6) {
6673 			if (ill != NULL) {
6674 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6675 			} else {
6676 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6677 			}
6678 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6679 			    "bad ifindex %d.\n", ifindex));
6680 		} else {
6681 			BUMP_MIB(&ip_mib, ipOutDiscards);
6682 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6683 			    "bad ifindex %d.\n", ifindex));
6684 		}
6685 		if (ret_ill != NULL)
6686 			ill_refrele(ret_ill);
6687 		freemsg(first_mp);
6688 		return (NULL);
6689 	}
6690 
6691 	return (ret_ill);
6692 }
6693 
6694 /*
6695  * IPv4 -
6696  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6697  * out a packet to a destination address for which we do not have specific
6698  * (or sufficient) routing information.
6699  *
6700  * NOTE : These are the scopes of some of the variables that point at IRE,
6701  *	  which needs to be followed while making any future modifications
6702  *	  to avoid memory leaks.
6703  *
6704  *	- ire and sire are the entries looked up initially by
6705  *	  ire_ftable_lookup.
6706  *	- ipif_ire is used to hold the interface ire associated with
6707  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6708  *	  it before branching out to error paths.
6709  *	- save_ire is initialized before ire_create, so that ire returned
6710  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6711  *	  before breaking out of the switch.
6712  *
6713  *	Thus on failures, we have to REFRELE only ire and sire, if they
6714  *	are not NULL.
6715  */
6716 void
6717 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6718 {
6719 	areq_t	*areq;
6720 	ipaddr_t gw = 0;
6721 	ire_t	*ire = NULL;
6722 	mblk_t	*res_mp;
6723 	ipaddr_t *addrp;
6724 	ipaddr_t nexthop_addr;
6725 	ipif_t  *src_ipif = NULL;
6726 	ill_t	*dst_ill = NULL;
6727 	ipha_t  *ipha;
6728 	ire_t	*sire = NULL;
6729 	mblk_t	*first_mp;
6730 	ire_t	*save_ire;
6731 	mblk_t	*dlureq_mp;
6732 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6733 	ushort_t ire_marks = 0;
6734 	boolean_t mctl_present;
6735 	ipsec_out_t *io;
6736 	mblk_t	*saved_mp;
6737 	ire_t	*first_sire = NULL;
6738 	mblk_t	*copy_mp = NULL;
6739 	mblk_t	*xmit_mp = NULL;
6740 	ipaddr_t save_dst;
6741 	uint32_t multirt_flags =
6742 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6743 	boolean_t multirt_is_resolvable;
6744 	boolean_t multirt_resolve_next;
6745 	boolean_t do_attach_ill = B_FALSE;
6746 	boolean_t ip_nexthop = B_FALSE;
6747 	zoneid_t zoneid;
6748 
6749 	if (ip_debug > 2) {
6750 		/* ip1dbg */
6751 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6752 	}
6753 
6754 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6755 	if (mctl_present) {
6756 		io = (ipsec_out_t *)first_mp->b_rptr;
6757 		zoneid = io->ipsec_out_zoneid;
6758 		ASSERT(zoneid != ALL_ZONES);
6759 	} else if (connp != NULL) {
6760 		zoneid = connp->conn_zoneid;
6761 	} else {
6762 		zoneid = GLOBAL_ZONEID;
6763 	}
6764 
6765 	ipha = (ipha_t *)mp->b_rptr;
6766 
6767 	/* All multicast lookups come through ip_newroute_ipif() */
6768 	if (CLASSD(dst)) {
6769 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6770 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6771 		freemsg(first_mp);
6772 		return;
6773 	}
6774 
6775 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6776 		goto icmp_err_ret;
6777 	}
6778 
6779 	if (mctl_present && io->ipsec_out_attach_if) {
6780 		/* ip_grab_attach_ill returns a held ill */
6781 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6782 		    io->ipsec_out_ill_index, B_FALSE);
6783 
6784 		/* Failure case frees things for us. */
6785 		if (attach_ill == NULL)
6786 			return;
6787 
6788 		/*
6789 		 * Check if we need an ire that will not be
6790 		 * looked up by anybody else i.e. HIDDEN.
6791 		 */
6792 		if (ill_is_probeonly(attach_ill))
6793 			ire_marks = IRE_MARK_HIDDEN;
6794 	}
6795 	if (mctl_present && io->ipsec_out_ip_nexthop) {
6796 		ip_nexthop = B_TRUE;
6797 		nexthop_addr = io->ipsec_out_nexthop_addr;
6798 	}
6799 	/*
6800 	 * If this IRE is created for forwarding or it is not for
6801 	 * traffic for congestion controlled protocols, mark it as temporary.
6802 	 */
6803 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6804 		ire_marks |= IRE_MARK_TEMPORARY;
6805 
6806 	/*
6807 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6808 	 * chain until it gets the most specific information available.
6809 	 * For example, we know that there is no IRE_CACHE for this dest,
6810 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6811 	 * ire_ftable_lookup will look up the gateway, etc.
6812 	 * Check if in_ill != NULL. If it is true, the packet must be
6813 	 * from an incoming interface where RTA_SRCIFP is set.
6814 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6815 	 * to the destination, of equal netmask length in the forward table,
6816 	 * will be recursively explored. If no information is available
6817 	 * for the final gateway of that route, we force the returned ire
6818 	 * to be equal to sire using MATCH_IRE_PARENT.
6819 	 * At least, in this case we have a starting point (in the buckets)
6820 	 * to look for other routes to the destination in the forward table.
6821 	 * This is actually used only for multirouting, where a list
6822 	 * of routes has to be processed in sequence.
6823 	 */
6824 	if (in_ill != NULL) {
6825 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6826 		    in_ill, MATCH_IRE_TYPE);
6827 	} else if (ip_nexthop) {
6828 		/*
6829 		 * The first time we come here, we look for an IRE_INTERFACE
6830 		 * entry for the specified nexthop, set the dst to be the
6831 		 * nexthop address and create an IRE_CACHE entry for the
6832 		 * nexthop. The next time around, we are able to find an
6833 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
6834 		 * nexthop address and create an IRE_CACHE entry for the
6835 		 * destination address via the specified nexthop.
6836 		 */
6837 		ire = ire_cache_lookup(nexthop_addr, zoneid);
6838 		if (ire != NULL) {
6839 			gw = nexthop_addr;
6840 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
6841 		} else {
6842 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
6843 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
6844 			    MATCH_IRE_TYPE);
6845 			if (ire != NULL) {
6846 				dst = nexthop_addr;
6847 			}
6848 		}
6849 	} else if (attach_ill == NULL) {
6850 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6851 		    NULL, &sire, zoneid, 0,
6852 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6853 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6854 	} else {
6855 		/*
6856 		 * attach_ill is set only for communicating with
6857 		 * on-link hosts. So, don't look for DEFAULT.
6858 		 */
6859 		ipif_t	*attach_ipif;
6860 
6861 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6862 		if (attach_ipif == NULL) {
6863 			ill_refrele(attach_ill);
6864 			goto icmp_err_ret;
6865 		}
6866 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6867 		    &sire, zoneid, 0,
6868 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6869 		ipif_refrele(attach_ipif);
6870 	}
6871 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6872 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6873 
6874 	/*
6875 	 * This loop is run only once in most cases.
6876 	 * We loop to resolve further routes only when the destination
6877 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6878 	 */
6879 	do {
6880 		/* Clear the previous iteration's values */
6881 		if (src_ipif != NULL) {
6882 			ipif_refrele(src_ipif);
6883 			src_ipif = NULL;
6884 		}
6885 		if (dst_ill != NULL) {
6886 			ill_refrele(dst_ill);
6887 			dst_ill = NULL;
6888 		}
6889 
6890 		multirt_resolve_next = B_FALSE;
6891 		/*
6892 		 * We check if packets have to be multirouted.
6893 		 * In this case, given the current <ire, sire> couple,
6894 		 * we look for the next suitable <ire, sire>.
6895 		 * This check is done in ire_multirt_lookup(),
6896 		 * which applies various criteria to find the next route
6897 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6898 		 * unchanged if it detects it has not been tried yet.
6899 		 */
6900 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6901 			ip3dbg(("ip_newroute: starting next_resolution "
6902 			    "with first_mp %p, tag %d\n",
6903 			    (void *)first_mp,
6904 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6905 
6906 			ASSERT(sire != NULL);
6907 			multirt_is_resolvable =
6908 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6909 
6910 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6911 			    "ire %p, sire %p\n",
6912 			    multirt_is_resolvable,
6913 			    (void *)ire, (void *)sire));
6914 
6915 			if (!multirt_is_resolvable) {
6916 				/*
6917 				 * No more multirt route to resolve; give up
6918 				 * (all routes resolved or no more
6919 				 * resolvable routes).
6920 				 */
6921 				if (ire != NULL) {
6922 					ire_refrele(ire);
6923 					ire = NULL;
6924 				}
6925 			} else {
6926 				ASSERT(sire != NULL);
6927 				ASSERT(ire != NULL);
6928 				/*
6929 				 * We simply use first_sire as a flag that
6930 				 * indicates if a resolvable multirt route
6931 				 * has already been found.
6932 				 * If it is not the case, we may have to send
6933 				 * an ICMP error to report that the
6934 				 * destination is unreachable.
6935 				 * We do not IRE_REFHOLD first_sire.
6936 				 */
6937 				if (first_sire == NULL) {
6938 					first_sire = sire;
6939 				}
6940 			}
6941 		}
6942 		if (ire == NULL) {
6943 			if (ip_debug > 3) {
6944 				/* ip2dbg */
6945 				pr_addr_dbg("ip_newroute: "
6946 				    "can't resolve %s\n", AF_INET, &dst);
6947 			}
6948 			ip3dbg(("ip_newroute: "
6949 			    "ire %p, sire %p, first_sire %p\n",
6950 			    (void *)ire, (void *)sire, (void *)first_sire));
6951 
6952 			if (sire != NULL) {
6953 				ire_refrele(sire);
6954 				sire = NULL;
6955 			}
6956 
6957 			if (first_sire != NULL) {
6958 				/*
6959 				 * At least one multirt route has been found
6960 				 * in the same call to ip_newroute();
6961 				 * there is no need to report an ICMP error.
6962 				 * first_sire was not IRE_REFHOLDed.
6963 				 */
6964 				MULTIRT_DEBUG_UNTAG(first_mp);
6965 				freemsg(first_mp);
6966 				return;
6967 			}
6968 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6969 			    RTA_DST);
6970 			if (attach_ill != NULL)
6971 				ill_refrele(attach_ill);
6972 			goto icmp_err_ret;
6973 		}
6974 
6975 		/*
6976 		 * When RTA_SRCIFP is used to add a route, then an interface
6977 		 * route is added in the source interface's routing table.
6978 		 * If the outgoing interface of this route is of type
6979 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6980 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6981 		 * first used for forwarding packet, ip_newroute() is called
6982 		 * to resolve the hardware address of the outgoing ipif.
6983 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6984 		 * source interface based table. We only come here if the
6985 		 * outgoing interface is a resolver interface and we don't
6986 		 * have the ire_dlureq_mp information yet.
6987 		 * If in_ill is not null that means it is called from
6988 		 * ip_rput.
6989 		 */
6990 
6991 		ASSERT(ire->ire_in_ill == NULL ||
6992 		    (ire->ire_type == IRE_IF_RESOLVER &&
6993 		    ire->ire_dlureq_mp == NULL));
6994 
6995 		/*
6996 		 * Verify that the returned IRE does not have either
6997 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6998 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6999 		 */
7000 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7001 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7002 			if (attach_ill != NULL)
7003 				ill_refrele(attach_ill);
7004 			goto icmp_err_ret;
7005 		}
7006 		/*
7007 		 * Increment the ire_ob_pkt_count field for ire if it is an
7008 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7009 		 * increment the same for the parent IRE, sire, if it is some
7010 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7011 		 * and HOST_REDIRECT).
7012 		 */
7013 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7014 			UPDATE_OB_PKT_COUNT(ire);
7015 			ire->ire_last_used_time = lbolt;
7016 		}
7017 
7018 		if (sire != NULL) {
7019 			gw = sire->ire_gateway_addr;
7020 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7021 			    IRE_INTERFACE)) == 0);
7022 			UPDATE_OB_PKT_COUNT(sire);
7023 			sire->ire_last_used_time = lbolt;
7024 		}
7025 		/*
7026 		 * We have a route to reach the destination.
7027 		 *
7028 		 * 1) If the interface is part of ill group, try to get a new
7029 		 *    ill taking load spreading into account.
7030 		 *
7031 		 * 2) After selecting the ill, get a source address that
7032 		 *    might create good inbound load spreading.
7033 		 *    ipif_select_source does this for us.
7034 		 *
7035 		 * If the application specified the ill (ifindex), we still
7036 		 * load spread. Only if the packets needs to go out
7037 		 * specifically on a given ill e.g. binding to
7038 		 * IPIF_NOFAILOVER address, then we don't try to use a
7039 		 * different ill for load spreading.
7040 		 */
7041 		if (attach_ill == NULL) {
7042 			/*
7043 			 * Don't perform outbound load spreading in the
7044 			 * case of an RTF_MULTIRT route, as we actually
7045 			 * typically want to replicate outgoing packets
7046 			 * through particular interfaces.
7047 			 */
7048 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7049 				dst_ill = ire->ire_ipif->ipif_ill;
7050 				/* for uniformity */
7051 				ill_refhold(dst_ill);
7052 			} else {
7053 				/*
7054 				 * If we are here trying to create an IRE_CACHE
7055 				 * for an offlink destination and have the
7056 				 * IRE_CACHE for the next hop and the latter is
7057 				 * using virtual IP source address selection i.e
7058 				 * it's ire->ire_ipif is pointing to a virtual
7059 				 * network interface (vni) then
7060 				 * ip_newroute_get_dst_ll() will return the vni
7061 				 * interface as the dst_ill. Since the vni is
7062 				 * virtual i.e not associated with any physical
7063 				 * interface, it cannot be the dst_ill, hence
7064 				 * in such a case call ip_newroute_get_dst_ll()
7065 				 * with the stq_ill instead of the ire_ipif ILL.
7066 				 * The function returns a refheld ill.
7067 				 */
7068 				if ((ire->ire_type == IRE_CACHE) &&
7069 				    IS_VNI(ire->ire_ipif->ipif_ill))
7070 					dst_ill = ip_newroute_get_dst_ill(
7071 						ire->ire_stq->q_ptr);
7072 				else
7073 					dst_ill = ip_newroute_get_dst_ill(
7074 						ire->ire_ipif->ipif_ill);
7075 			}
7076 			if (dst_ill == NULL) {
7077 				if (ip_debug > 2) {
7078 					pr_addr_dbg("ip_newroute: "
7079 					    "no dst ill for dst"
7080 					    " %s\n", AF_INET, &dst);
7081 				}
7082 				goto icmp_err_ret;
7083 			}
7084 		} else {
7085 			dst_ill = ire->ire_ipif->ipif_ill;
7086 			/* for uniformity */
7087 			ill_refhold(dst_ill);
7088 			/*
7089 			 * We should have found a route matching ill as we
7090 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7091 			 * Rather than asserting, when there is a mismatch,
7092 			 * we just drop the packet.
7093 			 */
7094 			if (dst_ill != attach_ill) {
7095 				ip0dbg(("ip_newroute: Packet dropped as "
7096 				    "IPIF_NOFAILOVER ill is %s, "
7097 				    "ire->ire_ipif->ipif_ill is %s\n",
7098 				    attach_ill->ill_name,
7099 				    dst_ill->ill_name));
7100 				ill_refrele(attach_ill);
7101 				goto icmp_err_ret;
7102 			}
7103 		}
7104 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7105 		if (attach_ill != NULL) {
7106 			ill_refrele(attach_ill);
7107 			attach_ill = NULL;
7108 			do_attach_ill = B_TRUE;
7109 		}
7110 		ASSERT(dst_ill != NULL);
7111 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7112 
7113 		/*
7114 		 * Pick the best source address from dst_ill.
7115 		 *
7116 		 * 1) If it is part of a multipathing group, we would
7117 		 *    like to spread the inbound packets across different
7118 		 *    interfaces. ipif_select_source picks a random source
7119 		 *    across the different ills in the group.
7120 		 *
7121 		 * 2) If it is not part of a multipathing group, we try
7122 		 *    to pick the source address from the destination
7123 		 *    route. Clustering assumes that when we have multiple
7124 		 *    prefixes hosted on an interface, the prefix of the
7125 		 *    source address matches the prefix of the destination
7126 		 *    route. We do this only if the address is not
7127 		 *    DEPRECATED.
7128 		 *
7129 		 * 3) If the conn is in a different zone than the ire, we
7130 		 *    need to pick a source address from the right zone.
7131 		 *
7132 		 * NOTE : If we hit case (1) above, the prefix of the source
7133 		 *	  address picked may not match the prefix of the
7134 		 *	  destination routes prefix as ipif_select_source
7135 		 *	  does not look at "dst" while picking a source
7136 		 *	  address.
7137 		 *	  If we want the same behavior as (2), we will need
7138 		 *	  to change the behavior of ipif_select_source.
7139 		 */
7140 		ASSERT(src_ipif == NULL);
7141 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7142 			/*
7143 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7144 			 * Check that the ipif matching the requested source
7145 			 * address still exists.
7146 			 */
7147 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7148 			    zoneid, NULL, NULL, NULL, NULL);
7149 		}
7150 		if (src_ipif == NULL) {
7151 			ire_marks |= IRE_MARK_USESRC_CHECK;
7152 			if ((dst_ill->ill_group != NULL) ||
7153 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7154 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
7155 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7156 				/*
7157 				 * If the destination is reachable via a
7158 				 * given gateway, the selected source address
7159 				 * should be in the same subnet as the gateway.
7160 				 * Otherwise, the destination is not reachable.
7161 				 *
7162 				 * If there are no interfaces on the same subnet
7163 				 * as the destination, ipif_select_source gives
7164 				 * first non-deprecated interface which might be
7165 				 * on a different subnet than the gateway.
7166 				 * This is not desirable. Hence pass the dst_ire
7167 				 * source address to ipif_select_source.
7168 				 * It is sure that the destination is reachable
7169 				 * with the dst_ire source address subnet.
7170 				 * So passing dst_ire source address to
7171 				 * ipif_select_source will make sure that the
7172 				 * selected source will be on the same subnet
7173 				 * as dst_ire source address.
7174 				 */
7175 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7176 				src_ipif = ipif_select_source(dst_ill, saddr,
7177 				    zoneid);
7178 				if (src_ipif == NULL) {
7179 					if (ip_debug > 2) {
7180 						pr_addr_dbg("ip_newroute: "
7181 						    "no src for dst %s ",
7182 						    AF_INET, &dst);
7183 						printf("through interface %s\n",
7184 						    dst_ill->ill_name);
7185 					}
7186 					goto icmp_err_ret;
7187 				}
7188 			} else {
7189 				src_ipif = ire->ire_ipif;
7190 				ASSERT(src_ipif != NULL);
7191 				/* hold src_ipif for uniformity */
7192 				ipif_refhold(src_ipif);
7193 			}
7194 		}
7195 
7196 		/*
7197 		 * Assign a source address while we have the conn.
7198 		 * We can't have ip_wput_ire pick a source address when the
7199 		 * packet returns from arp since we need to look at
7200 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7201 		 * going through arp.
7202 		 *
7203 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7204 		 *	  it uses ip6i to store this information.
7205 		 */
7206 		if (ipha->ipha_src == INADDR_ANY &&
7207 		    (connp == NULL || !connp->conn_unspec_src)) {
7208 			ipha->ipha_src = src_ipif->ipif_src_addr;
7209 		}
7210 		if (ip_debug > 3) {
7211 			/* ip2dbg */
7212 			pr_addr_dbg("ip_newroute: first hop %s\n",
7213 			    AF_INET, &gw);
7214 		}
7215 		ip2dbg(("\tire type %s (%d)\n",
7216 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7217 
7218 		/*
7219 		 * The TTL of multirouted packets is bounded by the
7220 		 * ip_multirt_ttl ndd variable.
7221 		 */
7222 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7223 			/* Force TTL of multirouted packets */
7224 			if ((ip_multirt_ttl > 0) &&
7225 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7226 				ip2dbg(("ip_newroute: forcing multirt TTL "
7227 				    "to %d (was %d), dst 0x%08x\n",
7228 				    ip_multirt_ttl, ipha->ipha_ttl,
7229 				    ntohl(sire->ire_addr)));
7230 				ipha->ipha_ttl = ip_multirt_ttl;
7231 			}
7232 		}
7233 		/*
7234 		 * At this point in ip_newroute(), ire is either the
7235 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7236 		 * destination or an IRE_INTERFACE type that should be used
7237 		 * to resolve an on-subnet destination or an on-subnet
7238 		 * next-hop gateway.
7239 		 *
7240 		 * In the IRE_CACHE case, we have the following :
7241 		 *
7242 		 * 1) src_ipif - used for getting a source address.
7243 		 *
7244 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7245 		 *    means packets using this IRE_CACHE will go out on
7246 		 *    dst_ill.
7247 		 *
7248 		 * 3) The IRE sire will point to the prefix that is the
7249 		 *    longest  matching route for the destination. These
7250 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7251 		 *    and IRE_HOST_REDIRECT.
7252 		 *
7253 		 *    The newly created IRE_CACHE entry for the off-subnet
7254 		 *    destination is tied to both the prefix route and the
7255 		 *    interface route used to resolve the next-hop gateway
7256 		 *    via the ire_phandle and ire_ihandle fields,
7257 		 *    respectively.
7258 		 *
7259 		 * In the IRE_INTERFACE case, we have the following :
7260 		 *
7261 		 * 1) src_ipif - used for getting a source address.
7262 		 *
7263 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7264 		 *    means packets using the IRE_CACHE that we will build
7265 		 *    here will go out on dst_ill.
7266 		 *
7267 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7268 		 *    to be created will only be tied to the IRE_INTERFACE
7269 		 *    that was derived from the ire_ihandle field.
7270 		 *
7271 		 *    If sire is non-NULL, it means the destination is
7272 		 *    off-link and we will first create the IRE_CACHE for the
7273 		 *    gateway. Next time through ip_newroute, we will create
7274 		 *    the IRE_CACHE for the final destination as described
7275 		 *    above.
7276 		 *
7277 		 * In both cases, after the current resolution has been
7278 		 * completed (or possibly initialised, in the IRE_INTERFACE
7279 		 * case), the loop may be re-entered to attempt the resolution
7280 		 * of another RTF_MULTIRT route.
7281 		 *
7282 		 * When an IRE_CACHE entry for the off-subnet destination is
7283 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7284 		 * for further processing in emission loops.
7285 		 */
7286 		save_ire = ire;
7287 		switch (ire->ire_type) {
7288 		case IRE_CACHE: {
7289 			ire_t	*ipif_ire;
7290 			mblk_t	*ire_fp_mp;
7291 
7292 			if (gw == 0)
7293 				gw = ire->ire_gateway_addr;
7294 			/*
7295 			 * We need 3 ire's to create a new cache ire for an
7296 			 * off-link destination from the cache ire of the
7297 			 * gateway.
7298 			 *
7299 			 *	1. The prefix ire 'sire' (Note that this does
7300 			 *	   not apply to the conn_nexthop_set case)
7301 			 *	2. The cache ire of the gateway 'ire'
7302 			 *	3. The interface ire 'ipif_ire'
7303 			 *
7304 			 * We have (1) and (2). We lookup (3) below.
7305 			 *
7306 			 * If there is no interface route to the gateway,
7307 			 * it is a race condition, where we found the cache
7308 			 * but the interface route has been deleted.
7309 			 */
7310 			if (ip_nexthop) {
7311 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7312 			} else {
7313 				ipif_ire =
7314 				    ire_ihandle_lookup_offlink(ire, sire);
7315 			}
7316 			if (ipif_ire == NULL) {
7317 				ip1dbg(("ip_newroute: "
7318 				    "ire_ihandle_lookup_offlink failed\n"));
7319 				goto icmp_err_ret;
7320 			}
7321 			/*
7322 			 * XXX We are using the same dlureq_mp
7323 			 * (DL_UNITDATA_REQ) though the save_ire is not
7324 			 * pointing at the same ill.
7325 			 * This is incorrect. We need to send it up to the
7326 			 * resolver to get the right dlureq_mp. For ethernets
7327 			 * this may be okay (ill_type == DL_ETHER).
7328 			 */
7329 			dlureq_mp = save_ire->ire_dlureq_mp;
7330 			ire_fp_mp = NULL;
7331 			/*
7332 			 * save_ire's ire_fp_mp can't change since it is
7333 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7334 			 * LOCK_IRE_FP_MP does not do any useful work in
7335 			 * the case of IRE_CACHE. So we don't use it below.
7336 			 */
7337 			if (save_ire->ire_stq == dst_ill->ill_wq)
7338 				ire_fp_mp = save_ire->ire_fp_mp;
7339 
7340 			ire = ire_create(
7341 			    (uchar_t *)&dst,		/* dest address */
7342 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7343 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7344 			    (uchar_t *)&gw,		/* gateway address */
7345 			    NULL,
7346 			    &save_ire->ire_max_frag,
7347 			    ire_fp_mp,			/* Fast Path header */
7348 			    dst_ill->ill_rq,		/* recv-from queue */
7349 			    dst_ill->ill_wq,		/* send-to queue */
7350 			    IRE_CACHE,			/* IRE type */
7351 			    save_ire->ire_dlureq_mp,
7352 			    src_ipif,
7353 			    in_ill,			/* incoming ill */
7354 			    (sire != NULL) ?
7355 				sire->ire_mask : 0, 	/* Parent mask */
7356 			    (sire != NULL) ?
7357 				sire->ire_phandle : 0,  /* Parent handle */
7358 			    ipif_ire->ire_ihandle,	/* Interface handle */
7359 			    (sire != NULL) ? (sire->ire_flags &
7360 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7361 			    (sire != NULL) ?
7362 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo));
7363 
7364 			if (ire == NULL) {
7365 				ire_refrele(ipif_ire);
7366 				ire_refrele(save_ire);
7367 				break;
7368 			}
7369 			ire->ire_marks |= ire_marks;
7370 
7371 			/*
7372 			 * Prevent sire and ipif_ire from getting deleted.
7373 			 * The newly created ire is tied to both of them via
7374 			 * the phandle and ihandle respectively.
7375 			 */
7376 			if (sire != NULL) {
7377 				IRB_REFHOLD(sire->ire_bucket);
7378 				/* Has it been removed already ? */
7379 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7380 					IRB_REFRELE(sire->ire_bucket);
7381 					ire_refrele(ipif_ire);
7382 					ire_refrele(save_ire);
7383 					break;
7384 				}
7385 			}
7386 
7387 			IRB_REFHOLD(ipif_ire->ire_bucket);
7388 			/* Has it been removed already ? */
7389 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7390 				IRB_REFRELE(ipif_ire->ire_bucket);
7391 				if (sire != NULL)
7392 					IRB_REFRELE(sire->ire_bucket);
7393 				ire_refrele(ipif_ire);
7394 				ire_refrele(save_ire);
7395 				break;
7396 			}
7397 
7398 			xmit_mp = first_mp;
7399 			/*
7400 			 * In the case of multirouting, a copy
7401 			 * of the packet is done before its sending.
7402 			 * The copy is used to attempt another
7403 			 * route resolution, in a next loop.
7404 			 */
7405 			if (ire->ire_flags & RTF_MULTIRT) {
7406 				copy_mp = copymsg(first_mp);
7407 				if (copy_mp != NULL) {
7408 					xmit_mp = copy_mp;
7409 					MULTIRT_DEBUG_TAG(first_mp);
7410 				}
7411 			}
7412 			ire_add_then_send(q, ire, xmit_mp);
7413 			ire_refrele(save_ire);
7414 
7415 			/* Assert that sire is not deleted yet. */
7416 			if (sire != NULL) {
7417 				ASSERT(sire->ire_ptpn != NULL);
7418 				IRB_REFRELE(sire->ire_bucket);
7419 			}
7420 
7421 			/* Assert that ipif_ire is not deleted yet. */
7422 			ASSERT(ipif_ire->ire_ptpn != NULL);
7423 			IRB_REFRELE(ipif_ire->ire_bucket);
7424 			ire_refrele(ipif_ire);
7425 
7426 			/*
7427 			 * If copy_mp is not NULL, multirouting was
7428 			 * requested. We loop to initiate a next
7429 			 * route resolution attempt, starting from sire.
7430 			 */
7431 			if (copy_mp != NULL) {
7432 				/*
7433 				 * Search for the next unresolved
7434 				 * multirt route.
7435 				 */
7436 				copy_mp = NULL;
7437 				ipif_ire = NULL;
7438 				ire = NULL;
7439 				multirt_resolve_next = B_TRUE;
7440 				continue;
7441 			}
7442 			if (sire != NULL)
7443 				ire_refrele(sire);
7444 			ipif_refrele(src_ipif);
7445 			ill_refrele(dst_ill);
7446 			return;
7447 		}
7448 		case IRE_IF_NORESOLVER: {
7449 			/*
7450 			 * We have what we need to build an IRE_CACHE.
7451 			 *
7452 			 * Create a new dlureq_mp with the IP gateway address
7453 			 * in destination address in the DLPI hdr if the
7454 			 * physical length is exactly 4 bytes.
7455 			 */
7456 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7457 				uchar_t *addr;
7458 
7459 				if (gw)
7460 					addr = (uchar_t *)&gw;
7461 				else
7462 					addr = (uchar_t *)&dst;
7463 
7464 				dlureq_mp = ill_dlur_gen(addr,
7465 				    dst_ill->ill_phys_addr_length,
7466 				    dst_ill->ill_sap,
7467 				    dst_ill->ill_sap_length);
7468 			} else {
7469 				dlureq_mp = ire->ire_dlureq_mp;
7470 			}
7471 
7472 			if (dlureq_mp == NULL) {
7473 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7474 				break;
7475 			}
7476 
7477 			ire = ire_create(
7478 			    (uchar_t *)&dst,		/* dest address */
7479 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7480 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7481 			    (uchar_t *)&gw,		/* gateway address */
7482 			    NULL,
7483 			    &save_ire->ire_max_frag,
7484 			    NULL,			/* Fast Path header */
7485 			    dst_ill->ill_rq,		/* recv-from queue */
7486 			    dst_ill->ill_wq,		/* send-to queue */
7487 			    IRE_CACHE,
7488 			    dlureq_mp,
7489 			    src_ipif,
7490 			    in_ill,			/* Incoming ill */
7491 			    save_ire->ire_mask,		/* Parent mask */
7492 			    (sire != NULL) ?		/* Parent handle */
7493 				sire->ire_phandle : 0,
7494 			    save_ire->ire_ihandle,	/* Interface handle */
7495 			    (sire != NULL) ? sire->ire_flags &
7496 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7497 			    &(save_ire->ire_uinfo));
7498 
7499 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7500 				freeb(dlureq_mp);
7501 
7502 			if (ire == NULL) {
7503 				ire_refrele(save_ire);
7504 				break;
7505 			}
7506 
7507 			ire->ire_marks |= ire_marks;
7508 
7509 			/* Prevent save_ire from getting deleted */
7510 			IRB_REFHOLD(save_ire->ire_bucket);
7511 			/* Has it been removed already ? */
7512 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7513 				IRB_REFRELE(save_ire->ire_bucket);
7514 				ire_refrele(save_ire);
7515 				break;
7516 			}
7517 
7518 			/*
7519 			 * In the case of multirouting, a copy
7520 			 * of the packet is made before it is sent.
7521 			 * The copy is used in the next
7522 			 * loop to attempt another resolution.
7523 			 */
7524 			xmit_mp = first_mp;
7525 			if ((sire != NULL) &&
7526 			    (sire->ire_flags & RTF_MULTIRT)) {
7527 				copy_mp = copymsg(first_mp);
7528 				if (copy_mp != NULL) {
7529 					xmit_mp = copy_mp;
7530 					MULTIRT_DEBUG_TAG(first_mp);
7531 				}
7532 			}
7533 			ire_add_then_send(q, ire, xmit_mp);
7534 
7535 			/* Assert that it is not deleted yet. */
7536 			ASSERT(save_ire->ire_ptpn != NULL);
7537 			IRB_REFRELE(save_ire->ire_bucket);
7538 			ire_refrele(save_ire);
7539 
7540 			if (copy_mp != NULL) {
7541 				/*
7542 				 * If we found a (no)resolver, we ignore any
7543 				 * trailing top priority IRE_CACHE in further
7544 				 * loops. This ensures that we do not omit any
7545 				 * (no)resolver.
7546 				 * This IRE_CACHE, if any, will be processed
7547 				 * by another thread entering ip_newroute().
7548 				 * IRE_CACHE entries, if any, will be processed
7549 				 * by another thread entering ip_newroute(),
7550 				 * (upon resolver response, for instance).
7551 				 * This aims to force parallel multirt
7552 				 * resolutions as soon as a packet must be sent.
7553 				 * In the best case, after the tx of only one
7554 				 * packet, all reachable routes are resolved.
7555 				 * Otherwise, the resolution of all RTF_MULTIRT
7556 				 * routes would require several emissions.
7557 				 */
7558 				multirt_flags &= ~MULTIRT_CACHEGW;
7559 
7560 				/*
7561 				 * Search for the next unresolved multirt
7562 				 * route.
7563 				 */
7564 				copy_mp = NULL;
7565 				save_ire = NULL;
7566 				ire = NULL;
7567 				multirt_resolve_next = B_TRUE;
7568 				continue;
7569 			}
7570 
7571 			/*
7572 			 * Don't need sire anymore
7573 			 */
7574 			if (sire != NULL)
7575 				ire_refrele(sire);
7576 
7577 			ipif_refrele(src_ipif);
7578 			ill_refrele(dst_ill);
7579 			return;
7580 		}
7581 		case IRE_IF_RESOLVER:
7582 			/*
7583 			 * We can't build an IRE_CACHE yet, but at least we
7584 			 * found a resolver that can help.
7585 			 */
7586 			res_mp = dst_ill->ill_resolver_mp;
7587 			if (!OK_RESOLVER_MP(res_mp))
7588 				break;
7589 			/*
7590 			 * To be at this point in the code with a non-zero gw
7591 			 * means that dst is reachable through a gateway that
7592 			 * we have never resolved.  By changing dst to the gw
7593 			 * addr we resolve the gateway first.
7594 			 * When ire_add_then_send() tries to put the IP dg
7595 			 * to dst, it will reenter ip_newroute() at which
7596 			 * time we will find the IRE_CACHE for the gw and
7597 			 * create another IRE_CACHE in case IRE_CACHE above.
7598 			 */
7599 			if (gw != INADDR_ANY) {
7600 				/*
7601 				 * The source ipif that was determined above was
7602 				 * relative to the destination address, not the
7603 				 * gateway's. If src_ipif was not taken out of
7604 				 * the IRE_IF_RESOLVER entry, we'll need to call
7605 				 * ipif_select_source() again.
7606 				 */
7607 				if (src_ipif != ire->ire_ipif) {
7608 					ipif_refrele(src_ipif);
7609 					src_ipif = ipif_select_source(dst_ill,
7610 					    gw, zoneid);
7611 					if (src_ipif == NULL) {
7612 						if (ip_debug > 2) {
7613 							pr_addr_dbg(
7614 							    "ip_newroute: no "
7615 							    "src for gw %s ",
7616 							    AF_INET, &gw);
7617 							printf("through "
7618 							    "interface %s\n",
7619 							    dst_ill->ill_name);
7620 						}
7621 						goto icmp_err_ret;
7622 					}
7623 				}
7624 				save_dst = dst;
7625 				dst = gw;
7626 				gw = INADDR_ANY;
7627 			}
7628 			/*
7629 			 * We obtain a partial IRE_CACHE which we will pass
7630 			 * along with the resolver query.  When the response
7631 			 * comes back it will be there ready for us to add.
7632 			 * The ire_max_frag is atomically set under the
7633 			 * irebucket lock in ire_add_v[46].
7634 			 */
7635 			ire = ire_create_mp(
7636 			    (uchar_t *)&dst,		/* dest address */
7637 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7638 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7639 			    (uchar_t *)&gw,		/* gateway address */
7640 			    NULL,			/* no in_src_addr */
7641 			    NULL,			/* ire_max_frag */
7642 			    NULL,			/* Fast Path header */
7643 			    dst_ill->ill_rq,		/* recv-from queue */
7644 			    dst_ill->ill_wq,		/* send-to queue */
7645 			    IRE_CACHE,
7646 			    res_mp,
7647 			    src_ipif,			/* Interface ipif */
7648 			    in_ill,			/* Incoming ILL */
7649 			    save_ire->ire_mask,		/* Parent mask */
7650 			    0,
7651 			    save_ire->ire_ihandle,	/* Interface handle */
7652 			    0,				/* flags if any */
7653 			    &(save_ire->ire_uinfo));
7654 
7655 			if (ire == NULL) {
7656 				ire_refrele(save_ire);
7657 				break;
7658 			}
7659 
7660 			if ((sire != NULL) &&
7661 			    (sire->ire_flags & RTF_MULTIRT)) {
7662 				copy_mp = copymsg(first_mp);
7663 				if (copy_mp != NULL)
7664 					MULTIRT_DEBUG_TAG(copy_mp);
7665 			}
7666 
7667 			ire->ire_marks |= ire_marks;
7668 
7669 			/*
7670 			 * Construct message chain for the resolver
7671 			 * of the form:
7672 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7673 			 * Packet could contain a IPSEC_OUT mp.
7674 			 *
7675 			 * NOTE : ire will be added later when the response
7676 			 * comes back from ARP. If the response does not
7677 			 * come back, ARP frees the packet. For this reason,
7678 			 * we can't REFHOLD the bucket of save_ire to prevent
7679 			 * deletions. We may not be able to REFRELE the bucket
7680 			 * if the response never comes back. Thus, before
7681 			 * adding the ire, ire_add_v4 will make sure that the
7682 			 * interface route does not get deleted. This is the
7683 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7684 			 * where we can always prevent deletions because of
7685 			 * the synchronous nature of adding IRES i.e
7686 			 * ire_add_then_send is called after creating the IRE.
7687 			 */
7688 			ASSERT(ire->ire_mp != NULL);
7689 			ire->ire_mp->b_cont = first_mp;
7690 			/* Have saved_mp handy, for cleanup if canput fails */
7691 			saved_mp = mp;
7692 			mp = ire->ire_dlureq_mp;
7693 			ASSERT(mp != NULL);
7694 			ire->ire_dlureq_mp = NULL;
7695 			linkb(mp, ire->ire_mp);
7696 
7697 
7698 			/*
7699 			 * Fill in the source and dest addrs for the resolver.
7700 			 * NOTE: this depends on memory layouts imposed by
7701 			 * ill_init().
7702 			 */
7703 			areq = (areq_t *)mp->b_rptr;
7704 			addrp = (ipaddr_t *)((char *)areq +
7705 			    areq->areq_sender_addr_offset);
7706 			if (do_attach_ill) {
7707 				/*
7708 				 * This is bind to no failover case.
7709 				 * arp packet also must go out on attach_ill.
7710 				 */
7711 				ASSERT(ipha->ipha_src != NULL);
7712 				*addrp = ipha->ipha_src;
7713 			} else {
7714 				*addrp = save_ire->ire_src_addr;
7715 			}
7716 
7717 			ire_refrele(save_ire);
7718 			addrp = (ipaddr_t *)((char *)areq +
7719 			    areq->areq_target_addr_offset);
7720 			*addrp = dst;
7721 			/* Up to the resolver. */
7722 			if (canputnext(dst_ill->ill_rq)) {
7723 				putnext(dst_ill->ill_rq, mp);
7724 				ire = NULL;
7725 				if (copy_mp != NULL) {
7726 					/*
7727 					 * If we found a resolver, we ignore
7728 					 * any trailing top priority IRE_CACHE
7729 					 * in the further loops. This ensures
7730 					 * that we do not omit any resolver.
7731 					 * IRE_CACHE entries, if any, will be
7732 					 * processed next time we enter
7733 					 * ip_newroute().
7734 					 */
7735 					multirt_flags &= ~MULTIRT_CACHEGW;
7736 					/*
7737 					 * Search for the next unresolved
7738 					 * multirt route.
7739 					 */
7740 					first_mp = copy_mp;
7741 					copy_mp = NULL;
7742 					/* Prepare the next resolution loop. */
7743 					mp = first_mp;
7744 					EXTRACT_PKT_MP(mp, first_mp,
7745 					    mctl_present);
7746 					if (mctl_present)
7747 						io = (ipsec_out_t *)
7748 						    first_mp->b_rptr;
7749 					ipha = (ipha_t *)mp->b_rptr;
7750 
7751 					ASSERT(sire != NULL);
7752 
7753 					dst = save_dst;
7754 					multirt_resolve_next = B_TRUE;
7755 					continue;
7756 				}
7757 
7758 				if (sire != NULL)
7759 					ire_refrele(sire);
7760 
7761 				/*
7762 				 * The response will come back in ip_wput
7763 				 * with db_type IRE_DB_TYPE.
7764 				 */
7765 				ipif_refrele(src_ipif);
7766 				ill_refrele(dst_ill);
7767 				return;
7768 			} else {
7769 				/* Prepare for cleanup */
7770 				ire->ire_dlureq_mp = mp;
7771 				mp->b_cont = NULL;
7772 				ire_delete(ire);
7773 				mp = saved_mp;
7774 				ire = NULL;
7775 				if (copy_mp != NULL) {
7776 					MULTIRT_DEBUG_UNTAG(copy_mp);
7777 					freemsg(copy_mp);
7778 					copy_mp = NULL;
7779 				}
7780 				break;
7781 			}
7782 		default:
7783 			break;
7784 		}
7785 	} while (multirt_resolve_next);
7786 
7787 	ip1dbg(("ip_newroute: dropped\n"));
7788 	/* Did this packet originate externally? */
7789 	if (mp->b_prev) {
7790 		mp->b_next = NULL;
7791 		mp->b_prev = NULL;
7792 		BUMP_MIB(&ip_mib, ipInDiscards);
7793 	} else {
7794 		BUMP_MIB(&ip_mib, ipOutDiscards);
7795 	}
7796 	ASSERT(copy_mp == NULL);
7797 	MULTIRT_DEBUG_UNTAG(first_mp);
7798 	freemsg(first_mp);
7799 	if (ire != NULL)
7800 		ire_refrele(ire);
7801 	if (sire != NULL)
7802 		ire_refrele(sire);
7803 	if (src_ipif != NULL)
7804 		ipif_refrele(src_ipif);
7805 	if (dst_ill != NULL)
7806 		ill_refrele(dst_ill);
7807 	return;
7808 
7809 icmp_err_ret:
7810 	ip1dbg(("ip_newroute: no route\n"));
7811 	if (src_ipif != NULL)
7812 		ipif_refrele(src_ipif);
7813 	if (dst_ill != NULL)
7814 		ill_refrele(dst_ill);
7815 	if (sire != NULL)
7816 		ire_refrele(sire);
7817 	/* Did this packet originate externally? */
7818 	if (mp->b_prev) {
7819 		mp->b_next = NULL;
7820 		mp->b_prev = NULL;
7821 		/* XXX ipInNoRoutes */
7822 		q = WR(q);
7823 	} else {
7824 		/*
7825 		 * Since ip_wput() isn't close to finished, we fill
7826 		 * in enough of the header for credible error reporting.
7827 		 */
7828 		if (ip_hdr_complete(ipha, zoneid)) {
7829 			/* Failed */
7830 			MULTIRT_DEBUG_UNTAG(first_mp);
7831 			freemsg(first_mp);
7832 			if (ire != NULL)
7833 				ire_refrele(ire);
7834 			return;
7835 		}
7836 	}
7837 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7838 
7839 	/*
7840 	 * At this point we will have ire only if RTF_BLACKHOLE
7841 	 * or RTF_REJECT flags are set on the IRE. It will not
7842 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7843 	 */
7844 	if (ire != NULL) {
7845 		if (ire->ire_flags & RTF_BLACKHOLE) {
7846 			ire_refrele(ire);
7847 			MULTIRT_DEBUG_UNTAG(first_mp);
7848 			freemsg(first_mp);
7849 			return;
7850 		}
7851 		ire_refrele(ire);
7852 	}
7853 	if (ip_source_routed(ipha)) {
7854 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7855 		return;
7856 	}
7857 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7858 }
7859 
7860 /*
7861  * IPv4 -
7862  * ip_newroute_ipif is called by ip_wput_multicast and
7863  * ip_rput_forward_multicast whenever we need to send
7864  * out a packet to a destination address for which we do not have specific
7865  * routing information. It is used when the packet will be sent out
7866  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7867  * socket option is set or icmp error message wants to go out on a particular
7868  * interface for a unicast packet.
7869  *
7870  * In most cases, the destination address is resolved thanks to the ipif
7871  * intrinsic resolver. However, there are some cases where the call to
7872  * ip_newroute_ipif must take into account the potential presence of
7873  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7874  * that uses the interface. This is specified through flags,
7875  * which can be a combination of:
7876  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7877  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7878  *   and flags. Additionally, the packet source address has to be set to
7879  *   the specified address. The caller is thus expected to set this flag
7880  *   if the packet has no specific source address yet.
7881  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7882  *   flag, the resulting ire will inherit the flag. All unresolved routes
7883  *   to the destination must be explored in the same call to
7884  *   ip_newroute_ipif().
7885  */
7886 static void
7887 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7888     conn_t *connp, uint32_t flags)
7889 {
7890 	areq_t	*areq;
7891 	ire_t	*ire = NULL;
7892 	mblk_t	*res_mp;
7893 	ipaddr_t *addrp;
7894 	mblk_t *first_mp;
7895 	ire_t	*save_ire = NULL;
7896 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7897 	ipif_t	*src_ipif = NULL;
7898 	ushort_t ire_marks = 0;
7899 	ill_t	*dst_ill = NULL;
7900 	boolean_t mctl_present;
7901 	ipsec_out_t *io;
7902 	ipha_t *ipha;
7903 	int	ihandle = 0;
7904 	mblk_t	*saved_mp;
7905 	ire_t   *fire = NULL;
7906 	mblk_t  *copy_mp = NULL;
7907 	boolean_t multirt_resolve_next;
7908 	ipaddr_t ipha_dst;
7909 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7910 
7911 	/*
7912 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7913 	 * here for uniformity
7914 	 */
7915 	ipif_refhold(ipif);
7916 
7917 	/*
7918 	 * This loop is run only once in most cases.
7919 	 * We loop to resolve further routes only when the destination
7920 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7921 	 */
7922 	do {
7923 		if (dst_ill != NULL) {
7924 			ill_refrele(dst_ill);
7925 			dst_ill = NULL;
7926 		}
7927 		if (src_ipif != NULL) {
7928 			ipif_refrele(src_ipif);
7929 			src_ipif = NULL;
7930 		}
7931 		multirt_resolve_next = B_FALSE;
7932 
7933 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7934 		    ipif->ipif_ill->ill_name));
7935 
7936 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7937 		if (mctl_present)
7938 			io = (ipsec_out_t *)first_mp->b_rptr;
7939 
7940 		ipha = (ipha_t *)mp->b_rptr;
7941 
7942 		/*
7943 		 * Save the packet destination address, we may need it after
7944 		 * the packet has been consumed.
7945 		 */
7946 		ipha_dst = ipha->ipha_dst;
7947 
7948 		/*
7949 		 * If the interface is a pt-pt interface we look for an
7950 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7951 		 * local_address and the pt-pt destination address. Otherwise
7952 		 * we just match the local address.
7953 		 * NOTE: dst could be different than ipha->ipha_dst in case
7954 		 * of sending igmp multicast packets over a point-to-point
7955 		 * connection.
7956 		 * Thus we must be careful enough to check ipha_dst to be a
7957 		 * multicast address, otherwise it will take xmit_if path for
7958 		 * multicast packets resulting into kernel stack overflow by
7959 		 * repeated calls to ip_newroute_ipif from ire_send().
7960 		 */
7961 		if (CLASSD(ipha_dst) &&
7962 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7963 			goto err_ret;
7964 		}
7965 
7966 		/*
7967 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7968 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7969 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7970 		 * propagate its flags to the new ire.
7971 		 */
7972 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7973 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7974 			ip2dbg(("ip_newroute_ipif: "
7975 			    "ipif_lookup_multi_ire("
7976 			    "ipif %p, dst %08x) = fire %p\n",
7977 			    (void *)ipif, ntohl(dst), (void *)fire));
7978 		}
7979 
7980 		if (mctl_present && io->ipsec_out_attach_if) {
7981 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7982 			    io->ipsec_out_ill_index, B_FALSE);
7983 
7984 			/* Failure case frees things for us. */
7985 			if (attach_ill == NULL) {
7986 				ipif_refrele(ipif);
7987 				if (fire != NULL)
7988 					ire_refrele(fire);
7989 				return;
7990 			}
7991 
7992 			/*
7993 			 * Check if we need an ire that will not be
7994 			 * looked up by anybody else i.e. HIDDEN.
7995 			 */
7996 			if (ill_is_probeonly(attach_ill)) {
7997 				ire_marks = IRE_MARK_HIDDEN;
7998 			}
7999 			/*
8000 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8001 			 * case.
8002 			 */
8003 			dst_ill = ipif->ipif_ill;
8004 			/* attach_ill has been refheld by ip_grab_attach_ill */
8005 			ASSERT(dst_ill == attach_ill);
8006 		} else {
8007 			/*
8008 			 * If this is set by IP_XMIT_IF, then make sure that
8009 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8010 			 * specified ill.
8011 			 */
8012 			ASSERT((connp == NULL) ||
8013 			    (connp->conn_xmit_if_ill == NULL) ||
8014 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8015 			/*
8016 			 * If the interface belongs to an interface group,
8017 			 * make sure the next possible interface in the group
8018 			 * is used.  This encourages load spreading among
8019 			 * peers in an interface group.
8020 			 * Note: load spreading is disabled for RTF_MULTIRT
8021 			 * routes.
8022 			 */
8023 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8024 			    (fire->ire_flags & RTF_MULTIRT)) {
8025 				/*
8026 				 * Don't perform outbound load spreading
8027 				 * in the case of an RTF_MULTIRT issued route,
8028 				 * we actually typically want to replicate
8029 				 * outgoing packets through particular
8030 				 * interfaces.
8031 				 */
8032 				dst_ill = ipif->ipif_ill;
8033 				ill_refhold(dst_ill);
8034 			} else {
8035 				dst_ill = ip_newroute_get_dst_ill(
8036 				    ipif->ipif_ill);
8037 			}
8038 			if (dst_ill == NULL) {
8039 				if (ip_debug > 2) {
8040 					pr_addr_dbg("ip_newroute_ipif: "
8041 					    "no dst ill for dst %s\n",
8042 					    AF_INET, &dst);
8043 				}
8044 				goto err_ret;
8045 			}
8046 		}
8047 
8048 		/*
8049 		 * Pick a source address preferring non-deprecated ones.
8050 		 * Unlike ip_newroute, we don't do any source address
8051 		 * selection here since for multicast it really does not help
8052 		 * in inbound load spreading as in the unicast case.
8053 		 */
8054 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8055 		    (fire->ire_flags & RTF_SETSRC)) {
8056 			/*
8057 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8058 			 * on that interface. This ire has RTF_SETSRC flag, so
8059 			 * the source address of the packet must be changed.
8060 			 * Check that the ipif matching the requested source
8061 			 * address still exists.
8062 			 */
8063 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8064 			    zoneid, NULL, NULL, NULL, NULL);
8065 		}
8066 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8067 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
8068 		    (src_ipif == NULL)) {
8069 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8070 			if (src_ipif == NULL) {
8071 				if (ip_debug > 2) {
8072 					/* ip1dbg */
8073 					pr_addr_dbg("ip_newroute_ipif: "
8074 					    "no src for dst %s",
8075 					    AF_INET, &dst);
8076 				}
8077 				ip1dbg((" through interface %s\n",
8078 				    dst_ill->ill_name));
8079 				goto err_ret;
8080 			}
8081 			ipif_refrele(ipif);
8082 			ipif = src_ipif;
8083 			ipif_refhold(ipif);
8084 		}
8085 		if (src_ipif == NULL) {
8086 			src_ipif = ipif;
8087 			ipif_refhold(src_ipif);
8088 		}
8089 
8090 		/*
8091 		 * Assign a source address while we have the conn.
8092 		 * We can't have ip_wput_ire pick a source address when the
8093 		 * packet returns from arp since conn_unspec_src might be set
8094 		 * and we loose the conn when going through arp.
8095 		 */
8096 		if (ipha->ipha_src == INADDR_ANY &&
8097 		    (connp == NULL || !connp->conn_unspec_src)) {
8098 			ipha->ipha_src = src_ipif->ipif_src_addr;
8099 		}
8100 
8101 		/*
8102 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8103 		 * interface does not have an interface ire.
8104 		 * Example: Thousands of mobileip PPP interfaces to mobile
8105 		 * nodes. We don't want to create interface ires because
8106 		 * packets from other mobile nodes must not take the route
8107 		 * via interface ires to the visiting mobile node without
8108 		 * going through the home agent, in absence of mobileip
8109 		 * route optimization.
8110 		 */
8111 		if (CLASSD(ipha_dst) && (connp == NULL ||
8112 		    connp->conn_xmit_if_ill == NULL)) {
8113 			/* ipif_to_ire returns an held ire */
8114 			ire = ipif_to_ire(ipif);
8115 			if (ire == NULL)
8116 				goto err_ret;
8117 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8118 				goto err_ret;
8119 			/*
8120 			 * ihandle is needed when the ire is added to
8121 			 * cache table.
8122 			 */
8123 			save_ire = ire;
8124 			ihandle = save_ire->ire_ihandle;
8125 
8126 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8127 			    "flags %04x\n",
8128 			    (void *)ire, (void *)ipif, flags));
8129 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8130 			    (fire->ire_flags & RTF_MULTIRT)) {
8131 				/*
8132 				 * As requested by flags, an IRE_OFFSUBNET was
8133 				 * looked up on that interface. This ire has
8134 				 * RTF_MULTIRT flag, so the resolution loop will
8135 				 * be re-entered to resolve additional routes on
8136 				 * other interfaces. For that purpose, a copy of
8137 				 * the packet is performed at this point.
8138 				 */
8139 				fire->ire_last_used_time = lbolt;
8140 				copy_mp = copymsg(first_mp);
8141 				if (copy_mp) {
8142 					MULTIRT_DEBUG_TAG(copy_mp);
8143 				}
8144 			}
8145 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8146 			    (fire->ire_flags & RTF_SETSRC)) {
8147 				/*
8148 				 * As requested by flags, an IRE_OFFSUBET was
8149 				 * looked up on that interface. This ire has
8150 				 * RTF_SETSRC flag, so the source address of the
8151 				 * packet must be changed.
8152 				 */
8153 				ipha->ipha_src = fire->ire_src_addr;
8154 			}
8155 		} else {
8156 			ASSERT((connp == NULL) ||
8157 			    (connp->conn_xmit_if_ill != NULL) ||
8158 			    (connp->conn_dontroute));
8159 			/*
8160 			 * The only ways we can come here are:
8161 			 * 1) IP_XMIT_IF socket option is set
8162 			 * 2) ICMP error message generated from
8163 			 *    ip_mrtun_forward() routine and it needs
8164 			 *    to go through the specified ill.
8165 			 * 3) SO_DONTROUTE socket option is set
8166 			 * In all cases, the new ire will not be added
8167 			 * into cache table.
8168 			 */
8169 			ire_marks |= IRE_MARK_NOADD;
8170 		}
8171 
8172 		switch (ipif->ipif_net_type) {
8173 		case IRE_IF_NORESOLVER: {
8174 			/* We have what we need to build an IRE_CACHE. */
8175 			mblk_t	*dlureq_mp;
8176 
8177 			/*
8178 			 * Create a new dlureq_mp with the
8179 			 * IP gateway address as destination address in the
8180 			 * DLPI hdr if the physical length is exactly 4 bytes.
8181 			 */
8182 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8183 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8184 				    dst_ill->ill_phys_addr_length,
8185 				    dst_ill->ill_sap,
8186 				    dst_ill->ill_sap_length);
8187 			} else {
8188 				/* use the value set in ip_ll_subnet_defaults */
8189 				dlureq_mp = ill_dlur_gen(NULL,
8190 				    dst_ill->ill_phys_addr_length,
8191 				    dst_ill->ill_sap,
8192 				    dst_ill->ill_sap_length);
8193 			}
8194 
8195 			if (dlureq_mp == NULL)
8196 				break;
8197 			/*
8198 			 * The new ire inherits the IRE_OFFSUBNET flags
8199 			 * and source address, if this was requested.
8200 			 */
8201 			ire = ire_create(
8202 			    (uchar_t *)&dst,		/* dest address */
8203 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8204 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8205 			    NULL,			/* gateway address */
8206 			    NULL,
8207 			    &ipif->ipif_mtu,
8208 			    NULL,			/* Fast Path header */
8209 			    dst_ill->ill_rq,		/* recv-from queue */
8210 			    dst_ill->ill_wq,		/* send-to queue */
8211 			    IRE_CACHE,
8212 			    dlureq_mp,
8213 			    src_ipif,
8214 			    NULL,
8215 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8216 			    (fire != NULL) ?		/* Parent handle */
8217 				fire->ire_phandle : 0,
8218 			    ihandle,			/* Interface handle */
8219 			    (fire != NULL) ?
8220 				(fire->ire_flags &
8221 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8222 			    (save_ire == NULL ? &ire_uinfo_null :
8223 				&save_ire->ire_uinfo));
8224 
8225 			freeb(dlureq_mp);
8226 
8227 			if (ire == NULL) {
8228 				if (save_ire != NULL)
8229 					ire_refrele(save_ire);
8230 				break;
8231 			}
8232 
8233 			ire->ire_marks |= ire_marks;
8234 
8235 			/* Prevent save_ire from getting deleted */
8236 			if (save_ire != NULL) {
8237 				IRB_REFHOLD(save_ire->ire_bucket);
8238 				/* Has it been removed already ? */
8239 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8240 					IRB_REFRELE(save_ire->ire_bucket);
8241 					ire_refrele(save_ire);
8242 					break;
8243 				}
8244 			}
8245 
8246 			ire_add_then_send(q, ire, first_mp);
8247 
8248 			/* Assert that save_ire is not deleted yet. */
8249 			if (save_ire != NULL) {
8250 				ASSERT(save_ire->ire_ptpn != NULL);
8251 				IRB_REFRELE(save_ire->ire_bucket);
8252 				ire_refrele(save_ire);
8253 				save_ire = NULL;
8254 			}
8255 			if (fire != NULL) {
8256 				ire_refrele(fire);
8257 				fire = NULL;
8258 			}
8259 
8260 			/*
8261 			 * the resolution loop is re-entered if this
8262 			 * was requested through flags and if we
8263 			 * actually are in a multirouting case.
8264 			 */
8265 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8266 				boolean_t need_resolve =
8267 				    ire_multirt_need_resolve(ipha_dst);
8268 				if (!need_resolve) {
8269 					MULTIRT_DEBUG_UNTAG(copy_mp);
8270 					freemsg(copy_mp);
8271 					copy_mp = NULL;
8272 				} else {
8273 					/*
8274 					 * ipif_lookup_group() calls
8275 					 * ire_lookup_multi() that uses
8276 					 * ire_ftable_lookup() to find
8277 					 * an IRE_INTERFACE for the group.
8278 					 * In the multirt case,
8279 					 * ire_lookup_multi() then invokes
8280 					 * ire_multirt_lookup() to find
8281 					 * the next resolvable ire.
8282 					 * As a result, we obtain an new
8283 					 * interface, derived from the
8284 					 * next ire.
8285 					 */
8286 					ipif_refrele(ipif);
8287 					ipif = ipif_lookup_group(ipha_dst,
8288 					    zoneid);
8289 					ip2dbg(("ip_newroute_ipif: "
8290 					    "multirt dst %08x, ipif %p\n",
8291 					    htonl(dst), (void *)ipif));
8292 					if (ipif != NULL) {
8293 						mp = copy_mp;
8294 						copy_mp = NULL;
8295 						multirt_resolve_next = B_TRUE;
8296 						continue;
8297 					} else {
8298 						freemsg(copy_mp);
8299 					}
8300 				}
8301 			}
8302 			if (ipif != NULL)
8303 				ipif_refrele(ipif);
8304 			ill_refrele(dst_ill);
8305 			ipif_refrele(src_ipif);
8306 			return;
8307 		}
8308 		case IRE_IF_RESOLVER:
8309 			/*
8310 			 * We can't build an IRE_CACHE yet, but at least
8311 			 * we found a resolver that can help.
8312 			 */
8313 			res_mp = dst_ill->ill_resolver_mp;
8314 			if (!OK_RESOLVER_MP(res_mp))
8315 				break;
8316 
8317 			/*
8318 			 * We obtain a partial IRE_CACHE which we will pass
8319 			 * along with the resolver query.  When the response
8320 			 * comes back it will be there ready for us to add.
8321 			 * The new ire inherits the IRE_OFFSUBNET flags
8322 			 * and source address, if this was requested.
8323 			 * The ire_max_frag is atomically set under the
8324 			 * irebucket lock in ire_add_v[46]. Only in the
8325 			 * case of IRE_MARK_NOADD, we set it here itself.
8326 			 */
8327 			ire = ire_create_mp(
8328 			    (uchar_t *)&dst,		/* dest address */
8329 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8330 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8331 			    NULL,			/* gateway address */
8332 			    NULL,			/* no in_src_addr */
8333 			    (ire_marks & IRE_MARK_NOADD) ?
8334 				ipif->ipif_mtu : 0,	/* max_frag */
8335 			    NULL,			/* Fast path header */
8336 			    dst_ill->ill_rq,		/* recv-from queue */
8337 			    dst_ill->ill_wq,		/* send-to queue */
8338 			    IRE_CACHE,
8339 			    res_mp,
8340 			    src_ipif,
8341 			    NULL,
8342 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8343 			    (fire != NULL) ?		/* Parent handle */
8344 				fire->ire_phandle : 0,
8345 			    ihandle,			/* Interface handle */
8346 			    (fire != NULL) ?		/* flags if any */
8347 				(fire->ire_flags &
8348 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8349 			    (save_ire == NULL ? &ire_uinfo_null :
8350 				&save_ire->ire_uinfo));
8351 
8352 			if (save_ire != NULL) {
8353 				ire_refrele(save_ire);
8354 				save_ire = NULL;
8355 			}
8356 			if (ire == NULL)
8357 				break;
8358 
8359 			ire->ire_marks |= ire_marks;
8360 			/*
8361 			 * Construct message chain for the resolver of the
8362 			 * form:
8363 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8364 			 *
8365 			 * NOTE : ire will be added later when the response
8366 			 * comes back from ARP. If the response does not
8367 			 * come back, ARP frees the packet. For this reason,
8368 			 * we can't REFHOLD the bucket of save_ire to prevent
8369 			 * deletions. We may not be able to REFRELE the
8370 			 * bucket if the response never comes back.
8371 			 * Thus, before adding the ire, ire_add_v4 will make
8372 			 * sure that the interface route does not get deleted.
8373 			 * This is the only case unlike ip_newroute_v6,
8374 			 * ip_newroute_ipif_v6 where we can always prevent
8375 			 * deletions because ire_add_then_send is called after
8376 			 * creating the IRE.
8377 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8378 			 * does not add this IRE into the IRE CACHE.
8379 			 */
8380 			ASSERT(ire->ire_mp != NULL);
8381 			ire->ire_mp->b_cont = first_mp;
8382 			/* Have saved_mp handy, for cleanup if canput fails */
8383 			saved_mp = mp;
8384 			mp = ire->ire_dlureq_mp;
8385 			ASSERT(mp != NULL);
8386 			ire->ire_dlureq_mp = NULL;
8387 			linkb(mp, ire->ire_mp);
8388 
8389 			/*
8390 			 * Fill in the source and dest addrs for the resolver.
8391 			 * NOTE: this depends on memory layouts imposed by
8392 			 * ill_init().
8393 			 */
8394 			areq = (areq_t *)mp->b_rptr;
8395 			addrp = (ipaddr_t *)((char *)areq +
8396 			    areq->areq_sender_addr_offset);
8397 			*addrp = ire->ire_src_addr;
8398 			addrp = (ipaddr_t *)((char *)areq +
8399 			    areq->areq_target_addr_offset);
8400 			*addrp = dst;
8401 			/* Up to the resolver. */
8402 			if (canputnext(dst_ill->ill_rq)) {
8403 				putnext(dst_ill->ill_rq, mp);
8404 				/*
8405 				 * The response will come back in ip_wput
8406 				 * with db_type IRE_DB_TYPE.
8407 				 */
8408 			} else {
8409 				ire->ire_dlureq_mp = mp;
8410 				mp->b_cont = NULL;
8411 				ire_delete(ire);
8412 				saved_mp->b_next = NULL;
8413 				saved_mp->b_prev = NULL;
8414 				freemsg(first_mp);
8415 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8416 			}
8417 
8418 			if (fire != NULL) {
8419 				ire_refrele(fire);
8420 				fire = NULL;
8421 			}
8422 
8423 
8424 			/*
8425 			 * The resolution loop is re-entered if this was
8426 			 * requested through flags and we actually are
8427 			 * in a multirouting case.
8428 			 */
8429 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8430 				boolean_t need_resolve =
8431 				    ire_multirt_need_resolve(ipha_dst);
8432 				if (!need_resolve) {
8433 					MULTIRT_DEBUG_UNTAG(copy_mp);
8434 					freemsg(copy_mp);
8435 					copy_mp = NULL;
8436 				} else {
8437 					/*
8438 					 * ipif_lookup_group() calls
8439 					 * ire_lookup_multi() that uses
8440 					 * ire_ftable_lookup() to find
8441 					 * an IRE_INTERFACE for the group.
8442 					 * In the multirt case,
8443 					 * ire_lookup_multi() then invokes
8444 					 * ire_multirt_lookup() to find
8445 					 * the next resolvable ire.
8446 					 * As a result, we obtain an new
8447 					 * interface, derived from the
8448 					 * next ire.
8449 					 */
8450 					ipif_refrele(ipif);
8451 					ipif = ipif_lookup_group(ipha_dst,
8452 					    zoneid);
8453 					if (ipif != NULL) {
8454 						mp = copy_mp;
8455 						copy_mp = NULL;
8456 						multirt_resolve_next = B_TRUE;
8457 						continue;
8458 					} else {
8459 						freemsg(copy_mp);
8460 					}
8461 				}
8462 			}
8463 			if (ipif != NULL)
8464 				ipif_refrele(ipif);
8465 			ill_refrele(dst_ill);
8466 			ipif_refrele(src_ipif);
8467 			return;
8468 		default:
8469 			break;
8470 		}
8471 	} while (multirt_resolve_next);
8472 
8473 err_ret:
8474 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8475 	if (fire != NULL)
8476 		ire_refrele(fire);
8477 	ipif_refrele(ipif);
8478 	/* Did this packet originate externally? */
8479 	if (dst_ill != NULL)
8480 		ill_refrele(dst_ill);
8481 	if (src_ipif != NULL)
8482 		ipif_refrele(src_ipif);
8483 	if (mp->b_prev || mp->b_next) {
8484 		mp->b_next = NULL;
8485 		mp->b_prev = NULL;
8486 	} else {
8487 		/*
8488 		 * Since ip_wput() isn't close to finished, we fill
8489 		 * in enough of the header for credible error reporting.
8490 		 */
8491 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8492 			/* Failed */
8493 			freemsg(first_mp);
8494 			if (ire != NULL)
8495 				ire_refrele(ire);
8496 			return;
8497 		}
8498 	}
8499 	/*
8500 	 * At this point we will have ire only if RTF_BLACKHOLE
8501 	 * or RTF_REJECT flags are set on the IRE. It will not
8502 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8503 	 */
8504 	if (ire != NULL) {
8505 		if (ire->ire_flags & RTF_BLACKHOLE) {
8506 			ire_refrele(ire);
8507 			freemsg(first_mp);
8508 			return;
8509 		}
8510 		ire_refrele(ire);
8511 	}
8512 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8513 }
8514 
8515 /* Name/Value Table Lookup Routine */
8516 char *
8517 ip_nv_lookup(nv_t *nv, int value)
8518 {
8519 	if (!nv)
8520 		return (NULL);
8521 	for (; nv->nv_name; nv++) {
8522 		if (nv->nv_value == value)
8523 			return (nv->nv_name);
8524 	}
8525 	return ("unknown");
8526 }
8527 
8528 /*
8529  * one day it can be patched to 1 from /etc/system for machines that have few
8530  * fast network interfaces feeding multiple cpus.
8531  */
8532 int ill_stream_putlocks = 0;
8533 
8534 /*
8535  * This is a module open, i.e. this is a control stream for access
8536  * to a DLPI device.  We allocate an ill_t as the instance data in
8537  * this case.
8538  */
8539 int
8540 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8541 {
8542 	uint32_t mem_cnt;
8543 	uint32_t cpu_cnt;
8544 	uint32_t min_cnt;
8545 	pgcnt_t mem_avail;
8546 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8547 	ill_t	*ill;
8548 	int	err;
8549 
8550 	/*
8551 	 * Prevent unprivileged processes from pushing IP so that
8552 	 * they can't send raw IP.
8553 	 */
8554 	if (secpolicy_net_rawaccess(credp) != 0)
8555 		return (EPERM);
8556 
8557 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8558 	q->q_ptr = WR(q)->q_ptr = ill;
8559 
8560 	/*
8561 	 * ill_init initializes the ill fields and then sends down
8562 	 * down a DL_INFO_REQ after calling qprocson.
8563 	 */
8564 	err = ill_init(q, ill);
8565 	if (err != 0) {
8566 		mi_free(ill);
8567 		q->q_ptr = NULL;
8568 		WR(q)->q_ptr = NULL;
8569 		return (err);
8570 	}
8571 
8572 	/* ill_init initializes the ipsq marking this thread as writer */
8573 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8574 	/* Wait for the DL_INFO_ACK */
8575 	mutex_enter(&ill->ill_lock);
8576 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8577 		/*
8578 		 * Return value of 0 indicates a pending signal.
8579 		 */
8580 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8581 		if (err == 0) {
8582 			mutex_exit(&ill->ill_lock);
8583 			(void) ip_close(q, 0);
8584 			return (EINTR);
8585 		}
8586 	}
8587 	mutex_exit(&ill->ill_lock);
8588 
8589 	/*
8590 	 * ip_rput_other could have set an error  in ill_error on
8591 	 * receipt of M_ERROR.
8592 	 */
8593 
8594 	err = ill->ill_error;
8595 	if (err != 0) {
8596 		(void) ip_close(q, 0);
8597 		return (err);
8598 	}
8599 
8600 	/*
8601 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8602 	 * size and the cpu speed of the machine. This is upper
8603 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8604 	 * and is lower bounded by the compile time value of
8605 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8606 	 * ip6_ire_max_bucket_cnt.
8607 	 */
8608 	mem_avail = kmem_avail();
8609 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8610 	    ip_cache_table_size / sizeof (ire_t);
8611 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8612 
8613 	min_cnt = MIN(cpu_cnt, mem_cnt);
8614 	if (min_cnt < ip_ire_min_bucket_cnt)
8615 		min_cnt = ip_ire_min_bucket_cnt;
8616 	if (ip_ire_max_bucket_cnt > min_cnt) {
8617 		ip_ire_max_bucket_cnt = min_cnt;
8618 	}
8619 
8620 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8621 	    ip6_cache_table_size / sizeof (ire_t);
8622 	min_cnt = MIN(cpu_cnt, mem_cnt);
8623 	if (min_cnt < ip6_ire_min_bucket_cnt)
8624 		min_cnt = ip6_ire_min_bucket_cnt;
8625 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8626 		ip6_ire_max_bucket_cnt = min_cnt;
8627 	}
8628 
8629 	ill->ill_credp = credp;
8630 	crhold(credp);
8631 
8632 	mutex_enter(&ip_mi_lock);
8633 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8634 	mutex_exit(&ip_mi_lock);
8635 	if (err) {
8636 		(void) ip_close(q, 0);
8637 		return (err);
8638 	}
8639 	return (0);
8640 }
8641 
8642 /* IP open routine. */
8643 int
8644 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8645 {
8646 	conn_t 		*connp;
8647 	major_t		maj;
8648 
8649 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8650 
8651 	/* Allow reopen. */
8652 	if (q->q_ptr != NULL)
8653 		return (0);
8654 
8655 	if (sflag & MODOPEN) {
8656 		/* This is a module open */
8657 		return (ip_modopen(q, devp, flag, sflag, credp));
8658 	}
8659 
8660 	/*
8661 	 * We are opening as a device. This is an IP client stream, and we
8662 	 * allocate an conn_t as the instance data.
8663 	 */
8664 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8665 	connp->conn_upq = q;
8666 	q->q_ptr = WR(q)->q_ptr = connp;
8667 
8668 	if (flag & SO_SOCKSTR)
8669 		connp->conn_flags |= IPCL_SOCKET;
8670 
8671 	/* Minor tells us which /dev entry was opened */
8672 	if (geteminor(*devp) == IPV6_MINOR) {
8673 		connp->conn_flags |= IPCL_ISV6;
8674 		connp->conn_af_isv6 = B_TRUE;
8675 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8676 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8677 	} else {
8678 		connp->conn_af_isv6 = B_FALSE;
8679 		connp->conn_pkt_isv6 = B_FALSE;
8680 	}
8681 
8682 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
8683 		q->q_ptr = WR(q)->q_ptr = NULL;
8684 		CONN_DEC_REF(connp);
8685 		return (EBUSY);
8686 	}
8687 
8688 	maj = getemajor(*devp);
8689 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8690 
8691 	/*
8692 	 * connp->conn_cred is crfree()ed in ip_close().
8693 	 */
8694 	connp->conn_cred = credp;
8695 	crhold(connp->conn_cred);
8696 
8697 	connp->conn_zoneid = getzoneid();
8698 
8699 	/*
8700 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8701 	 * administrative ops.  In these cases, we just need a normal conn_t
8702 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8703 	 * an error will be returned.
8704 	 */
8705 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8706 		connp->conn_rq = q;
8707 		connp->conn_wq = WR(q);
8708 	} else {
8709 		connp->conn_ulp = IPPROTO_SCTP;
8710 		connp->conn_rq = connp->conn_wq = NULL;
8711 	}
8712 	/* Non-zero default values */
8713 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8714 
8715 	/*
8716 	 * Make the conn globally visible to walkers
8717 	 */
8718 	mutex_enter(&connp->conn_lock);
8719 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8720 	mutex_exit(&connp->conn_lock);
8721 	ASSERT(connp->conn_ref == 1);
8722 
8723 	qprocson(q);
8724 
8725 	return (0);
8726 }
8727 
8728 /*
8729  * Change q_qinfo based on the value of isv6.
8730  * This can not called on an ill queue.
8731  * Note that there is no race since either q_qinfo works for conn queues - it
8732  * is just an optimization to enter the best wput routine directly.
8733  */
8734 void
8735 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8736 {
8737 	ASSERT(q->q_flag & QREADR);
8738 	ASSERT(WR(q)->q_next == NULL);
8739 	ASSERT(q->q_ptr != NULL);
8740 
8741 	if (minor == IPV6_MINOR)  {
8742 		if (bump_mib)
8743 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8744 		q->q_qinfo = &rinit_ipv6;
8745 		WR(q)->q_qinfo = &winit_ipv6;
8746 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8747 	} else {
8748 		if (bump_mib)
8749 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8750 		q->q_qinfo = &rinit;
8751 		WR(q)->q_qinfo = &winit;
8752 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8753 	}
8754 
8755 }
8756 
8757 /*
8758  * See if IPsec needs loading because of the options in mp.
8759  */
8760 static boolean_t
8761 ipsec_opt_present(mblk_t *mp)
8762 {
8763 	uint8_t *optcp, *next_optcp, *opt_endcp;
8764 	struct opthdr *opt;
8765 	struct T_opthdr *topt;
8766 	int opthdr_len;
8767 	t_uscalar_t optname, optlevel;
8768 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8769 	ipsec_req_t *ipsr;
8770 
8771 	/*
8772 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8773 	 * return TRUE.
8774 	 */
8775 
8776 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8777 	opt_endcp = optcp + tor->OPT_length;
8778 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8779 		opthdr_len = sizeof (struct T_opthdr);
8780 	} else {		/* O_OPTMGMT_REQ */
8781 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8782 		opthdr_len = sizeof (struct opthdr);
8783 	}
8784 	for (; optcp < opt_endcp; optcp = next_optcp) {
8785 		if (optcp + opthdr_len > opt_endcp)
8786 			return (B_FALSE);	/* Not enough option header. */
8787 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8788 			topt = (struct T_opthdr *)optcp;
8789 			optlevel = topt->level;
8790 			optname = topt->name;
8791 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8792 		} else {
8793 			opt = (struct opthdr *)optcp;
8794 			optlevel = opt->level;
8795 			optname = opt->name;
8796 			next_optcp = optcp + opthdr_len +
8797 			    _TPI_ALIGN_OPT(opt->len);
8798 		}
8799 		if ((next_optcp < optcp) || /* wraparound pointer space */
8800 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8801 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8802 			return (B_FALSE); /* bad option buffer */
8803 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8804 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8805 			/*
8806 			 * Check to see if it's an all-bypass or all-zeroes
8807 			 * IPsec request.  Don't bother loading IPsec if
8808 			 * the socket doesn't want to use it.  (A good example
8809 			 * is a bypass request.)
8810 			 *
8811 			 * Basically, if any of the non-NEVER bits are set,
8812 			 * load IPsec.
8813 			 */
8814 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8815 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8816 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8817 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8818 			    != 0)
8819 				return (B_TRUE);
8820 		}
8821 	}
8822 	return (B_FALSE);
8823 }
8824 
8825 /*
8826  * If conn is is waiting for ipsec to finish loading, kick it.
8827  */
8828 /* ARGSUSED */
8829 static void
8830 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8831 {
8832 	t_scalar_t	optreq_prim;
8833 	mblk_t		*mp;
8834 	cred_t		*cr;
8835 	int		err = 0;
8836 
8837 	/*
8838 	 * This function is called, after ipsec loading is complete.
8839 	 * Since IP checks exclusively and atomically (i.e it prevents
8840 	 * ipsec load from completing until ip_optcom_req completes)
8841 	 * whether ipsec load is complete, there cannot be a race with IP
8842 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8843 	 */
8844 	mutex_enter(&connp->conn_lock);
8845 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8846 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8847 		mp = connp->conn_ipsec_opt_mp;
8848 		connp->conn_ipsec_opt_mp = NULL;
8849 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8850 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8851 		mutex_exit(&connp->conn_lock);
8852 
8853 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8854 
8855 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8856 		if (optreq_prim == T_OPTMGMT_REQ) {
8857 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8858 			    &ip_opt_obj);
8859 		} else {
8860 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8861 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8862 			    &ip_opt_obj);
8863 		}
8864 		if (err != EINPROGRESS)
8865 			CONN_OPER_PENDING_DONE(connp);
8866 		return;
8867 	}
8868 	mutex_exit(&connp->conn_lock);
8869 }
8870 
8871 /*
8872  * Called from the ipsec_loader thread, outside any perimeter, to tell
8873  * ip qenable any of the queues waiting for the ipsec loader to
8874  * complete.
8875  *
8876  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8877  * are done with this lock held, so it's guaranteed that none of the
8878  * links will change along the way.
8879  */
8880 void
8881 ip_ipsec_load_complete()
8882 {
8883 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8884 }
8885 
8886 /*
8887  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8888  * determines the grp on which it has to become exclusive, queues the mp
8889  * and sq draining restarts the optmgmt
8890  */
8891 static boolean_t
8892 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8893 {
8894 	conn_t *connp;
8895 
8896 	/*
8897 	 * Take IPsec requests and treat them special.
8898 	 */
8899 	if (ipsec_opt_present(mp)) {
8900 		/* First check if IPsec is loaded. */
8901 		mutex_enter(&ipsec_loader_lock);
8902 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8903 			mutex_exit(&ipsec_loader_lock);
8904 			return (B_FALSE);
8905 		}
8906 		connp = Q_TO_CONN(q);
8907 		mutex_enter(&connp->conn_lock);
8908 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8909 
8910 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8911 		connp->conn_ipsec_opt_mp = mp;
8912 		mutex_exit(&connp->conn_lock);
8913 		mutex_exit(&ipsec_loader_lock);
8914 
8915 		ipsec_loader_loadnow();
8916 		return (B_TRUE);
8917 	}
8918 	return (B_FALSE);
8919 }
8920 
8921 /*
8922  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8923  * all of them are copied to the conn_t. If the req is "zero", the policy is
8924  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8925  * fields.
8926  * We keep only the latest setting of the policy and thus policy setting
8927  * is not incremental/cumulative.
8928  *
8929  * Requests to set policies with multiple alternative actions will
8930  * go through a different API.
8931  */
8932 int
8933 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8934 {
8935 	uint_t ah_req = 0;
8936 	uint_t esp_req = 0;
8937 	uint_t se_req = 0;
8938 	ipsec_selkey_t sel;
8939 	ipsec_act_t *actp = NULL;
8940 	uint_t nact;
8941 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8942 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8943 	ipsec_policy_root_t *pr;
8944 	ipsec_policy_head_t *ph;
8945 	int fam;
8946 	boolean_t is_pol_reset;
8947 	int error = 0;
8948 
8949 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8950 
8951 	/*
8952 	 * The IP_SEC_OPT option does not allow variable length parameters,
8953 	 * hence a request cannot be NULL.
8954 	 */
8955 	if (req == NULL)
8956 		return (EINVAL);
8957 
8958 	ah_req = req->ipsr_ah_req;
8959 	esp_req = req->ipsr_esp_req;
8960 	se_req = req->ipsr_self_encap_req;
8961 
8962 	/*
8963 	 * Are we dealing with a request to reset the policy (i.e.
8964 	 * zero requests).
8965 	 */
8966 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8967 	    (esp_req & REQ_MASK) == 0 &&
8968 	    (se_req & REQ_MASK) == 0);
8969 
8970 	if (!is_pol_reset) {
8971 		/*
8972 		 * If we couldn't load IPsec, fail with "protocol
8973 		 * not supported".
8974 		 * IPsec may not have been loaded for a request with zero
8975 		 * policies, so we don't fail in this case.
8976 		 */
8977 		mutex_enter(&ipsec_loader_lock);
8978 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8979 			mutex_exit(&ipsec_loader_lock);
8980 			return (EPROTONOSUPPORT);
8981 		}
8982 		mutex_exit(&ipsec_loader_lock);
8983 
8984 		/*
8985 		 * Test for valid requests. Invalid algorithms
8986 		 * need to be tested by IPSEC code because new
8987 		 * algorithms can be added dynamically.
8988 		 */
8989 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8990 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8991 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8992 			return (EINVAL);
8993 		}
8994 
8995 		/*
8996 		 * Only privileged users can issue these
8997 		 * requests.
8998 		 */
8999 		if (((ah_req & IPSEC_PREF_NEVER) ||
9000 		    (esp_req & IPSEC_PREF_NEVER) ||
9001 		    (se_req & IPSEC_PREF_NEVER)) &&
9002 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9003 			return (EPERM);
9004 		}
9005 
9006 		/*
9007 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9008 		 * are mutually exclusive.
9009 		 */
9010 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9011 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9012 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9013 			/* Both of them are set */
9014 			return (EINVAL);
9015 		}
9016 	}
9017 
9018 	mutex_enter(&connp->conn_lock);
9019 
9020 	/*
9021 	 * If we have already cached policies in ip_bind_connected*(), don't
9022 	 * let them change now. We cache policies for connections
9023 	 * whose src,dst [addr, port] is known.  The exception to this is
9024 	 * tunnels.  Tunnels are allowed to change policies after having
9025 	 * become fully bound.
9026 	 */
9027 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9028 		mutex_exit(&connp->conn_lock);
9029 		return (EINVAL);
9030 	}
9031 
9032 	/*
9033 	 * We have a zero policies, reset the connection policy if already
9034 	 * set. This will cause the connection to inherit the
9035 	 * global policy, if any.
9036 	 */
9037 	if (is_pol_reset) {
9038 		if (connp->conn_policy != NULL) {
9039 			IPPH_REFRELE(connp->conn_policy);
9040 			connp->conn_policy = NULL;
9041 		}
9042 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9043 		connp->conn_in_enforce_policy = B_FALSE;
9044 		connp->conn_out_enforce_policy = B_FALSE;
9045 		mutex_exit(&connp->conn_lock);
9046 		return (0);
9047 	}
9048 
9049 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9050 	if (ph == NULL)
9051 		goto enomem;
9052 
9053 	ipsec_actvec_from_req(req, &actp, &nact);
9054 	if (actp == NULL)
9055 		goto enomem;
9056 
9057 	/*
9058 	 * Always allocate IPv4 policy entries, since they can also
9059 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9060 	 */
9061 	bzero(&sel, sizeof (sel));
9062 	sel.ipsl_valid = IPSL_IPV4;
9063 
9064 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9065 	if (pin4 == NULL)
9066 		goto enomem;
9067 
9068 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9069 	if (pout4 == NULL)
9070 		goto enomem;
9071 
9072 	if (connp->conn_pkt_isv6) {
9073 		/*
9074 		 * We're looking at a v6 socket, also allocate the
9075 		 * v6-specific entries...
9076 		 */
9077 		sel.ipsl_valid = IPSL_IPV6;
9078 		pin6 = ipsec_policy_create(&sel, actp, nact,
9079 		    IPSEC_PRIO_SOCKET);
9080 		if (pin6 == NULL)
9081 			goto enomem;
9082 
9083 		pout6 = ipsec_policy_create(&sel, actp, nact,
9084 		    IPSEC_PRIO_SOCKET);
9085 		if (pout6 == NULL)
9086 			goto enomem;
9087 
9088 		/*
9089 		 * .. and file them away in the right place.
9090 		 */
9091 		fam = IPSEC_AF_V6;
9092 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9093 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9094 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9095 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9096 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9097 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9098 	}
9099 
9100 	ipsec_actvec_free(actp, nact);
9101 
9102 	/*
9103 	 * File the v4 policies.
9104 	 */
9105 	fam = IPSEC_AF_V4;
9106 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9107 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9108 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9109 
9110 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9111 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9112 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9113 
9114 	/*
9115 	 * If the requests need security, set enforce_policy.
9116 	 * If the requests are IPSEC_PREF_NEVER, one should
9117 	 * still set conn_out_enforce_policy so that an ipsec_out
9118 	 * gets attached in ip_wput. This is needed so that
9119 	 * for connections that we don't cache policy in ip_bind,
9120 	 * if global policy matches in ip_wput_attach_policy, we
9121 	 * don't wrongly inherit global policy. Similarly, we need
9122 	 * to set conn_in_enforce_policy also so that we don't verify
9123 	 * policy wrongly.
9124 	 */
9125 	if ((ah_req & REQ_MASK) != 0 ||
9126 	    (esp_req & REQ_MASK) != 0 ||
9127 	    (se_req & REQ_MASK) != 0) {
9128 		connp->conn_in_enforce_policy = B_TRUE;
9129 		connp->conn_out_enforce_policy = B_TRUE;
9130 		connp->conn_flags |= IPCL_CHECK_POLICY;
9131 	}
9132 
9133 	/*
9134 	 * Tunnels are allowed to set policy after having been fully bound.
9135 	 * If that's the case, cache policy here.
9136 	 */
9137 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9138 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9139 
9140 	mutex_exit(&connp->conn_lock);
9141 	return (error);
9142 #undef REQ_MASK
9143 
9144 	/*
9145 	 * Common memory-allocation-failure exit path.
9146 	 */
9147 enomem:
9148 	mutex_exit(&connp->conn_lock);
9149 	if (actp != NULL)
9150 		ipsec_actvec_free(actp, nact);
9151 	if (pin4 != NULL)
9152 		IPPOL_REFRELE(pin4);
9153 	if (pout4 != NULL)
9154 		IPPOL_REFRELE(pout4);
9155 	if (pin6 != NULL)
9156 		IPPOL_REFRELE(pin6);
9157 	if (pout6 != NULL)
9158 		IPPOL_REFRELE(pout6);
9159 	return (ENOMEM);
9160 }
9161 
9162 /*
9163  * Only for options that pass in an IP addr. Currently only V4 options
9164  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9165  * So this function assumes level is IPPROTO_IP
9166  */
9167 int
9168 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9169     mblk_t *first_mp)
9170 {
9171 	ipif_t *ipif = NULL;
9172 	int error;
9173 	ill_t *ill;
9174 
9175 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9176 
9177 	if (addr != INADDR_ANY || checkonly) {
9178 		ASSERT(connp != NULL);
9179 		if (option == IP_NEXTHOP) {
9180 			ipif =
9181 			    ipif_lookup_onlink_addr(addr, connp->conn_zoneid);
9182 		} else {
9183 			ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9184 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9185 			    &error);
9186 		}
9187 		if (ipif == NULL) {
9188 			if (error == EINPROGRESS)
9189 				return (error);
9190 			else if ((option == IP_MULTICAST_IF) ||
9191 			    (option == IP_NEXTHOP))
9192 				return (EHOSTUNREACH);
9193 			else
9194 				return (EINVAL);
9195 		} else if (checkonly) {
9196 			if (option == IP_MULTICAST_IF) {
9197 				ill = ipif->ipif_ill;
9198 				/* not supported by the virtual network iface */
9199 				if (IS_VNI(ill)) {
9200 					ipif_refrele(ipif);
9201 					return (EINVAL);
9202 				}
9203 			}
9204 			ipif_refrele(ipif);
9205 			return (0);
9206 		}
9207 		ill = ipif->ipif_ill;
9208 		mutex_enter(&connp->conn_lock);
9209 		mutex_enter(&ill->ill_lock);
9210 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9211 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9212 			mutex_exit(&ill->ill_lock);
9213 			mutex_exit(&connp->conn_lock);
9214 			ipif_refrele(ipif);
9215 			return (option == IP_MULTICAST_IF ?
9216 			    EHOSTUNREACH : EINVAL);
9217 		}
9218 	} else {
9219 		mutex_enter(&connp->conn_lock);
9220 	}
9221 
9222 	/* None of the options below are supported on the VNI */
9223 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9224 		mutex_exit(&ill->ill_lock);
9225 		mutex_exit(&connp->conn_lock);
9226 		ipif_refrele(ipif);
9227 		return (EINVAL);
9228 	}
9229 
9230 	switch (option) {
9231 	case IP_DONTFAILOVER_IF:
9232 		/*
9233 		 * This option is used by in.mpathd to ensure
9234 		 * that IPMP probe packets only go out on the
9235 		 * test interfaces. in.mpathd sets this option
9236 		 * on the non-failover interfaces.
9237 		 * For backward compatibility, this option
9238 		 * implicitly sets IP_MULTICAST_IF, as used
9239 		 * be done in bind(), so that ip_wput gets
9240 		 * this ipif to send mcast packets.
9241 		 */
9242 		if (ipif != NULL) {
9243 			ASSERT(addr != INADDR_ANY);
9244 			connp->conn_nofailover_ill = ipif->ipif_ill;
9245 			connp->conn_multicast_ipif = ipif;
9246 		} else {
9247 			ASSERT(addr == INADDR_ANY);
9248 			connp->conn_nofailover_ill = NULL;
9249 			connp->conn_multicast_ipif = NULL;
9250 		}
9251 		break;
9252 
9253 	case IP_MULTICAST_IF:
9254 		connp->conn_multicast_ipif = ipif;
9255 		break;
9256 	case IP_NEXTHOP:
9257 		connp->conn_nexthop_v4 = addr;
9258 		connp->conn_nexthop_set = B_TRUE;
9259 		break;
9260 	}
9261 
9262 	if (ipif != NULL) {
9263 		mutex_exit(&ill->ill_lock);
9264 		mutex_exit(&connp->conn_lock);
9265 		ipif_refrele(ipif);
9266 		return (0);
9267 	}
9268 	mutex_exit(&connp->conn_lock);
9269 	/* We succeded in cleared the option */
9270 	return (0);
9271 }
9272 
9273 /*
9274  * For options that pass in an ifindex specifying the ill. V6 options always
9275  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9276  */
9277 int
9278 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9279     int level, int option, mblk_t *first_mp)
9280 {
9281 	ill_t *ill = NULL;
9282 	int error = 0;
9283 
9284 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9285 	if (ifindex != 0) {
9286 		ASSERT(connp != NULL);
9287 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9288 		    first_mp, ip_restart_optmgmt, &error);
9289 		if (ill != NULL) {
9290 			if (checkonly) {
9291 				/* not supported by the virtual network iface */
9292 				if (IS_VNI(ill)) {
9293 					ill_refrele(ill);
9294 					return (EINVAL);
9295 				}
9296 				ill_refrele(ill);
9297 				return (0);
9298 			}
9299 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9300 			    0, NULL)) {
9301 				ill_refrele(ill);
9302 				ill = NULL;
9303 				mutex_enter(&connp->conn_lock);
9304 				goto setit;
9305 			}
9306 			mutex_enter(&connp->conn_lock);
9307 			mutex_enter(&ill->ill_lock);
9308 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9309 				mutex_exit(&ill->ill_lock);
9310 				mutex_exit(&connp->conn_lock);
9311 				ill_refrele(ill);
9312 				ill = NULL;
9313 				mutex_enter(&connp->conn_lock);
9314 			}
9315 			goto setit;
9316 		} else if (error == EINPROGRESS) {
9317 			return (error);
9318 		} else {
9319 			error = 0;
9320 		}
9321 	}
9322 	mutex_enter(&connp->conn_lock);
9323 setit:
9324 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9325 
9326 	/*
9327 	 * The options below assume that the ILL (if any) transmits and/or
9328 	 * receives traffic. Neither of which is true for the virtual network
9329 	 * interface, so fail setting these on a VNI.
9330 	 */
9331 	if (IS_VNI(ill)) {
9332 		ASSERT(ill != NULL);
9333 		mutex_exit(&ill->ill_lock);
9334 		mutex_exit(&connp->conn_lock);
9335 		ill_refrele(ill);
9336 		return (EINVAL);
9337 	}
9338 
9339 	if (level == IPPROTO_IP) {
9340 		switch (option) {
9341 		case IP_BOUND_IF:
9342 			connp->conn_incoming_ill = ill;
9343 			connp->conn_outgoing_ill = ill;
9344 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9345 			    0 : ifindex;
9346 			break;
9347 
9348 		case IP_XMIT_IF:
9349 			/*
9350 			 * Similar to IP_BOUND_IF, but this only
9351 			 * determines the outgoing interface for
9352 			 * unicast packets. Also no IRE_CACHE entry
9353 			 * is added for the destination of the
9354 			 * outgoing packets. This feature is needed
9355 			 * for mobile IP.
9356 			 */
9357 			connp->conn_xmit_if_ill = ill;
9358 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9359 			    0 : ifindex;
9360 			break;
9361 
9362 		case IP_MULTICAST_IF:
9363 			/*
9364 			 * This option is an internal special. The socket
9365 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9366 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9367 			 * specifies an ifindex and we try first on V6 ill's.
9368 			 * If we don't find one, we they try using on v4 ill's
9369 			 * intenally and we come here.
9370 			 */
9371 			if (!checkonly && ill != NULL) {
9372 				ipif_t	*ipif;
9373 				ipif = ill->ill_ipif;
9374 
9375 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9376 					mutex_exit(&ill->ill_lock);
9377 					mutex_exit(&connp->conn_lock);
9378 					ill_refrele(ill);
9379 					ill = NULL;
9380 					mutex_enter(&connp->conn_lock);
9381 				} else {
9382 					connp->conn_multicast_ipif = ipif;
9383 				}
9384 			}
9385 			break;
9386 		}
9387 	} else {
9388 		switch (option) {
9389 		case IPV6_BOUND_IF:
9390 			connp->conn_incoming_ill = ill;
9391 			connp->conn_outgoing_ill = ill;
9392 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9393 			    0 : ifindex;
9394 			break;
9395 
9396 		case IPV6_BOUND_PIF:
9397 			/*
9398 			 * Limit all transmit to this ill.
9399 			 * Unlike IPV6_BOUND_IF, using this option
9400 			 * prevents load spreading and failover from
9401 			 * happening when the interface is part of the
9402 			 * group. That's why we don't need to remember
9403 			 * the ifindex in orig_bound_ifindex as in
9404 			 * IPV6_BOUND_IF.
9405 			 */
9406 			connp->conn_outgoing_pill = ill;
9407 			break;
9408 
9409 		case IPV6_DONTFAILOVER_IF:
9410 			/*
9411 			 * This option is used by in.mpathd to ensure
9412 			 * that IPMP probe packets only go out on the
9413 			 * test interfaces. in.mpathd sets this option
9414 			 * on the non-failover interfaces.
9415 			 */
9416 			connp->conn_nofailover_ill = ill;
9417 			/*
9418 			 * For backward compatibility, this option
9419 			 * implicitly sets ip_multicast_ill as used in
9420 			 * IP_MULTICAST_IF so that ip_wput gets
9421 			 * this ipif to send mcast packets.
9422 			 */
9423 			connp->conn_multicast_ill = ill;
9424 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9425 			    0 : ifindex;
9426 			break;
9427 
9428 		case IPV6_MULTICAST_IF:
9429 			/*
9430 			 * Set conn_multicast_ill to be the IPv6 ill.
9431 			 * Set conn_multicast_ipif to be an IPv4 ipif
9432 			 * for ifindex to make IPv4 mapped addresses
9433 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9434 			 * Even if no IPv6 ill exists for the ifindex
9435 			 * we need to check for an IPv4 ifindex in order
9436 			 * for this to work with mapped addresses. In that
9437 			 * case only set conn_multicast_ipif.
9438 			 */
9439 			if (!checkonly) {
9440 				if (ifindex == 0) {
9441 					connp->conn_multicast_ill = NULL;
9442 					connp->conn_orig_multicast_ifindex = 0;
9443 					connp->conn_multicast_ipif = NULL;
9444 				} else if (ill != NULL) {
9445 					connp->conn_multicast_ill = ill;
9446 					connp->conn_orig_multicast_ifindex =
9447 					    ifindex;
9448 				}
9449 			}
9450 			break;
9451 		}
9452 	}
9453 
9454 	if (ill != NULL) {
9455 		mutex_exit(&ill->ill_lock);
9456 		mutex_exit(&connp->conn_lock);
9457 		ill_refrele(ill);
9458 		return (0);
9459 	}
9460 	mutex_exit(&connp->conn_lock);
9461 	/*
9462 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9463 	 * locate the ill and could not set the option (ifindex != 0)
9464 	 */
9465 	return (ifindex == 0 ? 0 : EINVAL);
9466 }
9467 
9468 /* This routine sets socket options. */
9469 /* ARGSUSED */
9470 int
9471 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9472     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9473     void *dummy, cred_t *cr, mblk_t *first_mp)
9474 {
9475 	int		*i1 = (int *)invalp;
9476 	conn_t		*connp = Q_TO_CONN(q);
9477 	int		error = 0;
9478 	boolean_t	checkonly;
9479 	ire_t		*ire;
9480 	boolean_t	found;
9481 
9482 	switch (optset_context) {
9483 
9484 	case SETFN_OPTCOM_CHECKONLY:
9485 		checkonly = B_TRUE;
9486 		/*
9487 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9488 		 * inlen != 0 implies value supplied and
9489 		 * 	we have to "pretend" to set it.
9490 		 * inlen == 0 implies that there is no
9491 		 * 	value part in T_CHECK request and just validation
9492 		 * done elsewhere should be enough, we just return here.
9493 		 */
9494 		if (inlen == 0) {
9495 			*outlenp = 0;
9496 			return (0);
9497 		}
9498 		break;
9499 	case SETFN_OPTCOM_NEGOTIATE:
9500 	case SETFN_UD_NEGOTIATE:
9501 	case SETFN_CONN_NEGOTIATE:
9502 		checkonly = B_FALSE;
9503 		break;
9504 	default:
9505 		/*
9506 		 * We should never get here
9507 		 */
9508 		*outlenp = 0;
9509 		return (EINVAL);
9510 	}
9511 
9512 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9513 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9514 
9515 	/*
9516 	 * For fixed length options, no sanity check
9517 	 * of passed in length is done. It is assumed *_optcom_req()
9518 	 * routines do the right thing.
9519 	 */
9520 
9521 	switch (level) {
9522 	case SOL_SOCKET:
9523 		/*
9524 		 * conn_lock protects the bitfields, and is used to
9525 		 * set the fields atomically.
9526 		 */
9527 		switch (name) {
9528 		case SO_BROADCAST:
9529 			if (!checkonly) {
9530 				/* TODO: use value someplace? */
9531 				mutex_enter(&connp->conn_lock);
9532 				connp->conn_broadcast = *i1 ? 1 : 0;
9533 				mutex_exit(&connp->conn_lock);
9534 			}
9535 			break;	/* goto sizeof (int) option return */
9536 		case SO_USELOOPBACK:
9537 			if (!checkonly) {
9538 				/* TODO: use value someplace? */
9539 				mutex_enter(&connp->conn_lock);
9540 				connp->conn_loopback = *i1 ? 1 : 0;
9541 				mutex_exit(&connp->conn_lock);
9542 			}
9543 			break;	/* goto sizeof (int) option return */
9544 		case SO_DONTROUTE:
9545 			if (!checkonly) {
9546 				mutex_enter(&connp->conn_lock);
9547 				connp->conn_dontroute = *i1 ? 1 : 0;
9548 				mutex_exit(&connp->conn_lock);
9549 			}
9550 			break;	/* goto sizeof (int) option return */
9551 		case SO_REUSEADDR:
9552 			if (!checkonly) {
9553 				mutex_enter(&connp->conn_lock);
9554 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9555 				mutex_exit(&connp->conn_lock);
9556 			}
9557 			break;	/* goto sizeof (int) option return */
9558 		case SO_PROTOTYPE:
9559 			if (!checkonly) {
9560 				mutex_enter(&connp->conn_lock);
9561 				connp->conn_proto = *i1;
9562 				mutex_exit(&connp->conn_lock);
9563 			}
9564 			break;	/* goto sizeof (int) option return */
9565 		default:
9566 			/*
9567 			 * "soft" error (negative)
9568 			 * option not handled at this level
9569 			 * Note: Do not modify *outlenp
9570 			 */
9571 			return (-EINVAL);
9572 		}
9573 		break;
9574 	case IPPROTO_IP:
9575 		switch (name) {
9576 		case IP_NEXTHOP:
9577 		case IP_MULTICAST_IF:
9578 		case IP_DONTFAILOVER_IF: {
9579 			ipaddr_t addr = *i1;
9580 
9581 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9582 			    first_mp);
9583 			if (error != 0)
9584 				return (error);
9585 			break;	/* goto sizeof (int) option return */
9586 		}
9587 
9588 		case IP_MULTICAST_TTL:
9589 			/* Recorded in transport above IP */
9590 			*outvalp = *invalp;
9591 			*outlenp = sizeof (uchar_t);
9592 			return (0);
9593 		case IP_MULTICAST_LOOP:
9594 			if (!checkonly) {
9595 				mutex_enter(&connp->conn_lock);
9596 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9597 				mutex_exit(&connp->conn_lock);
9598 			}
9599 			*outvalp = *invalp;
9600 			*outlenp = sizeof (uchar_t);
9601 			return (0);
9602 		case IP_ADD_MEMBERSHIP:
9603 		case MCAST_JOIN_GROUP:
9604 		case IP_DROP_MEMBERSHIP:
9605 		case MCAST_LEAVE_GROUP: {
9606 			struct ip_mreq *mreqp;
9607 			struct group_req *greqp;
9608 			ire_t *ire;
9609 			boolean_t done = B_FALSE;
9610 			ipaddr_t group, ifaddr;
9611 			struct sockaddr_in *sin;
9612 			uint32_t *ifindexp;
9613 			boolean_t mcast_opt = B_TRUE;
9614 			mcast_record_t fmode;
9615 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9616 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9617 
9618 			switch (name) {
9619 			case IP_ADD_MEMBERSHIP:
9620 				mcast_opt = B_FALSE;
9621 				/* FALLTHRU */
9622 			case MCAST_JOIN_GROUP:
9623 				fmode = MODE_IS_EXCLUDE;
9624 				optfn = ip_opt_add_group;
9625 				break;
9626 
9627 			case IP_DROP_MEMBERSHIP:
9628 				mcast_opt = B_FALSE;
9629 				/* FALLTHRU */
9630 			case MCAST_LEAVE_GROUP:
9631 				fmode = MODE_IS_INCLUDE;
9632 				optfn = ip_opt_delete_group;
9633 				break;
9634 			}
9635 
9636 			if (mcast_opt) {
9637 				greqp = (struct group_req *)i1;
9638 				sin = (struct sockaddr_in *)&greqp->gr_group;
9639 				if (sin->sin_family != AF_INET) {
9640 					*outlenp = 0;
9641 					return (ENOPROTOOPT);
9642 				}
9643 				group = (ipaddr_t)sin->sin_addr.s_addr;
9644 				ifaddr = INADDR_ANY;
9645 				ifindexp = &greqp->gr_interface;
9646 			} else {
9647 				mreqp = (struct ip_mreq *)i1;
9648 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9649 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9650 				ifindexp = NULL;
9651 			}
9652 
9653 			/*
9654 			 * In the multirouting case, we need to replicate
9655 			 * the request on all interfaces that will take part
9656 			 * in replication.  We do so because multirouting is
9657 			 * reflective, thus we will probably receive multi-
9658 			 * casts on those interfaces.
9659 			 * The ip_multirt_apply_membership() succeeds if the
9660 			 * operation succeeds on at least one interface.
9661 			 */
9662 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9663 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9664 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9665 			if (ire != NULL) {
9666 				if (ire->ire_flags & RTF_MULTIRT) {
9667 					error = ip_multirt_apply_membership(
9668 					    optfn, ire, connp, checkonly, group,
9669 					    fmode, INADDR_ANY, first_mp);
9670 					done = B_TRUE;
9671 				}
9672 				ire_refrele(ire);
9673 			}
9674 			if (!done) {
9675 				error = optfn(connp, checkonly, group, ifaddr,
9676 				    ifindexp, fmode, INADDR_ANY, first_mp);
9677 			}
9678 			if (error) {
9679 				/*
9680 				 * EINPROGRESS is a soft error, needs retry
9681 				 * so don't make *outlenp zero.
9682 				 */
9683 				if (error != EINPROGRESS)
9684 					*outlenp = 0;
9685 				return (error);
9686 			}
9687 			/* OK return - copy input buffer into output buffer */
9688 			if (invalp != outvalp) {
9689 				/* don't trust bcopy for identical src/dst */
9690 				bcopy(invalp, outvalp, inlen);
9691 			}
9692 			*outlenp = inlen;
9693 			return (0);
9694 		}
9695 		case IP_BLOCK_SOURCE:
9696 		case IP_UNBLOCK_SOURCE:
9697 		case IP_ADD_SOURCE_MEMBERSHIP:
9698 		case IP_DROP_SOURCE_MEMBERSHIP:
9699 		case MCAST_BLOCK_SOURCE:
9700 		case MCAST_UNBLOCK_SOURCE:
9701 		case MCAST_JOIN_SOURCE_GROUP:
9702 		case MCAST_LEAVE_SOURCE_GROUP: {
9703 			struct ip_mreq_source *imreqp;
9704 			struct group_source_req *gsreqp;
9705 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9706 			uint32_t ifindex = 0;
9707 			mcast_record_t fmode;
9708 			struct sockaddr_in *sin;
9709 			ire_t *ire;
9710 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9711 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9712 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9713 
9714 			switch (name) {
9715 			case IP_BLOCK_SOURCE:
9716 				mcast_opt = B_FALSE;
9717 				/* FALLTHRU */
9718 			case MCAST_BLOCK_SOURCE:
9719 				fmode = MODE_IS_EXCLUDE;
9720 				optfn = ip_opt_add_group;
9721 				break;
9722 
9723 			case IP_UNBLOCK_SOURCE:
9724 				mcast_opt = B_FALSE;
9725 				/* FALLTHRU */
9726 			case MCAST_UNBLOCK_SOURCE:
9727 				fmode = MODE_IS_EXCLUDE;
9728 				optfn = ip_opt_delete_group;
9729 				break;
9730 
9731 			case IP_ADD_SOURCE_MEMBERSHIP:
9732 				mcast_opt = B_FALSE;
9733 				/* FALLTHRU */
9734 			case MCAST_JOIN_SOURCE_GROUP:
9735 				fmode = MODE_IS_INCLUDE;
9736 				optfn = ip_opt_add_group;
9737 				break;
9738 
9739 			case IP_DROP_SOURCE_MEMBERSHIP:
9740 				mcast_opt = B_FALSE;
9741 				/* FALLTHRU */
9742 			case MCAST_LEAVE_SOURCE_GROUP:
9743 				fmode = MODE_IS_INCLUDE;
9744 				optfn = ip_opt_delete_group;
9745 				break;
9746 			}
9747 
9748 			if (mcast_opt) {
9749 				gsreqp = (struct group_source_req *)i1;
9750 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9751 					*outlenp = 0;
9752 					return (ENOPROTOOPT);
9753 				}
9754 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9755 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9756 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9757 				src = (ipaddr_t)sin->sin_addr.s_addr;
9758 				ifindex = gsreqp->gsr_interface;
9759 			} else {
9760 				imreqp = (struct ip_mreq_source *)i1;
9761 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9762 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9763 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9764 			}
9765 
9766 			/*
9767 			 * In the multirouting case, we need to replicate
9768 			 * the request as noted in the mcast cases above.
9769 			 */
9770 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9771 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9772 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9773 			if (ire != NULL) {
9774 				if (ire->ire_flags & RTF_MULTIRT) {
9775 					error = ip_multirt_apply_membership(
9776 					    optfn, ire, connp, checkonly, grp,
9777 					    fmode, src, first_mp);
9778 					done = B_TRUE;
9779 				}
9780 				ire_refrele(ire);
9781 			}
9782 			if (!done) {
9783 				error = optfn(connp, checkonly, grp, ifaddr,
9784 				    &ifindex, fmode, src, first_mp);
9785 			}
9786 			if (error != 0) {
9787 				/*
9788 				 * EINPROGRESS is a soft error, needs retry
9789 				 * so don't make *outlenp zero.
9790 				 */
9791 				if (error != EINPROGRESS)
9792 					*outlenp = 0;
9793 				return (error);
9794 			}
9795 			/* OK return - copy input buffer into output buffer */
9796 			if (invalp != outvalp) {
9797 				bcopy(invalp, outvalp, inlen);
9798 			}
9799 			*outlenp = inlen;
9800 			return (0);
9801 		}
9802 		case IP_SEC_OPT:
9803 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9804 			if (error != 0) {
9805 				*outlenp = 0;
9806 				return (error);
9807 			}
9808 			break;
9809 		case IP_HDRINCL:
9810 		case IP_OPTIONS:
9811 		case T_IP_OPTIONS:
9812 		case IP_TOS:
9813 		case T_IP_TOS:
9814 		case IP_TTL:
9815 		case IP_RECVDSTADDR:
9816 		case IP_RECVOPTS:
9817 			/* OK return - copy input buffer into output buffer */
9818 			if (invalp != outvalp) {
9819 				/* don't trust bcopy for identical src/dst */
9820 				bcopy(invalp, outvalp, inlen);
9821 			}
9822 			*outlenp = inlen;
9823 			return (0);
9824 		case IP_RECVIF:
9825 			/* Retrieve the inbound interface index */
9826 			if (!checkonly) {
9827 				mutex_enter(&connp->conn_lock);
9828 				connp->conn_recvif = *i1 ? 1 : 0;
9829 				mutex_exit(&connp->conn_lock);
9830 			}
9831 			break;	/* goto sizeof (int) option return */
9832 		case IP_RECVSLLA:
9833 			/* Retrieve the source link layer address */
9834 			if (!checkonly) {
9835 				mutex_enter(&connp->conn_lock);
9836 				connp->conn_recvslla = *i1 ? 1 : 0;
9837 				mutex_exit(&connp->conn_lock);
9838 			}
9839 			break;	/* goto sizeof (int) option return */
9840 		case MRT_INIT:
9841 		case MRT_DONE:
9842 		case MRT_ADD_VIF:
9843 		case MRT_DEL_VIF:
9844 		case MRT_ADD_MFC:
9845 		case MRT_DEL_MFC:
9846 		case MRT_ASSERT:
9847 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9848 				*outlenp = 0;
9849 				return (error);
9850 			}
9851 			error = ip_mrouter_set((int)name, q, checkonly,
9852 			    (uchar_t *)invalp, inlen, first_mp);
9853 			if (error) {
9854 				*outlenp = 0;
9855 				return (error);
9856 			}
9857 			/* OK return - copy input buffer into output buffer */
9858 			if (invalp != outvalp) {
9859 				/* don't trust bcopy for identical src/dst */
9860 				bcopy(invalp, outvalp, inlen);
9861 			}
9862 			*outlenp = inlen;
9863 			return (0);
9864 		case IP_BOUND_IF:
9865 		case IP_XMIT_IF:
9866 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9867 			    level, name, first_mp);
9868 			if (error != 0)
9869 				return (error);
9870 			break; 		/* goto sizeof (int) option return */
9871 
9872 		case IP_UNSPEC_SRC:
9873 			/* Allow sending with a zero source address */
9874 			if (!checkonly) {
9875 				mutex_enter(&connp->conn_lock);
9876 				connp->conn_unspec_src = *i1 ? 1 : 0;
9877 				mutex_exit(&connp->conn_lock);
9878 			}
9879 			break;	/* goto sizeof (int) option return */
9880 		default:
9881 			/*
9882 			 * "soft" error (negative)
9883 			 * option not handled at this level
9884 			 * Note: Do not modify *outlenp
9885 			 */
9886 			return (-EINVAL);
9887 		}
9888 		break;
9889 	case IPPROTO_IPV6:
9890 		switch (name) {
9891 		case IPV6_BOUND_IF:
9892 		case IPV6_BOUND_PIF:
9893 		case IPV6_DONTFAILOVER_IF:
9894 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9895 			    level, name, first_mp);
9896 			if (error != 0)
9897 				return (error);
9898 			break; 		/* goto sizeof (int) option return */
9899 
9900 		case IPV6_MULTICAST_IF:
9901 			/*
9902 			 * The only possible errors are EINPROGRESS and
9903 			 * EINVAL. EINPROGRESS will be restarted and is not
9904 			 * a hard error. We call this option on both V4 and V6
9905 			 * If both return EINVAL, then this call returns
9906 			 * EINVAL. If at least one of them succeeds we
9907 			 * return success.
9908 			 */
9909 			found = B_FALSE;
9910 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9911 			    level, name, first_mp);
9912 			if (error == EINPROGRESS)
9913 				return (error);
9914 			if (error == 0)
9915 				found = B_TRUE;
9916 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9917 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9918 			if (error == 0)
9919 				found = B_TRUE;
9920 			if (!found)
9921 				return (error);
9922 			break; 		/* goto sizeof (int) option return */
9923 
9924 		case IPV6_MULTICAST_HOPS:
9925 			/* Recorded in transport above IP */
9926 			break;	/* goto sizeof (int) option return */
9927 		case IPV6_MULTICAST_LOOP:
9928 			if (!checkonly) {
9929 				mutex_enter(&connp->conn_lock);
9930 				connp->conn_multicast_loop = *i1;
9931 				mutex_exit(&connp->conn_lock);
9932 			}
9933 			break;	/* goto sizeof (int) option return */
9934 		case IPV6_JOIN_GROUP:
9935 		case MCAST_JOIN_GROUP:
9936 		case IPV6_LEAVE_GROUP:
9937 		case MCAST_LEAVE_GROUP: {
9938 			struct ipv6_mreq *ip_mreqp;
9939 			struct group_req *greqp;
9940 			ire_t *ire;
9941 			boolean_t done = B_FALSE;
9942 			in6_addr_t groupv6;
9943 			uint32_t ifindex;
9944 			boolean_t mcast_opt = B_TRUE;
9945 			mcast_record_t fmode;
9946 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9947 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9948 
9949 			switch (name) {
9950 			case IPV6_JOIN_GROUP:
9951 				mcast_opt = B_FALSE;
9952 				/* FALLTHRU */
9953 			case MCAST_JOIN_GROUP:
9954 				fmode = MODE_IS_EXCLUDE;
9955 				optfn = ip_opt_add_group_v6;
9956 				break;
9957 
9958 			case IPV6_LEAVE_GROUP:
9959 				mcast_opt = B_FALSE;
9960 				/* FALLTHRU */
9961 			case MCAST_LEAVE_GROUP:
9962 				fmode = MODE_IS_INCLUDE;
9963 				optfn = ip_opt_delete_group_v6;
9964 				break;
9965 			}
9966 
9967 			if (mcast_opt) {
9968 				struct sockaddr_in *sin;
9969 				struct sockaddr_in6 *sin6;
9970 				greqp = (struct group_req *)i1;
9971 				if (greqp->gr_group.ss_family == AF_INET) {
9972 					sin = (struct sockaddr_in *)
9973 					    &(greqp->gr_group);
9974 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9975 					    &groupv6);
9976 				} else {
9977 					sin6 = (struct sockaddr_in6 *)
9978 					    &(greqp->gr_group);
9979 					groupv6 = sin6->sin6_addr;
9980 				}
9981 				ifindex = greqp->gr_interface;
9982 			} else {
9983 				ip_mreqp = (struct ipv6_mreq *)i1;
9984 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9985 				ifindex = ip_mreqp->ipv6mr_interface;
9986 			}
9987 			/*
9988 			 * In the multirouting case, we need to replicate
9989 			 * the request on all interfaces that will take part
9990 			 * in replication.  We do so because multirouting is
9991 			 * reflective, thus we will probably receive multi-
9992 			 * casts on those interfaces.
9993 			 * The ip_multirt_apply_membership_v6() succeeds if
9994 			 * the operation succeeds on at least one interface.
9995 			 */
9996 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9997 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9998 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9999 			if (ire != NULL) {
10000 				if (ire->ire_flags & RTF_MULTIRT) {
10001 					error = ip_multirt_apply_membership_v6(
10002 					    optfn, ire, connp, checkonly,
10003 					    &groupv6, fmode, &ipv6_all_zeros,
10004 					    first_mp);
10005 					done = B_TRUE;
10006 				}
10007 				ire_refrele(ire);
10008 			}
10009 			if (!done) {
10010 				error = optfn(connp, checkonly, &groupv6,
10011 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10012 			}
10013 			if (error) {
10014 				/*
10015 				 * EINPROGRESS is a soft error, needs retry
10016 				 * so don't make *outlenp zero.
10017 				 */
10018 				if (error != EINPROGRESS)
10019 					*outlenp = 0;
10020 				return (error);
10021 			}
10022 			/* OK return - copy input buffer into output buffer */
10023 			if (invalp != outvalp) {
10024 				/* don't trust bcopy for identical src/dst */
10025 				bcopy(invalp, outvalp, inlen);
10026 			}
10027 			*outlenp = inlen;
10028 			return (0);
10029 		}
10030 		case MCAST_BLOCK_SOURCE:
10031 		case MCAST_UNBLOCK_SOURCE:
10032 		case MCAST_JOIN_SOURCE_GROUP:
10033 		case MCAST_LEAVE_SOURCE_GROUP: {
10034 			struct group_source_req *gsreqp;
10035 			in6_addr_t v6grp, v6src;
10036 			uint32_t ifindex;
10037 			mcast_record_t fmode;
10038 			ire_t *ire;
10039 			boolean_t done = B_FALSE;
10040 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10041 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10042 
10043 			switch (name) {
10044 			case MCAST_BLOCK_SOURCE:
10045 				fmode = MODE_IS_EXCLUDE;
10046 				optfn = ip_opt_add_group_v6;
10047 				break;
10048 			case MCAST_UNBLOCK_SOURCE:
10049 				fmode = MODE_IS_EXCLUDE;
10050 				optfn = ip_opt_delete_group_v6;
10051 				break;
10052 			case MCAST_JOIN_SOURCE_GROUP:
10053 				fmode = MODE_IS_INCLUDE;
10054 				optfn = ip_opt_add_group_v6;
10055 				break;
10056 			case MCAST_LEAVE_SOURCE_GROUP:
10057 				fmode = MODE_IS_INCLUDE;
10058 				optfn = ip_opt_delete_group_v6;
10059 				break;
10060 			}
10061 
10062 			gsreqp = (struct group_source_req *)i1;
10063 			ifindex = gsreqp->gsr_interface;
10064 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10065 				struct sockaddr_in *s;
10066 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10067 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10068 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10069 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10070 			} else {
10071 				struct sockaddr_in6 *s6;
10072 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10073 				v6grp = s6->sin6_addr;
10074 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10075 				v6src = s6->sin6_addr;
10076 			}
10077 
10078 			/*
10079 			 * In the multirouting case, we need to replicate
10080 			 * the request as noted in the mcast cases above.
10081 			 */
10082 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10083 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10084 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10085 			if (ire != NULL) {
10086 				if (ire->ire_flags & RTF_MULTIRT) {
10087 					error = ip_multirt_apply_membership_v6(
10088 					    optfn, ire, connp, checkonly,
10089 					    &v6grp, fmode, &v6src, first_mp);
10090 					done = B_TRUE;
10091 				}
10092 				ire_refrele(ire);
10093 			}
10094 			if (!done) {
10095 				error = optfn(connp, checkonly, &v6grp,
10096 				    ifindex, fmode, &v6src, first_mp);
10097 			}
10098 			if (error != 0) {
10099 				/*
10100 				 * EINPROGRESS is a soft error, needs retry
10101 				 * so don't make *outlenp zero.
10102 				 */
10103 				if (error != EINPROGRESS)
10104 					*outlenp = 0;
10105 				return (error);
10106 			}
10107 			/* OK return - copy input buffer into output buffer */
10108 			if (invalp != outvalp) {
10109 				bcopy(invalp, outvalp, inlen);
10110 			}
10111 			*outlenp = inlen;
10112 			return (0);
10113 		}
10114 		case IPV6_UNICAST_HOPS:
10115 			/* Recorded in transport above IP */
10116 			break;	/* goto sizeof (int) option return */
10117 		case IPV6_UNSPEC_SRC:
10118 			/* Allow sending with a zero source address */
10119 			if (!checkonly) {
10120 				mutex_enter(&connp->conn_lock);
10121 				connp->conn_unspec_src = *i1 ? 1 : 0;
10122 				mutex_exit(&connp->conn_lock);
10123 			}
10124 			break;	/* goto sizeof (int) option return */
10125 		case IPV6_RECVPKTINFO:
10126 			if (!checkonly) {
10127 				mutex_enter(&connp->conn_lock);
10128 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10129 				mutex_exit(&connp->conn_lock);
10130 			}
10131 			break;	/* goto sizeof (int) option return */
10132 		case IPV6_RECVTCLASS:
10133 			if (!checkonly) {
10134 				if (*i1 < 0 || *i1 > 1) {
10135 					return (EINVAL);
10136 				}
10137 				mutex_enter(&connp->conn_lock);
10138 				connp->conn_ipv6_recvtclass = *i1;
10139 				mutex_exit(&connp->conn_lock);
10140 			}
10141 			break;
10142 		case IPV6_RECVPATHMTU:
10143 			if (!checkonly) {
10144 				if (*i1 < 0 || *i1 > 1) {
10145 					return (EINVAL);
10146 				}
10147 				mutex_enter(&connp->conn_lock);
10148 				connp->conn_ipv6_recvpathmtu = *i1;
10149 				mutex_exit(&connp->conn_lock);
10150 			}
10151 			break;
10152 		case IPV6_RECVHOPLIMIT:
10153 			if (!checkonly) {
10154 				mutex_enter(&connp->conn_lock);
10155 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10156 				mutex_exit(&connp->conn_lock);
10157 			}
10158 			break;	/* goto sizeof (int) option return */
10159 		case IPV6_RECVHOPOPTS:
10160 			if (!checkonly) {
10161 				mutex_enter(&connp->conn_lock);
10162 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10163 				mutex_exit(&connp->conn_lock);
10164 			}
10165 			break;	/* goto sizeof (int) option return */
10166 		case IPV6_RECVDSTOPTS:
10167 			if (!checkonly) {
10168 				mutex_enter(&connp->conn_lock);
10169 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10170 				mutex_exit(&connp->conn_lock);
10171 			}
10172 			break;	/* goto sizeof (int) option return */
10173 		case IPV6_RECVRTHDR:
10174 			if (!checkonly) {
10175 				mutex_enter(&connp->conn_lock);
10176 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10177 				mutex_exit(&connp->conn_lock);
10178 			}
10179 			break;	/* goto sizeof (int) option return */
10180 		case IPV6_RECVRTHDRDSTOPTS:
10181 			if (!checkonly) {
10182 				mutex_enter(&connp->conn_lock);
10183 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10184 				mutex_exit(&connp->conn_lock);
10185 			}
10186 			break;	/* goto sizeof (int) option return */
10187 		case IPV6_PKTINFO:
10188 			if (inlen == 0)
10189 				return (-EINVAL);	/* clearing option */
10190 			error = ip6_set_pktinfo(cr, connp,
10191 			    (struct in6_pktinfo *)invalp, first_mp);
10192 			if (error != 0)
10193 				*outlenp = 0;
10194 			else
10195 				*outlenp = inlen;
10196 			return (error);
10197 		case IPV6_NEXTHOP: {
10198 			struct sockaddr_in6 *sin6;
10199 
10200 			/* Verify that the nexthop is reachable */
10201 			if (inlen == 0)
10202 				return (-EINVAL);	/* clearing option */
10203 
10204 			sin6 = (struct sockaddr_in6 *)invalp;
10205 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10206 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10207 			    MATCH_IRE_DEFAULT);
10208 
10209 			if (ire == NULL) {
10210 				*outlenp = 0;
10211 				return (EHOSTUNREACH);
10212 			}
10213 			ire_refrele(ire);
10214 			return (-EINVAL);
10215 		}
10216 		case IPV6_SEC_OPT:
10217 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10218 			if (error != 0) {
10219 				*outlenp = 0;
10220 				return (error);
10221 			}
10222 			break;
10223 		case IPV6_SRC_PREFERENCES: {
10224 			/*
10225 			 * This is implemented strictly in the ip module
10226 			 * (here and in tcp_opt_*() to accomodate tcp
10227 			 * sockets).  Modules above ip pass this option
10228 			 * down here since ip is the only one that needs to
10229 			 * be aware of source address preferences.
10230 			 *
10231 			 * This socket option only affects connected
10232 			 * sockets that haven't already bound to a specific
10233 			 * IPv6 address.  In other words, sockets that
10234 			 * don't call bind() with an address other than the
10235 			 * unspecified address and that call connect().
10236 			 * ip_bind_connected_v6() passes these preferences
10237 			 * to the ipif_select_source_v6() function.
10238 			 */
10239 			if (inlen != sizeof (uint32_t))
10240 				return (EINVAL);
10241 			error = ip6_set_src_preferences(connp,
10242 			    *(uint32_t *)invalp);
10243 			if (error != 0) {
10244 				*outlenp = 0;
10245 				return (error);
10246 			} else {
10247 				*outlenp = sizeof (uint32_t);
10248 			}
10249 			break;
10250 		}
10251 		case IPV6_V6ONLY:
10252 			if (*i1 < 0 || *i1 > 1) {
10253 				return (EINVAL);
10254 			}
10255 			mutex_enter(&connp->conn_lock);
10256 			connp->conn_ipv6_v6only = *i1;
10257 			mutex_exit(&connp->conn_lock);
10258 			break;
10259 		default:
10260 			return (-EINVAL);
10261 		}
10262 		break;
10263 	default:
10264 		/*
10265 		 * "soft" error (negative)
10266 		 * option not handled at this level
10267 		 * Note: Do not modify *outlenp
10268 		 */
10269 		return (-EINVAL);
10270 	}
10271 	/*
10272 	 * Common case of return from an option that is sizeof (int)
10273 	 */
10274 	*(int *)outvalp = *i1;
10275 	*outlenp = sizeof (int);
10276 	return (0);
10277 }
10278 
10279 /*
10280  * This routine gets default values of certain options whose default
10281  * values are maintained by protocol specific code
10282  */
10283 /* ARGSUSED */
10284 int
10285 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10286 {
10287 	int *i1 = (int *)ptr;
10288 
10289 	switch (level) {
10290 	case IPPROTO_IP:
10291 		switch (name) {
10292 		case IP_MULTICAST_TTL:
10293 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10294 			return (sizeof (uchar_t));
10295 		case IP_MULTICAST_LOOP:
10296 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10297 			return (sizeof (uchar_t));
10298 		default:
10299 			return (-1);
10300 		}
10301 	case IPPROTO_IPV6:
10302 		switch (name) {
10303 		case IPV6_UNICAST_HOPS:
10304 			*i1 = ipv6_def_hops;
10305 			return (sizeof (int));
10306 		case IPV6_MULTICAST_HOPS:
10307 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10308 			return (sizeof (int));
10309 		case IPV6_MULTICAST_LOOP:
10310 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10311 			return (sizeof (int));
10312 		case IPV6_V6ONLY:
10313 			*i1 = 1;
10314 			return (sizeof (int));
10315 		default:
10316 			return (-1);
10317 		}
10318 	default:
10319 		return (-1);
10320 	}
10321 	/* NOTREACHED */
10322 }
10323 
10324 /*
10325  * Given a destination address and a pointer to where to put the information
10326  * this routine fills in the mtuinfo.
10327  */
10328 int
10329 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10330     struct ip6_mtuinfo *mtuinfo)
10331 {
10332 	ire_t *ire;
10333 
10334 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10335 		return (-1);
10336 
10337 	bzero(mtuinfo, sizeof (*mtuinfo));
10338 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10339 	mtuinfo->ip6m_addr.sin6_port = port;
10340 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10341 
10342 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10343 	if (ire != NULL) {
10344 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10345 		ire_refrele(ire);
10346 	} else {
10347 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10348 	}
10349 	return (sizeof (struct ip6_mtuinfo));
10350 }
10351 
10352 /*
10353  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10354  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10355  * isn't.  This doesn't matter as the error checking is done properly for the
10356  * other MRT options coming in through ip_opt_set.
10357  */
10358 int
10359 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10360 {
10361 	conn_t		*connp = Q_TO_CONN(q);
10362 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10363 
10364 	switch (level) {
10365 	case IPPROTO_IP:
10366 		switch (name) {
10367 		case MRT_VERSION:
10368 		case MRT_ASSERT:
10369 			(void) ip_mrouter_get(name, q, ptr);
10370 			return (sizeof (int));
10371 		case IP_SEC_OPT:
10372 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10373 		case IP_NEXTHOP:
10374 			if (connp->conn_nexthop_set) {
10375 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10376 				return (sizeof (ipaddr_t));
10377 			} else
10378 				return (0);
10379 		default:
10380 			break;
10381 		}
10382 		break;
10383 	case IPPROTO_IPV6:
10384 		switch (name) {
10385 		case IPV6_SEC_OPT:
10386 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10387 		case IPV6_SRC_PREFERENCES: {
10388 			return (ip6_get_src_preferences(connp,
10389 			    (uint32_t *)ptr));
10390 		}
10391 		case IPV6_V6ONLY:
10392 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10393 			return (sizeof (int));
10394 		case IPV6_PATHMTU:
10395 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10396 				(struct ip6_mtuinfo *)ptr));
10397 		default:
10398 			break;
10399 		}
10400 		break;
10401 	default:
10402 		break;
10403 	}
10404 	return (-1);
10405 }
10406 
10407 /* Named Dispatch routine to get a current value out of our parameter table. */
10408 /* ARGSUSED */
10409 static int
10410 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10411 {
10412 	ipparam_t *ippa = (ipparam_t *)cp;
10413 
10414 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10415 	return (0);
10416 }
10417 
10418 /* ARGSUSED */
10419 static int
10420 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10421 {
10422 
10423 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10424 	return (0);
10425 }
10426 
10427 /*
10428  * Set ip{,6}_forwarding values.  This means walking through all of the
10429  * ill's and toggling their forwarding values.
10430  */
10431 /* ARGSUSED */
10432 static int
10433 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10434 {
10435 	long new_value;
10436 	int *forwarding_value = (int *)cp;
10437 	ill_t *walker;
10438 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10439 	ill_walk_context_t ctx;
10440 
10441 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10442 	    new_value < 0 || new_value > 1) {
10443 		return (EINVAL);
10444 	}
10445 
10446 	*forwarding_value = new_value;
10447 
10448 	/*
10449 	 * Regardless of the current value of ip_forwarding, set all per-ill
10450 	 * values of ip_forwarding to the value being set.
10451 	 *
10452 	 * Bring all the ill's up to date with the new global value.
10453 	 */
10454 	rw_enter(&ill_g_lock, RW_READER);
10455 
10456 	if (isv6)
10457 		walker = ILL_START_WALK_V6(&ctx);
10458 	else
10459 		walker = ILL_START_WALK_V4(&ctx);
10460 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10461 		(void) ill_forward_set(q, mp, (new_value != 0),
10462 		    (caddr_t)walker);
10463 	}
10464 	rw_exit(&ill_g_lock);
10465 
10466 	return (0);
10467 }
10468 
10469 /*
10470  * Walk through the param array specified registering each element with the
10471  * Named Dispatch handler. This is called only during init. So it is ok
10472  * not to acquire any locks
10473  */
10474 static boolean_t
10475 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10476     ipndp_t *ipnd, size_t ipnd_cnt)
10477 {
10478 	for (; ippa_cnt-- > 0; ippa++) {
10479 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10480 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10481 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10482 				nd_free(&ip_g_nd);
10483 				return (B_FALSE);
10484 			}
10485 		}
10486 	}
10487 
10488 	for (; ipnd_cnt-- > 0; ipnd++) {
10489 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10490 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10491 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10492 			    ipnd->ip_ndp_data)) {
10493 				nd_free(&ip_g_nd);
10494 				return (B_FALSE);
10495 			}
10496 		}
10497 	}
10498 
10499 	return (B_TRUE);
10500 }
10501 
10502 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10503 /* ARGSUSED */
10504 static int
10505 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10506 {
10507 	long		new_value;
10508 	ipparam_t	*ippa = (ipparam_t *)cp;
10509 
10510 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10511 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10512 		return (EINVAL);
10513 	}
10514 	ippa->ip_param_value = new_value;
10515 	return (0);
10516 }
10517 
10518 /*
10519  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10520  * When an ipf is passed here for the first time, if
10521  * we already have in-order fragments on the queue, we convert from the fast-
10522  * path reassembly scheme to the hard-case scheme.  From then on, additional
10523  * fragments are reassembled here.  We keep track of the start and end offsets
10524  * of each piece, and the number of holes in the chain.  When the hole count
10525  * goes to zero, we are done!
10526  *
10527  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10528  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10529  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10530  * after the call to ip_reassemble().
10531  */
10532 int
10533 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10534     size_t msg_len)
10535 {
10536 	uint_t	end;
10537 	mblk_t	*next_mp;
10538 	mblk_t	*mp1;
10539 	uint_t	offset;
10540 	boolean_t incr_dups = B_TRUE;
10541 	boolean_t offset_zero_seen = B_FALSE;
10542 	boolean_t pkt_boundary_checked = B_FALSE;
10543 
10544 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10545 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10546 
10547 	/* Add in byte count */
10548 	ipf->ipf_count += msg_len;
10549 	if (ipf->ipf_end) {
10550 		/*
10551 		 * We were part way through in-order reassembly, but now there
10552 		 * is a hole.  We walk through messages already queued, and
10553 		 * mark them for hard case reassembly.  We know that up till
10554 		 * now they were in order starting from offset zero.
10555 		 */
10556 		offset = 0;
10557 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10558 			IP_REASS_SET_START(mp1, offset);
10559 			if (offset == 0) {
10560 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10561 				offset = -ipf->ipf_nf_hdr_len;
10562 			}
10563 			offset += mp1->b_wptr - mp1->b_rptr;
10564 			IP_REASS_SET_END(mp1, offset);
10565 		}
10566 		/* One hole at the end. */
10567 		ipf->ipf_hole_cnt = 1;
10568 		/* Brand it as a hard case, forever. */
10569 		ipf->ipf_end = 0;
10570 	}
10571 	/* Walk through all the new pieces. */
10572 	do {
10573 		end = start + (mp->b_wptr - mp->b_rptr);
10574 		/*
10575 		 * If start is 0, decrease 'end' only for the first mblk of
10576 		 * the fragment. Otherwise 'end' can get wrong value in the
10577 		 * second pass of the loop if first mblk is exactly the
10578 		 * size of ipf_nf_hdr_len.
10579 		 */
10580 		if (start == 0 && !offset_zero_seen) {
10581 			/* First segment */
10582 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10583 			end -= ipf->ipf_nf_hdr_len;
10584 			offset_zero_seen = B_TRUE;
10585 		}
10586 		next_mp = mp->b_cont;
10587 		/*
10588 		 * We are checking to see if there is any interesing data
10589 		 * to process.  If there isn't and the mblk isn't the
10590 		 * one which carries the unfragmentable header then we
10591 		 * drop it.  It's possible to have just the unfragmentable
10592 		 * header come through without any data.  That needs to be
10593 		 * saved.
10594 		 *
10595 		 * If the assert at the top of this function holds then the
10596 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10597 		 * is infrequently traveled enough that the test is left in
10598 		 * to protect against future code changes which break that
10599 		 * invariant.
10600 		 */
10601 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10602 			/* Empty.  Blast it. */
10603 			IP_REASS_SET_START(mp, 0);
10604 			IP_REASS_SET_END(mp, 0);
10605 			/*
10606 			 * If the ipf points to the mblk we are about to free,
10607 			 * update ipf to point to the next mblk (or NULL
10608 			 * if none).
10609 			 */
10610 			if (ipf->ipf_mp->b_cont == mp)
10611 				ipf->ipf_mp->b_cont = next_mp;
10612 			freeb(mp);
10613 			continue;
10614 		}
10615 		mp->b_cont = NULL;
10616 		IP_REASS_SET_START(mp, start);
10617 		IP_REASS_SET_END(mp, end);
10618 		if (!ipf->ipf_tail_mp) {
10619 			ipf->ipf_tail_mp = mp;
10620 			ipf->ipf_mp->b_cont = mp;
10621 			if (start == 0 || !more) {
10622 				ipf->ipf_hole_cnt = 1;
10623 				/*
10624 				 * if the first fragment comes in more than one
10625 				 * mblk, this loop will be executed for each
10626 				 * mblk. Need to adjust hole count so exiting
10627 				 * this routine will leave hole count at 1.
10628 				 */
10629 				if (next_mp)
10630 					ipf->ipf_hole_cnt++;
10631 			} else
10632 				ipf->ipf_hole_cnt = 2;
10633 			continue;
10634 		} else if (ipf->ipf_last_frag_seen && !more &&
10635 			    !pkt_boundary_checked) {
10636 			/*
10637 			 * We check datagram boundary only if this fragment
10638 			 * claims to be the last fragment and we have seen a
10639 			 * last fragment in the past too. We do this only
10640 			 * once for a given fragment.
10641 			 *
10642 			 * start cannot be 0 here as fragments with start=0
10643 			 * and MF=0 gets handled as a complete packet. These
10644 			 * fragments should not reach here.
10645 			 */
10646 
10647 			if (start + msgdsize(mp) !=
10648 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10649 				/*
10650 				 * We have two fragments both of which claim
10651 				 * to be the last fragment but gives conflicting
10652 				 * information about the whole datagram size.
10653 				 * Something fishy is going on. Drop the
10654 				 * fragment and free up the reassembly list.
10655 				 */
10656 				return (IP_REASS_FAILED);
10657 			}
10658 
10659 			/*
10660 			 * We shouldn't come to this code block again for this
10661 			 * particular fragment.
10662 			 */
10663 			pkt_boundary_checked = B_TRUE;
10664 		}
10665 
10666 		/* New stuff at or beyond tail? */
10667 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10668 		if (start >= offset) {
10669 			if (ipf->ipf_last_frag_seen) {
10670 				/* current fragment is beyond last fragment */
10671 				return (IP_REASS_FAILED);
10672 			}
10673 			/* Link it on end. */
10674 			ipf->ipf_tail_mp->b_cont = mp;
10675 			ipf->ipf_tail_mp = mp;
10676 			if (more) {
10677 				if (start != offset)
10678 					ipf->ipf_hole_cnt++;
10679 			} else if (start == offset && next_mp == NULL)
10680 					ipf->ipf_hole_cnt--;
10681 			continue;
10682 		}
10683 		mp1 = ipf->ipf_mp->b_cont;
10684 		offset = IP_REASS_START(mp1);
10685 		/* New stuff at the front? */
10686 		if (start < offset) {
10687 			if (start == 0) {
10688 				if (end >= offset) {
10689 					/* Nailed the hole at the begining. */
10690 					ipf->ipf_hole_cnt--;
10691 				}
10692 			} else if (end < offset) {
10693 				/*
10694 				 * A hole, stuff, and a hole where there used
10695 				 * to be just a hole.
10696 				 */
10697 				ipf->ipf_hole_cnt++;
10698 			}
10699 			mp->b_cont = mp1;
10700 			/* Check for overlap. */
10701 			while (end > offset) {
10702 				if (end < IP_REASS_END(mp1)) {
10703 					mp->b_wptr -= end - offset;
10704 					IP_REASS_SET_END(mp, offset);
10705 					if (ill->ill_isv6) {
10706 						BUMP_MIB(ill->ill_ip6_mib,
10707 						    ipv6ReasmPartDups);
10708 					} else {
10709 						BUMP_MIB(&ip_mib,
10710 						    ipReasmPartDups);
10711 					}
10712 					break;
10713 				}
10714 				/* Did we cover another hole? */
10715 				if ((mp1->b_cont &&
10716 				    IP_REASS_END(mp1) !=
10717 				    IP_REASS_START(mp1->b_cont) &&
10718 				    end >= IP_REASS_START(mp1->b_cont)) ||
10719 				    (!ipf->ipf_last_frag_seen && !more)) {
10720 					ipf->ipf_hole_cnt--;
10721 				}
10722 				/* Clip out mp1. */
10723 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10724 					/*
10725 					 * After clipping out mp1, this guy
10726 					 * is now hanging off the end.
10727 					 */
10728 					ipf->ipf_tail_mp = mp;
10729 				}
10730 				IP_REASS_SET_START(mp1, 0);
10731 				IP_REASS_SET_END(mp1, 0);
10732 				/* Subtract byte count */
10733 				ipf->ipf_count -= mp1->b_datap->db_lim -
10734 				    mp1->b_datap->db_base;
10735 				freeb(mp1);
10736 				if (ill->ill_isv6) {
10737 					BUMP_MIB(ill->ill_ip6_mib,
10738 					    ipv6ReasmPartDups);
10739 				} else {
10740 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10741 				}
10742 				mp1 = mp->b_cont;
10743 				if (!mp1)
10744 					break;
10745 				offset = IP_REASS_START(mp1);
10746 			}
10747 			ipf->ipf_mp->b_cont = mp;
10748 			continue;
10749 		}
10750 		/*
10751 		 * The new piece starts somewhere between the start of the head
10752 		 * and before the end of the tail.
10753 		 */
10754 		for (; mp1; mp1 = mp1->b_cont) {
10755 			offset = IP_REASS_END(mp1);
10756 			if (start < offset) {
10757 				if (end <= offset) {
10758 					/* Nothing new. */
10759 					IP_REASS_SET_START(mp, 0);
10760 					IP_REASS_SET_END(mp, 0);
10761 					/* Subtract byte count */
10762 					ipf->ipf_count -= mp->b_datap->db_lim -
10763 					    mp->b_datap->db_base;
10764 					if (incr_dups) {
10765 						ipf->ipf_num_dups++;
10766 						incr_dups = B_FALSE;
10767 					}
10768 					freeb(mp);
10769 					if (ill->ill_isv6) {
10770 						BUMP_MIB(ill->ill_ip6_mib,
10771 						    ipv6ReasmDuplicates);
10772 					} else {
10773 						BUMP_MIB(&ip_mib,
10774 						    ipReasmDuplicates);
10775 					}
10776 					break;
10777 				}
10778 				/*
10779 				 * Trim redundant stuff off beginning of new
10780 				 * piece.
10781 				 */
10782 				IP_REASS_SET_START(mp, offset);
10783 				mp->b_rptr += offset - start;
10784 				if (ill->ill_isv6) {
10785 					BUMP_MIB(ill->ill_ip6_mib,
10786 					    ipv6ReasmPartDups);
10787 				} else {
10788 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10789 				}
10790 				start = offset;
10791 				if (!mp1->b_cont) {
10792 					/*
10793 					 * After trimming, this guy is now
10794 					 * hanging off the end.
10795 					 */
10796 					mp1->b_cont = mp;
10797 					ipf->ipf_tail_mp = mp;
10798 					if (!more) {
10799 						ipf->ipf_hole_cnt--;
10800 					}
10801 					break;
10802 				}
10803 			}
10804 			if (start >= IP_REASS_START(mp1->b_cont))
10805 				continue;
10806 			/* Fill a hole */
10807 			if (start > offset)
10808 				ipf->ipf_hole_cnt++;
10809 			mp->b_cont = mp1->b_cont;
10810 			mp1->b_cont = mp;
10811 			mp1 = mp->b_cont;
10812 			offset = IP_REASS_START(mp1);
10813 			if (end >= offset) {
10814 				ipf->ipf_hole_cnt--;
10815 				/* Check for overlap. */
10816 				while (end > offset) {
10817 					if (end < IP_REASS_END(mp1)) {
10818 						mp->b_wptr -= end - offset;
10819 						IP_REASS_SET_END(mp, offset);
10820 						/*
10821 						 * TODO we might bump
10822 						 * this up twice if there is
10823 						 * overlap at both ends.
10824 						 */
10825 						if (ill->ill_isv6) {
10826 							BUMP_MIB(
10827 							    ill->ill_ip6_mib,
10828 							    ipv6ReasmPartDups);
10829 						} else {
10830 							BUMP_MIB(&ip_mib,
10831 							    ipReasmPartDups);
10832 						}
10833 						break;
10834 					}
10835 					/* Did we cover another hole? */
10836 					if ((mp1->b_cont &&
10837 					    IP_REASS_END(mp1)
10838 					    != IP_REASS_START(mp1->b_cont) &&
10839 					    end >=
10840 					    IP_REASS_START(mp1->b_cont)) ||
10841 					    (!ipf->ipf_last_frag_seen &&
10842 					    !more)) {
10843 						ipf->ipf_hole_cnt--;
10844 					}
10845 					/* Clip out mp1. */
10846 					if ((mp->b_cont = mp1->b_cont) ==
10847 					    NULL) {
10848 						/*
10849 						 * After clipping out mp1,
10850 						 * this guy is now hanging
10851 						 * off the end.
10852 						 */
10853 						ipf->ipf_tail_mp = mp;
10854 					}
10855 					IP_REASS_SET_START(mp1, 0);
10856 					IP_REASS_SET_END(mp1, 0);
10857 					/* Subtract byte count */
10858 					ipf->ipf_count -=
10859 					    mp1->b_datap->db_lim -
10860 					    mp1->b_datap->db_base;
10861 					freeb(mp1);
10862 					if (ill->ill_isv6) {
10863 						BUMP_MIB(ill->ill_ip6_mib,
10864 						    ipv6ReasmPartDups);
10865 					} else {
10866 						BUMP_MIB(&ip_mib,
10867 						    ipReasmPartDups);
10868 					}
10869 					mp1 = mp->b_cont;
10870 					if (!mp1)
10871 						break;
10872 					offset = IP_REASS_START(mp1);
10873 				}
10874 			}
10875 			break;
10876 		}
10877 	} while (start = end, mp = next_mp);
10878 
10879 	/* Fragment just processed could be the last one. Remember this fact */
10880 	if (!more)
10881 		ipf->ipf_last_frag_seen = B_TRUE;
10882 
10883 	/* Still got holes? */
10884 	if (ipf->ipf_hole_cnt)
10885 		return (IP_REASS_PARTIAL);
10886 	/* Clean up overloaded fields to avoid upstream disasters. */
10887 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10888 		IP_REASS_SET_START(mp1, 0);
10889 		IP_REASS_SET_END(mp1, 0);
10890 	}
10891 	return (IP_REASS_COMPLETE);
10892 }
10893 
10894 /*
10895  * ipsec processing for the fast path, used for input UDP Packets
10896  */
10897 static boolean_t
10898 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10899     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10900 {
10901 	uint32_t	ill_index;
10902 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10903 
10904 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10905 	/* The ill_index of the incoming ILL */
10906 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10907 
10908 	/* pass packet up to the transport */
10909 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10910 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10911 		    NULL, mctl_present);
10912 		if (*first_mpp == NULL) {
10913 			return (B_FALSE);
10914 		}
10915 	}
10916 
10917 	/* Initiate IPPF processing for fastpath UDP */
10918 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10919 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10920 		if (*mpp == NULL) {
10921 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10922 			    "deferred/dropped during IPPF processing\n"));
10923 			return (B_FALSE);
10924 		}
10925 	}
10926 	/*
10927 	 * We make the checks as below since we are in the fast path
10928 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10929 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10930 	 */
10931 	if (connp->conn_recvif || connp->conn_recvslla ||
10932 	    connp->conn_ipv6_recvpktinfo) {
10933 		if (connp->conn_recvif ||
10934 		    connp->conn_ipv6_recvpktinfo) {
10935 			in_flags = IPF_RECVIF;
10936 		}
10937 		if (connp->conn_recvslla) {
10938 			in_flags |= IPF_RECVSLLA;
10939 		}
10940 		/*
10941 		 * since in_flags are being set ill will be
10942 		 * referenced in ip_add_info, so it better not
10943 		 * be NULL.
10944 		 */
10945 		/*
10946 		 * the actual data will be contained in b_cont
10947 		 * upon successful return of the following call.
10948 		 * If the call fails then the original mblk is
10949 		 * returned.
10950 		 */
10951 		*mpp = ip_add_info(*mpp, ill, in_flags);
10952 	}
10953 
10954 	return (B_TRUE);
10955 }
10956 
10957 /*
10958  * Fragmentation reassembly.  Each ILL has a hash table for
10959  * queuing packets undergoing reassembly for all IPIFs
10960  * associated with the ILL.  The hash is based on the packet
10961  * IP ident field.  The ILL frag hash table was allocated
10962  * as a timer block at the time the ILL was created.  Whenever
10963  * there is anything on the reassembly queue, the timer will
10964  * be running.  Returns B_TRUE if successful else B_FALSE;
10965  * frees mp on failure.
10966  */
10967 static boolean_t
10968 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
10969     uint32_t *cksum_val, uint16_t *cksum_flags)
10970 {
10971 	uint32_t	frag_offset_flags;
10972 	ill_t		*ill = (ill_t *)q->q_ptr;
10973 	mblk_t		*mp = *mpp;
10974 	mblk_t		*t_mp;
10975 	ipaddr_t	dst;
10976 	uint8_t		proto = ipha->ipha_protocol;
10977 	uint32_t	sum_val;
10978 	uint16_t	sum_flags;
10979 	ipf_t		*ipf;
10980 	ipf_t		**ipfp;
10981 	ipfb_t		*ipfb;
10982 	uint16_t	ident;
10983 	uint32_t	offset;
10984 	ipaddr_t	src;
10985 	uint_t		hdr_length;
10986 	uint32_t	end;
10987 	mblk_t		*mp1;
10988 	mblk_t		*tail_mp;
10989 	size_t		count;
10990 	size_t		msg_len;
10991 	uint8_t		ecn_info = 0;
10992 	uint32_t	packet_size;
10993 	boolean_t	pruned = B_FALSE;
10994 
10995 	if (cksum_val != NULL)
10996 		*cksum_val = 0;
10997 	if (cksum_flags != NULL)
10998 		*cksum_flags = 0;
10999 
11000 	/*
11001 	 * Drop the fragmented as early as possible, if
11002 	 * we don't have resource(s) to re-assemble.
11003 	 */
11004 	if (ip_reass_queue_bytes == 0) {
11005 		freemsg(mp);
11006 		return (B_FALSE);
11007 	}
11008 
11009 	/* Check for fragmentation offset; return if there's none */
11010 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11011 	    (IPH_MF | IPH_OFFSET)) == 0)
11012 		return (B_TRUE);
11013 
11014 	/*
11015 	 * We utilize hardware computed checksum info only for UDP since
11016 	 * IP fragmentation is a normal occurence for the protocol.  In
11017 	 * addition, checksum offload support for IP fragments carrying
11018 	 * UDP payload is commonly implemented across network adapters.
11019 	 */
11020 	ASSERT(ill != NULL);
11021 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11022 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11023 		mblk_t *mp1 = mp->b_cont;
11024 		int32_t len;
11025 
11026 		/* Record checksum information from the packet */
11027 		sum_val = (uint32_t)DB_CKSUM16(mp);
11028 		sum_flags = DB_CKSUMFLAGS(mp);
11029 
11030 		/* IP payload offset from beginning of mblk */
11031 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11032 
11033 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11034 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11035 		    offset >= DB_CKSUMSTART(mp) &&
11036 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11037 			uint32_t adj;
11038 			/*
11039 			 * Partial checksum has been calculated by hardware
11040 			 * and attached to the packet; in addition, any
11041 			 * prepended extraneous data is even byte aligned.
11042 			 * If any such data exists, we adjust the checksum;
11043 			 * this would also handle any postpended data.
11044 			 */
11045 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11046 			    mp, mp1, len, adj);
11047 
11048 			/* One's complement subtract extraneous checksum */
11049 			if (adj >= sum_val)
11050 				sum_val = ~(adj - sum_val) & 0xFFFF;
11051 			else
11052 				sum_val -= adj;
11053 		}
11054 	} else {
11055 		sum_val = 0;
11056 		sum_flags = 0;
11057 	}
11058 
11059 	/* Clear hardware checksumming flag */
11060 	DB_CKSUMFLAGS(mp) = 0;
11061 
11062 	ident = ipha->ipha_ident;
11063 	offset = (frag_offset_flags << 3) & 0xFFFF;
11064 	src = ipha->ipha_src;
11065 	dst = ipha->ipha_dst;
11066 	hdr_length = IPH_HDR_LENGTH(ipha);
11067 	end = ntohs(ipha->ipha_length) - hdr_length;
11068 
11069 	/* If end == 0 then we have a packet with no data, so just free it */
11070 	if (end == 0) {
11071 		freemsg(mp);
11072 		return (B_FALSE);
11073 	}
11074 
11075 	/* Record the ECN field info. */
11076 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11077 	if (offset != 0) {
11078 		/*
11079 		 * If this isn't the first piece, strip the header, and
11080 		 * add the offset to the end value.
11081 		 */
11082 		mp->b_rptr += hdr_length;
11083 		end += offset;
11084 	}
11085 
11086 	msg_len = MBLKSIZE(mp);
11087 	tail_mp = mp;
11088 	while (tail_mp->b_cont != NULL) {
11089 		tail_mp = tail_mp->b_cont;
11090 		msg_len += MBLKSIZE(tail_mp);
11091 	}
11092 
11093 	/* If the reassembly list for this ILL will get too big, prune it */
11094 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11095 	    ip_reass_queue_bytes) {
11096 		ill_frag_prune(ill,
11097 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11098 		    (ip_reass_queue_bytes - msg_len));
11099 		pruned = B_TRUE;
11100 	}
11101 
11102 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11103 	mutex_enter(&ipfb->ipfb_lock);
11104 
11105 	ipfp = &ipfb->ipfb_ipf;
11106 	/* Try to find an existing fragment queue for this packet. */
11107 	for (;;) {
11108 		ipf = ipfp[0];
11109 		if (ipf != NULL) {
11110 			/*
11111 			 * It has to match on ident and src/dst address.
11112 			 */
11113 			if (ipf->ipf_ident == ident &&
11114 			    ipf->ipf_src == src &&
11115 			    ipf->ipf_dst == dst &&
11116 			    ipf->ipf_protocol == proto) {
11117 				/*
11118 				 * If we have received too many
11119 				 * duplicate fragments for this packet
11120 				 * free it.
11121 				 */
11122 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11123 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11124 					freemsg(mp);
11125 					mutex_exit(&ipfb->ipfb_lock);
11126 					return (B_FALSE);
11127 				}
11128 				/* Found it. */
11129 				break;
11130 			}
11131 			ipfp = &ipf->ipf_hash_next;
11132 			continue;
11133 		}
11134 
11135 		/*
11136 		 * If we pruned the list, do we want to store this new
11137 		 * fragment?. We apply an optimization here based on the
11138 		 * fact that most fragments will be received in order.
11139 		 * So if the offset of this incoming fragment is zero,
11140 		 * it is the first fragment of a new packet. We will
11141 		 * keep it.  Otherwise drop the fragment, as we have
11142 		 * probably pruned the packet already (since the
11143 		 * packet cannot be found).
11144 		 */
11145 		if (pruned && offset != 0) {
11146 			mutex_exit(&ipfb->ipfb_lock);
11147 			freemsg(mp);
11148 			return (B_FALSE);
11149 		}
11150 
11151 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11152 			/*
11153 			 * Too many fragmented packets in this hash
11154 			 * bucket. Free the oldest.
11155 			 */
11156 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11157 		}
11158 
11159 		/* New guy.  Allocate a frag message. */
11160 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11161 		if (mp1 == NULL) {
11162 			BUMP_MIB(&ip_mib, ipInDiscards);
11163 			freemsg(mp);
11164 reass_done:
11165 			mutex_exit(&ipfb->ipfb_lock);
11166 			return (B_FALSE);
11167 		}
11168 
11169 
11170 		BUMP_MIB(&ip_mib, ipReasmReqds);
11171 		mp1->b_cont = mp;
11172 
11173 		/* Initialize the fragment header. */
11174 		ipf = (ipf_t *)mp1->b_rptr;
11175 		ipf->ipf_mp = mp1;
11176 		ipf->ipf_ptphn = ipfp;
11177 		ipfp[0] = ipf;
11178 		ipf->ipf_hash_next = NULL;
11179 		ipf->ipf_ident = ident;
11180 		ipf->ipf_protocol = proto;
11181 		ipf->ipf_src = src;
11182 		ipf->ipf_dst = dst;
11183 		ipf->ipf_nf_hdr_len = 0;
11184 		/* Record reassembly start time. */
11185 		ipf->ipf_timestamp = gethrestime_sec();
11186 		/* Record ipf generation and account for frag header */
11187 		ipf->ipf_gen = ill->ill_ipf_gen++;
11188 		ipf->ipf_count = MBLKSIZE(mp1);
11189 		ipf->ipf_last_frag_seen = B_FALSE;
11190 		ipf->ipf_ecn = ecn_info;
11191 		ipf->ipf_num_dups = 0;
11192 		ipfb->ipfb_frag_pkts++;
11193 		ipf->ipf_checksum = 0;
11194 		ipf->ipf_checksum_flags = 0;
11195 
11196 		/* Store checksum value in fragment header */
11197 		if (sum_flags != 0) {
11198 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11199 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11200 			ipf->ipf_checksum = sum_val;
11201 			ipf->ipf_checksum_flags = sum_flags;
11202 		}
11203 
11204 		/*
11205 		 * We handle reassembly two ways.  In the easy case,
11206 		 * where all the fragments show up in order, we do
11207 		 * minimal bookkeeping, and just clip new pieces on
11208 		 * the end.  If we ever see a hole, then we go off
11209 		 * to ip_reassemble which has to mark the pieces and
11210 		 * keep track of the number of holes, etc.  Obviously,
11211 		 * the point of having both mechanisms is so we can
11212 		 * handle the easy case as efficiently as possible.
11213 		 */
11214 		if (offset == 0) {
11215 			/* Easy case, in-order reassembly so far. */
11216 			ipf->ipf_count += msg_len;
11217 			ipf->ipf_tail_mp = tail_mp;
11218 			/*
11219 			 * Keep track of next expected offset in
11220 			 * ipf_end.
11221 			 */
11222 			ipf->ipf_end = end;
11223 			ipf->ipf_nf_hdr_len = hdr_length;
11224 		} else {
11225 			/* Hard case, hole at the beginning. */
11226 			ipf->ipf_tail_mp = NULL;
11227 			/*
11228 			 * ipf_end == 0 means that we have given up
11229 			 * on easy reassembly.
11230 			 */
11231 			ipf->ipf_end = 0;
11232 
11233 			/* Forget checksum offload from now on */
11234 			ipf->ipf_checksum_flags = 0;
11235 
11236 			/*
11237 			 * ipf_hole_cnt is set by ip_reassemble.
11238 			 * ipf_count is updated by ip_reassemble.
11239 			 * No need to check for return value here
11240 			 * as we don't expect reassembly to complete
11241 			 * or fail for the first fragment itself.
11242 			 */
11243 			(void) ip_reassemble(mp, ipf,
11244 			    (frag_offset_flags & IPH_OFFSET) << 3,
11245 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11246 		}
11247 		/* Update per ipfb and ill byte counts */
11248 		ipfb->ipfb_count += ipf->ipf_count;
11249 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11250 		ill->ill_frag_count += ipf->ipf_count;
11251 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11252 		/* If the frag timer wasn't already going, start it. */
11253 		mutex_enter(&ill->ill_lock);
11254 		ill_frag_timer_start(ill);
11255 		mutex_exit(&ill->ill_lock);
11256 		goto reass_done;
11257 	}
11258 
11259 	/*
11260 	 * If the packet's flag has changed (it could be coming up
11261 	 * from an interface different than the previous, therefore
11262 	 * possibly different checksum capability), then forget about
11263 	 * any stored checksum states.  Otherwise add the value to
11264 	 * the existing one stored in the fragment header.
11265 	 */
11266 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11267 		sum_val += ipf->ipf_checksum;
11268 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11269 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11270 		ipf->ipf_checksum = sum_val;
11271 	} else if (ipf->ipf_checksum_flags != 0) {
11272 		/* Forget checksum offload from now on */
11273 		ipf->ipf_checksum_flags = 0;
11274 	}
11275 
11276 	/*
11277 	 * We have a new piece of a datagram which is already being
11278 	 * reassembled.  Update the ECN info if all IP fragments
11279 	 * are ECN capable.  If there is one which is not, clear
11280 	 * all the info.  If there is at least one which has CE
11281 	 * code point, IP needs to report that up to transport.
11282 	 */
11283 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11284 		if (ecn_info == IPH_ECN_CE)
11285 			ipf->ipf_ecn = IPH_ECN_CE;
11286 	} else {
11287 		ipf->ipf_ecn = IPH_ECN_NECT;
11288 	}
11289 	if (offset && ipf->ipf_end == offset) {
11290 		/* The new fragment fits at the end */
11291 		ipf->ipf_tail_mp->b_cont = mp;
11292 		/* Update the byte count */
11293 		ipf->ipf_count += msg_len;
11294 		/* Update per ipfb and ill byte counts */
11295 		ipfb->ipfb_count += msg_len;
11296 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11297 		ill->ill_frag_count += msg_len;
11298 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11299 		if (frag_offset_flags & IPH_MF) {
11300 			/* More to come. */
11301 			ipf->ipf_end = end;
11302 			ipf->ipf_tail_mp = tail_mp;
11303 			goto reass_done;
11304 		}
11305 	} else {
11306 		/* Go do the hard cases. */
11307 		int ret;
11308 
11309 		if (offset == 0)
11310 			ipf->ipf_nf_hdr_len = hdr_length;
11311 
11312 		/* Save current byte count */
11313 		count = ipf->ipf_count;
11314 		ret = ip_reassemble(mp, ipf,
11315 		    (frag_offset_flags & IPH_OFFSET) << 3,
11316 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11317 		/* Count of bytes added and subtracted (freeb()ed) */
11318 		count = ipf->ipf_count - count;
11319 		if (count) {
11320 			/* Update per ipfb and ill byte counts */
11321 			ipfb->ipfb_count += count;
11322 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11323 			ill->ill_frag_count += count;
11324 			ASSERT(ill->ill_frag_count > 0);
11325 		}
11326 		if (ret == IP_REASS_PARTIAL) {
11327 			goto reass_done;
11328 		} else if (ret == IP_REASS_FAILED) {
11329 			/* Reassembly failed. Free up all resources */
11330 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11331 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11332 				IP_REASS_SET_START(t_mp, 0);
11333 				IP_REASS_SET_END(t_mp, 0);
11334 			}
11335 			freemsg(mp);
11336 			goto reass_done;
11337 		}
11338 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11339 	}
11340 	/*
11341 	 * We have completed reassembly.  Unhook the frag header from
11342 	 * the reassembly list.
11343 	 *
11344 	 * Before we free the frag header, record the ECN info
11345 	 * to report back to the transport.
11346 	 */
11347 	ecn_info = ipf->ipf_ecn;
11348 	BUMP_MIB(&ip_mib, ipReasmOKs);
11349 	ipfp = ipf->ipf_ptphn;
11350 
11351 	/* We need to supply these to caller */
11352 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11353 		sum_val = ipf->ipf_checksum;
11354 	else
11355 		sum_val = 0;
11356 
11357 	mp1 = ipf->ipf_mp;
11358 	count = ipf->ipf_count;
11359 	ipf = ipf->ipf_hash_next;
11360 	if (ipf != NULL)
11361 		ipf->ipf_ptphn = ipfp;
11362 	ipfp[0] = ipf;
11363 	ill->ill_frag_count -= count;
11364 	ASSERT(ipfb->ipfb_count >= count);
11365 	ipfb->ipfb_count -= count;
11366 	ipfb->ipfb_frag_pkts--;
11367 	mutex_exit(&ipfb->ipfb_lock);
11368 	/* Ditch the frag header. */
11369 	mp = mp1->b_cont;
11370 
11371 	freeb(mp1);
11372 
11373 	/* Restore original IP length in header. */
11374 	packet_size = (uint32_t)msgdsize(mp);
11375 	if (packet_size > IP_MAXPACKET) {
11376 		freemsg(mp);
11377 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11378 		return (B_FALSE);
11379 	}
11380 
11381 	if (DB_REF(mp) > 1) {
11382 		mblk_t *mp2 = copymsg(mp);
11383 
11384 		freemsg(mp);
11385 		if (mp2 == NULL) {
11386 			BUMP_MIB(&ip_mib, ipInDiscards);
11387 			return (B_FALSE);
11388 		}
11389 		mp = mp2;
11390 	}
11391 	ipha = (ipha_t *)mp->b_rptr;
11392 
11393 	ipha->ipha_length = htons((uint16_t)packet_size);
11394 	/* We're now complete, zip the frag state */
11395 	ipha->ipha_fragment_offset_and_flags = 0;
11396 	/* Record the ECN info. */
11397 	ipha->ipha_type_of_service &= 0xFC;
11398 	ipha->ipha_type_of_service |= ecn_info;
11399 	*mpp = mp;
11400 
11401 	/* Reassembly is successful; return checksum information if needed */
11402 	if (cksum_val != NULL)
11403 		*cksum_val = sum_val;
11404 	if (cksum_flags != NULL)
11405 		*cksum_flags = sum_flags;
11406 
11407 	return (B_TRUE);
11408 }
11409 
11410 /*
11411  * Perform ip header check sum update local options.
11412  * return B_TRUE if all is well, else return B_FALSE and release
11413  * the mp. caller is responsible for decrementing ire ref cnt.
11414  */
11415 static boolean_t
11416 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11417 {
11418 	mblk_t		*first_mp;
11419 	boolean_t	mctl_present;
11420 	uint16_t	sum;
11421 
11422 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11423 	/*
11424 	 * Don't do the checksum if it has gone through AH/ESP
11425 	 * processing.
11426 	 */
11427 	if (!mctl_present) {
11428 		sum = ip_csum_hdr(ipha);
11429 		if (sum != 0) {
11430 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11431 			freemsg(first_mp);
11432 			return (B_FALSE);
11433 		}
11434 	}
11435 
11436 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11437 		if (mctl_present)
11438 			freeb(first_mp);
11439 		return (B_FALSE);
11440 	}
11441 
11442 	return (B_TRUE);
11443 }
11444 
11445 /*
11446  * All udp packet are delivered to the local host via this routine.
11447  */
11448 void
11449 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11450     ill_t *recv_ill)
11451 {
11452 	uint32_t	sum;
11453 	uint32_t	u1;
11454 	boolean_t	mctl_present;
11455 	conn_t		*connp;
11456 	mblk_t		*first_mp;
11457 	uint16_t	*up;
11458 	ill_t		*ill = (ill_t *)q->q_ptr;
11459 	uint16_t	reass_hck_flags = 0;
11460 
11461 #define	rptr    ((uchar_t *)ipha)
11462 
11463 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11464 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11465 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11466 
11467 	/*
11468 	 * FAST PATH for udp packets
11469 	 */
11470 
11471 	/* u1 is # words of IP options */
11472 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11473 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11474 
11475 	/* IP options present */
11476 	if (u1 != 0)
11477 		goto ipoptions;
11478 
11479 	/* Check the IP header checksum.  */
11480 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11481 		/* Clear the IP header h/w cksum flag */
11482 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11483 	} else {
11484 #define	uph	((uint16_t *)ipha)
11485 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11486 		    uph[6] + uph[7] + uph[8] + uph[9];
11487 #undef	uph
11488 		/* finish doing IP checksum */
11489 		sum = (sum & 0xFFFF) + (sum >> 16);
11490 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11491 		/*
11492 		 * Don't verify header checksum if this packet is coming
11493 		 * back from AH/ESP as we already did it.
11494 		 */
11495 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
11496 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11497 			freemsg(first_mp);
11498 			return;
11499 		}
11500 	}
11501 
11502 	/*
11503 	 * Count for SNMP of inbound packets for ire.
11504 	 * if mctl is present this might be a secure packet and
11505 	 * has already been counted for in ip_proto_input().
11506 	 */
11507 	if (!mctl_present) {
11508 		UPDATE_IB_PKT_COUNT(ire);
11509 		ire->ire_last_used_time = lbolt;
11510 	}
11511 
11512 	/* packet part of fragmented IP packet? */
11513 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11514 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11515 		goto fragmented;
11516 	}
11517 
11518 	/* u1 = IP header length (20 bytes) */
11519 	u1 = IP_SIMPLE_HDR_LENGTH;
11520 
11521 	/* packet does not contain complete IP & UDP headers */
11522 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11523 		goto udppullup;
11524 
11525 	/* up points to UDP header */
11526 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11527 #define	iphs    ((uint16_t *)ipha)
11528 
11529 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11530 	if (up[3] != 0) {
11531 		mblk_t *mp1 = mp->b_cont;
11532 		boolean_t cksum_err;
11533 		uint16_t hck_flags = 0;
11534 
11535 		/* Pseudo-header checksum */
11536 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11537 		    iphs[9] + up[2];
11538 
11539 		/*
11540 		 * Revert to software checksum calculation if the interface
11541 		 * isn't capable of checksum offload or if IPsec is present.
11542 		 */
11543 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11544 			hck_flags = DB_CKSUMFLAGS(mp);
11545 
11546 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11547 			IP_STAT(ip_in_sw_cksum);
11548 
11549 		IP_CKSUM_RECV(hck_flags, u1,
11550 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11551 		    (int32_t)((uchar_t *)up - rptr),
11552 		    mp, mp1, cksum_err);
11553 
11554 		if (cksum_err) {
11555 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11556 
11557 			if (hck_flags & HCK_FULLCKSUM)
11558 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11559 			else if (hck_flags & HCK_PARTIALCKSUM)
11560 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11561 			else
11562 				IP_STAT(ip_udp_in_sw_cksum_err);
11563 
11564 			freemsg(first_mp);
11565 			return;
11566 		}
11567 	}
11568 
11569 	/* Non-fragmented broadcast or multicast packet? */
11570 	if (ire->ire_type == IRE_BROADCAST)
11571 		goto udpslowpath;
11572 
11573 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11574 	    ire->ire_zoneid)) != NULL) {
11575 		ASSERT(connp->conn_upq != NULL);
11576 		IP_STAT(ip_udp_fast_path);
11577 
11578 		if (CONN_UDP_FLOWCTLD(connp)) {
11579 			freemsg(mp);
11580 			BUMP_MIB(&ip_mib, udpInOverflows);
11581 		} else {
11582 			if (!mctl_present) {
11583 				BUMP_MIB(&ip_mib, ipInDelivers);
11584 			}
11585 			/*
11586 			 * mp and first_mp can change.
11587 			 */
11588 			if (ip_udp_check(q, connp, recv_ill,
11589 			    ipha, &mp, &first_mp, mctl_present)) {
11590 				/* Send it upstream */
11591 				CONN_UDP_RECV(connp, mp);
11592 			}
11593 		}
11594 		/*
11595 		 * freeb() cannot deal with null mblk being passed
11596 		 * in and first_mp can be set to null in the call
11597 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11598 		 */
11599 		if (mctl_present && first_mp != NULL) {
11600 			freeb(first_mp);
11601 		}
11602 		CONN_DEC_REF(connp);
11603 		return;
11604 	}
11605 
11606 	/*
11607 	 * if we got here we know the packet is not fragmented and
11608 	 * has no options. The classifier could not find a conn_t and
11609 	 * most likely its an icmp packet so send it through slow path.
11610 	 */
11611 
11612 	goto udpslowpath;
11613 
11614 ipoptions:
11615 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11616 		goto slow_done;
11617 	}
11618 
11619 	UPDATE_IB_PKT_COUNT(ire);
11620 	ire->ire_last_used_time = lbolt;
11621 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11622 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11623 fragmented:
11624 		/*
11625 		 * "sum" and "reass_hck_flags" are non-zero if the
11626 		 * reassembled packet has a valid hardware computed
11627 		 * checksum information associated with it.
11628 		 */
11629 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
11630 			goto slow_done;
11631 		/*
11632 		 * Make sure that first_mp points back to mp as
11633 		 * the mp we came in with could have changed in
11634 		 * ip_rput_fragment().
11635 		 */
11636 		ASSERT(!mctl_present);
11637 		ipha = (ipha_t *)mp->b_rptr;
11638 		first_mp = mp;
11639 	}
11640 
11641 	/* Now we have a complete datagram, destined for this machine. */
11642 	u1 = IPH_HDR_LENGTH(ipha);
11643 	/* Pull up the UDP header, if necessary. */
11644 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
11645 udppullup:
11646 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11647 			BUMP_MIB(&ip_mib, ipInDiscards);
11648 			freemsg(first_mp);
11649 			goto slow_done;
11650 		}
11651 		ipha = (ipha_t *)mp->b_rptr;
11652 	}
11653 
11654 	/*
11655 	 * Validate the checksum for the reassembled packet; for the
11656 	 * pullup case we calculate the payload checksum in software.
11657 	 */
11658 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11659 	if (up[3] != 0) {
11660 		boolean_t cksum_err;
11661 
11662 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11663 			IP_STAT(ip_in_sw_cksum);
11664 
11665 		IP_CKSUM_RECV_REASS(reass_hck_flags,
11666 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11667 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11668 		    iphs[9] + up[2], sum, cksum_err);
11669 
11670 		if (cksum_err) {
11671 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11672 
11673 			if (reass_hck_flags & HCK_FULLCKSUM)
11674 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11675 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
11676 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11677 			else
11678 				IP_STAT(ip_udp_in_sw_cksum_err);
11679 
11680 			freemsg(first_mp);
11681 			goto slow_done;
11682 		}
11683 	}
11684 udpslowpath:
11685 
11686 	/* Clear hardware checksum flag to be safe */
11687 	DB_CKSUMFLAGS(mp) = 0;
11688 
11689 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
11690 	    (ire->ire_type == IRE_BROADCAST),
11691 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11692 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11693 
11694 slow_done:
11695 	IP_STAT(ip_udp_slow_path);
11696 	return;
11697 
11698 #undef  iphs
11699 #undef  rptr
11700 }
11701 
11702 /* ARGSUSED */
11703 static mblk_t *
11704 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11705     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11706     ill_rx_ring_t *ill_ring)
11707 {
11708 	conn_t		*connp;
11709 	uint32_t	sum;
11710 	uint32_t	u1;
11711 	uint16_t	*up;
11712 	int		offset;
11713 	ssize_t		len;
11714 	mblk_t		*mp1;
11715 	boolean_t	syn_present = B_FALSE;
11716 	tcph_t		*tcph;
11717 	uint_t		ip_hdr_len;
11718 	ill_t		*ill = (ill_t *)q->q_ptr;
11719 	zoneid_t	zoneid = ire->ire_zoneid;
11720 	boolean_t	cksum_err;
11721 	uint16_t	hck_flags = 0;
11722 
11723 #define	rptr	((uchar_t *)ipha)
11724 
11725 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11726 
11727 	/*
11728 	 * FAST PATH for tcp packets
11729 	 */
11730 
11731 	/* u1 is # words of IP options */
11732 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11733 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11734 
11735 	/* IP options present */
11736 	if (u1) {
11737 		goto ipoptions;
11738 	} else {
11739 		/* Check the IP header checksum.  */
11740 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11741 			/* Clear the IP header h/w cksum flag */
11742 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11743 		} else {
11744 #define	uph	((uint16_t *)ipha)
11745 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11746 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11747 #undef	uph
11748 			/* finish doing IP checksum */
11749 			sum = (sum & 0xFFFF) + (sum >> 16);
11750 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11751 			/*
11752 			 * Don't verify header checksum if this packet
11753 			 * is coming back from AH/ESP as we already did it.
11754 			 */
11755 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11756 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11757 				goto error;
11758 			}
11759 		}
11760 	}
11761 
11762 	if (!mctl_present) {
11763 		UPDATE_IB_PKT_COUNT(ire);
11764 		ire->ire_last_used_time = lbolt;
11765 	}
11766 
11767 	/* packet part of fragmented IP packet? */
11768 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11769 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11770 		goto fragmented;
11771 	}
11772 
11773 	/* u1 = IP header length (20 bytes) */
11774 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11775 
11776 	/* does packet contain IP+TCP headers? */
11777 	len = mp->b_wptr - rptr;
11778 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11779 		IP_STAT(ip_tcppullup);
11780 		goto tcppullup;
11781 	}
11782 
11783 	/* TCP options present? */
11784 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11785 
11786 	/*
11787 	 * If options need to be pulled up, then goto tcpoptions.
11788 	 * otherwise we are still in the fast path
11789 	 */
11790 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11791 		IP_STAT(ip_tcpoptions);
11792 		goto tcpoptions;
11793 	}
11794 
11795 	/* multiple mblks of tcp data? */
11796 	if ((mp1 = mp->b_cont) != NULL) {
11797 		/* more then two? */
11798 		if (mp1->b_cont != NULL) {
11799 			IP_STAT(ip_multipkttcp);
11800 			goto multipkttcp;
11801 		}
11802 		len += mp1->b_wptr - mp1->b_rptr;
11803 	}
11804 
11805 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11806 
11807 	/* part of pseudo checksum */
11808 
11809 	/* TCP datagram length */
11810 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11811 
11812 #define	iphs    ((uint16_t *)ipha)
11813 
11814 #ifdef	_BIG_ENDIAN
11815 	u1 += IPPROTO_TCP;
11816 #else
11817 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11818 #endif
11819 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11820 
11821 	/*
11822 	 * Revert to software checksum calculation if the interface
11823 	 * isn't capable of checksum offload or if IPsec is present.
11824 	 */
11825 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11826 		hck_flags = DB_CKSUMFLAGS(mp);
11827 
11828 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11829 		IP_STAT(ip_in_sw_cksum);
11830 
11831 	IP_CKSUM_RECV(hck_flags, u1,
11832 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11833 	    (int32_t)((uchar_t *)up - rptr),
11834 	    mp, mp1, cksum_err);
11835 
11836 	if (cksum_err) {
11837 		BUMP_MIB(&ip_mib, tcpInErrs);
11838 
11839 		if (hck_flags & HCK_FULLCKSUM)
11840 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
11841 		else if (hck_flags & HCK_PARTIALCKSUM)
11842 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
11843 		else
11844 			IP_STAT(ip_tcp_in_sw_cksum_err);
11845 
11846 		goto error;
11847 	}
11848 
11849 try_again:
11850 
11851 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11852 	    NULL) {
11853 		/* Send the TH_RST */
11854 		goto no_conn;
11855 	}
11856 
11857 	/*
11858 	 * TCP FAST PATH for AF_INET socket.
11859 	 *
11860 	 * TCP fast path to avoid extra work. An AF_INET socket type
11861 	 * does not have facility to receive extra information via
11862 	 * ip_process or ip_add_info. Also, when the connection was
11863 	 * established, we made a check if this connection is impacted
11864 	 * by any global IPSec policy or per connection policy (a
11865 	 * policy that comes in effect later will not apply to this
11866 	 * connection). Since all this can be determined at the
11867 	 * connection establishment time, a quick check of flags
11868 	 * can avoid extra work.
11869 	 */
11870 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11871 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11872 		ASSERT(first_mp == mp);
11873 		SET_SQUEUE(mp, tcp_rput_data, connp);
11874 		return (mp);
11875 	}
11876 
11877 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11878 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11879 		if (IPCL_IS_TCP(connp)) {
11880 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11881 			DB_CKSUMSTART(mp) =
11882 			    (intptr_t)ip_squeue_get(ill_ring);
11883 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11884 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11885 				SET_SQUEUE(mp, connp->conn_recv, connp);
11886 				return (mp);
11887 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11888 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11889 				ip_squeue_enter_unbound++;
11890 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11891 				    connp);
11892 				return (mp);
11893 			}
11894 			syn_present = B_TRUE;
11895 		}
11896 
11897 	}
11898 
11899 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11900 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11901 
11902 		/* No need to send this packet to TCP */
11903 		if ((flags & TH_RST) || (flags & TH_URG)) {
11904 			CONN_DEC_REF(connp);
11905 			freemsg(first_mp);
11906 			return (NULL);
11907 		}
11908 		if (flags & TH_ACK) {
11909 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11910 			CONN_DEC_REF(connp);
11911 			return (NULL);
11912 		}
11913 
11914 		CONN_DEC_REF(connp);
11915 		freemsg(first_mp);
11916 		return (NULL);
11917 	}
11918 
11919 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11920 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11921 		    ipha, NULL, mctl_present);
11922 		if (first_mp == NULL) {
11923 			CONN_DEC_REF(connp);
11924 			return (NULL);
11925 		}
11926 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11927 			ASSERT(syn_present);
11928 			if (mctl_present) {
11929 				ASSERT(first_mp != mp);
11930 				first_mp->b_datap->db_struioflag |=
11931 				    STRUIO_POLICY;
11932 			} else {
11933 				ASSERT(first_mp == mp);
11934 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11935 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11936 			}
11937 		} else {
11938 			/*
11939 			 * Discard first_mp early since we're dealing with a
11940 			 * fully-connected conn_t and tcp doesn't do policy in
11941 			 * this case.
11942 			 */
11943 			if (mctl_present) {
11944 				freeb(first_mp);
11945 				mctl_present = B_FALSE;
11946 			}
11947 			first_mp = mp;
11948 		}
11949 	}
11950 
11951 	/* Initiate IPPF processing for fastpath */
11952 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11953 		uint32_t	ill_index;
11954 
11955 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11956 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11957 		if (mp == NULL) {
11958 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11959 			    "deferred/dropped during IPPF processing\n"));
11960 			CONN_DEC_REF(connp);
11961 			if (mctl_present)
11962 				freeb(first_mp);
11963 			return (NULL);
11964 		} else if (mctl_present) {
11965 			/*
11966 			 * ip_process might return a new mp.
11967 			 */
11968 			ASSERT(first_mp != mp);
11969 			first_mp->b_cont = mp;
11970 		} else {
11971 			first_mp = mp;
11972 		}
11973 
11974 	}
11975 
11976 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11977 		mp = ip_add_info(mp, recv_ill, flags);
11978 		if (mp == NULL) {
11979 			CONN_DEC_REF(connp);
11980 			if (mctl_present)
11981 				freeb(first_mp);
11982 			return (NULL);
11983 		} else if (mctl_present) {
11984 			/*
11985 			 * ip_add_info might return a new mp.
11986 			 */
11987 			ASSERT(first_mp != mp);
11988 			first_mp->b_cont = mp;
11989 		} else {
11990 			first_mp = mp;
11991 		}
11992 	}
11993 
11994 	if (IPCL_IS_TCP(connp)) {
11995 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11996 		return (first_mp);
11997 	} else {
11998 		putnext(connp->conn_rq, first_mp);
11999 		CONN_DEC_REF(connp);
12000 		return (NULL);
12001 	}
12002 
12003 no_conn:
12004 	/* Initiate IPPf processing, if needed. */
12005 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12006 		uint32_t ill_index;
12007 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12008 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12009 		if (first_mp == NULL) {
12010 			return (NULL);
12011 		}
12012 	}
12013 	BUMP_MIB(&ip_mib, ipInDelivers);
12014 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12015 	return (NULL);
12016 ipoptions:
12017 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12018 		goto slow_done;
12019 	}
12020 
12021 	UPDATE_IB_PKT_COUNT(ire);
12022 	ire->ire_last_used_time = lbolt;
12023 
12024 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12025 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12026 fragmented:
12027 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12028 			if (mctl_present)
12029 				freeb(first_mp);
12030 			goto slow_done;
12031 		}
12032 		/*
12033 		 * Make sure that first_mp points back to mp as
12034 		 * the mp we came in with could have changed in
12035 		 * ip_rput_fragment().
12036 		 */
12037 		ASSERT(!mctl_present);
12038 		ipha = (ipha_t *)mp->b_rptr;
12039 		first_mp = mp;
12040 	}
12041 
12042 tcp_slow:
12043 	/* Now we have a complete datagram, destined for this machine. */
12044 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12045 
12046 	len = mp->b_wptr - mp->b_rptr;
12047 	/* Pull up a minimal TCP header, if necessary. */
12048 	if (len < (u1 + 20)) {
12049 tcppullup:
12050 		if (!pullupmsg(mp, u1 + 20)) {
12051 			BUMP_MIB(&ip_mib, ipInDiscards);
12052 			goto error;
12053 		}
12054 		ipha = (ipha_t *)mp->b_rptr;
12055 		len = mp->b_wptr - mp->b_rptr;
12056 	}
12057 
12058 	/*
12059 	 * Extract the offset field from the TCP header.  As usual, we
12060 	 * try to help the compiler more than the reader.
12061 	 */
12062 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12063 	if (offset != 5) {
12064 tcpoptions:
12065 		if (offset < 5) {
12066 			BUMP_MIB(&ip_mib, ipInDiscards);
12067 			goto error;
12068 		}
12069 		/*
12070 		 * There must be TCP options.
12071 		 * Make sure we can grab them.
12072 		 */
12073 		offset <<= 2;
12074 		offset += u1;
12075 		if (len < offset) {
12076 			if (!pullupmsg(mp, offset)) {
12077 				BUMP_MIB(&ip_mib, ipInDiscards);
12078 				goto error;
12079 			}
12080 			ipha = (ipha_t *)mp->b_rptr;
12081 			len = mp->b_wptr - rptr;
12082 		}
12083 	}
12084 
12085 	/* Get the total packet length in len, including headers. */
12086 	if (mp->b_cont) {
12087 multipkttcp:
12088 		len = msgdsize(mp);
12089 	}
12090 
12091 	/*
12092 	 * Check the TCP checksum by pulling together the pseudo-
12093 	 * header checksum, and passing it to ip_csum to be added in
12094 	 * with the TCP datagram.
12095 	 *
12096 	 * Since we are not using the hwcksum if available we must
12097 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12098 	 * If either of these fails along the way the mblk is freed.
12099 	 * If this logic ever changes and mblk is reused to say send
12100 	 * ICMP's back, then this flag may need to be cleared in
12101 	 * other places as well.
12102 	 */
12103 	DB_CKSUMFLAGS(mp) = 0;
12104 
12105 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12106 
12107 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12108 #ifdef	_BIG_ENDIAN
12109 	u1 += IPPROTO_TCP;
12110 #else
12111 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12112 #endif
12113 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12114 	/*
12115 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12116 	 */
12117 	IP_STAT(ip_in_sw_cksum);
12118 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12119 		BUMP_MIB(&ip_mib, tcpInErrs);
12120 		goto error;
12121 	}
12122 
12123 	IP_STAT(ip_tcp_slow_path);
12124 	goto try_again;
12125 #undef  iphs
12126 #undef  rptr
12127 
12128 error:
12129 	freemsg(first_mp);
12130 slow_done:
12131 	return (NULL);
12132 }
12133 
12134 /* ARGSUSED */
12135 static void
12136 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12137     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12138 {
12139 	conn_t		*connp;
12140 	uint32_t	sum;
12141 	uint32_t	u1;
12142 	ssize_t		len;
12143 	sctp_hdr_t	*sctph;
12144 	zoneid_t	zoneid = ire->ire_zoneid;
12145 	uint32_t	pktsum;
12146 	uint32_t	calcsum;
12147 	uint32_t	ports;
12148 	uint_t		ipif_seqid;
12149 	in6_addr_t	map_src, map_dst;
12150 	ill_t		*ill = (ill_t *)q->q_ptr;
12151 
12152 #define	rptr	((uchar_t *)ipha)
12153 
12154 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12155 
12156 	/* u1 is # words of IP options */
12157 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12158 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12159 
12160 	/* IP options present */
12161 	if (u1 > 0) {
12162 		goto ipoptions;
12163 	} else {
12164 		/* Check the IP header checksum.  */
12165 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12166 			/*
12167 			 * Since there is no SCTP h/w cksum support yet, just
12168 			 * clear the flag.
12169 			 */
12170 			DB_CKSUMFLAGS(mp) = 0;
12171 		} else {
12172 #define	uph	((uint16_t *)ipha)
12173 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12174 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12175 #undef	uph
12176 			/* finish doing IP checksum */
12177 			sum = (sum & 0xFFFF) + (sum >> 16);
12178 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12179 			/*
12180 			 * Don't verify header checksum if this packet
12181 			 * is coming back from AH/ESP as we already did it.
12182 			 */
12183 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12184 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12185 				goto error;
12186 			}
12187 		}
12188 	}
12189 
12190 	/*
12191 	 * Don't verify header checksum if this packet is coming
12192 	 * back from AH/ESP as we already did it.
12193 	 */
12194 	if (!mctl_present) {
12195 		UPDATE_IB_PKT_COUNT(ire);
12196 		ire->ire_last_used_time = lbolt;
12197 	}
12198 
12199 	/* packet part of fragmented IP packet? */
12200 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12201 	if (u1 & (IPH_MF | IPH_OFFSET))
12202 		goto fragmented;
12203 
12204 	/* u1 = IP header length (20 bytes) */
12205 	u1 = IP_SIMPLE_HDR_LENGTH;
12206 
12207 find_sctp_client:
12208 	/* Pullup if we don't have the sctp common header. */
12209 	len = MBLKL(mp);
12210 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12211 		if (mp->b_cont == NULL ||
12212 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12213 			BUMP_MIB(&ip_mib, ipInDiscards);
12214 			goto error;
12215 		}
12216 		ipha = (ipha_t *)mp->b_rptr;
12217 		len = MBLKL(mp);
12218 	}
12219 
12220 	sctph = (sctp_hdr_t *)(rptr + u1);
12221 #ifdef	DEBUG
12222 	if (!skip_sctp_cksum) {
12223 #endif
12224 		pktsum = sctph->sh_chksum;
12225 		sctph->sh_chksum = 0;
12226 		calcsum = sctp_cksum(mp, u1);
12227 		if (calcsum != pktsum) {
12228 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12229 			goto error;
12230 		}
12231 		sctph->sh_chksum = pktsum;
12232 #ifdef	DEBUG	/* skip_sctp_cksum */
12233 	}
12234 #endif
12235 	/* get the ports */
12236 	ports = *(uint32_t *)&sctph->sh_sport;
12237 
12238 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12239 	IRE_REFRELE(ire);
12240 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12241 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12242 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12243 	    zoneid)) == NULL) {
12244 		/* Check for raw socket or OOTB handling */
12245 		goto no_conn;
12246 	}
12247 
12248 	/* Found a client; up it goes */
12249 	BUMP_MIB(&ip_mib, ipInDelivers);
12250 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12251 	return;
12252 
12253 no_conn:
12254 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12255 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12256 	return;
12257 
12258 ipoptions:
12259 	DB_CKSUMFLAGS(mp) = 0;
12260 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12261 		goto slow_done;
12262 
12263 	UPDATE_IB_PKT_COUNT(ire);
12264 	ire->ire_last_used_time = lbolt;
12265 
12266 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12267 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12268 fragmented:
12269 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12270 			goto slow_done;
12271 		/*
12272 		 * Make sure that first_mp points back to mp as
12273 		 * the mp we came in with could have changed in
12274 		 * ip_rput_fragment().
12275 		 */
12276 		ASSERT(!mctl_present);
12277 		ipha = (ipha_t *)mp->b_rptr;
12278 		first_mp = mp;
12279 	}
12280 
12281 	/* Now we have a complete datagram, destined for this machine. */
12282 	u1 = IPH_HDR_LENGTH(ipha);
12283 	goto find_sctp_client;
12284 #undef  iphs
12285 #undef  rptr
12286 
12287 error:
12288 	freemsg(first_mp);
12289 slow_done:
12290 	IRE_REFRELE(ire);
12291 }
12292 
12293 #define	VER_BITS	0xF0
12294 #define	VERSION_6	0x60
12295 
12296 static boolean_t
12297 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12298     ipaddr_t *dstp)
12299 {
12300 	uint_t	opt_len;
12301 	ipha_t *ipha;
12302 	ssize_t len;
12303 	uint_t	pkt_len;
12304 
12305 	IP_STAT(ip_ipoptions);
12306 	ipha = *iphapp;
12307 
12308 #define	rptr    ((uchar_t *)ipha)
12309 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12310 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12311 		BUMP_MIB(&ip_mib, ipInIPv6);
12312 		freemsg(mp);
12313 		return (B_FALSE);
12314 	}
12315 
12316 	/* multiple mblk or too short */
12317 	pkt_len = ntohs(ipha->ipha_length);
12318 
12319 	/* Get the number of words of IP options in the IP header. */
12320 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12321 	if (opt_len) {
12322 		/* IP Options present!  Validate and process. */
12323 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12324 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12325 			goto done;
12326 		}
12327 		/*
12328 		 * Recompute complete header length and make sure we
12329 		 * have access to all of it.
12330 		 */
12331 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12332 		if (len > (mp->b_wptr - rptr)) {
12333 			if (len > pkt_len) {
12334 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12335 				goto done;
12336 			}
12337 			if (!pullupmsg(mp, len)) {
12338 				BUMP_MIB(&ip_mib, ipInDiscards);
12339 				goto done;
12340 			}
12341 			ipha = (ipha_t *)mp->b_rptr;
12342 		}
12343 		/*
12344 		 * Go off to ip_rput_options which returns the next hop
12345 		 * destination address, which may have been affected
12346 		 * by source routing.
12347 		 */
12348 		IP_STAT(ip_opt);
12349 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12350 			return (B_FALSE);
12351 		}
12352 	}
12353 	*iphapp = ipha;
12354 	return (B_TRUE);
12355 done:
12356 	/* clear b_prev - used by ip_mroute_decap */
12357 	mp->b_prev = NULL;
12358 	freemsg(mp);
12359 	return (B_FALSE);
12360 #undef  rptr
12361 }
12362 
12363 /*
12364  * Deal with the fact that there is no ire for the destination.
12365  * The incoming ill (in_ill) is passed in to ip_newroute only
12366  * in the case of packets coming from mobile ip forward tunnel.
12367  * It must be null otherwise.
12368  */
12369 static void
12370 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12371     ipaddr_t dst)
12372 {
12373 	ipha_t	*ipha;
12374 	ill_t	*ill;
12375 
12376 	ipha = (ipha_t *)mp->b_rptr;
12377 	ill = (ill_t *)q->q_ptr;
12378 
12379 	ASSERT(ill != NULL);
12380 	/*
12381 	 * No IRE for this destination, so it can't be for us.
12382 	 * Unless we are forwarding, drop the packet.
12383 	 * We have to let source routed packets through
12384 	 * since we don't yet know if they are 'ping -l'
12385 	 * packets i.e. if they will go out over the
12386 	 * same interface as they came in on.
12387 	 */
12388 	if (ll_multicast) {
12389 		freemsg(mp);
12390 		return;
12391 	}
12392 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12393 		BUMP_MIB(&ip_mib, ipForwProhibits);
12394 		freemsg(mp);
12395 		return;
12396 	}
12397 
12398 	/* Check for Martian addresses */
12399 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12400 		freemsg(mp);
12401 		return;
12402 	}
12403 
12404 	/* Mark this packet as having originated externally */
12405 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12406 
12407 	/*
12408 	 * Clear the indication that this may have a hardware checksum
12409 	 * as we are not using it
12410 	 */
12411 	DB_CKSUMFLAGS(mp) = 0;
12412 
12413 	/*
12414 	 * Now hand the packet to ip_newroute.
12415 	 */
12416 	ip_newroute(q, mp, dst, in_ill, NULL);
12417 }
12418 
12419 /*
12420  * check ip header length and align it.
12421  */
12422 static boolean_t
12423 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12424 {
12425 	ssize_t len;
12426 	ill_t *ill;
12427 	ipha_t	*ipha;
12428 
12429 	len = MBLKL(mp);
12430 
12431 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12432 		if (!OK_32PTR(mp->b_rptr))
12433 			IP_STAT(ip_notaligned1);
12434 		else
12435 			IP_STAT(ip_notaligned2);
12436 		/* Guard against bogus device drivers */
12437 		if (len < 0) {
12438 			/* clear b_prev - used by ip_mroute_decap */
12439 			mp->b_prev = NULL;
12440 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12441 			freemsg(mp);
12442 			return (B_FALSE);
12443 		}
12444 
12445 		if (ip_rput_pullups++ == 0) {
12446 			ill = (ill_t *)q->q_ptr;
12447 			ipha = (ipha_t *)mp->b_rptr;
12448 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12449 			    "ip_check_and_align_header: %s forced us to "
12450 			    " pullup pkt, hdr len %ld, hdr addr %p",
12451 			    ill->ill_name, len, ipha);
12452 		}
12453 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12454 			/* clear b_prev - used by ip_mroute_decap */
12455 			mp->b_prev = NULL;
12456 			BUMP_MIB(&ip_mib, ipInDiscards);
12457 			freemsg(mp);
12458 			return (B_FALSE);
12459 		}
12460 	}
12461 	return (B_TRUE);
12462 }
12463 
12464 static boolean_t
12465 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12466 {
12467 	ill_group_t	*ill_group;
12468 	ill_group_t	*ire_group;
12469 	queue_t 	*q;
12470 	ill_t		*ire_ill;
12471 	uint_t		ill_ifindex;
12472 
12473 	q = *qp;
12474 	/*
12475 	 * We need to check to make sure the packet came in
12476 	 * on the queue associated with the destination IRE.
12477 	 * Note that for multicast packets and broadcast packets sent to
12478 	 * a broadcast address which is shared between multiple interfaces
12479 	 * we should not do this since we just got a random broadcast ire.
12480 	 */
12481 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12482 		boolean_t check_multi = B_TRUE;
12483 
12484 		/*
12485 		 * This packet came in on an interface other than the
12486 		 * one associated with the destination address.
12487 		 * "Gateway" it to the appropriate interface here.
12488 		 * As long as the ills belong to the same group,
12489 		 * we don't consider them to arriving on the wrong
12490 		 * interface. Thus, when the switch is doing inbound
12491 		 * load spreading, we won't drop packets when we
12492 		 * are doing strict multihoming checks. Note, the
12493 		 * same holds true for 'usesrc groups' where the
12494 		 * destination address may belong to another interface
12495 		 * to allow multipathing to happen
12496 		 */
12497 		ill_group = ill->ill_group;
12498 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12499 		ill_ifindex = ill->ill_usesrc_ifindex;
12500 		ire_group = ire_ill->ill_group;
12501 
12502 		/*
12503 		 * If it's part of the same IPMP group, or if it's a legal
12504 		 * address on the 'usesrc' interface, then bypass strict
12505 		 * checks.
12506 		 */
12507 		if (ill_group != NULL && ill_group == ire_group) {
12508 			check_multi = B_FALSE;
12509 		} else if (ill_ifindex != 0 &&
12510 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12511 			check_multi = B_FALSE;
12512 		}
12513 
12514 		if (check_multi &&
12515 		    ip_strict_dst_multihoming &&
12516 		    ((ill->ill_flags &
12517 		    ire->ire_ipif->ipif_ill->ill_flags &
12518 		    ILLF_ROUTER) == 0)) {
12519 			/* Drop packet */
12520 			BUMP_MIB(&ip_mib, ipForwProhibits);
12521 			freemsg(mp);
12522 			ire_refrele(ire);
12523 			return (B_TRUE);
12524 		}
12525 
12526 		/*
12527 		 * Change the queue (for non-virtual destination network
12528 		 * interfaces) and ip_rput_local will be called with the right
12529 		 * queue
12530 		 */
12531 		q = ire->ire_rfq;
12532 	}
12533 	/* Must be broadcast.  We'll take it. */
12534 	*qp = q;
12535 	return (B_FALSE);
12536 }
12537 
12538 static void
12539 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12540     ill_t *ill, int ll_multicast)
12541 {
12542 	ill_group_t	*ill_group;
12543 	ill_group_t	*ire_group;
12544 	queue_t	*dev_q;
12545 
12546 	ASSERT(ire->ire_stq != NULL);
12547 	if (ll_multicast != 0)
12548 		goto drop_pkt;
12549 
12550 	if (ip_no_forward(ipha, ill))
12551 		goto drop_pkt;
12552 
12553 	ill_group = ill->ill_group;
12554 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12555 	/*
12556 	 * Check if we want to forward this one at this time.
12557 	 * We allow source routed packets on a host provided that
12558 	 * they go out the same interface or same interface group
12559 	 * as they came in on.
12560 	 *
12561 	 * XXX To be quicker, we may wish to not chase pointers to
12562 	 * get the ILLF_ROUTER flag and instead store the
12563 	 * forwarding policy in the ire.  An unfortunate
12564 	 * side-effect of that would be requiring an ire flush
12565 	 * whenever the ILLF_ROUTER flag changes.
12566 	 */
12567 	if (((ill->ill_flags &
12568 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12569 	    ILLF_ROUTER) == 0) &&
12570 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12571 	    (ill_group != NULL && ill_group == ire_group)))) {
12572 		BUMP_MIB(&ip_mib, ipForwProhibits);
12573 		if (ip_source_routed(ipha)) {
12574 			q = WR(q);
12575 			/*
12576 			 * Clear the indication that this may have
12577 			 * hardware checksum as we are not using it.
12578 			 */
12579 			DB_CKSUMFLAGS(mp) = 0;
12580 			icmp_unreachable(q, mp,
12581 			    ICMP_SOURCE_ROUTE_FAILED);
12582 			ire_refrele(ire);
12583 			return;
12584 		}
12585 		goto drop_pkt;
12586 	}
12587 
12588 	/* Packet is being forwarded. Turning off hwcksum flag. */
12589 	DB_CKSUMFLAGS(mp) = 0;
12590 	if (ip_g_send_redirects) {
12591 		/*
12592 		 * Check whether the incoming interface and outgoing
12593 		 * interface is part of the same group. If so,
12594 		 * send redirects.
12595 		 *
12596 		 * Check the source address to see if it originated
12597 		 * on the same logical subnet it is going back out on.
12598 		 * If so, we should be able to send it a redirect.
12599 		 * Avoid sending a redirect if the destination
12600 		 * is directly connected (gw_addr == 0),
12601 		 * or if the packet was source routed out this
12602 		 * interface.
12603 		 */
12604 		ipaddr_t src;
12605 		mblk_t	*mp1;
12606 		ire_t	*src_ire = NULL;
12607 
12608 		/*
12609 		 * Check whether ire_rfq and q are from the same ill
12610 		 * or if they are not same, they at least belong
12611 		 * to the same group. If so, send redirects.
12612 		 */
12613 		if ((ire->ire_rfq == q ||
12614 		    (ill_group != NULL && ill_group == ire_group)) &&
12615 		    (ire->ire_gateway_addr != 0) &&
12616 		    !ip_source_routed(ipha)) {
12617 
12618 			src = ipha->ipha_src;
12619 			src_ire = ire_ftable_lookup(src, 0, 0,
12620 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12621 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12622 
12623 			if (src_ire != NULL) {
12624 				/*
12625 				 * The source is directly connected.
12626 				 * Just copy the ip header (which is
12627 				 * in the first mblk)
12628 				 */
12629 				mp1 = copyb(mp);
12630 				if (mp1 != NULL) {
12631 					icmp_send_redirect(WR(q), mp1,
12632 					    ire->ire_gateway_addr);
12633 				}
12634 				ire_refrele(src_ire);
12635 			}
12636 		}
12637 	}
12638 
12639 	dev_q = ire->ire_stq->q_next;
12640 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12641 		BUMP_MIB(&ip_mib, ipInDiscards);
12642 		freemsg(mp);
12643 		ire_refrele(ire);
12644 		return;
12645 	}
12646 
12647 	ip_rput_forward(ire, ipha, mp, ill);
12648 	IRE_REFRELE(ire);
12649 	return;
12650 
12651 drop_pkt:
12652 	ire_refrele(ire);
12653 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12654 	freemsg(mp);
12655 }
12656 
12657 static boolean_t
12658 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12659     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12660 {
12661 	queue_t		*q;
12662 	ire_t		*ire;
12663 	uint16_t	hcksumflags;
12664 
12665 	q = *qp;
12666 	ire = *irep;
12667 
12668 	/*
12669 	 * Clear the indication that this may have hardware
12670 	 * checksum as we are not using it for forwarding.
12671 	 */
12672 	hcksumflags = DB_CKSUMFLAGS(mp);
12673 	DB_CKSUMFLAGS(mp) = 0;
12674 
12675 	/*
12676 	 * Directed broadcast forwarding: if the packet came in over a
12677 	 * different interface then it is routed out over we can forward it.
12678 	 */
12679 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12680 		ire_refrele(ire);
12681 		freemsg(mp);
12682 		BUMP_MIB(&ip_mib, ipInDiscards);
12683 		return (B_TRUE);
12684 	}
12685 	/*
12686 	 * For multicast we have set dst to be INADDR_BROADCAST
12687 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12688 	 * only for broadcast packets.
12689 	 */
12690 	if (!CLASSD(ipha->ipha_dst)) {
12691 		ire_t *new_ire;
12692 		ipif_t *ipif;
12693 		/*
12694 		 * For ill groups, as the switch duplicates broadcasts
12695 		 * across all the ports, we need to filter out and
12696 		 * send up only one copy. There is one copy for every
12697 		 * broadcast address on each ill. Thus, we look for a
12698 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12699 		 * later to see whether this ill is eligible to receive
12700 		 * them or not. ill_nominate_bcast_rcv() nominates only
12701 		 * one set of IREs for receiving.
12702 		 */
12703 
12704 		ipif = ipif_get_next_ipif(NULL, ill);
12705 		if (ipif == NULL) {
12706 			ire_refrele(ire);
12707 			freemsg(mp);
12708 			BUMP_MIB(&ip_mib, ipInDiscards);
12709 			return (B_TRUE);
12710 		}
12711 		new_ire = ire_ctable_lookup(dst, 0, 0,
12712 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12713 		ipif_refrele(ipif);
12714 
12715 		if (new_ire != NULL) {
12716 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12717 				ire_refrele(ire);
12718 				ire_refrele(new_ire);
12719 				freemsg(mp);
12720 				BUMP_MIB(&ip_mib, ipInDiscards);
12721 				return (B_TRUE);
12722 			}
12723 			/*
12724 			 * In the special case of multirouted broadcast
12725 			 * packets, we unconditionally need to "gateway"
12726 			 * them to the appropriate interface here.
12727 			 * In the normal case, this cannot happen, because
12728 			 * there is no broadcast IRE tagged with the
12729 			 * RTF_MULTIRT flag.
12730 			 */
12731 			if (new_ire->ire_flags & RTF_MULTIRT) {
12732 				ire_refrele(new_ire);
12733 				if (ire->ire_rfq != NULL) {
12734 					q = ire->ire_rfq;
12735 					*qp = q;
12736 				}
12737 			} else {
12738 				ire_refrele(ire);
12739 				ire = new_ire;
12740 			}
12741 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12742 			if (!ip_g_forward_directed_bcast) {
12743 				/*
12744 				 * Free the message if
12745 				 * ip_g_forward_directed_bcast is turned
12746 				 * off for non-local broadcast.
12747 				 */
12748 				ire_refrele(ire);
12749 				freemsg(mp);
12750 				BUMP_MIB(&ip_mib, ipInDiscards);
12751 				return (B_TRUE);
12752 			}
12753 		} else {
12754 			/*
12755 			 * This CGTP packet successfully passed the
12756 			 * CGTP filter, but the related CGTP
12757 			 * broadcast IRE has not been found,
12758 			 * meaning that the redundant ipif is
12759 			 * probably down. However, if we discarded
12760 			 * this packet, its duplicate would be
12761 			 * filtered out by the CGTP filter so none
12762 			 * of them would get through. So we keep
12763 			 * going with this one.
12764 			 */
12765 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12766 			if (ire->ire_rfq != NULL) {
12767 				q = ire->ire_rfq;
12768 				*qp = q;
12769 			}
12770 		}
12771 	}
12772 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12773 		/*
12774 		 * Verify that there are not more then one
12775 		 * IRE_BROADCAST with this broadcast address which
12776 		 * has ire_stq set.
12777 		 * TODO: simplify, loop over all IRE's
12778 		 */
12779 		ire_t	*ire1;
12780 		int	num_stq = 0;
12781 		mblk_t	*mp1;
12782 
12783 		/* Find the first one with ire_stq set */
12784 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12785 		for (ire1 = ire; ire1 &&
12786 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12787 		    ire1 = ire1->ire_next)
12788 			;
12789 		if (ire1) {
12790 			ire_refrele(ire);
12791 			ire = ire1;
12792 			IRE_REFHOLD(ire);
12793 		}
12794 
12795 		/* Check if there are additional ones with stq set */
12796 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12797 			if (ire->ire_addr != ire1->ire_addr)
12798 				break;
12799 			if (ire1->ire_stq) {
12800 				num_stq++;
12801 				break;
12802 			}
12803 		}
12804 		rw_exit(&ire->ire_bucket->irb_lock);
12805 		if (num_stq == 1 && ire->ire_stq != NULL) {
12806 			ip1dbg(("ip_rput_process_broadcast: directed "
12807 			    "broadcast to 0x%x\n",
12808 			    ntohl(ire->ire_addr)));
12809 			mp1 = copymsg(mp);
12810 			if (mp1) {
12811 				switch (ipha->ipha_protocol) {
12812 				case IPPROTO_UDP:
12813 					ip_udp_input(q, mp1, ipha, ire, ill);
12814 					break;
12815 				default:
12816 					ip_proto_input(q, mp1, ipha, ire, ill);
12817 					break;
12818 				}
12819 			}
12820 			/*
12821 			 * Adjust ttl to 2 (1+1 - the forward engine
12822 			 * will decrement it by one.
12823 			 */
12824 			if (ip_csum_hdr(ipha)) {
12825 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12826 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12827 				freemsg(mp);
12828 				ire_refrele(ire);
12829 				return (B_TRUE);
12830 			}
12831 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12832 			ipha->ipha_hdr_checksum = 0;
12833 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12834 			ip_rput_process_forward(q, mp, ire, ipha,
12835 			    ill, ll_multicast);
12836 			return (B_TRUE);
12837 		}
12838 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12839 		    ntohl(ire->ire_addr)));
12840 	}
12841 
12842 	*irep = ire;
12843 
12844 	/* Restore any hardware checksum flags */
12845 	DB_CKSUMFLAGS(mp) = hcksumflags;
12846 	return (B_FALSE);
12847 }
12848 
12849 /* ARGSUSED */
12850 static boolean_t
12851 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12852     int *ll_multicast, ipaddr_t *dstp)
12853 {
12854 	/*
12855 	 * Forward packets only if we have joined the allmulti
12856 	 * group on this interface.
12857 	 */
12858 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12859 		int retval;
12860 
12861 		/*
12862 		 * Clear the indication that this may have hardware
12863 		 * checksum as we are not using it.
12864 		 */
12865 		DB_CKSUMFLAGS(mp) = 0;
12866 		retval = ip_mforward(ill, ipha, mp);
12867 		/* ip_mforward updates mib variables if needed */
12868 		/* clear b_prev - used by ip_mroute_decap */
12869 		mp->b_prev = NULL;
12870 
12871 		switch (retval) {
12872 		case 0:
12873 			/*
12874 			 * pkt is okay and arrived on phyint.
12875 			 *
12876 			 * If we are running as a multicast router
12877 			 * we need to see all IGMP and/or PIM packets.
12878 			 */
12879 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12880 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12881 				goto done;
12882 			}
12883 			break;
12884 		case -1:
12885 			/* pkt is mal-formed, toss it */
12886 			goto drop_pkt;
12887 		case 1:
12888 			/* pkt is okay and arrived on a tunnel */
12889 			/*
12890 			 * If we are running a multicast router
12891 			 *  we need to see all igmp packets.
12892 			 */
12893 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12894 				*dstp = INADDR_BROADCAST;
12895 				*ll_multicast = 1;
12896 				return (B_FALSE);
12897 			}
12898 
12899 			goto drop_pkt;
12900 		}
12901 	}
12902 
12903 	ILM_WALKER_HOLD(ill);
12904 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12905 		/*
12906 		 * This might just be caused by the fact that
12907 		 * multiple IP Multicast addresses map to the same
12908 		 * link layer multicast - no need to increment counter!
12909 		 */
12910 		ILM_WALKER_RELE(ill);
12911 		freemsg(mp);
12912 		return (B_TRUE);
12913 	}
12914 	ILM_WALKER_RELE(ill);
12915 done:
12916 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12917 	/*
12918 	 * This assumes the we deliver to all streams for multicast
12919 	 * and broadcast packets.
12920 	 */
12921 	*dstp = INADDR_BROADCAST;
12922 	*ll_multicast = 1;
12923 	return (B_FALSE);
12924 drop_pkt:
12925 	ip2dbg(("ip_rput: drop pkt\n"));
12926 	freemsg(mp);
12927 	return (B_TRUE);
12928 }
12929 
12930 static boolean_t
12931 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12932     int *ll_multicast, mblk_t **mpp)
12933 {
12934 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12935 	boolean_t must_copy = B_FALSE;
12936 	struct iocblk   *iocp;
12937 	ipha_t		*ipha;
12938 
12939 #define	rptr    ((uchar_t *)ipha)
12940 
12941 	first_mp = *first_mpp;
12942 	mp = *mpp;
12943 
12944 	ASSERT(first_mp == mp);
12945 
12946 	/*
12947 	 * if db_ref > 1 then copymsg and free original. Packet may be
12948 	 * changed and do not want other entity who has a reference to this
12949 	 * message to trip over the changes. This is a blind change because
12950 	 * trying to catch all places that might change packet is too
12951 	 * difficult (since it may be a module above this one)
12952 	 *
12953 	 * This corresponds to the non-fast path case. We walk down the full
12954 	 * chain in this case, and check the db_ref count of all the dblks,
12955 	 * and do a copymsg if required. It is possible that the db_ref counts
12956 	 * of the data blocks in the mblk chain can be different.
12957 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12958 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12959 	 * 'snoop' is running.
12960 	 */
12961 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12962 		if (mp1->b_datap->db_ref > 1) {
12963 			must_copy = B_TRUE;
12964 			break;
12965 		}
12966 	}
12967 
12968 	if (must_copy) {
12969 		mp1 = copymsg(mp);
12970 		if (mp1 == NULL) {
12971 			for (mp1 = mp; mp1 != NULL;
12972 			    mp1 = mp1->b_cont) {
12973 				mp1->b_next = NULL;
12974 				mp1->b_prev = NULL;
12975 			}
12976 			freemsg(mp);
12977 			BUMP_MIB(&ip_mib, ipInDiscards);
12978 			return (B_TRUE);
12979 		}
12980 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12981 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12982 			/* Copy b_next - used in M_BREAK messages */
12983 			to_mp->b_next = from_mp->b_next;
12984 			from_mp->b_next = NULL;
12985 			/* Copy b_prev - used by ip_mroute_decap */
12986 			to_mp->b_prev = from_mp->b_prev;
12987 			from_mp->b_prev = NULL;
12988 		}
12989 		*first_mpp = first_mp = mp1;
12990 		freemsg(mp);
12991 		mp = mp1;
12992 		*mpp = mp1;
12993 	}
12994 
12995 	ipha = (ipha_t *)mp->b_rptr;
12996 
12997 	/*
12998 	 * previous code has a case for M_DATA.
12999 	 * We want to check how that happens.
13000 	 */
13001 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13002 	switch (first_mp->b_datap->db_type) {
13003 	case M_PROTO:
13004 	case M_PCPROTO:
13005 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13006 		    DL_UNITDATA_IND) {
13007 			/* Go handle anything other than data elsewhere. */
13008 			ip_rput_dlpi(q, mp);
13009 			return (B_TRUE);
13010 		}
13011 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13012 		/* Ditch the DLPI header. */
13013 		mp1 = mp->b_cont;
13014 		ASSERT(first_mp == mp);
13015 		*first_mpp = mp1;
13016 		freeb(mp);
13017 		*mpp = mp1;
13018 		return (B_FALSE);
13019 	case M_BREAK:
13020 		/*
13021 		 * A packet arrives as M_BREAK following a cycle through
13022 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13023 		 * This is an IP datagram sans lower level header.
13024 		 * M_BREAK are also used to pass back in multicast packets
13025 		 * that are encapsulated with a source route.
13026 		 */
13027 		/* Ditch the M_BREAK mblk */
13028 		mp1 = mp->b_cont;
13029 		ASSERT(first_mp == mp);
13030 		*first_mpp = mp1;
13031 		freeb(mp);
13032 		mp = mp1;
13033 		mp->b_next = NULL;
13034 		*mpp = mp;
13035 		*ll_multicast = 0;
13036 		return (B_FALSE);
13037 	case M_IOCACK:
13038 		ip1dbg(("got iocack "));
13039 		iocp = (struct iocblk *)mp->b_rptr;
13040 		switch (iocp->ioc_cmd) {
13041 		case DL_IOC_HDR_INFO:
13042 			ill = (ill_t *)q->q_ptr;
13043 			ill_fastpath_ack(ill, mp);
13044 			return (B_TRUE);
13045 		case SIOCSTUNPARAM:
13046 		case OSIOCSTUNPARAM:
13047 			/* Go through qwriter_ip */
13048 			break;
13049 		case SIOCGTUNPARAM:
13050 		case OSIOCGTUNPARAM:
13051 			ip_rput_other(NULL, q, mp, NULL);
13052 			return (B_TRUE);
13053 		default:
13054 			putnext(q, mp);
13055 			return (B_TRUE);
13056 		}
13057 		/* FALLTHRU */
13058 	case M_ERROR:
13059 	case M_HANGUP:
13060 		/*
13061 		 * Since this is on the ill stream we unconditionally
13062 		 * bump up the refcount
13063 		 */
13064 		ill_refhold(ill);
13065 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13066 		    B_FALSE);
13067 		return (B_TRUE);
13068 	case M_CTL:
13069 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13070 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13071 			IPHADA_M_CTL)) {
13072 			/*
13073 			 * It's an IPsec accelerated packet.
13074 			 * Make sure that the ill from which we received the
13075 			 * packet has enabled IPsec hardware acceleration.
13076 			 */
13077 			if (!(ill->ill_capabilities &
13078 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13079 				/* IPsec kstats: bean counter */
13080 				freemsg(mp);
13081 				return (B_TRUE);
13082 			}
13083 
13084 			/*
13085 			 * Make mp point to the mblk following the M_CTL,
13086 			 * then process according to type of mp.
13087 			 * After this processing, first_mp will point to
13088 			 * the data-attributes and mp to the pkt following
13089 			 * the M_CTL.
13090 			 */
13091 			mp = first_mp->b_cont;
13092 			if (mp == NULL) {
13093 				freemsg(first_mp);
13094 				return (B_TRUE);
13095 			}
13096 			/*
13097 			 * A Hardware Accelerated packet can only be M_DATA
13098 			 * ESP or AH packet.
13099 			 */
13100 			if (mp->b_datap->db_type != M_DATA) {
13101 				/* non-M_DATA IPsec accelerated packet */
13102 				IPSECHW_DEBUG(IPSECHW_PKT,
13103 				    ("non-M_DATA IPsec accelerated pkt\n"));
13104 				freemsg(first_mp);
13105 				return (B_TRUE);
13106 			}
13107 			ipha = (ipha_t *)mp->b_rptr;
13108 			if (ipha->ipha_protocol != IPPROTO_AH &&
13109 			    ipha->ipha_protocol != IPPROTO_ESP) {
13110 				IPSECHW_DEBUG(IPSECHW_PKT,
13111 				    ("non-M_DATA IPsec accelerated pkt\n"));
13112 				freemsg(first_mp);
13113 				return (B_TRUE);
13114 			}
13115 			*mpp = mp;
13116 			return (B_FALSE);
13117 		}
13118 		putnext(q, mp);
13119 		return (B_TRUE);
13120 	case M_FLUSH:
13121 		if (*mp->b_rptr & FLUSHW) {
13122 			*mp->b_rptr &= ~FLUSHR;
13123 			qreply(q, mp);
13124 			return (B_TRUE);
13125 		}
13126 		freemsg(mp);
13127 		return (B_TRUE);
13128 	case M_IOCNAK:
13129 		ip1dbg(("got iocnak "));
13130 		iocp = (struct iocblk *)mp->b_rptr;
13131 		switch (iocp->ioc_cmd) {
13132 		case DL_IOC_HDR_INFO:
13133 		case SIOCSTUNPARAM:
13134 		case OSIOCSTUNPARAM:
13135 			/*
13136 			 * Since this is on the ill stream we unconditionally
13137 			 * bump up the refcount
13138 			 */
13139 			ill_refhold(ill);
13140 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13141 			    CUR_OP, B_FALSE);
13142 			return (B_TRUE);
13143 		case SIOCGTUNPARAM:
13144 		case OSIOCGTUNPARAM:
13145 			ip_rput_other(NULL, q, mp, NULL);
13146 			return (B_TRUE);
13147 		default:
13148 			break;
13149 		}
13150 		/* FALLTHRU */
13151 	default:
13152 		putnext(q, mp);
13153 		return (B_TRUE);
13154 	}
13155 }
13156 
13157 /* Read side put procedure.  Packets coming from the wire arrive here. */
13158 void
13159 ip_rput(queue_t *q, mblk_t *mp)
13160 {
13161 	ill_t		*ill;
13162 
13163 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13164 
13165 	ill = (ill_t *)q->q_ptr;
13166 
13167 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13168 		union DL_primitives *dl;
13169 
13170 		/*
13171 		 * Things are opening or closing. Only accept DLPI control
13172 		 * messages. In the open case, the ill->ill_ipif has not yet
13173 		 * been created. In the close case, things hanging off the
13174 		 * ill could have been freed already. In either case it
13175 		 * may not be safe to proceed further.
13176 		 */
13177 
13178 		dl = (union DL_primitives *)mp->b_rptr;
13179 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13180 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13181 			/*
13182 			 * Also SIOC[GS]TUN* ioctls can come here.
13183 			 */
13184 			inet_freemsg(mp);
13185 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13186 			    "ip_input_end: q %p (%S)", q, "uninit");
13187 			return;
13188 		}
13189 	}
13190 
13191 	/*
13192 	 * if db_ref > 1 then copymsg and free original. Packet may be
13193 	 * changed and we do not want the other entity who has a reference to
13194 	 * this message to trip over the changes. This is a blind change because
13195 	 * trying to catch all places that might change the packet is too
13196 	 * difficult.
13197 	 *
13198 	 * This corresponds to the fast path case, where we have a chain of
13199 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13200 	 * in the mblk chain. There doesn't seem to be a reason why a device
13201 	 * driver would send up data with varying db_ref counts in the mblk
13202 	 * chain. In any case the Fast path is a private interface, and our
13203 	 * drivers don't do such a thing. Given the above assumption, there is
13204 	 * no need to walk down the entire mblk chain (which could have a
13205 	 * potential performance problem)
13206 	 */
13207 	if (mp->b_datap->db_ref > 1) {
13208 		mblk_t  *mp1;
13209 		boolean_t adjusted = B_FALSE;
13210 		IP_STAT(ip_db_ref);
13211 
13212 		/*
13213 		 * The IP_RECVSLLA option depends on having the link layer
13214 		 * header. First check that:
13215 		 * a> the underlying device is of type ether, since this
13216 		 * option is currently supported only over ethernet.
13217 		 * b> there is enough room to copy over the link layer header.
13218 		 *
13219 		 * Once the checks are done, adjust rptr so that the link layer
13220 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13221 		 * be returned by some non-ethernet drivers but in this case the
13222 		 * second check will fail.
13223 		 */
13224 		if (ill->ill_type == IFT_ETHER &&
13225 		    (mp->b_rptr - mp->b_datap->db_base) >=
13226 		    sizeof (struct ether_header)) {
13227 			mp->b_rptr -= sizeof (struct ether_header);
13228 			adjusted = B_TRUE;
13229 		}
13230 		mp1 = copymsg(mp);
13231 		if (mp1 == NULL) {
13232 			/* Clear b_next - used in M_BREAK messages */
13233 			mp->b_next = NULL;
13234 			/* clear b_prev - used by ip_mroute_decap */
13235 			mp->b_prev = NULL;
13236 			freemsg(mp);
13237 			BUMP_MIB(&ip_mib, ipInDiscards);
13238 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13239 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13240 			return;
13241 		}
13242 		if (adjusted) {
13243 			/*
13244 			 * Copy is done. Restore the pointer in the _new_ mblk
13245 			 */
13246 			mp1->b_rptr += sizeof (struct ether_header);
13247 		}
13248 		/* Copy b_next - used in M_BREAK messages */
13249 		mp1->b_next = mp->b_next;
13250 		mp->b_next = NULL;
13251 		/* Copy b_prev - used by ip_mroute_decap */
13252 		mp1->b_prev = mp->b_prev;
13253 		mp->b_prev = NULL;
13254 		freemsg(mp);
13255 		mp = mp1;
13256 	}
13257 
13258 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13259 	    "ip_rput_end: q %p (%S)", q, "end");
13260 
13261 	ip_input(ill, NULL, mp, 0);
13262 }
13263 
13264 /*
13265  * Direct read side procedure capable of dealing with chains. GLDv3 based
13266  * drivers call this function directly with mblk chains while STREAMS
13267  * read side procedure ip_rput() calls this for single packet with ip_ring
13268  * set to NULL to process one packet at a time.
13269  *
13270  * The ill will always be valid if this function is called directly from
13271  * the driver.
13272  */
13273 /*ARGSUSED*/
13274 void
13275 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13276 {
13277 	ipaddr_t		dst;
13278 	ire_t			*ire;
13279 	ipha_t			*ipha;
13280 	uint_t			pkt_len;
13281 	ssize_t			len;
13282 	uint_t			opt_len;
13283 	int			ll_multicast;
13284 	int			cgtp_flt_pkt;
13285 	queue_t			*q = ill->ill_rq;
13286 	squeue_t		*curr_sqp = NULL;
13287 	mblk_t 			*head = NULL;
13288 	mblk_t			*tail = NULL;
13289 	mblk_t			*first_mp;
13290 	mblk_t 			*mp;
13291 	int			cnt = 0;
13292 
13293 	ASSERT(mp_chain != NULL);
13294 	ASSERT(ill != NULL);
13295 
13296 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13297 
13298 #define	rptr	((uchar_t *)ipha)
13299 
13300 	while (mp_chain != NULL) {
13301 		first_mp = mp = mp_chain;
13302 		mp_chain = mp_chain->b_next;
13303 		mp->b_next = NULL;
13304 		ll_multicast = 0;
13305 		ire = NULL;
13306 
13307 		/*
13308 		 * ip_input fast path
13309 		 */
13310 
13311 		/* mblk type is not M_DATA */
13312 		if (mp->b_datap->db_type != M_DATA) {
13313 			if (ip_rput_process_notdata(q, &first_mp, ill,
13314 			    &ll_multicast, &mp))
13315 				continue;
13316 		}
13317 
13318 		ASSERT(mp->b_datap->db_type == M_DATA);
13319 		ASSERT(mp->b_datap->db_ref == 1);
13320 
13321 		/*
13322 		 * Invoke the CGTP (multirouting) filtering module to process
13323 		 * the incoming packet. Packets identified as duplicates
13324 		 * must be discarded. Filtering is active only if the
13325 		 * the ip_cgtp_filter ndd variable is non-zero.
13326 		 */
13327 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13328 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13329 			cgtp_flt_pkt =
13330 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13331 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13332 				freemsg(first_mp);
13333 				continue;
13334 			}
13335 		}
13336 
13337 		ipha = (ipha_t *)mp->b_rptr;
13338 		len = mp->b_wptr - rptr;
13339 
13340 		BUMP_MIB(&ip_mib, ipInReceives);
13341 
13342 		/*
13343 		 * IP header ptr not aligned?
13344 		 * OR IP header not complete in first mblk
13345 		 */
13346 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13347 			if (!ip_check_and_align_header(q, mp))
13348 				continue;
13349 			ipha = (ipha_t *)mp->b_rptr;
13350 			len = mp->b_wptr - rptr;
13351 		}
13352 
13353 		/* multiple mblk or too short */
13354 		pkt_len = ntohs(ipha->ipha_length);
13355 		len -= pkt_len;
13356 		if (len != 0) {
13357 			/*
13358 			 * Make sure we have data length consistent
13359 			 * with the IP header.
13360 			 */
13361 			if (mp->b_cont == NULL) {
13362 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13363 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13364 					ip2dbg(("ip_input: drop pkt\n"));
13365 					freemsg(mp);
13366 					continue;
13367 				}
13368 				mp->b_wptr = rptr + pkt_len;
13369 			} else if (len += msgdsize(mp->b_cont)) {
13370 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13371 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13372 					ip2dbg(("ip_input: drop pkt\n"));
13373 					freemsg(mp);
13374 					continue;
13375 				}
13376 				(void) adjmsg(mp, -len);
13377 				IP_STAT(ip_multimblk3);
13378 			}
13379 		}
13380 
13381 		if (ip_loopback_src_or_dst(ipha, ill)) {
13382 			ip2dbg(("ip_input: drop pkt\n"));
13383 			freemsg(mp);
13384 			continue;
13385 		}
13386 
13387 		opt_len = ipha->ipha_version_and_hdr_length -
13388 		    IP_SIMPLE_HDR_VERSION;
13389 		/* IP version bad or there are IP options */
13390 		if (opt_len) {
13391 			if (len != 0)
13392 				IP_STAT(ip_multimblk4);
13393 			else
13394 				IP_STAT(ip_ipoptions);
13395 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13396 				continue;
13397 		} else {
13398 			dst = ipha->ipha_dst;
13399 		}
13400 
13401 		/*
13402 		 * If rsvpd is running, let RSVP daemon handle its processing
13403 		 * and forwarding of RSVP multicast/unicast packets.
13404 		 * If rsvpd is not running but mrouted is running, RSVP
13405 		 * multicast packets are forwarded as multicast traffic
13406 		 * and RSVP unicast packets are forwarded by unicast router.
13407 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13408 		 * packets are not forwarded, but the unicast packets are
13409 		 * forwarded like unicast traffic.
13410 		 */
13411 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13412 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13413 			/* RSVP packet and rsvpd running. Treat as ours */
13414 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13415 			/*
13416 			 * This assumes that we deliver to all streams for
13417 			 * multicast and broadcast packets.
13418 			 * We have to force ll_multicast to 1 to handle the
13419 			 * M_DATA messages passed in from ip_mroute_decap.
13420 			 */
13421 			dst = INADDR_BROADCAST;
13422 			ll_multicast = 1;
13423 		} else if (CLASSD(dst)) {
13424 			/* packet is multicast */
13425 			mp->b_next = NULL;
13426 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13427 			    &ll_multicast, &dst))
13428 				continue;
13429 		}
13430 
13431 
13432 		/*
13433 		 * Check if the packet is coming from the Mobile IP
13434 		 * forward tunnel interface
13435 		 */
13436 		if (ill->ill_srcif_refcnt > 0) {
13437 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13438 			    NULL, ill, MATCH_IRE_TYPE);
13439 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13440 			    ire->ire_ipif->ipif_net_type ==
13441 			    IRE_IF_RESOLVER) {
13442 				/* We need to resolve the link layer info */
13443 				ire_refrele(ire);
13444 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13445 				    ll_multicast, dst);
13446 				continue;
13447 			}
13448 		}
13449 
13450 		if (ire == NULL)
13451 			ire = ire_cache_lookup(dst, ALL_ZONES);
13452 
13453 		/*
13454 		 * If mipagent is running and reverse tunnel is created as per
13455 		 * mobile node request, then any packet coming through the
13456 		 * incoming interface from the mobile-node, should be reverse
13457 		 * tunneled to it's home agent except those that are destined
13458 		 * to foreign agent only.
13459 		 * This needs source address based ire lookup. The routing
13460 		 * entries for source address based lookup are only created by
13461 		 * mipagent program only when a reverse tunnel is created.
13462 		 * Reference : RFC2002, RFC2344
13463 		 */
13464 		if (ill->ill_mrtun_refcnt > 0) {
13465 			ipaddr_t	srcaddr;
13466 			ire_t		*tmp_ire;
13467 
13468 			tmp_ire = ire;	/* Save, we might need it later */
13469 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13470 			    ire->ire_type != IRE_BROADCAST)) {
13471 				srcaddr = ipha->ipha_src;
13472 				ire = ire_mrtun_lookup(srcaddr, ill);
13473 				if (ire != NULL) {
13474 					/*
13475 					 * Should not be getting iphada packet
13476 					 * here. we should only get those for
13477 					 * IRE_LOCAL traffic, excluded above.
13478 					 * Fail-safe (drop packet) in the event
13479 					 * hardware is misbehaving.
13480 					 */
13481 					if (first_mp != mp) {
13482 						/* IPsec KSTATS: beancount me */
13483 						freemsg(first_mp);
13484 					} else {
13485 						/*
13486 						 * This packet must be forwarded
13487 						 * to Reverse Tunnel
13488 						 */
13489 						ip_mrtun_forward(ire, ill, mp);
13490 					}
13491 					ire_refrele(ire);
13492 					if (tmp_ire != NULL)
13493 						ire_refrele(tmp_ire);
13494 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13495 					    "ip_input_end: q %p (%S)",
13496 					    q, "uninit");
13497 					continue;
13498 				}
13499 			}
13500 			/*
13501 			 * If this packet is from a non-mobilenode  or a
13502 			 * mobile-node which does not request reverse
13503 			 * tunnel service
13504 			 */
13505 			ire = tmp_ire;
13506 		}
13507 
13508 
13509 		/*
13510 		 * If we reach here that means the incoming packet satisfies
13511 		 * one of the following conditions:
13512 		 *   - packet is from a mobile node which does not request
13513 		 *	reverse tunnel
13514 		 *   - packet is from a non-mobile node, which is the most
13515 		 *	common case
13516 		 *   - packet is from a reverse tunnel enabled mobile node
13517 		 *	and destined to foreign agent only
13518 		 */
13519 
13520 		if (ire == NULL) {
13521 			/*
13522 			 * No IRE for this destination, so it can't be for us.
13523 			 * Unless we are forwarding, drop the packet.
13524 			 * We have to let source routed packets through
13525 			 * since we don't yet know if they are 'ping -l'
13526 			 * packets i.e. if they will go out over the
13527 			 * same interface as they came in on.
13528 			 */
13529 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13530 			continue;
13531 		}
13532 
13533 		/*
13534 		 * Broadcast IRE may indicate either broadcast or
13535 		 * multicast packet
13536 		 */
13537 		if (ire->ire_type == IRE_BROADCAST) {
13538 			/*
13539 			 * Skip broadcast checks if packet is UDP multicast;
13540 			 * we'd rather not enter ip_rput_process_broadcast()
13541 			 * unless the packet is broadcast for real, since
13542 			 * that routine is a no-op for multicast.
13543 			 */
13544 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
13545 			    !CLASSD(ipha->ipha_dst)) &&
13546 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13547 			    dst, cgtp_flt_pkt, ll_multicast)) {
13548 				continue;
13549 			}
13550 		} else if (ire->ire_stq != NULL) {
13551 			/* fowarding? */
13552 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13553 			    ll_multicast);
13554 			continue;
13555 		}
13556 
13557 		/* packet not for us */
13558 		if (ire->ire_rfq != q) {
13559 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13560 				continue;
13561 			}
13562 		}
13563 
13564 		switch (ipha->ipha_protocol) {
13565 		case IPPROTO_TCP:
13566 			ASSERT(first_mp == mp);
13567 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13568 				mp, 0, q, ip_ring)) != NULL) {
13569 				if (curr_sqp == NULL) {
13570 					curr_sqp = GET_SQUEUE(mp);
13571 					ASSERT(cnt == 0);
13572 					cnt++;
13573 					head = tail = mp;
13574 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13575 					ASSERT(tail != NULL);
13576 					cnt++;
13577 					tail->b_next = mp;
13578 					tail = mp;
13579 				} else {
13580 					/*
13581 					 * A different squeue. Send the
13582 					 * chain for the previous squeue on
13583 					 * its way. This shouldn't happen
13584 					 * often unless interrupt binding
13585 					 * changes.
13586 					 */
13587 					IP_STAT(ip_input_multi_squeue);
13588 					squeue_enter_chain(curr_sqp, head,
13589 					    tail, cnt, SQTAG_IP_INPUT);
13590 					curr_sqp = GET_SQUEUE(mp);
13591 					head = mp;
13592 					tail = mp;
13593 					cnt = 1;
13594 				}
13595 			}
13596 			IRE_REFRELE(ire);
13597 			continue;
13598 		case IPPROTO_UDP:
13599 			ASSERT(first_mp == mp);
13600 			ip_udp_input(q, mp, ipha, ire, ill);
13601 			IRE_REFRELE(ire);
13602 			continue;
13603 		case IPPROTO_SCTP:
13604 			ASSERT(first_mp == mp);
13605 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13606 			    q, dst);
13607 			continue;
13608 		default:
13609 			ip_proto_input(q, first_mp, ipha, ire, ill);
13610 			IRE_REFRELE(ire);
13611 			continue;
13612 		}
13613 	}
13614 
13615 	if (head != NULL)
13616 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13617 
13618 	/*
13619 	 * This code is there just to make netperf/ttcp look good.
13620 	 *
13621 	 * Its possible that after being in polling mode (and having cleared
13622 	 * the backlog), squeues have turned the interrupt frequency higher
13623 	 * to improve latency at the expense of more CPU utilization (less
13624 	 * packets per interrupts or more number of interrupts). Workloads
13625 	 * like ttcp/netperf do manage to tickle polling once in a while
13626 	 * but for the remaining time, stay in higher interrupt mode since
13627 	 * their packet arrival rate is pretty uniform and this shows up
13628 	 * as higher CPU utilization. Since people care about CPU utilization
13629 	 * while running netperf/ttcp, turn the interrupt frequency back to
13630 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13631 	 */
13632 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13633 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13634 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13635 			ip_ring->rr_blank(ip_ring->rr_handle,
13636 			    ip_ring->rr_normal_blank_time,
13637 			    ip_ring->rr_normal_pkt_cnt);
13638 		}
13639 	}
13640 
13641 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13642 	    "ip_input_end: q %p (%S)", q, "end");
13643 #undef	rptr
13644 }
13645 
13646 static void
13647 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13648     t_uscalar_t err)
13649 {
13650 	if (dl_err == DL_SYSERR) {
13651 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13652 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13653 		    ill->ill_name, dlpi_prim_str(prim), err);
13654 		return;
13655 	}
13656 
13657 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13658 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13659 	    dlpi_err_str(dl_err));
13660 }
13661 
13662 /*
13663  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13664  * than DL_UNITDATA_IND messages. If we need to process this message
13665  * exclusively, we call qwriter_ip, in which case we also need to call
13666  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13667  */
13668 void
13669 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13670 {
13671 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13672 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13673 	ill_t		*ill;
13674 
13675 	ip1dbg(("ip_rput_dlpi"));
13676 	ill = (ill_t *)q->q_ptr;
13677 	switch (dloa->dl_primitive) {
13678 	case DL_ERROR_ACK:
13679 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13680 		    "%s (0x%x), unix %u\n", ill->ill_name,
13681 		    dlpi_prim_str(dlea->dl_error_primitive),
13682 		    dlea->dl_error_primitive,
13683 		    dlpi_err_str(dlea->dl_errno),
13684 		    dlea->dl_errno,
13685 		    dlea->dl_unix_errno));
13686 		switch (dlea->dl_error_primitive) {
13687 		case DL_NOTIFY_REQ:
13688 		case DL_UNBIND_REQ:
13689 		case DL_ATTACH_REQ:
13690 		case DL_DETACH_REQ:
13691 		case DL_INFO_REQ:
13692 		case DL_BIND_REQ:
13693 		case DL_ENABMULTI_REQ:
13694 		case DL_PHYS_ADDR_REQ:
13695 		case DL_CAPABILITY_REQ:
13696 		case DL_CONTROL_REQ:
13697 			/*
13698 			 * Refhold the ill to match qwriter_ip which does a
13699 			 * refrele. Since this is on the ill stream we
13700 			 * unconditionally bump up the refcount without
13701 			 * checking for ILL_CAN_LOOKUP
13702 			 */
13703 			ill_refhold(ill);
13704 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13705 			    CUR_OP, B_FALSE);
13706 			return;
13707 		case DL_DISABMULTI_REQ:
13708 			freemsg(mp);	/* Don't want to pass this up */
13709 			return;
13710 		default:
13711 			break;
13712 		}
13713 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13714 		    dlea->dl_errno, dlea->dl_unix_errno);
13715 		freemsg(mp);
13716 		return;
13717 	case DL_INFO_ACK:
13718 	case DL_BIND_ACK:
13719 	case DL_PHYS_ADDR_ACK:
13720 	case DL_NOTIFY_ACK:
13721 	case DL_CAPABILITY_ACK:
13722 	case DL_CONTROL_ACK:
13723 		/*
13724 		 * Refhold the ill to match qwriter_ip which does a refrele
13725 		 * Since this is on the ill stream we unconditionally
13726 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13727 		 */
13728 		ill_refhold(ill);
13729 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13730 		    CUR_OP, B_FALSE);
13731 		return;
13732 	case DL_NOTIFY_IND:
13733 		ill_refhold(ill);
13734 		/*
13735 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13736 		 * relation to the current ioctl in progress (if any). Hence we
13737 		 * pass in NEW_OP in this case.
13738 		 */
13739 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13740 		    NEW_OP, B_FALSE);
13741 		return;
13742 	case DL_OK_ACK:
13743 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13744 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13745 		switch (dloa->dl_correct_primitive) {
13746 		case DL_UNBIND_REQ:
13747 			mutex_enter(&ill->ill_lock);
13748 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13749 			cv_signal(&ill->ill_cv);
13750 			mutex_exit(&ill->ill_lock);
13751 			/* FALLTHRU */
13752 		case DL_ATTACH_REQ:
13753 		case DL_DETACH_REQ:
13754 			/*
13755 			 * Refhold the ill to match qwriter_ip which does a
13756 			 * refrele. Since this is on the ill stream we
13757 			 * unconditionally bump up the refcount
13758 			 */
13759 			ill_refhold(ill);
13760 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13761 			    CUR_OP, B_FALSE);
13762 			return;
13763 		case DL_ENABMULTI_REQ:
13764 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13765 				ill->ill_dlpi_multicast_state = IDMS_OK;
13766 			break;
13767 
13768 		}
13769 		break;
13770 	default:
13771 		break;
13772 	}
13773 	freemsg(mp);
13774 }
13775 
13776 /*
13777  * Handling of DLPI messages that require exclusive access to the ipsq.
13778  *
13779  * Need to do ill_pending_mp_release on ioctl completion, which could
13780  * happen here. (along with mi_copy_done)
13781  */
13782 /* ARGSUSED */
13783 static void
13784 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13785 {
13786 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13787 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13788 	int		err = 0;
13789 	ill_t		*ill;
13790 	ipif_t		*ipif = NULL;
13791 	mblk_t		*mp1 = NULL;
13792 	conn_t		*connp = NULL;
13793 	t_uscalar_t	physaddr_req;
13794 	mblk_t		*mp_hw;
13795 	union DL_primitives *dlp;
13796 	boolean_t	success;
13797 	boolean_t	ioctl_aborted = B_FALSE;
13798 	boolean_t	log = B_TRUE;
13799 
13800 	ip1dbg(("ip_rput_dlpi_writer .."));
13801 	ill = (ill_t *)q->q_ptr;
13802 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13803 
13804 	ASSERT(IAM_WRITER_ILL(ill));
13805 
13806 	/*
13807 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13808 	 * both are null or non-null. However we can assert that only
13809 	 * after grabbing the ipsq_lock. So we don't make any assertion
13810 	 * here and in other places in the code.
13811 	 */
13812 	ipif = ipsq->ipsq_pending_ipif;
13813 	/*
13814 	 * The current ioctl could have been aborted by the user and a new
13815 	 * ioctl to bring up another ill could have started. We could still
13816 	 * get a response from the driver later.
13817 	 */
13818 	if (ipif != NULL && ipif->ipif_ill != ill)
13819 		ioctl_aborted = B_TRUE;
13820 
13821 	switch (dloa->dl_primitive) {
13822 	case DL_ERROR_ACK:
13823 		switch (dlea->dl_error_primitive) {
13824 		case DL_UNBIND_REQ:
13825 		case DL_ATTACH_REQ:
13826 		case DL_DETACH_REQ:
13827 		case DL_INFO_REQ:
13828 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13829 			break;
13830 		case DL_NOTIFY_REQ:
13831 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13832 			log = B_FALSE;
13833 			break;
13834 		case DL_PHYS_ADDR_REQ:
13835 			/*
13836 			 * For IPv6 only, there are two additional
13837 			 * phys_addr_req's sent to the driver to get the
13838 			 * IPv6 token and lla. This allows IP to acquire
13839 			 * the hardware address format for a given interface
13840 			 * without having built in knowledge of the hardware
13841 			 * address. ill_phys_addr_pend keeps track of the last
13842 			 * DL_PAR sent so we know which response we are
13843 			 * dealing with. ill_dlpi_done will update
13844 			 * ill_phys_addr_pend when it sends the next req.
13845 			 * We don't complete the IOCTL until all three DL_PARs
13846 			 * have been attempted, so set *_len to 0 and break.
13847 			 */
13848 			physaddr_req = ill->ill_phys_addr_pend;
13849 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13850 			if (physaddr_req == DL_IPV6_TOKEN) {
13851 				ill->ill_token_length = 0;
13852 				log = B_FALSE;
13853 				break;
13854 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13855 				ill->ill_nd_lla_len = 0;
13856 				log = B_FALSE;
13857 				break;
13858 			}
13859 			/*
13860 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13861 			 * We presumably have an IOCTL hanging out waiting
13862 			 * for completion. Find it and complete the IOCTL
13863 			 * with the error noted.
13864 			 * However, ill_dl_phys was called on an ill queue
13865 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13866 			 * set. But the ioctl is known to be pending on ill_wq.
13867 			 */
13868 			if (!ill->ill_ifname_pending)
13869 				break;
13870 			ill->ill_ifname_pending = 0;
13871 			if (!ioctl_aborted)
13872 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13873 			if (mp1 != NULL) {
13874 				/*
13875 				 * This operation (SIOCSLIFNAME) must have
13876 				 * happened on the ill. Assert there is no conn
13877 				 */
13878 				ASSERT(connp == NULL);
13879 				q = ill->ill_wq;
13880 			}
13881 			break;
13882 		case DL_BIND_REQ:
13883 			ill_dlpi_done(ill, DL_BIND_REQ);
13884 			if (ill->ill_ifname_pending)
13885 				break;
13886 			/*
13887 			 * Something went wrong with the bind.  We presumably
13888 			 * have an IOCTL hanging out waiting for completion.
13889 			 * Find it, take down the interface that was coming
13890 			 * up, and complete the IOCTL with the error noted.
13891 			 */
13892 			if (!ioctl_aborted)
13893 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13894 			if (mp1 != NULL) {
13895 				/*
13896 				 * This operation (SIOCSLIFFLAGS) must have
13897 				 * happened from a conn.
13898 				 */
13899 				ASSERT(connp != NULL);
13900 				q = CONNP_TO_WQ(connp);
13901 				if (ill->ill_move_in_progress) {
13902 					ILL_CLEAR_MOVE(ill);
13903 				}
13904 				(void) ipif_down(ipif, NULL, NULL);
13905 				/* error is set below the switch */
13906 			}
13907 			break;
13908 		case DL_ENABMULTI_REQ:
13909 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13910 
13911 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13912 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13913 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13914 				ipif_t *ipif;
13915 
13916 				log = B_FALSE;
13917 				printf("ip: joining multicasts failed (%d)"
13918 				    " on %s - will use link layer "
13919 				    "broadcasts for multicast\n",
13920 				    dlea->dl_errno, ill->ill_name);
13921 
13922 				/*
13923 				 * Set up the multicast mapping alone.
13924 				 * writer, so ok to access ill->ill_ipif
13925 				 * without any lock.
13926 				 */
13927 				ipif = ill->ill_ipif;
13928 				mutex_enter(&ill->ill_phyint->phyint_lock);
13929 				ill->ill_phyint->phyint_flags |=
13930 				    PHYI_MULTI_BCAST;
13931 				mutex_exit(&ill->ill_phyint->phyint_lock);
13932 
13933 				if (!ill->ill_isv6) {
13934 					(void) ipif_arp_setup_multicast(ipif,
13935 					    NULL);
13936 				} else {
13937 					(void) ipif_ndp_setup_multicast(ipif,
13938 					    NULL);
13939 				}
13940 			}
13941 			freemsg(mp);	/* Don't want to pass this up */
13942 			return;
13943 		case DL_CAPABILITY_REQ:
13944 		case DL_CONTROL_REQ:
13945 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13946 			    "DL_CAPABILITY/CONTROL REQ\n"));
13947 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13948 			ill->ill_capab_state = IDMS_FAILED;
13949 			freemsg(mp);
13950 			return;
13951 		}
13952 		/*
13953 		 * Note the error for IOCTL completion (mp1 is set when
13954 		 * ready to complete ioctl). If ill_ifname_pending_err is
13955 		 * set, an error occured during plumbing (ill_ifname_pending),
13956 		 * so we want to report that error.
13957 		 *
13958 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13959 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13960 		 * expected to get errack'd if the driver doesn't support
13961 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13962 		 * if these error conditions are encountered.
13963 		 */
13964 		if (mp1 != NULL) {
13965 			if (ill->ill_ifname_pending_err != 0)  {
13966 				err = ill->ill_ifname_pending_err;
13967 				ill->ill_ifname_pending_err = 0;
13968 			} else {
13969 				err = dlea->dl_unix_errno ?
13970 				    dlea->dl_unix_errno : ENXIO;
13971 			}
13972 		/*
13973 		 * If we're plumbing an interface and an error hasn't already
13974 		 * been saved, set ill_ifname_pending_err to the error passed
13975 		 * up. Ignore the error if log is B_FALSE (see comment above).
13976 		 */
13977 		} else if (log && ill->ill_ifname_pending &&
13978 		    ill->ill_ifname_pending_err == 0) {
13979 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13980 			dlea->dl_unix_errno : ENXIO;
13981 		}
13982 
13983 		if (log)
13984 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13985 			    dlea->dl_errno, dlea->dl_unix_errno);
13986 		break;
13987 	case DL_CAPABILITY_ACK: {
13988 		boolean_t reneg_flag = B_FALSE;
13989 		/* Call a routine to handle this one. */
13990 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13991 		/*
13992 		 * Check if the ACK is due to renegotiation case since we
13993 		 * will need to send a new CAPABILITY_REQ later.
13994 		 */
13995 		if (ill->ill_capab_state == IDMS_RENEG) {
13996 			/* This is the ack for a renogiation case */
13997 			reneg_flag = B_TRUE;
13998 			ill->ill_capab_state = IDMS_UNKNOWN;
13999 		}
14000 		ill_capability_ack(ill, mp);
14001 		if (reneg_flag)
14002 			ill_capability_probe(ill);
14003 		break;
14004 	}
14005 	case DL_CONTROL_ACK:
14006 		/* We treat all of these as "fire and forget" */
14007 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14008 		break;
14009 	case DL_INFO_ACK:
14010 		/* Call a routine to handle this one. */
14011 		ill_dlpi_done(ill, DL_INFO_REQ);
14012 		ip_ll_subnet_defaults(ill, mp);
14013 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14014 		return;
14015 	case DL_BIND_ACK:
14016 		/*
14017 		 * We should have an IOCTL waiting on this unless
14018 		 * sent by ill_dl_phys, in which case just return
14019 		 */
14020 		ill_dlpi_done(ill, DL_BIND_REQ);
14021 		if (ill->ill_ifname_pending)
14022 			break;
14023 
14024 		if (!ioctl_aborted)
14025 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14026 		if (mp1 == NULL)
14027 			break;
14028 		ASSERT(connp != NULL);
14029 		q = CONNP_TO_WQ(connp);
14030 
14031 		/*
14032 		 * We are exclusive. So nothing can change even after
14033 		 * we get the pending mp. If need be we can put it back
14034 		 * and restart, as in calling ipif_arp_up()  below.
14035 		 */
14036 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14037 
14038 		mutex_enter(&ill->ill_lock);
14039 		ill->ill_dl_up = 1;
14040 		mutex_exit(&ill->ill_lock);
14041 
14042 		/*
14043 		 * Now bring up the resolver, when that is
14044 		 * done we'll create IREs and we are done.
14045 		 */
14046 		if (ill->ill_isv6) {
14047 			/*
14048 			 * v6 interfaces.
14049 			 * Unlike ARP which has to do another bind
14050 			 * and attach, once we get here we are
14051 			 * done withh NDP. Except in the case of
14052 			 * ILLF_XRESOLV, in which case we send an
14053 			 * AR_INTERFACE_UP to the external resolver.
14054 			 * If all goes well, the ioctl will complete
14055 			 * in ip_rput(). If there's an error, we
14056 			 * complete it here.
14057 			 */
14058 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14059 			    B_FALSE);
14060 			if (err == 0) {
14061 				if (ill->ill_flags & ILLF_XRESOLV) {
14062 					mutex_enter(&connp->conn_lock);
14063 					mutex_enter(&ill->ill_lock);
14064 					success = ipsq_pending_mp_add(
14065 					    connp, ipif, q, mp1, 0);
14066 					mutex_exit(&ill->ill_lock);
14067 					mutex_exit(&connp->conn_lock);
14068 					if (success) {
14069 						err = ipif_resolver_up(ipif,
14070 						    B_FALSE);
14071 						if (err == EINPROGRESS) {
14072 							freemsg(mp);
14073 							return;
14074 						}
14075 						ASSERT(err != 0);
14076 						mp1 = ipsq_pending_mp_get(ipsq,
14077 						    &connp);
14078 						ASSERT(mp1 != NULL);
14079 					} else {
14080 						/* conn has started closing */
14081 						err = EINTR;
14082 					}
14083 				} else { /* Non XRESOLV interface */
14084 					err = ipif_up_done_v6(ipif);
14085 				}
14086 			}
14087 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14088 			/*
14089 			 * ARP and other v4 external resolvers.
14090 			 * Leave the pending mblk intact so that
14091 			 * the ioctl completes in ip_rput().
14092 			 */
14093 			mutex_enter(&connp->conn_lock);
14094 			mutex_enter(&ill->ill_lock);
14095 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14096 			mutex_exit(&ill->ill_lock);
14097 			mutex_exit(&connp->conn_lock);
14098 			if (success) {
14099 				err = ipif_resolver_up(ipif, B_FALSE);
14100 				if (err == EINPROGRESS) {
14101 					freemsg(mp);
14102 					return;
14103 				}
14104 				ASSERT(err != 0);
14105 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14106 			} else {
14107 				/* The conn has started closing */
14108 				err = EINTR;
14109 			}
14110 		} else {
14111 			/*
14112 			 * This one is complete. Reply to pending ioctl.
14113 			 */
14114 			err = ipif_up_done(ipif);
14115 		}
14116 
14117 		if ((err == 0) && (ill->ill_up_ipifs)) {
14118 			err = ill_up_ipifs(ill, q, mp1);
14119 			if (err == EINPROGRESS) {
14120 				freemsg(mp);
14121 				return;
14122 			}
14123 		}
14124 
14125 		if (ill->ill_up_ipifs) {
14126 			ill_group_cleanup(ill);
14127 		}
14128 
14129 		break;
14130 	case DL_NOTIFY_IND: {
14131 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14132 		ire_t *ire;
14133 		boolean_t need_ire_walk_v4 = B_FALSE;
14134 		boolean_t need_ire_walk_v6 = B_FALSE;
14135 
14136 		/*
14137 		 * Change the address everywhere we need to.
14138 		 * What we're getting here is a link-level addr or phys addr.
14139 		 * The new addr is at notify + notify->dl_addr_offset
14140 		 * The address length is notify->dl_addr_length;
14141 		 */
14142 		switch (notify->dl_notification) {
14143 		case DL_NOTE_PHYS_ADDR:
14144 			mp_hw = copyb(mp);
14145 			if (mp_hw == NULL) {
14146 				err = ENOMEM;
14147 				break;
14148 			}
14149 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14150 			/*
14151 			 * We currently don't support changing
14152 			 * the token via DL_NOTIFY_IND.
14153 			 * When we do support it, we have to consider
14154 			 * what the implications are with respect to
14155 			 * the token and the link local address.
14156 			 */
14157 			mutex_enter(&ill->ill_lock);
14158 			if (dlp->notify_ind.dl_data ==
14159 			    DL_IPV6_LINK_LAYER_ADDR) {
14160 				if (ill->ill_nd_lla_mp != NULL)
14161 					freemsg(ill->ill_nd_lla_mp);
14162 				ill->ill_nd_lla_mp = mp_hw;
14163 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14164 				    dlp->notify_ind.dl_addr_offset;
14165 				ill->ill_nd_lla_len =
14166 				    dlp->notify_ind.dl_addr_length -
14167 				    ABS(ill->ill_sap_length);
14168 				mutex_exit(&ill->ill_lock);
14169 				break;
14170 			} else if (dlp->notify_ind.dl_data ==
14171 			    DL_CURR_PHYS_ADDR) {
14172 				if (ill->ill_phys_addr_mp != NULL)
14173 					freemsg(ill->ill_phys_addr_mp);
14174 				ill->ill_phys_addr_mp = mp_hw;
14175 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14176 				    dlp->notify_ind.dl_addr_offset;
14177 				ill->ill_phys_addr_length =
14178 				    dlp->notify_ind.dl_addr_length -
14179 				    ABS(ill->ill_sap_length);
14180 				if (ill->ill_isv6 &&
14181 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14182 					if (ill->ill_nd_lla_mp != NULL)
14183 						freemsg(ill->ill_nd_lla_mp);
14184 					ill->ill_nd_lla_mp = copyb(mp_hw);
14185 					ill->ill_nd_lla = (uchar_t *)
14186 					    ill->ill_nd_lla_mp->b_rptr +
14187 					    dlp->notify_ind.dl_addr_offset;
14188 					ill->ill_nd_lla_len =
14189 					    ill->ill_phys_addr_length;
14190 				}
14191 			}
14192 			mutex_exit(&ill->ill_lock);
14193 			/*
14194 			 * Send out gratuitous arp request for our new
14195 			 * hardware address.
14196 			 */
14197 			for (ipif = ill->ill_ipif; ipif != NULL;
14198 			    ipif = ipif->ipif_next) {
14199 				if (!(ipif->ipif_flags & IPIF_UP))
14200 					continue;
14201 				if (ill->ill_isv6) {
14202 					ipif_ndp_down(ipif);
14203 					/*
14204 					 * Set B_TRUE to enable
14205 					 * ipif_ndp_up() to send out
14206 					 * unsolicited advertisements.
14207 					 */
14208 					err = ipif_ndp_up(ipif,
14209 					    &ipif->ipif_v6lcl_addr,
14210 					    B_TRUE);
14211 					if (err) {
14212 						ip1dbg((
14213 						    "ip_rput_dlpi_writer: "
14214 						    "Failed to update ndp "
14215 						    "err %d\n", err));
14216 					}
14217 				} else {
14218 					/*
14219 					 * IPv4 ARP case
14220 					 *
14221 					 * Set B_TRUE, as we only want
14222 					 * ipif_resolver_up to send an
14223 					 * AR_ENTRY_ADD request up to
14224 					 * ARP.
14225 					 */
14226 					err = ipif_resolver_up(ipif,
14227 					    B_TRUE);
14228 					if (err) {
14229 						ip1dbg((
14230 						    "ip_rput_dlpi_writer: "
14231 						    "Failed to update arp "
14232 						    "err %d\n", err));
14233 					}
14234 				}
14235 			}
14236 			/*
14237 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14238 			 * case so that all old fastpath information can be
14239 			 * purged from IRE caches.
14240 			 */
14241 		/* FALLTHRU */
14242 		case DL_NOTE_FASTPATH_FLUSH:
14243 			/*
14244 			 * Any fastpath probe sent henceforth will get the
14245 			 * new fp mp. So we first delete any ires that are
14246 			 * waiting for the fastpath. Then walk all ires and
14247 			 * delete the ire or delete the fp mp. In the case of
14248 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14249 			 * recreate the ire's without going through a complex
14250 			 * ipif up/down dance. So we don't delete the ire
14251 			 * itself, but just the ire_fp_mp for these 2 ire's
14252 			 * In the case of the other ire's we delete the ire's
14253 			 * themselves. Access to ire_fp_mp is completely
14254 			 * protected by ire_lock for IRE_MIPRTUN and
14255 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14256 			 * other cases for performance.
14257 			 */
14258 			if (ill->ill_isv6) {
14259 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14260 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14261 				    NULL);
14262 			} else {
14263 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14264 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14265 				    IRE_CACHE | IRE_BROADCAST,
14266 				    ire_fastpath_flush, NULL, ill);
14267 				mutex_enter(&ire_mrtun_lock);
14268 				if (ire_mrtun_count != 0) {
14269 					mutex_exit(&ire_mrtun_lock);
14270 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14271 					    IRE_MIPRTUN, ire_fastpath_flush,
14272 					    NULL, ill);
14273 				} else {
14274 					mutex_exit(&ire_mrtun_lock);
14275 				}
14276 			}
14277 			break;
14278 		case DL_NOTE_SDU_SIZE:
14279 			/*
14280 			 * Change the MTU size of the interface, of all
14281 			 * attached ipif's, and of all relevant ire's.  The
14282 			 * new value's a uint32_t at notify->dl_data.
14283 			 * Mtu change Vs. new ire creation - protocol below.
14284 			 *
14285 			 * a Mark the ipif as IPIF_CHANGING.
14286 			 * b Set the new mtu in the ipif.
14287 			 * c Change the ire_max_frag on all affected ires
14288 			 * d Unmark the IPIF_CHANGING
14289 			 *
14290 			 * To see how the protocol works, assume an interface
14291 			 * route is also being added simultaneously by
14292 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14293 			 * the ire. If the ire is created before step a,
14294 			 * it will be cleaned up by step c. If the ire is
14295 			 * created after step d, it will see the new value of
14296 			 * ipif_mtu. Any attempt to create the ire between
14297 			 * steps a to d will fail because of the IPIF_CHANGING
14298 			 * flag. Note that ire_create() is passed a pointer to
14299 			 * the ipif_mtu, and not the value. During ire_add
14300 			 * under the bucket lock, the ire_max_frag of the
14301 			 * new ire being created is set from the ipif/ire from
14302 			 * which it is being derived.
14303 			 */
14304 			mutex_enter(&ill->ill_lock);
14305 			ill->ill_max_frag = (uint_t)notify->dl_data;
14306 
14307 			/*
14308 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14309 			 * leave it alone
14310 			 */
14311 			if (ill->ill_mtu_userspecified) {
14312 				mutex_exit(&ill->ill_lock);
14313 				break;
14314 			}
14315 			ill->ill_max_mtu = ill->ill_max_frag;
14316 			if (ill->ill_isv6) {
14317 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14318 					ill->ill_max_mtu = IPV6_MIN_MTU;
14319 			} else {
14320 				if (ill->ill_max_mtu < IP_MIN_MTU)
14321 					ill->ill_max_mtu = IP_MIN_MTU;
14322 			}
14323 			for (ipif = ill->ill_ipif; ipif != NULL;
14324 			    ipif = ipif->ipif_next) {
14325 				/*
14326 				 * Don't override the mtu if the user
14327 				 * has explicitly set it.
14328 				 */
14329 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14330 					continue;
14331 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14332 				if (ipif->ipif_isv6)
14333 					ire = ipif_to_ire_v6(ipif);
14334 				else
14335 					ire = ipif_to_ire(ipif);
14336 				if (ire != NULL) {
14337 					ire->ire_max_frag = ipif->ipif_mtu;
14338 					ire_refrele(ire);
14339 				}
14340 				if (ipif->ipif_flags & IPIF_UP) {
14341 					if (ill->ill_isv6)
14342 						need_ire_walk_v6 = B_TRUE;
14343 					else
14344 						need_ire_walk_v4 = B_TRUE;
14345 				}
14346 			}
14347 			mutex_exit(&ill->ill_lock);
14348 			if (need_ire_walk_v4)
14349 				ire_walk_v4(ill_mtu_change, (char *)ill,
14350 				    ALL_ZONES);
14351 			if (need_ire_walk_v6)
14352 				ire_walk_v6(ill_mtu_change, (char *)ill,
14353 				    ALL_ZONES);
14354 			break;
14355 		case DL_NOTE_LINK_UP:
14356 		case DL_NOTE_LINK_DOWN: {
14357 			/*
14358 			 * We are writer. ill / phyint / ipsq assocs stable.
14359 			 * The RUNNING flag reflects the state of the link.
14360 			 */
14361 			phyint_t *phyint = ill->ill_phyint;
14362 			uint64_t new_phyint_flags;
14363 			boolean_t changed = B_FALSE;
14364 
14365 			mutex_enter(&phyint->phyint_lock);
14366 			new_phyint_flags =
14367 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14368 			    phyint->phyint_flags | PHYI_RUNNING :
14369 			    phyint->phyint_flags & ~PHYI_RUNNING;
14370 			if (new_phyint_flags != phyint->phyint_flags) {
14371 				phyint->phyint_flags = new_phyint_flags;
14372 				changed = B_TRUE;
14373 			}
14374 			mutex_exit(&phyint->phyint_lock);
14375 			/*
14376 			 * If the flags have changed, send a message to
14377 			 * the routing socket.
14378 			 */
14379 			if (changed) {
14380 				if (phyint->phyint_illv4 != NULL) {
14381 					ip_rts_ifmsg(
14382 					    phyint->phyint_illv4->ill_ipif);
14383 				}
14384 				if (phyint->phyint_illv6 != NULL) {
14385 					ip_rts_ifmsg(
14386 					    phyint->phyint_illv6->ill_ipif);
14387 				}
14388 			}
14389 			break;
14390 		}
14391 		case DL_NOTE_PROMISC_ON_PHYS:
14392 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14393 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14394 			mutex_enter(&ill->ill_lock);
14395 			ill->ill_promisc_on_phys = B_TRUE;
14396 			mutex_exit(&ill->ill_lock);
14397 			break;
14398 		case DL_NOTE_PROMISC_OFF_PHYS:
14399 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14400 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14401 			mutex_enter(&ill->ill_lock);
14402 			ill->ill_promisc_on_phys = B_FALSE;
14403 			mutex_exit(&ill->ill_lock);
14404 			break;
14405 		case DL_NOTE_CAPAB_RENEG:
14406 			/*
14407 			 * Something changed on the driver side.
14408 			 * It wants us to renegotiate the capabilities
14409 			 * on this ill. The most likely cause is the
14410 			 * aggregation interface under us where a
14411 			 * port got added or went away.
14412 			 *
14413 			 * We reset the capabilities and set the
14414 			 * state to IDMS_RENG so that when the ack
14415 			 * comes back, we can start the
14416 			 * renegotiation process.
14417 			 */
14418 			ill_capability_reset(ill);
14419 			ill->ill_capab_state = IDMS_RENEG;
14420 			break;
14421 		default:
14422 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14423 			    "type 0x%x for DL_NOTIFY_IND\n",
14424 			    notify->dl_notification));
14425 			break;
14426 		}
14427 
14428 		/*
14429 		 * As this is an asynchronous operation, we
14430 		 * should not call ill_dlpi_done
14431 		 */
14432 		break;
14433 	}
14434 	case DL_NOTIFY_ACK:
14435 		/*
14436 		 * Don't really need to check for what notifications
14437 		 * are supported; we'll process what gets sent upstream,
14438 		 * and we know it'll be something we support changing
14439 		 * based on our DL_NOTIFY_REQ.
14440 		 */
14441 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14442 		break;
14443 	case DL_PHYS_ADDR_ACK: {
14444 		/*
14445 		 * We should have an IOCTL waiting on this when request
14446 		 * sent by ill_dl_phys.
14447 		 * However, ill_dl_phys was called on an ill queue (from
14448 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14449 		 * ioctl is known to be pending on ill_wq.
14450 		 * There are two additional phys_addr_req's sent to the
14451 		 * driver to get the token and lla. ill_phys_addr_pend
14452 		 * keeps track of the last one sent so we know which
14453 		 * response we are dealing with. ill_dlpi_done will
14454 		 * update ill_phys_addr_pend when it sends the next req.
14455 		 * We don't complete the IOCTL until all three DL_PARs
14456 		 * have been attempted.
14457 		 *
14458 		 * We don't need any lock to update ill_nd_lla* fields,
14459 		 * since the ill is not yet up, We grab the lock just
14460 		 * for uniformity with other code that accesses ill_nd_lla.
14461 		 */
14462 		physaddr_req = ill->ill_phys_addr_pend;
14463 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14464 		if (physaddr_req == DL_IPV6_TOKEN ||
14465 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14466 			if (physaddr_req == DL_IPV6_TOKEN) {
14467 				/*
14468 				 * bcopy to low-order bits of ill_token
14469 				 *
14470 				 * XXX Temporary hack - currently,
14471 				 * all known tokens are 64 bits,
14472 				 * so I'll cheat for the moment.
14473 				 */
14474 				dlp = (union DL_primitives *)mp->b_rptr;
14475 
14476 				mutex_enter(&ill->ill_lock);
14477 				bcopy((uchar_t *)(mp->b_rptr +
14478 				dlp->physaddr_ack.dl_addr_offset),
14479 				(void *)&ill->ill_token.s6_addr32[2],
14480 				dlp->physaddr_ack.dl_addr_length);
14481 				ill->ill_token_length =
14482 					dlp->physaddr_ack.dl_addr_length;
14483 				mutex_exit(&ill->ill_lock);
14484 			} else {
14485 				ASSERT(ill->ill_nd_lla_mp == NULL);
14486 				mp_hw = copyb(mp);
14487 				if (mp_hw == NULL) {
14488 					err = ENOMEM;
14489 					break;
14490 				}
14491 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14492 				mutex_enter(&ill->ill_lock);
14493 				ill->ill_nd_lla_mp = mp_hw;
14494 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14495 				dlp->physaddr_ack.dl_addr_offset;
14496 				ill->ill_nd_lla_len =
14497 					dlp->physaddr_ack.dl_addr_length;
14498 				mutex_exit(&ill->ill_lock);
14499 			}
14500 			break;
14501 		}
14502 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14503 		ASSERT(ill->ill_phys_addr_mp == NULL);
14504 		if (!ill->ill_ifname_pending)
14505 			break;
14506 		ill->ill_ifname_pending = 0;
14507 		if (!ioctl_aborted)
14508 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14509 		if (mp1 != NULL) {
14510 			ASSERT(connp == NULL);
14511 			q = ill->ill_wq;
14512 		}
14513 		/*
14514 		 * If any error acks received during the plumbing sequence,
14515 		 * ill_ifname_pending_err will be set. Break out and send up
14516 		 * the error to the pending ioctl.
14517 		 */
14518 		if (ill->ill_ifname_pending_err != 0) {
14519 			err = ill->ill_ifname_pending_err;
14520 			ill->ill_ifname_pending_err = 0;
14521 			break;
14522 		}
14523 		/*
14524 		 * Get the interface token.  If the zeroth interface
14525 		 * address is zero then set the address to the link local
14526 		 * address
14527 		 */
14528 		mp_hw = copyb(mp);
14529 		if (mp_hw == NULL) {
14530 			err = ENOMEM;
14531 			break;
14532 		}
14533 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14534 		ill->ill_phys_addr_mp = mp_hw;
14535 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14536 				dlp->physaddr_ack.dl_addr_offset;
14537 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14538 		    ill->ill_phys_addr_length == 0 ||
14539 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14540 			/*
14541 			 * Compatibility: atun driver returns a length of 0.
14542 			 * ipdptp has an ill_phys_addr_length of zero(from
14543 			 * DL_BIND_ACK) but a non-zero length here.
14544 			 * ipd has an ill_phys_addr_length of 4(from
14545 			 * DL_BIND_ACK) but a non-zero length here.
14546 			 */
14547 			ill->ill_phys_addr = NULL;
14548 		} else if (dlp->physaddr_ack.dl_addr_length !=
14549 		    ill->ill_phys_addr_length) {
14550 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14551 			    "Address length mismatch %d %d\n",
14552 			    dlp->physaddr_ack.dl_addr_length,
14553 			    ill->ill_phys_addr_length));
14554 			err = EINVAL;
14555 			break;
14556 		}
14557 		mutex_enter(&ill->ill_lock);
14558 		if (ill->ill_nd_lla_mp == NULL) {
14559 			ill->ill_nd_lla_mp = copyb(mp_hw);
14560 			if (ill->ill_nd_lla_mp == NULL) {
14561 				err = ENOMEM;
14562 				mutex_exit(&ill->ill_lock);
14563 				break;
14564 			}
14565 			ill->ill_nd_lla =
14566 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14567 			    dlp->physaddr_ack.dl_addr_offset;
14568 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14569 		}
14570 		mutex_exit(&ill->ill_lock);
14571 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14572 			(void) ill_setdefaulttoken(ill);
14573 
14574 		/*
14575 		 * If the ill zero interface has a zero address assign
14576 		 * it the proper link local address.
14577 		 */
14578 		ASSERT(ill->ill_ipif->ipif_id == 0);
14579 		if (ipif != NULL &&
14580 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14581 			(void) ipif_setlinklocal(ipif);
14582 		break;
14583 	}
14584 	case DL_OK_ACK:
14585 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14586 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14587 		    dloa->dl_correct_primitive));
14588 		switch (dloa->dl_correct_primitive) {
14589 		case DL_UNBIND_REQ:
14590 		case DL_ATTACH_REQ:
14591 		case DL_DETACH_REQ:
14592 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14593 			break;
14594 		}
14595 		break;
14596 	default:
14597 		break;
14598 	}
14599 
14600 	freemsg(mp);
14601 	if (mp1) {
14602 		struct iocblk *iocp;
14603 		int mode;
14604 
14605 		/*
14606 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14607 		 * SIOCSLIFNAME do a copyout.
14608 		 */
14609 		iocp = (struct iocblk *)mp1->b_rptr;
14610 
14611 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14612 		    iocp->ioc_cmd == SIOCSLIFNAME)
14613 			mode = COPYOUT;
14614 		else
14615 			mode = NO_COPYOUT;
14616 		/*
14617 		 * The ioctl must complete now without EINPROGRESS
14618 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14619 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14620 		 * stuck for ever in the ipsq.
14621 		 */
14622 		ASSERT(err != EINPROGRESS);
14623 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14624 
14625 	}
14626 }
14627 
14628 /*
14629  * ip_rput_other is called by ip_rput to handle messages modifying the global
14630  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14631  */
14632 /* ARGSUSED */
14633 void
14634 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14635 {
14636 	ill_t		*ill;
14637 	struct iocblk	*iocp;
14638 	mblk_t		*mp1;
14639 	conn_t		*connp = NULL;
14640 
14641 	ip1dbg(("ip_rput_other "));
14642 	ill = (ill_t *)q->q_ptr;
14643 	/*
14644 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14645 	 * in which case ipsq is NULL.
14646 	 */
14647 	if (ipsq != NULL) {
14648 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14649 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14650 	}
14651 
14652 	switch (mp->b_datap->db_type) {
14653 	case M_ERROR:
14654 	case M_HANGUP:
14655 		/*
14656 		 * The device has a problem.  We force the ILL down.  It can
14657 		 * be brought up again manually using SIOCSIFFLAGS (via
14658 		 * ifconfig or equivalent).
14659 		 */
14660 		ASSERT(ipsq != NULL);
14661 		if (mp->b_rptr < mp->b_wptr)
14662 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14663 		if (ill->ill_error == 0)
14664 			ill->ill_error = ENXIO;
14665 		if (!ill_down_start(q, mp))
14666 			return;
14667 		ipif_all_down_tail(ipsq, q, mp, NULL);
14668 		break;
14669 	case M_IOCACK:
14670 		iocp = (struct iocblk *)mp->b_rptr;
14671 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14672 		switch (iocp->ioc_cmd) {
14673 		case SIOCSTUNPARAM:
14674 		case OSIOCSTUNPARAM:
14675 			ASSERT(ipsq != NULL);
14676 			/*
14677 			 * Finish socket ioctl passed through to tun.
14678 			 * We should have an IOCTL waiting on this.
14679 			 */
14680 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14681 			if (ill->ill_isv6) {
14682 				struct iftun_req *ta;
14683 
14684 				/*
14685 				 * if a source or destination is
14686 				 * being set, try and set the link
14687 				 * local address for the tunnel
14688 				 */
14689 				ta = (struct iftun_req *)mp->b_cont->
14690 				    b_cont->b_rptr;
14691 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14692 					ipif_set_tun_llink(ill, ta);
14693 				}
14694 
14695 			}
14696 			if (mp1 != NULL) {
14697 				/*
14698 				 * Now copy back the b_next/b_prev used by
14699 				 * mi code for the mi_copy* functions.
14700 				 * See ip_sioctl_tunparam() for the reason.
14701 				 * Also protect against missing b_cont.
14702 				 */
14703 				if (mp->b_cont != NULL) {
14704 					mp->b_cont->b_next =
14705 					    mp1->b_cont->b_next;
14706 					mp->b_cont->b_prev =
14707 					    mp1->b_cont->b_prev;
14708 				}
14709 				inet_freemsg(mp1);
14710 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14711 				ASSERT(connp != NULL);
14712 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14713 				    iocp->ioc_error, NO_COPYOUT,
14714 				    ipsq->ipsq_current_ipif, ipsq);
14715 			} else {
14716 				ASSERT(connp == NULL);
14717 				putnext(q, mp);
14718 			}
14719 			break;
14720 		case SIOCGTUNPARAM:
14721 		case OSIOCGTUNPARAM:
14722 			/*
14723 			 * This is really M_IOCDATA from the tunnel driver.
14724 			 * convert back and complete the ioctl.
14725 			 * We should have an IOCTL waiting on this.
14726 			 */
14727 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14728 			if (mp1) {
14729 				/*
14730 				 * Now copy back the b_next/b_prev used by
14731 				 * mi code for the mi_copy* functions.
14732 				 * See ip_sioctl_tunparam() for the reason.
14733 				 * Also protect against missing b_cont.
14734 				 */
14735 				if (mp->b_cont != NULL) {
14736 					mp->b_cont->b_next =
14737 					    mp1->b_cont->b_next;
14738 					mp->b_cont->b_prev =
14739 					    mp1->b_cont->b_prev;
14740 				}
14741 				inet_freemsg(mp1);
14742 				if (iocp->ioc_error == 0)
14743 					mp->b_datap->db_type = M_IOCDATA;
14744 				ASSERT(connp != NULL);
14745 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14746 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14747 			} else {
14748 				ASSERT(connp == NULL);
14749 				putnext(q, mp);
14750 			}
14751 			break;
14752 		default:
14753 			break;
14754 		}
14755 		break;
14756 	case M_IOCNAK:
14757 		iocp = (struct iocblk *)mp->b_rptr;
14758 
14759 		switch (iocp->ioc_cmd) {
14760 		int mode;
14761 		ipif_t	*ipif;
14762 
14763 		case DL_IOC_HDR_INFO:
14764 			/*
14765 			 * If this was the first attempt turn of the
14766 			 * fastpath probing.
14767 			 */
14768 			mutex_enter(&ill->ill_lock);
14769 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14770 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14771 				mutex_exit(&ill->ill_lock);
14772 				ill_fastpath_nack(ill);
14773 				ip1dbg(("ip_rput: DLPI fastpath off on "
14774 				    "interface %s\n",
14775 				    ill->ill_name));
14776 			} else {
14777 				mutex_exit(&ill->ill_lock);
14778 			}
14779 			freemsg(mp);
14780 			break;
14781 		case SIOCSTUNPARAM:
14782 		case OSIOCSTUNPARAM:
14783 			ASSERT(ipsq != NULL);
14784 			/*
14785 			 * Finish socket ioctl passed through to tun
14786 			 * We should have an IOCTL waiting on this.
14787 			 */
14788 			/* FALLTHRU */
14789 		case SIOCGTUNPARAM:
14790 		case OSIOCGTUNPARAM:
14791 			/*
14792 			 * This is really M_IOCDATA from the tunnel driver.
14793 			 * convert back and complete the ioctl.
14794 			 * We should have an IOCTL waiting on this.
14795 			 */
14796 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14797 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14798 				mp1 = ill_pending_mp_get(ill, &connp,
14799 				    iocp->ioc_id);
14800 				mode = COPYOUT;
14801 				ipsq = NULL;
14802 				ipif = NULL;
14803 			} else {
14804 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14805 				mode = NO_COPYOUT;
14806 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14807 				ipif = ipsq->ipsq_current_ipif;
14808 			}
14809 			if (mp1 != NULL) {
14810 				/*
14811 				 * Now copy back the b_next/b_prev used by
14812 				 * mi code for the mi_copy* functions.
14813 				 * See ip_sioctl_tunparam() for the reason.
14814 				 * Also protect against missing b_cont.
14815 				 */
14816 				if (mp->b_cont != NULL) {
14817 					mp->b_cont->b_next =
14818 					    mp1->b_cont->b_next;
14819 					mp->b_cont->b_prev =
14820 					    mp1->b_cont->b_prev;
14821 				}
14822 				inet_freemsg(mp1);
14823 				if (iocp->ioc_error == 0)
14824 					iocp->ioc_error = EINVAL;
14825 				ASSERT(connp != NULL);
14826 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14827 				    iocp->ioc_error, mode, ipif, ipsq);
14828 			} else {
14829 				ASSERT(connp == NULL);
14830 				putnext(q, mp);
14831 			}
14832 			break;
14833 		default:
14834 			break;
14835 		}
14836 	default:
14837 		break;
14838 	}
14839 }
14840 
14841 /*
14842  * NOTE : This function does not ire_refrele the ire argument passed in.
14843  *
14844  * IPQoS notes
14845  * IP policy is invoked twice for a forwarded packet, once on the read side
14846  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14847  * enabled. An additional parameter, in_ill, has been added for this purpose.
14848  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14849  * because ip_mroute drops this information.
14850  *
14851  */
14852 void
14853 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14854 {
14855 	uint32_t	pkt_len;
14856 	queue_t	*q;
14857 	uint32_t	sum;
14858 #define	rptr	((uchar_t *)ipha)
14859 	uint32_t	max_frag;
14860 	uint32_t	ill_index;
14861 
14862 	/* Get the ill_index of the incoming ILL */
14863 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14864 
14865 	/* Initiate Read side IPPF processing */
14866 	if (IPP_ENABLED(IPP_FWD_IN)) {
14867 		ip_process(IPP_FWD_IN, &mp, ill_index);
14868 		if (mp == NULL) {
14869 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14870 			    "during IPPF processing\n"));
14871 			return;
14872 		}
14873 	}
14874 	pkt_len = ntohs(ipha->ipha_length);
14875 
14876 	/* Adjust the checksum to reflect the ttl decrement. */
14877 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14878 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14879 
14880 	if (ipha->ipha_ttl-- <= 1) {
14881 		if (ip_csum_hdr(ipha)) {
14882 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14883 			goto drop_pkt;
14884 		}
14885 		/*
14886 		 * Note: ire_stq this will be NULL for multicast
14887 		 * datagrams using the long path through arp (the IRE
14888 		 * is not an IRE_CACHE). This should not cause
14889 		 * problems since we don't generate ICMP errors for
14890 		 * multicast packets.
14891 		 */
14892 		q = ire->ire_stq;
14893 		if (q)
14894 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14895 		else
14896 			freemsg(mp);
14897 		return;
14898 	}
14899 
14900 	/*
14901 	 * Don't forward if the interface is down
14902 	 */
14903 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14904 		BUMP_MIB(&ip_mib, ipInDiscards);
14905 		goto drop_pkt;
14906 	}
14907 
14908 	/* Get the ill_index of the outgoing ILL */
14909 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14910 
14911 	/* Check if there are options to update */
14912 	if (!IS_SIMPLE_IPH(ipha)) {
14913 		if (ip_csum_hdr(ipha)) {
14914 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14915 			goto drop_pkt;
14916 		}
14917 		if (ip_rput_forward_options(mp, ipha, ire)) {
14918 			return;
14919 		}
14920 
14921 		ipha->ipha_hdr_checksum = 0;
14922 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14923 	}
14924 	max_frag = ire->ire_max_frag;
14925 	if (pkt_len > max_frag) {
14926 		/*
14927 		 * It needs fragging on its way out.  We haven't
14928 		 * verified the header checksum yet.  Since we
14929 		 * are going to put a surely good checksum in the
14930 		 * outgoing header, we have to make sure that it
14931 		 * was good coming in.
14932 		 */
14933 		if (ip_csum_hdr(ipha)) {
14934 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14935 			goto drop_pkt;
14936 		}
14937 		/* Initiate Write side IPPF processing */
14938 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14939 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14940 			if (mp == NULL) {
14941 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14942 				    " during IPPF processing\n"));
14943 				return;
14944 			}
14945 		}
14946 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14947 		return;
14948 	}
14949 
14950 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14951 	if (mp == NULL) {
14952 		BUMP_MIB(&ip_mib, ipInDiscards);
14953 		return;
14954 	}
14955 
14956 	q = ire->ire_stq;
14957 	UPDATE_IB_PKT_COUNT(ire);
14958 	ire->ire_last_used_time = lbolt;
14959 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14960 	putnext(q, mp);
14961 	return;
14962 
14963 drop_pkt:;
14964 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14965 	freemsg(mp);
14966 #undef	rptr
14967 }
14968 
14969 void
14970 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14971 {
14972 	ire_t	*ire;
14973 
14974 	ASSERT(!ipif->ipif_isv6);
14975 	/*
14976 	 * Find an IRE which matches the destination and the outgoing
14977 	 * queue in the cache table. All we need is an IRE_CACHE which
14978 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14979 	 * then it is enough to have some IRE_CACHE in the group.
14980 	 */
14981 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14982 		dst = ipif->ipif_pp_dst_addr;
14983 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14984 	    MATCH_IRE_ILL_GROUP);
14985 	if (!ire) {
14986 		/*
14987 		 * Mark this packet to make it be delivered to
14988 		 * ip_rput_forward after the new ire has been
14989 		 * created.
14990 		 */
14991 		mp->b_prev = NULL;
14992 		mp->b_next = mp;
14993 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14994 		    NULL, 0);
14995 	} else {
14996 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14997 		IRE_REFRELE(ire);
14998 	}
14999 }
15000 
15001 /* Update any source route, record route or timestamp options */
15002 static int
15003 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15004 {
15005 	ipoptp_t	opts;
15006 	uchar_t		*opt;
15007 	uint8_t		optval;
15008 	uint8_t		optlen;
15009 	ipaddr_t	dst;
15010 	uint32_t	ts;
15011 	ire_t		*dst_ire = NULL;
15012 	ire_t		*tmp_ire = NULL;
15013 	timestruc_t	now;
15014 
15015 	ip2dbg(("ip_rput_forward_options\n"));
15016 	dst = ipha->ipha_dst;
15017 	for (optval = ipoptp_first(&opts, ipha);
15018 	    optval != IPOPT_EOL;
15019 	    optval = ipoptp_next(&opts)) {
15020 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15021 		opt = opts.ipoptp_cur;
15022 		optlen = opts.ipoptp_len;
15023 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15024 		    optval, opts.ipoptp_len));
15025 		switch (optval) {
15026 			uint32_t off;
15027 		case IPOPT_SSRR:
15028 		case IPOPT_LSRR:
15029 			/* Check if adminstratively disabled */
15030 			if (!ip_forward_src_routed) {
15031 				BUMP_MIB(&ip_mib, ipForwProhibits);
15032 				if (ire->ire_stq)
15033 					icmp_unreachable(ire->ire_stq, mp,
15034 					    ICMP_SOURCE_ROUTE_FAILED);
15035 				else {
15036 					ip0dbg(("ip_rput_forward_options: "
15037 					    "unable to send unreach\n"));
15038 					freemsg(mp);
15039 				}
15040 				return (-1);
15041 			}
15042 
15043 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15044 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15045 			if (dst_ire == NULL) {
15046 				/*
15047 				 * Must be partial since ip_rput_options
15048 				 * checked for strict.
15049 				 */
15050 				break;
15051 			}
15052 			off = opt[IPOPT_OFFSET];
15053 			off--;
15054 		redo_srr:
15055 			if (optlen < IP_ADDR_LEN ||
15056 			    off > optlen - IP_ADDR_LEN) {
15057 				/* End of source route */
15058 				ip1dbg((
15059 				    "ip_rput_forward_options: end of SR\n"));
15060 				ire_refrele(dst_ire);
15061 				break;
15062 			}
15063 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15064 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15065 			    IP_ADDR_LEN);
15066 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15067 			    ntohl(dst)));
15068 
15069 			/*
15070 			 * Check if our address is present more than
15071 			 * once as consecutive hops in source route.
15072 			 */
15073 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15074 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15075 			if (tmp_ire != NULL) {
15076 				ire_refrele(tmp_ire);
15077 				off += IP_ADDR_LEN;
15078 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15079 				goto redo_srr;
15080 			}
15081 			ipha->ipha_dst = dst;
15082 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15083 			ire_refrele(dst_ire);
15084 			break;
15085 		case IPOPT_RR:
15086 			off = opt[IPOPT_OFFSET];
15087 			off--;
15088 			if (optlen < IP_ADDR_LEN ||
15089 			    off > optlen - IP_ADDR_LEN) {
15090 				/* No more room - ignore */
15091 				ip1dbg((
15092 				    "ip_rput_forward_options: end of RR\n"));
15093 				break;
15094 			}
15095 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15096 			    IP_ADDR_LEN);
15097 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15098 			break;
15099 		case IPOPT_TS:
15100 			/* Insert timestamp if there is room */
15101 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15102 			case IPOPT_TS_TSONLY:
15103 				off = IPOPT_TS_TIMELEN;
15104 				break;
15105 			case IPOPT_TS_PRESPEC:
15106 			case IPOPT_TS_PRESPEC_RFC791:
15107 				/* Verify that the address matched */
15108 				off = opt[IPOPT_OFFSET] - 1;
15109 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15110 				dst_ire = ire_ctable_lookup(dst, 0,
15111 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
15112 				if (dst_ire == NULL) {
15113 					/* Not for us */
15114 					break;
15115 				}
15116 				ire_refrele(dst_ire);
15117 				/* FALLTHRU */
15118 			case IPOPT_TS_TSANDADDR:
15119 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15120 				break;
15121 			default:
15122 				/*
15123 				 * ip_*put_options should have already
15124 				 * dropped this packet.
15125 				 */
15126 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15127 				    "unknown IT - bug in ip_rput_options?\n");
15128 				return (0);	/* Keep "lint" happy */
15129 			}
15130 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15131 				/* Increase overflow counter */
15132 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15133 				opt[IPOPT_POS_OV_FLG] =
15134 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15135 				    (off << 4));
15136 				break;
15137 			}
15138 			off = opt[IPOPT_OFFSET] - 1;
15139 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15140 			case IPOPT_TS_PRESPEC:
15141 			case IPOPT_TS_PRESPEC_RFC791:
15142 			case IPOPT_TS_TSANDADDR:
15143 				bcopy(&ire->ire_src_addr,
15144 				    (char *)opt + off, IP_ADDR_LEN);
15145 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15146 				/* FALLTHRU */
15147 			case IPOPT_TS_TSONLY:
15148 				off = opt[IPOPT_OFFSET] - 1;
15149 				/* Compute # of milliseconds since midnight */
15150 				gethrestime(&now);
15151 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15152 				    now.tv_nsec / (NANOSEC / MILLISEC);
15153 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15154 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15155 				break;
15156 			}
15157 			break;
15158 		}
15159 	}
15160 	return (0);
15161 }
15162 
15163 /*
15164  * This is called after processing at least one of AH/ESP headers.
15165  *
15166  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15167  * the actual, physical interface on which the packet was received,
15168  * but, when ip_strict_dst_multihoming is set to 1, could be the
15169  * interface which had the ipha_dst configured when the packet went
15170  * through ip_rput. The ill_index corresponding to the recv_ill
15171  * is saved in ipsec_in_rill_index
15172  */
15173 void
15174 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15175 {
15176 	mblk_t *mp;
15177 	ipaddr_t dst;
15178 	in6_addr_t *v6dstp;
15179 	ipha_t *ipha;
15180 	ip6_t *ip6h;
15181 	ipsec_in_t *ii;
15182 	boolean_t ill_need_rele = B_FALSE;
15183 	boolean_t rill_need_rele = B_FALSE;
15184 	boolean_t ire_need_rele = B_FALSE;
15185 
15186 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15187 	ASSERT(ii->ipsec_in_ill_index != 0);
15188 
15189 	mp = ipsec_mp->b_cont;
15190 	ASSERT(mp != NULL);
15191 
15192 
15193 	if (ill == NULL) {
15194 		ASSERT(recv_ill == NULL);
15195 		/*
15196 		 * We need to get the original queue on which ip_rput_local
15197 		 * or ip_rput_data_v6 was called.
15198 		 */
15199 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15200 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15201 		ill_need_rele = B_TRUE;
15202 
15203 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15204 			recv_ill = ill_lookup_on_ifindex(
15205 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15206 			    NULL, NULL, NULL, NULL);
15207 			rill_need_rele = B_TRUE;
15208 		} else {
15209 			recv_ill = ill;
15210 		}
15211 
15212 		if ((ill == NULL) || (recv_ill == NULL)) {
15213 			ip0dbg(("ip_fanout_proto_again: interface "
15214 			    "disappeared\n"));
15215 			if (ill != NULL)
15216 				ill_refrele(ill);
15217 			if (recv_ill != NULL)
15218 				ill_refrele(recv_ill);
15219 			freemsg(ipsec_mp);
15220 			return;
15221 		}
15222 	}
15223 
15224 	ASSERT(ill != NULL && recv_ill != NULL);
15225 
15226 	if (mp->b_datap->db_type == M_CTL) {
15227 		/*
15228 		 * AH/ESP is returning the ICMP message after
15229 		 * removing their headers. Fanout again till
15230 		 * it gets to the right protocol.
15231 		 */
15232 		if (ii->ipsec_in_v4) {
15233 			icmph_t *icmph;
15234 			int iph_hdr_length;
15235 			int hdr_length;
15236 
15237 			ipha = (ipha_t *)mp->b_rptr;
15238 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15239 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15240 			ipha = (ipha_t *)&icmph[1];
15241 			hdr_length = IPH_HDR_LENGTH(ipha);
15242 			/*
15243 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15244 			 * Reset the type to M_DATA.
15245 			 */
15246 			mp->b_datap->db_type = M_DATA;
15247 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15248 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15249 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15250 		} else {
15251 			icmp6_t *icmp6;
15252 			int hdr_length;
15253 
15254 			ip6h = (ip6_t *)mp->b_rptr;
15255 			/* Don't call hdr_length_v6() unless you have to. */
15256 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15257 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15258 			else
15259 				hdr_length = IPV6_HDR_LEN;
15260 
15261 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15262 			/*
15263 			 * icmp_inbound_error_fanout_v6 may need to do
15264 			 * pullupmsg.  Reset the type to M_DATA.
15265 			 */
15266 			mp->b_datap->db_type = M_DATA;
15267 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15268 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15269 		}
15270 		if (ill_need_rele)
15271 			ill_refrele(ill);
15272 		if (rill_need_rele)
15273 			ill_refrele(recv_ill);
15274 		return;
15275 	}
15276 
15277 	if (ii->ipsec_in_v4) {
15278 		ipha = (ipha_t *)mp->b_rptr;
15279 		dst = ipha->ipha_dst;
15280 		if (CLASSD(dst)) {
15281 			/*
15282 			 * Multicast has to be delivered to all streams.
15283 			 */
15284 			dst = INADDR_BROADCAST;
15285 		}
15286 
15287 		if (ire == NULL) {
15288 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15289 			if (ire == NULL) {
15290 				if (ill_need_rele)
15291 					ill_refrele(ill);
15292 				if (rill_need_rele)
15293 					ill_refrele(recv_ill);
15294 				ip1dbg(("ip_fanout_proto_again: "
15295 				    "IRE not found"));
15296 				freemsg(ipsec_mp);
15297 				return;
15298 			}
15299 			ire_need_rele = B_TRUE;
15300 		}
15301 
15302 		switch (ipha->ipha_protocol) {
15303 			case IPPROTO_UDP:
15304 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15305 				    recv_ill);
15306 				if (ire_need_rele)
15307 					ire_refrele(ire);
15308 				break;
15309 			case IPPROTO_TCP:
15310 				if (!ire_need_rele)
15311 					IRE_REFHOLD(ire);
15312 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15313 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15314 				IRE_REFRELE(ire);
15315 				if (mp != NULL)
15316 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15317 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15318 				break;
15319 			case IPPROTO_SCTP:
15320 				if (!ire_need_rele)
15321 					IRE_REFHOLD(ire);
15322 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15323 				    ipsec_mp, 0, ill->ill_rq, dst);
15324 				break;
15325 			default:
15326 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15327 				    recv_ill);
15328 				if (ire_need_rele)
15329 					ire_refrele(ire);
15330 				break;
15331 		}
15332 	} else {
15333 		uint32_t rput_flags = 0;
15334 
15335 		ip6h = (ip6_t *)mp->b_rptr;
15336 		v6dstp = &ip6h->ip6_dst;
15337 		/*
15338 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15339 		 * address.
15340 		 *
15341 		 * Currently, we don't store that state in the IPSEC_IN
15342 		 * message, and we may need to.
15343 		 */
15344 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15345 		    IP6_IN_LLMCAST : 0);
15346 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15347 		    NULL);
15348 	}
15349 	if (ill_need_rele)
15350 		ill_refrele(ill);
15351 	if (rill_need_rele)
15352 		ill_refrele(recv_ill);
15353 }
15354 
15355 /*
15356  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15357  * returns 'true' if there are still fragments left on the queue, in
15358  * which case we restart the timer.
15359  */
15360 void
15361 ill_frag_timer(void *arg)
15362 {
15363 	ill_t	*ill = (ill_t *)arg;
15364 	boolean_t frag_pending;
15365 
15366 	mutex_enter(&ill->ill_lock);
15367 	ASSERT(!ill->ill_fragtimer_executing);
15368 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15369 		ill->ill_frag_timer_id = 0;
15370 		mutex_exit(&ill->ill_lock);
15371 		return;
15372 	}
15373 	ill->ill_fragtimer_executing = 1;
15374 	mutex_exit(&ill->ill_lock);
15375 
15376 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15377 
15378 	/*
15379 	 * Restart the timer, if we have fragments pending or if someone
15380 	 * wanted us to be scheduled again.
15381 	 */
15382 	mutex_enter(&ill->ill_lock);
15383 	ill->ill_fragtimer_executing = 0;
15384 	ill->ill_frag_timer_id = 0;
15385 	if (frag_pending || ill->ill_fragtimer_needrestart)
15386 		ill_frag_timer_start(ill);
15387 	mutex_exit(&ill->ill_lock);
15388 }
15389 
15390 void
15391 ill_frag_timer_start(ill_t *ill)
15392 {
15393 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15394 
15395 	/* If the ill is closing or opening don't proceed */
15396 	if (ill->ill_state_flags & ILL_CONDEMNED)
15397 		return;
15398 
15399 	if (ill->ill_fragtimer_executing) {
15400 		/*
15401 		 * ill_frag_timer is currently executing. Just record the
15402 		 * the fact that we want the timer to be restarted.
15403 		 * ill_frag_timer will post a timeout before it returns,
15404 		 * ensuring it will be called again.
15405 		 */
15406 		ill->ill_fragtimer_needrestart = 1;
15407 		return;
15408 	}
15409 
15410 	if (ill->ill_frag_timer_id == 0) {
15411 		/*
15412 		 * The timer is neither running nor is the timeout handler
15413 		 * executing. Post a timeout so that ill_frag_timer will be
15414 		 * called
15415 		 */
15416 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15417 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15418 		ill->ill_fragtimer_needrestart = 0;
15419 	}
15420 }
15421 
15422 /*
15423  * This routine is needed for loopback when forwarding multicasts.
15424  *
15425  * IPQoS Notes:
15426  * IPPF processing is done in fanout routines.
15427  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15428  * processing for IPSec packets is done when it comes back in clear.
15429  * NOTE : The callers of this function need to do the ire_refrele for the
15430  *	  ire that is being passed in.
15431  */
15432 void
15433 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15434     ill_t *recv_ill)
15435 {
15436 	ill_t	*ill = (ill_t *)q->q_ptr;
15437 	uint32_t	sum;
15438 	uint32_t	u1;
15439 	uint32_t	u2;
15440 	int		hdr_length;
15441 	boolean_t	mctl_present;
15442 	mblk_t		*first_mp = mp;
15443 	mblk_t		*hada_mp = NULL;
15444 	ipha_t		*inner_ipha;
15445 
15446 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15447 	    "ip_rput_locl_start: q %p", q);
15448 
15449 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15450 
15451 
15452 #define	rptr	((uchar_t *)ipha)
15453 #define	iphs	((uint16_t *)ipha)
15454 
15455 	/*
15456 	 * no UDP or TCP packet should come here anymore.
15457 	 */
15458 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15459 	    (ipha->ipha_protocol != IPPROTO_UDP));
15460 
15461 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15462 	if (mctl_present &&
15463 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15464 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15465 
15466 		/*
15467 		 * It's an IPsec accelerated packet.
15468 		 * Keep a pointer to the data attributes around until
15469 		 * we allocate the ipsec_info_t.
15470 		 */
15471 		IPSECHW_DEBUG(IPSECHW_PKT,
15472 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15473 		hada_mp = first_mp;
15474 		hada_mp->b_cont = NULL;
15475 		/*
15476 		 * Since it is accelerated, it comes directly from
15477 		 * the ill and the data attributes is followed by
15478 		 * the packet data.
15479 		 */
15480 		ASSERT(mp->b_datap->db_type != M_CTL);
15481 		first_mp = mp;
15482 		mctl_present = B_FALSE;
15483 	}
15484 
15485 	/*
15486 	 * IF M_CTL is not present, then ipsec_in_is_secure
15487 	 * should return B_TRUE. There is a case where loopback
15488 	 * packets has an M_CTL in the front with all the
15489 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15490 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15491 	 * packets never comes here, it is safe to ASSERT the
15492 	 * following.
15493 	 */
15494 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15495 
15496 
15497 	/* u1 is # words of IP options */
15498 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15499 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15500 
15501 	if (u1) {
15502 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15503 			if (hada_mp != NULL)
15504 				freemsg(hada_mp);
15505 			return;
15506 		}
15507 	} else {
15508 		/* Check the IP header checksum.  */
15509 #define	uph	((uint16_t *)ipha)
15510 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15511 		    uph[6] + uph[7] + uph[8] + uph[9];
15512 #undef  uph
15513 		/* finish doing IP checksum */
15514 		sum = (sum & 0xFFFF) + (sum >> 16);
15515 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15516 		/*
15517 		 * Don't verify header checksum if this packet is coming
15518 		 * back from AH/ESP as we already did it.
15519 		 */
15520 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15521 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15522 			goto drop_pkt;
15523 		}
15524 	}
15525 
15526 	/*
15527 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15528 	 * might be called more than once for secure packets, count only
15529 	 * the first time.
15530 	 */
15531 	if (!mctl_present) {
15532 		UPDATE_IB_PKT_COUNT(ire);
15533 		ire->ire_last_used_time = lbolt;
15534 	}
15535 
15536 	/* Check for fragmentation offset. */
15537 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15538 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15539 	if (u1) {
15540 		/*
15541 		 * We re-assemble fragments before we do the AH/ESP
15542 		 * processing. Thus, M_CTL should not be present
15543 		 * while we are re-assembling.
15544 		 */
15545 		ASSERT(!mctl_present);
15546 		ASSERT(first_mp == mp);
15547 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
15548 			return;
15549 		}
15550 		/*
15551 		 * Make sure that first_mp points back to mp as
15552 		 * the mp we came in with could have changed in
15553 		 * ip_rput_fragment().
15554 		 */
15555 		ipha = (ipha_t *)mp->b_rptr;
15556 		first_mp = mp;
15557 	}
15558 
15559 	/*
15560 	 * Clear hardware checksumming flag as it is currently only
15561 	 * used by TCP and UDP.
15562 	 */
15563 	DB_CKSUMFLAGS(mp) = 0;
15564 
15565 	/* Now we have a complete datagram, destined for this machine. */
15566 	u1 = IPH_HDR_LENGTH(ipha);
15567 	switch (ipha->ipha_protocol) {
15568 	case IPPROTO_ICMP: {
15569 		ire_t		*ire_zone;
15570 		ilm_t		*ilm;
15571 		mblk_t		*mp1;
15572 		zoneid_t	last_zoneid;
15573 
15574 		if (CLASSD(ipha->ipha_dst) &&
15575 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15576 			ASSERT(ire->ire_type == IRE_BROADCAST);
15577 			/*
15578 			 * In the multicast case, applications may have joined
15579 			 * the group from different zones, so we need to deliver
15580 			 * the packet to each of them. Loop through the
15581 			 * multicast memberships structures (ilm) on the receive
15582 			 * ill and send a copy of the packet up each matching
15583 			 * one. However, we don't do this for multicasts sent on
15584 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15585 			 * they must stay in the sender's zone.
15586 			 *
15587 			 * ilm_add_v6() ensures that ilms in the same zone are
15588 			 * contiguous in the ill_ilm list. We use this property
15589 			 * to avoid sending duplicates needed when two
15590 			 * applications in the same zone join the same group on
15591 			 * different logical interfaces: we ignore the ilm if
15592 			 * its zoneid is the same as the last matching one.
15593 			 * In addition, the sending of the packet for
15594 			 * ire_zoneid is delayed until all of the other ilms
15595 			 * have been exhausted.
15596 			 */
15597 			last_zoneid = -1;
15598 			ILM_WALKER_HOLD(recv_ill);
15599 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15600 			    ilm = ilm->ilm_next) {
15601 				if ((ilm->ilm_flags & ILM_DELETED) ||
15602 				    ipha->ipha_dst != ilm->ilm_addr ||
15603 				    ilm->ilm_zoneid == last_zoneid ||
15604 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15605 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15606 					continue;
15607 				mp1 = ip_copymsg(first_mp);
15608 				if (mp1 == NULL)
15609 					continue;
15610 				icmp_inbound(q, mp1, B_TRUE, ill,
15611 				    0, sum, mctl_present, B_TRUE,
15612 				    recv_ill, ilm->ilm_zoneid);
15613 				last_zoneid = ilm->ilm_zoneid;
15614 			}
15615 			ILM_WALKER_RELE(recv_ill);
15616 		} else if (ire->ire_type == IRE_BROADCAST) {
15617 			/*
15618 			 * In the broadcast case, there may be many zones
15619 			 * which need a copy of the packet delivered to them.
15620 			 * There is one IRE_BROADCAST per broadcast address
15621 			 * and per zone; we walk those using a helper function.
15622 			 * In addition, the sending of the packet for ire is
15623 			 * delayed until all of the other ires have been
15624 			 * processed.
15625 			 */
15626 			IRB_REFHOLD(ire->ire_bucket);
15627 			ire_zone = NULL;
15628 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15629 			    ire)) != NULL) {
15630 				mp1 = ip_copymsg(first_mp);
15631 				if (mp1 == NULL)
15632 					continue;
15633 
15634 				UPDATE_IB_PKT_COUNT(ire_zone);
15635 				ire_zone->ire_last_used_time = lbolt;
15636 				icmp_inbound(q, mp1, B_TRUE, ill,
15637 				    0, sum, mctl_present, B_TRUE,
15638 				    recv_ill, ire_zone->ire_zoneid);
15639 			}
15640 			IRB_REFRELE(ire->ire_bucket);
15641 		}
15642 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15643 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15644 		    ire->ire_zoneid);
15645 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15646 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15647 		return;
15648 	}
15649 	case IPPROTO_IGMP:
15650 		/*
15651 		 * If we are not willing to accept IGMP packets in clear,
15652 		 * then check with global policy.
15653 		 */
15654 		if (igmp_accept_clear_messages == 0) {
15655 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15656 			    ipha, NULL, mctl_present);
15657 			if (first_mp == NULL)
15658 				return;
15659 		}
15660 		if (igmp_input(q, mp, ill)) {
15661 			/* Bad packet - discarded by igmp_input */
15662 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15663 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15664 			if (mctl_present)
15665 				freeb(first_mp);
15666 			return;
15667 		}
15668 		/*
15669 		 * igmp_input() may have pulled up the message so ipha needs to
15670 		 * be reinitialized.
15671 		 */
15672 		ipha = (ipha_t *)mp->b_rptr;
15673 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15674 			/* No user-level listener for IGMP packets */
15675 			goto drop_pkt;
15676 		}
15677 		/* deliver to local raw users */
15678 		break;
15679 	case IPPROTO_PIM:
15680 		/*
15681 		 * If we are not willing to accept PIM packets in clear,
15682 		 * then check with global policy.
15683 		 */
15684 		if (pim_accept_clear_messages == 0) {
15685 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15686 			    ipha, NULL, mctl_present);
15687 			if (first_mp == NULL)
15688 				return;
15689 		}
15690 		if (pim_input(q, mp) != 0) {
15691 			/* Bad packet - discarded by pim_input */
15692 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15693 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15694 			if (mctl_present)
15695 				freeb(first_mp);
15696 			return;
15697 		}
15698 
15699 		/*
15700 		 * pim_input() may have pulled up the message so ipha needs to
15701 		 * be reinitialized.
15702 		 */
15703 		ipha = (ipha_t *)mp->b_rptr;
15704 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15705 			/* No user-level listener for PIM packets */
15706 			goto drop_pkt;
15707 		}
15708 		/* deliver to local raw users */
15709 		break;
15710 	case IPPROTO_ENCAP:
15711 		/*
15712 		 * Handle self-encapsulated packets (IP-in-IP where
15713 		 * the inner addresses == the outer addresses).
15714 		 */
15715 		hdr_length = IPH_HDR_LENGTH(ipha);
15716 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15717 		    mp->b_wptr) {
15718 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15719 			    sizeof (ipha_t) - mp->b_rptr)) {
15720 				BUMP_MIB(&ip_mib, ipInDiscards);
15721 				freemsg(first_mp);
15722 				return;
15723 			}
15724 			ipha = (ipha_t *)mp->b_rptr;
15725 		}
15726 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15727 		/*
15728 		 * Check the sanity of the inner IP header.
15729 		 */
15730 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15731 			BUMP_MIB(&ip_mib, ipInDiscards);
15732 			freemsg(first_mp);
15733 			return;
15734 		}
15735 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15736 			BUMP_MIB(&ip_mib, ipInDiscards);
15737 			freemsg(first_mp);
15738 			return;
15739 		}
15740 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15741 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15742 			ipsec_in_t *ii;
15743 
15744 			/*
15745 			 * Self-encapsulated tunnel packet. Remove
15746 			 * the outer IP header and fanout again.
15747 			 * We also need to make sure that the inner
15748 			 * header is pulled up until options.
15749 			 */
15750 			mp->b_rptr = (uchar_t *)inner_ipha;
15751 			ipha = inner_ipha;
15752 			hdr_length = IPH_HDR_LENGTH(ipha);
15753 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15754 				if (!pullupmsg(mp, (uchar_t *)ipha +
15755 				    + hdr_length - mp->b_rptr)) {
15756 					freemsg(first_mp);
15757 					return;
15758 				}
15759 				ipha = (ipha_t *)mp->b_rptr;
15760 			}
15761 			if (!mctl_present) {
15762 				ASSERT(first_mp == mp);
15763 				/*
15764 				 * This means that somebody is sending
15765 				 * Self-encapsualted packets without AH/ESP.
15766 				 * If AH/ESP was present, we would have already
15767 				 * allocated the first_mp.
15768 				 */
15769 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15770 				    NULL) {
15771 					ip1dbg(("ip_proto_input: IPSEC_IN "
15772 					    "allocation failure.\n"));
15773 					BUMP_MIB(&ip_mib, ipInDiscards);
15774 					freemsg(mp);
15775 					return;
15776 				}
15777 				first_mp->b_cont = mp;
15778 			}
15779 			/*
15780 			 * We generally store the ill_index if we need to
15781 			 * do IPSEC processing as we lose the ill queue when
15782 			 * we come back. But in this case, we never should
15783 			 * have to store the ill_index here as it should have
15784 			 * been stored previously when we processed the
15785 			 * AH/ESP header in this routine or for non-ipsec
15786 			 * cases, we still have the queue. But for some bad
15787 			 * packets from the wire, we can get to IPSEC after
15788 			 * this and we better store the index for that case.
15789 			 */
15790 			ill = (ill_t *)q->q_ptr;
15791 			ii = (ipsec_in_t *)first_mp->b_rptr;
15792 			ii->ipsec_in_ill_index =
15793 			    ill->ill_phyint->phyint_ifindex;
15794 			ii->ipsec_in_rill_index =
15795 			    recv_ill->ill_phyint->phyint_ifindex;
15796 			if (ii->ipsec_in_decaps) {
15797 				/*
15798 				 * This packet is self-encapsulated multiple
15799 				 * times. We don't want to recurse infinitely.
15800 				 * To keep it simple, drop the packet.
15801 				 */
15802 				BUMP_MIB(&ip_mib, ipInDiscards);
15803 				freemsg(first_mp);
15804 				return;
15805 			}
15806 			ii->ipsec_in_decaps = B_TRUE;
15807 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15808 			return;
15809 		}
15810 		break;
15811 	case IPPROTO_AH:
15812 	case IPPROTO_ESP: {
15813 		/*
15814 		 * Fast path for AH/ESP. If this is the first time
15815 		 * we are sending a datagram to AH/ESP, allocate
15816 		 * a IPSEC_IN message and prepend it. Otherwise,
15817 		 * just fanout.
15818 		 */
15819 
15820 		int ipsec_rc;
15821 		ipsec_in_t *ii;
15822 
15823 		IP_STAT(ipsec_proto_ahesp);
15824 		if (!mctl_present) {
15825 			ASSERT(first_mp == mp);
15826 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15827 				ip1dbg(("ip_proto_input: IPSEC_IN "
15828 				    "allocation failure.\n"));
15829 				freemsg(hada_mp); /* okay ifnull */
15830 				BUMP_MIB(&ip_mib, ipInDiscards);
15831 				freemsg(mp);
15832 				return;
15833 			}
15834 			/*
15835 			 * Store the ill_index so that when we come back
15836 			 * from IPSEC we ride on the same queue.
15837 			 */
15838 			ill = (ill_t *)q->q_ptr;
15839 			ii = (ipsec_in_t *)first_mp->b_rptr;
15840 			ii->ipsec_in_ill_index =
15841 			    ill->ill_phyint->phyint_ifindex;
15842 			ii->ipsec_in_rill_index =
15843 			    recv_ill->ill_phyint->phyint_ifindex;
15844 			first_mp->b_cont = mp;
15845 			/*
15846 			 * Cache hardware acceleration info.
15847 			 */
15848 			if (hada_mp != NULL) {
15849 				IPSECHW_DEBUG(IPSECHW_PKT,
15850 				    ("ip_rput_local: caching data attr.\n"));
15851 				ii->ipsec_in_accelerated = B_TRUE;
15852 				ii->ipsec_in_da = hada_mp;
15853 				hada_mp = NULL;
15854 			}
15855 		} else {
15856 			ii = (ipsec_in_t *)first_mp->b_rptr;
15857 		}
15858 
15859 		if (!ipsec_loaded()) {
15860 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15861 			    ire->ire_zoneid);
15862 			return;
15863 		}
15864 
15865 		/* select inbound SA and have IPsec process the pkt */
15866 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15867 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15868 			if (esph == NULL)
15869 				return;
15870 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15871 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15872 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15873 			    first_mp, esph);
15874 		} else {
15875 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15876 			if (ah == NULL)
15877 				return;
15878 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15879 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15880 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15881 			    first_mp, ah);
15882 		}
15883 
15884 		switch (ipsec_rc) {
15885 		case IPSEC_STATUS_SUCCESS:
15886 			break;
15887 		case IPSEC_STATUS_FAILED:
15888 			BUMP_MIB(&ip_mib, ipInDiscards);
15889 			/* FALLTHRU */
15890 		case IPSEC_STATUS_PENDING:
15891 			return;
15892 		}
15893 		/* we're done with IPsec processing, send it up */
15894 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15895 		return;
15896 	}
15897 	default:
15898 		break;
15899 	}
15900 	/*
15901 	 * Handle protocols with which IP is less intimate.  There
15902 	 * can be more than one stream bound to a particular
15903 	 * protocol.  When this is the case, each one gets a copy
15904 	 * of any incoming packets.
15905 	 */
15906 	ip_fanout_proto(q, first_mp, ill, ipha,
15907 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15908 	    B_TRUE, recv_ill, ire->ire_zoneid);
15909 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15910 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15911 	return;
15912 
15913 drop_pkt:
15914 	freemsg(first_mp);
15915 	if (hada_mp != NULL)
15916 		freeb(hada_mp);
15917 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15918 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15919 #undef	rptr
15920 #undef  iphs
15921 
15922 }
15923 
15924 /*
15925  * Update any source route, record route or timestamp options.
15926  * Check that we are at end of strict source route.
15927  * The options have already been checked for sanity in ip_rput_options().
15928  */
15929 static boolean_t
15930 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15931 {
15932 	ipoptp_t	opts;
15933 	uchar_t		*opt;
15934 	uint8_t		optval;
15935 	uint8_t		optlen;
15936 	ipaddr_t	dst;
15937 	uint32_t	ts;
15938 	ire_t		*dst_ire;
15939 	timestruc_t	now;
15940 
15941 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15942 
15943 	ip2dbg(("ip_rput_local_options\n"));
15944 
15945 	for (optval = ipoptp_first(&opts, ipha);
15946 	    optval != IPOPT_EOL;
15947 	    optval = ipoptp_next(&opts)) {
15948 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15949 		opt = opts.ipoptp_cur;
15950 		optlen = opts.ipoptp_len;
15951 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15952 		    optval, optlen));
15953 		switch (optval) {
15954 			uint32_t off;
15955 		case IPOPT_SSRR:
15956 		case IPOPT_LSRR:
15957 			off = opt[IPOPT_OFFSET];
15958 			off--;
15959 			if (optlen < IP_ADDR_LEN ||
15960 			    off > optlen - IP_ADDR_LEN) {
15961 				/* End of source route */
15962 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15963 				break;
15964 			}
15965 			/*
15966 			 * This will only happen if two consecutive entries
15967 			 * in the source route contains our address or if
15968 			 * it is a packet with a loose source route which
15969 			 * reaches us before consuming the whole source route
15970 			 */
15971 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15972 			if (optval == IPOPT_SSRR) {
15973 				goto bad_src_route;
15974 			}
15975 			/*
15976 			 * Hack: instead of dropping the packet truncate the
15977 			 * source route to what has been used by filling the
15978 			 * rest with IPOPT_NOP.
15979 			 */
15980 			opt[IPOPT_OLEN] = (uint8_t)off;
15981 			while (off < optlen) {
15982 				opt[off++] = IPOPT_NOP;
15983 			}
15984 			break;
15985 		case IPOPT_RR:
15986 			off = opt[IPOPT_OFFSET];
15987 			off--;
15988 			if (optlen < IP_ADDR_LEN ||
15989 			    off > optlen - IP_ADDR_LEN) {
15990 				/* No more room - ignore */
15991 				ip1dbg((
15992 				    "ip_rput_local_options: end of RR\n"));
15993 				break;
15994 			}
15995 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15996 			    IP_ADDR_LEN);
15997 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15998 			break;
15999 		case IPOPT_TS:
16000 			/* Insert timestamp if there is romm */
16001 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16002 			case IPOPT_TS_TSONLY:
16003 				off = IPOPT_TS_TIMELEN;
16004 				break;
16005 			case IPOPT_TS_PRESPEC:
16006 			case IPOPT_TS_PRESPEC_RFC791:
16007 				/* Verify that the address matched */
16008 				off = opt[IPOPT_OFFSET] - 1;
16009 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16010 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16011 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
16012 				if (dst_ire == NULL) {
16013 					/* Not for us */
16014 					break;
16015 				}
16016 				ire_refrele(dst_ire);
16017 				/* FALLTHRU */
16018 			case IPOPT_TS_TSANDADDR:
16019 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16020 				break;
16021 			default:
16022 				/*
16023 				 * ip_*put_options should have already
16024 				 * dropped this packet.
16025 				 */
16026 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16027 				    "unknown IT - bug in ip_rput_options?\n");
16028 				return (B_TRUE);	/* Keep "lint" happy */
16029 			}
16030 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16031 				/* Increase overflow counter */
16032 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16033 				opt[IPOPT_POS_OV_FLG] =
16034 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16035 				    (off << 4));
16036 				break;
16037 			}
16038 			off = opt[IPOPT_OFFSET] - 1;
16039 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16040 			case IPOPT_TS_PRESPEC:
16041 			case IPOPT_TS_PRESPEC_RFC791:
16042 			case IPOPT_TS_TSANDADDR:
16043 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16044 				    IP_ADDR_LEN);
16045 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16046 				/* FALLTHRU */
16047 			case IPOPT_TS_TSONLY:
16048 				off = opt[IPOPT_OFFSET] - 1;
16049 				/* Compute # of milliseconds since midnight */
16050 				gethrestime(&now);
16051 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16052 				    now.tv_nsec / (NANOSEC / MILLISEC);
16053 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16054 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16055 				break;
16056 			}
16057 			break;
16058 		}
16059 	}
16060 	return (B_TRUE);
16061 
16062 bad_src_route:
16063 	q = WR(q);
16064 	/* make sure we clear any indication of a hardware checksum */
16065 	DB_CKSUMFLAGS(mp) = 0;
16066 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16067 	return (B_FALSE);
16068 
16069 }
16070 
16071 /*
16072  * Process IP options in an inbound packet.  If an option affects the
16073  * effective destination address, return the next hop address via dstp.
16074  * Returns -1 if something fails in which case an ICMP error has been sent
16075  * and mp freed.
16076  */
16077 static int
16078 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16079 {
16080 	ipoptp_t	opts;
16081 	uchar_t		*opt;
16082 	uint8_t		optval;
16083 	uint8_t		optlen;
16084 	ipaddr_t	dst;
16085 	intptr_t	code = 0;
16086 	ire_t		*ire = NULL;
16087 
16088 	ip2dbg(("ip_rput_options\n"));
16089 	dst = ipha->ipha_dst;
16090 	for (optval = ipoptp_first(&opts, ipha);
16091 	    optval != IPOPT_EOL;
16092 	    optval = ipoptp_next(&opts)) {
16093 		opt = opts.ipoptp_cur;
16094 		optlen = opts.ipoptp_len;
16095 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16096 		    optval, optlen));
16097 		/*
16098 		 * Note: we need to verify the checksum before we
16099 		 * modify anything thus this routine only extracts the next
16100 		 * hop dst from any source route.
16101 		 */
16102 		switch (optval) {
16103 			uint32_t off;
16104 		case IPOPT_SSRR:
16105 		case IPOPT_LSRR:
16106 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16107 			    ALL_ZONES, MATCH_IRE_TYPE);
16108 			if (ire == NULL) {
16109 				if (optval == IPOPT_SSRR) {
16110 					ip1dbg(("ip_rput_options: not next"
16111 					    " strict source route 0x%x\n",
16112 					    ntohl(dst)));
16113 					code = (char *)&ipha->ipha_dst -
16114 					    (char *)ipha;
16115 					goto param_prob; /* RouterReq's */
16116 				}
16117 				ip2dbg(("ip_rput_options: "
16118 				    "not next source route 0x%x\n",
16119 				    ntohl(dst)));
16120 				break;
16121 			}
16122 			ire_refrele(ire);
16123 
16124 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16125 				ip1dbg((
16126 				    "ip_rput_options: bad option offset\n"));
16127 				code = (char *)&opt[IPOPT_OLEN] -
16128 				    (char *)ipha;
16129 				goto param_prob;
16130 			}
16131 			off = opt[IPOPT_OFFSET];
16132 			off--;
16133 		redo_srr:
16134 			if (optlen < IP_ADDR_LEN ||
16135 			    off > optlen - IP_ADDR_LEN) {
16136 				/* End of source route */
16137 				ip1dbg(("ip_rput_options: end of SR\n"));
16138 				break;
16139 			}
16140 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16141 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16142 			    ntohl(dst)));
16143 
16144 			/*
16145 			 * Check if our address is present more than
16146 			 * once as consecutive hops in source route.
16147 			 * XXX verify per-interface ip_forwarding
16148 			 * for source route?
16149 			 */
16150 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16151 			    ALL_ZONES, MATCH_IRE_TYPE);
16152 
16153 			if (ire != NULL) {
16154 				ire_refrele(ire);
16155 				off += IP_ADDR_LEN;
16156 				goto redo_srr;
16157 			}
16158 
16159 			if (dst == htonl(INADDR_LOOPBACK)) {
16160 				ip1dbg(("ip_rput_options: loopback addr in "
16161 				    "source route!\n"));
16162 				goto bad_src_route;
16163 			}
16164 			/*
16165 			 * For strict: verify that dst is directly
16166 			 * reachable.
16167 			 */
16168 			if (optval == IPOPT_SSRR) {
16169 				ire = ire_ftable_lookup(dst, 0, 0,
16170 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16171 				    MATCH_IRE_TYPE);
16172 				if (ire == NULL) {
16173 					ip1dbg(("ip_rput_options: SSRR not "
16174 					    "directly reachable: 0x%x\n",
16175 					    ntohl(dst)));
16176 					goto bad_src_route;
16177 				}
16178 				ire_refrele(ire);
16179 			}
16180 			/*
16181 			 * Defer update of the offset and the record route
16182 			 * until the packet is forwarded.
16183 			 */
16184 			break;
16185 		case IPOPT_RR:
16186 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16187 				ip1dbg((
16188 				    "ip_rput_options: bad option offset\n"));
16189 				code = (char *)&opt[IPOPT_OLEN] -
16190 				    (char *)ipha;
16191 				goto param_prob;
16192 			}
16193 			break;
16194 		case IPOPT_TS:
16195 			/*
16196 			 * Verify that length >= 5 and that there is either
16197 			 * room for another timestamp or that the overflow
16198 			 * counter is not maxed out.
16199 			 */
16200 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16201 			if (optlen < IPOPT_MINLEN_IT) {
16202 				goto param_prob;
16203 			}
16204 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16205 				ip1dbg((
16206 				    "ip_rput_options: bad option offset\n"));
16207 				code = (char *)&opt[IPOPT_OFFSET] -
16208 				    (char *)ipha;
16209 				goto param_prob;
16210 			}
16211 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16212 			case IPOPT_TS_TSONLY:
16213 				off = IPOPT_TS_TIMELEN;
16214 				break;
16215 			case IPOPT_TS_TSANDADDR:
16216 			case IPOPT_TS_PRESPEC:
16217 			case IPOPT_TS_PRESPEC_RFC791:
16218 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16219 				break;
16220 			default:
16221 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16222 				    (char *)ipha;
16223 				goto param_prob;
16224 			}
16225 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16226 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16227 				/*
16228 				 * No room and the overflow counter is 15
16229 				 * already.
16230 				 */
16231 				goto param_prob;
16232 			}
16233 			break;
16234 		}
16235 	}
16236 
16237 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16238 		*dstp = dst;
16239 		return (0);
16240 	}
16241 
16242 	ip1dbg(("ip_rput_options: error processing IP options."));
16243 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16244 
16245 param_prob:
16246 	q = WR(q);
16247 	/* make sure we clear any indication of a hardware checksum */
16248 	DB_CKSUMFLAGS(mp) = 0;
16249 	icmp_param_problem(q, mp, (uint8_t)code);
16250 	return (-1);
16251 
16252 bad_src_route:
16253 	q = WR(q);
16254 	/* make sure we clear any indication of a hardware checksum */
16255 	DB_CKSUMFLAGS(mp) = 0;
16256 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16257 	return (-1);
16258 }
16259 
16260 /*
16261  * IP & ICMP info in >=14 msg's ...
16262  *  - ip fixed part (mib2_ip_t)
16263  *  - icmp fixed part (mib2_icmp_t)
16264  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16265  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16266  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16267  *  - ip multicast membership (ip_member_t)
16268  *  - ip multicast source filtering (ip_grpsrc_t)
16269  *  - igmp fixed part (struct igmpstat)
16270  *  - multicast routing stats (struct mrtstat)
16271  *  - multicast routing vifs (array of struct vifctl)
16272  *  - multicast routing routes (array of struct mfcctl)
16273  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16274  *					One per ill plus one generic
16275  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16276  *					One per ill plus one generic
16277  *  - ipv6RouteEntry			all IPv6 IREs
16278  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16279  *  - ipv6AddrEntry			all IPv6 ipifs
16280  *  - ipv6 multicast membership (ipv6_member_t)
16281  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16282  *
16283  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16284  * already present.
16285  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16286  * already filled in by caller.
16287  * Return value of 0 indicates that no messages were sent and caller
16288  * should free mpctl.
16289  */
16290 int
16291 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16292 {
16293 
16294 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16295 		return (0);
16296 	}
16297 
16298 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16299 		return (1);
16300 	}
16301 
16302 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16303 		return (1);
16304 	}
16305 
16306 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16307 		return (1);
16308 	}
16309 
16310 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16311 		return (1);
16312 	}
16313 
16314 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16315 		return (1);
16316 	}
16317 
16318 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16319 		return (1);
16320 	}
16321 
16322 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16323 		return (1);
16324 	}
16325 
16326 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16327 		return (1);
16328 	}
16329 
16330 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16331 		return (1);
16332 	}
16333 
16334 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16335 		return (1);
16336 	}
16337 
16338 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16339 		return (1);
16340 	}
16341 
16342 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16343 		return (1);
16344 	}
16345 
16346 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16347 		return (1);
16348 	}
16349 
16350 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16351 		return (1);
16352 	}
16353 
16354 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16355 		return (1);
16356 	}
16357 
16358 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16359 		return (1);
16360 	}
16361 
16362 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16363 		return (1);
16364 	}
16365 	freemsg(mpctl);
16366 	return (1);
16367 }
16368 
16369 
16370 /* Get global IPv4 statistics */
16371 static mblk_t *
16372 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16373 {
16374 	struct opthdr		*optp;
16375 	mblk_t			*mp2ctl;
16376 
16377 	/*
16378 	 * make a copy of the original message
16379 	 */
16380 	mp2ctl = copymsg(mpctl);
16381 
16382 	/* fixed length IP structure... */
16383 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16384 	optp->level = MIB2_IP;
16385 	optp->name = 0;
16386 	SET_MIB(ip_mib.ipForwarding,
16387 	    (WE_ARE_FORWARDING ? 1 : 2));
16388 	SET_MIB(ip_mib.ipDefaultTTL,
16389 	    (uint32_t)ip_def_ttl);
16390 	SET_MIB(ip_mib.ipReasmTimeout,
16391 	    ip_g_frag_timeout);
16392 	SET_MIB(ip_mib.ipAddrEntrySize,
16393 	    sizeof (mib2_ipAddrEntry_t));
16394 	SET_MIB(ip_mib.ipRouteEntrySize,
16395 	    sizeof (mib2_ipRouteEntry_t));
16396 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16397 	    sizeof (mib2_ipNetToMediaEntry_t));
16398 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16399 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16400 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16401 	    (int)sizeof (ip_mib))) {
16402 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16403 		    (uint_t)sizeof (ip_mib)));
16404 	}
16405 
16406 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16407 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16408 	    (int)optp->level, (int)optp->name, (int)optp->len));
16409 	qreply(q, mpctl);
16410 	return (mp2ctl);
16411 }
16412 
16413 /* Global IPv4 ICMP statistics */
16414 static mblk_t *
16415 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16416 {
16417 	struct opthdr		*optp;
16418 	mblk_t			*mp2ctl;
16419 
16420 	/*
16421 	 * Make a copy of the original message
16422 	 */
16423 	mp2ctl = copymsg(mpctl);
16424 
16425 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16426 	optp->level = MIB2_ICMP;
16427 	optp->name = 0;
16428 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16429 	    (int)sizeof (icmp_mib))) {
16430 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16431 		    (uint_t)sizeof (icmp_mib)));
16432 	}
16433 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16434 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16435 	    (int)optp->level, (int)optp->name, (int)optp->len));
16436 	qreply(q, mpctl);
16437 	return (mp2ctl);
16438 }
16439 
16440 /* Global IPv4 IGMP statistics */
16441 static mblk_t *
16442 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16443 {
16444 	struct opthdr		*optp;
16445 	mblk_t			*mp2ctl;
16446 
16447 	/*
16448 	 * make a copy of the original message
16449 	 */
16450 	mp2ctl = copymsg(mpctl);
16451 
16452 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16453 	optp->level = EXPER_IGMP;
16454 	optp->name = 0;
16455 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16456 	    (int)sizeof (igmpstat))) {
16457 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16458 		    (uint_t)sizeof (igmpstat)));
16459 	}
16460 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16461 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16462 	    (int)optp->level, (int)optp->name, (int)optp->len));
16463 	qreply(q, mpctl);
16464 	return (mp2ctl);
16465 }
16466 
16467 /* Global IPv4 Multicast Routing statistics */
16468 static mblk_t *
16469 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16470 {
16471 	struct opthdr		*optp;
16472 	mblk_t			*mp2ctl;
16473 
16474 	/*
16475 	 * make a copy of the original message
16476 	 */
16477 	mp2ctl = copymsg(mpctl);
16478 
16479 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16480 	optp->level = EXPER_DVMRP;
16481 	optp->name = 0;
16482 	if (!ip_mroute_stats(mpctl->b_cont)) {
16483 		ip0dbg(("ip_mroute_stats: failed\n"));
16484 	}
16485 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16486 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16487 	    (int)optp->level, (int)optp->name, (int)optp->len));
16488 	qreply(q, mpctl);
16489 	return (mp2ctl);
16490 }
16491 
16492 /* IPv4 address information */
16493 static mblk_t *
16494 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16495 {
16496 	struct opthdr		*optp;
16497 	mblk_t			*mp2ctl;
16498 	mblk_t			*mp_tail = NULL;
16499 	ill_t			*ill;
16500 	ipif_t			*ipif;
16501 	uint_t			bitval;
16502 	mib2_ipAddrEntry_t	mae;
16503 	zoneid_t		zoneid;
16504 	ill_walk_context_t ctx;
16505 
16506 	/*
16507 	 * make a copy of the original message
16508 	 */
16509 	mp2ctl = copymsg(mpctl);
16510 
16511 	/* ipAddrEntryTable */
16512 
16513 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16514 	optp->level = MIB2_IP;
16515 	optp->name = MIB2_IP_ADDR;
16516 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16517 
16518 	rw_enter(&ill_g_lock, RW_READER);
16519 	ill = ILL_START_WALK_V4(&ctx);
16520 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16521 		for (ipif = ill->ill_ipif; ipif != NULL;
16522 		    ipif = ipif->ipif_next) {
16523 			if (ipif->ipif_zoneid != zoneid)
16524 				continue;
16525 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16526 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16527 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16528 
16529 			(void) ipif_get_name(ipif,
16530 			    mae.ipAdEntIfIndex.o_bytes,
16531 			    OCTET_LENGTH);
16532 			mae.ipAdEntIfIndex.o_length =
16533 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16534 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16535 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16536 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16537 			mae.ipAdEntInfo.ae_subnet_len =
16538 			    ip_mask_to_plen(ipif->ipif_net_mask);
16539 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16540 			for (bitval = 1;
16541 			    bitval &&
16542 			    !(bitval & ipif->ipif_brd_addr);
16543 			    bitval <<= 1)
16544 				noop;
16545 			mae.ipAdEntBcastAddr = bitval;
16546 			mae.ipAdEntReasmMaxSize = 65535;
16547 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16548 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16549 			mae.ipAdEntInfo.ae_broadcast_addr =
16550 			    ipif->ipif_brd_addr;
16551 			mae.ipAdEntInfo.ae_pp_dst_addr =
16552 			    ipif->ipif_pp_dst_addr;
16553 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16554 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16555 
16556 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16557 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16558 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16559 				    "allocate %u bytes\n",
16560 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16561 			}
16562 		}
16563 	}
16564 	rw_exit(&ill_g_lock);
16565 
16566 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16567 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16568 	    (int)optp->level, (int)optp->name, (int)optp->len));
16569 	qreply(q, mpctl);
16570 	return (mp2ctl);
16571 }
16572 
16573 /* IPv6 address information */
16574 static mblk_t *
16575 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16576 {
16577 	struct opthdr		*optp;
16578 	mblk_t			*mp2ctl;
16579 	mblk_t			*mp_tail = NULL;
16580 	ill_t			*ill;
16581 	ipif_t			*ipif;
16582 	mib2_ipv6AddrEntry_t	mae6;
16583 	zoneid_t		zoneid;
16584 	ill_walk_context_t	ctx;
16585 
16586 	/*
16587 	 * make a copy of the original message
16588 	 */
16589 	mp2ctl = copymsg(mpctl);
16590 
16591 	/* ipv6AddrEntryTable */
16592 
16593 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16594 	optp->level = MIB2_IP6;
16595 	optp->name = MIB2_IP6_ADDR;
16596 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16597 
16598 	rw_enter(&ill_g_lock, RW_READER);
16599 	ill = ILL_START_WALK_V6(&ctx);
16600 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16601 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16602 			if (ipif->ipif_zoneid != zoneid)
16603 				continue;
16604 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16605 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16606 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16607 
16608 			(void) ipif_get_name(ipif,
16609 			    mae6.ipv6AddrIfIndex.o_bytes,
16610 			    OCTET_LENGTH);
16611 			mae6.ipv6AddrIfIndex.o_length =
16612 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16613 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16614 			mae6.ipv6AddrPfxLength =
16615 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16616 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16617 			mae6.ipv6AddrInfo.ae_subnet_len =
16618 			    mae6.ipv6AddrPfxLength;
16619 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16620 
16621 			/* Type: stateless(1), stateful(2), unknown(3) */
16622 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16623 				mae6.ipv6AddrType = 1;
16624 			else
16625 				mae6.ipv6AddrType = 2;
16626 			/* Anycast: true(1), false(2) */
16627 			if (ipif->ipif_flags & IPIF_ANYCAST)
16628 				mae6.ipv6AddrAnycastFlag = 1;
16629 			else
16630 				mae6.ipv6AddrAnycastFlag = 2;
16631 
16632 			/*
16633 			 * Address status: preferred(1), deprecated(2),
16634 			 * invalid(3), inaccessible(4), unknown(5)
16635 			 */
16636 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16637 				mae6.ipv6AddrStatus = 3;
16638 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16639 				mae6.ipv6AddrStatus = 2;
16640 			else
16641 				mae6.ipv6AddrStatus = 1;
16642 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16643 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16644 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16645 						ipif->ipif_v6pp_dst_addr;
16646 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16647 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16648 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16649 				(char *)&mae6,
16650 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16651 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16652 				    "allocate %u bytes\n",
16653 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16654 			}
16655 		}
16656 	}
16657 	rw_exit(&ill_g_lock);
16658 
16659 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16660 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16661 	    (int)optp->level, (int)optp->name, (int)optp->len));
16662 	qreply(q, mpctl);
16663 	return (mp2ctl);
16664 }
16665 
16666 /* IPv4 multicast group membership. */
16667 static mblk_t *
16668 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16669 {
16670 	struct opthdr		*optp;
16671 	mblk_t			*mp2ctl;
16672 	ill_t			*ill;
16673 	ipif_t			*ipif;
16674 	ilm_t			*ilm;
16675 	ip_member_t		ipm;
16676 	mblk_t			*mp_tail = NULL;
16677 	ill_walk_context_t	ctx;
16678 	zoneid_t		zoneid;
16679 
16680 	/*
16681 	 * make a copy of the original message
16682 	 */
16683 	mp2ctl = copymsg(mpctl);
16684 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16685 
16686 	/* ipGroupMember table */
16687 	optp = (struct opthdr *)&mpctl->b_rptr[
16688 	    sizeof (struct T_optmgmt_ack)];
16689 	optp->level = MIB2_IP;
16690 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16691 
16692 	rw_enter(&ill_g_lock, RW_READER);
16693 	ill = ILL_START_WALK_V4(&ctx);
16694 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16695 		ILM_WALKER_HOLD(ill);
16696 		for (ipif = ill->ill_ipif; ipif != NULL;
16697 		    ipif = ipif->ipif_next) {
16698 			if (ipif->ipif_zoneid != zoneid)
16699 				continue;	/* not this zone */
16700 			(void) ipif_get_name(ipif,
16701 			    ipm.ipGroupMemberIfIndex.o_bytes,
16702 			    OCTET_LENGTH);
16703 			ipm.ipGroupMemberIfIndex.o_length =
16704 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16705 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16706 				ASSERT(ilm->ilm_ipif != NULL);
16707 				ASSERT(ilm->ilm_ill == NULL);
16708 				if (ilm->ilm_ipif != ipif)
16709 					continue;
16710 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16711 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16712 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16713 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16714 				    (char *)&ipm, (int)sizeof (ipm))) {
16715 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16716 					    "failed to allocate %u bytes\n",
16717 						(uint_t)sizeof (ipm)));
16718 				}
16719 			}
16720 		}
16721 		ILM_WALKER_RELE(ill);
16722 	}
16723 	rw_exit(&ill_g_lock);
16724 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16725 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16726 	    (int)optp->level, (int)optp->name, (int)optp->len));
16727 	qreply(q, mpctl);
16728 	return (mp2ctl);
16729 }
16730 
16731 /* IPv6 multicast group membership. */
16732 static mblk_t *
16733 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16734 {
16735 	struct opthdr		*optp;
16736 	mblk_t			*mp2ctl;
16737 	ill_t			*ill;
16738 	ilm_t			*ilm;
16739 	ipv6_member_t		ipm6;
16740 	mblk_t			*mp_tail = NULL;
16741 	ill_walk_context_t	ctx;
16742 	zoneid_t		zoneid;
16743 
16744 	/*
16745 	 * make a copy of the original message
16746 	 */
16747 	mp2ctl = copymsg(mpctl);
16748 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16749 
16750 	/* ip6GroupMember table */
16751 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16752 	optp->level = MIB2_IP6;
16753 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16754 
16755 	rw_enter(&ill_g_lock, RW_READER);
16756 	ill = ILL_START_WALK_V6(&ctx);
16757 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16758 		ILM_WALKER_HOLD(ill);
16759 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16760 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16761 			ASSERT(ilm->ilm_ipif == NULL);
16762 			ASSERT(ilm->ilm_ill != NULL);
16763 			if (ilm->ilm_zoneid != zoneid)
16764 				continue;	/* not this zone */
16765 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16766 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16767 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16768 			if (!snmp_append_data2(mpctl->b_cont,
16769 			    &mp_tail,
16770 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16771 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16772 				    "failed to allocate %u bytes\n",
16773 				    (uint_t)sizeof (ipm6)));
16774 			}
16775 		}
16776 		ILM_WALKER_RELE(ill);
16777 	}
16778 	rw_exit(&ill_g_lock);
16779 
16780 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16781 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16782 	    (int)optp->level, (int)optp->name, (int)optp->len));
16783 	qreply(q, mpctl);
16784 	return (mp2ctl);
16785 }
16786 
16787 /* IP multicast filtered sources */
16788 static mblk_t *
16789 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16790 {
16791 	struct opthdr		*optp;
16792 	mblk_t			*mp2ctl;
16793 	ill_t			*ill;
16794 	ipif_t			*ipif;
16795 	ilm_t			*ilm;
16796 	ip_grpsrc_t		ips;
16797 	mblk_t			*mp_tail = NULL;
16798 	ill_walk_context_t	ctx;
16799 	zoneid_t		zoneid;
16800 	int			i;
16801 	slist_t			*sl;
16802 
16803 	/*
16804 	 * make a copy of the original message
16805 	 */
16806 	mp2ctl = copymsg(mpctl);
16807 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16808 
16809 	/* ipGroupSource table */
16810 	optp = (struct opthdr *)&mpctl->b_rptr[
16811 	    sizeof (struct T_optmgmt_ack)];
16812 	optp->level = MIB2_IP;
16813 	optp->name = EXPER_IP_GROUP_SOURCES;
16814 
16815 	rw_enter(&ill_g_lock, RW_READER);
16816 	ill = ILL_START_WALK_V4(&ctx);
16817 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16818 		ILM_WALKER_HOLD(ill);
16819 		for (ipif = ill->ill_ipif; ipif != NULL;
16820 		    ipif = ipif->ipif_next) {
16821 			if (ipif->ipif_zoneid != zoneid)
16822 				continue;	/* not this zone */
16823 			(void) ipif_get_name(ipif,
16824 			    ips.ipGroupSourceIfIndex.o_bytes,
16825 			    OCTET_LENGTH);
16826 			ips.ipGroupSourceIfIndex.o_length =
16827 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16828 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16829 				ASSERT(ilm->ilm_ipif != NULL);
16830 				ASSERT(ilm->ilm_ill == NULL);
16831 				sl = ilm->ilm_filter;
16832 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16833 					continue;
16834 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16835 				for (i = 0; i < sl->sl_numsrc; i++) {
16836 					if (!IN6_IS_ADDR_V4MAPPED(
16837 					    &sl->sl_addr[i]))
16838 						continue;
16839 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16840 					    ips.ipGroupSourceAddress);
16841 					if (snmp_append_data2(mpctl->b_cont,
16842 					    &mp_tail, (char *)&ips,
16843 					    (int)sizeof (ips)) == 0) {
16844 						ip1dbg(("ip_snmp_get_mib2_"
16845 						    "ip_group_src: failed to "
16846 						    "allocate %u bytes\n",
16847 						    (uint_t)sizeof (ips)));
16848 					}
16849 				}
16850 			}
16851 		}
16852 		ILM_WALKER_RELE(ill);
16853 	}
16854 	rw_exit(&ill_g_lock);
16855 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16856 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16857 	    (int)optp->level, (int)optp->name, (int)optp->len));
16858 	qreply(q, mpctl);
16859 	return (mp2ctl);
16860 }
16861 
16862 /* IPv6 multicast filtered sources. */
16863 static mblk_t *
16864 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16865 {
16866 	struct opthdr		*optp;
16867 	mblk_t			*mp2ctl;
16868 	ill_t			*ill;
16869 	ilm_t			*ilm;
16870 	ipv6_grpsrc_t		ips6;
16871 	mblk_t			*mp_tail = NULL;
16872 	ill_walk_context_t	ctx;
16873 	zoneid_t		zoneid;
16874 	int			i;
16875 	slist_t			*sl;
16876 
16877 	/*
16878 	 * make a copy of the original message
16879 	 */
16880 	mp2ctl = copymsg(mpctl);
16881 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16882 
16883 	/* ip6GroupMember table */
16884 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16885 	optp->level = MIB2_IP6;
16886 	optp->name = EXPER_IP6_GROUP_SOURCES;
16887 
16888 	rw_enter(&ill_g_lock, RW_READER);
16889 	ill = ILL_START_WALK_V6(&ctx);
16890 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16891 		ILM_WALKER_HOLD(ill);
16892 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16893 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16894 			ASSERT(ilm->ilm_ipif == NULL);
16895 			ASSERT(ilm->ilm_ill != NULL);
16896 			sl = ilm->ilm_filter;
16897 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16898 				continue;
16899 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16900 			for (i = 0; i < sl->sl_numsrc; i++) {
16901 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16902 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16903 				    (char *)&ips6, (int)sizeof (ips6))) {
16904 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16905 					    "group_src: failed to allocate "
16906 					    "%u bytes\n",
16907 					    (uint_t)sizeof (ips6)));
16908 				}
16909 			}
16910 		}
16911 		ILM_WALKER_RELE(ill);
16912 	}
16913 	rw_exit(&ill_g_lock);
16914 
16915 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16916 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16917 	    (int)optp->level, (int)optp->name, (int)optp->len));
16918 	qreply(q, mpctl);
16919 	return (mp2ctl);
16920 }
16921 
16922 /* Multicast routing virtual interface table. */
16923 static mblk_t *
16924 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16925 {
16926 	struct opthdr		*optp;
16927 	mblk_t			*mp2ctl;
16928 
16929 	/*
16930 	 * make a copy of the original message
16931 	 */
16932 	mp2ctl = copymsg(mpctl);
16933 
16934 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16935 	optp->level = EXPER_DVMRP;
16936 	optp->name = EXPER_DVMRP_VIF;
16937 	if (!ip_mroute_vif(mpctl->b_cont)) {
16938 		ip0dbg(("ip_mroute_vif: failed\n"));
16939 	}
16940 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16941 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16942 	    (int)optp->level, (int)optp->name, (int)optp->len));
16943 	qreply(q, mpctl);
16944 	return (mp2ctl);
16945 }
16946 
16947 /* Multicast routing table. */
16948 static mblk_t *
16949 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16950 {
16951 	struct opthdr		*optp;
16952 	mblk_t			*mp2ctl;
16953 
16954 	/*
16955 	 * make a copy of the original message
16956 	 */
16957 	mp2ctl = copymsg(mpctl);
16958 
16959 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16960 	optp->level = EXPER_DVMRP;
16961 	optp->name = EXPER_DVMRP_MRT;
16962 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16963 		ip0dbg(("ip_mroute_mrt: failed\n"));
16964 	}
16965 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16966 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16967 	    (int)optp->level, (int)optp->name, (int)optp->len));
16968 	qreply(q, mpctl);
16969 	return (mp2ctl);
16970 }
16971 
16972 /*
16973  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16974  * in one IRE walk.
16975  */
16976 static mblk_t *
16977 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16978 {
16979 	struct opthdr		*optp;
16980 	mblk_t			*mp2ctl;	/* Returned */
16981 	mblk_t			*mp3ctl;	/* nettomedia */
16982 	/*
16983 	 * We need two listptrs, for ipRouteEntryTable and
16984 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16985 	 */
16986 	listptr_t		re_ntme_v4[2];
16987 	zoneid_t		zoneid;
16988 
16989 	/*
16990 	 * make a copy of the original message
16991 	 */
16992 	mp2ctl = copymsg(mpctl);
16993 	mp3ctl = copymsg(mpctl);
16994 	if (mp3ctl == NULL) {
16995 		freemsg(mp2ctl);
16996 		freemsg(mpctl);
16997 		return (NULL);
16998 	}
16999 
17000 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
17001 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
17002 	/*
17003 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17004 	 * proper values when called.
17005 	 */
17006 	re_ntme_v4[0].lp_tail = NULL;
17007 	re_ntme_v4[1].lp_tail = NULL;
17008 
17009 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17010 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
17011 	if (zoneid == GLOBAL_ZONEID) {
17012 		/*
17013 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17014 		 * the sys_net_config privilege, it can only run in the global
17015 		 * zone, so we don't display these IREs in the other zones.
17016 		 */
17017 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
17018 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
17019 		    NULL);
17020 	}
17021 
17022 	/* ipRouteEntryTable in mpctl */
17023 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17024 	optp->level = MIB2_IP;
17025 	optp->name = MIB2_IP_ROUTE;
17026 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
17027 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17028 	    (int)optp->level, (int)optp->name, (int)optp->len));
17029 	qreply(q, mpctl);
17030 
17031 	/* ipNetToMediaEntryTable in mp3ctl */
17032 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17033 	optp->level = MIB2_IP;
17034 	optp->name = MIB2_IP_MEDIA;
17035 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
17036 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17037 	    (int)optp->level, (int)optp->name, (int)optp->len));
17038 	qreply(q, mp3ctl);
17039 	return (mp2ctl);
17040 }
17041 
17042 /*
17043  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
17044  * in one IRE walk.
17045  */
17046 static mblk_t *
17047 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17048 {
17049 	struct opthdr		*optp;
17050 	mblk_t			*mp2ctl;	/* Returned */
17051 	mblk_t			*mp3ctl;	/* nettomedia */
17052 	listptr_t		re_ntme_v6;
17053 	zoneid_t		zoneid;
17054 
17055 	/*
17056 	 * make a copy of the original message
17057 	 */
17058 	mp2ctl = copymsg(mpctl);
17059 	mp3ctl = copymsg(mpctl);
17060 	if (mp3ctl == NULL) {
17061 		freemsg(mp2ctl);
17062 		freemsg(mpctl);
17063 		return (NULL);
17064 	}
17065 
17066 	/*
17067 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17068 	 * proper values when called.  ipv6RouteEntryTable in is placed
17069 	 * in mpctl.
17070 	 */
17071 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
17072 	re_ntme_v6.lp_tail = NULL;
17073 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17074 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
17075 
17076 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17077 	optp->level = MIB2_IP6;
17078 	optp->name = MIB2_IP6_ROUTE;
17079 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17080 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17081 	    (int)optp->level, (int)optp->name, (int)optp->len));
17082 	qreply(q, mpctl);
17083 
17084 	/* ipv6NetToMediaEntryTable in mp3ctl */
17085 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
17086 	re_ntme_v6.lp_tail = NULL;
17087 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
17088 
17089 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17090 	optp->level = MIB2_IP6;
17091 	optp->name = MIB2_IP6_MEDIA;
17092 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17093 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17094 	    (int)optp->level, (int)optp->name, (int)optp->len));
17095 	qreply(q, mp3ctl);
17096 	return (mp2ctl);
17097 }
17098 
17099 /*
17100  * ICMPv6 mib: One per ill
17101  */
17102 static mblk_t *
17103 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17104 {
17105 	struct opthdr		*optp;
17106 	mblk_t			*mp2ctl;
17107 	ill_t			*ill;
17108 	ill_walk_context_t	ctx;
17109 	mblk_t			*mp_tail = NULL;
17110 
17111 	/*
17112 	 * Make a copy of the original message
17113 	 */
17114 	mp2ctl = copymsg(mpctl);
17115 
17116 	/* fixed length IPv6 structure ... */
17117 
17118 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17119 	optp->level = MIB2_IP6;
17120 	optp->name = 0;
17121 	/* Include "unknown interface" ip6_mib */
17122 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17123 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17124 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17125 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17126 	    sizeof (mib2_ipv6IfStatsEntry_t));
17127 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17128 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17129 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17130 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17131 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17132 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17133 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17134 	    (int)sizeof (ip6_mib))) {
17135 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17136 		    (uint_t)sizeof (ip6_mib)));
17137 	}
17138 
17139 	rw_enter(&ill_g_lock, RW_READER);
17140 	ill = ILL_START_WALK_V6(&ctx);
17141 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17142 		ill->ill_ip6_mib->ipv6IfIndex =
17143 		    ill->ill_phyint->phyint_ifindex;
17144 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17145 		    ipv6_forward ? 1 : 2);
17146 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17147 		    ill->ill_max_hops);
17148 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17149 		    sizeof (mib2_ipv6IfStatsEntry_t));
17150 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17151 		    sizeof (mib2_ipv6AddrEntry_t));
17152 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17153 		    sizeof (mib2_ipv6RouteEntry_t));
17154 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17155 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17156 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17157 		    sizeof (ipv6_member_t));
17158 
17159 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17160 		    (char *)ill->ill_ip6_mib,
17161 		    (int)sizeof (*ill->ill_ip6_mib))) {
17162 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17163 				"%u bytes\n",
17164 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17165 		}
17166 	}
17167 	rw_exit(&ill_g_lock);
17168 
17169 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17170 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17171 	    (int)optp->level, (int)optp->name, (int)optp->len));
17172 	qreply(q, mpctl);
17173 	return (mp2ctl);
17174 }
17175 
17176 /*
17177  * ICMPv6 mib: One per ill
17178  */
17179 static mblk_t *
17180 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17181 {
17182 	struct opthdr		*optp;
17183 	mblk_t			*mp2ctl;
17184 	ill_t			*ill;
17185 	ill_walk_context_t	ctx;
17186 	mblk_t			*mp_tail = NULL;
17187 	/*
17188 	 * Make a copy of the original message
17189 	 */
17190 	mp2ctl = copymsg(mpctl);
17191 
17192 	/* fixed length ICMPv6 structure ... */
17193 
17194 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17195 	optp->level = MIB2_ICMP6;
17196 	optp->name = 0;
17197 	/* Include "unknown interface" icmp6_mib */
17198 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17199 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17200 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17201 	    (int)sizeof (icmp6_mib))) {
17202 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17203 		    (uint_t)sizeof (icmp6_mib)));
17204 	}
17205 
17206 	rw_enter(&ill_g_lock, RW_READER);
17207 	ill = ILL_START_WALK_V6(&ctx);
17208 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17209 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17210 		    ill->ill_phyint->phyint_ifindex;
17211 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17212 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17213 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17214 		    (char *)ill->ill_icmp6_mib,
17215 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17216 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17217 			    "%u bytes\n",
17218 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17219 		}
17220 	}
17221 	rw_exit(&ill_g_lock);
17222 
17223 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17224 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17225 	    (int)optp->level, (int)optp->name, (int)optp->len));
17226 	qreply(q, mpctl);
17227 	return (mp2ctl);
17228 }
17229 
17230 /*
17231  * ire_walk routine to create both ipRouteEntryTable and
17232  * ipNetToMediaEntryTable in one IRE walk
17233  */
17234 static void
17235 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17236 {
17237 	ill_t				*ill;
17238 	ipif_t				*ipif;
17239 	mblk_t				*llmp;
17240 	dl_unitdata_req_t		*dlup;
17241 	mib2_ipRouteEntry_t		re;
17242 	mib2_ipNetToMediaEntry_t	ntme;
17243 	ipaddr_t			gw_addr;
17244 
17245 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17246 
17247 	/*
17248 	 * Return all IRE types for route table... let caller pick and choose
17249 	 */
17250 	re.ipRouteDest = ire->ire_addr;
17251 	ipif = ire->ire_ipif;
17252 	re.ipRouteIfIndex.o_length = 0;
17253 	if (ire->ire_type == IRE_CACHE) {
17254 		ill = (ill_t *)ire->ire_stq->q_ptr;
17255 		re.ipRouteIfIndex.o_length =
17256 		    ill->ill_name_length == 0 ? 0 :
17257 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17258 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17259 		    re.ipRouteIfIndex.o_length);
17260 	} else if (ipif != NULL) {
17261 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17262 		    OCTET_LENGTH);
17263 		re.ipRouteIfIndex.o_length =
17264 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17265 	}
17266 	re.ipRouteMetric1 = -1;
17267 	re.ipRouteMetric2 = -1;
17268 	re.ipRouteMetric3 = -1;
17269 	re.ipRouteMetric4 = -1;
17270 
17271 	gw_addr = ire->ire_gateway_addr;
17272 
17273 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17274 		re.ipRouteNextHop = ire->ire_src_addr;
17275 	else
17276 		re.ipRouteNextHop = gw_addr;
17277 	/* indirect(4), direct(3), or invalid(2) */
17278 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17279 		re.ipRouteType = 2;
17280 	else
17281 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17282 	re.ipRouteProto = -1;
17283 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17284 	re.ipRouteMask = ire->ire_mask;
17285 	re.ipRouteMetric5 = -1;
17286 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17287 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17288 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17289 	llmp = ire->ire_dlureq_mp;
17290 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17291 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17292 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17293 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17294 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17295 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17296 	re.ipRouteInfo.re_in_ill.o_length = 0;
17297 	if (ire->ire_in_ill != NULL) {
17298 		re.ipRouteInfo.re_in_ill.o_length =
17299 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17300 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17301 		bcopy(ire->ire_in_ill->ill_name,
17302 		    re.ipRouteInfo.re_in_ill.o_bytes,
17303 		    re.ipRouteInfo.re_in_ill.o_length);
17304 	}
17305 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17306 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17307 	    (char *)&re, (int)sizeof (re))) {
17308 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17309 		    (uint_t)sizeof (re)));
17310 	}
17311 
17312 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17313 		return;
17314 	/*
17315 	 * only IRE_CACHE entries that are for a directly connected subnet
17316 	 * get appended to net -> phys addr table
17317 	 * (others in arp)
17318 	 */
17319 	ntme.ipNetToMediaIfIndex.o_length = 0;
17320 	ill = ire_to_ill(ire);
17321 	ASSERT(ill != NULL);
17322 	ntme.ipNetToMediaIfIndex.o_length =
17323 	    ill->ill_name_length == 0 ? 0 :
17324 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17325 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17326 		    ntme.ipNetToMediaIfIndex.o_length);
17327 
17328 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17329 	if (llmp) {
17330 		uchar_t *addr;
17331 
17332 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17333 		/* Remove sap from  address */
17334 		if (ill->ill_sap_length < 0)
17335 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17336 		else
17337 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17338 			    ill->ill_sap_length;
17339 
17340 		ntme.ipNetToMediaPhysAddress.o_length =
17341 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17342 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17343 		    ntme.ipNetToMediaPhysAddress.o_length);
17344 	}
17345 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17346 	/* assume dynamic (may be changed in arp) */
17347 	ntme.ipNetToMediaType = 3;
17348 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17349 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17350 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17351 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17352 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17353 	    (char *)&ntme, (int)sizeof (ntme))) {
17354 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17355 		    (uint_t)sizeof (ntme)));
17356 	}
17357 }
17358 
17359 /*
17360  * ire_walk routine to create ipv6RouteEntryTable.
17361  */
17362 static void
17363 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17364 {
17365 	ill_t				*ill;
17366 	ipif_t				*ipif;
17367 	mib2_ipv6RouteEntry_t		re;
17368 	in6_addr_t			gw_addr_v6;
17369 
17370 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17371 
17372 	/*
17373 	 * Return all IRE types for route table... let caller pick and choose
17374 	 */
17375 	re.ipv6RouteDest = ire->ire_addr_v6;
17376 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17377 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17378 	re.ipv6RouteIfIndex.o_length = 0;
17379 	ipif = ire->ire_ipif;
17380 	if (ire->ire_type == IRE_CACHE) {
17381 		ill = (ill_t *)ire->ire_stq->q_ptr;
17382 		re.ipv6RouteIfIndex.o_length =
17383 		    ill->ill_name_length == 0 ? 0 :
17384 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17385 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17386 		    re.ipv6RouteIfIndex.o_length);
17387 	} else if (ipif != NULL) {
17388 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17389 		    OCTET_LENGTH);
17390 		re.ipv6RouteIfIndex.o_length =
17391 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17392 	}
17393 
17394 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17395 
17396 	mutex_enter(&ire->ire_lock);
17397 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17398 	mutex_exit(&ire->ire_lock);
17399 
17400 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17401 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17402 	else
17403 		re.ipv6RouteNextHop = gw_addr_v6;
17404 
17405 	/* remote(4), local(3), or discard(2) */
17406 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17407 		re.ipv6RouteType = 2;
17408 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17409 		re.ipv6RouteType = 3;
17410 	else
17411 		re.ipv6RouteType = 4;
17412 
17413 	re.ipv6RouteProtocol		= -1;
17414 	re.ipv6RoutePolicy		= 0;
17415 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17416 	re.ipv6RouteNextHopRDI		= 0;
17417 	re.ipv6RouteWeight		= 0;
17418 	re.ipv6RouteMetric		= 0;
17419 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17420 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17421 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17422 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17423 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17424 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17425 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17426 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17427 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17428 
17429 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17430 	    (char *)&re, (int)sizeof (re))) {
17431 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17432 		    (uint_t)sizeof (re)));
17433 	}
17434 }
17435 
17436 /*
17437  * ndp_walk routine to create ipv6NetToMediaEntryTable
17438  */
17439 static int
17440 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17441 {
17442 	ill_t				*ill;
17443 	mib2_ipv6NetToMediaEntry_t	ntme;
17444 	dl_unitdata_req_t		*dl;
17445 
17446 	ill = nce->nce_ill;
17447 	ASSERT(ill->ill_isv6);
17448 
17449 	/*
17450 	 * Neighbor cache entry attached to IRE with on-link
17451 	 * destination.
17452 	 */
17453 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17454 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17455 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17456 	    (nce->nce_res_mp != NULL)) {
17457 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17458 		ntme.ipv6NetToMediaPhysAddress.o_length =
17459 		    dl->dl_dest_addr_length;
17460 	} else {
17461 		ntme.ipv6NetToMediaPhysAddress.o_length =
17462 		    ill->ill_phys_addr_length;
17463 	}
17464 	if (nce->nce_res_mp != NULL) {
17465 		bcopy((char *)nce->nce_res_mp->b_rptr +
17466 		    NCE_LL_ADDR_OFFSET(ill),
17467 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17468 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17469 	} else {
17470 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17471 		    ill->ill_phys_addr_length);
17472 	}
17473 	/*
17474 	 * Note: Returns ND_* states. Should be:
17475 	 * reachable(1), stale(2), delay(3), probe(4),
17476 	 * invalid(5), unknown(6)
17477 	 */
17478 	ntme.ipv6NetToMediaState = nce->nce_state;
17479 	ntme.ipv6NetToMediaLastUpdated = 0;
17480 
17481 	/* other(1), dynamic(2), static(3), local(4) */
17482 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17483 		ntme.ipv6NetToMediaType = 4;
17484 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17485 		ntme.ipv6NetToMediaType = 1;
17486 	} else {
17487 		ntme.ipv6NetToMediaType = 2;
17488 	}
17489 
17490 	if (!snmp_append_data2(re_ntme->lp_head,
17491 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17492 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17493 		    (uint_t)sizeof (ntme)));
17494 	}
17495 	return (0);
17496 }
17497 
17498 /*
17499  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17500  */
17501 /* ARGSUSED */
17502 int
17503 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17504 {
17505 	switch (level) {
17506 	case MIB2_IP:
17507 	case MIB2_ICMP:
17508 		switch (name) {
17509 		default:
17510 			break;
17511 		}
17512 		return (1);
17513 	default:
17514 		return (1);
17515 	}
17516 }
17517 
17518 /*
17519  * Called before the options are updated to check if this packet will
17520  * be source routed from here.
17521  * This routine assumes that the options are well formed i.e. that they
17522  * have already been checked.
17523  */
17524 static boolean_t
17525 ip_source_routed(ipha_t *ipha)
17526 {
17527 	ipoptp_t	opts;
17528 	uchar_t		*opt;
17529 	uint8_t		optval;
17530 	uint8_t		optlen;
17531 	ipaddr_t	dst;
17532 	ire_t		*ire;
17533 
17534 	if (IS_SIMPLE_IPH(ipha)) {
17535 		ip2dbg(("not source routed\n"));
17536 		return (B_FALSE);
17537 	}
17538 	dst = ipha->ipha_dst;
17539 	for (optval = ipoptp_first(&opts, ipha);
17540 	    optval != IPOPT_EOL;
17541 	    optval = ipoptp_next(&opts)) {
17542 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17543 		opt = opts.ipoptp_cur;
17544 		optlen = opts.ipoptp_len;
17545 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17546 		    optval, optlen));
17547 		switch (optval) {
17548 			uint32_t off;
17549 		case IPOPT_SSRR:
17550 		case IPOPT_LSRR:
17551 			/*
17552 			 * If dst is one of our addresses and there are some
17553 			 * entries left in the source route return (true).
17554 			 */
17555 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17556 			    ALL_ZONES, MATCH_IRE_TYPE);
17557 			if (ire == NULL) {
17558 				ip2dbg(("ip_source_routed: not next"
17559 				    " source route 0x%x\n",
17560 				    ntohl(dst)));
17561 				return (B_FALSE);
17562 			}
17563 			ire_refrele(ire);
17564 			off = opt[IPOPT_OFFSET];
17565 			off--;
17566 			if (optlen < IP_ADDR_LEN ||
17567 			    off > optlen - IP_ADDR_LEN) {
17568 				/* End of source route */
17569 				ip1dbg(("ip_source_routed: end of SR\n"));
17570 				return (B_FALSE);
17571 			}
17572 			return (B_TRUE);
17573 		}
17574 	}
17575 	ip2dbg(("not source routed\n"));
17576 	return (B_FALSE);
17577 }
17578 
17579 /*
17580  * Check if the packet contains any source route.
17581  */
17582 static boolean_t
17583 ip_source_route_included(ipha_t *ipha)
17584 {
17585 	ipoptp_t	opts;
17586 	uint8_t		optval;
17587 
17588 	if (IS_SIMPLE_IPH(ipha))
17589 		return (B_FALSE);
17590 	for (optval = ipoptp_first(&opts, ipha);
17591 	    optval != IPOPT_EOL;
17592 	    optval = ipoptp_next(&opts)) {
17593 		switch (optval) {
17594 		case IPOPT_SSRR:
17595 		case IPOPT_LSRR:
17596 			return (B_TRUE);
17597 		}
17598 	}
17599 	return (B_FALSE);
17600 }
17601 
17602 /*
17603  * Called when the IRE expiration timer fires.
17604  */
17605 /* ARGSUSED */
17606 void
17607 ip_trash_timer_expire(void *args)
17608 {
17609 	int	flush_flag = 0;
17610 
17611 	/*
17612 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17613 	 * This lock makes sure that a new invocation of this function
17614 	 * that occurs due to an almost immediate timer firing will not
17615 	 * progress beyond this point until the current invocation is done
17616 	 */
17617 	mutex_enter(&ip_trash_timer_lock);
17618 	ip_ire_expire_id = 0;
17619 	mutex_exit(&ip_trash_timer_lock);
17620 
17621 	/* Periodic timer */
17622 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17623 		/*
17624 		 * Remove all IRE_CACHE entries since they might
17625 		 * contain arp information.
17626 		 */
17627 		flush_flag |= FLUSH_ARP_TIME;
17628 		ip_ire_arp_time_elapsed = 0;
17629 		IP_STAT(ip_ire_arp_timer_expired);
17630 	}
17631 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17632 		/* Remove all redirects */
17633 		flush_flag |= FLUSH_REDIRECT_TIME;
17634 		ip_ire_rd_time_elapsed = 0;
17635 		IP_STAT(ip_ire_redirect_timer_expired);
17636 	}
17637 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17638 		/* Increase path mtu */
17639 		flush_flag |= FLUSH_MTU_TIME;
17640 		ip_ire_pmtu_time_elapsed = 0;
17641 		IP_STAT(ip_ire_pmtu_timer_expired);
17642 	}
17643 	if (flush_flag != 0) {
17644 		/* Walk all IPv4 IRE's and update them */
17645 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17646 		    ALL_ZONES);
17647 	}
17648 	if (flush_flag & FLUSH_MTU_TIME) {
17649 		/*
17650 		 * Walk all IPv6 IRE's and update them
17651 		 * Note that ARP and redirect timers are not
17652 		 * needed since NUD handles stale entries.
17653 		 */
17654 		flush_flag = FLUSH_MTU_TIME;
17655 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17656 		    ALL_ZONES);
17657 	}
17658 
17659 	ip_ire_arp_time_elapsed += ip_timer_interval;
17660 	ip_ire_rd_time_elapsed += ip_timer_interval;
17661 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17662 
17663 	/*
17664 	 * Hold the lock to serialize timeout calls and prevent
17665 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17666 	 * for the timer to fire and a new invocation of this function
17667 	 * to start before the return value of timeout has been stored
17668 	 * in ip_ire_expire_id by the current invocation.
17669 	 */
17670 	mutex_enter(&ip_trash_timer_lock);
17671 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17672 	    MSEC_TO_TICK(ip_timer_interval));
17673 	mutex_exit(&ip_trash_timer_lock);
17674 }
17675 
17676 /*
17677  * Called by the memory allocator subsystem directly, when the system
17678  * is running low on memory.
17679  */
17680 /* ARGSUSED */
17681 void
17682 ip_trash_ire_reclaim(void *args)
17683 {
17684 	ire_cache_count_t icc;
17685 	ire_cache_reclaim_t icr;
17686 	ncc_cache_count_t ncc;
17687 	nce_cache_reclaim_t ncr;
17688 	uint_t delete_cnt;
17689 	/*
17690 	 * Memory reclaim call back.
17691 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17692 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17693 	 * entries, determine what fraction to free for
17694 	 * each category of IRE_CACHE entries giving absolute priority
17695 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17696 	 * entry will be freed unless all offlink entries are freed).
17697 	 */
17698 	icc.icc_total = 0;
17699 	icc.icc_unused = 0;
17700 	icc.icc_offlink = 0;
17701 	icc.icc_pmtu = 0;
17702 	icc.icc_onlink = 0;
17703 	ire_walk(ire_cache_count, (char *)&icc);
17704 
17705 	/*
17706 	 * Free NCEs for IPv6 like the onlink ires.
17707 	 */
17708 	ncc.ncc_total = 0;
17709 	ncc.ncc_host = 0;
17710 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17711 
17712 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17713 	    icc.icc_pmtu + icc.icc_onlink);
17714 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17715 	IP_STAT(ip_trash_ire_reclaim_calls);
17716 	if (delete_cnt == 0)
17717 		return;
17718 	IP_STAT(ip_trash_ire_reclaim_success);
17719 	/* Always delete all unused offlink entries */
17720 	icr.icr_unused = 1;
17721 	if (delete_cnt <= icc.icc_unused) {
17722 		/*
17723 		 * Only need to free unused entries.  In other words,
17724 		 * there are enough unused entries to free to meet our
17725 		 * target number of freed ire cache entries.
17726 		 */
17727 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17728 		ncr.ncr_host = 0;
17729 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17730 		/*
17731 		 * Only need to free unused entries, plus a fraction of offlink
17732 		 * entries.  It follows from the first if statement that
17733 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17734 		 */
17735 		delete_cnt -= icc.icc_unused;
17736 		/* Round up # deleted by truncating fraction */
17737 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17738 		icr.icr_pmtu = icr.icr_onlink = 0;
17739 		ncr.ncr_host = 0;
17740 	} else if (delete_cnt <=
17741 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17742 		/*
17743 		 * Free all unused and offlink entries, plus a fraction of
17744 		 * pmtu entries.  It follows from the previous if statement
17745 		 * that icc_pmtu is non-zero, and that
17746 		 * delete_cnt != icc_unused + icc_offlink.
17747 		 */
17748 		icr.icr_offlink = 1;
17749 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17750 		/* Round up # deleted by truncating fraction */
17751 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17752 		icr.icr_onlink = 0;
17753 		ncr.ncr_host = 0;
17754 	} else {
17755 		/*
17756 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17757 		 * of onlink entries.  If we're here, then we know that
17758 		 * icc_onlink is non-zero, and that
17759 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17760 		 */
17761 		icr.icr_offlink = icr.icr_pmtu = 1;
17762 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17763 		    icc.icc_pmtu;
17764 		/* Round up # deleted by truncating fraction */
17765 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17766 		/* Using the same delete fraction as for onlink IREs */
17767 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17768 	}
17769 #ifdef DEBUG
17770 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17771 	    "fractions %d/%d/%d/%d\n",
17772 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17773 	    icc.icc_unused, icc.icc_offlink,
17774 	    icc.icc_pmtu, icc.icc_onlink,
17775 	    icr.icr_unused, icr.icr_offlink,
17776 	    icr.icr_pmtu, icr.icr_onlink));
17777 #endif
17778 	ire_walk(ire_cache_reclaim, (char *)&icr);
17779 	if (ncr.ncr_host != 0)
17780 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17781 		    (uchar_t *)&ncr);
17782 #ifdef DEBUG
17783 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17784 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17785 	ire_walk(ire_cache_count, (char *)&icc);
17786 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17787 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17788 	    icc.icc_pmtu, icc.icc_onlink));
17789 #endif
17790 }
17791 
17792 /*
17793  * ip_unbind is called when a copy of an unbind request is received from the
17794  * upper level protocol.  We remove this conn from any fanout hash list it is
17795  * on, and zero out the bind information.  No reply is expected up above.
17796  */
17797 mblk_t *
17798 ip_unbind(queue_t *q, mblk_t *mp)
17799 {
17800 	conn_t	*connp = Q_TO_CONN(q);
17801 
17802 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17803 
17804 	ipcl_hash_remove(connp);
17805 
17806 	ASSERT(mp->b_cont == NULL);
17807 	/*
17808 	 * Convert mp into a T_OK_ACK
17809 	 */
17810 	mp = mi_tpi_ok_ack_alloc(mp);
17811 
17812 	/*
17813 	 * should not happen in practice... T_OK_ACK is smaller than the
17814 	 * original message.
17815 	 */
17816 	if (mp == NULL)
17817 		return (NULL);
17818 
17819 	/*
17820 	 * Don't bzero the ports if its TCP since TCP still needs the
17821 	 * lport to remove it from its own bind hash. TCP will do the
17822 	 * cleanup.
17823 	 */
17824 	if (!IPCL_IS_TCP(connp))
17825 		bzero(&connp->u_port, sizeof (connp->u_port));
17826 
17827 	return (mp);
17828 }
17829 
17830 /*
17831  * Write side put procedure.  Outbound data, IOCTLs, responses from
17832  * resolvers, etc, come down through here.
17833  */
17834 void
17835 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17836 {
17837 	conn_t		*connp = NULL;
17838 	queue_t		*q = (queue_t *)arg2;
17839 	ipha_t		*ipha;
17840 #define	rptr	((uchar_t *)ipha)
17841 	ire_t		*ire = NULL;
17842 	ire_t		*sctp_ire = NULL;
17843 	uint32_t	v_hlen_tos_len;
17844 	ipaddr_t	dst;
17845 	mblk_t		*first_mp = NULL;
17846 	boolean_t	mctl_present;
17847 	ipsec_out_t	*io;
17848 	int		match_flags;
17849 	ill_t		*attach_ill = NULL;
17850 					/* Bind to IPIF_NOFAILOVER ill etc. */
17851 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17852 	ipif_t		*dst_ipif;
17853 	boolean_t	multirt_need_resolve = B_FALSE;
17854 	mblk_t		*copy_mp = NULL;
17855 	int		err;
17856 	zoneid_t	zoneid;
17857 	boolean_t	need_decref = B_FALSE;
17858 	boolean_t	ignore_dontroute = B_FALSE;
17859 	boolean_t	ignore_nexthop = B_FALSE;
17860 	boolean_t	ip_nexthop = B_FALSE;
17861 	ipaddr_t	nexthop_addr;
17862 
17863 #ifdef	_BIG_ENDIAN
17864 #define	V_HLEN	(v_hlen_tos_len >> 24)
17865 #else
17866 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17867 #endif
17868 
17869 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17870 	    "ip_wput_start: q %p", q);
17871 
17872 	/*
17873 	 * ip_wput fast path
17874 	 */
17875 
17876 	/* is packet from ARP ? */
17877 	if (q->q_next != NULL)
17878 		goto qnext;
17879 
17880 	connp = (conn_t *)arg;
17881 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17882 
17883 	/* is queue flow controlled? */
17884 	if ((q->q_first != NULL || connp->conn_draining) &&
17885 	    (caller == IP_WPUT)) {
17886 		ASSERT(!need_decref);
17887 		(void) putq(q, mp);
17888 		return;
17889 	}
17890 
17891 	/* Multidata transmit? */
17892 	if (DB_TYPE(mp) == M_MULTIDATA) {
17893 		/*
17894 		 * We should never get here, since all Multidata messages
17895 		 * originating from tcp should have been directed over to
17896 		 * tcp_multisend() in the first place.
17897 		 */
17898 		BUMP_MIB(&ip_mib, ipOutDiscards);
17899 		freemsg(mp);
17900 		return;
17901 	} else if (DB_TYPE(mp) != M_DATA)
17902 		goto notdata;
17903 	if (mp->b_flag & MSGHASREF) {
17904 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17905 		mp->b_flag &= ~MSGHASREF;
17906 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17907 		need_decref = B_TRUE;
17908 	}
17909 	ipha = (ipha_t *)mp->b_rptr;
17910 
17911 	/* is IP header non-aligned or mblk smaller than basic IP header */
17912 #ifndef SAFETY_BEFORE_SPEED
17913 	if (!OK_32PTR(rptr) ||
17914 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17915 		goto hdrtoosmall;
17916 #endif
17917 
17918 	/*
17919 	 * If there is a policy, try to attach an ipsec_out in
17920 	 * the front. At the end, first_mp either points to a
17921 	 * M_DATA message or IPSEC_OUT message linked to a
17922 	 * M_DATA message. We have to do it now as we might
17923 	 * lose the "conn" if we go through ip_newroute.
17924 	 */
17925 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17926 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17927 		    ipha->ipha_protocol)) == NULL)) {
17928 			if (need_decref)
17929 				CONN_DEC_REF(connp);
17930 			return;
17931 		} else {
17932 			ASSERT(mp->b_datap->db_type == M_CTL);
17933 			first_mp = mp;
17934 			mp = mp->b_cont;
17935 			mctl_present = B_TRUE;
17936 		}
17937 	} else {
17938 		first_mp = mp;
17939 		mctl_present = B_FALSE;
17940 	}
17941 
17942 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17943 
17944 	/* is wrong version or IP options present */
17945 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17946 		goto version_hdrlen_check;
17947 	dst = ipha->ipha_dst;
17948 
17949 	if (connp->conn_nofailover_ill != NULL) {
17950 		attach_ill = conn_get_held_ill(connp,
17951 		    &connp->conn_nofailover_ill, &err);
17952 		if (err == ILL_LOOKUP_FAILED) {
17953 			if (need_decref)
17954 				CONN_DEC_REF(connp);
17955 			freemsg(first_mp);
17956 			return;
17957 		}
17958 	}
17959 
17960 	/* is packet multicast? */
17961 	if (CLASSD(dst))
17962 		goto multicast;
17963 
17964 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
17965 	    (connp->conn_nexthop_set)) {
17966 		/*
17967 		 * If the destination is a broadcast or a loopback
17968 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
17969 		 * through the standard path. But in the case of local
17970 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
17971 		 * the standard path not IP_XMIT_IF.
17972 		 */
17973 		ire = ire_cache_lookup(dst, zoneid);
17974 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17975 		    (ire->ire_type != IRE_LOOPBACK))) {
17976 			if ((connp->conn_dontroute ||
17977 			    connp->conn_nexthop_set) && (ire != NULL) &&
17978 			    (ire->ire_type == IRE_LOCAL))
17979 				goto standard_path;
17980 
17981 			if (ire != NULL) {
17982 				ire_refrele(ire);
17983 				/* No more access to ire */
17984 				ire = NULL;
17985 			}
17986 			/*
17987 			 * bypass routing checks and go directly to
17988 			 * interface.
17989 			 */
17990 			if (connp->conn_dontroute) {
17991 				goto dontroute;
17992 			} else if (connp->conn_nexthop_set) {
17993 				ip_nexthop = B_TRUE;
17994 				nexthop_addr = connp->conn_nexthop_v4;
17995 				goto send_from_ill;
17996 			}
17997 
17998 			/*
17999 			 * If IP_XMIT_IF socket option is set,
18000 			 * then we allow unicast and multicast
18001 			 * packets to go through the ill. It is
18002 			 * quite possible that the destination
18003 			 * is not in the ire cache table and we
18004 			 * do not want to go to ip_newroute()
18005 			 * instead we call ip_newroute_ipif.
18006 			 */
18007 			xmit_ill = conn_get_held_ill(connp,
18008 			    &connp->conn_xmit_if_ill, &err);
18009 			if (err == ILL_LOOKUP_FAILED) {
18010 				if (attach_ill != NULL)
18011 					ill_refrele(attach_ill);
18012 				if (need_decref)
18013 					CONN_DEC_REF(connp);
18014 				freemsg(first_mp);
18015 				return;
18016 			}
18017 			goto send_from_ill;
18018 		}
18019 standard_path:
18020 		/* Must be a broadcast, a loopback or a local ire */
18021 		if (ire != NULL) {
18022 			ire_refrele(ire);
18023 			/* No more access to ire */
18024 			ire = NULL;
18025 		}
18026 	}
18027 
18028 	if (attach_ill != NULL)
18029 		goto send_from_ill;
18030 
18031 	/*
18032 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18033 	 * this for the tcp global queue and listen end point
18034 	 * as it does not really have a real destination to
18035 	 * talk to.  This is also true for SCTP.
18036 	 */
18037 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18038 	    !connp->conn_fully_bound) {
18039 		ire = ire_cache_lookup(dst, zoneid);
18040 		if (ire == NULL)
18041 			goto noirefound;
18042 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18043 		    "ip_wput_end: q %p (%S)", q, "end");
18044 
18045 		/*
18046 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18047 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18048 		 */
18049 		if (ire->ire_flags & RTF_MULTIRT) {
18050 
18051 			/*
18052 			 * Force the TTL of multirouted packets if required.
18053 			 * The TTL of such packets is bounded by the
18054 			 * ip_multirt_ttl ndd variable.
18055 			 */
18056 			if ((ip_multirt_ttl > 0) &&
18057 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18058 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18059 				    "(was %d), dst 0x%08x\n",
18060 				    ip_multirt_ttl, ipha->ipha_ttl,
18061 				    ntohl(ire->ire_addr)));
18062 				ipha->ipha_ttl = ip_multirt_ttl;
18063 			}
18064 			/*
18065 			 * We look at this point if there are pending
18066 			 * unresolved routes. ire_multirt_resolvable()
18067 			 * checks in O(n) that all IRE_OFFSUBNET ire
18068 			 * entries for the packet's destination and
18069 			 * flagged RTF_MULTIRT are currently resolved.
18070 			 * If some remain unresolved, we make a copy
18071 			 * of the current message. It will be used
18072 			 * to initiate additional route resolutions.
18073 			 */
18074 			multirt_need_resolve =
18075 			    ire_multirt_need_resolve(ire->ire_addr);
18076 			ip2dbg(("ip_wput[TCP]: ire %p, "
18077 			    "multirt_need_resolve %d, first_mp %p\n",
18078 			    (void *)ire, multirt_need_resolve,
18079 			    (void *)first_mp));
18080 			if (multirt_need_resolve) {
18081 				copy_mp = copymsg(first_mp);
18082 				if (copy_mp != NULL) {
18083 					MULTIRT_DEBUG_TAG(copy_mp);
18084 				}
18085 			}
18086 		}
18087 
18088 		ip_wput_ire(q, first_mp, ire, connp, caller);
18089 
18090 		/*
18091 		 * Try to resolve another multiroute if
18092 		 * ire_multirt_need_resolve() deemed it necessary.
18093 		 */
18094 		if (copy_mp != NULL) {
18095 			ip_newroute(q, copy_mp, dst, NULL, connp);
18096 		}
18097 		if (need_decref)
18098 			CONN_DEC_REF(connp);
18099 		return;
18100 	}
18101 
18102 	/*
18103 	 * Access to conn_ire_cache. (protected by conn_lock)
18104 	 *
18105 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18106 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18107 	 * send a packet or two with the IRE_CACHE that is going away.
18108 	 * Access to the ire requires an ire refhold on the ire prior to
18109 	 * its use since an interface unplumb thread may delete the cached
18110 	 * ire and release the refhold at any time.
18111 	 *
18112 	 * Caching an ire in the conn_ire_cache
18113 	 *
18114 	 * o Caching an ire pointer in the conn requires a strict check for
18115 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18116 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18117 	 * in the conn is done after making sure under the bucket lock that the
18118 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18119 	 * caching an ire after the unplumb thread has cleaned up the conn.
18120 	 * If the conn does not send a packet subsequently the unplumb thread
18121 	 * will be hanging waiting for the ire count to drop to zero.
18122 	 *
18123 	 * o We also need to atomically test for a null conn_ire_cache and
18124 	 * set the conn_ire_cache under the the protection of the conn_lock
18125 	 * to avoid races among concurrent threads trying to simultaneously
18126 	 * cache an ire in the conn_ire_cache.
18127 	 */
18128 	mutex_enter(&connp->conn_lock);
18129 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18130 
18131 	if (ire != NULL && ire->ire_addr == dst &&
18132 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18133 
18134 		IRE_REFHOLD(ire);
18135 		mutex_exit(&connp->conn_lock);
18136 
18137 	} else {
18138 		boolean_t cached = B_FALSE;
18139 		connp->conn_ire_cache = NULL;
18140 		mutex_exit(&connp->conn_lock);
18141 		/* Release the old ire */
18142 		if (ire != NULL && sctp_ire == NULL)
18143 			IRE_REFRELE_NOTR(ire);
18144 
18145 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
18146 		if (ire == NULL)
18147 			goto noirefound;
18148 		IRE_REFHOLD_NOTR(ire);
18149 
18150 		mutex_enter(&connp->conn_lock);
18151 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18152 		    connp->conn_ire_cache == NULL) {
18153 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18154 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18155 				connp->conn_ire_cache = ire;
18156 				cached = B_TRUE;
18157 			}
18158 			rw_exit(&ire->ire_bucket->irb_lock);
18159 		}
18160 		mutex_exit(&connp->conn_lock);
18161 
18162 		/*
18163 		 * We can continue to use the ire but since it was
18164 		 * not cached, we should drop the extra reference.
18165 		 */
18166 		if (!cached)
18167 			IRE_REFRELE_NOTR(ire);
18168 	}
18169 
18170 
18171 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18172 	    "ip_wput_end: q %p (%S)", q, "end");
18173 
18174 	/*
18175 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18176 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18177 	 */
18178 	if (ire->ire_flags & RTF_MULTIRT) {
18179 
18180 		/*
18181 		 * Force the TTL of multirouted packets if required.
18182 		 * The TTL of such packets is bounded by the
18183 		 * ip_multirt_ttl ndd variable.
18184 		 */
18185 		if ((ip_multirt_ttl > 0) &&
18186 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18187 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18188 			    "(was %d), dst 0x%08x\n",
18189 			    ip_multirt_ttl, ipha->ipha_ttl,
18190 			    ntohl(ire->ire_addr)));
18191 			ipha->ipha_ttl = ip_multirt_ttl;
18192 		}
18193 
18194 		/*
18195 		 * At this point, we check to see if there are any pending
18196 		 * unresolved routes. ire_multirt_resolvable()
18197 		 * checks in O(n) that all IRE_OFFSUBNET ire
18198 		 * entries for the packet's destination and
18199 		 * flagged RTF_MULTIRT are currently resolved.
18200 		 * If some remain unresolved, we make a copy
18201 		 * of the current message. It will be used
18202 		 * to initiate additional route resolutions.
18203 		 */
18204 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18205 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18206 		    "multirt_need_resolve %d, first_mp %p\n",
18207 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18208 		if (multirt_need_resolve) {
18209 			copy_mp = copymsg(first_mp);
18210 			if (copy_mp != NULL) {
18211 				MULTIRT_DEBUG_TAG(copy_mp);
18212 			}
18213 		}
18214 	}
18215 
18216 	ip_wput_ire(q, first_mp, ire, connp, caller);
18217 
18218 	/*
18219 	 * Try to resolve another multiroute if
18220 	 * ire_multirt_resolvable() deemed it necessary
18221 	 */
18222 	if (copy_mp != NULL) {
18223 		ip_newroute(q, copy_mp, dst, NULL, connp);
18224 	}
18225 	if (need_decref)
18226 		CONN_DEC_REF(connp);
18227 	return;
18228 
18229 qnext:
18230 	/*
18231 	 * Upper Level Protocols pass down complete IP datagrams
18232 	 * as M_DATA messages.	Everything else is a sideshow.
18233 	 *
18234 	 * 1) We could be re-entering ip_wput because of ip_neworute
18235 	 *    in which case we could have a IPSEC_OUT message. We
18236 	 *    need to pass through ip_wput like other datagrams and
18237 	 *    hence cannot branch to ip_wput_nondata.
18238 	 *
18239 	 * 2) ARP, AH, ESP, and other clients who are on the module
18240 	 *    instance of IP stream, give us something to deal with.
18241 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18242 	 *
18243 	 * 3) ICMP replies also could come here.
18244 	 */
18245 	if (DB_TYPE(mp) != M_DATA) {
18246 	    notdata:
18247 		if (DB_TYPE(mp) == M_CTL) {
18248 			/*
18249 			 * M_CTL messages are used by ARP, AH and ESP to
18250 			 * communicate with IP. We deal with IPSEC_IN and
18251 			 * IPSEC_OUT here. ip_wput_nondata handles other
18252 			 * cases.
18253 			 */
18254 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18255 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18256 				first_mp = mp->b_cont;
18257 				first_mp->b_flag &= ~MSGHASREF;
18258 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18259 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18260 				CONN_DEC_REF(connp);
18261 				connp = NULL;
18262 			}
18263 			if (ii->ipsec_info_type == IPSEC_IN) {
18264 				/*
18265 				 * Either this message goes back to
18266 				 * IPSEC for further processing or to
18267 				 * ULP after policy checks.
18268 				 */
18269 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18270 				return;
18271 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18272 				io = (ipsec_out_t *)ii;
18273 				if (io->ipsec_out_proc_begin) {
18274 					/*
18275 					 * IPSEC processing has already started.
18276 					 * Complete it.
18277 					 * IPQoS notes: We don't care what is
18278 					 * in ipsec_out_ill_index since this
18279 					 * won't be processed for IPQoS policies
18280 					 * in ipsec_out_process.
18281 					 */
18282 					ipsec_out_process(q, mp, NULL,
18283 					    io->ipsec_out_ill_index);
18284 					return;
18285 				} else {
18286 					connp = (q->q_next != NULL) ?
18287 					    NULL : Q_TO_CONN(q);
18288 					first_mp = mp;
18289 					mp = mp->b_cont;
18290 					mctl_present = B_TRUE;
18291 				}
18292 				zoneid = io->ipsec_out_zoneid;
18293 				ASSERT(zoneid != ALL_ZONES);
18294 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18295 				/*
18296 				 * It's an IPsec control message requesting
18297 				 * an SADB update to be sent to the IPsec
18298 				 * hardware acceleration capable ills.
18299 				 */
18300 				ipsec_ctl_t *ipsec_ctl =
18301 				    (ipsec_ctl_t *)mp->b_rptr;
18302 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18303 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18304 				mblk_t *cmp = mp->b_cont;
18305 
18306 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18307 				ASSERT(cmp != NULL);
18308 
18309 				freeb(mp);
18310 				ill_ipsec_capab_send_all(satype, cmp, sa);
18311 				return;
18312 			} else {
18313 				/*
18314 				 * This must be ARP.
18315 				 */
18316 				ip_wput_nondata(NULL, q, mp, NULL);
18317 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18318 				    "ip_wput_end: q %p (%S)", q, "nondata");
18319 				return;
18320 			}
18321 		} else {
18322 			/*
18323 			 * This must be non-(ARP/AH/ESP) messages.
18324 			 */
18325 			ASSERT(!need_decref);
18326 			ip_wput_nondata(NULL, q, mp, NULL);
18327 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18328 			    "ip_wput_end: q %p (%S)", q, "nondata");
18329 			return;
18330 		}
18331 	} else {
18332 		first_mp = mp;
18333 		mctl_present = B_FALSE;
18334 	}
18335 
18336 	ASSERT(first_mp != NULL);
18337 	/*
18338 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18339 	 * to make sure that this packet goes out on the same interface it
18340 	 * came in. We handle that here.
18341 	 */
18342 	if (mctl_present) {
18343 		uint_t ifindex;
18344 
18345 		io = (ipsec_out_t *)first_mp->b_rptr;
18346 		if (io->ipsec_out_attach_if ||
18347 		    io->ipsec_out_xmit_if ||
18348 		    io->ipsec_out_ip_nexthop) {
18349 			ill_t	*ill;
18350 
18351 			/*
18352 			 * We may have lost the conn context if we are
18353 			 * coming here from ip_newroute(). Copy the
18354 			 * nexthop information.
18355 			 */
18356 			if (io->ipsec_out_ip_nexthop) {
18357 				ip_nexthop = B_TRUE;
18358 				nexthop_addr = io->ipsec_out_nexthop_addr;
18359 
18360 				ipha = (ipha_t *)mp->b_rptr;
18361 				dst = ipha->ipha_dst;
18362 				goto send_from_ill;
18363 			} else {
18364 				ASSERT(io->ipsec_out_ill_index != 0);
18365 				ifindex = io->ipsec_out_ill_index;
18366 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18367 				    NULL, NULL, NULL, NULL);
18368 				/*
18369 				 * ipsec_out_xmit_if bit is used to tell
18370 				 * ip_wput to use the ill to send outgoing data
18371 				 * as we have no conn when data comes from ICMP
18372 				 * error msg routines. Currently this feature is
18373 				 * only used by ip_mrtun_forward routine.
18374 				 */
18375 				if (io->ipsec_out_xmit_if) {
18376 					xmit_ill = ill;
18377 					if (xmit_ill == NULL) {
18378 						ip1dbg(("ip_output:bad ifindex "
18379 						    "for xmit_ill %d\n",
18380 						    ifindex));
18381 						freemsg(first_mp);
18382 						BUMP_MIB(&ip_mib,
18383 						    ipOutDiscards);
18384 						ASSERT(!need_decref);
18385 						return;
18386 					}
18387 					/* Free up the ipsec_out_t mblk */
18388 					ASSERT(first_mp->b_cont == mp);
18389 					first_mp->b_cont = NULL;
18390 					freeb(first_mp);
18391 					/* Just send the IP header+ICMP+data */
18392 					first_mp = mp;
18393 					ipha = (ipha_t *)mp->b_rptr;
18394 					dst = ipha->ipha_dst;
18395 					goto send_from_ill;
18396 				} else {
18397 					attach_ill = ill;
18398 				}
18399 
18400 				if (attach_ill == NULL) {
18401 					ASSERT(xmit_ill == NULL);
18402 					ip1dbg(("ip_output: bad ifindex for "
18403 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
18404 					    ifindex));
18405 					freemsg(first_mp);
18406 					BUMP_MIB(&ip_mib, ipOutDiscards);
18407 					ASSERT(!need_decref);
18408 					return;
18409 				}
18410 			}
18411 		}
18412 	}
18413 
18414 	ASSERT(xmit_ill == NULL);
18415 
18416 	/* We have a complete IP datagram heading outbound. */
18417 	ipha = (ipha_t *)mp->b_rptr;
18418 
18419 #ifndef SPEED_BEFORE_SAFETY
18420 	/*
18421 	 * Make sure we have a full-word aligned message and that at least
18422 	 * a simple IP header is accessible in the first message.  If not,
18423 	 * try a pullup.
18424 	 */
18425 	if (!OK_32PTR(rptr) ||
18426 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18427 	    hdrtoosmall:
18428 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18429 			BUMP_MIB(&ip_mib, ipOutDiscards);
18430 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18431 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18432 			if (first_mp == NULL)
18433 				first_mp = mp;
18434 			goto drop_pkt;
18435 		}
18436 		ipha = (ipha_t *)mp->b_rptr;
18437 		if (first_mp == NULL) {
18438 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18439 			/*
18440 			 * If we got here because of "goto hdrtoosmall"
18441 			 * We need to attach a IPSEC_OUT.
18442 			 */
18443 			if (connp->conn_out_enforce_policy) {
18444 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18445 				    NULL, ipha->ipha_protocol)) == NULL)) {
18446 					if (need_decref)
18447 						CONN_DEC_REF(connp);
18448 					return;
18449 				} else {
18450 					ASSERT(mp->b_datap->db_type == M_CTL);
18451 					first_mp = mp;
18452 					mp = mp->b_cont;
18453 					mctl_present = B_TRUE;
18454 				}
18455 			} else {
18456 				first_mp = mp;
18457 				mctl_present = B_FALSE;
18458 			}
18459 		}
18460 	}
18461 #endif
18462 
18463 	/* Most of the code below is written for speed, not readability */
18464 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18465 
18466 	/*
18467 	 * If ip_newroute() fails, we're going to need a full
18468 	 * header for the icmp wraparound.
18469 	 */
18470 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18471 		uint_t	v_hlen;
18472 	    version_hdrlen_check:
18473 		ASSERT(first_mp != NULL);
18474 		v_hlen = V_HLEN;
18475 		/*
18476 		 * siphon off IPv6 packets coming down from transport
18477 		 * layer modules here.
18478 		 * Note: high-order bit carries NUD reachability confirmation
18479 		 */
18480 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18481 			/*
18482 			 * XXX implement a IPv4 and IPv6 packet counter per
18483 			 * conn and switch when ratio exceeds e.g. 10:1
18484 			 */
18485 #ifdef notyet
18486 			if (q->q_next == NULL) /* Avoid ill queue */
18487 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18488 #endif
18489 			BUMP_MIB(&ip_mib, ipOutIPv6);
18490 			ASSERT(xmit_ill == NULL);
18491 			if (attach_ill != NULL)
18492 				ill_refrele(attach_ill);
18493 			if (need_decref)
18494 				mp->b_flag |= MSGHASREF;
18495 			(void) ip_output_v6(connp, first_mp, q, caller);
18496 			return;
18497 		}
18498 
18499 		if ((v_hlen >> 4) != IP_VERSION) {
18500 			BUMP_MIB(&ip_mib, ipOutDiscards);
18501 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18502 			    "ip_wput_end: q %p (%S)", q, "badvers");
18503 			goto drop_pkt;
18504 		}
18505 		/*
18506 		 * Is the header length at least 20 bytes?
18507 		 *
18508 		 * Are there enough bytes accessible in the header?  If
18509 		 * not, try a pullup.
18510 		 */
18511 		v_hlen &= 0xF;
18512 		v_hlen <<= 2;
18513 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18514 			BUMP_MIB(&ip_mib, ipOutDiscards);
18515 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18516 			    "ip_wput_end: q %p (%S)", q, "badlen");
18517 			goto drop_pkt;
18518 		}
18519 		if (v_hlen > (mp->b_wptr - rptr)) {
18520 			if (!pullupmsg(mp, v_hlen)) {
18521 				BUMP_MIB(&ip_mib, ipOutDiscards);
18522 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18523 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18524 				goto drop_pkt;
18525 			}
18526 			ipha = (ipha_t *)mp->b_rptr;
18527 		}
18528 		/*
18529 		 * Move first entry from any source route into ipha_dst and
18530 		 * verify the options
18531 		 */
18532 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18533 			ASSERT(xmit_ill == NULL);
18534 			if (attach_ill != NULL)
18535 				ill_refrele(attach_ill);
18536 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18537 			    "ip_wput_end: q %p (%S)", q, "badopts");
18538 			if (need_decref)
18539 				CONN_DEC_REF(connp);
18540 			return;
18541 		}
18542 	}
18543 	dst = ipha->ipha_dst;
18544 
18545 	/*
18546 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18547 	 * we have to run the packet through ip_newroute which will take
18548 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18549 	 * a resolver, or assigning a default gateway, etc.
18550 	 */
18551 	if (CLASSD(dst)) {
18552 		ipif_t	*ipif;
18553 		uint32_t setsrc = 0;
18554 
18555 	    multicast:
18556 		ASSERT(first_mp != NULL);
18557 		ASSERT(xmit_ill == NULL);
18558 		ip2dbg(("ip_wput: CLASSD\n"));
18559 		if (connp == NULL) {
18560 			/*
18561 			 * Use the first good ipif on the ill.
18562 			 * XXX Should this ever happen? (Appears
18563 			 * to show up with just ppp and no ethernet due
18564 			 * to in.rdisc.)
18565 			 * However, ire_send should be able to
18566 			 * call ip_wput_ire directly.
18567 			 *
18568 			 * XXX Also, this can happen for ICMP and other packets
18569 			 * with multicast source addresses.  Perhaps we should
18570 			 * fix things so that we drop the packet in question,
18571 			 * but for now, just run with it.
18572 			 */
18573 			ill_t *ill = (ill_t *)q->q_ptr;
18574 
18575 			/*
18576 			 * Don't honor attach_if for this case. If ill
18577 			 * is part of the group, ipif could belong to
18578 			 * any ill and we cannot maintain attach_ill
18579 			 * and ipif_ill same anymore and the assert
18580 			 * below would fail.
18581 			 */
18582 			if (mctl_present) {
18583 				io->ipsec_out_ill_index = 0;
18584 				io->ipsec_out_attach_if = B_FALSE;
18585 				ASSERT(attach_ill != NULL);
18586 				ill_refrele(attach_ill);
18587 				attach_ill = NULL;
18588 			}
18589 
18590 			ASSERT(attach_ill == NULL);
18591 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18592 			if (ipif == NULL) {
18593 				if (need_decref)
18594 					CONN_DEC_REF(connp);
18595 				freemsg(first_mp);
18596 				return;
18597 			}
18598 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18599 			    ntohl(dst), ill->ill_name));
18600 		} else {
18601 			/*
18602 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18603 			 * IP_XMIT_IF is honoured.
18604 			 * Block comment above this function explains the
18605 			 * locking mechanism used here
18606 			 */
18607 			xmit_ill = conn_get_held_ill(connp,
18608 			    &connp->conn_xmit_if_ill, &err);
18609 			if (err == ILL_LOOKUP_FAILED) {
18610 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18611 				goto drop_pkt;
18612 			}
18613 			if (xmit_ill == NULL) {
18614 				ipif = conn_get_held_ipif(connp,
18615 				    &connp->conn_multicast_ipif, &err);
18616 				if (err == IPIF_LOOKUP_FAILED) {
18617 					ip1dbg(("ip_wput: No ipif for "
18618 					    "multicast\n"));
18619 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18620 					goto drop_pkt;
18621 				}
18622 			}
18623 			if (xmit_ill != NULL) {
18624 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18625 				if (ipif == NULL) {
18626 					ip1dbg(("ip_wput: No ipif for "
18627 					    "IP_XMIT_IF\n"));
18628 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18629 					goto drop_pkt;
18630 				}
18631 			} else if (ipif == NULL || ipif->ipif_isv6) {
18632 				/*
18633 				 * We must do this ipif determination here
18634 				 * else we could pass through ip_newroute
18635 				 * and come back here without the conn context.
18636 				 *
18637 				 * Note: we do late binding i.e. we bind to
18638 				 * the interface when the first packet is sent.
18639 				 * For performance reasons we do not rebind on
18640 				 * each packet but keep the binding until the
18641 				 * next IP_MULTICAST_IF option.
18642 				 *
18643 				 * conn_multicast_{ipif,ill} are shared between
18644 				 * IPv4 and IPv6 and AF_INET6 sockets can
18645 				 * send both IPv4 and IPv6 packets. Hence
18646 				 * we have to check that "isv6" matches above.
18647 				 */
18648 				if (ipif != NULL)
18649 					ipif_refrele(ipif);
18650 				ipif = ipif_lookup_group(dst, zoneid);
18651 				if (ipif == NULL) {
18652 					ip1dbg(("ip_wput: No ipif for "
18653 					    "multicast\n"));
18654 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18655 					goto drop_pkt;
18656 				}
18657 				err = conn_set_held_ipif(connp,
18658 				    &connp->conn_multicast_ipif, ipif);
18659 				if (err == IPIF_LOOKUP_FAILED) {
18660 					ipif_refrele(ipif);
18661 					ip1dbg(("ip_wput: No ipif for "
18662 					    "multicast\n"));
18663 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18664 					goto drop_pkt;
18665 				}
18666 			}
18667 		}
18668 		ASSERT(!ipif->ipif_isv6);
18669 		/*
18670 		 * As we may lose the conn by the time we reach ip_wput_ire,
18671 		 * we copy conn_multicast_loop and conn_dontroute on to an
18672 		 * ipsec_out. In case if this datagram goes out secure,
18673 		 * we need the ill_index also. Copy that also into the
18674 		 * ipsec_out.
18675 		 */
18676 		if (mctl_present) {
18677 			io = (ipsec_out_t *)first_mp->b_rptr;
18678 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18679 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18680 		} else {
18681 			ASSERT(mp == first_mp);
18682 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18683 			    BPRI_HI)) == NULL) {
18684 				ipif_refrele(ipif);
18685 				first_mp = mp;
18686 				goto drop_pkt;
18687 			}
18688 			first_mp->b_datap->db_type = M_CTL;
18689 			first_mp->b_wptr += sizeof (ipsec_info_t);
18690 			/* ipsec_out_secure is B_FALSE now */
18691 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18692 			io = (ipsec_out_t *)first_mp->b_rptr;
18693 			io->ipsec_out_type = IPSEC_OUT;
18694 			io->ipsec_out_len = sizeof (ipsec_out_t);
18695 			io->ipsec_out_use_global_policy = B_TRUE;
18696 			first_mp->b_cont = mp;
18697 			mctl_present = B_TRUE;
18698 		}
18699 		if (attach_ill != NULL) {
18700 			ASSERT(attach_ill == ipif->ipif_ill);
18701 			match_flags = MATCH_IRE_ILL;
18702 
18703 			/*
18704 			 * Check if we need an ire that will not be
18705 			 * looked up by anybody else i.e. HIDDEN.
18706 			 */
18707 			if (ill_is_probeonly(attach_ill)) {
18708 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18709 			}
18710 			io->ipsec_out_ill_index =
18711 			    attach_ill->ill_phyint->phyint_ifindex;
18712 			io->ipsec_out_attach_if = B_TRUE;
18713 		} else {
18714 			match_flags = MATCH_IRE_ILL_GROUP;
18715 			io->ipsec_out_ill_index =
18716 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18717 		}
18718 		if (connp != NULL) {
18719 			io->ipsec_out_multicast_loop =
18720 			    connp->conn_multicast_loop;
18721 			io->ipsec_out_dontroute = connp->conn_dontroute;
18722 			io->ipsec_out_zoneid = connp->conn_zoneid;
18723 		}
18724 		/*
18725 		 * If the application uses IP_MULTICAST_IF with
18726 		 * different logical addresses of the same ILL, we
18727 		 * need to make sure that the soruce address of
18728 		 * the packet matches the logical IP address used
18729 		 * in the option. We do it by initializing ipha_src
18730 		 * here. This should keep IPSEC also happy as
18731 		 * when we return from IPSEC processing, we don't
18732 		 * have to worry about getting the right address on
18733 		 * the packet. Thus it is sufficient to look for
18734 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18735 		 * MATCH_IRE_IPIF.
18736 		 *
18737 		 * NOTE : We need to do it for non-secure case also as
18738 		 * this might go out secure if there is a global policy
18739 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18740 		 * address, the source should be initialized already and
18741 		 * hence we won't be initializing here.
18742 		 *
18743 		 * As we do not have the ire yet, it is possible that
18744 		 * we set the source address here and then later discover
18745 		 * that the ire implies the source address to be assigned
18746 		 * through the RTF_SETSRC flag.
18747 		 * In that case, the setsrc variable will remind us
18748 		 * that overwritting the source address by the one
18749 		 * of the RTF_SETSRC-flagged ire is allowed.
18750 		 */
18751 		if (ipha->ipha_src == INADDR_ANY &&
18752 		    (connp == NULL || !connp->conn_unspec_src)) {
18753 			ipha->ipha_src = ipif->ipif_src_addr;
18754 			setsrc = RTF_SETSRC;
18755 		}
18756 		/*
18757 		 * Find an IRE which matches the destination and the outgoing
18758 		 * queue (i.e. the outgoing interface.)
18759 		 * For loopback use a unicast IP address for
18760 		 * the ire lookup.
18761 		 */
18762 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18763 		    PHYI_LOOPBACK) {
18764 			dst = ipif->ipif_lcl_addr;
18765 		}
18766 		/*
18767 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18768 		 * We don't need to lookup ire in ctable as the packet
18769 		 * needs to be sent to the destination through the specified
18770 		 * ill irrespective of ires in the cache table.
18771 		 */
18772 		ire = NULL;
18773 		if (xmit_ill == NULL) {
18774 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18775 			    zoneid, match_flags);
18776 		}
18777 
18778 		/*
18779 		 * refrele attach_ill as its not needed anymore.
18780 		 */
18781 		if (attach_ill != NULL) {
18782 			ill_refrele(attach_ill);
18783 			attach_ill = NULL;
18784 		}
18785 
18786 		if (ire == NULL) {
18787 			/*
18788 			 * Multicast loopback and multicast forwarding is
18789 			 * done in ip_wput_ire.
18790 			 *
18791 			 * Mark this packet to make it be delivered to
18792 			 * ip_wput_ire after the new ire has been
18793 			 * created.
18794 			 *
18795 			 * The call to ip_newroute_ipif takes into account
18796 			 * the setsrc reminder. In any case, we take care
18797 			 * of the RTF_MULTIRT flag.
18798 			 */
18799 			mp->b_prev = mp->b_next = NULL;
18800 			if (xmit_ill == NULL ||
18801 			    xmit_ill->ill_ipif_up_count > 0) {
18802 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18803 				    setsrc | RTF_MULTIRT);
18804 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18805 				    "ip_wput_end: q %p (%S)", q, "noire");
18806 			} else {
18807 				freemsg(first_mp);
18808 			}
18809 			ipif_refrele(ipif);
18810 			if (xmit_ill != NULL)
18811 				ill_refrele(xmit_ill);
18812 			if (need_decref)
18813 				CONN_DEC_REF(connp);
18814 			return;
18815 		}
18816 
18817 		ipif_refrele(ipif);
18818 		ipif = NULL;
18819 		ASSERT(xmit_ill == NULL);
18820 
18821 		/*
18822 		 * Honor the RTF_SETSRC flag for multicast packets,
18823 		 * if allowed by the setsrc reminder.
18824 		 */
18825 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18826 			ipha->ipha_src = ire->ire_src_addr;
18827 		}
18828 
18829 		/*
18830 		 * Unconditionally force the TTL to 1 for
18831 		 * multirouted multicast packets:
18832 		 * multirouted multicast should not cross
18833 		 * multicast routers.
18834 		 */
18835 		if (ire->ire_flags & RTF_MULTIRT) {
18836 			if (ipha->ipha_ttl > 1) {
18837 				ip2dbg(("ip_wput: forcing multicast "
18838 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18839 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18840 				ipha->ipha_ttl = 1;
18841 			}
18842 		}
18843 	} else {
18844 		ire = ire_cache_lookup(dst, zoneid);
18845 		if ((ire != NULL) && (ire->ire_type &
18846 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18847 			ignore_dontroute = B_TRUE;
18848 			ignore_nexthop = B_TRUE;
18849 		}
18850 		if (ire != NULL) {
18851 			ire_refrele(ire);
18852 			ire = NULL;
18853 		}
18854 		/*
18855 		 * Guard against coming in from arp in which case conn is NULL.
18856 		 * Also guard against non M_DATA with dontroute set but
18857 		 * destined to local, loopback or broadcast addresses.
18858 		 */
18859 		if (connp != NULL && connp->conn_dontroute &&
18860 		    !ignore_dontroute) {
18861 dontroute:
18862 			/*
18863 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18864 			 * routing protocols from seeing false direct
18865 			 * connectivity.
18866 			 */
18867 			ipha->ipha_ttl = 1;
18868 			/*
18869 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18870 			 * along with SO_DONTROUTE, higher precedence is
18871 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18872 			 */
18873 			if (connp->conn_xmit_if_ill == NULL) {
18874 				/* If suitable ipif not found, drop packet */
18875 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18876 				if (dst_ipif == NULL) {
18877 					ip1dbg(("ip_wput: no route for "
18878 					    "dst using SO_DONTROUTE\n"));
18879 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18880 					mp->b_prev = mp->b_next = NULL;
18881 					if (first_mp == NULL)
18882 						first_mp = mp;
18883 					goto drop_pkt;
18884 				} else {
18885 					/*
18886 					 * If suitable ipif has been found, set
18887 					 * xmit_ill to the corresponding
18888 					 * ipif_ill because we'll be following
18889 					 * the IP_XMIT_IF logic.
18890 					 */
18891 					ASSERT(xmit_ill == NULL);
18892 					xmit_ill = dst_ipif->ipif_ill;
18893 					mutex_enter(&xmit_ill->ill_lock);
18894 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18895 						mutex_exit(&xmit_ill->ill_lock);
18896 						xmit_ill = NULL;
18897 						ipif_refrele(dst_ipif);
18898 						ip1dbg(("ip_wput: no route for"
18899 						    " dst using"
18900 						    " SO_DONTROUTE\n"));
18901 						BUMP_MIB(&ip_mib,
18902 						    ipOutNoRoutes);
18903 						mp->b_prev = mp->b_next = NULL;
18904 						if (first_mp == NULL)
18905 							first_mp = mp;
18906 						goto drop_pkt;
18907 					}
18908 					ill_refhold_locked(xmit_ill);
18909 					mutex_exit(&xmit_ill->ill_lock);
18910 					ipif_refrele(dst_ipif);
18911 				}
18912 			}
18913 
18914 		}
18915 		/*
18916 		 * If we are bound to IPIF_NOFAILOVER address, look for
18917 		 * an IRE_CACHE matching the ill.
18918 		 */
18919 send_from_ill:
18920 		if (attach_ill != NULL) {
18921 			ipif_t	*attach_ipif;
18922 
18923 			match_flags = MATCH_IRE_ILL;
18924 
18925 			/*
18926 			 * Check if we need an ire that will not be
18927 			 * looked up by anybody else i.e. HIDDEN.
18928 			 */
18929 			if (ill_is_probeonly(attach_ill)) {
18930 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18931 			}
18932 
18933 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18934 			if (attach_ipif == NULL) {
18935 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18936 				goto drop_pkt;
18937 			}
18938 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18939 			    zoneid, match_flags);
18940 			ipif_refrele(attach_ipif);
18941 		} else if (xmit_ill != NULL || (connp != NULL &&
18942 			    connp->conn_xmit_if_ill != NULL)) {
18943 			/*
18944 			 * Mark this packet as originated locally
18945 			 */
18946 			mp->b_prev = mp->b_next = NULL;
18947 			/*
18948 			 * xmit_ill could be NULL if SO_DONTROUTE
18949 			 * is also set.
18950 			 */
18951 			if (xmit_ill == NULL) {
18952 				xmit_ill = conn_get_held_ill(connp,
18953 				    &connp->conn_xmit_if_ill, &err);
18954 				if (err == ILL_LOOKUP_FAILED) {
18955 					if (need_decref)
18956 						CONN_DEC_REF(connp);
18957 					freemsg(first_mp);
18958 					return;
18959 				}
18960 				if (xmit_ill == NULL) {
18961 					if (connp->conn_dontroute)
18962 						goto dontroute;
18963 					goto send_from_ill;
18964 				}
18965 			}
18966 			/*
18967 			 * could be SO_DONTROUTE case also.
18968 			 * check at least one interface is UP as
18969 			 * spcified by this ILL, and then call
18970 			 * ip_newroute_ipif()
18971 			 */
18972 			if (xmit_ill->ill_ipif_up_count > 0) {
18973 				ipif_t *ipif;
18974 
18975 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18976 				if (ipif != NULL) {
18977 					ip_newroute_ipif(q, first_mp, ipif,
18978 					    dst, connp, 0);
18979 					ipif_refrele(ipif);
18980 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18981 				}
18982 			} else {
18983 				freemsg(first_mp);
18984 			}
18985 			ill_refrele(xmit_ill);
18986 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18987 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18988 			if (need_decref)
18989 				CONN_DEC_REF(connp);
18990 			return;
18991 		} else if (ip_nexthop || (connp != NULL &&
18992 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
18993 			if (!ip_nexthop) {
18994 				ip_nexthop = B_TRUE;
18995 				nexthop_addr = connp->conn_nexthop_v4;
18996 			}
18997 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
18998 			    MATCH_IRE_GW;
18999 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19000 			    NULL, zoneid, match_flags);
19001 		} else {
19002 			ire = ire_cache_lookup(dst, zoneid);
19003 		}
19004 		if (!ire) {
19005 			/*
19006 			 * Make sure we don't load spread if this
19007 			 * is IPIF_NOFAILOVER case.
19008 			 */
19009 			if ((attach_ill != NULL) ||
19010 			    (ip_nexthop && !ignore_nexthop)) {
19011 				if (mctl_present) {
19012 					io = (ipsec_out_t *)first_mp->b_rptr;
19013 					ASSERT(first_mp->b_datap->db_type ==
19014 					    M_CTL);
19015 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19016 				} else {
19017 					ASSERT(mp == first_mp);
19018 					first_mp = allocb(
19019 					    sizeof (ipsec_info_t), BPRI_HI);
19020 					if (first_mp == NULL) {
19021 						first_mp = mp;
19022 						goto drop_pkt;
19023 					}
19024 					first_mp->b_datap->db_type = M_CTL;
19025 					first_mp->b_wptr +=
19026 					    sizeof (ipsec_info_t);
19027 					/* ipsec_out_secure is B_FALSE now */
19028 					bzero(first_mp->b_rptr,
19029 					    sizeof (ipsec_info_t));
19030 					io = (ipsec_out_t *)first_mp->b_rptr;
19031 					io->ipsec_out_type = IPSEC_OUT;
19032 					io->ipsec_out_len =
19033 					    sizeof (ipsec_out_t);
19034 					io->ipsec_out_use_global_policy =
19035 					    B_TRUE;
19036 					first_mp->b_cont = mp;
19037 					mctl_present = B_TRUE;
19038 				}
19039 				if (attach_ill != NULL) {
19040 					io->ipsec_out_ill_index = attach_ill->
19041 					    ill_phyint->phyint_ifindex;
19042 					io->ipsec_out_attach_if = B_TRUE;
19043 				} else {
19044 					io->ipsec_out_ip_nexthop = ip_nexthop;
19045 					io->ipsec_out_nexthop_addr =
19046 					    nexthop_addr;
19047 				}
19048 			}
19049 noirefound:
19050 			/*
19051 			 * Mark this packet as having originated on
19052 			 * this machine.  This will be noted in
19053 			 * ire_add_then_send, which needs to know
19054 			 * whether to run it back through ip_wput or
19055 			 * ip_rput following successful resolution.
19056 			 */
19057 			mp->b_prev = NULL;
19058 			mp->b_next = NULL;
19059 			ip_newroute(q, first_mp, dst, NULL, connp);
19060 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19061 			    "ip_wput_end: q %p (%S)", q, "newroute");
19062 			if (attach_ill != NULL)
19063 				ill_refrele(attach_ill);
19064 			if (xmit_ill != NULL)
19065 				ill_refrele(xmit_ill);
19066 			if (need_decref)
19067 				CONN_DEC_REF(connp);
19068 			return;
19069 		}
19070 	}
19071 
19072 	/* We now know where we are going with it. */
19073 
19074 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19075 	    "ip_wput_end: q %p (%S)", q, "end");
19076 
19077 	/*
19078 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19079 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19080 	 */
19081 	if (ire->ire_flags & RTF_MULTIRT) {
19082 		/*
19083 		 * Force the TTL of multirouted packets if required.
19084 		 * The TTL of such packets is bounded by the
19085 		 * ip_multirt_ttl ndd variable.
19086 		 */
19087 		if ((ip_multirt_ttl > 0) &&
19088 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19089 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19090 			    "(was %d), dst 0x%08x\n",
19091 			    ip_multirt_ttl, ipha->ipha_ttl,
19092 			    ntohl(ire->ire_addr)));
19093 			ipha->ipha_ttl = ip_multirt_ttl;
19094 		}
19095 		/*
19096 		 * At this point, we check to see if there are any pending
19097 		 * unresolved routes. ire_multirt_resolvable()
19098 		 * checks in O(n) that all IRE_OFFSUBNET ire
19099 		 * entries for the packet's destination and
19100 		 * flagged RTF_MULTIRT are currently resolved.
19101 		 * If some remain unresolved, we make a copy
19102 		 * of the current message. It will be used
19103 		 * to initiate additional route resolutions.
19104 		 */
19105 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
19106 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19107 		    "multirt_need_resolve %d, first_mp %p\n",
19108 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19109 		if (multirt_need_resolve) {
19110 			copy_mp = copymsg(first_mp);
19111 			if (copy_mp != NULL) {
19112 				MULTIRT_DEBUG_TAG(copy_mp);
19113 			}
19114 		}
19115 	}
19116 
19117 	ip_wput_ire(q, first_mp, ire, connp, caller);
19118 	/*
19119 	 * Try to resolve another multiroute if
19120 	 * ire_multirt_resolvable() deemed it necessary.
19121 	 * At this point, we need to distinguish
19122 	 * multicasts from other packets. For multicasts,
19123 	 * we call ip_newroute_ipif() and request that both
19124 	 * multirouting and setsrc flags are checked.
19125 	 */
19126 	if (copy_mp != NULL) {
19127 		if (CLASSD(dst)) {
19128 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19129 			if (ipif) {
19130 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19131 				    RTF_SETSRC | RTF_MULTIRT);
19132 				ipif_refrele(ipif);
19133 			} else {
19134 				MULTIRT_DEBUG_UNTAG(copy_mp);
19135 				freemsg(copy_mp);
19136 				copy_mp = NULL;
19137 			}
19138 		} else {
19139 			ip_newroute(q, copy_mp, dst, NULL, connp);
19140 		}
19141 	}
19142 	if (attach_ill != NULL)
19143 		ill_refrele(attach_ill);
19144 	if (xmit_ill != NULL)
19145 		ill_refrele(xmit_ill);
19146 	if (need_decref)
19147 		CONN_DEC_REF(connp);
19148 	return;
19149 
19150 drop_pkt:
19151 	ip1dbg(("ip_wput: dropped packet\n"));
19152 	if (ire != NULL)
19153 		ire_refrele(ire);
19154 	if (need_decref)
19155 		CONN_DEC_REF(connp);
19156 	freemsg(first_mp);
19157 	if (attach_ill != NULL)
19158 		ill_refrele(attach_ill);
19159 	if (xmit_ill != NULL)
19160 		ill_refrele(xmit_ill);
19161 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19162 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19163 }
19164 
19165 void
19166 ip_wput(queue_t *q, mblk_t *mp)
19167 {
19168 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19169 }
19170 
19171 /*
19172  *
19173  * The following rules must be observed when accessing any ipif or ill
19174  * that has been cached in the conn. Typically conn_nofailover_ill,
19175  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19176  *
19177  * Access: The ipif or ill pointed to from the conn can be accessed under
19178  * the protection of the conn_lock or after it has been refheld under the
19179  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19180  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19181  * The reason for this is that a concurrent unplumb could actually be
19182  * cleaning up these cached pointers by walking the conns and might have
19183  * finished cleaning up the conn in question. The macros check that an
19184  * unplumb has not yet started on the ipif or ill.
19185  *
19186  * Caching: An ipif or ill pointer may be cached in the conn only after
19187  * making sure that an unplumb has not started. So the caching is done
19188  * while holding both the conn_lock and the ill_lock and after using the
19189  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
19190  * flag before starting the cleanup of conns.
19191  *
19192  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
19193  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
19194  * or a reference to the ipif or a reference to an ire that references the
19195  * ipif. An ipif does not change its ill except for failover/failback. Since
19196  * failover/failback happens only after bringing down the ipif and making sure
19197  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
19198  * the above holds.
19199  */
19200 ipif_t *
19201 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
19202 {
19203 	ipif_t	*ipif;
19204 	ill_t	*ill;
19205 
19206 	*err = 0;
19207 	rw_enter(&ill_g_lock, RW_READER);
19208 	mutex_enter(&connp->conn_lock);
19209 	ipif = *ipifp;
19210 	if (ipif != NULL) {
19211 		ill = ipif->ipif_ill;
19212 		mutex_enter(&ill->ill_lock);
19213 		if (IPIF_CAN_LOOKUP(ipif)) {
19214 			ipif_refhold_locked(ipif);
19215 			mutex_exit(&ill->ill_lock);
19216 			mutex_exit(&connp->conn_lock);
19217 			rw_exit(&ill_g_lock);
19218 			return (ipif);
19219 		} else {
19220 			*err = IPIF_LOOKUP_FAILED;
19221 		}
19222 		mutex_exit(&ill->ill_lock);
19223 	}
19224 	mutex_exit(&connp->conn_lock);
19225 	rw_exit(&ill_g_lock);
19226 	return (NULL);
19227 }
19228 
19229 ill_t *
19230 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
19231 {
19232 	ill_t	*ill;
19233 
19234 	*err = 0;
19235 	mutex_enter(&connp->conn_lock);
19236 	ill = *illp;
19237 	if (ill != NULL) {
19238 		mutex_enter(&ill->ill_lock);
19239 		if (ILL_CAN_LOOKUP(ill)) {
19240 			ill_refhold_locked(ill);
19241 			mutex_exit(&ill->ill_lock);
19242 			mutex_exit(&connp->conn_lock);
19243 			return (ill);
19244 		} else {
19245 			*err = ILL_LOOKUP_FAILED;
19246 		}
19247 		mutex_exit(&ill->ill_lock);
19248 	}
19249 	mutex_exit(&connp->conn_lock);
19250 	return (NULL);
19251 }
19252 
19253 static int
19254 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
19255 {
19256 	ill_t	*ill;
19257 
19258 	ill = ipif->ipif_ill;
19259 	mutex_enter(&connp->conn_lock);
19260 	mutex_enter(&ill->ill_lock);
19261 	if (IPIF_CAN_LOOKUP(ipif)) {
19262 		*ipifp = ipif;
19263 		mutex_exit(&ill->ill_lock);
19264 		mutex_exit(&connp->conn_lock);
19265 		return (0);
19266 	}
19267 	mutex_exit(&ill->ill_lock);
19268 	mutex_exit(&connp->conn_lock);
19269 	return (IPIF_LOOKUP_FAILED);
19270 }
19271 
19272 /*
19273  * This is called if the outbound datagram needs fragmentation.
19274  *
19275  * NOTE : This function does not ire_refrele the ire argument passed in.
19276  */
19277 static void
19278 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19279 {
19280 	ipha_t		*ipha;
19281 	mblk_t		*mp;
19282 	uint32_t	v_hlen_tos_len;
19283 	uint32_t	max_frag;
19284 	uint32_t	frag_flag;
19285 	boolean_t	dont_use;
19286 
19287 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19288 		mp = ipsec_mp->b_cont;
19289 	} else {
19290 		mp = ipsec_mp;
19291 	}
19292 
19293 	ipha = (ipha_t *)mp->b_rptr;
19294 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19295 
19296 #ifdef	_BIG_ENDIAN
19297 #define	V_HLEN	(v_hlen_tos_len >> 24)
19298 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19299 #else
19300 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19301 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19302 #endif
19303 
19304 #ifndef SPEED_BEFORE_SAFETY
19305 	/*
19306 	 * Check that ipha_length is consistent with
19307 	 * the mblk length
19308 	 */
19309 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19310 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19311 		    LENGTH, msgdsize(mp)));
19312 		freemsg(ipsec_mp);
19313 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19314 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19315 		    "packet length mismatch");
19316 		return;
19317 	}
19318 #endif
19319 	/*
19320 	 * Don't use frag_flag if pre-built packet or source
19321 	 * routed or if multicast (since multicast packets do not solicit
19322 	 * ICMP "packet too big" messages). Get the values of
19323 	 * max_frag and frag_flag atomically by acquiring the
19324 	 * ire_lock.
19325 	 */
19326 	mutex_enter(&ire->ire_lock);
19327 	max_frag = ire->ire_max_frag;
19328 	frag_flag = ire->ire_frag_flag;
19329 	mutex_exit(&ire->ire_lock);
19330 
19331 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19332 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19333 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19334 
19335 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19336 	    (dont_use ? 0 : frag_flag));
19337 }
19338 
19339 /*
19340  * Used for deciding the MSS size for the upper layer. Thus
19341  * we need to check the outbound policy values in the conn.
19342  */
19343 int
19344 conn_ipsec_length(conn_t *connp)
19345 {
19346 	ipsec_latch_t *ipl;
19347 
19348 	ipl = connp->conn_latch;
19349 	if (ipl == NULL)
19350 		return (0);
19351 
19352 	if (ipl->ipl_out_policy == NULL)
19353 		return (0);
19354 
19355 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19356 }
19357 
19358 /*
19359  * Returns an estimate of the IPSEC headers size. This is used if
19360  * we don't want to call into IPSEC to get the exact size.
19361  */
19362 int
19363 ipsec_out_extra_length(mblk_t *ipsec_mp)
19364 {
19365 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19366 	ipsec_action_t *a;
19367 
19368 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19369 	if (!io->ipsec_out_secure)
19370 		return (0);
19371 
19372 	a = io->ipsec_out_act;
19373 
19374 	if (a == NULL) {
19375 		ASSERT(io->ipsec_out_policy != NULL);
19376 		a = io->ipsec_out_policy->ipsp_act;
19377 	}
19378 	ASSERT(a != NULL);
19379 
19380 	return (a->ipa_ovhd);
19381 }
19382 
19383 /*
19384  * Returns an estimate of the IPSEC headers size. This is used if
19385  * we don't want to call into IPSEC to get the exact size.
19386  */
19387 int
19388 ipsec_in_extra_length(mblk_t *ipsec_mp)
19389 {
19390 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19391 	ipsec_action_t *a;
19392 
19393 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19394 
19395 	a = ii->ipsec_in_action;
19396 	return (a == NULL ? 0 : a->ipa_ovhd);
19397 }
19398 
19399 /*
19400  * If there are any source route options, return the true final
19401  * destination. Otherwise, return the destination.
19402  */
19403 ipaddr_t
19404 ip_get_dst(ipha_t *ipha)
19405 {
19406 	ipoptp_t	opts;
19407 	uchar_t		*opt;
19408 	uint8_t		optval;
19409 	uint8_t		optlen;
19410 	ipaddr_t	dst;
19411 	uint32_t off;
19412 
19413 	dst = ipha->ipha_dst;
19414 
19415 	if (IS_SIMPLE_IPH(ipha))
19416 		return (dst);
19417 
19418 	for (optval = ipoptp_first(&opts, ipha);
19419 	    optval != IPOPT_EOL;
19420 	    optval = ipoptp_next(&opts)) {
19421 		opt = opts.ipoptp_cur;
19422 		optlen = opts.ipoptp_len;
19423 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19424 		switch (optval) {
19425 		case IPOPT_SSRR:
19426 		case IPOPT_LSRR:
19427 			off = opt[IPOPT_OFFSET];
19428 			/*
19429 			 * If one of the conditions is true, it means
19430 			 * end of options and dst already has the right
19431 			 * value.
19432 			 */
19433 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19434 				off = optlen - IP_ADDR_LEN;
19435 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19436 			}
19437 			return (dst);
19438 		default:
19439 			break;
19440 		}
19441 	}
19442 
19443 	return (dst);
19444 }
19445 
19446 mblk_t *
19447 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19448     conn_t *connp, boolean_t unspec_src)
19449 {
19450 	ipsec_out_t	*io;
19451 	mblk_t		*first_mp;
19452 	boolean_t policy_present;
19453 
19454 	first_mp = mp;
19455 	if (mp->b_datap->db_type == M_CTL) {
19456 		io = (ipsec_out_t *)first_mp->b_rptr;
19457 		/*
19458 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19459 		 *
19460 		 * 1) There is per-socket policy (including cached global
19461 		 *    policy).
19462 		 * 2) There is no per-socket policy, but it is
19463 		 *    a multicast packet that needs to go out
19464 		 *    on a specific interface. This is the case
19465 		 *    where (ip_wput and ip_wput_multicast) attaches
19466 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19467 		 *
19468 		 * In case (2) we check with global policy to
19469 		 * see if there is a match and set the ill_index
19470 		 * appropriately so that we can lookup the ire
19471 		 * properly in ip_wput_ipsec_out.
19472 		 */
19473 
19474 		/*
19475 		 * ipsec_out_use_global_policy is set to B_FALSE
19476 		 * in ipsec_in_to_out(). Refer to that function for
19477 		 * details.
19478 		 */
19479 		if ((io->ipsec_out_latch == NULL) &&
19480 		    (io->ipsec_out_use_global_policy)) {
19481 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19482 			    ire, connp, unspec_src));
19483 		}
19484 		if (!io->ipsec_out_secure) {
19485 			/*
19486 			 * If this is not a secure packet, drop
19487 			 * the IPSEC_OUT mp and treat it as a clear
19488 			 * packet. This happens when we are sending
19489 			 * a ICMP reply back to a clear packet. See
19490 			 * ipsec_in_to_out() for details.
19491 			 */
19492 			mp = first_mp->b_cont;
19493 			freeb(first_mp);
19494 		}
19495 		return (mp);
19496 	}
19497 	/*
19498 	 * See whether we need to attach a global policy here. We
19499 	 * don't depend on the conn (as it could be null) for deciding
19500 	 * what policy this datagram should go through because it
19501 	 * should have happened in ip_wput if there was some
19502 	 * policy. This normally happens for connections which are not
19503 	 * fully bound preventing us from caching policies in
19504 	 * ip_bind. Packets coming from the TCP listener/global queue
19505 	 * - which are non-hard_bound - could also be affected by
19506 	 * applying policy here.
19507 	 *
19508 	 * If this packet is coming from tcp global queue or listener,
19509 	 * we will be applying policy here.  This may not be *right*
19510 	 * if these packets are coming from the detached connection as
19511 	 * it could have gone in clear before. This happens only if a
19512 	 * TCP connection started when there is no policy and somebody
19513 	 * added policy before it became detached. Thus packets of the
19514 	 * detached connection could go out secure and the other end
19515 	 * would drop it because it will be expecting in clear. The
19516 	 * converse is not true i.e if somebody starts a TCP
19517 	 * connection and deletes the policy, all the packets will
19518 	 * still go out with the policy that existed before deleting
19519 	 * because ip_unbind sends up policy information which is used
19520 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19521 	 * TCP to attach a dummy IPSEC_OUT and set
19522 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19523 	 * affect performance for normal cases, we are not doing it.
19524 	 * Thus, set policy before starting any TCP connections.
19525 	 *
19526 	 * NOTE - We might apply policy even for a hard bound connection
19527 	 * - for which we cached policy in ip_bind - if somebody added
19528 	 * global policy after we inherited the policy in ip_bind.
19529 	 * This means that the packets that were going out in clear
19530 	 * previously would start going secure and hence get dropped
19531 	 * on the other side. To fix this, TCP attaches a dummy
19532 	 * ipsec_out and make sure that we don't apply global policy.
19533 	 */
19534 	if (ipha != NULL)
19535 		policy_present = ipsec_outbound_v4_policy_present;
19536 	else
19537 		policy_present = ipsec_outbound_v6_policy_present;
19538 	if (!policy_present)
19539 		return (mp);
19540 
19541 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19542 }
19543 
19544 ire_t *
19545 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19546 {
19547 	ipaddr_t addr;
19548 	ire_t *save_ire;
19549 	irb_t *irb;
19550 	ill_group_t *illgrp;
19551 	int	err;
19552 
19553 	save_ire = ire;
19554 	addr = ire->ire_addr;
19555 
19556 	ASSERT(ire->ire_type == IRE_BROADCAST);
19557 
19558 	illgrp = connp->conn_outgoing_ill->ill_group;
19559 	if (illgrp == NULL) {
19560 		*conn_outgoing_ill = conn_get_held_ill(connp,
19561 		    &connp->conn_outgoing_ill, &err);
19562 		if (err == ILL_LOOKUP_FAILED) {
19563 			ire_refrele(save_ire);
19564 			return (NULL);
19565 		}
19566 		return (save_ire);
19567 	}
19568 	/*
19569 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19570 	 * If it is part of the group, we need to send on the ire
19571 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19572 	 * to this group. This is okay as IP_BOUND_IF really means
19573 	 * any ill in the group. We depend on the fact that the
19574 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19575 	 * if such an ire exists. This is possible only if you have
19576 	 * at least one ill in the group that has not failed.
19577 	 *
19578 	 * First get to the ire that matches the address and group.
19579 	 *
19580 	 * We don't look for an ire with a matching zoneid because a given zone
19581 	 * won't always have broadcast ires on all ills in the group.
19582 	 */
19583 	irb = ire->ire_bucket;
19584 	rw_enter(&irb->irb_lock, RW_READER);
19585 	if (ire->ire_marks & IRE_MARK_NORECV) {
19586 		/*
19587 		 * If the current zone only has an ire broadcast for this
19588 		 * address marked NORECV, the ire we want is ahead in the
19589 		 * bucket, so we look it up deliberately ignoring the zoneid.
19590 		 */
19591 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19592 			if (ire->ire_addr != addr)
19593 				continue;
19594 			/* skip over deleted ires */
19595 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19596 				continue;
19597 		}
19598 	}
19599 	while (ire != NULL) {
19600 		/*
19601 		 * If a new interface is coming up, we could end up
19602 		 * seeing the loopback ire and the non-loopback ire
19603 		 * may not have been added yet. So check for ire_stq
19604 		 */
19605 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19606 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19607 			break;
19608 		}
19609 		ire = ire->ire_next;
19610 	}
19611 	if (ire != NULL && ire->ire_addr == addr &&
19612 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19613 		IRE_REFHOLD(ire);
19614 		rw_exit(&irb->irb_lock);
19615 		ire_refrele(save_ire);
19616 		*conn_outgoing_ill = ire_to_ill(ire);
19617 		/*
19618 		 * Refhold the ill to make the conn_outgoing_ill
19619 		 * independent of the ire. ip_wput_ire goes in a loop
19620 		 * and may refrele the ire. Since we have an ire at this
19621 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19622 		 */
19623 		ill_refhold(*conn_outgoing_ill);
19624 		return (ire);
19625 	}
19626 	rw_exit(&irb->irb_lock);
19627 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19628 	/*
19629 	 * If we can't find a suitable ire, return the original ire.
19630 	 */
19631 	return (save_ire);
19632 }
19633 
19634 /*
19635  * This function does the ire_refrele of the ire passed in as the
19636  * argument. As this function looks up more ires i.e broadcast ires,
19637  * it needs to REFRELE them. Currently, for simplicity we don't
19638  * differentiate the one passed in and looked up here. We always
19639  * REFRELE.
19640  * IPQoS Notes:
19641  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19642  * IPSec packets are done in ipsec_out_process.
19643  *
19644  */
19645 void
19646 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19647 {
19648 	ipha_t		*ipha;
19649 #define	rptr	((uchar_t *)ipha)
19650 	mblk_t		*mp1;
19651 	queue_t		*stq;
19652 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19653 	uint32_t	v_hlen_tos_len;
19654 	uint32_t	ttl_protocol;
19655 	ipaddr_t	src;
19656 	ipaddr_t	dst;
19657 	uint32_t	cksum;
19658 	ipaddr_t	orig_src;
19659 	ire_t		*ire1;
19660 	mblk_t		*next_mp;
19661 	uint_t		hlen;
19662 	uint16_t	*up;
19663 	uint32_t	max_frag = ire->ire_max_frag;
19664 	ill_t		*ill = ire_to_ill(ire);
19665 	int		clusterwide;
19666 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19667 	int		ipsec_len;
19668 	mblk_t		*first_mp;
19669 	ipsec_out_t	*io;
19670 	boolean_t	conn_dontroute;		/* conn value for multicast */
19671 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19672 	boolean_t	multicast_forward;	/* Should we forward ? */
19673 	boolean_t	unspec_src;
19674 	ill_t		*conn_outgoing_ill = NULL;
19675 	ill_t		*ire_ill;
19676 	ill_t		*ire1_ill;
19677 	uint32_t 	ill_index = 0;
19678 	boolean_t	multirt_send = B_FALSE;
19679 	int		err;
19680 	zoneid_t	zoneid;
19681 
19682 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19683 	    "ip_wput_ire_start: q %p", q);
19684 
19685 	multicast_forward = B_FALSE;
19686 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19687 
19688 	if (ire->ire_flags & RTF_MULTIRT) {
19689 		/*
19690 		 * Multirouting case. The bucket where ire is stored
19691 		 * probably holds other RTF_MULTIRT flagged ire
19692 		 * to the destination. In this call to ip_wput_ire,
19693 		 * we attempt to send the packet through all
19694 		 * those ires. Thus, we first ensure that ire is the
19695 		 * first RTF_MULTIRT ire in the bucket,
19696 		 * before walking the ire list.
19697 		 */
19698 		ire_t *first_ire;
19699 		irb_t *irb = ire->ire_bucket;
19700 		ASSERT(irb != NULL);
19701 
19702 		/* Make sure we do not omit any multiroute ire. */
19703 		IRB_REFHOLD(irb);
19704 		for (first_ire = irb->irb_ire;
19705 		    first_ire != NULL;
19706 		    first_ire = first_ire->ire_next) {
19707 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19708 			    (first_ire->ire_addr == ire->ire_addr) &&
19709 			    !(first_ire->ire_marks &
19710 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19711 				break;
19712 		}
19713 
19714 		if ((first_ire != NULL) && (first_ire != ire)) {
19715 			IRE_REFHOLD(first_ire);
19716 			ire_refrele(ire);
19717 			ire = first_ire;
19718 			ill = ire_to_ill(ire);
19719 		}
19720 		IRB_REFRELE(irb);
19721 	}
19722 
19723 	/*
19724 	 * conn_outgoing_ill is used only in the broadcast loop.
19725 	 * for performance we don't grab the mutexs in the fastpath
19726 	 */
19727 	if ((connp != NULL) &&
19728 	    (connp->conn_xmit_if_ill == NULL) &&
19729 	    (ire->ire_type == IRE_BROADCAST) &&
19730 	    ((connp->conn_nofailover_ill != NULL) ||
19731 	    (connp->conn_outgoing_ill != NULL))) {
19732 		/*
19733 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19734 		 * option. So, see if this endpoint is bound to a
19735 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19736 		 * that if the interface is failed, we will still send
19737 		 * the packet on the same ill which is what we want.
19738 		 */
19739 		conn_outgoing_ill = conn_get_held_ill(connp,
19740 		    &connp->conn_nofailover_ill, &err);
19741 		if (err == ILL_LOOKUP_FAILED) {
19742 			ire_refrele(ire);
19743 			freemsg(mp);
19744 			return;
19745 		}
19746 		if (conn_outgoing_ill == NULL) {
19747 			/*
19748 			 * Choose a good ill in the group to send the
19749 			 * packets on.
19750 			 */
19751 			ire = conn_set_outgoing_ill(connp, ire,
19752 			    &conn_outgoing_ill);
19753 			if (ire == NULL) {
19754 				freemsg(mp);
19755 				return;
19756 			}
19757 		}
19758 	}
19759 
19760 	if (mp->b_datap->db_type != M_CTL) {
19761 		ipha = (ipha_t *)mp->b_rptr;
19762 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19763 	} else {
19764 		io = (ipsec_out_t *)mp->b_rptr;
19765 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19766 		zoneid = io->ipsec_out_zoneid;
19767 		ASSERT(zoneid != ALL_ZONES);
19768 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19769 		dst = ipha->ipha_dst;
19770 		/*
19771 		 * For the multicast case, ipsec_out carries conn_dontroute and
19772 		 * conn_multicast_loop as conn may not be available here. We
19773 		 * need this for multicast loopback and forwarding which is done
19774 		 * later in the code.
19775 		 */
19776 		if (CLASSD(dst)) {
19777 			conn_dontroute = io->ipsec_out_dontroute;
19778 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19779 			/*
19780 			 * If conn_dontroute is not set or conn_multicast_loop
19781 			 * is set, we need to do forwarding/loopback. For
19782 			 * datagrams from ip_wput_multicast, conn_dontroute is
19783 			 * set to B_TRUE and conn_multicast_loop is set to
19784 			 * B_FALSE so that we neither do forwarding nor
19785 			 * loopback.
19786 			 */
19787 			if (!conn_dontroute || conn_multicast_loop)
19788 				multicast_forward = B_TRUE;
19789 		}
19790 	}
19791 
19792 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19793 		/*
19794 		 * When a zone sends a packet to another zone, we try to deliver
19795 		 * the packet under the same conditions as if the destination
19796 		 * was a real node on the network. To do so, we look for a
19797 		 * matching route in the forwarding table.
19798 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19799 		 * ip_newroute() does.
19800 		 */
19801 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19802 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19803 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19804 		if (src_ire != NULL &&
19805 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19806 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19807 				ipha->ipha_src = src_ire->ire_src_addr;
19808 			ire_refrele(src_ire);
19809 		} else {
19810 			ire_refrele(ire);
19811 			if (conn_outgoing_ill != NULL)
19812 				ill_refrele(conn_outgoing_ill);
19813 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19814 			if (src_ire != NULL) {
19815 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19816 					ire_refrele(src_ire);
19817 					freemsg(mp);
19818 					return;
19819 				}
19820 				ire_refrele(src_ire);
19821 			}
19822 			if (ip_hdr_complete(ipha, zoneid)) {
19823 				/* Failed */
19824 				freemsg(mp);
19825 				return;
19826 			}
19827 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19828 			return;
19829 		}
19830 	}
19831 
19832 	if (mp->b_datap->db_type == M_CTL ||
19833 	    ipsec_outbound_v4_policy_present) {
19834 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19835 		    unspec_src);
19836 		if (mp == NULL) {
19837 			ire_refrele(ire);
19838 			if (conn_outgoing_ill != NULL)
19839 				ill_refrele(conn_outgoing_ill);
19840 			return;
19841 		}
19842 	}
19843 
19844 	first_mp = mp;
19845 	ipsec_len = 0;
19846 
19847 	if (first_mp->b_datap->db_type == M_CTL) {
19848 		io = (ipsec_out_t *)first_mp->b_rptr;
19849 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19850 		mp = first_mp->b_cont;
19851 		ipsec_len = ipsec_out_extra_length(first_mp);
19852 		ASSERT(ipsec_len >= 0);
19853 		zoneid = io->ipsec_out_zoneid;
19854 		ASSERT(zoneid != ALL_ZONES);
19855 
19856 		/*
19857 		 * Drop M_CTL here if IPsec processing is not needed.
19858 		 * (Non-IPsec use of M_CTL extracted any information it
19859 		 * needed above).
19860 		 */
19861 		if (ipsec_len == 0) {
19862 			freeb(first_mp);
19863 			first_mp = mp;
19864 		}
19865 	}
19866 
19867 	/*
19868 	 * Fast path for ip_wput_ire
19869 	 */
19870 
19871 	ipha = (ipha_t *)mp->b_rptr;
19872 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19873 	dst = ipha->ipha_dst;
19874 
19875 	/*
19876 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19877 	 * if the socket is a SOCK_RAW type. The transport checksum should
19878 	 * be provided in the pre-built packet, so we don't need to compute it.
19879 	 * Also, other application set flags, like DF, should not be altered.
19880 	 * Other transport MUST pass down zero.
19881 	 */
19882 	ip_hdr_included = ipha->ipha_ident;
19883 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19884 
19885 	if (CLASSD(dst)) {
19886 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19887 		    ntohl(dst),
19888 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19889 		    ntohl(ire->ire_addr)));
19890 	}
19891 
19892 /* Macros to extract header fields from data already in registers */
19893 #ifdef	_BIG_ENDIAN
19894 #define	V_HLEN	(v_hlen_tos_len >> 24)
19895 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19896 #define	PROTO	(ttl_protocol & 0xFF)
19897 #else
19898 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19899 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19900 #define	PROTO	(ttl_protocol >> 8)
19901 #endif
19902 
19903 
19904 	orig_src = src = ipha->ipha_src;
19905 	/* (The loop back to "another" is explained down below.) */
19906 another:;
19907 	/*
19908 	 * Assign an ident value for this packet.  We assign idents on
19909 	 * a per destination basis out of the IRE.  There could be
19910 	 * other threads targeting the same destination, so we have to
19911 	 * arrange for a atomic increment.  Note that we use a 32-bit
19912 	 * atomic add because it has better performance than its
19913 	 * 16-bit sibling.
19914 	 *
19915 	 * If running in cluster mode and if the source address
19916 	 * belongs to a replicated service then vector through
19917 	 * cl_inet_ipident vector to allocate ip identifier
19918 	 * NOTE: This is a contract private interface with the
19919 	 * clustering group.
19920 	 */
19921 	clusterwide = 0;
19922 	if (cl_inet_ipident) {
19923 		ASSERT(cl_inet_isclusterwide);
19924 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19925 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19926 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19927 			    AF_INET, (uint8_t *)(uintptr_t)src,
19928 			    (uint8_t *)(uintptr_t)dst);
19929 			clusterwide = 1;
19930 		}
19931 	}
19932 	if (!clusterwide) {
19933 		ipha->ipha_ident =
19934 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19935 	}
19936 
19937 #ifndef _BIG_ENDIAN
19938 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19939 #endif
19940 
19941 	/*
19942 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19943 	 * This is needed to obey conn_unspec_src when packets go through
19944 	 * ip_newroute + arp.
19945 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19946 	 */
19947 	if (src == INADDR_ANY && !unspec_src) {
19948 		/*
19949 		 * Assign the appropriate source address from the IRE if none
19950 		 * was specified.
19951 		 */
19952 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19953 
19954 		/*
19955 		 * With IP multipathing, broadcast packets are sent on the ire
19956 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19957 		 * the group. However, this ire might not be in the same zone so
19958 		 * we can't always use its source address. We look for a
19959 		 * broadcast ire in the same group and in the right zone.
19960 		 */
19961 		if (ire->ire_type == IRE_BROADCAST &&
19962 		    ire->ire_zoneid != zoneid) {
19963 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19964 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19965 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19966 			if (src_ire != NULL) {
19967 				src = src_ire->ire_src_addr;
19968 				ire_refrele(src_ire);
19969 			} else {
19970 				ire_refrele(ire);
19971 				if (conn_outgoing_ill != NULL)
19972 					ill_refrele(conn_outgoing_ill);
19973 				freemsg(first_mp);
19974 				BUMP_MIB(&ip_mib, ipOutDiscards);
19975 				return;
19976 			}
19977 		} else {
19978 			src = ire->ire_src_addr;
19979 		}
19980 
19981 		if (connp == NULL) {
19982 			ip1dbg(("ip_wput_ire: no connp and no src "
19983 			    "address for dst 0x%x, using src 0x%x\n",
19984 			    ntohl(dst),
19985 			    ntohl(src)));
19986 		}
19987 		ipha->ipha_src = src;
19988 	}
19989 	stq = ire->ire_stq;
19990 
19991 	/*
19992 	 * We only allow ire chains for broadcasts since there will
19993 	 * be multiple IRE_CACHE entries for the same multicast
19994 	 * address (one per ipif).
19995 	 */
19996 	next_mp = NULL;
19997 
19998 	/* broadcast packet */
19999 	if (ire->ire_type == IRE_BROADCAST)
20000 		goto broadcast;
20001 
20002 	/* loopback ? */
20003 	if (stq == NULL)
20004 		goto nullstq;
20005 
20006 	/* The ill_index for outbound ILL */
20007 	ill_index = Q_TO_INDEX(stq);
20008 
20009 	BUMP_MIB(&ip_mib, ipOutRequests);
20010 	ttl_protocol = ((uint16_t *)ipha)[4];
20011 
20012 	/* pseudo checksum (do it in parts for IP header checksum) */
20013 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20014 
20015 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20016 		queue_t *dev_q = stq->q_next;
20017 
20018 		/* flow controlled */
20019 		if ((dev_q->q_next || dev_q->q_first) &&
20020 		    !canput(dev_q))
20021 			goto blocked;
20022 		if ((PROTO == IPPROTO_UDP) &&
20023 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20024 			hlen = (V_HLEN & 0xF) << 2;
20025 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20026 			if (*up != 0) {
20027 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20028 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20029 				/* Software checksum? */
20030 				if (DB_CKSUMFLAGS(mp) == 0) {
20031 					IP_STAT(ip_out_sw_cksum);
20032 					IP_STAT_UPDATE(
20033 					    ip_udp_out_sw_cksum_bytes,
20034 					    LENGTH - hlen);
20035 				}
20036 			}
20037 		}
20038 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20039 		hlen = (V_HLEN & 0xF) << 2;
20040 		if (PROTO == IPPROTO_TCP) {
20041 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20042 			/*
20043 			 * The packet header is processed once and for all, even
20044 			 * in the multirouting case. We disable hardware
20045 			 * checksum if the packet is multirouted, as it will be
20046 			 * replicated via several interfaces, and not all of
20047 			 * them may have this capability.
20048 			 */
20049 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20050 			    LENGTH, max_frag, ipsec_len, cksum);
20051 			/* Software checksum? */
20052 			if (DB_CKSUMFLAGS(mp) == 0) {
20053 				IP_STAT(ip_out_sw_cksum);
20054 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20055 				    LENGTH - hlen);
20056 			}
20057 		} else {
20058 			sctp_hdr_t	*sctph;
20059 
20060 			ASSERT(PROTO == IPPROTO_SCTP);
20061 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20062 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20063 			/*
20064 			 * Zero out the checksum field to ensure proper
20065 			 * checksum calculation.
20066 			 */
20067 			sctph->sh_chksum = 0;
20068 #ifdef	DEBUG
20069 			if (!skip_sctp_cksum)
20070 #endif
20071 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20072 		}
20073 	}
20074 
20075 	/*
20076 	 * If this is a multicast packet and originated from ip_wput
20077 	 * we need to do loopback and forwarding checks. If it comes
20078 	 * from ip_wput_multicast, we SHOULD not do this.
20079 	 */
20080 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20081 
20082 	/* checksum */
20083 	cksum += ttl_protocol;
20084 
20085 	/* fragment the packet */
20086 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20087 		goto fragmentit;
20088 	/*
20089 	 * Don't use frag_flag if packet is pre-built or source
20090 	 * routed or if multicast (since multicast packets do
20091 	 * not solicit ICMP "packet too big" messages).
20092 	 */
20093 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20094 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20095 	    !ip_source_route_included(ipha)) &&
20096 	    !CLASSD(ipha->ipha_dst))
20097 		ipha->ipha_fragment_offset_and_flags |=
20098 		    htons(ire->ire_frag_flag);
20099 
20100 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20101 		/* calculate IP header checksum */
20102 		cksum += ipha->ipha_ident;
20103 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20104 		cksum += ipha->ipha_fragment_offset_and_flags;
20105 
20106 		/* IP options present */
20107 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20108 		if (hlen)
20109 			goto checksumoptions;
20110 
20111 		/* calculate hdr checksum */
20112 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20113 		cksum = ~(cksum + (cksum >> 16));
20114 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20115 	}
20116 	if (ipsec_len != 0) {
20117 		/*
20118 		 * We will do the rest of the processing after
20119 		 * we come back from IPSEC in ip_wput_ipsec_out().
20120 		 */
20121 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20122 
20123 		io = (ipsec_out_t *)first_mp->b_rptr;
20124 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20125 				ill_phyint->phyint_ifindex;
20126 
20127 		ipsec_out_process(q, first_mp, ire, ill_index);
20128 		ire_refrele(ire);
20129 		if (conn_outgoing_ill != NULL)
20130 			ill_refrele(conn_outgoing_ill);
20131 		return;
20132 	}
20133 
20134 	/*
20135 	 * In most cases, the emission loop below is entered only
20136 	 * once. Only in the case where the ire holds the
20137 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20138 	 * flagged ires in the bucket, and send the packet
20139 	 * through all crossed RTF_MULTIRT routes.
20140 	 */
20141 	if (ire->ire_flags & RTF_MULTIRT) {
20142 		multirt_send = B_TRUE;
20143 	}
20144 	do {
20145 		if (multirt_send) {
20146 			irb_t *irb;
20147 			/*
20148 			 * We are in a multiple send case, need to get
20149 			 * the next ire and make a duplicate of the packet.
20150 			 * ire1 holds here the next ire to process in the
20151 			 * bucket. If multirouting is expected,
20152 			 * any non-RTF_MULTIRT ire that has the
20153 			 * right destination address is ignored.
20154 			 */
20155 			irb = ire->ire_bucket;
20156 			ASSERT(irb != NULL);
20157 
20158 			IRB_REFHOLD(irb);
20159 			for (ire1 = ire->ire_next;
20160 			    ire1 != NULL;
20161 			    ire1 = ire1->ire_next) {
20162 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20163 					continue;
20164 				if (ire1->ire_addr != ire->ire_addr)
20165 					continue;
20166 				if (ire1->ire_marks &
20167 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20168 					continue;
20169 
20170 				/* Got one */
20171 				IRE_REFHOLD(ire1);
20172 				break;
20173 			}
20174 			IRB_REFRELE(irb);
20175 
20176 			if (ire1 != NULL) {
20177 				next_mp = copyb(mp);
20178 				if ((next_mp == NULL) ||
20179 				    ((mp->b_cont != NULL) &&
20180 				    ((next_mp->b_cont =
20181 				    dupmsg(mp->b_cont)) == NULL))) {
20182 					freemsg(next_mp);
20183 					next_mp = NULL;
20184 					ire_refrele(ire1);
20185 					ire1 = NULL;
20186 				}
20187 			}
20188 
20189 			/* Last multiroute ire; don't loop anymore. */
20190 			if (ire1 == NULL) {
20191 				multirt_send = B_FALSE;
20192 			}
20193 		}
20194 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20195 		if (mp == NULL) {
20196 			BUMP_MIB(&ip_mib, ipOutDiscards);
20197 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20198 			    "during IPPF processing\n"));
20199 			ire_refrele(ire);
20200 			if (next_mp != NULL) {
20201 				freemsg(next_mp);
20202 				ire_refrele(ire1);
20203 			}
20204 			if (conn_outgoing_ill != NULL)
20205 				ill_refrele(conn_outgoing_ill);
20206 			return;
20207 		}
20208 		UPDATE_OB_PKT_COUNT(ire);
20209 		ire->ire_last_used_time = lbolt;
20210 
20211 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20212 		    "ip_wput_ire_end: q %p (%S)",
20213 		    q, "last copy out");
20214 		putnext(stq, mp);
20215 		IRE_REFRELE(ire);
20216 
20217 		if (multirt_send) {
20218 			ASSERT(ire1);
20219 			/*
20220 			 * Proceed with the next RTF_MULTIRT ire,
20221 			 * Also set up the send-to queue accordingly.
20222 			 */
20223 			ire = ire1;
20224 			ire1 = NULL;
20225 			stq = ire->ire_stq;
20226 			mp = next_mp;
20227 			next_mp = NULL;
20228 			ipha = (ipha_t *)mp->b_rptr;
20229 			ill_index = Q_TO_INDEX(stq);
20230 		}
20231 	} while (multirt_send);
20232 	if (conn_outgoing_ill != NULL)
20233 		ill_refrele(conn_outgoing_ill);
20234 	return;
20235 
20236 	/*
20237 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20238 	 */
20239 broadcast:
20240 	{
20241 		/*
20242 		 * Avoid broadcast storms by setting the ttl to 1
20243 		 * for broadcasts. This parameter can be set
20244 		 * via ndd, so make sure that for the SO_DONTROUTE
20245 		 * case that ipha_ttl is always set to 1.
20246 		 * In the event that we are replying to incoming
20247 		 * ICMP packets, conn could be NULL.
20248 		 */
20249 		if ((connp != NULL) && connp->conn_dontroute)
20250 			ipha->ipha_ttl = 1;
20251 		else
20252 			ipha->ipha_ttl = ip_broadcast_ttl;
20253 
20254 		/*
20255 		 * Note that we are not doing a IRB_REFHOLD here.
20256 		 * Actually we don't care if the list changes i.e
20257 		 * if somebody deletes an IRE from the list while
20258 		 * we drop the lock, the next time we come around
20259 		 * ire_next will be NULL and hence we won't send
20260 		 * out multiple copies which is fine.
20261 		 */
20262 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20263 		ire1 = ire->ire_next;
20264 		if (conn_outgoing_ill != NULL) {
20265 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20266 				ASSERT(ire1 == ire->ire_next);
20267 				if (ire1 != NULL && ire1->ire_addr == dst) {
20268 					ire_refrele(ire);
20269 					ire = ire1;
20270 					IRE_REFHOLD(ire);
20271 					ire1 = ire->ire_next;
20272 					continue;
20273 				}
20274 				rw_exit(&ire->ire_bucket->irb_lock);
20275 				/* Did not find a matching ill */
20276 				ip1dbg(("ip_wput_ire: broadcast with no "
20277 				    "matching IP_BOUND_IF ill %s\n",
20278 				    conn_outgoing_ill->ill_name));
20279 				freemsg(first_mp);
20280 				if (ire != NULL)
20281 					ire_refrele(ire);
20282 				ill_refrele(conn_outgoing_ill);
20283 				return;
20284 			}
20285 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20286 			/*
20287 			 * If the next IRE has the same address and is not one
20288 			 * of the two copies that we need to send, try to see
20289 			 * whether this copy should be sent at all. This
20290 			 * assumes that we insert loopbacks first and then
20291 			 * non-loopbacks. This is acheived by inserting the
20292 			 * loopback always before non-loopback.
20293 			 * This is used to send a single copy of a broadcast
20294 			 * packet out all physical interfaces that have an
20295 			 * matching IRE_BROADCAST while also looping
20296 			 * back one copy (to ip_wput_local) for each
20297 			 * matching physical interface. However, we avoid
20298 			 * sending packets out different logical that match by
20299 			 * having ipif_up/ipif_down supress duplicate
20300 			 * IRE_BROADCASTS.
20301 			 *
20302 			 * This feature is currently used to get broadcasts
20303 			 * sent to multiple interfaces, when the broadcast
20304 			 * address being used applies to multiple interfaces.
20305 			 * For example, a whole net broadcast will be
20306 			 * replicated on every connected subnet of
20307 			 * the target net.
20308 			 *
20309 			 * Each zone has its own set of IRE_BROADCASTs, so that
20310 			 * we're able to distribute inbound packets to multiple
20311 			 * zones who share a broadcast address. We avoid looping
20312 			 * back outbound packets in different zones but on the
20313 			 * same ill, as the application would see duplicates.
20314 			 *
20315 			 * If the interfaces are part of the same group,
20316 			 * we would want to send only one copy out for
20317 			 * whole group.
20318 			 *
20319 			 * This logic assumes that ire_add_v4() groups the
20320 			 * IRE_BROADCAST entries so that those with the same
20321 			 * ire_addr and ill_group are kept together.
20322 			 */
20323 			ire_ill = ire->ire_ipif->ipif_ill;
20324 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20325 				if (ire_ill->ill_group != NULL &&
20326 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20327 					/*
20328 					 * If the current zone only has an ire
20329 					 * broadcast for this address marked
20330 					 * NORECV, the ire we want is ahead in
20331 					 * the bucket, so we look it up
20332 					 * deliberately ignoring the zoneid.
20333 					 */
20334 					for (ire1 = ire->ire_bucket->irb_ire;
20335 					    ire1 != NULL;
20336 					    ire1 = ire1->ire_next) {
20337 						ire1_ill =
20338 						    ire1->ire_ipif->ipif_ill;
20339 						if (ire1->ire_addr != dst)
20340 							continue;
20341 						/* skip over the current ire */
20342 						if (ire1 == ire)
20343 							continue;
20344 						/* skip over deleted ires */
20345 						if (ire1->ire_marks &
20346 						    IRE_MARK_CONDEMNED)
20347 							continue;
20348 						/*
20349 						 * non-loopback ire in our
20350 						 * group: use it for the next
20351 						 * pass in the loop
20352 						 */
20353 						if (ire1->ire_stq != NULL &&
20354 						    ire1_ill->ill_group ==
20355 						    ire_ill->ill_group)
20356 							break;
20357 					}
20358 				}
20359 			} else {
20360 				while (ire1 != NULL && ire1->ire_addr == dst) {
20361 					ire1_ill = ire1->ire_ipif->ipif_ill;
20362 					/*
20363 					 * We can have two broadcast ires on the
20364 					 * same ill in different zones; here
20365 					 * we'll send a copy of the packet on
20366 					 * each ill and the fanout code will
20367 					 * call conn_wantpacket() to check that
20368 					 * the zone has the broadcast address
20369 					 * configured on the ill. If the two
20370 					 * ires are in the same group we only
20371 					 * send one copy up.
20372 					 */
20373 					if (ire1_ill != ire_ill &&
20374 					    (ire1_ill->ill_group == NULL ||
20375 					    ire_ill->ill_group == NULL ||
20376 					    ire1_ill->ill_group !=
20377 					    ire_ill->ill_group)) {
20378 						break;
20379 					}
20380 					ire1 = ire1->ire_next;
20381 				}
20382 			}
20383 		}
20384 		ASSERT(multirt_send == B_FALSE);
20385 		if (ire1 != NULL && ire1->ire_addr == dst) {
20386 			if ((ire->ire_flags & RTF_MULTIRT) &&
20387 			    (ire1->ire_flags & RTF_MULTIRT)) {
20388 				/*
20389 				 * We are in the multirouting case.
20390 				 * The message must be sent at least
20391 				 * on both ires. These ires have been
20392 				 * inserted AFTER the standard ones
20393 				 * in ip_rt_add(). There are thus no
20394 				 * other ire entries for the destination
20395 				 * address in the rest of the bucket
20396 				 * that do not have the RTF_MULTIRT
20397 				 * flag. We don't process a copy
20398 				 * of the message here. This will be
20399 				 * done in the final sending loop.
20400 				 */
20401 				multirt_send = B_TRUE;
20402 			} else {
20403 				next_mp = ip_copymsg(first_mp);
20404 				if (next_mp != NULL)
20405 					IRE_REFHOLD(ire1);
20406 			}
20407 		}
20408 		rw_exit(&ire->ire_bucket->irb_lock);
20409 	}
20410 
20411 	if (stq) {
20412 		/*
20413 		 * A non-NULL send-to queue means this packet is going
20414 		 * out of this machine.
20415 		 */
20416 
20417 		BUMP_MIB(&ip_mib, ipOutRequests);
20418 		ttl_protocol = ((uint16_t *)ipha)[4];
20419 		/*
20420 		 * We accumulate the pseudo header checksum in cksum.
20421 		 * This is pretty hairy code, so watch close.  One
20422 		 * thing to keep in mind is that UDP and TCP have
20423 		 * stored their respective datagram lengths in their
20424 		 * checksum fields.  This lines things up real nice.
20425 		 */
20426 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20427 		    (src >> 16) + (src & 0xFFFF);
20428 		/*
20429 		 * We assume the udp checksum field contains the
20430 		 * length, so to compute the pseudo header checksum,
20431 		 * all we need is the protocol number and src/dst.
20432 		 */
20433 		/* Provide the checksums for UDP and TCP. */
20434 		if ((PROTO == IPPROTO_TCP) &&
20435 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20436 			/* hlen gets the number of uchar_ts in the IP header */
20437 			hlen = (V_HLEN & 0xF) << 2;
20438 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20439 			IP_STAT(ip_out_sw_cksum);
20440 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20441 			    LENGTH - hlen);
20442 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20443 			if (*up == 0)
20444 				*up = 0xFFFF;
20445 		} else if (PROTO == IPPROTO_SCTP &&
20446 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20447 			sctp_hdr_t	*sctph;
20448 
20449 			hlen = (V_HLEN & 0xF) << 2;
20450 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20451 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20452 			sctph->sh_chksum = 0;
20453 #ifdef	DEBUG
20454 			if (!skip_sctp_cksum)
20455 #endif
20456 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20457 		} else {
20458 			queue_t *dev_q = stq->q_next;
20459 
20460 			if ((dev_q->q_next || dev_q->q_first) &&
20461 			    !canput(dev_q)) {
20462 			    blocked:
20463 				ipha->ipha_ident = ip_hdr_included;
20464 				/*
20465 				 * If we don't have a conn to apply
20466 				 * backpressure, free the message.
20467 				 * In the ire_send path, we don't know
20468 				 * the position to requeue the packet. Rather
20469 				 * than reorder packets, we just drop this
20470 				 * packet.
20471 				 */
20472 				if (ip_output_queue && connp != NULL &&
20473 				    caller != IRE_SEND) {
20474 					if (caller == IP_WSRV) {
20475 						connp->conn_did_putbq = 1;
20476 						(void) putbq(connp->conn_wq,
20477 						    first_mp);
20478 						conn_drain_insert(connp);
20479 						/*
20480 						 * This is the service thread,
20481 						 * and the queue is already
20482 						 * noenabled. The check for
20483 						 * canput and the putbq is not
20484 						 * atomic. So we need to check
20485 						 * again.
20486 						 */
20487 						if (canput(stq->q_next))
20488 							connp->conn_did_putbq
20489 							    = 0;
20490 						IP_STAT(ip_conn_flputbq);
20491 					} else {
20492 						/*
20493 						 * We are not the service proc.
20494 						 * ip_wsrv will be scheduled or
20495 						 * is already running.
20496 						 */
20497 						(void) putq(connp->conn_wq,
20498 						    first_mp);
20499 					}
20500 				} else {
20501 					BUMP_MIB(&ip_mib, ipOutDiscards);
20502 					freemsg(first_mp);
20503 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20504 					    "ip_wput_ire_end: q %p (%S)",
20505 					    q, "discard");
20506 				}
20507 				ire_refrele(ire);
20508 				if (next_mp) {
20509 					ire_refrele(ire1);
20510 					freemsg(next_mp);
20511 				}
20512 				if (conn_outgoing_ill != NULL)
20513 					ill_refrele(conn_outgoing_ill);
20514 				return;
20515 			}
20516 			if ((PROTO == IPPROTO_UDP) &&
20517 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20518 				/*
20519 				 * hlen gets the number of uchar_ts in the
20520 				 * IP header
20521 				 */
20522 				hlen = (V_HLEN & 0xF) << 2;
20523 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20524 				max_frag = ire->ire_max_frag;
20525 				if (*up != 0) {
20526 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
20527 					    up, PROTO, hlen, LENGTH, max_frag,
20528 					    ipsec_len, cksum);
20529 					/* Software checksum? */
20530 					if (DB_CKSUMFLAGS(mp) == 0) {
20531 						IP_STAT(ip_out_sw_cksum);
20532 						IP_STAT_UPDATE(
20533 						    ip_udp_out_sw_cksum_bytes,
20534 						    LENGTH - hlen);
20535 					}
20536 				}
20537 			}
20538 		}
20539 		/*
20540 		 * Need to do this even when fragmenting. The local
20541 		 * loopback can be done without computing checksums
20542 		 * but forwarding out other interface must be done
20543 		 * after the IP checksum (and ULP checksums) have been
20544 		 * computed.
20545 		 *
20546 		 * NOTE : multicast_forward is set only if this packet
20547 		 * originated from ip_wput. For packets originating from
20548 		 * ip_wput_multicast, it is not set.
20549 		 */
20550 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20551 		    multi_loopback:
20552 			ip2dbg(("ip_wput: multicast, loop %d\n",
20553 			    conn_multicast_loop));
20554 
20555 			/*  Forget header checksum offload */
20556 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
20557 
20558 			/*
20559 			 * Local loopback of multicasts?  Check the
20560 			 * ill.
20561 			 *
20562 			 * Note that the loopback function will not come
20563 			 * in through ip_rput - it will only do the
20564 			 * client fanout thus we need to do an mforward
20565 			 * as well.  The is different from the BSD
20566 			 * logic.
20567 			 */
20568 			if (ill != NULL) {
20569 				ilm_t	*ilm;
20570 
20571 				ILM_WALKER_HOLD(ill);
20572 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20573 				    ALL_ZONES);
20574 				ILM_WALKER_RELE(ill);
20575 				if (ilm != NULL) {
20576 					/*
20577 					 * Pass along the virtual output q.
20578 					 * ip_wput_local() will distribute the
20579 					 * packet to all the matching zones,
20580 					 * except the sending zone when
20581 					 * IP_MULTICAST_LOOP is false.
20582 					 */
20583 					ip_multicast_loopback(q, ill, first_mp,
20584 					    conn_multicast_loop ? 0 :
20585 					    IP_FF_NO_MCAST_LOOP, zoneid);
20586 				}
20587 			}
20588 			if (ipha->ipha_ttl == 0) {
20589 				/*
20590 				 * 0 => only to this host i.e. we are
20591 				 * done. We are also done if this was the
20592 				 * loopback interface since it is sufficient
20593 				 * to loopback one copy of a multicast packet.
20594 				 */
20595 				freemsg(first_mp);
20596 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20597 				    "ip_wput_ire_end: q %p (%S)",
20598 				    q, "loopback");
20599 				ire_refrele(ire);
20600 				if (conn_outgoing_ill != NULL)
20601 					ill_refrele(conn_outgoing_ill);
20602 				return;
20603 			}
20604 			/*
20605 			 * ILLF_MULTICAST is checked in ip_newroute
20606 			 * i.e. we don't need to check it here since
20607 			 * all IRE_CACHEs come from ip_newroute.
20608 			 * For multicast traffic, SO_DONTROUTE is interpreted
20609 			 * to mean only send the packet out the interface
20610 			 * (optionally specified with IP_MULTICAST_IF)
20611 			 * and do not forward it out additional interfaces.
20612 			 * RSVP and the rsvp daemon is an example of a
20613 			 * protocol and user level process that
20614 			 * handles it's own routing. Hence, it uses the
20615 			 * SO_DONTROUTE option to accomplish this.
20616 			 */
20617 
20618 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20619 				/* Unconditionally redo the checksum */
20620 				ipha->ipha_hdr_checksum = 0;
20621 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20622 
20623 				/*
20624 				 * If this needs to go out secure, we need
20625 				 * to wait till we finish the IPSEC
20626 				 * processing.
20627 				 */
20628 				if (ipsec_len == 0 &&
20629 				    ip_mforward(ill, ipha, mp)) {
20630 					freemsg(first_mp);
20631 					ip1dbg(("ip_wput: mforward failed\n"));
20632 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20633 					    "ip_wput_ire_end: q %p (%S)",
20634 					    q, "mforward failed");
20635 					ire_refrele(ire);
20636 					if (conn_outgoing_ill != NULL)
20637 						ill_refrele(conn_outgoing_ill);
20638 					return;
20639 				}
20640 			}
20641 		}
20642 		max_frag = ire->ire_max_frag;
20643 		cksum += ttl_protocol;
20644 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
20645 			/* No fragmentation required for this one. */
20646 			/*
20647 			 * Don't use frag_flag if packet is pre-built or source
20648 			 * routed or if multicast (since multicast packets do
20649 			 * not solicit ICMP "packet too big" messages).
20650 			 */
20651 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20652 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20653 			    !ip_source_route_included(ipha)) &&
20654 			    !CLASSD(ipha->ipha_dst))
20655 				ipha->ipha_fragment_offset_and_flags |=
20656 				    htons(ire->ire_frag_flag);
20657 
20658 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20659 				/* Complete the IP header checksum. */
20660 				cksum += ipha->ipha_ident;
20661 				cksum += (v_hlen_tos_len >> 16)+
20662 				    (v_hlen_tos_len & 0xFFFF);
20663 				cksum += ipha->ipha_fragment_offset_and_flags;
20664 				hlen = (V_HLEN & 0xF) -
20665 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20666 				if (hlen) {
20667 				    checksumoptions:
20668 					/*
20669 					 * Account for the IP Options in the IP
20670 					 * header checksum.
20671 					 */
20672 					up = (uint16_t *)(rptr+
20673 					    IP_SIMPLE_HDR_LENGTH);
20674 					do {
20675 						cksum += up[0];
20676 						cksum += up[1];
20677 						up += 2;
20678 					} while (--hlen);
20679 				}
20680 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20681 				cksum = ~(cksum + (cksum >> 16));
20682 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
20683 			}
20684 			if (ipsec_len != 0) {
20685 				ipsec_out_process(q, first_mp, ire, ill_index);
20686 				if (!next_mp) {
20687 					ire_refrele(ire);
20688 					if (conn_outgoing_ill != NULL)
20689 						ill_refrele(conn_outgoing_ill);
20690 					return;
20691 				}
20692 				goto next;
20693 			}
20694 
20695 			/*
20696 			 * multirt_send has already been handled
20697 			 * for broadcast, but not yet for multicast
20698 			 * or IP options.
20699 			 */
20700 			if (next_mp == NULL) {
20701 				if (ire->ire_flags & RTF_MULTIRT) {
20702 					multirt_send = B_TRUE;
20703 				}
20704 			}
20705 
20706 			/*
20707 			 * In most cases, the emission loop below is
20708 			 * entered only once. Only in the case where
20709 			 * the ire holds the RTF_MULTIRT flag, do we loop
20710 			 * to process all RTF_MULTIRT ires in the bucket,
20711 			 * and send the packet through all crossed
20712 			 * RTF_MULTIRT routes.
20713 			 */
20714 			do {
20715 				if (multirt_send) {
20716 					irb_t *irb;
20717 
20718 					irb = ire->ire_bucket;
20719 					ASSERT(irb != NULL);
20720 					/*
20721 					 * We are in a multiple send case,
20722 					 * need to get the next IRE and make
20723 					 * a duplicate of the packet.
20724 					 */
20725 					IRB_REFHOLD(irb);
20726 					for (ire1 = ire->ire_next;
20727 					    ire1 != NULL;
20728 					    ire1 = ire1->ire_next) {
20729 						if (!(ire1->ire_flags &
20730 						    RTF_MULTIRT))
20731 							continue;
20732 						if (ire1->ire_addr !=
20733 						    ire->ire_addr)
20734 							continue;
20735 						if (ire1->ire_marks &
20736 						    (IRE_MARK_CONDEMNED|
20737 							IRE_MARK_HIDDEN))
20738 							continue;
20739 
20740 						/* Got one */
20741 						IRE_REFHOLD(ire1);
20742 						break;
20743 					}
20744 					IRB_REFRELE(irb);
20745 
20746 					if (ire1 != NULL) {
20747 						next_mp = copyb(mp);
20748 						if ((next_mp == NULL) ||
20749 						    ((mp->b_cont != NULL) &&
20750 						    ((next_mp->b_cont =
20751 						    dupmsg(mp->b_cont))
20752 						    == NULL))) {
20753 							freemsg(next_mp);
20754 							next_mp = NULL;
20755 							ire_refrele(ire1);
20756 							ire1 = NULL;
20757 						}
20758 					}
20759 
20760 					/*
20761 					 * Last multiroute ire; don't loop
20762 					 * anymore. The emission is over
20763 					 * and next_mp is NULL.
20764 					 */
20765 					if (ire1 == NULL) {
20766 						multirt_send = B_FALSE;
20767 					}
20768 				}
20769 
20770 			noprepend:
20771 				ASSERT(ipsec_len == 0);
20772 				mp1 = ip_wput_attach_llhdr(mp, ire,
20773 				    IPP_LOCAL_OUT, ill_index);
20774 				if (mp1 == NULL) {
20775 					BUMP_MIB(&ip_mib, ipOutDiscards);
20776 					if (next_mp) {
20777 						freemsg(next_mp);
20778 						ire_refrele(ire1);
20779 					}
20780 					ire_refrele(ire);
20781 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20782 					    "ip_wput_ire_end: q %p (%S)",
20783 					    q, "discard MDATA");
20784 					if (conn_outgoing_ill != NULL)
20785 						ill_refrele(conn_outgoing_ill);
20786 					return;
20787 				}
20788 				UPDATE_OB_PKT_COUNT(ire);
20789 				ire->ire_last_used_time = lbolt;
20790 
20791 				if (multirt_send) {
20792 					/*
20793 					 * We are in a multiple send case,
20794 					 * need to re-enter the sending loop
20795 					 * using the next ire.
20796 					 */
20797 					putnext(stq, mp1);
20798 					ire_refrele(ire);
20799 					ire = ire1;
20800 					stq = ire->ire_stq;
20801 					mp = next_mp;
20802 					next_mp = NULL;
20803 					ipha = (ipha_t *)mp->b_rptr;
20804 					ill_index = Q_TO_INDEX(stq);
20805 				}
20806 			} while (multirt_send);
20807 
20808 			if (!next_mp) {
20809 				/*
20810 				 * Last copy going out (the ultra-common
20811 				 * case).  Note that we intentionally replicate
20812 				 * the putnext rather than calling it before
20813 				 * the next_mp check in hopes of a little
20814 				 * tail-call action out of the compiler.
20815 				 */
20816 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20817 				    "ip_wput_ire_end: q %p (%S)",
20818 				    q, "last copy out(1)");
20819 				putnext(stq, mp1);
20820 				ire_refrele(ire);
20821 				if (conn_outgoing_ill != NULL)
20822 					ill_refrele(conn_outgoing_ill);
20823 				return;
20824 			}
20825 			/* More copies going out below. */
20826 			putnext(stq, mp1);
20827 		} else {
20828 			int offset;
20829 		    fragmentit:
20830 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20831 			/*
20832 			 * If this would generate a icmp_frag_needed message,
20833 			 * we need to handle it before we do the IPSEC
20834 			 * processing. Otherwise, we need to strip the IPSEC
20835 			 * headers before we send up the message to the ULPs
20836 			 * which becomes messy and difficult.
20837 			 */
20838 			if (ipsec_len != 0) {
20839 				if ((max_frag < (unsigned int)(LENGTH +
20840 				    ipsec_len)) && (offset & IPH_DF)) {
20841 
20842 					BUMP_MIB(&ip_mib, ipFragFails);
20843 					ipha->ipha_hdr_checksum = 0;
20844 					ipha->ipha_hdr_checksum =
20845 					    (uint16_t)ip_csum_hdr(ipha);
20846 					icmp_frag_needed(ire->ire_stq, first_mp,
20847 					    max_frag);
20848 					if (!next_mp) {
20849 						ire_refrele(ire);
20850 						if (conn_outgoing_ill != NULL) {
20851 							ill_refrele(
20852 							    conn_outgoing_ill);
20853 						}
20854 						return;
20855 					}
20856 				} else {
20857 					/*
20858 					 * This won't cause a icmp_frag_needed
20859 					 * message. to be gnerated. Send it on
20860 					 * the wire. Note that this could still
20861 					 * cause fragmentation and all we
20862 					 * do is the generation of the message
20863 					 * to the ULP if needed before IPSEC.
20864 					 */
20865 					if (!next_mp) {
20866 						ipsec_out_process(q, first_mp,
20867 						    ire, ill_index);
20868 						TRACE_2(TR_FAC_IP,
20869 						    TR_IP_WPUT_IRE_END,
20870 						    "ip_wput_ire_end: q %p "
20871 						    "(%S)", q,
20872 						    "last ipsec_out_process");
20873 						ire_refrele(ire);
20874 						if (conn_outgoing_ill != NULL) {
20875 							ill_refrele(
20876 							    conn_outgoing_ill);
20877 						}
20878 						return;
20879 					}
20880 					ipsec_out_process(q, first_mp,
20881 					    ire, ill_index);
20882 				}
20883 			} else {
20884 				/* Initiate IPPF processing */
20885 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20886 					ip_process(IPP_LOCAL_OUT, &mp,
20887 					    ill_index);
20888 					if (mp == NULL) {
20889 						BUMP_MIB(&ip_mib,
20890 						    ipOutDiscards);
20891 						if (next_mp != NULL) {
20892 							freemsg(next_mp);
20893 							ire_refrele(ire1);
20894 						}
20895 						ire_refrele(ire);
20896 						TRACE_2(TR_FAC_IP,
20897 						    TR_IP_WPUT_IRE_END,
20898 						    "ip_wput_ire: q %p (%S)",
20899 						    q, "discard MDATA");
20900 						if (conn_outgoing_ill != NULL) {
20901 							ill_refrele(
20902 							    conn_outgoing_ill);
20903 						}
20904 						return;
20905 					}
20906 				}
20907 				if (!next_mp) {
20908 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20909 					    "ip_wput_ire_end: q %p (%S)",
20910 					    q, "last fragmentation");
20911 					ip_wput_ire_fragmentit(mp, ire);
20912 					ire_refrele(ire);
20913 					if (conn_outgoing_ill != NULL)
20914 						ill_refrele(conn_outgoing_ill);
20915 					return;
20916 				}
20917 				ip_wput_ire_fragmentit(mp, ire);
20918 			}
20919 		}
20920 	} else {
20921 	    nullstq:
20922 		/* A NULL stq means the destination address is local. */
20923 		UPDATE_OB_PKT_COUNT(ire);
20924 		ire->ire_last_used_time = lbolt;
20925 		ASSERT(ire->ire_ipif != NULL);
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, "local address");
20930 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20931 			    first_mp, ire, 0, ire->ire_zoneid);
20932 			ire_refrele(ire);
20933 			if (conn_outgoing_ill != NULL)
20934 				ill_refrele(conn_outgoing_ill);
20935 			return;
20936 		}
20937 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20938 		    ire, 0, ire->ire_zoneid);
20939 	}
20940 next:
20941 	/*
20942 	 * More copies going out to additional interfaces.
20943 	 * ire1 has already been held. We don't need the
20944 	 * "ire" anymore.
20945 	 */
20946 	ire_refrele(ire);
20947 	ire = ire1;
20948 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20949 	mp = next_mp;
20950 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20951 	ill = ire_to_ill(ire);
20952 	first_mp = mp;
20953 	if (ipsec_len != 0) {
20954 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20955 		mp = mp->b_cont;
20956 	}
20957 	dst = ire->ire_addr;
20958 	ipha = (ipha_t *)mp->b_rptr;
20959 	/*
20960 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20961 	 * Restore ipha_ident "no checksum" flag.
20962 	 */
20963 	src = orig_src;
20964 	ipha->ipha_ident = ip_hdr_included;
20965 	goto another;
20966 
20967 #undef	rptr
20968 #undef	Q_TO_INDEX
20969 }
20970 
20971 /*
20972  * Routine to allocate a message that is used to notify the ULP about MDT.
20973  * The caller may provide a pointer to the link-layer MDT capabilities,
20974  * or NULL if MDT is to be disabled on the stream.
20975  */
20976 mblk_t *
20977 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20978 {
20979 	mblk_t *mp;
20980 	ip_mdt_info_t *mdti;
20981 	ill_mdt_capab_t *idst;
20982 
20983 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20984 		DB_TYPE(mp) = M_CTL;
20985 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20986 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20987 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20988 		idst = &(mdti->mdt_capab);
20989 
20990 		/*
20991 		 * If the caller provides us with the capability, copy
20992 		 * it over into our notification message; otherwise
20993 		 * we zero out the capability portion.
20994 		 */
20995 		if (isrc != NULL)
20996 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20997 		else
20998 			bzero((caddr_t)idst, sizeof (*idst));
20999 	}
21000 	return (mp);
21001 }
21002 
21003 /*
21004  * Routine which determines whether MDT can be enabled on the destination
21005  * IRE and IPC combination, and if so, allocates and returns the MDT
21006  * notification mblk that may be used by ULP.  We also check if we need to
21007  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21008  * MDT usage in the past have been lifted.  This gets called during IP
21009  * and ULP binding.
21010  */
21011 mblk_t *
21012 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21013     ill_mdt_capab_t *mdt_cap)
21014 {
21015 	mblk_t *mp;
21016 	boolean_t rc = B_FALSE;
21017 
21018 	ASSERT(dst_ire != NULL);
21019 	ASSERT(connp != NULL);
21020 	ASSERT(mdt_cap != NULL);
21021 
21022 	/*
21023 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21024 	 * Multidata, which is handled in tcp_multisend().  This
21025 	 * is the reason why we do all these checks here, to ensure
21026 	 * that we don't enable Multidata for the cases which we
21027 	 * can't handle at the moment.
21028 	 */
21029 	do {
21030 		/* Only do TCP at the moment */
21031 		if (connp->conn_ulp != IPPROTO_TCP)
21032 			break;
21033 
21034 		/*
21035 		 * IPSEC outbound policy present?  Note that we get here
21036 		 * after calling ipsec_conn_cache_policy() where the global
21037 		 * policy checking is performed.  conn_latch will be
21038 		 * non-NULL as long as there's a policy defined,
21039 		 * i.e. conn_out_enforce_policy may be NULL in such case
21040 		 * when the connection is non-secure, and hence we check
21041 		 * further if the latch refers to an outbound policy.
21042 		 */
21043 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21044 			break;
21045 
21046 		/* CGTP (multiroute) is enabled? */
21047 		if (dst_ire->ire_flags & RTF_MULTIRT)
21048 			break;
21049 
21050 		/* Outbound IPQoS enabled? */
21051 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21052 			/*
21053 			 * In this case, we disable MDT for this and all
21054 			 * future connections going over the interface.
21055 			 */
21056 			mdt_cap->ill_mdt_on = 0;
21057 			break;
21058 		}
21059 
21060 		/* socket option(s) present? */
21061 		if (!CONN_IS_MD_FASTPATH(connp))
21062 			break;
21063 
21064 		rc = B_TRUE;
21065 	/* CONSTCOND */
21066 	} while (0);
21067 
21068 	/* Remember the result */
21069 	connp->conn_mdt_ok = rc;
21070 
21071 	if (!rc)
21072 		return (NULL);
21073 	else if (!mdt_cap->ill_mdt_on) {
21074 		/*
21075 		 * If MDT has been previously turned off in the past, and we
21076 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21077 		 * then enable it for this interface.
21078 		 */
21079 		mdt_cap->ill_mdt_on = 1;
21080 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21081 		    "interface %s\n", ill_name));
21082 	}
21083 
21084 	/* Allocate the MDT info mblk */
21085 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21086 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21087 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21088 		return (NULL);
21089 	}
21090 	return (mp);
21091 }
21092 
21093 /*
21094  * Create destination address attribute, and fill it with the physical
21095  * destination address and SAP taken from the template DL_UNITDATA_REQ
21096  * message block.
21097  */
21098 boolean_t
21099 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21100 {
21101 	dl_unitdata_req_t *dlurp;
21102 	pattr_t *pa;
21103 	pattrinfo_t pa_info;
21104 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21105 	uint_t das_len, das_off;
21106 
21107 	ASSERT(dlmp != NULL);
21108 
21109 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21110 	das_len = dlurp->dl_dest_addr_length;
21111 	das_off = dlurp->dl_dest_addr_offset;
21112 
21113 	pa_info.type = PATTR_DSTADDRSAP;
21114 	pa_info.len = sizeof (**das) + das_len - 1;
21115 
21116 	/* create and associate the attribute */
21117 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21118 	if (pa != NULL) {
21119 		ASSERT(*das != NULL);
21120 		(*das)->addr_is_group = 0;
21121 		(*das)->addr_len = (uint8_t)das_len;
21122 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21123 	}
21124 
21125 	return (pa != NULL);
21126 }
21127 
21128 /*
21129  * Create hardware checksum attribute and fill it with the values passed.
21130  */
21131 boolean_t
21132 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21133     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21134 {
21135 	pattr_t *pa;
21136 	pattrinfo_t pa_info;
21137 
21138 	ASSERT(mmd != NULL);
21139 
21140 	pa_info.type = PATTR_HCKSUM;
21141 	pa_info.len = sizeof (pattr_hcksum_t);
21142 
21143 	/* create and associate the attribute */
21144 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21145 	if (pa != NULL) {
21146 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21147 
21148 		hck->hcksum_start_offset = start_offset;
21149 		hck->hcksum_stuff_offset = stuff_offset;
21150 		hck->hcksum_end_offset = end_offset;
21151 		hck->hcksum_flags = flags;
21152 	}
21153 	return (pa != NULL);
21154 }
21155 
21156 /*
21157  * Create zerocopy attribute and fill it with the specified flags
21158  */
21159 boolean_t
21160 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21161 {
21162 	pattr_t *pa;
21163 	pattrinfo_t pa_info;
21164 
21165 	ASSERT(mmd != NULL);
21166 	pa_info.type = PATTR_ZCOPY;
21167 	pa_info.len = sizeof (pattr_zcopy_t);
21168 
21169 	/* create and associate the attribute */
21170 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21171 	if (pa != NULL) {
21172 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21173 
21174 		zcopy->zcopy_flags = flags;
21175 	}
21176 	return (pa != NULL);
21177 }
21178 
21179 /*
21180  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21181  * block chain. We could rewrite to handle arbitrary message block chains but
21182  * that would make the code complicated and slow. Right now there three
21183  * restrictions:
21184  *
21185  *   1. The first message block must contain the complete IP header and
21186  *	at least 1 byte of payload data.
21187  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
21188  *	so that we can use a single Multidata message.
21189  *   3. No frag must be distributed over two or more message blocks so
21190  *	that we don't need more than two packet descriptors per frag.
21191  *
21192  * The above restrictions allow us to support userland applications (which
21193  * will send down a single message block) and NFS over UDP (which will
21194  * send down a chain of at most three message blocks).
21195  *
21196  * We also don't use MDT for payloads with less than or equal to
21197  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
21198  */
21199 boolean_t
21200 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
21201 {
21202 	int	blocks;
21203 	ssize_t	total, missing, size;
21204 
21205 	ASSERT(mp != NULL);
21206 	ASSERT(hdr_len > 0);
21207 
21208 	size = MBLKL(mp) - hdr_len;
21209 	if (size <= 0)
21210 		return (B_FALSE);
21211 
21212 	/* The first mblk contains the header and some payload. */
21213 	blocks = 1;
21214 	total = size;
21215 	size %= len;
21216 	missing = (size == 0) ? 0 : (len - size);
21217 	mp = mp->b_cont;
21218 
21219 	while (mp != NULL) {
21220 		/*
21221 		 * Give up if we encounter a zero length message block.
21222 		 * In practice, this should rarely happen and therefore
21223 		 * not worth the trouble of freeing and re-linking the
21224 		 * mblk from the chain to handle such case.
21225 		 */
21226 		if ((size = MBLKL(mp)) == 0)
21227 			return (B_FALSE);
21228 
21229 		/* Too many payload buffers for a single Multidata message? */
21230 		if (++blocks > MULTIDATA_MAX_PBUFS)
21231 			return (B_FALSE);
21232 
21233 		total += size;
21234 		/* Is a frag distributed over two or more message blocks? */
21235 		if (missing > size)
21236 			return (B_FALSE);
21237 		size -= missing;
21238 
21239 		size %= len;
21240 		missing = (size == 0) ? 0 : (len - size);
21241 
21242 		mp = mp->b_cont;
21243 	}
21244 
21245 	return (total > ip_wput_frag_mdt_min);
21246 }
21247 
21248 /*
21249  * Outbound IPv4 fragmentation routine using MDT.
21250  */
21251 static void
21252 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
21253     uint32_t frag_flag, int offset)
21254 {
21255 	ipha_t		*ipha_orig;
21256 	int		i1, ip_data_end;
21257 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
21258 	mblk_t		*hdr_mp, *md_mp = NULL;
21259 	unsigned char	*hdr_ptr, *pld_ptr;
21260 	multidata_t	*mmd;
21261 	ip_pdescinfo_t	pdi;
21262 
21263 	ASSERT(DB_TYPE(mp) == M_DATA);
21264 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
21265 
21266 	ipha_orig = (ipha_t *)mp->b_rptr;
21267 	mp->b_rptr += sizeof (ipha_t);
21268 
21269 	/* Calculate how many packets we will send out */
21270 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
21271 	pkts = (i1 + len - 1) / len;
21272 	ASSERT(pkts > 1);
21273 
21274 	/* Allocate a message block which will hold all the IP Headers. */
21275 	wroff = ip_wroff_extra;
21276 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
21277 
21278 	i1 = pkts * hdr_chunk_len;
21279 	/*
21280 	 * Create the header buffer, Multidata and destination address
21281 	 * and SAP attribute that should be associated with it.
21282 	 */
21283 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
21284 	    ((hdr_mp->b_wptr += i1),
21285 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
21286 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
21287 		freemsg(mp);
21288 		if (md_mp == NULL) {
21289 			freemsg(hdr_mp);
21290 		} else {
21291 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
21292 			freemsg(md_mp);
21293 		}
21294 		IP_STAT(ip_frag_mdt_allocfail);
21295 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
21296 		return;
21297 	}
21298 	IP_STAT(ip_frag_mdt_allocd);
21299 
21300 	/*
21301 	 * Add a payload buffer to the Multidata; this operation must not
21302 	 * fail, or otherwise our logic in this routine is broken.  There
21303 	 * is no memory allocation done by the routine, so any returned
21304 	 * failure simply tells us that we've done something wrong.
21305 	 *
21306 	 * A failure tells us that either we're adding the same payload
21307 	 * buffer more than once, or we're trying to add more buffers than
21308 	 * allowed.  None of the above cases should happen, and we panic
21309 	 * because either there's horrible heap corruption, and/or
21310 	 * programming mistake.
21311 	 */
21312 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21313 		goto pbuf_panic;
21314 
21315 	hdr_ptr = hdr_mp->b_rptr;
21316 	pld_ptr = mp->b_rptr;
21317 
21318 	/* Establish the ending byte offset, based on the starting offset. */
21319 	offset <<= 3;
21320 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
21321 	    IP_SIMPLE_HDR_LENGTH;
21322 
21323 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
21324 
21325 	while (pld_ptr < mp->b_wptr) {
21326 		ipha_t		*ipha;
21327 		uint16_t	offset_and_flags;
21328 		uint16_t	ip_len;
21329 		int		error;
21330 
21331 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
21332 		ipha = (ipha_t *)(hdr_ptr + wroff);
21333 		ASSERT(OK_32PTR(ipha));
21334 		*ipha = *ipha_orig;
21335 
21336 		if (ip_data_end - offset > len) {
21337 			offset_and_flags = IPH_MF;
21338 		} else {
21339 			/*
21340 			 * Last frag. Set len to the length of this last piece.
21341 			 */
21342 			len = ip_data_end - offset;
21343 			/* A frag of a frag might have IPH_MF non-zero */
21344 			offset_and_flags =
21345 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21346 			    IPH_MF;
21347 		}
21348 		offset_and_flags |= (uint16_t)(offset >> 3);
21349 		offset_and_flags |= (uint16_t)frag_flag;
21350 		/* Store the offset and flags in the IP header. */
21351 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21352 
21353 		/* Store the length in the IP header. */
21354 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
21355 		ipha->ipha_length = htons(ip_len);
21356 
21357 		/*
21358 		 * Set the IP header checksum.  Note that mp is just
21359 		 * the header, so this is easy to pass to ip_csum.
21360 		 */
21361 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21362 
21363 		/*
21364 		 * Record offset and size of header and data of the next packet
21365 		 * in the multidata message.
21366 		 */
21367 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
21368 		PDESC_PLD_INIT(&pdi);
21369 		i1 = MIN(mp->b_wptr - pld_ptr, len);
21370 		ASSERT(i1 > 0);
21371 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
21372 		if (i1 == len) {
21373 			pld_ptr += len;
21374 		} else {
21375 			i1 = len - i1;
21376 			mp = mp->b_cont;
21377 			ASSERT(mp != NULL);
21378 			ASSERT(MBLKL(mp) >= i1);
21379 			/*
21380 			 * Attach the next payload message block to the
21381 			 * multidata message.
21382 			 */
21383 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21384 				goto pbuf_panic;
21385 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
21386 			pld_ptr = mp->b_rptr + i1;
21387 		}
21388 
21389 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
21390 		    KM_NOSLEEP)) == NULL) {
21391 			/*
21392 			 * Any failure other than ENOMEM indicates that we
21393 			 * have passed in invalid pdesc info or parameters
21394 			 * to mmd_addpdesc, which must not happen.
21395 			 *
21396 			 * EINVAL is a result of failure on boundary checks
21397 			 * against the pdesc info contents.  It should not
21398 			 * happen, and we panic because either there's
21399 			 * horrible heap corruption, and/or programming
21400 			 * mistake.
21401 			 */
21402 			if (error != ENOMEM) {
21403 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
21404 				    "pdesc logic error detected for "
21405 				    "mmd %p pinfo %p (%d)\n",
21406 				    (void *)mmd, (void *)&pdi, error);
21407 				/* NOTREACHED */
21408 			}
21409 			IP_STAT(ip_frag_mdt_addpdescfail);
21410 			/* Free unattached payload message blocks as well */
21411 			md_mp->b_cont = mp->b_cont;
21412 			goto free_mmd;
21413 		}
21414 
21415 		/* Advance fragment offset. */
21416 		offset += len;
21417 
21418 		/* Advance to location for next header in the buffer. */
21419 		hdr_ptr += hdr_chunk_len;
21420 
21421 		/* Did we reach the next payload message block? */
21422 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
21423 			mp = mp->b_cont;
21424 			/*
21425 			 * Attach the next message block with payload
21426 			 * data to the multidata message.
21427 			 */
21428 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21429 				goto pbuf_panic;
21430 			pld_ptr = mp->b_rptr;
21431 		}
21432 	}
21433 
21434 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
21435 	ASSERT(mp->b_wptr == pld_ptr);
21436 
21437 	/* Update IP statistics */
21438 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
21439 	BUMP_MIB(&ip_mib, ipFragOKs);
21440 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
21441 
21442 	if (pkt_type == OB_PKT) {
21443 		ire->ire_ob_pkt_count += pkts;
21444 		if (ire->ire_ipif != NULL)
21445 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
21446 	} else {
21447 		/*
21448 		 * The type is IB_PKT in the forwarding path and in
21449 		 * the mobile IP case when the packet is being reverse-
21450 		 * tunneled to the home agent.
21451 		 */
21452 		ire->ire_ib_pkt_count += pkts;
21453 		ASSERT(!IRE_IS_LOCAL(ire));
21454 		if (ire->ire_type & IRE_BROADCAST)
21455 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
21456 		else
21457 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
21458 	}
21459 	ire->ire_last_used_time = lbolt;
21460 	/* Send it down */
21461 	putnext(ire->ire_stq, md_mp);
21462 	return;
21463 
21464 pbuf_panic:
21465 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
21466 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
21467 	    pbuf_idx);
21468 	/* NOTREACHED */
21469 }
21470 
21471 /*
21472  * Outbound IP fragmentation routine.
21473  *
21474  * NOTE : This routine does not ire_refrele the ire that is passed in
21475  * as the argument.
21476  */
21477 static void
21478 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21479     uint32_t frag_flag)
21480 {
21481 	int		i1;
21482 	mblk_t		*ll_hdr_mp;
21483 	int 		ll_hdr_len;
21484 	int		hdr_len;
21485 	mblk_t		*hdr_mp;
21486 	ipha_t		*ipha;
21487 	int		ip_data_end;
21488 	int		len;
21489 	mblk_t		*mp = mp_orig;
21490 	int		offset;
21491 	queue_t		*q;
21492 	uint32_t	v_hlen_tos_len;
21493 	mblk_t		*first_mp;
21494 	boolean_t	mctl_present;
21495 	ill_t		*ill;
21496 	mblk_t		*xmit_mp;
21497 	mblk_t		*carve_mp;
21498 	ire_t		*ire1 = NULL;
21499 	ire_t		*save_ire = NULL;
21500 	mblk_t  	*next_mp = NULL;
21501 	boolean_t	last_frag = B_FALSE;
21502 	boolean_t	multirt_send = B_FALSE;
21503 	ire_t		*first_ire = NULL;
21504 	irb_t		*irb = NULL;
21505 
21506 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21507 	    "ip_wput_frag_start:");
21508 
21509 	if (mp->b_datap->db_type == M_CTL) {
21510 		first_mp = mp;
21511 		mp_orig = mp = mp->b_cont;
21512 		mctl_present = B_TRUE;
21513 	} else {
21514 		first_mp = mp;
21515 		mctl_present = B_FALSE;
21516 	}
21517 
21518 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
21519 	ipha = (ipha_t *)mp->b_rptr;
21520 
21521 	/*
21522 	 * If the Don't Fragment flag is on, generate an ICMP destination
21523 	 * unreachable, fragmentation needed.
21524 	 */
21525 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21526 	if (offset & IPH_DF) {
21527 		BUMP_MIB(&ip_mib, ipFragFails);
21528 		/*
21529 		 * Need to compute hdr checksum if called from ip_wput_ire.
21530 		 * Note that ip_rput_forward verifies the checksum before
21531 		 * calling this routine so in that case this is a noop.
21532 		 */
21533 		ipha->ipha_hdr_checksum = 0;
21534 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21535 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21536 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21537 		    "ip_wput_frag_end:(%S)",
21538 		    "don't fragment");
21539 		return;
21540 	}
21541 	if (mctl_present)
21542 		freeb(first_mp);
21543 	/*
21544 	 * Establish the starting offset.  May not be zero if we are fragging
21545 	 * a fragment that is being forwarded.
21546 	 */
21547 	offset = offset & IPH_OFFSET;
21548 
21549 	/* TODO why is this test needed? */
21550 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21551 	if (((max_frag - LENGTH) & ~7) < 8) {
21552 		/* TODO: notify ulp somehow */
21553 		BUMP_MIB(&ip_mib, ipFragFails);
21554 		freemsg(mp);
21555 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21556 		    "ip_wput_frag_end:(%S)",
21557 		    "len < 8");
21558 		return;
21559 	}
21560 
21561 	hdr_len = (V_HLEN & 0xF) << 2;
21562 
21563 	ipha->ipha_hdr_checksum = 0;
21564 
21565 	/*
21566 	 * Establish the number of bytes maximum per frag, after putting
21567 	 * in the header.
21568 	 */
21569 	len = (max_frag - hdr_len) & ~7;
21570 
21571 	/* Check if we can use MDT to send out the frags. */
21572 	ASSERT(!IRE_IS_LOCAL(ire));
21573 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
21574 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
21575 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
21576 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
21577 		ASSERT(ill->ill_mdt_capab != NULL);
21578 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21579 			/*
21580 			 * If MDT has been previously turned off in the past,
21581 			 * and we currently can do MDT (due to IPQoS policy
21582 			 * removal, etc.) then enable it for this interface.
21583 			 */
21584 			ill->ill_mdt_capab->ill_mdt_on = 1;
21585 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
21586 			    ill->ill_name));
21587 		}
21588 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
21589 		    offset);
21590 		return;
21591 	}
21592 
21593 	/* Get a copy of the header for the trailing frags */
21594 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21595 	if (!hdr_mp) {
21596 		BUMP_MIB(&ip_mib, ipOutDiscards);
21597 		freemsg(mp);
21598 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21599 		    "ip_wput_frag_end:(%S)",
21600 		    "couldn't copy hdr");
21601 		return;
21602 	}
21603 
21604 	/* Store the starting offset, with the MoreFrags flag. */
21605 	i1 = offset | IPH_MF | frag_flag;
21606 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21607 
21608 	/* Establish the ending byte offset, based on the starting offset. */
21609 	offset <<= 3;
21610 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21611 
21612 	/* Store the length of the first fragment in the IP header. */
21613 	i1 = len + hdr_len;
21614 	ASSERT(i1 <= IP_MAXPACKET);
21615 	ipha->ipha_length = htons((uint16_t)i1);
21616 
21617 	/*
21618 	 * Compute the IP header checksum for the first frag.  We have to
21619 	 * watch out that we stop at the end of the header.
21620 	 */
21621 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21622 
21623 	/*
21624 	 * Now carve off the first frag.  Note that this will include the
21625 	 * original IP header.
21626 	 */
21627 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21628 		BUMP_MIB(&ip_mib, ipOutDiscards);
21629 		freeb(hdr_mp);
21630 		freemsg(mp_orig);
21631 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21632 		    "ip_wput_frag_end:(%S)",
21633 		    "couldn't carve first");
21634 		return;
21635 	}
21636 
21637 	/*
21638 	 * Multirouting case. Each fragment is replicated
21639 	 * via all non-condemned RTF_MULTIRT routes
21640 	 * currently resolved.
21641 	 * We ensure that first_ire is the first RTF_MULTIRT
21642 	 * ire in the bucket.
21643 	 */
21644 	if (ire->ire_flags & RTF_MULTIRT) {
21645 		irb = ire->ire_bucket;
21646 		ASSERT(irb != NULL);
21647 
21648 		multirt_send = B_TRUE;
21649 
21650 		/* Make sure we do not omit any multiroute ire. */
21651 		IRB_REFHOLD(irb);
21652 		for (first_ire = irb->irb_ire;
21653 		    first_ire != NULL;
21654 		    first_ire = first_ire->ire_next) {
21655 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21656 			    (first_ire->ire_addr == ire->ire_addr) &&
21657 			    !(first_ire->ire_marks &
21658 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21659 				break;
21660 		}
21661 
21662 		if (first_ire != NULL) {
21663 			if (first_ire != ire) {
21664 				IRE_REFHOLD(first_ire);
21665 				/*
21666 				 * Do not release the ire passed in
21667 				 * as the argument.
21668 				 */
21669 				ire = first_ire;
21670 			} else {
21671 				first_ire = NULL;
21672 			}
21673 		}
21674 		IRB_REFRELE(irb);
21675 
21676 		/*
21677 		 * Save the first ire; we will need to restore it
21678 		 * for the trailing frags.
21679 		 * We REFHOLD save_ire, as each iterated ire will be
21680 		 * REFRELEd.
21681 		 */
21682 		save_ire = ire;
21683 		IRE_REFHOLD(save_ire);
21684 	}
21685 
21686 	/*
21687 	 * First fragment emission loop.
21688 	 * In most cases, the emission loop below is entered only
21689 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21690 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21691 	 * bucket, and send the fragment through all crossed
21692 	 * RTF_MULTIRT routes.
21693 	 */
21694 	do {
21695 		if (ire->ire_flags & RTF_MULTIRT) {
21696 			/*
21697 			 * We are in a multiple send case, need to get
21698 			 * the next ire and make a copy of the packet.
21699 			 * ire1 holds here the next ire to process in the
21700 			 * bucket. If multirouting is expected,
21701 			 * any non-RTF_MULTIRT ire that has the
21702 			 * right destination address is ignored.
21703 			 *
21704 			 * We have to take into account the MTU of
21705 			 * each walked ire. max_frag is set by the
21706 			 * the caller and generally refers to
21707 			 * the primary ire entry. Here we ensure that
21708 			 * no route with a lower MTU will be used, as
21709 			 * fragments are carved once for all ires,
21710 			 * then replicated.
21711 			 */
21712 			ASSERT(irb != NULL);
21713 			IRB_REFHOLD(irb);
21714 			for (ire1 = ire->ire_next;
21715 			    ire1 != NULL;
21716 			    ire1 = ire1->ire_next) {
21717 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21718 					continue;
21719 				if (ire1->ire_addr != ire->ire_addr)
21720 					continue;
21721 				if (ire1->ire_marks &
21722 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21723 					continue;
21724 				/*
21725 				 * Ensure we do not exceed the MTU
21726 				 * of the next route.
21727 				 */
21728 				if (ire1->ire_max_frag < max_frag) {
21729 					ip_multirt_bad_mtu(ire1, max_frag);
21730 					continue;
21731 				}
21732 
21733 				/* Got one. */
21734 				IRE_REFHOLD(ire1);
21735 				break;
21736 			}
21737 			IRB_REFRELE(irb);
21738 
21739 			if (ire1 != NULL) {
21740 				next_mp = copyb(mp);
21741 				if ((next_mp == NULL) ||
21742 				    ((mp->b_cont != NULL) &&
21743 				    ((next_mp->b_cont =
21744 				    dupmsg(mp->b_cont)) == NULL))) {
21745 					freemsg(next_mp);
21746 					next_mp = NULL;
21747 					ire_refrele(ire1);
21748 					ire1 = NULL;
21749 				}
21750 			}
21751 
21752 			/* Last multiroute ire; don't loop anymore. */
21753 			if (ire1 == NULL) {
21754 				multirt_send = B_FALSE;
21755 			}
21756 		}
21757 
21758 		ll_hdr_len = 0;
21759 		LOCK_IRE_FP_MP(ire);
21760 		ll_hdr_mp = ire->ire_fp_mp;
21761 		if (ll_hdr_mp != NULL) {
21762 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21763 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21764 		} else {
21765 			ll_hdr_mp = ire->ire_dlureq_mp;
21766 		}
21767 
21768 		/* If there is a transmit header, get a copy for this frag. */
21769 		/*
21770 		 * TODO: should check db_ref before calling ip_carve_mp since
21771 		 * it might give us a dup.
21772 		 */
21773 		if (!ll_hdr_mp) {
21774 			/* No xmit header. */
21775 			xmit_mp = mp;
21776 		} else if (mp->b_datap->db_ref == 1 &&
21777 		    ll_hdr_len != 0 &&
21778 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21779 			/* M_DATA fastpath */
21780 			mp->b_rptr -= ll_hdr_len;
21781 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21782 			xmit_mp = mp;
21783 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21784 			UNLOCK_IRE_FP_MP(ire);
21785 			BUMP_MIB(&ip_mib, ipOutDiscards);
21786 			freeb(hdr_mp);
21787 			freemsg(mp);
21788 			freemsg(mp_orig);
21789 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21790 			    "ip_wput_frag_end:(%S)",
21791 			    "discard");
21792 
21793 			if (multirt_send) {
21794 				ASSERT(ire1);
21795 				ASSERT(next_mp);
21796 
21797 				freemsg(next_mp);
21798 				ire_refrele(ire1);
21799 			}
21800 			if (save_ire != NULL)
21801 				IRE_REFRELE(save_ire);
21802 
21803 			if (first_ire != NULL)
21804 				ire_refrele(first_ire);
21805 			return;
21806 		} else {
21807 			xmit_mp->b_cont = mp;
21808 			/* Get priority marking, if any. */
21809 			if (DB_TYPE(xmit_mp) == M_DATA)
21810 				xmit_mp->b_band = mp->b_band;
21811 		}
21812 		UNLOCK_IRE_FP_MP(ire);
21813 		q = ire->ire_stq;
21814 		BUMP_MIB(&ip_mib, ipFragCreates);
21815 		putnext(q, xmit_mp);
21816 		if (pkt_type != OB_PKT) {
21817 			/*
21818 			 * Update the packet count of trailing
21819 			 * RTF_MULTIRT ires.
21820 			 */
21821 			UPDATE_OB_PKT_COUNT(ire);
21822 		}
21823 
21824 		if (multirt_send) {
21825 			/*
21826 			 * We are in a multiple send case; look for
21827 			 * the next ire and re-enter the loop.
21828 			 */
21829 			ASSERT(ire1);
21830 			ASSERT(next_mp);
21831 			/* REFRELE the current ire before looping */
21832 			ire_refrele(ire);
21833 			ire = ire1;
21834 			ire1 = NULL;
21835 			mp = next_mp;
21836 			next_mp = NULL;
21837 		}
21838 	} while (multirt_send);
21839 
21840 	ASSERT(ire1 == NULL);
21841 
21842 	/* Restore the original ire; we need it for the trailing frags */
21843 	if (save_ire != NULL) {
21844 		/* REFRELE the last iterated ire */
21845 		ire_refrele(ire);
21846 		/* save_ire has been REFHOLDed */
21847 		ire = save_ire;
21848 		save_ire = NULL;
21849 		q = ire->ire_stq;
21850 	}
21851 
21852 	if (pkt_type == OB_PKT) {
21853 		UPDATE_OB_PKT_COUNT(ire);
21854 	} else {
21855 		UPDATE_IB_PKT_COUNT(ire);
21856 	}
21857 
21858 	/* Advance the offset to the second frag starting point. */
21859 	offset += len;
21860 	/*
21861 	 * Update hdr_len from the copied header - there might be less options
21862 	 * in the later fragments.
21863 	 */
21864 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21865 	/* Loop until done. */
21866 	for (;;) {
21867 		uint16_t	offset_and_flags;
21868 		uint16_t	ip_len;
21869 
21870 		if (ip_data_end - offset > len) {
21871 			/*
21872 			 * Carve off the appropriate amount from the original
21873 			 * datagram.
21874 			 */
21875 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21876 				mp = NULL;
21877 				break;
21878 			}
21879 			/*
21880 			 * More frags after this one.  Get another copy
21881 			 * of the header.
21882 			 */
21883 			if (carve_mp->b_datap->db_ref == 1 &&
21884 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21885 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21886 				/* Inline IP header */
21887 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21888 				    hdr_mp->b_rptr;
21889 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21890 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21891 				mp = carve_mp;
21892 			} else {
21893 				if (!(mp = copyb(hdr_mp))) {
21894 					freemsg(carve_mp);
21895 					break;
21896 				}
21897 				/* Get priority marking, if any. */
21898 				mp->b_band = carve_mp->b_band;
21899 				mp->b_cont = carve_mp;
21900 			}
21901 			ipha = (ipha_t *)mp->b_rptr;
21902 			offset_and_flags = IPH_MF;
21903 		} else {
21904 			/*
21905 			 * Last frag.  Consume the header. Set len to
21906 			 * the length of this last piece.
21907 			 */
21908 			len = ip_data_end - offset;
21909 
21910 			/*
21911 			 * Carve off the appropriate amount from the original
21912 			 * datagram.
21913 			 */
21914 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21915 				mp = NULL;
21916 				break;
21917 			}
21918 			if (carve_mp->b_datap->db_ref == 1 &&
21919 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21920 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21921 				/* Inline IP header */
21922 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21923 				    hdr_mp->b_rptr;
21924 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21925 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21926 				mp = carve_mp;
21927 				freeb(hdr_mp);
21928 				hdr_mp = mp;
21929 			} else {
21930 				mp = hdr_mp;
21931 				/* Get priority marking, if any. */
21932 				mp->b_band = carve_mp->b_band;
21933 				mp->b_cont = carve_mp;
21934 			}
21935 			ipha = (ipha_t *)mp->b_rptr;
21936 			/* A frag of a frag might have IPH_MF non-zero */
21937 			offset_and_flags =
21938 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21939 			    IPH_MF;
21940 		}
21941 		offset_and_flags |= (uint16_t)(offset >> 3);
21942 		offset_and_flags |= (uint16_t)frag_flag;
21943 		/* Store the offset and flags in the IP header. */
21944 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21945 
21946 		/* Store the length in the IP header. */
21947 		ip_len = (uint16_t)(len + hdr_len);
21948 		ipha->ipha_length = htons(ip_len);
21949 
21950 		/*
21951 		 * Set the IP header checksum.	Note that mp is just
21952 		 * the header, so this is easy to pass to ip_csum.
21953 		 */
21954 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21955 
21956 		/* Attach a transmit header, if any, and ship it. */
21957 		if (pkt_type == OB_PKT) {
21958 			UPDATE_OB_PKT_COUNT(ire);
21959 		} else {
21960 			UPDATE_IB_PKT_COUNT(ire);
21961 		}
21962 
21963 		if (ire->ire_flags & RTF_MULTIRT) {
21964 			irb = ire->ire_bucket;
21965 			ASSERT(irb != NULL);
21966 
21967 			multirt_send = B_TRUE;
21968 
21969 			/*
21970 			 * Save the original ire; we will need to restore it
21971 			 * for the tailing frags.
21972 			 */
21973 			save_ire = ire;
21974 			IRE_REFHOLD(save_ire);
21975 		}
21976 		/*
21977 		 * Emission loop for this fragment, similar
21978 		 * to what is done for the first fragment.
21979 		 */
21980 		do {
21981 			if (multirt_send) {
21982 				/*
21983 				 * We are in a multiple send case, need to get
21984 				 * the next ire and make a copy of the packet.
21985 				 */
21986 				ASSERT(irb != NULL);
21987 				IRB_REFHOLD(irb);
21988 				for (ire1 = ire->ire_next;
21989 				    ire1 != NULL;
21990 				    ire1 = ire1->ire_next) {
21991 					if (!(ire1->ire_flags & RTF_MULTIRT))
21992 						continue;
21993 					if (ire1->ire_addr != ire->ire_addr)
21994 						continue;
21995 					if (ire1->ire_marks &
21996 					    (IRE_MARK_CONDEMNED|
21997 						IRE_MARK_HIDDEN))
21998 						continue;
21999 					/*
22000 					 * Ensure we do not exceed the MTU
22001 					 * of the next route.
22002 					 */
22003 					if (ire1->ire_max_frag < max_frag) {
22004 						ip_multirt_bad_mtu(ire1,
22005 						    max_frag);
22006 						continue;
22007 					}
22008 
22009 					/* Got one. */
22010 					IRE_REFHOLD(ire1);
22011 					break;
22012 				}
22013 				IRB_REFRELE(irb);
22014 
22015 				if (ire1 != NULL) {
22016 					next_mp = copyb(mp);
22017 					if ((next_mp == NULL) ||
22018 					    ((mp->b_cont != NULL) &&
22019 					    ((next_mp->b_cont =
22020 					    dupmsg(mp->b_cont)) == NULL))) {
22021 						freemsg(next_mp);
22022 						next_mp = NULL;
22023 						ire_refrele(ire1);
22024 						ire1 = NULL;
22025 					}
22026 				}
22027 
22028 				/* Last multiroute ire; don't loop anymore. */
22029 				if (ire1 == NULL) {
22030 					multirt_send = B_FALSE;
22031 				}
22032 			}
22033 
22034 			/* Update transmit header */
22035 			ll_hdr_len = 0;
22036 			LOCK_IRE_FP_MP(ire);
22037 			ll_hdr_mp = ire->ire_fp_mp;
22038 			if (ll_hdr_mp != NULL) {
22039 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22040 				ll_hdr_len = MBLKL(ll_hdr_mp);
22041 			} else {
22042 				ll_hdr_mp = ire->ire_dlureq_mp;
22043 			}
22044 
22045 			if (!ll_hdr_mp) {
22046 				xmit_mp = mp;
22047 			} else if (mp->b_datap->db_ref == 1 &&
22048 			    ll_hdr_len != 0 &&
22049 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22050 				/* M_DATA fastpath */
22051 				mp->b_rptr -= ll_hdr_len;
22052 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22053 				    ll_hdr_len);
22054 				xmit_mp = mp;
22055 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22056 				xmit_mp->b_cont = mp;
22057 				/* Get priority marking, if any. */
22058 				if (DB_TYPE(xmit_mp) == M_DATA)
22059 					xmit_mp->b_band = mp->b_band;
22060 			} else {
22061 				/*
22062 				 * Exit both the replication and
22063 				 * fragmentation loops.
22064 				 */
22065 				UNLOCK_IRE_FP_MP(ire);
22066 				goto drop_pkt;
22067 			}
22068 			UNLOCK_IRE_FP_MP(ire);
22069 			BUMP_MIB(&ip_mib, ipFragCreates);
22070 			putnext(q, xmit_mp);
22071 
22072 			if (pkt_type != OB_PKT) {
22073 				/*
22074 				 * Update the packet count of trailing
22075 				 * RTF_MULTIRT ires.
22076 				 */
22077 				UPDATE_OB_PKT_COUNT(ire);
22078 			}
22079 
22080 			/* All done if we just consumed the hdr_mp. */
22081 			if (mp == hdr_mp) {
22082 				last_frag = B_TRUE;
22083 			}
22084 
22085 			if (multirt_send) {
22086 				/*
22087 				 * We are in a multiple send case; look for
22088 				 * the next ire and re-enter the loop.
22089 				 */
22090 				ASSERT(ire1);
22091 				ASSERT(next_mp);
22092 				/* REFRELE the current ire before looping */
22093 				ire_refrele(ire);
22094 				ire = ire1;
22095 				ire1 = NULL;
22096 				q = ire->ire_stq;
22097 				mp = next_mp;
22098 				next_mp = NULL;
22099 			}
22100 		} while (multirt_send);
22101 		/*
22102 		 * Restore the original ire; we need it for the
22103 		 * trailing frags
22104 		 */
22105 		if (save_ire != NULL) {
22106 			ASSERT(ire1 == NULL);
22107 			/* REFRELE the last iterated ire */
22108 			ire_refrele(ire);
22109 			/* save_ire has been REFHOLDed */
22110 			ire = save_ire;
22111 			q = ire->ire_stq;
22112 			save_ire = NULL;
22113 		}
22114 
22115 		if (last_frag) {
22116 			BUMP_MIB(&ip_mib, ipFragOKs);
22117 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22118 			    "ip_wput_frag_end:(%S)",
22119 			    "consumed hdr_mp");
22120 
22121 			if (first_ire != NULL)
22122 				ire_refrele(first_ire);
22123 			return;
22124 		}
22125 		/* Otherwise, advance and loop. */
22126 		offset += len;
22127 	}
22128 
22129 drop_pkt:
22130 	/* Clean up following allocation failure. */
22131 	BUMP_MIB(&ip_mib, ipOutDiscards);
22132 	freemsg(mp);
22133 	if (mp != hdr_mp)
22134 		freeb(hdr_mp);
22135 	if (mp != mp_orig)
22136 		freemsg(mp_orig);
22137 
22138 	if (save_ire != NULL)
22139 		IRE_REFRELE(save_ire);
22140 	if (first_ire != NULL)
22141 		ire_refrele(first_ire);
22142 
22143 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22144 	    "ip_wput_frag_end:(%S)",
22145 	    "end--alloc failure");
22146 }
22147 
22148 /*
22149  * Copy the header plus those options which have the copy bit set
22150  */
22151 static mblk_t *
22152 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22153 {
22154 	mblk_t	*mp;
22155 	uchar_t	*up;
22156 
22157 	/*
22158 	 * Quick check if we need to look for options without the copy bit
22159 	 * set
22160 	 */
22161 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22162 	if (!mp)
22163 		return (mp);
22164 	mp->b_rptr += ip_wroff_extra;
22165 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22166 		bcopy(rptr, mp->b_rptr, hdr_len);
22167 		mp->b_wptr += hdr_len + ip_wroff_extra;
22168 		return (mp);
22169 	}
22170 	up  = mp->b_rptr;
22171 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22172 	up += IP_SIMPLE_HDR_LENGTH;
22173 	rptr += IP_SIMPLE_HDR_LENGTH;
22174 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22175 	while (hdr_len > 0) {
22176 		uint32_t optval;
22177 		uint32_t optlen;
22178 
22179 		optval = *rptr;
22180 		if (optval == IPOPT_EOL)
22181 			break;
22182 		if (optval == IPOPT_NOP)
22183 			optlen = 1;
22184 		else
22185 			optlen = rptr[1];
22186 		if (optval & IPOPT_COPY) {
22187 			bcopy(rptr, up, optlen);
22188 			up += optlen;
22189 		}
22190 		rptr += optlen;
22191 		hdr_len -= optlen;
22192 	}
22193 	/*
22194 	 * Make sure that we drop an even number of words by filling
22195 	 * with EOL to the next word boundary.
22196 	 */
22197 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
22198 	    hdr_len & 0x3; hdr_len++)
22199 		*up++ = IPOPT_EOL;
22200 	mp->b_wptr = up;
22201 	/* Update header length */
22202 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
22203 	return (mp);
22204 }
22205 
22206 /*
22207  * Delivery to local recipients including fanout to multiple recipients.
22208  * Does not do checksumming of UDP/TCP.
22209  * Note: q should be the read side queue for either the ill or conn.
22210  * Note: rq should be the read side q for the lower (ill) stream.
22211  * We don't send packets to IPPF processing, thus the last argument
22212  * to all the fanout calls are B_FALSE.
22213  */
22214 void
22215 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
22216     int fanout_flags, zoneid_t zoneid)
22217 {
22218 	uint32_t	protocol;
22219 	mblk_t		*first_mp;
22220 	boolean_t	mctl_present;
22221 	int		ire_type;
22222 #define	rptr	((uchar_t *)ipha)
22223 
22224 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
22225 	    "ip_wput_local_start: q %p", q);
22226 
22227 	if (ire != NULL) {
22228 		ire_type = ire->ire_type;
22229 	} else {
22230 		/*
22231 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
22232 		 * packet is not multicast, we can't tell the ire type.
22233 		 */
22234 		ASSERT(CLASSD(ipha->ipha_dst));
22235 		ire_type = IRE_BROADCAST;
22236 	}
22237 
22238 	first_mp = mp;
22239 	if (first_mp->b_datap->db_type == M_CTL) {
22240 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
22241 		if (!io->ipsec_out_secure) {
22242 			/*
22243 			 * This ipsec_out_t was allocated in ip_wput
22244 			 * for multicast packets to store the ill_index.
22245 			 * As this is being delivered locally, we don't
22246 			 * need this anymore.
22247 			 */
22248 			mp = first_mp->b_cont;
22249 			freeb(first_mp);
22250 			first_mp = mp;
22251 			mctl_present = B_FALSE;
22252 		} else {
22253 			mctl_present = B_TRUE;
22254 			mp = first_mp->b_cont;
22255 			ASSERT(mp != NULL);
22256 			ipsec_out_to_in(first_mp);
22257 		}
22258 	} else {
22259 		mctl_present = B_FALSE;
22260 	}
22261 
22262 	loopback_packets++;
22263 
22264 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
22265 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
22266 	if (!IS_SIMPLE_IPH(ipha)) {
22267 		ip_wput_local_options(ipha);
22268 	}
22269 
22270 	protocol = ipha->ipha_protocol;
22271 	switch (protocol) {
22272 	case IPPROTO_ICMP: {
22273 		ire_t		*ire_zone;
22274 		ilm_t		*ilm;
22275 		mblk_t		*mp1;
22276 		zoneid_t	last_zoneid;
22277 
22278 		if (CLASSD(ipha->ipha_dst) &&
22279 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
22280 			ASSERT(ire_type == IRE_BROADCAST);
22281 			/*
22282 			 * In the multicast case, applications may have joined
22283 			 * the group from different zones, so we need to deliver
22284 			 * the packet to each of them. Loop through the
22285 			 * multicast memberships structures (ilm) on the receive
22286 			 * ill and send a copy of the packet up each matching
22287 			 * one. However, we don't do this for multicasts sent on
22288 			 * the loopback interface (PHYI_LOOPBACK flag set) as
22289 			 * they must stay in the sender's zone.
22290 			 *
22291 			 * ilm_add_v6() ensures that ilms in the same zone are
22292 			 * contiguous in the ill_ilm list. We use this property
22293 			 * to avoid sending duplicates needed when two
22294 			 * applications in the same zone join the same group on
22295 			 * different logical interfaces: we ignore the ilm if
22296 			 * its zoneid is the same as the last matching one.
22297 			 * In addition, the sending of the packet for
22298 			 * ire_zoneid is delayed until all of the other ilms
22299 			 * have been exhausted.
22300 			 */
22301 			last_zoneid = -1;
22302 			ILM_WALKER_HOLD(ill);
22303 			for (ilm = ill->ill_ilm; ilm != NULL;
22304 			    ilm = ilm->ilm_next) {
22305 				if ((ilm->ilm_flags & ILM_DELETED) ||
22306 				    ipha->ipha_dst != ilm->ilm_addr ||
22307 				    ilm->ilm_zoneid == last_zoneid ||
22308 				    ilm->ilm_zoneid == zoneid ||
22309 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
22310 					continue;
22311 				mp1 = ip_copymsg(first_mp);
22312 				if (mp1 == NULL)
22313 					continue;
22314 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22315 				    mctl_present, B_FALSE, ill,
22316 				    ilm->ilm_zoneid);
22317 				last_zoneid = ilm->ilm_zoneid;
22318 			}
22319 			ILM_WALKER_RELE(ill);
22320 			/*
22321 			 * Loopback case: the sending endpoint has
22322 			 * IP_MULTICAST_LOOP disabled, therefore we don't
22323 			 * dispatch the multicast packet to the sending zone.
22324 			 */
22325 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
22326 				freemsg(first_mp);
22327 				return;
22328 			}
22329 		} else if (ire_type == IRE_BROADCAST) {
22330 			/*
22331 			 * In the broadcast case, there may be many zones
22332 			 * which need a copy of the packet delivered to them.
22333 			 * There is one IRE_BROADCAST per broadcast address
22334 			 * and per zone; we walk those using a helper function.
22335 			 * In addition, the sending of the packet for zoneid is
22336 			 * delayed until all of the other ires have been
22337 			 * processed.
22338 			 */
22339 			IRB_REFHOLD(ire->ire_bucket);
22340 			ire_zone = NULL;
22341 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
22342 			    ire)) != NULL) {
22343 				mp1 = ip_copymsg(first_mp);
22344 				if (mp1 == NULL)
22345 					continue;
22346 
22347 				UPDATE_IB_PKT_COUNT(ire_zone);
22348 				ire_zone->ire_last_used_time = lbolt;
22349 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22350 				    mctl_present, B_FALSE, ill,
22351 				    ire_zone->ire_zoneid);
22352 			}
22353 			IRB_REFRELE(ire->ire_bucket);
22354 		}
22355 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
22356 		    0, mctl_present, B_FALSE, ill, zoneid);
22357 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22358 		    "ip_wput_local_end: q %p (%S)",
22359 		    q, "icmp");
22360 		return;
22361 	}
22362 	case IPPROTO_IGMP:
22363 		if (igmp_input(q, mp, ill)) {
22364 			/* Bad packet - discarded by igmp_input */
22365 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22366 			    "ip_wput_local_end: q %p (%S)",
22367 			    q, "igmp_input--bad packet");
22368 			if (mctl_present)
22369 				freeb(first_mp);
22370 			return;
22371 		}
22372 		/*
22373 		 * igmp_input() may have pulled up the message so ipha needs to
22374 		 * be reinitialized.
22375 		 */
22376 		ipha = (ipha_t *)mp->b_rptr;
22377 		/* deliver to local raw users */
22378 		break;
22379 	case IPPROTO_ENCAP:
22380 		/*
22381 		 * This case is covered by either ip_fanout_proto, or by
22382 		 * the above security processing for self-tunneled packets.
22383 		 */
22384 		break;
22385 	case IPPROTO_UDP: {
22386 		uint16_t	*up;
22387 		uint32_t	ports;
22388 
22389 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
22390 		    UDP_PORTS_OFFSET);
22391 		/* Force a 'valid' checksum. */
22392 		up[3] = 0;
22393 
22394 		ports = *(uint32_t *)up;
22395 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
22396 		    (ire_type == IRE_BROADCAST),
22397 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22398 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
22399 		    ill, zoneid);
22400 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22401 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
22402 		return;
22403 	}
22404 	case IPPROTO_TCP: {
22405 
22406 		/*
22407 		 * For TCP, discard broadcast packets.
22408 		 */
22409 		if ((ushort_t)ire_type == IRE_BROADCAST) {
22410 			freemsg(first_mp);
22411 			BUMP_MIB(&ip_mib, ipInDiscards);
22412 			return;
22413 		}
22414 
22415 		if (mp->b_datap->db_type == M_DATA) {
22416 			/*
22417 			 * M_DATA mblk, so init mblk (chain) for no struio().
22418 			 */
22419 			mblk_t	*mp1 = mp;
22420 
22421 			do
22422 				mp1->b_datap->db_struioflag = 0;
22423 			while ((mp1 = mp1->b_cont) != NULL);
22424 		}
22425 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
22426 		    <= mp->b_wptr);
22427 		ip_fanout_tcp(q, first_mp, ill, ipha,
22428 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22429 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
22430 		    mctl_present, B_FALSE, zoneid);
22431 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22432 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
22433 		return;
22434 	}
22435 	case IPPROTO_SCTP:
22436 	{
22437 		uint32_t	ports;
22438 
22439 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
22440 		ip_fanout_sctp(first_mp, ill, ipha, ports,
22441 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22442 		    IP_FF_IP6INFO,
22443 		    mctl_present, B_FALSE, 0, zoneid);
22444 		return;
22445 	}
22446 
22447 	default:
22448 		break;
22449 	}
22450 	/*
22451 	 * Find a client for some other protocol.  We give
22452 	 * copies to multiple clients, if more than one is
22453 	 * bound.
22454 	 */
22455 	ip_fanout_proto(q, first_mp, ill, ipha,
22456 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
22457 	    mctl_present, B_FALSE, ill, zoneid);
22458 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22459 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
22460 #undef	rptr
22461 }
22462 
22463 /*
22464  * Update any source route, record route, or timestamp options.
22465  * Check that we are at end of strict source route.
22466  * The options have been sanity checked by ip_wput_options().
22467  */
22468 static void
22469 ip_wput_local_options(ipha_t *ipha)
22470 {
22471 	ipoptp_t	opts;
22472 	uchar_t		*opt;
22473 	uint8_t		optval;
22474 	uint8_t		optlen;
22475 	ipaddr_t	dst;
22476 	uint32_t	ts;
22477 	ire_t		*ire;
22478 	timestruc_t	now;
22479 
22480 	ip2dbg(("ip_wput_local_options\n"));
22481 	for (optval = ipoptp_first(&opts, ipha);
22482 	    optval != IPOPT_EOL;
22483 	    optval = ipoptp_next(&opts)) {
22484 		opt = opts.ipoptp_cur;
22485 		optlen = opts.ipoptp_len;
22486 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22487 		switch (optval) {
22488 			uint32_t off;
22489 		case IPOPT_SSRR:
22490 		case IPOPT_LSRR:
22491 			off = opt[IPOPT_OFFSET];
22492 			off--;
22493 			if (optlen < IP_ADDR_LEN ||
22494 			    off > optlen - IP_ADDR_LEN) {
22495 				/* End of source route */
22496 				break;
22497 			}
22498 			/*
22499 			 * This will only happen if two consecutive entries
22500 			 * in the source route contains our address or if
22501 			 * it is a packet with a loose source route which
22502 			 * reaches us before consuming the whole source route
22503 			 */
22504 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22505 			if (optval == IPOPT_SSRR) {
22506 				return;
22507 			}
22508 			/*
22509 			 * Hack: instead of dropping the packet truncate the
22510 			 * source route to what has been used by filling the
22511 			 * rest with IPOPT_NOP.
22512 			 */
22513 			opt[IPOPT_OLEN] = (uint8_t)off;
22514 			while (off < optlen) {
22515 				opt[off++] = IPOPT_NOP;
22516 			}
22517 			break;
22518 		case IPOPT_RR:
22519 			off = opt[IPOPT_OFFSET];
22520 			off--;
22521 			if (optlen < IP_ADDR_LEN ||
22522 			    off > optlen - IP_ADDR_LEN) {
22523 				/* No more room - ignore */
22524 				ip1dbg((
22525 				    "ip_wput_forward_options: end of RR\n"));
22526 				break;
22527 			}
22528 			dst = htonl(INADDR_LOOPBACK);
22529 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22530 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22531 			break;
22532 		case IPOPT_TS:
22533 			/* Insert timestamp if there is romm */
22534 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22535 			case IPOPT_TS_TSONLY:
22536 				off = IPOPT_TS_TIMELEN;
22537 				break;
22538 			case IPOPT_TS_PRESPEC:
22539 			case IPOPT_TS_PRESPEC_RFC791:
22540 				/* Verify that the address matched */
22541 				off = opt[IPOPT_OFFSET] - 1;
22542 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22543 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22544 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22545 				if (ire == NULL) {
22546 					/* Not for us */
22547 					break;
22548 				}
22549 				ire_refrele(ire);
22550 				/* FALLTHRU */
22551 			case IPOPT_TS_TSANDADDR:
22552 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22553 				break;
22554 			default:
22555 				/*
22556 				 * ip_*put_options should have already
22557 				 * dropped this packet.
22558 				 */
22559 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22560 				    "unknown IT - bug in ip_wput_options?\n");
22561 				return;	/* Keep "lint" happy */
22562 			}
22563 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22564 				/* Increase overflow counter */
22565 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22566 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22567 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22568 				    (off << 4);
22569 				break;
22570 			}
22571 			off = opt[IPOPT_OFFSET] - 1;
22572 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22573 			case IPOPT_TS_PRESPEC:
22574 			case IPOPT_TS_PRESPEC_RFC791:
22575 			case IPOPT_TS_TSANDADDR:
22576 				dst = htonl(INADDR_LOOPBACK);
22577 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22578 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22579 				/* FALLTHRU */
22580 			case IPOPT_TS_TSONLY:
22581 				off = opt[IPOPT_OFFSET] - 1;
22582 				/* Compute # of milliseconds since midnight */
22583 				gethrestime(&now);
22584 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22585 				    now.tv_nsec / (NANOSEC / MILLISEC);
22586 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22587 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22588 				break;
22589 			}
22590 			break;
22591 		}
22592 	}
22593 }
22594 
22595 /*
22596  * Send out a multicast packet on interface ipif.
22597  * The sender does not have an conn.
22598  * Caller verifies that this isn't a PHYI_LOOPBACK.
22599  */
22600 void
22601 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22602 {
22603 	ipha_t	*ipha;
22604 	ire_t	*ire;
22605 	ipaddr_t	dst;
22606 	mblk_t		*first_mp;
22607 
22608 	/* igmp_sendpkt always allocates a ipsec_out_t */
22609 	ASSERT(mp->b_datap->db_type == M_CTL);
22610 	ASSERT(!ipif->ipif_isv6);
22611 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22612 
22613 	first_mp = mp;
22614 	mp = first_mp->b_cont;
22615 	ASSERT(mp->b_datap->db_type == M_DATA);
22616 	ipha = (ipha_t *)mp->b_rptr;
22617 
22618 	/*
22619 	 * Find an IRE which matches the destination and the outgoing
22620 	 * queue (i.e. the outgoing interface.)
22621 	 */
22622 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22623 		dst = ipif->ipif_pp_dst_addr;
22624 	else
22625 		dst = ipha->ipha_dst;
22626 	/*
22627 	 * The source address has already been initialized by the
22628 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22629 	 * be sufficient rather than MATCH_IRE_IPIF.
22630 	 *
22631 	 * This function is used for sending IGMP packets. We need
22632 	 * to make sure that we send the packet out of the interface
22633 	 * (ipif->ipif_ill) where we joined the group. This is to
22634 	 * prevent from switches doing IGMP snooping to send us multicast
22635 	 * packets for a given group on the interface we have joined.
22636 	 * If we can't find an ire, igmp_sendpkt has already initialized
22637 	 * ipsec_out_attach_if so that this will not be load spread in
22638 	 * ip_newroute_ipif.
22639 	 */
22640 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22641 	if (!ire) {
22642 		/*
22643 		 * Mark this packet to make it be delivered to
22644 		 * ip_wput_ire after the new ire has been
22645 		 * created.
22646 		 */
22647 		mp->b_prev = NULL;
22648 		mp->b_next = NULL;
22649 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22650 		return;
22651 	}
22652 
22653 	/*
22654 	 * Honor the RTF_SETSRC flag; this is the only case
22655 	 * where we force this addr whatever the current src addr is,
22656 	 * because this address is set by igmp_sendpkt(), and
22657 	 * cannot be specified by any user.
22658 	 */
22659 	if (ire->ire_flags & RTF_SETSRC) {
22660 		ipha->ipha_src = ire->ire_src_addr;
22661 	}
22662 
22663 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22664 }
22665 
22666 /*
22667  * NOTE : This function does not ire_refrele the ire argument passed in.
22668  *
22669  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22670  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22671  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22672  * the ire_lock to access the ire_fp_mp in this case.
22673  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22674  * prepending a fastpath message IPQoS processing must precede it, we also set
22675  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22676  * (IPQoS might have set the b_band for CoS marking).
22677  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22678  * must follow it so that IPQoS can mark the dl_priority field for CoS
22679  * marking, if needed.
22680  */
22681 static mblk_t *
22682 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22683 {
22684 	uint_t	hlen;
22685 	ipha_t *ipha;
22686 	mblk_t *mp1;
22687 	boolean_t qos_done = B_FALSE;
22688 	uchar_t	*ll_hdr;
22689 
22690 #define	rptr	((uchar_t *)ipha)
22691 
22692 	ipha = (ipha_t *)mp->b_rptr;
22693 	hlen = 0;
22694 	LOCK_IRE_FP_MP(ire);
22695 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22696 		ASSERT(DB_TYPE(mp1) == M_DATA);
22697 		/* Initiate IPPF processing */
22698 		if ((proc != 0) && IPP_ENABLED(proc)) {
22699 			UNLOCK_IRE_FP_MP(ire);
22700 			ip_process(proc, &mp, ill_index);
22701 			if (mp == NULL)
22702 				return (NULL);
22703 
22704 			ipha = (ipha_t *)mp->b_rptr;
22705 			LOCK_IRE_FP_MP(ire);
22706 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22707 				qos_done = B_TRUE;
22708 				goto no_fp_mp;
22709 			}
22710 			ASSERT(DB_TYPE(mp1) == M_DATA);
22711 		}
22712 		hlen = MBLKL(mp1);
22713 		/*
22714 		 * Check if we have enough room to prepend fastpath
22715 		 * header
22716 		 */
22717 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22718 			ll_hdr = rptr - hlen;
22719 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22720 			/* XXX ipha is not aligned here */
22721 			ipha = (ipha_t *)(rptr - hlen);
22722 			/*
22723 			 * Set the b_rptr to the start of the link layer
22724 			 * header
22725 			 */
22726 			mp->b_rptr = rptr;
22727 			mp1 = mp;
22728 		} else {
22729 			mp1 = copyb(mp1);
22730 			if (mp1 == NULL)
22731 				goto unlock_err;
22732 			mp1->b_band = mp->b_band;
22733 			mp1->b_cont = mp;
22734 			/*
22735 			 * XXX disable ICK_VALID and compute checksum
22736 			 * here; can happen if ire_fp_mp changes and
22737 			 * it can't be copied now due to insufficient
22738 			 * space. (unlikely, fp mp can change, but it
22739 			 * does not increase in length)
22740 			 */
22741 		}
22742 		UNLOCK_IRE_FP_MP(ire);
22743 	} else {
22744 no_fp_mp:
22745 		mp1 = copyb(ire->ire_dlureq_mp);
22746 		if (mp1 == NULL) {
22747 unlock_err:
22748 			UNLOCK_IRE_FP_MP(ire);
22749 			freemsg(mp);
22750 			return (NULL);
22751 		}
22752 		UNLOCK_IRE_FP_MP(ire);
22753 		mp1->b_cont = mp;
22754 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22755 			ip_process(proc, &mp1, ill_index);
22756 			if (mp1 == NULL)
22757 				return (NULL);
22758 		}
22759 	}
22760 	return (mp1);
22761 #undef rptr
22762 }
22763 
22764 /*
22765  * Finish the outbound IPsec processing for an IPv6 packet. This function
22766  * is called from ipsec_out_process() if the IPsec packet was processed
22767  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22768  * asynchronously.
22769  */
22770 void
22771 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22772     ire_t *ire_arg)
22773 {
22774 	in6_addr_t *v6dstp;
22775 	ire_t *ire;
22776 	mblk_t *mp;
22777 	uint_t	ill_index;
22778 	ipsec_out_t *io;
22779 	boolean_t attach_if, hwaccel;
22780 	uint32_t flags = IP6_NO_IPPOLICY;
22781 	int match_flags;
22782 	zoneid_t zoneid;
22783 	boolean_t ill_need_rele = B_FALSE;
22784 	boolean_t ire_need_rele = B_FALSE;
22785 
22786 	mp = ipsec_mp->b_cont;
22787 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22788 	ill_index = io->ipsec_out_ill_index;
22789 	if (io->ipsec_out_reachable) {
22790 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22791 	}
22792 	attach_if = io->ipsec_out_attach_if;
22793 	hwaccel = io->ipsec_out_accelerated;
22794 	zoneid = io->ipsec_out_zoneid;
22795 	ASSERT(zoneid != ALL_ZONES);
22796 	match_flags = MATCH_IRE_ILL_GROUP;
22797 	/* Multicast addresses should have non-zero ill_index. */
22798 	v6dstp = &ip6h->ip6_dst;
22799 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22800 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22801 	ASSERT(!attach_if || ill_index != 0);
22802 	if (ill_index != 0) {
22803 		if (ill == NULL) {
22804 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22805 			    B_TRUE);
22806 
22807 			/* Failure case frees things for us. */
22808 			if (ill == NULL)
22809 				return;
22810 
22811 			ill_need_rele = B_TRUE;
22812 		}
22813 		/*
22814 		 * If this packet needs to go out on a particular interface
22815 		 * honor it.
22816 		 */
22817 		if (attach_if) {
22818 			match_flags = MATCH_IRE_ILL;
22819 
22820 			/*
22821 			 * Check if we need an ire that will not be
22822 			 * looked up by anybody else i.e. HIDDEN.
22823 			 */
22824 			if (ill_is_probeonly(ill)) {
22825 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22826 			}
22827 		}
22828 	}
22829 	ASSERT(mp != NULL);
22830 
22831 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22832 		boolean_t unspec_src;
22833 		ipif_t	*ipif;
22834 
22835 		/*
22836 		 * Use the ill_index to get the right ill.
22837 		 */
22838 		unspec_src = io->ipsec_out_unspec_src;
22839 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22840 		if (ipif == NULL) {
22841 			if (ill_need_rele)
22842 				ill_refrele(ill);
22843 			freemsg(ipsec_mp);
22844 			return;
22845 		}
22846 
22847 		if (ire_arg != NULL) {
22848 			ire = ire_arg;
22849 		} else {
22850 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22851 			    zoneid, match_flags);
22852 			ire_need_rele = B_TRUE;
22853 		}
22854 		if (ire != NULL) {
22855 			ipif_refrele(ipif);
22856 			/*
22857 			 * XXX Do the multicast forwarding now, as the IPSEC
22858 			 * processing has been done.
22859 			 */
22860 			goto send;
22861 		}
22862 
22863 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22864 		mp->b_prev = NULL;
22865 		mp->b_next = NULL;
22866 
22867 		/*
22868 		 * If the IPsec packet was processed asynchronously,
22869 		 * drop it now.
22870 		 */
22871 		if (q == NULL) {
22872 			if (ill_need_rele)
22873 				ill_refrele(ill);
22874 			freemsg(ipsec_mp);
22875 			return;
22876 		}
22877 
22878 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22879 		    unspec_src, zoneid);
22880 		ipif_refrele(ipif);
22881 	} else {
22882 		if (attach_if) {
22883 			ipif_t	*ipif;
22884 
22885 			ipif = ipif_get_next_ipif(NULL, ill);
22886 			if (ipif == NULL) {
22887 				if (ill_need_rele)
22888 					ill_refrele(ill);
22889 				freemsg(ipsec_mp);
22890 				return;
22891 			}
22892 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22893 			    zoneid, match_flags);
22894 			ire_need_rele = B_TRUE;
22895 			ipif_refrele(ipif);
22896 		} else {
22897 			if (ire_arg != NULL) {
22898 				ire = ire_arg;
22899 			} else {
22900 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22901 				ire_need_rele = B_TRUE;
22902 			}
22903 		}
22904 		if (ire != NULL)
22905 			goto send;
22906 		/*
22907 		 * ire disappeared underneath.
22908 		 *
22909 		 * What we need to do here is the ip_newroute
22910 		 * logic to get the ire without doing the IPSEC
22911 		 * processing. Follow the same old path. But this
22912 		 * time, ip_wput or ire_add_then_send will call us
22913 		 * directly as all the IPSEC operations are done.
22914 		 */
22915 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22916 		mp->b_prev = NULL;
22917 		mp->b_next = NULL;
22918 
22919 		/*
22920 		 * If the IPsec packet was processed asynchronously,
22921 		 * drop it now.
22922 		 */
22923 		if (q == NULL) {
22924 			if (ill_need_rele)
22925 				ill_refrele(ill);
22926 			freemsg(ipsec_mp);
22927 			return;
22928 		}
22929 
22930 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22931 		    zoneid);
22932 	}
22933 	if (ill != NULL && ill_need_rele)
22934 		ill_refrele(ill);
22935 	return;
22936 send:
22937 	if (ill != NULL && ill_need_rele)
22938 		ill_refrele(ill);
22939 
22940 	/* Local delivery */
22941 	if (ire->ire_stq == NULL) {
22942 		ASSERT(q != NULL);
22943 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22944 		    ire, 0);
22945 		if (ire_need_rele)
22946 			ire_refrele(ire);
22947 		return;
22948 	}
22949 	/*
22950 	 * Everything is done. Send it out on the wire.
22951 	 * We force the insertion of a fragment header using the
22952 	 * IPH_FRAG_HDR flag in two cases:
22953 	 * - after reception of an ICMPv6 "packet too big" message
22954 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22955 	 * - for multirouted IPv6 packets, so that the receiver can
22956 	 *   discard duplicates according to their fragment identifier
22957 	 */
22958 	/* XXX fix flow control problems. */
22959 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22960 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22961 		if (hwaccel) {
22962 			/*
22963 			 * hardware acceleration does not handle these
22964 			 * "slow path" cases.
22965 			 */
22966 			/* IPsec KSTATS: should bump bean counter here. */
22967 			if (ire_need_rele)
22968 				ire_refrele(ire);
22969 			freemsg(ipsec_mp);
22970 			return;
22971 		}
22972 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22973 		    (mp->b_cont ? msgdsize(mp) :
22974 		    mp->b_wptr - (uchar_t *)ip6h)) {
22975 			/* IPsec KSTATS: should bump bean counter here. */
22976 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22977 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22978 			    msgdsize(mp)));
22979 			if (ire_need_rele)
22980 				ire_refrele(ire);
22981 			freemsg(ipsec_mp);
22982 			return;
22983 		}
22984 		ASSERT(mp->b_prev == NULL);
22985 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22986 		    ntohs(ip6h->ip6_plen) +
22987 		    IPV6_HDR_LEN, ire->ire_max_frag));
22988 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22989 		    ire->ire_max_frag);
22990 	} else {
22991 		UPDATE_OB_PKT_COUNT(ire);
22992 		ire->ire_last_used_time = lbolt;
22993 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22994 	}
22995 	if (ire_need_rele)
22996 		ire_refrele(ire);
22997 	freeb(ipsec_mp);
22998 }
22999 
23000 void
23001 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23002 {
23003 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23004 	da_ipsec_t *hada;	/* data attributes */
23005 	ill_t *ill = (ill_t *)q->q_ptr;
23006 
23007 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23008 
23009 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23010 		/* IPsec KSTATS: Bump lose counter here! */
23011 		freemsg(mp);
23012 		return;
23013 	}
23014 
23015 	/*
23016 	 * It's an IPsec packet that must be
23017 	 * accelerated by the Provider, and the
23018 	 * outbound ill is IPsec acceleration capable.
23019 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23020 	 * to the ill.
23021 	 * IPsec KSTATS: should bump packet counter here.
23022 	 */
23023 
23024 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23025 	if (hada_mp == NULL) {
23026 		/* IPsec KSTATS: should bump packet counter here. */
23027 		freemsg(mp);
23028 		return;
23029 	}
23030 
23031 	hada_mp->b_datap->db_type = M_CTL;
23032 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23033 	hada_mp->b_cont = mp;
23034 
23035 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23036 	bzero(hada, sizeof (da_ipsec_t));
23037 	hada->da_type = IPHADA_M_CTL;
23038 
23039 	putnext(q, hada_mp);
23040 }
23041 
23042 /*
23043  * Finish the outbound IPsec processing. This function is called from
23044  * ipsec_out_process() if the IPsec packet was processed
23045  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23046  * asynchronously.
23047  */
23048 void
23049 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23050     ire_t *ire_arg)
23051 {
23052 	uint32_t v_hlen_tos_len;
23053 	ipaddr_t	dst;
23054 	ipif_t	*ipif = NULL;
23055 	ire_t *ire;
23056 	ire_t *ire1 = NULL;
23057 	mblk_t *next_mp = NULL;
23058 	uint32_t max_frag;
23059 	boolean_t multirt_send = B_FALSE;
23060 	mblk_t *mp;
23061 	mblk_t *mp1;
23062 	uint_t	ill_index;
23063 	ipsec_out_t *io;
23064 	boolean_t attach_if;
23065 	int match_flags, offset;
23066 	irb_t *irb = NULL;
23067 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23068 	zoneid_t zoneid;
23069 	uint32_t cksum;
23070 	uint16_t *up;
23071 #ifdef	_BIG_ENDIAN
23072 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23073 #else
23074 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23075 #endif
23076 
23077 	mp = ipsec_mp->b_cont;
23078 	ASSERT(mp != NULL);
23079 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23080 	dst = ipha->ipha_dst;
23081 
23082 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23083 	ill_index = io->ipsec_out_ill_index;
23084 	attach_if = io->ipsec_out_attach_if;
23085 	zoneid = io->ipsec_out_zoneid;
23086 	ASSERT(zoneid != ALL_ZONES);
23087 	match_flags = MATCH_IRE_ILL_GROUP;
23088 	if (ill_index != 0) {
23089 		if (ill == NULL) {
23090 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23091 			    ill_index, B_FALSE);
23092 
23093 			/* Failure case frees things for us. */
23094 			if (ill == NULL)
23095 				return;
23096 
23097 			ill_need_rele = B_TRUE;
23098 		}
23099 		/*
23100 		 * If this packet needs to go out on a particular interface
23101 		 * honor it.
23102 		 */
23103 		if (attach_if) {
23104 			match_flags = MATCH_IRE_ILL;
23105 
23106 			/*
23107 			 * Check if we need an ire that will not be
23108 			 * looked up by anybody else i.e. HIDDEN.
23109 			 */
23110 			if (ill_is_probeonly(ill)) {
23111 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23112 			}
23113 		}
23114 	}
23115 
23116 	if (CLASSD(dst)) {
23117 		boolean_t conn_dontroute;
23118 		/*
23119 		 * Use the ill_index to get the right ipif.
23120 		 */
23121 		conn_dontroute = io->ipsec_out_dontroute;
23122 		if (ill_index == 0)
23123 			ipif = ipif_lookup_group(dst, zoneid);
23124 		else
23125 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23126 		if (ipif == NULL) {
23127 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23128 			    " multicast\n"));
23129 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23130 			freemsg(ipsec_mp);
23131 			goto done;
23132 		}
23133 		/*
23134 		 * ipha_src has already been intialized with the
23135 		 * value of the ipif in ip_wput. All we need now is
23136 		 * an ire to send this downstream.
23137 		 */
23138 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
23139 		if (ire != NULL) {
23140 			ill_t *ill1;
23141 			/*
23142 			 * Do the multicast forwarding now, as the IPSEC
23143 			 * processing has been done.
23144 			 */
23145 			if (ip_g_mrouter && !conn_dontroute &&
23146 			    (ill1 = ire_to_ill(ire))) {
23147 				if (ip_mforward(ill1, ipha, mp)) {
23148 					freemsg(ipsec_mp);
23149 					ip1dbg(("ip_wput_ipsec_out: mforward "
23150 					    "failed\n"));
23151 					ire_refrele(ire);
23152 					goto done;
23153 				}
23154 			}
23155 			goto send;
23156 		}
23157 
23158 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23159 		mp->b_prev = NULL;
23160 		mp->b_next = NULL;
23161 
23162 		/*
23163 		 * If the IPsec packet was processed asynchronously,
23164 		 * drop it now.
23165 		 */
23166 		if (q == NULL) {
23167 			freemsg(ipsec_mp);
23168 			goto done;
23169 		}
23170 
23171 		/*
23172 		 * We may be using a wrong ipif to create the ire.
23173 		 * But it is okay as the source address is assigned
23174 		 * for the packet already. Next outbound packet would
23175 		 * create the IRE with the right IPIF in ip_wput.
23176 		 *
23177 		 * Also handle RTF_MULTIRT routes.
23178 		 */
23179 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
23180 	} else {
23181 		if (attach_if) {
23182 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
23183 			    zoneid, match_flags);
23184 		} else {
23185 			if (ire_arg != NULL) {
23186 				ire = ire_arg;
23187 				ire_need_rele = B_FALSE;
23188 			} else {
23189 				ire = ire_cache_lookup(dst, zoneid);
23190 			}
23191 		}
23192 		if (ire != NULL) {
23193 			goto send;
23194 		}
23195 
23196 		/*
23197 		 * ire disappeared underneath.
23198 		 *
23199 		 * What we need to do here is the ip_newroute
23200 		 * logic to get the ire without doing the IPSEC
23201 		 * processing. Follow the same old path. But this
23202 		 * time, ip_wput or ire_add_then_put will call us
23203 		 * directly as all the IPSEC operations are done.
23204 		 */
23205 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
23206 		mp->b_prev = NULL;
23207 		mp->b_next = NULL;
23208 
23209 		/*
23210 		 * If the IPsec packet was processed asynchronously,
23211 		 * drop it now.
23212 		 */
23213 		if (q == NULL) {
23214 			freemsg(ipsec_mp);
23215 			goto done;
23216 		}
23217 
23218 		/*
23219 		 * Since we're going through ip_newroute() again, we
23220 		 * need to make sure we don't:
23221 		 *
23222 		 *	1.) Trigger the ASSERT() with the ipha_ident
23223 		 *	    overloading.
23224 		 *	2.) Redo transport-layer checksumming, since we've
23225 		 *	    already done all that to get this far.
23226 		 *
23227 		 * The easiest way not do either of the above is to set
23228 		 * the ipha_ident field to IP_HDR_INCLUDED.
23229 		 */
23230 		ipha->ipha_ident = IP_HDR_INCLUDED;
23231 		ip_newroute(q, ipsec_mp, dst, NULL,
23232 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
23233 	}
23234 	goto done;
23235 send:
23236 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
23237 		/*
23238 		 * ESP NAT-Traversal packet.
23239 		 *
23240 		 * Just do software checksum for now.
23241 		 */
23242 
23243 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
23244 		IP_STAT(ip_out_sw_cksum);
23245 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
23246 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
23247 #define	iphs	((uint16_t *)ipha)
23248 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
23249 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
23250 		    IP_SIMPLE_HDR_LENGTH);
23251 #undef iphs
23252 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
23253 			cksum = 0xFFFF;
23254 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
23255 			if (mp1->b_wptr - mp1->b_rptr >=
23256 			    offset + sizeof (uint16_t)) {
23257 				up = (uint16_t *)(mp1->b_rptr + offset);
23258 				*up = cksum;
23259 				break;	/* out of for loop */
23260 			} else {
23261 				offset -= (mp->b_wptr - mp->b_rptr);
23262 			}
23263 	} /* Otherwise, just keep the all-zero checksum. */
23264 
23265 	if (ire->ire_stq == NULL) {
23266 		/*
23267 		 * Loopbacks go through ip_wput_local except for one case.
23268 		 * We come here if we generate a icmp_frag_needed message
23269 		 * after IPSEC processing is over. When this function calls
23270 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
23271 		 * icmp_frag_needed. The message generated comes back here
23272 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
23273 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
23274 		 * source address as it is usually set in ip_wput_ire. As
23275 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
23276 		 * and we end up here. We can't enter ip_wput_ire once the
23277 		 * IPSEC processing is over and hence we need to do it here.
23278 		 */
23279 		ASSERT(q != NULL);
23280 		UPDATE_OB_PKT_COUNT(ire);
23281 		ire->ire_last_used_time = lbolt;
23282 		if (ipha->ipha_src == 0)
23283 			ipha->ipha_src = ire->ire_src_addr;
23284 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
23285 		    ire, 0, zoneid);
23286 		if (ire_need_rele)
23287 			ire_refrele(ire);
23288 		goto done;
23289 	}
23290 
23291 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
23292 		/*
23293 		 * We are through with IPSEC processing.
23294 		 * Fragment this and send it on the wire.
23295 		 */
23296 		if (io->ipsec_out_accelerated) {
23297 			/*
23298 			 * The packet has been accelerated but must
23299 			 * be fragmented. This should not happen
23300 			 * since AH and ESP must not accelerate
23301 			 * packets that need fragmentation, however
23302 			 * the configuration could have changed
23303 			 * since the AH or ESP processing.
23304 			 * Drop packet.
23305 			 * IPsec KSTATS: bump bean counter here.
23306 			 */
23307 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
23308 			    "fragmented accelerated packet!\n"));
23309 			freemsg(ipsec_mp);
23310 		} else {
23311 			ip_wput_ire_fragmentit(ipsec_mp, ire);
23312 		}
23313 		if (ire_need_rele)
23314 			ire_refrele(ire);
23315 		goto done;
23316 	}
23317 
23318 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
23319 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
23320 	    (void *)ire->ire_ipif, (void *)ipif));
23321 
23322 	/*
23323 	 * Multiroute the secured packet, unless IPsec really
23324 	 * requires the packet to go out only through a particular
23325 	 * interface.
23326 	 */
23327 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
23328 		ire_t *first_ire;
23329 		irb = ire->ire_bucket;
23330 		ASSERT(irb != NULL);
23331 		/*
23332 		 * This ire has been looked up as the one that
23333 		 * goes through the given ipif;
23334 		 * make sure we do not omit any other multiroute ire
23335 		 * that may be present in the bucket before this one.
23336 		 */
23337 		IRB_REFHOLD(irb);
23338 		for (first_ire = irb->irb_ire;
23339 		    first_ire != NULL;
23340 		    first_ire = first_ire->ire_next) {
23341 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23342 			    (first_ire->ire_addr == ire->ire_addr) &&
23343 			    !(first_ire->ire_marks &
23344 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23345 				break;
23346 		}
23347 
23348 		if ((first_ire != NULL) && (first_ire != ire)) {
23349 			/*
23350 			 * Don't change the ire if the packet must
23351 			 * be fragmented if sent via this new one.
23352 			 */
23353 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
23354 				IRE_REFHOLD(first_ire);
23355 				if (ire_need_rele)
23356 					ire_refrele(ire);
23357 				else
23358 					ire_need_rele = B_TRUE;
23359 				ire = first_ire;
23360 			}
23361 		}
23362 		IRB_REFRELE(irb);
23363 
23364 		multirt_send = B_TRUE;
23365 		max_frag = ire->ire_max_frag;
23366 	} else {
23367 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
23368 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
23369 			    "flag, attach_if %d\n", attach_if));
23370 		}
23371 	}
23372 
23373 	/*
23374 	 * In most cases, the emission loop below is entered only once.
23375 	 * Only in the case where the ire holds the RTF_MULTIRT
23376 	 * flag, we loop to process all RTF_MULTIRT ires in the
23377 	 * bucket, and send the packet through all crossed
23378 	 * RTF_MULTIRT routes.
23379 	 */
23380 	do {
23381 		if (multirt_send) {
23382 			/*
23383 			 * ire1 holds here the next ire to process in the
23384 			 * bucket. If multirouting is expected,
23385 			 * any non-RTF_MULTIRT ire that has the
23386 			 * right destination address is ignored.
23387 			 */
23388 			ASSERT(irb != NULL);
23389 			IRB_REFHOLD(irb);
23390 			for (ire1 = ire->ire_next;
23391 			    ire1 != NULL;
23392 			    ire1 = ire1->ire_next) {
23393 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23394 					continue;
23395 				if (ire1->ire_addr != ire->ire_addr)
23396 					continue;
23397 				if (ire1->ire_marks &
23398 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23399 					continue;
23400 				/* No loopback here */
23401 				if (ire1->ire_stq == NULL)
23402 					continue;
23403 				/*
23404 				 * Ensure we do not exceed the MTU
23405 				 * of the next route.
23406 				 */
23407 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
23408 					ip_multirt_bad_mtu(ire1, max_frag);
23409 					continue;
23410 				}
23411 
23412 				IRE_REFHOLD(ire1);
23413 				break;
23414 			}
23415 			IRB_REFRELE(irb);
23416 			if (ire1 != NULL) {
23417 				/*
23418 				 * We are in a multiple send case, need to
23419 				 * make a copy of the packet.
23420 				 */
23421 				next_mp = copymsg(ipsec_mp);
23422 				if (next_mp == NULL) {
23423 					ire_refrele(ire1);
23424 					ire1 = NULL;
23425 				}
23426 			}
23427 		}
23428 
23429 		/* Everything is done. Send it out on the wire */
23430 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
23431 		if (mp1 == NULL) {
23432 			BUMP_MIB(&ip_mib, ipOutDiscards);
23433 			freemsg(ipsec_mp);
23434 			if (ire_need_rele)
23435 				ire_refrele(ire);
23436 			if (ire1 != NULL) {
23437 				ire_refrele(ire1);
23438 				freemsg(next_mp);
23439 			}
23440 			goto done;
23441 		}
23442 		UPDATE_OB_PKT_COUNT(ire);
23443 		ire->ire_last_used_time = lbolt;
23444 		if (!io->ipsec_out_accelerated) {
23445 			putnext(ire->ire_stq, mp1);
23446 		} else {
23447 			/*
23448 			 * Safety Pup says: make sure this is going to
23449 			 * the right interface!
23450 			 */
23451 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
23452 			int ifindex = ill1->ill_phyint->phyint_ifindex;
23453 
23454 			if (ifindex != io->ipsec_out_capab_ill_index) {
23455 				/* IPsec kstats: bump lose counter */
23456 				freemsg(mp1);
23457 			} else {
23458 				ipsec_hw_putnext(ire->ire_stq, mp1);
23459 			}
23460 		}
23461 
23462 		freeb(ipsec_mp);
23463 		if (ire_need_rele)
23464 			ire_refrele(ire);
23465 
23466 		if (ire1 != NULL) {
23467 			ire = ire1;
23468 			ire_need_rele = B_TRUE;
23469 			ASSERT(next_mp);
23470 			ipsec_mp = next_mp;
23471 			mp = ipsec_mp->b_cont;
23472 			ire1 = NULL;
23473 			next_mp = NULL;
23474 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
23475 		} else {
23476 			multirt_send = B_FALSE;
23477 		}
23478 	} while (multirt_send);
23479 done:
23480 	if (ill != NULL && ill_need_rele)
23481 		ill_refrele(ill);
23482 	if (ipif != NULL)
23483 		ipif_refrele(ipif);
23484 }
23485 
23486 /*
23487  * Get the ill corresponding to the specified ire, and compare its
23488  * capabilities with the protocol and algorithms specified by the
23489  * the SA obtained from ipsec_out. If they match, annotate the
23490  * ipsec_out structure to indicate that the packet needs acceleration.
23491  *
23492  *
23493  * A packet is eligible for outbound hardware acceleration if the
23494  * following conditions are satisfied:
23495  *
23496  * 1. the packet will not be fragmented
23497  * 2. the provider supports the algorithm
23498  * 3. there is no pending control message being exchanged
23499  * 4. snoop is not attached
23500  * 5. the destination address is not a broadcast or multicast address.
23501  *
23502  * Rationale:
23503  *	- Hardware drivers do not support fragmentation with
23504  *	  the current interface.
23505  *	- snoop, multicast, and broadcast may result in exposure of
23506  *	  a cleartext datagram.
23507  * We check all five of these conditions here.
23508  *
23509  * XXX would like to nuke "ire_t *" parameter here; problem is that
23510  * IRE is only way to figure out if a v4 address is a broadcast and
23511  * thus ineligible for acceleration...
23512  */
23513 static void
23514 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23515 {
23516 	ipsec_out_t *io;
23517 	mblk_t *data_mp;
23518 	uint_t plen, overhead;
23519 
23520 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23521 		return;
23522 
23523 	if (ill == NULL)
23524 		return;
23525 
23526 	/*
23527 	 * Destination address is a broadcast or multicast.  Punt.
23528 	 */
23529 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23530 	    IRE_LOCAL)))
23531 		return;
23532 
23533 	data_mp = ipsec_mp->b_cont;
23534 
23535 	if (ill->ill_isv6) {
23536 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23537 
23538 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23539 			return;
23540 
23541 		plen = ip6h->ip6_plen;
23542 	} else {
23543 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23544 
23545 		if (CLASSD(ipha->ipha_dst))
23546 			return;
23547 
23548 		plen = ipha->ipha_length;
23549 	}
23550 	/*
23551 	 * Is there a pending DLPI control message being exchanged
23552 	 * between IP/IPsec and the DLS Provider? If there is, it
23553 	 * could be a SADB update, and the state of the DLS Provider
23554 	 * SADB might not be in sync with the SADB maintained by
23555 	 * IPsec. To avoid dropping packets or using the wrong keying
23556 	 * material, we do not accelerate this packet.
23557 	 */
23558 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23559 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23560 		    "ill_dlpi_pending! don't accelerate packet\n"));
23561 		return;
23562 	}
23563 
23564 	/*
23565 	 * Is the Provider in promiscous mode? If it does, we don't
23566 	 * accelerate the packet since it will bounce back up to the
23567 	 * listeners in the clear.
23568 	 */
23569 	if (ill->ill_promisc_on_phys) {
23570 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23571 		    "ill in promiscous mode, don't accelerate packet\n"));
23572 		return;
23573 	}
23574 
23575 	/*
23576 	 * Will the packet require fragmentation?
23577 	 */
23578 
23579 	/*
23580 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23581 	 * as is used elsewhere.
23582 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23583 	 *	+ 2-byte trailer
23584 	 */
23585 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23586 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23587 
23588 	if ((plen + overhead) > ill->ill_max_mtu)
23589 		return;
23590 
23591 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23592 
23593 	/*
23594 	 * Can the ill accelerate this IPsec protocol and algorithm
23595 	 * specified by the SA?
23596 	 */
23597 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23598 	    ill->ill_isv6, sa)) {
23599 		return;
23600 	}
23601 
23602 	/*
23603 	 * Tell AH or ESP that the outbound ill is capable of
23604 	 * accelerating this packet.
23605 	 */
23606 	io->ipsec_out_is_capab_ill = B_TRUE;
23607 }
23608 
23609 /*
23610  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23611  *
23612  * If this function returns B_TRUE, the requested SA's have been filled
23613  * into the ipsec_out_*_sa pointers.
23614  *
23615  * If the function returns B_FALSE, the packet has been "consumed", most
23616  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23617  *
23618  * The SA references created by the protocol-specific "select"
23619  * function will be released when the ipsec_mp is freed, thanks to the
23620  * ipsec_out_free destructor -- see spd.c.
23621  */
23622 static boolean_t
23623 ipsec_out_select_sa(mblk_t *ipsec_mp)
23624 {
23625 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23626 	ipsec_out_t *io;
23627 	ipsec_policy_t *pp;
23628 	ipsec_action_t *ap;
23629 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23630 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23631 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23632 
23633 	if (!io->ipsec_out_secure) {
23634 		/*
23635 		 * We came here by mistake.
23636 		 * Don't bother with ipsec processing
23637 		 * We should "discourage" this path in the future.
23638 		 */
23639 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23640 		return (B_FALSE);
23641 	}
23642 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23643 	ASSERT((io->ipsec_out_policy != NULL) ||
23644 	    (io->ipsec_out_act != NULL));
23645 
23646 	ASSERT(io->ipsec_out_failed == B_FALSE);
23647 
23648 	/*
23649 	 * IPSEC processing has started.
23650 	 */
23651 	io->ipsec_out_proc_begin = B_TRUE;
23652 	ap = io->ipsec_out_act;
23653 	if (ap == NULL) {
23654 		pp = io->ipsec_out_policy;
23655 		ASSERT(pp != NULL);
23656 		ap = pp->ipsp_act;
23657 		ASSERT(ap != NULL);
23658 	}
23659 
23660 	/*
23661 	 * We have an action.  now, let's select SA's.
23662 	 * (In the future, we can cache this in the conn_t..)
23663 	 */
23664 	if (ap->ipa_want_esp) {
23665 		if (io->ipsec_out_esp_sa == NULL) {
23666 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23667 			    IPPROTO_ESP);
23668 		}
23669 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23670 	}
23671 
23672 	if (ap->ipa_want_ah) {
23673 		if (io->ipsec_out_ah_sa == NULL) {
23674 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23675 			    IPPROTO_AH);
23676 		}
23677 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23678 		/*
23679 		 * The ESP and AH processing order needs to be preserved
23680 		 * when both protocols are required (ESP should be applied
23681 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23682 		 * when both ESP and AH are required, and an AH ACQUIRE
23683 		 * is needed.
23684 		 */
23685 		if (ap->ipa_want_esp && need_ah_acquire)
23686 			need_esp_acquire = B_TRUE;
23687 	}
23688 
23689 	/*
23690 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23691 	 * Release SAs that got referenced, but will not be used until we
23692 	 * acquire _all_ of the SAs we need.
23693 	 */
23694 	if (need_ah_acquire || need_esp_acquire) {
23695 		if (io->ipsec_out_ah_sa != NULL) {
23696 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23697 			io->ipsec_out_ah_sa = NULL;
23698 		}
23699 		if (io->ipsec_out_esp_sa != NULL) {
23700 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23701 			io->ipsec_out_esp_sa = NULL;
23702 		}
23703 
23704 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23705 		return (B_FALSE);
23706 	}
23707 
23708 	return (B_TRUE);
23709 }
23710 
23711 /*
23712  * Process an IPSEC_OUT message and see what you can
23713  * do with it.
23714  * IPQoS Notes:
23715  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23716  * IPSec.
23717  * XXX would like to nuke ire_t.
23718  * XXX ill_index better be "real"
23719  */
23720 void
23721 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23722 {
23723 	ipsec_out_t *io;
23724 	ipsec_policy_t *pp;
23725 	ipsec_action_t *ap;
23726 	ipha_t *ipha;
23727 	ip6_t *ip6h;
23728 	mblk_t *mp;
23729 	ill_t *ill;
23730 	zoneid_t zoneid;
23731 	ipsec_status_t ipsec_rc;
23732 	boolean_t ill_need_rele = B_FALSE;
23733 
23734 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23735 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23736 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23737 	mp = ipsec_mp->b_cont;
23738 
23739 	/*
23740 	 * Initiate IPPF processing. We do it here to account for packets
23741 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23742 	 * We can check for ipsec_out_proc_begin even for such packets, as
23743 	 * they will always be false (asserted below).
23744 	 */
23745 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23746 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23747 		    io->ipsec_out_ill_index : ill_index);
23748 		if (mp == NULL) {
23749 			ip2dbg(("ipsec_out_process: packet dropped "\
23750 			    "during IPPF processing\n"));
23751 			freeb(ipsec_mp);
23752 			BUMP_MIB(&ip_mib, ipOutDiscards);
23753 			return;
23754 		}
23755 	}
23756 
23757 	if (!io->ipsec_out_secure) {
23758 		/*
23759 		 * We came here by mistake.
23760 		 * Don't bother with ipsec processing
23761 		 * Should "discourage" this path in the future.
23762 		 */
23763 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23764 		goto done;
23765 	}
23766 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23767 	ASSERT((io->ipsec_out_policy != NULL) ||
23768 	    (io->ipsec_out_act != NULL));
23769 	ASSERT(io->ipsec_out_failed == B_FALSE);
23770 
23771 	if (!ipsec_loaded()) {
23772 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23773 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23774 			BUMP_MIB(&ip_mib, ipOutDiscards);
23775 		} else {
23776 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23777 		}
23778 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23779 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23780 		return;
23781 	}
23782 
23783 	/*
23784 	 * IPSEC processing has started.
23785 	 */
23786 	io->ipsec_out_proc_begin = B_TRUE;
23787 	ap = io->ipsec_out_act;
23788 	if (ap == NULL) {
23789 		pp = io->ipsec_out_policy;
23790 		ASSERT(pp != NULL);
23791 		ap = pp->ipsp_act;
23792 		ASSERT(ap != NULL);
23793 	}
23794 
23795 	/*
23796 	 * Save the outbound ill index. When the packet comes back
23797 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23798 	 * before sending it the accelerated packet.
23799 	 */
23800 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23801 		int ifindex;
23802 		ill = ire_to_ill(ire);
23803 		ifindex = ill->ill_phyint->phyint_ifindex;
23804 		io->ipsec_out_capab_ill_index = ifindex;
23805 	}
23806 
23807 	/*
23808 	 * The order of processing is first insert a IP header if needed.
23809 	 * Then insert the ESP header and then the AH header.
23810 	 */
23811 	if ((io->ipsec_out_se_done == B_FALSE) &&
23812 	    (ap->ipa_want_se)) {
23813 		/*
23814 		 * First get the outer IP header before sending
23815 		 * it to ESP.
23816 		 */
23817 		ipha_t *oipha, *iipha;
23818 		mblk_t *outer_mp, *inner_mp;
23819 
23820 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23821 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23822 			    "ipsec_out_process: "
23823 			    "Self-Encapsulation failed: Out of memory\n");
23824 			freemsg(ipsec_mp);
23825 			BUMP_MIB(&ip_mib, ipOutDiscards);
23826 			return;
23827 		}
23828 		inner_mp = ipsec_mp->b_cont;
23829 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23830 		oipha = (ipha_t *)outer_mp->b_rptr;
23831 		iipha = (ipha_t *)inner_mp->b_rptr;
23832 		*oipha = *iipha;
23833 		outer_mp->b_wptr += sizeof (ipha_t);
23834 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23835 		    sizeof (ipha_t));
23836 		oipha->ipha_protocol = IPPROTO_ENCAP;
23837 		oipha->ipha_version_and_hdr_length =
23838 		    IP_SIMPLE_HDR_VERSION;
23839 		oipha->ipha_hdr_checksum = 0;
23840 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23841 		outer_mp->b_cont = inner_mp;
23842 		ipsec_mp->b_cont = outer_mp;
23843 
23844 		io->ipsec_out_se_done = B_TRUE;
23845 		io->ipsec_out_encaps = B_TRUE;
23846 	}
23847 
23848 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23849 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23850 	    !ipsec_out_select_sa(ipsec_mp))
23851 		return;
23852 
23853 	/*
23854 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23855 	 * to do the heavy lifting.
23856 	 */
23857 	zoneid = io->ipsec_out_zoneid;
23858 	ASSERT(zoneid != ALL_ZONES);
23859 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23860 		ASSERT(io->ipsec_out_esp_sa != NULL);
23861 		io->ipsec_out_esp_done = B_TRUE;
23862 		/*
23863 		 * Note that since hw accel can only apply one transform,
23864 		 * not two, we skip hw accel for ESP if we also have AH
23865 		 * This is an design limitation of the interface
23866 		 * which should be revisited.
23867 		 */
23868 		ASSERT(ire != NULL);
23869 		if (io->ipsec_out_ah_sa == NULL) {
23870 			ill = (ill_t *)ire->ire_stq->q_ptr;
23871 			ipsec_out_is_accelerated(ipsec_mp,
23872 			    io->ipsec_out_esp_sa, ill, ire);
23873 		}
23874 
23875 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23876 		switch (ipsec_rc) {
23877 		case IPSEC_STATUS_SUCCESS:
23878 			break;
23879 		case IPSEC_STATUS_FAILED:
23880 			BUMP_MIB(&ip_mib, ipOutDiscards);
23881 			/* FALLTHRU */
23882 		case IPSEC_STATUS_PENDING:
23883 			return;
23884 		}
23885 	}
23886 
23887 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23888 		ASSERT(io->ipsec_out_ah_sa != NULL);
23889 		io->ipsec_out_ah_done = B_TRUE;
23890 		if (ire == NULL) {
23891 			int idx = io->ipsec_out_capab_ill_index;
23892 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23893 			    NULL, NULL, NULL, NULL);
23894 			ill_need_rele = B_TRUE;
23895 		} else {
23896 			ill = (ill_t *)ire->ire_stq->q_ptr;
23897 		}
23898 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23899 		    ire);
23900 
23901 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23902 		switch (ipsec_rc) {
23903 		case IPSEC_STATUS_SUCCESS:
23904 			break;
23905 		case IPSEC_STATUS_FAILED:
23906 			BUMP_MIB(&ip_mib, ipOutDiscards);
23907 			/* FALLTHRU */
23908 		case IPSEC_STATUS_PENDING:
23909 			if (ill != NULL && ill_need_rele)
23910 				ill_refrele(ill);
23911 			return;
23912 		}
23913 	}
23914 	/*
23915 	 * We are done with IPSEC processing. Send it over
23916 	 * the wire.
23917 	 */
23918 done:
23919 	mp = ipsec_mp->b_cont;
23920 	ipha = (ipha_t *)mp->b_rptr;
23921 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23922 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23923 	} else {
23924 		ip6h = (ip6_t *)ipha;
23925 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23926 	}
23927 	if (ill != NULL && ill_need_rele)
23928 		ill_refrele(ill);
23929 }
23930 
23931 /* ARGSUSED */
23932 void
23933 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23934 {
23935 	opt_restart_t	*or;
23936 	int	err;
23937 	conn_t	*connp;
23938 
23939 	ASSERT(CONN_Q(q));
23940 	connp = Q_TO_CONN(q);
23941 
23942 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23943 	or = (opt_restart_t *)first_mp->b_rptr;
23944 	/*
23945 	 * We don't need to pass any credentials here since this is just
23946 	 * a restart. The credentials are passed in when svr4_optcom_req
23947 	 * is called the first time (from ip_wput_nondata).
23948 	 */
23949 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23950 		err = svr4_optcom_req(q, first_mp, NULL,
23951 		    &ip_opt_obj);
23952 	} else {
23953 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23954 		err = tpi_optcom_req(q, first_mp, NULL,
23955 		    &ip_opt_obj);
23956 	}
23957 	if (err != EINPROGRESS) {
23958 		/* operation is done */
23959 		CONN_OPER_PENDING_DONE(connp);
23960 	}
23961 }
23962 
23963 /*
23964  * ioctls that go through a down/up sequence may need to wait for the down
23965  * to complete. This involves waiting for the ire and ipif refcnts to go down
23966  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23967  */
23968 /* ARGSUSED */
23969 void
23970 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23971 {
23972 	struct iocblk *iocp;
23973 	mblk_t *mp1;
23974 	ipif_t	*ipif;
23975 	ip_ioctl_cmd_t *ipip;
23976 	int err;
23977 	sin_t	*sin;
23978 	struct lifreq *lifr;
23979 	struct ifreq *ifr;
23980 
23981 	iocp = (struct iocblk *)mp->b_rptr;
23982 	ASSERT(ipsq != NULL);
23983 	/* Existence of mp1 verified in ip_wput_nondata */
23984 	mp1 = mp->b_cont->b_cont;
23985 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23986 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23987 		ill_t *ill;
23988 		/*
23989 		 * Special case where ipsq_current_ipif may not be set.
23990 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23991 		 * ill could also have become part of a ipmp group in the
23992 		 * process, we are here as were not able to complete the
23993 		 * operation in ipif_set_values because we could not become
23994 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23995 		 * will not be set so we need to set it.
23996 		 */
23997 		ill = (ill_t *)q->q_ptr;
23998 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23999 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24000 	}
24001 
24002 	ipif = ipsq->ipsq_current_ipif;
24003 	ASSERT(ipif != NULL);
24004 	if (ipip->ipi_cmd_type == IF_CMD) {
24005 		/* This a old style SIOC[GS]IF* command */
24006 		ifr = (struct ifreq *)mp1->b_rptr;
24007 		sin = (sin_t *)&ifr->ifr_addr;
24008 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24009 		/* This a new style SIOC[GS]LIF* command */
24010 		lifr = (struct lifreq *)mp1->b_rptr;
24011 		sin = (sin_t *)&lifr->lifr_addr;
24012 	} else {
24013 		sin = NULL;
24014 	}
24015 
24016 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24017 	    (void *)mp1->b_rptr);
24018 
24019 	/* SIOCLIFREMOVEIF could have removed the ipif */
24020 	ip_ioctl_finish(q, mp, err,
24021 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24022 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24023 }
24024 
24025 /*
24026  * ioctl processing
24027  *
24028  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24029  * the ioctl command in the ioctl tables and determines the copyin data size
24030  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24031  * size.
24032  *
24033  * ioctl processing then continues when the M_IOCDATA makes its way down.
24034  * Now the ioctl is looked up again in the ioctl table, and its properties are
24035  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24036  * and the general ioctl processing function ip_process_ioctl is called.
24037  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24038  * so goes thru the serialization primitive ipsq_try_enter. Then the
24039  * appropriate function to handle the ioctl is called based on the entry in
24040  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24041  * which also refreleases the 'conn' that was refheld at the start of the
24042  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24043  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24044  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24045  *
24046  * Many exclusive ioctls go thru an internal down up sequence as part of
24047  * the operation. For example an attempt to change the IP address of an
24048  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24049  * does all the cleanup such as deleting all ires that use this address.
24050  * Then we need to wait till all references to the interface go away.
24051  */
24052 void
24053 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24054 {
24055 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24056 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24057 	cmd_info_t ci;
24058 	int err;
24059 	boolean_t entered_ipsq = B_FALSE;
24060 
24061 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24062 
24063 	if (ipip == NULL)
24064 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24065 
24066 	/*
24067 	 * SIOCLIFADDIF needs to go thru a special path since the
24068 	 * ill may not exist yet. This happens in the case of lo0
24069 	 * which is created using this ioctl.
24070 	 */
24071 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24072 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24073 		ip_ioctl_finish(q, mp, err,
24074 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24075 		    NULL, NULL);
24076 		return;
24077 	}
24078 
24079 	ci.ci_ipif = NULL;
24080 	switch (ipip->ipi_cmd_type) {
24081 	case IF_CMD:
24082 	case LIF_CMD:
24083 		/*
24084 		 * ioctls that pass in a [l]ifreq appear here.
24085 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24086 		 * ci.ci_ipif
24087 		 */
24088 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24089 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24090 		if (err != 0) {
24091 			ip_ioctl_finish(q, mp, err,
24092 			    ipip->ipi_flags & IPI_GET_CMD ?
24093 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24094 			return;
24095 		}
24096 		ASSERT(ci.ci_ipif != NULL);
24097 		break;
24098 
24099 	case TUN_CMD:
24100 		/*
24101 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24102 		 * a refheld ipif in ci.ci_ipif
24103 		 */
24104 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24105 		if (err != 0) {
24106 			ip_ioctl_finish(q, mp, err,
24107 			    ipip->ipi_flags & IPI_GET_CMD ?
24108 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24109 			return;
24110 		}
24111 		ASSERT(ci.ci_ipif != NULL);
24112 		break;
24113 
24114 	case MISC_CMD:
24115 		/*
24116 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24117 		 * For eg. SIOCGLIFCONF will appear here.
24118 		 */
24119 		switch (ipip->ipi_cmd) {
24120 		case IF_UNITSEL:
24121 			/* ioctl comes down the ill */
24122 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24123 			ipif_refhold(ci.ci_ipif);
24124 			break;
24125 		case SIOCGMSFILTER:
24126 		case SIOCSMSFILTER:
24127 		case SIOCGIPMSFILTER:
24128 		case SIOCSIPMSFILTER:
24129 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24130 			    ip_process_ioctl);
24131 			if (err != 0) {
24132 				ip_ioctl_finish(q, mp, err,
24133 				    ipip->ipi_flags & IPI_GET_CMD ?
24134 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24135 				return;
24136 			}
24137 			break;
24138 		}
24139 		err = 0;
24140 		ci.ci_sin = NULL;
24141 		ci.ci_sin6 = NULL;
24142 		ci.ci_lifr = NULL;
24143 		break;
24144 	}
24145 
24146 	/*
24147 	 * If ipsq is non-null, we are already being called exclusively
24148 	 */
24149 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24150 	if (!(ipip->ipi_flags & IPI_WR)) {
24151 		/*
24152 		 * A return value of EINPROGRESS means the ioctl is
24153 		 * either queued and waiting for some reason or has
24154 		 * already completed.
24155 		 */
24156 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24157 		    ci.ci_lifr);
24158 		if (ci.ci_ipif != NULL)
24159 			ipif_refrele(ci.ci_ipif);
24160 		ip_ioctl_finish(q, mp, err,
24161 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24162 		    NULL, NULL);
24163 		return;
24164 	}
24165 
24166 	ASSERT(ci.ci_ipif != NULL);
24167 
24168 	if (ipsq == NULL) {
24169 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
24170 		    ip_process_ioctl, NEW_OP, B_TRUE);
24171 		entered_ipsq = B_TRUE;
24172 	}
24173 	/*
24174 	 * Release the ipif so that ipif_down and friends that wait for
24175 	 * references to go away are not misled about the current ipif_refcnt
24176 	 * values. We are writer so we can access the ipif even after releasing
24177 	 * the ipif.
24178 	 */
24179 	ipif_refrele(ci.ci_ipif);
24180 	if (ipsq == NULL)
24181 		return;
24182 
24183 	mutex_enter(&ipsq->ipsq_lock);
24184 	ASSERT(ipsq->ipsq_current_ipif == NULL);
24185 	ipsq->ipsq_current_ipif = ci.ci_ipif;
24186 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24187 	mutex_exit(&ipsq->ipsq_lock);
24188 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
24189 	/*
24190 	 * For most set ioctls that come here, this serves as a single point
24191 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
24192 	 * be any new references to the ipif. This helps functions that go
24193 	 * through this path and end up trying to wait for the refcnts
24194 	 * associated with the ipif to go down to zero. Some exceptions are
24195 	 * Failover, Failback, and Groupname commands that operate on more than
24196 	 * just the ci.ci_ipif. These commands internally determine the
24197 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
24198 	 * flags on that set. Another exception is the Removeif command that
24199 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
24200 	 * ipif to operate on.
24201 	 */
24202 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
24203 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
24204 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
24205 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
24206 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
24207 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
24208 
24209 	/*
24210 	 * A return value of EINPROGRESS means the ioctl is
24211 	 * either queued and waiting for some reason or has
24212 	 * already completed.
24213 	 */
24214 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24215 	    ci.ci_lifr);
24216 
24217 	/* SIOCLIFREMOVEIF could have removed the ipif */
24218 	ip_ioctl_finish(q, mp, err,
24219 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24220 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
24221 
24222 	if (entered_ipsq)
24223 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
24224 }
24225 
24226 /*
24227  * Complete the ioctl. Typically ioctls use the mi package and need to
24228  * do mi_copyout/mi_copy_done.
24229  */
24230 void
24231 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
24232     ipif_t *ipif, ipsq_t *ipsq)
24233 {
24234 	conn_t	*connp = NULL;
24235 
24236 	if (err == EINPROGRESS)
24237 		return;
24238 
24239 	if (CONN_Q(q)) {
24240 		connp = Q_TO_CONN(q);
24241 		ASSERT(connp->conn_ref >= 2);
24242 	}
24243 
24244 	switch (mode) {
24245 	case COPYOUT:
24246 		if (err == 0)
24247 			mi_copyout(q, mp);
24248 		else
24249 			mi_copy_done(q, mp, err);
24250 		break;
24251 
24252 	case NO_COPYOUT:
24253 		mi_copy_done(q, mp, err);
24254 		break;
24255 
24256 	default:
24257 		/* An ioctl aborted through a conn close would take this path */
24258 		break;
24259 	}
24260 
24261 	/*
24262 	 * The refhold placed at the start of the ioctl is released here.
24263 	 */
24264 	if (connp != NULL)
24265 		CONN_OPER_PENDING_DONE(connp);
24266 
24267 	/*
24268 	 * If the ioctl were an exclusive ioctl it would have set
24269 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
24270 	 */
24271 	if (ipif != NULL) {
24272 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
24273 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
24274 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
24275 	}
24276 
24277 	/*
24278 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
24279 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
24280 	 * entering the ipsq
24281 	 */
24282 	if (ipsq != NULL) {
24283 		mutex_enter(&ipsq->ipsq_lock);
24284 		ipsq->ipsq_current_ipif = NULL;
24285 		mutex_exit(&ipsq->ipsq_lock);
24286 	}
24287 }
24288 
24289 /*
24290  * This is called from ip_wput_nondata to resume a deferred TCP bind.
24291  */
24292 /* ARGSUSED */
24293 void
24294 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
24295 {
24296 	conn_t *connp = arg;
24297 	tcp_t	*tcp;
24298 
24299 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
24300 	tcp = connp->conn_tcp;
24301 
24302 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
24303 		freemsg(mp);
24304 	else
24305 		tcp_rput_other(tcp, mp);
24306 	CONN_OPER_PENDING_DONE(connp);
24307 }
24308 
24309 /* Called from ip_wput for all non data messages */
24310 /* ARGSUSED */
24311 void
24312 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24313 {
24314 	mblk_t		*mp1;
24315 	ire_t		*ire;
24316 	ill_t		*ill;
24317 	struct iocblk	*iocp;
24318 	ip_ioctl_cmd_t	*ipip;
24319 	cred_t		*cr;
24320 	conn_t		*connp = NULL;
24321 	int		cmd, err;
24322 
24323 	if (CONN_Q(q))
24324 		connp = Q_TO_CONN(q);
24325 
24326 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
24327 
24328 	/* Check if it is a queue to /dev/sctp. */
24329 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
24330 	    connp->conn_rq == NULL) {
24331 		sctp_wput(q, mp);
24332 		return;
24333 	}
24334 
24335 	switch (DB_TYPE(mp)) {
24336 	case M_IOCTL:
24337 		/*
24338 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
24339 		 * will arrange to copy in associated control structures.
24340 		 */
24341 		ip_sioctl_copyin_setup(q, mp);
24342 		return;
24343 	case M_IOCDATA:
24344 		/*
24345 		 * Ensure that this is associated with one of our trans-
24346 		 * parent ioctls.  If it's not ours, discard it if we're
24347 		 * running as a driver, or pass it on if we're a module.
24348 		 */
24349 		iocp = (struct iocblk *)mp->b_rptr;
24350 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24351 		if (ipip == NULL) {
24352 			if (q->q_next == NULL) {
24353 				goto nak;
24354 			} else {
24355 				putnext(q, mp);
24356 			}
24357 			return;
24358 		} else if ((q->q_next != NULL) &&
24359 		    !(ipip->ipi_flags & IPI_MODOK)) {
24360 			/*
24361 			 * the ioctl is one we recognise, but is not
24362 			 * consumed by IP as a module, pass M_IOCDATA
24363 			 * for processing downstream, but only for
24364 			 * common Streams ioctls.
24365 			 */
24366 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
24367 				putnext(q, mp);
24368 				return;
24369 			} else {
24370 				goto nak;
24371 			}
24372 		}
24373 
24374 		/* IOCTL continuation following copyin or copyout. */
24375 		if (mi_copy_state(q, mp, NULL) == -1) {
24376 			/*
24377 			 * The copy operation failed.  mi_copy_state already
24378 			 * cleaned up, so we're out of here.
24379 			 */
24380 			return;
24381 		}
24382 		/*
24383 		 * If we just completed a copy in, we become writer and
24384 		 * continue processing in ip_sioctl_copyin_done.  If it
24385 		 * was a copy out, we call mi_copyout again.  If there is
24386 		 * nothing more to copy out, it will complete the IOCTL.
24387 		 */
24388 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
24389 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
24390 				mi_copy_done(q, mp, EPROTO);
24391 				return;
24392 			}
24393 			/*
24394 			 * Check for cases that need more copying.  A return
24395 			 * value of 0 means a second copyin has been started,
24396 			 * so we return; a return value of 1 means no more
24397 			 * copying is needed, so we continue.
24398 			 */
24399 			cmd = iocp->ioc_cmd;
24400 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
24401 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
24402 			    MI_COPY_COUNT(mp) == 1) {
24403 				if (ip_copyin_msfilter(q, mp) == 0)
24404 					return;
24405 			}
24406 			/*
24407 			 * Refhold the conn, till the ioctl completes. This is
24408 			 * needed in case the ioctl ends up in the pending mp
24409 			 * list. Every mp in the ill_pending_mp list and
24410 			 * the ipsq_pending_mp must have a refhold on the conn
24411 			 * to resume processing. The refhold is released when
24412 			 * the ioctl completes. (normally or abnormally)
24413 			 * In all cases ip_ioctl_finish is called to finish
24414 			 * the ioctl.
24415 			 */
24416 			if (connp != NULL) {
24417 				/* This is not a reentry */
24418 				ASSERT(ipsq == NULL);
24419 				CONN_INC_REF(connp);
24420 			} else {
24421 				if (!(ipip->ipi_flags & IPI_MODOK)) {
24422 					mi_copy_done(q, mp, EINVAL);
24423 					return;
24424 				}
24425 			}
24426 
24427 			ip_process_ioctl(ipsq, q, mp, ipip);
24428 
24429 		} else {
24430 			mi_copyout(q, mp);
24431 		}
24432 		return;
24433 nak:
24434 		iocp->ioc_error = EINVAL;
24435 		mp->b_datap->db_type = M_IOCNAK;
24436 		iocp->ioc_count = 0;
24437 		qreply(q, mp);
24438 		return;
24439 
24440 	case M_IOCNAK:
24441 		/*
24442 		 * The only way we could get here is if a resolver didn't like
24443 		 * an IOCTL we sent it.	 This shouldn't happen.
24444 		 */
24445 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
24446 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
24447 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
24448 		freemsg(mp);
24449 		return;
24450 	case M_IOCACK:
24451 		/* Finish socket ioctls passed through to ARP. */
24452 		ip_sioctl_iocack(q, mp);
24453 		return;
24454 	case M_FLUSH:
24455 		if (*mp->b_rptr & FLUSHW)
24456 			flushq(q, FLUSHALL);
24457 		if (q->q_next) {
24458 			/*
24459 			 * M_FLUSH is sent up to IP by some drivers during
24460 			 * unbind. ip_rput has already replied to it. We are
24461 			 * here for the M_FLUSH that we originated in IP
24462 			 * before sending the unbind request to the driver.
24463 			 * Just free it as we don't queue packets in IP
24464 			 * on the write side of the device instance.
24465 			 */
24466 			freemsg(mp);
24467 			return;
24468 		}
24469 		if (*mp->b_rptr & FLUSHR) {
24470 			*mp->b_rptr &= ~FLUSHW;
24471 			qreply(q, mp);
24472 			return;
24473 		}
24474 		freemsg(mp);
24475 		return;
24476 	case IRE_DB_REQ_TYPE:
24477 		/* An Upper Level Protocol wants a copy of an IRE. */
24478 		ip_ire_req(q, mp);
24479 		return;
24480 	case M_CTL:
24481 		/* M_CTL messages are used by ARP to tell us things. */
24482 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
24483 			break;
24484 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
24485 		case AR_ENTRY_SQUERY:
24486 			ip_wput_ctl(q, mp);
24487 			return;
24488 		case AR_CLIENT_NOTIFY:
24489 			ip_arp_news(q, mp);
24490 			return;
24491 		case AR_DLPIOP_DONE:
24492 			ASSERT(q->q_next != NULL);
24493 			ill = (ill_t *)q->q_ptr;
24494 			/* qwriter_ip releases the refhold */
24495 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24496 			ill_refhold(ill);
24497 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24498 			    CUR_OP, B_FALSE);
24499 			return;
24500 		case AR_ARP_CLOSING:
24501 			/*
24502 			 * ARP (above us) is closing. If no ARP bringup is
24503 			 * currently pending, ack the message so that ARP
24504 			 * can complete its close. Also mark ill_arp_closing
24505 			 * so that new ARP bringups will fail. If any
24506 			 * ARP bringup is currently in progress, we will
24507 			 * ack this when the current ARP bringup completes.
24508 			 */
24509 			ASSERT(q->q_next != NULL);
24510 			ill = (ill_t *)q->q_ptr;
24511 			mutex_enter(&ill->ill_lock);
24512 			ill->ill_arp_closing = 1;
24513 			if (!ill->ill_arp_bringup_pending) {
24514 				mutex_exit(&ill->ill_lock);
24515 				qreply(q, mp);
24516 			} else {
24517 				mutex_exit(&ill->ill_lock);
24518 				freemsg(mp);
24519 			}
24520 			return;
24521 		default:
24522 			break;
24523 		}
24524 		break;
24525 	case M_PROTO:
24526 	case M_PCPROTO:
24527 		/*
24528 		 * The only PROTO messages we expect are ULP binds and
24529 		 * copies of option negotiation acknowledgements.
24530 		 */
24531 		switch (((union T_primitives *)mp->b_rptr)->type) {
24532 		case O_T_BIND_REQ:
24533 		case T_BIND_REQ: {
24534 			/* Request can get queued in bind */
24535 			ASSERT(connp != NULL);
24536 			/*
24537 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
24538 			 * instead of going through this path.  We only get
24539 			 * here in the following cases:
24540 			 *
24541 			 * a. Bind retries, where ipsq is non-NULL.
24542 			 * b. T_BIND_REQ is issued from non TCP/UDP
24543 			 *    transport, e.g. icmp for raw socket,
24544 			 *    in which case ipsq will be NULL.
24545 			 */
24546 			ASSERT(ipsq != NULL ||
24547 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
24548 
24549 			/* Don't increment refcnt if this is a re-entry */
24550 			if (ipsq == NULL)
24551 				CONN_INC_REF(connp);
24552 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
24553 			    connp, NULL) : ip_bind_v4(q, mp, connp);
24554 			if (mp == NULL)
24555 				return;
24556 			if (IPCL_IS_TCP(connp)) {
24557 				/*
24558 				 * In the case of TCP endpoint we
24559 				 * come here only for bind retries
24560 				 */
24561 				ASSERT(ipsq != NULL);
24562 				CONN_INC_REF(connp);
24563 				squeue_fill(connp->conn_sqp, mp,
24564 				    ip_resume_tcp_bind, connp,
24565 				    SQTAG_BIND_RETRY);
24566 				return;
24567 			} else if (IPCL_IS_UDP(connp)) {
24568 				/*
24569 				 * In the case of UDP endpoint we
24570 				 * come here only for bind retries
24571 				 */
24572 				ASSERT(ipsq != NULL);
24573 				udp_resume_bind(connp, mp);
24574 				return;
24575 			}
24576 			qreply(q, mp);
24577 			CONN_OPER_PENDING_DONE(connp);
24578 			return;
24579 		}
24580 		case T_SVR4_OPTMGMT_REQ:
24581 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24582 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24583 
24584 			ASSERT(connp != NULL);
24585 			if (!snmpcom_req(q, mp, ip_snmp_set,
24586 			    ip_snmp_get, cr)) {
24587 				/*
24588 				 * Call svr4_optcom_req so that it can
24589 				 * generate the ack. We don't come here
24590 				 * if this operation is being restarted.
24591 				 * ip_restart_optmgmt will drop the conn ref.
24592 				 * In the case of ipsec option after the ipsec
24593 				 * load is complete conn_restart_ipsec_waiter
24594 				 * drops the conn ref.
24595 				 */
24596 				ASSERT(ipsq == NULL);
24597 				CONN_INC_REF(connp);
24598 				if (ip_check_for_ipsec_opt(q, mp))
24599 					return;
24600 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24601 				if (err != EINPROGRESS) {
24602 					/* Operation is done */
24603 					CONN_OPER_PENDING_DONE(connp);
24604 				}
24605 			}
24606 			return;
24607 		case T_OPTMGMT_REQ:
24608 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24609 			/*
24610 			 * Note: No snmpcom_req support through new
24611 			 * T_OPTMGMT_REQ.
24612 			 * Call tpi_optcom_req so that it can
24613 			 * generate the ack.
24614 			 */
24615 			ASSERT(connp != NULL);
24616 			ASSERT(ipsq == NULL);
24617 			/*
24618 			 * We don't come here for restart. ip_restart_optmgmt
24619 			 * will drop the conn ref. In the case of ipsec option
24620 			 * after the ipsec load is complete
24621 			 * conn_restart_ipsec_waiter drops the conn ref.
24622 			 */
24623 			CONN_INC_REF(connp);
24624 			if (ip_check_for_ipsec_opt(q, mp))
24625 				return;
24626 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24627 			if (err != EINPROGRESS) {
24628 				/* Operation is done */
24629 				CONN_OPER_PENDING_DONE(connp);
24630 			}
24631 			return;
24632 		case T_UNBIND_REQ:
24633 			mp = ip_unbind(q, mp);
24634 			qreply(q, mp);
24635 			return;
24636 		default:
24637 			/*
24638 			 * Have to drop any DLPI messages coming down from
24639 			 * arp (such as an info_req which would cause ip
24640 			 * to receive an extra info_ack if it was passed
24641 			 * through.
24642 			 */
24643 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24644 			    (int)*(uint_t *)mp->b_rptr));
24645 			freemsg(mp);
24646 			return;
24647 		}
24648 		/* NOTREACHED */
24649 	case IRE_DB_TYPE: {
24650 		nce_t		*nce;
24651 		ill_t		*ill;
24652 		in6_addr_t	gw_addr_v6;
24653 
24654 
24655 		/*
24656 		 * This is a response back from a resolver.  It
24657 		 * consists of a message chain containing:
24658 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24659 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24660 		 * The LL_HDR_MBLK is the DLPI header to use to get
24661 		 * the attached packet, and subsequent ones for the
24662 		 * same destination, transmitted.
24663 		 */
24664 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24665 			break;
24666 		/*
24667 		 * First, check to make sure the resolution succeeded.
24668 		 * If it failed, the second mblk will be empty.
24669 		 * If it is, free the chain, dropping the packet.
24670 		 * (We must ire_delete the ire; that frees the ire mblk)
24671 		 * We're doing this now to support PVCs for ATM; it's
24672 		 * a partial xresolv implementation. When we fully implement
24673 		 * xresolv interfaces, instead of freeing everything here
24674 		 * we'll initiate neighbor discovery.
24675 		 *
24676 		 * For v4 (ARP and other external resolvers) the resolver
24677 		 * frees the message, so no check is needed. This check
24678 		 * is required, though, for a full xresolve implementation.
24679 		 * Including this code here now both shows how external
24680 		 * resolvers can NACK a resolution request using an
24681 		 * existing design that has no specific provisions for NACKs,
24682 		 * and also takes into account that the current non-ARP
24683 		 * external resolver has been coded to use this method of
24684 		 * NACKing for all IPv6 (xresolv) cases,
24685 		 * whether our xresolv implementation is complete or not.
24686 		 *
24687 		 */
24688 		ire = (ire_t *)mp->b_rptr;
24689 		ill = ire_to_ill(ire);
24690 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24691 		if (mp1->b_rptr == mp1->b_wptr) {
24692 			if (ire->ire_ipversion == IPV6_VERSION) {
24693 				/*
24694 				 * XRESOLV interface.
24695 				 */
24696 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24697 				mutex_enter(&ire->ire_lock);
24698 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24699 				mutex_exit(&ire->ire_lock);
24700 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24701 					nce = ndp_lookup(ill,
24702 					    &ire->ire_addr_v6, B_FALSE);
24703 				} else {
24704 					nce = ndp_lookup(ill, &gw_addr_v6,
24705 					    B_FALSE);
24706 				}
24707 				if (nce != NULL) {
24708 					nce_resolv_failed(nce);
24709 					ndp_delete(nce);
24710 					NCE_REFRELE(nce);
24711 				}
24712 			}
24713 			mp->b_cont = NULL;
24714 			freemsg(mp1);		/* frees the pkt as well */
24715 			ire_delete((ire_t *)mp->b_rptr);
24716 			return;
24717 		}
24718 		/*
24719 		 * Split them into IRE_MBLK and pkt and feed it into
24720 		 * ire_add_then_send. Then in ire_add_then_send
24721 		 * the IRE will be added, and then the packet will be
24722 		 * run back through ip_wput. This time it will make
24723 		 * it to the wire.
24724 		 */
24725 		mp->b_cont = NULL;
24726 		mp = mp1->b_cont;		/* now, mp points to pkt */
24727 		mp1->b_cont = NULL;
24728 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24729 		if (ire->ire_ipversion == IPV6_VERSION) {
24730 			/*
24731 			 * XRESOLV interface. Find the nce and put a copy
24732 			 * of the dl_unitdata_req in nce_res_mp
24733 			 */
24734 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24735 			mutex_enter(&ire->ire_lock);
24736 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24737 			mutex_exit(&ire->ire_lock);
24738 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24739 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24740 				    B_FALSE);
24741 			} else {
24742 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24743 			}
24744 			if (nce != NULL) {
24745 				/*
24746 				 * We have to protect nce_res_mp here
24747 				 * from being accessed by other threads
24748 				 * while we change the mblk pointer.
24749 				 * Other functions will also lock the nce when
24750 				 * accessing nce_res_mp.
24751 				 *
24752 				 * The reason we change the mblk pointer
24753 				 * here rather than copying the resolved address
24754 				 * into the template is that, unlike with
24755 				 * ethernet, we have no guarantee that the
24756 				 * resolved address length will be
24757 				 * smaller than or equal to the lla length
24758 				 * with which the template was allocated,
24759 				 * (for ethernet, they're equal)
24760 				 * so we have to use the actual resolved
24761 				 * address mblk - which holds the real
24762 				 * dl_unitdata_req with the resolved address.
24763 				 *
24764 				 * Doing this is the same behavior as was
24765 				 * previously used in the v4 ARP case.
24766 				 */
24767 				mutex_enter(&nce->nce_lock);
24768 				if (nce->nce_res_mp != NULL)
24769 					freemsg(nce->nce_res_mp);
24770 				nce->nce_res_mp = mp1;
24771 				mutex_exit(&nce->nce_lock);
24772 				/*
24773 				 * We do a fastpath probe here because
24774 				 * we have resolved the address without
24775 				 * using Neighbor Discovery.
24776 				 * In the non-XRESOLV v6 case, the fastpath
24777 				 * probe is done right after neighbor
24778 				 * discovery completes.
24779 				 */
24780 				if (nce->nce_res_mp != NULL) {
24781 					int res;
24782 					nce_fastpath_list_add(nce);
24783 					res = ill_fastpath_probe(ill,
24784 					    nce->nce_res_mp);
24785 					if (res != 0 && res != EAGAIN)
24786 						nce_fastpath_list_delete(nce);
24787 				}
24788 
24789 				ire_add_then_send(q, ire, mp);
24790 				/*
24791 				 * Now we have to clean out any packets
24792 				 * that may have been queued on the nce
24793 				 * while it was waiting for address resolution
24794 				 * to complete.
24795 				 */
24796 				mutex_enter(&nce->nce_lock);
24797 				mp1 = nce->nce_qd_mp;
24798 				nce->nce_qd_mp = NULL;
24799 				mutex_exit(&nce->nce_lock);
24800 				while (mp1 != NULL) {
24801 					mblk_t *nxt_mp;
24802 					queue_t *fwdq = NULL;
24803 					ill_t   *inbound_ill;
24804 					uint_t ifindex;
24805 
24806 					nxt_mp = mp1->b_next;
24807 					mp1->b_next = NULL;
24808 					/*
24809 					 * Retrieve ifindex stored in
24810 					 * ip_rput_data_v6()
24811 					 */
24812 					ifindex =
24813 					    (uint_t)(uintptr_t)mp1->b_prev;
24814 					inbound_ill =
24815 						ill_lookup_on_ifindex(ifindex,
24816 						    B_TRUE, NULL, NULL, NULL,
24817 						    NULL);
24818 					mp1->b_prev = NULL;
24819 					if (inbound_ill != NULL)
24820 						fwdq = inbound_ill->ill_rq;
24821 
24822 					if (fwdq != NULL) {
24823 						put(fwdq, mp1);
24824 						ill_refrele(inbound_ill);
24825 					} else
24826 						put(WR(ill->ill_rq), mp1);
24827 					mp1 = nxt_mp;
24828 				}
24829 				NCE_REFRELE(nce);
24830 			} else {	/* nce is NULL; clean up */
24831 				ire_delete(ire);
24832 				freemsg(mp);
24833 				freemsg(mp1);
24834 				return;
24835 			}
24836 		} else {
24837 			ire->ire_dlureq_mp = mp1;
24838 			ire_add_then_send(q, ire, mp);
24839 		}
24840 		return;	/* All is well, the packet has been sent. */
24841 	}
24842 	default:
24843 		break;
24844 	}
24845 	if (q->q_next) {
24846 		putnext(q, mp);
24847 	} else
24848 		freemsg(mp);
24849 }
24850 
24851 /*
24852  * Process IP options in an outbound packet.  Modify the destination if there
24853  * is a source route option.
24854  * Returns non-zero if something fails in which case an ICMP error has been
24855  * sent and mp freed.
24856  */
24857 static int
24858 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24859     boolean_t mctl_present, zoneid_t zoneid)
24860 {
24861 	ipoptp_t	opts;
24862 	uchar_t		*opt;
24863 	uint8_t		optval;
24864 	uint8_t		optlen;
24865 	ipaddr_t	dst;
24866 	intptr_t	code = 0;
24867 	mblk_t		*mp;
24868 	ire_t		*ire = NULL;
24869 
24870 	ip2dbg(("ip_wput_options\n"));
24871 	mp = ipsec_mp;
24872 	if (mctl_present) {
24873 		mp = ipsec_mp->b_cont;
24874 	}
24875 
24876 	dst = ipha->ipha_dst;
24877 	for (optval = ipoptp_first(&opts, ipha);
24878 	    optval != IPOPT_EOL;
24879 	    optval = ipoptp_next(&opts)) {
24880 		opt = opts.ipoptp_cur;
24881 		optlen = opts.ipoptp_len;
24882 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24883 		    optval, optlen));
24884 		switch (optval) {
24885 			uint32_t off;
24886 		case IPOPT_SSRR:
24887 		case IPOPT_LSRR:
24888 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24889 				ip1dbg((
24890 				    "ip_wput_options: bad option offset\n"));
24891 				code = (char *)&opt[IPOPT_OLEN] -
24892 				    (char *)ipha;
24893 				goto param_prob;
24894 			}
24895 			off = opt[IPOPT_OFFSET];
24896 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24897 			    ntohl(dst)));
24898 			/*
24899 			 * For strict: verify that dst is directly
24900 			 * reachable.
24901 			 */
24902 			if (optval == IPOPT_SSRR) {
24903 				ire = ire_ftable_lookup(dst, 0, 0,
24904 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24905 				    MATCH_IRE_TYPE);
24906 				if (ire == NULL) {
24907 					ip1dbg(("ip_wput_options: SSRR not"
24908 					    " directly reachable: 0x%x\n",
24909 					    ntohl(dst)));
24910 					goto bad_src_route;
24911 				}
24912 				ire_refrele(ire);
24913 			}
24914 			break;
24915 		case IPOPT_RR:
24916 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24917 				ip1dbg((
24918 				    "ip_wput_options: bad option offset\n"));
24919 				code = (char *)&opt[IPOPT_OLEN] -
24920 				    (char *)ipha;
24921 				goto param_prob;
24922 			}
24923 			break;
24924 		case IPOPT_TS:
24925 			/*
24926 			 * Verify that length >=5 and that there is either
24927 			 * room for another timestamp or that the overflow
24928 			 * counter is not maxed out.
24929 			 */
24930 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24931 			if (optlen < IPOPT_MINLEN_IT) {
24932 				goto param_prob;
24933 			}
24934 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24935 				ip1dbg((
24936 				    "ip_wput_options: bad option offset\n"));
24937 				code = (char *)&opt[IPOPT_OFFSET] -
24938 				    (char *)ipha;
24939 				goto param_prob;
24940 			}
24941 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24942 			case IPOPT_TS_TSONLY:
24943 				off = IPOPT_TS_TIMELEN;
24944 				break;
24945 			case IPOPT_TS_TSANDADDR:
24946 			case IPOPT_TS_PRESPEC:
24947 			case IPOPT_TS_PRESPEC_RFC791:
24948 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24949 				break;
24950 			default:
24951 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24952 				    (char *)ipha;
24953 				goto param_prob;
24954 			}
24955 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24956 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24957 				/*
24958 				 * No room and the overflow counter is 15
24959 				 * already.
24960 				 */
24961 				goto param_prob;
24962 			}
24963 			break;
24964 		}
24965 	}
24966 
24967 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24968 		return (0);
24969 
24970 	ip1dbg(("ip_wput_options: error processing IP options."));
24971 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24972 
24973 param_prob:
24974 	/*
24975 	 * Since ip_wput() isn't close to finished, we fill
24976 	 * in enough of the header for credible error reporting.
24977 	 */
24978 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24979 		/* Failed */
24980 		freemsg(ipsec_mp);
24981 		return (-1);
24982 	}
24983 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24984 	return (-1);
24985 
24986 bad_src_route:
24987 	/*
24988 	 * Since ip_wput() isn't close to finished, we fill
24989 	 * in enough of the header for credible error reporting.
24990 	 */
24991 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24992 		/* Failed */
24993 		freemsg(ipsec_mp);
24994 		return (-1);
24995 	}
24996 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24997 	return (-1);
24998 }
24999 
25000 /*
25001  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25002  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25003  * thru /etc/system.
25004  */
25005 #define	CONN_MAXDRAINCNT	64
25006 
25007 static void
25008 conn_drain_init(void)
25009 {
25010 	int i;
25011 
25012 	conn_drain_list_cnt = conn_drain_nthreads;
25013 
25014 	if ((conn_drain_list_cnt == 0) ||
25015 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25016 		/*
25017 		 * Default value of the number of drainers is the
25018 		 * number of cpus, subject to maximum of 8 drainers.
25019 		 */
25020 		if (boot_max_ncpus != -1)
25021 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25022 		else
25023 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25024 	}
25025 
25026 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25027 	    KM_SLEEP);
25028 
25029 	for (i = 0; i < conn_drain_list_cnt; i++) {
25030 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25031 		    MUTEX_DEFAULT, NULL);
25032 	}
25033 }
25034 
25035 static void
25036 conn_drain_fini(void)
25037 {
25038 	int i;
25039 
25040 	for (i = 0; i < conn_drain_list_cnt; i++)
25041 		mutex_destroy(&conn_drain_list[i].idl_lock);
25042 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25043 	conn_drain_list = NULL;
25044 }
25045 
25046 /*
25047  * Note: For an overview of how flowcontrol is handled in IP please see the
25048  * IP Flowcontrol notes at the top of this file.
25049  *
25050  * Flow control has blocked us from proceeding. Insert the given conn in one
25051  * of the conn drain lists. These conn wq's will be qenabled later on when
25052  * STREAMS flow control does a backenable. conn_walk_drain will enable
25053  * the first conn in each of these drain lists. Each of these qenabled conns
25054  * in turn enables the next in the list, after it runs, or when it closes,
25055  * thus sustaining the drain process.
25056  *
25057  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25058  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25059  * running at any time, on a given conn, since there can be only 1 service proc
25060  * running on a queue at any time.
25061  */
25062 void
25063 conn_drain_insert(conn_t *connp)
25064 {
25065 	idl_t	*idl;
25066 	uint_t	index;
25067 
25068 	mutex_enter(&connp->conn_lock);
25069 	if (connp->conn_state_flags & CONN_CLOSING) {
25070 		/*
25071 		 * The conn is closing as a result of which CONN_CLOSING
25072 		 * is set. Return.
25073 		 */
25074 		mutex_exit(&connp->conn_lock);
25075 		return;
25076 	} else if (connp->conn_idl == NULL) {
25077 		/*
25078 		 * Assign the next drain list round robin. We dont' use
25079 		 * a lock, and thus it may not be strictly round robin.
25080 		 * Atomicity of load/stores is enough to make sure that
25081 		 * conn_drain_list_index is always within bounds.
25082 		 */
25083 		index = conn_drain_list_index;
25084 		ASSERT(index < conn_drain_list_cnt);
25085 		connp->conn_idl = &conn_drain_list[index];
25086 		index++;
25087 		if (index == conn_drain_list_cnt)
25088 			index = 0;
25089 		conn_drain_list_index = index;
25090 	}
25091 	mutex_exit(&connp->conn_lock);
25092 
25093 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25094 	if ((connp->conn_drain_prev != NULL) ||
25095 	    (connp->conn_state_flags & CONN_CLOSING)) {
25096 		/*
25097 		 * The conn is already in the drain list, OR
25098 		 * the conn is closing. We need to check again for
25099 		 * the closing case again since close can happen
25100 		 * after we drop the conn_lock, and before we
25101 		 * acquire the CONN_DRAIN_LIST_LOCK.
25102 		 */
25103 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25104 		return;
25105 	} else {
25106 		idl = connp->conn_idl;
25107 	}
25108 
25109 	/*
25110 	 * The conn is not in the drain list. Insert it at the
25111 	 * tail of the drain list. The drain list is circular
25112 	 * and doubly linked. idl_conn points to the 1st element
25113 	 * in the list.
25114 	 */
25115 	if (idl->idl_conn == NULL) {
25116 		idl->idl_conn = connp;
25117 		connp->conn_drain_next = connp;
25118 		connp->conn_drain_prev = connp;
25119 	} else {
25120 		conn_t *head = idl->idl_conn;
25121 
25122 		connp->conn_drain_next = head;
25123 		connp->conn_drain_prev = head->conn_drain_prev;
25124 		head->conn_drain_prev->conn_drain_next = connp;
25125 		head->conn_drain_prev = connp;
25126 	}
25127 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25128 }
25129 
25130 /*
25131  * This conn is closing, and we are called from ip_close. OR
25132  * This conn has been serviced by ip_wsrv, and we need to do the tail
25133  * processing.
25134  * If this conn is part of the drain list, we may need to sustain the drain
25135  * process by qenabling the next conn in the drain list. We may also need to
25136  * remove this conn from the list, if it is done.
25137  */
25138 static void
25139 conn_drain_tail(conn_t *connp, boolean_t closing)
25140 {
25141 	idl_t *idl;
25142 
25143 	/*
25144 	 * connp->conn_idl is stable at this point, and no lock is needed
25145 	 * to check it. If we are called from ip_close, close has already
25146 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
25147 	 * called us only because conn_idl is non-null. If we are called thru
25148 	 * service, conn_idl could be null, but it cannot change because
25149 	 * service is single-threaded per queue, and there cannot be another
25150 	 * instance of service trying to call conn_drain_insert on this conn
25151 	 * now.
25152 	 */
25153 	ASSERT(!closing || (connp->conn_idl != NULL));
25154 
25155 	/*
25156 	 * If connp->conn_idl is null, the conn has not been inserted into any
25157 	 * drain list even once since creation of the conn. Just return.
25158 	 */
25159 	if (connp->conn_idl == NULL)
25160 		return;
25161 
25162 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25163 
25164 	if (connp->conn_drain_prev == NULL) {
25165 		/* This conn is currently not in the drain list.  */
25166 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25167 		return;
25168 	}
25169 	idl = connp->conn_idl;
25170 	if (idl->idl_conn_draining == connp) {
25171 		/*
25172 		 * This conn is the current drainer. If this is the last conn
25173 		 * in the drain list, we need to do more checks, in the 'if'
25174 		 * below. Otherwwise we need to just qenable the next conn,
25175 		 * to sustain the draining, and is handled in the 'else'
25176 		 * below.
25177 		 */
25178 		if (connp->conn_drain_next == idl->idl_conn) {
25179 			/*
25180 			 * This conn is the last in this list. This round
25181 			 * of draining is complete. If idl_repeat is set,
25182 			 * it means another flow enabling has happened from
25183 			 * the driver/streams and we need to another round
25184 			 * of draining.
25185 			 * If there are more than 2 conns in the drain list,
25186 			 * do a left rotate by 1, so that all conns except the
25187 			 * conn at the head move towards the head by 1, and the
25188 			 * the conn at the head goes to the tail. This attempts
25189 			 * a more even share for all queues that are being
25190 			 * drained.
25191 			 */
25192 			if ((connp->conn_drain_next != connp) &&
25193 			    (idl->idl_conn->conn_drain_next != connp)) {
25194 				idl->idl_conn = idl->idl_conn->conn_drain_next;
25195 			}
25196 			if (idl->idl_repeat) {
25197 				qenable(idl->idl_conn->conn_wq);
25198 				idl->idl_conn_draining = idl->idl_conn;
25199 				idl->idl_repeat = 0;
25200 			} else {
25201 				idl->idl_conn_draining = NULL;
25202 			}
25203 		} else {
25204 			/*
25205 			 * If the next queue that we are now qenable'ing,
25206 			 * is closing, it will remove itself from this list
25207 			 * and qenable the subsequent queue in ip_close().
25208 			 * Serialization is acheived thru idl_lock.
25209 			 */
25210 			qenable(connp->conn_drain_next->conn_wq);
25211 			idl->idl_conn_draining = connp->conn_drain_next;
25212 		}
25213 	}
25214 	if (!connp->conn_did_putbq || closing) {
25215 		/*
25216 		 * Remove ourself from the drain list, if we did not do
25217 		 * a putbq, or if the conn is closing.
25218 		 * Note: It is possible that q->q_first is non-null. It means
25219 		 * that these messages landed after we did a enableok() in
25220 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
25221 		 * service them.
25222 		 */
25223 		if (connp->conn_drain_next == connp) {
25224 			/* Singleton in the list */
25225 			ASSERT(connp->conn_drain_prev == connp);
25226 			idl->idl_conn = NULL;
25227 			idl->idl_conn_draining = NULL;
25228 		} else {
25229 			connp->conn_drain_prev->conn_drain_next =
25230 			    connp->conn_drain_next;
25231 			connp->conn_drain_next->conn_drain_prev =
25232 			    connp->conn_drain_prev;
25233 			if (idl->idl_conn == connp)
25234 				idl->idl_conn = connp->conn_drain_next;
25235 			ASSERT(idl->idl_conn_draining != connp);
25236 
25237 		}
25238 		connp->conn_drain_next = NULL;
25239 		connp->conn_drain_prev = NULL;
25240 	}
25241 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25242 }
25243 
25244 /*
25245  * Write service routine. Shared perimeter entry point.
25246  * ip_wsrv can be called in any of the following ways.
25247  * 1. The device queue's messages has fallen below the low water mark
25248  *    and STREAMS has backenabled the ill_wq. We walk thru all the
25249  *    the drain lists and backenable the first conn in each list.
25250  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
25251  *    qenabled non-tcp upper layers. We start dequeing messages and call
25252  *    ip_wput for each message.
25253  */
25254 
25255 void
25256 ip_wsrv(queue_t *q)
25257 {
25258 	conn_t	*connp;
25259 	ill_t	*ill;
25260 	mblk_t	*mp;
25261 
25262 	if (q->q_next) {
25263 		ill = (ill_t *)q->q_ptr;
25264 		if (ill->ill_state_flags == 0) {
25265 			/*
25266 			 * The device flow control has opened up.
25267 			 * Walk through conn drain lists and qenable the
25268 			 * first conn in each list. This makes sense only
25269 			 * if the stream is fully plumbed and setup.
25270 			 * Hence the if check above.
25271 			 */
25272 			ip1dbg(("ip_wsrv: walking\n"));
25273 			conn_walk_drain();
25274 		}
25275 		return;
25276 	}
25277 
25278 	connp = Q_TO_CONN(q);
25279 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
25280 
25281 	/*
25282 	 * 1. Set conn_draining flag to signal that service is active.
25283 	 *
25284 	 * 2. ip_output determines whether it has been called from service,
25285 	 *    based on the last parameter. If it is IP_WSRV it concludes it
25286 	 *    has been called from service.
25287 	 *
25288 	 * 3. Message ordering is preserved by the following logic.
25289 	 *    i. A directly called ip_output (i.e. not thru service) will queue
25290 	 *    the message at the tail, if conn_draining is set (i.e. service
25291 	 *    is running) or if q->q_first is non-null.
25292 	 *
25293 	 *    ii. If ip_output is called from service, and if ip_output cannot
25294 	 *    putnext due to flow control, it does a putbq.
25295 	 *
25296 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
25297 	 *    (causing an infinite loop).
25298 	 */
25299 	ASSERT(!connp->conn_did_putbq);
25300 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
25301 		connp->conn_draining = 1;
25302 		noenable(q);
25303 		while ((mp = getq(q)) != NULL) {
25304 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
25305 			if (connp->conn_did_putbq) {
25306 				/* ip_wput did a putbq */
25307 				break;
25308 			}
25309 		}
25310 		/*
25311 		 * At this point, a thread coming down from top, calling
25312 		 * ip_wput, may end up queueing the message. We have not yet
25313 		 * enabled the queue, so ip_wsrv won't be called again.
25314 		 * To avoid this race, check q->q_first again (in the loop)
25315 		 * If the other thread queued the message before we call
25316 		 * enableok(), we will catch it in the q->q_first check.
25317 		 * If the other thread queues the message after we call
25318 		 * enableok(), ip_wsrv will be called again by STREAMS.
25319 		 */
25320 		connp->conn_draining = 0;
25321 		enableok(q);
25322 	}
25323 
25324 	/* Enable the next conn for draining */
25325 	conn_drain_tail(connp, B_FALSE);
25326 
25327 	connp->conn_did_putbq = 0;
25328 }
25329 
25330 /*
25331  * Walk the list of all conn's calling the function provided with the
25332  * specified argument for each.	 Note that this only walks conn's that
25333  * have been bound.
25334  * Applies to both IPv4 and IPv6.
25335  */
25336 static void
25337 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
25338 {
25339 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
25340 	    func, arg, zoneid);
25341 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
25342 	    func, arg, zoneid);
25343 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
25344 	    func, arg, zoneid);
25345 	conn_walk_fanout_table(ipcl_proto_fanout,
25346 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
25347 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
25348 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
25349 }
25350 
25351 /*
25352  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
25353  * of conns that need to be drained, check if drain is already in progress.
25354  * If so set the idl_repeat bit, indicating that the last conn in the list
25355  * needs to reinitiate the drain once again, for the list. If drain is not
25356  * in progress for the list, initiate the draining, by qenabling the 1st
25357  * conn in the list. The drain is self-sustaining, each qenabled conn will
25358  * in turn qenable the next conn, when it is done/blocked/closing.
25359  */
25360 static void
25361 conn_walk_drain(void)
25362 {
25363 	int i;
25364 	idl_t *idl;
25365 
25366 	IP_STAT(ip_conn_walk_drain);
25367 
25368 	for (i = 0; i < conn_drain_list_cnt; i++) {
25369 		idl = &conn_drain_list[i];
25370 		mutex_enter(&idl->idl_lock);
25371 		if (idl->idl_conn == NULL) {
25372 			mutex_exit(&idl->idl_lock);
25373 			continue;
25374 		}
25375 		/*
25376 		 * If this list is not being drained currently by
25377 		 * an ip_wsrv thread, start the process.
25378 		 */
25379 		if (idl->idl_conn_draining == NULL) {
25380 			ASSERT(idl->idl_repeat == 0);
25381 			qenable(idl->idl_conn->conn_wq);
25382 			idl->idl_conn_draining = idl->idl_conn;
25383 		} else {
25384 			idl->idl_repeat = 1;
25385 		}
25386 		mutex_exit(&idl->idl_lock);
25387 	}
25388 }
25389 
25390 /*
25391  * Walk an conn hash table of `count' buckets, calling func for each entry.
25392  */
25393 static void
25394 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
25395     zoneid_t zoneid)
25396 {
25397 	conn_t	*connp;
25398 
25399 	while (count-- > 0) {
25400 		mutex_enter(&connfp->connf_lock);
25401 		for (connp = connfp->connf_head; connp != NULL;
25402 		    connp = connp->conn_next) {
25403 			if (zoneid == GLOBAL_ZONEID ||
25404 			    zoneid == connp->conn_zoneid) {
25405 				CONN_INC_REF(connp);
25406 				mutex_exit(&connfp->connf_lock);
25407 				(*func)(connp, arg);
25408 				mutex_enter(&connfp->connf_lock);
25409 				CONN_DEC_REF(connp);
25410 			}
25411 		}
25412 		mutex_exit(&connfp->connf_lock);
25413 		connfp++;
25414 	}
25415 }
25416 
25417 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
25418 static void
25419 conn_report1(conn_t *connp, void *mp)
25420 {
25421 	char	buf1[INET6_ADDRSTRLEN];
25422 	char	buf2[INET6_ADDRSTRLEN];
25423 	uint_t	print_len, buf_len;
25424 
25425 	ASSERT(connp != NULL);
25426 
25427 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
25428 	if (buf_len <= 0)
25429 		return;
25430 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
25431 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
25432 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
25433 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
25434 	    "%5d %s/%05d %s/%05d\n",
25435 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
25436 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
25437 	    buf1, connp->conn_lport,
25438 	    buf2, connp->conn_fport);
25439 	if (print_len < buf_len) {
25440 		((mblk_t *)mp)->b_wptr += print_len;
25441 	} else {
25442 		((mblk_t *)mp)->b_wptr += buf_len;
25443 	}
25444 }
25445 
25446 /*
25447  * Named Dispatch routine to produce a formatted report on all conns
25448  * that are listed in one of the fanout tables.
25449  * This report is accessed by using the ndd utility to "get" ND variable
25450  * "ip_conn_status".
25451  */
25452 /* ARGSUSED */
25453 static int
25454 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
25455 {
25456 	(void) mi_mpprintf(mp,
25457 	    "CONN      " MI_COL_HDRPAD_STR
25458 	    "rfq      " MI_COL_HDRPAD_STR
25459 	    "stq      " MI_COL_HDRPAD_STR
25460 	    " zone local                 remote");
25461 
25462 	/*
25463 	 * Because of the ndd constraint, at most we can have 64K buffer
25464 	 * to put in all conn info.  So to be more efficient, just
25465 	 * allocate a 64K buffer here, assuming we need that large buffer.
25466 	 * This should be OK as only privileged processes can do ndd /dev/ip.
25467 	 */
25468 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
25469 		/* The following may work even if we cannot get a large buf. */
25470 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
25471 		return (0);
25472 	}
25473 
25474 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
25475 	return (0);
25476 }
25477 
25478 /*
25479  * Determine if the ill and multicast aspects of that packets
25480  * "matches" the conn.
25481  */
25482 boolean_t
25483 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
25484     zoneid_t zoneid)
25485 {
25486 	ill_t *in_ill;
25487 	boolean_t found;
25488 	ipif_t *ipif;
25489 	ire_t *ire;
25490 	ipaddr_t dst, src;
25491 
25492 	dst = ipha->ipha_dst;
25493 	src = ipha->ipha_src;
25494 
25495 	/*
25496 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
25497 	 * unicast, broadcast and multicast reception to
25498 	 * conn_incoming_ill. conn_wantpacket itself is called
25499 	 * only for BROADCAST and multicast.
25500 	 *
25501 	 * 1) ip_rput supresses duplicate broadcasts if the ill
25502 	 *    is part of a group. Hence, we should be receiving
25503 	 *    just one copy of broadcast for the whole group.
25504 	 *    Thus, if it is part of the group the packet could
25505 	 *    come on any ill of the group and hence we need a
25506 	 *    match on the group. Otherwise, match on ill should
25507 	 *    be sufficient.
25508 	 *
25509 	 * 2) ip_rput does not suppress duplicate multicast packets.
25510 	 *    If there are two interfaces in a ill group and we have
25511 	 *    2 applications (conns) joined a multicast group G on
25512 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25513 	 *    will give us two packets because we join G on both the
25514 	 *    interfaces rather than nominating just one interface
25515 	 *    for receiving multicast like broadcast above. So,
25516 	 *    we have to call ilg_lookup_ill to filter out duplicate
25517 	 *    copies, if ill is part of a group.
25518 	 */
25519 	in_ill = connp->conn_incoming_ill;
25520 	if (in_ill != NULL) {
25521 		if (in_ill->ill_group == NULL) {
25522 			if (in_ill != ill)
25523 				return (B_FALSE);
25524 		} else if (in_ill->ill_group != ill->ill_group) {
25525 			return (B_FALSE);
25526 		}
25527 	}
25528 
25529 	if (!CLASSD(dst)) {
25530 		if (connp->conn_zoneid == zoneid)
25531 			return (B_TRUE);
25532 		/*
25533 		 * The conn is in a different zone; we need to check that this
25534 		 * broadcast address is configured in the application's zone and
25535 		 * on one ill in the group.
25536 		 */
25537 		ipif = ipif_get_next_ipif(NULL, ill);
25538 		if (ipif == NULL)
25539 			return (B_FALSE);
25540 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25541 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25542 		ipif_refrele(ipif);
25543 		if (ire != NULL) {
25544 			ire_refrele(ire);
25545 			return (B_TRUE);
25546 		} else {
25547 			return (B_FALSE);
25548 		}
25549 	}
25550 
25551 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25552 	    connp->conn_zoneid == zoneid) {
25553 		/*
25554 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25555 		 * disabled, therefore we don't dispatch the multicast packet to
25556 		 * the sending zone.
25557 		 */
25558 		return (B_FALSE);
25559 	}
25560 
25561 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25562 	    connp->conn_zoneid != zoneid) {
25563 		/*
25564 		 * Multicast packet on the loopback interface: we only match
25565 		 * conns who joined the group in the specified zone.
25566 		 */
25567 		return (B_FALSE);
25568 	}
25569 
25570 	if (connp->conn_multi_router) {
25571 		/* multicast packet and multicast router socket: send up */
25572 		return (B_TRUE);
25573 	}
25574 
25575 	mutex_enter(&connp->conn_lock);
25576 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25577 	mutex_exit(&connp->conn_lock);
25578 	return (found);
25579 }
25580 
25581 /*
25582  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25583  */
25584 /* ARGSUSED */
25585 static void
25586 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25587 {
25588 	ill_t *ill = (ill_t *)q->q_ptr;
25589 	mblk_t	*mp1, *mp2;
25590 	ipif_t  *ipif;
25591 	int err = 0;
25592 	conn_t *connp = NULL;
25593 	ipsq_t	*ipsq;
25594 	arc_t	*arc;
25595 
25596 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25597 
25598 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25599 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25600 
25601 	ASSERT(IAM_WRITER_ILL(ill));
25602 	mp2 = mp->b_cont;
25603 	mp->b_cont = NULL;
25604 
25605 	/*
25606 	 * We have now received the arp bringup completion message
25607 	 * from ARP. Mark the arp bringup as done. Also if the arp
25608 	 * stream has already started closing, send up the AR_ARP_CLOSING
25609 	 * ack now since ARP is waiting in close for this ack.
25610 	 */
25611 	mutex_enter(&ill->ill_lock);
25612 	ill->ill_arp_bringup_pending = 0;
25613 	if (ill->ill_arp_closing) {
25614 		mutex_exit(&ill->ill_lock);
25615 		/* Let's reuse the mp for sending the ack */
25616 		arc = (arc_t *)mp->b_rptr;
25617 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25618 		arc->arc_cmd = AR_ARP_CLOSING;
25619 		qreply(q, mp);
25620 	} else {
25621 		mutex_exit(&ill->ill_lock);
25622 		freeb(mp);
25623 	}
25624 
25625 	/* We should have an IOCTL waiting on this. */
25626 	ipsq = ill->ill_phyint->phyint_ipsq;
25627 	ipif = ipsq->ipsq_pending_ipif;
25628 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25629 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25630 	if (mp1 == NULL) {
25631 		/* bringup was aborted by the user */
25632 		freemsg(mp2);
25633 		return;
25634 	}
25635 	ASSERT(connp != NULL);
25636 	q = CONNP_TO_WQ(connp);
25637 	/*
25638 	 * If the DL_BIND_REQ fails, it is noted
25639 	 * in arc_name_offset.
25640 	 */
25641 	err = *((int *)mp2->b_rptr);
25642 	if (err == 0) {
25643 		if (ipif->ipif_isv6) {
25644 			if ((err = ipif_up_done_v6(ipif)) != 0)
25645 				ip0dbg(("ip_arp_done: init failed\n"));
25646 		} else {
25647 			if ((err = ipif_up_done(ipif)) != 0)
25648 				ip0dbg(("ip_arp_done: init failed\n"));
25649 		}
25650 	} else {
25651 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25652 	}
25653 
25654 	freemsg(mp2);
25655 
25656 	if ((err == 0) && (ill->ill_up_ipifs)) {
25657 		err = ill_up_ipifs(ill, q, mp1);
25658 		if (err == EINPROGRESS)
25659 			return;
25660 	}
25661 
25662 	if (ill->ill_up_ipifs) {
25663 		ill_group_cleanup(ill);
25664 	}
25665 
25666 	/*
25667 	 * The ioctl must complete now without EINPROGRESS
25668 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25669 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25670 	 * stuck for ever in the ipsq.
25671 	 */
25672 	ASSERT(err != EINPROGRESS);
25673 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25674 }
25675 
25676 /* Allocate the private structure */
25677 static int
25678 ip_priv_alloc(void **bufp)
25679 {
25680 	void	*buf;
25681 
25682 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25683 		return (ENOMEM);
25684 
25685 	*bufp = buf;
25686 	return (0);
25687 }
25688 
25689 /* Function to delete the private structure */
25690 void
25691 ip_priv_free(void *buf)
25692 {
25693 	ASSERT(buf != NULL);
25694 	kmem_free(buf, sizeof (ip_priv_t));
25695 }
25696 
25697 /*
25698  * The entry point for IPPF processing.
25699  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25700  * routine just returns.
25701  *
25702  * When called, ip_process generates an ipp_packet_t structure
25703  * which holds the state information for this packet and invokes the
25704  * the classifier (via ipp_packet_process). The classification, depending on
25705  * configured filters, results in a list of actions for this packet. Invoking
25706  * an action may cause the packet to be dropped, in which case the resulting
25707  * mblk (*mpp) is NULL. proc indicates the callout position for
25708  * this packet and ill_index is the interface this packet on or will leave
25709  * on (inbound and outbound resp.).
25710  */
25711 void
25712 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25713 {
25714 	mblk_t		*mp;
25715 	ip_priv_t	*priv;
25716 	ipp_action_id_t	aid;
25717 	int		rc = 0;
25718 	ipp_packet_t	*pp;
25719 #define	IP_CLASS	"ip"
25720 
25721 	/* If the classifier is not loaded, return  */
25722 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25723 		return;
25724 	}
25725 
25726 	mp = *mpp;
25727 	ASSERT(mp != NULL);
25728 
25729 	/* Allocate the packet structure */
25730 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25731 	if (rc != 0) {
25732 		*mpp = NULL;
25733 		freemsg(mp);
25734 		return;
25735 	}
25736 
25737 	/* Allocate the private structure */
25738 	rc = ip_priv_alloc((void **)&priv);
25739 	if (rc != 0) {
25740 		*mpp = NULL;
25741 		freemsg(mp);
25742 		ipp_packet_free(pp);
25743 		return;
25744 	}
25745 	priv->proc = proc;
25746 	priv->ill_index = ill_index;
25747 	ipp_packet_set_private(pp, priv, ip_priv_free);
25748 	ipp_packet_set_data(pp, mp);
25749 
25750 	/* Invoke the classifier */
25751 	rc = ipp_packet_process(&pp);
25752 	if (pp != NULL) {
25753 		mp = ipp_packet_get_data(pp);
25754 		ipp_packet_free(pp);
25755 		if (rc != 0) {
25756 			freemsg(mp);
25757 			*mpp = NULL;
25758 		}
25759 	} else {
25760 		*mpp = NULL;
25761 	}
25762 #undef	IP_CLASS
25763 }
25764 
25765 /*
25766  * Propagate a multicast group membership operation (add/drop) on
25767  * all the interfaces crossed by the related multirt routes.
25768  * The call is considered successful if the operation succeeds
25769  * on at least one interface.
25770  */
25771 static int
25772 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25773     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25774     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25775     mblk_t *first_mp)
25776 {
25777 	ire_t		*ire_gw;
25778 	irb_t		*irb;
25779 	int		error = 0;
25780 	opt_restart_t	*or;
25781 
25782 	irb = ire->ire_bucket;
25783 	ASSERT(irb != NULL);
25784 
25785 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25786 
25787 	or = (opt_restart_t *)first_mp->b_rptr;
25788 	IRB_REFHOLD(irb);
25789 	for (; ire != NULL; ire = ire->ire_next) {
25790 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25791 			continue;
25792 		if (ire->ire_addr != group)
25793 			continue;
25794 
25795 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25796 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25797 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25798 		/* No resolver exists for the gateway; skip this ire. */
25799 		if (ire_gw == NULL)
25800 			continue;
25801 
25802 		/*
25803 		 * This function can return EINPROGRESS. If so the operation
25804 		 * will be restarted from ip_restart_optmgmt which will
25805 		 * call ip_opt_set and option processing will restart for
25806 		 * this option. So we may end up calling 'fn' more than once.
25807 		 * This requires that 'fn' is idempotent except for the
25808 		 * return value. The operation is considered a success if
25809 		 * it succeeds at least once on any one interface.
25810 		 */
25811 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25812 		    NULL, fmode, src, first_mp);
25813 		if (error == 0)
25814 			or->or_private = CGTP_MCAST_SUCCESS;
25815 
25816 		if (ip_debug > 0) {
25817 			ulong_t	off;
25818 			char	*ksym;
25819 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25820 			ip2dbg(("ip_multirt_apply_membership: "
25821 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25822 			    "error %d [success %u]\n",
25823 			    ksym ? ksym : "?",
25824 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25825 			    error, or->or_private));
25826 		}
25827 
25828 		ire_refrele(ire_gw);
25829 		if (error == EINPROGRESS) {
25830 			IRB_REFRELE(irb);
25831 			return (error);
25832 		}
25833 	}
25834 	IRB_REFRELE(irb);
25835 	/*
25836 	 * Consider the call as successful if we succeeded on at least
25837 	 * one interface. Otherwise, return the last encountered error.
25838 	 */
25839 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25840 }
25841 
25842 
25843 /*
25844  * Issue a warning regarding a route crossing an interface with an
25845  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25846  * amount of time is logged.
25847  */
25848 static void
25849 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25850 {
25851 	hrtime_t	current = gethrtime();
25852 	char		buf[16];
25853 
25854 	/* Convert interval in ms to hrtime in ns */
25855 	if (multirt_bad_mtu_last_time +
25856 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25857 	    current) {
25858 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25859 		    "to %s, incorrect MTU %u (expected %u)\n",
25860 		    ip_dot_addr(ire->ire_addr, buf),
25861 		    ire->ire_max_frag, max_frag);
25862 
25863 		multirt_bad_mtu_last_time = current;
25864 	}
25865 }
25866 
25867 
25868 /*
25869  * Get the CGTP (multirouting) filtering status.
25870  * If 0, the CGTP hooks are transparent.
25871  */
25872 /* ARGSUSED */
25873 static int
25874 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25875 {
25876 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25877 
25878 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25879 	return (0);
25880 }
25881 
25882 
25883 /*
25884  * Set the CGTP (multirouting) filtering status.
25885  * If the status is changed from active to transparent
25886  * or from transparent to active, forward the new status
25887  * to the filtering module (if loaded).
25888  */
25889 /* ARGSUSED */
25890 static int
25891 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25892     cred_t *ioc_cr)
25893 {
25894 	long		new_value;
25895 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25896 
25897 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25898 	    new_value < 0 || new_value > 1) {
25899 		return (EINVAL);
25900 	}
25901 
25902 	/*
25903 	 * Do not enable CGTP filtering - thus preventing the hooks
25904 	 * from being invoked - if the version number of the
25905 	 * filtering module hooks does not match.
25906 	 */
25907 	if ((ip_cgtp_filter_ops != NULL) &&
25908 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25909 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25910 		    "(module hooks version %d, expecting %d)\n",
25911 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25912 		return (ENOTSUP);
25913 	}
25914 
25915 	if ((!*ip_cgtp_filter_value) && new_value) {
25916 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25917 		    ip_cgtp_filter_ops == NULL ?
25918 		    " (module not loaded)" : "");
25919 	}
25920 	if (*ip_cgtp_filter_value && (!new_value)) {
25921 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25922 		    ip_cgtp_filter_ops == NULL ?
25923 		    " (module not loaded)" : "");
25924 	}
25925 
25926 	if (ip_cgtp_filter_ops != NULL) {
25927 		int	res;
25928 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25929 			return (res);
25930 		}
25931 	}
25932 
25933 	*ip_cgtp_filter_value = (boolean_t)new_value;
25934 
25935 	return (0);
25936 }
25937 
25938 
25939 /*
25940  * Return the expected CGTP hooks version number.
25941  */
25942 int
25943 ip_cgtp_filter_supported(void)
25944 {
25945 	return (ip_cgtp_filter_rev);
25946 }
25947 
25948 
25949 /*
25950  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25951  * or by invoking this function. In the first case, the version number
25952  * of the registered structure is checked at hooks activation time
25953  * in ip_cgtp_filter_set().
25954  */
25955 int
25956 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25957 {
25958 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25959 		return (ENOTSUP);
25960 
25961 	ip_cgtp_filter_ops = ops;
25962 	return (0);
25963 }
25964 
25965 static squeue_func_t
25966 ip_squeue_switch(int val)
25967 {
25968 	squeue_func_t rval = squeue_fill;
25969 
25970 	switch (val) {
25971 	case IP_SQUEUE_ENTER_NODRAIN:
25972 		rval = squeue_enter_nodrain;
25973 		break;
25974 	case IP_SQUEUE_ENTER:
25975 		rval = squeue_enter;
25976 		break;
25977 	default:
25978 		break;
25979 	}
25980 	return (rval);
25981 }
25982 
25983 /* ARGSUSED */
25984 static int
25985 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25986     caddr_t addr, cred_t *cr)
25987 {
25988 	int *v = (int *)addr;
25989 	long new_value;
25990 
25991 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25992 		return (EINVAL);
25993 
25994 	ip_input_proc = ip_squeue_switch(new_value);
25995 	*v = new_value;
25996 	return (0);
25997 }
25998 
25999 /* ARGSUSED */
26000 static int
26001 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26002     caddr_t addr, cred_t *cr)
26003 {
26004 	int *v = (int *)addr;
26005 	long new_value;
26006 
26007 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26008 		return (EINVAL);
26009 
26010 	*v = new_value;
26011 	return (0);
26012 }
26013 
26014 static void
26015 ip_kstat_init(void)
26016 {
26017 	ip_named_kstat_t template = {
26018 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26019 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26020 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26021 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26022 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26023 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26024 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26025 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26026 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26027 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26028 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26029 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26030 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26031 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26032 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26033 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26034 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26035 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26036 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26037 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26038 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26039 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26040 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26041 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26042 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26043 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26044 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26045 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26046 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26047 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26048 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26049 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26050 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26051 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26052 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26053 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26054 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26055 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26056 	};
26057 
26058 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26059 					NUM_OF_FIELDS(ip_named_kstat_t),
26060 					0);
26061 	if (!ip_mibkp)
26062 		return;
26063 
26064 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26065 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26066 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26067 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26068 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26069 
26070 	template.netToMediaEntrySize.value.i32 =
26071 		sizeof (mib2_ipNetToMediaEntry_t);
26072 
26073 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26074 
26075 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26076 
26077 	ip_mibkp->ks_update = ip_kstat_update;
26078 
26079 	kstat_install(ip_mibkp);
26080 }
26081 
26082 static void
26083 ip_kstat_fini(void)
26084 {
26085 
26086 	if (ip_mibkp != NULL) {
26087 		kstat_delete(ip_mibkp);
26088 		ip_mibkp = NULL;
26089 	}
26090 }
26091 
26092 static int
26093 ip_kstat_update(kstat_t *kp, int rw)
26094 {
26095 	ip_named_kstat_t *ipkp;
26096 
26097 	if (!kp || !kp->ks_data)
26098 		return (EIO);
26099 
26100 	if (rw == KSTAT_WRITE)
26101 		return (EACCES);
26102 
26103 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26104 
26105 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26106 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26107 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26108 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26109 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26110 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26111 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26112 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26113 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26114 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26115 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26116 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26117 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26118 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26119 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26120 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26121 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26122 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26123 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26124 
26125 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26126 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26127 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26128 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26129 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26130 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26131 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26132 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26133 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26134 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26135 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26136 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26137 
26138 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
26139 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
26140 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
26141 
26142 	return (0);
26143 }
26144 
26145 static void
26146 icmp_kstat_init(void)
26147 {
26148 	icmp_named_kstat_t template = {
26149 		{ "inMsgs",		KSTAT_DATA_UINT32 },
26150 		{ "inErrors",		KSTAT_DATA_UINT32 },
26151 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
26152 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
26153 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
26154 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
26155 		{ "inRedirects",	KSTAT_DATA_UINT32 },
26156 		{ "inEchos",		KSTAT_DATA_UINT32 },
26157 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
26158 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
26159 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
26160 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
26161 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
26162 		{ "outMsgs",		KSTAT_DATA_UINT32 },
26163 		{ "outErrors",		KSTAT_DATA_UINT32 },
26164 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
26165 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
26166 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
26167 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
26168 		{ "outRedirects",	KSTAT_DATA_UINT32 },
26169 		{ "outEchos",		KSTAT_DATA_UINT32 },
26170 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
26171 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
26172 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
26173 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
26174 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
26175 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
26176 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
26177 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
26178 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
26179 		{ "outDrops",		KSTAT_DATA_UINT32 },
26180 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
26181 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
26182 	};
26183 
26184 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
26185 					NUM_OF_FIELDS(icmp_named_kstat_t),
26186 					0);
26187 	if (icmp_mibkp == NULL)
26188 		return;
26189 
26190 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
26191 
26192 	icmp_mibkp->ks_update = icmp_kstat_update;
26193 
26194 	kstat_install(icmp_mibkp);
26195 }
26196 
26197 static void
26198 icmp_kstat_fini(void)
26199 {
26200 
26201 	if (icmp_mibkp != NULL) {
26202 		kstat_delete(icmp_mibkp);
26203 		icmp_mibkp = NULL;
26204 	}
26205 }
26206 
26207 static int
26208 icmp_kstat_update(kstat_t *kp, int rw)
26209 {
26210 	icmp_named_kstat_t *icmpkp;
26211 
26212 	if ((kp == NULL) || (kp->ks_data == NULL))
26213 		return (EIO);
26214 
26215 	if (rw == KSTAT_WRITE)
26216 		return (EACCES);
26217 
26218 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
26219 
26220 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
26221 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
26222 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
26223 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
26224 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
26225 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
26226 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
26227 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
26228 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
26229 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
26230 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
26231 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
26232 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
26233 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
26234 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
26235 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
26236 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
26237 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
26238 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
26239 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
26240 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
26241 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
26242 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
26243 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
26244 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
26245 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
26246 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
26247 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
26248 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
26249 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
26250 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
26251 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
26252 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
26253 
26254 	return (0);
26255 }
26256 
26257 /*
26258  * This is the fanout function for raw socket opened for SCTP.  Note
26259  * that it is called after SCTP checks that there is no socket which
26260  * wants a packet.  Then before SCTP handles this out of the blue packet,
26261  * this function is called to see if there is any raw socket for SCTP.
26262  * If there is and it is bound to the correct address, the packet will
26263  * be sent to that socket.  Note that only one raw socket can be bound to
26264  * a port.  This is assured in ipcl_sctp_hash_insert();
26265  */
26266 void
26267 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
26268     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
26269     uint_t ipif_seqid, zoneid_t zoneid)
26270 {
26271 	conn_t		*connp;
26272 	queue_t		*rq;
26273 	mblk_t		*first_mp;
26274 	boolean_t	secure;
26275 	ip6_t		*ip6h;
26276 
26277 	first_mp = mp;
26278 	if (mctl_present) {
26279 		mp = first_mp->b_cont;
26280 		secure = ipsec_in_is_secure(first_mp);
26281 		ASSERT(mp != NULL);
26282 	} else {
26283 		secure = B_FALSE;
26284 	}
26285 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
26286 
26287 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
26288 	if (connp == NULL) {
26289 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
26290 		    mctl_present);
26291 		return;
26292 	}
26293 	rq = connp->conn_rq;
26294 	if (!canputnext(rq)) {
26295 		CONN_DEC_REF(connp);
26296 		BUMP_MIB(&ip_mib, rawipInOverflows);
26297 		freemsg(first_mp);
26298 		return;
26299 	}
26300 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
26301 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
26302 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
26303 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
26304 		if (first_mp == NULL) {
26305 			CONN_DEC_REF(connp);
26306 			return;
26307 		}
26308 	}
26309 	/*
26310 	 * We probably should not send M_CTL message up to
26311 	 * raw socket.
26312 	 */
26313 	if (mctl_present)
26314 		freeb(first_mp);
26315 
26316 	/* Initiate IPPF processing here if needed. */
26317 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
26318 	    (!isv4 && IP6_IN_IPP(flags))) {
26319 		ip_process(IPP_LOCAL_IN, &mp,
26320 		    recv_ill->ill_phyint->phyint_ifindex);
26321 		if (mp == NULL) {
26322 			CONN_DEC_REF(connp);
26323 			return;
26324 		}
26325 	}
26326 
26327 	if (connp->conn_recvif || connp->conn_recvslla ||
26328 	    ((connp->conn_ipv6_recvpktinfo ||
26329 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
26330 	    (flags & IP_FF_IP6INFO))) {
26331 		int in_flags = 0;
26332 
26333 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
26334 			in_flags = IPF_RECVIF;
26335 		}
26336 		if (connp->conn_recvslla) {
26337 			in_flags |= IPF_RECVSLLA;
26338 		}
26339 		if (isv4) {
26340 			mp = ip_add_info(mp, recv_ill, in_flags);
26341 		} else {
26342 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
26343 			if (mp == NULL) {
26344 				CONN_DEC_REF(connp);
26345 				return;
26346 			}
26347 		}
26348 	}
26349 
26350 	BUMP_MIB(&ip_mib, ipInDelivers);
26351 	/*
26352 	 * We are sending the IPSEC_IN message also up. Refer
26353 	 * to comments above this function.
26354 	 */
26355 	putnext(rq, mp);
26356 	CONN_DEC_REF(connp);
26357 }
26358 
26359 /*
26360  * Martian Address Filtering [RFC 1812, Section 5.3.7]
26361  */
26362 static boolean_t
26363 ip_no_forward(ipha_t *ipha, ill_t *ill)
26364 {
26365 	ipaddr_t ip_src, ip_dst;
26366 	ire_t *src_ire = NULL;
26367 
26368 	ip_src = ntohl(ipha->ipha_src);
26369 	ip_dst = ntohl(ipha->ipha_dst);
26370 
26371 	if (ip_dst == INADDR_ANY)
26372 		goto dont_forward;
26373 
26374 	if (IN_CLASSD(ip_src))
26375 		goto dont_forward;
26376 
26377 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
26378 		goto dont_forward;
26379 
26380 	if (IN_BADCLASS(ip_dst))
26381 		goto dont_forward;
26382 
26383 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
26384 	    ALL_ZONES, MATCH_IRE_TYPE);
26385 	if (src_ire != NULL) {
26386 		ire_refrele(src_ire);
26387 		goto dont_forward;
26388 	}
26389 
26390 	return (B_FALSE);
26391 
26392 dont_forward:
26393 	if (ip_debug > 2) {
26394 		printf("ip_no_forward: dropping packet received on %s\n",
26395 		    ill->ill_name);
26396 		pr_addr_dbg("ip_no_forward: from src %s\n",
26397 		    AF_INET, &ipha->ipha_src);
26398 		pr_addr_dbg("ip_no_forward: to dst %s\n",
26399 		    AF_INET, &ipha->ipha_dst);
26400 	}
26401 	BUMP_MIB(&ip_mib, ipForwProhibits);
26402 	return (B_TRUE);
26403 }
26404 
26405 static boolean_t
26406 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
26407 {
26408 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
26409 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
26410 		if (ip_debug > 2) {
26411 			if (ill != NULL) {
26412 				printf("ip_loopback_src_or_dst: "
26413 				    "dropping packet received on %s\n",
26414 				    ill->ill_name);
26415 			} else {
26416 				printf("ip_loopback_src_or_dst: "
26417 				    "dropping packet\n");
26418 			}
26419 
26420 			pr_addr_dbg(
26421 			    "ip_loopback_src_or_dst: from src %s\n",
26422 			    AF_INET, &ipha->ipha_src);
26423 			pr_addr_dbg(
26424 			    "ip_loopback_src_or_dst: to dst %s\n",
26425 			    AF_INET, &ipha->ipha_dst);
26426 		}
26427 
26428 		BUMP_MIB(&ip_mib, ipInAddrErrors);
26429 		return (B_TRUE);
26430 	}
26431 	return (B_FALSE);
26432 }
26433