xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 7f7322febbcfe774b7270abc3b191c094bfcc517)
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 2006 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 			ASSERT(Q_TO_CONN(q) != NULL);
5728 			if (do_tcp_fusion &&
5729 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5730 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
5731 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
5732 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
5733 				sqp = Q_TO_CONN(q)->conn_sqp;
5734 			} else {
5735 				sqp = IP_SQUEUE_GET(lbolt);
5736 			}
5737 
5738 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5739 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
5740 			syn_present = B_TRUE;
5741 		}
5742 	}
5743 
5744 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5745 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5746 		if ((flags & TH_RST) || (flags & TH_URG)) {
5747 			CONN_DEC_REF(connp);
5748 			freemsg(first_mp);
5749 			return;
5750 		}
5751 		if (flags & TH_ACK) {
5752 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5753 			CONN_DEC_REF(connp);
5754 			return;
5755 		}
5756 
5757 		CONN_DEC_REF(connp);
5758 		freemsg(first_mp);
5759 		return;
5760 	}
5761 
5762 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5763 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5764 		    NULL, mctl_present);
5765 		if (first_mp == NULL) {
5766 			CONN_DEC_REF(connp);
5767 			return;
5768 		}
5769 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5770 			ASSERT(syn_present);
5771 			if (mctl_present) {
5772 				ASSERT(first_mp != mp);
5773 				first_mp->b_datap->db_struioflag |=
5774 				    STRUIO_POLICY;
5775 			} else {
5776 				ASSERT(first_mp == mp);
5777 				mp->b_datap->db_struioflag &=
5778 				    ~STRUIO_EAGER;
5779 				mp->b_datap->db_struioflag |=
5780 				    STRUIO_POLICY;
5781 			}
5782 		} else {
5783 			/*
5784 			 * Discard first_mp early since we're dealing with a
5785 			 * fully-connected conn_t and tcp doesn't do policy in
5786 			 * this case.
5787 			 */
5788 			if (mctl_present) {
5789 				freeb(first_mp);
5790 				mctl_present = B_FALSE;
5791 			}
5792 			first_mp = mp;
5793 		}
5794 	}
5795 
5796 	/*
5797 	 * Initiate policy processing here if needed. If we get here from
5798 	 * icmp_inbound_error_fanout, ip_policy is false.
5799 	 */
5800 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5801 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5802 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5803 		if (mp == NULL) {
5804 			CONN_DEC_REF(connp);
5805 			if (mctl_present)
5806 				freeb(first_mp);
5807 			return;
5808 		} else if (mctl_present) {
5809 			ASSERT(first_mp != mp);
5810 			first_mp->b_cont = mp;
5811 		} else {
5812 			first_mp = mp;
5813 		}
5814 	}
5815 
5816 
5817 
5818 	/* Handle IPv6 socket options. */
5819 	if (!syn_present &&
5820 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5821 		/* Add header */
5822 		ASSERT(recv_ill != NULL);
5823 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5824 		if (mp == NULL) {
5825 			CONN_DEC_REF(connp);
5826 			if (mctl_present)
5827 				freeb(first_mp);
5828 			return;
5829 		} else if (mctl_present) {
5830 			/*
5831 			 * ip_add_info might return a new mp.
5832 			 */
5833 			ASSERT(first_mp != mp);
5834 			first_mp->b_cont = mp;
5835 		} else {
5836 			first_mp = mp;
5837 		}
5838 	}
5839 
5840 	BUMP_MIB(&ip_mib, ipInDelivers);
5841 	if (IPCL_IS_TCP(connp)) {
5842 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5843 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5844 	} else {
5845 		putnext(connp->conn_rq, first_mp);
5846 		CONN_DEC_REF(connp);
5847 	}
5848 }
5849 
5850 /*
5851  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5852  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5853  * Caller is responsible for dropping references to the conn, and freeing
5854  * first_mp.
5855  *
5856  * IPQoS Notes
5857  * Before sending it to the client, invoke IPPF processing. Policy processing
5858  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5859  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5860  * ip_wput_local, ip_policy is false.
5861  */
5862 static void
5863 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5864     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5865     boolean_t ip_policy)
5866 {
5867 	boolean_t	mctl_present = (first_mp != NULL);
5868 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5869 	uint32_t	ill_index;
5870 
5871 	if (mctl_present)
5872 		first_mp->b_cont = mp;
5873 	else
5874 		first_mp = mp;
5875 
5876 	if (CONN_UDP_FLOWCTLD(connp)) {
5877 		BUMP_MIB(&ip_mib, udpInOverflows);
5878 		freemsg(first_mp);
5879 		return;
5880 	}
5881 
5882 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5883 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5884 		    NULL, mctl_present);
5885 		if (first_mp == NULL)
5886 			return;	/* Freed by ipsec_check_inbound_policy(). */
5887 	}
5888 	if (mctl_present)
5889 		freeb(first_mp);
5890 
5891 	if (connp->conn_recvif)
5892 		in_flags = IPF_RECVIF;
5893 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5894 		in_flags |= IPF_RECVSLLA;
5895 
5896 	/* Handle IPv6 options. */
5897 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5898 		in_flags |= IPF_RECVIF;
5899 
5900 	/*
5901 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5902 	 * freed if the packet is dropped. The caller will do so.
5903 	 */
5904 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5905 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5906 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5907 		if (mp == NULL) {
5908 			return;
5909 		}
5910 	}
5911 	if ((in_flags != 0) &&
5912 	    (mp->b_datap->db_type != M_CTL)) {
5913 		/*
5914 		 * The actual data will be contained in b_cont
5915 		 * upon successful return of the following call
5916 		 * else original mblk is returned
5917 		 */
5918 		ASSERT(recv_ill != NULL);
5919 		mp = ip_add_info(mp, recv_ill, in_flags);
5920 	}
5921 	BUMP_MIB(&ip_mib, ipInDelivers);
5922 
5923 	/* Send it upstream */
5924 	CONN_UDP_RECV(connp, mp);
5925 }
5926 
5927 /*
5928  * Fanout for UDP packets.
5929  * The caller puts <fport, lport> in the ports parameter.
5930  *
5931  * If SO_REUSEADDR is set all multicast and broadcast packets
5932  * will be delivered to all streams bound to the same port.
5933  *
5934  * Zones notes:
5935  * Multicast and broadcast packets will be distributed to streams in all zones.
5936  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5937  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5938  * packets. To maintain this behavior with multiple zones, the conns are grouped
5939  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5940  * each zone. If unset, all the following conns in the same zone are skipped.
5941  */
5942 static void
5943 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5944     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5945     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5946 {
5947 	uint32_t	dstport, srcport;
5948 	ipaddr_t	dst;
5949 	mblk_t		*first_mp;
5950 	boolean_t	secure;
5951 	in6_addr_t	v6src;
5952 	conn_t		*connp;
5953 	connf_t		*connfp;
5954 	conn_t		*first_connp;
5955 	conn_t		*next_connp;
5956 	mblk_t		*mp1, *first_mp1;
5957 	ipaddr_t	src;
5958 	zoneid_t	last_zoneid;
5959 	boolean_t	reuseaddr;
5960 
5961 	first_mp = mp;
5962 	if (mctl_present) {
5963 		mp = first_mp->b_cont;
5964 		first_mp->b_cont = NULL;
5965 		secure = ipsec_in_is_secure(first_mp);
5966 		ASSERT(mp != NULL);
5967 	} else {
5968 		first_mp = NULL;
5969 		secure = B_FALSE;
5970 	}
5971 
5972 	/* Extract ports in net byte order */
5973 	dstport = htons(ntohl(ports) & 0xFFFF);
5974 	srcport = htons(ntohl(ports) >> 16);
5975 	dst = ipha->ipha_dst;
5976 	src = ipha->ipha_src;
5977 
5978 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5979 	mutex_enter(&connfp->connf_lock);
5980 	connp = connfp->connf_head;
5981 	if (!broadcast && !CLASSD(dst)) {
5982 		/*
5983 		 * Not broadcast or multicast. Send to the one (first)
5984 		 * client we find. No need to check conn_wantpacket()
5985 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5986 		 * IPv4 unicast packets.
5987 		 */
5988 		while ((connp != NULL) &&
5989 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5990 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5991 			connp = connp->conn_next;
5992 		}
5993 
5994 		if (connp == NULL || connp->conn_upq == NULL)
5995 			goto notfound;
5996 		CONN_INC_REF(connp);
5997 		mutex_exit(&connfp->connf_lock);
5998 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5999 		    recv_ill, ip_policy);
6000 		IP_STAT(ip_udp_fannorm);
6001 		CONN_DEC_REF(connp);
6002 		return;
6003 	}
6004 
6005 	/*
6006 	 * Broadcast and multicast case
6007 	 *
6008 	 * Need to check conn_wantpacket().
6009 	 * If SO_REUSEADDR has been set on the first we send the
6010 	 * packet to all clients that have joined the group and
6011 	 * match the port.
6012 	 */
6013 
6014 	while (connp != NULL) {
6015 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6016 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6017 			break;
6018 		connp = connp->conn_next;
6019 	}
6020 
6021 	if (connp == NULL || connp->conn_upq == NULL)
6022 		goto notfound;
6023 
6024 	first_connp = connp;
6025 	/*
6026 	 * When SO_REUSEADDR is not set, send the packet only to the first
6027 	 * matching connection in its zone by keeping track of the zoneid.
6028 	 */
6029 	reuseaddr = first_connp->conn_reuseaddr;
6030 	last_zoneid = first_connp->conn_zoneid;
6031 
6032 	CONN_INC_REF(connp);
6033 	connp = connp->conn_next;
6034 	for (;;) {
6035 		while (connp != NULL) {
6036 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6037 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6038 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6039 				break;
6040 			connp = connp->conn_next;
6041 		}
6042 		/*
6043 		 * Just copy the data part alone. The mctl part is
6044 		 * needed just for verifying policy and it is never
6045 		 * sent up.
6046 		 */
6047 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6048 		    ((mp1 = copymsg(mp)) == NULL))) {
6049 			/*
6050 			 * No more interested clients or memory
6051 			 * allocation failed
6052 			 */
6053 			connp = first_connp;
6054 			break;
6055 		}
6056 		if (connp->conn_zoneid != last_zoneid) {
6057 			/*
6058 			 * Update the zoneid so that the packet isn't sent to
6059 			 * any more conns in the same zone unless SO_REUSEADDR
6060 			 * is set.
6061 			 */
6062 			reuseaddr = connp->conn_reuseaddr;
6063 			last_zoneid = connp->conn_zoneid;
6064 		}
6065 		if (first_mp != NULL) {
6066 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6067 			    ipsec_info_type == IPSEC_IN);
6068 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6069 			if (first_mp1 == NULL) {
6070 				freemsg(mp1);
6071 				connp = first_connp;
6072 				break;
6073 			}
6074 		} else {
6075 			first_mp1 = NULL;
6076 		}
6077 		CONN_INC_REF(connp);
6078 		mutex_exit(&connfp->connf_lock);
6079 		/*
6080 		 * IPQoS notes: We don't send the packet for policy
6081 		 * processing here, will do it for the last one (below).
6082 		 * i.e. we do it per-packet now, but if we do policy
6083 		 * processing per-conn, then we would need to do it
6084 		 * here too.
6085 		 */
6086 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6087 		    ipha, flags, recv_ill, B_FALSE);
6088 		mutex_enter(&connfp->connf_lock);
6089 		/* Follow the next pointer before releasing the conn. */
6090 		next_connp = connp->conn_next;
6091 		IP_STAT(ip_udp_fanmb);
6092 		CONN_DEC_REF(connp);
6093 		connp = next_connp;
6094 	}
6095 
6096 	/* Last one.  Send it upstream. */
6097 	mutex_exit(&connfp->connf_lock);
6098 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6099 	    ip_policy);
6100 	IP_STAT(ip_udp_fanmb);
6101 	CONN_DEC_REF(connp);
6102 	return;
6103 
6104 notfound:
6105 
6106 	mutex_exit(&connfp->connf_lock);
6107 	IP_STAT(ip_udp_fanothers);
6108 	/*
6109 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6110 	 * have already been matched above, since they live in the IPv4
6111 	 * fanout tables. This implies we only need to
6112 	 * check for IPv6 in6addr_any endpoints here.
6113 	 * Thus we compare using ipv6_all_zeros instead of the destination
6114 	 * address, except for the multicast group membership lookup which
6115 	 * uses the IPv4 destination.
6116 	 */
6117 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6118 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6119 	mutex_enter(&connfp->connf_lock);
6120 	connp = connfp->connf_head;
6121 	if (!broadcast && !CLASSD(dst)) {
6122 		while (connp != NULL) {
6123 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6124 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6125 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6126 			    !connp->conn_ipv6_v6only)
6127 				break;
6128 			connp = connp->conn_next;
6129 		}
6130 
6131 		if (connp == NULL || connp->conn_upq == NULL) {
6132 			/*
6133 			 * No one bound to this port.  Is
6134 			 * there a client that wants all
6135 			 * unclaimed datagrams?
6136 			 */
6137 			mutex_exit(&connfp->connf_lock);
6138 
6139 			if (mctl_present)
6140 				first_mp->b_cont = mp;
6141 			else
6142 				first_mp = mp;
6143 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6144 				ip_fanout_proto(q, first_mp, ill, ipha,
6145 				    flags | IP_FF_RAWIP, mctl_present,
6146 				    ip_policy, recv_ill, zoneid);
6147 			} else {
6148 				if (ip_fanout_send_icmp(q, first_mp, flags,
6149 				    ICMP_DEST_UNREACHABLE,
6150 				    ICMP_PORT_UNREACHABLE,
6151 				    mctl_present, zoneid)) {
6152 					BUMP_MIB(&ip_mib, udpNoPorts);
6153 				}
6154 			}
6155 			return;
6156 		}
6157 		CONN_INC_REF(connp);
6158 		mutex_exit(&connfp->connf_lock);
6159 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6160 		    recv_ill, ip_policy);
6161 		CONN_DEC_REF(connp);
6162 		return;
6163 	}
6164 	/*
6165 	 * IPv4 multicast packet being delivered to an AF_INET6
6166 	 * in6addr_any endpoint.
6167 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6168 	 * and not conn_wantpacket_v6() since any multicast membership is
6169 	 * for an IPv4-mapped multicast address.
6170 	 * The packet is sent to all clients in all zones that have joined the
6171 	 * group and match the port.
6172 	 */
6173 	while (connp != NULL) {
6174 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6175 		    srcport, v6src) &&
6176 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6177 			break;
6178 		connp = connp->conn_next;
6179 	}
6180 
6181 	if (connp == NULL || connp->conn_upq == NULL) {
6182 		/*
6183 		 * No one bound to this port.  Is
6184 		 * there a client that wants all
6185 		 * unclaimed datagrams?
6186 		 */
6187 		mutex_exit(&connfp->connf_lock);
6188 
6189 		if (mctl_present)
6190 			first_mp->b_cont = mp;
6191 		else
6192 			first_mp = mp;
6193 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6194 			ip_fanout_proto(q, first_mp, ill, ipha,
6195 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6196 			    recv_ill, zoneid);
6197 		} else {
6198 			/*
6199 			 * We used to attempt to send an icmp error here, but
6200 			 * since this is known to be a multicast packet
6201 			 * and we don't send icmp errors in response to
6202 			 * multicast, just drop the packet and give up sooner.
6203 			 */
6204 			BUMP_MIB(&ip_mib, udpNoPorts);
6205 			freemsg(first_mp);
6206 		}
6207 		return;
6208 	}
6209 
6210 	first_connp = connp;
6211 
6212 	CONN_INC_REF(connp);
6213 	connp = connp->conn_next;
6214 	for (;;) {
6215 		while (connp != NULL) {
6216 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6217 			    ipv6_all_zeros, srcport, v6src) &&
6218 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6219 				break;
6220 			connp = connp->conn_next;
6221 		}
6222 		/*
6223 		 * Just copy the data part alone. The mctl part is
6224 		 * needed just for verifying policy and it is never
6225 		 * sent up.
6226 		 */
6227 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6228 		    ((mp1 = copymsg(mp)) == NULL))) {
6229 			/*
6230 			 * No more intested clients or memory
6231 			 * allocation failed
6232 			 */
6233 			connp = first_connp;
6234 			break;
6235 		}
6236 		if (first_mp != NULL) {
6237 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6238 			    ipsec_info_type == IPSEC_IN);
6239 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6240 			if (first_mp1 == NULL) {
6241 				freemsg(mp1);
6242 				connp = first_connp;
6243 				break;
6244 			}
6245 		} else {
6246 			first_mp1 = NULL;
6247 		}
6248 		CONN_INC_REF(connp);
6249 		mutex_exit(&connfp->connf_lock);
6250 		/*
6251 		 * IPQoS notes: We don't send the packet for policy
6252 		 * processing here, will do it for the last one (below).
6253 		 * i.e. we do it per-packet now, but if we do policy
6254 		 * processing per-conn, then we would need to do it
6255 		 * here too.
6256 		 */
6257 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6258 		    ipha, flags, recv_ill, B_FALSE);
6259 		mutex_enter(&connfp->connf_lock);
6260 		/* Follow the next pointer before releasing the conn. */
6261 		next_connp = connp->conn_next;
6262 		CONN_DEC_REF(connp);
6263 		connp = next_connp;
6264 	}
6265 
6266 	/* Last one.  Send it upstream. */
6267 	mutex_exit(&connfp->connf_lock);
6268 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6269 	    ip_policy);
6270 	CONN_DEC_REF(connp);
6271 }
6272 
6273 /*
6274  * Complete the ip_wput header so that it
6275  * is possible to generate ICMP
6276  * errors.
6277  */
6278 static int
6279 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6280 {
6281 	ire_t *ire;
6282 
6283 	if (ipha->ipha_src == INADDR_ANY) {
6284 		ire = ire_lookup_local(zoneid);
6285 		if (ire == NULL) {
6286 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6287 			return (1);
6288 		}
6289 		ipha->ipha_src = ire->ire_addr;
6290 		ire_refrele(ire);
6291 	}
6292 	ipha->ipha_ttl = ip_def_ttl;
6293 	ipha->ipha_hdr_checksum = 0;
6294 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6295 	return (0);
6296 }
6297 
6298 /*
6299  * Nobody should be sending
6300  * packets up this stream
6301  */
6302 static void
6303 ip_lrput(queue_t *q, mblk_t *mp)
6304 {
6305 	mblk_t *mp1;
6306 
6307 	switch (mp->b_datap->db_type) {
6308 	case M_FLUSH:
6309 		/* Turn around */
6310 		if (*mp->b_rptr & FLUSHW) {
6311 			*mp->b_rptr &= ~FLUSHR;
6312 			qreply(q, mp);
6313 			return;
6314 		}
6315 		break;
6316 	}
6317 	/* Could receive messages that passed through ar_rput */
6318 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6319 		mp1->b_prev = mp1->b_next = NULL;
6320 	freemsg(mp);
6321 }
6322 
6323 /* Nobody should be sending packets down this stream */
6324 /* ARGSUSED */
6325 void
6326 ip_lwput(queue_t *q, mblk_t *mp)
6327 {
6328 	freemsg(mp);
6329 }
6330 
6331 /*
6332  * Move the first hop in any source route to ipha_dst and remove that part of
6333  * the source route.  Called by other protocols.  Errors in option formatting
6334  * are ignored - will be handled by ip_wput_options Return the final
6335  * destination (either ipha_dst or the last entry in a source route.)
6336  */
6337 ipaddr_t
6338 ip_massage_options(ipha_t *ipha)
6339 {
6340 	ipoptp_t	opts;
6341 	uchar_t		*opt;
6342 	uint8_t		optval;
6343 	uint8_t		optlen;
6344 	ipaddr_t	dst;
6345 	int		i;
6346 	ire_t		*ire;
6347 
6348 	ip2dbg(("ip_massage_options\n"));
6349 	dst = ipha->ipha_dst;
6350 	for (optval = ipoptp_first(&opts, ipha);
6351 	    optval != IPOPT_EOL;
6352 	    optval = ipoptp_next(&opts)) {
6353 		opt = opts.ipoptp_cur;
6354 		switch (optval) {
6355 			uint8_t off;
6356 		case IPOPT_SSRR:
6357 		case IPOPT_LSRR:
6358 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6359 				ip1dbg(("ip_massage_options: bad src route\n"));
6360 				break;
6361 			}
6362 			optlen = opts.ipoptp_len;
6363 			off = opt[IPOPT_OFFSET];
6364 			off--;
6365 		redo_srr:
6366 			if (optlen < IP_ADDR_LEN ||
6367 			    off > optlen - IP_ADDR_LEN) {
6368 				/* End of source route */
6369 				ip1dbg(("ip_massage_options: end of SR\n"));
6370 				break;
6371 			}
6372 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6373 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6374 			    ntohl(dst)));
6375 			/*
6376 			 * Check if our address is present more than
6377 			 * once as consecutive hops in source route.
6378 			 * XXX verify per-interface ip_forwarding
6379 			 * for source route?
6380 			 */
6381 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6382 			    ALL_ZONES, MATCH_IRE_TYPE);
6383 			if (ire != NULL) {
6384 				ire_refrele(ire);
6385 				off += IP_ADDR_LEN;
6386 				goto redo_srr;
6387 			}
6388 			if (dst == htonl(INADDR_LOOPBACK)) {
6389 				ip1dbg(("ip_massage_options: loopback addr in "
6390 				    "source route!\n"));
6391 				break;
6392 			}
6393 			/*
6394 			 * Update ipha_dst to be the first hop and remove the
6395 			 * first hop from the source route (by overwriting
6396 			 * part of the option with NOP options).
6397 			 */
6398 			ipha->ipha_dst = dst;
6399 			/* Put the last entry in dst */
6400 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6401 			    3;
6402 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6403 
6404 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6405 			    ntohl(dst)));
6406 			/* Move down and overwrite */
6407 			opt[IP_ADDR_LEN] = opt[0];
6408 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6409 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6410 			for (i = 0; i < IP_ADDR_LEN; i++)
6411 				opt[i] = IPOPT_NOP;
6412 			break;
6413 		}
6414 	}
6415 	return (dst);
6416 }
6417 
6418 /*
6419  * This function's job is to forward data to the reverse tunnel (FA->HA)
6420  * after doing a few checks. It is assumed that the incoming interface
6421  * of the packet is always different than the outgoing interface and the
6422  * ire_type of the found ire has to be a non-resolver type.
6423  *
6424  * IPQoS notes
6425  * IP policy is invoked twice for a forwarded packet, once on the read side
6426  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6427  * enabled.
6428  */
6429 static void
6430 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6431 {
6432 	ipha_t		*ipha;
6433 	queue_t		*q;
6434 	uint32_t 	pkt_len;
6435 #define	rptr    ((uchar_t *)ipha)
6436 	uint32_t 	sum;
6437 	uint32_t 	max_frag;
6438 	mblk_t		*first_mp;
6439 	uint32_t	ill_index;
6440 
6441 	ASSERT(ire != NULL);
6442 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6443 	ASSERT(ire->ire_stq != NULL);
6444 
6445 	/* Initiate read side IPPF processing */
6446 	if (IPP_ENABLED(IPP_FWD_IN)) {
6447 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6448 		ip_process(IPP_FWD_IN, &mp, ill_index);
6449 		if (mp == NULL) {
6450 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6451 			    "dropped during IPPF processing\n"));
6452 			return;
6453 		}
6454 	}
6455 
6456 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6457 		ILLF_ROUTER) == 0) ||
6458 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6459 		BUMP_MIB(&ip_mib, ipForwProhibits);
6460 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6461 		    "forwarding is not turned on\n"));
6462 		goto drop_pkt;
6463 	}
6464 
6465 	/*
6466 	 * Don't forward if the interface is down
6467 	 */
6468 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6469 		BUMP_MIB(&ip_mib, ipInDiscards);
6470 		goto drop_pkt;
6471 	}
6472 
6473 	ipha = (ipha_t *)mp->b_rptr;
6474 	pkt_len = ntohs(ipha->ipha_length);
6475 	/* Adjust the checksum to reflect the ttl decrement. */
6476 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6477 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6478 	if (ipha->ipha_ttl-- <= 1) {
6479 		if (ip_csum_hdr(ipha)) {
6480 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6481 			goto drop_pkt;
6482 		}
6483 		q = ire->ire_stq;
6484 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6485 		    BPRI_HI)) == NULL) {
6486 			goto drop_pkt;
6487 		}
6488 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6489 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6490 
6491 		return;
6492 	}
6493 
6494 	/* Get the ill_index of the ILL */
6495 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6496 
6497 	/*
6498 	 * ip_mrtun_forward is only used by foreign agent to reverse
6499 	 * tunnel the incoming packet. So it does not do any option
6500 	 * processing for source routing.
6501 	 */
6502 	max_frag = ire->ire_max_frag;
6503 	if (pkt_len > max_frag) {
6504 		/*
6505 		 * It needs fragging on its way out.  We haven't
6506 		 * verified the header checksum yet.  Since we
6507 		 * are going to put a surely good checksum in the
6508 		 * outgoing header, we have to make sure that it
6509 		 * was good coming in.
6510 		 */
6511 		if (ip_csum_hdr(ipha)) {
6512 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6513 			goto drop_pkt;
6514 		}
6515 
6516 		/* Initiate write side IPPF processing */
6517 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6518 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6519 			if (mp == NULL) {
6520 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6521 				    "dropped/deferred during ip policy "\
6522 				    "processing\n"));
6523 				return;
6524 			}
6525 		}
6526 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6527 		    BPRI_HI)) == NULL) {
6528 			goto drop_pkt;
6529 		}
6530 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6531 		mp = first_mp;
6532 
6533 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6534 		return;
6535 	}
6536 
6537 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6538 
6539 	ASSERT(ire->ire_ipif != NULL);
6540 
6541 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6542 	if (mp == NULL) {
6543 		BUMP_MIB(&ip_mib, ipInDiscards);
6544 		return;
6545 	}
6546 
6547 	/* Now send the packet to the tunnel interface */
6548 	q = ire->ire_stq;
6549 	UPDATE_IB_PKT_COUNT(ire);
6550 	ire->ire_last_used_time = lbolt;
6551 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6552 	putnext(q, mp);
6553 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6554 	return;
6555 
6556 drop_pkt:;
6557 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6558 	freemsg(mp);
6559 #undef	rptr
6560 }
6561 
6562 /*
6563  * Fills the ipsec_out_t data structure with appropriate fields and
6564  * prepends it to mp which contains the IP hdr + data that was meant
6565  * to be forwarded. Please note that ipsec_out_info data structure
6566  * is used here to communicate the outgoing ill path at ip_wput()
6567  * for the ICMP error packet. This has nothing to do with ipsec IP
6568  * security. ipsec_out_t is really used to pass the info to the module
6569  * IP where this information cannot be extracted from conn.
6570  * This functions is called by ip_mrtun_forward().
6571  */
6572 void
6573 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6574 {
6575 	ipsec_out_t	*io;
6576 
6577 	ASSERT(xmit_ill != NULL);
6578 	first_mp->b_datap->db_type = M_CTL;
6579 	first_mp->b_wptr += sizeof (ipsec_info_t);
6580 	/*
6581 	 * This is to pass info to ip_wput in absence of conn.
6582 	 * ipsec_out_secure will be B_FALSE because of this.
6583 	 * Thus ipsec_out_secure being B_FALSE indicates that
6584 	 * this is not IPSEC security related information.
6585 	 */
6586 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6587 	io = (ipsec_out_t *)first_mp->b_rptr;
6588 	io->ipsec_out_type = IPSEC_OUT;
6589 	io->ipsec_out_len = sizeof (ipsec_out_t);
6590 	first_mp->b_cont = mp;
6591 	io->ipsec_out_ill_index =
6592 	    xmit_ill->ill_phyint->phyint_ifindex;
6593 	io->ipsec_out_xmit_if = B_TRUE;
6594 }
6595 
6596 /*
6597  * Return the network mask
6598  * associated with the specified address.
6599  */
6600 ipaddr_t
6601 ip_net_mask(ipaddr_t addr)
6602 {
6603 	uchar_t	*up = (uchar_t *)&addr;
6604 	ipaddr_t mask = 0;
6605 	uchar_t	*maskp = (uchar_t *)&mask;
6606 
6607 #if defined(__i386) || defined(__amd64)
6608 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6609 #endif
6610 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6611 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6612 #endif
6613 	if (CLASSD(addr)) {
6614 		maskp[0] = 0xF0;
6615 		return (mask);
6616 	}
6617 	if (addr == 0)
6618 		return (0);
6619 	maskp[0] = 0xFF;
6620 	if ((up[0] & 0x80) == 0)
6621 		return (mask);
6622 
6623 	maskp[1] = 0xFF;
6624 	if ((up[0] & 0xC0) == 0x80)
6625 		return (mask);
6626 
6627 	maskp[2] = 0xFF;
6628 	if ((up[0] & 0xE0) == 0xC0)
6629 		return (mask);
6630 
6631 	/* Must be experimental or multicast, indicate as much */
6632 	return ((ipaddr_t)0);
6633 }
6634 
6635 /*
6636  * Select an ill for the packet by considering load spreading across
6637  * a different ill in the group if dst_ill is part of some group.
6638  */
6639 static ill_t *
6640 ip_newroute_get_dst_ill(ill_t *dst_ill)
6641 {
6642 	ill_t *ill;
6643 
6644 	/*
6645 	 * We schedule irrespective of whether the source address is
6646 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6647 	 */
6648 	ill = illgrp_scheduler(dst_ill);
6649 	if (ill == NULL)
6650 		return (NULL);
6651 
6652 	/*
6653 	 * For groups with names ip_sioctl_groupname ensures that all
6654 	 * ills are of same type. For groups without names, ifgrp_insert
6655 	 * ensures this.
6656 	 */
6657 	ASSERT(dst_ill->ill_type == ill->ill_type);
6658 
6659 	return (ill);
6660 }
6661 
6662 /*
6663  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6664  */
6665 ill_t *
6666 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6667 {
6668 	ill_t *ret_ill;
6669 
6670 	ASSERT(ifindex != 0);
6671 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6672 	if (ret_ill == NULL ||
6673 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6674 		if (isv6) {
6675 			if (ill != NULL) {
6676 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6677 			} else {
6678 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6679 			}
6680 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6681 			    "bad ifindex %d.\n", ifindex));
6682 		} else {
6683 			BUMP_MIB(&ip_mib, ipOutDiscards);
6684 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6685 			    "bad ifindex %d.\n", ifindex));
6686 		}
6687 		if (ret_ill != NULL)
6688 			ill_refrele(ret_ill);
6689 		freemsg(first_mp);
6690 		return (NULL);
6691 	}
6692 
6693 	return (ret_ill);
6694 }
6695 
6696 /*
6697  * IPv4 -
6698  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6699  * out a packet to a destination address for which we do not have specific
6700  * (or sufficient) routing information.
6701  *
6702  * NOTE : These are the scopes of some of the variables that point at IRE,
6703  *	  which needs to be followed while making any future modifications
6704  *	  to avoid memory leaks.
6705  *
6706  *	- ire and sire are the entries looked up initially by
6707  *	  ire_ftable_lookup.
6708  *	- ipif_ire is used to hold the interface ire associated with
6709  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6710  *	  it before branching out to error paths.
6711  *	- save_ire is initialized before ire_create, so that ire returned
6712  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6713  *	  before breaking out of the switch.
6714  *
6715  *	Thus on failures, we have to REFRELE only ire and sire, if they
6716  *	are not NULL.
6717  */
6718 void
6719 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6720 {
6721 	areq_t	*areq;
6722 	ipaddr_t gw = 0;
6723 	ire_t	*ire = NULL;
6724 	mblk_t	*res_mp;
6725 	ipaddr_t *addrp;
6726 	ipaddr_t nexthop_addr;
6727 	ipif_t  *src_ipif = NULL;
6728 	ill_t	*dst_ill = NULL;
6729 	ipha_t  *ipha;
6730 	ire_t	*sire = NULL;
6731 	mblk_t	*first_mp;
6732 	ire_t	*save_ire;
6733 	mblk_t	*dlureq_mp;
6734 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6735 	ushort_t ire_marks = 0;
6736 	boolean_t mctl_present;
6737 	ipsec_out_t *io;
6738 	mblk_t	*saved_mp;
6739 	ire_t	*first_sire = NULL;
6740 	mblk_t	*copy_mp = NULL;
6741 	mblk_t	*xmit_mp = NULL;
6742 	ipaddr_t save_dst;
6743 	uint32_t multirt_flags =
6744 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6745 	boolean_t multirt_is_resolvable;
6746 	boolean_t multirt_resolve_next;
6747 	boolean_t do_attach_ill = B_FALSE;
6748 	boolean_t ip_nexthop = B_FALSE;
6749 	zoneid_t zoneid;
6750 
6751 	if (ip_debug > 2) {
6752 		/* ip1dbg */
6753 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6754 	}
6755 
6756 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6757 	if (mctl_present) {
6758 		io = (ipsec_out_t *)first_mp->b_rptr;
6759 		zoneid = io->ipsec_out_zoneid;
6760 		ASSERT(zoneid != ALL_ZONES);
6761 	} else if (connp != NULL) {
6762 		zoneid = connp->conn_zoneid;
6763 	} else {
6764 		zoneid = GLOBAL_ZONEID;
6765 	}
6766 
6767 	ipha = (ipha_t *)mp->b_rptr;
6768 
6769 	/* All multicast lookups come through ip_newroute_ipif() */
6770 	if (CLASSD(dst)) {
6771 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6772 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6773 		freemsg(first_mp);
6774 		return;
6775 	}
6776 
6777 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6778 		goto icmp_err_ret;
6779 	}
6780 
6781 	if (mctl_present && io->ipsec_out_attach_if) {
6782 		/* ip_grab_attach_ill returns a held ill */
6783 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6784 		    io->ipsec_out_ill_index, B_FALSE);
6785 
6786 		/* Failure case frees things for us. */
6787 		if (attach_ill == NULL)
6788 			return;
6789 
6790 		/*
6791 		 * Check if we need an ire that will not be
6792 		 * looked up by anybody else i.e. HIDDEN.
6793 		 */
6794 		if (ill_is_probeonly(attach_ill))
6795 			ire_marks = IRE_MARK_HIDDEN;
6796 	}
6797 	if (mctl_present && io->ipsec_out_ip_nexthop) {
6798 		ip_nexthop = B_TRUE;
6799 		nexthop_addr = io->ipsec_out_nexthop_addr;
6800 	}
6801 	/*
6802 	 * If this IRE is created for forwarding or it is not for
6803 	 * traffic for congestion controlled protocols, mark it as temporary.
6804 	 */
6805 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6806 		ire_marks |= IRE_MARK_TEMPORARY;
6807 
6808 	/*
6809 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6810 	 * chain until it gets the most specific information available.
6811 	 * For example, we know that there is no IRE_CACHE for this dest,
6812 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6813 	 * ire_ftable_lookup will look up the gateway, etc.
6814 	 * Check if in_ill != NULL. If it is true, the packet must be
6815 	 * from an incoming interface where RTA_SRCIFP is set.
6816 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6817 	 * to the destination, of equal netmask length in the forward table,
6818 	 * will be recursively explored. If no information is available
6819 	 * for the final gateway of that route, we force the returned ire
6820 	 * to be equal to sire using MATCH_IRE_PARENT.
6821 	 * At least, in this case we have a starting point (in the buckets)
6822 	 * to look for other routes to the destination in the forward table.
6823 	 * This is actually used only for multirouting, where a list
6824 	 * of routes has to be processed in sequence.
6825 	 */
6826 	if (in_ill != NULL) {
6827 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6828 		    in_ill, MATCH_IRE_TYPE);
6829 	} else if (ip_nexthop) {
6830 		/*
6831 		 * The first time we come here, we look for an IRE_INTERFACE
6832 		 * entry for the specified nexthop, set the dst to be the
6833 		 * nexthop address and create an IRE_CACHE entry for the
6834 		 * nexthop. The next time around, we are able to find an
6835 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
6836 		 * nexthop address and create an IRE_CACHE entry for the
6837 		 * destination address via the specified nexthop.
6838 		 */
6839 		ire = ire_cache_lookup(nexthop_addr, zoneid);
6840 		if (ire != NULL) {
6841 			gw = nexthop_addr;
6842 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
6843 		} else {
6844 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
6845 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
6846 			    MATCH_IRE_TYPE);
6847 			if (ire != NULL) {
6848 				dst = nexthop_addr;
6849 			}
6850 		}
6851 	} else if (attach_ill == NULL) {
6852 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6853 		    NULL, &sire, zoneid, 0,
6854 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6855 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6856 	} else {
6857 		/*
6858 		 * attach_ill is set only for communicating with
6859 		 * on-link hosts. So, don't look for DEFAULT.
6860 		 */
6861 		ipif_t	*attach_ipif;
6862 
6863 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6864 		if (attach_ipif == NULL) {
6865 			ill_refrele(attach_ill);
6866 			goto icmp_err_ret;
6867 		}
6868 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6869 		    &sire, zoneid, 0,
6870 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6871 		ipif_refrele(attach_ipif);
6872 	}
6873 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6874 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6875 
6876 	/*
6877 	 * This loop is run only once in most cases.
6878 	 * We loop to resolve further routes only when the destination
6879 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6880 	 */
6881 	do {
6882 		/* Clear the previous iteration's values */
6883 		if (src_ipif != NULL) {
6884 			ipif_refrele(src_ipif);
6885 			src_ipif = NULL;
6886 		}
6887 		if (dst_ill != NULL) {
6888 			ill_refrele(dst_ill);
6889 			dst_ill = NULL;
6890 		}
6891 
6892 		multirt_resolve_next = B_FALSE;
6893 		/*
6894 		 * We check if packets have to be multirouted.
6895 		 * In this case, given the current <ire, sire> couple,
6896 		 * we look for the next suitable <ire, sire>.
6897 		 * This check is done in ire_multirt_lookup(),
6898 		 * which applies various criteria to find the next route
6899 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6900 		 * unchanged if it detects it has not been tried yet.
6901 		 */
6902 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6903 			ip3dbg(("ip_newroute: starting next_resolution "
6904 			    "with first_mp %p, tag %d\n",
6905 			    (void *)first_mp,
6906 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6907 
6908 			ASSERT(sire != NULL);
6909 			multirt_is_resolvable =
6910 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6911 
6912 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6913 			    "ire %p, sire %p\n",
6914 			    multirt_is_resolvable,
6915 			    (void *)ire, (void *)sire));
6916 
6917 			if (!multirt_is_resolvable) {
6918 				/*
6919 				 * No more multirt route to resolve; give up
6920 				 * (all routes resolved or no more
6921 				 * resolvable routes).
6922 				 */
6923 				if (ire != NULL) {
6924 					ire_refrele(ire);
6925 					ire = NULL;
6926 				}
6927 			} else {
6928 				ASSERT(sire != NULL);
6929 				ASSERT(ire != NULL);
6930 				/*
6931 				 * We simply use first_sire as a flag that
6932 				 * indicates if a resolvable multirt route
6933 				 * has already been found.
6934 				 * If it is not the case, we may have to send
6935 				 * an ICMP error to report that the
6936 				 * destination is unreachable.
6937 				 * We do not IRE_REFHOLD first_sire.
6938 				 */
6939 				if (first_sire == NULL) {
6940 					first_sire = sire;
6941 				}
6942 			}
6943 		}
6944 		if (ire == NULL) {
6945 			if (ip_debug > 3) {
6946 				/* ip2dbg */
6947 				pr_addr_dbg("ip_newroute: "
6948 				    "can't resolve %s\n", AF_INET, &dst);
6949 			}
6950 			ip3dbg(("ip_newroute: "
6951 			    "ire %p, sire %p, first_sire %p\n",
6952 			    (void *)ire, (void *)sire, (void *)first_sire));
6953 
6954 			if (sire != NULL) {
6955 				ire_refrele(sire);
6956 				sire = NULL;
6957 			}
6958 
6959 			if (first_sire != NULL) {
6960 				/*
6961 				 * At least one multirt route has been found
6962 				 * in the same call to ip_newroute();
6963 				 * there is no need to report an ICMP error.
6964 				 * first_sire was not IRE_REFHOLDed.
6965 				 */
6966 				MULTIRT_DEBUG_UNTAG(first_mp);
6967 				freemsg(first_mp);
6968 				return;
6969 			}
6970 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6971 			    RTA_DST);
6972 			if (attach_ill != NULL)
6973 				ill_refrele(attach_ill);
6974 			goto icmp_err_ret;
6975 		}
6976 
6977 		/*
6978 		 * When RTA_SRCIFP is used to add a route, then an interface
6979 		 * route is added in the source interface's routing table.
6980 		 * If the outgoing interface of this route is of type
6981 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6982 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6983 		 * first used for forwarding packet, ip_newroute() is called
6984 		 * to resolve the hardware address of the outgoing ipif.
6985 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6986 		 * source interface based table. We only come here if the
6987 		 * outgoing interface is a resolver interface and we don't
6988 		 * have the ire_dlureq_mp information yet.
6989 		 * If in_ill is not null that means it is called from
6990 		 * ip_rput.
6991 		 */
6992 
6993 		ASSERT(ire->ire_in_ill == NULL ||
6994 		    (ire->ire_type == IRE_IF_RESOLVER &&
6995 		    ire->ire_dlureq_mp == NULL));
6996 
6997 		/*
6998 		 * Verify that the returned IRE does not have either
6999 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7000 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7001 		 */
7002 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7003 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7004 			if (attach_ill != NULL)
7005 				ill_refrele(attach_ill);
7006 			goto icmp_err_ret;
7007 		}
7008 		/*
7009 		 * Increment the ire_ob_pkt_count field for ire if it is an
7010 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7011 		 * increment the same for the parent IRE, sire, if it is some
7012 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7013 		 * and HOST_REDIRECT).
7014 		 */
7015 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7016 			UPDATE_OB_PKT_COUNT(ire);
7017 			ire->ire_last_used_time = lbolt;
7018 		}
7019 
7020 		if (sire != NULL) {
7021 			gw = sire->ire_gateway_addr;
7022 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7023 			    IRE_INTERFACE)) == 0);
7024 			UPDATE_OB_PKT_COUNT(sire);
7025 			sire->ire_last_used_time = lbolt;
7026 		}
7027 		/*
7028 		 * We have a route to reach the destination.
7029 		 *
7030 		 * 1) If the interface is part of ill group, try to get a new
7031 		 *    ill taking load spreading into account.
7032 		 *
7033 		 * 2) After selecting the ill, get a source address that
7034 		 *    might create good inbound load spreading.
7035 		 *    ipif_select_source does this for us.
7036 		 *
7037 		 * If the application specified the ill (ifindex), we still
7038 		 * load spread. Only if the packets needs to go out
7039 		 * specifically on a given ill e.g. binding to
7040 		 * IPIF_NOFAILOVER address, then we don't try to use a
7041 		 * different ill for load spreading.
7042 		 */
7043 		if (attach_ill == NULL) {
7044 			/*
7045 			 * Don't perform outbound load spreading in the
7046 			 * case of an RTF_MULTIRT route, as we actually
7047 			 * typically want to replicate outgoing packets
7048 			 * through particular interfaces.
7049 			 */
7050 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7051 				dst_ill = ire->ire_ipif->ipif_ill;
7052 				/* for uniformity */
7053 				ill_refhold(dst_ill);
7054 			} else {
7055 				/*
7056 				 * If we are here trying to create an IRE_CACHE
7057 				 * for an offlink destination and have the
7058 				 * IRE_CACHE for the next hop and the latter is
7059 				 * using virtual IP source address selection i.e
7060 				 * it's ire->ire_ipif is pointing to a virtual
7061 				 * network interface (vni) then
7062 				 * ip_newroute_get_dst_ll() will return the vni
7063 				 * interface as the dst_ill. Since the vni is
7064 				 * virtual i.e not associated with any physical
7065 				 * interface, it cannot be the dst_ill, hence
7066 				 * in such a case call ip_newroute_get_dst_ll()
7067 				 * with the stq_ill instead of the ire_ipif ILL.
7068 				 * The function returns a refheld ill.
7069 				 */
7070 				if ((ire->ire_type == IRE_CACHE) &&
7071 				    IS_VNI(ire->ire_ipif->ipif_ill))
7072 					dst_ill = ip_newroute_get_dst_ill(
7073 						ire->ire_stq->q_ptr);
7074 				else
7075 					dst_ill = ip_newroute_get_dst_ill(
7076 						ire->ire_ipif->ipif_ill);
7077 			}
7078 			if (dst_ill == NULL) {
7079 				if (ip_debug > 2) {
7080 					pr_addr_dbg("ip_newroute: "
7081 					    "no dst ill for dst"
7082 					    " %s\n", AF_INET, &dst);
7083 				}
7084 				goto icmp_err_ret;
7085 			}
7086 		} else {
7087 			dst_ill = ire->ire_ipif->ipif_ill;
7088 			/* for uniformity */
7089 			ill_refhold(dst_ill);
7090 			/*
7091 			 * We should have found a route matching ill as we
7092 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7093 			 * Rather than asserting, when there is a mismatch,
7094 			 * we just drop the packet.
7095 			 */
7096 			if (dst_ill != attach_ill) {
7097 				ip0dbg(("ip_newroute: Packet dropped as "
7098 				    "IPIF_NOFAILOVER ill is %s, "
7099 				    "ire->ire_ipif->ipif_ill is %s\n",
7100 				    attach_ill->ill_name,
7101 				    dst_ill->ill_name));
7102 				ill_refrele(attach_ill);
7103 				goto icmp_err_ret;
7104 			}
7105 		}
7106 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7107 		if (attach_ill != NULL) {
7108 			ill_refrele(attach_ill);
7109 			attach_ill = NULL;
7110 			do_attach_ill = B_TRUE;
7111 		}
7112 		ASSERT(dst_ill != NULL);
7113 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7114 
7115 		/*
7116 		 * Pick the best source address from dst_ill.
7117 		 *
7118 		 * 1) If it is part of a multipathing group, we would
7119 		 *    like to spread the inbound packets across different
7120 		 *    interfaces. ipif_select_source picks a random source
7121 		 *    across the different ills in the group.
7122 		 *
7123 		 * 2) If it is not part of a multipathing group, we try
7124 		 *    to pick the source address from the destination
7125 		 *    route. Clustering assumes that when we have multiple
7126 		 *    prefixes hosted on an interface, the prefix of the
7127 		 *    source address matches the prefix of the destination
7128 		 *    route. We do this only if the address is not
7129 		 *    DEPRECATED.
7130 		 *
7131 		 * 3) If the conn is in a different zone than the ire, we
7132 		 *    need to pick a source address from the right zone.
7133 		 *
7134 		 * NOTE : If we hit case (1) above, the prefix of the source
7135 		 *	  address picked may not match the prefix of the
7136 		 *	  destination routes prefix as ipif_select_source
7137 		 *	  does not look at "dst" while picking a source
7138 		 *	  address.
7139 		 *	  If we want the same behavior as (2), we will need
7140 		 *	  to change the behavior of ipif_select_source.
7141 		 */
7142 		ASSERT(src_ipif == NULL);
7143 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7144 			/*
7145 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7146 			 * Check that the ipif matching the requested source
7147 			 * address still exists.
7148 			 */
7149 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7150 			    zoneid, NULL, NULL, NULL, NULL);
7151 		}
7152 		if (src_ipif == NULL) {
7153 			ire_marks |= IRE_MARK_USESRC_CHECK;
7154 			if ((dst_ill->ill_group != NULL) ||
7155 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7156 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
7157 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7158 				/*
7159 				 * If the destination is reachable via a
7160 				 * given gateway, the selected source address
7161 				 * should be in the same subnet as the gateway.
7162 				 * Otherwise, the destination is not reachable.
7163 				 *
7164 				 * If there are no interfaces on the same subnet
7165 				 * as the destination, ipif_select_source gives
7166 				 * first non-deprecated interface which might be
7167 				 * on a different subnet than the gateway.
7168 				 * This is not desirable. Hence pass the dst_ire
7169 				 * source address to ipif_select_source.
7170 				 * It is sure that the destination is reachable
7171 				 * with the dst_ire source address subnet.
7172 				 * So passing dst_ire source address to
7173 				 * ipif_select_source will make sure that the
7174 				 * selected source will be on the same subnet
7175 				 * as dst_ire source address.
7176 				 */
7177 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7178 				src_ipif = ipif_select_source(dst_ill, saddr,
7179 				    zoneid);
7180 				if (src_ipif == NULL) {
7181 					if (ip_debug > 2) {
7182 						pr_addr_dbg("ip_newroute: "
7183 						    "no src for dst %s ",
7184 						    AF_INET, &dst);
7185 						printf("through interface %s\n",
7186 						    dst_ill->ill_name);
7187 					}
7188 					goto icmp_err_ret;
7189 				}
7190 			} else {
7191 				src_ipif = ire->ire_ipif;
7192 				ASSERT(src_ipif != NULL);
7193 				/* hold src_ipif for uniformity */
7194 				ipif_refhold(src_ipif);
7195 			}
7196 		}
7197 
7198 		/*
7199 		 * Assign a source address while we have the conn.
7200 		 * We can't have ip_wput_ire pick a source address when the
7201 		 * packet returns from arp since we need to look at
7202 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7203 		 * going through arp.
7204 		 *
7205 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7206 		 *	  it uses ip6i to store this information.
7207 		 */
7208 		if (ipha->ipha_src == INADDR_ANY &&
7209 		    (connp == NULL || !connp->conn_unspec_src)) {
7210 			ipha->ipha_src = src_ipif->ipif_src_addr;
7211 		}
7212 		if (ip_debug > 3) {
7213 			/* ip2dbg */
7214 			pr_addr_dbg("ip_newroute: first hop %s\n",
7215 			    AF_INET, &gw);
7216 		}
7217 		ip2dbg(("\tire type %s (%d)\n",
7218 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7219 
7220 		/*
7221 		 * The TTL of multirouted packets is bounded by the
7222 		 * ip_multirt_ttl ndd variable.
7223 		 */
7224 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7225 			/* Force TTL of multirouted packets */
7226 			if ((ip_multirt_ttl > 0) &&
7227 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7228 				ip2dbg(("ip_newroute: forcing multirt TTL "
7229 				    "to %d (was %d), dst 0x%08x\n",
7230 				    ip_multirt_ttl, ipha->ipha_ttl,
7231 				    ntohl(sire->ire_addr)));
7232 				ipha->ipha_ttl = ip_multirt_ttl;
7233 			}
7234 		}
7235 		/*
7236 		 * At this point in ip_newroute(), ire is either the
7237 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7238 		 * destination or an IRE_INTERFACE type that should be used
7239 		 * to resolve an on-subnet destination or an on-subnet
7240 		 * next-hop gateway.
7241 		 *
7242 		 * In the IRE_CACHE case, we have the following :
7243 		 *
7244 		 * 1) src_ipif - used for getting a source address.
7245 		 *
7246 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7247 		 *    means packets using this IRE_CACHE will go out on
7248 		 *    dst_ill.
7249 		 *
7250 		 * 3) The IRE sire will point to the prefix that is the
7251 		 *    longest  matching route for the destination. These
7252 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7253 		 *    and IRE_HOST_REDIRECT.
7254 		 *
7255 		 *    The newly created IRE_CACHE entry for the off-subnet
7256 		 *    destination is tied to both the prefix route and the
7257 		 *    interface route used to resolve the next-hop gateway
7258 		 *    via the ire_phandle and ire_ihandle fields,
7259 		 *    respectively.
7260 		 *
7261 		 * In the IRE_INTERFACE case, we have the following :
7262 		 *
7263 		 * 1) src_ipif - used for getting a source address.
7264 		 *
7265 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7266 		 *    means packets using the IRE_CACHE that we will build
7267 		 *    here will go out on dst_ill.
7268 		 *
7269 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7270 		 *    to be created will only be tied to the IRE_INTERFACE
7271 		 *    that was derived from the ire_ihandle field.
7272 		 *
7273 		 *    If sire is non-NULL, it means the destination is
7274 		 *    off-link and we will first create the IRE_CACHE for the
7275 		 *    gateway. Next time through ip_newroute, we will create
7276 		 *    the IRE_CACHE for the final destination as described
7277 		 *    above.
7278 		 *
7279 		 * In both cases, after the current resolution has been
7280 		 * completed (or possibly initialised, in the IRE_INTERFACE
7281 		 * case), the loop may be re-entered to attempt the resolution
7282 		 * of another RTF_MULTIRT route.
7283 		 *
7284 		 * When an IRE_CACHE entry for the off-subnet destination is
7285 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7286 		 * for further processing in emission loops.
7287 		 */
7288 		save_ire = ire;
7289 		switch (ire->ire_type) {
7290 		case IRE_CACHE: {
7291 			ire_t	*ipif_ire;
7292 			mblk_t	*ire_fp_mp;
7293 
7294 			if (gw == 0)
7295 				gw = ire->ire_gateway_addr;
7296 			/*
7297 			 * We need 3 ire's to create a new cache ire for an
7298 			 * off-link destination from the cache ire of the
7299 			 * gateway.
7300 			 *
7301 			 *	1. The prefix ire 'sire' (Note that this does
7302 			 *	   not apply to the conn_nexthop_set case)
7303 			 *	2. The cache ire of the gateway 'ire'
7304 			 *	3. The interface ire 'ipif_ire'
7305 			 *
7306 			 * We have (1) and (2). We lookup (3) below.
7307 			 *
7308 			 * If there is no interface route to the gateway,
7309 			 * it is a race condition, where we found the cache
7310 			 * but the interface route has been deleted.
7311 			 */
7312 			if (ip_nexthop) {
7313 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7314 			} else {
7315 				ipif_ire =
7316 				    ire_ihandle_lookup_offlink(ire, sire);
7317 			}
7318 			if (ipif_ire == NULL) {
7319 				ip1dbg(("ip_newroute: "
7320 				    "ire_ihandle_lookup_offlink failed\n"));
7321 				goto icmp_err_ret;
7322 			}
7323 			/*
7324 			 * XXX We are using the same dlureq_mp
7325 			 * (DL_UNITDATA_REQ) though the save_ire is not
7326 			 * pointing at the same ill.
7327 			 * This is incorrect. We need to send it up to the
7328 			 * resolver to get the right dlureq_mp. For ethernets
7329 			 * this may be okay (ill_type == DL_ETHER).
7330 			 */
7331 			dlureq_mp = save_ire->ire_dlureq_mp;
7332 			ire_fp_mp = NULL;
7333 			/*
7334 			 * save_ire's ire_fp_mp can't change since it is
7335 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7336 			 * LOCK_IRE_FP_MP does not do any useful work in
7337 			 * the case of IRE_CACHE. So we don't use it below.
7338 			 */
7339 			if (save_ire->ire_stq == dst_ill->ill_wq)
7340 				ire_fp_mp = save_ire->ire_fp_mp;
7341 
7342 			ire = ire_create(
7343 			    (uchar_t *)&dst,		/* dest address */
7344 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7345 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7346 			    (uchar_t *)&gw,		/* gateway address */
7347 			    NULL,
7348 			    &save_ire->ire_max_frag,
7349 			    ire_fp_mp,			/* Fast Path header */
7350 			    dst_ill->ill_rq,		/* recv-from queue */
7351 			    dst_ill->ill_wq,		/* send-to queue */
7352 			    IRE_CACHE,			/* IRE type */
7353 			    save_ire->ire_dlureq_mp,
7354 			    src_ipif,
7355 			    in_ill,			/* incoming ill */
7356 			    (sire != NULL) ?
7357 				sire->ire_mask : 0, 	/* Parent mask */
7358 			    (sire != NULL) ?
7359 				sire->ire_phandle : 0,  /* Parent handle */
7360 			    ipif_ire->ire_ihandle,	/* Interface handle */
7361 			    (sire != NULL) ? (sire->ire_flags &
7362 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7363 			    (sire != NULL) ?
7364 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo));
7365 
7366 			if (ire == NULL) {
7367 				ire_refrele(ipif_ire);
7368 				ire_refrele(save_ire);
7369 				break;
7370 			}
7371 			ire->ire_marks |= ire_marks;
7372 
7373 			/*
7374 			 * Prevent sire and ipif_ire from getting deleted.
7375 			 * The newly created ire is tied to both of them via
7376 			 * the phandle and ihandle respectively.
7377 			 */
7378 			if (sire != NULL) {
7379 				IRB_REFHOLD(sire->ire_bucket);
7380 				/* Has it been removed already ? */
7381 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7382 					IRB_REFRELE(sire->ire_bucket);
7383 					ire_refrele(ipif_ire);
7384 					ire_refrele(save_ire);
7385 					break;
7386 				}
7387 			}
7388 
7389 			IRB_REFHOLD(ipif_ire->ire_bucket);
7390 			/* Has it been removed already ? */
7391 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7392 				IRB_REFRELE(ipif_ire->ire_bucket);
7393 				if (sire != NULL)
7394 					IRB_REFRELE(sire->ire_bucket);
7395 				ire_refrele(ipif_ire);
7396 				ire_refrele(save_ire);
7397 				break;
7398 			}
7399 
7400 			xmit_mp = first_mp;
7401 			/*
7402 			 * In the case of multirouting, a copy
7403 			 * of the packet is done before its sending.
7404 			 * The copy is used to attempt another
7405 			 * route resolution, in a next loop.
7406 			 */
7407 			if (ire->ire_flags & RTF_MULTIRT) {
7408 				copy_mp = copymsg(first_mp);
7409 				if (copy_mp != NULL) {
7410 					xmit_mp = copy_mp;
7411 					MULTIRT_DEBUG_TAG(first_mp);
7412 				}
7413 			}
7414 			ire_add_then_send(q, ire, xmit_mp);
7415 			ire_refrele(save_ire);
7416 
7417 			/* Assert that sire is not deleted yet. */
7418 			if (sire != NULL) {
7419 				ASSERT(sire->ire_ptpn != NULL);
7420 				IRB_REFRELE(sire->ire_bucket);
7421 			}
7422 
7423 			/* Assert that ipif_ire is not deleted yet. */
7424 			ASSERT(ipif_ire->ire_ptpn != NULL);
7425 			IRB_REFRELE(ipif_ire->ire_bucket);
7426 			ire_refrele(ipif_ire);
7427 
7428 			/*
7429 			 * If copy_mp is not NULL, multirouting was
7430 			 * requested. We loop to initiate a next
7431 			 * route resolution attempt, starting from sire.
7432 			 */
7433 			if (copy_mp != NULL) {
7434 				/*
7435 				 * Search for the next unresolved
7436 				 * multirt route.
7437 				 */
7438 				copy_mp = NULL;
7439 				ipif_ire = NULL;
7440 				ire = NULL;
7441 				multirt_resolve_next = B_TRUE;
7442 				continue;
7443 			}
7444 			if (sire != NULL)
7445 				ire_refrele(sire);
7446 			ipif_refrele(src_ipif);
7447 			ill_refrele(dst_ill);
7448 			return;
7449 		}
7450 		case IRE_IF_NORESOLVER: {
7451 			/*
7452 			 * We have what we need to build an IRE_CACHE.
7453 			 *
7454 			 * Create a new dlureq_mp with the IP gateway address
7455 			 * in destination address in the DLPI hdr if the
7456 			 * physical length is exactly 4 bytes.
7457 			 */
7458 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7459 				uchar_t *addr;
7460 
7461 				if (gw)
7462 					addr = (uchar_t *)&gw;
7463 				else
7464 					addr = (uchar_t *)&dst;
7465 
7466 				dlureq_mp = ill_dlur_gen(addr,
7467 				    dst_ill->ill_phys_addr_length,
7468 				    dst_ill->ill_sap,
7469 				    dst_ill->ill_sap_length);
7470 			} else {
7471 				dlureq_mp = ire->ire_dlureq_mp;
7472 			}
7473 
7474 			if (dlureq_mp == NULL) {
7475 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7476 				break;
7477 			}
7478 
7479 			ire = ire_create(
7480 			    (uchar_t *)&dst,		/* dest address */
7481 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7482 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7483 			    (uchar_t *)&gw,		/* gateway address */
7484 			    NULL,
7485 			    &save_ire->ire_max_frag,
7486 			    NULL,			/* Fast Path header */
7487 			    dst_ill->ill_rq,		/* recv-from queue */
7488 			    dst_ill->ill_wq,		/* send-to queue */
7489 			    IRE_CACHE,
7490 			    dlureq_mp,
7491 			    src_ipif,
7492 			    in_ill,			/* Incoming ill */
7493 			    save_ire->ire_mask,		/* Parent mask */
7494 			    (sire != NULL) ?		/* Parent handle */
7495 				sire->ire_phandle : 0,
7496 			    save_ire->ire_ihandle,	/* Interface handle */
7497 			    (sire != NULL) ? sire->ire_flags &
7498 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7499 			    &(save_ire->ire_uinfo));
7500 
7501 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7502 				freeb(dlureq_mp);
7503 
7504 			if (ire == NULL) {
7505 				ire_refrele(save_ire);
7506 				break;
7507 			}
7508 
7509 			ire->ire_marks |= ire_marks;
7510 
7511 			/* Prevent save_ire from getting deleted */
7512 			IRB_REFHOLD(save_ire->ire_bucket);
7513 			/* Has it been removed already ? */
7514 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7515 				IRB_REFRELE(save_ire->ire_bucket);
7516 				ire_refrele(save_ire);
7517 				break;
7518 			}
7519 
7520 			/*
7521 			 * In the case of multirouting, a copy
7522 			 * of the packet is made before it is sent.
7523 			 * The copy is used in the next
7524 			 * loop to attempt another resolution.
7525 			 */
7526 			xmit_mp = first_mp;
7527 			if ((sire != NULL) &&
7528 			    (sire->ire_flags & RTF_MULTIRT)) {
7529 				copy_mp = copymsg(first_mp);
7530 				if (copy_mp != NULL) {
7531 					xmit_mp = copy_mp;
7532 					MULTIRT_DEBUG_TAG(first_mp);
7533 				}
7534 			}
7535 			ire_add_then_send(q, ire, xmit_mp);
7536 
7537 			/* Assert that it is not deleted yet. */
7538 			ASSERT(save_ire->ire_ptpn != NULL);
7539 			IRB_REFRELE(save_ire->ire_bucket);
7540 			ire_refrele(save_ire);
7541 
7542 			if (copy_mp != NULL) {
7543 				/*
7544 				 * If we found a (no)resolver, we ignore any
7545 				 * trailing top priority IRE_CACHE in further
7546 				 * loops. This ensures that we do not omit any
7547 				 * (no)resolver.
7548 				 * This IRE_CACHE, if any, will be processed
7549 				 * by another thread entering ip_newroute().
7550 				 * IRE_CACHE entries, if any, will be processed
7551 				 * by another thread entering ip_newroute(),
7552 				 * (upon resolver response, for instance).
7553 				 * This aims to force parallel multirt
7554 				 * resolutions as soon as a packet must be sent.
7555 				 * In the best case, after the tx of only one
7556 				 * packet, all reachable routes are resolved.
7557 				 * Otherwise, the resolution of all RTF_MULTIRT
7558 				 * routes would require several emissions.
7559 				 */
7560 				multirt_flags &= ~MULTIRT_CACHEGW;
7561 
7562 				/*
7563 				 * Search for the next unresolved multirt
7564 				 * route.
7565 				 */
7566 				copy_mp = NULL;
7567 				save_ire = NULL;
7568 				ire = NULL;
7569 				multirt_resolve_next = B_TRUE;
7570 				continue;
7571 			}
7572 
7573 			/*
7574 			 * Don't need sire anymore
7575 			 */
7576 			if (sire != NULL)
7577 				ire_refrele(sire);
7578 
7579 			ipif_refrele(src_ipif);
7580 			ill_refrele(dst_ill);
7581 			return;
7582 		}
7583 		case IRE_IF_RESOLVER:
7584 			/*
7585 			 * We can't build an IRE_CACHE yet, but at least we
7586 			 * found a resolver that can help.
7587 			 */
7588 			res_mp = dst_ill->ill_resolver_mp;
7589 			if (!OK_RESOLVER_MP(res_mp))
7590 				break;
7591 			/*
7592 			 * To be at this point in the code with a non-zero gw
7593 			 * means that dst is reachable through a gateway that
7594 			 * we have never resolved.  By changing dst to the gw
7595 			 * addr we resolve the gateway first.
7596 			 * When ire_add_then_send() tries to put the IP dg
7597 			 * to dst, it will reenter ip_newroute() at which
7598 			 * time we will find the IRE_CACHE for the gw and
7599 			 * create another IRE_CACHE in case IRE_CACHE above.
7600 			 */
7601 			if (gw != INADDR_ANY) {
7602 				/*
7603 				 * The source ipif that was determined above was
7604 				 * relative to the destination address, not the
7605 				 * gateway's. If src_ipif was not taken out of
7606 				 * the IRE_IF_RESOLVER entry, we'll need to call
7607 				 * ipif_select_source() again.
7608 				 */
7609 				if (src_ipif != ire->ire_ipif) {
7610 					ipif_refrele(src_ipif);
7611 					src_ipif = ipif_select_source(dst_ill,
7612 					    gw, zoneid);
7613 					if (src_ipif == NULL) {
7614 						if (ip_debug > 2) {
7615 							pr_addr_dbg(
7616 							    "ip_newroute: no "
7617 							    "src for gw %s ",
7618 							    AF_INET, &gw);
7619 							printf("through "
7620 							    "interface %s\n",
7621 							    dst_ill->ill_name);
7622 						}
7623 						goto icmp_err_ret;
7624 					}
7625 				}
7626 				save_dst = dst;
7627 				dst = gw;
7628 				gw = INADDR_ANY;
7629 			}
7630 			/*
7631 			 * We obtain a partial IRE_CACHE which we will pass
7632 			 * along with the resolver query.  When the response
7633 			 * comes back it will be there ready for us to add.
7634 			 * The ire_max_frag is atomically set under the
7635 			 * irebucket lock in ire_add_v[46].
7636 			 */
7637 			ire = ire_create_mp(
7638 			    (uchar_t *)&dst,		/* dest address */
7639 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7640 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7641 			    (uchar_t *)&gw,		/* gateway address */
7642 			    NULL,			/* no in_src_addr */
7643 			    NULL,			/* ire_max_frag */
7644 			    NULL,			/* Fast Path header */
7645 			    dst_ill->ill_rq,		/* recv-from queue */
7646 			    dst_ill->ill_wq,		/* send-to queue */
7647 			    IRE_CACHE,
7648 			    res_mp,
7649 			    src_ipif,			/* Interface ipif */
7650 			    in_ill,			/* Incoming ILL */
7651 			    save_ire->ire_mask,		/* Parent mask */
7652 			    0,
7653 			    save_ire->ire_ihandle,	/* Interface handle */
7654 			    0,				/* flags if any */
7655 			    &(save_ire->ire_uinfo));
7656 
7657 			if (ire == NULL) {
7658 				ire_refrele(save_ire);
7659 				break;
7660 			}
7661 
7662 			if ((sire != NULL) &&
7663 			    (sire->ire_flags & RTF_MULTIRT)) {
7664 				copy_mp = copymsg(first_mp);
7665 				if (copy_mp != NULL)
7666 					MULTIRT_DEBUG_TAG(copy_mp);
7667 			}
7668 
7669 			ire->ire_marks |= ire_marks;
7670 
7671 			/*
7672 			 * Construct message chain for the resolver
7673 			 * of the form:
7674 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7675 			 * Packet could contain a IPSEC_OUT mp.
7676 			 *
7677 			 * NOTE : ire will be added later when the response
7678 			 * comes back from ARP. If the response does not
7679 			 * come back, ARP frees the packet. For this reason,
7680 			 * we can't REFHOLD the bucket of save_ire to prevent
7681 			 * deletions. We may not be able to REFRELE the bucket
7682 			 * if the response never comes back. Thus, before
7683 			 * adding the ire, ire_add_v4 will make sure that the
7684 			 * interface route does not get deleted. This is the
7685 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7686 			 * where we can always prevent deletions because of
7687 			 * the synchronous nature of adding IRES i.e
7688 			 * ire_add_then_send is called after creating the IRE.
7689 			 */
7690 			ASSERT(ire->ire_mp != NULL);
7691 			ire->ire_mp->b_cont = first_mp;
7692 			/* Have saved_mp handy, for cleanup if canput fails */
7693 			saved_mp = mp;
7694 			mp = ire->ire_dlureq_mp;
7695 			ASSERT(mp != NULL);
7696 			ire->ire_dlureq_mp = NULL;
7697 			linkb(mp, ire->ire_mp);
7698 
7699 
7700 			/*
7701 			 * Fill in the source and dest addrs for the resolver.
7702 			 * NOTE: this depends on memory layouts imposed by
7703 			 * ill_init().
7704 			 */
7705 			areq = (areq_t *)mp->b_rptr;
7706 			addrp = (ipaddr_t *)((char *)areq +
7707 			    areq->areq_sender_addr_offset);
7708 			if (do_attach_ill) {
7709 				/*
7710 				 * This is bind to no failover case.
7711 				 * arp packet also must go out on attach_ill.
7712 				 */
7713 				ASSERT(ipha->ipha_src != NULL);
7714 				*addrp = ipha->ipha_src;
7715 			} else {
7716 				*addrp = save_ire->ire_src_addr;
7717 			}
7718 
7719 			ire_refrele(save_ire);
7720 			addrp = (ipaddr_t *)((char *)areq +
7721 			    areq->areq_target_addr_offset);
7722 			*addrp = dst;
7723 			/* Up to the resolver. */
7724 			if (canputnext(dst_ill->ill_rq)) {
7725 				putnext(dst_ill->ill_rq, mp);
7726 				ire = NULL;
7727 				if (copy_mp != NULL) {
7728 					/*
7729 					 * If we found a resolver, we ignore
7730 					 * any trailing top priority IRE_CACHE
7731 					 * in the further loops. This ensures
7732 					 * that we do not omit any resolver.
7733 					 * IRE_CACHE entries, if any, will be
7734 					 * processed next time we enter
7735 					 * ip_newroute().
7736 					 */
7737 					multirt_flags &= ~MULTIRT_CACHEGW;
7738 					/*
7739 					 * Search for the next unresolved
7740 					 * multirt route.
7741 					 */
7742 					first_mp = copy_mp;
7743 					copy_mp = NULL;
7744 					/* Prepare the next resolution loop. */
7745 					mp = first_mp;
7746 					EXTRACT_PKT_MP(mp, first_mp,
7747 					    mctl_present);
7748 					if (mctl_present)
7749 						io = (ipsec_out_t *)
7750 						    first_mp->b_rptr;
7751 					ipha = (ipha_t *)mp->b_rptr;
7752 
7753 					ASSERT(sire != NULL);
7754 
7755 					dst = save_dst;
7756 					multirt_resolve_next = B_TRUE;
7757 					continue;
7758 				}
7759 
7760 				if (sire != NULL)
7761 					ire_refrele(sire);
7762 
7763 				/*
7764 				 * The response will come back in ip_wput
7765 				 * with db_type IRE_DB_TYPE.
7766 				 */
7767 				ipif_refrele(src_ipif);
7768 				ill_refrele(dst_ill);
7769 				return;
7770 			} else {
7771 				/* Prepare for cleanup */
7772 				ire->ire_dlureq_mp = mp;
7773 				mp->b_cont = NULL;
7774 				ire_delete(ire);
7775 				mp = saved_mp;
7776 				ire = NULL;
7777 				if (copy_mp != NULL) {
7778 					MULTIRT_DEBUG_UNTAG(copy_mp);
7779 					freemsg(copy_mp);
7780 					copy_mp = NULL;
7781 				}
7782 				break;
7783 			}
7784 		default:
7785 			break;
7786 		}
7787 	} while (multirt_resolve_next);
7788 
7789 	ip1dbg(("ip_newroute: dropped\n"));
7790 	/* Did this packet originate externally? */
7791 	if (mp->b_prev) {
7792 		mp->b_next = NULL;
7793 		mp->b_prev = NULL;
7794 		BUMP_MIB(&ip_mib, ipInDiscards);
7795 	} else {
7796 		BUMP_MIB(&ip_mib, ipOutDiscards);
7797 	}
7798 	ASSERT(copy_mp == NULL);
7799 	MULTIRT_DEBUG_UNTAG(first_mp);
7800 	freemsg(first_mp);
7801 	if (ire != NULL)
7802 		ire_refrele(ire);
7803 	if (sire != NULL)
7804 		ire_refrele(sire);
7805 	if (src_ipif != NULL)
7806 		ipif_refrele(src_ipif);
7807 	if (dst_ill != NULL)
7808 		ill_refrele(dst_ill);
7809 	return;
7810 
7811 icmp_err_ret:
7812 	ip1dbg(("ip_newroute: no route\n"));
7813 	if (src_ipif != NULL)
7814 		ipif_refrele(src_ipif);
7815 	if (dst_ill != NULL)
7816 		ill_refrele(dst_ill);
7817 	if (sire != NULL)
7818 		ire_refrele(sire);
7819 	/* Did this packet originate externally? */
7820 	if (mp->b_prev) {
7821 		mp->b_next = NULL;
7822 		mp->b_prev = NULL;
7823 		/* XXX ipInNoRoutes */
7824 		q = WR(q);
7825 	} else {
7826 		/*
7827 		 * Since ip_wput() isn't close to finished, we fill
7828 		 * in enough of the header for credible error reporting.
7829 		 */
7830 		if (ip_hdr_complete(ipha, zoneid)) {
7831 			/* Failed */
7832 			MULTIRT_DEBUG_UNTAG(first_mp);
7833 			freemsg(first_mp);
7834 			if (ire != NULL)
7835 				ire_refrele(ire);
7836 			return;
7837 		}
7838 	}
7839 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7840 
7841 	/*
7842 	 * At this point we will have ire only if RTF_BLACKHOLE
7843 	 * or RTF_REJECT flags are set on the IRE. It will not
7844 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7845 	 */
7846 	if (ire != NULL) {
7847 		if (ire->ire_flags & RTF_BLACKHOLE) {
7848 			ire_refrele(ire);
7849 			MULTIRT_DEBUG_UNTAG(first_mp);
7850 			freemsg(first_mp);
7851 			return;
7852 		}
7853 		ire_refrele(ire);
7854 	}
7855 	if (ip_source_routed(ipha)) {
7856 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7857 		return;
7858 	}
7859 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7860 }
7861 
7862 /*
7863  * IPv4 -
7864  * ip_newroute_ipif is called by ip_wput_multicast and
7865  * ip_rput_forward_multicast whenever we need to send
7866  * out a packet to a destination address for which we do not have specific
7867  * routing information. It is used when the packet will be sent out
7868  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7869  * socket option is set or icmp error message wants to go out on a particular
7870  * interface for a unicast packet.
7871  *
7872  * In most cases, the destination address is resolved thanks to the ipif
7873  * intrinsic resolver. However, there are some cases where the call to
7874  * ip_newroute_ipif must take into account the potential presence of
7875  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7876  * that uses the interface. This is specified through flags,
7877  * which can be a combination of:
7878  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7879  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7880  *   and flags. Additionally, the packet source address has to be set to
7881  *   the specified address. The caller is thus expected to set this flag
7882  *   if the packet has no specific source address yet.
7883  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7884  *   flag, the resulting ire will inherit the flag. All unresolved routes
7885  *   to the destination must be explored in the same call to
7886  *   ip_newroute_ipif().
7887  */
7888 static void
7889 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7890     conn_t *connp, uint32_t flags)
7891 {
7892 	areq_t	*areq;
7893 	ire_t	*ire = NULL;
7894 	mblk_t	*res_mp;
7895 	ipaddr_t *addrp;
7896 	mblk_t *first_mp;
7897 	ire_t	*save_ire = NULL;
7898 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7899 	ipif_t	*src_ipif = NULL;
7900 	ushort_t ire_marks = 0;
7901 	ill_t	*dst_ill = NULL;
7902 	boolean_t mctl_present;
7903 	ipsec_out_t *io;
7904 	ipha_t *ipha;
7905 	int	ihandle = 0;
7906 	mblk_t	*saved_mp;
7907 	ire_t   *fire = NULL;
7908 	mblk_t  *copy_mp = NULL;
7909 	boolean_t multirt_resolve_next;
7910 	ipaddr_t ipha_dst;
7911 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7912 
7913 	/*
7914 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7915 	 * here for uniformity
7916 	 */
7917 	ipif_refhold(ipif);
7918 
7919 	/*
7920 	 * This loop is run only once in most cases.
7921 	 * We loop to resolve further routes only when the destination
7922 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7923 	 */
7924 	do {
7925 		if (dst_ill != NULL) {
7926 			ill_refrele(dst_ill);
7927 			dst_ill = NULL;
7928 		}
7929 		if (src_ipif != NULL) {
7930 			ipif_refrele(src_ipif);
7931 			src_ipif = NULL;
7932 		}
7933 		multirt_resolve_next = B_FALSE;
7934 
7935 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7936 		    ipif->ipif_ill->ill_name));
7937 
7938 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7939 		if (mctl_present)
7940 			io = (ipsec_out_t *)first_mp->b_rptr;
7941 
7942 		ipha = (ipha_t *)mp->b_rptr;
7943 
7944 		/*
7945 		 * Save the packet destination address, we may need it after
7946 		 * the packet has been consumed.
7947 		 */
7948 		ipha_dst = ipha->ipha_dst;
7949 
7950 		/*
7951 		 * If the interface is a pt-pt interface we look for an
7952 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7953 		 * local_address and the pt-pt destination address. Otherwise
7954 		 * we just match the local address.
7955 		 * NOTE: dst could be different than ipha->ipha_dst in case
7956 		 * of sending igmp multicast packets over a point-to-point
7957 		 * connection.
7958 		 * Thus we must be careful enough to check ipha_dst to be a
7959 		 * multicast address, otherwise it will take xmit_if path for
7960 		 * multicast packets resulting into kernel stack overflow by
7961 		 * repeated calls to ip_newroute_ipif from ire_send().
7962 		 */
7963 		if (CLASSD(ipha_dst) &&
7964 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7965 			goto err_ret;
7966 		}
7967 
7968 		/*
7969 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7970 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7971 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7972 		 * propagate its flags to the new ire.
7973 		 */
7974 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7975 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7976 			ip2dbg(("ip_newroute_ipif: "
7977 			    "ipif_lookup_multi_ire("
7978 			    "ipif %p, dst %08x) = fire %p\n",
7979 			    (void *)ipif, ntohl(dst), (void *)fire));
7980 		}
7981 
7982 		if (mctl_present && io->ipsec_out_attach_if) {
7983 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7984 			    io->ipsec_out_ill_index, B_FALSE);
7985 
7986 			/* Failure case frees things for us. */
7987 			if (attach_ill == NULL) {
7988 				ipif_refrele(ipif);
7989 				if (fire != NULL)
7990 					ire_refrele(fire);
7991 				return;
7992 			}
7993 
7994 			/*
7995 			 * Check if we need an ire that will not be
7996 			 * looked up by anybody else i.e. HIDDEN.
7997 			 */
7998 			if (ill_is_probeonly(attach_ill)) {
7999 				ire_marks = IRE_MARK_HIDDEN;
8000 			}
8001 			/*
8002 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8003 			 * case.
8004 			 */
8005 			dst_ill = ipif->ipif_ill;
8006 			/* attach_ill has been refheld by ip_grab_attach_ill */
8007 			ASSERT(dst_ill == attach_ill);
8008 		} else {
8009 			/*
8010 			 * If this is set by IP_XMIT_IF, then make sure that
8011 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8012 			 * specified ill.
8013 			 */
8014 			ASSERT((connp == NULL) ||
8015 			    (connp->conn_xmit_if_ill == NULL) ||
8016 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8017 			/*
8018 			 * If the interface belongs to an interface group,
8019 			 * make sure the next possible interface in the group
8020 			 * is used.  This encourages load spreading among
8021 			 * peers in an interface group.
8022 			 * Note: load spreading is disabled for RTF_MULTIRT
8023 			 * routes.
8024 			 */
8025 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8026 			    (fire->ire_flags & RTF_MULTIRT)) {
8027 				/*
8028 				 * Don't perform outbound load spreading
8029 				 * in the case of an RTF_MULTIRT issued route,
8030 				 * we actually typically want to replicate
8031 				 * outgoing packets through particular
8032 				 * interfaces.
8033 				 */
8034 				dst_ill = ipif->ipif_ill;
8035 				ill_refhold(dst_ill);
8036 			} else {
8037 				dst_ill = ip_newroute_get_dst_ill(
8038 				    ipif->ipif_ill);
8039 			}
8040 			if (dst_ill == NULL) {
8041 				if (ip_debug > 2) {
8042 					pr_addr_dbg("ip_newroute_ipif: "
8043 					    "no dst ill for dst %s\n",
8044 					    AF_INET, &dst);
8045 				}
8046 				goto err_ret;
8047 			}
8048 		}
8049 
8050 		/*
8051 		 * Pick a source address preferring non-deprecated ones.
8052 		 * Unlike ip_newroute, we don't do any source address
8053 		 * selection here since for multicast it really does not help
8054 		 * in inbound load spreading as in the unicast case.
8055 		 */
8056 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8057 		    (fire->ire_flags & RTF_SETSRC)) {
8058 			/*
8059 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8060 			 * on that interface. This ire has RTF_SETSRC flag, so
8061 			 * the source address of the packet must be changed.
8062 			 * Check that the ipif matching the requested source
8063 			 * address still exists.
8064 			 */
8065 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8066 			    zoneid, NULL, NULL, NULL, NULL);
8067 		}
8068 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8069 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
8070 		    (src_ipif == NULL)) {
8071 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8072 			if (src_ipif == NULL) {
8073 				if (ip_debug > 2) {
8074 					/* ip1dbg */
8075 					pr_addr_dbg("ip_newroute_ipif: "
8076 					    "no src for dst %s",
8077 					    AF_INET, &dst);
8078 				}
8079 				ip1dbg((" through interface %s\n",
8080 				    dst_ill->ill_name));
8081 				goto err_ret;
8082 			}
8083 			ipif_refrele(ipif);
8084 			ipif = src_ipif;
8085 			ipif_refhold(ipif);
8086 		}
8087 		if (src_ipif == NULL) {
8088 			src_ipif = ipif;
8089 			ipif_refhold(src_ipif);
8090 		}
8091 
8092 		/*
8093 		 * Assign a source address while we have the conn.
8094 		 * We can't have ip_wput_ire pick a source address when the
8095 		 * packet returns from arp since conn_unspec_src might be set
8096 		 * and we loose the conn when going through arp.
8097 		 */
8098 		if (ipha->ipha_src == INADDR_ANY &&
8099 		    (connp == NULL || !connp->conn_unspec_src)) {
8100 			ipha->ipha_src = src_ipif->ipif_src_addr;
8101 		}
8102 
8103 		/*
8104 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8105 		 * interface does not have an interface ire.
8106 		 * Example: Thousands of mobileip PPP interfaces to mobile
8107 		 * nodes. We don't want to create interface ires because
8108 		 * packets from other mobile nodes must not take the route
8109 		 * via interface ires to the visiting mobile node without
8110 		 * going through the home agent, in absence of mobileip
8111 		 * route optimization.
8112 		 */
8113 		if (CLASSD(ipha_dst) && (connp == NULL ||
8114 		    connp->conn_xmit_if_ill == NULL)) {
8115 			/* ipif_to_ire returns an held ire */
8116 			ire = ipif_to_ire(ipif);
8117 			if (ire == NULL)
8118 				goto err_ret;
8119 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8120 				goto err_ret;
8121 			/*
8122 			 * ihandle is needed when the ire is added to
8123 			 * cache table.
8124 			 */
8125 			save_ire = ire;
8126 			ihandle = save_ire->ire_ihandle;
8127 
8128 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8129 			    "flags %04x\n",
8130 			    (void *)ire, (void *)ipif, flags));
8131 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8132 			    (fire->ire_flags & RTF_MULTIRT)) {
8133 				/*
8134 				 * As requested by flags, an IRE_OFFSUBNET was
8135 				 * looked up on that interface. This ire has
8136 				 * RTF_MULTIRT flag, so the resolution loop will
8137 				 * be re-entered to resolve additional routes on
8138 				 * other interfaces. For that purpose, a copy of
8139 				 * the packet is performed at this point.
8140 				 */
8141 				fire->ire_last_used_time = lbolt;
8142 				copy_mp = copymsg(first_mp);
8143 				if (copy_mp) {
8144 					MULTIRT_DEBUG_TAG(copy_mp);
8145 				}
8146 			}
8147 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8148 			    (fire->ire_flags & RTF_SETSRC)) {
8149 				/*
8150 				 * As requested by flags, an IRE_OFFSUBET was
8151 				 * looked up on that interface. This ire has
8152 				 * RTF_SETSRC flag, so the source address of the
8153 				 * packet must be changed.
8154 				 */
8155 				ipha->ipha_src = fire->ire_src_addr;
8156 			}
8157 		} else {
8158 			ASSERT((connp == NULL) ||
8159 			    (connp->conn_xmit_if_ill != NULL) ||
8160 			    (connp->conn_dontroute));
8161 			/*
8162 			 * The only ways we can come here are:
8163 			 * 1) IP_XMIT_IF socket option is set
8164 			 * 2) ICMP error message generated from
8165 			 *    ip_mrtun_forward() routine and it needs
8166 			 *    to go through the specified ill.
8167 			 * 3) SO_DONTROUTE socket option is set
8168 			 * In all cases, the new ire will not be added
8169 			 * into cache table.
8170 			 */
8171 			ire_marks |= IRE_MARK_NOADD;
8172 		}
8173 
8174 		switch (ipif->ipif_net_type) {
8175 		case IRE_IF_NORESOLVER: {
8176 			/* We have what we need to build an IRE_CACHE. */
8177 			mblk_t	*dlureq_mp;
8178 
8179 			/*
8180 			 * Create a new dlureq_mp with the
8181 			 * IP gateway address as destination address in the
8182 			 * DLPI hdr if the physical length is exactly 4 bytes.
8183 			 */
8184 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8185 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8186 				    dst_ill->ill_phys_addr_length,
8187 				    dst_ill->ill_sap,
8188 				    dst_ill->ill_sap_length);
8189 			} else {
8190 				/* use the value set in ip_ll_subnet_defaults */
8191 				dlureq_mp = ill_dlur_gen(NULL,
8192 				    dst_ill->ill_phys_addr_length,
8193 				    dst_ill->ill_sap,
8194 				    dst_ill->ill_sap_length);
8195 			}
8196 
8197 			if (dlureq_mp == NULL)
8198 				break;
8199 			/*
8200 			 * The new ire inherits the IRE_OFFSUBNET flags
8201 			 * and source address, if this was requested.
8202 			 */
8203 			ire = ire_create(
8204 			    (uchar_t *)&dst,		/* dest address */
8205 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8206 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8207 			    NULL,			/* gateway address */
8208 			    NULL,
8209 			    &ipif->ipif_mtu,
8210 			    NULL,			/* Fast Path header */
8211 			    dst_ill->ill_rq,		/* recv-from queue */
8212 			    dst_ill->ill_wq,		/* send-to queue */
8213 			    IRE_CACHE,
8214 			    dlureq_mp,
8215 			    src_ipif,
8216 			    NULL,
8217 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8218 			    (fire != NULL) ?		/* Parent handle */
8219 				fire->ire_phandle : 0,
8220 			    ihandle,			/* Interface handle */
8221 			    (fire != NULL) ?
8222 				(fire->ire_flags &
8223 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8224 			    (save_ire == NULL ? &ire_uinfo_null :
8225 				&save_ire->ire_uinfo));
8226 
8227 			freeb(dlureq_mp);
8228 
8229 			if (ire == NULL) {
8230 				if (save_ire != NULL)
8231 					ire_refrele(save_ire);
8232 				break;
8233 			}
8234 
8235 			ire->ire_marks |= ire_marks;
8236 
8237 			/* Prevent save_ire from getting deleted */
8238 			if (save_ire != NULL) {
8239 				IRB_REFHOLD(save_ire->ire_bucket);
8240 				/* Has it been removed already ? */
8241 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8242 					IRB_REFRELE(save_ire->ire_bucket);
8243 					ire_refrele(save_ire);
8244 					break;
8245 				}
8246 			}
8247 
8248 			ire_add_then_send(q, ire, first_mp);
8249 
8250 			/* Assert that save_ire is not deleted yet. */
8251 			if (save_ire != NULL) {
8252 				ASSERT(save_ire->ire_ptpn != NULL);
8253 				IRB_REFRELE(save_ire->ire_bucket);
8254 				ire_refrele(save_ire);
8255 				save_ire = NULL;
8256 			}
8257 			if (fire != NULL) {
8258 				ire_refrele(fire);
8259 				fire = NULL;
8260 			}
8261 
8262 			/*
8263 			 * the resolution loop is re-entered if this
8264 			 * was requested through flags and if we
8265 			 * actually are in a multirouting case.
8266 			 */
8267 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8268 				boolean_t need_resolve =
8269 				    ire_multirt_need_resolve(ipha_dst);
8270 				if (!need_resolve) {
8271 					MULTIRT_DEBUG_UNTAG(copy_mp);
8272 					freemsg(copy_mp);
8273 					copy_mp = NULL;
8274 				} else {
8275 					/*
8276 					 * ipif_lookup_group() calls
8277 					 * ire_lookup_multi() that uses
8278 					 * ire_ftable_lookup() to find
8279 					 * an IRE_INTERFACE for the group.
8280 					 * In the multirt case,
8281 					 * ire_lookup_multi() then invokes
8282 					 * ire_multirt_lookup() to find
8283 					 * the next resolvable ire.
8284 					 * As a result, we obtain an new
8285 					 * interface, derived from the
8286 					 * next ire.
8287 					 */
8288 					ipif_refrele(ipif);
8289 					ipif = ipif_lookup_group(ipha_dst,
8290 					    zoneid);
8291 					ip2dbg(("ip_newroute_ipif: "
8292 					    "multirt dst %08x, ipif %p\n",
8293 					    htonl(dst), (void *)ipif));
8294 					if (ipif != NULL) {
8295 						mp = copy_mp;
8296 						copy_mp = NULL;
8297 						multirt_resolve_next = B_TRUE;
8298 						continue;
8299 					} else {
8300 						freemsg(copy_mp);
8301 					}
8302 				}
8303 			}
8304 			if (ipif != NULL)
8305 				ipif_refrele(ipif);
8306 			ill_refrele(dst_ill);
8307 			ipif_refrele(src_ipif);
8308 			return;
8309 		}
8310 		case IRE_IF_RESOLVER:
8311 			/*
8312 			 * We can't build an IRE_CACHE yet, but at least
8313 			 * we found a resolver that can help.
8314 			 */
8315 			res_mp = dst_ill->ill_resolver_mp;
8316 			if (!OK_RESOLVER_MP(res_mp))
8317 				break;
8318 
8319 			/*
8320 			 * We obtain a partial IRE_CACHE which we will pass
8321 			 * along with the resolver query.  When the response
8322 			 * comes back it will be there ready for us to add.
8323 			 * The new ire inherits the IRE_OFFSUBNET flags
8324 			 * and source address, if this was requested.
8325 			 * The ire_max_frag is atomically set under the
8326 			 * irebucket lock in ire_add_v[46]. Only in the
8327 			 * case of IRE_MARK_NOADD, we set it here itself.
8328 			 */
8329 			ire = ire_create_mp(
8330 			    (uchar_t *)&dst,		/* dest address */
8331 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8332 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8333 			    NULL,			/* gateway address */
8334 			    NULL,			/* no in_src_addr */
8335 			    (ire_marks & IRE_MARK_NOADD) ?
8336 				ipif->ipif_mtu : 0,	/* max_frag */
8337 			    NULL,			/* Fast path header */
8338 			    dst_ill->ill_rq,		/* recv-from queue */
8339 			    dst_ill->ill_wq,		/* send-to queue */
8340 			    IRE_CACHE,
8341 			    res_mp,
8342 			    src_ipif,
8343 			    NULL,
8344 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8345 			    (fire != NULL) ?		/* Parent handle */
8346 				fire->ire_phandle : 0,
8347 			    ihandle,			/* Interface handle */
8348 			    (fire != NULL) ?		/* flags if any */
8349 				(fire->ire_flags &
8350 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8351 			    (save_ire == NULL ? &ire_uinfo_null :
8352 				&save_ire->ire_uinfo));
8353 
8354 			if (save_ire != NULL) {
8355 				ire_refrele(save_ire);
8356 				save_ire = NULL;
8357 			}
8358 			if (ire == NULL)
8359 				break;
8360 
8361 			ire->ire_marks |= ire_marks;
8362 			/*
8363 			 * Construct message chain for the resolver of the
8364 			 * form:
8365 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8366 			 *
8367 			 * NOTE : ire will be added later when the response
8368 			 * comes back from ARP. If the response does not
8369 			 * come back, ARP frees the packet. For this reason,
8370 			 * we can't REFHOLD the bucket of save_ire to prevent
8371 			 * deletions. We may not be able to REFRELE the
8372 			 * bucket if the response never comes back.
8373 			 * Thus, before adding the ire, ire_add_v4 will make
8374 			 * sure that the interface route does not get deleted.
8375 			 * This is the only case unlike ip_newroute_v6,
8376 			 * ip_newroute_ipif_v6 where we can always prevent
8377 			 * deletions because ire_add_then_send is called after
8378 			 * creating the IRE.
8379 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8380 			 * does not add this IRE into the IRE CACHE.
8381 			 */
8382 			ASSERT(ire->ire_mp != NULL);
8383 			ire->ire_mp->b_cont = first_mp;
8384 			/* Have saved_mp handy, for cleanup if canput fails */
8385 			saved_mp = mp;
8386 			mp = ire->ire_dlureq_mp;
8387 			ASSERT(mp != NULL);
8388 			ire->ire_dlureq_mp = NULL;
8389 			linkb(mp, ire->ire_mp);
8390 
8391 			/*
8392 			 * Fill in the source and dest addrs for the resolver.
8393 			 * NOTE: this depends on memory layouts imposed by
8394 			 * ill_init().
8395 			 */
8396 			areq = (areq_t *)mp->b_rptr;
8397 			addrp = (ipaddr_t *)((char *)areq +
8398 			    areq->areq_sender_addr_offset);
8399 			*addrp = ire->ire_src_addr;
8400 			addrp = (ipaddr_t *)((char *)areq +
8401 			    areq->areq_target_addr_offset);
8402 			*addrp = dst;
8403 			/* Up to the resolver. */
8404 			if (canputnext(dst_ill->ill_rq)) {
8405 				putnext(dst_ill->ill_rq, mp);
8406 				/*
8407 				 * The response will come back in ip_wput
8408 				 * with db_type IRE_DB_TYPE.
8409 				 */
8410 			} else {
8411 				ire->ire_dlureq_mp = mp;
8412 				mp->b_cont = NULL;
8413 				ire_delete(ire);
8414 				saved_mp->b_next = NULL;
8415 				saved_mp->b_prev = NULL;
8416 				freemsg(first_mp);
8417 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8418 			}
8419 
8420 			if (fire != NULL) {
8421 				ire_refrele(fire);
8422 				fire = NULL;
8423 			}
8424 
8425 
8426 			/*
8427 			 * The resolution loop is re-entered if this was
8428 			 * requested through flags and we actually are
8429 			 * in a multirouting case.
8430 			 */
8431 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8432 				boolean_t need_resolve =
8433 				    ire_multirt_need_resolve(ipha_dst);
8434 				if (!need_resolve) {
8435 					MULTIRT_DEBUG_UNTAG(copy_mp);
8436 					freemsg(copy_mp);
8437 					copy_mp = NULL;
8438 				} else {
8439 					/*
8440 					 * ipif_lookup_group() calls
8441 					 * ire_lookup_multi() that uses
8442 					 * ire_ftable_lookup() to find
8443 					 * an IRE_INTERFACE for the group.
8444 					 * In the multirt case,
8445 					 * ire_lookup_multi() then invokes
8446 					 * ire_multirt_lookup() to find
8447 					 * the next resolvable ire.
8448 					 * As a result, we obtain an new
8449 					 * interface, derived from the
8450 					 * next ire.
8451 					 */
8452 					ipif_refrele(ipif);
8453 					ipif = ipif_lookup_group(ipha_dst,
8454 					    zoneid);
8455 					if (ipif != NULL) {
8456 						mp = copy_mp;
8457 						copy_mp = NULL;
8458 						multirt_resolve_next = B_TRUE;
8459 						continue;
8460 					} else {
8461 						freemsg(copy_mp);
8462 					}
8463 				}
8464 			}
8465 			if (ipif != NULL)
8466 				ipif_refrele(ipif);
8467 			ill_refrele(dst_ill);
8468 			ipif_refrele(src_ipif);
8469 			return;
8470 		default:
8471 			break;
8472 		}
8473 	} while (multirt_resolve_next);
8474 
8475 err_ret:
8476 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8477 	if (fire != NULL)
8478 		ire_refrele(fire);
8479 	ipif_refrele(ipif);
8480 	/* Did this packet originate externally? */
8481 	if (dst_ill != NULL)
8482 		ill_refrele(dst_ill);
8483 	if (src_ipif != NULL)
8484 		ipif_refrele(src_ipif);
8485 	if (mp->b_prev || mp->b_next) {
8486 		mp->b_next = NULL;
8487 		mp->b_prev = NULL;
8488 	} else {
8489 		/*
8490 		 * Since ip_wput() isn't close to finished, we fill
8491 		 * in enough of the header for credible error reporting.
8492 		 */
8493 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8494 			/* Failed */
8495 			freemsg(first_mp);
8496 			if (ire != NULL)
8497 				ire_refrele(ire);
8498 			return;
8499 		}
8500 	}
8501 	/*
8502 	 * At this point we will have ire only if RTF_BLACKHOLE
8503 	 * or RTF_REJECT flags are set on the IRE. It will not
8504 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8505 	 */
8506 	if (ire != NULL) {
8507 		if (ire->ire_flags & RTF_BLACKHOLE) {
8508 			ire_refrele(ire);
8509 			freemsg(first_mp);
8510 			return;
8511 		}
8512 		ire_refrele(ire);
8513 	}
8514 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8515 }
8516 
8517 /* Name/Value Table Lookup Routine */
8518 char *
8519 ip_nv_lookup(nv_t *nv, int value)
8520 {
8521 	if (!nv)
8522 		return (NULL);
8523 	for (; nv->nv_name; nv++) {
8524 		if (nv->nv_value == value)
8525 			return (nv->nv_name);
8526 	}
8527 	return ("unknown");
8528 }
8529 
8530 /*
8531  * one day it can be patched to 1 from /etc/system for machines that have few
8532  * fast network interfaces feeding multiple cpus.
8533  */
8534 int ill_stream_putlocks = 0;
8535 
8536 /*
8537  * This is a module open, i.e. this is a control stream for access
8538  * to a DLPI device.  We allocate an ill_t as the instance data in
8539  * this case.
8540  */
8541 int
8542 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8543 {
8544 	uint32_t mem_cnt;
8545 	uint32_t cpu_cnt;
8546 	uint32_t min_cnt;
8547 	pgcnt_t mem_avail;
8548 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8549 	ill_t	*ill;
8550 	int	err;
8551 
8552 	/*
8553 	 * Prevent unprivileged processes from pushing IP so that
8554 	 * they can't send raw IP.
8555 	 */
8556 	if (secpolicy_net_rawaccess(credp) != 0)
8557 		return (EPERM);
8558 
8559 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8560 	q->q_ptr = WR(q)->q_ptr = ill;
8561 
8562 	/*
8563 	 * ill_init initializes the ill fields and then sends down
8564 	 * down a DL_INFO_REQ after calling qprocson.
8565 	 */
8566 	err = ill_init(q, ill);
8567 	if (err != 0) {
8568 		mi_free(ill);
8569 		q->q_ptr = NULL;
8570 		WR(q)->q_ptr = NULL;
8571 		return (err);
8572 	}
8573 
8574 	/* ill_init initializes the ipsq marking this thread as writer */
8575 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8576 	/* Wait for the DL_INFO_ACK */
8577 	mutex_enter(&ill->ill_lock);
8578 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8579 		/*
8580 		 * Return value of 0 indicates a pending signal.
8581 		 */
8582 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8583 		if (err == 0) {
8584 			mutex_exit(&ill->ill_lock);
8585 			(void) ip_close(q, 0);
8586 			return (EINTR);
8587 		}
8588 	}
8589 	mutex_exit(&ill->ill_lock);
8590 
8591 	/*
8592 	 * ip_rput_other could have set an error  in ill_error on
8593 	 * receipt of M_ERROR.
8594 	 */
8595 
8596 	err = ill->ill_error;
8597 	if (err != 0) {
8598 		(void) ip_close(q, 0);
8599 		return (err);
8600 	}
8601 
8602 	/*
8603 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8604 	 * size and the cpu speed of the machine. This is upper
8605 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8606 	 * and is lower bounded by the compile time value of
8607 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8608 	 * ip6_ire_max_bucket_cnt.
8609 	 */
8610 	mem_avail = kmem_avail();
8611 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8612 	    ip_cache_table_size / sizeof (ire_t);
8613 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8614 
8615 	min_cnt = MIN(cpu_cnt, mem_cnt);
8616 	if (min_cnt < ip_ire_min_bucket_cnt)
8617 		min_cnt = ip_ire_min_bucket_cnt;
8618 	if (ip_ire_max_bucket_cnt > min_cnt) {
8619 		ip_ire_max_bucket_cnt = min_cnt;
8620 	}
8621 
8622 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8623 	    ip6_cache_table_size / sizeof (ire_t);
8624 	min_cnt = MIN(cpu_cnt, mem_cnt);
8625 	if (min_cnt < ip6_ire_min_bucket_cnt)
8626 		min_cnt = ip6_ire_min_bucket_cnt;
8627 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8628 		ip6_ire_max_bucket_cnt = min_cnt;
8629 	}
8630 
8631 	ill->ill_credp = credp;
8632 	crhold(credp);
8633 
8634 	mutex_enter(&ip_mi_lock);
8635 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8636 	mutex_exit(&ip_mi_lock);
8637 	if (err) {
8638 		(void) ip_close(q, 0);
8639 		return (err);
8640 	}
8641 	return (0);
8642 }
8643 
8644 /* IP open routine. */
8645 int
8646 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8647 {
8648 	conn_t 		*connp;
8649 	major_t		maj;
8650 
8651 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8652 
8653 	/* Allow reopen. */
8654 	if (q->q_ptr != NULL)
8655 		return (0);
8656 
8657 	if (sflag & MODOPEN) {
8658 		/* This is a module open */
8659 		return (ip_modopen(q, devp, flag, sflag, credp));
8660 	}
8661 
8662 	/*
8663 	 * We are opening as a device. This is an IP client stream, and we
8664 	 * allocate an conn_t as the instance data.
8665 	 */
8666 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8667 	connp->conn_upq = q;
8668 	q->q_ptr = WR(q)->q_ptr = connp;
8669 
8670 	if (flag & SO_SOCKSTR)
8671 		connp->conn_flags |= IPCL_SOCKET;
8672 
8673 	/* Minor tells us which /dev entry was opened */
8674 	if (geteminor(*devp) == IPV6_MINOR) {
8675 		connp->conn_flags |= IPCL_ISV6;
8676 		connp->conn_af_isv6 = B_TRUE;
8677 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8678 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8679 	} else {
8680 		connp->conn_af_isv6 = B_FALSE;
8681 		connp->conn_pkt_isv6 = B_FALSE;
8682 	}
8683 
8684 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
8685 		q->q_ptr = WR(q)->q_ptr = NULL;
8686 		CONN_DEC_REF(connp);
8687 		return (EBUSY);
8688 	}
8689 
8690 	maj = getemajor(*devp);
8691 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8692 
8693 	/*
8694 	 * connp->conn_cred is crfree()ed in ip_close().
8695 	 */
8696 	connp->conn_cred = credp;
8697 	crhold(connp->conn_cred);
8698 
8699 	connp->conn_zoneid = getzoneid();
8700 
8701 	/*
8702 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8703 	 * administrative ops.  In these cases, we just need a normal conn_t
8704 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8705 	 * an error will be returned.
8706 	 */
8707 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8708 		connp->conn_rq = q;
8709 		connp->conn_wq = WR(q);
8710 	} else {
8711 		connp->conn_ulp = IPPROTO_SCTP;
8712 		connp->conn_rq = connp->conn_wq = NULL;
8713 	}
8714 	/* Non-zero default values */
8715 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8716 
8717 	/*
8718 	 * Make the conn globally visible to walkers
8719 	 */
8720 	mutex_enter(&connp->conn_lock);
8721 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8722 	mutex_exit(&connp->conn_lock);
8723 	ASSERT(connp->conn_ref == 1);
8724 
8725 	qprocson(q);
8726 
8727 	return (0);
8728 }
8729 
8730 /*
8731  * Change q_qinfo based on the value of isv6.
8732  * This can not called on an ill queue.
8733  * Note that there is no race since either q_qinfo works for conn queues - it
8734  * is just an optimization to enter the best wput routine directly.
8735  */
8736 void
8737 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8738 {
8739 	ASSERT(q->q_flag & QREADR);
8740 	ASSERT(WR(q)->q_next == NULL);
8741 	ASSERT(q->q_ptr != NULL);
8742 
8743 	if (minor == IPV6_MINOR)  {
8744 		if (bump_mib)
8745 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8746 		q->q_qinfo = &rinit_ipv6;
8747 		WR(q)->q_qinfo = &winit_ipv6;
8748 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8749 	} else {
8750 		if (bump_mib)
8751 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8752 		q->q_qinfo = &rinit;
8753 		WR(q)->q_qinfo = &winit;
8754 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8755 	}
8756 
8757 }
8758 
8759 /*
8760  * See if IPsec needs loading because of the options in mp.
8761  */
8762 static boolean_t
8763 ipsec_opt_present(mblk_t *mp)
8764 {
8765 	uint8_t *optcp, *next_optcp, *opt_endcp;
8766 	struct opthdr *opt;
8767 	struct T_opthdr *topt;
8768 	int opthdr_len;
8769 	t_uscalar_t optname, optlevel;
8770 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8771 	ipsec_req_t *ipsr;
8772 
8773 	/*
8774 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8775 	 * return TRUE.
8776 	 */
8777 
8778 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8779 	opt_endcp = optcp + tor->OPT_length;
8780 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8781 		opthdr_len = sizeof (struct T_opthdr);
8782 	} else {		/* O_OPTMGMT_REQ */
8783 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8784 		opthdr_len = sizeof (struct opthdr);
8785 	}
8786 	for (; optcp < opt_endcp; optcp = next_optcp) {
8787 		if (optcp + opthdr_len > opt_endcp)
8788 			return (B_FALSE);	/* Not enough option header. */
8789 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8790 			topt = (struct T_opthdr *)optcp;
8791 			optlevel = topt->level;
8792 			optname = topt->name;
8793 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8794 		} else {
8795 			opt = (struct opthdr *)optcp;
8796 			optlevel = opt->level;
8797 			optname = opt->name;
8798 			next_optcp = optcp + opthdr_len +
8799 			    _TPI_ALIGN_OPT(opt->len);
8800 		}
8801 		if ((next_optcp < optcp) || /* wraparound pointer space */
8802 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8803 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8804 			return (B_FALSE); /* bad option buffer */
8805 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8806 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8807 			/*
8808 			 * Check to see if it's an all-bypass or all-zeroes
8809 			 * IPsec request.  Don't bother loading IPsec if
8810 			 * the socket doesn't want to use it.  (A good example
8811 			 * is a bypass request.)
8812 			 *
8813 			 * Basically, if any of the non-NEVER bits are set,
8814 			 * load IPsec.
8815 			 */
8816 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8817 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8818 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8819 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8820 			    != 0)
8821 				return (B_TRUE);
8822 		}
8823 	}
8824 	return (B_FALSE);
8825 }
8826 
8827 /*
8828  * If conn is is waiting for ipsec to finish loading, kick it.
8829  */
8830 /* ARGSUSED */
8831 static void
8832 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8833 {
8834 	t_scalar_t	optreq_prim;
8835 	mblk_t		*mp;
8836 	cred_t		*cr;
8837 	int		err = 0;
8838 
8839 	/*
8840 	 * This function is called, after ipsec loading is complete.
8841 	 * Since IP checks exclusively and atomically (i.e it prevents
8842 	 * ipsec load from completing until ip_optcom_req completes)
8843 	 * whether ipsec load is complete, there cannot be a race with IP
8844 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8845 	 */
8846 	mutex_enter(&connp->conn_lock);
8847 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8848 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8849 		mp = connp->conn_ipsec_opt_mp;
8850 		connp->conn_ipsec_opt_mp = NULL;
8851 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8852 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8853 		mutex_exit(&connp->conn_lock);
8854 
8855 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8856 
8857 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8858 		if (optreq_prim == T_OPTMGMT_REQ) {
8859 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8860 			    &ip_opt_obj);
8861 		} else {
8862 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8863 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8864 			    &ip_opt_obj);
8865 		}
8866 		if (err != EINPROGRESS)
8867 			CONN_OPER_PENDING_DONE(connp);
8868 		return;
8869 	}
8870 	mutex_exit(&connp->conn_lock);
8871 }
8872 
8873 /*
8874  * Called from the ipsec_loader thread, outside any perimeter, to tell
8875  * ip qenable any of the queues waiting for the ipsec loader to
8876  * complete.
8877  *
8878  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8879  * are done with this lock held, so it's guaranteed that none of the
8880  * links will change along the way.
8881  */
8882 void
8883 ip_ipsec_load_complete()
8884 {
8885 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8886 }
8887 
8888 /*
8889  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8890  * determines the grp on which it has to become exclusive, queues the mp
8891  * and sq draining restarts the optmgmt
8892  */
8893 static boolean_t
8894 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8895 {
8896 	conn_t *connp;
8897 
8898 	/*
8899 	 * Take IPsec requests and treat them special.
8900 	 */
8901 	if (ipsec_opt_present(mp)) {
8902 		/* First check if IPsec is loaded. */
8903 		mutex_enter(&ipsec_loader_lock);
8904 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8905 			mutex_exit(&ipsec_loader_lock);
8906 			return (B_FALSE);
8907 		}
8908 		connp = Q_TO_CONN(q);
8909 		mutex_enter(&connp->conn_lock);
8910 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8911 
8912 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8913 		connp->conn_ipsec_opt_mp = mp;
8914 		mutex_exit(&connp->conn_lock);
8915 		mutex_exit(&ipsec_loader_lock);
8916 
8917 		ipsec_loader_loadnow();
8918 		return (B_TRUE);
8919 	}
8920 	return (B_FALSE);
8921 }
8922 
8923 /*
8924  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8925  * all of them are copied to the conn_t. If the req is "zero", the policy is
8926  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8927  * fields.
8928  * We keep only the latest setting of the policy and thus policy setting
8929  * is not incremental/cumulative.
8930  *
8931  * Requests to set policies with multiple alternative actions will
8932  * go through a different API.
8933  */
8934 int
8935 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8936 {
8937 	uint_t ah_req = 0;
8938 	uint_t esp_req = 0;
8939 	uint_t se_req = 0;
8940 	ipsec_selkey_t sel;
8941 	ipsec_act_t *actp = NULL;
8942 	uint_t nact;
8943 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8944 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8945 	ipsec_policy_root_t *pr;
8946 	ipsec_policy_head_t *ph;
8947 	int fam;
8948 	boolean_t is_pol_reset;
8949 	int error = 0;
8950 
8951 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8952 
8953 	/*
8954 	 * The IP_SEC_OPT option does not allow variable length parameters,
8955 	 * hence a request cannot be NULL.
8956 	 */
8957 	if (req == NULL)
8958 		return (EINVAL);
8959 
8960 	ah_req = req->ipsr_ah_req;
8961 	esp_req = req->ipsr_esp_req;
8962 	se_req = req->ipsr_self_encap_req;
8963 
8964 	/*
8965 	 * Are we dealing with a request to reset the policy (i.e.
8966 	 * zero requests).
8967 	 */
8968 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8969 	    (esp_req & REQ_MASK) == 0 &&
8970 	    (se_req & REQ_MASK) == 0);
8971 
8972 	if (!is_pol_reset) {
8973 		/*
8974 		 * If we couldn't load IPsec, fail with "protocol
8975 		 * not supported".
8976 		 * IPsec may not have been loaded for a request with zero
8977 		 * policies, so we don't fail in this case.
8978 		 */
8979 		mutex_enter(&ipsec_loader_lock);
8980 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8981 			mutex_exit(&ipsec_loader_lock);
8982 			return (EPROTONOSUPPORT);
8983 		}
8984 		mutex_exit(&ipsec_loader_lock);
8985 
8986 		/*
8987 		 * Test for valid requests. Invalid algorithms
8988 		 * need to be tested by IPSEC code because new
8989 		 * algorithms can be added dynamically.
8990 		 */
8991 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8992 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8993 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8994 			return (EINVAL);
8995 		}
8996 
8997 		/*
8998 		 * Only privileged users can issue these
8999 		 * requests.
9000 		 */
9001 		if (((ah_req & IPSEC_PREF_NEVER) ||
9002 		    (esp_req & IPSEC_PREF_NEVER) ||
9003 		    (se_req & IPSEC_PREF_NEVER)) &&
9004 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9005 			return (EPERM);
9006 		}
9007 
9008 		/*
9009 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9010 		 * are mutually exclusive.
9011 		 */
9012 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9013 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9014 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9015 			/* Both of them are set */
9016 			return (EINVAL);
9017 		}
9018 	}
9019 
9020 	mutex_enter(&connp->conn_lock);
9021 
9022 	/*
9023 	 * If we have already cached policies in ip_bind_connected*(), don't
9024 	 * let them change now. We cache policies for connections
9025 	 * whose src,dst [addr, port] is known.  The exception to this is
9026 	 * tunnels.  Tunnels are allowed to change policies after having
9027 	 * become fully bound.
9028 	 */
9029 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9030 		mutex_exit(&connp->conn_lock);
9031 		return (EINVAL);
9032 	}
9033 
9034 	/*
9035 	 * We have a zero policies, reset the connection policy if already
9036 	 * set. This will cause the connection to inherit the
9037 	 * global policy, if any.
9038 	 */
9039 	if (is_pol_reset) {
9040 		if (connp->conn_policy != NULL) {
9041 			IPPH_REFRELE(connp->conn_policy);
9042 			connp->conn_policy = NULL;
9043 		}
9044 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9045 		connp->conn_in_enforce_policy = B_FALSE;
9046 		connp->conn_out_enforce_policy = B_FALSE;
9047 		mutex_exit(&connp->conn_lock);
9048 		return (0);
9049 	}
9050 
9051 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9052 	if (ph == NULL)
9053 		goto enomem;
9054 
9055 	ipsec_actvec_from_req(req, &actp, &nact);
9056 	if (actp == NULL)
9057 		goto enomem;
9058 
9059 	/*
9060 	 * Always allocate IPv4 policy entries, since they can also
9061 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9062 	 */
9063 	bzero(&sel, sizeof (sel));
9064 	sel.ipsl_valid = IPSL_IPV4;
9065 
9066 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9067 	if (pin4 == NULL)
9068 		goto enomem;
9069 
9070 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9071 	if (pout4 == NULL)
9072 		goto enomem;
9073 
9074 	if (connp->conn_pkt_isv6) {
9075 		/*
9076 		 * We're looking at a v6 socket, also allocate the
9077 		 * v6-specific entries...
9078 		 */
9079 		sel.ipsl_valid = IPSL_IPV6;
9080 		pin6 = ipsec_policy_create(&sel, actp, nact,
9081 		    IPSEC_PRIO_SOCKET);
9082 		if (pin6 == NULL)
9083 			goto enomem;
9084 
9085 		pout6 = ipsec_policy_create(&sel, actp, nact,
9086 		    IPSEC_PRIO_SOCKET);
9087 		if (pout6 == NULL)
9088 			goto enomem;
9089 
9090 		/*
9091 		 * .. and file them away in the right place.
9092 		 */
9093 		fam = IPSEC_AF_V6;
9094 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9095 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9096 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9097 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9098 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9099 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9100 	}
9101 
9102 	ipsec_actvec_free(actp, nact);
9103 
9104 	/*
9105 	 * File the v4 policies.
9106 	 */
9107 	fam = IPSEC_AF_V4;
9108 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9109 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9110 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9111 
9112 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9113 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9114 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9115 
9116 	/*
9117 	 * If the requests need security, set enforce_policy.
9118 	 * If the requests are IPSEC_PREF_NEVER, one should
9119 	 * still set conn_out_enforce_policy so that an ipsec_out
9120 	 * gets attached in ip_wput. This is needed so that
9121 	 * for connections that we don't cache policy in ip_bind,
9122 	 * if global policy matches in ip_wput_attach_policy, we
9123 	 * don't wrongly inherit global policy. Similarly, we need
9124 	 * to set conn_in_enforce_policy also so that we don't verify
9125 	 * policy wrongly.
9126 	 */
9127 	if ((ah_req & REQ_MASK) != 0 ||
9128 	    (esp_req & REQ_MASK) != 0 ||
9129 	    (se_req & REQ_MASK) != 0) {
9130 		connp->conn_in_enforce_policy = B_TRUE;
9131 		connp->conn_out_enforce_policy = B_TRUE;
9132 		connp->conn_flags |= IPCL_CHECK_POLICY;
9133 	}
9134 
9135 	/*
9136 	 * Tunnels are allowed to set policy after having been fully bound.
9137 	 * If that's the case, cache policy here.
9138 	 */
9139 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9140 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9141 
9142 	mutex_exit(&connp->conn_lock);
9143 	return (error);
9144 #undef REQ_MASK
9145 
9146 	/*
9147 	 * Common memory-allocation-failure exit path.
9148 	 */
9149 enomem:
9150 	mutex_exit(&connp->conn_lock);
9151 	if (actp != NULL)
9152 		ipsec_actvec_free(actp, nact);
9153 	if (pin4 != NULL)
9154 		IPPOL_REFRELE(pin4);
9155 	if (pout4 != NULL)
9156 		IPPOL_REFRELE(pout4);
9157 	if (pin6 != NULL)
9158 		IPPOL_REFRELE(pin6);
9159 	if (pout6 != NULL)
9160 		IPPOL_REFRELE(pout6);
9161 	return (ENOMEM);
9162 }
9163 
9164 /*
9165  * Only for options that pass in an IP addr. Currently only V4 options
9166  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9167  * So this function assumes level is IPPROTO_IP
9168  */
9169 int
9170 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9171     mblk_t *first_mp)
9172 {
9173 	ipif_t *ipif = NULL;
9174 	int error;
9175 	ill_t *ill;
9176 
9177 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9178 
9179 	if (addr != INADDR_ANY || checkonly) {
9180 		ASSERT(connp != NULL);
9181 		if (option == IP_NEXTHOP) {
9182 			ipif =
9183 			    ipif_lookup_onlink_addr(addr, connp->conn_zoneid);
9184 		} else {
9185 			ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9186 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9187 			    &error);
9188 		}
9189 		if (ipif == NULL) {
9190 			if (error == EINPROGRESS)
9191 				return (error);
9192 			else if ((option == IP_MULTICAST_IF) ||
9193 			    (option == IP_NEXTHOP))
9194 				return (EHOSTUNREACH);
9195 			else
9196 				return (EINVAL);
9197 		} else if (checkonly) {
9198 			if (option == IP_MULTICAST_IF) {
9199 				ill = ipif->ipif_ill;
9200 				/* not supported by the virtual network iface */
9201 				if (IS_VNI(ill)) {
9202 					ipif_refrele(ipif);
9203 					return (EINVAL);
9204 				}
9205 			}
9206 			ipif_refrele(ipif);
9207 			return (0);
9208 		}
9209 		ill = ipif->ipif_ill;
9210 		mutex_enter(&connp->conn_lock);
9211 		mutex_enter(&ill->ill_lock);
9212 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9213 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9214 			mutex_exit(&ill->ill_lock);
9215 			mutex_exit(&connp->conn_lock);
9216 			ipif_refrele(ipif);
9217 			return (option == IP_MULTICAST_IF ?
9218 			    EHOSTUNREACH : EINVAL);
9219 		}
9220 	} else {
9221 		mutex_enter(&connp->conn_lock);
9222 	}
9223 
9224 	/* None of the options below are supported on the VNI */
9225 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9226 		mutex_exit(&ill->ill_lock);
9227 		mutex_exit(&connp->conn_lock);
9228 		ipif_refrele(ipif);
9229 		return (EINVAL);
9230 	}
9231 
9232 	switch (option) {
9233 	case IP_DONTFAILOVER_IF:
9234 		/*
9235 		 * This option is used by in.mpathd to ensure
9236 		 * that IPMP probe packets only go out on the
9237 		 * test interfaces. in.mpathd sets this option
9238 		 * on the non-failover interfaces.
9239 		 * For backward compatibility, this option
9240 		 * implicitly sets IP_MULTICAST_IF, as used
9241 		 * be done in bind(), so that ip_wput gets
9242 		 * this ipif to send mcast packets.
9243 		 */
9244 		if (ipif != NULL) {
9245 			ASSERT(addr != INADDR_ANY);
9246 			connp->conn_nofailover_ill = ipif->ipif_ill;
9247 			connp->conn_multicast_ipif = ipif;
9248 		} else {
9249 			ASSERT(addr == INADDR_ANY);
9250 			connp->conn_nofailover_ill = NULL;
9251 			connp->conn_multicast_ipif = NULL;
9252 		}
9253 		break;
9254 
9255 	case IP_MULTICAST_IF:
9256 		connp->conn_multicast_ipif = ipif;
9257 		break;
9258 	case IP_NEXTHOP:
9259 		connp->conn_nexthop_v4 = addr;
9260 		connp->conn_nexthop_set = B_TRUE;
9261 		break;
9262 	}
9263 
9264 	if (ipif != NULL) {
9265 		mutex_exit(&ill->ill_lock);
9266 		mutex_exit(&connp->conn_lock);
9267 		ipif_refrele(ipif);
9268 		return (0);
9269 	}
9270 	mutex_exit(&connp->conn_lock);
9271 	/* We succeded in cleared the option */
9272 	return (0);
9273 }
9274 
9275 /*
9276  * For options that pass in an ifindex specifying the ill. V6 options always
9277  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9278  */
9279 int
9280 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9281     int level, int option, mblk_t *first_mp)
9282 {
9283 	ill_t *ill = NULL;
9284 	int error = 0;
9285 
9286 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9287 	if (ifindex != 0) {
9288 		ASSERT(connp != NULL);
9289 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9290 		    first_mp, ip_restart_optmgmt, &error);
9291 		if (ill != NULL) {
9292 			if (checkonly) {
9293 				/* not supported by the virtual network iface */
9294 				if (IS_VNI(ill)) {
9295 					ill_refrele(ill);
9296 					return (EINVAL);
9297 				}
9298 				ill_refrele(ill);
9299 				return (0);
9300 			}
9301 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9302 			    0, NULL)) {
9303 				ill_refrele(ill);
9304 				ill = NULL;
9305 				mutex_enter(&connp->conn_lock);
9306 				goto setit;
9307 			}
9308 			mutex_enter(&connp->conn_lock);
9309 			mutex_enter(&ill->ill_lock);
9310 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9311 				mutex_exit(&ill->ill_lock);
9312 				mutex_exit(&connp->conn_lock);
9313 				ill_refrele(ill);
9314 				ill = NULL;
9315 				mutex_enter(&connp->conn_lock);
9316 			}
9317 			goto setit;
9318 		} else if (error == EINPROGRESS) {
9319 			return (error);
9320 		} else {
9321 			error = 0;
9322 		}
9323 	}
9324 	mutex_enter(&connp->conn_lock);
9325 setit:
9326 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9327 
9328 	/*
9329 	 * The options below assume that the ILL (if any) transmits and/or
9330 	 * receives traffic. Neither of which is true for the virtual network
9331 	 * interface, so fail setting these on a VNI.
9332 	 */
9333 	if (IS_VNI(ill)) {
9334 		ASSERT(ill != NULL);
9335 		mutex_exit(&ill->ill_lock);
9336 		mutex_exit(&connp->conn_lock);
9337 		ill_refrele(ill);
9338 		return (EINVAL);
9339 	}
9340 
9341 	if (level == IPPROTO_IP) {
9342 		switch (option) {
9343 		case IP_BOUND_IF:
9344 			connp->conn_incoming_ill = ill;
9345 			connp->conn_outgoing_ill = ill;
9346 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9347 			    0 : ifindex;
9348 			break;
9349 
9350 		case IP_XMIT_IF:
9351 			/*
9352 			 * Similar to IP_BOUND_IF, but this only
9353 			 * determines the outgoing interface for
9354 			 * unicast packets. Also no IRE_CACHE entry
9355 			 * is added for the destination of the
9356 			 * outgoing packets. This feature is needed
9357 			 * for mobile IP.
9358 			 */
9359 			connp->conn_xmit_if_ill = ill;
9360 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9361 			    0 : ifindex;
9362 			break;
9363 
9364 		case IP_MULTICAST_IF:
9365 			/*
9366 			 * This option is an internal special. The socket
9367 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9368 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9369 			 * specifies an ifindex and we try first on V6 ill's.
9370 			 * If we don't find one, we they try using on v4 ill's
9371 			 * intenally and we come here.
9372 			 */
9373 			if (!checkonly && ill != NULL) {
9374 				ipif_t	*ipif;
9375 				ipif = ill->ill_ipif;
9376 
9377 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9378 					mutex_exit(&ill->ill_lock);
9379 					mutex_exit(&connp->conn_lock);
9380 					ill_refrele(ill);
9381 					ill = NULL;
9382 					mutex_enter(&connp->conn_lock);
9383 				} else {
9384 					connp->conn_multicast_ipif = ipif;
9385 				}
9386 			}
9387 			break;
9388 		}
9389 	} else {
9390 		switch (option) {
9391 		case IPV6_BOUND_IF:
9392 			connp->conn_incoming_ill = ill;
9393 			connp->conn_outgoing_ill = ill;
9394 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9395 			    0 : ifindex;
9396 			break;
9397 
9398 		case IPV6_BOUND_PIF:
9399 			/*
9400 			 * Limit all transmit to this ill.
9401 			 * Unlike IPV6_BOUND_IF, using this option
9402 			 * prevents load spreading and failover from
9403 			 * happening when the interface is part of the
9404 			 * group. That's why we don't need to remember
9405 			 * the ifindex in orig_bound_ifindex as in
9406 			 * IPV6_BOUND_IF.
9407 			 */
9408 			connp->conn_outgoing_pill = ill;
9409 			break;
9410 
9411 		case IPV6_DONTFAILOVER_IF:
9412 			/*
9413 			 * This option is used by in.mpathd to ensure
9414 			 * that IPMP probe packets only go out on the
9415 			 * test interfaces. in.mpathd sets this option
9416 			 * on the non-failover interfaces.
9417 			 */
9418 			connp->conn_nofailover_ill = ill;
9419 			/*
9420 			 * For backward compatibility, this option
9421 			 * implicitly sets ip_multicast_ill as used in
9422 			 * IP_MULTICAST_IF so that ip_wput gets
9423 			 * this ipif to send mcast packets.
9424 			 */
9425 			connp->conn_multicast_ill = ill;
9426 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9427 			    0 : ifindex;
9428 			break;
9429 
9430 		case IPV6_MULTICAST_IF:
9431 			/*
9432 			 * Set conn_multicast_ill to be the IPv6 ill.
9433 			 * Set conn_multicast_ipif to be an IPv4 ipif
9434 			 * for ifindex to make IPv4 mapped addresses
9435 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9436 			 * Even if no IPv6 ill exists for the ifindex
9437 			 * we need to check for an IPv4 ifindex in order
9438 			 * for this to work with mapped addresses. In that
9439 			 * case only set conn_multicast_ipif.
9440 			 */
9441 			if (!checkonly) {
9442 				if (ifindex == 0) {
9443 					connp->conn_multicast_ill = NULL;
9444 					connp->conn_orig_multicast_ifindex = 0;
9445 					connp->conn_multicast_ipif = NULL;
9446 				} else if (ill != NULL) {
9447 					connp->conn_multicast_ill = ill;
9448 					connp->conn_orig_multicast_ifindex =
9449 					    ifindex;
9450 				}
9451 			}
9452 			break;
9453 		}
9454 	}
9455 
9456 	if (ill != NULL) {
9457 		mutex_exit(&ill->ill_lock);
9458 		mutex_exit(&connp->conn_lock);
9459 		ill_refrele(ill);
9460 		return (0);
9461 	}
9462 	mutex_exit(&connp->conn_lock);
9463 	/*
9464 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9465 	 * locate the ill and could not set the option (ifindex != 0)
9466 	 */
9467 	return (ifindex == 0 ? 0 : EINVAL);
9468 }
9469 
9470 /* This routine sets socket options. */
9471 /* ARGSUSED */
9472 int
9473 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9474     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9475     void *dummy, cred_t *cr, mblk_t *first_mp)
9476 {
9477 	int		*i1 = (int *)invalp;
9478 	conn_t		*connp = Q_TO_CONN(q);
9479 	int		error = 0;
9480 	boolean_t	checkonly;
9481 	ire_t		*ire;
9482 	boolean_t	found;
9483 
9484 	switch (optset_context) {
9485 
9486 	case SETFN_OPTCOM_CHECKONLY:
9487 		checkonly = B_TRUE;
9488 		/*
9489 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9490 		 * inlen != 0 implies value supplied and
9491 		 * 	we have to "pretend" to set it.
9492 		 * inlen == 0 implies that there is no
9493 		 * 	value part in T_CHECK request and just validation
9494 		 * done elsewhere should be enough, we just return here.
9495 		 */
9496 		if (inlen == 0) {
9497 			*outlenp = 0;
9498 			return (0);
9499 		}
9500 		break;
9501 	case SETFN_OPTCOM_NEGOTIATE:
9502 	case SETFN_UD_NEGOTIATE:
9503 	case SETFN_CONN_NEGOTIATE:
9504 		checkonly = B_FALSE;
9505 		break;
9506 	default:
9507 		/*
9508 		 * We should never get here
9509 		 */
9510 		*outlenp = 0;
9511 		return (EINVAL);
9512 	}
9513 
9514 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9515 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9516 
9517 	/*
9518 	 * For fixed length options, no sanity check
9519 	 * of passed in length is done. It is assumed *_optcom_req()
9520 	 * routines do the right thing.
9521 	 */
9522 
9523 	switch (level) {
9524 	case SOL_SOCKET:
9525 		/*
9526 		 * conn_lock protects the bitfields, and is used to
9527 		 * set the fields atomically.
9528 		 */
9529 		switch (name) {
9530 		case SO_BROADCAST:
9531 			if (!checkonly) {
9532 				/* TODO: use value someplace? */
9533 				mutex_enter(&connp->conn_lock);
9534 				connp->conn_broadcast = *i1 ? 1 : 0;
9535 				mutex_exit(&connp->conn_lock);
9536 			}
9537 			break;	/* goto sizeof (int) option return */
9538 		case SO_USELOOPBACK:
9539 			if (!checkonly) {
9540 				/* TODO: use value someplace? */
9541 				mutex_enter(&connp->conn_lock);
9542 				connp->conn_loopback = *i1 ? 1 : 0;
9543 				mutex_exit(&connp->conn_lock);
9544 			}
9545 			break;	/* goto sizeof (int) option return */
9546 		case SO_DONTROUTE:
9547 			if (!checkonly) {
9548 				mutex_enter(&connp->conn_lock);
9549 				connp->conn_dontroute = *i1 ? 1 : 0;
9550 				mutex_exit(&connp->conn_lock);
9551 			}
9552 			break;	/* goto sizeof (int) option return */
9553 		case SO_REUSEADDR:
9554 			if (!checkonly) {
9555 				mutex_enter(&connp->conn_lock);
9556 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9557 				mutex_exit(&connp->conn_lock);
9558 			}
9559 			break;	/* goto sizeof (int) option return */
9560 		case SO_PROTOTYPE:
9561 			if (!checkonly) {
9562 				mutex_enter(&connp->conn_lock);
9563 				connp->conn_proto = *i1;
9564 				mutex_exit(&connp->conn_lock);
9565 			}
9566 			break;	/* goto sizeof (int) option return */
9567 		default:
9568 			/*
9569 			 * "soft" error (negative)
9570 			 * option not handled at this level
9571 			 * Note: Do not modify *outlenp
9572 			 */
9573 			return (-EINVAL);
9574 		}
9575 		break;
9576 	case IPPROTO_IP:
9577 		switch (name) {
9578 		case IP_NEXTHOP:
9579 		case IP_MULTICAST_IF:
9580 		case IP_DONTFAILOVER_IF: {
9581 			ipaddr_t addr = *i1;
9582 
9583 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9584 			    first_mp);
9585 			if (error != 0)
9586 				return (error);
9587 			break;	/* goto sizeof (int) option return */
9588 		}
9589 
9590 		case IP_MULTICAST_TTL:
9591 			/* Recorded in transport above IP */
9592 			*outvalp = *invalp;
9593 			*outlenp = sizeof (uchar_t);
9594 			return (0);
9595 		case IP_MULTICAST_LOOP:
9596 			if (!checkonly) {
9597 				mutex_enter(&connp->conn_lock);
9598 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9599 				mutex_exit(&connp->conn_lock);
9600 			}
9601 			*outvalp = *invalp;
9602 			*outlenp = sizeof (uchar_t);
9603 			return (0);
9604 		case IP_ADD_MEMBERSHIP:
9605 		case MCAST_JOIN_GROUP:
9606 		case IP_DROP_MEMBERSHIP:
9607 		case MCAST_LEAVE_GROUP: {
9608 			struct ip_mreq *mreqp;
9609 			struct group_req *greqp;
9610 			ire_t *ire;
9611 			boolean_t done = B_FALSE;
9612 			ipaddr_t group, ifaddr;
9613 			struct sockaddr_in *sin;
9614 			uint32_t *ifindexp;
9615 			boolean_t mcast_opt = B_TRUE;
9616 			mcast_record_t fmode;
9617 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9618 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9619 
9620 			switch (name) {
9621 			case IP_ADD_MEMBERSHIP:
9622 				mcast_opt = B_FALSE;
9623 				/* FALLTHRU */
9624 			case MCAST_JOIN_GROUP:
9625 				fmode = MODE_IS_EXCLUDE;
9626 				optfn = ip_opt_add_group;
9627 				break;
9628 
9629 			case IP_DROP_MEMBERSHIP:
9630 				mcast_opt = B_FALSE;
9631 				/* FALLTHRU */
9632 			case MCAST_LEAVE_GROUP:
9633 				fmode = MODE_IS_INCLUDE;
9634 				optfn = ip_opt_delete_group;
9635 				break;
9636 			}
9637 
9638 			if (mcast_opt) {
9639 				greqp = (struct group_req *)i1;
9640 				sin = (struct sockaddr_in *)&greqp->gr_group;
9641 				if (sin->sin_family != AF_INET) {
9642 					*outlenp = 0;
9643 					return (ENOPROTOOPT);
9644 				}
9645 				group = (ipaddr_t)sin->sin_addr.s_addr;
9646 				ifaddr = INADDR_ANY;
9647 				ifindexp = &greqp->gr_interface;
9648 			} else {
9649 				mreqp = (struct ip_mreq *)i1;
9650 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9651 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9652 				ifindexp = NULL;
9653 			}
9654 
9655 			/*
9656 			 * In the multirouting case, we need to replicate
9657 			 * the request on all interfaces that will take part
9658 			 * in replication.  We do so because multirouting is
9659 			 * reflective, thus we will probably receive multi-
9660 			 * casts on those interfaces.
9661 			 * The ip_multirt_apply_membership() succeeds if the
9662 			 * operation succeeds on at least one interface.
9663 			 */
9664 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9665 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9666 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9667 			if (ire != NULL) {
9668 				if (ire->ire_flags & RTF_MULTIRT) {
9669 					error = ip_multirt_apply_membership(
9670 					    optfn, ire, connp, checkonly, group,
9671 					    fmode, INADDR_ANY, first_mp);
9672 					done = B_TRUE;
9673 				}
9674 				ire_refrele(ire);
9675 			}
9676 			if (!done) {
9677 				error = optfn(connp, checkonly, group, ifaddr,
9678 				    ifindexp, fmode, INADDR_ANY, first_mp);
9679 			}
9680 			if (error) {
9681 				/*
9682 				 * EINPROGRESS is a soft error, needs retry
9683 				 * so don't make *outlenp zero.
9684 				 */
9685 				if (error != EINPROGRESS)
9686 					*outlenp = 0;
9687 				return (error);
9688 			}
9689 			/* OK return - copy input buffer into output buffer */
9690 			if (invalp != outvalp) {
9691 				/* don't trust bcopy for identical src/dst */
9692 				bcopy(invalp, outvalp, inlen);
9693 			}
9694 			*outlenp = inlen;
9695 			return (0);
9696 		}
9697 		case IP_BLOCK_SOURCE:
9698 		case IP_UNBLOCK_SOURCE:
9699 		case IP_ADD_SOURCE_MEMBERSHIP:
9700 		case IP_DROP_SOURCE_MEMBERSHIP:
9701 		case MCAST_BLOCK_SOURCE:
9702 		case MCAST_UNBLOCK_SOURCE:
9703 		case MCAST_JOIN_SOURCE_GROUP:
9704 		case MCAST_LEAVE_SOURCE_GROUP: {
9705 			struct ip_mreq_source *imreqp;
9706 			struct group_source_req *gsreqp;
9707 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9708 			uint32_t ifindex = 0;
9709 			mcast_record_t fmode;
9710 			struct sockaddr_in *sin;
9711 			ire_t *ire;
9712 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9713 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9714 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9715 
9716 			switch (name) {
9717 			case IP_BLOCK_SOURCE:
9718 				mcast_opt = B_FALSE;
9719 				/* FALLTHRU */
9720 			case MCAST_BLOCK_SOURCE:
9721 				fmode = MODE_IS_EXCLUDE;
9722 				optfn = ip_opt_add_group;
9723 				break;
9724 
9725 			case IP_UNBLOCK_SOURCE:
9726 				mcast_opt = B_FALSE;
9727 				/* FALLTHRU */
9728 			case MCAST_UNBLOCK_SOURCE:
9729 				fmode = MODE_IS_EXCLUDE;
9730 				optfn = ip_opt_delete_group;
9731 				break;
9732 
9733 			case IP_ADD_SOURCE_MEMBERSHIP:
9734 				mcast_opt = B_FALSE;
9735 				/* FALLTHRU */
9736 			case MCAST_JOIN_SOURCE_GROUP:
9737 				fmode = MODE_IS_INCLUDE;
9738 				optfn = ip_opt_add_group;
9739 				break;
9740 
9741 			case IP_DROP_SOURCE_MEMBERSHIP:
9742 				mcast_opt = B_FALSE;
9743 				/* FALLTHRU */
9744 			case MCAST_LEAVE_SOURCE_GROUP:
9745 				fmode = MODE_IS_INCLUDE;
9746 				optfn = ip_opt_delete_group;
9747 				break;
9748 			}
9749 
9750 			if (mcast_opt) {
9751 				gsreqp = (struct group_source_req *)i1;
9752 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9753 					*outlenp = 0;
9754 					return (ENOPROTOOPT);
9755 				}
9756 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9757 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9758 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9759 				src = (ipaddr_t)sin->sin_addr.s_addr;
9760 				ifindex = gsreqp->gsr_interface;
9761 			} else {
9762 				imreqp = (struct ip_mreq_source *)i1;
9763 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9764 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9765 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9766 			}
9767 
9768 			/*
9769 			 * In the multirouting case, we need to replicate
9770 			 * the request as noted in the mcast cases above.
9771 			 */
9772 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9773 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9774 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9775 			if (ire != NULL) {
9776 				if (ire->ire_flags & RTF_MULTIRT) {
9777 					error = ip_multirt_apply_membership(
9778 					    optfn, ire, connp, checkonly, grp,
9779 					    fmode, src, first_mp);
9780 					done = B_TRUE;
9781 				}
9782 				ire_refrele(ire);
9783 			}
9784 			if (!done) {
9785 				error = optfn(connp, checkonly, grp, ifaddr,
9786 				    &ifindex, fmode, src, first_mp);
9787 			}
9788 			if (error != 0) {
9789 				/*
9790 				 * EINPROGRESS is a soft error, needs retry
9791 				 * so don't make *outlenp zero.
9792 				 */
9793 				if (error != EINPROGRESS)
9794 					*outlenp = 0;
9795 				return (error);
9796 			}
9797 			/* OK return - copy input buffer into output buffer */
9798 			if (invalp != outvalp) {
9799 				bcopy(invalp, outvalp, inlen);
9800 			}
9801 			*outlenp = inlen;
9802 			return (0);
9803 		}
9804 		case IP_SEC_OPT:
9805 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9806 			if (error != 0) {
9807 				*outlenp = 0;
9808 				return (error);
9809 			}
9810 			break;
9811 		case IP_HDRINCL:
9812 		case IP_OPTIONS:
9813 		case T_IP_OPTIONS:
9814 		case IP_TOS:
9815 		case T_IP_TOS:
9816 		case IP_TTL:
9817 		case IP_RECVDSTADDR:
9818 		case IP_RECVOPTS:
9819 			/* OK return - copy input buffer into output buffer */
9820 			if (invalp != outvalp) {
9821 				/* don't trust bcopy for identical src/dst */
9822 				bcopy(invalp, outvalp, inlen);
9823 			}
9824 			*outlenp = inlen;
9825 			return (0);
9826 		case IP_RECVIF:
9827 			/* Retrieve the inbound interface index */
9828 			if (!checkonly) {
9829 				mutex_enter(&connp->conn_lock);
9830 				connp->conn_recvif = *i1 ? 1 : 0;
9831 				mutex_exit(&connp->conn_lock);
9832 			}
9833 			break;	/* goto sizeof (int) option return */
9834 		case IP_RECVSLLA:
9835 			/* Retrieve the source link layer address */
9836 			if (!checkonly) {
9837 				mutex_enter(&connp->conn_lock);
9838 				connp->conn_recvslla = *i1 ? 1 : 0;
9839 				mutex_exit(&connp->conn_lock);
9840 			}
9841 			break;	/* goto sizeof (int) option return */
9842 		case MRT_INIT:
9843 		case MRT_DONE:
9844 		case MRT_ADD_VIF:
9845 		case MRT_DEL_VIF:
9846 		case MRT_ADD_MFC:
9847 		case MRT_DEL_MFC:
9848 		case MRT_ASSERT:
9849 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9850 				*outlenp = 0;
9851 				return (error);
9852 			}
9853 			error = ip_mrouter_set((int)name, q, checkonly,
9854 			    (uchar_t *)invalp, inlen, first_mp);
9855 			if (error) {
9856 				*outlenp = 0;
9857 				return (error);
9858 			}
9859 			/* OK return - copy input buffer into output buffer */
9860 			if (invalp != outvalp) {
9861 				/* don't trust bcopy for identical src/dst */
9862 				bcopy(invalp, outvalp, inlen);
9863 			}
9864 			*outlenp = inlen;
9865 			return (0);
9866 		case IP_BOUND_IF:
9867 		case IP_XMIT_IF:
9868 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9869 			    level, name, first_mp);
9870 			if (error != 0)
9871 				return (error);
9872 			break; 		/* goto sizeof (int) option return */
9873 
9874 		case IP_UNSPEC_SRC:
9875 			/* Allow sending with a zero source address */
9876 			if (!checkonly) {
9877 				mutex_enter(&connp->conn_lock);
9878 				connp->conn_unspec_src = *i1 ? 1 : 0;
9879 				mutex_exit(&connp->conn_lock);
9880 			}
9881 			break;	/* goto sizeof (int) option return */
9882 		default:
9883 			/*
9884 			 * "soft" error (negative)
9885 			 * option not handled at this level
9886 			 * Note: Do not modify *outlenp
9887 			 */
9888 			return (-EINVAL);
9889 		}
9890 		break;
9891 	case IPPROTO_IPV6:
9892 		switch (name) {
9893 		case IPV6_BOUND_IF:
9894 		case IPV6_BOUND_PIF:
9895 		case IPV6_DONTFAILOVER_IF:
9896 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9897 			    level, name, first_mp);
9898 			if (error != 0)
9899 				return (error);
9900 			break; 		/* goto sizeof (int) option return */
9901 
9902 		case IPV6_MULTICAST_IF:
9903 			/*
9904 			 * The only possible errors are EINPROGRESS and
9905 			 * EINVAL. EINPROGRESS will be restarted and is not
9906 			 * a hard error. We call this option on both V4 and V6
9907 			 * If both return EINVAL, then this call returns
9908 			 * EINVAL. If at least one of them succeeds we
9909 			 * return success.
9910 			 */
9911 			found = B_FALSE;
9912 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9913 			    level, name, first_mp);
9914 			if (error == EINPROGRESS)
9915 				return (error);
9916 			if (error == 0)
9917 				found = B_TRUE;
9918 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9919 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9920 			if (error == 0)
9921 				found = B_TRUE;
9922 			if (!found)
9923 				return (error);
9924 			break; 		/* goto sizeof (int) option return */
9925 
9926 		case IPV6_MULTICAST_HOPS:
9927 			/* Recorded in transport above IP */
9928 			break;	/* goto sizeof (int) option return */
9929 		case IPV6_MULTICAST_LOOP:
9930 			if (!checkonly) {
9931 				mutex_enter(&connp->conn_lock);
9932 				connp->conn_multicast_loop = *i1;
9933 				mutex_exit(&connp->conn_lock);
9934 			}
9935 			break;	/* goto sizeof (int) option return */
9936 		case IPV6_JOIN_GROUP:
9937 		case MCAST_JOIN_GROUP:
9938 		case IPV6_LEAVE_GROUP:
9939 		case MCAST_LEAVE_GROUP: {
9940 			struct ipv6_mreq *ip_mreqp;
9941 			struct group_req *greqp;
9942 			ire_t *ire;
9943 			boolean_t done = B_FALSE;
9944 			in6_addr_t groupv6;
9945 			uint32_t ifindex;
9946 			boolean_t mcast_opt = B_TRUE;
9947 			mcast_record_t fmode;
9948 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9949 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9950 
9951 			switch (name) {
9952 			case IPV6_JOIN_GROUP:
9953 				mcast_opt = B_FALSE;
9954 				/* FALLTHRU */
9955 			case MCAST_JOIN_GROUP:
9956 				fmode = MODE_IS_EXCLUDE;
9957 				optfn = ip_opt_add_group_v6;
9958 				break;
9959 
9960 			case IPV6_LEAVE_GROUP:
9961 				mcast_opt = B_FALSE;
9962 				/* FALLTHRU */
9963 			case MCAST_LEAVE_GROUP:
9964 				fmode = MODE_IS_INCLUDE;
9965 				optfn = ip_opt_delete_group_v6;
9966 				break;
9967 			}
9968 
9969 			if (mcast_opt) {
9970 				struct sockaddr_in *sin;
9971 				struct sockaddr_in6 *sin6;
9972 				greqp = (struct group_req *)i1;
9973 				if (greqp->gr_group.ss_family == AF_INET) {
9974 					sin = (struct sockaddr_in *)
9975 					    &(greqp->gr_group);
9976 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9977 					    &groupv6);
9978 				} else {
9979 					sin6 = (struct sockaddr_in6 *)
9980 					    &(greqp->gr_group);
9981 					groupv6 = sin6->sin6_addr;
9982 				}
9983 				ifindex = greqp->gr_interface;
9984 			} else {
9985 				ip_mreqp = (struct ipv6_mreq *)i1;
9986 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9987 				ifindex = ip_mreqp->ipv6mr_interface;
9988 			}
9989 			/*
9990 			 * In the multirouting case, we need to replicate
9991 			 * the request on all interfaces that will take part
9992 			 * in replication.  We do so because multirouting is
9993 			 * reflective, thus we will probably receive multi-
9994 			 * casts on those interfaces.
9995 			 * The ip_multirt_apply_membership_v6() succeeds if
9996 			 * the operation succeeds on at least one interface.
9997 			 */
9998 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9999 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10000 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10001 			if (ire != NULL) {
10002 				if (ire->ire_flags & RTF_MULTIRT) {
10003 					error = ip_multirt_apply_membership_v6(
10004 					    optfn, ire, connp, checkonly,
10005 					    &groupv6, fmode, &ipv6_all_zeros,
10006 					    first_mp);
10007 					done = B_TRUE;
10008 				}
10009 				ire_refrele(ire);
10010 			}
10011 			if (!done) {
10012 				error = optfn(connp, checkonly, &groupv6,
10013 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10014 			}
10015 			if (error) {
10016 				/*
10017 				 * EINPROGRESS is a soft error, needs retry
10018 				 * so don't make *outlenp zero.
10019 				 */
10020 				if (error != EINPROGRESS)
10021 					*outlenp = 0;
10022 				return (error);
10023 			}
10024 			/* OK return - copy input buffer into output buffer */
10025 			if (invalp != outvalp) {
10026 				/* don't trust bcopy for identical src/dst */
10027 				bcopy(invalp, outvalp, inlen);
10028 			}
10029 			*outlenp = inlen;
10030 			return (0);
10031 		}
10032 		case MCAST_BLOCK_SOURCE:
10033 		case MCAST_UNBLOCK_SOURCE:
10034 		case MCAST_JOIN_SOURCE_GROUP:
10035 		case MCAST_LEAVE_SOURCE_GROUP: {
10036 			struct group_source_req *gsreqp;
10037 			in6_addr_t v6grp, v6src;
10038 			uint32_t ifindex;
10039 			mcast_record_t fmode;
10040 			ire_t *ire;
10041 			boolean_t done = B_FALSE;
10042 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10043 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10044 
10045 			switch (name) {
10046 			case MCAST_BLOCK_SOURCE:
10047 				fmode = MODE_IS_EXCLUDE;
10048 				optfn = ip_opt_add_group_v6;
10049 				break;
10050 			case MCAST_UNBLOCK_SOURCE:
10051 				fmode = MODE_IS_EXCLUDE;
10052 				optfn = ip_opt_delete_group_v6;
10053 				break;
10054 			case MCAST_JOIN_SOURCE_GROUP:
10055 				fmode = MODE_IS_INCLUDE;
10056 				optfn = ip_opt_add_group_v6;
10057 				break;
10058 			case MCAST_LEAVE_SOURCE_GROUP:
10059 				fmode = MODE_IS_INCLUDE;
10060 				optfn = ip_opt_delete_group_v6;
10061 				break;
10062 			}
10063 
10064 			gsreqp = (struct group_source_req *)i1;
10065 			ifindex = gsreqp->gsr_interface;
10066 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10067 				struct sockaddr_in *s;
10068 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10069 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10070 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10071 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10072 			} else {
10073 				struct sockaddr_in6 *s6;
10074 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10075 				v6grp = s6->sin6_addr;
10076 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10077 				v6src = s6->sin6_addr;
10078 			}
10079 
10080 			/*
10081 			 * In the multirouting case, we need to replicate
10082 			 * the request as noted in the mcast cases above.
10083 			 */
10084 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10085 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10086 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10087 			if (ire != NULL) {
10088 				if (ire->ire_flags & RTF_MULTIRT) {
10089 					error = ip_multirt_apply_membership_v6(
10090 					    optfn, ire, connp, checkonly,
10091 					    &v6grp, fmode, &v6src, first_mp);
10092 					done = B_TRUE;
10093 				}
10094 				ire_refrele(ire);
10095 			}
10096 			if (!done) {
10097 				error = optfn(connp, checkonly, &v6grp,
10098 				    ifindex, fmode, &v6src, first_mp);
10099 			}
10100 			if (error != 0) {
10101 				/*
10102 				 * EINPROGRESS is a soft error, needs retry
10103 				 * so don't make *outlenp zero.
10104 				 */
10105 				if (error != EINPROGRESS)
10106 					*outlenp = 0;
10107 				return (error);
10108 			}
10109 			/* OK return - copy input buffer into output buffer */
10110 			if (invalp != outvalp) {
10111 				bcopy(invalp, outvalp, inlen);
10112 			}
10113 			*outlenp = inlen;
10114 			return (0);
10115 		}
10116 		case IPV6_UNICAST_HOPS:
10117 			/* Recorded in transport above IP */
10118 			break;	/* goto sizeof (int) option return */
10119 		case IPV6_UNSPEC_SRC:
10120 			/* Allow sending with a zero source address */
10121 			if (!checkonly) {
10122 				mutex_enter(&connp->conn_lock);
10123 				connp->conn_unspec_src = *i1 ? 1 : 0;
10124 				mutex_exit(&connp->conn_lock);
10125 			}
10126 			break;	/* goto sizeof (int) option return */
10127 		case IPV6_RECVPKTINFO:
10128 			if (!checkonly) {
10129 				mutex_enter(&connp->conn_lock);
10130 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10131 				mutex_exit(&connp->conn_lock);
10132 			}
10133 			break;	/* goto sizeof (int) option return */
10134 		case IPV6_RECVTCLASS:
10135 			if (!checkonly) {
10136 				if (*i1 < 0 || *i1 > 1) {
10137 					return (EINVAL);
10138 				}
10139 				mutex_enter(&connp->conn_lock);
10140 				connp->conn_ipv6_recvtclass = *i1;
10141 				mutex_exit(&connp->conn_lock);
10142 			}
10143 			break;
10144 		case IPV6_RECVPATHMTU:
10145 			if (!checkonly) {
10146 				if (*i1 < 0 || *i1 > 1) {
10147 					return (EINVAL);
10148 				}
10149 				mutex_enter(&connp->conn_lock);
10150 				connp->conn_ipv6_recvpathmtu = *i1;
10151 				mutex_exit(&connp->conn_lock);
10152 			}
10153 			break;
10154 		case IPV6_RECVHOPLIMIT:
10155 			if (!checkonly) {
10156 				mutex_enter(&connp->conn_lock);
10157 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10158 				mutex_exit(&connp->conn_lock);
10159 			}
10160 			break;	/* goto sizeof (int) option return */
10161 		case IPV6_RECVHOPOPTS:
10162 			if (!checkonly) {
10163 				mutex_enter(&connp->conn_lock);
10164 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10165 				mutex_exit(&connp->conn_lock);
10166 			}
10167 			break;	/* goto sizeof (int) option return */
10168 		case IPV6_RECVDSTOPTS:
10169 			if (!checkonly) {
10170 				mutex_enter(&connp->conn_lock);
10171 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10172 				mutex_exit(&connp->conn_lock);
10173 			}
10174 			break;	/* goto sizeof (int) option return */
10175 		case IPV6_RECVRTHDR:
10176 			if (!checkonly) {
10177 				mutex_enter(&connp->conn_lock);
10178 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10179 				mutex_exit(&connp->conn_lock);
10180 			}
10181 			break;	/* goto sizeof (int) option return */
10182 		case IPV6_RECVRTHDRDSTOPTS:
10183 			if (!checkonly) {
10184 				mutex_enter(&connp->conn_lock);
10185 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10186 				mutex_exit(&connp->conn_lock);
10187 			}
10188 			break;	/* goto sizeof (int) option return */
10189 		case IPV6_PKTINFO:
10190 			if (inlen == 0)
10191 				return (-EINVAL);	/* clearing option */
10192 			error = ip6_set_pktinfo(cr, connp,
10193 			    (struct in6_pktinfo *)invalp, first_mp);
10194 			if (error != 0)
10195 				*outlenp = 0;
10196 			else
10197 				*outlenp = inlen;
10198 			return (error);
10199 		case IPV6_NEXTHOP: {
10200 			struct sockaddr_in6 *sin6;
10201 
10202 			/* Verify that the nexthop is reachable */
10203 			if (inlen == 0)
10204 				return (-EINVAL);	/* clearing option */
10205 
10206 			sin6 = (struct sockaddr_in6 *)invalp;
10207 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10208 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10209 			    MATCH_IRE_DEFAULT);
10210 
10211 			if (ire == NULL) {
10212 				*outlenp = 0;
10213 				return (EHOSTUNREACH);
10214 			}
10215 			ire_refrele(ire);
10216 			return (-EINVAL);
10217 		}
10218 		case IPV6_SEC_OPT:
10219 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10220 			if (error != 0) {
10221 				*outlenp = 0;
10222 				return (error);
10223 			}
10224 			break;
10225 		case IPV6_SRC_PREFERENCES: {
10226 			/*
10227 			 * This is implemented strictly in the ip module
10228 			 * (here and in tcp_opt_*() to accomodate tcp
10229 			 * sockets).  Modules above ip pass this option
10230 			 * down here since ip is the only one that needs to
10231 			 * be aware of source address preferences.
10232 			 *
10233 			 * This socket option only affects connected
10234 			 * sockets that haven't already bound to a specific
10235 			 * IPv6 address.  In other words, sockets that
10236 			 * don't call bind() with an address other than the
10237 			 * unspecified address and that call connect().
10238 			 * ip_bind_connected_v6() passes these preferences
10239 			 * to the ipif_select_source_v6() function.
10240 			 */
10241 			if (inlen != sizeof (uint32_t))
10242 				return (EINVAL);
10243 			error = ip6_set_src_preferences(connp,
10244 			    *(uint32_t *)invalp);
10245 			if (error != 0) {
10246 				*outlenp = 0;
10247 				return (error);
10248 			} else {
10249 				*outlenp = sizeof (uint32_t);
10250 			}
10251 			break;
10252 		}
10253 		case IPV6_V6ONLY:
10254 			if (*i1 < 0 || *i1 > 1) {
10255 				return (EINVAL);
10256 			}
10257 			mutex_enter(&connp->conn_lock);
10258 			connp->conn_ipv6_v6only = *i1;
10259 			mutex_exit(&connp->conn_lock);
10260 			break;
10261 		default:
10262 			return (-EINVAL);
10263 		}
10264 		break;
10265 	default:
10266 		/*
10267 		 * "soft" error (negative)
10268 		 * option not handled at this level
10269 		 * Note: Do not modify *outlenp
10270 		 */
10271 		return (-EINVAL);
10272 	}
10273 	/*
10274 	 * Common case of return from an option that is sizeof (int)
10275 	 */
10276 	*(int *)outvalp = *i1;
10277 	*outlenp = sizeof (int);
10278 	return (0);
10279 }
10280 
10281 /*
10282  * This routine gets default values of certain options whose default
10283  * values are maintained by protocol specific code
10284  */
10285 /* ARGSUSED */
10286 int
10287 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10288 {
10289 	int *i1 = (int *)ptr;
10290 
10291 	switch (level) {
10292 	case IPPROTO_IP:
10293 		switch (name) {
10294 		case IP_MULTICAST_TTL:
10295 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10296 			return (sizeof (uchar_t));
10297 		case IP_MULTICAST_LOOP:
10298 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10299 			return (sizeof (uchar_t));
10300 		default:
10301 			return (-1);
10302 		}
10303 	case IPPROTO_IPV6:
10304 		switch (name) {
10305 		case IPV6_UNICAST_HOPS:
10306 			*i1 = ipv6_def_hops;
10307 			return (sizeof (int));
10308 		case IPV6_MULTICAST_HOPS:
10309 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10310 			return (sizeof (int));
10311 		case IPV6_MULTICAST_LOOP:
10312 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10313 			return (sizeof (int));
10314 		case IPV6_V6ONLY:
10315 			*i1 = 1;
10316 			return (sizeof (int));
10317 		default:
10318 			return (-1);
10319 		}
10320 	default:
10321 		return (-1);
10322 	}
10323 	/* NOTREACHED */
10324 }
10325 
10326 /*
10327  * Given a destination address and a pointer to where to put the information
10328  * this routine fills in the mtuinfo.
10329  */
10330 int
10331 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10332     struct ip6_mtuinfo *mtuinfo)
10333 {
10334 	ire_t *ire;
10335 
10336 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10337 		return (-1);
10338 
10339 	bzero(mtuinfo, sizeof (*mtuinfo));
10340 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10341 	mtuinfo->ip6m_addr.sin6_port = port;
10342 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10343 
10344 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10345 	if (ire != NULL) {
10346 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10347 		ire_refrele(ire);
10348 	} else {
10349 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10350 	}
10351 	return (sizeof (struct ip6_mtuinfo));
10352 }
10353 
10354 /*
10355  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10356  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10357  * isn't.  This doesn't matter as the error checking is done properly for the
10358  * other MRT options coming in through ip_opt_set.
10359  */
10360 int
10361 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10362 {
10363 	conn_t		*connp = Q_TO_CONN(q);
10364 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10365 
10366 	switch (level) {
10367 	case IPPROTO_IP:
10368 		switch (name) {
10369 		case MRT_VERSION:
10370 		case MRT_ASSERT:
10371 			(void) ip_mrouter_get(name, q, ptr);
10372 			return (sizeof (int));
10373 		case IP_SEC_OPT:
10374 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10375 		case IP_NEXTHOP:
10376 			if (connp->conn_nexthop_set) {
10377 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10378 				return (sizeof (ipaddr_t));
10379 			} else
10380 				return (0);
10381 		default:
10382 			break;
10383 		}
10384 		break;
10385 	case IPPROTO_IPV6:
10386 		switch (name) {
10387 		case IPV6_SEC_OPT:
10388 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10389 		case IPV6_SRC_PREFERENCES: {
10390 			return (ip6_get_src_preferences(connp,
10391 			    (uint32_t *)ptr));
10392 		}
10393 		case IPV6_V6ONLY:
10394 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10395 			return (sizeof (int));
10396 		case IPV6_PATHMTU:
10397 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10398 				(struct ip6_mtuinfo *)ptr));
10399 		default:
10400 			break;
10401 		}
10402 		break;
10403 	default:
10404 		break;
10405 	}
10406 	return (-1);
10407 }
10408 
10409 /* Named Dispatch routine to get a current value out of our parameter table. */
10410 /* ARGSUSED */
10411 static int
10412 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10413 {
10414 	ipparam_t *ippa = (ipparam_t *)cp;
10415 
10416 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10417 	return (0);
10418 }
10419 
10420 /* ARGSUSED */
10421 static int
10422 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10423 {
10424 
10425 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10426 	return (0);
10427 }
10428 
10429 /*
10430  * Set ip{,6}_forwarding values.  This means walking through all of the
10431  * ill's and toggling their forwarding values.
10432  */
10433 /* ARGSUSED */
10434 static int
10435 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10436 {
10437 	long new_value;
10438 	int *forwarding_value = (int *)cp;
10439 	ill_t *walker;
10440 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10441 	ill_walk_context_t ctx;
10442 
10443 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10444 	    new_value < 0 || new_value > 1) {
10445 		return (EINVAL);
10446 	}
10447 
10448 	*forwarding_value = new_value;
10449 
10450 	/*
10451 	 * Regardless of the current value of ip_forwarding, set all per-ill
10452 	 * values of ip_forwarding to the value being set.
10453 	 *
10454 	 * Bring all the ill's up to date with the new global value.
10455 	 */
10456 	rw_enter(&ill_g_lock, RW_READER);
10457 
10458 	if (isv6)
10459 		walker = ILL_START_WALK_V6(&ctx);
10460 	else
10461 		walker = ILL_START_WALK_V4(&ctx);
10462 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10463 		(void) ill_forward_set(q, mp, (new_value != 0),
10464 		    (caddr_t)walker);
10465 	}
10466 	rw_exit(&ill_g_lock);
10467 
10468 	return (0);
10469 }
10470 
10471 /*
10472  * Walk through the param array specified registering each element with the
10473  * Named Dispatch handler. This is called only during init. So it is ok
10474  * not to acquire any locks
10475  */
10476 static boolean_t
10477 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10478     ipndp_t *ipnd, size_t ipnd_cnt)
10479 {
10480 	for (; ippa_cnt-- > 0; ippa++) {
10481 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10482 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10483 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10484 				nd_free(&ip_g_nd);
10485 				return (B_FALSE);
10486 			}
10487 		}
10488 	}
10489 
10490 	for (; ipnd_cnt-- > 0; ipnd++) {
10491 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10492 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10493 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10494 			    ipnd->ip_ndp_data)) {
10495 				nd_free(&ip_g_nd);
10496 				return (B_FALSE);
10497 			}
10498 		}
10499 	}
10500 
10501 	return (B_TRUE);
10502 }
10503 
10504 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10505 /* ARGSUSED */
10506 static int
10507 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10508 {
10509 	long		new_value;
10510 	ipparam_t	*ippa = (ipparam_t *)cp;
10511 
10512 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10513 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10514 		return (EINVAL);
10515 	}
10516 	ippa->ip_param_value = new_value;
10517 	return (0);
10518 }
10519 
10520 /*
10521  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10522  * When an ipf is passed here for the first time, if
10523  * we already have in-order fragments on the queue, we convert from the fast-
10524  * path reassembly scheme to the hard-case scheme.  From then on, additional
10525  * fragments are reassembled here.  We keep track of the start and end offsets
10526  * of each piece, and the number of holes in the chain.  When the hole count
10527  * goes to zero, we are done!
10528  *
10529  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10530  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10531  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10532  * after the call to ip_reassemble().
10533  */
10534 int
10535 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10536     size_t msg_len)
10537 {
10538 	uint_t	end;
10539 	mblk_t	*next_mp;
10540 	mblk_t	*mp1;
10541 	uint_t	offset;
10542 	boolean_t incr_dups = B_TRUE;
10543 	boolean_t offset_zero_seen = B_FALSE;
10544 	boolean_t pkt_boundary_checked = B_FALSE;
10545 
10546 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10547 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10548 
10549 	/* Add in byte count */
10550 	ipf->ipf_count += msg_len;
10551 	if (ipf->ipf_end) {
10552 		/*
10553 		 * We were part way through in-order reassembly, but now there
10554 		 * is a hole.  We walk through messages already queued, and
10555 		 * mark them for hard case reassembly.  We know that up till
10556 		 * now they were in order starting from offset zero.
10557 		 */
10558 		offset = 0;
10559 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10560 			IP_REASS_SET_START(mp1, offset);
10561 			if (offset == 0) {
10562 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10563 				offset = -ipf->ipf_nf_hdr_len;
10564 			}
10565 			offset += mp1->b_wptr - mp1->b_rptr;
10566 			IP_REASS_SET_END(mp1, offset);
10567 		}
10568 		/* One hole at the end. */
10569 		ipf->ipf_hole_cnt = 1;
10570 		/* Brand it as a hard case, forever. */
10571 		ipf->ipf_end = 0;
10572 	}
10573 	/* Walk through all the new pieces. */
10574 	do {
10575 		end = start + (mp->b_wptr - mp->b_rptr);
10576 		/*
10577 		 * If start is 0, decrease 'end' only for the first mblk of
10578 		 * the fragment. Otherwise 'end' can get wrong value in the
10579 		 * second pass of the loop if first mblk is exactly the
10580 		 * size of ipf_nf_hdr_len.
10581 		 */
10582 		if (start == 0 && !offset_zero_seen) {
10583 			/* First segment */
10584 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10585 			end -= ipf->ipf_nf_hdr_len;
10586 			offset_zero_seen = B_TRUE;
10587 		}
10588 		next_mp = mp->b_cont;
10589 		/*
10590 		 * We are checking to see if there is any interesing data
10591 		 * to process.  If there isn't and the mblk isn't the
10592 		 * one which carries the unfragmentable header then we
10593 		 * drop it.  It's possible to have just the unfragmentable
10594 		 * header come through without any data.  That needs to be
10595 		 * saved.
10596 		 *
10597 		 * If the assert at the top of this function holds then the
10598 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10599 		 * is infrequently traveled enough that the test is left in
10600 		 * to protect against future code changes which break that
10601 		 * invariant.
10602 		 */
10603 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10604 			/* Empty.  Blast it. */
10605 			IP_REASS_SET_START(mp, 0);
10606 			IP_REASS_SET_END(mp, 0);
10607 			/*
10608 			 * If the ipf points to the mblk we are about to free,
10609 			 * update ipf to point to the next mblk (or NULL
10610 			 * if none).
10611 			 */
10612 			if (ipf->ipf_mp->b_cont == mp)
10613 				ipf->ipf_mp->b_cont = next_mp;
10614 			freeb(mp);
10615 			continue;
10616 		}
10617 		mp->b_cont = NULL;
10618 		IP_REASS_SET_START(mp, start);
10619 		IP_REASS_SET_END(mp, end);
10620 		if (!ipf->ipf_tail_mp) {
10621 			ipf->ipf_tail_mp = mp;
10622 			ipf->ipf_mp->b_cont = mp;
10623 			if (start == 0 || !more) {
10624 				ipf->ipf_hole_cnt = 1;
10625 				/*
10626 				 * if the first fragment comes in more than one
10627 				 * mblk, this loop will be executed for each
10628 				 * mblk. Need to adjust hole count so exiting
10629 				 * this routine will leave hole count at 1.
10630 				 */
10631 				if (next_mp)
10632 					ipf->ipf_hole_cnt++;
10633 			} else
10634 				ipf->ipf_hole_cnt = 2;
10635 			continue;
10636 		} else if (ipf->ipf_last_frag_seen && !more &&
10637 			    !pkt_boundary_checked) {
10638 			/*
10639 			 * We check datagram boundary only if this fragment
10640 			 * claims to be the last fragment and we have seen a
10641 			 * last fragment in the past too. We do this only
10642 			 * once for a given fragment.
10643 			 *
10644 			 * start cannot be 0 here as fragments with start=0
10645 			 * and MF=0 gets handled as a complete packet. These
10646 			 * fragments should not reach here.
10647 			 */
10648 
10649 			if (start + msgdsize(mp) !=
10650 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10651 				/*
10652 				 * We have two fragments both of which claim
10653 				 * to be the last fragment but gives conflicting
10654 				 * information about the whole datagram size.
10655 				 * Something fishy is going on. Drop the
10656 				 * fragment and free up the reassembly list.
10657 				 */
10658 				return (IP_REASS_FAILED);
10659 			}
10660 
10661 			/*
10662 			 * We shouldn't come to this code block again for this
10663 			 * particular fragment.
10664 			 */
10665 			pkt_boundary_checked = B_TRUE;
10666 		}
10667 
10668 		/* New stuff at or beyond tail? */
10669 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10670 		if (start >= offset) {
10671 			if (ipf->ipf_last_frag_seen) {
10672 				/* current fragment is beyond last fragment */
10673 				return (IP_REASS_FAILED);
10674 			}
10675 			/* Link it on end. */
10676 			ipf->ipf_tail_mp->b_cont = mp;
10677 			ipf->ipf_tail_mp = mp;
10678 			if (more) {
10679 				if (start != offset)
10680 					ipf->ipf_hole_cnt++;
10681 			} else if (start == offset && next_mp == NULL)
10682 					ipf->ipf_hole_cnt--;
10683 			continue;
10684 		}
10685 		mp1 = ipf->ipf_mp->b_cont;
10686 		offset = IP_REASS_START(mp1);
10687 		/* New stuff at the front? */
10688 		if (start < offset) {
10689 			if (start == 0) {
10690 				if (end >= offset) {
10691 					/* Nailed the hole at the begining. */
10692 					ipf->ipf_hole_cnt--;
10693 				}
10694 			} else if (end < offset) {
10695 				/*
10696 				 * A hole, stuff, and a hole where there used
10697 				 * to be just a hole.
10698 				 */
10699 				ipf->ipf_hole_cnt++;
10700 			}
10701 			mp->b_cont = mp1;
10702 			/* Check for overlap. */
10703 			while (end > offset) {
10704 				if (end < IP_REASS_END(mp1)) {
10705 					mp->b_wptr -= end - offset;
10706 					IP_REASS_SET_END(mp, offset);
10707 					if (ill->ill_isv6) {
10708 						BUMP_MIB(ill->ill_ip6_mib,
10709 						    ipv6ReasmPartDups);
10710 					} else {
10711 						BUMP_MIB(&ip_mib,
10712 						    ipReasmPartDups);
10713 					}
10714 					break;
10715 				}
10716 				/* Did we cover another hole? */
10717 				if ((mp1->b_cont &&
10718 				    IP_REASS_END(mp1) !=
10719 				    IP_REASS_START(mp1->b_cont) &&
10720 				    end >= IP_REASS_START(mp1->b_cont)) ||
10721 				    (!ipf->ipf_last_frag_seen && !more)) {
10722 					ipf->ipf_hole_cnt--;
10723 				}
10724 				/* Clip out mp1. */
10725 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10726 					/*
10727 					 * After clipping out mp1, this guy
10728 					 * is now hanging off the end.
10729 					 */
10730 					ipf->ipf_tail_mp = mp;
10731 				}
10732 				IP_REASS_SET_START(mp1, 0);
10733 				IP_REASS_SET_END(mp1, 0);
10734 				/* Subtract byte count */
10735 				ipf->ipf_count -= mp1->b_datap->db_lim -
10736 				    mp1->b_datap->db_base;
10737 				freeb(mp1);
10738 				if (ill->ill_isv6) {
10739 					BUMP_MIB(ill->ill_ip6_mib,
10740 					    ipv6ReasmPartDups);
10741 				} else {
10742 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10743 				}
10744 				mp1 = mp->b_cont;
10745 				if (!mp1)
10746 					break;
10747 				offset = IP_REASS_START(mp1);
10748 			}
10749 			ipf->ipf_mp->b_cont = mp;
10750 			continue;
10751 		}
10752 		/*
10753 		 * The new piece starts somewhere between the start of the head
10754 		 * and before the end of the tail.
10755 		 */
10756 		for (; mp1; mp1 = mp1->b_cont) {
10757 			offset = IP_REASS_END(mp1);
10758 			if (start < offset) {
10759 				if (end <= offset) {
10760 					/* Nothing new. */
10761 					IP_REASS_SET_START(mp, 0);
10762 					IP_REASS_SET_END(mp, 0);
10763 					/* Subtract byte count */
10764 					ipf->ipf_count -= mp->b_datap->db_lim -
10765 					    mp->b_datap->db_base;
10766 					if (incr_dups) {
10767 						ipf->ipf_num_dups++;
10768 						incr_dups = B_FALSE;
10769 					}
10770 					freeb(mp);
10771 					if (ill->ill_isv6) {
10772 						BUMP_MIB(ill->ill_ip6_mib,
10773 						    ipv6ReasmDuplicates);
10774 					} else {
10775 						BUMP_MIB(&ip_mib,
10776 						    ipReasmDuplicates);
10777 					}
10778 					break;
10779 				}
10780 				/*
10781 				 * Trim redundant stuff off beginning of new
10782 				 * piece.
10783 				 */
10784 				IP_REASS_SET_START(mp, offset);
10785 				mp->b_rptr += offset - start;
10786 				if (ill->ill_isv6) {
10787 					BUMP_MIB(ill->ill_ip6_mib,
10788 					    ipv6ReasmPartDups);
10789 				} else {
10790 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10791 				}
10792 				start = offset;
10793 				if (!mp1->b_cont) {
10794 					/*
10795 					 * After trimming, this guy is now
10796 					 * hanging off the end.
10797 					 */
10798 					mp1->b_cont = mp;
10799 					ipf->ipf_tail_mp = mp;
10800 					if (!more) {
10801 						ipf->ipf_hole_cnt--;
10802 					}
10803 					break;
10804 				}
10805 			}
10806 			if (start >= IP_REASS_START(mp1->b_cont))
10807 				continue;
10808 			/* Fill a hole */
10809 			if (start > offset)
10810 				ipf->ipf_hole_cnt++;
10811 			mp->b_cont = mp1->b_cont;
10812 			mp1->b_cont = mp;
10813 			mp1 = mp->b_cont;
10814 			offset = IP_REASS_START(mp1);
10815 			if (end >= offset) {
10816 				ipf->ipf_hole_cnt--;
10817 				/* Check for overlap. */
10818 				while (end > offset) {
10819 					if (end < IP_REASS_END(mp1)) {
10820 						mp->b_wptr -= end - offset;
10821 						IP_REASS_SET_END(mp, offset);
10822 						/*
10823 						 * TODO we might bump
10824 						 * this up twice if there is
10825 						 * overlap at both ends.
10826 						 */
10827 						if (ill->ill_isv6) {
10828 							BUMP_MIB(
10829 							    ill->ill_ip6_mib,
10830 							    ipv6ReasmPartDups);
10831 						} else {
10832 							BUMP_MIB(&ip_mib,
10833 							    ipReasmPartDups);
10834 						}
10835 						break;
10836 					}
10837 					/* Did we cover another hole? */
10838 					if ((mp1->b_cont &&
10839 					    IP_REASS_END(mp1)
10840 					    != IP_REASS_START(mp1->b_cont) &&
10841 					    end >=
10842 					    IP_REASS_START(mp1->b_cont)) ||
10843 					    (!ipf->ipf_last_frag_seen &&
10844 					    !more)) {
10845 						ipf->ipf_hole_cnt--;
10846 					}
10847 					/* Clip out mp1. */
10848 					if ((mp->b_cont = mp1->b_cont) ==
10849 					    NULL) {
10850 						/*
10851 						 * After clipping out mp1,
10852 						 * this guy is now hanging
10853 						 * off the end.
10854 						 */
10855 						ipf->ipf_tail_mp = mp;
10856 					}
10857 					IP_REASS_SET_START(mp1, 0);
10858 					IP_REASS_SET_END(mp1, 0);
10859 					/* Subtract byte count */
10860 					ipf->ipf_count -=
10861 					    mp1->b_datap->db_lim -
10862 					    mp1->b_datap->db_base;
10863 					freeb(mp1);
10864 					if (ill->ill_isv6) {
10865 						BUMP_MIB(ill->ill_ip6_mib,
10866 						    ipv6ReasmPartDups);
10867 					} else {
10868 						BUMP_MIB(&ip_mib,
10869 						    ipReasmPartDups);
10870 					}
10871 					mp1 = mp->b_cont;
10872 					if (!mp1)
10873 						break;
10874 					offset = IP_REASS_START(mp1);
10875 				}
10876 			}
10877 			break;
10878 		}
10879 	} while (start = end, mp = next_mp);
10880 
10881 	/* Fragment just processed could be the last one. Remember this fact */
10882 	if (!more)
10883 		ipf->ipf_last_frag_seen = B_TRUE;
10884 
10885 	/* Still got holes? */
10886 	if (ipf->ipf_hole_cnt)
10887 		return (IP_REASS_PARTIAL);
10888 	/* Clean up overloaded fields to avoid upstream disasters. */
10889 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10890 		IP_REASS_SET_START(mp1, 0);
10891 		IP_REASS_SET_END(mp1, 0);
10892 	}
10893 	return (IP_REASS_COMPLETE);
10894 }
10895 
10896 /*
10897  * ipsec processing for the fast path, used for input UDP Packets
10898  */
10899 static boolean_t
10900 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10901     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10902 {
10903 	uint32_t	ill_index;
10904 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10905 
10906 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10907 	/* The ill_index of the incoming ILL */
10908 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10909 
10910 	/* pass packet up to the transport */
10911 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10912 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10913 		    NULL, mctl_present);
10914 		if (*first_mpp == NULL) {
10915 			return (B_FALSE);
10916 		}
10917 	}
10918 
10919 	/* Initiate IPPF processing for fastpath UDP */
10920 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10921 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10922 		if (*mpp == NULL) {
10923 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10924 			    "deferred/dropped during IPPF processing\n"));
10925 			return (B_FALSE);
10926 		}
10927 	}
10928 	/*
10929 	 * We make the checks as below since we are in the fast path
10930 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10931 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10932 	 */
10933 	if (connp->conn_recvif || connp->conn_recvslla ||
10934 	    connp->conn_ipv6_recvpktinfo) {
10935 		if (connp->conn_recvif ||
10936 		    connp->conn_ipv6_recvpktinfo) {
10937 			in_flags = IPF_RECVIF;
10938 		}
10939 		if (connp->conn_recvslla) {
10940 			in_flags |= IPF_RECVSLLA;
10941 		}
10942 		/*
10943 		 * since in_flags are being set ill will be
10944 		 * referenced in ip_add_info, so it better not
10945 		 * be NULL.
10946 		 */
10947 		/*
10948 		 * the actual data will be contained in b_cont
10949 		 * upon successful return of the following call.
10950 		 * If the call fails then the original mblk is
10951 		 * returned.
10952 		 */
10953 		*mpp = ip_add_info(*mpp, ill, in_flags);
10954 	}
10955 
10956 	return (B_TRUE);
10957 }
10958 
10959 /*
10960  * Fragmentation reassembly.  Each ILL has a hash table for
10961  * queuing packets undergoing reassembly for all IPIFs
10962  * associated with the ILL.  The hash is based on the packet
10963  * IP ident field.  The ILL frag hash table was allocated
10964  * as a timer block at the time the ILL was created.  Whenever
10965  * there is anything on the reassembly queue, the timer will
10966  * be running.  Returns B_TRUE if successful else B_FALSE;
10967  * frees mp on failure.
10968  */
10969 static boolean_t
10970 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
10971     uint32_t *cksum_val, uint16_t *cksum_flags)
10972 {
10973 	uint32_t	frag_offset_flags;
10974 	ill_t		*ill = (ill_t *)q->q_ptr;
10975 	mblk_t		*mp = *mpp;
10976 	mblk_t		*t_mp;
10977 	ipaddr_t	dst;
10978 	uint8_t		proto = ipha->ipha_protocol;
10979 	uint32_t	sum_val;
10980 	uint16_t	sum_flags;
10981 	ipf_t		*ipf;
10982 	ipf_t		**ipfp;
10983 	ipfb_t		*ipfb;
10984 	uint16_t	ident;
10985 	uint32_t	offset;
10986 	ipaddr_t	src;
10987 	uint_t		hdr_length;
10988 	uint32_t	end;
10989 	mblk_t		*mp1;
10990 	mblk_t		*tail_mp;
10991 	size_t		count;
10992 	size_t		msg_len;
10993 	uint8_t		ecn_info = 0;
10994 	uint32_t	packet_size;
10995 	boolean_t	pruned = B_FALSE;
10996 
10997 	if (cksum_val != NULL)
10998 		*cksum_val = 0;
10999 	if (cksum_flags != NULL)
11000 		*cksum_flags = 0;
11001 
11002 	/*
11003 	 * Drop the fragmented as early as possible, if
11004 	 * we don't have resource(s) to re-assemble.
11005 	 */
11006 	if (ip_reass_queue_bytes == 0) {
11007 		freemsg(mp);
11008 		return (B_FALSE);
11009 	}
11010 
11011 	/* Check for fragmentation offset; return if there's none */
11012 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11013 	    (IPH_MF | IPH_OFFSET)) == 0)
11014 		return (B_TRUE);
11015 
11016 	/*
11017 	 * We utilize hardware computed checksum info only for UDP since
11018 	 * IP fragmentation is a normal occurence for the protocol.  In
11019 	 * addition, checksum offload support for IP fragments carrying
11020 	 * UDP payload is commonly implemented across network adapters.
11021 	 */
11022 	ASSERT(ill != NULL);
11023 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11024 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11025 		mblk_t *mp1 = mp->b_cont;
11026 		int32_t len;
11027 
11028 		/* Record checksum information from the packet */
11029 		sum_val = (uint32_t)DB_CKSUM16(mp);
11030 		sum_flags = DB_CKSUMFLAGS(mp);
11031 
11032 		/* IP payload offset from beginning of mblk */
11033 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11034 
11035 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11036 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11037 		    offset >= DB_CKSUMSTART(mp) &&
11038 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11039 			uint32_t adj;
11040 			/*
11041 			 * Partial checksum has been calculated by hardware
11042 			 * and attached to the packet; in addition, any
11043 			 * prepended extraneous data is even byte aligned.
11044 			 * If any such data exists, we adjust the checksum;
11045 			 * this would also handle any postpended data.
11046 			 */
11047 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11048 			    mp, mp1, len, adj);
11049 
11050 			/* One's complement subtract extraneous checksum */
11051 			if (adj >= sum_val)
11052 				sum_val = ~(adj - sum_val) & 0xFFFF;
11053 			else
11054 				sum_val -= adj;
11055 		}
11056 	} else {
11057 		sum_val = 0;
11058 		sum_flags = 0;
11059 	}
11060 
11061 	/* Clear hardware checksumming flag */
11062 	DB_CKSUMFLAGS(mp) = 0;
11063 
11064 	ident = ipha->ipha_ident;
11065 	offset = (frag_offset_flags << 3) & 0xFFFF;
11066 	src = ipha->ipha_src;
11067 	dst = ipha->ipha_dst;
11068 	hdr_length = IPH_HDR_LENGTH(ipha);
11069 	end = ntohs(ipha->ipha_length) - hdr_length;
11070 
11071 	/* If end == 0 then we have a packet with no data, so just free it */
11072 	if (end == 0) {
11073 		freemsg(mp);
11074 		return (B_FALSE);
11075 	}
11076 
11077 	/* Record the ECN field info. */
11078 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11079 	if (offset != 0) {
11080 		/*
11081 		 * If this isn't the first piece, strip the header, and
11082 		 * add the offset to the end value.
11083 		 */
11084 		mp->b_rptr += hdr_length;
11085 		end += offset;
11086 	}
11087 
11088 	msg_len = MBLKSIZE(mp);
11089 	tail_mp = mp;
11090 	while (tail_mp->b_cont != NULL) {
11091 		tail_mp = tail_mp->b_cont;
11092 		msg_len += MBLKSIZE(tail_mp);
11093 	}
11094 
11095 	/* If the reassembly list for this ILL will get too big, prune it */
11096 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11097 	    ip_reass_queue_bytes) {
11098 		ill_frag_prune(ill,
11099 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11100 		    (ip_reass_queue_bytes - msg_len));
11101 		pruned = B_TRUE;
11102 	}
11103 
11104 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11105 	mutex_enter(&ipfb->ipfb_lock);
11106 
11107 	ipfp = &ipfb->ipfb_ipf;
11108 	/* Try to find an existing fragment queue for this packet. */
11109 	for (;;) {
11110 		ipf = ipfp[0];
11111 		if (ipf != NULL) {
11112 			/*
11113 			 * It has to match on ident and src/dst address.
11114 			 */
11115 			if (ipf->ipf_ident == ident &&
11116 			    ipf->ipf_src == src &&
11117 			    ipf->ipf_dst == dst &&
11118 			    ipf->ipf_protocol == proto) {
11119 				/*
11120 				 * If we have received too many
11121 				 * duplicate fragments for this packet
11122 				 * free it.
11123 				 */
11124 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11125 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11126 					freemsg(mp);
11127 					mutex_exit(&ipfb->ipfb_lock);
11128 					return (B_FALSE);
11129 				}
11130 				/* Found it. */
11131 				break;
11132 			}
11133 			ipfp = &ipf->ipf_hash_next;
11134 			continue;
11135 		}
11136 
11137 		/*
11138 		 * If we pruned the list, do we want to store this new
11139 		 * fragment?. We apply an optimization here based on the
11140 		 * fact that most fragments will be received in order.
11141 		 * So if the offset of this incoming fragment is zero,
11142 		 * it is the first fragment of a new packet. We will
11143 		 * keep it.  Otherwise drop the fragment, as we have
11144 		 * probably pruned the packet already (since the
11145 		 * packet cannot be found).
11146 		 */
11147 		if (pruned && offset != 0) {
11148 			mutex_exit(&ipfb->ipfb_lock);
11149 			freemsg(mp);
11150 			return (B_FALSE);
11151 		}
11152 
11153 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11154 			/*
11155 			 * Too many fragmented packets in this hash
11156 			 * bucket. Free the oldest.
11157 			 */
11158 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11159 		}
11160 
11161 		/* New guy.  Allocate a frag message. */
11162 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11163 		if (mp1 == NULL) {
11164 			BUMP_MIB(&ip_mib, ipInDiscards);
11165 			freemsg(mp);
11166 reass_done:
11167 			mutex_exit(&ipfb->ipfb_lock);
11168 			return (B_FALSE);
11169 		}
11170 
11171 
11172 		BUMP_MIB(&ip_mib, ipReasmReqds);
11173 		mp1->b_cont = mp;
11174 
11175 		/* Initialize the fragment header. */
11176 		ipf = (ipf_t *)mp1->b_rptr;
11177 		ipf->ipf_mp = mp1;
11178 		ipf->ipf_ptphn = ipfp;
11179 		ipfp[0] = ipf;
11180 		ipf->ipf_hash_next = NULL;
11181 		ipf->ipf_ident = ident;
11182 		ipf->ipf_protocol = proto;
11183 		ipf->ipf_src = src;
11184 		ipf->ipf_dst = dst;
11185 		ipf->ipf_nf_hdr_len = 0;
11186 		/* Record reassembly start time. */
11187 		ipf->ipf_timestamp = gethrestime_sec();
11188 		/* Record ipf generation and account for frag header */
11189 		ipf->ipf_gen = ill->ill_ipf_gen++;
11190 		ipf->ipf_count = MBLKSIZE(mp1);
11191 		ipf->ipf_last_frag_seen = B_FALSE;
11192 		ipf->ipf_ecn = ecn_info;
11193 		ipf->ipf_num_dups = 0;
11194 		ipfb->ipfb_frag_pkts++;
11195 		ipf->ipf_checksum = 0;
11196 		ipf->ipf_checksum_flags = 0;
11197 
11198 		/* Store checksum value in fragment header */
11199 		if (sum_flags != 0) {
11200 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11201 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11202 			ipf->ipf_checksum = sum_val;
11203 			ipf->ipf_checksum_flags = sum_flags;
11204 		}
11205 
11206 		/*
11207 		 * We handle reassembly two ways.  In the easy case,
11208 		 * where all the fragments show up in order, we do
11209 		 * minimal bookkeeping, and just clip new pieces on
11210 		 * the end.  If we ever see a hole, then we go off
11211 		 * to ip_reassemble which has to mark the pieces and
11212 		 * keep track of the number of holes, etc.  Obviously,
11213 		 * the point of having both mechanisms is so we can
11214 		 * handle the easy case as efficiently as possible.
11215 		 */
11216 		if (offset == 0) {
11217 			/* Easy case, in-order reassembly so far. */
11218 			ipf->ipf_count += msg_len;
11219 			ipf->ipf_tail_mp = tail_mp;
11220 			/*
11221 			 * Keep track of next expected offset in
11222 			 * ipf_end.
11223 			 */
11224 			ipf->ipf_end = end;
11225 			ipf->ipf_nf_hdr_len = hdr_length;
11226 		} else {
11227 			/* Hard case, hole at the beginning. */
11228 			ipf->ipf_tail_mp = NULL;
11229 			/*
11230 			 * ipf_end == 0 means that we have given up
11231 			 * on easy reassembly.
11232 			 */
11233 			ipf->ipf_end = 0;
11234 
11235 			/* Forget checksum offload from now on */
11236 			ipf->ipf_checksum_flags = 0;
11237 
11238 			/*
11239 			 * ipf_hole_cnt is set by ip_reassemble.
11240 			 * ipf_count is updated by ip_reassemble.
11241 			 * No need to check for return value here
11242 			 * as we don't expect reassembly to complete
11243 			 * or fail for the first fragment itself.
11244 			 */
11245 			(void) ip_reassemble(mp, ipf,
11246 			    (frag_offset_flags & IPH_OFFSET) << 3,
11247 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11248 		}
11249 		/* Update per ipfb and ill byte counts */
11250 		ipfb->ipfb_count += ipf->ipf_count;
11251 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11252 		ill->ill_frag_count += ipf->ipf_count;
11253 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11254 		/* If the frag timer wasn't already going, start it. */
11255 		mutex_enter(&ill->ill_lock);
11256 		ill_frag_timer_start(ill);
11257 		mutex_exit(&ill->ill_lock);
11258 		goto reass_done;
11259 	}
11260 
11261 	/*
11262 	 * If the packet's flag has changed (it could be coming up
11263 	 * from an interface different than the previous, therefore
11264 	 * possibly different checksum capability), then forget about
11265 	 * any stored checksum states.  Otherwise add the value to
11266 	 * the existing one stored in the fragment header.
11267 	 */
11268 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11269 		sum_val += ipf->ipf_checksum;
11270 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11271 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11272 		ipf->ipf_checksum = sum_val;
11273 	} else if (ipf->ipf_checksum_flags != 0) {
11274 		/* Forget checksum offload from now on */
11275 		ipf->ipf_checksum_flags = 0;
11276 	}
11277 
11278 	/*
11279 	 * We have a new piece of a datagram which is already being
11280 	 * reassembled.  Update the ECN info if all IP fragments
11281 	 * are ECN capable.  If there is one which is not, clear
11282 	 * all the info.  If there is at least one which has CE
11283 	 * code point, IP needs to report that up to transport.
11284 	 */
11285 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11286 		if (ecn_info == IPH_ECN_CE)
11287 			ipf->ipf_ecn = IPH_ECN_CE;
11288 	} else {
11289 		ipf->ipf_ecn = IPH_ECN_NECT;
11290 	}
11291 	if (offset && ipf->ipf_end == offset) {
11292 		/* The new fragment fits at the end */
11293 		ipf->ipf_tail_mp->b_cont = mp;
11294 		/* Update the byte count */
11295 		ipf->ipf_count += msg_len;
11296 		/* Update per ipfb and ill byte counts */
11297 		ipfb->ipfb_count += msg_len;
11298 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11299 		ill->ill_frag_count += msg_len;
11300 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11301 		if (frag_offset_flags & IPH_MF) {
11302 			/* More to come. */
11303 			ipf->ipf_end = end;
11304 			ipf->ipf_tail_mp = tail_mp;
11305 			goto reass_done;
11306 		}
11307 	} else {
11308 		/* Go do the hard cases. */
11309 		int ret;
11310 
11311 		if (offset == 0)
11312 			ipf->ipf_nf_hdr_len = hdr_length;
11313 
11314 		/* Save current byte count */
11315 		count = ipf->ipf_count;
11316 		ret = ip_reassemble(mp, ipf,
11317 		    (frag_offset_flags & IPH_OFFSET) << 3,
11318 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11319 		/* Count of bytes added and subtracted (freeb()ed) */
11320 		count = ipf->ipf_count - count;
11321 		if (count) {
11322 			/* Update per ipfb and ill byte counts */
11323 			ipfb->ipfb_count += count;
11324 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11325 			ill->ill_frag_count += count;
11326 			ASSERT(ill->ill_frag_count > 0);
11327 		}
11328 		if (ret == IP_REASS_PARTIAL) {
11329 			goto reass_done;
11330 		} else if (ret == IP_REASS_FAILED) {
11331 			/* Reassembly failed. Free up all resources */
11332 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11333 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11334 				IP_REASS_SET_START(t_mp, 0);
11335 				IP_REASS_SET_END(t_mp, 0);
11336 			}
11337 			freemsg(mp);
11338 			goto reass_done;
11339 		}
11340 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11341 	}
11342 	/*
11343 	 * We have completed reassembly.  Unhook the frag header from
11344 	 * the reassembly list.
11345 	 *
11346 	 * Before we free the frag header, record the ECN info
11347 	 * to report back to the transport.
11348 	 */
11349 	ecn_info = ipf->ipf_ecn;
11350 	BUMP_MIB(&ip_mib, ipReasmOKs);
11351 	ipfp = ipf->ipf_ptphn;
11352 
11353 	/* We need to supply these to caller */
11354 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11355 		sum_val = ipf->ipf_checksum;
11356 	else
11357 		sum_val = 0;
11358 
11359 	mp1 = ipf->ipf_mp;
11360 	count = ipf->ipf_count;
11361 	ipf = ipf->ipf_hash_next;
11362 	if (ipf != NULL)
11363 		ipf->ipf_ptphn = ipfp;
11364 	ipfp[0] = ipf;
11365 	ill->ill_frag_count -= count;
11366 	ASSERT(ipfb->ipfb_count >= count);
11367 	ipfb->ipfb_count -= count;
11368 	ipfb->ipfb_frag_pkts--;
11369 	mutex_exit(&ipfb->ipfb_lock);
11370 	/* Ditch the frag header. */
11371 	mp = mp1->b_cont;
11372 
11373 	freeb(mp1);
11374 
11375 	/* Restore original IP length in header. */
11376 	packet_size = (uint32_t)msgdsize(mp);
11377 	if (packet_size > IP_MAXPACKET) {
11378 		freemsg(mp);
11379 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11380 		return (B_FALSE);
11381 	}
11382 
11383 	if (DB_REF(mp) > 1) {
11384 		mblk_t *mp2 = copymsg(mp);
11385 
11386 		freemsg(mp);
11387 		if (mp2 == NULL) {
11388 			BUMP_MIB(&ip_mib, ipInDiscards);
11389 			return (B_FALSE);
11390 		}
11391 		mp = mp2;
11392 	}
11393 	ipha = (ipha_t *)mp->b_rptr;
11394 
11395 	ipha->ipha_length = htons((uint16_t)packet_size);
11396 	/* We're now complete, zip the frag state */
11397 	ipha->ipha_fragment_offset_and_flags = 0;
11398 	/* Record the ECN info. */
11399 	ipha->ipha_type_of_service &= 0xFC;
11400 	ipha->ipha_type_of_service |= ecn_info;
11401 	*mpp = mp;
11402 
11403 	/* Reassembly is successful; return checksum information if needed */
11404 	if (cksum_val != NULL)
11405 		*cksum_val = sum_val;
11406 	if (cksum_flags != NULL)
11407 		*cksum_flags = sum_flags;
11408 
11409 	return (B_TRUE);
11410 }
11411 
11412 /*
11413  * Perform ip header check sum update local options.
11414  * return B_TRUE if all is well, else return B_FALSE and release
11415  * the mp. caller is responsible for decrementing ire ref cnt.
11416  */
11417 static boolean_t
11418 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11419 {
11420 	mblk_t		*first_mp;
11421 	boolean_t	mctl_present;
11422 	uint16_t	sum;
11423 
11424 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11425 	/*
11426 	 * Don't do the checksum if it has gone through AH/ESP
11427 	 * processing.
11428 	 */
11429 	if (!mctl_present) {
11430 		sum = ip_csum_hdr(ipha);
11431 		if (sum != 0) {
11432 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11433 			freemsg(first_mp);
11434 			return (B_FALSE);
11435 		}
11436 	}
11437 
11438 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11439 		if (mctl_present)
11440 			freeb(first_mp);
11441 		return (B_FALSE);
11442 	}
11443 
11444 	return (B_TRUE);
11445 }
11446 
11447 /*
11448  * All udp packet are delivered to the local host via this routine.
11449  */
11450 void
11451 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11452     ill_t *recv_ill)
11453 {
11454 	uint32_t	sum;
11455 	uint32_t	u1;
11456 	boolean_t	mctl_present;
11457 	conn_t		*connp;
11458 	mblk_t		*first_mp;
11459 	uint16_t	*up;
11460 	ill_t		*ill = (ill_t *)q->q_ptr;
11461 	uint16_t	reass_hck_flags = 0;
11462 
11463 #define	rptr    ((uchar_t *)ipha)
11464 
11465 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11466 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11467 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11468 
11469 	/*
11470 	 * FAST PATH for udp packets
11471 	 */
11472 
11473 	/* u1 is # words of IP options */
11474 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11475 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11476 
11477 	/* IP options present */
11478 	if (u1 != 0)
11479 		goto ipoptions;
11480 
11481 	/* Check the IP header checksum.  */
11482 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11483 		/* Clear the IP header h/w cksum flag */
11484 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11485 	} else {
11486 #define	uph	((uint16_t *)ipha)
11487 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11488 		    uph[6] + uph[7] + uph[8] + uph[9];
11489 #undef	uph
11490 		/* finish doing IP checksum */
11491 		sum = (sum & 0xFFFF) + (sum >> 16);
11492 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11493 		/*
11494 		 * Don't verify header checksum if this packet is coming
11495 		 * back from AH/ESP as we already did it.
11496 		 */
11497 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
11498 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11499 			freemsg(first_mp);
11500 			return;
11501 		}
11502 	}
11503 
11504 	/*
11505 	 * Count for SNMP of inbound packets for ire.
11506 	 * if mctl is present this might be a secure packet and
11507 	 * has already been counted for in ip_proto_input().
11508 	 */
11509 	if (!mctl_present) {
11510 		UPDATE_IB_PKT_COUNT(ire);
11511 		ire->ire_last_used_time = lbolt;
11512 	}
11513 
11514 	/* packet part of fragmented IP packet? */
11515 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11516 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11517 		goto fragmented;
11518 	}
11519 
11520 	/* u1 = IP header length (20 bytes) */
11521 	u1 = IP_SIMPLE_HDR_LENGTH;
11522 
11523 	/* packet does not contain complete IP & UDP headers */
11524 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11525 		goto udppullup;
11526 
11527 	/* up points to UDP header */
11528 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11529 #define	iphs    ((uint16_t *)ipha)
11530 
11531 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11532 	if (up[3] != 0) {
11533 		mblk_t *mp1 = mp->b_cont;
11534 		boolean_t cksum_err;
11535 		uint16_t hck_flags = 0;
11536 
11537 		/* Pseudo-header checksum */
11538 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11539 		    iphs[9] + up[2];
11540 
11541 		/*
11542 		 * Revert to software checksum calculation if the interface
11543 		 * isn't capable of checksum offload or if IPsec is present.
11544 		 */
11545 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11546 			hck_flags = DB_CKSUMFLAGS(mp);
11547 
11548 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11549 			IP_STAT(ip_in_sw_cksum);
11550 
11551 		IP_CKSUM_RECV(hck_flags, u1,
11552 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11553 		    (int32_t)((uchar_t *)up - rptr),
11554 		    mp, mp1, cksum_err);
11555 
11556 		if (cksum_err) {
11557 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11558 
11559 			if (hck_flags & HCK_FULLCKSUM)
11560 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11561 			else if (hck_flags & HCK_PARTIALCKSUM)
11562 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11563 			else
11564 				IP_STAT(ip_udp_in_sw_cksum_err);
11565 
11566 			freemsg(first_mp);
11567 			return;
11568 		}
11569 	}
11570 
11571 	/* Non-fragmented broadcast or multicast packet? */
11572 	if (ire->ire_type == IRE_BROADCAST)
11573 		goto udpslowpath;
11574 
11575 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11576 	    ire->ire_zoneid)) != NULL) {
11577 		ASSERT(connp->conn_upq != NULL);
11578 		IP_STAT(ip_udp_fast_path);
11579 
11580 		if (CONN_UDP_FLOWCTLD(connp)) {
11581 			freemsg(mp);
11582 			BUMP_MIB(&ip_mib, udpInOverflows);
11583 		} else {
11584 			if (!mctl_present) {
11585 				BUMP_MIB(&ip_mib, ipInDelivers);
11586 			}
11587 			/*
11588 			 * mp and first_mp can change.
11589 			 */
11590 			if (ip_udp_check(q, connp, recv_ill,
11591 			    ipha, &mp, &first_mp, mctl_present)) {
11592 				/* Send it upstream */
11593 				CONN_UDP_RECV(connp, mp);
11594 			}
11595 		}
11596 		/*
11597 		 * freeb() cannot deal with null mblk being passed
11598 		 * in and first_mp can be set to null in the call
11599 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11600 		 */
11601 		if (mctl_present && first_mp != NULL) {
11602 			freeb(first_mp);
11603 		}
11604 		CONN_DEC_REF(connp);
11605 		return;
11606 	}
11607 
11608 	/*
11609 	 * if we got here we know the packet is not fragmented and
11610 	 * has no options. The classifier could not find a conn_t and
11611 	 * most likely its an icmp packet so send it through slow path.
11612 	 */
11613 
11614 	goto udpslowpath;
11615 
11616 ipoptions:
11617 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11618 		goto slow_done;
11619 	}
11620 
11621 	UPDATE_IB_PKT_COUNT(ire);
11622 	ire->ire_last_used_time = lbolt;
11623 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11624 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11625 fragmented:
11626 		/*
11627 		 * "sum" and "reass_hck_flags" are non-zero if the
11628 		 * reassembled packet has a valid hardware computed
11629 		 * checksum information associated with it.
11630 		 */
11631 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
11632 			goto slow_done;
11633 		/*
11634 		 * Make sure that first_mp points back to mp as
11635 		 * the mp we came in with could have changed in
11636 		 * ip_rput_fragment().
11637 		 */
11638 		ASSERT(!mctl_present);
11639 		ipha = (ipha_t *)mp->b_rptr;
11640 		first_mp = mp;
11641 	}
11642 
11643 	/* Now we have a complete datagram, destined for this machine. */
11644 	u1 = IPH_HDR_LENGTH(ipha);
11645 	/* Pull up the UDP header, if necessary. */
11646 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
11647 udppullup:
11648 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11649 			BUMP_MIB(&ip_mib, ipInDiscards);
11650 			freemsg(first_mp);
11651 			goto slow_done;
11652 		}
11653 		ipha = (ipha_t *)mp->b_rptr;
11654 	}
11655 
11656 	/*
11657 	 * Validate the checksum for the reassembled packet; for the
11658 	 * pullup case we calculate the payload checksum in software.
11659 	 */
11660 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11661 	if (up[3] != 0) {
11662 		boolean_t cksum_err;
11663 
11664 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11665 			IP_STAT(ip_in_sw_cksum);
11666 
11667 		IP_CKSUM_RECV_REASS(reass_hck_flags,
11668 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11669 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11670 		    iphs[9] + up[2], sum, cksum_err);
11671 
11672 		if (cksum_err) {
11673 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11674 
11675 			if (reass_hck_flags & HCK_FULLCKSUM)
11676 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11677 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
11678 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11679 			else
11680 				IP_STAT(ip_udp_in_sw_cksum_err);
11681 
11682 			freemsg(first_mp);
11683 			goto slow_done;
11684 		}
11685 	}
11686 udpslowpath:
11687 
11688 	/* Clear hardware checksum flag to be safe */
11689 	DB_CKSUMFLAGS(mp) = 0;
11690 
11691 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
11692 	    (ire->ire_type == IRE_BROADCAST),
11693 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11694 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11695 
11696 slow_done:
11697 	IP_STAT(ip_udp_slow_path);
11698 	return;
11699 
11700 #undef  iphs
11701 #undef  rptr
11702 }
11703 
11704 /* ARGSUSED */
11705 static mblk_t *
11706 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11707     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11708     ill_rx_ring_t *ill_ring)
11709 {
11710 	conn_t		*connp;
11711 	uint32_t	sum;
11712 	uint32_t	u1;
11713 	uint16_t	*up;
11714 	int		offset;
11715 	ssize_t		len;
11716 	mblk_t		*mp1;
11717 	boolean_t	syn_present = B_FALSE;
11718 	tcph_t		*tcph;
11719 	uint_t		ip_hdr_len;
11720 	ill_t		*ill = (ill_t *)q->q_ptr;
11721 	zoneid_t	zoneid = ire->ire_zoneid;
11722 	boolean_t	cksum_err;
11723 	uint16_t	hck_flags = 0;
11724 
11725 #define	rptr	((uchar_t *)ipha)
11726 
11727 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11728 
11729 	/*
11730 	 * FAST PATH for tcp packets
11731 	 */
11732 
11733 	/* u1 is # words of IP options */
11734 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11735 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11736 
11737 	/* IP options present */
11738 	if (u1) {
11739 		goto ipoptions;
11740 	} else {
11741 		/* Check the IP header checksum.  */
11742 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11743 			/* Clear the IP header h/w cksum flag */
11744 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11745 		} else {
11746 #define	uph	((uint16_t *)ipha)
11747 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11748 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11749 #undef	uph
11750 			/* finish doing IP checksum */
11751 			sum = (sum & 0xFFFF) + (sum >> 16);
11752 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11753 			/*
11754 			 * Don't verify header checksum if this packet
11755 			 * is coming back from AH/ESP as we already did it.
11756 			 */
11757 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11758 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11759 				goto error;
11760 			}
11761 		}
11762 	}
11763 
11764 	if (!mctl_present) {
11765 		UPDATE_IB_PKT_COUNT(ire);
11766 		ire->ire_last_used_time = lbolt;
11767 	}
11768 
11769 	/* packet part of fragmented IP packet? */
11770 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11771 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11772 		goto fragmented;
11773 	}
11774 
11775 	/* u1 = IP header length (20 bytes) */
11776 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11777 
11778 	/* does packet contain IP+TCP headers? */
11779 	len = mp->b_wptr - rptr;
11780 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11781 		IP_STAT(ip_tcppullup);
11782 		goto tcppullup;
11783 	}
11784 
11785 	/* TCP options present? */
11786 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11787 
11788 	/*
11789 	 * If options need to be pulled up, then goto tcpoptions.
11790 	 * otherwise we are still in the fast path
11791 	 */
11792 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11793 		IP_STAT(ip_tcpoptions);
11794 		goto tcpoptions;
11795 	}
11796 
11797 	/* multiple mblks of tcp data? */
11798 	if ((mp1 = mp->b_cont) != NULL) {
11799 		/* more then two? */
11800 		if (mp1->b_cont != NULL) {
11801 			IP_STAT(ip_multipkttcp);
11802 			goto multipkttcp;
11803 		}
11804 		len += mp1->b_wptr - mp1->b_rptr;
11805 	}
11806 
11807 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11808 
11809 	/* part of pseudo checksum */
11810 
11811 	/* TCP datagram length */
11812 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11813 
11814 #define	iphs    ((uint16_t *)ipha)
11815 
11816 #ifdef	_BIG_ENDIAN
11817 	u1 += IPPROTO_TCP;
11818 #else
11819 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11820 #endif
11821 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11822 
11823 	/*
11824 	 * Revert to software checksum calculation if the interface
11825 	 * isn't capable of checksum offload or if IPsec is present.
11826 	 */
11827 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11828 		hck_flags = DB_CKSUMFLAGS(mp);
11829 
11830 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11831 		IP_STAT(ip_in_sw_cksum);
11832 
11833 	IP_CKSUM_RECV(hck_flags, u1,
11834 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11835 	    (int32_t)((uchar_t *)up - rptr),
11836 	    mp, mp1, cksum_err);
11837 
11838 	if (cksum_err) {
11839 		BUMP_MIB(&ip_mib, tcpInErrs);
11840 
11841 		if (hck_flags & HCK_FULLCKSUM)
11842 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
11843 		else if (hck_flags & HCK_PARTIALCKSUM)
11844 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
11845 		else
11846 			IP_STAT(ip_tcp_in_sw_cksum_err);
11847 
11848 		goto error;
11849 	}
11850 
11851 try_again:
11852 
11853 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11854 	    NULL) {
11855 		/* Send the TH_RST */
11856 		goto no_conn;
11857 	}
11858 
11859 	/*
11860 	 * TCP FAST PATH for AF_INET socket.
11861 	 *
11862 	 * TCP fast path to avoid extra work. An AF_INET socket type
11863 	 * does not have facility to receive extra information via
11864 	 * ip_process or ip_add_info. Also, when the connection was
11865 	 * established, we made a check if this connection is impacted
11866 	 * by any global IPSec policy or per connection policy (a
11867 	 * policy that comes in effect later will not apply to this
11868 	 * connection). Since all this can be determined at the
11869 	 * connection establishment time, a quick check of flags
11870 	 * can avoid extra work.
11871 	 */
11872 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11873 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11874 		ASSERT(first_mp == mp);
11875 		SET_SQUEUE(mp, tcp_rput_data, connp);
11876 		return (mp);
11877 	}
11878 
11879 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11880 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11881 		if (IPCL_IS_TCP(connp)) {
11882 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11883 			DB_CKSUMSTART(mp) =
11884 			    (intptr_t)ip_squeue_get(ill_ring);
11885 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11886 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11887 				SET_SQUEUE(mp, connp->conn_recv, connp);
11888 				return (mp);
11889 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11890 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11891 				ip_squeue_enter_unbound++;
11892 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11893 				    connp);
11894 				return (mp);
11895 			}
11896 			syn_present = B_TRUE;
11897 		}
11898 
11899 	}
11900 
11901 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11902 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11903 
11904 		/* No need to send this packet to TCP */
11905 		if ((flags & TH_RST) || (flags & TH_URG)) {
11906 			CONN_DEC_REF(connp);
11907 			freemsg(first_mp);
11908 			return (NULL);
11909 		}
11910 		if (flags & TH_ACK) {
11911 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11912 			CONN_DEC_REF(connp);
11913 			return (NULL);
11914 		}
11915 
11916 		CONN_DEC_REF(connp);
11917 		freemsg(first_mp);
11918 		return (NULL);
11919 	}
11920 
11921 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11922 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11923 		    ipha, NULL, mctl_present);
11924 		if (first_mp == NULL) {
11925 			CONN_DEC_REF(connp);
11926 			return (NULL);
11927 		}
11928 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11929 			ASSERT(syn_present);
11930 			if (mctl_present) {
11931 				ASSERT(first_mp != mp);
11932 				first_mp->b_datap->db_struioflag |=
11933 				    STRUIO_POLICY;
11934 			} else {
11935 				ASSERT(first_mp == mp);
11936 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11937 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11938 			}
11939 		} else {
11940 			/*
11941 			 * Discard first_mp early since we're dealing with a
11942 			 * fully-connected conn_t and tcp doesn't do policy in
11943 			 * this case.
11944 			 */
11945 			if (mctl_present) {
11946 				freeb(first_mp);
11947 				mctl_present = B_FALSE;
11948 			}
11949 			first_mp = mp;
11950 		}
11951 	}
11952 
11953 	/* Initiate IPPF processing for fastpath */
11954 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11955 		uint32_t	ill_index;
11956 
11957 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11958 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11959 		if (mp == NULL) {
11960 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11961 			    "deferred/dropped during IPPF processing\n"));
11962 			CONN_DEC_REF(connp);
11963 			if (mctl_present)
11964 				freeb(first_mp);
11965 			return (NULL);
11966 		} else if (mctl_present) {
11967 			/*
11968 			 * ip_process might return a new mp.
11969 			 */
11970 			ASSERT(first_mp != mp);
11971 			first_mp->b_cont = mp;
11972 		} else {
11973 			first_mp = mp;
11974 		}
11975 
11976 	}
11977 
11978 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11979 		mp = ip_add_info(mp, recv_ill, flags);
11980 		if (mp == NULL) {
11981 			CONN_DEC_REF(connp);
11982 			if (mctl_present)
11983 				freeb(first_mp);
11984 			return (NULL);
11985 		} else if (mctl_present) {
11986 			/*
11987 			 * ip_add_info might return a new mp.
11988 			 */
11989 			ASSERT(first_mp != mp);
11990 			first_mp->b_cont = mp;
11991 		} else {
11992 			first_mp = mp;
11993 		}
11994 	}
11995 
11996 	if (IPCL_IS_TCP(connp)) {
11997 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11998 		return (first_mp);
11999 	} else {
12000 		putnext(connp->conn_rq, first_mp);
12001 		CONN_DEC_REF(connp);
12002 		return (NULL);
12003 	}
12004 
12005 no_conn:
12006 	/* Initiate IPPf processing, if needed. */
12007 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12008 		uint32_t ill_index;
12009 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12010 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12011 		if (first_mp == NULL) {
12012 			return (NULL);
12013 		}
12014 	}
12015 	BUMP_MIB(&ip_mib, ipInDelivers);
12016 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12017 	return (NULL);
12018 ipoptions:
12019 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12020 		goto slow_done;
12021 	}
12022 
12023 	UPDATE_IB_PKT_COUNT(ire);
12024 	ire->ire_last_used_time = lbolt;
12025 
12026 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12027 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12028 fragmented:
12029 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12030 			if (mctl_present)
12031 				freeb(first_mp);
12032 			goto slow_done;
12033 		}
12034 		/*
12035 		 * Make sure that first_mp points back to mp as
12036 		 * the mp we came in with could have changed in
12037 		 * ip_rput_fragment().
12038 		 */
12039 		ASSERT(!mctl_present);
12040 		ipha = (ipha_t *)mp->b_rptr;
12041 		first_mp = mp;
12042 	}
12043 
12044 tcp_slow:
12045 	/* Now we have a complete datagram, destined for this machine. */
12046 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12047 
12048 	len = mp->b_wptr - mp->b_rptr;
12049 	/* Pull up a minimal TCP header, if necessary. */
12050 	if (len < (u1 + 20)) {
12051 tcppullup:
12052 		if (!pullupmsg(mp, u1 + 20)) {
12053 			BUMP_MIB(&ip_mib, ipInDiscards);
12054 			goto error;
12055 		}
12056 		ipha = (ipha_t *)mp->b_rptr;
12057 		len = mp->b_wptr - mp->b_rptr;
12058 	}
12059 
12060 	/*
12061 	 * Extract the offset field from the TCP header.  As usual, we
12062 	 * try to help the compiler more than the reader.
12063 	 */
12064 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12065 	if (offset != 5) {
12066 tcpoptions:
12067 		if (offset < 5) {
12068 			BUMP_MIB(&ip_mib, ipInDiscards);
12069 			goto error;
12070 		}
12071 		/*
12072 		 * There must be TCP options.
12073 		 * Make sure we can grab them.
12074 		 */
12075 		offset <<= 2;
12076 		offset += u1;
12077 		if (len < offset) {
12078 			if (!pullupmsg(mp, offset)) {
12079 				BUMP_MIB(&ip_mib, ipInDiscards);
12080 				goto error;
12081 			}
12082 			ipha = (ipha_t *)mp->b_rptr;
12083 			len = mp->b_wptr - rptr;
12084 		}
12085 	}
12086 
12087 	/* Get the total packet length in len, including headers. */
12088 	if (mp->b_cont) {
12089 multipkttcp:
12090 		len = msgdsize(mp);
12091 	}
12092 
12093 	/*
12094 	 * Check the TCP checksum by pulling together the pseudo-
12095 	 * header checksum, and passing it to ip_csum to be added in
12096 	 * with the TCP datagram.
12097 	 *
12098 	 * Since we are not using the hwcksum if available we must
12099 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12100 	 * If either of these fails along the way the mblk is freed.
12101 	 * If this logic ever changes and mblk is reused to say send
12102 	 * ICMP's back, then this flag may need to be cleared in
12103 	 * other places as well.
12104 	 */
12105 	DB_CKSUMFLAGS(mp) = 0;
12106 
12107 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12108 
12109 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12110 #ifdef	_BIG_ENDIAN
12111 	u1 += IPPROTO_TCP;
12112 #else
12113 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12114 #endif
12115 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12116 	/*
12117 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12118 	 */
12119 	IP_STAT(ip_in_sw_cksum);
12120 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12121 		BUMP_MIB(&ip_mib, tcpInErrs);
12122 		goto error;
12123 	}
12124 
12125 	IP_STAT(ip_tcp_slow_path);
12126 	goto try_again;
12127 #undef  iphs
12128 #undef  rptr
12129 
12130 error:
12131 	freemsg(first_mp);
12132 slow_done:
12133 	return (NULL);
12134 }
12135 
12136 /* ARGSUSED */
12137 static void
12138 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12139     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12140 {
12141 	conn_t		*connp;
12142 	uint32_t	sum;
12143 	uint32_t	u1;
12144 	ssize_t		len;
12145 	sctp_hdr_t	*sctph;
12146 	zoneid_t	zoneid = ire->ire_zoneid;
12147 	uint32_t	pktsum;
12148 	uint32_t	calcsum;
12149 	uint32_t	ports;
12150 	uint_t		ipif_seqid;
12151 	in6_addr_t	map_src, map_dst;
12152 	ill_t		*ill = (ill_t *)q->q_ptr;
12153 
12154 #define	rptr	((uchar_t *)ipha)
12155 
12156 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12157 
12158 	/* u1 is # words of IP options */
12159 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12160 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12161 
12162 	/* IP options present */
12163 	if (u1 > 0) {
12164 		goto ipoptions;
12165 	} else {
12166 		/* Check the IP header checksum.  */
12167 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12168 			/*
12169 			 * Since there is no SCTP h/w cksum support yet, just
12170 			 * clear the flag.
12171 			 */
12172 			DB_CKSUMFLAGS(mp) = 0;
12173 		} else {
12174 #define	uph	((uint16_t *)ipha)
12175 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12176 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12177 #undef	uph
12178 			/* finish doing IP checksum */
12179 			sum = (sum & 0xFFFF) + (sum >> 16);
12180 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12181 			/*
12182 			 * Don't verify header checksum if this packet
12183 			 * is coming back from AH/ESP as we already did it.
12184 			 */
12185 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12186 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12187 				goto error;
12188 			}
12189 		}
12190 	}
12191 
12192 	/*
12193 	 * Don't verify header checksum if this packet is coming
12194 	 * back from AH/ESP as we already did it.
12195 	 */
12196 	if (!mctl_present) {
12197 		UPDATE_IB_PKT_COUNT(ire);
12198 		ire->ire_last_used_time = lbolt;
12199 	}
12200 
12201 	/* packet part of fragmented IP packet? */
12202 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12203 	if (u1 & (IPH_MF | IPH_OFFSET))
12204 		goto fragmented;
12205 
12206 	/* u1 = IP header length (20 bytes) */
12207 	u1 = IP_SIMPLE_HDR_LENGTH;
12208 
12209 find_sctp_client:
12210 	/* Pullup if we don't have the sctp common header. */
12211 	len = MBLKL(mp);
12212 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12213 		if (mp->b_cont == NULL ||
12214 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12215 			BUMP_MIB(&ip_mib, ipInDiscards);
12216 			goto error;
12217 		}
12218 		ipha = (ipha_t *)mp->b_rptr;
12219 		len = MBLKL(mp);
12220 	}
12221 
12222 	sctph = (sctp_hdr_t *)(rptr + u1);
12223 #ifdef	DEBUG
12224 	if (!skip_sctp_cksum) {
12225 #endif
12226 		pktsum = sctph->sh_chksum;
12227 		sctph->sh_chksum = 0;
12228 		calcsum = sctp_cksum(mp, u1);
12229 		if (calcsum != pktsum) {
12230 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12231 			goto error;
12232 		}
12233 		sctph->sh_chksum = pktsum;
12234 #ifdef	DEBUG	/* skip_sctp_cksum */
12235 	}
12236 #endif
12237 	/* get the ports */
12238 	ports = *(uint32_t *)&sctph->sh_sport;
12239 
12240 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12241 	IRE_REFRELE(ire);
12242 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12243 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12244 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12245 	    zoneid)) == NULL) {
12246 		/* Check for raw socket or OOTB handling */
12247 		goto no_conn;
12248 	}
12249 
12250 	/* Found a client; up it goes */
12251 	BUMP_MIB(&ip_mib, ipInDelivers);
12252 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12253 	return;
12254 
12255 no_conn:
12256 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12257 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12258 	return;
12259 
12260 ipoptions:
12261 	DB_CKSUMFLAGS(mp) = 0;
12262 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12263 		goto slow_done;
12264 
12265 	UPDATE_IB_PKT_COUNT(ire);
12266 	ire->ire_last_used_time = lbolt;
12267 
12268 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12269 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12270 fragmented:
12271 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12272 			goto slow_done;
12273 		/*
12274 		 * Make sure that first_mp points back to mp as
12275 		 * the mp we came in with could have changed in
12276 		 * ip_rput_fragment().
12277 		 */
12278 		ASSERT(!mctl_present);
12279 		ipha = (ipha_t *)mp->b_rptr;
12280 		first_mp = mp;
12281 	}
12282 
12283 	/* Now we have a complete datagram, destined for this machine. */
12284 	u1 = IPH_HDR_LENGTH(ipha);
12285 	goto find_sctp_client;
12286 #undef  iphs
12287 #undef  rptr
12288 
12289 error:
12290 	freemsg(first_mp);
12291 slow_done:
12292 	IRE_REFRELE(ire);
12293 }
12294 
12295 #define	VER_BITS	0xF0
12296 #define	VERSION_6	0x60
12297 
12298 static boolean_t
12299 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12300     ipaddr_t *dstp)
12301 {
12302 	uint_t	opt_len;
12303 	ipha_t *ipha;
12304 	ssize_t len;
12305 	uint_t	pkt_len;
12306 
12307 	IP_STAT(ip_ipoptions);
12308 	ipha = *iphapp;
12309 
12310 #define	rptr    ((uchar_t *)ipha)
12311 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12312 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12313 		BUMP_MIB(&ip_mib, ipInIPv6);
12314 		freemsg(mp);
12315 		return (B_FALSE);
12316 	}
12317 
12318 	/* multiple mblk or too short */
12319 	pkt_len = ntohs(ipha->ipha_length);
12320 
12321 	/* Get the number of words of IP options in the IP header. */
12322 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12323 	if (opt_len) {
12324 		/* IP Options present!  Validate and process. */
12325 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12326 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12327 			goto done;
12328 		}
12329 		/*
12330 		 * Recompute complete header length and make sure we
12331 		 * have access to all of it.
12332 		 */
12333 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12334 		if (len > (mp->b_wptr - rptr)) {
12335 			if (len > pkt_len) {
12336 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12337 				goto done;
12338 			}
12339 			if (!pullupmsg(mp, len)) {
12340 				BUMP_MIB(&ip_mib, ipInDiscards);
12341 				goto done;
12342 			}
12343 			ipha = (ipha_t *)mp->b_rptr;
12344 		}
12345 		/*
12346 		 * Go off to ip_rput_options which returns the next hop
12347 		 * destination address, which may have been affected
12348 		 * by source routing.
12349 		 */
12350 		IP_STAT(ip_opt);
12351 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12352 			return (B_FALSE);
12353 		}
12354 	}
12355 	*iphapp = ipha;
12356 	return (B_TRUE);
12357 done:
12358 	/* clear b_prev - used by ip_mroute_decap */
12359 	mp->b_prev = NULL;
12360 	freemsg(mp);
12361 	return (B_FALSE);
12362 #undef  rptr
12363 }
12364 
12365 /*
12366  * Deal with the fact that there is no ire for the destination.
12367  * The incoming ill (in_ill) is passed in to ip_newroute only
12368  * in the case of packets coming from mobile ip forward tunnel.
12369  * It must be null otherwise.
12370  */
12371 static void
12372 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12373     ipaddr_t dst)
12374 {
12375 	ipha_t	*ipha;
12376 	ill_t	*ill;
12377 
12378 	ipha = (ipha_t *)mp->b_rptr;
12379 	ill = (ill_t *)q->q_ptr;
12380 
12381 	ASSERT(ill != NULL);
12382 	/*
12383 	 * No IRE for this destination, so it can't be for us.
12384 	 * Unless we are forwarding, drop the packet.
12385 	 * We have to let source routed packets through
12386 	 * since we don't yet know if they are 'ping -l'
12387 	 * packets i.e. if they will go out over the
12388 	 * same interface as they came in on.
12389 	 */
12390 	if (ll_multicast) {
12391 		freemsg(mp);
12392 		return;
12393 	}
12394 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12395 		BUMP_MIB(&ip_mib, ipForwProhibits);
12396 		freemsg(mp);
12397 		return;
12398 	}
12399 
12400 	/* Check for Martian addresses */
12401 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12402 		freemsg(mp);
12403 		return;
12404 	}
12405 
12406 	/* Mark this packet as having originated externally */
12407 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12408 
12409 	/*
12410 	 * Clear the indication that this may have a hardware checksum
12411 	 * as we are not using it
12412 	 */
12413 	DB_CKSUMFLAGS(mp) = 0;
12414 
12415 	/*
12416 	 * Now hand the packet to ip_newroute.
12417 	 */
12418 	ip_newroute(q, mp, dst, in_ill, NULL);
12419 }
12420 
12421 /*
12422  * check ip header length and align it.
12423  */
12424 static boolean_t
12425 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12426 {
12427 	ssize_t len;
12428 	ill_t *ill;
12429 	ipha_t	*ipha;
12430 
12431 	len = MBLKL(mp);
12432 
12433 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12434 		if (!OK_32PTR(mp->b_rptr))
12435 			IP_STAT(ip_notaligned1);
12436 		else
12437 			IP_STAT(ip_notaligned2);
12438 		/* Guard against bogus device drivers */
12439 		if (len < 0) {
12440 			/* clear b_prev - used by ip_mroute_decap */
12441 			mp->b_prev = NULL;
12442 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12443 			freemsg(mp);
12444 			return (B_FALSE);
12445 		}
12446 
12447 		if (ip_rput_pullups++ == 0) {
12448 			ill = (ill_t *)q->q_ptr;
12449 			ipha = (ipha_t *)mp->b_rptr;
12450 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12451 			    "ip_check_and_align_header: %s forced us to "
12452 			    " pullup pkt, hdr len %ld, hdr addr %p",
12453 			    ill->ill_name, len, ipha);
12454 		}
12455 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12456 			/* clear b_prev - used by ip_mroute_decap */
12457 			mp->b_prev = NULL;
12458 			BUMP_MIB(&ip_mib, ipInDiscards);
12459 			freemsg(mp);
12460 			return (B_FALSE);
12461 		}
12462 	}
12463 	return (B_TRUE);
12464 }
12465 
12466 static boolean_t
12467 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12468 {
12469 	ill_group_t	*ill_group;
12470 	ill_group_t	*ire_group;
12471 	queue_t 	*q;
12472 	ill_t		*ire_ill;
12473 	uint_t		ill_ifindex;
12474 
12475 	q = *qp;
12476 	/*
12477 	 * We need to check to make sure the packet came in
12478 	 * on the queue associated with the destination IRE.
12479 	 * Note that for multicast packets and broadcast packets sent to
12480 	 * a broadcast address which is shared between multiple interfaces
12481 	 * we should not do this since we just got a random broadcast ire.
12482 	 */
12483 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12484 		boolean_t check_multi = B_TRUE;
12485 
12486 		/*
12487 		 * This packet came in on an interface other than the
12488 		 * one associated with the destination address.
12489 		 * "Gateway" it to the appropriate interface here.
12490 		 * As long as the ills belong to the same group,
12491 		 * we don't consider them to arriving on the wrong
12492 		 * interface. Thus, when the switch is doing inbound
12493 		 * load spreading, we won't drop packets when we
12494 		 * are doing strict multihoming checks. Note, the
12495 		 * same holds true for 'usesrc groups' where the
12496 		 * destination address may belong to another interface
12497 		 * to allow multipathing to happen
12498 		 */
12499 		ill_group = ill->ill_group;
12500 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12501 		ill_ifindex = ill->ill_usesrc_ifindex;
12502 		ire_group = ire_ill->ill_group;
12503 
12504 		/*
12505 		 * If it's part of the same IPMP group, or if it's a legal
12506 		 * address on the 'usesrc' interface, then bypass strict
12507 		 * checks.
12508 		 */
12509 		if (ill_group != NULL && ill_group == ire_group) {
12510 			check_multi = B_FALSE;
12511 		} else if (ill_ifindex != 0 &&
12512 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12513 			check_multi = B_FALSE;
12514 		}
12515 
12516 		if (check_multi &&
12517 		    ip_strict_dst_multihoming &&
12518 		    ((ill->ill_flags &
12519 		    ire->ire_ipif->ipif_ill->ill_flags &
12520 		    ILLF_ROUTER) == 0)) {
12521 			/* Drop packet */
12522 			BUMP_MIB(&ip_mib, ipForwProhibits);
12523 			freemsg(mp);
12524 			ire_refrele(ire);
12525 			return (B_TRUE);
12526 		}
12527 
12528 		/*
12529 		 * Change the queue (for non-virtual destination network
12530 		 * interfaces) and ip_rput_local will be called with the right
12531 		 * queue
12532 		 */
12533 		q = ire->ire_rfq;
12534 	}
12535 	/* Must be broadcast.  We'll take it. */
12536 	*qp = q;
12537 	return (B_FALSE);
12538 }
12539 
12540 static void
12541 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12542     ill_t *ill, int ll_multicast)
12543 {
12544 	ill_group_t	*ill_group;
12545 	ill_group_t	*ire_group;
12546 	queue_t	*dev_q;
12547 
12548 	ASSERT(ire->ire_stq != NULL);
12549 	if (ll_multicast != 0)
12550 		goto drop_pkt;
12551 
12552 	if (ip_no_forward(ipha, ill))
12553 		goto drop_pkt;
12554 
12555 	ill_group = ill->ill_group;
12556 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12557 	/*
12558 	 * Check if we want to forward this one at this time.
12559 	 * We allow source routed packets on a host provided that
12560 	 * they go out the same interface or same interface group
12561 	 * as they came in on.
12562 	 *
12563 	 * XXX To be quicker, we may wish to not chase pointers to
12564 	 * get the ILLF_ROUTER flag and instead store the
12565 	 * forwarding policy in the ire.  An unfortunate
12566 	 * side-effect of that would be requiring an ire flush
12567 	 * whenever the ILLF_ROUTER flag changes.
12568 	 */
12569 	if (((ill->ill_flags &
12570 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12571 	    ILLF_ROUTER) == 0) &&
12572 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12573 	    (ill_group != NULL && ill_group == ire_group)))) {
12574 		BUMP_MIB(&ip_mib, ipForwProhibits);
12575 		if (ip_source_routed(ipha)) {
12576 			q = WR(q);
12577 			/*
12578 			 * Clear the indication that this may have
12579 			 * hardware checksum as we are not using it.
12580 			 */
12581 			DB_CKSUMFLAGS(mp) = 0;
12582 			icmp_unreachable(q, mp,
12583 			    ICMP_SOURCE_ROUTE_FAILED);
12584 			ire_refrele(ire);
12585 			return;
12586 		}
12587 		goto drop_pkt;
12588 	}
12589 
12590 	/* Packet is being forwarded. Turning off hwcksum flag. */
12591 	DB_CKSUMFLAGS(mp) = 0;
12592 	if (ip_g_send_redirects) {
12593 		/*
12594 		 * Check whether the incoming interface and outgoing
12595 		 * interface is part of the same group. If so,
12596 		 * send redirects.
12597 		 *
12598 		 * Check the source address to see if it originated
12599 		 * on the same logical subnet it is going back out on.
12600 		 * If so, we should be able to send it a redirect.
12601 		 * Avoid sending a redirect if the destination
12602 		 * is directly connected (gw_addr == 0),
12603 		 * or if the packet was source routed out this
12604 		 * interface.
12605 		 */
12606 		ipaddr_t src;
12607 		mblk_t	*mp1;
12608 		ire_t	*src_ire = NULL;
12609 
12610 		/*
12611 		 * Check whether ire_rfq and q are from the same ill
12612 		 * or if they are not same, they at least belong
12613 		 * to the same group. If so, send redirects.
12614 		 */
12615 		if ((ire->ire_rfq == q ||
12616 		    (ill_group != NULL && ill_group == ire_group)) &&
12617 		    (ire->ire_gateway_addr != 0) &&
12618 		    !ip_source_routed(ipha)) {
12619 
12620 			src = ipha->ipha_src;
12621 			src_ire = ire_ftable_lookup(src, 0, 0,
12622 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12623 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12624 
12625 			if (src_ire != NULL) {
12626 				/*
12627 				 * The source is directly connected.
12628 				 * Just copy the ip header (which is
12629 				 * in the first mblk)
12630 				 */
12631 				mp1 = copyb(mp);
12632 				if (mp1 != NULL) {
12633 					icmp_send_redirect(WR(q), mp1,
12634 					    ire->ire_gateway_addr);
12635 				}
12636 				ire_refrele(src_ire);
12637 			}
12638 		}
12639 	}
12640 
12641 	dev_q = ire->ire_stq->q_next;
12642 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12643 		BUMP_MIB(&ip_mib, ipInDiscards);
12644 		freemsg(mp);
12645 		ire_refrele(ire);
12646 		return;
12647 	}
12648 
12649 	ip_rput_forward(ire, ipha, mp, ill);
12650 	IRE_REFRELE(ire);
12651 	return;
12652 
12653 drop_pkt:
12654 	ire_refrele(ire);
12655 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12656 	freemsg(mp);
12657 }
12658 
12659 static boolean_t
12660 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12661     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12662 {
12663 	queue_t		*q;
12664 	ire_t		*ire;
12665 	uint16_t	hcksumflags;
12666 
12667 	q = *qp;
12668 	ire = *irep;
12669 
12670 	/*
12671 	 * Clear the indication that this may have hardware
12672 	 * checksum as we are not using it for forwarding.
12673 	 */
12674 	hcksumflags = DB_CKSUMFLAGS(mp);
12675 	DB_CKSUMFLAGS(mp) = 0;
12676 
12677 	/*
12678 	 * Directed broadcast forwarding: if the packet came in over a
12679 	 * different interface then it is routed out over we can forward it.
12680 	 */
12681 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12682 		ire_refrele(ire);
12683 		freemsg(mp);
12684 		BUMP_MIB(&ip_mib, ipInDiscards);
12685 		return (B_TRUE);
12686 	}
12687 	/*
12688 	 * For multicast we have set dst to be INADDR_BROADCAST
12689 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12690 	 * only for broadcast packets.
12691 	 */
12692 	if (!CLASSD(ipha->ipha_dst)) {
12693 		ire_t *new_ire;
12694 		ipif_t *ipif;
12695 		/*
12696 		 * For ill groups, as the switch duplicates broadcasts
12697 		 * across all the ports, we need to filter out and
12698 		 * send up only one copy. There is one copy for every
12699 		 * broadcast address on each ill. Thus, we look for a
12700 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12701 		 * later to see whether this ill is eligible to receive
12702 		 * them or not. ill_nominate_bcast_rcv() nominates only
12703 		 * one set of IREs for receiving.
12704 		 */
12705 
12706 		ipif = ipif_get_next_ipif(NULL, ill);
12707 		if (ipif == NULL) {
12708 			ire_refrele(ire);
12709 			freemsg(mp);
12710 			BUMP_MIB(&ip_mib, ipInDiscards);
12711 			return (B_TRUE);
12712 		}
12713 		new_ire = ire_ctable_lookup(dst, 0, 0,
12714 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12715 		ipif_refrele(ipif);
12716 
12717 		if (new_ire != NULL) {
12718 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12719 				ire_refrele(ire);
12720 				ire_refrele(new_ire);
12721 				freemsg(mp);
12722 				BUMP_MIB(&ip_mib, ipInDiscards);
12723 				return (B_TRUE);
12724 			}
12725 			/*
12726 			 * In the special case of multirouted broadcast
12727 			 * packets, we unconditionally need to "gateway"
12728 			 * them to the appropriate interface here.
12729 			 * In the normal case, this cannot happen, because
12730 			 * there is no broadcast IRE tagged with the
12731 			 * RTF_MULTIRT flag.
12732 			 */
12733 			if (new_ire->ire_flags & RTF_MULTIRT) {
12734 				ire_refrele(new_ire);
12735 				if (ire->ire_rfq != NULL) {
12736 					q = ire->ire_rfq;
12737 					*qp = q;
12738 				}
12739 			} else {
12740 				ire_refrele(ire);
12741 				ire = new_ire;
12742 			}
12743 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12744 			if (!ip_g_forward_directed_bcast) {
12745 				/*
12746 				 * Free the message if
12747 				 * ip_g_forward_directed_bcast is turned
12748 				 * off for non-local broadcast.
12749 				 */
12750 				ire_refrele(ire);
12751 				freemsg(mp);
12752 				BUMP_MIB(&ip_mib, ipInDiscards);
12753 				return (B_TRUE);
12754 			}
12755 		} else {
12756 			/*
12757 			 * This CGTP packet successfully passed the
12758 			 * CGTP filter, but the related CGTP
12759 			 * broadcast IRE has not been found,
12760 			 * meaning that the redundant ipif is
12761 			 * probably down. However, if we discarded
12762 			 * this packet, its duplicate would be
12763 			 * filtered out by the CGTP filter so none
12764 			 * of them would get through. So we keep
12765 			 * going with this one.
12766 			 */
12767 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12768 			if (ire->ire_rfq != NULL) {
12769 				q = ire->ire_rfq;
12770 				*qp = q;
12771 			}
12772 		}
12773 	}
12774 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12775 		/*
12776 		 * Verify that there are not more then one
12777 		 * IRE_BROADCAST with this broadcast address which
12778 		 * has ire_stq set.
12779 		 * TODO: simplify, loop over all IRE's
12780 		 */
12781 		ire_t	*ire1;
12782 		int	num_stq = 0;
12783 		mblk_t	*mp1;
12784 
12785 		/* Find the first one with ire_stq set */
12786 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12787 		for (ire1 = ire; ire1 &&
12788 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12789 		    ire1 = ire1->ire_next)
12790 			;
12791 		if (ire1) {
12792 			ire_refrele(ire);
12793 			ire = ire1;
12794 			IRE_REFHOLD(ire);
12795 		}
12796 
12797 		/* Check if there are additional ones with stq set */
12798 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12799 			if (ire->ire_addr != ire1->ire_addr)
12800 				break;
12801 			if (ire1->ire_stq) {
12802 				num_stq++;
12803 				break;
12804 			}
12805 		}
12806 		rw_exit(&ire->ire_bucket->irb_lock);
12807 		if (num_stq == 1 && ire->ire_stq != NULL) {
12808 			ip1dbg(("ip_rput_process_broadcast: directed "
12809 			    "broadcast to 0x%x\n",
12810 			    ntohl(ire->ire_addr)));
12811 			mp1 = copymsg(mp);
12812 			if (mp1) {
12813 				switch (ipha->ipha_protocol) {
12814 				case IPPROTO_UDP:
12815 					ip_udp_input(q, mp1, ipha, ire, ill);
12816 					break;
12817 				default:
12818 					ip_proto_input(q, mp1, ipha, ire, ill);
12819 					break;
12820 				}
12821 			}
12822 			/*
12823 			 * Adjust ttl to 2 (1+1 - the forward engine
12824 			 * will decrement it by one.
12825 			 */
12826 			if (ip_csum_hdr(ipha)) {
12827 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12828 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12829 				freemsg(mp);
12830 				ire_refrele(ire);
12831 				return (B_TRUE);
12832 			}
12833 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12834 			ipha->ipha_hdr_checksum = 0;
12835 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12836 			ip_rput_process_forward(q, mp, ire, ipha,
12837 			    ill, ll_multicast);
12838 			return (B_TRUE);
12839 		}
12840 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12841 		    ntohl(ire->ire_addr)));
12842 	}
12843 
12844 	*irep = ire;
12845 
12846 	/* Restore any hardware checksum flags */
12847 	DB_CKSUMFLAGS(mp) = hcksumflags;
12848 	return (B_FALSE);
12849 }
12850 
12851 /* ARGSUSED */
12852 static boolean_t
12853 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12854     int *ll_multicast, ipaddr_t *dstp)
12855 {
12856 	/*
12857 	 * Forward packets only if we have joined the allmulti
12858 	 * group on this interface.
12859 	 */
12860 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12861 		int retval;
12862 
12863 		/*
12864 		 * Clear the indication that this may have hardware
12865 		 * checksum as we are not using it.
12866 		 */
12867 		DB_CKSUMFLAGS(mp) = 0;
12868 		retval = ip_mforward(ill, ipha, mp);
12869 		/* ip_mforward updates mib variables if needed */
12870 		/* clear b_prev - used by ip_mroute_decap */
12871 		mp->b_prev = NULL;
12872 
12873 		switch (retval) {
12874 		case 0:
12875 			/*
12876 			 * pkt is okay and arrived on phyint.
12877 			 *
12878 			 * If we are running as a multicast router
12879 			 * we need to see all IGMP and/or PIM packets.
12880 			 */
12881 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12882 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12883 				goto done;
12884 			}
12885 			break;
12886 		case -1:
12887 			/* pkt is mal-formed, toss it */
12888 			goto drop_pkt;
12889 		case 1:
12890 			/* pkt is okay and arrived on a tunnel */
12891 			/*
12892 			 * If we are running a multicast router
12893 			 *  we need to see all igmp packets.
12894 			 */
12895 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12896 				*dstp = INADDR_BROADCAST;
12897 				*ll_multicast = 1;
12898 				return (B_FALSE);
12899 			}
12900 
12901 			goto drop_pkt;
12902 		}
12903 	}
12904 
12905 	ILM_WALKER_HOLD(ill);
12906 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12907 		/*
12908 		 * This might just be caused by the fact that
12909 		 * multiple IP Multicast addresses map to the same
12910 		 * link layer multicast - no need to increment counter!
12911 		 */
12912 		ILM_WALKER_RELE(ill);
12913 		freemsg(mp);
12914 		return (B_TRUE);
12915 	}
12916 	ILM_WALKER_RELE(ill);
12917 done:
12918 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12919 	/*
12920 	 * This assumes the we deliver to all streams for multicast
12921 	 * and broadcast packets.
12922 	 */
12923 	*dstp = INADDR_BROADCAST;
12924 	*ll_multicast = 1;
12925 	return (B_FALSE);
12926 drop_pkt:
12927 	ip2dbg(("ip_rput: drop pkt\n"));
12928 	freemsg(mp);
12929 	return (B_TRUE);
12930 }
12931 
12932 static boolean_t
12933 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12934     int *ll_multicast, mblk_t **mpp)
12935 {
12936 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12937 	boolean_t must_copy = B_FALSE;
12938 	struct iocblk   *iocp;
12939 	ipha_t		*ipha;
12940 
12941 #define	rptr    ((uchar_t *)ipha)
12942 
12943 	first_mp = *first_mpp;
12944 	mp = *mpp;
12945 
12946 	ASSERT(first_mp == mp);
12947 
12948 	/*
12949 	 * if db_ref > 1 then copymsg and free original. Packet may be
12950 	 * changed and do not want other entity who has a reference to this
12951 	 * message to trip over the changes. This is a blind change because
12952 	 * trying to catch all places that might change packet is too
12953 	 * difficult (since it may be a module above this one)
12954 	 *
12955 	 * This corresponds to the non-fast path case. We walk down the full
12956 	 * chain in this case, and check the db_ref count of all the dblks,
12957 	 * and do a copymsg if required. It is possible that the db_ref counts
12958 	 * of the data blocks in the mblk chain can be different.
12959 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12960 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12961 	 * 'snoop' is running.
12962 	 */
12963 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12964 		if (mp1->b_datap->db_ref > 1) {
12965 			must_copy = B_TRUE;
12966 			break;
12967 		}
12968 	}
12969 
12970 	if (must_copy) {
12971 		mp1 = copymsg(mp);
12972 		if (mp1 == NULL) {
12973 			for (mp1 = mp; mp1 != NULL;
12974 			    mp1 = mp1->b_cont) {
12975 				mp1->b_next = NULL;
12976 				mp1->b_prev = NULL;
12977 			}
12978 			freemsg(mp);
12979 			BUMP_MIB(&ip_mib, ipInDiscards);
12980 			return (B_TRUE);
12981 		}
12982 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12983 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12984 			/* Copy b_next - used in M_BREAK messages */
12985 			to_mp->b_next = from_mp->b_next;
12986 			from_mp->b_next = NULL;
12987 			/* Copy b_prev - used by ip_mroute_decap */
12988 			to_mp->b_prev = from_mp->b_prev;
12989 			from_mp->b_prev = NULL;
12990 		}
12991 		*first_mpp = first_mp = mp1;
12992 		freemsg(mp);
12993 		mp = mp1;
12994 		*mpp = mp1;
12995 	}
12996 
12997 	ipha = (ipha_t *)mp->b_rptr;
12998 
12999 	/*
13000 	 * previous code has a case for M_DATA.
13001 	 * We want to check how that happens.
13002 	 */
13003 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13004 	switch (first_mp->b_datap->db_type) {
13005 	case M_PROTO:
13006 	case M_PCPROTO:
13007 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13008 		    DL_UNITDATA_IND) {
13009 			/* Go handle anything other than data elsewhere. */
13010 			ip_rput_dlpi(q, mp);
13011 			return (B_TRUE);
13012 		}
13013 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13014 		/* Ditch the DLPI header. */
13015 		mp1 = mp->b_cont;
13016 		ASSERT(first_mp == mp);
13017 		*first_mpp = mp1;
13018 		freeb(mp);
13019 		*mpp = mp1;
13020 		return (B_FALSE);
13021 	case M_BREAK:
13022 		/*
13023 		 * A packet arrives as M_BREAK following a cycle through
13024 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13025 		 * This is an IP datagram sans lower level header.
13026 		 * M_BREAK are also used to pass back in multicast packets
13027 		 * that are encapsulated with a source route.
13028 		 */
13029 		/* Ditch the M_BREAK mblk */
13030 		mp1 = mp->b_cont;
13031 		ASSERT(first_mp == mp);
13032 		*first_mpp = mp1;
13033 		freeb(mp);
13034 		mp = mp1;
13035 		mp->b_next = NULL;
13036 		*mpp = mp;
13037 		*ll_multicast = 0;
13038 		return (B_FALSE);
13039 	case M_IOCACK:
13040 		ip1dbg(("got iocack "));
13041 		iocp = (struct iocblk *)mp->b_rptr;
13042 		switch (iocp->ioc_cmd) {
13043 		case DL_IOC_HDR_INFO:
13044 			ill = (ill_t *)q->q_ptr;
13045 			ill_fastpath_ack(ill, mp);
13046 			return (B_TRUE);
13047 		case SIOCSTUNPARAM:
13048 		case OSIOCSTUNPARAM:
13049 			/* Go through qwriter_ip */
13050 			break;
13051 		case SIOCGTUNPARAM:
13052 		case OSIOCGTUNPARAM:
13053 			ip_rput_other(NULL, q, mp, NULL);
13054 			return (B_TRUE);
13055 		default:
13056 			putnext(q, mp);
13057 			return (B_TRUE);
13058 		}
13059 		/* FALLTHRU */
13060 	case M_ERROR:
13061 	case M_HANGUP:
13062 		/*
13063 		 * Since this is on the ill stream we unconditionally
13064 		 * bump up the refcount
13065 		 */
13066 		ill_refhold(ill);
13067 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13068 		    B_FALSE);
13069 		return (B_TRUE);
13070 	case M_CTL:
13071 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13072 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13073 			IPHADA_M_CTL)) {
13074 			/*
13075 			 * It's an IPsec accelerated packet.
13076 			 * Make sure that the ill from which we received the
13077 			 * packet has enabled IPsec hardware acceleration.
13078 			 */
13079 			if (!(ill->ill_capabilities &
13080 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13081 				/* IPsec kstats: bean counter */
13082 				freemsg(mp);
13083 				return (B_TRUE);
13084 			}
13085 
13086 			/*
13087 			 * Make mp point to the mblk following the M_CTL,
13088 			 * then process according to type of mp.
13089 			 * After this processing, first_mp will point to
13090 			 * the data-attributes and mp to the pkt following
13091 			 * the M_CTL.
13092 			 */
13093 			mp = first_mp->b_cont;
13094 			if (mp == NULL) {
13095 				freemsg(first_mp);
13096 				return (B_TRUE);
13097 			}
13098 			/*
13099 			 * A Hardware Accelerated packet can only be M_DATA
13100 			 * ESP or AH packet.
13101 			 */
13102 			if (mp->b_datap->db_type != M_DATA) {
13103 				/* non-M_DATA IPsec accelerated packet */
13104 				IPSECHW_DEBUG(IPSECHW_PKT,
13105 				    ("non-M_DATA IPsec accelerated pkt\n"));
13106 				freemsg(first_mp);
13107 				return (B_TRUE);
13108 			}
13109 			ipha = (ipha_t *)mp->b_rptr;
13110 			if (ipha->ipha_protocol != IPPROTO_AH &&
13111 			    ipha->ipha_protocol != IPPROTO_ESP) {
13112 				IPSECHW_DEBUG(IPSECHW_PKT,
13113 				    ("non-M_DATA IPsec accelerated pkt\n"));
13114 				freemsg(first_mp);
13115 				return (B_TRUE);
13116 			}
13117 			*mpp = mp;
13118 			return (B_FALSE);
13119 		}
13120 		putnext(q, mp);
13121 		return (B_TRUE);
13122 	case M_FLUSH:
13123 		if (*mp->b_rptr & FLUSHW) {
13124 			*mp->b_rptr &= ~FLUSHR;
13125 			qreply(q, mp);
13126 			return (B_TRUE);
13127 		}
13128 		freemsg(mp);
13129 		return (B_TRUE);
13130 	case M_IOCNAK:
13131 		ip1dbg(("got iocnak "));
13132 		iocp = (struct iocblk *)mp->b_rptr;
13133 		switch (iocp->ioc_cmd) {
13134 		case DL_IOC_HDR_INFO:
13135 		case SIOCSTUNPARAM:
13136 		case OSIOCSTUNPARAM:
13137 			/*
13138 			 * Since this is on the ill stream we unconditionally
13139 			 * bump up the refcount
13140 			 */
13141 			ill_refhold(ill);
13142 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13143 			    CUR_OP, B_FALSE);
13144 			return (B_TRUE);
13145 		case SIOCGTUNPARAM:
13146 		case OSIOCGTUNPARAM:
13147 			ip_rput_other(NULL, q, mp, NULL);
13148 			return (B_TRUE);
13149 		default:
13150 			break;
13151 		}
13152 		/* FALLTHRU */
13153 	default:
13154 		putnext(q, mp);
13155 		return (B_TRUE);
13156 	}
13157 }
13158 
13159 /* Read side put procedure.  Packets coming from the wire arrive here. */
13160 void
13161 ip_rput(queue_t *q, mblk_t *mp)
13162 {
13163 	ill_t		*ill;
13164 
13165 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13166 
13167 	ill = (ill_t *)q->q_ptr;
13168 
13169 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13170 		union DL_primitives *dl;
13171 
13172 		/*
13173 		 * Things are opening or closing. Only accept DLPI control
13174 		 * messages. In the open case, the ill->ill_ipif has not yet
13175 		 * been created. In the close case, things hanging off the
13176 		 * ill could have been freed already. In either case it
13177 		 * may not be safe to proceed further.
13178 		 */
13179 
13180 		dl = (union DL_primitives *)mp->b_rptr;
13181 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13182 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13183 			/*
13184 			 * Also SIOC[GS]TUN* ioctls can come here.
13185 			 */
13186 			inet_freemsg(mp);
13187 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13188 			    "ip_input_end: q %p (%S)", q, "uninit");
13189 			return;
13190 		}
13191 	}
13192 
13193 	/*
13194 	 * if db_ref > 1 then copymsg and free original. Packet may be
13195 	 * changed and we do not want the other entity who has a reference to
13196 	 * this message to trip over the changes. This is a blind change because
13197 	 * trying to catch all places that might change the packet is too
13198 	 * difficult.
13199 	 *
13200 	 * This corresponds to the fast path case, where we have a chain of
13201 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13202 	 * in the mblk chain. There doesn't seem to be a reason why a device
13203 	 * driver would send up data with varying db_ref counts in the mblk
13204 	 * chain. In any case the Fast path is a private interface, and our
13205 	 * drivers don't do such a thing. Given the above assumption, there is
13206 	 * no need to walk down the entire mblk chain (which could have a
13207 	 * potential performance problem)
13208 	 */
13209 	if (mp->b_datap->db_ref > 1) {
13210 		mblk_t  *mp1;
13211 		boolean_t adjusted = B_FALSE;
13212 		IP_STAT(ip_db_ref);
13213 
13214 		/*
13215 		 * The IP_RECVSLLA option depends on having the link layer
13216 		 * header. First check that:
13217 		 * a> the underlying device is of type ether, since this
13218 		 * option is currently supported only over ethernet.
13219 		 * b> there is enough room to copy over the link layer header.
13220 		 *
13221 		 * Once the checks are done, adjust rptr so that the link layer
13222 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13223 		 * be returned by some non-ethernet drivers but in this case the
13224 		 * second check will fail.
13225 		 */
13226 		if (ill->ill_type == IFT_ETHER &&
13227 		    (mp->b_rptr - mp->b_datap->db_base) >=
13228 		    sizeof (struct ether_header)) {
13229 			mp->b_rptr -= sizeof (struct ether_header);
13230 			adjusted = B_TRUE;
13231 		}
13232 		mp1 = copymsg(mp);
13233 		if (mp1 == NULL) {
13234 			/* Clear b_next - used in M_BREAK messages */
13235 			mp->b_next = NULL;
13236 			/* clear b_prev - used by ip_mroute_decap */
13237 			mp->b_prev = NULL;
13238 			freemsg(mp);
13239 			BUMP_MIB(&ip_mib, ipInDiscards);
13240 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13241 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13242 			return;
13243 		}
13244 		if (adjusted) {
13245 			/*
13246 			 * Copy is done. Restore the pointer in the _new_ mblk
13247 			 */
13248 			mp1->b_rptr += sizeof (struct ether_header);
13249 		}
13250 		/* Copy b_next - used in M_BREAK messages */
13251 		mp1->b_next = mp->b_next;
13252 		mp->b_next = NULL;
13253 		/* Copy b_prev - used by ip_mroute_decap */
13254 		mp1->b_prev = mp->b_prev;
13255 		mp->b_prev = NULL;
13256 		freemsg(mp);
13257 		mp = mp1;
13258 	}
13259 
13260 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13261 	    "ip_rput_end: q %p (%S)", q, "end");
13262 
13263 	ip_input(ill, NULL, mp, 0);
13264 }
13265 
13266 /*
13267  * Direct read side procedure capable of dealing with chains. GLDv3 based
13268  * drivers call this function directly with mblk chains while STREAMS
13269  * read side procedure ip_rput() calls this for single packet with ip_ring
13270  * set to NULL to process one packet at a time.
13271  *
13272  * The ill will always be valid if this function is called directly from
13273  * the driver.
13274  */
13275 /*ARGSUSED*/
13276 void
13277 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13278 {
13279 	ipaddr_t		dst;
13280 	ire_t			*ire;
13281 	ipha_t			*ipha;
13282 	uint_t			pkt_len;
13283 	ssize_t			len;
13284 	uint_t			opt_len;
13285 	int			ll_multicast;
13286 	int			cgtp_flt_pkt;
13287 	queue_t			*q = ill->ill_rq;
13288 	squeue_t		*curr_sqp = NULL;
13289 	mblk_t 			*head = NULL;
13290 	mblk_t			*tail = NULL;
13291 	mblk_t			*first_mp;
13292 	mblk_t 			*mp;
13293 	int			cnt = 0;
13294 
13295 	ASSERT(mp_chain != NULL);
13296 	ASSERT(ill != NULL);
13297 
13298 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13299 
13300 #define	rptr	((uchar_t *)ipha)
13301 
13302 	while (mp_chain != NULL) {
13303 		first_mp = mp = mp_chain;
13304 		mp_chain = mp_chain->b_next;
13305 		mp->b_next = NULL;
13306 		ll_multicast = 0;
13307 		ire = NULL;
13308 
13309 		/*
13310 		 * ip_input fast path
13311 		 */
13312 
13313 		/* mblk type is not M_DATA */
13314 		if (mp->b_datap->db_type != M_DATA) {
13315 			if (ip_rput_process_notdata(q, &first_mp, ill,
13316 			    &ll_multicast, &mp))
13317 				continue;
13318 		}
13319 
13320 		ASSERT(mp->b_datap->db_type == M_DATA);
13321 		ASSERT(mp->b_datap->db_ref == 1);
13322 
13323 		/*
13324 		 * Invoke the CGTP (multirouting) filtering module to process
13325 		 * the incoming packet. Packets identified as duplicates
13326 		 * must be discarded. Filtering is active only if the
13327 		 * the ip_cgtp_filter ndd variable is non-zero.
13328 		 */
13329 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13330 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13331 			cgtp_flt_pkt =
13332 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13333 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13334 				freemsg(first_mp);
13335 				continue;
13336 			}
13337 		}
13338 
13339 		ipha = (ipha_t *)mp->b_rptr;
13340 		len = mp->b_wptr - rptr;
13341 
13342 		BUMP_MIB(&ip_mib, ipInReceives);
13343 
13344 		/*
13345 		 * IP header ptr not aligned?
13346 		 * OR IP header not complete in first mblk
13347 		 */
13348 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13349 			if (!ip_check_and_align_header(q, mp))
13350 				continue;
13351 			ipha = (ipha_t *)mp->b_rptr;
13352 			len = mp->b_wptr - rptr;
13353 		}
13354 
13355 		/* multiple mblk or too short */
13356 		pkt_len = ntohs(ipha->ipha_length);
13357 		len -= pkt_len;
13358 		if (len != 0) {
13359 			/*
13360 			 * Make sure we have data length consistent
13361 			 * with the IP header.
13362 			 */
13363 			if (mp->b_cont == NULL) {
13364 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13365 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13366 					ip2dbg(("ip_input: drop pkt\n"));
13367 					freemsg(mp);
13368 					continue;
13369 				}
13370 				mp->b_wptr = rptr + pkt_len;
13371 			} else if (len += msgdsize(mp->b_cont)) {
13372 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13373 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13374 					ip2dbg(("ip_input: drop pkt\n"));
13375 					freemsg(mp);
13376 					continue;
13377 				}
13378 				(void) adjmsg(mp, -len);
13379 				IP_STAT(ip_multimblk3);
13380 			}
13381 		}
13382 
13383 		if (ip_loopback_src_or_dst(ipha, ill)) {
13384 			ip2dbg(("ip_input: drop pkt\n"));
13385 			freemsg(mp);
13386 			continue;
13387 		}
13388 
13389 		opt_len = ipha->ipha_version_and_hdr_length -
13390 		    IP_SIMPLE_HDR_VERSION;
13391 		/* IP version bad or there are IP options */
13392 		if (opt_len) {
13393 			if (len != 0)
13394 				IP_STAT(ip_multimblk4);
13395 			else
13396 				IP_STAT(ip_ipoptions);
13397 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13398 				continue;
13399 		} else {
13400 			dst = ipha->ipha_dst;
13401 		}
13402 
13403 		/*
13404 		 * If rsvpd is running, let RSVP daemon handle its processing
13405 		 * and forwarding of RSVP multicast/unicast packets.
13406 		 * If rsvpd is not running but mrouted is running, RSVP
13407 		 * multicast packets are forwarded as multicast traffic
13408 		 * and RSVP unicast packets are forwarded by unicast router.
13409 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13410 		 * packets are not forwarded, but the unicast packets are
13411 		 * forwarded like unicast traffic.
13412 		 */
13413 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13414 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13415 			/* RSVP packet and rsvpd running. Treat as ours */
13416 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13417 			/*
13418 			 * This assumes that we deliver to all streams for
13419 			 * multicast and broadcast packets.
13420 			 * We have to force ll_multicast to 1 to handle the
13421 			 * M_DATA messages passed in from ip_mroute_decap.
13422 			 */
13423 			dst = INADDR_BROADCAST;
13424 			ll_multicast = 1;
13425 		} else if (CLASSD(dst)) {
13426 			/* packet is multicast */
13427 			mp->b_next = NULL;
13428 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13429 			    &ll_multicast, &dst))
13430 				continue;
13431 		}
13432 
13433 
13434 		/*
13435 		 * Check if the packet is coming from the Mobile IP
13436 		 * forward tunnel interface
13437 		 */
13438 		if (ill->ill_srcif_refcnt > 0) {
13439 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13440 			    NULL, ill, MATCH_IRE_TYPE);
13441 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13442 			    ire->ire_ipif->ipif_net_type ==
13443 			    IRE_IF_RESOLVER) {
13444 				/* We need to resolve the link layer info */
13445 				ire_refrele(ire);
13446 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13447 				    ll_multicast, dst);
13448 				continue;
13449 			}
13450 		}
13451 
13452 		if (ire == NULL)
13453 			ire = ire_cache_lookup(dst, ALL_ZONES);
13454 
13455 		/*
13456 		 * If mipagent is running and reverse tunnel is created as per
13457 		 * mobile node request, then any packet coming through the
13458 		 * incoming interface from the mobile-node, should be reverse
13459 		 * tunneled to it's home agent except those that are destined
13460 		 * to foreign agent only.
13461 		 * This needs source address based ire lookup. The routing
13462 		 * entries for source address based lookup are only created by
13463 		 * mipagent program only when a reverse tunnel is created.
13464 		 * Reference : RFC2002, RFC2344
13465 		 */
13466 		if (ill->ill_mrtun_refcnt > 0) {
13467 			ipaddr_t	srcaddr;
13468 			ire_t		*tmp_ire;
13469 
13470 			tmp_ire = ire;	/* Save, we might need it later */
13471 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13472 			    ire->ire_type != IRE_BROADCAST)) {
13473 				srcaddr = ipha->ipha_src;
13474 				ire = ire_mrtun_lookup(srcaddr, ill);
13475 				if (ire != NULL) {
13476 					/*
13477 					 * Should not be getting iphada packet
13478 					 * here. we should only get those for
13479 					 * IRE_LOCAL traffic, excluded above.
13480 					 * Fail-safe (drop packet) in the event
13481 					 * hardware is misbehaving.
13482 					 */
13483 					if (first_mp != mp) {
13484 						/* IPsec KSTATS: beancount me */
13485 						freemsg(first_mp);
13486 					} else {
13487 						/*
13488 						 * This packet must be forwarded
13489 						 * to Reverse Tunnel
13490 						 */
13491 						ip_mrtun_forward(ire, ill, mp);
13492 					}
13493 					ire_refrele(ire);
13494 					if (tmp_ire != NULL)
13495 						ire_refrele(tmp_ire);
13496 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13497 					    "ip_input_end: q %p (%S)",
13498 					    q, "uninit");
13499 					continue;
13500 				}
13501 			}
13502 			/*
13503 			 * If this packet is from a non-mobilenode  or a
13504 			 * mobile-node which does not request reverse
13505 			 * tunnel service
13506 			 */
13507 			ire = tmp_ire;
13508 		}
13509 
13510 
13511 		/*
13512 		 * If we reach here that means the incoming packet satisfies
13513 		 * one of the following conditions:
13514 		 *   - packet is from a mobile node which does not request
13515 		 *	reverse tunnel
13516 		 *   - packet is from a non-mobile node, which is the most
13517 		 *	common case
13518 		 *   - packet is from a reverse tunnel enabled mobile node
13519 		 *	and destined to foreign agent only
13520 		 */
13521 
13522 		if (ire == NULL) {
13523 			/*
13524 			 * No IRE for this destination, so it can't be for us.
13525 			 * Unless we are forwarding, drop the packet.
13526 			 * We have to let source routed packets through
13527 			 * since we don't yet know if they are 'ping -l'
13528 			 * packets i.e. if they will go out over the
13529 			 * same interface as they came in on.
13530 			 */
13531 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13532 			continue;
13533 		}
13534 
13535 		/*
13536 		 * Broadcast IRE may indicate either broadcast or
13537 		 * multicast packet
13538 		 */
13539 		if (ire->ire_type == IRE_BROADCAST) {
13540 			/*
13541 			 * Skip broadcast checks if packet is UDP multicast;
13542 			 * we'd rather not enter ip_rput_process_broadcast()
13543 			 * unless the packet is broadcast for real, since
13544 			 * that routine is a no-op for multicast.
13545 			 */
13546 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
13547 			    !CLASSD(ipha->ipha_dst)) &&
13548 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13549 			    dst, cgtp_flt_pkt, ll_multicast)) {
13550 				continue;
13551 			}
13552 		} else if (ire->ire_stq != NULL) {
13553 			/* fowarding? */
13554 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13555 			    ll_multicast);
13556 			continue;
13557 		}
13558 
13559 		/* packet not for us */
13560 		if (ire->ire_rfq != q) {
13561 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13562 				continue;
13563 			}
13564 		}
13565 
13566 		switch (ipha->ipha_protocol) {
13567 		case IPPROTO_TCP:
13568 			ASSERT(first_mp == mp);
13569 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13570 				mp, 0, q, ip_ring)) != NULL) {
13571 				if (curr_sqp == NULL) {
13572 					curr_sqp = GET_SQUEUE(mp);
13573 					ASSERT(cnt == 0);
13574 					cnt++;
13575 					head = tail = mp;
13576 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13577 					ASSERT(tail != NULL);
13578 					cnt++;
13579 					tail->b_next = mp;
13580 					tail = mp;
13581 				} else {
13582 					/*
13583 					 * A different squeue. Send the
13584 					 * chain for the previous squeue on
13585 					 * its way. This shouldn't happen
13586 					 * often unless interrupt binding
13587 					 * changes.
13588 					 */
13589 					IP_STAT(ip_input_multi_squeue);
13590 					squeue_enter_chain(curr_sqp, head,
13591 					    tail, cnt, SQTAG_IP_INPUT);
13592 					curr_sqp = GET_SQUEUE(mp);
13593 					head = mp;
13594 					tail = mp;
13595 					cnt = 1;
13596 				}
13597 			}
13598 			IRE_REFRELE(ire);
13599 			continue;
13600 		case IPPROTO_UDP:
13601 			ASSERT(first_mp == mp);
13602 			ip_udp_input(q, mp, ipha, ire, ill);
13603 			IRE_REFRELE(ire);
13604 			continue;
13605 		case IPPROTO_SCTP:
13606 			ASSERT(first_mp == mp);
13607 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13608 			    q, dst);
13609 			continue;
13610 		default:
13611 			ip_proto_input(q, first_mp, ipha, ire, ill);
13612 			IRE_REFRELE(ire);
13613 			continue;
13614 		}
13615 	}
13616 
13617 	if (head != NULL)
13618 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13619 
13620 	/*
13621 	 * This code is there just to make netperf/ttcp look good.
13622 	 *
13623 	 * Its possible that after being in polling mode (and having cleared
13624 	 * the backlog), squeues have turned the interrupt frequency higher
13625 	 * to improve latency at the expense of more CPU utilization (less
13626 	 * packets per interrupts or more number of interrupts). Workloads
13627 	 * like ttcp/netperf do manage to tickle polling once in a while
13628 	 * but for the remaining time, stay in higher interrupt mode since
13629 	 * their packet arrival rate is pretty uniform and this shows up
13630 	 * as higher CPU utilization. Since people care about CPU utilization
13631 	 * while running netperf/ttcp, turn the interrupt frequency back to
13632 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13633 	 */
13634 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13635 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13636 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13637 			ip_ring->rr_blank(ip_ring->rr_handle,
13638 			    ip_ring->rr_normal_blank_time,
13639 			    ip_ring->rr_normal_pkt_cnt);
13640 		}
13641 	}
13642 
13643 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13644 	    "ip_input_end: q %p (%S)", q, "end");
13645 #undef	rptr
13646 }
13647 
13648 static void
13649 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13650     t_uscalar_t err)
13651 {
13652 	if (dl_err == DL_SYSERR) {
13653 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13654 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13655 		    ill->ill_name, dlpi_prim_str(prim), err);
13656 		return;
13657 	}
13658 
13659 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13660 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13661 	    dlpi_err_str(dl_err));
13662 }
13663 
13664 /*
13665  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13666  * than DL_UNITDATA_IND messages. If we need to process this message
13667  * exclusively, we call qwriter_ip, in which case we also need to call
13668  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13669  */
13670 void
13671 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13672 {
13673 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13674 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13675 	ill_t		*ill;
13676 
13677 	ip1dbg(("ip_rput_dlpi"));
13678 	ill = (ill_t *)q->q_ptr;
13679 	switch (dloa->dl_primitive) {
13680 	case DL_ERROR_ACK:
13681 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13682 		    "%s (0x%x), unix %u\n", ill->ill_name,
13683 		    dlpi_prim_str(dlea->dl_error_primitive),
13684 		    dlea->dl_error_primitive,
13685 		    dlpi_err_str(dlea->dl_errno),
13686 		    dlea->dl_errno,
13687 		    dlea->dl_unix_errno));
13688 		switch (dlea->dl_error_primitive) {
13689 		case DL_NOTIFY_REQ:
13690 		case DL_UNBIND_REQ:
13691 		case DL_ATTACH_REQ:
13692 		case DL_DETACH_REQ:
13693 		case DL_INFO_REQ:
13694 		case DL_BIND_REQ:
13695 		case DL_ENABMULTI_REQ:
13696 		case DL_PHYS_ADDR_REQ:
13697 		case DL_CAPABILITY_REQ:
13698 		case DL_CONTROL_REQ:
13699 			/*
13700 			 * Refhold the ill to match qwriter_ip which does a
13701 			 * refrele. Since this is on the ill stream we
13702 			 * unconditionally bump up the refcount without
13703 			 * checking for ILL_CAN_LOOKUP
13704 			 */
13705 			ill_refhold(ill);
13706 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13707 			    CUR_OP, B_FALSE);
13708 			return;
13709 		case DL_DISABMULTI_REQ:
13710 			freemsg(mp);	/* Don't want to pass this up */
13711 			return;
13712 		default:
13713 			break;
13714 		}
13715 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13716 		    dlea->dl_errno, dlea->dl_unix_errno);
13717 		freemsg(mp);
13718 		return;
13719 	case DL_INFO_ACK:
13720 	case DL_BIND_ACK:
13721 	case DL_PHYS_ADDR_ACK:
13722 	case DL_NOTIFY_ACK:
13723 	case DL_CAPABILITY_ACK:
13724 	case DL_CONTROL_ACK:
13725 		/*
13726 		 * Refhold the ill to match qwriter_ip which does a refrele
13727 		 * Since this is on the ill stream we unconditionally
13728 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13729 		 */
13730 		ill_refhold(ill);
13731 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13732 		    CUR_OP, B_FALSE);
13733 		return;
13734 	case DL_NOTIFY_IND:
13735 		ill_refhold(ill);
13736 		/*
13737 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13738 		 * relation to the current ioctl in progress (if any). Hence we
13739 		 * pass in NEW_OP in this case.
13740 		 */
13741 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13742 		    NEW_OP, B_FALSE);
13743 		return;
13744 	case DL_OK_ACK:
13745 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13746 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13747 		switch (dloa->dl_correct_primitive) {
13748 		case DL_UNBIND_REQ:
13749 			mutex_enter(&ill->ill_lock);
13750 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13751 			cv_signal(&ill->ill_cv);
13752 			mutex_exit(&ill->ill_lock);
13753 			/* FALLTHRU */
13754 		case DL_ATTACH_REQ:
13755 		case DL_DETACH_REQ:
13756 			/*
13757 			 * Refhold the ill to match qwriter_ip which does a
13758 			 * refrele. Since this is on the ill stream we
13759 			 * unconditionally bump up the refcount
13760 			 */
13761 			ill_refhold(ill);
13762 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13763 			    CUR_OP, B_FALSE);
13764 			return;
13765 		case DL_ENABMULTI_REQ:
13766 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13767 				ill->ill_dlpi_multicast_state = IDMS_OK;
13768 			break;
13769 
13770 		}
13771 		break;
13772 	default:
13773 		break;
13774 	}
13775 	freemsg(mp);
13776 }
13777 
13778 /*
13779  * Handling of DLPI messages that require exclusive access to the ipsq.
13780  *
13781  * Need to do ill_pending_mp_release on ioctl completion, which could
13782  * happen here. (along with mi_copy_done)
13783  */
13784 /* ARGSUSED */
13785 static void
13786 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13787 {
13788 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13789 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13790 	int		err = 0;
13791 	ill_t		*ill;
13792 	ipif_t		*ipif = NULL;
13793 	mblk_t		*mp1 = NULL;
13794 	conn_t		*connp = NULL;
13795 	t_uscalar_t	physaddr_req;
13796 	mblk_t		*mp_hw;
13797 	union DL_primitives *dlp;
13798 	boolean_t	success;
13799 	boolean_t	ioctl_aborted = B_FALSE;
13800 	boolean_t	log = B_TRUE;
13801 
13802 	ip1dbg(("ip_rput_dlpi_writer .."));
13803 	ill = (ill_t *)q->q_ptr;
13804 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13805 
13806 	ASSERT(IAM_WRITER_ILL(ill));
13807 
13808 	/*
13809 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13810 	 * both are null or non-null. However we can assert that only
13811 	 * after grabbing the ipsq_lock. So we don't make any assertion
13812 	 * here and in other places in the code.
13813 	 */
13814 	ipif = ipsq->ipsq_pending_ipif;
13815 	/*
13816 	 * The current ioctl could have been aborted by the user and a new
13817 	 * ioctl to bring up another ill could have started. We could still
13818 	 * get a response from the driver later.
13819 	 */
13820 	if (ipif != NULL && ipif->ipif_ill != ill)
13821 		ioctl_aborted = B_TRUE;
13822 
13823 	switch (dloa->dl_primitive) {
13824 	case DL_ERROR_ACK:
13825 		switch (dlea->dl_error_primitive) {
13826 		case DL_UNBIND_REQ:
13827 		case DL_ATTACH_REQ:
13828 		case DL_DETACH_REQ:
13829 		case DL_INFO_REQ:
13830 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13831 			break;
13832 		case DL_NOTIFY_REQ:
13833 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13834 			log = B_FALSE;
13835 			break;
13836 		case DL_PHYS_ADDR_REQ:
13837 			/*
13838 			 * For IPv6 only, there are two additional
13839 			 * phys_addr_req's sent to the driver to get the
13840 			 * IPv6 token and lla. This allows IP to acquire
13841 			 * the hardware address format for a given interface
13842 			 * without having built in knowledge of the hardware
13843 			 * address. ill_phys_addr_pend keeps track of the last
13844 			 * DL_PAR sent so we know which response we are
13845 			 * dealing with. ill_dlpi_done will update
13846 			 * ill_phys_addr_pend when it sends the next req.
13847 			 * We don't complete the IOCTL until all three DL_PARs
13848 			 * have been attempted, so set *_len to 0 and break.
13849 			 */
13850 			physaddr_req = ill->ill_phys_addr_pend;
13851 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13852 			if (physaddr_req == DL_IPV6_TOKEN) {
13853 				ill->ill_token_length = 0;
13854 				log = B_FALSE;
13855 				break;
13856 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13857 				ill->ill_nd_lla_len = 0;
13858 				log = B_FALSE;
13859 				break;
13860 			}
13861 			/*
13862 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13863 			 * We presumably have an IOCTL hanging out waiting
13864 			 * for completion. Find it and complete the IOCTL
13865 			 * with the error noted.
13866 			 * However, ill_dl_phys was called on an ill queue
13867 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13868 			 * set. But the ioctl is known to be pending on ill_wq.
13869 			 */
13870 			if (!ill->ill_ifname_pending)
13871 				break;
13872 			ill->ill_ifname_pending = 0;
13873 			if (!ioctl_aborted)
13874 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13875 			if (mp1 != NULL) {
13876 				/*
13877 				 * This operation (SIOCSLIFNAME) must have
13878 				 * happened on the ill. Assert there is no conn
13879 				 */
13880 				ASSERT(connp == NULL);
13881 				q = ill->ill_wq;
13882 			}
13883 			break;
13884 		case DL_BIND_REQ:
13885 			ill_dlpi_done(ill, DL_BIND_REQ);
13886 			if (ill->ill_ifname_pending)
13887 				break;
13888 			/*
13889 			 * Something went wrong with the bind.  We presumably
13890 			 * have an IOCTL hanging out waiting for completion.
13891 			 * Find it, take down the interface that was coming
13892 			 * up, and complete the IOCTL with the error noted.
13893 			 */
13894 			if (!ioctl_aborted)
13895 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13896 			if (mp1 != NULL) {
13897 				/*
13898 				 * This operation (SIOCSLIFFLAGS) must have
13899 				 * happened from a conn.
13900 				 */
13901 				ASSERT(connp != NULL);
13902 				q = CONNP_TO_WQ(connp);
13903 				if (ill->ill_move_in_progress) {
13904 					ILL_CLEAR_MOVE(ill);
13905 				}
13906 				(void) ipif_down(ipif, NULL, NULL);
13907 				/* error is set below the switch */
13908 			}
13909 			break;
13910 		case DL_ENABMULTI_REQ:
13911 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13912 
13913 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13914 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13915 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13916 				ipif_t *ipif;
13917 
13918 				log = B_FALSE;
13919 				printf("ip: joining multicasts failed (%d)"
13920 				    " on %s - will use link layer "
13921 				    "broadcasts for multicast\n",
13922 				    dlea->dl_errno, ill->ill_name);
13923 
13924 				/*
13925 				 * Set up the multicast mapping alone.
13926 				 * writer, so ok to access ill->ill_ipif
13927 				 * without any lock.
13928 				 */
13929 				ipif = ill->ill_ipif;
13930 				mutex_enter(&ill->ill_phyint->phyint_lock);
13931 				ill->ill_phyint->phyint_flags |=
13932 				    PHYI_MULTI_BCAST;
13933 				mutex_exit(&ill->ill_phyint->phyint_lock);
13934 
13935 				if (!ill->ill_isv6) {
13936 					(void) ipif_arp_setup_multicast(ipif,
13937 					    NULL);
13938 				} else {
13939 					(void) ipif_ndp_setup_multicast(ipif,
13940 					    NULL);
13941 				}
13942 			}
13943 			freemsg(mp);	/* Don't want to pass this up */
13944 			return;
13945 		case DL_CAPABILITY_REQ:
13946 		case DL_CONTROL_REQ:
13947 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13948 			    "DL_CAPABILITY/CONTROL REQ\n"));
13949 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13950 			ill->ill_capab_state = IDMS_FAILED;
13951 			freemsg(mp);
13952 			return;
13953 		}
13954 		/*
13955 		 * Note the error for IOCTL completion (mp1 is set when
13956 		 * ready to complete ioctl). If ill_ifname_pending_err is
13957 		 * set, an error occured during plumbing (ill_ifname_pending),
13958 		 * so we want to report that error.
13959 		 *
13960 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13961 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13962 		 * expected to get errack'd if the driver doesn't support
13963 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13964 		 * if these error conditions are encountered.
13965 		 */
13966 		if (mp1 != NULL) {
13967 			if (ill->ill_ifname_pending_err != 0)  {
13968 				err = ill->ill_ifname_pending_err;
13969 				ill->ill_ifname_pending_err = 0;
13970 			} else {
13971 				err = dlea->dl_unix_errno ?
13972 				    dlea->dl_unix_errno : ENXIO;
13973 			}
13974 		/*
13975 		 * If we're plumbing an interface and an error hasn't already
13976 		 * been saved, set ill_ifname_pending_err to the error passed
13977 		 * up. Ignore the error if log is B_FALSE (see comment above).
13978 		 */
13979 		} else if (log && ill->ill_ifname_pending &&
13980 		    ill->ill_ifname_pending_err == 0) {
13981 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13982 			dlea->dl_unix_errno : ENXIO;
13983 		}
13984 
13985 		if (log)
13986 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13987 			    dlea->dl_errno, dlea->dl_unix_errno);
13988 		break;
13989 	case DL_CAPABILITY_ACK: {
13990 		boolean_t reneg_flag = B_FALSE;
13991 		/* Call a routine to handle this one. */
13992 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13993 		/*
13994 		 * Check if the ACK is due to renegotiation case since we
13995 		 * will need to send a new CAPABILITY_REQ later.
13996 		 */
13997 		if (ill->ill_capab_state == IDMS_RENEG) {
13998 			/* This is the ack for a renogiation case */
13999 			reneg_flag = B_TRUE;
14000 			ill->ill_capab_state = IDMS_UNKNOWN;
14001 		}
14002 		ill_capability_ack(ill, mp);
14003 		if (reneg_flag)
14004 			ill_capability_probe(ill);
14005 		break;
14006 	}
14007 	case DL_CONTROL_ACK:
14008 		/* We treat all of these as "fire and forget" */
14009 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14010 		break;
14011 	case DL_INFO_ACK:
14012 		/* Call a routine to handle this one. */
14013 		ill_dlpi_done(ill, DL_INFO_REQ);
14014 		ip_ll_subnet_defaults(ill, mp);
14015 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14016 		return;
14017 	case DL_BIND_ACK:
14018 		/*
14019 		 * We should have an IOCTL waiting on this unless
14020 		 * sent by ill_dl_phys, in which case just return
14021 		 */
14022 		ill_dlpi_done(ill, DL_BIND_REQ);
14023 		if (ill->ill_ifname_pending)
14024 			break;
14025 
14026 		if (!ioctl_aborted)
14027 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14028 		if (mp1 == NULL)
14029 			break;
14030 		ASSERT(connp != NULL);
14031 		q = CONNP_TO_WQ(connp);
14032 
14033 		/*
14034 		 * We are exclusive. So nothing can change even after
14035 		 * we get the pending mp. If need be we can put it back
14036 		 * and restart, as in calling ipif_arp_up()  below.
14037 		 */
14038 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14039 
14040 		mutex_enter(&ill->ill_lock);
14041 		ill->ill_dl_up = 1;
14042 		mutex_exit(&ill->ill_lock);
14043 
14044 		/*
14045 		 * Now bring up the resolver, when that is
14046 		 * done we'll create IREs and we are done.
14047 		 */
14048 		if (ill->ill_isv6) {
14049 			/*
14050 			 * v6 interfaces.
14051 			 * Unlike ARP which has to do another bind
14052 			 * and attach, once we get here we are
14053 			 * done withh NDP. Except in the case of
14054 			 * ILLF_XRESOLV, in which case we send an
14055 			 * AR_INTERFACE_UP to the external resolver.
14056 			 * If all goes well, the ioctl will complete
14057 			 * in ip_rput(). If there's an error, we
14058 			 * complete it here.
14059 			 */
14060 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14061 			    B_FALSE);
14062 			if (err == 0) {
14063 				if (ill->ill_flags & ILLF_XRESOLV) {
14064 					mutex_enter(&connp->conn_lock);
14065 					mutex_enter(&ill->ill_lock);
14066 					success = ipsq_pending_mp_add(
14067 					    connp, ipif, q, mp1, 0);
14068 					mutex_exit(&ill->ill_lock);
14069 					mutex_exit(&connp->conn_lock);
14070 					if (success) {
14071 						err = ipif_resolver_up(ipif,
14072 						    B_FALSE);
14073 						if (err == EINPROGRESS) {
14074 							freemsg(mp);
14075 							return;
14076 						}
14077 						ASSERT(err != 0);
14078 						mp1 = ipsq_pending_mp_get(ipsq,
14079 						    &connp);
14080 						ASSERT(mp1 != NULL);
14081 					} else {
14082 						/* conn has started closing */
14083 						err = EINTR;
14084 					}
14085 				} else { /* Non XRESOLV interface */
14086 					err = ipif_up_done_v6(ipif);
14087 				}
14088 			}
14089 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14090 			/*
14091 			 * ARP and other v4 external resolvers.
14092 			 * Leave the pending mblk intact so that
14093 			 * the ioctl completes in ip_rput().
14094 			 */
14095 			mutex_enter(&connp->conn_lock);
14096 			mutex_enter(&ill->ill_lock);
14097 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14098 			mutex_exit(&ill->ill_lock);
14099 			mutex_exit(&connp->conn_lock);
14100 			if (success) {
14101 				err = ipif_resolver_up(ipif, B_FALSE);
14102 				if (err == EINPROGRESS) {
14103 					freemsg(mp);
14104 					return;
14105 				}
14106 				ASSERT(err != 0);
14107 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14108 			} else {
14109 				/* The conn has started closing */
14110 				err = EINTR;
14111 			}
14112 		} else {
14113 			/*
14114 			 * This one is complete. Reply to pending ioctl.
14115 			 */
14116 			err = ipif_up_done(ipif);
14117 		}
14118 
14119 		if ((err == 0) && (ill->ill_up_ipifs)) {
14120 			err = ill_up_ipifs(ill, q, mp1);
14121 			if (err == EINPROGRESS) {
14122 				freemsg(mp);
14123 				return;
14124 			}
14125 		}
14126 
14127 		if (ill->ill_up_ipifs) {
14128 			ill_group_cleanup(ill);
14129 		}
14130 
14131 		break;
14132 	case DL_NOTIFY_IND: {
14133 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14134 		ire_t *ire;
14135 		boolean_t need_ire_walk_v4 = B_FALSE;
14136 		boolean_t need_ire_walk_v6 = B_FALSE;
14137 
14138 		/*
14139 		 * Change the address everywhere we need to.
14140 		 * What we're getting here is a link-level addr or phys addr.
14141 		 * The new addr is at notify + notify->dl_addr_offset
14142 		 * The address length is notify->dl_addr_length;
14143 		 */
14144 		switch (notify->dl_notification) {
14145 		case DL_NOTE_PHYS_ADDR:
14146 			mp_hw = copyb(mp);
14147 			if (mp_hw == NULL) {
14148 				err = ENOMEM;
14149 				break;
14150 			}
14151 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14152 			/*
14153 			 * We currently don't support changing
14154 			 * the token via DL_NOTIFY_IND.
14155 			 * When we do support it, we have to consider
14156 			 * what the implications are with respect to
14157 			 * the token and the link local address.
14158 			 */
14159 			mutex_enter(&ill->ill_lock);
14160 			if (dlp->notify_ind.dl_data ==
14161 			    DL_IPV6_LINK_LAYER_ADDR) {
14162 				if (ill->ill_nd_lla_mp != NULL)
14163 					freemsg(ill->ill_nd_lla_mp);
14164 				ill->ill_nd_lla_mp = mp_hw;
14165 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14166 				    dlp->notify_ind.dl_addr_offset;
14167 				ill->ill_nd_lla_len =
14168 				    dlp->notify_ind.dl_addr_length -
14169 				    ABS(ill->ill_sap_length);
14170 				mutex_exit(&ill->ill_lock);
14171 				break;
14172 			} else if (dlp->notify_ind.dl_data ==
14173 			    DL_CURR_PHYS_ADDR) {
14174 				if (ill->ill_phys_addr_mp != NULL)
14175 					freemsg(ill->ill_phys_addr_mp);
14176 				ill->ill_phys_addr_mp = mp_hw;
14177 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14178 				    dlp->notify_ind.dl_addr_offset;
14179 				ill->ill_phys_addr_length =
14180 				    dlp->notify_ind.dl_addr_length -
14181 				    ABS(ill->ill_sap_length);
14182 				if (ill->ill_isv6 &&
14183 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14184 					if (ill->ill_nd_lla_mp != NULL)
14185 						freemsg(ill->ill_nd_lla_mp);
14186 					ill->ill_nd_lla_mp = copyb(mp_hw);
14187 					ill->ill_nd_lla = (uchar_t *)
14188 					    ill->ill_nd_lla_mp->b_rptr +
14189 					    dlp->notify_ind.dl_addr_offset;
14190 					ill->ill_nd_lla_len =
14191 					    ill->ill_phys_addr_length;
14192 				}
14193 			}
14194 			mutex_exit(&ill->ill_lock);
14195 			/*
14196 			 * Send out gratuitous arp request for our new
14197 			 * hardware address.
14198 			 */
14199 			for (ipif = ill->ill_ipif; ipif != NULL;
14200 			    ipif = ipif->ipif_next) {
14201 				if (!(ipif->ipif_flags & IPIF_UP))
14202 					continue;
14203 				if (ill->ill_isv6) {
14204 					ipif_ndp_down(ipif);
14205 					/*
14206 					 * Set B_TRUE to enable
14207 					 * ipif_ndp_up() to send out
14208 					 * unsolicited advertisements.
14209 					 */
14210 					err = ipif_ndp_up(ipif,
14211 					    &ipif->ipif_v6lcl_addr,
14212 					    B_TRUE);
14213 					if (err) {
14214 						ip1dbg((
14215 						    "ip_rput_dlpi_writer: "
14216 						    "Failed to update ndp "
14217 						    "err %d\n", err));
14218 					}
14219 				} else {
14220 					/*
14221 					 * IPv4 ARP case
14222 					 *
14223 					 * Set B_TRUE, as we only want
14224 					 * ipif_resolver_up to send an
14225 					 * AR_ENTRY_ADD request up to
14226 					 * ARP.
14227 					 */
14228 					err = ipif_resolver_up(ipif,
14229 					    B_TRUE);
14230 					if (err) {
14231 						ip1dbg((
14232 						    "ip_rput_dlpi_writer: "
14233 						    "Failed to update arp "
14234 						    "err %d\n", err));
14235 					}
14236 				}
14237 			}
14238 			/*
14239 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14240 			 * case so that all old fastpath information can be
14241 			 * purged from IRE caches.
14242 			 */
14243 		/* FALLTHRU */
14244 		case DL_NOTE_FASTPATH_FLUSH:
14245 			/*
14246 			 * Any fastpath probe sent henceforth will get the
14247 			 * new fp mp. So we first delete any ires that are
14248 			 * waiting for the fastpath. Then walk all ires and
14249 			 * delete the ire or delete the fp mp. In the case of
14250 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14251 			 * recreate the ire's without going through a complex
14252 			 * ipif up/down dance. So we don't delete the ire
14253 			 * itself, but just the ire_fp_mp for these 2 ire's
14254 			 * In the case of the other ire's we delete the ire's
14255 			 * themselves. Access to ire_fp_mp is completely
14256 			 * protected by ire_lock for IRE_MIPRTUN and
14257 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14258 			 * other cases for performance.
14259 			 */
14260 			if (ill->ill_isv6) {
14261 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14262 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14263 				    NULL);
14264 			} else {
14265 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14266 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14267 				    IRE_CACHE | IRE_BROADCAST,
14268 				    ire_fastpath_flush, NULL, ill);
14269 				mutex_enter(&ire_mrtun_lock);
14270 				if (ire_mrtun_count != 0) {
14271 					mutex_exit(&ire_mrtun_lock);
14272 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14273 					    IRE_MIPRTUN, ire_fastpath_flush,
14274 					    NULL, ill);
14275 				} else {
14276 					mutex_exit(&ire_mrtun_lock);
14277 				}
14278 			}
14279 			break;
14280 		case DL_NOTE_SDU_SIZE:
14281 			/*
14282 			 * Change the MTU size of the interface, of all
14283 			 * attached ipif's, and of all relevant ire's.  The
14284 			 * new value's a uint32_t at notify->dl_data.
14285 			 * Mtu change Vs. new ire creation - protocol below.
14286 			 *
14287 			 * a Mark the ipif as IPIF_CHANGING.
14288 			 * b Set the new mtu in the ipif.
14289 			 * c Change the ire_max_frag on all affected ires
14290 			 * d Unmark the IPIF_CHANGING
14291 			 *
14292 			 * To see how the protocol works, assume an interface
14293 			 * route is also being added simultaneously by
14294 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14295 			 * the ire. If the ire is created before step a,
14296 			 * it will be cleaned up by step c. If the ire is
14297 			 * created after step d, it will see the new value of
14298 			 * ipif_mtu. Any attempt to create the ire between
14299 			 * steps a to d will fail because of the IPIF_CHANGING
14300 			 * flag. Note that ire_create() is passed a pointer to
14301 			 * the ipif_mtu, and not the value. During ire_add
14302 			 * under the bucket lock, the ire_max_frag of the
14303 			 * new ire being created is set from the ipif/ire from
14304 			 * which it is being derived.
14305 			 */
14306 			mutex_enter(&ill->ill_lock);
14307 			ill->ill_max_frag = (uint_t)notify->dl_data;
14308 
14309 			/*
14310 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14311 			 * leave it alone
14312 			 */
14313 			if (ill->ill_mtu_userspecified) {
14314 				mutex_exit(&ill->ill_lock);
14315 				break;
14316 			}
14317 			ill->ill_max_mtu = ill->ill_max_frag;
14318 			if (ill->ill_isv6) {
14319 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14320 					ill->ill_max_mtu = IPV6_MIN_MTU;
14321 			} else {
14322 				if (ill->ill_max_mtu < IP_MIN_MTU)
14323 					ill->ill_max_mtu = IP_MIN_MTU;
14324 			}
14325 			for (ipif = ill->ill_ipif; ipif != NULL;
14326 			    ipif = ipif->ipif_next) {
14327 				/*
14328 				 * Don't override the mtu if the user
14329 				 * has explicitly set it.
14330 				 */
14331 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14332 					continue;
14333 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14334 				if (ipif->ipif_isv6)
14335 					ire = ipif_to_ire_v6(ipif);
14336 				else
14337 					ire = ipif_to_ire(ipif);
14338 				if (ire != NULL) {
14339 					ire->ire_max_frag = ipif->ipif_mtu;
14340 					ire_refrele(ire);
14341 				}
14342 				if (ipif->ipif_flags & IPIF_UP) {
14343 					if (ill->ill_isv6)
14344 						need_ire_walk_v6 = B_TRUE;
14345 					else
14346 						need_ire_walk_v4 = B_TRUE;
14347 				}
14348 			}
14349 			mutex_exit(&ill->ill_lock);
14350 			if (need_ire_walk_v4)
14351 				ire_walk_v4(ill_mtu_change, (char *)ill,
14352 				    ALL_ZONES);
14353 			if (need_ire_walk_v6)
14354 				ire_walk_v6(ill_mtu_change, (char *)ill,
14355 				    ALL_ZONES);
14356 			break;
14357 		case DL_NOTE_LINK_UP:
14358 		case DL_NOTE_LINK_DOWN: {
14359 			/*
14360 			 * We are writer. ill / phyint / ipsq assocs stable.
14361 			 * The RUNNING flag reflects the state of the link.
14362 			 */
14363 			phyint_t *phyint = ill->ill_phyint;
14364 			uint64_t new_phyint_flags;
14365 			boolean_t changed = B_FALSE;
14366 
14367 			mutex_enter(&phyint->phyint_lock);
14368 			new_phyint_flags =
14369 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14370 			    phyint->phyint_flags | PHYI_RUNNING :
14371 			    phyint->phyint_flags & ~PHYI_RUNNING;
14372 			if (new_phyint_flags != phyint->phyint_flags) {
14373 				phyint->phyint_flags = new_phyint_flags;
14374 				changed = B_TRUE;
14375 			}
14376 			mutex_exit(&phyint->phyint_lock);
14377 			/*
14378 			 * If the flags have changed, send a message to
14379 			 * the routing socket.
14380 			 */
14381 			if (changed) {
14382 				if (phyint->phyint_illv4 != NULL) {
14383 					ip_rts_ifmsg(
14384 					    phyint->phyint_illv4->ill_ipif);
14385 				}
14386 				if (phyint->phyint_illv6 != NULL) {
14387 					ip_rts_ifmsg(
14388 					    phyint->phyint_illv6->ill_ipif);
14389 				}
14390 			}
14391 			break;
14392 		}
14393 		case DL_NOTE_PROMISC_ON_PHYS:
14394 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14395 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14396 			mutex_enter(&ill->ill_lock);
14397 			ill->ill_promisc_on_phys = B_TRUE;
14398 			mutex_exit(&ill->ill_lock);
14399 			break;
14400 		case DL_NOTE_PROMISC_OFF_PHYS:
14401 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14402 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14403 			mutex_enter(&ill->ill_lock);
14404 			ill->ill_promisc_on_phys = B_FALSE;
14405 			mutex_exit(&ill->ill_lock);
14406 			break;
14407 		case DL_NOTE_CAPAB_RENEG:
14408 			/*
14409 			 * Something changed on the driver side.
14410 			 * It wants us to renegotiate the capabilities
14411 			 * on this ill. The most likely cause is the
14412 			 * aggregation interface under us where a
14413 			 * port got added or went away.
14414 			 *
14415 			 * We reset the capabilities and set the
14416 			 * state to IDMS_RENG so that when the ack
14417 			 * comes back, we can start the
14418 			 * renegotiation process.
14419 			 */
14420 			ill_capability_reset(ill);
14421 			ill->ill_capab_state = IDMS_RENEG;
14422 			break;
14423 		default:
14424 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14425 			    "type 0x%x for DL_NOTIFY_IND\n",
14426 			    notify->dl_notification));
14427 			break;
14428 		}
14429 
14430 		/*
14431 		 * As this is an asynchronous operation, we
14432 		 * should not call ill_dlpi_done
14433 		 */
14434 		break;
14435 	}
14436 	case DL_NOTIFY_ACK:
14437 		/*
14438 		 * Don't really need to check for what notifications
14439 		 * are supported; we'll process what gets sent upstream,
14440 		 * and we know it'll be something we support changing
14441 		 * based on our DL_NOTIFY_REQ.
14442 		 */
14443 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14444 		break;
14445 	case DL_PHYS_ADDR_ACK: {
14446 		/*
14447 		 * We should have an IOCTL waiting on this when request
14448 		 * sent by ill_dl_phys.
14449 		 * However, ill_dl_phys was called on an ill queue (from
14450 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14451 		 * ioctl is known to be pending on ill_wq.
14452 		 * There are two additional phys_addr_req's sent to the
14453 		 * driver to get the token and lla. ill_phys_addr_pend
14454 		 * keeps track of the last one sent so we know which
14455 		 * response we are dealing with. ill_dlpi_done will
14456 		 * update ill_phys_addr_pend when it sends the next req.
14457 		 * We don't complete the IOCTL until all three DL_PARs
14458 		 * have been attempted.
14459 		 *
14460 		 * We don't need any lock to update ill_nd_lla* fields,
14461 		 * since the ill is not yet up, We grab the lock just
14462 		 * for uniformity with other code that accesses ill_nd_lla.
14463 		 */
14464 		physaddr_req = ill->ill_phys_addr_pend;
14465 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14466 		if (physaddr_req == DL_IPV6_TOKEN ||
14467 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14468 			if (physaddr_req == DL_IPV6_TOKEN) {
14469 				/*
14470 				 * bcopy to low-order bits of ill_token
14471 				 *
14472 				 * XXX Temporary hack - currently,
14473 				 * all known tokens are 64 bits,
14474 				 * so I'll cheat for the moment.
14475 				 */
14476 				dlp = (union DL_primitives *)mp->b_rptr;
14477 
14478 				mutex_enter(&ill->ill_lock);
14479 				bcopy((uchar_t *)(mp->b_rptr +
14480 				dlp->physaddr_ack.dl_addr_offset),
14481 				(void *)&ill->ill_token.s6_addr32[2],
14482 				dlp->physaddr_ack.dl_addr_length);
14483 				ill->ill_token_length =
14484 					dlp->physaddr_ack.dl_addr_length;
14485 				mutex_exit(&ill->ill_lock);
14486 			} else {
14487 				ASSERT(ill->ill_nd_lla_mp == NULL);
14488 				mp_hw = copyb(mp);
14489 				if (mp_hw == NULL) {
14490 					err = ENOMEM;
14491 					break;
14492 				}
14493 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14494 				mutex_enter(&ill->ill_lock);
14495 				ill->ill_nd_lla_mp = mp_hw;
14496 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14497 				dlp->physaddr_ack.dl_addr_offset;
14498 				ill->ill_nd_lla_len =
14499 					dlp->physaddr_ack.dl_addr_length;
14500 				mutex_exit(&ill->ill_lock);
14501 			}
14502 			break;
14503 		}
14504 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14505 		ASSERT(ill->ill_phys_addr_mp == NULL);
14506 		if (!ill->ill_ifname_pending)
14507 			break;
14508 		ill->ill_ifname_pending = 0;
14509 		if (!ioctl_aborted)
14510 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14511 		if (mp1 != NULL) {
14512 			ASSERT(connp == NULL);
14513 			q = ill->ill_wq;
14514 		}
14515 		/*
14516 		 * If any error acks received during the plumbing sequence,
14517 		 * ill_ifname_pending_err will be set. Break out and send up
14518 		 * the error to the pending ioctl.
14519 		 */
14520 		if (ill->ill_ifname_pending_err != 0) {
14521 			err = ill->ill_ifname_pending_err;
14522 			ill->ill_ifname_pending_err = 0;
14523 			break;
14524 		}
14525 		/*
14526 		 * Get the interface token.  If the zeroth interface
14527 		 * address is zero then set the address to the link local
14528 		 * address
14529 		 */
14530 		mp_hw = copyb(mp);
14531 		if (mp_hw == NULL) {
14532 			err = ENOMEM;
14533 			break;
14534 		}
14535 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14536 		ill->ill_phys_addr_mp = mp_hw;
14537 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14538 				dlp->physaddr_ack.dl_addr_offset;
14539 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14540 		    ill->ill_phys_addr_length == 0 ||
14541 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14542 			/*
14543 			 * Compatibility: atun driver returns a length of 0.
14544 			 * ipdptp has an ill_phys_addr_length of zero(from
14545 			 * DL_BIND_ACK) but a non-zero length here.
14546 			 * ipd has an ill_phys_addr_length of 4(from
14547 			 * DL_BIND_ACK) but a non-zero length here.
14548 			 */
14549 			ill->ill_phys_addr = NULL;
14550 		} else if (dlp->physaddr_ack.dl_addr_length !=
14551 		    ill->ill_phys_addr_length) {
14552 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14553 			    "Address length mismatch %d %d\n",
14554 			    dlp->physaddr_ack.dl_addr_length,
14555 			    ill->ill_phys_addr_length));
14556 			err = EINVAL;
14557 			break;
14558 		}
14559 		mutex_enter(&ill->ill_lock);
14560 		if (ill->ill_nd_lla_mp == NULL) {
14561 			ill->ill_nd_lla_mp = copyb(mp_hw);
14562 			if (ill->ill_nd_lla_mp == NULL) {
14563 				err = ENOMEM;
14564 				mutex_exit(&ill->ill_lock);
14565 				break;
14566 			}
14567 			ill->ill_nd_lla =
14568 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14569 			    dlp->physaddr_ack.dl_addr_offset;
14570 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14571 		}
14572 		mutex_exit(&ill->ill_lock);
14573 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14574 			(void) ill_setdefaulttoken(ill);
14575 
14576 		/*
14577 		 * If the ill zero interface has a zero address assign
14578 		 * it the proper link local address.
14579 		 */
14580 		ASSERT(ill->ill_ipif->ipif_id == 0);
14581 		if (ipif != NULL &&
14582 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14583 			(void) ipif_setlinklocal(ipif);
14584 		break;
14585 	}
14586 	case DL_OK_ACK:
14587 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14588 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14589 		    dloa->dl_correct_primitive));
14590 		switch (dloa->dl_correct_primitive) {
14591 		case DL_UNBIND_REQ:
14592 		case DL_ATTACH_REQ:
14593 		case DL_DETACH_REQ:
14594 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14595 			break;
14596 		}
14597 		break;
14598 	default:
14599 		break;
14600 	}
14601 
14602 	freemsg(mp);
14603 	if (mp1) {
14604 		struct iocblk *iocp;
14605 		int mode;
14606 
14607 		/*
14608 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14609 		 * SIOCSLIFNAME do a copyout.
14610 		 */
14611 		iocp = (struct iocblk *)mp1->b_rptr;
14612 
14613 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14614 		    iocp->ioc_cmd == SIOCSLIFNAME)
14615 			mode = COPYOUT;
14616 		else
14617 			mode = NO_COPYOUT;
14618 		/*
14619 		 * The ioctl must complete now without EINPROGRESS
14620 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14621 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14622 		 * stuck for ever in the ipsq.
14623 		 */
14624 		ASSERT(err != EINPROGRESS);
14625 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14626 
14627 	}
14628 }
14629 
14630 /*
14631  * ip_rput_other is called by ip_rput to handle messages modifying the global
14632  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14633  */
14634 /* ARGSUSED */
14635 void
14636 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14637 {
14638 	ill_t		*ill;
14639 	struct iocblk	*iocp;
14640 	mblk_t		*mp1;
14641 	conn_t		*connp = NULL;
14642 
14643 	ip1dbg(("ip_rput_other "));
14644 	ill = (ill_t *)q->q_ptr;
14645 	/*
14646 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14647 	 * in which case ipsq is NULL.
14648 	 */
14649 	if (ipsq != NULL) {
14650 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14651 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14652 	}
14653 
14654 	switch (mp->b_datap->db_type) {
14655 	case M_ERROR:
14656 	case M_HANGUP:
14657 		/*
14658 		 * The device has a problem.  We force the ILL down.  It can
14659 		 * be brought up again manually using SIOCSIFFLAGS (via
14660 		 * ifconfig or equivalent).
14661 		 */
14662 		ASSERT(ipsq != NULL);
14663 		if (mp->b_rptr < mp->b_wptr)
14664 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14665 		if (ill->ill_error == 0)
14666 			ill->ill_error = ENXIO;
14667 		if (!ill_down_start(q, mp))
14668 			return;
14669 		ipif_all_down_tail(ipsq, q, mp, NULL);
14670 		break;
14671 	case M_IOCACK:
14672 		iocp = (struct iocblk *)mp->b_rptr;
14673 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14674 		switch (iocp->ioc_cmd) {
14675 		case SIOCSTUNPARAM:
14676 		case OSIOCSTUNPARAM:
14677 			ASSERT(ipsq != NULL);
14678 			/*
14679 			 * Finish socket ioctl passed through to tun.
14680 			 * We should have an IOCTL waiting on this.
14681 			 */
14682 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14683 			if (ill->ill_isv6) {
14684 				struct iftun_req *ta;
14685 
14686 				/*
14687 				 * if a source or destination is
14688 				 * being set, try and set the link
14689 				 * local address for the tunnel
14690 				 */
14691 				ta = (struct iftun_req *)mp->b_cont->
14692 				    b_cont->b_rptr;
14693 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14694 					ipif_set_tun_llink(ill, ta);
14695 				}
14696 
14697 			}
14698 			if (mp1 != NULL) {
14699 				/*
14700 				 * Now copy back the b_next/b_prev used by
14701 				 * mi code for the mi_copy* functions.
14702 				 * See ip_sioctl_tunparam() for the reason.
14703 				 * Also protect against missing b_cont.
14704 				 */
14705 				if (mp->b_cont != NULL) {
14706 					mp->b_cont->b_next =
14707 					    mp1->b_cont->b_next;
14708 					mp->b_cont->b_prev =
14709 					    mp1->b_cont->b_prev;
14710 				}
14711 				inet_freemsg(mp1);
14712 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14713 				ASSERT(connp != NULL);
14714 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14715 				    iocp->ioc_error, NO_COPYOUT,
14716 				    ipsq->ipsq_current_ipif, ipsq);
14717 			} else {
14718 				ASSERT(connp == NULL);
14719 				putnext(q, mp);
14720 			}
14721 			break;
14722 		case SIOCGTUNPARAM:
14723 		case OSIOCGTUNPARAM:
14724 			/*
14725 			 * This is really M_IOCDATA from the tunnel driver.
14726 			 * convert back and complete the ioctl.
14727 			 * We should have an IOCTL waiting on this.
14728 			 */
14729 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14730 			if (mp1) {
14731 				/*
14732 				 * Now copy back the b_next/b_prev used by
14733 				 * mi code for the mi_copy* functions.
14734 				 * See ip_sioctl_tunparam() for the reason.
14735 				 * Also protect against missing b_cont.
14736 				 */
14737 				if (mp->b_cont != NULL) {
14738 					mp->b_cont->b_next =
14739 					    mp1->b_cont->b_next;
14740 					mp->b_cont->b_prev =
14741 					    mp1->b_cont->b_prev;
14742 				}
14743 				inet_freemsg(mp1);
14744 				if (iocp->ioc_error == 0)
14745 					mp->b_datap->db_type = M_IOCDATA;
14746 				ASSERT(connp != NULL);
14747 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14748 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14749 			} else {
14750 				ASSERT(connp == NULL);
14751 				putnext(q, mp);
14752 			}
14753 			break;
14754 		default:
14755 			break;
14756 		}
14757 		break;
14758 	case M_IOCNAK:
14759 		iocp = (struct iocblk *)mp->b_rptr;
14760 
14761 		switch (iocp->ioc_cmd) {
14762 		int mode;
14763 		ipif_t	*ipif;
14764 
14765 		case DL_IOC_HDR_INFO:
14766 			/*
14767 			 * If this was the first attempt turn of the
14768 			 * fastpath probing.
14769 			 */
14770 			mutex_enter(&ill->ill_lock);
14771 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14772 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14773 				mutex_exit(&ill->ill_lock);
14774 				ill_fastpath_nack(ill);
14775 				ip1dbg(("ip_rput: DLPI fastpath off on "
14776 				    "interface %s\n",
14777 				    ill->ill_name));
14778 			} else {
14779 				mutex_exit(&ill->ill_lock);
14780 			}
14781 			freemsg(mp);
14782 			break;
14783 		case SIOCSTUNPARAM:
14784 		case OSIOCSTUNPARAM:
14785 			ASSERT(ipsq != NULL);
14786 			/*
14787 			 * Finish socket ioctl passed through to tun
14788 			 * We should have an IOCTL waiting on this.
14789 			 */
14790 			/* FALLTHRU */
14791 		case SIOCGTUNPARAM:
14792 		case OSIOCGTUNPARAM:
14793 			/*
14794 			 * This is really M_IOCDATA from the tunnel driver.
14795 			 * convert back and complete the ioctl.
14796 			 * We should have an IOCTL waiting on this.
14797 			 */
14798 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14799 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14800 				mp1 = ill_pending_mp_get(ill, &connp,
14801 				    iocp->ioc_id);
14802 				mode = COPYOUT;
14803 				ipsq = NULL;
14804 				ipif = NULL;
14805 			} else {
14806 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14807 				mode = NO_COPYOUT;
14808 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14809 				ipif = ipsq->ipsq_current_ipif;
14810 			}
14811 			if (mp1 != NULL) {
14812 				/*
14813 				 * Now copy back the b_next/b_prev used by
14814 				 * mi code for the mi_copy* functions.
14815 				 * See ip_sioctl_tunparam() for the reason.
14816 				 * Also protect against missing b_cont.
14817 				 */
14818 				if (mp->b_cont != NULL) {
14819 					mp->b_cont->b_next =
14820 					    mp1->b_cont->b_next;
14821 					mp->b_cont->b_prev =
14822 					    mp1->b_cont->b_prev;
14823 				}
14824 				inet_freemsg(mp1);
14825 				if (iocp->ioc_error == 0)
14826 					iocp->ioc_error = EINVAL;
14827 				ASSERT(connp != NULL);
14828 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14829 				    iocp->ioc_error, mode, ipif, ipsq);
14830 			} else {
14831 				ASSERT(connp == NULL);
14832 				putnext(q, mp);
14833 			}
14834 			break;
14835 		default:
14836 			break;
14837 		}
14838 	default:
14839 		break;
14840 	}
14841 }
14842 
14843 /*
14844  * NOTE : This function does not ire_refrele the ire argument passed in.
14845  *
14846  * IPQoS notes
14847  * IP policy is invoked twice for a forwarded packet, once on the read side
14848  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14849  * enabled. An additional parameter, in_ill, has been added for this purpose.
14850  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14851  * because ip_mroute drops this information.
14852  *
14853  */
14854 void
14855 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14856 {
14857 	uint32_t	pkt_len;
14858 	queue_t	*q;
14859 	uint32_t	sum;
14860 #define	rptr	((uchar_t *)ipha)
14861 	uint32_t	max_frag;
14862 	uint32_t	ill_index;
14863 
14864 	/* Get the ill_index of the incoming ILL */
14865 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14866 
14867 	/* Initiate Read side IPPF processing */
14868 	if (IPP_ENABLED(IPP_FWD_IN)) {
14869 		ip_process(IPP_FWD_IN, &mp, ill_index);
14870 		if (mp == NULL) {
14871 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14872 			    "during IPPF processing\n"));
14873 			return;
14874 		}
14875 	}
14876 	pkt_len = ntohs(ipha->ipha_length);
14877 
14878 	/* Adjust the checksum to reflect the ttl decrement. */
14879 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14880 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14881 
14882 	if (ipha->ipha_ttl-- <= 1) {
14883 		if (ip_csum_hdr(ipha)) {
14884 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14885 			goto drop_pkt;
14886 		}
14887 		/*
14888 		 * Note: ire_stq this will be NULL for multicast
14889 		 * datagrams using the long path through arp (the IRE
14890 		 * is not an IRE_CACHE). This should not cause
14891 		 * problems since we don't generate ICMP errors for
14892 		 * multicast packets.
14893 		 */
14894 		q = ire->ire_stq;
14895 		if (q)
14896 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14897 		else
14898 			freemsg(mp);
14899 		return;
14900 	}
14901 
14902 	/*
14903 	 * Don't forward if the interface is down
14904 	 */
14905 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14906 		BUMP_MIB(&ip_mib, ipInDiscards);
14907 		goto drop_pkt;
14908 	}
14909 
14910 	/* Get the ill_index of the outgoing ILL */
14911 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14912 
14913 	/* Check if there are options to update */
14914 	if (!IS_SIMPLE_IPH(ipha)) {
14915 		if (ip_csum_hdr(ipha)) {
14916 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14917 			goto drop_pkt;
14918 		}
14919 		if (ip_rput_forward_options(mp, ipha, ire)) {
14920 			return;
14921 		}
14922 
14923 		ipha->ipha_hdr_checksum = 0;
14924 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14925 	}
14926 	max_frag = ire->ire_max_frag;
14927 	if (pkt_len > max_frag) {
14928 		/*
14929 		 * It needs fragging on its way out.  We haven't
14930 		 * verified the header checksum yet.  Since we
14931 		 * are going to put a surely good checksum in the
14932 		 * outgoing header, we have to make sure that it
14933 		 * was good coming in.
14934 		 */
14935 		if (ip_csum_hdr(ipha)) {
14936 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14937 			goto drop_pkt;
14938 		}
14939 		/* Initiate Write side IPPF processing */
14940 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14941 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14942 			if (mp == NULL) {
14943 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14944 				    " during IPPF processing\n"));
14945 				return;
14946 			}
14947 		}
14948 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14949 		return;
14950 	}
14951 
14952 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14953 	if (mp == NULL) {
14954 		BUMP_MIB(&ip_mib, ipInDiscards);
14955 		return;
14956 	}
14957 
14958 	q = ire->ire_stq;
14959 	UPDATE_IB_PKT_COUNT(ire);
14960 	ire->ire_last_used_time = lbolt;
14961 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14962 	putnext(q, mp);
14963 	return;
14964 
14965 drop_pkt:;
14966 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14967 	freemsg(mp);
14968 #undef	rptr
14969 }
14970 
14971 void
14972 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14973 {
14974 	ire_t	*ire;
14975 
14976 	ASSERT(!ipif->ipif_isv6);
14977 	/*
14978 	 * Find an IRE which matches the destination and the outgoing
14979 	 * queue in the cache table. All we need is an IRE_CACHE which
14980 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14981 	 * then it is enough to have some IRE_CACHE in the group.
14982 	 */
14983 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14984 		dst = ipif->ipif_pp_dst_addr;
14985 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14986 	    MATCH_IRE_ILL_GROUP);
14987 	if (!ire) {
14988 		/*
14989 		 * Mark this packet to make it be delivered to
14990 		 * ip_rput_forward after the new ire has been
14991 		 * created.
14992 		 */
14993 		mp->b_prev = NULL;
14994 		mp->b_next = mp;
14995 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14996 		    NULL, 0);
14997 	} else {
14998 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14999 		IRE_REFRELE(ire);
15000 	}
15001 }
15002 
15003 /* Update any source route, record route or timestamp options */
15004 static int
15005 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15006 {
15007 	ipoptp_t	opts;
15008 	uchar_t		*opt;
15009 	uint8_t		optval;
15010 	uint8_t		optlen;
15011 	ipaddr_t	dst;
15012 	uint32_t	ts;
15013 	ire_t		*dst_ire = NULL;
15014 	ire_t		*tmp_ire = NULL;
15015 	timestruc_t	now;
15016 
15017 	ip2dbg(("ip_rput_forward_options\n"));
15018 	dst = ipha->ipha_dst;
15019 	for (optval = ipoptp_first(&opts, ipha);
15020 	    optval != IPOPT_EOL;
15021 	    optval = ipoptp_next(&opts)) {
15022 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15023 		opt = opts.ipoptp_cur;
15024 		optlen = opts.ipoptp_len;
15025 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15026 		    optval, opts.ipoptp_len));
15027 		switch (optval) {
15028 			uint32_t off;
15029 		case IPOPT_SSRR:
15030 		case IPOPT_LSRR:
15031 			/* Check if adminstratively disabled */
15032 			if (!ip_forward_src_routed) {
15033 				BUMP_MIB(&ip_mib, ipForwProhibits);
15034 				if (ire->ire_stq)
15035 					icmp_unreachable(ire->ire_stq, mp,
15036 					    ICMP_SOURCE_ROUTE_FAILED);
15037 				else {
15038 					ip0dbg(("ip_rput_forward_options: "
15039 					    "unable to send unreach\n"));
15040 					freemsg(mp);
15041 				}
15042 				return (-1);
15043 			}
15044 
15045 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15046 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15047 			if (dst_ire == NULL) {
15048 				/*
15049 				 * Must be partial since ip_rput_options
15050 				 * checked for strict.
15051 				 */
15052 				break;
15053 			}
15054 			off = opt[IPOPT_OFFSET];
15055 			off--;
15056 		redo_srr:
15057 			if (optlen < IP_ADDR_LEN ||
15058 			    off > optlen - IP_ADDR_LEN) {
15059 				/* End of source route */
15060 				ip1dbg((
15061 				    "ip_rput_forward_options: end of SR\n"));
15062 				ire_refrele(dst_ire);
15063 				break;
15064 			}
15065 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15066 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15067 			    IP_ADDR_LEN);
15068 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15069 			    ntohl(dst)));
15070 
15071 			/*
15072 			 * Check if our address is present more than
15073 			 * once as consecutive hops in source route.
15074 			 */
15075 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15076 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15077 			if (tmp_ire != NULL) {
15078 				ire_refrele(tmp_ire);
15079 				off += IP_ADDR_LEN;
15080 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15081 				goto redo_srr;
15082 			}
15083 			ipha->ipha_dst = dst;
15084 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15085 			ire_refrele(dst_ire);
15086 			break;
15087 		case IPOPT_RR:
15088 			off = opt[IPOPT_OFFSET];
15089 			off--;
15090 			if (optlen < IP_ADDR_LEN ||
15091 			    off > optlen - IP_ADDR_LEN) {
15092 				/* No more room - ignore */
15093 				ip1dbg((
15094 				    "ip_rput_forward_options: end of RR\n"));
15095 				break;
15096 			}
15097 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15098 			    IP_ADDR_LEN);
15099 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15100 			break;
15101 		case IPOPT_TS:
15102 			/* Insert timestamp if there is room */
15103 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15104 			case IPOPT_TS_TSONLY:
15105 				off = IPOPT_TS_TIMELEN;
15106 				break;
15107 			case IPOPT_TS_PRESPEC:
15108 			case IPOPT_TS_PRESPEC_RFC791:
15109 				/* Verify that the address matched */
15110 				off = opt[IPOPT_OFFSET] - 1;
15111 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15112 				dst_ire = ire_ctable_lookup(dst, 0,
15113 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
15114 				if (dst_ire == NULL) {
15115 					/* Not for us */
15116 					break;
15117 				}
15118 				ire_refrele(dst_ire);
15119 				/* FALLTHRU */
15120 			case IPOPT_TS_TSANDADDR:
15121 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15122 				break;
15123 			default:
15124 				/*
15125 				 * ip_*put_options should have already
15126 				 * dropped this packet.
15127 				 */
15128 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15129 				    "unknown IT - bug in ip_rput_options?\n");
15130 				return (0);	/* Keep "lint" happy */
15131 			}
15132 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15133 				/* Increase overflow counter */
15134 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15135 				opt[IPOPT_POS_OV_FLG] =
15136 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15137 				    (off << 4));
15138 				break;
15139 			}
15140 			off = opt[IPOPT_OFFSET] - 1;
15141 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15142 			case IPOPT_TS_PRESPEC:
15143 			case IPOPT_TS_PRESPEC_RFC791:
15144 			case IPOPT_TS_TSANDADDR:
15145 				bcopy(&ire->ire_src_addr,
15146 				    (char *)opt + off, IP_ADDR_LEN);
15147 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15148 				/* FALLTHRU */
15149 			case IPOPT_TS_TSONLY:
15150 				off = opt[IPOPT_OFFSET] - 1;
15151 				/* Compute # of milliseconds since midnight */
15152 				gethrestime(&now);
15153 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15154 				    now.tv_nsec / (NANOSEC / MILLISEC);
15155 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15156 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15157 				break;
15158 			}
15159 			break;
15160 		}
15161 	}
15162 	return (0);
15163 }
15164 
15165 /*
15166  * This is called after processing at least one of AH/ESP headers.
15167  *
15168  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15169  * the actual, physical interface on which the packet was received,
15170  * but, when ip_strict_dst_multihoming is set to 1, could be the
15171  * interface which had the ipha_dst configured when the packet went
15172  * through ip_rput. The ill_index corresponding to the recv_ill
15173  * is saved in ipsec_in_rill_index
15174  */
15175 void
15176 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15177 {
15178 	mblk_t *mp;
15179 	ipaddr_t dst;
15180 	in6_addr_t *v6dstp;
15181 	ipha_t *ipha;
15182 	ip6_t *ip6h;
15183 	ipsec_in_t *ii;
15184 	boolean_t ill_need_rele = B_FALSE;
15185 	boolean_t rill_need_rele = B_FALSE;
15186 	boolean_t ire_need_rele = B_FALSE;
15187 
15188 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15189 	ASSERT(ii->ipsec_in_ill_index != 0);
15190 
15191 	mp = ipsec_mp->b_cont;
15192 	ASSERT(mp != NULL);
15193 
15194 
15195 	if (ill == NULL) {
15196 		ASSERT(recv_ill == NULL);
15197 		/*
15198 		 * We need to get the original queue on which ip_rput_local
15199 		 * or ip_rput_data_v6 was called.
15200 		 */
15201 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15202 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15203 		ill_need_rele = B_TRUE;
15204 
15205 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15206 			recv_ill = ill_lookup_on_ifindex(
15207 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15208 			    NULL, NULL, NULL, NULL);
15209 			rill_need_rele = B_TRUE;
15210 		} else {
15211 			recv_ill = ill;
15212 		}
15213 
15214 		if ((ill == NULL) || (recv_ill == NULL)) {
15215 			ip0dbg(("ip_fanout_proto_again: interface "
15216 			    "disappeared\n"));
15217 			if (ill != NULL)
15218 				ill_refrele(ill);
15219 			if (recv_ill != NULL)
15220 				ill_refrele(recv_ill);
15221 			freemsg(ipsec_mp);
15222 			return;
15223 		}
15224 	}
15225 
15226 	ASSERT(ill != NULL && recv_ill != NULL);
15227 
15228 	if (mp->b_datap->db_type == M_CTL) {
15229 		/*
15230 		 * AH/ESP is returning the ICMP message after
15231 		 * removing their headers. Fanout again till
15232 		 * it gets to the right protocol.
15233 		 */
15234 		if (ii->ipsec_in_v4) {
15235 			icmph_t *icmph;
15236 			int iph_hdr_length;
15237 			int hdr_length;
15238 
15239 			ipha = (ipha_t *)mp->b_rptr;
15240 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15241 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15242 			ipha = (ipha_t *)&icmph[1];
15243 			hdr_length = IPH_HDR_LENGTH(ipha);
15244 			/*
15245 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15246 			 * Reset the type to M_DATA.
15247 			 */
15248 			mp->b_datap->db_type = M_DATA;
15249 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15250 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15251 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15252 		} else {
15253 			icmp6_t *icmp6;
15254 			int hdr_length;
15255 
15256 			ip6h = (ip6_t *)mp->b_rptr;
15257 			/* Don't call hdr_length_v6() unless you have to. */
15258 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15259 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15260 			else
15261 				hdr_length = IPV6_HDR_LEN;
15262 
15263 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15264 			/*
15265 			 * icmp_inbound_error_fanout_v6 may need to do
15266 			 * pullupmsg.  Reset the type to M_DATA.
15267 			 */
15268 			mp->b_datap->db_type = M_DATA;
15269 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15270 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15271 		}
15272 		if (ill_need_rele)
15273 			ill_refrele(ill);
15274 		if (rill_need_rele)
15275 			ill_refrele(recv_ill);
15276 		return;
15277 	}
15278 
15279 	if (ii->ipsec_in_v4) {
15280 		ipha = (ipha_t *)mp->b_rptr;
15281 		dst = ipha->ipha_dst;
15282 		if (CLASSD(dst)) {
15283 			/*
15284 			 * Multicast has to be delivered to all streams.
15285 			 */
15286 			dst = INADDR_BROADCAST;
15287 		}
15288 
15289 		if (ire == NULL) {
15290 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15291 			if (ire == NULL) {
15292 				if (ill_need_rele)
15293 					ill_refrele(ill);
15294 				if (rill_need_rele)
15295 					ill_refrele(recv_ill);
15296 				ip1dbg(("ip_fanout_proto_again: "
15297 				    "IRE not found"));
15298 				freemsg(ipsec_mp);
15299 				return;
15300 			}
15301 			ire_need_rele = B_TRUE;
15302 		}
15303 
15304 		switch (ipha->ipha_protocol) {
15305 			case IPPROTO_UDP:
15306 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15307 				    recv_ill);
15308 				if (ire_need_rele)
15309 					ire_refrele(ire);
15310 				break;
15311 			case IPPROTO_TCP:
15312 				if (!ire_need_rele)
15313 					IRE_REFHOLD(ire);
15314 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15315 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15316 				IRE_REFRELE(ire);
15317 				if (mp != NULL)
15318 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15319 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15320 				break;
15321 			case IPPROTO_SCTP:
15322 				if (!ire_need_rele)
15323 					IRE_REFHOLD(ire);
15324 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15325 				    ipsec_mp, 0, ill->ill_rq, dst);
15326 				break;
15327 			default:
15328 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15329 				    recv_ill);
15330 				if (ire_need_rele)
15331 					ire_refrele(ire);
15332 				break;
15333 		}
15334 	} else {
15335 		uint32_t rput_flags = 0;
15336 
15337 		ip6h = (ip6_t *)mp->b_rptr;
15338 		v6dstp = &ip6h->ip6_dst;
15339 		/*
15340 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15341 		 * address.
15342 		 *
15343 		 * Currently, we don't store that state in the IPSEC_IN
15344 		 * message, and we may need to.
15345 		 */
15346 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15347 		    IP6_IN_LLMCAST : 0);
15348 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15349 		    NULL);
15350 	}
15351 	if (ill_need_rele)
15352 		ill_refrele(ill);
15353 	if (rill_need_rele)
15354 		ill_refrele(recv_ill);
15355 }
15356 
15357 /*
15358  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15359  * returns 'true' if there are still fragments left on the queue, in
15360  * which case we restart the timer.
15361  */
15362 void
15363 ill_frag_timer(void *arg)
15364 {
15365 	ill_t	*ill = (ill_t *)arg;
15366 	boolean_t frag_pending;
15367 
15368 	mutex_enter(&ill->ill_lock);
15369 	ASSERT(!ill->ill_fragtimer_executing);
15370 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15371 		ill->ill_frag_timer_id = 0;
15372 		mutex_exit(&ill->ill_lock);
15373 		return;
15374 	}
15375 	ill->ill_fragtimer_executing = 1;
15376 	mutex_exit(&ill->ill_lock);
15377 
15378 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15379 
15380 	/*
15381 	 * Restart the timer, if we have fragments pending or if someone
15382 	 * wanted us to be scheduled again.
15383 	 */
15384 	mutex_enter(&ill->ill_lock);
15385 	ill->ill_fragtimer_executing = 0;
15386 	ill->ill_frag_timer_id = 0;
15387 	if (frag_pending || ill->ill_fragtimer_needrestart)
15388 		ill_frag_timer_start(ill);
15389 	mutex_exit(&ill->ill_lock);
15390 }
15391 
15392 void
15393 ill_frag_timer_start(ill_t *ill)
15394 {
15395 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15396 
15397 	/* If the ill is closing or opening don't proceed */
15398 	if (ill->ill_state_flags & ILL_CONDEMNED)
15399 		return;
15400 
15401 	if (ill->ill_fragtimer_executing) {
15402 		/*
15403 		 * ill_frag_timer is currently executing. Just record the
15404 		 * the fact that we want the timer to be restarted.
15405 		 * ill_frag_timer will post a timeout before it returns,
15406 		 * ensuring it will be called again.
15407 		 */
15408 		ill->ill_fragtimer_needrestart = 1;
15409 		return;
15410 	}
15411 
15412 	if (ill->ill_frag_timer_id == 0) {
15413 		/*
15414 		 * The timer is neither running nor is the timeout handler
15415 		 * executing. Post a timeout so that ill_frag_timer will be
15416 		 * called
15417 		 */
15418 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15419 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15420 		ill->ill_fragtimer_needrestart = 0;
15421 	}
15422 }
15423 
15424 /*
15425  * This routine is needed for loopback when forwarding multicasts.
15426  *
15427  * IPQoS Notes:
15428  * IPPF processing is done in fanout routines.
15429  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15430  * processing for IPSec packets is done when it comes back in clear.
15431  * NOTE : The callers of this function need to do the ire_refrele for the
15432  *	  ire that is being passed in.
15433  */
15434 void
15435 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15436     ill_t *recv_ill)
15437 {
15438 	ill_t	*ill = (ill_t *)q->q_ptr;
15439 	uint32_t	sum;
15440 	uint32_t	u1;
15441 	uint32_t	u2;
15442 	int		hdr_length;
15443 	boolean_t	mctl_present;
15444 	mblk_t		*first_mp = mp;
15445 	mblk_t		*hada_mp = NULL;
15446 	ipha_t		*inner_ipha;
15447 
15448 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15449 	    "ip_rput_locl_start: q %p", q);
15450 
15451 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15452 
15453 
15454 #define	rptr	((uchar_t *)ipha)
15455 #define	iphs	((uint16_t *)ipha)
15456 
15457 	/*
15458 	 * no UDP or TCP packet should come here anymore.
15459 	 */
15460 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15461 	    (ipha->ipha_protocol != IPPROTO_UDP));
15462 
15463 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15464 	if (mctl_present &&
15465 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15466 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15467 
15468 		/*
15469 		 * It's an IPsec accelerated packet.
15470 		 * Keep a pointer to the data attributes around until
15471 		 * we allocate the ipsec_info_t.
15472 		 */
15473 		IPSECHW_DEBUG(IPSECHW_PKT,
15474 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15475 		hada_mp = first_mp;
15476 		hada_mp->b_cont = NULL;
15477 		/*
15478 		 * Since it is accelerated, it comes directly from
15479 		 * the ill and the data attributes is followed by
15480 		 * the packet data.
15481 		 */
15482 		ASSERT(mp->b_datap->db_type != M_CTL);
15483 		first_mp = mp;
15484 		mctl_present = B_FALSE;
15485 	}
15486 
15487 	/*
15488 	 * IF M_CTL is not present, then ipsec_in_is_secure
15489 	 * should return B_TRUE. There is a case where loopback
15490 	 * packets has an M_CTL in the front with all the
15491 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15492 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15493 	 * packets never comes here, it is safe to ASSERT the
15494 	 * following.
15495 	 */
15496 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15497 
15498 
15499 	/* u1 is # words of IP options */
15500 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15501 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15502 
15503 	if (u1) {
15504 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15505 			if (hada_mp != NULL)
15506 				freemsg(hada_mp);
15507 			return;
15508 		}
15509 	} else {
15510 		/* Check the IP header checksum.  */
15511 #define	uph	((uint16_t *)ipha)
15512 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15513 		    uph[6] + uph[7] + uph[8] + uph[9];
15514 #undef  uph
15515 		/* finish doing IP checksum */
15516 		sum = (sum & 0xFFFF) + (sum >> 16);
15517 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15518 		/*
15519 		 * Don't verify header checksum if this packet is coming
15520 		 * back from AH/ESP as we already did it.
15521 		 */
15522 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15523 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15524 			goto drop_pkt;
15525 		}
15526 	}
15527 
15528 	/*
15529 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15530 	 * might be called more than once for secure packets, count only
15531 	 * the first time.
15532 	 */
15533 	if (!mctl_present) {
15534 		UPDATE_IB_PKT_COUNT(ire);
15535 		ire->ire_last_used_time = lbolt;
15536 	}
15537 
15538 	/* Check for fragmentation offset. */
15539 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15540 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15541 	if (u1) {
15542 		/*
15543 		 * We re-assemble fragments before we do the AH/ESP
15544 		 * processing. Thus, M_CTL should not be present
15545 		 * while we are re-assembling.
15546 		 */
15547 		ASSERT(!mctl_present);
15548 		ASSERT(first_mp == mp);
15549 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
15550 			return;
15551 		}
15552 		/*
15553 		 * Make sure that first_mp points back to mp as
15554 		 * the mp we came in with could have changed in
15555 		 * ip_rput_fragment().
15556 		 */
15557 		ipha = (ipha_t *)mp->b_rptr;
15558 		first_mp = mp;
15559 	}
15560 
15561 	/*
15562 	 * Clear hardware checksumming flag as it is currently only
15563 	 * used by TCP and UDP.
15564 	 */
15565 	DB_CKSUMFLAGS(mp) = 0;
15566 
15567 	/* Now we have a complete datagram, destined for this machine. */
15568 	u1 = IPH_HDR_LENGTH(ipha);
15569 	switch (ipha->ipha_protocol) {
15570 	case IPPROTO_ICMP: {
15571 		ire_t		*ire_zone;
15572 		ilm_t		*ilm;
15573 		mblk_t		*mp1;
15574 		zoneid_t	last_zoneid;
15575 
15576 		if (CLASSD(ipha->ipha_dst) &&
15577 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15578 			ASSERT(ire->ire_type == IRE_BROADCAST);
15579 			/*
15580 			 * In the multicast case, applications may have joined
15581 			 * the group from different zones, so we need to deliver
15582 			 * the packet to each of them. Loop through the
15583 			 * multicast memberships structures (ilm) on the receive
15584 			 * ill and send a copy of the packet up each matching
15585 			 * one. However, we don't do this for multicasts sent on
15586 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15587 			 * they must stay in the sender's zone.
15588 			 *
15589 			 * ilm_add_v6() ensures that ilms in the same zone are
15590 			 * contiguous in the ill_ilm list. We use this property
15591 			 * to avoid sending duplicates needed when two
15592 			 * applications in the same zone join the same group on
15593 			 * different logical interfaces: we ignore the ilm if
15594 			 * its zoneid is the same as the last matching one.
15595 			 * In addition, the sending of the packet for
15596 			 * ire_zoneid is delayed until all of the other ilms
15597 			 * have been exhausted.
15598 			 */
15599 			last_zoneid = -1;
15600 			ILM_WALKER_HOLD(recv_ill);
15601 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15602 			    ilm = ilm->ilm_next) {
15603 				if ((ilm->ilm_flags & ILM_DELETED) ||
15604 				    ipha->ipha_dst != ilm->ilm_addr ||
15605 				    ilm->ilm_zoneid == last_zoneid ||
15606 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15607 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15608 					continue;
15609 				mp1 = ip_copymsg(first_mp);
15610 				if (mp1 == NULL)
15611 					continue;
15612 				icmp_inbound(q, mp1, B_TRUE, ill,
15613 				    0, sum, mctl_present, B_TRUE,
15614 				    recv_ill, ilm->ilm_zoneid);
15615 				last_zoneid = ilm->ilm_zoneid;
15616 			}
15617 			ILM_WALKER_RELE(recv_ill);
15618 		} else if (ire->ire_type == IRE_BROADCAST) {
15619 			/*
15620 			 * In the broadcast case, there may be many zones
15621 			 * which need a copy of the packet delivered to them.
15622 			 * There is one IRE_BROADCAST per broadcast address
15623 			 * and per zone; we walk those using a helper function.
15624 			 * In addition, the sending of the packet for ire is
15625 			 * delayed until all of the other ires have been
15626 			 * processed.
15627 			 */
15628 			IRB_REFHOLD(ire->ire_bucket);
15629 			ire_zone = NULL;
15630 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15631 			    ire)) != NULL) {
15632 				mp1 = ip_copymsg(first_mp);
15633 				if (mp1 == NULL)
15634 					continue;
15635 
15636 				UPDATE_IB_PKT_COUNT(ire_zone);
15637 				ire_zone->ire_last_used_time = lbolt;
15638 				icmp_inbound(q, mp1, B_TRUE, ill,
15639 				    0, sum, mctl_present, B_TRUE,
15640 				    recv_ill, ire_zone->ire_zoneid);
15641 			}
15642 			IRB_REFRELE(ire->ire_bucket);
15643 		}
15644 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15645 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15646 		    ire->ire_zoneid);
15647 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15648 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15649 		return;
15650 	}
15651 	case IPPROTO_IGMP:
15652 		/*
15653 		 * If we are not willing to accept IGMP packets in clear,
15654 		 * then check with global policy.
15655 		 */
15656 		if (igmp_accept_clear_messages == 0) {
15657 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15658 			    ipha, NULL, mctl_present);
15659 			if (first_mp == NULL)
15660 				return;
15661 		}
15662 		if (igmp_input(q, mp, ill)) {
15663 			/* Bad packet - discarded by igmp_input */
15664 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15665 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15666 			if (mctl_present)
15667 				freeb(first_mp);
15668 			return;
15669 		}
15670 		/*
15671 		 * igmp_input() may have pulled up the message so ipha needs to
15672 		 * be reinitialized.
15673 		 */
15674 		ipha = (ipha_t *)mp->b_rptr;
15675 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15676 			/* No user-level listener for IGMP packets */
15677 			goto drop_pkt;
15678 		}
15679 		/* deliver to local raw users */
15680 		break;
15681 	case IPPROTO_PIM:
15682 		/*
15683 		 * If we are not willing to accept PIM packets in clear,
15684 		 * then check with global policy.
15685 		 */
15686 		if (pim_accept_clear_messages == 0) {
15687 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15688 			    ipha, NULL, mctl_present);
15689 			if (first_mp == NULL)
15690 				return;
15691 		}
15692 		if (pim_input(q, mp) != 0) {
15693 			/* Bad packet - discarded by pim_input */
15694 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15695 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15696 			if (mctl_present)
15697 				freeb(first_mp);
15698 			return;
15699 		}
15700 
15701 		/*
15702 		 * pim_input() may have pulled up the message so ipha needs to
15703 		 * be reinitialized.
15704 		 */
15705 		ipha = (ipha_t *)mp->b_rptr;
15706 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15707 			/* No user-level listener for PIM packets */
15708 			goto drop_pkt;
15709 		}
15710 		/* deliver to local raw users */
15711 		break;
15712 	case IPPROTO_ENCAP:
15713 		/*
15714 		 * Handle self-encapsulated packets (IP-in-IP where
15715 		 * the inner addresses == the outer addresses).
15716 		 */
15717 		hdr_length = IPH_HDR_LENGTH(ipha);
15718 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15719 		    mp->b_wptr) {
15720 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15721 			    sizeof (ipha_t) - mp->b_rptr)) {
15722 				BUMP_MIB(&ip_mib, ipInDiscards);
15723 				freemsg(first_mp);
15724 				return;
15725 			}
15726 			ipha = (ipha_t *)mp->b_rptr;
15727 		}
15728 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15729 		/*
15730 		 * Check the sanity of the inner IP header.
15731 		 */
15732 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15733 			BUMP_MIB(&ip_mib, ipInDiscards);
15734 			freemsg(first_mp);
15735 			return;
15736 		}
15737 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15738 			BUMP_MIB(&ip_mib, ipInDiscards);
15739 			freemsg(first_mp);
15740 			return;
15741 		}
15742 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15743 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15744 			ipsec_in_t *ii;
15745 
15746 			/*
15747 			 * Self-encapsulated tunnel packet. Remove
15748 			 * the outer IP header and fanout again.
15749 			 * We also need to make sure that the inner
15750 			 * header is pulled up until options.
15751 			 */
15752 			mp->b_rptr = (uchar_t *)inner_ipha;
15753 			ipha = inner_ipha;
15754 			hdr_length = IPH_HDR_LENGTH(ipha);
15755 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15756 				if (!pullupmsg(mp, (uchar_t *)ipha +
15757 				    + hdr_length - mp->b_rptr)) {
15758 					freemsg(first_mp);
15759 					return;
15760 				}
15761 				ipha = (ipha_t *)mp->b_rptr;
15762 			}
15763 			if (!mctl_present) {
15764 				ASSERT(first_mp == mp);
15765 				/*
15766 				 * This means that somebody is sending
15767 				 * Self-encapsualted packets without AH/ESP.
15768 				 * If AH/ESP was present, we would have already
15769 				 * allocated the first_mp.
15770 				 */
15771 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15772 				    NULL) {
15773 					ip1dbg(("ip_proto_input: IPSEC_IN "
15774 					    "allocation failure.\n"));
15775 					BUMP_MIB(&ip_mib, ipInDiscards);
15776 					freemsg(mp);
15777 					return;
15778 				}
15779 				first_mp->b_cont = mp;
15780 			}
15781 			/*
15782 			 * We generally store the ill_index if we need to
15783 			 * do IPSEC processing as we lose the ill queue when
15784 			 * we come back. But in this case, we never should
15785 			 * have to store the ill_index here as it should have
15786 			 * been stored previously when we processed the
15787 			 * AH/ESP header in this routine or for non-ipsec
15788 			 * cases, we still have the queue. But for some bad
15789 			 * packets from the wire, we can get to IPSEC after
15790 			 * this and we better store the index for that case.
15791 			 */
15792 			ill = (ill_t *)q->q_ptr;
15793 			ii = (ipsec_in_t *)first_mp->b_rptr;
15794 			ii->ipsec_in_ill_index =
15795 			    ill->ill_phyint->phyint_ifindex;
15796 			ii->ipsec_in_rill_index =
15797 			    recv_ill->ill_phyint->phyint_ifindex;
15798 			if (ii->ipsec_in_decaps) {
15799 				/*
15800 				 * This packet is self-encapsulated multiple
15801 				 * times. We don't want to recurse infinitely.
15802 				 * To keep it simple, drop the packet.
15803 				 */
15804 				BUMP_MIB(&ip_mib, ipInDiscards);
15805 				freemsg(first_mp);
15806 				return;
15807 			}
15808 			ii->ipsec_in_decaps = B_TRUE;
15809 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15810 			return;
15811 		}
15812 		break;
15813 	case IPPROTO_AH:
15814 	case IPPROTO_ESP: {
15815 		/*
15816 		 * Fast path for AH/ESP. If this is the first time
15817 		 * we are sending a datagram to AH/ESP, allocate
15818 		 * a IPSEC_IN message and prepend it. Otherwise,
15819 		 * just fanout.
15820 		 */
15821 
15822 		int ipsec_rc;
15823 		ipsec_in_t *ii;
15824 
15825 		IP_STAT(ipsec_proto_ahesp);
15826 		if (!mctl_present) {
15827 			ASSERT(first_mp == mp);
15828 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15829 				ip1dbg(("ip_proto_input: IPSEC_IN "
15830 				    "allocation failure.\n"));
15831 				freemsg(hada_mp); /* okay ifnull */
15832 				BUMP_MIB(&ip_mib, ipInDiscards);
15833 				freemsg(mp);
15834 				return;
15835 			}
15836 			/*
15837 			 * Store the ill_index so that when we come back
15838 			 * from IPSEC we ride on the same queue.
15839 			 */
15840 			ill = (ill_t *)q->q_ptr;
15841 			ii = (ipsec_in_t *)first_mp->b_rptr;
15842 			ii->ipsec_in_ill_index =
15843 			    ill->ill_phyint->phyint_ifindex;
15844 			ii->ipsec_in_rill_index =
15845 			    recv_ill->ill_phyint->phyint_ifindex;
15846 			first_mp->b_cont = mp;
15847 			/*
15848 			 * Cache hardware acceleration info.
15849 			 */
15850 			if (hada_mp != NULL) {
15851 				IPSECHW_DEBUG(IPSECHW_PKT,
15852 				    ("ip_rput_local: caching data attr.\n"));
15853 				ii->ipsec_in_accelerated = B_TRUE;
15854 				ii->ipsec_in_da = hada_mp;
15855 				hada_mp = NULL;
15856 			}
15857 		} else {
15858 			ii = (ipsec_in_t *)first_mp->b_rptr;
15859 		}
15860 
15861 		if (!ipsec_loaded()) {
15862 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15863 			    ire->ire_zoneid);
15864 			return;
15865 		}
15866 
15867 		/* select inbound SA and have IPsec process the pkt */
15868 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15869 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15870 			if (esph == NULL)
15871 				return;
15872 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15873 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15874 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15875 			    first_mp, esph);
15876 		} else {
15877 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15878 			if (ah == NULL)
15879 				return;
15880 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15881 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15882 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15883 			    first_mp, ah);
15884 		}
15885 
15886 		switch (ipsec_rc) {
15887 		case IPSEC_STATUS_SUCCESS:
15888 			break;
15889 		case IPSEC_STATUS_FAILED:
15890 			BUMP_MIB(&ip_mib, ipInDiscards);
15891 			/* FALLTHRU */
15892 		case IPSEC_STATUS_PENDING:
15893 			return;
15894 		}
15895 		/* we're done with IPsec processing, send it up */
15896 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15897 		return;
15898 	}
15899 	default:
15900 		break;
15901 	}
15902 	/*
15903 	 * Handle protocols with which IP is less intimate.  There
15904 	 * can be more than one stream bound to a particular
15905 	 * protocol.  When this is the case, each one gets a copy
15906 	 * of any incoming packets.
15907 	 */
15908 	ip_fanout_proto(q, first_mp, ill, ipha,
15909 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15910 	    B_TRUE, recv_ill, ire->ire_zoneid);
15911 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15912 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15913 	return;
15914 
15915 drop_pkt:
15916 	freemsg(first_mp);
15917 	if (hada_mp != NULL)
15918 		freeb(hada_mp);
15919 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15920 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15921 #undef	rptr
15922 #undef  iphs
15923 
15924 }
15925 
15926 /*
15927  * Update any source route, record route or timestamp options.
15928  * Check that we are at end of strict source route.
15929  * The options have already been checked for sanity in ip_rput_options().
15930  */
15931 static boolean_t
15932 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15933 {
15934 	ipoptp_t	opts;
15935 	uchar_t		*opt;
15936 	uint8_t		optval;
15937 	uint8_t		optlen;
15938 	ipaddr_t	dst;
15939 	uint32_t	ts;
15940 	ire_t		*dst_ire;
15941 	timestruc_t	now;
15942 
15943 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15944 
15945 	ip2dbg(("ip_rput_local_options\n"));
15946 
15947 	for (optval = ipoptp_first(&opts, ipha);
15948 	    optval != IPOPT_EOL;
15949 	    optval = ipoptp_next(&opts)) {
15950 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15951 		opt = opts.ipoptp_cur;
15952 		optlen = opts.ipoptp_len;
15953 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15954 		    optval, optlen));
15955 		switch (optval) {
15956 			uint32_t off;
15957 		case IPOPT_SSRR:
15958 		case IPOPT_LSRR:
15959 			off = opt[IPOPT_OFFSET];
15960 			off--;
15961 			if (optlen < IP_ADDR_LEN ||
15962 			    off > optlen - IP_ADDR_LEN) {
15963 				/* End of source route */
15964 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15965 				break;
15966 			}
15967 			/*
15968 			 * This will only happen if two consecutive entries
15969 			 * in the source route contains our address or if
15970 			 * it is a packet with a loose source route which
15971 			 * reaches us before consuming the whole source route
15972 			 */
15973 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15974 			if (optval == IPOPT_SSRR) {
15975 				goto bad_src_route;
15976 			}
15977 			/*
15978 			 * Hack: instead of dropping the packet truncate the
15979 			 * source route to what has been used by filling the
15980 			 * rest with IPOPT_NOP.
15981 			 */
15982 			opt[IPOPT_OLEN] = (uint8_t)off;
15983 			while (off < optlen) {
15984 				opt[off++] = IPOPT_NOP;
15985 			}
15986 			break;
15987 		case IPOPT_RR:
15988 			off = opt[IPOPT_OFFSET];
15989 			off--;
15990 			if (optlen < IP_ADDR_LEN ||
15991 			    off > optlen - IP_ADDR_LEN) {
15992 				/* No more room - ignore */
15993 				ip1dbg((
15994 				    "ip_rput_local_options: end of RR\n"));
15995 				break;
15996 			}
15997 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15998 			    IP_ADDR_LEN);
15999 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16000 			break;
16001 		case IPOPT_TS:
16002 			/* Insert timestamp if there is romm */
16003 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16004 			case IPOPT_TS_TSONLY:
16005 				off = IPOPT_TS_TIMELEN;
16006 				break;
16007 			case IPOPT_TS_PRESPEC:
16008 			case IPOPT_TS_PRESPEC_RFC791:
16009 				/* Verify that the address matched */
16010 				off = opt[IPOPT_OFFSET] - 1;
16011 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16012 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16013 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
16014 				if (dst_ire == NULL) {
16015 					/* Not for us */
16016 					break;
16017 				}
16018 				ire_refrele(dst_ire);
16019 				/* FALLTHRU */
16020 			case IPOPT_TS_TSANDADDR:
16021 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16022 				break;
16023 			default:
16024 				/*
16025 				 * ip_*put_options should have already
16026 				 * dropped this packet.
16027 				 */
16028 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16029 				    "unknown IT - bug in ip_rput_options?\n");
16030 				return (B_TRUE);	/* Keep "lint" happy */
16031 			}
16032 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16033 				/* Increase overflow counter */
16034 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16035 				opt[IPOPT_POS_OV_FLG] =
16036 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16037 				    (off << 4));
16038 				break;
16039 			}
16040 			off = opt[IPOPT_OFFSET] - 1;
16041 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16042 			case IPOPT_TS_PRESPEC:
16043 			case IPOPT_TS_PRESPEC_RFC791:
16044 			case IPOPT_TS_TSANDADDR:
16045 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16046 				    IP_ADDR_LEN);
16047 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16048 				/* FALLTHRU */
16049 			case IPOPT_TS_TSONLY:
16050 				off = opt[IPOPT_OFFSET] - 1;
16051 				/* Compute # of milliseconds since midnight */
16052 				gethrestime(&now);
16053 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16054 				    now.tv_nsec / (NANOSEC / MILLISEC);
16055 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16056 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16057 				break;
16058 			}
16059 			break;
16060 		}
16061 	}
16062 	return (B_TRUE);
16063 
16064 bad_src_route:
16065 	q = WR(q);
16066 	/* make sure we clear any indication of a hardware checksum */
16067 	DB_CKSUMFLAGS(mp) = 0;
16068 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16069 	return (B_FALSE);
16070 
16071 }
16072 
16073 /*
16074  * Process IP options in an inbound packet.  If an option affects the
16075  * effective destination address, return the next hop address via dstp.
16076  * Returns -1 if something fails in which case an ICMP error has been sent
16077  * and mp freed.
16078  */
16079 static int
16080 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16081 {
16082 	ipoptp_t	opts;
16083 	uchar_t		*opt;
16084 	uint8_t		optval;
16085 	uint8_t		optlen;
16086 	ipaddr_t	dst;
16087 	intptr_t	code = 0;
16088 	ire_t		*ire = NULL;
16089 
16090 	ip2dbg(("ip_rput_options\n"));
16091 	dst = ipha->ipha_dst;
16092 	for (optval = ipoptp_first(&opts, ipha);
16093 	    optval != IPOPT_EOL;
16094 	    optval = ipoptp_next(&opts)) {
16095 		opt = opts.ipoptp_cur;
16096 		optlen = opts.ipoptp_len;
16097 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16098 		    optval, optlen));
16099 		/*
16100 		 * Note: we need to verify the checksum before we
16101 		 * modify anything thus this routine only extracts the next
16102 		 * hop dst from any source route.
16103 		 */
16104 		switch (optval) {
16105 			uint32_t off;
16106 		case IPOPT_SSRR:
16107 		case IPOPT_LSRR:
16108 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16109 			    ALL_ZONES, MATCH_IRE_TYPE);
16110 			if (ire == NULL) {
16111 				if (optval == IPOPT_SSRR) {
16112 					ip1dbg(("ip_rput_options: not next"
16113 					    " strict source route 0x%x\n",
16114 					    ntohl(dst)));
16115 					code = (char *)&ipha->ipha_dst -
16116 					    (char *)ipha;
16117 					goto param_prob; /* RouterReq's */
16118 				}
16119 				ip2dbg(("ip_rput_options: "
16120 				    "not next source route 0x%x\n",
16121 				    ntohl(dst)));
16122 				break;
16123 			}
16124 			ire_refrele(ire);
16125 
16126 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16127 				ip1dbg((
16128 				    "ip_rput_options: bad option offset\n"));
16129 				code = (char *)&opt[IPOPT_OLEN] -
16130 				    (char *)ipha;
16131 				goto param_prob;
16132 			}
16133 			off = opt[IPOPT_OFFSET];
16134 			off--;
16135 		redo_srr:
16136 			if (optlen < IP_ADDR_LEN ||
16137 			    off > optlen - IP_ADDR_LEN) {
16138 				/* End of source route */
16139 				ip1dbg(("ip_rput_options: end of SR\n"));
16140 				break;
16141 			}
16142 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16143 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16144 			    ntohl(dst)));
16145 
16146 			/*
16147 			 * Check if our address is present more than
16148 			 * once as consecutive hops in source route.
16149 			 * XXX verify per-interface ip_forwarding
16150 			 * for source route?
16151 			 */
16152 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16153 			    ALL_ZONES, MATCH_IRE_TYPE);
16154 
16155 			if (ire != NULL) {
16156 				ire_refrele(ire);
16157 				off += IP_ADDR_LEN;
16158 				goto redo_srr;
16159 			}
16160 
16161 			if (dst == htonl(INADDR_LOOPBACK)) {
16162 				ip1dbg(("ip_rput_options: loopback addr in "
16163 				    "source route!\n"));
16164 				goto bad_src_route;
16165 			}
16166 			/*
16167 			 * For strict: verify that dst is directly
16168 			 * reachable.
16169 			 */
16170 			if (optval == IPOPT_SSRR) {
16171 				ire = ire_ftable_lookup(dst, 0, 0,
16172 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16173 				    MATCH_IRE_TYPE);
16174 				if (ire == NULL) {
16175 					ip1dbg(("ip_rput_options: SSRR not "
16176 					    "directly reachable: 0x%x\n",
16177 					    ntohl(dst)));
16178 					goto bad_src_route;
16179 				}
16180 				ire_refrele(ire);
16181 			}
16182 			/*
16183 			 * Defer update of the offset and the record route
16184 			 * until the packet is forwarded.
16185 			 */
16186 			break;
16187 		case IPOPT_RR:
16188 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16189 				ip1dbg((
16190 				    "ip_rput_options: bad option offset\n"));
16191 				code = (char *)&opt[IPOPT_OLEN] -
16192 				    (char *)ipha;
16193 				goto param_prob;
16194 			}
16195 			break;
16196 		case IPOPT_TS:
16197 			/*
16198 			 * Verify that length >= 5 and that there is either
16199 			 * room for another timestamp or that the overflow
16200 			 * counter is not maxed out.
16201 			 */
16202 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16203 			if (optlen < IPOPT_MINLEN_IT) {
16204 				goto param_prob;
16205 			}
16206 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16207 				ip1dbg((
16208 				    "ip_rput_options: bad option offset\n"));
16209 				code = (char *)&opt[IPOPT_OFFSET] -
16210 				    (char *)ipha;
16211 				goto param_prob;
16212 			}
16213 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16214 			case IPOPT_TS_TSONLY:
16215 				off = IPOPT_TS_TIMELEN;
16216 				break;
16217 			case IPOPT_TS_TSANDADDR:
16218 			case IPOPT_TS_PRESPEC:
16219 			case IPOPT_TS_PRESPEC_RFC791:
16220 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16221 				break;
16222 			default:
16223 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16224 				    (char *)ipha;
16225 				goto param_prob;
16226 			}
16227 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16228 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16229 				/*
16230 				 * No room and the overflow counter is 15
16231 				 * already.
16232 				 */
16233 				goto param_prob;
16234 			}
16235 			break;
16236 		}
16237 	}
16238 
16239 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16240 		*dstp = dst;
16241 		return (0);
16242 	}
16243 
16244 	ip1dbg(("ip_rput_options: error processing IP options."));
16245 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16246 
16247 param_prob:
16248 	q = WR(q);
16249 	/* make sure we clear any indication of a hardware checksum */
16250 	DB_CKSUMFLAGS(mp) = 0;
16251 	icmp_param_problem(q, mp, (uint8_t)code);
16252 	return (-1);
16253 
16254 bad_src_route:
16255 	q = WR(q);
16256 	/* make sure we clear any indication of a hardware checksum */
16257 	DB_CKSUMFLAGS(mp) = 0;
16258 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16259 	return (-1);
16260 }
16261 
16262 /*
16263  * IP & ICMP info in >=14 msg's ...
16264  *  - ip fixed part (mib2_ip_t)
16265  *  - icmp fixed part (mib2_icmp_t)
16266  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16267  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16268  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16269  *  - ip multicast membership (ip_member_t)
16270  *  - ip multicast source filtering (ip_grpsrc_t)
16271  *  - igmp fixed part (struct igmpstat)
16272  *  - multicast routing stats (struct mrtstat)
16273  *  - multicast routing vifs (array of struct vifctl)
16274  *  - multicast routing routes (array of struct mfcctl)
16275  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16276  *					One per ill plus one generic
16277  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16278  *					One per ill plus one generic
16279  *  - ipv6RouteEntry			all IPv6 IREs
16280  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16281  *  - ipv6AddrEntry			all IPv6 ipifs
16282  *  - ipv6 multicast membership (ipv6_member_t)
16283  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16284  *
16285  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16286  * already present.
16287  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16288  * already filled in by caller.
16289  * Return value of 0 indicates that no messages were sent and caller
16290  * should free mpctl.
16291  */
16292 int
16293 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16294 {
16295 
16296 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16297 		return (0);
16298 	}
16299 
16300 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16301 		return (1);
16302 	}
16303 
16304 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16305 		return (1);
16306 	}
16307 
16308 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16309 		return (1);
16310 	}
16311 
16312 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16313 		return (1);
16314 	}
16315 
16316 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16317 		return (1);
16318 	}
16319 
16320 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16321 		return (1);
16322 	}
16323 
16324 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16325 		return (1);
16326 	}
16327 
16328 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16329 		return (1);
16330 	}
16331 
16332 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16333 		return (1);
16334 	}
16335 
16336 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16337 		return (1);
16338 	}
16339 
16340 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16341 		return (1);
16342 	}
16343 
16344 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16345 		return (1);
16346 	}
16347 
16348 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16349 		return (1);
16350 	}
16351 
16352 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16353 		return (1);
16354 	}
16355 
16356 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16357 		return (1);
16358 	}
16359 
16360 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16361 		return (1);
16362 	}
16363 
16364 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16365 		return (1);
16366 	}
16367 	freemsg(mpctl);
16368 	return (1);
16369 }
16370 
16371 
16372 /* Get global IPv4 statistics */
16373 static mblk_t *
16374 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16375 {
16376 	struct opthdr		*optp;
16377 	mblk_t			*mp2ctl;
16378 
16379 	/*
16380 	 * make a copy of the original message
16381 	 */
16382 	mp2ctl = copymsg(mpctl);
16383 
16384 	/* fixed length IP structure... */
16385 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16386 	optp->level = MIB2_IP;
16387 	optp->name = 0;
16388 	SET_MIB(ip_mib.ipForwarding,
16389 	    (WE_ARE_FORWARDING ? 1 : 2));
16390 	SET_MIB(ip_mib.ipDefaultTTL,
16391 	    (uint32_t)ip_def_ttl);
16392 	SET_MIB(ip_mib.ipReasmTimeout,
16393 	    ip_g_frag_timeout);
16394 	SET_MIB(ip_mib.ipAddrEntrySize,
16395 	    sizeof (mib2_ipAddrEntry_t));
16396 	SET_MIB(ip_mib.ipRouteEntrySize,
16397 	    sizeof (mib2_ipRouteEntry_t));
16398 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16399 	    sizeof (mib2_ipNetToMediaEntry_t));
16400 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16401 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16402 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16403 	    (int)sizeof (ip_mib))) {
16404 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16405 		    (uint_t)sizeof (ip_mib)));
16406 	}
16407 
16408 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16409 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16410 	    (int)optp->level, (int)optp->name, (int)optp->len));
16411 	qreply(q, mpctl);
16412 	return (mp2ctl);
16413 }
16414 
16415 /* Global IPv4 ICMP statistics */
16416 static mblk_t *
16417 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16418 {
16419 	struct opthdr		*optp;
16420 	mblk_t			*mp2ctl;
16421 
16422 	/*
16423 	 * Make a copy of the original message
16424 	 */
16425 	mp2ctl = copymsg(mpctl);
16426 
16427 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16428 	optp->level = MIB2_ICMP;
16429 	optp->name = 0;
16430 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16431 	    (int)sizeof (icmp_mib))) {
16432 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16433 		    (uint_t)sizeof (icmp_mib)));
16434 	}
16435 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16436 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16437 	    (int)optp->level, (int)optp->name, (int)optp->len));
16438 	qreply(q, mpctl);
16439 	return (mp2ctl);
16440 }
16441 
16442 /* Global IPv4 IGMP statistics */
16443 static mblk_t *
16444 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16445 {
16446 	struct opthdr		*optp;
16447 	mblk_t			*mp2ctl;
16448 
16449 	/*
16450 	 * make a copy of the original message
16451 	 */
16452 	mp2ctl = copymsg(mpctl);
16453 
16454 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16455 	optp->level = EXPER_IGMP;
16456 	optp->name = 0;
16457 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16458 	    (int)sizeof (igmpstat))) {
16459 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16460 		    (uint_t)sizeof (igmpstat)));
16461 	}
16462 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16463 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16464 	    (int)optp->level, (int)optp->name, (int)optp->len));
16465 	qreply(q, mpctl);
16466 	return (mp2ctl);
16467 }
16468 
16469 /* Global IPv4 Multicast Routing statistics */
16470 static mblk_t *
16471 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16472 {
16473 	struct opthdr		*optp;
16474 	mblk_t			*mp2ctl;
16475 
16476 	/*
16477 	 * make a copy of the original message
16478 	 */
16479 	mp2ctl = copymsg(mpctl);
16480 
16481 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16482 	optp->level = EXPER_DVMRP;
16483 	optp->name = 0;
16484 	if (!ip_mroute_stats(mpctl->b_cont)) {
16485 		ip0dbg(("ip_mroute_stats: failed\n"));
16486 	}
16487 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16488 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16489 	    (int)optp->level, (int)optp->name, (int)optp->len));
16490 	qreply(q, mpctl);
16491 	return (mp2ctl);
16492 }
16493 
16494 /* IPv4 address information */
16495 static mblk_t *
16496 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16497 {
16498 	struct opthdr		*optp;
16499 	mblk_t			*mp2ctl;
16500 	mblk_t			*mp_tail = NULL;
16501 	ill_t			*ill;
16502 	ipif_t			*ipif;
16503 	uint_t			bitval;
16504 	mib2_ipAddrEntry_t	mae;
16505 	zoneid_t		zoneid;
16506 	ill_walk_context_t ctx;
16507 
16508 	/*
16509 	 * make a copy of the original message
16510 	 */
16511 	mp2ctl = copymsg(mpctl);
16512 
16513 	/* ipAddrEntryTable */
16514 
16515 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16516 	optp->level = MIB2_IP;
16517 	optp->name = MIB2_IP_ADDR;
16518 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16519 
16520 	rw_enter(&ill_g_lock, RW_READER);
16521 	ill = ILL_START_WALK_V4(&ctx);
16522 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16523 		for (ipif = ill->ill_ipif; ipif != NULL;
16524 		    ipif = ipif->ipif_next) {
16525 			if (ipif->ipif_zoneid != zoneid)
16526 				continue;
16527 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16528 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16529 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16530 
16531 			(void) ipif_get_name(ipif,
16532 			    mae.ipAdEntIfIndex.o_bytes,
16533 			    OCTET_LENGTH);
16534 			mae.ipAdEntIfIndex.o_length =
16535 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16536 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16537 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16538 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16539 			mae.ipAdEntInfo.ae_subnet_len =
16540 			    ip_mask_to_plen(ipif->ipif_net_mask);
16541 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16542 			for (bitval = 1;
16543 			    bitval &&
16544 			    !(bitval & ipif->ipif_brd_addr);
16545 			    bitval <<= 1)
16546 				noop;
16547 			mae.ipAdEntBcastAddr = bitval;
16548 			mae.ipAdEntReasmMaxSize = 65535;
16549 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16550 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16551 			mae.ipAdEntInfo.ae_broadcast_addr =
16552 			    ipif->ipif_brd_addr;
16553 			mae.ipAdEntInfo.ae_pp_dst_addr =
16554 			    ipif->ipif_pp_dst_addr;
16555 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16556 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16557 
16558 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16559 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16560 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16561 				    "allocate %u bytes\n",
16562 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16563 			}
16564 		}
16565 	}
16566 	rw_exit(&ill_g_lock);
16567 
16568 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16569 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16570 	    (int)optp->level, (int)optp->name, (int)optp->len));
16571 	qreply(q, mpctl);
16572 	return (mp2ctl);
16573 }
16574 
16575 /* IPv6 address information */
16576 static mblk_t *
16577 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16578 {
16579 	struct opthdr		*optp;
16580 	mblk_t			*mp2ctl;
16581 	mblk_t			*mp_tail = NULL;
16582 	ill_t			*ill;
16583 	ipif_t			*ipif;
16584 	mib2_ipv6AddrEntry_t	mae6;
16585 	zoneid_t		zoneid;
16586 	ill_walk_context_t	ctx;
16587 
16588 	/*
16589 	 * make a copy of the original message
16590 	 */
16591 	mp2ctl = copymsg(mpctl);
16592 
16593 	/* ipv6AddrEntryTable */
16594 
16595 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16596 	optp->level = MIB2_IP6;
16597 	optp->name = MIB2_IP6_ADDR;
16598 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16599 
16600 	rw_enter(&ill_g_lock, RW_READER);
16601 	ill = ILL_START_WALK_V6(&ctx);
16602 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16603 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16604 			if (ipif->ipif_zoneid != zoneid)
16605 				continue;
16606 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16607 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16608 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16609 
16610 			(void) ipif_get_name(ipif,
16611 			    mae6.ipv6AddrIfIndex.o_bytes,
16612 			    OCTET_LENGTH);
16613 			mae6.ipv6AddrIfIndex.o_length =
16614 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16615 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16616 			mae6.ipv6AddrPfxLength =
16617 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16618 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16619 			mae6.ipv6AddrInfo.ae_subnet_len =
16620 			    mae6.ipv6AddrPfxLength;
16621 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16622 
16623 			/* Type: stateless(1), stateful(2), unknown(3) */
16624 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16625 				mae6.ipv6AddrType = 1;
16626 			else
16627 				mae6.ipv6AddrType = 2;
16628 			/* Anycast: true(1), false(2) */
16629 			if (ipif->ipif_flags & IPIF_ANYCAST)
16630 				mae6.ipv6AddrAnycastFlag = 1;
16631 			else
16632 				mae6.ipv6AddrAnycastFlag = 2;
16633 
16634 			/*
16635 			 * Address status: preferred(1), deprecated(2),
16636 			 * invalid(3), inaccessible(4), unknown(5)
16637 			 */
16638 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16639 				mae6.ipv6AddrStatus = 3;
16640 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16641 				mae6.ipv6AddrStatus = 2;
16642 			else
16643 				mae6.ipv6AddrStatus = 1;
16644 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16645 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16646 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16647 						ipif->ipif_v6pp_dst_addr;
16648 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16649 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16650 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16651 				(char *)&mae6,
16652 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16653 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16654 				    "allocate %u bytes\n",
16655 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16656 			}
16657 		}
16658 	}
16659 	rw_exit(&ill_g_lock);
16660 
16661 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16662 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16663 	    (int)optp->level, (int)optp->name, (int)optp->len));
16664 	qreply(q, mpctl);
16665 	return (mp2ctl);
16666 }
16667 
16668 /* IPv4 multicast group membership. */
16669 static mblk_t *
16670 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16671 {
16672 	struct opthdr		*optp;
16673 	mblk_t			*mp2ctl;
16674 	ill_t			*ill;
16675 	ipif_t			*ipif;
16676 	ilm_t			*ilm;
16677 	ip_member_t		ipm;
16678 	mblk_t			*mp_tail = NULL;
16679 	ill_walk_context_t	ctx;
16680 	zoneid_t		zoneid;
16681 
16682 	/*
16683 	 * make a copy of the original message
16684 	 */
16685 	mp2ctl = copymsg(mpctl);
16686 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16687 
16688 	/* ipGroupMember table */
16689 	optp = (struct opthdr *)&mpctl->b_rptr[
16690 	    sizeof (struct T_optmgmt_ack)];
16691 	optp->level = MIB2_IP;
16692 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16693 
16694 	rw_enter(&ill_g_lock, RW_READER);
16695 	ill = ILL_START_WALK_V4(&ctx);
16696 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16697 		ILM_WALKER_HOLD(ill);
16698 		for (ipif = ill->ill_ipif; ipif != NULL;
16699 		    ipif = ipif->ipif_next) {
16700 			if (ipif->ipif_zoneid != zoneid)
16701 				continue;	/* not this zone */
16702 			(void) ipif_get_name(ipif,
16703 			    ipm.ipGroupMemberIfIndex.o_bytes,
16704 			    OCTET_LENGTH);
16705 			ipm.ipGroupMemberIfIndex.o_length =
16706 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16707 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16708 				ASSERT(ilm->ilm_ipif != NULL);
16709 				ASSERT(ilm->ilm_ill == NULL);
16710 				if (ilm->ilm_ipif != ipif)
16711 					continue;
16712 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16713 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16714 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16715 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16716 				    (char *)&ipm, (int)sizeof (ipm))) {
16717 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16718 					    "failed to allocate %u bytes\n",
16719 						(uint_t)sizeof (ipm)));
16720 				}
16721 			}
16722 		}
16723 		ILM_WALKER_RELE(ill);
16724 	}
16725 	rw_exit(&ill_g_lock);
16726 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16727 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16728 	    (int)optp->level, (int)optp->name, (int)optp->len));
16729 	qreply(q, mpctl);
16730 	return (mp2ctl);
16731 }
16732 
16733 /* IPv6 multicast group membership. */
16734 static mblk_t *
16735 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16736 {
16737 	struct opthdr		*optp;
16738 	mblk_t			*mp2ctl;
16739 	ill_t			*ill;
16740 	ilm_t			*ilm;
16741 	ipv6_member_t		ipm6;
16742 	mblk_t			*mp_tail = NULL;
16743 	ill_walk_context_t	ctx;
16744 	zoneid_t		zoneid;
16745 
16746 	/*
16747 	 * make a copy of the original message
16748 	 */
16749 	mp2ctl = copymsg(mpctl);
16750 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16751 
16752 	/* ip6GroupMember table */
16753 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16754 	optp->level = MIB2_IP6;
16755 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16756 
16757 	rw_enter(&ill_g_lock, RW_READER);
16758 	ill = ILL_START_WALK_V6(&ctx);
16759 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16760 		ILM_WALKER_HOLD(ill);
16761 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16762 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16763 			ASSERT(ilm->ilm_ipif == NULL);
16764 			ASSERT(ilm->ilm_ill != NULL);
16765 			if (ilm->ilm_zoneid != zoneid)
16766 				continue;	/* not this zone */
16767 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16768 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16769 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16770 			if (!snmp_append_data2(mpctl->b_cont,
16771 			    &mp_tail,
16772 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16773 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16774 				    "failed to allocate %u bytes\n",
16775 				    (uint_t)sizeof (ipm6)));
16776 			}
16777 		}
16778 		ILM_WALKER_RELE(ill);
16779 	}
16780 	rw_exit(&ill_g_lock);
16781 
16782 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16783 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16784 	    (int)optp->level, (int)optp->name, (int)optp->len));
16785 	qreply(q, mpctl);
16786 	return (mp2ctl);
16787 }
16788 
16789 /* IP multicast filtered sources */
16790 static mblk_t *
16791 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16792 {
16793 	struct opthdr		*optp;
16794 	mblk_t			*mp2ctl;
16795 	ill_t			*ill;
16796 	ipif_t			*ipif;
16797 	ilm_t			*ilm;
16798 	ip_grpsrc_t		ips;
16799 	mblk_t			*mp_tail = NULL;
16800 	ill_walk_context_t	ctx;
16801 	zoneid_t		zoneid;
16802 	int			i;
16803 	slist_t			*sl;
16804 
16805 	/*
16806 	 * make a copy of the original message
16807 	 */
16808 	mp2ctl = copymsg(mpctl);
16809 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16810 
16811 	/* ipGroupSource table */
16812 	optp = (struct opthdr *)&mpctl->b_rptr[
16813 	    sizeof (struct T_optmgmt_ack)];
16814 	optp->level = MIB2_IP;
16815 	optp->name = EXPER_IP_GROUP_SOURCES;
16816 
16817 	rw_enter(&ill_g_lock, RW_READER);
16818 	ill = ILL_START_WALK_V4(&ctx);
16819 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16820 		ILM_WALKER_HOLD(ill);
16821 		for (ipif = ill->ill_ipif; ipif != NULL;
16822 		    ipif = ipif->ipif_next) {
16823 			if (ipif->ipif_zoneid != zoneid)
16824 				continue;	/* not this zone */
16825 			(void) ipif_get_name(ipif,
16826 			    ips.ipGroupSourceIfIndex.o_bytes,
16827 			    OCTET_LENGTH);
16828 			ips.ipGroupSourceIfIndex.o_length =
16829 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16830 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16831 				ASSERT(ilm->ilm_ipif != NULL);
16832 				ASSERT(ilm->ilm_ill == NULL);
16833 				sl = ilm->ilm_filter;
16834 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16835 					continue;
16836 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16837 				for (i = 0; i < sl->sl_numsrc; i++) {
16838 					if (!IN6_IS_ADDR_V4MAPPED(
16839 					    &sl->sl_addr[i]))
16840 						continue;
16841 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16842 					    ips.ipGroupSourceAddress);
16843 					if (snmp_append_data2(mpctl->b_cont,
16844 					    &mp_tail, (char *)&ips,
16845 					    (int)sizeof (ips)) == 0) {
16846 						ip1dbg(("ip_snmp_get_mib2_"
16847 						    "ip_group_src: failed to "
16848 						    "allocate %u bytes\n",
16849 						    (uint_t)sizeof (ips)));
16850 					}
16851 				}
16852 			}
16853 		}
16854 		ILM_WALKER_RELE(ill);
16855 	}
16856 	rw_exit(&ill_g_lock);
16857 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16858 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16859 	    (int)optp->level, (int)optp->name, (int)optp->len));
16860 	qreply(q, mpctl);
16861 	return (mp2ctl);
16862 }
16863 
16864 /* IPv6 multicast filtered sources. */
16865 static mblk_t *
16866 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16867 {
16868 	struct opthdr		*optp;
16869 	mblk_t			*mp2ctl;
16870 	ill_t			*ill;
16871 	ilm_t			*ilm;
16872 	ipv6_grpsrc_t		ips6;
16873 	mblk_t			*mp_tail = NULL;
16874 	ill_walk_context_t	ctx;
16875 	zoneid_t		zoneid;
16876 	int			i;
16877 	slist_t			*sl;
16878 
16879 	/*
16880 	 * make a copy of the original message
16881 	 */
16882 	mp2ctl = copymsg(mpctl);
16883 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16884 
16885 	/* ip6GroupMember table */
16886 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16887 	optp->level = MIB2_IP6;
16888 	optp->name = EXPER_IP6_GROUP_SOURCES;
16889 
16890 	rw_enter(&ill_g_lock, RW_READER);
16891 	ill = ILL_START_WALK_V6(&ctx);
16892 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16893 		ILM_WALKER_HOLD(ill);
16894 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16895 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16896 			ASSERT(ilm->ilm_ipif == NULL);
16897 			ASSERT(ilm->ilm_ill != NULL);
16898 			sl = ilm->ilm_filter;
16899 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16900 				continue;
16901 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16902 			for (i = 0; i < sl->sl_numsrc; i++) {
16903 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16904 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16905 				    (char *)&ips6, (int)sizeof (ips6))) {
16906 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16907 					    "group_src: failed to allocate "
16908 					    "%u bytes\n",
16909 					    (uint_t)sizeof (ips6)));
16910 				}
16911 			}
16912 		}
16913 		ILM_WALKER_RELE(ill);
16914 	}
16915 	rw_exit(&ill_g_lock);
16916 
16917 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16918 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16919 	    (int)optp->level, (int)optp->name, (int)optp->len));
16920 	qreply(q, mpctl);
16921 	return (mp2ctl);
16922 }
16923 
16924 /* Multicast routing virtual interface table. */
16925 static mblk_t *
16926 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16927 {
16928 	struct opthdr		*optp;
16929 	mblk_t			*mp2ctl;
16930 
16931 	/*
16932 	 * make a copy of the original message
16933 	 */
16934 	mp2ctl = copymsg(mpctl);
16935 
16936 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16937 	optp->level = EXPER_DVMRP;
16938 	optp->name = EXPER_DVMRP_VIF;
16939 	if (!ip_mroute_vif(mpctl->b_cont)) {
16940 		ip0dbg(("ip_mroute_vif: failed\n"));
16941 	}
16942 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16943 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16944 	    (int)optp->level, (int)optp->name, (int)optp->len));
16945 	qreply(q, mpctl);
16946 	return (mp2ctl);
16947 }
16948 
16949 /* Multicast routing table. */
16950 static mblk_t *
16951 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16952 {
16953 	struct opthdr		*optp;
16954 	mblk_t			*mp2ctl;
16955 
16956 	/*
16957 	 * make a copy of the original message
16958 	 */
16959 	mp2ctl = copymsg(mpctl);
16960 
16961 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16962 	optp->level = EXPER_DVMRP;
16963 	optp->name = EXPER_DVMRP_MRT;
16964 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16965 		ip0dbg(("ip_mroute_mrt: failed\n"));
16966 	}
16967 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16968 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16969 	    (int)optp->level, (int)optp->name, (int)optp->len));
16970 	qreply(q, mpctl);
16971 	return (mp2ctl);
16972 }
16973 
16974 /*
16975  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16976  * in one IRE walk.
16977  */
16978 static mblk_t *
16979 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16980 {
16981 	struct opthdr		*optp;
16982 	mblk_t			*mp2ctl;	/* Returned */
16983 	mblk_t			*mp3ctl;	/* nettomedia */
16984 	/*
16985 	 * We need two listptrs, for ipRouteEntryTable and
16986 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16987 	 */
16988 	listptr_t		re_ntme_v4[2];
16989 	zoneid_t		zoneid;
16990 
16991 	/*
16992 	 * make a copy of the original message
16993 	 */
16994 	mp2ctl = copymsg(mpctl);
16995 	mp3ctl = copymsg(mpctl);
16996 	if (mp3ctl == NULL) {
16997 		freemsg(mp2ctl);
16998 		freemsg(mpctl);
16999 		return (NULL);
17000 	}
17001 
17002 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
17003 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
17004 	/*
17005 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17006 	 * proper values when called.
17007 	 */
17008 	re_ntme_v4[0].lp_tail = NULL;
17009 	re_ntme_v4[1].lp_tail = NULL;
17010 
17011 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17012 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
17013 	if (zoneid == GLOBAL_ZONEID) {
17014 		/*
17015 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17016 		 * the sys_net_config privilege, it can only run in the global
17017 		 * zone, so we don't display these IREs in the other zones.
17018 		 */
17019 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
17020 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
17021 		    NULL);
17022 	}
17023 
17024 	/* ipRouteEntryTable in mpctl */
17025 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17026 	optp->level = MIB2_IP;
17027 	optp->name = MIB2_IP_ROUTE;
17028 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
17029 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17030 	    (int)optp->level, (int)optp->name, (int)optp->len));
17031 	qreply(q, mpctl);
17032 
17033 	/* ipNetToMediaEntryTable in mp3ctl */
17034 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17035 	optp->level = MIB2_IP;
17036 	optp->name = MIB2_IP_MEDIA;
17037 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
17038 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17039 	    (int)optp->level, (int)optp->name, (int)optp->len));
17040 	qreply(q, mp3ctl);
17041 	return (mp2ctl);
17042 }
17043 
17044 /*
17045  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
17046  * in one IRE walk.
17047  */
17048 static mblk_t *
17049 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17050 {
17051 	struct opthdr		*optp;
17052 	mblk_t			*mp2ctl;	/* Returned */
17053 	mblk_t			*mp3ctl;	/* nettomedia */
17054 	listptr_t		re_ntme_v6;
17055 	zoneid_t		zoneid;
17056 
17057 	/*
17058 	 * make a copy of the original message
17059 	 */
17060 	mp2ctl = copymsg(mpctl);
17061 	mp3ctl = copymsg(mpctl);
17062 	if (mp3ctl == NULL) {
17063 		freemsg(mp2ctl);
17064 		freemsg(mpctl);
17065 		return (NULL);
17066 	}
17067 
17068 	/*
17069 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17070 	 * proper values when called.  ipv6RouteEntryTable in is placed
17071 	 * in mpctl.
17072 	 */
17073 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
17074 	re_ntme_v6.lp_tail = NULL;
17075 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17076 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
17077 
17078 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17079 	optp->level = MIB2_IP6;
17080 	optp->name = MIB2_IP6_ROUTE;
17081 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17082 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17083 	    (int)optp->level, (int)optp->name, (int)optp->len));
17084 	qreply(q, mpctl);
17085 
17086 	/* ipv6NetToMediaEntryTable in mp3ctl */
17087 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
17088 	re_ntme_v6.lp_tail = NULL;
17089 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
17090 
17091 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17092 	optp->level = MIB2_IP6;
17093 	optp->name = MIB2_IP6_MEDIA;
17094 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17095 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17096 	    (int)optp->level, (int)optp->name, (int)optp->len));
17097 	qreply(q, mp3ctl);
17098 	return (mp2ctl);
17099 }
17100 
17101 /*
17102  * ICMPv6 mib: One per ill
17103  */
17104 static mblk_t *
17105 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17106 {
17107 	struct opthdr		*optp;
17108 	mblk_t			*mp2ctl;
17109 	ill_t			*ill;
17110 	ill_walk_context_t	ctx;
17111 	mblk_t			*mp_tail = NULL;
17112 
17113 	/*
17114 	 * Make a copy of the original message
17115 	 */
17116 	mp2ctl = copymsg(mpctl);
17117 
17118 	/* fixed length IPv6 structure ... */
17119 
17120 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17121 	optp->level = MIB2_IP6;
17122 	optp->name = 0;
17123 	/* Include "unknown interface" ip6_mib */
17124 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17125 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17126 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17127 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17128 	    sizeof (mib2_ipv6IfStatsEntry_t));
17129 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17130 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17131 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17132 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17133 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17134 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17135 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17136 	    (int)sizeof (ip6_mib))) {
17137 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17138 		    (uint_t)sizeof (ip6_mib)));
17139 	}
17140 
17141 	rw_enter(&ill_g_lock, RW_READER);
17142 	ill = ILL_START_WALK_V6(&ctx);
17143 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17144 		ill->ill_ip6_mib->ipv6IfIndex =
17145 		    ill->ill_phyint->phyint_ifindex;
17146 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17147 		    ipv6_forward ? 1 : 2);
17148 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17149 		    ill->ill_max_hops);
17150 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17151 		    sizeof (mib2_ipv6IfStatsEntry_t));
17152 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17153 		    sizeof (mib2_ipv6AddrEntry_t));
17154 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17155 		    sizeof (mib2_ipv6RouteEntry_t));
17156 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17157 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17158 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17159 		    sizeof (ipv6_member_t));
17160 
17161 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17162 		    (char *)ill->ill_ip6_mib,
17163 		    (int)sizeof (*ill->ill_ip6_mib))) {
17164 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17165 				"%u bytes\n",
17166 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17167 		}
17168 	}
17169 	rw_exit(&ill_g_lock);
17170 
17171 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17172 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17173 	    (int)optp->level, (int)optp->name, (int)optp->len));
17174 	qreply(q, mpctl);
17175 	return (mp2ctl);
17176 }
17177 
17178 /*
17179  * ICMPv6 mib: One per ill
17180  */
17181 static mblk_t *
17182 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17183 {
17184 	struct opthdr		*optp;
17185 	mblk_t			*mp2ctl;
17186 	ill_t			*ill;
17187 	ill_walk_context_t	ctx;
17188 	mblk_t			*mp_tail = NULL;
17189 	/*
17190 	 * Make a copy of the original message
17191 	 */
17192 	mp2ctl = copymsg(mpctl);
17193 
17194 	/* fixed length ICMPv6 structure ... */
17195 
17196 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17197 	optp->level = MIB2_ICMP6;
17198 	optp->name = 0;
17199 	/* Include "unknown interface" icmp6_mib */
17200 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17201 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17202 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17203 	    (int)sizeof (icmp6_mib))) {
17204 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17205 		    (uint_t)sizeof (icmp6_mib)));
17206 	}
17207 
17208 	rw_enter(&ill_g_lock, RW_READER);
17209 	ill = ILL_START_WALK_V6(&ctx);
17210 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17211 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17212 		    ill->ill_phyint->phyint_ifindex;
17213 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17214 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17215 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17216 		    (char *)ill->ill_icmp6_mib,
17217 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17218 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17219 			    "%u bytes\n",
17220 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17221 		}
17222 	}
17223 	rw_exit(&ill_g_lock);
17224 
17225 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17226 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17227 	    (int)optp->level, (int)optp->name, (int)optp->len));
17228 	qreply(q, mpctl);
17229 	return (mp2ctl);
17230 }
17231 
17232 /*
17233  * ire_walk routine to create both ipRouteEntryTable and
17234  * ipNetToMediaEntryTable in one IRE walk
17235  */
17236 static void
17237 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17238 {
17239 	ill_t				*ill;
17240 	ipif_t				*ipif;
17241 	mblk_t				*llmp;
17242 	dl_unitdata_req_t		*dlup;
17243 	mib2_ipRouteEntry_t		re;
17244 	mib2_ipNetToMediaEntry_t	ntme;
17245 	ipaddr_t			gw_addr;
17246 
17247 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17248 
17249 	/*
17250 	 * Return all IRE types for route table... let caller pick and choose
17251 	 */
17252 	re.ipRouteDest = ire->ire_addr;
17253 	ipif = ire->ire_ipif;
17254 	re.ipRouteIfIndex.o_length = 0;
17255 	if (ire->ire_type == IRE_CACHE) {
17256 		ill = (ill_t *)ire->ire_stq->q_ptr;
17257 		re.ipRouteIfIndex.o_length =
17258 		    ill->ill_name_length == 0 ? 0 :
17259 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17260 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17261 		    re.ipRouteIfIndex.o_length);
17262 	} else if (ipif != NULL) {
17263 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17264 		    OCTET_LENGTH);
17265 		re.ipRouteIfIndex.o_length =
17266 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17267 	}
17268 	re.ipRouteMetric1 = -1;
17269 	re.ipRouteMetric2 = -1;
17270 	re.ipRouteMetric3 = -1;
17271 	re.ipRouteMetric4 = -1;
17272 
17273 	gw_addr = ire->ire_gateway_addr;
17274 
17275 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17276 		re.ipRouteNextHop = ire->ire_src_addr;
17277 	else
17278 		re.ipRouteNextHop = gw_addr;
17279 	/* indirect(4), direct(3), or invalid(2) */
17280 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17281 		re.ipRouteType = 2;
17282 	else
17283 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17284 	re.ipRouteProto = -1;
17285 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17286 	re.ipRouteMask = ire->ire_mask;
17287 	re.ipRouteMetric5 = -1;
17288 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17289 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17290 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17291 	llmp = ire->ire_dlureq_mp;
17292 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17293 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17294 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17295 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17296 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17297 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17298 	re.ipRouteInfo.re_in_ill.o_length = 0;
17299 	if (ire->ire_in_ill != NULL) {
17300 		re.ipRouteInfo.re_in_ill.o_length =
17301 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17302 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17303 		bcopy(ire->ire_in_ill->ill_name,
17304 		    re.ipRouteInfo.re_in_ill.o_bytes,
17305 		    re.ipRouteInfo.re_in_ill.o_length);
17306 	}
17307 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17308 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17309 	    (char *)&re, (int)sizeof (re))) {
17310 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17311 		    (uint_t)sizeof (re)));
17312 	}
17313 
17314 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17315 		return;
17316 	/*
17317 	 * only IRE_CACHE entries that are for a directly connected subnet
17318 	 * get appended to net -> phys addr table
17319 	 * (others in arp)
17320 	 */
17321 	ntme.ipNetToMediaIfIndex.o_length = 0;
17322 	ill = ire_to_ill(ire);
17323 	ASSERT(ill != NULL);
17324 	ntme.ipNetToMediaIfIndex.o_length =
17325 	    ill->ill_name_length == 0 ? 0 :
17326 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17327 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17328 		    ntme.ipNetToMediaIfIndex.o_length);
17329 
17330 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17331 	if (llmp) {
17332 		uchar_t *addr;
17333 
17334 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17335 		/* Remove sap from  address */
17336 		if (ill->ill_sap_length < 0)
17337 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17338 		else
17339 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17340 			    ill->ill_sap_length;
17341 
17342 		ntme.ipNetToMediaPhysAddress.o_length =
17343 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17344 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17345 		    ntme.ipNetToMediaPhysAddress.o_length);
17346 	}
17347 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17348 	/* assume dynamic (may be changed in arp) */
17349 	ntme.ipNetToMediaType = 3;
17350 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17351 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17352 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17353 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17354 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17355 	    (char *)&ntme, (int)sizeof (ntme))) {
17356 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17357 		    (uint_t)sizeof (ntme)));
17358 	}
17359 }
17360 
17361 /*
17362  * ire_walk routine to create ipv6RouteEntryTable.
17363  */
17364 static void
17365 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17366 {
17367 	ill_t				*ill;
17368 	ipif_t				*ipif;
17369 	mib2_ipv6RouteEntry_t		re;
17370 	in6_addr_t			gw_addr_v6;
17371 
17372 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17373 
17374 	/*
17375 	 * Return all IRE types for route table... let caller pick and choose
17376 	 */
17377 	re.ipv6RouteDest = ire->ire_addr_v6;
17378 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17379 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17380 	re.ipv6RouteIfIndex.o_length = 0;
17381 	ipif = ire->ire_ipif;
17382 	if (ire->ire_type == IRE_CACHE) {
17383 		ill = (ill_t *)ire->ire_stq->q_ptr;
17384 		re.ipv6RouteIfIndex.o_length =
17385 		    ill->ill_name_length == 0 ? 0 :
17386 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17387 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17388 		    re.ipv6RouteIfIndex.o_length);
17389 	} else if (ipif != NULL) {
17390 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17391 		    OCTET_LENGTH);
17392 		re.ipv6RouteIfIndex.o_length =
17393 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17394 	}
17395 
17396 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17397 
17398 	mutex_enter(&ire->ire_lock);
17399 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17400 	mutex_exit(&ire->ire_lock);
17401 
17402 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17403 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17404 	else
17405 		re.ipv6RouteNextHop = gw_addr_v6;
17406 
17407 	/* remote(4), local(3), or discard(2) */
17408 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17409 		re.ipv6RouteType = 2;
17410 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17411 		re.ipv6RouteType = 3;
17412 	else
17413 		re.ipv6RouteType = 4;
17414 
17415 	re.ipv6RouteProtocol		= -1;
17416 	re.ipv6RoutePolicy		= 0;
17417 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17418 	re.ipv6RouteNextHopRDI		= 0;
17419 	re.ipv6RouteWeight		= 0;
17420 	re.ipv6RouteMetric		= 0;
17421 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17422 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17423 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17424 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17425 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17426 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17427 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17428 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17429 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17430 
17431 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17432 	    (char *)&re, (int)sizeof (re))) {
17433 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17434 		    (uint_t)sizeof (re)));
17435 	}
17436 }
17437 
17438 /*
17439  * ndp_walk routine to create ipv6NetToMediaEntryTable
17440  */
17441 static int
17442 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17443 {
17444 	ill_t				*ill;
17445 	mib2_ipv6NetToMediaEntry_t	ntme;
17446 	dl_unitdata_req_t		*dl;
17447 
17448 	ill = nce->nce_ill;
17449 	ASSERT(ill->ill_isv6);
17450 
17451 	/*
17452 	 * Neighbor cache entry attached to IRE with on-link
17453 	 * destination.
17454 	 */
17455 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17456 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17457 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17458 	    (nce->nce_res_mp != NULL)) {
17459 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17460 		ntme.ipv6NetToMediaPhysAddress.o_length =
17461 		    dl->dl_dest_addr_length;
17462 	} else {
17463 		ntme.ipv6NetToMediaPhysAddress.o_length =
17464 		    ill->ill_phys_addr_length;
17465 	}
17466 	if (nce->nce_res_mp != NULL) {
17467 		bcopy((char *)nce->nce_res_mp->b_rptr +
17468 		    NCE_LL_ADDR_OFFSET(ill),
17469 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17470 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17471 	} else {
17472 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17473 		    ill->ill_phys_addr_length);
17474 	}
17475 	/*
17476 	 * Note: Returns ND_* states. Should be:
17477 	 * reachable(1), stale(2), delay(3), probe(4),
17478 	 * invalid(5), unknown(6)
17479 	 */
17480 	ntme.ipv6NetToMediaState = nce->nce_state;
17481 	ntme.ipv6NetToMediaLastUpdated = 0;
17482 
17483 	/* other(1), dynamic(2), static(3), local(4) */
17484 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17485 		ntme.ipv6NetToMediaType = 4;
17486 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17487 		ntme.ipv6NetToMediaType = 1;
17488 	} else {
17489 		ntme.ipv6NetToMediaType = 2;
17490 	}
17491 
17492 	if (!snmp_append_data2(re_ntme->lp_head,
17493 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17494 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17495 		    (uint_t)sizeof (ntme)));
17496 	}
17497 	return (0);
17498 }
17499 
17500 /*
17501  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17502  */
17503 /* ARGSUSED */
17504 int
17505 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17506 {
17507 	switch (level) {
17508 	case MIB2_IP:
17509 	case MIB2_ICMP:
17510 		switch (name) {
17511 		default:
17512 			break;
17513 		}
17514 		return (1);
17515 	default:
17516 		return (1);
17517 	}
17518 }
17519 
17520 /*
17521  * Called before the options are updated to check if this packet will
17522  * be source routed from here.
17523  * This routine assumes that the options are well formed i.e. that they
17524  * have already been checked.
17525  */
17526 static boolean_t
17527 ip_source_routed(ipha_t *ipha)
17528 {
17529 	ipoptp_t	opts;
17530 	uchar_t		*opt;
17531 	uint8_t		optval;
17532 	uint8_t		optlen;
17533 	ipaddr_t	dst;
17534 	ire_t		*ire;
17535 
17536 	if (IS_SIMPLE_IPH(ipha)) {
17537 		ip2dbg(("not source routed\n"));
17538 		return (B_FALSE);
17539 	}
17540 	dst = ipha->ipha_dst;
17541 	for (optval = ipoptp_first(&opts, ipha);
17542 	    optval != IPOPT_EOL;
17543 	    optval = ipoptp_next(&opts)) {
17544 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17545 		opt = opts.ipoptp_cur;
17546 		optlen = opts.ipoptp_len;
17547 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17548 		    optval, optlen));
17549 		switch (optval) {
17550 			uint32_t off;
17551 		case IPOPT_SSRR:
17552 		case IPOPT_LSRR:
17553 			/*
17554 			 * If dst is one of our addresses and there are some
17555 			 * entries left in the source route return (true).
17556 			 */
17557 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17558 			    ALL_ZONES, MATCH_IRE_TYPE);
17559 			if (ire == NULL) {
17560 				ip2dbg(("ip_source_routed: not next"
17561 				    " source route 0x%x\n",
17562 				    ntohl(dst)));
17563 				return (B_FALSE);
17564 			}
17565 			ire_refrele(ire);
17566 			off = opt[IPOPT_OFFSET];
17567 			off--;
17568 			if (optlen < IP_ADDR_LEN ||
17569 			    off > optlen - IP_ADDR_LEN) {
17570 				/* End of source route */
17571 				ip1dbg(("ip_source_routed: end of SR\n"));
17572 				return (B_FALSE);
17573 			}
17574 			return (B_TRUE);
17575 		}
17576 	}
17577 	ip2dbg(("not source routed\n"));
17578 	return (B_FALSE);
17579 }
17580 
17581 /*
17582  * Check if the packet contains any source route.
17583  */
17584 static boolean_t
17585 ip_source_route_included(ipha_t *ipha)
17586 {
17587 	ipoptp_t	opts;
17588 	uint8_t		optval;
17589 
17590 	if (IS_SIMPLE_IPH(ipha))
17591 		return (B_FALSE);
17592 	for (optval = ipoptp_first(&opts, ipha);
17593 	    optval != IPOPT_EOL;
17594 	    optval = ipoptp_next(&opts)) {
17595 		switch (optval) {
17596 		case IPOPT_SSRR:
17597 		case IPOPT_LSRR:
17598 			return (B_TRUE);
17599 		}
17600 	}
17601 	return (B_FALSE);
17602 }
17603 
17604 /*
17605  * Called when the IRE expiration timer fires.
17606  */
17607 /* ARGSUSED */
17608 void
17609 ip_trash_timer_expire(void *args)
17610 {
17611 	int	flush_flag = 0;
17612 
17613 	/*
17614 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17615 	 * This lock makes sure that a new invocation of this function
17616 	 * that occurs due to an almost immediate timer firing will not
17617 	 * progress beyond this point until the current invocation is done
17618 	 */
17619 	mutex_enter(&ip_trash_timer_lock);
17620 	ip_ire_expire_id = 0;
17621 	mutex_exit(&ip_trash_timer_lock);
17622 
17623 	/* Periodic timer */
17624 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17625 		/*
17626 		 * Remove all IRE_CACHE entries since they might
17627 		 * contain arp information.
17628 		 */
17629 		flush_flag |= FLUSH_ARP_TIME;
17630 		ip_ire_arp_time_elapsed = 0;
17631 		IP_STAT(ip_ire_arp_timer_expired);
17632 	}
17633 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17634 		/* Remove all redirects */
17635 		flush_flag |= FLUSH_REDIRECT_TIME;
17636 		ip_ire_rd_time_elapsed = 0;
17637 		IP_STAT(ip_ire_redirect_timer_expired);
17638 	}
17639 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17640 		/* Increase path mtu */
17641 		flush_flag |= FLUSH_MTU_TIME;
17642 		ip_ire_pmtu_time_elapsed = 0;
17643 		IP_STAT(ip_ire_pmtu_timer_expired);
17644 	}
17645 	if (flush_flag != 0) {
17646 		/* Walk all IPv4 IRE's and update them */
17647 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17648 		    ALL_ZONES);
17649 	}
17650 	if (flush_flag & FLUSH_MTU_TIME) {
17651 		/*
17652 		 * Walk all IPv6 IRE's and update them
17653 		 * Note that ARP and redirect timers are not
17654 		 * needed since NUD handles stale entries.
17655 		 */
17656 		flush_flag = FLUSH_MTU_TIME;
17657 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17658 		    ALL_ZONES);
17659 	}
17660 
17661 	ip_ire_arp_time_elapsed += ip_timer_interval;
17662 	ip_ire_rd_time_elapsed += ip_timer_interval;
17663 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17664 
17665 	/*
17666 	 * Hold the lock to serialize timeout calls and prevent
17667 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17668 	 * for the timer to fire and a new invocation of this function
17669 	 * to start before the return value of timeout has been stored
17670 	 * in ip_ire_expire_id by the current invocation.
17671 	 */
17672 	mutex_enter(&ip_trash_timer_lock);
17673 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17674 	    MSEC_TO_TICK(ip_timer_interval));
17675 	mutex_exit(&ip_trash_timer_lock);
17676 }
17677 
17678 /*
17679  * Called by the memory allocator subsystem directly, when the system
17680  * is running low on memory.
17681  */
17682 /* ARGSUSED */
17683 void
17684 ip_trash_ire_reclaim(void *args)
17685 {
17686 	ire_cache_count_t icc;
17687 	ire_cache_reclaim_t icr;
17688 	ncc_cache_count_t ncc;
17689 	nce_cache_reclaim_t ncr;
17690 	uint_t delete_cnt;
17691 	/*
17692 	 * Memory reclaim call back.
17693 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17694 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17695 	 * entries, determine what fraction to free for
17696 	 * each category of IRE_CACHE entries giving absolute priority
17697 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17698 	 * entry will be freed unless all offlink entries are freed).
17699 	 */
17700 	icc.icc_total = 0;
17701 	icc.icc_unused = 0;
17702 	icc.icc_offlink = 0;
17703 	icc.icc_pmtu = 0;
17704 	icc.icc_onlink = 0;
17705 	ire_walk(ire_cache_count, (char *)&icc);
17706 
17707 	/*
17708 	 * Free NCEs for IPv6 like the onlink ires.
17709 	 */
17710 	ncc.ncc_total = 0;
17711 	ncc.ncc_host = 0;
17712 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17713 
17714 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17715 	    icc.icc_pmtu + icc.icc_onlink);
17716 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17717 	IP_STAT(ip_trash_ire_reclaim_calls);
17718 	if (delete_cnt == 0)
17719 		return;
17720 	IP_STAT(ip_trash_ire_reclaim_success);
17721 	/* Always delete all unused offlink entries */
17722 	icr.icr_unused = 1;
17723 	if (delete_cnt <= icc.icc_unused) {
17724 		/*
17725 		 * Only need to free unused entries.  In other words,
17726 		 * there are enough unused entries to free to meet our
17727 		 * target number of freed ire cache entries.
17728 		 */
17729 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17730 		ncr.ncr_host = 0;
17731 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17732 		/*
17733 		 * Only need to free unused entries, plus a fraction of offlink
17734 		 * entries.  It follows from the first if statement that
17735 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17736 		 */
17737 		delete_cnt -= icc.icc_unused;
17738 		/* Round up # deleted by truncating fraction */
17739 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17740 		icr.icr_pmtu = icr.icr_onlink = 0;
17741 		ncr.ncr_host = 0;
17742 	} else if (delete_cnt <=
17743 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17744 		/*
17745 		 * Free all unused and offlink entries, plus a fraction of
17746 		 * pmtu entries.  It follows from the previous if statement
17747 		 * that icc_pmtu is non-zero, and that
17748 		 * delete_cnt != icc_unused + icc_offlink.
17749 		 */
17750 		icr.icr_offlink = 1;
17751 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17752 		/* Round up # deleted by truncating fraction */
17753 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17754 		icr.icr_onlink = 0;
17755 		ncr.ncr_host = 0;
17756 	} else {
17757 		/*
17758 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17759 		 * of onlink entries.  If we're here, then we know that
17760 		 * icc_onlink is non-zero, and that
17761 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17762 		 */
17763 		icr.icr_offlink = icr.icr_pmtu = 1;
17764 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17765 		    icc.icc_pmtu;
17766 		/* Round up # deleted by truncating fraction */
17767 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17768 		/* Using the same delete fraction as for onlink IREs */
17769 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17770 	}
17771 #ifdef DEBUG
17772 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17773 	    "fractions %d/%d/%d/%d\n",
17774 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17775 	    icc.icc_unused, icc.icc_offlink,
17776 	    icc.icc_pmtu, icc.icc_onlink,
17777 	    icr.icr_unused, icr.icr_offlink,
17778 	    icr.icr_pmtu, icr.icr_onlink));
17779 #endif
17780 	ire_walk(ire_cache_reclaim, (char *)&icr);
17781 	if (ncr.ncr_host != 0)
17782 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17783 		    (uchar_t *)&ncr);
17784 #ifdef DEBUG
17785 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17786 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17787 	ire_walk(ire_cache_count, (char *)&icc);
17788 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17789 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17790 	    icc.icc_pmtu, icc.icc_onlink));
17791 #endif
17792 }
17793 
17794 /*
17795  * ip_unbind is called when a copy of an unbind request is received from the
17796  * upper level protocol.  We remove this conn from any fanout hash list it is
17797  * on, and zero out the bind information.  No reply is expected up above.
17798  */
17799 mblk_t *
17800 ip_unbind(queue_t *q, mblk_t *mp)
17801 {
17802 	conn_t	*connp = Q_TO_CONN(q);
17803 
17804 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17805 
17806 	ipcl_hash_remove(connp);
17807 
17808 	ASSERT(mp->b_cont == NULL);
17809 	/*
17810 	 * Convert mp into a T_OK_ACK
17811 	 */
17812 	mp = mi_tpi_ok_ack_alloc(mp);
17813 
17814 	/*
17815 	 * should not happen in practice... T_OK_ACK is smaller than the
17816 	 * original message.
17817 	 */
17818 	if (mp == NULL)
17819 		return (NULL);
17820 
17821 	/*
17822 	 * Don't bzero the ports if its TCP since TCP still needs the
17823 	 * lport to remove it from its own bind hash. TCP will do the
17824 	 * cleanup.
17825 	 */
17826 	if (!IPCL_IS_TCP(connp))
17827 		bzero(&connp->u_port, sizeof (connp->u_port));
17828 
17829 	return (mp);
17830 }
17831 
17832 /*
17833  * Write side put procedure.  Outbound data, IOCTLs, responses from
17834  * resolvers, etc, come down through here.
17835  */
17836 void
17837 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17838 {
17839 	conn_t		*connp = NULL;
17840 	queue_t		*q = (queue_t *)arg2;
17841 	ipha_t		*ipha;
17842 #define	rptr	((uchar_t *)ipha)
17843 	ire_t		*ire = NULL;
17844 	ire_t		*sctp_ire = NULL;
17845 	uint32_t	v_hlen_tos_len;
17846 	ipaddr_t	dst;
17847 	mblk_t		*first_mp = NULL;
17848 	boolean_t	mctl_present;
17849 	ipsec_out_t	*io;
17850 	int		match_flags;
17851 	ill_t		*attach_ill = NULL;
17852 					/* Bind to IPIF_NOFAILOVER ill etc. */
17853 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17854 	ipif_t		*dst_ipif;
17855 	boolean_t	multirt_need_resolve = B_FALSE;
17856 	mblk_t		*copy_mp = NULL;
17857 	int		err;
17858 	zoneid_t	zoneid;
17859 	boolean_t	need_decref = B_FALSE;
17860 	boolean_t	ignore_dontroute = B_FALSE;
17861 	boolean_t	ignore_nexthop = B_FALSE;
17862 	boolean_t	ip_nexthop = B_FALSE;
17863 	ipaddr_t	nexthop_addr;
17864 
17865 #ifdef	_BIG_ENDIAN
17866 #define	V_HLEN	(v_hlen_tos_len >> 24)
17867 #else
17868 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17869 #endif
17870 
17871 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17872 	    "ip_wput_start: q %p", q);
17873 
17874 	/*
17875 	 * ip_wput fast path
17876 	 */
17877 
17878 	/* is packet from ARP ? */
17879 	if (q->q_next != NULL)
17880 		goto qnext;
17881 
17882 	connp = (conn_t *)arg;
17883 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17884 
17885 	/* is queue flow controlled? */
17886 	if ((q->q_first != NULL || connp->conn_draining) &&
17887 	    (caller == IP_WPUT)) {
17888 		ASSERT(!need_decref);
17889 		(void) putq(q, mp);
17890 		return;
17891 	}
17892 
17893 	/* Multidata transmit? */
17894 	if (DB_TYPE(mp) == M_MULTIDATA) {
17895 		/*
17896 		 * We should never get here, since all Multidata messages
17897 		 * originating from tcp should have been directed over to
17898 		 * tcp_multisend() in the first place.
17899 		 */
17900 		BUMP_MIB(&ip_mib, ipOutDiscards);
17901 		freemsg(mp);
17902 		return;
17903 	} else if (DB_TYPE(mp) != M_DATA)
17904 		goto notdata;
17905 	if (mp->b_flag & MSGHASREF) {
17906 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17907 		mp->b_flag &= ~MSGHASREF;
17908 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17909 		need_decref = B_TRUE;
17910 	}
17911 	ipha = (ipha_t *)mp->b_rptr;
17912 
17913 	/* is IP header non-aligned or mblk smaller than basic IP header */
17914 #ifndef SAFETY_BEFORE_SPEED
17915 	if (!OK_32PTR(rptr) ||
17916 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17917 		goto hdrtoosmall;
17918 #endif
17919 
17920 	/*
17921 	 * If there is a policy, try to attach an ipsec_out in
17922 	 * the front. At the end, first_mp either points to a
17923 	 * M_DATA message or IPSEC_OUT message linked to a
17924 	 * M_DATA message. We have to do it now as we might
17925 	 * lose the "conn" if we go through ip_newroute.
17926 	 */
17927 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17928 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17929 		    ipha->ipha_protocol)) == NULL)) {
17930 			if (need_decref)
17931 				CONN_DEC_REF(connp);
17932 			return;
17933 		} else {
17934 			ASSERT(mp->b_datap->db_type == M_CTL);
17935 			first_mp = mp;
17936 			mp = mp->b_cont;
17937 			mctl_present = B_TRUE;
17938 		}
17939 	} else {
17940 		first_mp = mp;
17941 		mctl_present = B_FALSE;
17942 	}
17943 
17944 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17945 
17946 	/* is wrong version or IP options present */
17947 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17948 		goto version_hdrlen_check;
17949 	dst = ipha->ipha_dst;
17950 
17951 	if (connp->conn_nofailover_ill != NULL) {
17952 		attach_ill = conn_get_held_ill(connp,
17953 		    &connp->conn_nofailover_ill, &err);
17954 		if (err == ILL_LOOKUP_FAILED) {
17955 			if (need_decref)
17956 				CONN_DEC_REF(connp);
17957 			freemsg(first_mp);
17958 			return;
17959 		}
17960 	}
17961 
17962 	/* is packet multicast? */
17963 	if (CLASSD(dst))
17964 		goto multicast;
17965 
17966 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
17967 	    (connp->conn_nexthop_set)) {
17968 		/*
17969 		 * If the destination is a broadcast or a loopback
17970 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
17971 		 * through the standard path. But in the case of local
17972 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
17973 		 * the standard path not IP_XMIT_IF.
17974 		 */
17975 		ire = ire_cache_lookup(dst, zoneid);
17976 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17977 		    (ire->ire_type != IRE_LOOPBACK))) {
17978 			if ((connp->conn_dontroute ||
17979 			    connp->conn_nexthop_set) && (ire != NULL) &&
17980 			    (ire->ire_type == IRE_LOCAL))
17981 				goto standard_path;
17982 
17983 			if (ire != NULL) {
17984 				ire_refrele(ire);
17985 				/* No more access to ire */
17986 				ire = NULL;
17987 			}
17988 			/*
17989 			 * bypass routing checks and go directly to
17990 			 * interface.
17991 			 */
17992 			if (connp->conn_dontroute) {
17993 				goto dontroute;
17994 			} else if (connp->conn_nexthop_set) {
17995 				ip_nexthop = B_TRUE;
17996 				nexthop_addr = connp->conn_nexthop_v4;
17997 				goto send_from_ill;
17998 			}
17999 
18000 			/*
18001 			 * If IP_XMIT_IF socket option is set,
18002 			 * then we allow unicast and multicast
18003 			 * packets to go through the ill. It is
18004 			 * quite possible that the destination
18005 			 * is not in the ire cache table and we
18006 			 * do not want to go to ip_newroute()
18007 			 * instead we call ip_newroute_ipif.
18008 			 */
18009 			xmit_ill = conn_get_held_ill(connp,
18010 			    &connp->conn_xmit_if_ill, &err);
18011 			if (err == ILL_LOOKUP_FAILED) {
18012 				if (attach_ill != NULL)
18013 					ill_refrele(attach_ill);
18014 				if (need_decref)
18015 					CONN_DEC_REF(connp);
18016 				freemsg(first_mp);
18017 				return;
18018 			}
18019 			goto send_from_ill;
18020 		}
18021 standard_path:
18022 		/* Must be a broadcast, a loopback or a local ire */
18023 		if (ire != NULL) {
18024 			ire_refrele(ire);
18025 			/* No more access to ire */
18026 			ire = NULL;
18027 		}
18028 	}
18029 
18030 	if (attach_ill != NULL)
18031 		goto send_from_ill;
18032 
18033 	/*
18034 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18035 	 * this for the tcp global queue and listen end point
18036 	 * as it does not really have a real destination to
18037 	 * talk to.  This is also true for SCTP.
18038 	 */
18039 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18040 	    !connp->conn_fully_bound) {
18041 		ire = ire_cache_lookup(dst, zoneid);
18042 		if (ire == NULL)
18043 			goto noirefound;
18044 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18045 		    "ip_wput_end: q %p (%S)", q, "end");
18046 
18047 		/*
18048 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18049 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18050 		 */
18051 		if (ire->ire_flags & RTF_MULTIRT) {
18052 
18053 			/*
18054 			 * Force the TTL of multirouted packets if required.
18055 			 * The TTL of such packets is bounded by the
18056 			 * ip_multirt_ttl ndd variable.
18057 			 */
18058 			if ((ip_multirt_ttl > 0) &&
18059 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18060 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18061 				    "(was %d), dst 0x%08x\n",
18062 				    ip_multirt_ttl, ipha->ipha_ttl,
18063 				    ntohl(ire->ire_addr)));
18064 				ipha->ipha_ttl = ip_multirt_ttl;
18065 			}
18066 			/*
18067 			 * We look at this point if there are pending
18068 			 * unresolved routes. ire_multirt_resolvable()
18069 			 * checks in O(n) that all IRE_OFFSUBNET ire
18070 			 * entries for the packet's destination and
18071 			 * flagged RTF_MULTIRT are currently resolved.
18072 			 * If some remain unresolved, we make a copy
18073 			 * of the current message. It will be used
18074 			 * to initiate additional route resolutions.
18075 			 */
18076 			multirt_need_resolve =
18077 			    ire_multirt_need_resolve(ire->ire_addr);
18078 			ip2dbg(("ip_wput[TCP]: ire %p, "
18079 			    "multirt_need_resolve %d, first_mp %p\n",
18080 			    (void *)ire, multirt_need_resolve,
18081 			    (void *)first_mp));
18082 			if (multirt_need_resolve) {
18083 				copy_mp = copymsg(first_mp);
18084 				if (copy_mp != NULL) {
18085 					MULTIRT_DEBUG_TAG(copy_mp);
18086 				}
18087 			}
18088 		}
18089 
18090 		ip_wput_ire(q, first_mp, ire, connp, caller);
18091 
18092 		/*
18093 		 * Try to resolve another multiroute if
18094 		 * ire_multirt_need_resolve() deemed it necessary.
18095 		 */
18096 		if (copy_mp != NULL) {
18097 			ip_newroute(q, copy_mp, dst, NULL, connp);
18098 		}
18099 		if (need_decref)
18100 			CONN_DEC_REF(connp);
18101 		return;
18102 	}
18103 
18104 	/*
18105 	 * Access to conn_ire_cache. (protected by conn_lock)
18106 	 *
18107 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18108 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18109 	 * send a packet or two with the IRE_CACHE that is going away.
18110 	 * Access to the ire requires an ire refhold on the ire prior to
18111 	 * its use since an interface unplumb thread may delete the cached
18112 	 * ire and release the refhold at any time.
18113 	 *
18114 	 * Caching an ire in the conn_ire_cache
18115 	 *
18116 	 * o Caching an ire pointer in the conn requires a strict check for
18117 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18118 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18119 	 * in the conn is done after making sure under the bucket lock that the
18120 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18121 	 * caching an ire after the unplumb thread has cleaned up the conn.
18122 	 * If the conn does not send a packet subsequently the unplumb thread
18123 	 * will be hanging waiting for the ire count to drop to zero.
18124 	 *
18125 	 * o We also need to atomically test for a null conn_ire_cache and
18126 	 * set the conn_ire_cache under the the protection of the conn_lock
18127 	 * to avoid races among concurrent threads trying to simultaneously
18128 	 * cache an ire in the conn_ire_cache.
18129 	 */
18130 	mutex_enter(&connp->conn_lock);
18131 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18132 
18133 	if (ire != NULL && ire->ire_addr == dst &&
18134 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18135 
18136 		IRE_REFHOLD(ire);
18137 		mutex_exit(&connp->conn_lock);
18138 
18139 	} else {
18140 		boolean_t cached = B_FALSE;
18141 		connp->conn_ire_cache = NULL;
18142 		mutex_exit(&connp->conn_lock);
18143 		/* Release the old ire */
18144 		if (ire != NULL && sctp_ire == NULL)
18145 			IRE_REFRELE_NOTR(ire);
18146 
18147 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
18148 		if (ire == NULL)
18149 			goto noirefound;
18150 		IRE_REFHOLD_NOTR(ire);
18151 
18152 		mutex_enter(&connp->conn_lock);
18153 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18154 		    connp->conn_ire_cache == NULL) {
18155 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18156 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18157 				connp->conn_ire_cache = ire;
18158 				cached = B_TRUE;
18159 			}
18160 			rw_exit(&ire->ire_bucket->irb_lock);
18161 		}
18162 		mutex_exit(&connp->conn_lock);
18163 
18164 		/*
18165 		 * We can continue to use the ire but since it was
18166 		 * not cached, we should drop the extra reference.
18167 		 */
18168 		if (!cached)
18169 			IRE_REFRELE_NOTR(ire);
18170 	}
18171 
18172 
18173 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18174 	    "ip_wput_end: q %p (%S)", q, "end");
18175 
18176 	/*
18177 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18178 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18179 	 */
18180 	if (ire->ire_flags & RTF_MULTIRT) {
18181 
18182 		/*
18183 		 * Force the TTL of multirouted packets if required.
18184 		 * The TTL of such packets is bounded by the
18185 		 * ip_multirt_ttl ndd variable.
18186 		 */
18187 		if ((ip_multirt_ttl > 0) &&
18188 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18189 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18190 			    "(was %d), dst 0x%08x\n",
18191 			    ip_multirt_ttl, ipha->ipha_ttl,
18192 			    ntohl(ire->ire_addr)));
18193 			ipha->ipha_ttl = ip_multirt_ttl;
18194 		}
18195 
18196 		/*
18197 		 * At this point, we check to see if there are any pending
18198 		 * unresolved routes. ire_multirt_resolvable()
18199 		 * checks in O(n) that all IRE_OFFSUBNET ire
18200 		 * entries for the packet's destination and
18201 		 * flagged RTF_MULTIRT are currently resolved.
18202 		 * If some remain unresolved, we make a copy
18203 		 * of the current message. It will be used
18204 		 * to initiate additional route resolutions.
18205 		 */
18206 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18207 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18208 		    "multirt_need_resolve %d, first_mp %p\n",
18209 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18210 		if (multirt_need_resolve) {
18211 			copy_mp = copymsg(first_mp);
18212 			if (copy_mp != NULL) {
18213 				MULTIRT_DEBUG_TAG(copy_mp);
18214 			}
18215 		}
18216 	}
18217 
18218 	ip_wput_ire(q, first_mp, ire, connp, caller);
18219 
18220 	/*
18221 	 * Try to resolve another multiroute if
18222 	 * ire_multirt_resolvable() deemed it necessary
18223 	 */
18224 	if (copy_mp != NULL) {
18225 		ip_newroute(q, copy_mp, dst, NULL, connp);
18226 	}
18227 	if (need_decref)
18228 		CONN_DEC_REF(connp);
18229 	return;
18230 
18231 qnext:
18232 	/*
18233 	 * Upper Level Protocols pass down complete IP datagrams
18234 	 * as M_DATA messages.	Everything else is a sideshow.
18235 	 *
18236 	 * 1) We could be re-entering ip_wput because of ip_neworute
18237 	 *    in which case we could have a IPSEC_OUT message. We
18238 	 *    need to pass through ip_wput like other datagrams and
18239 	 *    hence cannot branch to ip_wput_nondata.
18240 	 *
18241 	 * 2) ARP, AH, ESP, and other clients who are on the module
18242 	 *    instance of IP stream, give us something to deal with.
18243 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18244 	 *
18245 	 * 3) ICMP replies also could come here.
18246 	 */
18247 	if (DB_TYPE(mp) != M_DATA) {
18248 	    notdata:
18249 		if (DB_TYPE(mp) == M_CTL) {
18250 			/*
18251 			 * M_CTL messages are used by ARP, AH and ESP to
18252 			 * communicate with IP. We deal with IPSEC_IN and
18253 			 * IPSEC_OUT here. ip_wput_nondata handles other
18254 			 * cases.
18255 			 */
18256 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18257 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18258 				first_mp = mp->b_cont;
18259 				first_mp->b_flag &= ~MSGHASREF;
18260 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18261 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18262 				CONN_DEC_REF(connp);
18263 				connp = NULL;
18264 			}
18265 			if (ii->ipsec_info_type == IPSEC_IN) {
18266 				/*
18267 				 * Either this message goes back to
18268 				 * IPSEC for further processing or to
18269 				 * ULP after policy checks.
18270 				 */
18271 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18272 				return;
18273 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18274 				io = (ipsec_out_t *)ii;
18275 				if (io->ipsec_out_proc_begin) {
18276 					/*
18277 					 * IPSEC processing has already started.
18278 					 * Complete it.
18279 					 * IPQoS notes: We don't care what is
18280 					 * in ipsec_out_ill_index since this
18281 					 * won't be processed for IPQoS policies
18282 					 * in ipsec_out_process.
18283 					 */
18284 					ipsec_out_process(q, mp, NULL,
18285 					    io->ipsec_out_ill_index);
18286 					return;
18287 				} else {
18288 					connp = (q->q_next != NULL) ?
18289 					    NULL : Q_TO_CONN(q);
18290 					first_mp = mp;
18291 					mp = mp->b_cont;
18292 					mctl_present = B_TRUE;
18293 				}
18294 				zoneid = io->ipsec_out_zoneid;
18295 				ASSERT(zoneid != ALL_ZONES);
18296 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18297 				/*
18298 				 * It's an IPsec control message requesting
18299 				 * an SADB update to be sent to the IPsec
18300 				 * hardware acceleration capable ills.
18301 				 */
18302 				ipsec_ctl_t *ipsec_ctl =
18303 				    (ipsec_ctl_t *)mp->b_rptr;
18304 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18305 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18306 				mblk_t *cmp = mp->b_cont;
18307 
18308 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18309 				ASSERT(cmp != NULL);
18310 
18311 				freeb(mp);
18312 				ill_ipsec_capab_send_all(satype, cmp, sa);
18313 				return;
18314 			} else {
18315 				/*
18316 				 * This must be ARP.
18317 				 */
18318 				ip_wput_nondata(NULL, q, mp, NULL);
18319 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18320 				    "ip_wput_end: q %p (%S)", q, "nondata");
18321 				return;
18322 			}
18323 		} else {
18324 			/*
18325 			 * This must be non-(ARP/AH/ESP) messages.
18326 			 */
18327 			ASSERT(!need_decref);
18328 			ip_wput_nondata(NULL, q, mp, NULL);
18329 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18330 			    "ip_wput_end: q %p (%S)", q, "nondata");
18331 			return;
18332 		}
18333 	} else {
18334 		first_mp = mp;
18335 		mctl_present = B_FALSE;
18336 	}
18337 
18338 	ASSERT(first_mp != NULL);
18339 	/*
18340 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18341 	 * to make sure that this packet goes out on the same interface it
18342 	 * came in. We handle that here.
18343 	 */
18344 	if (mctl_present) {
18345 		uint_t ifindex;
18346 
18347 		io = (ipsec_out_t *)first_mp->b_rptr;
18348 		if (io->ipsec_out_attach_if ||
18349 		    io->ipsec_out_xmit_if ||
18350 		    io->ipsec_out_ip_nexthop) {
18351 			ill_t	*ill;
18352 
18353 			/*
18354 			 * We may have lost the conn context if we are
18355 			 * coming here from ip_newroute(). Copy the
18356 			 * nexthop information.
18357 			 */
18358 			if (io->ipsec_out_ip_nexthop) {
18359 				ip_nexthop = B_TRUE;
18360 				nexthop_addr = io->ipsec_out_nexthop_addr;
18361 
18362 				ipha = (ipha_t *)mp->b_rptr;
18363 				dst = ipha->ipha_dst;
18364 				goto send_from_ill;
18365 			} else {
18366 				ASSERT(io->ipsec_out_ill_index != 0);
18367 				ifindex = io->ipsec_out_ill_index;
18368 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18369 				    NULL, NULL, NULL, NULL);
18370 				/*
18371 				 * ipsec_out_xmit_if bit is used to tell
18372 				 * ip_wput to use the ill to send outgoing data
18373 				 * as we have no conn when data comes from ICMP
18374 				 * error msg routines. Currently this feature is
18375 				 * only used by ip_mrtun_forward routine.
18376 				 */
18377 				if (io->ipsec_out_xmit_if) {
18378 					xmit_ill = ill;
18379 					if (xmit_ill == NULL) {
18380 						ip1dbg(("ip_output:bad ifindex "
18381 						    "for xmit_ill %d\n",
18382 						    ifindex));
18383 						freemsg(first_mp);
18384 						BUMP_MIB(&ip_mib,
18385 						    ipOutDiscards);
18386 						ASSERT(!need_decref);
18387 						return;
18388 					}
18389 					/* Free up the ipsec_out_t mblk */
18390 					ASSERT(first_mp->b_cont == mp);
18391 					first_mp->b_cont = NULL;
18392 					freeb(first_mp);
18393 					/* Just send the IP header+ICMP+data */
18394 					first_mp = mp;
18395 					ipha = (ipha_t *)mp->b_rptr;
18396 					dst = ipha->ipha_dst;
18397 					goto send_from_ill;
18398 				} else {
18399 					attach_ill = ill;
18400 				}
18401 
18402 				if (attach_ill == NULL) {
18403 					ASSERT(xmit_ill == NULL);
18404 					ip1dbg(("ip_output: bad ifindex for "
18405 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
18406 					    ifindex));
18407 					freemsg(first_mp);
18408 					BUMP_MIB(&ip_mib, ipOutDiscards);
18409 					ASSERT(!need_decref);
18410 					return;
18411 				}
18412 			}
18413 		}
18414 	}
18415 
18416 	ASSERT(xmit_ill == NULL);
18417 
18418 	/* We have a complete IP datagram heading outbound. */
18419 	ipha = (ipha_t *)mp->b_rptr;
18420 
18421 #ifndef SPEED_BEFORE_SAFETY
18422 	/*
18423 	 * Make sure we have a full-word aligned message and that at least
18424 	 * a simple IP header is accessible in the first message.  If not,
18425 	 * try a pullup.
18426 	 */
18427 	if (!OK_32PTR(rptr) ||
18428 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18429 	    hdrtoosmall:
18430 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18431 			BUMP_MIB(&ip_mib, ipOutDiscards);
18432 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18433 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18434 			if (first_mp == NULL)
18435 				first_mp = mp;
18436 			goto drop_pkt;
18437 		}
18438 		ipha = (ipha_t *)mp->b_rptr;
18439 		if (first_mp == NULL) {
18440 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18441 			/*
18442 			 * If we got here because of "goto hdrtoosmall"
18443 			 * We need to attach a IPSEC_OUT.
18444 			 */
18445 			if (connp->conn_out_enforce_policy) {
18446 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18447 				    NULL, ipha->ipha_protocol)) == NULL)) {
18448 					if (need_decref)
18449 						CONN_DEC_REF(connp);
18450 					return;
18451 				} else {
18452 					ASSERT(mp->b_datap->db_type == M_CTL);
18453 					first_mp = mp;
18454 					mp = mp->b_cont;
18455 					mctl_present = B_TRUE;
18456 				}
18457 			} else {
18458 				first_mp = mp;
18459 				mctl_present = B_FALSE;
18460 			}
18461 		}
18462 	}
18463 #endif
18464 
18465 	/* Most of the code below is written for speed, not readability */
18466 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18467 
18468 	/*
18469 	 * If ip_newroute() fails, we're going to need a full
18470 	 * header for the icmp wraparound.
18471 	 */
18472 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18473 		uint_t	v_hlen;
18474 	    version_hdrlen_check:
18475 		ASSERT(first_mp != NULL);
18476 		v_hlen = V_HLEN;
18477 		/*
18478 		 * siphon off IPv6 packets coming down from transport
18479 		 * layer modules here.
18480 		 * Note: high-order bit carries NUD reachability confirmation
18481 		 */
18482 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18483 			/*
18484 			 * XXX implement a IPv4 and IPv6 packet counter per
18485 			 * conn and switch when ratio exceeds e.g. 10:1
18486 			 */
18487 #ifdef notyet
18488 			if (q->q_next == NULL) /* Avoid ill queue */
18489 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18490 #endif
18491 			BUMP_MIB(&ip_mib, ipOutIPv6);
18492 			ASSERT(xmit_ill == NULL);
18493 			if (attach_ill != NULL)
18494 				ill_refrele(attach_ill);
18495 			if (need_decref)
18496 				mp->b_flag |= MSGHASREF;
18497 			(void) ip_output_v6(connp, first_mp, q, caller);
18498 			return;
18499 		}
18500 
18501 		if ((v_hlen >> 4) != IP_VERSION) {
18502 			BUMP_MIB(&ip_mib, ipOutDiscards);
18503 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18504 			    "ip_wput_end: q %p (%S)", q, "badvers");
18505 			goto drop_pkt;
18506 		}
18507 		/*
18508 		 * Is the header length at least 20 bytes?
18509 		 *
18510 		 * Are there enough bytes accessible in the header?  If
18511 		 * not, try a pullup.
18512 		 */
18513 		v_hlen &= 0xF;
18514 		v_hlen <<= 2;
18515 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18516 			BUMP_MIB(&ip_mib, ipOutDiscards);
18517 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18518 			    "ip_wput_end: q %p (%S)", q, "badlen");
18519 			goto drop_pkt;
18520 		}
18521 		if (v_hlen > (mp->b_wptr - rptr)) {
18522 			if (!pullupmsg(mp, v_hlen)) {
18523 				BUMP_MIB(&ip_mib, ipOutDiscards);
18524 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18525 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18526 				goto drop_pkt;
18527 			}
18528 			ipha = (ipha_t *)mp->b_rptr;
18529 		}
18530 		/*
18531 		 * Move first entry from any source route into ipha_dst and
18532 		 * verify the options
18533 		 */
18534 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18535 			ASSERT(xmit_ill == NULL);
18536 			if (attach_ill != NULL)
18537 				ill_refrele(attach_ill);
18538 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18539 			    "ip_wput_end: q %p (%S)", q, "badopts");
18540 			if (need_decref)
18541 				CONN_DEC_REF(connp);
18542 			return;
18543 		}
18544 	}
18545 	dst = ipha->ipha_dst;
18546 
18547 	/*
18548 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18549 	 * we have to run the packet through ip_newroute which will take
18550 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18551 	 * a resolver, or assigning a default gateway, etc.
18552 	 */
18553 	if (CLASSD(dst)) {
18554 		ipif_t	*ipif;
18555 		uint32_t setsrc = 0;
18556 
18557 	    multicast:
18558 		ASSERT(first_mp != NULL);
18559 		ASSERT(xmit_ill == NULL);
18560 		ip2dbg(("ip_wput: CLASSD\n"));
18561 		if (connp == NULL) {
18562 			/*
18563 			 * Use the first good ipif on the ill.
18564 			 * XXX Should this ever happen? (Appears
18565 			 * to show up with just ppp and no ethernet due
18566 			 * to in.rdisc.)
18567 			 * However, ire_send should be able to
18568 			 * call ip_wput_ire directly.
18569 			 *
18570 			 * XXX Also, this can happen for ICMP and other packets
18571 			 * with multicast source addresses.  Perhaps we should
18572 			 * fix things so that we drop the packet in question,
18573 			 * but for now, just run with it.
18574 			 */
18575 			ill_t *ill = (ill_t *)q->q_ptr;
18576 
18577 			/*
18578 			 * Don't honor attach_if for this case. If ill
18579 			 * is part of the group, ipif could belong to
18580 			 * any ill and we cannot maintain attach_ill
18581 			 * and ipif_ill same anymore and the assert
18582 			 * below would fail.
18583 			 */
18584 			if (mctl_present) {
18585 				io->ipsec_out_ill_index = 0;
18586 				io->ipsec_out_attach_if = B_FALSE;
18587 				ASSERT(attach_ill != NULL);
18588 				ill_refrele(attach_ill);
18589 				attach_ill = NULL;
18590 			}
18591 
18592 			ASSERT(attach_ill == NULL);
18593 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18594 			if (ipif == NULL) {
18595 				if (need_decref)
18596 					CONN_DEC_REF(connp);
18597 				freemsg(first_mp);
18598 				return;
18599 			}
18600 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18601 			    ntohl(dst), ill->ill_name));
18602 		} else {
18603 			/*
18604 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18605 			 * IP_XMIT_IF is honoured.
18606 			 * Block comment above this function explains the
18607 			 * locking mechanism used here
18608 			 */
18609 			xmit_ill = conn_get_held_ill(connp,
18610 			    &connp->conn_xmit_if_ill, &err);
18611 			if (err == ILL_LOOKUP_FAILED) {
18612 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18613 				goto drop_pkt;
18614 			}
18615 			if (xmit_ill == NULL) {
18616 				ipif = conn_get_held_ipif(connp,
18617 				    &connp->conn_multicast_ipif, &err);
18618 				if (err == IPIF_LOOKUP_FAILED) {
18619 					ip1dbg(("ip_wput: No ipif for "
18620 					    "multicast\n"));
18621 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18622 					goto drop_pkt;
18623 				}
18624 			}
18625 			if (xmit_ill != NULL) {
18626 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18627 				if (ipif == NULL) {
18628 					ip1dbg(("ip_wput: No ipif for "
18629 					    "IP_XMIT_IF\n"));
18630 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18631 					goto drop_pkt;
18632 				}
18633 			} else if (ipif == NULL || ipif->ipif_isv6) {
18634 				/*
18635 				 * We must do this ipif determination here
18636 				 * else we could pass through ip_newroute
18637 				 * and come back here without the conn context.
18638 				 *
18639 				 * Note: we do late binding i.e. we bind to
18640 				 * the interface when the first packet is sent.
18641 				 * For performance reasons we do not rebind on
18642 				 * each packet but keep the binding until the
18643 				 * next IP_MULTICAST_IF option.
18644 				 *
18645 				 * conn_multicast_{ipif,ill} are shared between
18646 				 * IPv4 and IPv6 and AF_INET6 sockets can
18647 				 * send both IPv4 and IPv6 packets. Hence
18648 				 * we have to check that "isv6" matches above.
18649 				 */
18650 				if (ipif != NULL)
18651 					ipif_refrele(ipif);
18652 				ipif = ipif_lookup_group(dst, zoneid);
18653 				if (ipif == NULL) {
18654 					ip1dbg(("ip_wput: No ipif for "
18655 					    "multicast\n"));
18656 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18657 					goto drop_pkt;
18658 				}
18659 				err = conn_set_held_ipif(connp,
18660 				    &connp->conn_multicast_ipif, ipif);
18661 				if (err == IPIF_LOOKUP_FAILED) {
18662 					ipif_refrele(ipif);
18663 					ip1dbg(("ip_wput: No ipif for "
18664 					    "multicast\n"));
18665 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18666 					goto drop_pkt;
18667 				}
18668 			}
18669 		}
18670 		ASSERT(!ipif->ipif_isv6);
18671 		/*
18672 		 * As we may lose the conn by the time we reach ip_wput_ire,
18673 		 * we copy conn_multicast_loop and conn_dontroute on to an
18674 		 * ipsec_out. In case if this datagram goes out secure,
18675 		 * we need the ill_index also. Copy that also into the
18676 		 * ipsec_out.
18677 		 */
18678 		if (mctl_present) {
18679 			io = (ipsec_out_t *)first_mp->b_rptr;
18680 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18681 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18682 		} else {
18683 			ASSERT(mp == first_mp);
18684 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18685 			    BPRI_HI)) == NULL) {
18686 				ipif_refrele(ipif);
18687 				first_mp = mp;
18688 				goto drop_pkt;
18689 			}
18690 			first_mp->b_datap->db_type = M_CTL;
18691 			first_mp->b_wptr += sizeof (ipsec_info_t);
18692 			/* ipsec_out_secure is B_FALSE now */
18693 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18694 			io = (ipsec_out_t *)first_mp->b_rptr;
18695 			io->ipsec_out_type = IPSEC_OUT;
18696 			io->ipsec_out_len = sizeof (ipsec_out_t);
18697 			io->ipsec_out_use_global_policy = B_TRUE;
18698 			first_mp->b_cont = mp;
18699 			mctl_present = B_TRUE;
18700 		}
18701 		if (attach_ill != NULL) {
18702 			ASSERT(attach_ill == ipif->ipif_ill);
18703 			match_flags = MATCH_IRE_ILL;
18704 
18705 			/*
18706 			 * Check if we need an ire that will not be
18707 			 * looked up by anybody else i.e. HIDDEN.
18708 			 */
18709 			if (ill_is_probeonly(attach_ill)) {
18710 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18711 			}
18712 			io->ipsec_out_ill_index =
18713 			    attach_ill->ill_phyint->phyint_ifindex;
18714 			io->ipsec_out_attach_if = B_TRUE;
18715 		} else {
18716 			match_flags = MATCH_IRE_ILL_GROUP;
18717 			io->ipsec_out_ill_index =
18718 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18719 		}
18720 		if (connp != NULL) {
18721 			io->ipsec_out_multicast_loop =
18722 			    connp->conn_multicast_loop;
18723 			io->ipsec_out_dontroute = connp->conn_dontroute;
18724 			io->ipsec_out_zoneid = connp->conn_zoneid;
18725 		}
18726 		/*
18727 		 * If the application uses IP_MULTICAST_IF with
18728 		 * different logical addresses of the same ILL, we
18729 		 * need to make sure that the soruce address of
18730 		 * the packet matches the logical IP address used
18731 		 * in the option. We do it by initializing ipha_src
18732 		 * here. This should keep IPSEC also happy as
18733 		 * when we return from IPSEC processing, we don't
18734 		 * have to worry about getting the right address on
18735 		 * the packet. Thus it is sufficient to look for
18736 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18737 		 * MATCH_IRE_IPIF.
18738 		 *
18739 		 * NOTE : We need to do it for non-secure case also as
18740 		 * this might go out secure if there is a global policy
18741 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18742 		 * address, the source should be initialized already and
18743 		 * hence we won't be initializing here.
18744 		 *
18745 		 * As we do not have the ire yet, it is possible that
18746 		 * we set the source address here and then later discover
18747 		 * that the ire implies the source address to be assigned
18748 		 * through the RTF_SETSRC flag.
18749 		 * In that case, the setsrc variable will remind us
18750 		 * that overwritting the source address by the one
18751 		 * of the RTF_SETSRC-flagged ire is allowed.
18752 		 */
18753 		if (ipha->ipha_src == INADDR_ANY &&
18754 		    (connp == NULL || !connp->conn_unspec_src)) {
18755 			ipha->ipha_src = ipif->ipif_src_addr;
18756 			setsrc = RTF_SETSRC;
18757 		}
18758 		/*
18759 		 * Find an IRE which matches the destination and the outgoing
18760 		 * queue (i.e. the outgoing interface.)
18761 		 * For loopback use a unicast IP address for
18762 		 * the ire lookup.
18763 		 */
18764 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18765 		    PHYI_LOOPBACK) {
18766 			dst = ipif->ipif_lcl_addr;
18767 		}
18768 		/*
18769 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18770 		 * We don't need to lookup ire in ctable as the packet
18771 		 * needs to be sent to the destination through the specified
18772 		 * ill irrespective of ires in the cache table.
18773 		 */
18774 		ire = NULL;
18775 		if (xmit_ill == NULL) {
18776 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18777 			    zoneid, match_flags);
18778 		}
18779 
18780 		/*
18781 		 * refrele attach_ill as its not needed anymore.
18782 		 */
18783 		if (attach_ill != NULL) {
18784 			ill_refrele(attach_ill);
18785 			attach_ill = NULL;
18786 		}
18787 
18788 		if (ire == NULL) {
18789 			/*
18790 			 * Multicast loopback and multicast forwarding is
18791 			 * done in ip_wput_ire.
18792 			 *
18793 			 * Mark this packet to make it be delivered to
18794 			 * ip_wput_ire after the new ire has been
18795 			 * created.
18796 			 *
18797 			 * The call to ip_newroute_ipif takes into account
18798 			 * the setsrc reminder. In any case, we take care
18799 			 * of the RTF_MULTIRT flag.
18800 			 */
18801 			mp->b_prev = mp->b_next = NULL;
18802 			if (xmit_ill == NULL ||
18803 			    xmit_ill->ill_ipif_up_count > 0) {
18804 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18805 				    setsrc | RTF_MULTIRT);
18806 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18807 				    "ip_wput_end: q %p (%S)", q, "noire");
18808 			} else {
18809 				freemsg(first_mp);
18810 			}
18811 			ipif_refrele(ipif);
18812 			if (xmit_ill != NULL)
18813 				ill_refrele(xmit_ill);
18814 			if (need_decref)
18815 				CONN_DEC_REF(connp);
18816 			return;
18817 		}
18818 
18819 		ipif_refrele(ipif);
18820 		ipif = NULL;
18821 		ASSERT(xmit_ill == NULL);
18822 
18823 		/*
18824 		 * Honor the RTF_SETSRC flag for multicast packets,
18825 		 * if allowed by the setsrc reminder.
18826 		 */
18827 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18828 			ipha->ipha_src = ire->ire_src_addr;
18829 		}
18830 
18831 		/*
18832 		 * Unconditionally force the TTL to 1 for
18833 		 * multirouted multicast packets:
18834 		 * multirouted multicast should not cross
18835 		 * multicast routers.
18836 		 */
18837 		if (ire->ire_flags & RTF_MULTIRT) {
18838 			if (ipha->ipha_ttl > 1) {
18839 				ip2dbg(("ip_wput: forcing multicast "
18840 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18841 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18842 				ipha->ipha_ttl = 1;
18843 			}
18844 		}
18845 	} else {
18846 		ire = ire_cache_lookup(dst, zoneid);
18847 		if ((ire != NULL) && (ire->ire_type &
18848 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18849 			ignore_dontroute = B_TRUE;
18850 			ignore_nexthop = B_TRUE;
18851 		}
18852 		if (ire != NULL) {
18853 			ire_refrele(ire);
18854 			ire = NULL;
18855 		}
18856 		/*
18857 		 * Guard against coming in from arp in which case conn is NULL.
18858 		 * Also guard against non M_DATA with dontroute set but
18859 		 * destined to local, loopback or broadcast addresses.
18860 		 */
18861 		if (connp != NULL && connp->conn_dontroute &&
18862 		    !ignore_dontroute) {
18863 dontroute:
18864 			/*
18865 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18866 			 * routing protocols from seeing false direct
18867 			 * connectivity.
18868 			 */
18869 			ipha->ipha_ttl = 1;
18870 			/*
18871 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18872 			 * along with SO_DONTROUTE, higher precedence is
18873 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18874 			 */
18875 			if (connp->conn_xmit_if_ill == NULL) {
18876 				/* If suitable ipif not found, drop packet */
18877 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18878 				if (dst_ipif == NULL) {
18879 					ip1dbg(("ip_wput: no route for "
18880 					    "dst using SO_DONTROUTE\n"));
18881 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18882 					mp->b_prev = mp->b_next = NULL;
18883 					if (first_mp == NULL)
18884 						first_mp = mp;
18885 					goto drop_pkt;
18886 				} else {
18887 					/*
18888 					 * If suitable ipif has been found, set
18889 					 * xmit_ill to the corresponding
18890 					 * ipif_ill because we'll be following
18891 					 * the IP_XMIT_IF logic.
18892 					 */
18893 					ASSERT(xmit_ill == NULL);
18894 					xmit_ill = dst_ipif->ipif_ill;
18895 					mutex_enter(&xmit_ill->ill_lock);
18896 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18897 						mutex_exit(&xmit_ill->ill_lock);
18898 						xmit_ill = NULL;
18899 						ipif_refrele(dst_ipif);
18900 						ip1dbg(("ip_wput: no route for"
18901 						    " dst using"
18902 						    " SO_DONTROUTE\n"));
18903 						BUMP_MIB(&ip_mib,
18904 						    ipOutNoRoutes);
18905 						mp->b_prev = mp->b_next = NULL;
18906 						if (first_mp == NULL)
18907 							first_mp = mp;
18908 						goto drop_pkt;
18909 					}
18910 					ill_refhold_locked(xmit_ill);
18911 					mutex_exit(&xmit_ill->ill_lock);
18912 					ipif_refrele(dst_ipif);
18913 				}
18914 			}
18915 
18916 		}
18917 		/*
18918 		 * If we are bound to IPIF_NOFAILOVER address, look for
18919 		 * an IRE_CACHE matching the ill.
18920 		 */
18921 send_from_ill:
18922 		if (attach_ill != NULL) {
18923 			ipif_t	*attach_ipif;
18924 
18925 			match_flags = MATCH_IRE_ILL;
18926 
18927 			/*
18928 			 * Check if we need an ire that will not be
18929 			 * looked up by anybody else i.e. HIDDEN.
18930 			 */
18931 			if (ill_is_probeonly(attach_ill)) {
18932 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18933 			}
18934 
18935 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18936 			if (attach_ipif == NULL) {
18937 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18938 				goto drop_pkt;
18939 			}
18940 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18941 			    zoneid, match_flags);
18942 			ipif_refrele(attach_ipif);
18943 		} else if (xmit_ill != NULL || (connp != NULL &&
18944 			    connp->conn_xmit_if_ill != NULL)) {
18945 			/*
18946 			 * Mark this packet as originated locally
18947 			 */
18948 			mp->b_prev = mp->b_next = NULL;
18949 			/*
18950 			 * xmit_ill could be NULL if SO_DONTROUTE
18951 			 * is also set.
18952 			 */
18953 			if (xmit_ill == NULL) {
18954 				xmit_ill = conn_get_held_ill(connp,
18955 				    &connp->conn_xmit_if_ill, &err);
18956 				if (err == ILL_LOOKUP_FAILED) {
18957 					if (need_decref)
18958 						CONN_DEC_REF(connp);
18959 					freemsg(first_mp);
18960 					return;
18961 				}
18962 				if (xmit_ill == NULL) {
18963 					if (connp->conn_dontroute)
18964 						goto dontroute;
18965 					goto send_from_ill;
18966 				}
18967 			}
18968 			/*
18969 			 * could be SO_DONTROUTE case also.
18970 			 * check at least one interface is UP as
18971 			 * spcified by this ILL, and then call
18972 			 * ip_newroute_ipif()
18973 			 */
18974 			if (xmit_ill->ill_ipif_up_count > 0) {
18975 				ipif_t *ipif;
18976 
18977 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18978 				if (ipif != NULL) {
18979 					ip_newroute_ipif(q, first_mp, ipif,
18980 					    dst, connp, 0);
18981 					ipif_refrele(ipif);
18982 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18983 				}
18984 			} else {
18985 				freemsg(first_mp);
18986 			}
18987 			ill_refrele(xmit_ill);
18988 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18989 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18990 			if (need_decref)
18991 				CONN_DEC_REF(connp);
18992 			return;
18993 		} else if (ip_nexthop || (connp != NULL &&
18994 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
18995 			if (!ip_nexthop) {
18996 				ip_nexthop = B_TRUE;
18997 				nexthop_addr = connp->conn_nexthop_v4;
18998 			}
18999 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19000 			    MATCH_IRE_GW;
19001 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19002 			    NULL, zoneid, match_flags);
19003 		} else {
19004 			ire = ire_cache_lookup(dst, zoneid);
19005 		}
19006 		if (!ire) {
19007 			/*
19008 			 * Make sure we don't load spread if this
19009 			 * is IPIF_NOFAILOVER case.
19010 			 */
19011 			if ((attach_ill != NULL) ||
19012 			    (ip_nexthop && !ignore_nexthop)) {
19013 				if (mctl_present) {
19014 					io = (ipsec_out_t *)first_mp->b_rptr;
19015 					ASSERT(first_mp->b_datap->db_type ==
19016 					    M_CTL);
19017 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19018 				} else {
19019 					ASSERT(mp == first_mp);
19020 					first_mp = allocb(
19021 					    sizeof (ipsec_info_t), BPRI_HI);
19022 					if (first_mp == NULL) {
19023 						first_mp = mp;
19024 						goto drop_pkt;
19025 					}
19026 					first_mp->b_datap->db_type = M_CTL;
19027 					first_mp->b_wptr +=
19028 					    sizeof (ipsec_info_t);
19029 					/* ipsec_out_secure is B_FALSE now */
19030 					bzero(first_mp->b_rptr,
19031 					    sizeof (ipsec_info_t));
19032 					io = (ipsec_out_t *)first_mp->b_rptr;
19033 					io->ipsec_out_type = IPSEC_OUT;
19034 					io->ipsec_out_len =
19035 					    sizeof (ipsec_out_t);
19036 					io->ipsec_out_use_global_policy =
19037 					    B_TRUE;
19038 					first_mp->b_cont = mp;
19039 					mctl_present = B_TRUE;
19040 				}
19041 				if (attach_ill != NULL) {
19042 					io->ipsec_out_ill_index = attach_ill->
19043 					    ill_phyint->phyint_ifindex;
19044 					io->ipsec_out_attach_if = B_TRUE;
19045 				} else {
19046 					io->ipsec_out_ip_nexthop = ip_nexthop;
19047 					io->ipsec_out_nexthop_addr =
19048 					    nexthop_addr;
19049 				}
19050 			}
19051 noirefound:
19052 			/*
19053 			 * Mark this packet as having originated on
19054 			 * this machine.  This will be noted in
19055 			 * ire_add_then_send, which needs to know
19056 			 * whether to run it back through ip_wput or
19057 			 * ip_rput following successful resolution.
19058 			 */
19059 			mp->b_prev = NULL;
19060 			mp->b_next = NULL;
19061 			ip_newroute(q, first_mp, dst, NULL, connp);
19062 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19063 			    "ip_wput_end: q %p (%S)", q, "newroute");
19064 			if (attach_ill != NULL)
19065 				ill_refrele(attach_ill);
19066 			if (xmit_ill != NULL)
19067 				ill_refrele(xmit_ill);
19068 			if (need_decref)
19069 				CONN_DEC_REF(connp);
19070 			return;
19071 		}
19072 	}
19073 
19074 	/* We now know where we are going with it. */
19075 
19076 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19077 	    "ip_wput_end: q %p (%S)", q, "end");
19078 
19079 	/*
19080 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19081 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19082 	 */
19083 	if (ire->ire_flags & RTF_MULTIRT) {
19084 		/*
19085 		 * Force the TTL of multirouted packets if required.
19086 		 * The TTL of such packets is bounded by the
19087 		 * ip_multirt_ttl ndd variable.
19088 		 */
19089 		if ((ip_multirt_ttl > 0) &&
19090 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19091 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19092 			    "(was %d), dst 0x%08x\n",
19093 			    ip_multirt_ttl, ipha->ipha_ttl,
19094 			    ntohl(ire->ire_addr)));
19095 			ipha->ipha_ttl = ip_multirt_ttl;
19096 		}
19097 		/*
19098 		 * At this point, we check to see if there are any pending
19099 		 * unresolved routes. ire_multirt_resolvable()
19100 		 * checks in O(n) that all IRE_OFFSUBNET ire
19101 		 * entries for the packet's destination and
19102 		 * flagged RTF_MULTIRT are currently resolved.
19103 		 * If some remain unresolved, we make a copy
19104 		 * of the current message. It will be used
19105 		 * to initiate additional route resolutions.
19106 		 */
19107 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
19108 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19109 		    "multirt_need_resolve %d, first_mp %p\n",
19110 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19111 		if (multirt_need_resolve) {
19112 			copy_mp = copymsg(first_mp);
19113 			if (copy_mp != NULL) {
19114 				MULTIRT_DEBUG_TAG(copy_mp);
19115 			}
19116 		}
19117 	}
19118 
19119 	ip_wput_ire(q, first_mp, ire, connp, caller);
19120 	/*
19121 	 * Try to resolve another multiroute if
19122 	 * ire_multirt_resolvable() deemed it necessary.
19123 	 * At this point, we need to distinguish
19124 	 * multicasts from other packets. For multicasts,
19125 	 * we call ip_newroute_ipif() and request that both
19126 	 * multirouting and setsrc flags are checked.
19127 	 */
19128 	if (copy_mp != NULL) {
19129 		if (CLASSD(dst)) {
19130 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19131 			if (ipif) {
19132 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19133 				    RTF_SETSRC | RTF_MULTIRT);
19134 				ipif_refrele(ipif);
19135 			} else {
19136 				MULTIRT_DEBUG_UNTAG(copy_mp);
19137 				freemsg(copy_mp);
19138 				copy_mp = NULL;
19139 			}
19140 		} else {
19141 			ip_newroute(q, copy_mp, dst, NULL, connp);
19142 		}
19143 	}
19144 	if (attach_ill != NULL)
19145 		ill_refrele(attach_ill);
19146 	if (xmit_ill != NULL)
19147 		ill_refrele(xmit_ill);
19148 	if (need_decref)
19149 		CONN_DEC_REF(connp);
19150 	return;
19151 
19152 drop_pkt:
19153 	ip1dbg(("ip_wput: dropped packet\n"));
19154 	if (ire != NULL)
19155 		ire_refrele(ire);
19156 	if (need_decref)
19157 		CONN_DEC_REF(connp);
19158 	freemsg(first_mp);
19159 	if (attach_ill != NULL)
19160 		ill_refrele(attach_ill);
19161 	if (xmit_ill != NULL)
19162 		ill_refrele(xmit_ill);
19163 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19164 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19165 }
19166 
19167 void
19168 ip_wput(queue_t *q, mblk_t *mp)
19169 {
19170 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19171 }
19172 
19173 /*
19174  *
19175  * The following rules must be observed when accessing any ipif or ill
19176  * that has been cached in the conn. Typically conn_nofailover_ill,
19177  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19178  *
19179  * Access: The ipif or ill pointed to from the conn can be accessed under
19180  * the protection of the conn_lock or after it has been refheld under the
19181  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19182  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19183  * The reason for this is that a concurrent unplumb could actually be
19184  * cleaning up these cached pointers by walking the conns and might have
19185  * finished cleaning up the conn in question. The macros check that an
19186  * unplumb has not yet started on the ipif or ill.
19187  *
19188  * Caching: An ipif or ill pointer may be cached in the conn only after
19189  * making sure that an unplumb has not started. So the caching is done
19190  * while holding both the conn_lock and the ill_lock and after using the
19191  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
19192  * flag before starting the cleanup of conns.
19193  *
19194  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
19195  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
19196  * or a reference to the ipif or a reference to an ire that references the
19197  * ipif. An ipif does not change its ill except for failover/failback. Since
19198  * failover/failback happens only after bringing down the ipif and making sure
19199  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
19200  * the above holds.
19201  */
19202 ipif_t *
19203 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
19204 {
19205 	ipif_t	*ipif;
19206 	ill_t	*ill;
19207 
19208 	*err = 0;
19209 	rw_enter(&ill_g_lock, RW_READER);
19210 	mutex_enter(&connp->conn_lock);
19211 	ipif = *ipifp;
19212 	if (ipif != NULL) {
19213 		ill = ipif->ipif_ill;
19214 		mutex_enter(&ill->ill_lock);
19215 		if (IPIF_CAN_LOOKUP(ipif)) {
19216 			ipif_refhold_locked(ipif);
19217 			mutex_exit(&ill->ill_lock);
19218 			mutex_exit(&connp->conn_lock);
19219 			rw_exit(&ill_g_lock);
19220 			return (ipif);
19221 		} else {
19222 			*err = IPIF_LOOKUP_FAILED;
19223 		}
19224 		mutex_exit(&ill->ill_lock);
19225 	}
19226 	mutex_exit(&connp->conn_lock);
19227 	rw_exit(&ill_g_lock);
19228 	return (NULL);
19229 }
19230 
19231 ill_t *
19232 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
19233 {
19234 	ill_t	*ill;
19235 
19236 	*err = 0;
19237 	mutex_enter(&connp->conn_lock);
19238 	ill = *illp;
19239 	if (ill != NULL) {
19240 		mutex_enter(&ill->ill_lock);
19241 		if (ILL_CAN_LOOKUP(ill)) {
19242 			ill_refhold_locked(ill);
19243 			mutex_exit(&ill->ill_lock);
19244 			mutex_exit(&connp->conn_lock);
19245 			return (ill);
19246 		} else {
19247 			*err = ILL_LOOKUP_FAILED;
19248 		}
19249 		mutex_exit(&ill->ill_lock);
19250 	}
19251 	mutex_exit(&connp->conn_lock);
19252 	return (NULL);
19253 }
19254 
19255 static int
19256 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
19257 {
19258 	ill_t	*ill;
19259 
19260 	ill = ipif->ipif_ill;
19261 	mutex_enter(&connp->conn_lock);
19262 	mutex_enter(&ill->ill_lock);
19263 	if (IPIF_CAN_LOOKUP(ipif)) {
19264 		*ipifp = ipif;
19265 		mutex_exit(&ill->ill_lock);
19266 		mutex_exit(&connp->conn_lock);
19267 		return (0);
19268 	}
19269 	mutex_exit(&ill->ill_lock);
19270 	mutex_exit(&connp->conn_lock);
19271 	return (IPIF_LOOKUP_FAILED);
19272 }
19273 
19274 /*
19275  * This is called if the outbound datagram needs fragmentation.
19276  *
19277  * NOTE : This function does not ire_refrele the ire argument passed in.
19278  */
19279 static void
19280 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19281 {
19282 	ipha_t		*ipha;
19283 	mblk_t		*mp;
19284 	uint32_t	v_hlen_tos_len;
19285 	uint32_t	max_frag;
19286 	uint32_t	frag_flag;
19287 	boolean_t	dont_use;
19288 
19289 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19290 		mp = ipsec_mp->b_cont;
19291 	} else {
19292 		mp = ipsec_mp;
19293 	}
19294 
19295 	ipha = (ipha_t *)mp->b_rptr;
19296 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19297 
19298 #ifdef	_BIG_ENDIAN
19299 #define	V_HLEN	(v_hlen_tos_len >> 24)
19300 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19301 #else
19302 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19303 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19304 #endif
19305 
19306 #ifndef SPEED_BEFORE_SAFETY
19307 	/*
19308 	 * Check that ipha_length is consistent with
19309 	 * the mblk length
19310 	 */
19311 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19312 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19313 		    LENGTH, msgdsize(mp)));
19314 		freemsg(ipsec_mp);
19315 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19316 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19317 		    "packet length mismatch");
19318 		return;
19319 	}
19320 #endif
19321 	/*
19322 	 * Don't use frag_flag if pre-built packet or source
19323 	 * routed or if multicast (since multicast packets do not solicit
19324 	 * ICMP "packet too big" messages). Get the values of
19325 	 * max_frag and frag_flag atomically by acquiring the
19326 	 * ire_lock.
19327 	 */
19328 	mutex_enter(&ire->ire_lock);
19329 	max_frag = ire->ire_max_frag;
19330 	frag_flag = ire->ire_frag_flag;
19331 	mutex_exit(&ire->ire_lock);
19332 
19333 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19334 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19335 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19336 
19337 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19338 	    (dont_use ? 0 : frag_flag));
19339 }
19340 
19341 /*
19342  * Used for deciding the MSS size for the upper layer. Thus
19343  * we need to check the outbound policy values in the conn.
19344  */
19345 int
19346 conn_ipsec_length(conn_t *connp)
19347 {
19348 	ipsec_latch_t *ipl;
19349 
19350 	ipl = connp->conn_latch;
19351 	if (ipl == NULL)
19352 		return (0);
19353 
19354 	if (ipl->ipl_out_policy == NULL)
19355 		return (0);
19356 
19357 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19358 }
19359 
19360 /*
19361  * Returns an estimate of the IPSEC headers size. This is used if
19362  * we don't want to call into IPSEC to get the exact size.
19363  */
19364 int
19365 ipsec_out_extra_length(mblk_t *ipsec_mp)
19366 {
19367 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19368 	ipsec_action_t *a;
19369 
19370 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19371 	if (!io->ipsec_out_secure)
19372 		return (0);
19373 
19374 	a = io->ipsec_out_act;
19375 
19376 	if (a == NULL) {
19377 		ASSERT(io->ipsec_out_policy != NULL);
19378 		a = io->ipsec_out_policy->ipsp_act;
19379 	}
19380 	ASSERT(a != NULL);
19381 
19382 	return (a->ipa_ovhd);
19383 }
19384 
19385 /*
19386  * Returns an estimate of the IPSEC headers size. This is used if
19387  * we don't want to call into IPSEC to get the exact size.
19388  */
19389 int
19390 ipsec_in_extra_length(mblk_t *ipsec_mp)
19391 {
19392 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19393 	ipsec_action_t *a;
19394 
19395 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19396 
19397 	a = ii->ipsec_in_action;
19398 	return (a == NULL ? 0 : a->ipa_ovhd);
19399 }
19400 
19401 /*
19402  * If there are any source route options, return the true final
19403  * destination. Otherwise, return the destination.
19404  */
19405 ipaddr_t
19406 ip_get_dst(ipha_t *ipha)
19407 {
19408 	ipoptp_t	opts;
19409 	uchar_t		*opt;
19410 	uint8_t		optval;
19411 	uint8_t		optlen;
19412 	ipaddr_t	dst;
19413 	uint32_t off;
19414 
19415 	dst = ipha->ipha_dst;
19416 
19417 	if (IS_SIMPLE_IPH(ipha))
19418 		return (dst);
19419 
19420 	for (optval = ipoptp_first(&opts, ipha);
19421 	    optval != IPOPT_EOL;
19422 	    optval = ipoptp_next(&opts)) {
19423 		opt = opts.ipoptp_cur;
19424 		optlen = opts.ipoptp_len;
19425 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19426 		switch (optval) {
19427 		case IPOPT_SSRR:
19428 		case IPOPT_LSRR:
19429 			off = opt[IPOPT_OFFSET];
19430 			/*
19431 			 * If one of the conditions is true, it means
19432 			 * end of options and dst already has the right
19433 			 * value.
19434 			 */
19435 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19436 				off = optlen - IP_ADDR_LEN;
19437 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19438 			}
19439 			return (dst);
19440 		default:
19441 			break;
19442 		}
19443 	}
19444 
19445 	return (dst);
19446 }
19447 
19448 mblk_t *
19449 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19450     conn_t *connp, boolean_t unspec_src)
19451 {
19452 	ipsec_out_t	*io;
19453 	mblk_t		*first_mp;
19454 	boolean_t policy_present;
19455 
19456 	first_mp = mp;
19457 	if (mp->b_datap->db_type == M_CTL) {
19458 		io = (ipsec_out_t *)first_mp->b_rptr;
19459 		/*
19460 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19461 		 *
19462 		 * 1) There is per-socket policy (including cached global
19463 		 *    policy).
19464 		 * 2) There is no per-socket policy, but it is
19465 		 *    a multicast packet that needs to go out
19466 		 *    on a specific interface. This is the case
19467 		 *    where (ip_wput and ip_wput_multicast) attaches
19468 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19469 		 *
19470 		 * In case (2) we check with global policy to
19471 		 * see if there is a match and set the ill_index
19472 		 * appropriately so that we can lookup the ire
19473 		 * properly in ip_wput_ipsec_out.
19474 		 */
19475 
19476 		/*
19477 		 * ipsec_out_use_global_policy is set to B_FALSE
19478 		 * in ipsec_in_to_out(). Refer to that function for
19479 		 * details.
19480 		 */
19481 		if ((io->ipsec_out_latch == NULL) &&
19482 		    (io->ipsec_out_use_global_policy)) {
19483 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19484 			    ire, connp, unspec_src));
19485 		}
19486 		if (!io->ipsec_out_secure) {
19487 			/*
19488 			 * If this is not a secure packet, drop
19489 			 * the IPSEC_OUT mp and treat it as a clear
19490 			 * packet. This happens when we are sending
19491 			 * a ICMP reply back to a clear packet. See
19492 			 * ipsec_in_to_out() for details.
19493 			 */
19494 			mp = first_mp->b_cont;
19495 			freeb(first_mp);
19496 		}
19497 		return (mp);
19498 	}
19499 	/*
19500 	 * See whether we need to attach a global policy here. We
19501 	 * don't depend on the conn (as it could be null) for deciding
19502 	 * what policy this datagram should go through because it
19503 	 * should have happened in ip_wput if there was some
19504 	 * policy. This normally happens for connections which are not
19505 	 * fully bound preventing us from caching policies in
19506 	 * ip_bind. Packets coming from the TCP listener/global queue
19507 	 * - which are non-hard_bound - could also be affected by
19508 	 * applying policy here.
19509 	 *
19510 	 * If this packet is coming from tcp global queue or listener,
19511 	 * we will be applying policy here.  This may not be *right*
19512 	 * if these packets are coming from the detached connection as
19513 	 * it could have gone in clear before. This happens only if a
19514 	 * TCP connection started when there is no policy and somebody
19515 	 * added policy before it became detached. Thus packets of the
19516 	 * detached connection could go out secure and the other end
19517 	 * would drop it because it will be expecting in clear. The
19518 	 * converse is not true i.e if somebody starts a TCP
19519 	 * connection and deletes the policy, all the packets will
19520 	 * still go out with the policy that existed before deleting
19521 	 * because ip_unbind sends up policy information which is used
19522 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19523 	 * TCP to attach a dummy IPSEC_OUT and set
19524 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19525 	 * affect performance for normal cases, we are not doing it.
19526 	 * Thus, set policy before starting any TCP connections.
19527 	 *
19528 	 * NOTE - We might apply policy even for a hard bound connection
19529 	 * - for which we cached policy in ip_bind - if somebody added
19530 	 * global policy after we inherited the policy in ip_bind.
19531 	 * This means that the packets that were going out in clear
19532 	 * previously would start going secure and hence get dropped
19533 	 * on the other side. To fix this, TCP attaches a dummy
19534 	 * ipsec_out and make sure that we don't apply global policy.
19535 	 */
19536 	if (ipha != NULL)
19537 		policy_present = ipsec_outbound_v4_policy_present;
19538 	else
19539 		policy_present = ipsec_outbound_v6_policy_present;
19540 	if (!policy_present)
19541 		return (mp);
19542 
19543 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19544 }
19545 
19546 ire_t *
19547 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19548 {
19549 	ipaddr_t addr;
19550 	ire_t *save_ire;
19551 	irb_t *irb;
19552 	ill_group_t *illgrp;
19553 	int	err;
19554 
19555 	save_ire = ire;
19556 	addr = ire->ire_addr;
19557 
19558 	ASSERT(ire->ire_type == IRE_BROADCAST);
19559 
19560 	illgrp = connp->conn_outgoing_ill->ill_group;
19561 	if (illgrp == NULL) {
19562 		*conn_outgoing_ill = conn_get_held_ill(connp,
19563 		    &connp->conn_outgoing_ill, &err);
19564 		if (err == ILL_LOOKUP_FAILED) {
19565 			ire_refrele(save_ire);
19566 			return (NULL);
19567 		}
19568 		return (save_ire);
19569 	}
19570 	/*
19571 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19572 	 * If it is part of the group, we need to send on the ire
19573 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19574 	 * to this group. This is okay as IP_BOUND_IF really means
19575 	 * any ill in the group. We depend on the fact that the
19576 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19577 	 * if such an ire exists. This is possible only if you have
19578 	 * at least one ill in the group that has not failed.
19579 	 *
19580 	 * First get to the ire that matches the address and group.
19581 	 *
19582 	 * We don't look for an ire with a matching zoneid because a given zone
19583 	 * won't always have broadcast ires on all ills in the group.
19584 	 */
19585 	irb = ire->ire_bucket;
19586 	rw_enter(&irb->irb_lock, RW_READER);
19587 	if (ire->ire_marks & IRE_MARK_NORECV) {
19588 		/*
19589 		 * If the current zone only has an ire broadcast for this
19590 		 * address marked NORECV, the ire we want is ahead in the
19591 		 * bucket, so we look it up deliberately ignoring the zoneid.
19592 		 */
19593 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19594 			if (ire->ire_addr != addr)
19595 				continue;
19596 			/* skip over deleted ires */
19597 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19598 				continue;
19599 		}
19600 	}
19601 	while (ire != NULL) {
19602 		/*
19603 		 * If a new interface is coming up, we could end up
19604 		 * seeing the loopback ire and the non-loopback ire
19605 		 * may not have been added yet. So check for ire_stq
19606 		 */
19607 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19608 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19609 			break;
19610 		}
19611 		ire = ire->ire_next;
19612 	}
19613 	if (ire != NULL && ire->ire_addr == addr &&
19614 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19615 		IRE_REFHOLD(ire);
19616 		rw_exit(&irb->irb_lock);
19617 		ire_refrele(save_ire);
19618 		*conn_outgoing_ill = ire_to_ill(ire);
19619 		/*
19620 		 * Refhold the ill to make the conn_outgoing_ill
19621 		 * independent of the ire. ip_wput_ire goes in a loop
19622 		 * and may refrele the ire. Since we have an ire at this
19623 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19624 		 */
19625 		ill_refhold(*conn_outgoing_ill);
19626 		return (ire);
19627 	}
19628 	rw_exit(&irb->irb_lock);
19629 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19630 	/*
19631 	 * If we can't find a suitable ire, return the original ire.
19632 	 */
19633 	return (save_ire);
19634 }
19635 
19636 /*
19637  * This function does the ire_refrele of the ire passed in as the
19638  * argument. As this function looks up more ires i.e broadcast ires,
19639  * it needs to REFRELE them. Currently, for simplicity we don't
19640  * differentiate the one passed in and looked up here. We always
19641  * REFRELE.
19642  * IPQoS Notes:
19643  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19644  * IPSec packets are done in ipsec_out_process.
19645  *
19646  */
19647 void
19648 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19649 {
19650 	ipha_t		*ipha;
19651 #define	rptr	((uchar_t *)ipha)
19652 	mblk_t		*mp1;
19653 	queue_t		*stq;
19654 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19655 	uint32_t	v_hlen_tos_len;
19656 	uint32_t	ttl_protocol;
19657 	ipaddr_t	src;
19658 	ipaddr_t	dst;
19659 	uint32_t	cksum;
19660 	ipaddr_t	orig_src;
19661 	ire_t		*ire1;
19662 	mblk_t		*next_mp;
19663 	uint_t		hlen;
19664 	uint16_t	*up;
19665 	uint32_t	max_frag = ire->ire_max_frag;
19666 	ill_t		*ill = ire_to_ill(ire);
19667 	int		clusterwide;
19668 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19669 	int		ipsec_len;
19670 	mblk_t		*first_mp;
19671 	ipsec_out_t	*io;
19672 	boolean_t	conn_dontroute;		/* conn value for multicast */
19673 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19674 	boolean_t	multicast_forward;	/* Should we forward ? */
19675 	boolean_t	unspec_src;
19676 	ill_t		*conn_outgoing_ill = NULL;
19677 	ill_t		*ire_ill;
19678 	ill_t		*ire1_ill;
19679 	uint32_t 	ill_index = 0;
19680 	boolean_t	multirt_send = B_FALSE;
19681 	int		err;
19682 	zoneid_t	zoneid;
19683 
19684 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19685 	    "ip_wput_ire_start: q %p", q);
19686 
19687 	multicast_forward = B_FALSE;
19688 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19689 
19690 	if (ire->ire_flags & RTF_MULTIRT) {
19691 		/*
19692 		 * Multirouting case. The bucket where ire is stored
19693 		 * probably holds other RTF_MULTIRT flagged ire
19694 		 * to the destination. In this call to ip_wput_ire,
19695 		 * we attempt to send the packet through all
19696 		 * those ires. Thus, we first ensure that ire is the
19697 		 * first RTF_MULTIRT ire in the bucket,
19698 		 * before walking the ire list.
19699 		 */
19700 		ire_t *first_ire;
19701 		irb_t *irb = ire->ire_bucket;
19702 		ASSERT(irb != NULL);
19703 
19704 		/* Make sure we do not omit any multiroute ire. */
19705 		IRB_REFHOLD(irb);
19706 		for (first_ire = irb->irb_ire;
19707 		    first_ire != NULL;
19708 		    first_ire = first_ire->ire_next) {
19709 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19710 			    (first_ire->ire_addr == ire->ire_addr) &&
19711 			    !(first_ire->ire_marks &
19712 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19713 				break;
19714 		}
19715 
19716 		if ((first_ire != NULL) && (first_ire != ire)) {
19717 			IRE_REFHOLD(first_ire);
19718 			ire_refrele(ire);
19719 			ire = first_ire;
19720 			ill = ire_to_ill(ire);
19721 		}
19722 		IRB_REFRELE(irb);
19723 	}
19724 
19725 	/*
19726 	 * conn_outgoing_ill is used only in the broadcast loop.
19727 	 * for performance we don't grab the mutexs in the fastpath
19728 	 */
19729 	if ((connp != NULL) &&
19730 	    (connp->conn_xmit_if_ill == NULL) &&
19731 	    (ire->ire_type == IRE_BROADCAST) &&
19732 	    ((connp->conn_nofailover_ill != NULL) ||
19733 	    (connp->conn_outgoing_ill != NULL))) {
19734 		/*
19735 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19736 		 * option. So, see if this endpoint is bound to a
19737 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19738 		 * that if the interface is failed, we will still send
19739 		 * the packet on the same ill which is what we want.
19740 		 */
19741 		conn_outgoing_ill = conn_get_held_ill(connp,
19742 		    &connp->conn_nofailover_ill, &err);
19743 		if (err == ILL_LOOKUP_FAILED) {
19744 			ire_refrele(ire);
19745 			freemsg(mp);
19746 			return;
19747 		}
19748 		if (conn_outgoing_ill == NULL) {
19749 			/*
19750 			 * Choose a good ill in the group to send the
19751 			 * packets on.
19752 			 */
19753 			ire = conn_set_outgoing_ill(connp, ire,
19754 			    &conn_outgoing_ill);
19755 			if (ire == NULL) {
19756 				freemsg(mp);
19757 				return;
19758 			}
19759 		}
19760 	}
19761 
19762 	if (mp->b_datap->db_type != M_CTL) {
19763 		ipha = (ipha_t *)mp->b_rptr;
19764 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19765 	} else {
19766 		io = (ipsec_out_t *)mp->b_rptr;
19767 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19768 		zoneid = io->ipsec_out_zoneid;
19769 		ASSERT(zoneid != ALL_ZONES);
19770 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19771 		dst = ipha->ipha_dst;
19772 		/*
19773 		 * For the multicast case, ipsec_out carries conn_dontroute and
19774 		 * conn_multicast_loop as conn may not be available here. We
19775 		 * need this for multicast loopback and forwarding which is done
19776 		 * later in the code.
19777 		 */
19778 		if (CLASSD(dst)) {
19779 			conn_dontroute = io->ipsec_out_dontroute;
19780 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19781 			/*
19782 			 * If conn_dontroute is not set or conn_multicast_loop
19783 			 * is set, we need to do forwarding/loopback. For
19784 			 * datagrams from ip_wput_multicast, conn_dontroute is
19785 			 * set to B_TRUE and conn_multicast_loop is set to
19786 			 * B_FALSE so that we neither do forwarding nor
19787 			 * loopback.
19788 			 */
19789 			if (!conn_dontroute || conn_multicast_loop)
19790 				multicast_forward = B_TRUE;
19791 		}
19792 	}
19793 
19794 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19795 		/*
19796 		 * When a zone sends a packet to another zone, we try to deliver
19797 		 * the packet under the same conditions as if the destination
19798 		 * was a real node on the network. To do so, we look for a
19799 		 * matching route in the forwarding table.
19800 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19801 		 * ip_newroute() does.
19802 		 */
19803 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19804 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19805 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19806 		if (src_ire != NULL &&
19807 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19808 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19809 				ipha->ipha_src = src_ire->ire_src_addr;
19810 			ire_refrele(src_ire);
19811 		} else {
19812 			ire_refrele(ire);
19813 			if (conn_outgoing_ill != NULL)
19814 				ill_refrele(conn_outgoing_ill);
19815 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19816 			if (src_ire != NULL) {
19817 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19818 					ire_refrele(src_ire);
19819 					freemsg(mp);
19820 					return;
19821 				}
19822 				ire_refrele(src_ire);
19823 			}
19824 			if (ip_hdr_complete(ipha, zoneid)) {
19825 				/* Failed */
19826 				freemsg(mp);
19827 				return;
19828 			}
19829 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19830 			return;
19831 		}
19832 	}
19833 
19834 	if (mp->b_datap->db_type == M_CTL ||
19835 	    ipsec_outbound_v4_policy_present) {
19836 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19837 		    unspec_src);
19838 		if (mp == NULL) {
19839 			ire_refrele(ire);
19840 			if (conn_outgoing_ill != NULL)
19841 				ill_refrele(conn_outgoing_ill);
19842 			return;
19843 		}
19844 	}
19845 
19846 	first_mp = mp;
19847 	ipsec_len = 0;
19848 
19849 	if (first_mp->b_datap->db_type == M_CTL) {
19850 		io = (ipsec_out_t *)first_mp->b_rptr;
19851 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19852 		mp = first_mp->b_cont;
19853 		ipsec_len = ipsec_out_extra_length(first_mp);
19854 		ASSERT(ipsec_len >= 0);
19855 		zoneid = io->ipsec_out_zoneid;
19856 		ASSERT(zoneid != ALL_ZONES);
19857 
19858 		/*
19859 		 * Drop M_CTL here if IPsec processing is not needed.
19860 		 * (Non-IPsec use of M_CTL extracted any information it
19861 		 * needed above).
19862 		 */
19863 		if (ipsec_len == 0) {
19864 			freeb(first_mp);
19865 			first_mp = mp;
19866 		}
19867 	}
19868 
19869 	/*
19870 	 * Fast path for ip_wput_ire
19871 	 */
19872 
19873 	ipha = (ipha_t *)mp->b_rptr;
19874 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19875 	dst = ipha->ipha_dst;
19876 
19877 	/*
19878 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19879 	 * if the socket is a SOCK_RAW type. The transport checksum should
19880 	 * be provided in the pre-built packet, so we don't need to compute it.
19881 	 * Also, other application set flags, like DF, should not be altered.
19882 	 * Other transport MUST pass down zero.
19883 	 */
19884 	ip_hdr_included = ipha->ipha_ident;
19885 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19886 
19887 	if (CLASSD(dst)) {
19888 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19889 		    ntohl(dst),
19890 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19891 		    ntohl(ire->ire_addr)));
19892 	}
19893 
19894 /* Macros to extract header fields from data already in registers */
19895 #ifdef	_BIG_ENDIAN
19896 #define	V_HLEN	(v_hlen_tos_len >> 24)
19897 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19898 #define	PROTO	(ttl_protocol & 0xFF)
19899 #else
19900 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19901 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19902 #define	PROTO	(ttl_protocol >> 8)
19903 #endif
19904 
19905 
19906 	orig_src = src = ipha->ipha_src;
19907 	/* (The loop back to "another" is explained down below.) */
19908 another:;
19909 	/*
19910 	 * Assign an ident value for this packet.  We assign idents on
19911 	 * a per destination basis out of the IRE.  There could be
19912 	 * other threads targeting the same destination, so we have to
19913 	 * arrange for a atomic increment.  Note that we use a 32-bit
19914 	 * atomic add because it has better performance than its
19915 	 * 16-bit sibling.
19916 	 *
19917 	 * If running in cluster mode and if the source address
19918 	 * belongs to a replicated service then vector through
19919 	 * cl_inet_ipident vector to allocate ip identifier
19920 	 * NOTE: This is a contract private interface with the
19921 	 * clustering group.
19922 	 */
19923 	clusterwide = 0;
19924 	if (cl_inet_ipident) {
19925 		ASSERT(cl_inet_isclusterwide);
19926 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19927 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19928 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19929 			    AF_INET, (uint8_t *)(uintptr_t)src,
19930 			    (uint8_t *)(uintptr_t)dst);
19931 			clusterwide = 1;
19932 		}
19933 	}
19934 	if (!clusterwide) {
19935 		ipha->ipha_ident =
19936 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19937 	}
19938 
19939 #ifndef _BIG_ENDIAN
19940 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19941 #endif
19942 
19943 	/*
19944 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19945 	 * This is needed to obey conn_unspec_src when packets go through
19946 	 * ip_newroute + arp.
19947 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19948 	 */
19949 	if (src == INADDR_ANY && !unspec_src) {
19950 		/*
19951 		 * Assign the appropriate source address from the IRE if none
19952 		 * was specified.
19953 		 */
19954 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19955 
19956 		/*
19957 		 * With IP multipathing, broadcast packets are sent on the ire
19958 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19959 		 * the group. However, this ire might not be in the same zone so
19960 		 * we can't always use its source address. We look for a
19961 		 * broadcast ire in the same group and in the right zone.
19962 		 */
19963 		if (ire->ire_type == IRE_BROADCAST &&
19964 		    ire->ire_zoneid != zoneid) {
19965 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19966 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19967 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19968 			if (src_ire != NULL) {
19969 				src = src_ire->ire_src_addr;
19970 				ire_refrele(src_ire);
19971 			} else {
19972 				ire_refrele(ire);
19973 				if (conn_outgoing_ill != NULL)
19974 					ill_refrele(conn_outgoing_ill);
19975 				freemsg(first_mp);
19976 				BUMP_MIB(&ip_mib, ipOutDiscards);
19977 				return;
19978 			}
19979 		} else {
19980 			src = ire->ire_src_addr;
19981 		}
19982 
19983 		if (connp == NULL) {
19984 			ip1dbg(("ip_wput_ire: no connp and no src "
19985 			    "address for dst 0x%x, using src 0x%x\n",
19986 			    ntohl(dst),
19987 			    ntohl(src)));
19988 		}
19989 		ipha->ipha_src = src;
19990 	}
19991 	stq = ire->ire_stq;
19992 
19993 	/*
19994 	 * We only allow ire chains for broadcasts since there will
19995 	 * be multiple IRE_CACHE entries for the same multicast
19996 	 * address (one per ipif).
19997 	 */
19998 	next_mp = NULL;
19999 
20000 	/* broadcast packet */
20001 	if (ire->ire_type == IRE_BROADCAST)
20002 		goto broadcast;
20003 
20004 	/* loopback ? */
20005 	if (stq == NULL)
20006 		goto nullstq;
20007 
20008 	/* The ill_index for outbound ILL */
20009 	ill_index = Q_TO_INDEX(stq);
20010 
20011 	BUMP_MIB(&ip_mib, ipOutRequests);
20012 	ttl_protocol = ((uint16_t *)ipha)[4];
20013 
20014 	/* pseudo checksum (do it in parts for IP header checksum) */
20015 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20016 
20017 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20018 		queue_t *dev_q = stq->q_next;
20019 
20020 		/* flow controlled */
20021 		if ((dev_q->q_next || dev_q->q_first) &&
20022 		    !canput(dev_q))
20023 			goto blocked;
20024 		if ((PROTO == IPPROTO_UDP) &&
20025 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20026 			hlen = (V_HLEN & 0xF) << 2;
20027 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20028 			if (*up != 0) {
20029 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20030 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20031 				/* Software checksum? */
20032 				if (DB_CKSUMFLAGS(mp) == 0) {
20033 					IP_STAT(ip_out_sw_cksum);
20034 					IP_STAT_UPDATE(
20035 					    ip_udp_out_sw_cksum_bytes,
20036 					    LENGTH - hlen);
20037 				}
20038 			}
20039 		}
20040 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20041 		hlen = (V_HLEN & 0xF) << 2;
20042 		if (PROTO == IPPROTO_TCP) {
20043 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20044 			/*
20045 			 * The packet header is processed once and for all, even
20046 			 * in the multirouting case. We disable hardware
20047 			 * checksum if the packet is multirouted, as it will be
20048 			 * replicated via several interfaces, and not all of
20049 			 * them may have this capability.
20050 			 */
20051 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20052 			    LENGTH, max_frag, ipsec_len, cksum);
20053 			/* Software checksum? */
20054 			if (DB_CKSUMFLAGS(mp) == 0) {
20055 				IP_STAT(ip_out_sw_cksum);
20056 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20057 				    LENGTH - hlen);
20058 			}
20059 		} else {
20060 			sctp_hdr_t	*sctph;
20061 
20062 			ASSERT(PROTO == IPPROTO_SCTP);
20063 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20064 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20065 			/*
20066 			 * Zero out the checksum field to ensure proper
20067 			 * checksum calculation.
20068 			 */
20069 			sctph->sh_chksum = 0;
20070 #ifdef	DEBUG
20071 			if (!skip_sctp_cksum)
20072 #endif
20073 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20074 		}
20075 	}
20076 
20077 	/*
20078 	 * If this is a multicast packet and originated from ip_wput
20079 	 * we need to do loopback and forwarding checks. If it comes
20080 	 * from ip_wput_multicast, we SHOULD not do this.
20081 	 */
20082 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20083 
20084 	/* checksum */
20085 	cksum += ttl_protocol;
20086 
20087 	/* fragment the packet */
20088 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20089 		goto fragmentit;
20090 	/*
20091 	 * Don't use frag_flag if packet is pre-built or source
20092 	 * routed or if multicast (since multicast packets do
20093 	 * not solicit ICMP "packet too big" messages).
20094 	 */
20095 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20096 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20097 	    !ip_source_route_included(ipha)) &&
20098 	    !CLASSD(ipha->ipha_dst))
20099 		ipha->ipha_fragment_offset_and_flags |=
20100 		    htons(ire->ire_frag_flag);
20101 
20102 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20103 		/* calculate IP header checksum */
20104 		cksum += ipha->ipha_ident;
20105 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20106 		cksum += ipha->ipha_fragment_offset_and_flags;
20107 
20108 		/* IP options present */
20109 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20110 		if (hlen)
20111 			goto checksumoptions;
20112 
20113 		/* calculate hdr checksum */
20114 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20115 		cksum = ~(cksum + (cksum >> 16));
20116 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20117 	}
20118 	if (ipsec_len != 0) {
20119 		/*
20120 		 * We will do the rest of the processing after
20121 		 * we come back from IPSEC in ip_wput_ipsec_out().
20122 		 */
20123 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20124 
20125 		io = (ipsec_out_t *)first_mp->b_rptr;
20126 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20127 				ill_phyint->phyint_ifindex;
20128 
20129 		ipsec_out_process(q, first_mp, ire, ill_index);
20130 		ire_refrele(ire);
20131 		if (conn_outgoing_ill != NULL)
20132 			ill_refrele(conn_outgoing_ill);
20133 		return;
20134 	}
20135 
20136 	/*
20137 	 * In most cases, the emission loop below is entered only
20138 	 * once. Only in the case where the ire holds the
20139 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20140 	 * flagged ires in the bucket, and send the packet
20141 	 * through all crossed RTF_MULTIRT routes.
20142 	 */
20143 	if (ire->ire_flags & RTF_MULTIRT) {
20144 		multirt_send = B_TRUE;
20145 	}
20146 	do {
20147 		if (multirt_send) {
20148 			irb_t *irb;
20149 			/*
20150 			 * We are in a multiple send case, need to get
20151 			 * the next ire and make a duplicate of the packet.
20152 			 * ire1 holds here the next ire to process in the
20153 			 * bucket. If multirouting is expected,
20154 			 * any non-RTF_MULTIRT ire that has the
20155 			 * right destination address is ignored.
20156 			 */
20157 			irb = ire->ire_bucket;
20158 			ASSERT(irb != NULL);
20159 
20160 			IRB_REFHOLD(irb);
20161 			for (ire1 = ire->ire_next;
20162 			    ire1 != NULL;
20163 			    ire1 = ire1->ire_next) {
20164 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20165 					continue;
20166 				if (ire1->ire_addr != ire->ire_addr)
20167 					continue;
20168 				if (ire1->ire_marks &
20169 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20170 					continue;
20171 
20172 				/* Got one */
20173 				IRE_REFHOLD(ire1);
20174 				break;
20175 			}
20176 			IRB_REFRELE(irb);
20177 
20178 			if (ire1 != NULL) {
20179 				next_mp = copyb(mp);
20180 				if ((next_mp == NULL) ||
20181 				    ((mp->b_cont != NULL) &&
20182 				    ((next_mp->b_cont =
20183 				    dupmsg(mp->b_cont)) == NULL))) {
20184 					freemsg(next_mp);
20185 					next_mp = NULL;
20186 					ire_refrele(ire1);
20187 					ire1 = NULL;
20188 				}
20189 			}
20190 
20191 			/* Last multiroute ire; don't loop anymore. */
20192 			if (ire1 == NULL) {
20193 				multirt_send = B_FALSE;
20194 			}
20195 		}
20196 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20197 		if (mp == NULL) {
20198 			BUMP_MIB(&ip_mib, ipOutDiscards);
20199 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20200 			    "during IPPF processing\n"));
20201 			ire_refrele(ire);
20202 			if (next_mp != NULL) {
20203 				freemsg(next_mp);
20204 				ire_refrele(ire1);
20205 			}
20206 			if (conn_outgoing_ill != NULL)
20207 				ill_refrele(conn_outgoing_ill);
20208 			return;
20209 		}
20210 		UPDATE_OB_PKT_COUNT(ire);
20211 		ire->ire_last_used_time = lbolt;
20212 
20213 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20214 		    "ip_wput_ire_end: q %p (%S)",
20215 		    q, "last copy out");
20216 		putnext(stq, mp);
20217 		IRE_REFRELE(ire);
20218 
20219 		if (multirt_send) {
20220 			ASSERT(ire1);
20221 			/*
20222 			 * Proceed with the next RTF_MULTIRT ire,
20223 			 * Also set up the send-to queue accordingly.
20224 			 */
20225 			ire = ire1;
20226 			ire1 = NULL;
20227 			stq = ire->ire_stq;
20228 			mp = next_mp;
20229 			next_mp = NULL;
20230 			ipha = (ipha_t *)mp->b_rptr;
20231 			ill_index = Q_TO_INDEX(stq);
20232 		}
20233 	} while (multirt_send);
20234 	if (conn_outgoing_ill != NULL)
20235 		ill_refrele(conn_outgoing_ill);
20236 	return;
20237 
20238 	/*
20239 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20240 	 */
20241 broadcast:
20242 	{
20243 		/*
20244 		 * Avoid broadcast storms by setting the ttl to 1
20245 		 * for broadcasts. This parameter can be set
20246 		 * via ndd, so make sure that for the SO_DONTROUTE
20247 		 * case that ipha_ttl is always set to 1.
20248 		 * In the event that we are replying to incoming
20249 		 * ICMP packets, conn could be NULL.
20250 		 */
20251 		if ((connp != NULL) && connp->conn_dontroute)
20252 			ipha->ipha_ttl = 1;
20253 		else
20254 			ipha->ipha_ttl = ip_broadcast_ttl;
20255 
20256 		/*
20257 		 * Note that we are not doing a IRB_REFHOLD here.
20258 		 * Actually we don't care if the list changes i.e
20259 		 * if somebody deletes an IRE from the list while
20260 		 * we drop the lock, the next time we come around
20261 		 * ire_next will be NULL and hence we won't send
20262 		 * out multiple copies which is fine.
20263 		 */
20264 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20265 		ire1 = ire->ire_next;
20266 		if (conn_outgoing_ill != NULL) {
20267 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20268 				ASSERT(ire1 == ire->ire_next);
20269 				if (ire1 != NULL && ire1->ire_addr == dst) {
20270 					ire_refrele(ire);
20271 					ire = ire1;
20272 					IRE_REFHOLD(ire);
20273 					ire1 = ire->ire_next;
20274 					continue;
20275 				}
20276 				rw_exit(&ire->ire_bucket->irb_lock);
20277 				/* Did not find a matching ill */
20278 				ip1dbg(("ip_wput_ire: broadcast with no "
20279 				    "matching IP_BOUND_IF ill %s\n",
20280 				    conn_outgoing_ill->ill_name));
20281 				freemsg(first_mp);
20282 				if (ire != NULL)
20283 					ire_refrele(ire);
20284 				ill_refrele(conn_outgoing_ill);
20285 				return;
20286 			}
20287 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20288 			/*
20289 			 * If the next IRE has the same address and is not one
20290 			 * of the two copies that we need to send, try to see
20291 			 * whether this copy should be sent at all. This
20292 			 * assumes that we insert loopbacks first and then
20293 			 * non-loopbacks. This is acheived by inserting the
20294 			 * loopback always before non-loopback.
20295 			 * This is used to send a single copy of a broadcast
20296 			 * packet out all physical interfaces that have an
20297 			 * matching IRE_BROADCAST while also looping
20298 			 * back one copy (to ip_wput_local) for each
20299 			 * matching physical interface. However, we avoid
20300 			 * sending packets out different logical that match by
20301 			 * having ipif_up/ipif_down supress duplicate
20302 			 * IRE_BROADCASTS.
20303 			 *
20304 			 * This feature is currently used to get broadcasts
20305 			 * sent to multiple interfaces, when the broadcast
20306 			 * address being used applies to multiple interfaces.
20307 			 * For example, a whole net broadcast will be
20308 			 * replicated on every connected subnet of
20309 			 * the target net.
20310 			 *
20311 			 * Each zone has its own set of IRE_BROADCASTs, so that
20312 			 * we're able to distribute inbound packets to multiple
20313 			 * zones who share a broadcast address. We avoid looping
20314 			 * back outbound packets in different zones but on the
20315 			 * same ill, as the application would see duplicates.
20316 			 *
20317 			 * If the interfaces are part of the same group,
20318 			 * we would want to send only one copy out for
20319 			 * whole group.
20320 			 *
20321 			 * This logic assumes that ire_add_v4() groups the
20322 			 * IRE_BROADCAST entries so that those with the same
20323 			 * ire_addr and ill_group are kept together.
20324 			 */
20325 			ire_ill = ire->ire_ipif->ipif_ill;
20326 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20327 				if (ire_ill->ill_group != NULL &&
20328 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20329 					/*
20330 					 * If the current zone only has an ire
20331 					 * broadcast for this address marked
20332 					 * NORECV, the ire we want is ahead in
20333 					 * the bucket, so we look it up
20334 					 * deliberately ignoring the zoneid.
20335 					 */
20336 					for (ire1 = ire->ire_bucket->irb_ire;
20337 					    ire1 != NULL;
20338 					    ire1 = ire1->ire_next) {
20339 						ire1_ill =
20340 						    ire1->ire_ipif->ipif_ill;
20341 						if (ire1->ire_addr != dst)
20342 							continue;
20343 						/* skip over the current ire */
20344 						if (ire1 == ire)
20345 							continue;
20346 						/* skip over deleted ires */
20347 						if (ire1->ire_marks &
20348 						    IRE_MARK_CONDEMNED)
20349 							continue;
20350 						/*
20351 						 * non-loopback ire in our
20352 						 * group: use it for the next
20353 						 * pass in the loop
20354 						 */
20355 						if (ire1->ire_stq != NULL &&
20356 						    ire1_ill->ill_group ==
20357 						    ire_ill->ill_group)
20358 							break;
20359 					}
20360 				}
20361 			} else {
20362 				while (ire1 != NULL && ire1->ire_addr == dst) {
20363 					ire1_ill = ire1->ire_ipif->ipif_ill;
20364 					/*
20365 					 * We can have two broadcast ires on the
20366 					 * same ill in different zones; here
20367 					 * we'll send a copy of the packet on
20368 					 * each ill and the fanout code will
20369 					 * call conn_wantpacket() to check that
20370 					 * the zone has the broadcast address
20371 					 * configured on the ill. If the two
20372 					 * ires are in the same group we only
20373 					 * send one copy up.
20374 					 */
20375 					if (ire1_ill != ire_ill &&
20376 					    (ire1_ill->ill_group == NULL ||
20377 					    ire_ill->ill_group == NULL ||
20378 					    ire1_ill->ill_group !=
20379 					    ire_ill->ill_group)) {
20380 						break;
20381 					}
20382 					ire1 = ire1->ire_next;
20383 				}
20384 			}
20385 		}
20386 		ASSERT(multirt_send == B_FALSE);
20387 		if (ire1 != NULL && ire1->ire_addr == dst) {
20388 			if ((ire->ire_flags & RTF_MULTIRT) &&
20389 			    (ire1->ire_flags & RTF_MULTIRT)) {
20390 				/*
20391 				 * We are in the multirouting case.
20392 				 * The message must be sent at least
20393 				 * on both ires. These ires have been
20394 				 * inserted AFTER the standard ones
20395 				 * in ip_rt_add(). There are thus no
20396 				 * other ire entries for the destination
20397 				 * address in the rest of the bucket
20398 				 * that do not have the RTF_MULTIRT
20399 				 * flag. We don't process a copy
20400 				 * of the message here. This will be
20401 				 * done in the final sending loop.
20402 				 */
20403 				multirt_send = B_TRUE;
20404 			} else {
20405 				next_mp = ip_copymsg(first_mp);
20406 				if (next_mp != NULL)
20407 					IRE_REFHOLD(ire1);
20408 			}
20409 		}
20410 		rw_exit(&ire->ire_bucket->irb_lock);
20411 	}
20412 
20413 	if (stq) {
20414 		/*
20415 		 * A non-NULL send-to queue means this packet is going
20416 		 * out of this machine.
20417 		 */
20418 
20419 		BUMP_MIB(&ip_mib, ipOutRequests);
20420 		ttl_protocol = ((uint16_t *)ipha)[4];
20421 		/*
20422 		 * We accumulate the pseudo header checksum in cksum.
20423 		 * This is pretty hairy code, so watch close.  One
20424 		 * thing to keep in mind is that UDP and TCP have
20425 		 * stored their respective datagram lengths in their
20426 		 * checksum fields.  This lines things up real nice.
20427 		 */
20428 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20429 		    (src >> 16) + (src & 0xFFFF);
20430 		/*
20431 		 * We assume the udp checksum field contains the
20432 		 * length, so to compute the pseudo header checksum,
20433 		 * all we need is the protocol number and src/dst.
20434 		 */
20435 		/* Provide the checksums for UDP and TCP. */
20436 		if ((PROTO == IPPROTO_TCP) &&
20437 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20438 			/* hlen gets the number of uchar_ts in the IP header */
20439 			hlen = (V_HLEN & 0xF) << 2;
20440 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20441 			IP_STAT(ip_out_sw_cksum);
20442 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20443 			    LENGTH - hlen);
20444 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20445 			if (*up == 0)
20446 				*up = 0xFFFF;
20447 		} else if (PROTO == IPPROTO_SCTP &&
20448 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20449 			sctp_hdr_t	*sctph;
20450 
20451 			hlen = (V_HLEN & 0xF) << 2;
20452 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20453 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20454 			sctph->sh_chksum = 0;
20455 #ifdef	DEBUG
20456 			if (!skip_sctp_cksum)
20457 #endif
20458 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20459 		} else {
20460 			queue_t *dev_q = stq->q_next;
20461 
20462 			if ((dev_q->q_next || dev_q->q_first) &&
20463 			    !canput(dev_q)) {
20464 			    blocked:
20465 				ipha->ipha_ident = ip_hdr_included;
20466 				/*
20467 				 * If we don't have a conn to apply
20468 				 * backpressure, free the message.
20469 				 * In the ire_send path, we don't know
20470 				 * the position to requeue the packet. Rather
20471 				 * than reorder packets, we just drop this
20472 				 * packet.
20473 				 */
20474 				if (ip_output_queue && connp != NULL &&
20475 				    caller != IRE_SEND) {
20476 					if (caller == IP_WSRV) {
20477 						connp->conn_did_putbq = 1;
20478 						(void) putbq(connp->conn_wq,
20479 						    first_mp);
20480 						conn_drain_insert(connp);
20481 						/*
20482 						 * This is the service thread,
20483 						 * and the queue is already
20484 						 * noenabled. The check for
20485 						 * canput and the putbq is not
20486 						 * atomic. So we need to check
20487 						 * again.
20488 						 */
20489 						if (canput(stq->q_next))
20490 							connp->conn_did_putbq
20491 							    = 0;
20492 						IP_STAT(ip_conn_flputbq);
20493 					} else {
20494 						/*
20495 						 * We are not the service proc.
20496 						 * ip_wsrv will be scheduled or
20497 						 * is already running.
20498 						 */
20499 						(void) putq(connp->conn_wq,
20500 						    first_mp);
20501 					}
20502 				} else {
20503 					BUMP_MIB(&ip_mib, ipOutDiscards);
20504 					freemsg(first_mp);
20505 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20506 					    "ip_wput_ire_end: q %p (%S)",
20507 					    q, "discard");
20508 				}
20509 				ire_refrele(ire);
20510 				if (next_mp) {
20511 					ire_refrele(ire1);
20512 					freemsg(next_mp);
20513 				}
20514 				if (conn_outgoing_ill != NULL)
20515 					ill_refrele(conn_outgoing_ill);
20516 				return;
20517 			}
20518 			if ((PROTO == IPPROTO_UDP) &&
20519 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20520 				/*
20521 				 * hlen gets the number of uchar_ts in the
20522 				 * IP header
20523 				 */
20524 				hlen = (V_HLEN & 0xF) << 2;
20525 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20526 				max_frag = ire->ire_max_frag;
20527 				if (*up != 0) {
20528 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
20529 					    up, PROTO, hlen, LENGTH, max_frag,
20530 					    ipsec_len, cksum);
20531 					/* Software checksum? */
20532 					if (DB_CKSUMFLAGS(mp) == 0) {
20533 						IP_STAT(ip_out_sw_cksum);
20534 						IP_STAT_UPDATE(
20535 						    ip_udp_out_sw_cksum_bytes,
20536 						    LENGTH - hlen);
20537 					}
20538 				}
20539 			}
20540 		}
20541 		/*
20542 		 * Need to do this even when fragmenting. The local
20543 		 * loopback can be done without computing checksums
20544 		 * but forwarding out other interface must be done
20545 		 * after the IP checksum (and ULP checksums) have been
20546 		 * computed.
20547 		 *
20548 		 * NOTE : multicast_forward is set only if this packet
20549 		 * originated from ip_wput. For packets originating from
20550 		 * ip_wput_multicast, it is not set.
20551 		 */
20552 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20553 		    multi_loopback:
20554 			ip2dbg(("ip_wput: multicast, loop %d\n",
20555 			    conn_multicast_loop));
20556 
20557 			/*  Forget header checksum offload */
20558 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
20559 
20560 			/*
20561 			 * Local loopback of multicasts?  Check the
20562 			 * ill.
20563 			 *
20564 			 * Note that the loopback function will not come
20565 			 * in through ip_rput - it will only do the
20566 			 * client fanout thus we need to do an mforward
20567 			 * as well.  The is different from the BSD
20568 			 * logic.
20569 			 */
20570 			if (ill != NULL) {
20571 				ilm_t	*ilm;
20572 
20573 				ILM_WALKER_HOLD(ill);
20574 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20575 				    ALL_ZONES);
20576 				ILM_WALKER_RELE(ill);
20577 				if (ilm != NULL) {
20578 					/*
20579 					 * Pass along the virtual output q.
20580 					 * ip_wput_local() will distribute the
20581 					 * packet to all the matching zones,
20582 					 * except the sending zone when
20583 					 * IP_MULTICAST_LOOP is false.
20584 					 */
20585 					ip_multicast_loopback(q, ill, first_mp,
20586 					    conn_multicast_loop ? 0 :
20587 					    IP_FF_NO_MCAST_LOOP, zoneid);
20588 				}
20589 			}
20590 			if (ipha->ipha_ttl == 0) {
20591 				/*
20592 				 * 0 => only to this host i.e. we are
20593 				 * done. We are also done if this was the
20594 				 * loopback interface since it is sufficient
20595 				 * to loopback one copy of a multicast packet.
20596 				 */
20597 				freemsg(first_mp);
20598 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20599 				    "ip_wput_ire_end: q %p (%S)",
20600 				    q, "loopback");
20601 				ire_refrele(ire);
20602 				if (conn_outgoing_ill != NULL)
20603 					ill_refrele(conn_outgoing_ill);
20604 				return;
20605 			}
20606 			/*
20607 			 * ILLF_MULTICAST is checked in ip_newroute
20608 			 * i.e. we don't need to check it here since
20609 			 * all IRE_CACHEs come from ip_newroute.
20610 			 * For multicast traffic, SO_DONTROUTE is interpreted
20611 			 * to mean only send the packet out the interface
20612 			 * (optionally specified with IP_MULTICAST_IF)
20613 			 * and do not forward it out additional interfaces.
20614 			 * RSVP and the rsvp daemon is an example of a
20615 			 * protocol and user level process that
20616 			 * handles it's own routing. Hence, it uses the
20617 			 * SO_DONTROUTE option to accomplish this.
20618 			 */
20619 
20620 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20621 				/* Unconditionally redo the checksum */
20622 				ipha->ipha_hdr_checksum = 0;
20623 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20624 
20625 				/*
20626 				 * If this needs to go out secure, we need
20627 				 * to wait till we finish the IPSEC
20628 				 * processing.
20629 				 */
20630 				if (ipsec_len == 0 &&
20631 				    ip_mforward(ill, ipha, mp)) {
20632 					freemsg(first_mp);
20633 					ip1dbg(("ip_wput: mforward failed\n"));
20634 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20635 					    "ip_wput_ire_end: q %p (%S)",
20636 					    q, "mforward failed");
20637 					ire_refrele(ire);
20638 					if (conn_outgoing_ill != NULL)
20639 						ill_refrele(conn_outgoing_ill);
20640 					return;
20641 				}
20642 			}
20643 		}
20644 		max_frag = ire->ire_max_frag;
20645 		cksum += ttl_protocol;
20646 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
20647 			/* No fragmentation required for this one. */
20648 			/*
20649 			 * Don't use frag_flag if packet is pre-built or source
20650 			 * routed or if multicast (since multicast packets do
20651 			 * not solicit ICMP "packet too big" messages).
20652 			 */
20653 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20654 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20655 			    !ip_source_route_included(ipha)) &&
20656 			    !CLASSD(ipha->ipha_dst))
20657 				ipha->ipha_fragment_offset_and_flags |=
20658 				    htons(ire->ire_frag_flag);
20659 
20660 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20661 				/* Complete the IP header checksum. */
20662 				cksum += ipha->ipha_ident;
20663 				cksum += (v_hlen_tos_len >> 16)+
20664 				    (v_hlen_tos_len & 0xFFFF);
20665 				cksum += ipha->ipha_fragment_offset_and_flags;
20666 				hlen = (V_HLEN & 0xF) -
20667 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20668 				if (hlen) {
20669 				    checksumoptions:
20670 					/*
20671 					 * Account for the IP Options in the IP
20672 					 * header checksum.
20673 					 */
20674 					up = (uint16_t *)(rptr+
20675 					    IP_SIMPLE_HDR_LENGTH);
20676 					do {
20677 						cksum += up[0];
20678 						cksum += up[1];
20679 						up += 2;
20680 					} while (--hlen);
20681 				}
20682 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20683 				cksum = ~(cksum + (cksum >> 16));
20684 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
20685 			}
20686 			if (ipsec_len != 0) {
20687 				ipsec_out_process(q, first_mp, ire, ill_index);
20688 				if (!next_mp) {
20689 					ire_refrele(ire);
20690 					if (conn_outgoing_ill != NULL)
20691 						ill_refrele(conn_outgoing_ill);
20692 					return;
20693 				}
20694 				goto next;
20695 			}
20696 
20697 			/*
20698 			 * multirt_send has already been handled
20699 			 * for broadcast, but not yet for multicast
20700 			 * or IP options.
20701 			 */
20702 			if (next_mp == NULL) {
20703 				if (ire->ire_flags & RTF_MULTIRT) {
20704 					multirt_send = B_TRUE;
20705 				}
20706 			}
20707 
20708 			/*
20709 			 * In most cases, the emission loop below is
20710 			 * entered only once. Only in the case where
20711 			 * the ire holds the RTF_MULTIRT flag, do we loop
20712 			 * to process all RTF_MULTIRT ires in the bucket,
20713 			 * and send the packet through all crossed
20714 			 * RTF_MULTIRT routes.
20715 			 */
20716 			do {
20717 				if (multirt_send) {
20718 					irb_t *irb;
20719 
20720 					irb = ire->ire_bucket;
20721 					ASSERT(irb != NULL);
20722 					/*
20723 					 * We are in a multiple send case,
20724 					 * need to get the next IRE and make
20725 					 * a duplicate of the packet.
20726 					 */
20727 					IRB_REFHOLD(irb);
20728 					for (ire1 = ire->ire_next;
20729 					    ire1 != NULL;
20730 					    ire1 = ire1->ire_next) {
20731 						if (!(ire1->ire_flags &
20732 						    RTF_MULTIRT))
20733 							continue;
20734 						if (ire1->ire_addr !=
20735 						    ire->ire_addr)
20736 							continue;
20737 						if (ire1->ire_marks &
20738 						    (IRE_MARK_CONDEMNED|
20739 							IRE_MARK_HIDDEN))
20740 							continue;
20741 
20742 						/* Got one */
20743 						IRE_REFHOLD(ire1);
20744 						break;
20745 					}
20746 					IRB_REFRELE(irb);
20747 
20748 					if (ire1 != NULL) {
20749 						next_mp = copyb(mp);
20750 						if ((next_mp == NULL) ||
20751 						    ((mp->b_cont != NULL) &&
20752 						    ((next_mp->b_cont =
20753 						    dupmsg(mp->b_cont))
20754 						    == NULL))) {
20755 							freemsg(next_mp);
20756 							next_mp = NULL;
20757 							ire_refrele(ire1);
20758 							ire1 = NULL;
20759 						}
20760 					}
20761 
20762 					/*
20763 					 * Last multiroute ire; don't loop
20764 					 * anymore. The emission is over
20765 					 * and next_mp is NULL.
20766 					 */
20767 					if (ire1 == NULL) {
20768 						multirt_send = B_FALSE;
20769 					}
20770 				}
20771 
20772 			noprepend:
20773 				ASSERT(ipsec_len == 0);
20774 				mp1 = ip_wput_attach_llhdr(mp, ire,
20775 				    IPP_LOCAL_OUT, ill_index);
20776 				if (mp1 == NULL) {
20777 					BUMP_MIB(&ip_mib, ipOutDiscards);
20778 					if (next_mp) {
20779 						freemsg(next_mp);
20780 						ire_refrele(ire1);
20781 					}
20782 					ire_refrele(ire);
20783 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20784 					    "ip_wput_ire_end: q %p (%S)",
20785 					    q, "discard MDATA");
20786 					if (conn_outgoing_ill != NULL)
20787 						ill_refrele(conn_outgoing_ill);
20788 					return;
20789 				}
20790 				UPDATE_OB_PKT_COUNT(ire);
20791 				ire->ire_last_used_time = lbolt;
20792 
20793 				if (multirt_send) {
20794 					/*
20795 					 * We are in a multiple send case,
20796 					 * need to re-enter the sending loop
20797 					 * using the next ire.
20798 					 */
20799 					putnext(stq, mp1);
20800 					ire_refrele(ire);
20801 					ire = ire1;
20802 					stq = ire->ire_stq;
20803 					mp = next_mp;
20804 					next_mp = NULL;
20805 					ipha = (ipha_t *)mp->b_rptr;
20806 					ill_index = Q_TO_INDEX(stq);
20807 				}
20808 			} while (multirt_send);
20809 
20810 			if (!next_mp) {
20811 				/*
20812 				 * Last copy going out (the ultra-common
20813 				 * case).  Note that we intentionally replicate
20814 				 * the putnext rather than calling it before
20815 				 * the next_mp check in hopes of a little
20816 				 * tail-call action out of the compiler.
20817 				 */
20818 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20819 				    "ip_wput_ire_end: q %p (%S)",
20820 				    q, "last copy out(1)");
20821 				putnext(stq, mp1);
20822 				ire_refrele(ire);
20823 				if (conn_outgoing_ill != NULL)
20824 					ill_refrele(conn_outgoing_ill);
20825 				return;
20826 			}
20827 			/* More copies going out below. */
20828 			putnext(stq, mp1);
20829 		} else {
20830 			int offset;
20831 		    fragmentit:
20832 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20833 			/*
20834 			 * If this would generate a icmp_frag_needed message,
20835 			 * we need to handle it before we do the IPSEC
20836 			 * processing. Otherwise, we need to strip the IPSEC
20837 			 * headers before we send up the message to the ULPs
20838 			 * which becomes messy and difficult.
20839 			 */
20840 			if (ipsec_len != 0) {
20841 				if ((max_frag < (unsigned int)(LENGTH +
20842 				    ipsec_len)) && (offset & IPH_DF)) {
20843 
20844 					BUMP_MIB(&ip_mib, ipFragFails);
20845 					ipha->ipha_hdr_checksum = 0;
20846 					ipha->ipha_hdr_checksum =
20847 					    (uint16_t)ip_csum_hdr(ipha);
20848 					icmp_frag_needed(ire->ire_stq, first_mp,
20849 					    max_frag);
20850 					if (!next_mp) {
20851 						ire_refrele(ire);
20852 						if (conn_outgoing_ill != NULL) {
20853 							ill_refrele(
20854 							    conn_outgoing_ill);
20855 						}
20856 						return;
20857 					}
20858 				} else {
20859 					/*
20860 					 * This won't cause a icmp_frag_needed
20861 					 * message. to be gnerated. Send it on
20862 					 * the wire. Note that this could still
20863 					 * cause fragmentation and all we
20864 					 * do is the generation of the message
20865 					 * to the ULP if needed before IPSEC.
20866 					 */
20867 					if (!next_mp) {
20868 						ipsec_out_process(q, first_mp,
20869 						    ire, ill_index);
20870 						TRACE_2(TR_FAC_IP,
20871 						    TR_IP_WPUT_IRE_END,
20872 						    "ip_wput_ire_end: q %p "
20873 						    "(%S)", q,
20874 						    "last ipsec_out_process");
20875 						ire_refrele(ire);
20876 						if (conn_outgoing_ill != NULL) {
20877 							ill_refrele(
20878 							    conn_outgoing_ill);
20879 						}
20880 						return;
20881 					}
20882 					ipsec_out_process(q, first_mp,
20883 					    ire, ill_index);
20884 				}
20885 			} else {
20886 				/* Initiate IPPF processing */
20887 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20888 					ip_process(IPP_LOCAL_OUT, &mp,
20889 					    ill_index);
20890 					if (mp == NULL) {
20891 						BUMP_MIB(&ip_mib,
20892 						    ipOutDiscards);
20893 						if (next_mp != NULL) {
20894 							freemsg(next_mp);
20895 							ire_refrele(ire1);
20896 						}
20897 						ire_refrele(ire);
20898 						TRACE_2(TR_FAC_IP,
20899 						    TR_IP_WPUT_IRE_END,
20900 						    "ip_wput_ire: q %p (%S)",
20901 						    q, "discard MDATA");
20902 						if (conn_outgoing_ill != NULL) {
20903 							ill_refrele(
20904 							    conn_outgoing_ill);
20905 						}
20906 						return;
20907 					}
20908 				}
20909 				if (!next_mp) {
20910 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20911 					    "ip_wput_ire_end: q %p (%S)",
20912 					    q, "last fragmentation");
20913 					ip_wput_ire_fragmentit(mp, ire);
20914 					ire_refrele(ire);
20915 					if (conn_outgoing_ill != NULL)
20916 						ill_refrele(conn_outgoing_ill);
20917 					return;
20918 				}
20919 				ip_wput_ire_fragmentit(mp, ire);
20920 			}
20921 		}
20922 	} else {
20923 	    nullstq:
20924 		/* A NULL stq means the destination address is local. */
20925 		UPDATE_OB_PKT_COUNT(ire);
20926 		ire->ire_last_used_time = lbolt;
20927 		ASSERT(ire->ire_ipif != NULL);
20928 		if (!next_mp) {
20929 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20930 			    "ip_wput_ire_end: q %p (%S)",
20931 			    q, "local address");
20932 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20933 			    first_mp, ire, 0, ire->ire_zoneid);
20934 			ire_refrele(ire);
20935 			if (conn_outgoing_ill != NULL)
20936 				ill_refrele(conn_outgoing_ill);
20937 			return;
20938 		}
20939 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20940 		    ire, 0, ire->ire_zoneid);
20941 	}
20942 next:
20943 	/*
20944 	 * More copies going out to additional interfaces.
20945 	 * ire1 has already been held. We don't need the
20946 	 * "ire" anymore.
20947 	 */
20948 	ire_refrele(ire);
20949 	ire = ire1;
20950 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20951 	mp = next_mp;
20952 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20953 	ill = ire_to_ill(ire);
20954 	first_mp = mp;
20955 	if (ipsec_len != 0) {
20956 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20957 		mp = mp->b_cont;
20958 	}
20959 	dst = ire->ire_addr;
20960 	ipha = (ipha_t *)mp->b_rptr;
20961 	/*
20962 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20963 	 * Restore ipha_ident "no checksum" flag.
20964 	 */
20965 	src = orig_src;
20966 	ipha->ipha_ident = ip_hdr_included;
20967 	goto another;
20968 
20969 #undef	rptr
20970 #undef	Q_TO_INDEX
20971 }
20972 
20973 /*
20974  * Routine to allocate a message that is used to notify the ULP about MDT.
20975  * The caller may provide a pointer to the link-layer MDT capabilities,
20976  * or NULL if MDT is to be disabled on the stream.
20977  */
20978 mblk_t *
20979 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20980 {
20981 	mblk_t *mp;
20982 	ip_mdt_info_t *mdti;
20983 	ill_mdt_capab_t *idst;
20984 
20985 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20986 		DB_TYPE(mp) = M_CTL;
20987 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20988 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20989 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20990 		idst = &(mdti->mdt_capab);
20991 
20992 		/*
20993 		 * If the caller provides us with the capability, copy
20994 		 * it over into our notification message; otherwise
20995 		 * we zero out the capability portion.
20996 		 */
20997 		if (isrc != NULL)
20998 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20999 		else
21000 			bzero((caddr_t)idst, sizeof (*idst));
21001 	}
21002 	return (mp);
21003 }
21004 
21005 /*
21006  * Routine which determines whether MDT can be enabled on the destination
21007  * IRE and IPC combination, and if so, allocates and returns the MDT
21008  * notification mblk that may be used by ULP.  We also check if we need to
21009  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21010  * MDT usage in the past have been lifted.  This gets called during IP
21011  * and ULP binding.
21012  */
21013 mblk_t *
21014 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21015     ill_mdt_capab_t *mdt_cap)
21016 {
21017 	mblk_t *mp;
21018 	boolean_t rc = B_FALSE;
21019 
21020 	ASSERT(dst_ire != NULL);
21021 	ASSERT(connp != NULL);
21022 	ASSERT(mdt_cap != NULL);
21023 
21024 	/*
21025 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21026 	 * Multidata, which is handled in tcp_multisend().  This
21027 	 * is the reason why we do all these checks here, to ensure
21028 	 * that we don't enable Multidata for the cases which we
21029 	 * can't handle at the moment.
21030 	 */
21031 	do {
21032 		/* Only do TCP at the moment */
21033 		if (connp->conn_ulp != IPPROTO_TCP)
21034 			break;
21035 
21036 		/*
21037 		 * IPSEC outbound policy present?  Note that we get here
21038 		 * after calling ipsec_conn_cache_policy() where the global
21039 		 * policy checking is performed.  conn_latch will be
21040 		 * non-NULL as long as there's a policy defined,
21041 		 * i.e. conn_out_enforce_policy may be NULL in such case
21042 		 * when the connection is non-secure, and hence we check
21043 		 * further if the latch refers to an outbound policy.
21044 		 */
21045 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21046 			break;
21047 
21048 		/* CGTP (multiroute) is enabled? */
21049 		if (dst_ire->ire_flags & RTF_MULTIRT)
21050 			break;
21051 
21052 		/* Outbound IPQoS enabled? */
21053 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21054 			/*
21055 			 * In this case, we disable MDT for this and all
21056 			 * future connections going over the interface.
21057 			 */
21058 			mdt_cap->ill_mdt_on = 0;
21059 			break;
21060 		}
21061 
21062 		/* socket option(s) present? */
21063 		if (!CONN_IS_MD_FASTPATH(connp))
21064 			break;
21065 
21066 		rc = B_TRUE;
21067 	/* CONSTCOND */
21068 	} while (0);
21069 
21070 	/* Remember the result */
21071 	connp->conn_mdt_ok = rc;
21072 
21073 	if (!rc)
21074 		return (NULL);
21075 	else if (!mdt_cap->ill_mdt_on) {
21076 		/*
21077 		 * If MDT has been previously turned off in the past, and we
21078 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21079 		 * then enable it for this interface.
21080 		 */
21081 		mdt_cap->ill_mdt_on = 1;
21082 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21083 		    "interface %s\n", ill_name));
21084 	}
21085 
21086 	/* Allocate the MDT info mblk */
21087 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21088 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21089 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21090 		return (NULL);
21091 	}
21092 	return (mp);
21093 }
21094 
21095 /*
21096  * Create destination address attribute, and fill it with the physical
21097  * destination address and SAP taken from the template DL_UNITDATA_REQ
21098  * message block.
21099  */
21100 boolean_t
21101 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21102 {
21103 	dl_unitdata_req_t *dlurp;
21104 	pattr_t *pa;
21105 	pattrinfo_t pa_info;
21106 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21107 	uint_t das_len, das_off;
21108 
21109 	ASSERT(dlmp != NULL);
21110 
21111 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21112 	das_len = dlurp->dl_dest_addr_length;
21113 	das_off = dlurp->dl_dest_addr_offset;
21114 
21115 	pa_info.type = PATTR_DSTADDRSAP;
21116 	pa_info.len = sizeof (**das) + das_len - 1;
21117 
21118 	/* create and associate the attribute */
21119 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21120 	if (pa != NULL) {
21121 		ASSERT(*das != NULL);
21122 		(*das)->addr_is_group = 0;
21123 		(*das)->addr_len = (uint8_t)das_len;
21124 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21125 	}
21126 
21127 	return (pa != NULL);
21128 }
21129 
21130 /*
21131  * Create hardware checksum attribute and fill it with the values passed.
21132  */
21133 boolean_t
21134 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21135     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21136 {
21137 	pattr_t *pa;
21138 	pattrinfo_t pa_info;
21139 
21140 	ASSERT(mmd != NULL);
21141 
21142 	pa_info.type = PATTR_HCKSUM;
21143 	pa_info.len = sizeof (pattr_hcksum_t);
21144 
21145 	/* create and associate the attribute */
21146 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21147 	if (pa != NULL) {
21148 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21149 
21150 		hck->hcksum_start_offset = start_offset;
21151 		hck->hcksum_stuff_offset = stuff_offset;
21152 		hck->hcksum_end_offset = end_offset;
21153 		hck->hcksum_flags = flags;
21154 	}
21155 	return (pa != NULL);
21156 }
21157 
21158 /*
21159  * Create zerocopy attribute and fill it with the specified flags
21160  */
21161 boolean_t
21162 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21163 {
21164 	pattr_t *pa;
21165 	pattrinfo_t pa_info;
21166 
21167 	ASSERT(mmd != NULL);
21168 	pa_info.type = PATTR_ZCOPY;
21169 	pa_info.len = sizeof (pattr_zcopy_t);
21170 
21171 	/* create and associate the attribute */
21172 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21173 	if (pa != NULL) {
21174 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21175 
21176 		zcopy->zcopy_flags = flags;
21177 	}
21178 	return (pa != NULL);
21179 }
21180 
21181 /*
21182  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21183  * block chain. We could rewrite to handle arbitrary message block chains but
21184  * that would make the code complicated and slow. Right now there three
21185  * restrictions:
21186  *
21187  *   1. The first message block must contain the complete IP header and
21188  *	at least 1 byte of payload data.
21189  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
21190  *	so that we can use a single Multidata message.
21191  *   3. No frag must be distributed over two or more message blocks so
21192  *	that we don't need more than two packet descriptors per frag.
21193  *
21194  * The above restrictions allow us to support userland applications (which
21195  * will send down a single message block) and NFS over UDP (which will
21196  * send down a chain of at most three message blocks).
21197  *
21198  * We also don't use MDT for payloads with less than or equal to
21199  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
21200  */
21201 boolean_t
21202 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
21203 {
21204 	int	blocks;
21205 	ssize_t	total, missing, size;
21206 
21207 	ASSERT(mp != NULL);
21208 	ASSERT(hdr_len > 0);
21209 
21210 	size = MBLKL(mp) - hdr_len;
21211 	if (size <= 0)
21212 		return (B_FALSE);
21213 
21214 	/* The first mblk contains the header and some payload. */
21215 	blocks = 1;
21216 	total = size;
21217 	size %= len;
21218 	missing = (size == 0) ? 0 : (len - size);
21219 	mp = mp->b_cont;
21220 
21221 	while (mp != NULL) {
21222 		/*
21223 		 * Give up if we encounter a zero length message block.
21224 		 * In practice, this should rarely happen and therefore
21225 		 * not worth the trouble of freeing and re-linking the
21226 		 * mblk from the chain to handle such case.
21227 		 */
21228 		if ((size = MBLKL(mp)) == 0)
21229 			return (B_FALSE);
21230 
21231 		/* Too many payload buffers for a single Multidata message? */
21232 		if (++blocks > MULTIDATA_MAX_PBUFS)
21233 			return (B_FALSE);
21234 
21235 		total += size;
21236 		/* Is a frag distributed over two or more message blocks? */
21237 		if (missing > size)
21238 			return (B_FALSE);
21239 		size -= missing;
21240 
21241 		size %= len;
21242 		missing = (size == 0) ? 0 : (len - size);
21243 
21244 		mp = mp->b_cont;
21245 	}
21246 
21247 	return (total > ip_wput_frag_mdt_min);
21248 }
21249 
21250 /*
21251  * Outbound IPv4 fragmentation routine using MDT.
21252  */
21253 static void
21254 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
21255     uint32_t frag_flag, int offset)
21256 {
21257 	ipha_t		*ipha_orig;
21258 	int		i1, ip_data_end;
21259 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
21260 	mblk_t		*hdr_mp, *md_mp = NULL;
21261 	unsigned char	*hdr_ptr, *pld_ptr;
21262 	multidata_t	*mmd;
21263 	ip_pdescinfo_t	pdi;
21264 
21265 	ASSERT(DB_TYPE(mp) == M_DATA);
21266 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
21267 
21268 	ipha_orig = (ipha_t *)mp->b_rptr;
21269 	mp->b_rptr += sizeof (ipha_t);
21270 
21271 	/* Calculate how many packets we will send out */
21272 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
21273 	pkts = (i1 + len - 1) / len;
21274 	ASSERT(pkts > 1);
21275 
21276 	/* Allocate a message block which will hold all the IP Headers. */
21277 	wroff = ip_wroff_extra;
21278 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
21279 
21280 	i1 = pkts * hdr_chunk_len;
21281 	/*
21282 	 * Create the header buffer, Multidata and destination address
21283 	 * and SAP attribute that should be associated with it.
21284 	 */
21285 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
21286 	    ((hdr_mp->b_wptr += i1),
21287 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
21288 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
21289 		freemsg(mp);
21290 		if (md_mp == NULL) {
21291 			freemsg(hdr_mp);
21292 		} else {
21293 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
21294 			freemsg(md_mp);
21295 		}
21296 		IP_STAT(ip_frag_mdt_allocfail);
21297 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
21298 		return;
21299 	}
21300 	IP_STAT(ip_frag_mdt_allocd);
21301 
21302 	/*
21303 	 * Add a payload buffer to the Multidata; this operation must not
21304 	 * fail, or otherwise our logic in this routine is broken.  There
21305 	 * is no memory allocation done by the routine, so any returned
21306 	 * failure simply tells us that we've done something wrong.
21307 	 *
21308 	 * A failure tells us that either we're adding the same payload
21309 	 * buffer more than once, or we're trying to add more buffers than
21310 	 * allowed.  None of the above cases should happen, and we panic
21311 	 * because either there's horrible heap corruption, and/or
21312 	 * programming mistake.
21313 	 */
21314 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21315 		goto pbuf_panic;
21316 
21317 	hdr_ptr = hdr_mp->b_rptr;
21318 	pld_ptr = mp->b_rptr;
21319 
21320 	/* Establish the ending byte offset, based on the starting offset. */
21321 	offset <<= 3;
21322 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
21323 	    IP_SIMPLE_HDR_LENGTH;
21324 
21325 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
21326 
21327 	while (pld_ptr < mp->b_wptr) {
21328 		ipha_t		*ipha;
21329 		uint16_t	offset_and_flags;
21330 		uint16_t	ip_len;
21331 		int		error;
21332 
21333 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
21334 		ipha = (ipha_t *)(hdr_ptr + wroff);
21335 		ASSERT(OK_32PTR(ipha));
21336 		*ipha = *ipha_orig;
21337 
21338 		if (ip_data_end - offset > len) {
21339 			offset_and_flags = IPH_MF;
21340 		} else {
21341 			/*
21342 			 * Last frag. Set len to the length of this last piece.
21343 			 */
21344 			len = ip_data_end - offset;
21345 			/* A frag of a frag might have IPH_MF non-zero */
21346 			offset_and_flags =
21347 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21348 			    IPH_MF;
21349 		}
21350 		offset_and_flags |= (uint16_t)(offset >> 3);
21351 		offset_and_flags |= (uint16_t)frag_flag;
21352 		/* Store the offset and flags in the IP header. */
21353 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21354 
21355 		/* Store the length in the IP header. */
21356 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
21357 		ipha->ipha_length = htons(ip_len);
21358 
21359 		/*
21360 		 * Set the IP header checksum.  Note that mp is just
21361 		 * the header, so this is easy to pass to ip_csum.
21362 		 */
21363 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21364 
21365 		/*
21366 		 * Record offset and size of header and data of the next packet
21367 		 * in the multidata message.
21368 		 */
21369 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
21370 		PDESC_PLD_INIT(&pdi);
21371 		i1 = MIN(mp->b_wptr - pld_ptr, len);
21372 		ASSERT(i1 > 0);
21373 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
21374 		if (i1 == len) {
21375 			pld_ptr += len;
21376 		} else {
21377 			i1 = len - i1;
21378 			mp = mp->b_cont;
21379 			ASSERT(mp != NULL);
21380 			ASSERT(MBLKL(mp) >= i1);
21381 			/*
21382 			 * Attach the next payload message block to the
21383 			 * multidata message.
21384 			 */
21385 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21386 				goto pbuf_panic;
21387 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
21388 			pld_ptr = mp->b_rptr + i1;
21389 		}
21390 
21391 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
21392 		    KM_NOSLEEP)) == NULL) {
21393 			/*
21394 			 * Any failure other than ENOMEM indicates that we
21395 			 * have passed in invalid pdesc info or parameters
21396 			 * to mmd_addpdesc, which must not happen.
21397 			 *
21398 			 * EINVAL is a result of failure on boundary checks
21399 			 * against the pdesc info contents.  It should not
21400 			 * happen, and we panic because either there's
21401 			 * horrible heap corruption, and/or programming
21402 			 * mistake.
21403 			 */
21404 			if (error != ENOMEM) {
21405 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
21406 				    "pdesc logic error detected for "
21407 				    "mmd %p pinfo %p (%d)\n",
21408 				    (void *)mmd, (void *)&pdi, error);
21409 				/* NOTREACHED */
21410 			}
21411 			IP_STAT(ip_frag_mdt_addpdescfail);
21412 			/* Free unattached payload message blocks as well */
21413 			md_mp->b_cont = mp->b_cont;
21414 			goto free_mmd;
21415 		}
21416 
21417 		/* Advance fragment offset. */
21418 		offset += len;
21419 
21420 		/* Advance to location for next header in the buffer. */
21421 		hdr_ptr += hdr_chunk_len;
21422 
21423 		/* Did we reach the next payload message block? */
21424 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
21425 			mp = mp->b_cont;
21426 			/*
21427 			 * Attach the next message block with payload
21428 			 * data to the multidata message.
21429 			 */
21430 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21431 				goto pbuf_panic;
21432 			pld_ptr = mp->b_rptr;
21433 		}
21434 	}
21435 
21436 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
21437 	ASSERT(mp->b_wptr == pld_ptr);
21438 
21439 	/* Update IP statistics */
21440 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
21441 	BUMP_MIB(&ip_mib, ipFragOKs);
21442 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
21443 
21444 	if (pkt_type == OB_PKT) {
21445 		ire->ire_ob_pkt_count += pkts;
21446 		if (ire->ire_ipif != NULL)
21447 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
21448 	} else {
21449 		/*
21450 		 * The type is IB_PKT in the forwarding path and in
21451 		 * the mobile IP case when the packet is being reverse-
21452 		 * tunneled to the home agent.
21453 		 */
21454 		ire->ire_ib_pkt_count += pkts;
21455 		ASSERT(!IRE_IS_LOCAL(ire));
21456 		if (ire->ire_type & IRE_BROADCAST)
21457 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
21458 		else
21459 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
21460 	}
21461 	ire->ire_last_used_time = lbolt;
21462 	/* Send it down */
21463 	putnext(ire->ire_stq, md_mp);
21464 	return;
21465 
21466 pbuf_panic:
21467 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
21468 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
21469 	    pbuf_idx);
21470 	/* NOTREACHED */
21471 }
21472 
21473 /*
21474  * Outbound IP fragmentation routine.
21475  *
21476  * NOTE : This routine does not ire_refrele the ire that is passed in
21477  * as the argument.
21478  */
21479 static void
21480 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21481     uint32_t frag_flag)
21482 {
21483 	int		i1;
21484 	mblk_t		*ll_hdr_mp;
21485 	int 		ll_hdr_len;
21486 	int		hdr_len;
21487 	mblk_t		*hdr_mp;
21488 	ipha_t		*ipha;
21489 	int		ip_data_end;
21490 	int		len;
21491 	mblk_t		*mp = mp_orig;
21492 	int		offset;
21493 	queue_t		*q;
21494 	uint32_t	v_hlen_tos_len;
21495 	mblk_t		*first_mp;
21496 	boolean_t	mctl_present;
21497 	ill_t		*ill;
21498 	mblk_t		*xmit_mp;
21499 	mblk_t		*carve_mp;
21500 	ire_t		*ire1 = NULL;
21501 	ire_t		*save_ire = NULL;
21502 	mblk_t  	*next_mp = NULL;
21503 	boolean_t	last_frag = B_FALSE;
21504 	boolean_t	multirt_send = B_FALSE;
21505 	ire_t		*first_ire = NULL;
21506 	irb_t		*irb = NULL;
21507 
21508 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21509 	    "ip_wput_frag_start:");
21510 
21511 	if (mp->b_datap->db_type == M_CTL) {
21512 		first_mp = mp;
21513 		mp_orig = mp = mp->b_cont;
21514 		mctl_present = B_TRUE;
21515 	} else {
21516 		first_mp = mp;
21517 		mctl_present = B_FALSE;
21518 	}
21519 
21520 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
21521 	ipha = (ipha_t *)mp->b_rptr;
21522 
21523 	/*
21524 	 * If the Don't Fragment flag is on, generate an ICMP destination
21525 	 * unreachable, fragmentation needed.
21526 	 */
21527 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21528 	if (offset & IPH_DF) {
21529 		BUMP_MIB(&ip_mib, ipFragFails);
21530 		/*
21531 		 * Need to compute hdr checksum if called from ip_wput_ire.
21532 		 * Note that ip_rput_forward verifies the checksum before
21533 		 * calling this routine so in that case this is a noop.
21534 		 */
21535 		ipha->ipha_hdr_checksum = 0;
21536 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21537 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21538 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21539 		    "ip_wput_frag_end:(%S)",
21540 		    "don't fragment");
21541 		return;
21542 	}
21543 	if (mctl_present)
21544 		freeb(first_mp);
21545 	/*
21546 	 * Establish the starting offset.  May not be zero if we are fragging
21547 	 * a fragment that is being forwarded.
21548 	 */
21549 	offset = offset & IPH_OFFSET;
21550 
21551 	/* TODO why is this test needed? */
21552 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21553 	if (((max_frag - LENGTH) & ~7) < 8) {
21554 		/* TODO: notify ulp somehow */
21555 		BUMP_MIB(&ip_mib, ipFragFails);
21556 		freemsg(mp);
21557 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21558 		    "ip_wput_frag_end:(%S)",
21559 		    "len < 8");
21560 		return;
21561 	}
21562 
21563 	hdr_len = (V_HLEN & 0xF) << 2;
21564 
21565 	ipha->ipha_hdr_checksum = 0;
21566 
21567 	/*
21568 	 * Establish the number of bytes maximum per frag, after putting
21569 	 * in the header.
21570 	 */
21571 	len = (max_frag - hdr_len) & ~7;
21572 
21573 	/* Check if we can use MDT to send out the frags. */
21574 	ASSERT(!IRE_IS_LOCAL(ire));
21575 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
21576 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
21577 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
21578 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
21579 		ASSERT(ill->ill_mdt_capab != NULL);
21580 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21581 			/*
21582 			 * If MDT has been previously turned off in the past,
21583 			 * and we currently can do MDT (due to IPQoS policy
21584 			 * removal, etc.) then enable it for this interface.
21585 			 */
21586 			ill->ill_mdt_capab->ill_mdt_on = 1;
21587 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
21588 			    ill->ill_name));
21589 		}
21590 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
21591 		    offset);
21592 		return;
21593 	}
21594 
21595 	/* Get a copy of the header for the trailing frags */
21596 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21597 	if (!hdr_mp) {
21598 		BUMP_MIB(&ip_mib, ipOutDiscards);
21599 		freemsg(mp);
21600 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21601 		    "ip_wput_frag_end:(%S)",
21602 		    "couldn't copy hdr");
21603 		return;
21604 	}
21605 
21606 	/* Store the starting offset, with the MoreFrags flag. */
21607 	i1 = offset | IPH_MF | frag_flag;
21608 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21609 
21610 	/* Establish the ending byte offset, based on the starting offset. */
21611 	offset <<= 3;
21612 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21613 
21614 	/* Store the length of the first fragment in the IP header. */
21615 	i1 = len + hdr_len;
21616 	ASSERT(i1 <= IP_MAXPACKET);
21617 	ipha->ipha_length = htons((uint16_t)i1);
21618 
21619 	/*
21620 	 * Compute the IP header checksum for the first frag.  We have to
21621 	 * watch out that we stop at the end of the header.
21622 	 */
21623 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21624 
21625 	/*
21626 	 * Now carve off the first frag.  Note that this will include the
21627 	 * original IP header.
21628 	 */
21629 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21630 		BUMP_MIB(&ip_mib, ipOutDiscards);
21631 		freeb(hdr_mp);
21632 		freemsg(mp_orig);
21633 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21634 		    "ip_wput_frag_end:(%S)",
21635 		    "couldn't carve first");
21636 		return;
21637 	}
21638 
21639 	/*
21640 	 * Multirouting case. Each fragment is replicated
21641 	 * via all non-condemned RTF_MULTIRT routes
21642 	 * currently resolved.
21643 	 * We ensure that first_ire is the first RTF_MULTIRT
21644 	 * ire in the bucket.
21645 	 */
21646 	if (ire->ire_flags & RTF_MULTIRT) {
21647 		irb = ire->ire_bucket;
21648 		ASSERT(irb != NULL);
21649 
21650 		multirt_send = B_TRUE;
21651 
21652 		/* Make sure we do not omit any multiroute ire. */
21653 		IRB_REFHOLD(irb);
21654 		for (first_ire = irb->irb_ire;
21655 		    first_ire != NULL;
21656 		    first_ire = first_ire->ire_next) {
21657 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21658 			    (first_ire->ire_addr == ire->ire_addr) &&
21659 			    !(first_ire->ire_marks &
21660 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21661 				break;
21662 		}
21663 
21664 		if (first_ire != NULL) {
21665 			if (first_ire != ire) {
21666 				IRE_REFHOLD(first_ire);
21667 				/*
21668 				 * Do not release the ire passed in
21669 				 * as the argument.
21670 				 */
21671 				ire = first_ire;
21672 			} else {
21673 				first_ire = NULL;
21674 			}
21675 		}
21676 		IRB_REFRELE(irb);
21677 
21678 		/*
21679 		 * Save the first ire; we will need to restore it
21680 		 * for the trailing frags.
21681 		 * We REFHOLD save_ire, as each iterated ire will be
21682 		 * REFRELEd.
21683 		 */
21684 		save_ire = ire;
21685 		IRE_REFHOLD(save_ire);
21686 	}
21687 
21688 	/*
21689 	 * First fragment emission loop.
21690 	 * In most cases, the emission loop below is entered only
21691 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21692 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21693 	 * bucket, and send the fragment through all crossed
21694 	 * RTF_MULTIRT routes.
21695 	 */
21696 	do {
21697 		if (ire->ire_flags & RTF_MULTIRT) {
21698 			/*
21699 			 * We are in a multiple send case, need to get
21700 			 * the next ire and make a copy of the packet.
21701 			 * ire1 holds here the next ire to process in the
21702 			 * bucket. If multirouting is expected,
21703 			 * any non-RTF_MULTIRT ire that has the
21704 			 * right destination address is ignored.
21705 			 *
21706 			 * We have to take into account the MTU of
21707 			 * each walked ire. max_frag is set by the
21708 			 * the caller and generally refers to
21709 			 * the primary ire entry. Here we ensure that
21710 			 * no route with a lower MTU will be used, as
21711 			 * fragments are carved once for all ires,
21712 			 * then replicated.
21713 			 */
21714 			ASSERT(irb != NULL);
21715 			IRB_REFHOLD(irb);
21716 			for (ire1 = ire->ire_next;
21717 			    ire1 != NULL;
21718 			    ire1 = ire1->ire_next) {
21719 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21720 					continue;
21721 				if (ire1->ire_addr != ire->ire_addr)
21722 					continue;
21723 				if (ire1->ire_marks &
21724 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21725 					continue;
21726 				/*
21727 				 * Ensure we do not exceed the MTU
21728 				 * of the next route.
21729 				 */
21730 				if (ire1->ire_max_frag < max_frag) {
21731 					ip_multirt_bad_mtu(ire1, max_frag);
21732 					continue;
21733 				}
21734 
21735 				/* Got one. */
21736 				IRE_REFHOLD(ire1);
21737 				break;
21738 			}
21739 			IRB_REFRELE(irb);
21740 
21741 			if (ire1 != NULL) {
21742 				next_mp = copyb(mp);
21743 				if ((next_mp == NULL) ||
21744 				    ((mp->b_cont != NULL) &&
21745 				    ((next_mp->b_cont =
21746 				    dupmsg(mp->b_cont)) == NULL))) {
21747 					freemsg(next_mp);
21748 					next_mp = NULL;
21749 					ire_refrele(ire1);
21750 					ire1 = NULL;
21751 				}
21752 			}
21753 
21754 			/* Last multiroute ire; don't loop anymore. */
21755 			if (ire1 == NULL) {
21756 				multirt_send = B_FALSE;
21757 			}
21758 		}
21759 
21760 		ll_hdr_len = 0;
21761 		LOCK_IRE_FP_MP(ire);
21762 		ll_hdr_mp = ire->ire_fp_mp;
21763 		if (ll_hdr_mp != NULL) {
21764 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21765 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21766 		} else {
21767 			ll_hdr_mp = ire->ire_dlureq_mp;
21768 		}
21769 
21770 		/* If there is a transmit header, get a copy for this frag. */
21771 		/*
21772 		 * TODO: should check db_ref before calling ip_carve_mp since
21773 		 * it might give us a dup.
21774 		 */
21775 		if (!ll_hdr_mp) {
21776 			/* No xmit header. */
21777 			xmit_mp = mp;
21778 		} else if (mp->b_datap->db_ref == 1 &&
21779 		    ll_hdr_len != 0 &&
21780 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21781 			/* M_DATA fastpath */
21782 			mp->b_rptr -= ll_hdr_len;
21783 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21784 			xmit_mp = mp;
21785 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21786 			UNLOCK_IRE_FP_MP(ire);
21787 			BUMP_MIB(&ip_mib, ipOutDiscards);
21788 			freeb(hdr_mp);
21789 			freemsg(mp);
21790 			freemsg(mp_orig);
21791 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21792 			    "ip_wput_frag_end:(%S)",
21793 			    "discard");
21794 
21795 			if (multirt_send) {
21796 				ASSERT(ire1);
21797 				ASSERT(next_mp);
21798 
21799 				freemsg(next_mp);
21800 				ire_refrele(ire1);
21801 			}
21802 			if (save_ire != NULL)
21803 				IRE_REFRELE(save_ire);
21804 
21805 			if (first_ire != NULL)
21806 				ire_refrele(first_ire);
21807 			return;
21808 		} else {
21809 			xmit_mp->b_cont = mp;
21810 			/* Get priority marking, if any. */
21811 			if (DB_TYPE(xmit_mp) == M_DATA)
21812 				xmit_mp->b_band = mp->b_band;
21813 		}
21814 		UNLOCK_IRE_FP_MP(ire);
21815 		q = ire->ire_stq;
21816 		BUMP_MIB(&ip_mib, ipFragCreates);
21817 		putnext(q, xmit_mp);
21818 		if (pkt_type != OB_PKT) {
21819 			/*
21820 			 * Update the packet count of trailing
21821 			 * RTF_MULTIRT ires.
21822 			 */
21823 			UPDATE_OB_PKT_COUNT(ire);
21824 		}
21825 
21826 		if (multirt_send) {
21827 			/*
21828 			 * We are in a multiple send case; look for
21829 			 * the next ire and re-enter the loop.
21830 			 */
21831 			ASSERT(ire1);
21832 			ASSERT(next_mp);
21833 			/* REFRELE the current ire before looping */
21834 			ire_refrele(ire);
21835 			ire = ire1;
21836 			ire1 = NULL;
21837 			mp = next_mp;
21838 			next_mp = NULL;
21839 		}
21840 	} while (multirt_send);
21841 
21842 	ASSERT(ire1 == NULL);
21843 
21844 	/* Restore the original ire; we need it for the trailing frags */
21845 	if (save_ire != NULL) {
21846 		/* REFRELE the last iterated ire */
21847 		ire_refrele(ire);
21848 		/* save_ire has been REFHOLDed */
21849 		ire = save_ire;
21850 		save_ire = NULL;
21851 		q = ire->ire_stq;
21852 	}
21853 
21854 	if (pkt_type == OB_PKT) {
21855 		UPDATE_OB_PKT_COUNT(ire);
21856 	} else {
21857 		UPDATE_IB_PKT_COUNT(ire);
21858 	}
21859 
21860 	/* Advance the offset to the second frag starting point. */
21861 	offset += len;
21862 	/*
21863 	 * Update hdr_len from the copied header - there might be less options
21864 	 * in the later fragments.
21865 	 */
21866 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21867 	/* Loop until done. */
21868 	for (;;) {
21869 		uint16_t	offset_and_flags;
21870 		uint16_t	ip_len;
21871 
21872 		if (ip_data_end - offset > len) {
21873 			/*
21874 			 * Carve off the appropriate amount from the original
21875 			 * datagram.
21876 			 */
21877 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21878 				mp = NULL;
21879 				break;
21880 			}
21881 			/*
21882 			 * More frags after this one.  Get another copy
21883 			 * of the header.
21884 			 */
21885 			if (carve_mp->b_datap->db_ref == 1 &&
21886 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21887 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21888 				/* Inline IP header */
21889 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21890 				    hdr_mp->b_rptr;
21891 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21892 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21893 				mp = carve_mp;
21894 			} else {
21895 				if (!(mp = copyb(hdr_mp))) {
21896 					freemsg(carve_mp);
21897 					break;
21898 				}
21899 				/* Get priority marking, if any. */
21900 				mp->b_band = carve_mp->b_band;
21901 				mp->b_cont = carve_mp;
21902 			}
21903 			ipha = (ipha_t *)mp->b_rptr;
21904 			offset_and_flags = IPH_MF;
21905 		} else {
21906 			/*
21907 			 * Last frag.  Consume the header. Set len to
21908 			 * the length of this last piece.
21909 			 */
21910 			len = ip_data_end - offset;
21911 
21912 			/*
21913 			 * Carve off the appropriate amount from the original
21914 			 * datagram.
21915 			 */
21916 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21917 				mp = NULL;
21918 				break;
21919 			}
21920 			if (carve_mp->b_datap->db_ref == 1 &&
21921 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21922 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21923 				/* Inline IP header */
21924 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21925 				    hdr_mp->b_rptr;
21926 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21927 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21928 				mp = carve_mp;
21929 				freeb(hdr_mp);
21930 				hdr_mp = mp;
21931 			} else {
21932 				mp = hdr_mp;
21933 				/* Get priority marking, if any. */
21934 				mp->b_band = carve_mp->b_band;
21935 				mp->b_cont = carve_mp;
21936 			}
21937 			ipha = (ipha_t *)mp->b_rptr;
21938 			/* A frag of a frag might have IPH_MF non-zero */
21939 			offset_and_flags =
21940 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21941 			    IPH_MF;
21942 		}
21943 		offset_and_flags |= (uint16_t)(offset >> 3);
21944 		offset_and_flags |= (uint16_t)frag_flag;
21945 		/* Store the offset and flags in the IP header. */
21946 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21947 
21948 		/* Store the length in the IP header. */
21949 		ip_len = (uint16_t)(len + hdr_len);
21950 		ipha->ipha_length = htons(ip_len);
21951 
21952 		/*
21953 		 * Set the IP header checksum.	Note that mp is just
21954 		 * the header, so this is easy to pass to ip_csum.
21955 		 */
21956 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21957 
21958 		/* Attach a transmit header, if any, and ship it. */
21959 		if (pkt_type == OB_PKT) {
21960 			UPDATE_OB_PKT_COUNT(ire);
21961 		} else {
21962 			UPDATE_IB_PKT_COUNT(ire);
21963 		}
21964 
21965 		if (ire->ire_flags & RTF_MULTIRT) {
21966 			irb = ire->ire_bucket;
21967 			ASSERT(irb != NULL);
21968 
21969 			multirt_send = B_TRUE;
21970 
21971 			/*
21972 			 * Save the original ire; we will need to restore it
21973 			 * for the tailing frags.
21974 			 */
21975 			save_ire = ire;
21976 			IRE_REFHOLD(save_ire);
21977 		}
21978 		/*
21979 		 * Emission loop for this fragment, similar
21980 		 * to what is done for the first fragment.
21981 		 */
21982 		do {
21983 			if (multirt_send) {
21984 				/*
21985 				 * We are in a multiple send case, need to get
21986 				 * the next ire and make a copy of the packet.
21987 				 */
21988 				ASSERT(irb != NULL);
21989 				IRB_REFHOLD(irb);
21990 				for (ire1 = ire->ire_next;
21991 				    ire1 != NULL;
21992 				    ire1 = ire1->ire_next) {
21993 					if (!(ire1->ire_flags & RTF_MULTIRT))
21994 						continue;
21995 					if (ire1->ire_addr != ire->ire_addr)
21996 						continue;
21997 					if (ire1->ire_marks &
21998 					    (IRE_MARK_CONDEMNED|
21999 						IRE_MARK_HIDDEN))
22000 						continue;
22001 					/*
22002 					 * Ensure we do not exceed the MTU
22003 					 * of the next route.
22004 					 */
22005 					if (ire1->ire_max_frag < max_frag) {
22006 						ip_multirt_bad_mtu(ire1,
22007 						    max_frag);
22008 						continue;
22009 					}
22010 
22011 					/* Got one. */
22012 					IRE_REFHOLD(ire1);
22013 					break;
22014 				}
22015 				IRB_REFRELE(irb);
22016 
22017 				if (ire1 != NULL) {
22018 					next_mp = copyb(mp);
22019 					if ((next_mp == NULL) ||
22020 					    ((mp->b_cont != NULL) &&
22021 					    ((next_mp->b_cont =
22022 					    dupmsg(mp->b_cont)) == NULL))) {
22023 						freemsg(next_mp);
22024 						next_mp = NULL;
22025 						ire_refrele(ire1);
22026 						ire1 = NULL;
22027 					}
22028 				}
22029 
22030 				/* Last multiroute ire; don't loop anymore. */
22031 				if (ire1 == NULL) {
22032 					multirt_send = B_FALSE;
22033 				}
22034 			}
22035 
22036 			/* Update transmit header */
22037 			ll_hdr_len = 0;
22038 			LOCK_IRE_FP_MP(ire);
22039 			ll_hdr_mp = ire->ire_fp_mp;
22040 			if (ll_hdr_mp != NULL) {
22041 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22042 				ll_hdr_len = MBLKL(ll_hdr_mp);
22043 			} else {
22044 				ll_hdr_mp = ire->ire_dlureq_mp;
22045 			}
22046 
22047 			if (!ll_hdr_mp) {
22048 				xmit_mp = mp;
22049 			} else if (mp->b_datap->db_ref == 1 &&
22050 			    ll_hdr_len != 0 &&
22051 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22052 				/* M_DATA fastpath */
22053 				mp->b_rptr -= ll_hdr_len;
22054 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22055 				    ll_hdr_len);
22056 				xmit_mp = mp;
22057 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22058 				xmit_mp->b_cont = mp;
22059 				/* Get priority marking, if any. */
22060 				if (DB_TYPE(xmit_mp) == M_DATA)
22061 					xmit_mp->b_band = mp->b_band;
22062 			} else {
22063 				/*
22064 				 * Exit both the replication and
22065 				 * fragmentation loops.
22066 				 */
22067 				UNLOCK_IRE_FP_MP(ire);
22068 				goto drop_pkt;
22069 			}
22070 			UNLOCK_IRE_FP_MP(ire);
22071 			BUMP_MIB(&ip_mib, ipFragCreates);
22072 			putnext(q, xmit_mp);
22073 
22074 			if (pkt_type != OB_PKT) {
22075 				/*
22076 				 * Update the packet count of trailing
22077 				 * RTF_MULTIRT ires.
22078 				 */
22079 				UPDATE_OB_PKT_COUNT(ire);
22080 			}
22081 
22082 			/* All done if we just consumed the hdr_mp. */
22083 			if (mp == hdr_mp) {
22084 				last_frag = B_TRUE;
22085 			}
22086 
22087 			if (multirt_send) {
22088 				/*
22089 				 * We are in a multiple send case; look for
22090 				 * the next ire and re-enter the loop.
22091 				 */
22092 				ASSERT(ire1);
22093 				ASSERT(next_mp);
22094 				/* REFRELE the current ire before looping */
22095 				ire_refrele(ire);
22096 				ire = ire1;
22097 				ire1 = NULL;
22098 				q = ire->ire_stq;
22099 				mp = next_mp;
22100 				next_mp = NULL;
22101 			}
22102 		} while (multirt_send);
22103 		/*
22104 		 * Restore the original ire; we need it for the
22105 		 * trailing frags
22106 		 */
22107 		if (save_ire != NULL) {
22108 			ASSERT(ire1 == NULL);
22109 			/* REFRELE the last iterated ire */
22110 			ire_refrele(ire);
22111 			/* save_ire has been REFHOLDed */
22112 			ire = save_ire;
22113 			q = ire->ire_stq;
22114 			save_ire = NULL;
22115 		}
22116 
22117 		if (last_frag) {
22118 			BUMP_MIB(&ip_mib, ipFragOKs);
22119 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22120 			    "ip_wput_frag_end:(%S)",
22121 			    "consumed hdr_mp");
22122 
22123 			if (first_ire != NULL)
22124 				ire_refrele(first_ire);
22125 			return;
22126 		}
22127 		/* Otherwise, advance and loop. */
22128 		offset += len;
22129 	}
22130 
22131 drop_pkt:
22132 	/* Clean up following allocation failure. */
22133 	BUMP_MIB(&ip_mib, ipOutDiscards);
22134 	freemsg(mp);
22135 	if (mp != hdr_mp)
22136 		freeb(hdr_mp);
22137 	if (mp != mp_orig)
22138 		freemsg(mp_orig);
22139 
22140 	if (save_ire != NULL)
22141 		IRE_REFRELE(save_ire);
22142 	if (first_ire != NULL)
22143 		ire_refrele(first_ire);
22144 
22145 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22146 	    "ip_wput_frag_end:(%S)",
22147 	    "end--alloc failure");
22148 }
22149 
22150 /*
22151  * Copy the header plus those options which have the copy bit set
22152  */
22153 static mblk_t *
22154 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22155 {
22156 	mblk_t	*mp;
22157 	uchar_t	*up;
22158 
22159 	/*
22160 	 * Quick check if we need to look for options without the copy bit
22161 	 * set
22162 	 */
22163 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22164 	if (!mp)
22165 		return (mp);
22166 	mp->b_rptr += ip_wroff_extra;
22167 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22168 		bcopy(rptr, mp->b_rptr, hdr_len);
22169 		mp->b_wptr += hdr_len + ip_wroff_extra;
22170 		return (mp);
22171 	}
22172 	up  = mp->b_rptr;
22173 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22174 	up += IP_SIMPLE_HDR_LENGTH;
22175 	rptr += IP_SIMPLE_HDR_LENGTH;
22176 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22177 	while (hdr_len > 0) {
22178 		uint32_t optval;
22179 		uint32_t optlen;
22180 
22181 		optval = *rptr;
22182 		if (optval == IPOPT_EOL)
22183 			break;
22184 		if (optval == IPOPT_NOP)
22185 			optlen = 1;
22186 		else
22187 			optlen = rptr[1];
22188 		if (optval & IPOPT_COPY) {
22189 			bcopy(rptr, up, optlen);
22190 			up += optlen;
22191 		}
22192 		rptr += optlen;
22193 		hdr_len -= optlen;
22194 	}
22195 	/*
22196 	 * Make sure that we drop an even number of words by filling
22197 	 * with EOL to the next word boundary.
22198 	 */
22199 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
22200 	    hdr_len & 0x3; hdr_len++)
22201 		*up++ = IPOPT_EOL;
22202 	mp->b_wptr = up;
22203 	/* Update header length */
22204 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
22205 	return (mp);
22206 }
22207 
22208 /*
22209  * Delivery to local recipients including fanout to multiple recipients.
22210  * Does not do checksumming of UDP/TCP.
22211  * Note: q should be the read side queue for either the ill or conn.
22212  * Note: rq should be the read side q for the lower (ill) stream.
22213  * We don't send packets to IPPF processing, thus the last argument
22214  * to all the fanout calls are B_FALSE.
22215  */
22216 void
22217 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
22218     int fanout_flags, zoneid_t zoneid)
22219 {
22220 	uint32_t	protocol;
22221 	mblk_t		*first_mp;
22222 	boolean_t	mctl_present;
22223 	int		ire_type;
22224 #define	rptr	((uchar_t *)ipha)
22225 
22226 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
22227 	    "ip_wput_local_start: q %p", q);
22228 
22229 	if (ire != NULL) {
22230 		ire_type = ire->ire_type;
22231 	} else {
22232 		/*
22233 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
22234 		 * packet is not multicast, we can't tell the ire type.
22235 		 */
22236 		ASSERT(CLASSD(ipha->ipha_dst));
22237 		ire_type = IRE_BROADCAST;
22238 	}
22239 
22240 	first_mp = mp;
22241 	if (first_mp->b_datap->db_type == M_CTL) {
22242 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
22243 		if (!io->ipsec_out_secure) {
22244 			/*
22245 			 * This ipsec_out_t was allocated in ip_wput
22246 			 * for multicast packets to store the ill_index.
22247 			 * As this is being delivered locally, we don't
22248 			 * need this anymore.
22249 			 */
22250 			mp = first_mp->b_cont;
22251 			freeb(first_mp);
22252 			first_mp = mp;
22253 			mctl_present = B_FALSE;
22254 		} else {
22255 			mctl_present = B_TRUE;
22256 			mp = first_mp->b_cont;
22257 			ASSERT(mp != NULL);
22258 			ipsec_out_to_in(first_mp);
22259 		}
22260 	} else {
22261 		mctl_present = B_FALSE;
22262 	}
22263 
22264 	loopback_packets++;
22265 
22266 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
22267 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
22268 	if (!IS_SIMPLE_IPH(ipha)) {
22269 		ip_wput_local_options(ipha);
22270 	}
22271 
22272 	protocol = ipha->ipha_protocol;
22273 	switch (protocol) {
22274 	case IPPROTO_ICMP: {
22275 		ire_t		*ire_zone;
22276 		ilm_t		*ilm;
22277 		mblk_t		*mp1;
22278 		zoneid_t	last_zoneid;
22279 
22280 		if (CLASSD(ipha->ipha_dst) &&
22281 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
22282 			ASSERT(ire_type == IRE_BROADCAST);
22283 			/*
22284 			 * In the multicast case, applications may have joined
22285 			 * the group from different zones, so we need to deliver
22286 			 * the packet to each of them. Loop through the
22287 			 * multicast memberships structures (ilm) on the receive
22288 			 * ill and send a copy of the packet up each matching
22289 			 * one. However, we don't do this for multicasts sent on
22290 			 * the loopback interface (PHYI_LOOPBACK flag set) as
22291 			 * they must stay in the sender's zone.
22292 			 *
22293 			 * ilm_add_v6() ensures that ilms in the same zone are
22294 			 * contiguous in the ill_ilm list. We use this property
22295 			 * to avoid sending duplicates needed when two
22296 			 * applications in the same zone join the same group on
22297 			 * different logical interfaces: we ignore the ilm if
22298 			 * its zoneid is the same as the last matching one.
22299 			 * In addition, the sending of the packet for
22300 			 * ire_zoneid is delayed until all of the other ilms
22301 			 * have been exhausted.
22302 			 */
22303 			last_zoneid = -1;
22304 			ILM_WALKER_HOLD(ill);
22305 			for (ilm = ill->ill_ilm; ilm != NULL;
22306 			    ilm = ilm->ilm_next) {
22307 				if ((ilm->ilm_flags & ILM_DELETED) ||
22308 				    ipha->ipha_dst != ilm->ilm_addr ||
22309 				    ilm->ilm_zoneid == last_zoneid ||
22310 				    ilm->ilm_zoneid == zoneid ||
22311 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
22312 					continue;
22313 				mp1 = ip_copymsg(first_mp);
22314 				if (mp1 == NULL)
22315 					continue;
22316 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22317 				    mctl_present, B_FALSE, ill,
22318 				    ilm->ilm_zoneid);
22319 				last_zoneid = ilm->ilm_zoneid;
22320 			}
22321 			ILM_WALKER_RELE(ill);
22322 			/*
22323 			 * Loopback case: the sending endpoint has
22324 			 * IP_MULTICAST_LOOP disabled, therefore we don't
22325 			 * dispatch the multicast packet to the sending zone.
22326 			 */
22327 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
22328 				freemsg(first_mp);
22329 				return;
22330 			}
22331 		} else if (ire_type == IRE_BROADCAST) {
22332 			/*
22333 			 * In the broadcast case, there may be many zones
22334 			 * which need a copy of the packet delivered to them.
22335 			 * There is one IRE_BROADCAST per broadcast address
22336 			 * and per zone; we walk those using a helper function.
22337 			 * In addition, the sending of the packet for zoneid is
22338 			 * delayed until all of the other ires have been
22339 			 * processed.
22340 			 */
22341 			IRB_REFHOLD(ire->ire_bucket);
22342 			ire_zone = NULL;
22343 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
22344 			    ire)) != NULL) {
22345 				mp1 = ip_copymsg(first_mp);
22346 				if (mp1 == NULL)
22347 					continue;
22348 
22349 				UPDATE_IB_PKT_COUNT(ire_zone);
22350 				ire_zone->ire_last_used_time = lbolt;
22351 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22352 				    mctl_present, B_FALSE, ill,
22353 				    ire_zone->ire_zoneid);
22354 			}
22355 			IRB_REFRELE(ire->ire_bucket);
22356 		}
22357 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
22358 		    0, mctl_present, B_FALSE, ill, zoneid);
22359 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22360 		    "ip_wput_local_end: q %p (%S)",
22361 		    q, "icmp");
22362 		return;
22363 	}
22364 	case IPPROTO_IGMP:
22365 		if (igmp_input(q, mp, ill)) {
22366 			/* Bad packet - discarded by igmp_input */
22367 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22368 			    "ip_wput_local_end: q %p (%S)",
22369 			    q, "igmp_input--bad packet");
22370 			if (mctl_present)
22371 				freeb(first_mp);
22372 			return;
22373 		}
22374 		/*
22375 		 * igmp_input() may have pulled up the message so ipha needs to
22376 		 * be reinitialized.
22377 		 */
22378 		ipha = (ipha_t *)mp->b_rptr;
22379 		/* deliver to local raw users */
22380 		break;
22381 	case IPPROTO_ENCAP:
22382 		/*
22383 		 * This case is covered by either ip_fanout_proto, or by
22384 		 * the above security processing for self-tunneled packets.
22385 		 */
22386 		break;
22387 	case IPPROTO_UDP: {
22388 		uint16_t	*up;
22389 		uint32_t	ports;
22390 
22391 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
22392 		    UDP_PORTS_OFFSET);
22393 		/* Force a 'valid' checksum. */
22394 		up[3] = 0;
22395 
22396 		ports = *(uint32_t *)up;
22397 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
22398 		    (ire_type == IRE_BROADCAST),
22399 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22400 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
22401 		    ill, zoneid);
22402 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22403 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
22404 		return;
22405 	}
22406 	case IPPROTO_TCP: {
22407 
22408 		/*
22409 		 * For TCP, discard broadcast packets.
22410 		 */
22411 		if ((ushort_t)ire_type == IRE_BROADCAST) {
22412 			freemsg(first_mp);
22413 			BUMP_MIB(&ip_mib, ipInDiscards);
22414 			return;
22415 		}
22416 
22417 		if (mp->b_datap->db_type == M_DATA) {
22418 			/*
22419 			 * M_DATA mblk, so init mblk (chain) for no struio().
22420 			 */
22421 			mblk_t	*mp1 = mp;
22422 
22423 			do
22424 				mp1->b_datap->db_struioflag = 0;
22425 			while ((mp1 = mp1->b_cont) != NULL);
22426 		}
22427 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
22428 		    <= mp->b_wptr);
22429 		ip_fanout_tcp(q, first_mp, ill, ipha,
22430 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22431 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
22432 		    mctl_present, B_FALSE, zoneid);
22433 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22434 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
22435 		return;
22436 	}
22437 	case IPPROTO_SCTP:
22438 	{
22439 		uint32_t	ports;
22440 
22441 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
22442 		ip_fanout_sctp(first_mp, ill, ipha, ports,
22443 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22444 		    IP_FF_IP6INFO,
22445 		    mctl_present, B_FALSE, 0, zoneid);
22446 		return;
22447 	}
22448 
22449 	default:
22450 		break;
22451 	}
22452 	/*
22453 	 * Find a client for some other protocol.  We give
22454 	 * copies to multiple clients, if more than one is
22455 	 * bound.
22456 	 */
22457 	ip_fanout_proto(q, first_mp, ill, ipha,
22458 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
22459 	    mctl_present, B_FALSE, ill, zoneid);
22460 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22461 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
22462 #undef	rptr
22463 }
22464 
22465 /*
22466  * Update any source route, record route, or timestamp options.
22467  * Check that we are at end of strict source route.
22468  * The options have been sanity checked by ip_wput_options().
22469  */
22470 static void
22471 ip_wput_local_options(ipha_t *ipha)
22472 {
22473 	ipoptp_t	opts;
22474 	uchar_t		*opt;
22475 	uint8_t		optval;
22476 	uint8_t		optlen;
22477 	ipaddr_t	dst;
22478 	uint32_t	ts;
22479 	ire_t		*ire;
22480 	timestruc_t	now;
22481 
22482 	ip2dbg(("ip_wput_local_options\n"));
22483 	for (optval = ipoptp_first(&opts, ipha);
22484 	    optval != IPOPT_EOL;
22485 	    optval = ipoptp_next(&opts)) {
22486 		opt = opts.ipoptp_cur;
22487 		optlen = opts.ipoptp_len;
22488 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22489 		switch (optval) {
22490 			uint32_t off;
22491 		case IPOPT_SSRR:
22492 		case IPOPT_LSRR:
22493 			off = opt[IPOPT_OFFSET];
22494 			off--;
22495 			if (optlen < IP_ADDR_LEN ||
22496 			    off > optlen - IP_ADDR_LEN) {
22497 				/* End of source route */
22498 				break;
22499 			}
22500 			/*
22501 			 * This will only happen if two consecutive entries
22502 			 * in the source route contains our address or if
22503 			 * it is a packet with a loose source route which
22504 			 * reaches us before consuming the whole source route
22505 			 */
22506 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22507 			if (optval == IPOPT_SSRR) {
22508 				return;
22509 			}
22510 			/*
22511 			 * Hack: instead of dropping the packet truncate the
22512 			 * source route to what has been used by filling the
22513 			 * rest with IPOPT_NOP.
22514 			 */
22515 			opt[IPOPT_OLEN] = (uint8_t)off;
22516 			while (off < optlen) {
22517 				opt[off++] = IPOPT_NOP;
22518 			}
22519 			break;
22520 		case IPOPT_RR:
22521 			off = opt[IPOPT_OFFSET];
22522 			off--;
22523 			if (optlen < IP_ADDR_LEN ||
22524 			    off > optlen - IP_ADDR_LEN) {
22525 				/* No more room - ignore */
22526 				ip1dbg((
22527 				    "ip_wput_forward_options: end of RR\n"));
22528 				break;
22529 			}
22530 			dst = htonl(INADDR_LOOPBACK);
22531 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22532 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22533 			break;
22534 		case IPOPT_TS:
22535 			/* Insert timestamp if there is romm */
22536 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22537 			case IPOPT_TS_TSONLY:
22538 				off = IPOPT_TS_TIMELEN;
22539 				break;
22540 			case IPOPT_TS_PRESPEC:
22541 			case IPOPT_TS_PRESPEC_RFC791:
22542 				/* Verify that the address matched */
22543 				off = opt[IPOPT_OFFSET] - 1;
22544 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22545 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22546 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22547 				if (ire == NULL) {
22548 					/* Not for us */
22549 					break;
22550 				}
22551 				ire_refrele(ire);
22552 				/* FALLTHRU */
22553 			case IPOPT_TS_TSANDADDR:
22554 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22555 				break;
22556 			default:
22557 				/*
22558 				 * ip_*put_options should have already
22559 				 * dropped this packet.
22560 				 */
22561 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22562 				    "unknown IT - bug in ip_wput_options?\n");
22563 				return;	/* Keep "lint" happy */
22564 			}
22565 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22566 				/* Increase overflow counter */
22567 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22568 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22569 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22570 				    (off << 4);
22571 				break;
22572 			}
22573 			off = opt[IPOPT_OFFSET] - 1;
22574 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22575 			case IPOPT_TS_PRESPEC:
22576 			case IPOPT_TS_PRESPEC_RFC791:
22577 			case IPOPT_TS_TSANDADDR:
22578 				dst = htonl(INADDR_LOOPBACK);
22579 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22580 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22581 				/* FALLTHRU */
22582 			case IPOPT_TS_TSONLY:
22583 				off = opt[IPOPT_OFFSET] - 1;
22584 				/* Compute # of milliseconds since midnight */
22585 				gethrestime(&now);
22586 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22587 				    now.tv_nsec / (NANOSEC / MILLISEC);
22588 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22589 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22590 				break;
22591 			}
22592 			break;
22593 		}
22594 	}
22595 }
22596 
22597 /*
22598  * Send out a multicast packet on interface ipif.
22599  * The sender does not have an conn.
22600  * Caller verifies that this isn't a PHYI_LOOPBACK.
22601  */
22602 void
22603 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22604 {
22605 	ipha_t	*ipha;
22606 	ire_t	*ire;
22607 	ipaddr_t	dst;
22608 	mblk_t		*first_mp;
22609 
22610 	/* igmp_sendpkt always allocates a ipsec_out_t */
22611 	ASSERT(mp->b_datap->db_type == M_CTL);
22612 	ASSERT(!ipif->ipif_isv6);
22613 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22614 
22615 	first_mp = mp;
22616 	mp = first_mp->b_cont;
22617 	ASSERT(mp->b_datap->db_type == M_DATA);
22618 	ipha = (ipha_t *)mp->b_rptr;
22619 
22620 	/*
22621 	 * Find an IRE which matches the destination and the outgoing
22622 	 * queue (i.e. the outgoing interface.)
22623 	 */
22624 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22625 		dst = ipif->ipif_pp_dst_addr;
22626 	else
22627 		dst = ipha->ipha_dst;
22628 	/*
22629 	 * The source address has already been initialized by the
22630 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22631 	 * be sufficient rather than MATCH_IRE_IPIF.
22632 	 *
22633 	 * This function is used for sending IGMP packets. We need
22634 	 * to make sure that we send the packet out of the interface
22635 	 * (ipif->ipif_ill) where we joined the group. This is to
22636 	 * prevent from switches doing IGMP snooping to send us multicast
22637 	 * packets for a given group on the interface we have joined.
22638 	 * If we can't find an ire, igmp_sendpkt has already initialized
22639 	 * ipsec_out_attach_if so that this will not be load spread in
22640 	 * ip_newroute_ipif.
22641 	 */
22642 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22643 	if (!ire) {
22644 		/*
22645 		 * Mark this packet to make it be delivered to
22646 		 * ip_wput_ire after the new ire has been
22647 		 * created.
22648 		 */
22649 		mp->b_prev = NULL;
22650 		mp->b_next = NULL;
22651 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22652 		return;
22653 	}
22654 
22655 	/*
22656 	 * Honor the RTF_SETSRC flag; this is the only case
22657 	 * where we force this addr whatever the current src addr is,
22658 	 * because this address is set by igmp_sendpkt(), and
22659 	 * cannot be specified by any user.
22660 	 */
22661 	if (ire->ire_flags & RTF_SETSRC) {
22662 		ipha->ipha_src = ire->ire_src_addr;
22663 	}
22664 
22665 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22666 }
22667 
22668 /*
22669  * NOTE : This function does not ire_refrele the ire argument passed in.
22670  *
22671  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22672  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22673  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22674  * the ire_lock to access the ire_fp_mp in this case.
22675  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22676  * prepending a fastpath message IPQoS processing must precede it, we also set
22677  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22678  * (IPQoS might have set the b_band for CoS marking).
22679  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22680  * must follow it so that IPQoS can mark the dl_priority field for CoS
22681  * marking, if needed.
22682  */
22683 static mblk_t *
22684 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22685 {
22686 	uint_t	hlen;
22687 	ipha_t *ipha;
22688 	mblk_t *mp1;
22689 	boolean_t qos_done = B_FALSE;
22690 	uchar_t	*ll_hdr;
22691 
22692 #define	rptr	((uchar_t *)ipha)
22693 
22694 	ipha = (ipha_t *)mp->b_rptr;
22695 	hlen = 0;
22696 	LOCK_IRE_FP_MP(ire);
22697 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22698 		ASSERT(DB_TYPE(mp1) == M_DATA);
22699 		/* Initiate IPPF processing */
22700 		if ((proc != 0) && IPP_ENABLED(proc)) {
22701 			UNLOCK_IRE_FP_MP(ire);
22702 			ip_process(proc, &mp, ill_index);
22703 			if (mp == NULL)
22704 				return (NULL);
22705 
22706 			ipha = (ipha_t *)mp->b_rptr;
22707 			LOCK_IRE_FP_MP(ire);
22708 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22709 				qos_done = B_TRUE;
22710 				goto no_fp_mp;
22711 			}
22712 			ASSERT(DB_TYPE(mp1) == M_DATA);
22713 		}
22714 		hlen = MBLKL(mp1);
22715 		/*
22716 		 * Check if we have enough room to prepend fastpath
22717 		 * header
22718 		 */
22719 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22720 			ll_hdr = rptr - hlen;
22721 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22722 			/* XXX ipha is not aligned here */
22723 			ipha = (ipha_t *)(rptr - hlen);
22724 			/*
22725 			 * Set the b_rptr to the start of the link layer
22726 			 * header
22727 			 */
22728 			mp->b_rptr = rptr;
22729 			mp1 = mp;
22730 		} else {
22731 			mp1 = copyb(mp1);
22732 			if (mp1 == NULL)
22733 				goto unlock_err;
22734 			mp1->b_band = mp->b_band;
22735 			mp1->b_cont = mp;
22736 			/*
22737 			 * XXX disable ICK_VALID and compute checksum
22738 			 * here; can happen if ire_fp_mp changes and
22739 			 * it can't be copied now due to insufficient
22740 			 * space. (unlikely, fp mp can change, but it
22741 			 * does not increase in length)
22742 			 */
22743 		}
22744 		UNLOCK_IRE_FP_MP(ire);
22745 	} else {
22746 no_fp_mp:
22747 		mp1 = copyb(ire->ire_dlureq_mp);
22748 		if (mp1 == NULL) {
22749 unlock_err:
22750 			UNLOCK_IRE_FP_MP(ire);
22751 			freemsg(mp);
22752 			return (NULL);
22753 		}
22754 		UNLOCK_IRE_FP_MP(ire);
22755 		mp1->b_cont = mp;
22756 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22757 			ip_process(proc, &mp1, ill_index);
22758 			if (mp1 == NULL)
22759 				return (NULL);
22760 		}
22761 	}
22762 	return (mp1);
22763 #undef rptr
22764 }
22765 
22766 /*
22767  * Finish the outbound IPsec processing for an IPv6 packet. This function
22768  * is called from ipsec_out_process() if the IPsec packet was processed
22769  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22770  * asynchronously.
22771  */
22772 void
22773 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22774     ire_t *ire_arg)
22775 {
22776 	in6_addr_t *v6dstp;
22777 	ire_t *ire;
22778 	mblk_t *mp;
22779 	uint_t	ill_index;
22780 	ipsec_out_t *io;
22781 	boolean_t attach_if, hwaccel;
22782 	uint32_t flags = IP6_NO_IPPOLICY;
22783 	int match_flags;
22784 	zoneid_t zoneid;
22785 	boolean_t ill_need_rele = B_FALSE;
22786 	boolean_t ire_need_rele = B_FALSE;
22787 
22788 	mp = ipsec_mp->b_cont;
22789 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22790 	ill_index = io->ipsec_out_ill_index;
22791 	if (io->ipsec_out_reachable) {
22792 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22793 	}
22794 	attach_if = io->ipsec_out_attach_if;
22795 	hwaccel = io->ipsec_out_accelerated;
22796 	zoneid = io->ipsec_out_zoneid;
22797 	ASSERT(zoneid != ALL_ZONES);
22798 	match_flags = MATCH_IRE_ILL_GROUP;
22799 	/* Multicast addresses should have non-zero ill_index. */
22800 	v6dstp = &ip6h->ip6_dst;
22801 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22802 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22803 	ASSERT(!attach_if || ill_index != 0);
22804 	if (ill_index != 0) {
22805 		if (ill == NULL) {
22806 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22807 			    B_TRUE);
22808 
22809 			/* Failure case frees things for us. */
22810 			if (ill == NULL)
22811 				return;
22812 
22813 			ill_need_rele = B_TRUE;
22814 		}
22815 		/*
22816 		 * If this packet needs to go out on a particular interface
22817 		 * honor it.
22818 		 */
22819 		if (attach_if) {
22820 			match_flags = MATCH_IRE_ILL;
22821 
22822 			/*
22823 			 * Check if we need an ire that will not be
22824 			 * looked up by anybody else i.e. HIDDEN.
22825 			 */
22826 			if (ill_is_probeonly(ill)) {
22827 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22828 			}
22829 		}
22830 	}
22831 	ASSERT(mp != NULL);
22832 
22833 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22834 		boolean_t unspec_src;
22835 		ipif_t	*ipif;
22836 
22837 		/*
22838 		 * Use the ill_index to get the right ill.
22839 		 */
22840 		unspec_src = io->ipsec_out_unspec_src;
22841 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22842 		if (ipif == NULL) {
22843 			if (ill_need_rele)
22844 				ill_refrele(ill);
22845 			freemsg(ipsec_mp);
22846 			return;
22847 		}
22848 
22849 		if (ire_arg != NULL) {
22850 			ire = ire_arg;
22851 		} else {
22852 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22853 			    zoneid, match_flags);
22854 			ire_need_rele = B_TRUE;
22855 		}
22856 		if (ire != NULL) {
22857 			ipif_refrele(ipif);
22858 			/*
22859 			 * XXX Do the multicast forwarding now, as the IPSEC
22860 			 * processing has been done.
22861 			 */
22862 			goto send;
22863 		}
22864 
22865 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22866 		mp->b_prev = NULL;
22867 		mp->b_next = NULL;
22868 
22869 		/*
22870 		 * If the IPsec packet was processed asynchronously,
22871 		 * drop it now.
22872 		 */
22873 		if (q == NULL) {
22874 			if (ill_need_rele)
22875 				ill_refrele(ill);
22876 			freemsg(ipsec_mp);
22877 			return;
22878 		}
22879 
22880 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22881 		    unspec_src, zoneid);
22882 		ipif_refrele(ipif);
22883 	} else {
22884 		if (attach_if) {
22885 			ipif_t	*ipif;
22886 
22887 			ipif = ipif_get_next_ipif(NULL, ill);
22888 			if (ipif == NULL) {
22889 				if (ill_need_rele)
22890 					ill_refrele(ill);
22891 				freemsg(ipsec_mp);
22892 				return;
22893 			}
22894 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22895 			    zoneid, match_flags);
22896 			ire_need_rele = B_TRUE;
22897 			ipif_refrele(ipif);
22898 		} else {
22899 			if (ire_arg != NULL) {
22900 				ire = ire_arg;
22901 			} else {
22902 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22903 				ire_need_rele = B_TRUE;
22904 			}
22905 		}
22906 		if (ire != NULL)
22907 			goto send;
22908 		/*
22909 		 * ire disappeared underneath.
22910 		 *
22911 		 * What we need to do here is the ip_newroute
22912 		 * logic to get the ire without doing the IPSEC
22913 		 * processing. Follow the same old path. But this
22914 		 * time, ip_wput or ire_add_then_send will call us
22915 		 * directly as all the IPSEC operations are done.
22916 		 */
22917 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22918 		mp->b_prev = NULL;
22919 		mp->b_next = NULL;
22920 
22921 		/*
22922 		 * If the IPsec packet was processed asynchronously,
22923 		 * drop it now.
22924 		 */
22925 		if (q == NULL) {
22926 			if (ill_need_rele)
22927 				ill_refrele(ill);
22928 			freemsg(ipsec_mp);
22929 			return;
22930 		}
22931 
22932 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22933 		    zoneid);
22934 	}
22935 	if (ill != NULL && ill_need_rele)
22936 		ill_refrele(ill);
22937 	return;
22938 send:
22939 	if (ill != NULL && ill_need_rele)
22940 		ill_refrele(ill);
22941 
22942 	/* Local delivery */
22943 	if (ire->ire_stq == NULL) {
22944 		ASSERT(q != NULL);
22945 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22946 		    ire, 0);
22947 		if (ire_need_rele)
22948 			ire_refrele(ire);
22949 		return;
22950 	}
22951 	/*
22952 	 * Everything is done. Send it out on the wire.
22953 	 * We force the insertion of a fragment header using the
22954 	 * IPH_FRAG_HDR flag in two cases:
22955 	 * - after reception of an ICMPv6 "packet too big" message
22956 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22957 	 * - for multirouted IPv6 packets, so that the receiver can
22958 	 *   discard duplicates according to their fragment identifier
22959 	 */
22960 	/* XXX fix flow control problems. */
22961 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22962 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22963 		if (hwaccel) {
22964 			/*
22965 			 * hardware acceleration does not handle these
22966 			 * "slow path" cases.
22967 			 */
22968 			/* IPsec KSTATS: should bump bean counter here. */
22969 			if (ire_need_rele)
22970 				ire_refrele(ire);
22971 			freemsg(ipsec_mp);
22972 			return;
22973 		}
22974 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22975 		    (mp->b_cont ? msgdsize(mp) :
22976 		    mp->b_wptr - (uchar_t *)ip6h)) {
22977 			/* IPsec KSTATS: should bump bean counter here. */
22978 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22979 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22980 			    msgdsize(mp)));
22981 			if (ire_need_rele)
22982 				ire_refrele(ire);
22983 			freemsg(ipsec_mp);
22984 			return;
22985 		}
22986 		ASSERT(mp->b_prev == NULL);
22987 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22988 		    ntohs(ip6h->ip6_plen) +
22989 		    IPV6_HDR_LEN, ire->ire_max_frag));
22990 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22991 		    ire->ire_max_frag);
22992 	} else {
22993 		UPDATE_OB_PKT_COUNT(ire);
22994 		ire->ire_last_used_time = lbolt;
22995 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22996 	}
22997 	if (ire_need_rele)
22998 		ire_refrele(ire);
22999 	freeb(ipsec_mp);
23000 }
23001 
23002 void
23003 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23004 {
23005 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23006 	da_ipsec_t *hada;	/* data attributes */
23007 	ill_t *ill = (ill_t *)q->q_ptr;
23008 
23009 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23010 
23011 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23012 		/* IPsec KSTATS: Bump lose counter here! */
23013 		freemsg(mp);
23014 		return;
23015 	}
23016 
23017 	/*
23018 	 * It's an IPsec packet that must be
23019 	 * accelerated by the Provider, and the
23020 	 * outbound ill is IPsec acceleration capable.
23021 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23022 	 * to the ill.
23023 	 * IPsec KSTATS: should bump packet counter here.
23024 	 */
23025 
23026 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23027 	if (hada_mp == NULL) {
23028 		/* IPsec KSTATS: should bump packet counter here. */
23029 		freemsg(mp);
23030 		return;
23031 	}
23032 
23033 	hada_mp->b_datap->db_type = M_CTL;
23034 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23035 	hada_mp->b_cont = mp;
23036 
23037 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23038 	bzero(hada, sizeof (da_ipsec_t));
23039 	hada->da_type = IPHADA_M_CTL;
23040 
23041 	putnext(q, hada_mp);
23042 }
23043 
23044 /*
23045  * Finish the outbound IPsec processing. This function is called from
23046  * ipsec_out_process() if the IPsec packet was processed
23047  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23048  * asynchronously.
23049  */
23050 void
23051 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23052     ire_t *ire_arg)
23053 {
23054 	uint32_t v_hlen_tos_len;
23055 	ipaddr_t	dst;
23056 	ipif_t	*ipif = NULL;
23057 	ire_t *ire;
23058 	ire_t *ire1 = NULL;
23059 	mblk_t *next_mp = NULL;
23060 	uint32_t max_frag;
23061 	boolean_t multirt_send = B_FALSE;
23062 	mblk_t *mp;
23063 	mblk_t *mp1;
23064 	uint_t	ill_index;
23065 	ipsec_out_t *io;
23066 	boolean_t attach_if;
23067 	int match_flags, offset;
23068 	irb_t *irb = NULL;
23069 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23070 	zoneid_t zoneid;
23071 	uint32_t cksum;
23072 	uint16_t *up;
23073 #ifdef	_BIG_ENDIAN
23074 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23075 #else
23076 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23077 #endif
23078 
23079 	mp = ipsec_mp->b_cont;
23080 	ASSERT(mp != NULL);
23081 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23082 	dst = ipha->ipha_dst;
23083 
23084 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23085 	ill_index = io->ipsec_out_ill_index;
23086 	attach_if = io->ipsec_out_attach_if;
23087 	zoneid = io->ipsec_out_zoneid;
23088 	ASSERT(zoneid != ALL_ZONES);
23089 	match_flags = MATCH_IRE_ILL_GROUP;
23090 	if (ill_index != 0) {
23091 		if (ill == NULL) {
23092 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23093 			    ill_index, B_FALSE);
23094 
23095 			/* Failure case frees things for us. */
23096 			if (ill == NULL)
23097 				return;
23098 
23099 			ill_need_rele = B_TRUE;
23100 		}
23101 		/*
23102 		 * If this packet needs to go out on a particular interface
23103 		 * honor it.
23104 		 */
23105 		if (attach_if) {
23106 			match_flags = MATCH_IRE_ILL;
23107 
23108 			/*
23109 			 * Check if we need an ire that will not be
23110 			 * looked up by anybody else i.e. HIDDEN.
23111 			 */
23112 			if (ill_is_probeonly(ill)) {
23113 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23114 			}
23115 		}
23116 	}
23117 
23118 	if (CLASSD(dst)) {
23119 		boolean_t conn_dontroute;
23120 		/*
23121 		 * Use the ill_index to get the right ipif.
23122 		 */
23123 		conn_dontroute = io->ipsec_out_dontroute;
23124 		if (ill_index == 0)
23125 			ipif = ipif_lookup_group(dst, zoneid);
23126 		else
23127 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23128 		if (ipif == NULL) {
23129 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23130 			    " multicast\n"));
23131 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23132 			freemsg(ipsec_mp);
23133 			goto done;
23134 		}
23135 		/*
23136 		 * ipha_src has already been intialized with the
23137 		 * value of the ipif in ip_wput. All we need now is
23138 		 * an ire to send this downstream.
23139 		 */
23140 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
23141 		if (ire != NULL) {
23142 			ill_t *ill1;
23143 			/*
23144 			 * Do the multicast forwarding now, as the IPSEC
23145 			 * processing has been done.
23146 			 */
23147 			if (ip_g_mrouter && !conn_dontroute &&
23148 			    (ill1 = ire_to_ill(ire))) {
23149 				if (ip_mforward(ill1, ipha, mp)) {
23150 					freemsg(ipsec_mp);
23151 					ip1dbg(("ip_wput_ipsec_out: mforward "
23152 					    "failed\n"));
23153 					ire_refrele(ire);
23154 					goto done;
23155 				}
23156 			}
23157 			goto send;
23158 		}
23159 
23160 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23161 		mp->b_prev = NULL;
23162 		mp->b_next = NULL;
23163 
23164 		/*
23165 		 * If the IPsec packet was processed asynchronously,
23166 		 * drop it now.
23167 		 */
23168 		if (q == NULL) {
23169 			freemsg(ipsec_mp);
23170 			goto done;
23171 		}
23172 
23173 		/*
23174 		 * We may be using a wrong ipif to create the ire.
23175 		 * But it is okay as the source address is assigned
23176 		 * for the packet already. Next outbound packet would
23177 		 * create the IRE with the right IPIF in ip_wput.
23178 		 *
23179 		 * Also handle RTF_MULTIRT routes.
23180 		 */
23181 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
23182 	} else {
23183 		if (attach_if) {
23184 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
23185 			    zoneid, match_flags);
23186 		} else {
23187 			if (ire_arg != NULL) {
23188 				ire = ire_arg;
23189 				ire_need_rele = B_FALSE;
23190 			} else {
23191 				ire = ire_cache_lookup(dst, zoneid);
23192 			}
23193 		}
23194 		if (ire != NULL) {
23195 			goto send;
23196 		}
23197 
23198 		/*
23199 		 * ire disappeared underneath.
23200 		 *
23201 		 * What we need to do here is the ip_newroute
23202 		 * logic to get the ire without doing the IPSEC
23203 		 * processing. Follow the same old path. But this
23204 		 * time, ip_wput or ire_add_then_put will call us
23205 		 * directly as all the IPSEC operations are done.
23206 		 */
23207 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
23208 		mp->b_prev = NULL;
23209 		mp->b_next = NULL;
23210 
23211 		/*
23212 		 * If the IPsec packet was processed asynchronously,
23213 		 * drop it now.
23214 		 */
23215 		if (q == NULL) {
23216 			freemsg(ipsec_mp);
23217 			goto done;
23218 		}
23219 
23220 		/*
23221 		 * Since we're going through ip_newroute() again, we
23222 		 * need to make sure we don't:
23223 		 *
23224 		 *	1.) Trigger the ASSERT() with the ipha_ident
23225 		 *	    overloading.
23226 		 *	2.) Redo transport-layer checksumming, since we've
23227 		 *	    already done all that to get this far.
23228 		 *
23229 		 * The easiest way not do either of the above is to set
23230 		 * the ipha_ident field to IP_HDR_INCLUDED.
23231 		 */
23232 		ipha->ipha_ident = IP_HDR_INCLUDED;
23233 		ip_newroute(q, ipsec_mp, dst, NULL,
23234 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
23235 	}
23236 	goto done;
23237 send:
23238 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
23239 		/*
23240 		 * ESP NAT-Traversal packet.
23241 		 *
23242 		 * Just do software checksum for now.
23243 		 */
23244 
23245 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
23246 		IP_STAT(ip_out_sw_cksum);
23247 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
23248 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
23249 #define	iphs	((uint16_t *)ipha)
23250 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
23251 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
23252 		    IP_SIMPLE_HDR_LENGTH);
23253 #undef iphs
23254 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
23255 			cksum = 0xFFFF;
23256 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
23257 			if (mp1->b_wptr - mp1->b_rptr >=
23258 			    offset + sizeof (uint16_t)) {
23259 				up = (uint16_t *)(mp1->b_rptr + offset);
23260 				*up = cksum;
23261 				break;	/* out of for loop */
23262 			} else {
23263 				offset -= (mp->b_wptr - mp->b_rptr);
23264 			}
23265 	} /* Otherwise, just keep the all-zero checksum. */
23266 
23267 	if (ire->ire_stq == NULL) {
23268 		/*
23269 		 * Loopbacks go through ip_wput_local except for one case.
23270 		 * We come here if we generate a icmp_frag_needed message
23271 		 * after IPSEC processing is over. When this function calls
23272 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
23273 		 * icmp_frag_needed. The message generated comes back here
23274 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
23275 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
23276 		 * source address as it is usually set in ip_wput_ire. As
23277 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
23278 		 * and we end up here. We can't enter ip_wput_ire once the
23279 		 * IPSEC processing is over and hence we need to do it here.
23280 		 */
23281 		ASSERT(q != NULL);
23282 		UPDATE_OB_PKT_COUNT(ire);
23283 		ire->ire_last_used_time = lbolt;
23284 		if (ipha->ipha_src == 0)
23285 			ipha->ipha_src = ire->ire_src_addr;
23286 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
23287 		    ire, 0, zoneid);
23288 		if (ire_need_rele)
23289 			ire_refrele(ire);
23290 		goto done;
23291 	}
23292 
23293 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
23294 		/*
23295 		 * We are through with IPSEC processing.
23296 		 * Fragment this and send it on the wire.
23297 		 */
23298 		if (io->ipsec_out_accelerated) {
23299 			/*
23300 			 * The packet has been accelerated but must
23301 			 * be fragmented. This should not happen
23302 			 * since AH and ESP must not accelerate
23303 			 * packets that need fragmentation, however
23304 			 * the configuration could have changed
23305 			 * since the AH or ESP processing.
23306 			 * Drop packet.
23307 			 * IPsec KSTATS: bump bean counter here.
23308 			 */
23309 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
23310 			    "fragmented accelerated packet!\n"));
23311 			freemsg(ipsec_mp);
23312 		} else {
23313 			ip_wput_ire_fragmentit(ipsec_mp, ire);
23314 		}
23315 		if (ire_need_rele)
23316 			ire_refrele(ire);
23317 		goto done;
23318 	}
23319 
23320 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
23321 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
23322 	    (void *)ire->ire_ipif, (void *)ipif));
23323 
23324 	/*
23325 	 * Multiroute the secured packet, unless IPsec really
23326 	 * requires the packet to go out only through a particular
23327 	 * interface.
23328 	 */
23329 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
23330 		ire_t *first_ire;
23331 		irb = ire->ire_bucket;
23332 		ASSERT(irb != NULL);
23333 		/*
23334 		 * This ire has been looked up as the one that
23335 		 * goes through the given ipif;
23336 		 * make sure we do not omit any other multiroute ire
23337 		 * that may be present in the bucket before this one.
23338 		 */
23339 		IRB_REFHOLD(irb);
23340 		for (first_ire = irb->irb_ire;
23341 		    first_ire != NULL;
23342 		    first_ire = first_ire->ire_next) {
23343 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23344 			    (first_ire->ire_addr == ire->ire_addr) &&
23345 			    !(first_ire->ire_marks &
23346 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23347 				break;
23348 		}
23349 
23350 		if ((first_ire != NULL) && (first_ire != ire)) {
23351 			/*
23352 			 * Don't change the ire if the packet must
23353 			 * be fragmented if sent via this new one.
23354 			 */
23355 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
23356 				IRE_REFHOLD(first_ire);
23357 				if (ire_need_rele)
23358 					ire_refrele(ire);
23359 				else
23360 					ire_need_rele = B_TRUE;
23361 				ire = first_ire;
23362 			}
23363 		}
23364 		IRB_REFRELE(irb);
23365 
23366 		multirt_send = B_TRUE;
23367 		max_frag = ire->ire_max_frag;
23368 	} else {
23369 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
23370 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
23371 			    "flag, attach_if %d\n", attach_if));
23372 		}
23373 	}
23374 
23375 	/*
23376 	 * In most cases, the emission loop below is entered only once.
23377 	 * Only in the case where the ire holds the RTF_MULTIRT
23378 	 * flag, we loop to process all RTF_MULTIRT ires in the
23379 	 * bucket, and send the packet through all crossed
23380 	 * RTF_MULTIRT routes.
23381 	 */
23382 	do {
23383 		if (multirt_send) {
23384 			/*
23385 			 * ire1 holds here the next ire to process in the
23386 			 * bucket. If multirouting is expected,
23387 			 * any non-RTF_MULTIRT ire that has the
23388 			 * right destination address is ignored.
23389 			 */
23390 			ASSERT(irb != NULL);
23391 			IRB_REFHOLD(irb);
23392 			for (ire1 = ire->ire_next;
23393 			    ire1 != NULL;
23394 			    ire1 = ire1->ire_next) {
23395 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23396 					continue;
23397 				if (ire1->ire_addr != ire->ire_addr)
23398 					continue;
23399 				if (ire1->ire_marks &
23400 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23401 					continue;
23402 				/* No loopback here */
23403 				if (ire1->ire_stq == NULL)
23404 					continue;
23405 				/*
23406 				 * Ensure we do not exceed the MTU
23407 				 * of the next route.
23408 				 */
23409 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
23410 					ip_multirt_bad_mtu(ire1, max_frag);
23411 					continue;
23412 				}
23413 
23414 				IRE_REFHOLD(ire1);
23415 				break;
23416 			}
23417 			IRB_REFRELE(irb);
23418 			if (ire1 != NULL) {
23419 				/*
23420 				 * We are in a multiple send case, need to
23421 				 * make a copy of the packet.
23422 				 */
23423 				next_mp = copymsg(ipsec_mp);
23424 				if (next_mp == NULL) {
23425 					ire_refrele(ire1);
23426 					ire1 = NULL;
23427 				}
23428 			}
23429 		}
23430 
23431 		/* Everything is done. Send it out on the wire */
23432 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
23433 		if (mp1 == NULL) {
23434 			BUMP_MIB(&ip_mib, ipOutDiscards);
23435 			freemsg(ipsec_mp);
23436 			if (ire_need_rele)
23437 				ire_refrele(ire);
23438 			if (ire1 != NULL) {
23439 				ire_refrele(ire1);
23440 				freemsg(next_mp);
23441 			}
23442 			goto done;
23443 		}
23444 		UPDATE_OB_PKT_COUNT(ire);
23445 		ire->ire_last_used_time = lbolt;
23446 		if (!io->ipsec_out_accelerated) {
23447 			putnext(ire->ire_stq, mp1);
23448 		} else {
23449 			/*
23450 			 * Safety Pup says: make sure this is going to
23451 			 * the right interface!
23452 			 */
23453 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
23454 			int ifindex = ill1->ill_phyint->phyint_ifindex;
23455 
23456 			if (ifindex != io->ipsec_out_capab_ill_index) {
23457 				/* IPsec kstats: bump lose counter */
23458 				freemsg(mp1);
23459 			} else {
23460 				ipsec_hw_putnext(ire->ire_stq, mp1);
23461 			}
23462 		}
23463 
23464 		freeb(ipsec_mp);
23465 		if (ire_need_rele)
23466 			ire_refrele(ire);
23467 
23468 		if (ire1 != NULL) {
23469 			ire = ire1;
23470 			ire_need_rele = B_TRUE;
23471 			ASSERT(next_mp);
23472 			ipsec_mp = next_mp;
23473 			mp = ipsec_mp->b_cont;
23474 			ire1 = NULL;
23475 			next_mp = NULL;
23476 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
23477 		} else {
23478 			multirt_send = B_FALSE;
23479 		}
23480 	} while (multirt_send);
23481 done:
23482 	if (ill != NULL && ill_need_rele)
23483 		ill_refrele(ill);
23484 	if (ipif != NULL)
23485 		ipif_refrele(ipif);
23486 }
23487 
23488 /*
23489  * Get the ill corresponding to the specified ire, and compare its
23490  * capabilities with the protocol and algorithms specified by the
23491  * the SA obtained from ipsec_out. If they match, annotate the
23492  * ipsec_out structure to indicate that the packet needs acceleration.
23493  *
23494  *
23495  * A packet is eligible for outbound hardware acceleration if the
23496  * following conditions are satisfied:
23497  *
23498  * 1. the packet will not be fragmented
23499  * 2. the provider supports the algorithm
23500  * 3. there is no pending control message being exchanged
23501  * 4. snoop is not attached
23502  * 5. the destination address is not a broadcast or multicast address.
23503  *
23504  * Rationale:
23505  *	- Hardware drivers do not support fragmentation with
23506  *	  the current interface.
23507  *	- snoop, multicast, and broadcast may result in exposure of
23508  *	  a cleartext datagram.
23509  * We check all five of these conditions here.
23510  *
23511  * XXX would like to nuke "ire_t *" parameter here; problem is that
23512  * IRE is only way to figure out if a v4 address is a broadcast and
23513  * thus ineligible for acceleration...
23514  */
23515 static void
23516 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23517 {
23518 	ipsec_out_t *io;
23519 	mblk_t *data_mp;
23520 	uint_t plen, overhead;
23521 
23522 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23523 		return;
23524 
23525 	if (ill == NULL)
23526 		return;
23527 
23528 	/*
23529 	 * Destination address is a broadcast or multicast.  Punt.
23530 	 */
23531 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23532 	    IRE_LOCAL)))
23533 		return;
23534 
23535 	data_mp = ipsec_mp->b_cont;
23536 
23537 	if (ill->ill_isv6) {
23538 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23539 
23540 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23541 			return;
23542 
23543 		plen = ip6h->ip6_plen;
23544 	} else {
23545 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23546 
23547 		if (CLASSD(ipha->ipha_dst))
23548 			return;
23549 
23550 		plen = ipha->ipha_length;
23551 	}
23552 	/*
23553 	 * Is there a pending DLPI control message being exchanged
23554 	 * between IP/IPsec and the DLS Provider? If there is, it
23555 	 * could be a SADB update, and the state of the DLS Provider
23556 	 * SADB might not be in sync with the SADB maintained by
23557 	 * IPsec. To avoid dropping packets or using the wrong keying
23558 	 * material, we do not accelerate this packet.
23559 	 */
23560 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23561 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23562 		    "ill_dlpi_pending! don't accelerate packet\n"));
23563 		return;
23564 	}
23565 
23566 	/*
23567 	 * Is the Provider in promiscous mode? If it does, we don't
23568 	 * accelerate the packet since it will bounce back up to the
23569 	 * listeners in the clear.
23570 	 */
23571 	if (ill->ill_promisc_on_phys) {
23572 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23573 		    "ill in promiscous mode, don't accelerate packet\n"));
23574 		return;
23575 	}
23576 
23577 	/*
23578 	 * Will the packet require fragmentation?
23579 	 */
23580 
23581 	/*
23582 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23583 	 * as is used elsewhere.
23584 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23585 	 *	+ 2-byte trailer
23586 	 */
23587 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23588 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23589 
23590 	if ((plen + overhead) > ill->ill_max_mtu)
23591 		return;
23592 
23593 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23594 
23595 	/*
23596 	 * Can the ill accelerate this IPsec protocol and algorithm
23597 	 * specified by the SA?
23598 	 */
23599 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23600 	    ill->ill_isv6, sa)) {
23601 		return;
23602 	}
23603 
23604 	/*
23605 	 * Tell AH or ESP that the outbound ill is capable of
23606 	 * accelerating this packet.
23607 	 */
23608 	io->ipsec_out_is_capab_ill = B_TRUE;
23609 }
23610 
23611 /*
23612  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23613  *
23614  * If this function returns B_TRUE, the requested SA's have been filled
23615  * into the ipsec_out_*_sa pointers.
23616  *
23617  * If the function returns B_FALSE, the packet has been "consumed", most
23618  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23619  *
23620  * The SA references created by the protocol-specific "select"
23621  * function will be released when the ipsec_mp is freed, thanks to the
23622  * ipsec_out_free destructor -- see spd.c.
23623  */
23624 static boolean_t
23625 ipsec_out_select_sa(mblk_t *ipsec_mp)
23626 {
23627 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23628 	ipsec_out_t *io;
23629 	ipsec_policy_t *pp;
23630 	ipsec_action_t *ap;
23631 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23632 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23633 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23634 
23635 	if (!io->ipsec_out_secure) {
23636 		/*
23637 		 * We came here by mistake.
23638 		 * Don't bother with ipsec processing
23639 		 * We should "discourage" this path in the future.
23640 		 */
23641 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23642 		return (B_FALSE);
23643 	}
23644 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23645 	ASSERT((io->ipsec_out_policy != NULL) ||
23646 	    (io->ipsec_out_act != NULL));
23647 
23648 	ASSERT(io->ipsec_out_failed == B_FALSE);
23649 
23650 	/*
23651 	 * IPSEC processing has started.
23652 	 */
23653 	io->ipsec_out_proc_begin = B_TRUE;
23654 	ap = io->ipsec_out_act;
23655 	if (ap == NULL) {
23656 		pp = io->ipsec_out_policy;
23657 		ASSERT(pp != NULL);
23658 		ap = pp->ipsp_act;
23659 		ASSERT(ap != NULL);
23660 	}
23661 
23662 	/*
23663 	 * We have an action.  now, let's select SA's.
23664 	 * (In the future, we can cache this in the conn_t..)
23665 	 */
23666 	if (ap->ipa_want_esp) {
23667 		if (io->ipsec_out_esp_sa == NULL) {
23668 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23669 			    IPPROTO_ESP);
23670 		}
23671 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23672 	}
23673 
23674 	if (ap->ipa_want_ah) {
23675 		if (io->ipsec_out_ah_sa == NULL) {
23676 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23677 			    IPPROTO_AH);
23678 		}
23679 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23680 		/*
23681 		 * The ESP and AH processing order needs to be preserved
23682 		 * when both protocols are required (ESP should be applied
23683 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23684 		 * when both ESP and AH are required, and an AH ACQUIRE
23685 		 * is needed.
23686 		 */
23687 		if (ap->ipa_want_esp && need_ah_acquire)
23688 			need_esp_acquire = B_TRUE;
23689 	}
23690 
23691 	/*
23692 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23693 	 * Release SAs that got referenced, but will not be used until we
23694 	 * acquire _all_ of the SAs we need.
23695 	 */
23696 	if (need_ah_acquire || need_esp_acquire) {
23697 		if (io->ipsec_out_ah_sa != NULL) {
23698 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23699 			io->ipsec_out_ah_sa = NULL;
23700 		}
23701 		if (io->ipsec_out_esp_sa != NULL) {
23702 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23703 			io->ipsec_out_esp_sa = NULL;
23704 		}
23705 
23706 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23707 		return (B_FALSE);
23708 	}
23709 
23710 	return (B_TRUE);
23711 }
23712 
23713 /*
23714  * Process an IPSEC_OUT message and see what you can
23715  * do with it.
23716  * IPQoS Notes:
23717  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23718  * IPSec.
23719  * XXX would like to nuke ire_t.
23720  * XXX ill_index better be "real"
23721  */
23722 void
23723 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23724 {
23725 	ipsec_out_t *io;
23726 	ipsec_policy_t *pp;
23727 	ipsec_action_t *ap;
23728 	ipha_t *ipha;
23729 	ip6_t *ip6h;
23730 	mblk_t *mp;
23731 	ill_t *ill;
23732 	zoneid_t zoneid;
23733 	ipsec_status_t ipsec_rc;
23734 	boolean_t ill_need_rele = B_FALSE;
23735 
23736 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23737 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23738 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23739 	mp = ipsec_mp->b_cont;
23740 
23741 	/*
23742 	 * Initiate IPPF processing. We do it here to account for packets
23743 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23744 	 * We can check for ipsec_out_proc_begin even for such packets, as
23745 	 * they will always be false (asserted below).
23746 	 */
23747 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23748 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23749 		    io->ipsec_out_ill_index : ill_index);
23750 		if (mp == NULL) {
23751 			ip2dbg(("ipsec_out_process: packet dropped "\
23752 			    "during IPPF processing\n"));
23753 			freeb(ipsec_mp);
23754 			BUMP_MIB(&ip_mib, ipOutDiscards);
23755 			return;
23756 		}
23757 	}
23758 
23759 	if (!io->ipsec_out_secure) {
23760 		/*
23761 		 * We came here by mistake.
23762 		 * Don't bother with ipsec processing
23763 		 * Should "discourage" this path in the future.
23764 		 */
23765 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23766 		goto done;
23767 	}
23768 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23769 	ASSERT((io->ipsec_out_policy != NULL) ||
23770 	    (io->ipsec_out_act != NULL));
23771 	ASSERT(io->ipsec_out_failed == B_FALSE);
23772 
23773 	if (!ipsec_loaded()) {
23774 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23775 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23776 			BUMP_MIB(&ip_mib, ipOutDiscards);
23777 		} else {
23778 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23779 		}
23780 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23781 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23782 		return;
23783 	}
23784 
23785 	/*
23786 	 * IPSEC processing has started.
23787 	 */
23788 	io->ipsec_out_proc_begin = B_TRUE;
23789 	ap = io->ipsec_out_act;
23790 	if (ap == NULL) {
23791 		pp = io->ipsec_out_policy;
23792 		ASSERT(pp != NULL);
23793 		ap = pp->ipsp_act;
23794 		ASSERT(ap != NULL);
23795 	}
23796 
23797 	/*
23798 	 * Save the outbound ill index. When the packet comes back
23799 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23800 	 * before sending it the accelerated packet.
23801 	 */
23802 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23803 		int ifindex;
23804 		ill = ire_to_ill(ire);
23805 		ifindex = ill->ill_phyint->phyint_ifindex;
23806 		io->ipsec_out_capab_ill_index = ifindex;
23807 	}
23808 
23809 	/*
23810 	 * The order of processing is first insert a IP header if needed.
23811 	 * Then insert the ESP header and then the AH header.
23812 	 */
23813 	if ((io->ipsec_out_se_done == B_FALSE) &&
23814 	    (ap->ipa_want_se)) {
23815 		/*
23816 		 * First get the outer IP header before sending
23817 		 * it to ESP.
23818 		 */
23819 		ipha_t *oipha, *iipha;
23820 		mblk_t *outer_mp, *inner_mp;
23821 
23822 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23823 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23824 			    "ipsec_out_process: "
23825 			    "Self-Encapsulation failed: Out of memory\n");
23826 			freemsg(ipsec_mp);
23827 			BUMP_MIB(&ip_mib, ipOutDiscards);
23828 			return;
23829 		}
23830 		inner_mp = ipsec_mp->b_cont;
23831 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23832 		oipha = (ipha_t *)outer_mp->b_rptr;
23833 		iipha = (ipha_t *)inner_mp->b_rptr;
23834 		*oipha = *iipha;
23835 		outer_mp->b_wptr += sizeof (ipha_t);
23836 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23837 		    sizeof (ipha_t));
23838 		oipha->ipha_protocol = IPPROTO_ENCAP;
23839 		oipha->ipha_version_and_hdr_length =
23840 		    IP_SIMPLE_HDR_VERSION;
23841 		oipha->ipha_hdr_checksum = 0;
23842 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23843 		outer_mp->b_cont = inner_mp;
23844 		ipsec_mp->b_cont = outer_mp;
23845 
23846 		io->ipsec_out_se_done = B_TRUE;
23847 		io->ipsec_out_encaps = B_TRUE;
23848 	}
23849 
23850 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23851 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23852 	    !ipsec_out_select_sa(ipsec_mp))
23853 		return;
23854 
23855 	/*
23856 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23857 	 * to do the heavy lifting.
23858 	 */
23859 	zoneid = io->ipsec_out_zoneid;
23860 	ASSERT(zoneid != ALL_ZONES);
23861 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23862 		ASSERT(io->ipsec_out_esp_sa != NULL);
23863 		io->ipsec_out_esp_done = B_TRUE;
23864 		/*
23865 		 * Note that since hw accel can only apply one transform,
23866 		 * not two, we skip hw accel for ESP if we also have AH
23867 		 * This is an design limitation of the interface
23868 		 * which should be revisited.
23869 		 */
23870 		ASSERT(ire != NULL);
23871 		if (io->ipsec_out_ah_sa == NULL) {
23872 			ill = (ill_t *)ire->ire_stq->q_ptr;
23873 			ipsec_out_is_accelerated(ipsec_mp,
23874 			    io->ipsec_out_esp_sa, ill, ire);
23875 		}
23876 
23877 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23878 		switch (ipsec_rc) {
23879 		case IPSEC_STATUS_SUCCESS:
23880 			break;
23881 		case IPSEC_STATUS_FAILED:
23882 			BUMP_MIB(&ip_mib, ipOutDiscards);
23883 			/* FALLTHRU */
23884 		case IPSEC_STATUS_PENDING:
23885 			return;
23886 		}
23887 	}
23888 
23889 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23890 		ASSERT(io->ipsec_out_ah_sa != NULL);
23891 		io->ipsec_out_ah_done = B_TRUE;
23892 		if (ire == NULL) {
23893 			int idx = io->ipsec_out_capab_ill_index;
23894 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23895 			    NULL, NULL, NULL, NULL);
23896 			ill_need_rele = B_TRUE;
23897 		} else {
23898 			ill = (ill_t *)ire->ire_stq->q_ptr;
23899 		}
23900 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23901 		    ire);
23902 
23903 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23904 		switch (ipsec_rc) {
23905 		case IPSEC_STATUS_SUCCESS:
23906 			break;
23907 		case IPSEC_STATUS_FAILED:
23908 			BUMP_MIB(&ip_mib, ipOutDiscards);
23909 			/* FALLTHRU */
23910 		case IPSEC_STATUS_PENDING:
23911 			if (ill != NULL && ill_need_rele)
23912 				ill_refrele(ill);
23913 			return;
23914 		}
23915 	}
23916 	/*
23917 	 * We are done with IPSEC processing. Send it over
23918 	 * the wire.
23919 	 */
23920 done:
23921 	mp = ipsec_mp->b_cont;
23922 	ipha = (ipha_t *)mp->b_rptr;
23923 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23924 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23925 	} else {
23926 		ip6h = (ip6_t *)ipha;
23927 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23928 	}
23929 	if (ill != NULL && ill_need_rele)
23930 		ill_refrele(ill);
23931 }
23932 
23933 /* ARGSUSED */
23934 void
23935 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23936 {
23937 	opt_restart_t	*or;
23938 	int	err;
23939 	conn_t	*connp;
23940 
23941 	ASSERT(CONN_Q(q));
23942 	connp = Q_TO_CONN(q);
23943 
23944 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23945 	or = (opt_restart_t *)first_mp->b_rptr;
23946 	/*
23947 	 * We don't need to pass any credentials here since this is just
23948 	 * a restart. The credentials are passed in when svr4_optcom_req
23949 	 * is called the first time (from ip_wput_nondata).
23950 	 */
23951 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23952 		err = svr4_optcom_req(q, first_mp, NULL,
23953 		    &ip_opt_obj);
23954 	} else {
23955 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23956 		err = tpi_optcom_req(q, first_mp, NULL,
23957 		    &ip_opt_obj);
23958 	}
23959 	if (err != EINPROGRESS) {
23960 		/* operation is done */
23961 		CONN_OPER_PENDING_DONE(connp);
23962 	}
23963 }
23964 
23965 /*
23966  * ioctls that go through a down/up sequence may need to wait for the down
23967  * to complete. This involves waiting for the ire and ipif refcnts to go down
23968  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23969  */
23970 /* ARGSUSED */
23971 void
23972 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23973 {
23974 	struct iocblk *iocp;
23975 	mblk_t *mp1;
23976 	ipif_t	*ipif;
23977 	ip_ioctl_cmd_t *ipip;
23978 	int err;
23979 	sin_t	*sin;
23980 	struct lifreq *lifr;
23981 	struct ifreq *ifr;
23982 
23983 	iocp = (struct iocblk *)mp->b_rptr;
23984 	ASSERT(ipsq != NULL);
23985 	/* Existence of mp1 verified in ip_wput_nondata */
23986 	mp1 = mp->b_cont->b_cont;
23987 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23988 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23989 		ill_t *ill;
23990 		/*
23991 		 * Special case where ipsq_current_ipif may not be set.
23992 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23993 		 * ill could also have become part of a ipmp group in the
23994 		 * process, we are here as were not able to complete the
23995 		 * operation in ipif_set_values because we could not become
23996 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23997 		 * will not be set so we need to set it.
23998 		 */
23999 		ill = (ill_t *)q->q_ptr;
24000 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24001 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24002 	}
24003 
24004 	ipif = ipsq->ipsq_current_ipif;
24005 	ASSERT(ipif != NULL);
24006 	if (ipip->ipi_cmd_type == IF_CMD) {
24007 		/* This a old style SIOC[GS]IF* command */
24008 		ifr = (struct ifreq *)mp1->b_rptr;
24009 		sin = (sin_t *)&ifr->ifr_addr;
24010 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24011 		/* This a new style SIOC[GS]LIF* command */
24012 		lifr = (struct lifreq *)mp1->b_rptr;
24013 		sin = (sin_t *)&lifr->lifr_addr;
24014 	} else {
24015 		sin = NULL;
24016 	}
24017 
24018 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24019 	    (void *)mp1->b_rptr);
24020 
24021 	/* SIOCLIFREMOVEIF could have removed the ipif */
24022 	ip_ioctl_finish(q, mp, err,
24023 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24024 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24025 }
24026 
24027 /*
24028  * ioctl processing
24029  *
24030  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24031  * the ioctl command in the ioctl tables and determines the copyin data size
24032  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24033  * size.
24034  *
24035  * ioctl processing then continues when the M_IOCDATA makes its way down.
24036  * Now the ioctl is looked up again in the ioctl table, and its properties are
24037  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24038  * and the general ioctl processing function ip_process_ioctl is called.
24039  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24040  * so goes thru the serialization primitive ipsq_try_enter. Then the
24041  * appropriate function to handle the ioctl is called based on the entry in
24042  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24043  * which also refreleases the 'conn' that was refheld at the start of the
24044  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24045  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24046  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24047  *
24048  * Many exclusive ioctls go thru an internal down up sequence as part of
24049  * the operation. For example an attempt to change the IP address of an
24050  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24051  * does all the cleanup such as deleting all ires that use this address.
24052  * Then we need to wait till all references to the interface go away.
24053  */
24054 void
24055 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24056 {
24057 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24058 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24059 	cmd_info_t ci;
24060 	int err;
24061 	boolean_t entered_ipsq = B_FALSE;
24062 
24063 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24064 
24065 	if (ipip == NULL)
24066 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24067 
24068 	/*
24069 	 * SIOCLIFADDIF needs to go thru a special path since the
24070 	 * ill may not exist yet. This happens in the case of lo0
24071 	 * which is created using this ioctl.
24072 	 */
24073 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24074 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24075 		ip_ioctl_finish(q, mp, err,
24076 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24077 		    NULL, NULL);
24078 		return;
24079 	}
24080 
24081 	ci.ci_ipif = NULL;
24082 	switch (ipip->ipi_cmd_type) {
24083 	case IF_CMD:
24084 	case LIF_CMD:
24085 		/*
24086 		 * ioctls that pass in a [l]ifreq appear here.
24087 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24088 		 * ci.ci_ipif
24089 		 */
24090 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24091 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24092 		if (err != 0) {
24093 			ip_ioctl_finish(q, mp, err,
24094 			    ipip->ipi_flags & IPI_GET_CMD ?
24095 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24096 			return;
24097 		}
24098 		ASSERT(ci.ci_ipif != NULL);
24099 		break;
24100 
24101 	case TUN_CMD:
24102 		/*
24103 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24104 		 * a refheld ipif in ci.ci_ipif
24105 		 */
24106 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24107 		if (err != 0) {
24108 			ip_ioctl_finish(q, mp, err,
24109 			    ipip->ipi_flags & IPI_GET_CMD ?
24110 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24111 			return;
24112 		}
24113 		ASSERT(ci.ci_ipif != NULL);
24114 		break;
24115 
24116 	case MISC_CMD:
24117 		/*
24118 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24119 		 * For eg. SIOCGLIFCONF will appear here.
24120 		 */
24121 		switch (ipip->ipi_cmd) {
24122 		case IF_UNITSEL:
24123 			/* ioctl comes down the ill */
24124 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24125 			ipif_refhold(ci.ci_ipif);
24126 			break;
24127 		case SIOCGMSFILTER:
24128 		case SIOCSMSFILTER:
24129 		case SIOCGIPMSFILTER:
24130 		case SIOCSIPMSFILTER:
24131 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24132 			    ip_process_ioctl);
24133 			if (err != 0) {
24134 				ip_ioctl_finish(q, mp, err,
24135 				    ipip->ipi_flags & IPI_GET_CMD ?
24136 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24137 				return;
24138 			}
24139 			break;
24140 		}
24141 		err = 0;
24142 		ci.ci_sin = NULL;
24143 		ci.ci_sin6 = NULL;
24144 		ci.ci_lifr = NULL;
24145 		break;
24146 	}
24147 
24148 	/*
24149 	 * If ipsq is non-null, we are already being called exclusively
24150 	 */
24151 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24152 	if (!(ipip->ipi_flags & IPI_WR)) {
24153 		/*
24154 		 * A return value of EINPROGRESS means the ioctl is
24155 		 * either queued and waiting for some reason or has
24156 		 * already completed.
24157 		 */
24158 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24159 		    ci.ci_lifr);
24160 		if (ci.ci_ipif != NULL)
24161 			ipif_refrele(ci.ci_ipif);
24162 		ip_ioctl_finish(q, mp, err,
24163 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24164 		    NULL, NULL);
24165 		return;
24166 	}
24167 
24168 	ASSERT(ci.ci_ipif != NULL);
24169 
24170 	if (ipsq == NULL) {
24171 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
24172 		    ip_process_ioctl, NEW_OP, B_TRUE);
24173 		entered_ipsq = B_TRUE;
24174 	}
24175 	/*
24176 	 * Release the ipif so that ipif_down and friends that wait for
24177 	 * references to go away are not misled about the current ipif_refcnt
24178 	 * values. We are writer so we can access the ipif even after releasing
24179 	 * the ipif.
24180 	 */
24181 	ipif_refrele(ci.ci_ipif);
24182 	if (ipsq == NULL)
24183 		return;
24184 
24185 	mutex_enter(&ipsq->ipsq_lock);
24186 	ASSERT(ipsq->ipsq_current_ipif == NULL);
24187 	ipsq->ipsq_current_ipif = ci.ci_ipif;
24188 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24189 	mutex_exit(&ipsq->ipsq_lock);
24190 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
24191 	/*
24192 	 * For most set ioctls that come here, this serves as a single point
24193 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
24194 	 * be any new references to the ipif. This helps functions that go
24195 	 * through this path and end up trying to wait for the refcnts
24196 	 * associated with the ipif to go down to zero. Some exceptions are
24197 	 * Failover, Failback, and Groupname commands that operate on more than
24198 	 * just the ci.ci_ipif. These commands internally determine the
24199 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
24200 	 * flags on that set. Another exception is the Removeif command that
24201 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
24202 	 * ipif to operate on.
24203 	 */
24204 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
24205 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
24206 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
24207 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
24208 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
24209 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
24210 
24211 	/*
24212 	 * A return value of EINPROGRESS means the ioctl is
24213 	 * either queued and waiting for some reason or has
24214 	 * already completed.
24215 	 */
24216 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24217 	    ci.ci_lifr);
24218 
24219 	/* SIOCLIFREMOVEIF could have removed the ipif */
24220 	ip_ioctl_finish(q, mp, err,
24221 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24222 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
24223 
24224 	if (entered_ipsq)
24225 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
24226 }
24227 
24228 /*
24229  * Complete the ioctl. Typically ioctls use the mi package and need to
24230  * do mi_copyout/mi_copy_done.
24231  */
24232 void
24233 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
24234     ipif_t *ipif, ipsq_t *ipsq)
24235 {
24236 	conn_t	*connp = NULL;
24237 
24238 	if (err == EINPROGRESS)
24239 		return;
24240 
24241 	if (CONN_Q(q)) {
24242 		connp = Q_TO_CONN(q);
24243 		ASSERT(connp->conn_ref >= 2);
24244 	}
24245 
24246 	switch (mode) {
24247 	case COPYOUT:
24248 		if (err == 0)
24249 			mi_copyout(q, mp);
24250 		else
24251 			mi_copy_done(q, mp, err);
24252 		break;
24253 
24254 	case NO_COPYOUT:
24255 		mi_copy_done(q, mp, err);
24256 		break;
24257 
24258 	default:
24259 		/* An ioctl aborted through a conn close would take this path */
24260 		break;
24261 	}
24262 
24263 	/*
24264 	 * The refhold placed at the start of the ioctl is released here.
24265 	 */
24266 	if (connp != NULL)
24267 		CONN_OPER_PENDING_DONE(connp);
24268 
24269 	/*
24270 	 * If the ioctl were an exclusive ioctl it would have set
24271 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
24272 	 */
24273 	if (ipif != NULL) {
24274 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
24275 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
24276 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
24277 	}
24278 
24279 	/*
24280 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
24281 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
24282 	 * entering the ipsq
24283 	 */
24284 	if (ipsq != NULL) {
24285 		mutex_enter(&ipsq->ipsq_lock);
24286 		ipsq->ipsq_current_ipif = NULL;
24287 		mutex_exit(&ipsq->ipsq_lock);
24288 	}
24289 }
24290 
24291 /*
24292  * This is called from ip_wput_nondata to resume a deferred TCP bind.
24293  */
24294 /* ARGSUSED */
24295 void
24296 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
24297 {
24298 	conn_t *connp = arg;
24299 	tcp_t	*tcp;
24300 
24301 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
24302 	tcp = connp->conn_tcp;
24303 
24304 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
24305 		freemsg(mp);
24306 	else
24307 		tcp_rput_other(tcp, mp);
24308 	CONN_OPER_PENDING_DONE(connp);
24309 }
24310 
24311 /* Called from ip_wput for all non data messages */
24312 /* ARGSUSED */
24313 void
24314 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24315 {
24316 	mblk_t		*mp1;
24317 	ire_t		*ire;
24318 	ill_t		*ill;
24319 	struct iocblk	*iocp;
24320 	ip_ioctl_cmd_t	*ipip;
24321 	cred_t		*cr;
24322 	conn_t		*connp = NULL;
24323 	int		cmd, err;
24324 
24325 	if (CONN_Q(q))
24326 		connp = Q_TO_CONN(q);
24327 
24328 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
24329 
24330 	/* Check if it is a queue to /dev/sctp. */
24331 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
24332 	    connp->conn_rq == NULL) {
24333 		sctp_wput(q, mp);
24334 		return;
24335 	}
24336 
24337 	switch (DB_TYPE(mp)) {
24338 	case M_IOCTL:
24339 		/*
24340 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
24341 		 * will arrange to copy in associated control structures.
24342 		 */
24343 		ip_sioctl_copyin_setup(q, mp);
24344 		return;
24345 	case M_IOCDATA:
24346 		/*
24347 		 * Ensure that this is associated with one of our trans-
24348 		 * parent ioctls.  If it's not ours, discard it if we're
24349 		 * running as a driver, or pass it on if we're a module.
24350 		 */
24351 		iocp = (struct iocblk *)mp->b_rptr;
24352 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24353 		if (ipip == NULL) {
24354 			if (q->q_next == NULL) {
24355 				goto nak;
24356 			} else {
24357 				putnext(q, mp);
24358 			}
24359 			return;
24360 		} else if ((q->q_next != NULL) &&
24361 		    !(ipip->ipi_flags & IPI_MODOK)) {
24362 			/*
24363 			 * the ioctl is one we recognise, but is not
24364 			 * consumed by IP as a module, pass M_IOCDATA
24365 			 * for processing downstream, but only for
24366 			 * common Streams ioctls.
24367 			 */
24368 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
24369 				putnext(q, mp);
24370 				return;
24371 			} else {
24372 				goto nak;
24373 			}
24374 		}
24375 
24376 		/* IOCTL continuation following copyin or copyout. */
24377 		if (mi_copy_state(q, mp, NULL) == -1) {
24378 			/*
24379 			 * The copy operation failed.  mi_copy_state already
24380 			 * cleaned up, so we're out of here.
24381 			 */
24382 			return;
24383 		}
24384 		/*
24385 		 * If we just completed a copy in, we become writer and
24386 		 * continue processing in ip_sioctl_copyin_done.  If it
24387 		 * was a copy out, we call mi_copyout again.  If there is
24388 		 * nothing more to copy out, it will complete the IOCTL.
24389 		 */
24390 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
24391 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
24392 				mi_copy_done(q, mp, EPROTO);
24393 				return;
24394 			}
24395 			/*
24396 			 * Check for cases that need more copying.  A return
24397 			 * value of 0 means a second copyin has been started,
24398 			 * so we return; a return value of 1 means no more
24399 			 * copying is needed, so we continue.
24400 			 */
24401 			cmd = iocp->ioc_cmd;
24402 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
24403 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
24404 			    MI_COPY_COUNT(mp) == 1) {
24405 				if (ip_copyin_msfilter(q, mp) == 0)
24406 					return;
24407 			}
24408 			/*
24409 			 * Refhold the conn, till the ioctl completes. This is
24410 			 * needed in case the ioctl ends up in the pending mp
24411 			 * list. Every mp in the ill_pending_mp list and
24412 			 * the ipsq_pending_mp must have a refhold on the conn
24413 			 * to resume processing. The refhold is released when
24414 			 * the ioctl completes. (normally or abnormally)
24415 			 * In all cases ip_ioctl_finish is called to finish
24416 			 * the ioctl.
24417 			 */
24418 			if (connp != NULL) {
24419 				/* This is not a reentry */
24420 				ASSERT(ipsq == NULL);
24421 				CONN_INC_REF(connp);
24422 			} else {
24423 				if (!(ipip->ipi_flags & IPI_MODOK)) {
24424 					mi_copy_done(q, mp, EINVAL);
24425 					return;
24426 				}
24427 			}
24428 
24429 			ip_process_ioctl(ipsq, q, mp, ipip);
24430 
24431 		} else {
24432 			mi_copyout(q, mp);
24433 		}
24434 		return;
24435 nak:
24436 		iocp->ioc_error = EINVAL;
24437 		mp->b_datap->db_type = M_IOCNAK;
24438 		iocp->ioc_count = 0;
24439 		qreply(q, mp);
24440 		return;
24441 
24442 	case M_IOCNAK:
24443 		/*
24444 		 * The only way we could get here is if a resolver didn't like
24445 		 * an IOCTL we sent it.	 This shouldn't happen.
24446 		 */
24447 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
24448 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
24449 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
24450 		freemsg(mp);
24451 		return;
24452 	case M_IOCACK:
24453 		/* Finish socket ioctls passed through to ARP. */
24454 		ip_sioctl_iocack(q, mp);
24455 		return;
24456 	case M_FLUSH:
24457 		if (*mp->b_rptr & FLUSHW)
24458 			flushq(q, FLUSHALL);
24459 		if (q->q_next) {
24460 			/*
24461 			 * M_FLUSH is sent up to IP by some drivers during
24462 			 * unbind. ip_rput has already replied to it. We are
24463 			 * here for the M_FLUSH that we originated in IP
24464 			 * before sending the unbind request to the driver.
24465 			 * Just free it as we don't queue packets in IP
24466 			 * on the write side of the device instance.
24467 			 */
24468 			freemsg(mp);
24469 			return;
24470 		}
24471 		if (*mp->b_rptr & FLUSHR) {
24472 			*mp->b_rptr &= ~FLUSHW;
24473 			qreply(q, mp);
24474 			return;
24475 		}
24476 		freemsg(mp);
24477 		return;
24478 	case IRE_DB_REQ_TYPE:
24479 		/* An Upper Level Protocol wants a copy of an IRE. */
24480 		ip_ire_req(q, mp);
24481 		return;
24482 	case M_CTL:
24483 		/* M_CTL messages are used by ARP to tell us things. */
24484 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
24485 			break;
24486 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
24487 		case AR_ENTRY_SQUERY:
24488 			ip_wput_ctl(q, mp);
24489 			return;
24490 		case AR_CLIENT_NOTIFY:
24491 			ip_arp_news(q, mp);
24492 			return;
24493 		case AR_DLPIOP_DONE:
24494 			ASSERT(q->q_next != NULL);
24495 			ill = (ill_t *)q->q_ptr;
24496 			/* qwriter_ip releases the refhold */
24497 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24498 			ill_refhold(ill);
24499 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24500 			    CUR_OP, B_FALSE);
24501 			return;
24502 		case AR_ARP_CLOSING:
24503 			/*
24504 			 * ARP (above us) is closing. If no ARP bringup is
24505 			 * currently pending, ack the message so that ARP
24506 			 * can complete its close. Also mark ill_arp_closing
24507 			 * so that new ARP bringups will fail. If any
24508 			 * ARP bringup is currently in progress, we will
24509 			 * ack this when the current ARP bringup completes.
24510 			 */
24511 			ASSERT(q->q_next != NULL);
24512 			ill = (ill_t *)q->q_ptr;
24513 			mutex_enter(&ill->ill_lock);
24514 			ill->ill_arp_closing = 1;
24515 			if (!ill->ill_arp_bringup_pending) {
24516 				mutex_exit(&ill->ill_lock);
24517 				qreply(q, mp);
24518 			} else {
24519 				mutex_exit(&ill->ill_lock);
24520 				freemsg(mp);
24521 			}
24522 			return;
24523 		default:
24524 			break;
24525 		}
24526 		break;
24527 	case M_PROTO:
24528 	case M_PCPROTO:
24529 		/*
24530 		 * The only PROTO messages we expect are ULP binds and
24531 		 * copies of option negotiation acknowledgements.
24532 		 */
24533 		switch (((union T_primitives *)mp->b_rptr)->type) {
24534 		case O_T_BIND_REQ:
24535 		case T_BIND_REQ: {
24536 			/* Request can get queued in bind */
24537 			ASSERT(connp != NULL);
24538 			/*
24539 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
24540 			 * instead of going through this path.  We only get
24541 			 * here in the following cases:
24542 			 *
24543 			 * a. Bind retries, where ipsq is non-NULL.
24544 			 * b. T_BIND_REQ is issued from non TCP/UDP
24545 			 *    transport, e.g. icmp for raw socket,
24546 			 *    in which case ipsq will be NULL.
24547 			 */
24548 			ASSERT(ipsq != NULL ||
24549 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
24550 
24551 			/* Don't increment refcnt if this is a re-entry */
24552 			if (ipsq == NULL)
24553 				CONN_INC_REF(connp);
24554 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
24555 			    connp, NULL) : ip_bind_v4(q, mp, connp);
24556 			if (mp == NULL)
24557 				return;
24558 			if (IPCL_IS_TCP(connp)) {
24559 				/*
24560 				 * In the case of TCP endpoint we
24561 				 * come here only for bind retries
24562 				 */
24563 				ASSERT(ipsq != NULL);
24564 				CONN_INC_REF(connp);
24565 				squeue_fill(connp->conn_sqp, mp,
24566 				    ip_resume_tcp_bind, connp,
24567 				    SQTAG_BIND_RETRY);
24568 				return;
24569 			} else if (IPCL_IS_UDP(connp)) {
24570 				/*
24571 				 * In the case of UDP endpoint we
24572 				 * come here only for bind retries
24573 				 */
24574 				ASSERT(ipsq != NULL);
24575 				udp_resume_bind(connp, mp);
24576 				return;
24577 			}
24578 			qreply(q, mp);
24579 			CONN_OPER_PENDING_DONE(connp);
24580 			return;
24581 		}
24582 		case T_SVR4_OPTMGMT_REQ:
24583 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24584 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24585 
24586 			ASSERT(connp != NULL);
24587 			if (!snmpcom_req(q, mp, ip_snmp_set,
24588 			    ip_snmp_get, cr)) {
24589 				/*
24590 				 * Call svr4_optcom_req so that it can
24591 				 * generate the ack. We don't come here
24592 				 * if this operation is being restarted.
24593 				 * ip_restart_optmgmt will drop the conn ref.
24594 				 * In the case of ipsec option after the ipsec
24595 				 * load is complete conn_restart_ipsec_waiter
24596 				 * drops the conn ref.
24597 				 */
24598 				ASSERT(ipsq == NULL);
24599 				CONN_INC_REF(connp);
24600 				if (ip_check_for_ipsec_opt(q, mp))
24601 					return;
24602 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24603 				if (err != EINPROGRESS) {
24604 					/* Operation is done */
24605 					CONN_OPER_PENDING_DONE(connp);
24606 				}
24607 			}
24608 			return;
24609 		case T_OPTMGMT_REQ:
24610 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24611 			/*
24612 			 * Note: No snmpcom_req support through new
24613 			 * T_OPTMGMT_REQ.
24614 			 * Call tpi_optcom_req so that it can
24615 			 * generate the ack.
24616 			 */
24617 			ASSERT(connp != NULL);
24618 			ASSERT(ipsq == NULL);
24619 			/*
24620 			 * We don't come here for restart. ip_restart_optmgmt
24621 			 * will drop the conn ref. In the case of ipsec option
24622 			 * after the ipsec load is complete
24623 			 * conn_restart_ipsec_waiter drops the conn ref.
24624 			 */
24625 			CONN_INC_REF(connp);
24626 			if (ip_check_for_ipsec_opt(q, mp))
24627 				return;
24628 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24629 			if (err != EINPROGRESS) {
24630 				/* Operation is done */
24631 				CONN_OPER_PENDING_DONE(connp);
24632 			}
24633 			return;
24634 		case T_UNBIND_REQ:
24635 			mp = ip_unbind(q, mp);
24636 			qreply(q, mp);
24637 			return;
24638 		default:
24639 			/*
24640 			 * Have to drop any DLPI messages coming down from
24641 			 * arp (such as an info_req which would cause ip
24642 			 * to receive an extra info_ack if it was passed
24643 			 * through.
24644 			 */
24645 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24646 			    (int)*(uint_t *)mp->b_rptr));
24647 			freemsg(mp);
24648 			return;
24649 		}
24650 		/* NOTREACHED */
24651 	case IRE_DB_TYPE: {
24652 		nce_t		*nce;
24653 		ill_t		*ill;
24654 		in6_addr_t	gw_addr_v6;
24655 
24656 
24657 		/*
24658 		 * This is a response back from a resolver.  It
24659 		 * consists of a message chain containing:
24660 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24661 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24662 		 * The LL_HDR_MBLK is the DLPI header to use to get
24663 		 * the attached packet, and subsequent ones for the
24664 		 * same destination, transmitted.
24665 		 */
24666 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24667 			break;
24668 		/*
24669 		 * First, check to make sure the resolution succeeded.
24670 		 * If it failed, the second mblk will be empty.
24671 		 * If it is, free the chain, dropping the packet.
24672 		 * (We must ire_delete the ire; that frees the ire mblk)
24673 		 * We're doing this now to support PVCs for ATM; it's
24674 		 * a partial xresolv implementation. When we fully implement
24675 		 * xresolv interfaces, instead of freeing everything here
24676 		 * we'll initiate neighbor discovery.
24677 		 *
24678 		 * For v4 (ARP and other external resolvers) the resolver
24679 		 * frees the message, so no check is needed. This check
24680 		 * is required, though, for a full xresolve implementation.
24681 		 * Including this code here now both shows how external
24682 		 * resolvers can NACK a resolution request using an
24683 		 * existing design that has no specific provisions for NACKs,
24684 		 * and also takes into account that the current non-ARP
24685 		 * external resolver has been coded to use this method of
24686 		 * NACKing for all IPv6 (xresolv) cases,
24687 		 * whether our xresolv implementation is complete or not.
24688 		 *
24689 		 */
24690 		ire = (ire_t *)mp->b_rptr;
24691 		ill = ire_to_ill(ire);
24692 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24693 		if (mp1->b_rptr == mp1->b_wptr) {
24694 			if (ire->ire_ipversion == IPV6_VERSION) {
24695 				/*
24696 				 * XRESOLV interface.
24697 				 */
24698 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24699 				mutex_enter(&ire->ire_lock);
24700 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24701 				mutex_exit(&ire->ire_lock);
24702 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24703 					nce = ndp_lookup(ill,
24704 					    &ire->ire_addr_v6, B_FALSE);
24705 				} else {
24706 					nce = ndp_lookup(ill, &gw_addr_v6,
24707 					    B_FALSE);
24708 				}
24709 				if (nce != NULL) {
24710 					nce_resolv_failed(nce);
24711 					ndp_delete(nce);
24712 					NCE_REFRELE(nce);
24713 				}
24714 			}
24715 			mp->b_cont = NULL;
24716 			freemsg(mp1);		/* frees the pkt as well */
24717 			ire_delete((ire_t *)mp->b_rptr);
24718 			return;
24719 		}
24720 		/*
24721 		 * Split them into IRE_MBLK and pkt and feed it into
24722 		 * ire_add_then_send. Then in ire_add_then_send
24723 		 * the IRE will be added, and then the packet will be
24724 		 * run back through ip_wput. This time it will make
24725 		 * it to the wire.
24726 		 */
24727 		mp->b_cont = NULL;
24728 		mp = mp1->b_cont;		/* now, mp points to pkt */
24729 		mp1->b_cont = NULL;
24730 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24731 		if (ire->ire_ipversion == IPV6_VERSION) {
24732 			/*
24733 			 * XRESOLV interface. Find the nce and put a copy
24734 			 * of the dl_unitdata_req in nce_res_mp
24735 			 */
24736 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24737 			mutex_enter(&ire->ire_lock);
24738 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24739 			mutex_exit(&ire->ire_lock);
24740 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24741 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24742 				    B_FALSE);
24743 			} else {
24744 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24745 			}
24746 			if (nce != NULL) {
24747 				/*
24748 				 * We have to protect nce_res_mp here
24749 				 * from being accessed by other threads
24750 				 * while we change the mblk pointer.
24751 				 * Other functions will also lock the nce when
24752 				 * accessing nce_res_mp.
24753 				 *
24754 				 * The reason we change the mblk pointer
24755 				 * here rather than copying the resolved address
24756 				 * into the template is that, unlike with
24757 				 * ethernet, we have no guarantee that the
24758 				 * resolved address length will be
24759 				 * smaller than or equal to the lla length
24760 				 * with which the template was allocated,
24761 				 * (for ethernet, they're equal)
24762 				 * so we have to use the actual resolved
24763 				 * address mblk - which holds the real
24764 				 * dl_unitdata_req with the resolved address.
24765 				 *
24766 				 * Doing this is the same behavior as was
24767 				 * previously used in the v4 ARP case.
24768 				 */
24769 				mutex_enter(&nce->nce_lock);
24770 				if (nce->nce_res_mp != NULL)
24771 					freemsg(nce->nce_res_mp);
24772 				nce->nce_res_mp = mp1;
24773 				mutex_exit(&nce->nce_lock);
24774 				/*
24775 				 * We do a fastpath probe here because
24776 				 * we have resolved the address without
24777 				 * using Neighbor Discovery.
24778 				 * In the non-XRESOLV v6 case, the fastpath
24779 				 * probe is done right after neighbor
24780 				 * discovery completes.
24781 				 */
24782 				if (nce->nce_res_mp != NULL) {
24783 					int res;
24784 					nce_fastpath_list_add(nce);
24785 					res = ill_fastpath_probe(ill,
24786 					    nce->nce_res_mp);
24787 					if (res != 0 && res != EAGAIN)
24788 						nce_fastpath_list_delete(nce);
24789 				}
24790 
24791 				ire_add_then_send(q, ire, mp);
24792 				/*
24793 				 * Now we have to clean out any packets
24794 				 * that may have been queued on the nce
24795 				 * while it was waiting for address resolution
24796 				 * to complete.
24797 				 */
24798 				mutex_enter(&nce->nce_lock);
24799 				mp1 = nce->nce_qd_mp;
24800 				nce->nce_qd_mp = NULL;
24801 				mutex_exit(&nce->nce_lock);
24802 				while (mp1 != NULL) {
24803 					mblk_t *nxt_mp;
24804 					queue_t *fwdq = NULL;
24805 					ill_t   *inbound_ill;
24806 					uint_t ifindex;
24807 
24808 					nxt_mp = mp1->b_next;
24809 					mp1->b_next = NULL;
24810 					/*
24811 					 * Retrieve ifindex stored in
24812 					 * ip_rput_data_v6()
24813 					 */
24814 					ifindex =
24815 					    (uint_t)(uintptr_t)mp1->b_prev;
24816 					inbound_ill =
24817 						ill_lookup_on_ifindex(ifindex,
24818 						    B_TRUE, NULL, NULL, NULL,
24819 						    NULL);
24820 					mp1->b_prev = NULL;
24821 					if (inbound_ill != NULL)
24822 						fwdq = inbound_ill->ill_rq;
24823 
24824 					if (fwdq != NULL) {
24825 						put(fwdq, mp1);
24826 						ill_refrele(inbound_ill);
24827 					} else
24828 						put(WR(ill->ill_rq), mp1);
24829 					mp1 = nxt_mp;
24830 				}
24831 				NCE_REFRELE(nce);
24832 			} else {	/* nce is NULL; clean up */
24833 				ire_delete(ire);
24834 				freemsg(mp);
24835 				freemsg(mp1);
24836 				return;
24837 			}
24838 		} else {
24839 			ire->ire_dlureq_mp = mp1;
24840 			ire_add_then_send(q, ire, mp);
24841 		}
24842 		return;	/* All is well, the packet has been sent. */
24843 	}
24844 	default:
24845 		break;
24846 	}
24847 	if (q->q_next) {
24848 		putnext(q, mp);
24849 	} else
24850 		freemsg(mp);
24851 }
24852 
24853 /*
24854  * Process IP options in an outbound packet.  Modify the destination if there
24855  * is a source route option.
24856  * Returns non-zero if something fails in which case an ICMP error has been
24857  * sent and mp freed.
24858  */
24859 static int
24860 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24861     boolean_t mctl_present, zoneid_t zoneid)
24862 {
24863 	ipoptp_t	opts;
24864 	uchar_t		*opt;
24865 	uint8_t		optval;
24866 	uint8_t		optlen;
24867 	ipaddr_t	dst;
24868 	intptr_t	code = 0;
24869 	mblk_t		*mp;
24870 	ire_t		*ire = NULL;
24871 
24872 	ip2dbg(("ip_wput_options\n"));
24873 	mp = ipsec_mp;
24874 	if (mctl_present) {
24875 		mp = ipsec_mp->b_cont;
24876 	}
24877 
24878 	dst = ipha->ipha_dst;
24879 	for (optval = ipoptp_first(&opts, ipha);
24880 	    optval != IPOPT_EOL;
24881 	    optval = ipoptp_next(&opts)) {
24882 		opt = opts.ipoptp_cur;
24883 		optlen = opts.ipoptp_len;
24884 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24885 		    optval, optlen));
24886 		switch (optval) {
24887 			uint32_t off;
24888 		case IPOPT_SSRR:
24889 		case IPOPT_LSRR:
24890 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24891 				ip1dbg((
24892 				    "ip_wput_options: bad option offset\n"));
24893 				code = (char *)&opt[IPOPT_OLEN] -
24894 				    (char *)ipha;
24895 				goto param_prob;
24896 			}
24897 			off = opt[IPOPT_OFFSET];
24898 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24899 			    ntohl(dst)));
24900 			/*
24901 			 * For strict: verify that dst is directly
24902 			 * reachable.
24903 			 */
24904 			if (optval == IPOPT_SSRR) {
24905 				ire = ire_ftable_lookup(dst, 0, 0,
24906 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24907 				    MATCH_IRE_TYPE);
24908 				if (ire == NULL) {
24909 					ip1dbg(("ip_wput_options: SSRR not"
24910 					    " directly reachable: 0x%x\n",
24911 					    ntohl(dst)));
24912 					goto bad_src_route;
24913 				}
24914 				ire_refrele(ire);
24915 			}
24916 			break;
24917 		case IPOPT_RR:
24918 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24919 				ip1dbg((
24920 				    "ip_wput_options: bad option offset\n"));
24921 				code = (char *)&opt[IPOPT_OLEN] -
24922 				    (char *)ipha;
24923 				goto param_prob;
24924 			}
24925 			break;
24926 		case IPOPT_TS:
24927 			/*
24928 			 * Verify that length >=5 and that there is either
24929 			 * room for another timestamp or that the overflow
24930 			 * counter is not maxed out.
24931 			 */
24932 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24933 			if (optlen < IPOPT_MINLEN_IT) {
24934 				goto param_prob;
24935 			}
24936 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24937 				ip1dbg((
24938 				    "ip_wput_options: bad option offset\n"));
24939 				code = (char *)&opt[IPOPT_OFFSET] -
24940 				    (char *)ipha;
24941 				goto param_prob;
24942 			}
24943 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24944 			case IPOPT_TS_TSONLY:
24945 				off = IPOPT_TS_TIMELEN;
24946 				break;
24947 			case IPOPT_TS_TSANDADDR:
24948 			case IPOPT_TS_PRESPEC:
24949 			case IPOPT_TS_PRESPEC_RFC791:
24950 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24951 				break;
24952 			default:
24953 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24954 				    (char *)ipha;
24955 				goto param_prob;
24956 			}
24957 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24958 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24959 				/*
24960 				 * No room and the overflow counter is 15
24961 				 * already.
24962 				 */
24963 				goto param_prob;
24964 			}
24965 			break;
24966 		}
24967 	}
24968 
24969 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24970 		return (0);
24971 
24972 	ip1dbg(("ip_wput_options: error processing IP options."));
24973 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24974 
24975 param_prob:
24976 	/*
24977 	 * Since ip_wput() isn't close to finished, we fill
24978 	 * in enough of the header for credible error reporting.
24979 	 */
24980 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24981 		/* Failed */
24982 		freemsg(ipsec_mp);
24983 		return (-1);
24984 	}
24985 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24986 	return (-1);
24987 
24988 bad_src_route:
24989 	/*
24990 	 * Since ip_wput() isn't close to finished, we fill
24991 	 * in enough of the header for credible error reporting.
24992 	 */
24993 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24994 		/* Failed */
24995 		freemsg(ipsec_mp);
24996 		return (-1);
24997 	}
24998 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24999 	return (-1);
25000 }
25001 
25002 /*
25003  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25004  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25005  * thru /etc/system.
25006  */
25007 #define	CONN_MAXDRAINCNT	64
25008 
25009 static void
25010 conn_drain_init(void)
25011 {
25012 	int i;
25013 
25014 	conn_drain_list_cnt = conn_drain_nthreads;
25015 
25016 	if ((conn_drain_list_cnt == 0) ||
25017 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25018 		/*
25019 		 * Default value of the number of drainers is the
25020 		 * number of cpus, subject to maximum of 8 drainers.
25021 		 */
25022 		if (boot_max_ncpus != -1)
25023 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25024 		else
25025 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25026 	}
25027 
25028 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25029 	    KM_SLEEP);
25030 
25031 	for (i = 0; i < conn_drain_list_cnt; i++) {
25032 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25033 		    MUTEX_DEFAULT, NULL);
25034 	}
25035 }
25036 
25037 static void
25038 conn_drain_fini(void)
25039 {
25040 	int i;
25041 
25042 	for (i = 0; i < conn_drain_list_cnt; i++)
25043 		mutex_destroy(&conn_drain_list[i].idl_lock);
25044 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25045 	conn_drain_list = NULL;
25046 }
25047 
25048 /*
25049  * Note: For an overview of how flowcontrol is handled in IP please see the
25050  * IP Flowcontrol notes at the top of this file.
25051  *
25052  * Flow control has blocked us from proceeding. Insert the given conn in one
25053  * of the conn drain lists. These conn wq's will be qenabled later on when
25054  * STREAMS flow control does a backenable. conn_walk_drain will enable
25055  * the first conn in each of these drain lists. Each of these qenabled conns
25056  * in turn enables the next in the list, after it runs, or when it closes,
25057  * thus sustaining the drain process.
25058  *
25059  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25060  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25061  * running at any time, on a given conn, since there can be only 1 service proc
25062  * running on a queue at any time.
25063  */
25064 void
25065 conn_drain_insert(conn_t *connp)
25066 {
25067 	idl_t	*idl;
25068 	uint_t	index;
25069 
25070 	mutex_enter(&connp->conn_lock);
25071 	if (connp->conn_state_flags & CONN_CLOSING) {
25072 		/*
25073 		 * The conn is closing as a result of which CONN_CLOSING
25074 		 * is set. Return.
25075 		 */
25076 		mutex_exit(&connp->conn_lock);
25077 		return;
25078 	} else if (connp->conn_idl == NULL) {
25079 		/*
25080 		 * Assign the next drain list round robin. We dont' use
25081 		 * a lock, and thus it may not be strictly round robin.
25082 		 * Atomicity of load/stores is enough to make sure that
25083 		 * conn_drain_list_index is always within bounds.
25084 		 */
25085 		index = conn_drain_list_index;
25086 		ASSERT(index < conn_drain_list_cnt);
25087 		connp->conn_idl = &conn_drain_list[index];
25088 		index++;
25089 		if (index == conn_drain_list_cnt)
25090 			index = 0;
25091 		conn_drain_list_index = index;
25092 	}
25093 	mutex_exit(&connp->conn_lock);
25094 
25095 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25096 	if ((connp->conn_drain_prev != NULL) ||
25097 	    (connp->conn_state_flags & CONN_CLOSING)) {
25098 		/*
25099 		 * The conn is already in the drain list, OR
25100 		 * the conn is closing. We need to check again for
25101 		 * the closing case again since close can happen
25102 		 * after we drop the conn_lock, and before we
25103 		 * acquire the CONN_DRAIN_LIST_LOCK.
25104 		 */
25105 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25106 		return;
25107 	} else {
25108 		idl = connp->conn_idl;
25109 	}
25110 
25111 	/*
25112 	 * The conn is not in the drain list. Insert it at the
25113 	 * tail of the drain list. The drain list is circular
25114 	 * and doubly linked. idl_conn points to the 1st element
25115 	 * in the list.
25116 	 */
25117 	if (idl->idl_conn == NULL) {
25118 		idl->idl_conn = connp;
25119 		connp->conn_drain_next = connp;
25120 		connp->conn_drain_prev = connp;
25121 	} else {
25122 		conn_t *head = idl->idl_conn;
25123 
25124 		connp->conn_drain_next = head;
25125 		connp->conn_drain_prev = head->conn_drain_prev;
25126 		head->conn_drain_prev->conn_drain_next = connp;
25127 		head->conn_drain_prev = connp;
25128 	}
25129 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25130 }
25131 
25132 /*
25133  * This conn is closing, and we are called from ip_close. OR
25134  * This conn has been serviced by ip_wsrv, and we need to do the tail
25135  * processing.
25136  * If this conn is part of the drain list, we may need to sustain the drain
25137  * process by qenabling the next conn in the drain list. We may also need to
25138  * remove this conn from the list, if it is done.
25139  */
25140 static void
25141 conn_drain_tail(conn_t *connp, boolean_t closing)
25142 {
25143 	idl_t *idl;
25144 
25145 	/*
25146 	 * connp->conn_idl is stable at this point, and no lock is needed
25147 	 * to check it. If we are called from ip_close, close has already
25148 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
25149 	 * called us only because conn_idl is non-null. If we are called thru
25150 	 * service, conn_idl could be null, but it cannot change because
25151 	 * service is single-threaded per queue, and there cannot be another
25152 	 * instance of service trying to call conn_drain_insert on this conn
25153 	 * now.
25154 	 */
25155 	ASSERT(!closing || (connp->conn_idl != NULL));
25156 
25157 	/*
25158 	 * If connp->conn_idl is null, the conn has not been inserted into any
25159 	 * drain list even once since creation of the conn. Just return.
25160 	 */
25161 	if (connp->conn_idl == NULL)
25162 		return;
25163 
25164 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25165 
25166 	if (connp->conn_drain_prev == NULL) {
25167 		/* This conn is currently not in the drain list.  */
25168 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25169 		return;
25170 	}
25171 	idl = connp->conn_idl;
25172 	if (idl->idl_conn_draining == connp) {
25173 		/*
25174 		 * This conn is the current drainer. If this is the last conn
25175 		 * in the drain list, we need to do more checks, in the 'if'
25176 		 * below. Otherwwise we need to just qenable the next conn,
25177 		 * to sustain the draining, and is handled in the 'else'
25178 		 * below.
25179 		 */
25180 		if (connp->conn_drain_next == idl->idl_conn) {
25181 			/*
25182 			 * This conn is the last in this list. This round
25183 			 * of draining is complete. If idl_repeat is set,
25184 			 * it means another flow enabling has happened from
25185 			 * the driver/streams and we need to another round
25186 			 * of draining.
25187 			 * If there are more than 2 conns in the drain list,
25188 			 * do a left rotate by 1, so that all conns except the
25189 			 * conn at the head move towards the head by 1, and the
25190 			 * the conn at the head goes to the tail. This attempts
25191 			 * a more even share for all queues that are being
25192 			 * drained.
25193 			 */
25194 			if ((connp->conn_drain_next != connp) &&
25195 			    (idl->idl_conn->conn_drain_next != connp)) {
25196 				idl->idl_conn = idl->idl_conn->conn_drain_next;
25197 			}
25198 			if (idl->idl_repeat) {
25199 				qenable(idl->idl_conn->conn_wq);
25200 				idl->idl_conn_draining = idl->idl_conn;
25201 				idl->idl_repeat = 0;
25202 			} else {
25203 				idl->idl_conn_draining = NULL;
25204 			}
25205 		} else {
25206 			/*
25207 			 * If the next queue that we are now qenable'ing,
25208 			 * is closing, it will remove itself from this list
25209 			 * and qenable the subsequent queue in ip_close().
25210 			 * Serialization is acheived thru idl_lock.
25211 			 */
25212 			qenable(connp->conn_drain_next->conn_wq);
25213 			idl->idl_conn_draining = connp->conn_drain_next;
25214 		}
25215 	}
25216 	if (!connp->conn_did_putbq || closing) {
25217 		/*
25218 		 * Remove ourself from the drain list, if we did not do
25219 		 * a putbq, or if the conn is closing.
25220 		 * Note: It is possible that q->q_first is non-null. It means
25221 		 * that these messages landed after we did a enableok() in
25222 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
25223 		 * service them.
25224 		 */
25225 		if (connp->conn_drain_next == connp) {
25226 			/* Singleton in the list */
25227 			ASSERT(connp->conn_drain_prev == connp);
25228 			idl->idl_conn = NULL;
25229 			idl->idl_conn_draining = NULL;
25230 		} else {
25231 			connp->conn_drain_prev->conn_drain_next =
25232 			    connp->conn_drain_next;
25233 			connp->conn_drain_next->conn_drain_prev =
25234 			    connp->conn_drain_prev;
25235 			if (idl->idl_conn == connp)
25236 				idl->idl_conn = connp->conn_drain_next;
25237 			ASSERT(idl->idl_conn_draining != connp);
25238 
25239 		}
25240 		connp->conn_drain_next = NULL;
25241 		connp->conn_drain_prev = NULL;
25242 	}
25243 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25244 }
25245 
25246 /*
25247  * Write service routine. Shared perimeter entry point.
25248  * ip_wsrv can be called in any of the following ways.
25249  * 1. The device queue's messages has fallen below the low water mark
25250  *    and STREAMS has backenabled the ill_wq. We walk thru all the
25251  *    the drain lists and backenable the first conn in each list.
25252  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
25253  *    qenabled non-tcp upper layers. We start dequeing messages and call
25254  *    ip_wput for each message.
25255  */
25256 
25257 void
25258 ip_wsrv(queue_t *q)
25259 {
25260 	conn_t	*connp;
25261 	ill_t	*ill;
25262 	mblk_t	*mp;
25263 
25264 	if (q->q_next) {
25265 		ill = (ill_t *)q->q_ptr;
25266 		if (ill->ill_state_flags == 0) {
25267 			/*
25268 			 * The device flow control has opened up.
25269 			 * Walk through conn drain lists and qenable the
25270 			 * first conn in each list. This makes sense only
25271 			 * if the stream is fully plumbed and setup.
25272 			 * Hence the if check above.
25273 			 */
25274 			ip1dbg(("ip_wsrv: walking\n"));
25275 			conn_walk_drain();
25276 		}
25277 		return;
25278 	}
25279 
25280 	connp = Q_TO_CONN(q);
25281 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
25282 
25283 	/*
25284 	 * 1. Set conn_draining flag to signal that service is active.
25285 	 *
25286 	 * 2. ip_output determines whether it has been called from service,
25287 	 *    based on the last parameter. If it is IP_WSRV it concludes it
25288 	 *    has been called from service.
25289 	 *
25290 	 * 3. Message ordering is preserved by the following logic.
25291 	 *    i. A directly called ip_output (i.e. not thru service) will queue
25292 	 *    the message at the tail, if conn_draining is set (i.e. service
25293 	 *    is running) or if q->q_first is non-null.
25294 	 *
25295 	 *    ii. If ip_output is called from service, and if ip_output cannot
25296 	 *    putnext due to flow control, it does a putbq.
25297 	 *
25298 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
25299 	 *    (causing an infinite loop).
25300 	 */
25301 	ASSERT(!connp->conn_did_putbq);
25302 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
25303 		connp->conn_draining = 1;
25304 		noenable(q);
25305 		while ((mp = getq(q)) != NULL) {
25306 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
25307 			if (connp->conn_did_putbq) {
25308 				/* ip_wput did a putbq */
25309 				break;
25310 			}
25311 		}
25312 		/*
25313 		 * At this point, a thread coming down from top, calling
25314 		 * ip_wput, may end up queueing the message. We have not yet
25315 		 * enabled the queue, so ip_wsrv won't be called again.
25316 		 * To avoid this race, check q->q_first again (in the loop)
25317 		 * If the other thread queued the message before we call
25318 		 * enableok(), we will catch it in the q->q_first check.
25319 		 * If the other thread queues the message after we call
25320 		 * enableok(), ip_wsrv will be called again by STREAMS.
25321 		 */
25322 		connp->conn_draining = 0;
25323 		enableok(q);
25324 	}
25325 
25326 	/* Enable the next conn for draining */
25327 	conn_drain_tail(connp, B_FALSE);
25328 
25329 	connp->conn_did_putbq = 0;
25330 }
25331 
25332 /*
25333  * Walk the list of all conn's calling the function provided with the
25334  * specified argument for each.	 Note that this only walks conn's that
25335  * have been bound.
25336  * Applies to both IPv4 and IPv6.
25337  */
25338 static void
25339 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
25340 {
25341 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
25342 	    func, arg, zoneid);
25343 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
25344 	    func, arg, zoneid);
25345 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
25346 	    func, arg, zoneid);
25347 	conn_walk_fanout_table(ipcl_proto_fanout,
25348 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
25349 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
25350 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
25351 }
25352 
25353 /*
25354  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
25355  * of conns that need to be drained, check if drain is already in progress.
25356  * If so set the idl_repeat bit, indicating that the last conn in the list
25357  * needs to reinitiate the drain once again, for the list. If drain is not
25358  * in progress for the list, initiate the draining, by qenabling the 1st
25359  * conn in the list. The drain is self-sustaining, each qenabled conn will
25360  * in turn qenable the next conn, when it is done/blocked/closing.
25361  */
25362 static void
25363 conn_walk_drain(void)
25364 {
25365 	int i;
25366 	idl_t *idl;
25367 
25368 	IP_STAT(ip_conn_walk_drain);
25369 
25370 	for (i = 0; i < conn_drain_list_cnt; i++) {
25371 		idl = &conn_drain_list[i];
25372 		mutex_enter(&idl->idl_lock);
25373 		if (idl->idl_conn == NULL) {
25374 			mutex_exit(&idl->idl_lock);
25375 			continue;
25376 		}
25377 		/*
25378 		 * If this list is not being drained currently by
25379 		 * an ip_wsrv thread, start the process.
25380 		 */
25381 		if (idl->idl_conn_draining == NULL) {
25382 			ASSERT(idl->idl_repeat == 0);
25383 			qenable(idl->idl_conn->conn_wq);
25384 			idl->idl_conn_draining = idl->idl_conn;
25385 		} else {
25386 			idl->idl_repeat = 1;
25387 		}
25388 		mutex_exit(&idl->idl_lock);
25389 	}
25390 }
25391 
25392 /*
25393  * Walk an conn hash table of `count' buckets, calling func for each entry.
25394  */
25395 static void
25396 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
25397     zoneid_t zoneid)
25398 {
25399 	conn_t	*connp;
25400 
25401 	while (count-- > 0) {
25402 		mutex_enter(&connfp->connf_lock);
25403 		for (connp = connfp->connf_head; connp != NULL;
25404 		    connp = connp->conn_next) {
25405 			if (zoneid == GLOBAL_ZONEID ||
25406 			    zoneid == connp->conn_zoneid) {
25407 				CONN_INC_REF(connp);
25408 				mutex_exit(&connfp->connf_lock);
25409 				(*func)(connp, arg);
25410 				mutex_enter(&connfp->connf_lock);
25411 				CONN_DEC_REF(connp);
25412 			}
25413 		}
25414 		mutex_exit(&connfp->connf_lock);
25415 		connfp++;
25416 	}
25417 }
25418 
25419 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
25420 static void
25421 conn_report1(conn_t *connp, void *mp)
25422 {
25423 	char	buf1[INET6_ADDRSTRLEN];
25424 	char	buf2[INET6_ADDRSTRLEN];
25425 	uint_t	print_len, buf_len;
25426 
25427 	ASSERT(connp != NULL);
25428 
25429 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
25430 	if (buf_len <= 0)
25431 		return;
25432 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
25433 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
25434 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
25435 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
25436 	    "%5d %s/%05d %s/%05d\n",
25437 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
25438 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
25439 	    buf1, connp->conn_lport,
25440 	    buf2, connp->conn_fport);
25441 	if (print_len < buf_len) {
25442 		((mblk_t *)mp)->b_wptr += print_len;
25443 	} else {
25444 		((mblk_t *)mp)->b_wptr += buf_len;
25445 	}
25446 }
25447 
25448 /*
25449  * Named Dispatch routine to produce a formatted report on all conns
25450  * that are listed in one of the fanout tables.
25451  * This report is accessed by using the ndd utility to "get" ND variable
25452  * "ip_conn_status".
25453  */
25454 /* ARGSUSED */
25455 static int
25456 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
25457 {
25458 	(void) mi_mpprintf(mp,
25459 	    "CONN      " MI_COL_HDRPAD_STR
25460 	    "rfq      " MI_COL_HDRPAD_STR
25461 	    "stq      " MI_COL_HDRPAD_STR
25462 	    " zone local                 remote");
25463 
25464 	/*
25465 	 * Because of the ndd constraint, at most we can have 64K buffer
25466 	 * to put in all conn info.  So to be more efficient, just
25467 	 * allocate a 64K buffer here, assuming we need that large buffer.
25468 	 * This should be OK as only privileged processes can do ndd /dev/ip.
25469 	 */
25470 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
25471 		/* The following may work even if we cannot get a large buf. */
25472 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
25473 		return (0);
25474 	}
25475 
25476 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
25477 	return (0);
25478 }
25479 
25480 /*
25481  * Determine if the ill and multicast aspects of that packets
25482  * "matches" the conn.
25483  */
25484 boolean_t
25485 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
25486     zoneid_t zoneid)
25487 {
25488 	ill_t *in_ill;
25489 	boolean_t found;
25490 	ipif_t *ipif;
25491 	ire_t *ire;
25492 	ipaddr_t dst, src;
25493 
25494 	dst = ipha->ipha_dst;
25495 	src = ipha->ipha_src;
25496 
25497 	/*
25498 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
25499 	 * unicast, broadcast and multicast reception to
25500 	 * conn_incoming_ill. conn_wantpacket itself is called
25501 	 * only for BROADCAST and multicast.
25502 	 *
25503 	 * 1) ip_rput supresses duplicate broadcasts if the ill
25504 	 *    is part of a group. Hence, we should be receiving
25505 	 *    just one copy of broadcast for the whole group.
25506 	 *    Thus, if it is part of the group the packet could
25507 	 *    come on any ill of the group and hence we need a
25508 	 *    match on the group. Otherwise, match on ill should
25509 	 *    be sufficient.
25510 	 *
25511 	 * 2) ip_rput does not suppress duplicate multicast packets.
25512 	 *    If there are two interfaces in a ill group and we have
25513 	 *    2 applications (conns) joined a multicast group G on
25514 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25515 	 *    will give us two packets because we join G on both the
25516 	 *    interfaces rather than nominating just one interface
25517 	 *    for receiving multicast like broadcast above. So,
25518 	 *    we have to call ilg_lookup_ill to filter out duplicate
25519 	 *    copies, if ill is part of a group.
25520 	 */
25521 	in_ill = connp->conn_incoming_ill;
25522 	if (in_ill != NULL) {
25523 		if (in_ill->ill_group == NULL) {
25524 			if (in_ill != ill)
25525 				return (B_FALSE);
25526 		} else if (in_ill->ill_group != ill->ill_group) {
25527 			return (B_FALSE);
25528 		}
25529 	}
25530 
25531 	if (!CLASSD(dst)) {
25532 		if (connp->conn_zoneid == zoneid)
25533 			return (B_TRUE);
25534 		/*
25535 		 * The conn is in a different zone; we need to check that this
25536 		 * broadcast address is configured in the application's zone and
25537 		 * on one ill in the group.
25538 		 */
25539 		ipif = ipif_get_next_ipif(NULL, ill);
25540 		if (ipif == NULL)
25541 			return (B_FALSE);
25542 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25543 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25544 		ipif_refrele(ipif);
25545 		if (ire != NULL) {
25546 			ire_refrele(ire);
25547 			return (B_TRUE);
25548 		} else {
25549 			return (B_FALSE);
25550 		}
25551 	}
25552 
25553 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25554 	    connp->conn_zoneid == zoneid) {
25555 		/*
25556 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25557 		 * disabled, therefore we don't dispatch the multicast packet to
25558 		 * the sending zone.
25559 		 */
25560 		return (B_FALSE);
25561 	}
25562 
25563 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25564 	    connp->conn_zoneid != zoneid) {
25565 		/*
25566 		 * Multicast packet on the loopback interface: we only match
25567 		 * conns who joined the group in the specified zone.
25568 		 */
25569 		return (B_FALSE);
25570 	}
25571 
25572 	if (connp->conn_multi_router) {
25573 		/* multicast packet and multicast router socket: send up */
25574 		return (B_TRUE);
25575 	}
25576 
25577 	mutex_enter(&connp->conn_lock);
25578 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25579 	mutex_exit(&connp->conn_lock);
25580 	return (found);
25581 }
25582 
25583 /*
25584  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25585  */
25586 /* ARGSUSED */
25587 static void
25588 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25589 {
25590 	ill_t *ill = (ill_t *)q->q_ptr;
25591 	mblk_t	*mp1, *mp2;
25592 	ipif_t  *ipif;
25593 	int err = 0;
25594 	conn_t *connp = NULL;
25595 	ipsq_t	*ipsq;
25596 	arc_t	*arc;
25597 
25598 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25599 
25600 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25601 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25602 
25603 	ASSERT(IAM_WRITER_ILL(ill));
25604 	mp2 = mp->b_cont;
25605 	mp->b_cont = NULL;
25606 
25607 	/*
25608 	 * We have now received the arp bringup completion message
25609 	 * from ARP. Mark the arp bringup as done. Also if the arp
25610 	 * stream has already started closing, send up the AR_ARP_CLOSING
25611 	 * ack now since ARP is waiting in close for this ack.
25612 	 */
25613 	mutex_enter(&ill->ill_lock);
25614 	ill->ill_arp_bringup_pending = 0;
25615 	if (ill->ill_arp_closing) {
25616 		mutex_exit(&ill->ill_lock);
25617 		/* Let's reuse the mp for sending the ack */
25618 		arc = (arc_t *)mp->b_rptr;
25619 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25620 		arc->arc_cmd = AR_ARP_CLOSING;
25621 		qreply(q, mp);
25622 	} else {
25623 		mutex_exit(&ill->ill_lock);
25624 		freeb(mp);
25625 	}
25626 
25627 	/* We should have an IOCTL waiting on this. */
25628 	ipsq = ill->ill_phyint->phyint_ipsq;
25629 	ipif = ipsq->ipsq_pending_ipif;
25630 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25631 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25632 	if (mp1 == NULL) {
25633 		/* bringup was aborted by the user */
25634 		freemsg(mp2);
25635 		return;
25636 	}
25637 	ASSERT(connp != NULL);
25638 	q = CONNP_TO_WQ(connp);
25639 	/*
25640 	 * If the DL_BIND_REQ fails, it is noted
25641 	 * in arc_name_offset.
25642 	 */
25643 	err = *((int *)mp2->b_rptr);
25644 	if (err == 0) {
25645 		if (ipif->ipif_isv6) {
25646 			if ((err = ipif_up_done_v6(ipif)) != 0)
25647 				ip0dbg(("ip_arp_done: init failed\n"));
25648 		} else {
25649 			if ((err = ipif_up_done(ipif)) != 0)
25650 				ip0dbg(("ip_arp_done: init failed\n"));
25651 		}
25652 	} else {
25653 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25654 	}
25655 
25656 	freemsg(mp2);
25657 
25658 	if ((err == 0) && (ill->ill_up_ipifs)) {
25659 		err = ill_up_ipifs(ill, q, mp1);
25660 		if (err == EINPROGRESS)
25661 			return;
25662 	}
25663 
25664 	if (ill->ill_up_ipifs) {
25665 		ill_group_cleanup(ill);
25666 	}
25667 
25668 	/*
25669 	 * The ioctl must complete now without EINPROGRESS
25670 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25671 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25672 	 * stuck for ever in the ipsq.
25673 	 */
25674 	ASSERT(err != EINPROGRESS);
25675 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25676 }
25677 
25678 /* Allocate the private structure */
25679 static int
25680 ip_priv_alloc(void **bufp)
25681 {
25682 	void	*buf;
25683 
25684 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25685 		return (ENOMEM);
25686 
25687 	*bufp = buf;
25688 	return (0);
25689 }
25690 
25691 /* Function to delete the private structure */
25692 void
25693 ip_priv_free(void *buf)
25694 {
25695 	ASSERT(buf != NULL);
25696 	kmem_free(buf, sizeof (ip_priv_t));
25697 }
25698 
25699 /*
25700  * The entry point for IPPF processing.
25701  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25702  * routine just returns.
25703  *
25704  * When called, ip_process generates an ipp_packet_t structure
25705  * which holds the state information for this packet and invokes the
25706  * the classifier (via ipp_packet_process). The classification, depending on
25707  * configured filters, results in a list of actions for this packet. Invoking
25708  * an action may cause the packet to be dropped, in which case the resulting
25709  * mblk (*mpp) is NULL. proc indicates the callout position for
25710  * this packet and ill_index is the interface this packet on or will leave
25711  * on (inbound and outbound resp.).
25712  */
25713 void
25714 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25715 {
25716 	mblk_t		*mp;
25717 	ip_priv_t	*priv;
25718 	ipp_action_id_t	aid;
25719 	int		rc = 0;
25720 	ipp_packet_t	*pp;
25721 #define	IP_CLASS	"ip"
25722 
25723 	/* If the classifier is not loaded, return  */
25724 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25725 		return;
25726 	}
25727 
25728 	mp = *mpp;
25729 	ASSERT(mp != NULL);
25730 
25731 	/* Allocate the packet structure */
25732 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25733 	if (rc != 0) {
25734 		*mpp = NULL;
25735 		freemsg(mp);
25736 		return;
25737 	}
25738 
25739 	/* Allocate the private structure */
25740 	rc = ip_priv_alloc((void **)&priv);
25741 	if (rc != 0) {
25742 		*mpp = NULL;
25743 		freemsg(mp);
25744 		ipp_packet_free(pp);
25745 		return;
25746 	}
25747 	priv->proc = proc;
25748 	priv->ill_index = ill_index;
25749 	ipp_packet_set_private(pp, priv, ip_priv_free);
25750 	ipp_packet_set_data(pp, mp);
25751 
25752 	/* Invoke the classifier */
25753 	rc = ipp_packet_process(&pp);
25754 	if (pp != NULL) {
25755 		mp = ipp_packet_get_data(pp);
25756 		ipp_packet_free(pp);
25757 		if (rc != 0) {
25758 			freemsg(mp);
25759 			*mpp = NULL;
25760 		}
25761 	} else {
25762 		*mpp = NULL;
25763 	}
25764 #undef	IP_CLASS
25765 }
25766 
25767 /*
25768  * Propagate a multicast group membership operation (add/drop) on
25769  * all the interfaces crossed by the related multirt routes.
25770  * The call is considered successful if the operation succeeds
25771  * on at least one interface.
25772  */
25773 static int
25774 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25775     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25776     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25777     mblk_t *first_mp)
25778 {
25779 	ire_t		*ire_gw;
25780 	irb_t		*irb;
25781 	int		error = 0;
25782 	opt_restart_t	*or;
25783 
25784 	irb = ire->ire_bucket;
25785 	ASSERT(irb != NULL);
25786 
25787 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25788 
25789 	or = (opt_restart_t *)first_mp->b_rptr;
25790 	IRB_REFHOLD(irb);
25791 	for (; ire != NULL; ire = ire->ire_next) {
25792 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25793 			continue;
25794 		if (ire->ire_addr != group)
25795 			continue;
25796 
25797 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25798 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25799 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25800 		/* No resolver exists for the gateway; skip this ire. */
25801 		if (ire_gw == NULL)
25802 			continue;
25803 
25804 		/*
25805 		 * This function can return EINPROGRESS. If so the operation
25806 		 * will be restarted from ip_restart_optmgmt which will
25807 		 * call ip_opt_set and option processing will restart for
25808 		 * this option. So we may end up calling 'fn' more than once.
25809 		 * This requires that 'fn' is idempotent except for the
25810 		 * return value. The operation is considered a success if
25811 		 * it succeeds at least once on any one interface.
25812 		 */
25813 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25814 		    NULL, fmode, src, first_mp);
25815 		if (error == 0)
25816 			or->or_private = CGTP_MCAST_SUCCESS;
25817 
25818 		if (ip_debug > 0) {
25819 			ulong_t	off;
25820 			char	*ksym;
25821 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25822 			ip2dbg(("ip_multirt_apply_membership: "
25823 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25824 			    "error %d [success %u]\n",
25825 			    ksym ? ksym : "?",
25826 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25827 			    error, or->or_private));
25828 		}
25829 
25830 		ire_refrele(ire_gw);
25831 		if (error == EINPROGRESS) {
25832 			IRB_REFRELE(irb);
25833 			return (error);
25834 		}
25835 	}
25836 	IRB_REFRELE(irb);
25837 	/*
25838 	 * Consider the call as successful if we succeeded on at least
25839 	 * one interface. Otherwise, return the last encountered error.
25840 	 */
25841 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25842 }
25843 
25844 
25845 /*
25846  * Issue a warning regarding a route crossing an interface with an
25847  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25848  * amount of time is logged.
25849  */
25850 static void
25851 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25852 {
25853 	hrtime_t	current = gethrtime();
25854 	char		buf[16];
25855 
25856 	/* Convert interval in ms to hrtime in ns */
25857 	if (multirt_bad_mtu_last_time +
25858 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25859 	    current) {
25860 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25861 		    "to %s, incorrect MTU %u (expected %u)\n",
25862 		    ip_dot_addr(ire->ire_addr, buf),
25863 		    ire->ire_max_frag, max_frag);
25864 
25865 		multirt_bad_mtu_last_time = current;
25866 	}
25867 }
25868 
25869 
25870 /*
25871  * Get the CGTP (multirouting) filtering status.
25872  * If 0, the CGTP hooks are transparent.
25873  */
25874 /* ARGSUSED */
25875 static int
25876 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25877 {
25878 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25879 
25880 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25881 	return (0);
25882 }
25883 
25884 
25885 /*
25886  * Set the CGTP (multirouting) filtering status.
25887  * If the status is changed from active to transparent
25888  * or from transparent to active, forward the new status
25889  * to the filtering module (if loaded).
25890  */
25891 /* ARGSUSED */
25892 static int
25893 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25894     cred_t *ioc_cr)
25895 {
25896 	long		new_value;
25897 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25898 
25899 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25900 	    new_value < 0 || new_value > 1) {
25901 		return (EINVAL);
25902 	}
25903 
25904 	/*
25905 	 * Do not enable CGTP filtering - thus preventing the hooks
25906 	 * from being invoked - if the version number of the
25907 	 * filtering module hooks does not match.
25908 	 */
25909 	if ((ip_cgtp_filter_ops != NULL) &&
25910 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25911 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25912 		    "(module hooks version %d, expecting %d)\n",
25913 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25914 		return (ENOTSUP);
25915 	}
25916 
25917 	if ((!*ip_cgtp_filter_value) && new_value) {
25918 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25919 		    ip_cgtp_filter_ops == NULL ?
25920 		    " (module not loaded)" : "");
25921 	}
25922 	if (*ip_cgtp_filter_value && (!new_value)) {
25923 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25924 		    ip_cgtp_filter_ops == NULL ?
25925 		    " (module not loaded)" : "");
25926 	}
25927 
25928 	if (ip_cgtp_filter_ops != NULL) {
25929 		int	res;
25930 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25931 			return (res);
25932 		}
25933 	}
25934 
25935 	*ip_cgtp_filter_value = (boolean_t)new_value;
25936 
25937 	return (0);
25938 }
25939 
25940 
25941 /*
25942  * Return the expected CGTP hooks version number.
25943  */
25944 int
25945 ip_cgtp_filter_supported(void)
25946 {
25947 	return (ip_cgtp_filter_rev);
25948 }
25949 
25950 
25951 /*
25952  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25953  * or by invoking this function. In the first case, the version number
25954  * of the registered structure is checked at hooks activation time
25955  * in ip_cgtp_filter_set().
25956  */
25957 int
25958 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25959 {
25960 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25961 		return (ENOTSUP);
25962 
25963 	ip_cgtp_filter_ops = ops;
25964 	return (0);
25965 }
25966 
25967 static squeue_func_t
25968 ip_squeue_switch(int val)
25969 {
25970 	squeue_func_t rval = squeue_fill;
25971 
25972 	switch (val) {
25973 	case IP_SQUEUE_ENTER_NODRAIN:
25974 		rval = squeue_enter_nodrain;
25975 		break;
25976 	case IP_SQUEUE_ENTER:
25977 		rval = squeue_enter;
25978 		break;
25979 	default:
25980 		break;
25981 	}
25982 	return (rval);
25983 }
25984 
25985 /* ARGSUSED */
25986 static int
25987 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25988     caddr_t addr, cred_t *cr)
25989 {
25990 	int *v = (int *)addr;
25991 	long new_value;
25992 
25993 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25994 		return (EINVAL);
25995 
25996 	ip_input_proc = ip_squeue_switch(new_value);
25997 	*v = new_value;
25998 	return (0);
25999 }
26000 
26001 /* ARGSUSED */
26002 static int
26003 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26004     caddr_t addr, cred_t *cr)
26005 {
26006 	int *v = (int *)addr;
26007 	long new_value;
26008 
26009 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26010 		return (EINVAL);
26011 
26012 	*v = new_value;
26013 	return (0);
26014 }
26015 
26016 static void
26017 ip_kstat_init(void)
26018 {
26019 	ip_named_kstat_t template = {
26020 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26021 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26022 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26023 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26024 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26025 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26026 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26027 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26028 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26029 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26030 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26031 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26032 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26033 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26034 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26035 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26036 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26037 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26038 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26039 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26040 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26041 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26042 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26043 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26044 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26045 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26046 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26047 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26048 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26049 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26050 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26051 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26052 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26053 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26054 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26055 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26056 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26057 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26058 	};
26059 
26060 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26061 					NUM_OF_FIELDS(ip_named_kstat_t),
26062 					0);
26063 	if (!ip_mibkp)
26064 		return;
26065 
26066 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26067 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26068 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26069 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26070 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26071 
26072 	template.netToMediaEntrySize.value.i32 =
26073 		sizeof (mib2_ipNetToMediaEntry_t);
26074 
26075 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26076 
26077 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26078 
26079 	ip_mibkp->ks_update = ip_kstat_update;
26080 
26081 	kstat_install(ip_mibkp);
26082 }
26083 
26084 static void
26085 ip_kstat_fini(void)
26086 {
26087 
26088 	if (ip_mibkp != NULL) {
26089 		kstat_delete(ip_mibkp);
26090 		ip_mibkp = NULL;
26091 	}
26092 }
26093 
26094 static int
26095 ip_kstat_update(kstat_t *kp, int rw)
26096 {
26097 	ip_named_kstat_t *ipkp;
26098 
26099 	if (!kp || !kp->ks_data)
26100 		return (EIO);
26101 
26102 	if (rw == KSTAT_WRITE)
26103 		return (EACCES);
26104 
26105 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26106 
26107 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26108 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26109 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26110 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26111 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26112 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26113 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26114 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26115 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26116 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26117 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26118 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26119 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26120 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26121 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26122 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26123 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26124 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26125 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26126 
26127 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26128 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26129 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26130 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26131 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26132 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26133 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26134 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26135 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26136 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26137 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26138 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26139 
26140 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
26141 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
26142 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
26143 
26144 	return (0);
26145 }
26146 
26147 static void
26148 icmp_kstat_init(void)
26149 {
26150 	icmp_named_kstat_t template = {
26151 		{ "inMsgs",		KSTAT_DATA_UINT32 },
26152 		{ "inErrors",		KSTAT_DATA_UINT32 },
26153 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
26154 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
26155 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
26156 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
26157 		{ "inRedirects",	KSTAT_DATA_UINT32 },
26158 		{ "inEchos",		KSTAT_DATA_UINT32 },
26159 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
26160 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
26161 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
26162 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
26163 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
26164 		{ "outMsgs",		KSTAT_DATA_UINT32 },
26165 		{ "outErrors",		KSTAT_DATA_UINT32 },
26166 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
26167 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
26168 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
26169 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
26170 		{ "outRedirects",	KSTAT_DATA_UINT32 },
26171 		{ "outEchos",		KSTAT_DATA_UINT32 },
26172 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
26173 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
26174 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
26175 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
26176 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
26177 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
26178 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
26179 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
26180 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
26181 		{ "outDrops",		KSTAT_DATA_UINT32 },
26182 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
26183 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
26184 	};
26185 
26186 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
26187 					NUM_OF_FIELDS(icmp_named_kstat_t),
26188 					0);
26189 	if (icmp_mibkp == NULL)
26190 		return;
26191 
26192 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
26193 
26194 	icmp_mibkp->ks_update = icmp_kstat_update;
26195 
26196 	kstat_install(icmp_mibkp);
26197 }
26198 
26199 static void
26200 icmp_kstat_fini(void)
26201 {
26202 
26203 	if (icmp_mibkp != NULL) {
26204 		kstat_delete(icmp_mibkp);
26205 		icmp_mibkp = NULL;
26206 	}
26207 }
26208 
26209 static int
26210 icmp_kstat_update(kstat_t *kp, int rw)
26211 {
26212 	icmp_named_kstat_t *icmpkp;
26213 
26214 	if ((kp == NULL) || (kp->ks_data == NULL))
26215 		return (EIO);
26216 
26217 	if (rw == KSTAT_WRITE)
26218 		return (EACCES);
26219 
26220 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
26221 
26222 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
26223 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
26224 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
26225 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
26226 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
26227 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
26228 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
26229 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
26230 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
26231 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
26232 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
26233 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
26234 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
26235 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
26236 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
26237 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
26238 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
26239 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
26240 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
26241 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
26242 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
26243 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
26244 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
26245 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
26246 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
26247 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
26248 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
26249 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
26250 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
26251 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
26252 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
26253 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
26254 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
26255 
26256 	return (0);
26257 }
26258 
26259 /*
26260  * This is the fanout function for raw socket opened for SCTP.  Note
26261  * that it is called after SCTP checks that there is no socket which
26262  * wants a packet.  Then before SCTP handles this out of the blue packet,
26263  * this function is called to see if there is any raw socket for SCTP.
26264  * If there is and it is bound to the correct address, the packet will
26265  * be sent to that socket.  Note that only one raw socket can be bound to
26266  * a port.  This is assured in ipcl_sctp_hash_insert();
26267  */
26268 void
26269 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
26270     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
26271     uint_t ipif_seqid, zoneid_t zoneid)
26272 {
26273 	conn_t		*connp;
26274 	queue_t		*rq;
26275 	mblk_t		*first_mp;
26276 	boolean_t	secure;
26277 	ip6_t		*ip6h;
26278 
26279 	first_mp = mp;
26280 	if (mctl_present) {
26281 		mp = first_mp->b_cont;
26282 		secure = ipsec_in_is_secure(first_mp);
26283 		ASSERT(mp != NULL);
26284 	} else {
26285 		secure = B_FALSE;
26286 	}
26287 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
26288 
26289 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
26290 	if (connp == NULL) {
26291 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
26292 		    mctl_present);
26293 		return;
26294 	}
26295 	rq = connp->conn_rq;
26296 	if (!canputnext(rq)) {
26297 		CONN_DEC_REF(connp);
26298 		BUMP_MIB(&ip_mib, rawipInOverflows);
26299 		freemsg(first_mp);
26300 		return;
26301 	}
26302 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
26303 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
26304 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
26305 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
26306 		if (first_mp == NULL) {
26307 			CONN_DEC_REF(connp);
26308 			return;
26309 		}
26310 	}
26311 	/*
26312 	 * We probably should not send M_CTL message up to
26313 	 * raw socket.
26314 	 */
26315 	if (mctl_present)
26316 		freeb(first_mp);
26317 
26318 	/* Initiate IPPF processing here if needed. */
26319 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
26320 	    (!isv4 && IP6_IN_IPP(flags))) {
26321 		ip_process(IPP_LOCAL_IN, &mp,
26322 		    recv_ill->ill_phyint->phyint_ifindex);
26323 		if (mp == NULL) {
26324 			CONN_DEC_REF(connp);
26325 			return;
26326 		}
26327 	}
26328 
26329 	if (connp->conn_recvif || connp->conn_recvslla ||
26330 	    ((connp->conn_ipv6_recvpktinfo ||
26331 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
26332 	    (flags & IP_FF_IP6INFO))) {
26333 		int in_flags = 0;
26334 
26335 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
26336 			in_flags = IPF_RECVIF;
26337 		}
26338 		if (connp->conn_recvslla) {
26339 			in_flags |= IPF_RECVSLLA;
26340 		}
26341 		if (isv4) {
26342 			mp = ip_add_info(mp, recv_ill, in_flags);
26343 		} else {
26344 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
26345 			if (mp == NULL) {
26346 				CONN_DEC_REF(connp);
26347 				return;
26348 			}
26349 		}
26350 	}
26351 
26352 	BUMP_MIB(&ip_mib, ipInDelivers);
26353 	/*
26354 	 * We are sending the IPSEC_IN message also up. Refer
26355 	 * to comments above this function.
26356 	 */
26357 	putnext(rq, mp);
26358 	CONN_DEC_REF(connp);
26359 }
26360 
26361 /*
26362  * Martian Address Filtering [RFC 1812, Section 5.3.7]
26363  */
26364 static boolean_t
26365 ip_no_forward(ipha_t *ipha, ill_t *ill)
26366 {
26367 	ipaddr_t ip_src, ip_dst;
26368 	ire_t *src_ire = NULL;
26369 
26370 	ip_src = ntohl(ipha->ipha_src);
26371 	ip_dst = ntohl(ipha->ipha_dst);
26372 
26373 	if (ip_dst == INADDR_ANY)
26374 		goto dont_forward;
26375 
26376 	if (IN_CLASSD(ip_src))
26377 		goto dont_forward;
26378 
26379 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
26380 		goto dont_forward;
26381 
26382 	if (IN_BADCLASS(ip_dst))
26383 		goto dont_forward;
26384 
26385 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
26386 	    ALL_ZONES, MATCH_IRE_TYPE);
26387 	if (src_ire != NULL) {
26388 		ire_refrele(src_ire);
26389 		goto dont_forward;
26390 	}
26391 
26392 	return (B_FALSE);
26393 
26394 dont_forward:
26395 	if (ip_debug > 2) {
26396 		printf("ip_no_forward: dropping packet received on %s\n",
26397 		    ill->ill_name);
26398 		pr_addr_dbg("ip_no_forward: from src %s\n",
26399 		    AF_INET, &ipha->ipha_src);
26400 		pr_addr_dbg("ip_no_forward: to dst %s\n",
26401 		    AF_INET, &ipha->ipha_dst);
26402 	}
26403 	BUMP_MIB(&ip_mib, ipForwProhibits);
26404 	return (B_TRUE);
26405 }
26406 
26407 static boolean_t
26408 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
26409 {
26410 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
26411 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
26412 		if (ip_debug > 2) {
26413 			if (ill != NULL) {
26414 				printf("ip_loopback_src_or_dst: "
26415 				    "dropping packet received on %s\n",
26416 				    ill->ill_name);
26417 			} else {
26418 				printf("ip_loopback_src_or_dst: "
26419 				    "dropping packet\n");
26420 			}
26421 
26422 			pr_addr_dbg(
26423 			    "ip_loopback_src_or_dst: from src %s\n",
26424 			    AF_INET, &ipha->ipha_src);
26425 			pr_addr_dbg(
26426 			    "ip_loopback_src_or_dst: to dst %s\n",
26427 			    AF_INET, &ipha->ipha_dst);
26428 		}
26429 
26430 		BUMP_MIB(&ip_mib, ipInAddrErrors);
26431 		return (B_TRUE);
26432 	}
26433 	return (B_FALSE);
26434 }
26435