xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 43d18f1c320355e93c47399bea0b2e022fe06364)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_rts.h>
87 #include <inet/optcom.h>
88 #include <inet/ip_ndp.h>
89 #include <inet/ip_listutils.h>
90 #include <netinet/igmp.h>
91 #include <netinet/ip_mroute.h>
92 #include <inet/ipp_common.h>
93 
94 #include <net/pfkeyv2.h>
95 #include <inet/ipsec_info.h>
96 #include <inet/sadb.h>
97 #include <inet/ipsec_impl.h>
98 #include <sys/iphada.h>
99 #include <inet/tun.h>
100 #include <inet/ipdrop.h>
101 
102 #include <sys/ethernet.h>
103 #include <net/if_types.h>
104 #include <sys/cpuvar.h>
105 
106 #include <ipp/ipp.h>
107 #include <ipp/ipp_impl.h>
108 #include <ipp/ipgpc/ipgpc.h>
109 
110 #include <sys/multidata.h>
111 #include <sys/pattr.h>
112 
113 #include <inet/ipclassifier.h>
114 #include <inet/sctp_ip.h>
115 #include <inet/udp_impl.h>
116 
117 /*
118  * Values for squeue switch:
119  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
120  * IP_SQUEUE_ENTER: squeue_enter
121  * IP_SQUEUE_FILL: squeue_fill
122  */
123 int ip_squeue_enter = 2;
124 squeue_func_t ip_input_proc;
125 /*
126  * IP statistics.
127  */
128 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
129 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
130 
131 typedef struct ip_stat {
132 	kstat_named_t	ipsec_fanout_proto;
133 	kstat_named_t	ip_udp_fannorm;
134 	kstat_named_t	ip_udp_fanmb;
135 	kstat_named_t	ip_udp_fanothers;
136 	kstat_named_t	ip_udp_fast_path;
137 	kstat_named_t	ip_udp_slow_path;
138 	kstat_named_t	ip_udp_input_err;
139 	kstat_named_t	ip_tcppullup;
140 	kstat_named_t	ip_tcpoptions;
141 	kstat_named_t	ip_multipkttcp;
142 	kstat_named_t	ip_tcp_fast_path;
143 	kstat_named_t	ip_tcp_slow_path;
144 	kstat_named_t	ip_tcp_input_error;
145 	kstat_named_t	ip_db_ref;
146 	kstat_named_t	ip_notaligned1;
147 	kstat_named_t	ip_notaligned2;
148 	kstat_named_t	ip_multimblk3;
149 	kstat_named_t	ip_multimblk4;
150 	kstat_named_t	ip_ipoptions;
151 	kstat_named_t	ip_classify_fail;
152 	kstat_named_t	ip_opt;
153 	kstat_named_t	ip_udp_rput_local;
154 	kstat_named_t	ipsec_proto_ahesp;
155 	kstat_named_t	ip_conn_flputbq;
156 	kstat_named_t	ip_conn_walk_drain;
157 	kstat_named_t   ip_out_sw_cksum;
158 	kstat_named_t   ip_in_sw_cksum;
159 	kstat_named_t   ip_trash_ire_reclaim_calls;
160 	kstat_named_t   ip_trash_ire_reclaim_success;
161 	kstat_named_t   ip_ire_arp_timer_expired;
162 	kstat_named_t   ip_ire_redirect_timer_expired;
163 	kstat_named_t	ip_ire_pmtu_timer_expired;
164 	kstat_named_t	ip_input_multi_squeue;
165 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
166 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
167 	kstat_named_t	ip_tcp_in_sw_cksum_err;
168 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
169 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
170 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
171 	kstat_named_t	ip_udp_in_sw_cksum_err;
172 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
173 	kstat_named_t	ip_frag_mdt_pkt_out;
174 	kstat_named_t	ip_frag_mdt_discarded;
175 	kstat_named_t	ip_frag_mdt_allocfail;
176 	kstat_named_t	ip_frag_mdt_addpdescfail;
177 	kstat_named_t	ip_frag_mdt_allocd;
178 } ip_stat_t;
179 
180 static ip_stat_t ip_statistics = {
181 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
182 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
183 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
184 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
185 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
186 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
187 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
188 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
189 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
190 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
191 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
192 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
193 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
194 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
195 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
196 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
197 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
198 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
199 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
200 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
201 	{ "ip_opt",				KSTAT_DATA_UINT64 },
202 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
203 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
204 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
205 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
206 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
207 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
208 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
209 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
210 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
211 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
212 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
213 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
214 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
215 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
216 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
217 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
218 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
219 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
220 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
221 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
222 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
223 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
224 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
225 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
226 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
227 };
228 
229 static kstat_t *ip_kstat;
230 
231 #define	TCP6 "tcp6"
232 #define	TCP "tcp"
233 #define	SCTP "sctp"
234 #define	SCTP6 "sctp6"
235 
236 major_t TCP6_MAJ;
237 major_t TCP_MAJ;
238 major_t SCTP_MAJ;
239 major_t SCTP6_MAJ;
240 
241 int ip_poll_normal_ms = 100;
242 int ip_poll_normal_ticks = 0;
243 
244 /*
245  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
246  */
247 
248 struct listptr_s {
249 	mblk_t	*lp_head;	/* pointer to the head of the list */
250 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
251 };
252 
253 typedef struct listptr_s listptr_t;
254 
255 /*
256  * Cluster specific hooks. These should be NULL when booted as a non-cluster
257  */
258 
259 /*
260  * Hook functions to enable cluster networking
261  * On non-clustered systems these vectors must always be NULL.
262  *
263  * Hook function to Check ip specified ip address is a shared ip address
264  * in the cluster
265  *
266  */
267 int (*cl_inet_isclusterwide)(uint8_t protocol,
268     sa_family_t addr_family, uint8_t *laddrp) = NULL;
269 
270 /*
271  * Hook function to generate cluster wide ip fragment identifier
272  */
273 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
274     uint8_t *laddrp, uint8_t *faddrp) = NULL;
275 
276 /*
277  * Synchronization notes:
278  *
279  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
280  * MT level protection given by STREAMS. IP uses a combination of its own
281  * internal serialization mechanism and standard Solaris locking techniques.
282  * The internal serialization is per phyint (no IPMP) or per IPMP group.
283  * This is used to serialize plumbing operations, IPMP operations, certain
284  * multicast operations, most set ioctls, igmp/mld timers etc.
285  *
286  * Plumbing is a long sequence of operations involving message
287  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
288  * involved in plumbing operations. A natural model is to serialize these
289  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
290  * parallel without any interference. But various set ioctls on hme0 are best
291  * serialized. However if the system uses IPMP, the operations are easier if
292  * they are serialized on a per IPMP group basis since IPMP operations
293  * happen across ill's of a group. Thus the lowest common denominator is to
294  * serialize most set ioctls, multicast join/leave operations, IPMP operations
295  * igmp/mld timer operations, and processing of DLPI control messages received
296  * from drivers on a per IPMP group basis. If the system does not employ
297  * IPMP the serialization is on a per phyint basis. This serialization is
298  * provided by the ipsq_t and primitives operating on this. Details can
299  * be found in ip_if.c above the core primitives operating on ipsq_t.
300  *
301  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
302  * Simiarly lookup of an ire by a thread also returns a refheld ire.
303  * In addition ipif's and ill's referenced by the ire are also indirectly
304  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
305  * the ipif's address or netmask change as long as an ipif is refheld
306  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
307  * address of an ipif has to go through the ipsq_t. This ensures that only
308  * 1 such exclusive operation proceeds at any time on the ipif. It then
309  * deletes all ires associated with this ipif, and waits for all refcnts
310  * associated with this ipif to come down to zero. The address is changed
311  * only after the ipif has been quiesced. Then the ipif is brought up again.
312  * More details are described above the comment in ip_sioctl_flags.
313  *
314  * Packet processing is based mostly on IREs and are fully multi-threaded
315  * using standard Solaris MT techniques.
316  *
317  * There are explicit locks in IP to handle:
318  * - The ip_g_head list maintained by mi_open_link() and friends.
319  *
320  * - The reassembly data structures (one lock per hash bucket)
321  *
322  * - conn_lock is meant to protect conn_t fields. The fields actually
323  *   protected by conn_lock are documented in the conn_t definition.
324  *
325  * - ire_lock to protect some of the fields of the ire, IRE tables
326  *   (one lock per hash bucket). Refer to ip_ire.c for details.
327  *
328  * - ndp_g_lock and nce_lock for protecting NCEs.
329  *
330  * - ill_lock protects fields of the ill and ipif. Details in ip.h
331  *
332  * - ill_g_lock: This is a global reader/writer lock. Protects the following
333  *	* The AVL tree based global multi list of all ills.
334  *	* The linked list of all ipifs of an ill
335  *	* The <ill-ipsq> mapping
336  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
337  *	* The illgroup list threaded by ill_group_next.
338  *	* <ill-phyint> association
339  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
340  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
341  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
342  *   will all have to hold the ill_g_lock as writer for the actual duration
343  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
344  *   may be found in the IPMP section.
345  *
346  * - ill_lock:  This is a per ill mutex.
347  *   It protects some members of the ill and is documented below.
348  *   It also protects the <ill-ipsq> mapping
349  *   It also protects the illgroup list threaded by ill_group_next.
350  *   It also protects the <ill-phyint> assoc.
351  *   It also protects the list of ipifs hanging off the ill.
352  *
353  * - ipsq_lock: This is a per ipsq_t mutex lock.
354  *   This protects all the other members of the ipsq struct except
355  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
356  *
357  * - illgrp_lock: This is a per ill_group mutex lock.
358  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
359  *   which dictates which is the next ill in an ill_group that is to be chosen
360  *   for sending outgoing packets, through creation of an IRE_CACHE that
361  *   references this ill.
362  *
363  * - phyint_lock: This is a per phyint mutex lock. Protects just the
364  *   phyint_flags
365  *
366  * - ip_g_nd_lock: This is a global reader/writer lock.
367  *   Any call to nd_load to load a new parameter to the ND table must hold the
368  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
369  *   as reader.
370  *
371  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
372  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
373  *   uniqueness check also done atomically.
374  *
375  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
376  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
377  *   as a writer when adding or deleting elements from these lists, and
378  *   as a reader when walking these lists to send a SADB update to the
379  *   IPsec capable ills.
380  *
381  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
382  *   group list linked by ill_usesrc_grp_next. It also protects the
383  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
384  *   group is being added or deleted.  This lock is taken as a reader when
385  *   walking the list/group(eg: to get the number of members in a usesrc group).
386  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
387  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
388  *   example, it is not necessary to take this lock in the initial portion
389  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
390  *   ip_sioctl_flags since the these operations are executed exclusively and
391  *   that ensures that the "usesrc group state" cannot change. The "usesrc
392  *   group state" change can happen only in the latter part of
393  *   ip_sioctl_slifusesrc and in ill_delete.
394  *
395  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
396  *
397  * To change the <ill-phyint> association, the ill_g_lock must be held
398  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
399  * must be held.
400  *
401  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
402  * and the ill_lock of the ill in question must be held.
403  *
404  * To change the <ill-illgroup> association the ill_g_lock must be held as
405  * writer and the ill_lock of the ill in question must be held.
406  *
407  * To add or delete an ipif from the list of ipifs hanging off the ill,
408  * ill_g_lock (writer) and ill_lock must be held and the thread must be
409  * a writer on the associated ipsq,.
410  *
411  * To add or delete an ill to the system, the ill_g_lock must be held as
412  * writer and the thread must be a writer on the associated ipsq.
413  *
414  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
415  * must be a writer on the associated ipsq.
416  *
417  * Lock hierarchy
418  *
419  * Some lock hierarchy scenarios are listed below.
420  *
421  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
422  * ill_g_lock -> illgrp_lock -> ill_lock
423  * ill_g_lock -> ill_lock(s) -> phyint_lock
424  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
425  * ill_g_lock -> ip_addr_avail_lock
426  * conn_lock -> irb_lock -> ill_lock -> ire_lock
427  * ipsa_lock -> ill_g_lock -> ill_lock
428  * ill_g_lock -> ip_g_nd_lock
429  * irb_lock -> ill_lock -> ire_mrtun_lock
430  * irb_lock -> ill_lock -> ire_srcif_table_lock
431  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
432  * ipsec_capab_ills_lock -> ipsa_lock
433  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
434  *
435  * When more than 1 ill lock is needed to be held, all ill lock addresses
436  * are sorted on address and locked starting from highest addressed lock
437  * downward.
438  *
439  * IPSEC notes :
440  *
441  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
442  * in front of the actual packet. For outbound datagrams, the M_CTL
443  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
444  * information used by the IPSEC code for applying the right level of
445  * protection. The information initialized by IP in the ipsec_out_t
446  * is determined by the per-socket policy or global policy in the system.
447  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
448  * ipsec_info.h) which starts out with nothing in it. It gets filled
449  * with the right information if it goes through the AH/ESP code, which
450  * happens if the incoming packet is secure. The information initialized
451  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
452  * the policy requirements needed by per-socket policy or global policy
453  * is met or not.
454  *
455  * If there is both per-socket policy (set using setsockopt) and there
456  * is also global policy match for the 5 tuples of the socket,
457  * ipsec_override_policy() makes the decision of which one to use.
458  *
459  * For fully connected sockets i.e dst, src [addr, port] is known,
460  * conn_policy_cached is set indicating that policy has been cached.
461  * conn_in_enforce_policy may or may not be set depending on whether
462  * there is a global policy match or per-socket policy match.
463  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
464  * Once the right policy is set on the conn_t, policy cannot change for
465  * this socket. This makes life simpler for TCP (UDP ?) where
466  * re-transmissions go out with the same policy. For symmetry, policy
467  * is cached for fully connected UDP sockets also. Thus if policy is cached,
468  * it also implies that policy is latched i.e policy cannot change
469  * on these sockets. As we have the right policy on the conn, we don't
470  * have to lookup global policy for every outbound and inbound datagram
471  * and thus serving as an optimization. Note that a global policy change
472  * does not affect fully connected sockets if they have policy. If fully
473  * connected sockets did not have any policy associated with it, global
474  * policy change may affect them.
475  *
476  * IP Flow control notes:
477  *
478  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
479  * cannot be sent down to the driver by IP, because of a canput failure, IP
480  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
481  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
482  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
483  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
484  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
485  * the queued messages, and removes the conn from the drain list, if all
486  * messages were drained. It also qenables the next conn in the drain list to
487  * continue the drain process.
488  *
489  * In reality the drain list is not a single list, but a configurable number
490  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
491  * list. If the ip_wsrv of the next qenabled conn does not run, because the
492  * stream closes, ip_close takes responsibility to qenable the next conn in
493  * the drain list. The directly called ip_wput path always does a putq, if
494  * it cannot putnext. Thus synchronization problems are handled between
495  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
496  * functions that manipulate this drain list. Furthermore conn_drain_insert
497  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
498  * running on a queue at any time. conn_drain_tail can be simultaneously called
499  * from both ip_wsrv and ip_close.
500  *
501  * IPQOS notes:
502  *
503  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
504  * and IPQoS modules. IPPF includes hooks in IP at different control points
505  * (callout positions) which direct packets to IPQoS modules for policy
506  * processing. Policies, if present, are global.
507  *
508  * The callout positions are located in the following paths:
509  *		o local_in (packets destined for this host)
510  *		o local_out (packets orginating from this host )
511  *		o fwd_in  (packets forwarded by this m/c - inbound)
512  *		o fwd_out (packets forwarded by this m/c - outbound)
513  * Hooks at these callout points can be enabled/disabled using the ndd variable
514  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
515  * By default all the callout positions are enabled.
516  *
517  * Outbound (local_out)
518  * Hooks are placed in ip_wput_ire and ipsec_out_process.
519  *
520  * Inbound (local_in)
521  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
522  * TCP and UDP fanout routines.
523  *
524  * Forwarding (in and out)
525  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
526  *
527  * IP Policy Framework processing (IPPF processing)
528  * Policy processing for a packet is initiated by ip_process, which ascertains
529  * that the classifier (ipgpc) is loaded and configured, failing which the
530  * packet resumes normal processing in IP. If the clasifier is present, the
531  * packet is acted upon by one or more IPQoS modules (action instances), per
532  * filters configured in ipgpc and resumes normal IP processing thereafter.
533  * An action instance can drop a packet in course of its processing.
534  *
535  * A boolean variable, ip_policy, is used in all the fanout routines that can
536  * invoke ip_process for a packet. This variable indicates if the packet should
537  * to be sent for policy processing. The variable is set to B_TRUE by default,
538  * i.e. when the routines are invoked in the normal ip procesing path for a
539  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
540  * ip_policy is set to B_FALSE for all the routines called in these two
541  * functions because, in the former case,  we don't process loopback traffic
542  * currently while in the latter, the packets have already been processed in
543  * icmp_inbound.
544  *
545  * Zones notes:
546  *
547  * The partitioning rules for networking are as follows:
548  * 1) Packets coming from a zone must have a source address belonging to that
549  * zone.
550  * 2) Packets coming from a zone can only be sent on a physical interface on
551  * which the zone has an IP address.
552  * 3) Between two zones on the same machine, packet delivery is only allowed if
553  * there's a matching route for the destination and zone in the forwarding
554  * table.
555  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
556  * different zones can bind to the same port with the wildcard address
557  * (INADDR_ANY).
558  *
559  * The granularity of interface partitioning is at the logical interface level.
560  * Therefore, every zone has its own IP addresses, and incoming packets can be
561  * attributed to a zone unambiguously. A logical interface is placed into a zone
562  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
563  * structure. Rule (1) is implemented by modifying the source address selection
564  * algorithm so that the list of eligible addresses is filtered based on the
565  * sending process zone.
566  *
567  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
568  * across all zones, depending on their type. Here is the break-up:
569  *
570  * IRE type				Shared/exclusive
571  * --------				----------------
572  * IRE_BROADCAST			Exclusive
573  * IRE_DEFAULT (default routes)		Shared (*)
574  * IRE_LOCAL				Exclusive
575  * IRE_LOOPBACK				Exclusive
576  * IRE_PREFIX (net routes)		Shared (*)
577  * IRE_CACHE				Exclusive
578  * IRE_IF_NORESOLVER (interface routes)	Exclusive
579  * IRE_IF_RESOLVER (interface routes)	Exclusive
580  * IRE_HOST (host routes)		Shared (*)
581  *
582  * (*) A zone can only use a default or off-subnet route if the gateway is
583  * directly reachable from the zone, that is, if the gateway's address matches
584  * one of the zone's logical interfaces.
585  *
586  * Multiple zones can share a common broadcast address; typically all zones
587  * share the 255.255.255.255 address. Incoming as well as locally originated
588  * broadcast packets must be dispatched to all the zones on the broadcast
589  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
590  * since some zones may not be on the 10.16.72/24 network. To handle this, each
591  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
592  * sent to every zone that has an IRE_BROADCAST entry for the destination
593  * address on the input ill, see conn_wantpacket().
594  *
595  * Applications in different zones can join the same multicast group address.
596  * For IPv4, group memberships are per-logical interface, so they're already
597  * inherently part of a zone. For IPv6, group memberships are per-physical
598  * interface, so we distinguish IPv6 group memberships based on group address,
599  * interface and zoneid. In both cases, received multicast packets are sent to
600  * every zone for which a group membership entry exists. On IPv6 we need to
601  * check that the target zone still has an address on the receiving physical
602  * interface; it could have been removed since the application issued the
603  * IPV6_JOIN_GROUP.
604  */
605 
606 /*
607  * Squeue Fanout flags:
608  *	0: No fanout.
609  *	1: Fanout across all squeues
610  */
611 boolean_t	ip_squeue_fanout = 0;
612 
613 /*
614  * Maximum dups allowed per packet.
615  */
616 uint_t ip_max_frag_dups = 10;
617 
618 #define	IS_SIMPLE_IPH(ipha)						\
619 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
620 
621 /* RFC1122 Conformance */
622 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
623 
624 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
625 
626 /* Leave room for ip_newroute to tack on the src and target addresses */
627 #define	OK_RESOLVER_MP(mp)						\
628 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
629 
630 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
631 
632 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
633 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
634 
635 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
636 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
637     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
638 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
639 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
640 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
641 		    ill_t *, zoneid_t);
642 static void	icmp_options_update(ipha_t *);
643 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
644 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
645 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
646 static void	icmp_redirect(mblk_t *);
647 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
648 
649 static void	ip_arp_news(queue_t *, mblk_t *);
650 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
651 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
652 char		*ip_dot_addr(ipaddr_t, char *);
653 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
654 int		ip_close(queue_t *, int);
655 static char	*ip_dot_saddr(uchar_t *, char *);
656 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
657 		    boolean_t, boolean_t, ill_t *, zoneid_t);
658 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
659 		    boolean_t, boolean_t, zoneid_t);
660 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
661 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
662 static void	ip_lrput(queue_t *, mblk_t *);
663 ipaddr_t	ip_massage_options(ipha_t *);
664 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
665 ipaddr_t	ip_net_mask(ipaddr_t);
666 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
667 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
668 		    conn_t *, uint32_t);
669 static int	ip_hdr_complete(ipha_t *, zoneid_t);
670 char		*ip_nv_lookup(nv_t *, int);
671 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
672 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
673 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
674 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
675 			    size_t);
676 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
677 void	ip_rput(queue_t *, mblk_t *);
678 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
679 		    void *dummy_arg);
680 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
681 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
682 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
683 			    ire_t *);
684 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
685 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
686 		    uint16_t *);
687 int		ip_snmp_get(queue_t *, mblk_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
689 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
690 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
691 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
692 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
693 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
694 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
695 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
696 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
698 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
699 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
700 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
701 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
703 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
704 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
705 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 
711 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
712 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
713 static void	ip_wput_local_options(ipha_t *);
714 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
715     zoneid_t);
716 
717 static void	conn_drain_init(void);
718 static void	conn_drain_fini(void);
719 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
720 
721 static void	conn_walk_drain(void);
722 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
723     zoneid_t);
724 
725 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
726     zoneid_t);
727 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
728     void *dummy_arg);
729 
730 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
731 
732 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
733     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
734     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
735 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
736 
737 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
738 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
739     caddr_t, cred_t *);
740 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
741     caddr_t cp, cred_t *cr);
742 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
743     cred_t *);
744 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
745     caddr_t cp, cred_t *cr);
746 static int	ip_fanout_set(queue_t *, mblk_t *, char *, caddr_t,
747     cred_t *);
748 static squeue_func_t ip_squeue_switch(int);
749 
750 static void	ip_kstat_init(void);
751 static void	ip_kstat_fini(void);
752 static int	ip_kstat_update(kstat_t *kp, int rw);
753 static void	icmp_kstat_init(void);
754 static void	icmp_kstat_fini(void);
755 static int	icmp_kstat_update(kstat_t *kp, int rw);
756 
757 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
758 
759 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
760 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
761 
762 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
763     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
764 
765 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
766 
767 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
768 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
769 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
770 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
771 
772 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
773 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
774 
775 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
776 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
777 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
778 
779 /* How long, in seconds, we allow frags to hang around. */
780 #define	IP_FRAG_TIMEOUT	60
781 
782 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
783 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
784 
785 /*
786  * Threshold which determines whether MDT should be used when
787  * generating IP fragments; payload size must be greater than
788  * this threshold for MDT to take place.
789  */
790 #define	IP_WPUT_FRAG_MDT_MIN	32768
791 
792 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
793 
794 /* Protected by ip_mi_lock */
795 static void	*ip_g_head;		/* Instance Data List Head */
796 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
797 
798 /* Only modified during _init and _fini thus no locking is needed. */
799 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
800 
801 
802 static long ip_rput_pullups;
803 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
804 
805 vmem_t *ip_minor_arena;
806 
807 /*
808  * MIB-2 stuff for SNMP (both IP and ICMP)
809  */
810 mib2_ip_t	ip_mib;
811 mib2_icmp_t	icmp_mib;
812 
813 #ifdef DEBUG
814 uint32_t ipsechw_debug = 0;
815 #endif
816 
817 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
818 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
819 
820 uint_t	loopback_packets = 0;
821 
822 /*
823  * Multirouting/CGTP stuff
824  */
825 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
826 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
827 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
828 /* Interval (in ms) between consecutive 'bad MTU' warnings */
829 hrtime_t ip_multirt_log_interval = 1000;
830 /* Time since last warning issued. */
831 static hrtime_t	multirt_bad_mtu_last_time = 0;
832 
833 kmutex_t ip_trash_timer_lock;
834 krwlock_t ip_g_nd_lock;
835 
836 /*
837  * XXX following really should only be in a header. Would need more
838  * header and .c clean up first.
839  */
840 extern optdb_obj_t	ip_opt_obj;
841 
842 ulong_t ip_squeue_enter_unbound = 0;
843 
844 /*
845  * Named Dispatch Parameter Table.
846  * All of these are alterable, within the min/max values given, at run time.
847  */
848 static ipparam_t	lcl_param_arr[] = {
849 	/* min	max	value	name */
850 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
851 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
852 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
853 	{  0,	1,	0,	"ip_respond_to_timestamp"},
854 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
855 	{  0,	1,	1,	"ip_send_redirects"},
856 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
857 	{  0,	10,	0,	"ip_debug"},
858 	{  0,	10,	0,	"ip_mrtdebug"},
859 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
860 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
861 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
862 	{  1,	255,	255,	"ip_def_ttl" },
863 	{  0,	1,	0,	"ip_forward_src_routed"},
864 	{  0,	256,	32,	"ip_wroff_extra" },
865 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
866 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
867 	{  0,	1,	1,	"ip_path_mtu_discovery" },
868 	{  0,	240,	30,	"ip_ignore_delete_time" },
869 	{  0,	1,	0,	"ip_ignore_redirect" },
870 	{  0,	1,	1,	"ip_output_queue" },
871 	{  1,	254,	1,	"ip_broadcast_ttl" },
872 	{  0,	99999,	100,	"ip_icmp_err_interval" },
873 	{  1,	99999,	10,	"ip_icmp_err_burst" },
874 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
875 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
876 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
877 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
878 	{  0,	1,	1,	"icmp_accept_clear_messages" },
879 	{  0,	1,	1,	"igmp_accept_clear_messages" },
880 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
881 				"ip_ndp_delay_first_probe_time"},
882 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
883 				"ip_ndp_max_unicast_solicit"},
884 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
885 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
886 	{  0,	1,	0,	"ip6_forward_src_routed"},
887 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
888 	{  0,	1,	1,	"ip6_send_redirects"},
889 	{  0,	1,	0,	"ip6_ignore_redirect" },
890 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
891 
892 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
893 
894 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
895 
896 	{  0,	1,	1,	"pim_accept_clear_messages" },
897 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
898 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
899 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
900 	{  0,	15,	0,	"ip_policy_mask" },
901 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
902 	{  0,	255,	1,	"ip_multirt_ttl" },
903 	{  0,	1,	1,	"ip_multidata_outbound" },
904 #ifdef DEBUG
905 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
906 #endif
907 };
908 
909 ipparam_t	*ip_param_arr = lcl_param_arr;
910 
911 /* Extended NDP table */
912 static ipndp_t	lcl_ndp_arr[] = {
913 	/* getf			setf		data			name */
914 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
915 	    "ip_forwarding" },
916 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
917 	    "ip6_forwarding" },
918 	{  ip_ill_report,	NULL,		NULL,
919 	    "ip_ill_status" },
920 	{  ip_ipif_report,	NULL,		NULL,
921 	    "ip_ipif_status" },
922 	{  ip_ire_report,	NULL,		NULL,
923 	    "ipv4_ire_status" },
924 	{  ip_ire_report_mrtun,	NULL,		NULL,
925 	    "ipv4_mrtun_ire_status" },
926 	{  ip_ire_report_srcif,	NULL,		NULL,
927 	    "ipv4_srcif_ire_status" },
928 	{  ip_ire_report_v6,	NULL,		NULL,
929 	    "ipv6_ire_status" },
930 	{  ip_conn_report,	NULL,		NULL,
931 	    "ip_conn_status" },
932 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
933 	    "ip_rput_pullups" },
934 	{  ndp_report,		NULL,		NULL,
935 	    "ip_ndp_cache_report" },
936 	{  ip_srcid_report,	NULL,		NULL,
937 	    "ip_srcid_status" },
938 	{ ip_param_generic_get, ip_squeue_profile_set,
939 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
940 	{ ip_param_generic_get, ip_squeue_bind_set,
941 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
942 	{ ip_param_generic_get, ip_input_proc_set,
943 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
944 	{ ip_param_generic_get, ip_fanout_set,
945 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
946 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
947 	    "ip_cgtp_filter" }
948 };
949 
950 /*
951  * ip_g_forward controls IP forwarding.  It takes two values:
952  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
953  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
954  *
955  * RFC1122 says there must be a configuration switch to control forwarding,
956  * but that the default MUST be to not forward packets ever.  Implicit
957  * control based on configuration of multiple interfaces MUST NOT be
958  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
959  * and, in fact, it was the default.  That capability is now provided in the
960  * /etc/rc2.d/S69inet script.
961  */
962 int ip_g_forward = IP_FORWARD_DEFAULT;
963 
964 /* It also has an IPv6 counterpart. */
965 
966 int ipv6_forward = IP_FORWARD_DEFAULT;
967 
968 /* Following line is external, and in ip.h.  Normally marked with * *. */
969 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
970 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
971 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
972 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
973 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
974 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
975 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
976 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
977 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
978 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
979 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
980 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
981 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
982 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
983 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
984 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
985 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
986 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
987 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
988 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
989 #define	ip_output_queue			ip_param_arr[20].ip_param_value
990 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
991 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
992 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
993 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
994 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
995 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
996 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
997 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
998 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
999 
1000 /* IPv6 configuration knobs */
1001 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1002 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1003 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1004 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1005 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1006 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1007 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1008 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1009 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1010 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1011 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1012 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1013 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1014 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1015 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1016 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1017 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1018 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1019 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1020 #ifdef DEBUG
1021 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1022 #else
1023 #define	ipv6_drop_inbound_icmpv6	0
1024 #endif
1025 
1026 
1027 /*
1028  * Table of IP ioctls encoding the various properties of the ioctl and
1029  * indexed based on the last byte of the ioctl command. Occasionally there
1030  * is a clash, and there is more than 1 ioctl with the same last byte.
1031  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1032  * ioctls are encoded in the misc table. An entry in the ndx table is
1033  * retrieved by indexing on the last byte of the ioctl command and comparing
1034  * the ioctl command with the value in the ndx table. In the event of a
1035  * mismatch the misc table is then searched sequentially for the desired
1036  * ioctl command.
1037  *
1038  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1039  */
1040 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1041 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 
1052 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1053 			MISC_CMD, ip_siocaddrt, NULL },
1054 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1055 			MISC_CMD, ip_siocdelrt, NULL },
1056 
1057 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1058 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1059 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1060 			IF_CMD, ip_sioctl_get_addr, NULL },
1061 
1062 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1063 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1064 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1065 			IPI_GET_CMD | IPI_REPL,
1066 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1067 
1068 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1069 			IPI_PRIV | IPI_WR | IPI_REPL,
1070 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1071 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1072 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1073 			IF_CMD, ip_sioctl_get_flags, NULL },
1074 
1075 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* copyin size cannot be coded for SIOCGIFCONF */
1079 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1080 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1081 
1082 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_mtu, NULL },
1084 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_mtu, NULL },
1086 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1087 			IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1089 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1090 			IF_CMD, ip_sioctl_brdaddr, NULL },
1091 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1092 			IPI_GET_CMD | IPI_REPL,
1093 			IF_CMD, ip_sioctl_get_netmask, NULL },
1094 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1095 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1096 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1097 			IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_metric, NULL },
1099 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1100 			IF_CMD, ip_sioctl_metric, NULL },
1101 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* See 166-168 below for extended SIOC*XARP ioctls */
1104 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1105 			MISC_CMD, ip_sioctl_arp, NULL },
1106 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1107 			MISC_CMD, ip_sioctl_arp, NULL },
1108 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1109 			MISC_CMD, ip_sioctl_arp, NULL },
1110 
1111 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 
1133 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1134 			MISC_CMD, if_unitsel, if_unitsel_restart },
1135 
1136 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 
1155 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1156 			IPI_PRIV | IPI_WR | IPI_MODOK,
1157 			IF_CMD, ip_sioctl_sifname, NULL },
1158 
1159 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 
1173 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1174 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1175 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1176 			IF_CMD, ip_sioctl_get_muxid, NULL },
1177 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR | IPI_REPL,
1179 			IF_CMD, ip_sioctl_muxid, NULL },
1180 
1181 	/* Both if and lif variants share same func */
1182 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1183 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1184 	/* Both if and lif variants share same func */
1185 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1186 			IPI_PRIV | IPI_WR | IPI_REPL,
1187 			IF_CMD, ip_sioctl_slifindex, NULL },
1188 
1189 	/* copyin size cannot be coded for SIOCGIFCONF */
1190 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1191 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1192 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 
1210 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			LIF_CMD, ip_sioctl_removeif,
1213 			ip_sioctl_removeif_restart },
1214 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1215 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1216 			LIF_CMD, ip_sioctl_addif, NULL },
1217 #define	SIOCLIFADDR_NDX 112
1218 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1219 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1220 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1221 			IPI_GET_CMD | IPI_REPL,
1222 			LIF_CMD, ip_sioctl_get_addr, NULL },
1223 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1224 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1225 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1226 			IPI_GET_CMD | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1228 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR | IPI_REPL,
1230 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1231 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1232 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1233 			LIF_CMD, ip_sioctl_get_flags, NULL },
1234 
1235 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 
1238 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1239 			ip_sioctl_get_lifconf, NULL },
1240 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1241 			LIF_CMD, ip_sioctl_mtu, NULL },
1242 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1244 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1247 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1248 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1249 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1250 			IPI_GET_CMD | IPI_REPL,
1251 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1252 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1253 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1254 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1255 			IPI_GET_CMD | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_get_metric, NULL },
1257 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1258 			LIF_CMD, ip_sioctl_metric, NULL },
1259 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1260 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1261 			LIF_CMD, ip_sioctl_slifname,
1262 			ip_sioctl_slifname_restart },
1263 
1264 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1265 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1266 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1269 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1270 			IPI_PRIV | IPI_WR | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_muxid, NULL },
1272 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1273 			IPI_GET_CMD | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1275 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1276 			IPI_PRIV | IPI_WR | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_slifindex, 0 },
1278 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_token, NULL },
1280 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_token, NULL },
1283 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1285 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1286 			IPI_GET_CMD | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1288 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1290 
1291 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1294 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1295 			LIF_CMD, ip_siocdelndp_v6, NULL },
1296 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1297 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1298 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1299 			LIF_CMD, ip_siocsetndp_v6, NULL },
1300 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1302 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1303 			MISC_CMD, ip_sioctl_tonlink, NULL },
1304 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1305 			MISC_CMD, ip_sioctl_tmysite, NULL },
1306 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1307 			TUN_CMD, ip_sioctl_tunparam, NULL },
1308 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1309 			IPI_PRIV | IPI_WR,
1310 			TUN_CMD, ip_sioctl_tunparam, NULL },
1311 
1312 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1313 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1314 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1315 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1316 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1317 
1318 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1319 			IPI_PRIV | IPI_WR | IPI_REPL,
1320 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1321 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1322 			IPI_PRIV | IPI_WR | IPI_REPL,
1323 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1324 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR,
1326 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1327 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1328 			IPI_GET_CMD | IPI_REPL,
1329 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1330 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1331 			IPI_GET_CMD | IPI_REPL,
1332 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1333 
1334 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1335 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1336 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1337 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1338 
1339 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1340 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1341 
1342 	/* These are handled in ip_sioctl_copyin_setup itself */
1343 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1344 			MISC_CMD, NULL, NULL },
1345 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1346 			MISC_CMD, NULL, NULL },
1347 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1348 
1349 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1350 			ip_sioctl_get_lifconf, NULL },
1351 
1352 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1353 			MISC_CMD, ip_sioctl_xarp, NULL },
1354 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1355 			MISC_CMD, ip_sioctl_xarp, NULL },
1356 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1357 			MISC_CMD, ip_sioctl_xarp, NULL },
1358 
1359 	/* SIOCPOPSOCKFS is not handled by IP */
1360 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1361 
1362 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1363 			IPI_GET_CMD | IPI_REPL,
1364 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1365 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1366 			IPI_PRIV | IPI_WR | IPI_REPL,
1367 			LIF_CMD, ip_sioctl_slifzone,
1368 			ip_sioctl_slifzone_restart },
1369 	/* 172-174 are SCTP ioctls and not handled by IP */
1370 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1371 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1372 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1373 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1374 			IPI_GET_CMD, LIF_CMD,
1375 			ip_sioctl_get_lifusesrc, 0 },
1376 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1377 			IPI_PRIV | IPI_WR,
1378 			LIF_CMD, ip_sioctl_slifusesrc,
1379 			NULL },
1380 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1381 			ip_sioctl_get_lifsrcof, NULL },
1382 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1383 			MISC_CMD, ip_sioctl_msfilter, NULL },
1384 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1385 			MISC_CMD, ip_sioctl_msfilter, NULL },
1386 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1387 			MISC_CMD, ip_sioctl_msfilter, NULL },
1388 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1389 			MISC_CMD, ip_sioctl_msfilter, NULL },
1390 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1391 			ip_sioctl_set_ipmpfailback, NULL }
1392 };
1393 
1394 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1395 
1396 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1397 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1398 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1399 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1400 		TUN_CMD, ip_sioctl_tunparam, NULL },
1401 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1402 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1403 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1404 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1405 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1406 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1407 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1408 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1409 		MISC_CMD, mrt_ioctl},
1410 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1411 		MISC_CMD, mrt_ioctl},
1412 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1413 		MISC_CMD, mrt_ioctl}
1414 };
1415 
1416 int ip_misc_ioctl_count =
1417     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1418 
1419 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1420 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1421 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1422 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1423 					/* Settable in /etc/system */
1424 
1425 /* Defined in ip_ire.c */
1426 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1427 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1428 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1429 
1430 static nv_t	ire_nv_arr[] = {
1431 	{ IRE_BROADCAST, "BROADCAST" },
1432 	{ IRE_LOCAL, "LOCAL" },
1433 	{ IRE_LOOPBACK, "LOOPBACK" },
1434 	{ IRE_CACHE, "CACHE" },
1435 	{ IRE_DEFAULT, "DEFAULT" },
1436 	{ IRE_PREFIX, "PREFIX" },
1437 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1438 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1439 	{ IRE_HOST, "HOST" },
1440 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1441 	{ 0 }
1442 };
1443 
1444 nv_t	*ire_nv_tbl = ire_nv_arr;
1445 
1446 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1447 extern krwlock_t ipsec_capab_ills_lock;
1448 
1449 /* Packet dropper for IP IPsec processing failures */
1450 ipdropper_t ip_dropper;
1451 
1452 /* Simple ICMP IP Header Template */
1453 static ipha_t icmp_ipha = {
1454 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1455 };
1456 
1457 struct module_info ip_mod_info = {
1458 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1459 };
1460 
1461 static struct qinit rinit = {
1462 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1463 	&ip_mod_info
1464 };
1465 
1466 static struct qinit winit = {
1467 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1468 	&ip_mod_info
1469 };
1470 
1471 static struct qinit lrinit = {
1472 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1473 	&ip_mod_info
1474 };
1475 
1476 static struct qinit lwinit = {
1477 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1478 	&ip_mod_info
1479 };
1480 
1481 struct streamtab ipinfo = {
1482 	&rinit, &winit, &lrinit, &lwinit
1483 };
1484 
1485 #ifdef	DEBUG
1486 static boolean_t skip_sctp_cksum = B_FALSE;
1487 #endif
1488 /*
1489  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1490  */
1491 mblk_t *
1492 ip_copymsg(mblk_t *mp)
1493 {
1494 	mblk_t *nmp;
1495 	ipsec_info_t *in;
1496 
1497 	if (mp->b_datap->db_type != M_CTL)
1498 		return (copymsg(mp));
1499 
1500 	in = (ipsec_info_t *)mp->b_rptr;
1501 
1502 	/*
1503 	 * Note that M_CTL is also used for delivering ICMP error messages
1504 	 * upstream to transport layers.
1505 	 */
1506 	if (in->ipsec_info_type != IPSEC_OUT &&
1507 	    in->ipsec_info_type != IPSEC_IN)
1508 		return (copymsg(mp));
1509 
1510 	nmp = copymsg(mp->b_cont);
1511 
1512 	if (in->ipsec_info_type == IPSEC_OUT)
1513 		return (ipsec_out_tag(mp, nmp));
1514 	else
1515 		return (ipsec_in_tag(mp, nmp));
1516 }
1517 
1518 /* Generate an ICMP fragmentation needed message. */
1519 static void
1520 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1521 {
1522 	icmph_t	icmph;
1523 	mblk_t *first_mp;
1524 	boolean_t mctl_present;
1525 
1526 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1527 
1528 	if (!(mp = icmp_pkt_err_ok(mp))) {
1529 		if (mctl_present)
1530 			freeb(first_mp);
1531 		return;
1532 	}
1533 
1534 	bzero(&icmph, sizeof (icmph_t));
1535 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1536 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1537 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1538 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1539 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1540 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1541 }
1542 
1543 /*
1544  * icmp_inbound deals with ICMP messages in the following ways.
1545  *
1546  * 1) It needs to send a reply back and possibly delivering it
1547  *    to the "interested" upper clients.
1548  * 2) It needs to send it to the upper clients only.
1549  * 3) It needs to change some values in IP only.
1550  * 4) It needs to change some values in IP and upper layers e.g TCP.
1551  *
1552  * We need to accomodate icmp messages coming in clear until we get
1553  * everything secure from the wire. If icmp_accept_clear_messages
1554  * is zero we check with the global policy and act accordingly. If
1555  * it is non-zero, we accept the message without any checks. But
1556  * *this does not mean* that this will be delivered to the upper
1557  * clients. By accepting we might send replies back, change our MTU
1558  * value etc. but delivery to the ULP/clients depends on their policy
1559  * dispositions.
1560  *
1561  * We handle the above 4 cases in the context of IPSEC in the
1562  * following way :
1563  *
1564  * 1) Send the reply back in the same way as the request came in.
1565  *    If it came in encrypted, it goes out encrypted. If it came in
1566  *    clear, it goes out in clear. Thus, this will prevent chosen
1567  *    plain text attack.
1568  * 2) The client may or may not expect things to come in secure.
1569  *    If it comes in secure, the policy constraints are checked
1570  *    before delivering it to the upper layers. If it comes in
1571  *    clear, ipsec_inbound_accept_clear will decide whether to
1572  *    accept this in clear or not. In both the cases, if the returned
1573  *    message (IP header + 8 bytes) that caused the icmp message has
1574  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1575  *    sending up. If there are only 8 bytes of returned message, then
1576  *    upper client will not be notified.
1577  * 3) Check with global policy to see whether it matches the constaints.
1578  *    But this will be done only if icmp_accept_messages_in_clear is
1579  *    zero.
1580  * 4) If we need to change both in IP and ULP, then the decision taken
1581  *    while affecting the values in IP and while delivering up to TCP
1582  *    should be the same.
1583  *
1584  * 	There are two cases.
1585  *
1586  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1587  *	   failed), we will not deliver it to the ULP, even though they
1588  *	   are *willing* to accept in *clear*. This is fine as our global
1589  *	   disposition to icmp messages asks us reject the datagram.
1590  *
1591  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1592  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1593  *	   to deliver it to ULP (policy failed), it can lead to
1594  *	   consistency problems. The cases known at this time are
1595  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1596  *	   values :
1597  *
1598  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1599  *	     and Upper layer rejects. Then the communication will
1600  *	     come to a stop. This is solved by making similar decisions
1601  *	     at both levels. Currently, when we are unable to deliver
1602  *	     to the Upper Layer (due to policy failures) while IP has
1603  *	     adjusted ire_max_frag, the next outbound datagram would
1604  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1605  *	     will be with the right level of protection. Thus the right
1606  *	     value will be communicated even if we are not able to
1607  *	     communicate when we get from the wire initially. But this
1608  *	     assumes there would be at least one outbound datagram after
1609  *	     IP has adjusted its ire_max_frag value. To make things
1610  *	     simpler, we accept in clear after the validation of
1611  *	     AH/ESP headers.
1612  *
1613  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1614  *	     upper layer depending on the level of protection the upper
1615  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1616  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1617  *	     should be accepted in clear when the Upper layer expects secure.
1618  *	     Thus the communication may get aborted by some bad ICMP
1619  *	     packets.
1620  *
1621  * IPQoS Notes:
1622  * The only instance when a packet is sent for processing is when there
1623  * isn't an ICMP client and if we are interested in it.
1624  * If there is a client, IPPF processing will take place in the
1625  * ip_fanout_proto routine.
1626  *
1627  * Zones notes:
1628  * The packet is only processed in the context of the specified zone: typically
1629  * only this zone will reply to an echo request, and only interested clients in
1630  * this zone will receive a copy of the packet. This means that the caller must
1631  * call icmp_inbound() for each relevant zone.
1632  */
1633 static void
1634 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1635     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1636     ill_t *recv_ill, zoneid_t zoneid)
1637 {
1638 	icmph_t	*icmph;
1639 	ipha_t	*ipha;
1640 	int	iph_hdr_length;
1641 	int	hdr_length;
1642 	boolean_t	interested;
1643 	uint32_t	ts;
1644 	uchar_t	*wptr;
1645 	ipif_t	*ipif;
1646 	mblk_t *first_mp;
1647 	ipsec_in_t *ii;
1648 	ire_t *src_ire;
1649 	boolean_t onlink;
1650 	timestruc_t now;
1651 	uint32_t ill_index;
1652 
1653 	ASSERT(ill != NULL);
1654 
1655 	first_mp = mp;
1656 	if (mctl_present) {
1657 		mp = first_mp->b_cont;
1658 		ASSERT(mp != NULL);
1659 	}
1660 
1661 	ipha = (ipha_t *)mp->b_rptr;
1662 	if (icmp_accept_clear_messages == 0) {
1663 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1664 		    ipha, NULL, mctl_present);
1665 		if (first_mp == NULL)
1666 			return;
1667 	}
1668 	/*
1669 	 * We have accepted the ICMP message. It means that we will
1670 	 * respond to the packet if needed. It may not be delivered
1671 	 * to the upper client depending on the policy constraints
1672 	 * and the disposition in ipsec_inbound_accept_clear.
1673 	 */
1674 
1675 	ASSERT(ill != NULL);
1676 
1677 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1678 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1679 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1680 		/* Last chance to get real. */
1681 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1682 			BUMP_MIB(&icmp_mib, icmpInErrors);
1683 			freemsg(first_mp);
1684 			return;
1685 		}
1686 		/* Refresh iph following the pullup. */
1687 		ipha = (ipha_t *)mp->b_rptr;
1688 	}
1689 	/* ICMP header checksum, including checksum field, should be zero. */
1690 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1691 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1692 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1693 		freemsg(first_mp);
1694 		return;
1695 	}
1696 	/* The IP header will always be a multiple of four bytes */
1697 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1698 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1699 	    icmph->icmph_code));
1700 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1701 	/* We will set "interested" to "true" if we want a copy */
1702 	interested = B_FALSE;
1703 	switch (icmph->icmph_type) {
1704 	case ICMP_ECHO_REPLY:
1705 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1706 		break;
1707 	case ICMP_DEST_UNREACHABLE:
1708 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1709 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1710 		interested = B_TRUE;	/* Pass up to transport */
1711 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1712 		break;
1713 	case ICMP_SOURCE_QUENCH:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1716 		break;
1717 	case ICMP_REDIRECT:
1718 		if (!ip_ignore_redirect)
1719 			interested = B_TRUE;
1720 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1721 		break;
1722 	case ICMP_ECHO_REQUEST:
1723 		/*
1724 		 * Whether to respond to echo requests that come in as IP
1725 		 * broadcasts or as IP multicast is subject to debate
1726 		 * (what isn't?).  We aim to please, you pick it.
1727 		 * Default is do it.
1728 		 */
1729 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1730 			/* unicast: always respond */
1731 			interested = B_TRUE;
1732 		} else if (CLASSD(ipha->ipha_dst)) {
1733 			/* multicast: respond based on tunable */
1734 			interested = ip_g_resp_to_echo_mcast;
1735 		} else if (broadcast) {
1736 			/* broadcast: respond based on tunable */
1737 			interested = ip_g_resp_to_echo_bcast;
1738 		}
1739 		BUMP_MIB(&icmp_mib, icmpInEchos);
1740 		break;
1741 	case ICMP_ROUTER_ADVERTISEMENT:
1742 	case ICMP_ROUTER_SOLICITATION:
1743 		break;
1744 	case ICMP_TIME_EXCEEDED:
1745 		interested = B_TRUE;	/* Pass up to transport */
1746 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1747 		break;
1748 	case ICMP_PARAM_PROBLEM:
1749 		interested = B_TRUE;	/* Pass up to transport */
1750 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1751 		break;
1752 	case ICMP_TIME_STAMP_REQUEST:
1753 		/* Response to Time Stamp Requests is local policy. */
1754 		if (ip_g_resp_to_timestamp &&
1755 		    /* So is whether to respond if it was an IP broadcast. */
1756 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1757 			int tstamp_len = 3 * sizeof (uint32_t);
1758 
1759 			if (wptr +  tstamp_len > mp->b_wptr) {
1760 				if (!pullupmsg(mp, wptr + tstamp_len -
1761 				    mp->b_rptr)) {
1762 					BUMP_MIB(&ip_mib, ipInDiscards);
1763 					freemsg(first_mp);
1764 					return;
1765 				}
1766 				/* Refresh ipha following the pullup. */
1767 				ipha = (ipha_t *)mp->b_rptr;
1768 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1769 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1770 			}
1771 			interested = B_TRUE;
1772 		}
1773 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1774 		break;
1775 	case ICMP_TIME_STAMP_REPLY:
1776 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1777 		break;
1778 	case ICMP_INFO_REQUEST:
1779 		/* Per RFC 1122 3.2.2.7, ignore this. */
1780 	case ICMP_INFO_REPLY:
1781 		break;
1782 	case ICMP_ADDRESS_MASK_REQUEST:
1783 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1784 		    /* TODO m_pullup of complete header? */
1785 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1786 			interested = B_TRUE;
1787 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1788 		break;
1789 	case ICMP_ADDRESS_MASK_REPLY:
1790 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1791 		break;
1792 	default:
1793 		interested = B_TRUE;	/* Pass up to transport */
1794 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1795 		break;
1796 	}
1797 	/* See if there is an ICMP client. */
1798 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1799 		/* If there is an ICMP client and we want one too, copy it. */
1800 		mblk_t *first_mp1;
1801 
1802 		if (!interested) {
1803 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1804 			    ip_policy, recv_ill, zoneid);
1805 			return;
1806 		}
1807 		first_mp1 = ip_copymsg(first_mp);
1808 		if (first_mp1 != NULL) {
1809 			ip_fanout_proto(q, first_mp1, ill, ipha,
1810 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1811 		}
1812 	} else if (!interested) {
1813 		freemsg(first_mp);
1814 		return;
1815 	} else {
1816 		/*
1817 		 * Initiate policy processing for this packet if ip_policy
1818 		 * is true.
1819 		 */
1820 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1821 			ill_index = ill->ill_phyint->phyint_ifindex;
1822 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1823 			if (mp == NULL) {
1824 				if (mctl_present) {
1825 					freeb(first_mp);
1826 				}
1827 				BUMP_MIB(&icmp_mib, icmpInErrors);
1828 				return;
1829 			}
1830 		}
1831 	}
1832 	/* We want to do something with it. */
1833 	/* Check db_ref to make sure we can modify the packet. */
1834 	if (mp->b_datap->db_ref > 1) {
1835 		mblk_t	*first_mp1;
1836 
1837 		first_mp1 = ip_copymsg(first_mp);
1838 		freemsg(first_mp);
1839 		if (!first_mp1) {
1840 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1841 			return;
1842 		}
1843 		first_mp = first_mp1;
1844 		if (mctl_present) {
1845 			mp = first_mp->b_cont;
1846 			ASSERT(mp != NULL);
1847 		} else {
1848 			mp = first_mp;
1849 		}
1850 		ipha = (ipha_t *)mp->b_rptr;
1851 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1852 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1853 	}
1854 	switch (icmph->icmph_type) {
1855 	case ICMP_ADDRESS_MASK_REQUEST:
1856 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1857 		if (ipif == NULL) {
1858 			freemsg(first_mp);
1859 			return;
1860 		}
1861 		/*
1862 		 * outging interface must be IPv4
1863 		 */
1864 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1865 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1866 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1867 		ipif_refrele(ipif);
1868 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1869 		break;
1870 	case ICMP_ECHO_REQUEST:
1871 		icmph->icmph_type = ICMP_ECHO_REPLY;
1872 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1873 		break;
1874 	case ICMP_TIME_STAMP_REQUEST: {
1875 		uint32_t *tsp;
1876 
1877 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1878 		tsp = (uint32_t *)wptr;
1879 		tsp++;		/* Skip past 'originate time' */
1880 		/* Compute # of milliseconds since midnight */
1881 		gethrestime(&now);
1882 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1883 		    now.tv_nsec / (NANOSEC / MILLISEC);
1884 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1885 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1886 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1887 		break;
1888 	}
1889 	default:
1890 		ipha = (ipha_t *)&icmph[1];
1891 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1892 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1893 				BUMP_MIB(&ip_mib, ipInDiscards);
1894 				freemsg(first_mp);
1895 				return;
1896 			}
1897 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 			ipha = (ipha_t *)&icmph[1];
1899 		}
1900 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1901 			BUMP_MIB(&ip_mib, ipInDiscards);
1902 			freemsg(first_mp);
1903 			return;
1904 		}
1905 		hdr_length = IPH_HDR_LENGTH(ipha);
1906 		if (hdr_length < sizeof (ipha_t)) {
1907 			BUMP_MIB(&ip_mib, ipInDiscards);
1908 			freemsg(first_mp);
1909 			return;
1910 		}
1911 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1912 			if (!pullupmsg(mp,
1913 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1914 				BUMP_MIB(&ip_mib, ipInDiscards);
1915 				freemsg(first_mp);
1916 				return;
1917 			}
1918 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1919 			ipha = (ipha_t *)&icmph[1];
1920 		}
1921 		switch (icmph->icmph_type) {
1922 		case ICMP_REDIRECT:
1923 			/*
1924 			 * As there is no upper client to deliver, we don't
1925 			 * need the first_mp any more.
1926 			 */
1927 			if (mctl_present) {
1928 				freeb(first_mp);
1929 			}
1930 			icmp_redirect(mp);
1931 			return;
1932 		case ICMP_DEST_UNREACHABLE:
1933 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1934 				if (!icmp_inbound_too_big(icmph, ipha)) {
1935 					freemsg(first_mp);
1936 					return;
1937 				}
1938 			}
1939 			/* FALLTHRU */
1940 		default :
1941 			/*
1942 			 * IPQoS notes: Since we have already done IPQoS
1943 			 * processing we don't want to do it again in
1944 			 * the fanout routines called by
1945 			 * icmp_inbound_error_fanout, hence the last
1946 			 * argument, ip_policy, is B_FALSE.
1947 			 */
1948 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1949 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1950 			    B_FALSE, recv_ill, zoneid);
1951 		}
1952 		return;
1953 	}
1954 	/* Send out an ICMP packet */
1955 	icmph->icmph_checksum = 0;
1956 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1957 	if (icmph->icmph_checksum == 0)
1958 		icmph->icmph_checksum = 0xFFFF;
1959 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1960 		ipif_t	*ipif_chosen;
1961 		/*
1962 		 * Make it look like it was directed to us, so we don't look
1963 		 * like a fool with a broadcast or multicast source address.
1964 		 */
1965 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1966 		/*
1967 		 * Make sure that we haven't grabbed an interface that's DOWN.
1968 		 */
1969 		if (ipif != NULL) {
1970 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1971 			    ipha->ipha_src, zoneid);
1972 			if (ipif_chosen != NULL) {
1973 				ipif_refrele(ipif);
1974 				ipif = ipif_chosen;
1975 			}
1976 		}
1977 		if (ipif == NULL) {
1978 			ip0dbg(("icmp_inbound: "
1979 			    "No source for broadcast/multicast:\n"
1980 			    "\tsrc 0x%x dst 0x%x ill %p "
1981 			    "ipif_lcl_addr 0x%x\n",
1982 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1983 			    (void *)ill,
1984 			    ill->ill_ipif->ipif_lcl_addr));
1985 			freemsg(first_mp);
1986 			return;
1987 		}
1988 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1989 		ipha->ipha_dst = ipif->ipif_src_addr;
1990 		ipif_refrele(ipif);
1991 	}
1992 	/* Reset time to live. */
1993 	ipha->ipha_ttl = ip_def_ttl;
1994 	{
1995 		/* Swap source and destination addresses */
1996 		ipaddr_t tmp;
1997 
1998 		tmp = ipha->ipha_src;
1999 		ipha->ipha_src = ipha->ipha_dst;
2000 		ipha->ipha_dst = tmp;
2001 	}
2002 	ipha->ipha_ident = 0;
2003 	if (!IS_SIMPLE_IPH(ipha))
2004 		icmp_options_update(ipha);
2005 
2006 	/*
2007 	 * ICMP echo replies should go out on the same interface
2008 	 * the request came on as probes used by in.mpathd for detecting
2009 	 * NIC failures are ECHO packets. We turn-off load spreading
2010 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2011 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2012 	 * function. This is in turn handled by ip_wput and ip_newroute
2013 	 * to make sure that the packet goes out on the interface it came
2014 	 * in on. If we don't turnoff load spreading, the packets might get
2015 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2016 	 * to go out and in.mpathd would wrongly detect a failure or
2017 	 * mis-detect a NIC failure for link failure. As load spreading
2018 	 * can happen only if ill_group is not NULL, we do only for
2019 	 * that case and this does not affect the normal case.
2020 	 *
2021 	 * We turn off load spreading only on echo packets that came from
2022 	 * on-link hosts. If the interface route has been deleted, this will
2023 	 * not be enforced as we can't do much. For off-link hosts, as the
2024 	 * default routes in IPv4 does not typically have an ire_ipif
2025 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2026 	 * Moreover, expecting a default route through this interface may
2027 	 * not be correct. We use ipha_dst because of the swap above.
2028 	 */
2029 	onlink = B_FALSE;
2030 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2031 		/*
2032 		 * First, we need to make sure that it is not one of our
2033 		 * local addresses. If we set onlink when it is one of
2034 		 * our local addresses, we will end up creating IRE_CACHES
2035 		 * for one of our local addresses. Then, we will never
2036 		 * accept packets for them afterwards.
2037 		 */
2038 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2039 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2040 		if (src_ire == NULL) {
2041 			ipif = ipif_get_next_ipif(NULL, ill);
2042 			if (ipif == NULL) {
2043 				BUMP_MIB(&ip_mib, ipInDiscards);
2044 				freemsg(mp);
2045 				return;
2046 			}
2047 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2048 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2049 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2050 			ipif_refrele(ipif);
2051 			if (src_ire != NULL) {
2052 				onlink = B_TRUE;
2053 				ire_refrele(src_ire);
2054 			}
2055 		} else {
2056 			ire_refrele(src_ire);
2057 		}
2058 	}
2059 	if (!mctl_present) {
2060 		/*
2061 		 * This packet should go out the same way as it
2062 		 * came in i.e in clear. To make sure that global
2063 		 * policy will not be applied to this in ip_wput_ire,
2064 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2065 		 */
2066 		ASSERT(first_mp == mp);
2067 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2068 			BUMP_MIB(&ip_mib, ipInDiscards);
2069 			freemsg(mp);
2070 			return;
2071 		}
2072 		ii = (ipsec_in_t *)first_mp->b_rptr;
2073 
2074 		/* This is not a secure packet */
2075 		ii->ipsec_in_secure = B_FALSE;
2076 		if (onlink) {
2077 			ii->ipsec_in_attach_if = B_TRUE;
2078 			ii->ipsec_in_ill_index =
2079 			    ill->ill_phyint->phyint_ifindex;
2080 			ii->ipsec_in_rill_index =
2081 			    recv_ill->ill_phyint->phyint_ifindex;
2082 		}
2083 		first_mp->b_cont = mp;
2084 	} else if (onlink) {
2085 		ii = (ipsec_in_t *)first_mp->b_rptr;
2086 		ii->ipsec_in_attach_if = B_TRUE;
2087 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2088 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2089 	} else {
2090 		ii = (ipsec_in_t *)first_mp->b_rptr;
2091 	}
2092 	ii->ipsec_in_zoneid = zoneid;
2093 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2094 		BUMP_MIB(&ip_mib, ipInDiscards);
2095 		return;
2096 	}
2097 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2098 	put(WR(q), first_mp);
2099 }
2100 
2101 /* Table from RFC 1191 */
2102 static int icmp_frag_size_table[] =
2103 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2104 
2105 /*
2106  * Process received ICMP Packet too big.
2107  * After updating any IRE it does the fanout to any matching transport streams.
2108  * Assumes the message has been pulled up till the IP header that caused
2109  * the error.
2110  *
2111  * Returns B_FALSE on failure and B_TRUE on success.
2112  */
2113 static boolean_t
2114 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2115 {
2116 	ire_t	*ire, *first_ire;
2117 	int	mtu;
2118 	int	hdr_length;
2119 
2120 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2121 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2122 
2123 	hdr_length = IPH_HDR_LENGTH(ipha);
2124 
2125 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2126 	    ALL_ZONES, MATCH_IRE_TYPE);
2127 
2128 	if (!first_ire) {
2129 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2130 		    ntohl(ipha->ipha_dst)));
2131 		return (B_FALSE);
2132 	}
2133 	/* Drop if the original packet contained a source route */
2134 	if (ip_source_route_included(ipha)) {
2135 		ire_refrele(first_ire);
2136 		return (B_FALSE);
2137 	}
2138 	/* Check for MTU discovery advice as described in RFC 1191 */
2139 	mtu = ntohs(icmph->icmph_du_mtu);
2140 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2141 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2142 	    ire = ire->ire_next) {
2143 		mutex_enter(&ire->ire_lock);
2144 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2145 			/* Reduce the IRE max frag value as advised. */
2146 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2147 			ip1dbg(("Received mtu from router: %d\n", mtu));
2148 		} else {
2149 			uint32_t length;
2150 			int	i;
2151 
2152 			/*
2153 			 * Use the table from RFC 1191 to figure out
2154 			 * the next "plateau" based on the length in
2155 			 * the original IP packet.
2156 			 */
2157 			length = ntohs(ipha->ipha_length);
2158 			if (ire->ire_max_frag <= length &&
2159 			    ire->ire_max_frag >= length - hdr_length) {
2160 				/*
2161 				 * Handle broken BSD 4.2 systems that
2162 				 * return the wrong iph_length in ICMP
2163 				 * errors.
2164 				 */
2165 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2166 				    length, ire->ire_max_frag));
2167 				length -= hdr_length;
2168 			}
2169 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2170 				if (length > icmp_frag_size_table[i])
2171 					break;
2172 			}
2173 			if (i == A_CNT(icmp_frag_size_table)) {
2174 				/* Smaller than 68! */
2175 				ip1dbg(("Too big for packet size %d\n",
2176 				    length));
2177 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2178 				ire->ire_frag_flag = 0;
2179 			} else {
2180 				mtu = icmp_frag_size_table[i];
2181 				ip1dbg(("Calculated mtu %d, packet size %d, "
2182 				    "before %d", mtu, length,
2183 				    ire->ire_max_frag));
2184 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2185 				ip1dbg((", after %d\n", ire->ire_max_frag));
2186 			}
2187 			/* Record the new max frag size for the ULP. */
2188 			icmph->icmph_du_zero = 0;
2189 			icmph->icmph_du_mtu =
2190 			    htons((uint16_t)ire->ire_max_frag);
2191 		}
2192 		mutex_exit(&ire->ire_lock);
2193 	}
2194 	rw_exit(&first_ire->ire_bucket->irb_lock);
2195 	ire_refrele(first_ire);
2196 	return (B_TRUE);
2197 }
2198 
2199 /*
2200  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2201  * calls this function.
2202  */
2203 static mblk_t *
2204 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2205 {
2206 	ipha_t *ipha;
2207 	icmph_t *icmph;
2208 	ipha_t *in_ipha;
2209 	int length;
2210 
2211 	ASSERT(mp->b_datap->db_type == M_DATA);
2212 
2213 	/*
2214 	 * For Self-encapsulated packets, we added an extra IP header
2215 	 * without the options. Inner IP header is the one from which
2216 	 * the outer IP header was formed. Thus, we need to remove the
2217 	 * outer IP header. To do this, we pullup the whole message
2218 	 * and overlay whatever follows the outer IP header over the
2219 	 * outer IP header.
2220 	 */
2221 
2222 	if (!pullupmsg(mp, -1)) {
2223 		BUMP_MIB(&ip_mib, ipInDiscards);
2224 		return (NULL);
2225 	}
2226 
2227 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2228 	ipha = (ipha_t *)&icmph[1];
2229 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2230 
2231 	/*
2232 	 * The length that we want to overlay is following the inner
2233 	 * IP header. Subtracting the IP header + icmp header + outer
2234 	 * IP header's length should give us the length that we want to
2235 	 * overlay.
2236 	 */
2237 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2238 	    hdr_length;
2239 	/*
2240 	 * Overlay whatever follows the inner header over the
2241 	 * outer header.
2242 	 */
2243 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2244 
2245 	/* Set the wptr to account for the outer header */
2246 	mp->b_wptr -= hdr_length;
2247 	return (mp);
2248 }
2249 
2250 /*
2251  * Try to pass the ICMP message upstream in case the ULP cares.
2252  *
2253  * If the packet that caused the ICMP error is secure, we send
2254  * it to AH/ESP to make sure that the attached packet has a
2255  * valid association. ipha in the code below points to the
2256  * IP header of the packet that caused the error.
2257  *
2258  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2259  * in the context of IPSEC. Normally we tell the upper layer
2260  * whenever we send the ire (including ip_bind), the IPSEC header
2261  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2262  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2263  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2264  * same thing. As TCP has the IPSEC options size that needs to be
2265  * adjusted, we just pass the MTU unchanged.
2266  *
2267  * IFN could have been generated locally or by some router.
2268  *
2269  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2270  *	    This happens because IP adjusted its value of MTU on an
2271  *	    earlier IFN message and could not tell the upper layer,
2272  *	    the new adjusted value of MTU e.g. Packet was encrypted
2273  *	    or there was not enough information to fanout to upper
2274  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2275  *	    generates the IFN, where IPSEC processing has *not* been
2276  *	    done.
2277  *
2278  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2279  *	    could have generated this. This happens because ire_max_frag
2280  *	    value in IP was set to a new value, while the IPSEC processing
2281  *	    was being done and after we made the fragmentation check in
2282  *	    ip_wput_ire. Thus on return from IPSEC processing,
2283  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2284  *	    and generates the IFN. As IPSEC processing is over, we fanout
2285  *	    to AH/ESP to remove the header.
2286  *
2287  *	    In both these cases, ipsec_in_loopback will be set indicating
2288  *	    that IFN was generated locally.
2289  *
2290  * ROUTER : IFN could be secure or non-secure.
2291  *
2292  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2293  *	      packet in error has AH/ESP headers to validate the AH/ESP
2294  *	      headers. AH/ESP will verify whether there is a valid SA or
2295  *	      not and send it back. We will fanout again if we have more
2296  *	      data in the packet.
2297  *
2298  *	      If the packet in error does not have AH/ESP, we handle it
2299  *	      like any other case.
2300  *
2301  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2302  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2303  *	      for validation. AH/ESP will verify whether there is a
2304  *	      valid SA or not and send it back. We will fanout again if
2305  *	      we have more data in the packet.
2306  *
2307  *	      If the packet in error does not have AH/ESP, we handle it
2308  *	      like any other case.
2309  */
2310 static void
2311 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2312     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2313     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2314     zoneid_t zoneid)
2315 {
2316 	uint16_t *up;	/* Pointer to ports in ULP header */
2317 	uint32_t ports;	/* reversed ports for fanout */
2318 	ipha_t ripha;	/* With reversed addresses */
2319 	mblk_t *first_mp;
2320 	ipsec_in_t *ii;
2321 	tcph_t	*tcph;
2322 	conn_t	*connp;
2323 
2324 	first_mp = mp;
2325 	if (mctl_present) {
2326 		mp = first_mp->b_cont;
2327 		ASSERT(mp != NULL);
2328 
2329 		ii = (ipsec_in_t *)first_mp->b_rptr;
2330 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2331 	} else {
2332 		ii = NULL;
2333 	}
2334 
2335 	switch (ipha->ipha_protocol) {
2336 	case IPPROTO_UDP:
2337 		/*
2338 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2339 		 * transport header.
2340 		 */
2341 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2342 		    mp->b_wptr) {
2343 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2344 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2345 				BUMP_MIB(&ip_mib, ipInDiscards);
2346 				goto drop_pkt;
2347 			}
2348 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2349 			ipha = (ipha_t *)&icmph[1];
2350 		}
2351 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2352 
2353 		/*
2354 		 * Attempt to find a client stream based on port.
2355 		 * Note that we do a reverse lookup since the header is
2356 		 * in the form we sent it out.
2357 		 * The ripha header is only used for the IP_UDP_MATCH and we
2358 		 * only set the src and dst addresses and protocol.
2359 		 */
2360 		ripha.ipha_src = ipha->ipha_dst;
2361 		ripha.ipha_dst = ipha->ipha_src;
2362 		ripha.ipha_protocol = ipha->ipha_protocol;
2363 		((uint16_t *)&ports)[0] = up[1];
2364 		((uint16_t *)&ports)[1] = up[0];
2365 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2366 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2367 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2368 		    icmph->icmph_type, icmph->icmph_code));
2369 
2370 		/* Have to change db_type after any pullupmsg */
2371 		DB_TYPE(mp) = M_CTL;
2372 
2373 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2374 		    mctl_present, ip_policy, recv_ill, zoneid);
2375 		return;
2376 
2377 	case IPPROTO_TCP:
2378 		/*
2379 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2380 		 * transport header.
2381 		 */
2382 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2383 		    mp->b_wptr) {
2384 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2385 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2386 				BUMP_MIB(&ip_mib, ipInDiscards);
2387 				goto drop_pkt;
2388 			}
2389 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2390 			ipha = (ipha_t *)&icmph[1];
2391 		}
2392 		/*
2393 		 * Find a TCP client stream for this packet.
2394 		 * Note that we do a reverse lookup since the header is
2395 		 * in the form we sent it out.
2396 		 */
2397 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2398 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2399 		if (connp == NULL) {
2400 			BUMP_MIB(&ip_mib, ipInDiscards);
2401 			goto drop_pkt;
2402 		}
2403 
2404 		/* Have to change db_type after any pullupmsg */
2405 		DB_TYPE(mp) = M_CTL;
2406 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2407 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2408 		return;
2409 
2410 	case IPPROTO_SCTP:
2411 		/*
2412 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2413 		 * transport header.
2414 		 */
2415 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2416 		    mp->b_wptr) {
2417 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2418 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2419 				BUMP_MIB(&ip_mib, ipInDiscards);
2420 				goto drop_pkt;
2421 			}
2422 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2423 			ipha = (ipha_t *)&icmph[1];
2424 		}
2425 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2426 		/*
2427 		 * Find a SCTP client stream for this packet.
2428 		 * Note that we do a reverse lookup since the header is
2429 		 * in the form we sent it out.
2430 		 * The ripha header is only used for the matching and we
2431 		 * only set the src and dst addresses, protocol, and version.
2432 		 */
2433 		ripha.ipha_src = ipha->ipha_dst;
2434 		ripha.ipha_dst = ipha->ipha_src;
2435 		ripha.ipha_protocol = ipha->ipha_protocol;
2436 		ripha.ipha_version_and_hdr_length =
2437 		    ipha->ipha_version_and_hdr_length;
2438 		((uint16_t *)&ports)[0] = up[1];
2439 		((uint16_t *)&ports)[1] = up[0];
2440 
2441 		/* Have to change db_type after any pullupmsg */
2442 		DB_TYPE(mp) = M_CTL;
2443 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2444 		    mctl_present, ip_policy, 0, zoneid);
2445 		return;
2446 
2447 	case IPPROTO_ESP:
2448 	case IPPROTO_AH: {
2449 		int ipsec_rc;
2450 
2451 		/*
2452 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2453 		 * We will re-use the IPSEC_IN if it is already present as
2454 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2455 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2456 		 * one and attach it in the front.
2457 		 */
2458 		if (ii != NULL) {
2459 			/*
2460 			 * ip_fanout_proto_again converts the ICMP errors
2461 			 * that come back from AH/ESP to M_DATA so that
2462 			 * if it is non-AH/ESP and we do a pullupmsg in
2463 			 * this function, it would work. Convert it back
2464 			 * to M_CTL before we send up as this is a ICMP
2465 			 * error. This could have been generated locally or
2466 			 * by some router. Validate the inner IPSEC
2467 			 * headers.
2468 			 *
2469 			 * NOTE : ill_index is used by ip_fanout_proto_again
2470 			 * to locate the ill.
2471 			 */
2472 			ASSERT(ill != NULL);
2473 			ii->ipsec_in_ill_index =
2474 			    ill->ill_phyint->phyint_ifindex;
2475 			ii->ipsec_in_rill_index =
2476 			    recv_ill->ill_phyint->phyint_ifindex;
2477 			DB_TYPE(first_mp->b_cont) = M_CTL;
2478 		} else {
2479 			/*
2480 			 * IPSEC_IN is not present. We attach a ipsec_in
2481 			 * message and send up to IPSEC for validating
2482 			 * and removing the IPSEC headers. Clear
2483 			 * ipsec_in_secure so that when we return
2484 			 * from IPSEC, we don't mistakenly think that this
2485 			 * is a secure packet came from the network.
2486 			 *
2487 			 * NOTE : ill_index is used by ip_fanout_proto_again
2488 			 * to locate the ill.
2489 			 */
2490 			ASSERT(first_mp == mp);
2491 			first_mp = ipsec_in_alloc(B_TRUE);
2492 			if (first_mp == NULL) {
2493 				freemsg(mp);
2494 				BUMP_MIB(&ip_mib, ipInDiscards);
2495 				return;
2496 			}
2497 			ii = (ipsec_in_t *)first_mp->b_rptr;
2498 
2499 			/* This is not a secure packet */
2500 			ii->ipsec_in_secure = B_FALSE;
2501 			first_mp->b_cont = mp;
2502 			DB_TYPE(mp) = M_CTL;
2503 			ASSERT(ill != NULL);
2504 			ii->ipsec_in_ill_index =
2505 			    ill->ill_phyint->phyint_ifindex;
2506 			ii->ipsec_in_rill_index =
2507 			    recv_ill->ill_phyint->phyint_ifindex;
2508 		}
2509 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2510 
2511 		if (!ipsec_loaded()) {
2512 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2513 			return;
2514 		}
2515 
2516 		if (ipha->ipha_protocol == IPPROTO_ESP)
2517 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2518 		else
2519 			ipsec_rc = ipsecah_icmp_error(first_mp);
2520 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2521 			return;
2522 
2523 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2524 		return;
2525 	}
2526 	default:
2527 		/*
2528 		 * The ripha header is only used for the lookup and we
2529 		 * only set the src and dst addresses and protocol.
2530 		 */
2531 		ripha.ipha_src = ipha->ipha_dst;
2532 		ripha.ipha_dst = ipha->ipha_src;
2533 		ripha.ipha_protocol = ipha->ipha_protocol;
2534 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2535 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2536 		    ntohl(ipha->ipha_dst),
2537 		    icmph->icmph_type, icmph->icmph_code));
2538 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2539 			ipha_t *in_ipha;
2540 
2541 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2542 			    mp->b_wptr) {
2543 				if (!pullupmsg(mp, (uchar_t *)ipha +
2544 				    hdr_length + sizeof (ipha_t) -
2545 				    mp->b_rptr)) {
2546 
2547 					BUMP_MIB(&ip_mib, ipInDiscards);
2548 					goto drop_pkt;
2549 				}
2550 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2551 				ipha = (ipha_t *)&icmph[1];
2552 			}
2553 			/*
2554 			 * Caller has verified that length has to be
2555 			 * at least the size of IP header.
2556 			 */
2557 			ASSERT(hdr_length >= sizeof (ipha_t));
2558 			/*
2559 			 * Check the sanity of the inner IP header like
2560 			 * we did for the outer header.
2561 			 */
2562 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2563 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2564 				BUMP_MIB(&ip_mib, ipInDiscards);
2565 				goto drop_pkt;
2566 			}
2567 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2568 				BUMP_MIB(&ip_mib, ipInDiscards);
2569 				goto drop_pkt;
2570 			}
2571 			/* Check for Self-encapsulated tunnels */
2572 			if (in_ipha->ipha_src == ipha->ipha_src &&
2573 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2574 
2575 				mp = icmp_inbound_self_encap_error(mp,
2576 				    iph_hdr_length, hdr_length);
2577 				if (mp == NULL)
2578 					goto drop_pkt;
2579 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2580 				ipha = (ipha_t *)&icmph[1];
2581 				hdr_length = IPH_HDR_LENGTH(ipha);
2582 				/*
2583 				 * The packet in error is self-encapsualted.
2584 				 * And we are finding it further encapsulated
2585 				 * which we could not have possibly generated.
2586 				 */
2587 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2588 					BUMP_MIB(&ip_mib, ipInDiscards);
2589 					goto drop_pkt;
2590 				}
2591 				icmp_inbound_error_fanout(q, ill, first_mp,
2592 				    icmph, ipha, iph_hdr_length, hdr_length,
2593 				    mctl_present, ip_policy, recv_ill, zoneid);
2594 				return;
2595 			}
2596 		}
2597 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2598 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2599 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2600 		    ii != NULL &&
2601 		    ii->ipsec_in_loopback &&
2602 		    ii->ipsec_in_secure) {
2603 			/*
2604 			 * For IP tunnels that get a looped-back
2605 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2606 			 * reported new MTU to take into account the IPsec
2607 			 * headers protecting this configured tunnel.
2608 			 *
2609 			 * This allows the tunnel module (tun.c) to blindly
2610 			 * accept the MTU reported in an ICMP "too big"
2611 			 * message.
2612 			 *
2613 			 * Non-looped back ICMP messages will just be
2614 			 * handled by the security protocols (if needed),
2615 			 * and the first subsequent packet will hit this
2616 			 * path.
2617 			 */
2618 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2619 			    ipsec_in_extra_length(first_mp));
2620 		}
2621 		/* Have to change db_type after any pullupmsg */
2622 		DB_TYPE(mp) = M_CTL;
2623 
2624 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2625 		    ip_policy, recv_ill, zoneid);
2626 		return;
2627 	}
2628 	/* NOTREACHED */
2629 drop_pkt:;
2630 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2631 	freemsg(first_mp);
2632 }
2633 
2634 /*
2635  * Common IP options parser.
2636  *
2637  * Setup routine: fill in *optp with options-parsing state, then
2638  * tail-call ipoptp_next to return the first option.
2639  */
2640 uint8_t
2641 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2642 {
2643 	uint32_t totallen; /* total length of all options */
2644 
2645 	totallen = ipha->ipha_version_and_hdr_length -
2646 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2647 	totallen <<= 2;
2648 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2649 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2650 	optp->ipoptp_flags = 0;
2651 	return (ipoptp_next(optp));
2652 }
2653 
2654 /*
2655  * Common IP options parser: extract next option.
2656  */
2657 uint8_t
2658 ipoptp_next(ipoptp_t *optp)
2659 {
2660 	uint8_t *end = optp->ipoptp_end;
2661 	uint8_t *cur = optp->ipoptp_next;
2662 	uint8_t opt, len, pointer;
2663 
2664 	/*
2665 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2666 	 * has been corrupted.
2667 	 */
2668 	ASSERT(cur <= end);
2669 
2670 	if (cur == end)
2671 		return (IPOPT_EOL);
2672 
2673 	opt = cur[IPOPT_OPTVAL];
2674 
2675 	/*
2676 	 * Skip any NOP options.
2677 	 */
2678 	while (opt == IPOPT_NOP) {
2679 		cur++;
2680 		if (cur == end)
2681 			return (IPOPT_EOL);
2682 		opt = cur[IPOPT_OPTVAL];
2683 	}
2684 
2685 	if (opt == IPOPT_EOL)
2686 		return (IPOPT_EOL);
2687 
2688 	/*
2689 	 * Option requiring a length.
2690 	 */
2691 	if ((cur + 1) >= end) {
2692 		optp->ipoptp_flags |= IPOPTP_ERROR;
2693 		return (IPOPT_EOL);
2694 	}
2695 	len = cur[IPOPT_OLEN];
2696 	if (len < 2) {
2697 		optp->ipoptp_flags |= IPOPTP_ERROR;
2698 		return (IPOPT_EOL);
2699 	}
2700 	optp->ipoptp_cur = cur;
2701 	optp->ipoptp_len = len;
2702 	optp->ipoptp_next = cur + len;
2703 	if (cur + len > end) {
2704 		optp->ipoptp_flags |= IPOPTP_ERROR;
2705 		return (IPOPT_EOL);
2706 	}
2707 
2708 	/*
2709 	 * For the options which require a pointer field, make sure
2710 	 * its there, and make sure it points to either something
2711 	 * inside this option, or the end of the option.
2712 	 */
2713 	switch (opt) {
2714 	case IPOPT_RR:
2715 	case IPOPT_TS:
2716 	case IPOPT_LSRR:
2717 	case IPOPT_SSRR:
2718 		if (len <= IPOPT_OFFSET) {
2719 			optp->ipoptp_flags |= IPOPTP_ERROR;
2720 			return (opt);
2721 		}
2722 		pointer = cur[IPOPT_OFFSET];
2723 		if (pointer - 1 > len) {
2724 			optp->ipoptp_flags |= IPOPTP_ERROR;
2725 			return (opt);
2726 		}
2727 		break;
2728 	}
2729 
2730 	/*
2731 	 * Sanity check the pointer field based on the type of the
2732 	 * option.
2733 	 */
2734 	switch (opt) {
2735 	case IPOPT_RR:
2736 	case IPOPT_SSRR:
2737 	case IPOPT_LSRR:
2738 		if (pointer < IPOPT_MINOFF_SR)
2739 			optp->ipoptp_flags |= IPOPTP_ERROR;
2740 		break;
2741 	case IPOPT_TS:
2742 		if (pointer < IPOPT_MINOFF_IT)
2743 			optp->ipoptp_flags |= IPOPTP_ERROR;
2744 		/*
2745 		 * Note that the Internet Timestamp option also
2746 		 * contains two four bit fields (the Overflow field,
2747 		 * and the Flag field), which follow the pointer
2748 		 * field.  We don't need to check that these fields
2749 		 * fall within the length of the option because this
2750 		 * was implicitely done above.  We've checked that the
2751 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2752 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2753 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2754 		 */
2755 		ASSERT(len > IPOPT_POS_OV_FLG);
2756 		break;
2757 	}
2758 
2759 	return (opt);
2760 }
2761 
2762 /*
2763  * Update any record route or timestamp options to include this host.
2764  * Reverse any source route option.
2765  * This routine assumes that the options are well formed i.e. that they
2766  * have already been checked.
2767  */
2768 static void
2769 icmp_options_update(ipha_t *ipha)
2770 {
2771 	ipoptp_t	opts;
2772 	uchar_t		*opt;
2773 	uint8_t		optval;
2774 	ipaddr_t	src;		/* Our local address */
2775 	ipaddr_t	dst;
2776 
2777 	ip2dbg(("icmp_options_update\n"));
2778 	src = ipha->ipha_src;
2779 	dst = ipha->ipha_dst;
2780 
2781 	for (optval = ipoptp_first(&opts, ipha);
2782 	    optval != IPOPT_EOL;
2783 	    optval = ipoptp_next(&opts)) {
2784 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2785 		opt = opts.ipoptp_cur;
2786 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2787 		    optval, opts.ipoptp_len));
2788 		switch (optval) {
2789 			int off1, off2;
2790 		case IPOPT_SSRR:
2791 		case IPOPT_LSRR:
2792 			/*
2793 			 * Reverse the source route.  The first entry
2794 			 * should be the next to last one in the current
2795 			 * source route (the last entry is our address).
2796 			 * The last entry should be the final destination.
2797 			 */
2798 			off1 = IPOPT_MINOFF_SR - 1;
2799 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2800 			if (off2 < 0) {
2801 				/* No entries in source route */
2802 				ip1dbg((
2803 				    "icmp_options_update: bad src route\n"));
2804 				break;
2805 			}
2806 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2807 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2808 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2809 			off2 -= IP_ADDR_LEN;
2810 
2811 			while (off1 < off2) {
2812 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2813 				bcopy((char *)opt + off2, (char *)opt + off1,
2814 				    IP_ADDR_LEN);
2815 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2816 				off1 += IP_ADDR_LEN;
2817 				off2 -= IP_ADDR_LEN;
2818 			}
2819 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2820 			break;
2821 		}
2822 	}
2823 }
2824 
2825 /*
2826  * Process received ICMP Redirect messages.
2827  */
2828 /* ARGSUSED */
2829 static void
2830 icmp_redirect(mblk_t *mp)
2831 {
2832 	ipha_t	*ipha;
2833 	int	iph_hdr_length;
2834 	icmph_t	*icmph;
2835 	ipha_t	*ipha_err;
2836 	ire_t	*ire;
2837 	ire_t	*prev_ire;
2838 	ire_t	*save_ire;
2839 	ipaddr_t  src, dst, gateway;
2840 	iulp_t	ulp_info = { 0 };
2841 	int	error;
2842 
2843 	ipha = (ipha_t *)mp->b_rptr;
2844 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2845 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2846 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2847 		BUMP_MIB(&icmp_mib, icmpInErrors);
2848 		freemsg(mp);
2849 		return;
2850 	}
2851 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2852 	ipha_err = (ipha_t *)&icmph[1];
2853 	src = ipha->ipha_src;
2854 	dst = ipha_err->ipha_dst;
2855 	gateway = icmph->icmph_rd_gateway;
2856 	/* Make sure the new gateway is reachable somehow. */
2857 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2858 	    ALL_ZONES, MATCH_IRE_TYPE);
2859 	/*
2860 	 * Make sure we had a route for the dest in question and that
2861 	 * that route was pointing to the old gateway (the source of the
2862 	 * redirect packet.)
2863 	 */
2864 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2865 	    MATCH_IRE_GW);
2866 	/*
2867 	 * Check that
2868 	 *	the redirect was not from ourselves
2869 	 *	the new gateway and the old gateway are directly reachable
2870 	 */
2871 	if (!prev_ire ||
2872 	    !ire ||
2873 	    ire->ire_type == IRE_LOCAL) {
2874 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2875 		freemsg(mp);
2876 		if (ire != NULL)
2877 			ire_refrele(ire);
2878 		if (prev_ire != NULL)
2879 			ire_refrele(prev_ire);
2880 		return;
2881 	}
2882 
2883 	/*
2884 	 * Should we use the old ULP info to create the new gateway?  From
2885 	 * a user's perspective, we should inherit the info so that it
2886 	 * is a "smooth" transition.  If we do not do that, then new
2887 	 * connections going thru the new gateway will have no route metrics,
2888 	 * which is counter-intuitive to user.  From a network point of
2889 	 * view, this may or may not make sense even though the new gateway
2890 	 * is still directly connected to us so the route metrics should not
2891 	 * change much.
2892 	 *
2893 	 * But if the old ire_uinfo is not initialized, we do another
2894 	 * recursive lookup on the dest using the new gateway.  There may
2895 	 * be a route to that.  If so, use it to initialize the redirect
2896 	 * route.
2897 	 */
2898 	if (prev_ire->ire_uinfo.iulp_set) {
2899 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2900 	} else {
2901 		ire_t *tmp_ire;
2902 		ire_t *sire;
2903 
2904 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2905 		    ALL_ZONES, 0,
2906 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2907 		if (sire != NULL) {
2908 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2909 			/*
2910 			 * If sire != NULL, ire_ftable_lookup() should not
2911 			 * return a NULL value.
2912 			 */
2913 			ASSERT(tmp_ire != NULL);
2914 			ire_refrele(tmp_ire);
2915 			ire_refrele(sire);
2916 		} else if (tmp_ire != NULL) {
2917 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2918 			    sizeof (iulp_t));
2919 			ire_refrele(tmp_ire);
2920 		}
2921 	}
2922 	if (prev_ire->ire_type == IRE_CACHE)
2923 		ire_delete(prev_ire);
2924 	ire_refrele(prev_ire);
2925 	/*
2926 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2927 	 * require TOS routing
2928 	 */
2929 	switch (icmph->icmph_code) {
2930 	case 0:
2931 	case 1:
2932 		/* TODO: TOS specificity for cases 2 and 3 */
2933 	case 2:
2934 	case 3:
2935 		break;
2936 	default:
2937 		freemsg(mp);
2938 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2939 		ire_refrele(ire);
2940 		return;
2941 	}
2942 	/*
2943 	 * Create a Route Association.  This will allow us to remember that
2944 	 * someone we believe told us to use the particular gateway.
2945 	 */
2946 	save_ire = ire;
2947 	ire = ire_create(
2948 		(uchar_t *)&dst,			/* dest addr */
2949 		(uchar_t *)&ip_g_all_ones,		/* mask */
2950 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2951 		(uchar_t *)&gateway,			/* gateway addr */
2952 		NULL,					/* no in_srcaddr */
2953 		&save_ire->ire_max_frag,		/* max frag */
2954 		NULL,					/* Fast Path header */
2955 		NULL,					/* no rfq */
2956 		NULL,					/* no stq */
2957 		IRE_HOST_REDIRECT,
2958 		NULL,
2959 		NULL,
2960 		NULL,
2961 		0,
2962 		0,
2963 		0,
2964 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2965 		&ulp_info);
2966 
2967 	if (ire == NULL) {
2968 		freemsg(mp);
2969 		ire_refrele(save_ire);
2970 		return;
2971 	}
2972 	error = ire_add(&ire, NULL, NULL, NULL);
2973 	ire_refrele(save_ire);
2974 	if (error == 0) {
2975 		ire_refrele(ire);		/* Held in ire_add_v4 */
2976 		/* tell routing sockets that we received a redirect */
2977 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2978 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2979 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2980 	}
2981 
2982 	/*
2983 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2984 	 * This together with the added IRE has the effect of
2985 	 * modifying an existing redirect.
2986 	 */
2987 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2988 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2989 	if (prev_ire) {
2990 		ire_delete(prev_ire);
2991 		ire_refrele(prev_ire);
2992 	}
2993 
2994 	freemsg(mp);
2995 }
2996 
2997 /*
2998  * Generate an ICMP parameter problem message.
2999  */
3000 static void
3001 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3002 {
3003 	icmph_t	icmph;
3004 	boolean_t mctl_present;
3005 	mblk_t *first_mp;
3006 
3007 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3008 
3009 	if (!(mp = icmp_pkt_err_ok(mp))) {
3010 		if (mctl_present)
3011 			freeb(first_mp);
3012 		return;
3013 	}
3014 
3015 	bzero(&icmph, sizeof (icmph_t));
3016 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3017 	icmph.icmph_pp_ptr = ptr;
3018 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3019 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3020 }
3021 
3022 /*
3023  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3024  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3025  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3026  * an icmp error packet can be sent.
3027  * Assigns an appropriate source address to the packet. If ipha_dst is
3028  * one of our addresses use it for source. Otherwise pick a source based
3029  * on a route lookup back to ipha_src.
3030  * Note that ipha_src must be set here since the
3031  * packet is likely to arrive on an ill queue in ip_wput() which will
3032  * not set a source address.
3033  */
3034 static void
3035 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3036     boolean_t mctl_present)
3037 {
3038 	ipaddr_t dst;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha;
3041 	uint_t	len_needed;
3042 	size_t	msg_len;
3043 	mblk_t	*mp1;
3044 	ipaddr_t src;
3045 	ire_t	*ire;
3046 	mblk_t *ipsec_mp;
3047 	ipsec_out_t	*io = NULL;
3048 	boolean_t xmit_if_on = B_FALSE;
3049 	zoneid_t	zoneid;
3050 
3051 	if (mctl_present) {
3052 		/*
3053 		 * If it is :
3054 		 *
3055 		 * 1) a IPSEC_OUT, then this is caused by outbound
3056 		 *    datagram originating on this host. IPSEC processing
3057 		 *    may or may not have been done. Refer to comments above
3058 		 *    icmp_inbound_error_fanout for details.
3059 		 *
3060 		 * 2) a IPSEC_IN if we are generating a icmp_message
3061 		 *    for an incoming datagram destined for us i.e called
3062 		 *    from ip_fanout_send_icmp.
3063 		 */
3064 		ipsec_info_t *in;
3065 		ipsec_mp = mp;
3066 		mp = ipsec_mp->b_cont;
3067 
3068 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3069 		ipha = (ipha_t *)mp->b_rptr;
3070 
3071 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3072 		    in->ipsec_info_type == IPSEC_IN);
3073 
3074 		if (in->ipsec_info_type == IPSEC_IN) {
3075 			/*
3076 			 * Convert the IPSEC_IN to IPSEC_OUT.
3077 			 */
3078 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3079 				BUMP_MIB(&ip_mib, ipOutDiscards);
3080 				return;
3081 			}
3082 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3083 		} else {
3084 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3085 			io = (ipsec_out_t *)in;
3086 			if (io->ipsec_out_xmit_if)
3087 				xmit_if_on = B_TRUE;
3088 			/*
3089 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3090 			 * ire lookup.
3091 			 */
3092 			io->ipsec_out_proc_begin = B_FALSE;
3093 		}
3094 		zoneid = io->ipsec_out_zoneid;
3095 		ASSERT(zoneid != ALL_ZONES);
3096 	} else {
3097 		/*
3098 		 * This is in clear. The icmp message we are building
3099 		 * here should go out in clear.
3100 		 *
3101 		 * Pardon the convolution of it all, but it's easier to
3102 		 * allocate a "use cleartext" IPSEC_IN message and convert
3103 		 * it than it is to allocate a new one.
3104 		 */
3105 		ipsec_in_t *ii;
3106 		ASSERT(DB_TYPE(mp) == M_DATA);
3107 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3108 			freemsg(mp);
3109 			BUMP_MIB(&ip_mib, ipOutDiscards);
3110 			return;
3111 		}
3112 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3113 
3114 		/* This is not a secure packet */
3115 		ii->ipsec_in_secure = B_FALSE;
3116 		if (CONN_Q(q)) {
3117 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3118 		} else {
3119 			zoneid = GLOBAL_ZONEID;
3120 		}
3121 		ii->ipsec_in_zoneid = zoneid;
3122 		ipsec_mp->b_cont = mp;
3123 		ipha = (ipha_t *)mp->b_rptr;
3124 		/*
3125 		 * Convert the IPSEC_IN to IPSEC_OUT.
3126 		 */
3127 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3128 			BUMP_MIB(&ip_mib, ipOutDiscards);
3129 			return;
3130 		}
3131 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3132 	}
3133 
3134 	/* Remember our eventual destination */
3135 	dst = ipha->ipha_src;
3136 
3137 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3138 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3139 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3140 		src = ipha->ipha_dst;
3141 	} else if (!xmit_if_on) {
3142 		if (ire != NULL)
3143 			ire_refrele(ire);
3144 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3145 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3146 		if (ire == NULL) {
3147 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3148 			freemsg(ipsec_mp);
3149 			return;
3150 		}
3151 		src = ire->ire_src_addr;
3152 	} else {
3153 		ipif_t	*ipif = NULL;
3154 		ill_t	*ill;
3155 		/*
3156 		 * This must be an ICMP error coming from
3157 		 * ip_mrtun_forward(). The src addr should
3158 		 * be equal to the IP-addr of the outgoing
3159 		 * interface.
3160 		 */
3161 		if (io == NULL) {
3162 			/* This is not a IPSEC_OUT type control msg */
3163 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3164 			freemsg(ipsec_mp);
3165 			return;
3166 		}
3167 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3168 		    NULL, NULL, NULL, NULL);
3169 		if (ill != NULL) {
3170 			ipif = ipif_get_next_ipif(NULL, ill);
3171 			ill_refrele(ill);
3172 		}
3173 		if (ipif == NULL) {
3174 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3175 			freemsg(ipsec_mp);
3176 			return;
3177 		}
3178 		src = ipif->ipif_src_addr;
3179 		ipif_refrele(ipif);
3180 	}
3181 
3182 	if (ire != NULL)
3183 		ire_refrele(ire);
3184 
3185 	/*
3186 	 * Check if we can send back more then 8 bytes in addition
3187 	 * to the IP header. We will include as much as 64 bytes.
3188 	 */
3189 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3190 	msg_len = msgdsize(mp);
3191 	if (msg_len > len_needed) {
3192 		(void) adjmsg(mp, len_needed - msg_len);
3193 		msg_len = len_needed;
3194 	}
3195 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3196 	if (!mp1) {
3197 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3198 		freemsg(ipsec_mp);
3199 		return;
3200 	}
3201 	mp1->b_cont = mp;
3202 	mp = mp1;
3203 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3204 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3205 	    io->ipsec_out_type == IPSEC_OUT);
3206 	ipsec_mp->b_cont = mp;
3207 
3208 	/*
3209 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3210 	 * node generates be accepted in peace by all on-host destinations.
3211 	 * If we do NOT assume that all on-host destinations trust
3212 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3213 	 * (Look for ipsec_out_icmp_loopback).
3214 	 */
3215 	io->ipsec_out_icmp_loopback = B_TRUE;
3216 
3217 	ipha = (ipha_t *)mp->b_rptr;
3218 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3219 	*ipha = icmp_ipha;
3220 	ipha->ipha_src = src;
3221 	ipha->ipha_dst = dst;
3222 	ipha->ipha_ttl = ip_def_ttl;
3223 	msg_len += sizeof (icmp_ipha) + len;
3224 	if (msg_len > IP_MAXPACKET) {
3225 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3226 		msg_len = IP_MAXPACKET;
3227 	}
3228 	ipha->ipha_length = htons((uint16_t)msg_len);
3229 	icmph = (icmph_t *)&ipha[1];
3230 	bcopy(stuff, icmph, len);
3231 	icmph->icmph_checksum = 0;
3232 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3233 	if (icmph->icmph_checksum == 0)
3234 		icmph->icmph_checksum = 0xFFFF;
3235 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3236 	put(q, ipsec_mp);
3237 }
3238 
3239 /*
3240  * Determine if an ICMP error packet can be sent given the rate limit.
3241  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3242  * in milliseconds) and a burst size. Burst size number of packets can
3243  * be sent arbitrarely closely spaced.
3244  * The state is tracked using two variables to implement an approximate
3245  * token bucket filter:
3246  *	icmp_pkt_err_last - lbolt value when the last burst started
3247  *	icmp_pkt_err_sent - number of packets sent in current burst
3248  */
3249 boolean_t
3250 icmp_err_rate_limit(void)
3251 {
3252 	clock_t now = TICK_TO_MSEC(lbolt);
3253 	uint_t refilled; /* Number of packets refilled in tbf since last */
3254 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3255 
3256 	if (err_interval == 0)
3257 		return (B_FALSE);
3258 
3259 	if (icmp_pkt_err_last > now) {
3260 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3261 		icmp_pkt_err_last = 0;
3262 		icmp_pkt_err_sent = 0;
3263 	}
3264 	/*
3265 	 * If we are in a burst update the token bucket filter.
3266 	 * Update the "last" time to be close to "now" but make sure
3267 	 * we don't loose precision.
3268 	 */
3269 	if (icmp_pkt_err_sent != 0) {
3270 		refilled = (now - icmp_pkt_err_last)/err_interval;
3271 		if (refilled > icmp_pkt_err_sent) {
3272 			icmp_pkt_err_sent = 0;
3273 		} else {
3274 			icmp_pkt_err_sent -= refilled;
3275 			icmp_pkt_err_last += refilled * err_interval;
3276 		}
3277 	}
3278 	if (icmp_pkt_err_sent == 0) {
3279 		/* Start of new burst */
3280 		icmp_pkt_err_last = now;
3281 	}
3282 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3283 		icmp_pkt_err_sent++;
3284 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3285 		    icmp_pkt_err_sent));
3286 		return (B_FALSE);
3287 	}
3288 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3289 	return (B_TRUE);
3290 }
3291 
3292 /*
3293  * Check if it is ok to send an IPv4 ICMP error packet in
3294  * response to the IPv4 packet in mp.
3295  * Free the message and return null if no
3296  * ICMP error packet should be sent.
3297  */
3298 static mblk_t *
3299 icmp_pkt_err_ok(mblk_t *mp)
3300 {
3301 	icmph_t	*icmph;
3302 	ipha_t	*ipha;
3303 	uint_t	len_needed;
3304 	ire_t	*src_ire;
3305 	ire_t	*dst_ire;
3306 
3307 	if (!mp)
3308 		return (NULL);
3309 	ipha = (ipha_t *)mp->b_rptr;
3310 	if (ip_csum_hdr(ipha)) {
3311 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3312 		freemsg(mp);
3313 		return (NULL);
3314 	}
3315 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3316 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3317 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3318 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3319 	if (src_ire != NULL || dst_ire != NULL ||
3320 	    CLASSD(ipha->ipha_dst) ||
3321 	    CLASSD(ipha->ipha_src) ||
3322 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3323 		/* Note: only errors to the fragment with offset 0 */
3324 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3325 		freemsg(mp);
3326 		if (src_ire != NULL)
3327 			ire_refrele(src_ire);
3328 		if (dst_ire != NULL)
3329 			ire_refrele(dst_ire);
3330 		return (NULL);
3331 	}
3332 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3333 		/*
3334 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3335 		 * errors in response to any ICMP errors.
3336 		 */
3337 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3338 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3339 			if (!pullupmsg(mp, len_needed)) {
3340 				BUMP_MIB(&icmp_mib, icmpInErrors);
3341 				freemsg(mp);
3342 				return (NULL);
3343 			}
3344 			ipha = (ipha_t *)mp->b_rptr;
3345 		}
3346 		icmph = (icmph_t *)
3347 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3348 		switch (icmph->icmph_type) {
3349 		case ICMP_DEST_UNREACHABLE:
3350 		case ICMP_SOURCE_QUENCH:
3351 		case ICMP_TIME_EXCEEDED:
3352 		case ICMP_PARAM_PROBLEM:
3353 		case ICMP_REDIRECT:
3354 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3355 			freemsg(mp);
3356 			return (NULL);
3357 		default:
3358 			break;
3359 		}
3360 	}
3361 	if (icmp_err_rate_limit()) {
3362 		/*
3363 		 * Only send ICMP error packets every so often.
3364 		 * This should be done on a per port/source basis,
3365 		 * but for now this will suffice.
3366 		 */
3367 		freemsg(mp);
3368 		return (NULL);
3369 	}
3370 	return (mp);
3371 }
3372 
3373 /*
3374  * Generate an ICMP redirect message.
3375  */
3376 static void
3377 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3378 {
3379 	icmph_t	icmph;
3380 
3381 	/*
3382 	 * We are called from ip_rput where we could
3383 	 * not have attached an IPSEC_IN.
3384 	 */
3385 	ASSERT(mp->b_datap->db_type == M_DATA);
3386 
3387 	if (!(mp = icmp_pkt_err_ok(mp))) {
3388 		return;
3389 	}
3390 
3391 	bzero(&icmph, sizeof (icmph_t));
3392 	icmph.icmph_type = ICMP_REDIRECT;
3393 	icmph.icmph_code = 1;
3394 	icmph.icmph_rd_gateway = gateway;
3395 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3396 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3397 }
3398 
3399 /*
3400  * Generate an ICMP time exceeded message.
3401  */
3402 void
3403 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3404 {
3405 	icmph_t	icmph;
3406 	boolean_t mctl_present;
3407 	mblk_t *first_mp;
3408 
3409 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3410 
3411 	if (!(mp = icmp_pkt_err_ok(mp))) {
3412 		if (mctl_present)
3413 			freeb(first_mp);
3414 		return;
3415 	}
3416 
3417 	bzero(&icmph, sizeof (icmph_t));
3418 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3419 	icmph.icmph_code = code;
3420 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3421 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3422 }
3423 
3424 /*
3425  * Generate an ICMP unreachable message.
3426  */
3427 void
3428 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3429 {
3430 	icmph_t	icmph;
3431 	mblk_t *first_mp;
3432 	boolean_t mctl_present;
3433 
3434 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3435 
3436 	if (!(mp = icmp_pkt_err_ok(mp))) {
3437 		if (mctl_present)
3438 			freeb(first_mp);
3439 		return;
3440 	}
3441 
3442 	bzero(&icmph, sizeof (icmph_t));
3443 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3444 	icmph.icmph_code = code;
3445 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3446 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3447 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3448 }
3449 
3450 /*
3451  * News from ARP.  ARP sends notification of interesting events down
3452  * to its clients using M_CTL messages with the interesting ARP packet
3453  * attached via b_cont.
3454  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3455  * queue as opposed to ARP sending the message to all the clients, i.e. all
3456  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3457  * table if a cache IRE is found to delete all the entries for the address in
3458  * the packet.
3459  */
3460 static void
3461 ip_arp_news(queue_t *q, mblk_t *mp)
3462 {
3463 	arcn_t		*arcn;
3464 	arh_t		*arh;
3465 	char		*cp1;
3466 	uchar_t		*cp2;
3467 	ire_t		*ire = NULL;
3468 	int		i1;
3469 	char		hbuf[128];
3470 	char		sbuf[16];
3471 	ipaddr_t	src;
3472 	in6_addr_t	v6src;
3473 	boolean_t	isv6 = B_FALSE;
3474 
3475 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3476 		if (q->q_next) {
3477 			putnext(q, mp);
3478 		} else
3479 			freemsg(mp);
3480 		return;
3481 	}
3482 	arh = (arh_t *)mp->b_cont->b_rptr;
3483 	/* Is it one we are interested in? */
3484 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3485 		isv6 = B_TRUE;
3486 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3487 		    IPV6_ADDR_LEN);
3488 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3489 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3490 		    IP_ADDR_LEN);
3491 	} else {
3492 		freemsg(mp);
3493 		return;
3494 	}
3495 
3496 	arcn = (arcn_t *)mp->b_rptr;
3497 	switch (arcn->arcn_code) {
3498 	case AR_CN_BOGON:
3499 		/*
3500 		 * Someone is sending ARP packets with a source protocol
3501 		 * address which we have published.  Either they are
3502 		 * pretending to be us, or we have been asked to proxy
3503 		 * for a machine that can do fine for itself, or two
3504 		 * different machines are providing proxy service for the
3505 		 * same protocol address, or something.  We try and do
3506 		 * something appropriate here.
3507 		 */
3508 		cp2 = (uchar_t *)&arh[1];
3509 		cp1 = hbuf;
3510 		*cp1 = '\0';
3511 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3512 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3513 		if (cp1 != hbuf)
3514 			cp1[-1] = '\0';
3515 		(void) ip_dot_addr(src, sbuf);
3516 		if (isv6)
3517 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3518 		else
3519 			ire = ire_cache_lookup(src, ALL_ZONES);
3520 
3521 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3522 			cmn_err(CE_WARN,
3523 			    "IP: Hardware address '%s' trying"
3524 			    " to be our address %s!",
3525 			    hbuf, sbuf);
3526 		} else {
3527 			cmn_err(CE_WARN,
3528 			    "IP: Proxy ARP problem?  "
3529 			    "Hardware address '%s' thinks it is %s",
3530 			    hbuf, sbuf);
3531 		}
3532 		if (ire != NULL)
3533 			ire_refrele(ire);
3534 		break;
3535 	case AR_CN_ANNOUNCE:
3536 		if (isv6) {
3537 			/*
3538 			 * For XRESOLV interfaces.
3539 			 * Delete the IRE cache entry and NCE for this
3540 			 * v6 address
3541 			 */
3542 			ip_ire_clookup_and_delete_v6(&v6src);
3543 			/*
3544 			 * If v6src is a non-zero, it's a router address
3545 			 * as below. Do the same sort of thing to clean
3546 			 * out off-net IRE_CACHE entries that go through
3547 			 * the router.
3548 			 */
3549 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3550 				ire_walk_v6(ire_delete_cache_gw_v6,
3551 				    (char *)&v6src, ALL_ZONES);
3552 			}
3553 			break;
3554 		}
3555 		/*
3556 		 * ARP gives us a copy of any broadcast packet with identical
3557 		 * sender and receiver protocol address, in
3558 		 * case we want to intuit something from it.  Such a packet
3559 		 * usually means that a machine has just come up on the net.
3560 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3561 		 * immediately pick up the rare case of a host changing
3562 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3563 		 *
3564 		 * The address in "src" may be an entry for a router.
3565 		 * (Default router, or non-default router.)  If
3566 		 * that's true, then any off-net IRE_CACHE entries
3567 		 * that go through the router with address "src"
3568 		 * must be clobbered.  Use ire_walk to achieve this
3569 		 * goal.
3570 		 *
3571 		 * It should be possible to determine if the address
3572 		 * in src is or is not for a router.  This way,
3573 		 * the ire_walk() isn't called all of the time here.
3574 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3575 		 * as it would remove all IRE_CACHE entries for onlink
3576 		 * destinations. All onlink destinations have
3577 		 * ire_gateway_addr == 0.
3578 		 */
3579 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3580 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3581 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3582 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3583 			    ALL_ZONES);
3584 		}
3585 		/* From ire_ftable_lookup */
3586 		if (ire != NULL)
3587 			ire_refrele(ire);
3588 		break;
3589 	default:
3590 		if (ire != NULL)
3591 			ire_refrele(ire);
3592 		break;
3593 	}
3594 	freemsg(mp);
3595 }
3596 
3597 /*
3598  * Create a mblk suitable for carrying the interface index and/or source link
3599  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3600  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3601  * application.
3602  */
3603 mblk_t *
3604 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3605 {
3606 	mblk_t		*mp;
3607 	in_pktinfo_t	*pinfo;
3608 	ipha_t *ipha;
3609 	struct ether_header *pether;
3610 
3611 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3612 	if (mp == NULL) {
3613 		ip1dbg(("ip_add_info: allocation failure.\n"));
3614 		return (data_mp);
3615 	}
3616 
3617 	ipha	= (ipha_t *)data_mp->b_rptr;
3618 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3619 	bzero(pinfo, sizeof (in_pktinfo_t));
3620 	pinfo->in_pkt_flags = (uchar_t)flags;
3621 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3622 
3623 	if (flags & IPF_RECVIF)
3624 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3625 
3626 	pether = (struct ether_header *)((char *)ipha
3627 	    - sizeof (struct ether_header));
3628 	/*
3629 	 * Make sure the interface is an ethernet type, since this option
3630 	 * is currently supported only on this type of interface. Also make
3631 	 * sure we are pointing correctly above db_base.
3632 	 */
3633 
3634 	if ((flags & IPF_RECVSLLA) &&
3635 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3636 	    (ill->ill_type == IFT_ETHER) &&
3637 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3638 
3639 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3640 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3641 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3642 	} else {
3643 		/*
3644 		 * Clear the bit. Indicate to upper layer that IP is not
3645 		 * sending this ancillary info.
3646 		 */
3647 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3648 	}
3649 
3650 	mp->b_datap->db_type = M_CTL;
3651 	mp->b_wptr += sizeof (in_pktinfo_t);
3652 	mp->b_cont = data_mp;
3653 
3654 	return (mp);
3655 }
3656 
3657 /*
3658  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3659  * part of the bind request.
3660  */
3661 
3662 boolean_t
3663 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3664 {
3665 	ipsec_in_t *ii;
3666 
3667 	ASSERT(policy_mp != NULL);
3668 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3669 
3670 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3671 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3672 
3673 	connp->conn_policy = ii->ipsec_in_policy;
3674 	ii->ipsec_in_policy = NULL;
3675 
3676 	if (ii->ipsec_in_action != NULL) {
3677 		if (connp->conn_latch == NULL) {
3678 			connp->conn_latch = iplatch_create();
3679 			if (connp->conn_latch == NULL)
3680 				return (B_FALSE);
3681 		}
3682 		ipsec_latch_inbound(connp->conn_latch, ii);
3683 	}
3684 	return (B_TRUE);
3685 }
3686 
3687 /*
3688  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3689  * and to arrange for power-fanout assist.  The ULP is identified by
3690  * adding a single byte at the end of the original bind message.
3691  * A ULP other than UDP or TCP that wishes to be recognized passes
3692  * down a bind with a zero length address.
3693  *
3694  * The binding works as follows:
3695  * - A zero byte address means just bind to the protocol.
3696  * - A four byte address is treated as a request to validate
3697  *   that the address is a valid local address, appropriate for
3698  *   an application to bind to. This does not affect any fanout
3699  *   information in IP.
3700  * - A sizeof sin_t byte address is used to bind to only the local address
3701  *   and port.
3702  * - A sizeof ipa_conn_t byte address contains complete fanout information
3703  *   consisting of local and remote addresses and ports.  In
3704  *   this case, the addresses are both validated as appropriate
3705  *   for this operation, and, if so, the information is retained
3706  *   for use in the inbound fanout.
3707  *
3708  * The ULP (except in the zero-length bind) can append an
3709  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3710  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3711  * a copy of the source or destination IRE (source for local bind;
3712  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3713  * policy information contained should be copied on to the conn.
3714  *
3715  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3716  */
3717 mblk_t *
3718 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3719 {
3720 	ssize_t		len;
3721 	struct T_bind_req	*tbr;
3722 	sin_t		*sin;
3723 	ipa_conn_t	*ac;
3724 	uchar_t		*ucp;
3725 	mblk_t		*mp1;
3726 	boolean_t	ire_requested;
3727 	boolean_t	ipsec_policy_set = B_FALSE;
3728 	int		error = 0;
3729 	int		protocol;
3730 	ipa_conn_x_t	*acx;
3731 
3732 	ASSERT(!connp->conn_af_isv6);
3733 	connp->conn_pkt_isv6 = B_FALSE;
3734 
3735 	len = MBLKL(mp);
3736 	if (len < (sizeof (*tbr) + 1)) {
3737 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3738 		    "ip_bind: bogus msg, len %ld", len);
3739 		/* XXX: Need to return something better */
3740 		goto bad_addr;
3741 	}
3742 	/* Back up and extract the protocol identifier. */
3743 	mp->b_wptr--;
3744 	protocol = *mp->b_wptr & 0xFF;
3745 	tbr = (struct T_bind_req *)mp->b_rptr;
3746 	/* Reset the message type in preparation for shipping it back. */
3747 	DB_TYPE(mp) = M_PCPROTO;
3748 
3749 	connp->conn_ulp = (uint8_t)protocol;
3750 
3751 	/*
3752 	 * Check for a zero length address.  This is from a protocol that
3753 	 * wants to register to receive all packets of its type.
3754 	 */
3755 	if (tbr->ADDR_length == 0) {
3756 		/*
3757 		 * These protocols are now intercepted in ip_bind_v6().
3758 		 * Reject protocol-level binds here for now.
3759 		 *
3760 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3761 		 * so that the protocol type cannot be SCTP.
3762 		 */
3763 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3764 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3765 			goto bad_addr;
3766 		}
3767 
3768 		/* No hash here really.  The table is big enough. */
3769 		connp->conn_srcv6 = ipv6_all_zeros;
3770 
3771 		ipcl_proto_insert(connp, protocol);
3772 
3773 		tbr->PRIM_type = T_BIND_ACK;
3774 		return (mp);
3775 	}
3776 
3777 	/* Extract the address pointer from the message. */
3778 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3779 	    tbr->ADDR_length);
3780 	if (ucp == NULL) {
3781 		ip1dbg(("ip_bind: no address\n"));
3782 		goto bad_addr;
3783 	}
3784 	if (!OK_32PTR(ucp)) {
3785 		ip1dbg(("ip_bind: unaligned address\n"));
3786 		goto bad_addr;
3787 	}
3788 	/*
3789 	 * Check for trailing mps.
3790 	 */
3791 
3792 	mp1 = mp->b_cont;
3793 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
3794 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
3795 
3796 	switch (tbr->ADDR_length) {
3797 	default:
3798 		ip1dbg(("ip_bind: bad address length %d\n",
3799 		    (int)tbr->ADDR_length));
3800 		goto bad_addr;
3801 
3802 	case IP_ADDR_LEN:
3803 		/* Verification of local address only */
3804 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3805 		    ire_requested, ipsec_policy_set, B_FALSE);
3806 		break;
3807 
3808 	case sizeof (sin_t):
3809 		sin = (sin_t *)ucp;
3810 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3811 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3812 		if (protocol == IPPROTO_TCP)
3813 			connp->conn_recv = tcp_conn_request;
3814 		break;
3815 
3816 	case sizeof (ipa_conn_t):
3817 		ac = (ipa_conn_t *)ucp;
3818 		/* For raw socket, the local port is not set. */
3819 		if (ac->ac_lport == 0)
3820 			ac->ac_lport = connp->conn_lport;
3821 		/* Always verify destination reachability. */
3822 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3823 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3824 		    ipsec_policy_set, B_TRUE, B_TRUE);
3825 		if (protocol == IPPROTO_TCP)
3826 			connp->conn_recv = tcp_input;
3827 		break;
3828 
3829 	case sizeof (ipa_conn_x_t):
3830 		acx = (ipa_conn_x_t *)ucp;
3831 		/*
3832 		 * Whether or not to verify destination reachability depends
3833 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3834 		 */
3835 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3836 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3837 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3838 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3839 		if (protocol == IPPROTO_TCP)
3840 			connp->conn_recv = tcp_input;
3841 		break;
3842 	}
3843 	if (error == EINPROGRESS)
3844 		return (NULL);
3845 	else if (error != 0)
3846 		goto bad_addr;
3847 	/*
3848 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3849 	 * We can't do this in ip_bind_insert_ire because the policy
3850 	 * may not have been inherited at that point in time and hence
3851 	 * conn_out_enforce_policy may not be set.
3852 	 */
3853 	mp1 = mp->b_cont;
3854 	if (ire_requested && connp->conn_out_enforce_policy &&
3855 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3856 		ire_t *ire = (ire_t *)mp1->b_rptr;
3857 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3858 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3859 	}
3860 
3861 	/* Send it home. */
3862 	mp->b_datap->db_type = M_PCPROTO;
3863 	tbr->PRIM_type = T_BIND_ACK;
3864 	return (mp);
3865 
3866 bad_addr:
3867 	/*
3868 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3869 	 * a unix errno.
3870 	 */
3871 	if (error > 0)
3872 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3873 	else
3874 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3875 	return (mp);
3876 }
3877 
3878 /*
3879  * Here address is verified to be a valid local address.
3880  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3881  * address is also considered a valid local address.
3882  * In the case of a broadcast/multicast address, however, the
3883  * upper protocol is expected to reset the src address
3884  * to 0 if it sees a IRE_BROADCAST type returned so that
3885  * no packets are emitted with broadcast/multicast address as
3886  * source address (that violates hosts requirements RFC1122)
3887  * The addresses valid for bind are:
3888  *	(1) - INADDR_ANY (0)
3889  *	(2) - IP address of an UP interface
3890  *	(3) - IP address of a DOWN interface
3891  *	(4) - valid local IP broadcast addresses. In this case
3892  *	the conn will only receive packets destined to
3893  *	the specified broadcast address.
3894  *	(5) - a multicast address. In this case
3895  *	the conn will only receive packets destined to
3896  *	the specified multicast address. Note: the
3897  *	application still has to issue an
3898  *	IP_ADD_MEMBERSHIP socket option.
3899  *
3900  * On error, return -1 for TBADADDR otherwise pass the
3901  * errno with TSYSERR reply.
3902  *
3903  * In all the above cases, the bound address must be valid in the current zone.
3904  * When the address is loopback, multicast or broadcast, there might be many
3905  * matching IREs so bind has to look up based on the zone.
3906  */
3907 int
3908 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3909     boolean_t ire_requested, boolean_t ipsec_policy_set,
3910     boolean_t fanout_insert)
3911 {
3912 	int		error = 0;
3913 	ire_t		*src_ire;
3914 	mblk_t		*policy_mp;
3915 	ipif_t		*ipif;
3916 	zoneid_t	zoneid;
3917 
3918 	if (ipsec_policy_set) {
3919 		policy_mp = mp->b_cont;
3920 	}
3921 
3922 	/*
3923 	 * If it was previously connected, conn_fully_bound would have
3924 	 * been set.
3925 	 */
3926 	connp->conn_fully_bound = B_FALSE;
3927 
3928 	src_ire = NULL;
3929 	ipif = NULL;
3930 
3931 	zoneid = connp->conn_zoneid;
3932 
3933 	if (src_addr) {
3934 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3935 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3936 		/*
3937 		 * If an address other than 0.0.0.0 is requested,
3938 		 * we verify that it is a valid address for bind
3939 		 * Note: Following code is in if-else-if form for
3940 		 * readability compared to a condition check.
3941 		 */
3942 		/* LINTED - statement has no consequent */
3943 		if (IRE_IS_LOCAL(src_ire)) {
3944 			/*
3945 			 * (2) Bind to address of local UP interface
3946 			 */
3947 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3948 			/*
3949 			 * (4) Bind to broadcast address
3950 			 * Note: permitted only from transports that
3951 			 * request IRE
3952 			 */
3953 			if (!ire_requested)
3954 				error = EADDRNOTAVAIL;
3955 		} else {
3956 			/*
3957 			 * (3) Bind to address of local DOWN interface
3958 			 * (ipif_lookup_addr() looks up all interfaces
3959 			 * but we do not get here for UP interfaces
3960 			 * - case (2) above)
3961 			 * We put the protocol byte back into the mblk
3962 			 * since we may come back via ip_wput_nondata()
3963 			 * later with this mblk if ipif_lookup_addr chooses
3964 			 * to defer processing.
3965 			 */
3966 			*mp->b_wptr++ = (char)connp->conn_ulp;
3967 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3968 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3969 			    &error)) != NULL) {
3970 				ipif_refrele(ipif);
3971 			} else if (error == EINPROGRESS) {
3972 				if (src_ire != NULL)
3973 					ire_refrele(src_ire);
3974 				return (EINPROGRESS);
3975 			} else if (CLASSD(src_addr)) {
3976 				error = 0;
3977 				if (src_ire != NULL)
3978 					ire_refrele(src_ire);
3979 				/*
3980 				 * (5) bind to multicast address.
3981 				 * Fake out the IRE returned to upper
3982 				 * layer to be a broadcast IRE.
3983 				 */
3984 				src_ire = ire_ctable_lookup(
3985 				    INADDR_BROADCAST, INADDR_ANY,
3986 				    IRE_BROADCAST, NULL, zoneid,
3987 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3988 				if (src_ire == NULL || !ire_requested)
3989 					error = EADDRNOTAVAIL;
3990 			} else {
3991 				/*
3992 				 * Not a valid address for bind
3993 				 */
3994 				error = EADDRNOTAVAIL;
3995 			}
3996 			/*
3997 			 * Just to keep it consistent with the processing in
3998 			 * ip_bind_v4()
3999 			 */
4000 			mp->b_wptr--;
4001 		}
4002 		if (error) {
4003 			/* Red Alert!  Attempting to be a bogon! */
4004 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4005 			    ntohl(src_addr)));
4006 			goto bad_addr;
4007 		}
4008 	}
4009 
4010 	/*
4011 	 * Allow setting new policies. For example, disconnects come
4012 	 * down as ipa_t bind. As we would have set conn_policy_cached
4013 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4014 	 * can change after the disconnect.
4015 	 */
4016 	connp->conn_policy_cached = B_FALSE;
4017 
4018 	/*
4019 	 * If not fanout_insert this was just an address verification
4020 	 */
4021 	if (fanout_insert) {
4022 		/*
4023 		 * The addresses have been verified. Time to insert in
4024 		 * the correct fanout list.
4025 		 */
4026 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4027 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4028 		connp->conn_lport = lport;
4029 		connp->conn_fport = 0;
4030 		/*
4031 		 * Do we need to add a check to reject Multicast packets
4032 		 */
4033 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4034 	}
4035 done:
4036 	if (error == 0) {
4037 		if (ire_requested) {
4038 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4039 				error = -1;
4040 				/* Falls through to bad_addr */
4041 			}
4042 		} else if (ipsec_policy_set) {
4043 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4044 				error = -1;
4045 				/* Falls through to bad_addr */
4046 			}
4047 		}
4048 	}
4049 bad_addr:
4050 	if (src_ire != NULL)
4051 		IRE_REFRELE(src_ire);
4052 	if (ipsec_policy_set) {
4053 		ASSERT(policy_mp == mp->b_cont);
4054 		ASSERT(policy_mp != NULL);
4055 		freeb(policy_mp);
4056 		/*
4057 		 * As of now assume that nothing else accompanies
4058 		 * IPSEC_POLICY_SET.
4059 		 */
4060 		mp->b_cont = NULL;
4061 	}
4062 	return (error);
4063 }
4064 
4065 /*
4066  * Verify that both the source and destination addresses
4067  * are valid.  If verify_dst is false, then the destination address may be
4068  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4069  * destination reachability, while tunnels do not.
4070  * Note that we allow connect to broadcast and multicast
4071  * addresses when ire_requested is set. Thus the ULP
4072  * has to check for IRE_BROADCAST and multicast.
4073  *
4074  * Returns zero if ok.
4075  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4076  * (for use with TSYSERR reply).
4077  */
4078 int
4079 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4080     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4081     boolean_t ire_requested, boolean_t ipsec_policy_set,
4082     boolean_t fanout_insert, boolean_t verify_dst)
4083 {
4084 	ire_t		*src_ire;
4085 	ire_t		*dst_ire;
4086 	int		error = 0;
4087 	int 		protocol;
4088 	mblk_t		*policy_mp;
4089 	ire_t		*sire = NULL;
4090 	ire_t		*md_dst_ire = NULL;
4091 	ill_t		*md_ill = NULL;
4092 	zoneid_t	zoneid;
4093 	ipaddr_t	src_addr = *src_addrp;
4094 
4095 	src_ire = dst_ire = NULL;
4096 	protocol = *mp->b_wptr & 0xFF;
4097 
4098 	/*
4099 	 * If we never got a disconnect before, clear it now.
4100 	 */
4101 	connp->conn_fully_bound = B_FALSE;
4102 
4103 	if (ipsec_policy_set) {
4104 		policy_mp = mp->b_cont;
4105 	}
4106 
4107 	zoneid = connp->conn_zoneid;
4108 
4109 	if (CLASSD(dst_addr)) {
4110 		/* Pick up an IRE_BROADCAST */
4111 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4112 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4113 		    MATCH_IRE_RJ_BHOLE));
4114 	} else {
4115 		/*
4116 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4117 		 * and onlink ipif is not found set ENETUNREACH error.
4118 		 */
4119 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4120 			ipif_t *ipif;
4121 
4122 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4123 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4124 			if (ipif == NULL) {
4125 				error = ENETUNREACH;
4126 				goto bad_addr;
4127 			}
4128 			ipif_refrele(ipif);
4129 		}
4130 
4131 		if (connp->conn_nexthop_set) {
4132 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4133 			    0, 0, NULL, NULL, zoneid, 0);
4134 		} else {
4135 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4136 			    &sire, zoneid,
4137 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4138 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4139 		}
4140 	}
4141 	/*
4142 	 * dst_ire can't be a broadcast when not ire_requested.
4143 	 * We also prevent ire's with src address INADDR_ANY to
4144 	 * be used, which are created temporarily for
4145 	 * sending out packets from endpoints that have
4146 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4147 	 * reachable.  If verify_dst is false, the destination needn't be
4148 	 * reachable.
4149 	 *
4150 	 * If we match on a reject or black hole, then we've got a
4151 	 * local failure.  May as well fail out the connect() attempt,
4152 	 * since it's never going to succeed.
4153 	 */
4154 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4155 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4156 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4157 		/*
4158 		 * If we're verifying destination reachability, we always want
4159 		 * to complain here.
4160 		 *
4161 		 * If we're not verifying destination reachability but the
4162 		 * destination has a route, we still want to fail on the
4163 		 * temporary address and broadcast address tests.
4164 		 */
4165 		if (verify_dst || (dst_ire != NULL)) {
4166 			if (ip_debug > 2) {
4167 				pr_addr_dbg("ip_bind_connected: bad connected "
4168 				    "dst %s\n", AF_INET, &dst_addr);
4169 			}
4170 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4171 				error = ENETUNREACH;
4172 			else
4173 				error = EHOSTUNREACH;
4174 			goto bad_addr;
4175 		}
4176 	}
4177 	/*
4178 	 * If the app does a connect(), it means that it will most likely
4179 	 * send more than 1 packet to the destination.  It makes sense
4180 	 * to clear the temporary flag.
4181 	 */
4182 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4183 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4184 		irb_t *irb = dst_ire->ire_bucket;
4185 
4186 		rw_enter(&irb->irb_lock, RW_WRITER);
4187 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4188 		irb->irb_tmp_ire_cnt--;
4189 		rw_exit(&irb->irb_lock);
4190 	}
4191 
4192 	/*
4193 	 * See if we should notify ULP about MDT; we do this whether or not
4194 	 * ire_requested is TRUE, in order to handle active connects; MDT
4195 	 * eligibility tests for passive connects are handled separately
4196 	 * through tcp_adapt_ire().  We do this before the source address
4197 	 * selection, because dst_ire may change after a call to
4198 	 * ipif_select_source().  This is a best-effort check, as the
4199 	 * packet for this connection may not actually go through
4200 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4201 	 * calling ip_newroute().  This is why we further check on the
4202 	 * IRE during Multidata packet transmission in tcp_multisend().
4203 	 */
4204 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4205 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4206 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4207 	    ILL_MDT_CAPABLE(md_ill)) {
4208 		md_dst_ire = dst_ire;
4209 		IRE_REFHOLD(md_dst_ire);
4210 	}
4211 
4212 	if (dst_ire != NULL &&
4213 	    dst_ire->ire_type == IRE_LOCAL &&
4214 	    dst_ire->ire_zoneid != zoneid) {
4215 		/*
4216 		 * If the IRE belongs to a different zone, look for a matching
4217 		 * route in the forwarding table and use the source address from
4218 		 * that route.
4219 		 */
4220 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4221 		    zoneid, 0,
4222 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4223 		    MATCH_IRE_RJ_BHOLE);
4224 		if (src_ire == NULL) {
4225 			error = EHOSTUNREACH;
4226 			goto bad_addr;
4227 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4228 			if (!(src_ire->ire_type & IRE_HOST))
4229 				error = ENETUNREACH;
4230 			else
4231 				error = EHOSTUNREACH;
4232 			goto bad_addr;
4233 		}
4234 		if (src_addr == INADDR_ANY)
4235 			src_addr = src_ire->ire_src_addr;
4236 		ire_refrele(src_ire);
4237 		src_ire = NULL;
4238 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4239 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4240 			src_addr = sire->ire_src_addr;
4241 			ire_refrele(dst_ire);
4242 			dst_ire = sire;
4243 			sire = NULL;
4244 		} else {
4245 			/*
4246 			 * Pick a source address so that a proper inbound
4247 			 * load spreading would happen.
4248 			 */
4249 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4250 			ipif_t *src_ipif = NULL;
4251 			ire_t *ipif_ire;
4252 
4253 			/*
4254 			 * Supply a local source address such that inbound
4255 			 * load spreading happens.
4256 			 *
4257 			 * Determine the best source address on this ill for
4258 			 * the destination.
4259 			 *
4260 			 * 1) For broadcast, we should return a broadcast ire
4261 			 *    found above so that upper layers know that the
4262 			 *    destination address is a broadcast address.
4263 			 *
4264 			 * 2) If this is part of a group, select a better
4265 			 *    source address so that better inbound load
4266 			 *    balancing happens. Do the same if the ipif
4267 			 *    is DEPRECATED.
4268 			 *
4269 			 * 3) If the outgoing interface is part of a usesrc
4270 			 *    group, then try selecting a source address from
4271 			 *    the usesrc ILL.
4272 			 */
4273 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4274 			    ((dst_ill->ill_group != NULL) ||
4275 			    (dst_ire->ire_ipif->ipif_flags &
4276 			    IPIF_DEPRECATED) ||
4277 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4278 				src_ipif = ipif_select_source(dst_ill,
4279 				    dst_addr, zoneid);
4280 				if (src_ipif != NULL) {
4281 					if (IS_VNI(src_ipif->ipif_ill)) {
4282 						/*
4283 						 * For VNI there is no
4284 						 * interface route
4285 						 */
4286 						src_addr =
4287 						    src_ipif->ipif_src_addr;
4288 					} else {
4289 						ipif_ire =
4290 						    ipif_to_ire(src_ipif);
4291 						if (ipif_ire != NULL) {
4292 							IRE_REFRELE(dst_ire);
4293 							dst_ire = ipif_ire;
4294 						}
4295 						src_addr =
4296 						    dst_ire->ire_src_addr;
4297 					}
4298 					ipif_refrele(src_ipif);
4299 				} else {
4300 					src_addr = dst_ire->ire_src_addr;
4301 				}
4302 			} else {
4303 				src_addr = dst_ire->ire_src_addr;
4304 			}
4305 		}
4306 	}
4307 
4308 	/*
4309 	 * We do ire_route_lookup() here (and not
4310 	 * interface lookup as we assert that
4311 	 * src_addr should only come from an
4312 	 * UP interface for hard binding.
4313 	 */
4314 	ASSERT(src_ire == NULL);
4315 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4316 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4317 	/* src_ire must be a local|loopback */
4318 	if (!IRE_IS_LOCAL(src_ire)) {
4319 		if (ip_debug > 2) {
4320 			pr_addr_dbg("ip_bind_connected: bad connected "
4321 			    "src %s\n", AF_INET, &src_addr);
4322 		}
4323 		error = EADDRNOTAVAIL;
4324 		goto bad_addr;
4325 	}
4326 
4327 	/*
4328 	 * If the source address is a loopback address, the
4329 	 * destination had best be local or multicast.
4330 	 * The transports that can't handle multicast will reject
4331 	 * those addresses.
4332 	 */
4333 	if (src_ire->ire_type == IRE_LOOPBACK &&
4334 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4335 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4336 		error = -1;
4337 		goto bad_addr;
4338 	}
4339 
4340 	/*
4341 	 * Allow setting new policies. For example, disconnects come
4342 	 * down as ipa_t bind. As we would have set conn_policy_cached
4343 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4344 	 * can change after the disconnect.
4345 	 */
4346 	connp->conn_policy_cached = B_FALSE;
4347 
4348 	/*
4349 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4350 	 * can handle their passed-in conn's.
4351 	 */
4352 
4353 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4354 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4355 	connp->conn_lport = lport;
4356 	connp->conn_fport = fport;
4357 	*src_addrp = src_addr;
4358 
4359 	ASSERT(!(ipsec_policy_set && ire_requested));
4360 	if (ire_requested) {
4361 		iulp_t *ulp_info = NULL;
4362 
4363 		/*
4364 		 * Note that sire will not be NULL if this is an off-link
4365 		 * connection and there is not cache for that dest yet.
4366 		 *
4367 		 * XXX Because of an existing bug, if there are multiple
4368 		 * default routes, the IRE returned now may not be the actual
4369 		 * default route used (default routes are chosen in a
4370 		 * round robin fashion).  So if the metrics for different
4371 		 * default routes are different, we may return the wrong
4372 		 * metrics.  This will not be a problem if the existing
4373 		 * bug is fixed.
4374 		 */
4375 		if (sire != NULL) {
4376 			ulp_info = &(sire->ire_uinfo);
4377 		}
4378 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4379 			error = -1;
4380 			goto bad_addr;
4381 		}
4382 	} else if (ipsec_policy_set) {
4383 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4384 			error = -1;
4385 			goto bad_addr;
4386 		}
4387 	}
4388 
4389 	/*
4390 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4391 	 * we'll cache that.  If we don't, we'll inherit global policy.
4392 	 *
4393 	 * We can't insert until the conn reflects the policy. Note that
4394 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4395 	 * connections where we don't have a policy. This is to prevent
4396 	 * global policy lookups in the inbound path.
4397 	 *
4398 	 * If we insert before we set conn_policy_cached,
4399 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4400 	 * because global policy cound be non-empty. We normally call
4401 	 * ipsec_check_policy() for conn_policy_cached connections only if
4402 	 * ipc_in_enforce_policy is set. But in this case,
4403 	 * conn_policy_cached can get set anytime since we made the
4404 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4405 	 * called, which will make the above assumption false.  Thus, we
4406 	 * need to insert after we set conn_policy_cached.
4407 	 */
4408 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4409 		goto bad_addr;
4410 
4411 	if (fanout_insert) {
4412 		/*
4413 		 * The addresses have been verified. Time to insert in
4414 		 * the correct fanout list.
4415 		 */
4416 		error = ipcl_conn_insert(connp, protocol, src_addr,
4417 		    dst_addr, connp->conn_ports);
4418 	}
4419 
4420 	if (error == 0) {
4421 		connp->conn_fully_bound = B_TRUE;
4422 		/*
4423 		 * Our initial checks for MDT have passed; the IRE is not
4424 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4425 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4426 		 * ip_mdinfo_return(), which performs further checks
4427 		 * against them and upon success, returns the MDT info
4428 		 * mblk which we will attach to the bind acknowledgment.
4429 		 */
4430 		if (md_dst_ire != NULL) {
4431 			mblk_t *mdinfo_mp;
4432 
4433 			ASSERT(md_ill != NULL);
4434 			ASSERT(md_ill->ill_mdt_capab != NULL);
4435 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4436 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4437 				linkb(mp, mdinfo_mp);
4438 		}
4439 	}
4440 bad_addr:
4441 	if (ipsec_policy_set) {
4442 		ASSERT(policy_mp == mp->b_cont);
4443 		ASSERT(policy_mp != NULL);
4444 		freeb(policy_mp);
4445 		/*
4446 		 * As of now assume that nothing else accompanies
4447 		 * IPSEC_POLICY_SET.
4448 		 */
4449 		mp->b_cont = NULL;
4450 	}
4451 	if (src_ire != NULL)
4452 		IRE_REFRELE(src_ire);
4453 	if (dst_ire != NULL)
4454 		IRE_REFRELE(dst_ire);
4455 	if (sire != NULL)
4456 		IRE_REFRELE(sire);
4457 	if (md_dst_ire != NULL)
4458 		IRE_REFRELE(md_dst_ire);
4459 	return (error);
4460 }
4461 
4462 /*
4463  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4464  * Prefers dst_ire over src_ire.
4465  */
4466 static boolean_t
4467 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4468 {
4469 	mblk_t	*mp1;
4470 	ire_t *ret_ire = NULL;
4471 
4472 	mp1 = mp->b_cont;
4473 	ASSERT(mp1 != NULL);
4474 
4475 	if (ire != NULL) {
4476 		/*
4477 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4478 		 * appended mblk. Its <upper protocol>'s
4479 		 * job to make sure there is room.
4480 		 */
4481 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4482 			return (0);
4483 
4484 		mp1->b_datap->db_type = IRE_DB_TYPE;
4485 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4486 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4487 		ret_ire = (ire_t *)mp1->b_rptr;
4488 		/*
4489 		 * Pass the latest setting of the ip_path_mtu_discovery and
4490 		 * copy the ulp info if any.
4491 		 */
4492 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4493 		    IPH_DF : 0;
4494 		if (ulp_info != NULL) {
4495 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4496 			    sizeof (iulp_t));
4497 		}
4498 		ret_ire->ire_mp = mp1;
4499 	} else {
4500 		/*
4501 		 * No IRE was found. Remove IRE mblk.
4502 		 */
4503 		mp->b_cont = mp1->b_cont;
4504 		freeb(mp1);
4505 	}
4506 
4507 	return (1);
4508 }
4509 
4510 /*
4511  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4512  * the final piece where we don't.  Return a pointer to the first mblk in the
4513  * result, and update the pointer to the next mblk to chew on.  If anything
4514  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4515  * NULL pointer.
4516  */
4517 mblk_t *
4518 ip_carve_mp(mblk_t **mpp, ssize_t len)
4519 {
4520 	mblk_t	*mp0;
4521 	mblk_t	*mp1;
4522 	mblk_t	*mp2;
4523 
4524 	if (!len || !mpp || !(mp0 = *mpp))
4525 		return (NULL);
4526 	/* If we aren't going to consume the first mblk, we need a dup. */
4527 	if (mp0->b_wptr - mp0->b_rptr > len) {
4528 		mp1 = dupb(mp0);
4529 		if (mp1) {
4530 			/* Partition the data between the two mblks. */
4531 			mp1->b_wptr = mp1->b_rptr + len;
4532 			mp0->b_rptr = mp1->b_wptr;
4533 			/*
4534 			 * after adjustments if mblk not consumed is now
4535 			 * unaligned, try to align it. If this fails free
4536 			 * all messages and let upper layer recover.
4537 			 */
4538 			if (!OK_32PTR(mp0->b_rptr)) {
4539 				if (!pullupmsg(mp0, -1)) {
4540 					freemsg(mp0);
4541 					freemsg(mp1);
4542 					*mpp = NULL;
4543 					return (NULL);
4544 				}
4545 			}
4546 		}
4547 		return (mp1);
4548 	}
4549 	/* Eat through as many mblks as we need to get len bytes. */
4550 	len -= mp0->b_wptr - mp0->b_rptr;
4551 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4552 		if (mp2->b_wptr - mp2->b_rptr > len) {
4553 			/*
4554 			 * We won't consume the entire last mblk.  Like
4555 			 * above, dup and partition it.
4556 			 */
4557 			mp1->b_cont = dupb(mp2);
4558 			mp1 = mp1->b_cont;
4559 			if (!mp1) {
4560 				/*
4561 				 * Trouble.  Rather than go to a lot of
4562 				 * trouble to clean up, we free the messages.
4563 				 * This won't be any worse than losing it on
4564 				 * the wire.
4565 				 */
4566 				freemsg(mp0);
4567 				freemsg(mp2);
4568 				*mpp = NULL;
4569 				return (NULL);
4570 			}
4571 			mp1->b_wptr = mp1->b_rptr + len;
4572 			mp2->b_rptr = mp1->b_wptr;
4573 			/*
4574 			 * after adjustments if mblk not consumed is now
4575 			 * unaligned, try to align it. If this fails free
4576 			 * all messages and let upper layer recover.
4577 			 */
4578 			if (!OK_32PTR(mp2->b_rptr)) {
4579 				if (!pullupmsg(mp2, -1)) {
4580 					freemsg(mp0);
4581 					freemsg(mp2);
4582 					*mpp = NULL;
4583 					return (NULL);
4584 				}
4585 			}
4586 			*mpp = mp2;
4587 			return (mp0);
4588 		}
4589 		/* Decrement len by the amount we just got. */
4590 		len -= mp2->b_wptr - mp2->b_rptr;
4591 	}
4592 	/*
4593 	 * len should be reduced to zero now.  If not our caller has
4594 	 * screwed up.
4595 	 */
4596 	if (len) {
4597 		/* Shouldn't happen! */
4598 		freemsg(mp0);
4599 		*mpp = NULL;
4600 		return (NULL);
4601 	}
4602 	/*
4603 	 * We consumed up to exactly the end of an mblk.  Detach the part
4604 	 * we are returning from the rest of the chain.
4605 	 */
4606 	mp1->b_cont = NULL;
4607 	*mpp = mp2;
4608 	return (mp0);
4609 }
4610 
4611 /* The ill stream is being unplumbed. Called from ip_close */
4612 int
4613 ip_modclose(ill_t *ill)
4614 {
4615 
4616 	boolean_t success;
4617 	ipsq_t	*ipsq;
4618 	ipif_t	*ipif;
4619 	queue_t	*q = ill->ill_rq;
4620 
4621 	/*
4622 	 * Forcibly enter the ipsq after some delay. This is to take
4623 	 * care of the case when some ioctl does not complete because
4624 	 * we sent a control message to the driver and it did not
4625 	 * send us a reply. We want to be able to at least unplumb
4626 	 * and replumb rather than force the user to reboot the system.
4627 	 */
4628 	success = ipsq_enter(ill, B_FALSE);
4629 
4630 	/*
4631 	 * Open/close/push/pop is guaranteed to be single threaded
4632 	 * per stream by STREAMS. FS guarantees that all references
4633 	 * from top are gone before close is called. So there can't
4634 	 * be another close thread that has set CONDEMNED on this ill.
4635 	 * and cause ipsq_enter to return failure.
4636 	 */
4637 	ASSERT(success);
4638 	ipsq = ill->ill_phyint->phyint_ipsq;
4639 
4640 	/*
4641 	 * Mark it condemned. No new reference will be made to this ill.
4642 	 * Lookup functions will return an error. Threads that try to
4643 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4644 	 * that the refcnt will drop down to zero.
4645 	 */
4646 	mutex_enter(&ill->ill_lock);
4647 	ill->ill_state_flags |= ILL_CONDEMNED;
4648 	for (ipif = ill->ill_ipif; ipif != NULL;
4649 	    ipif = ipif->ipif_next) {
4650 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4651 	}
4652 	/*
4653 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4654 	 * returns  error if ILL_CONDEMNED is set
4655 	 */
4656 	cv_broadcast(&ill->ill_cv);
4657 	mutex_exit(&ill->ill_lock);
4658 
4659 	/*
4660 	 * Shut down fragmentation reassembly.
4661 	 * ill_frag_timer won't start a timer again.
4662 	 * Now cancel any existing timer
4663 	 */
4664 	(void) untimeout(ill->ill_frag_timer_id);
4665 	(void) ill_frag_timeout(ill, 0);
4666 
4667 	/*
4668 	 * If MOVE was in progress, clear the
4669 	 * move_in_progress fields also.
4670 	 */
4671 	if (ill->ill_move_in_progress) {
4672 		ILL_CLEAR_MOVE(ill);
4673 	}
4674 
4675 	/*
4676 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4677 	 * this ill. Then wait for the refcnts to drop to zero.
4678 	 * ill_is_quiescent checks whether the ill is really quiescent.
4679 	 * Then make sure that threads that are waiting to enter the
4680 	 * ipsq have seen the error returned by ipsq_enter and have
4681 	 * gone away. Then we call ill_delete_tail which does the
4682 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4683 	 */
4684 	ill_delete(ill);
4685 	mutex_enter(&ill->ill_lock);
4686 	while (!ill_is_quiescent(ill))
4687 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4688 	while (ill->ill_waiters)
4689 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4690 
4691 	mutex_exit(&ill->ill_lock);
4692 
4693 	/* qprocsoff is called in ill_delete_tail */
4694 	ill_delete_tail(ill);
4695 
4696 	/*
4697 	 * Walk through all upper (conn) streams and qenable
4698 	 * those that have queued data.
4699 	 * close synchronization needs this to
4700 	 * be done to ensure that all upper layers blocked
4701 	 * due to flow control to the closing device
4702 	 * get unblocked.
4703 	 */
4704 	ip1dbg(("ip_wsrv: walking\n"));
4705 	conn_walk_drain();
4706 
4707 	mutex_enter(&ip_mi_lock);
4708 	mi_close_unlink(&ip_g_head, (IDP)ill);
4709 	mutex_exit(&ip_mi_lock);
4710 
4711 	/*
4712 	 * credp could be null if the open didn't succeed and ip_modopen
4713 	 * itself calls ip_close.
4714 	 */
4715 	if (ill->ill_credp != NULL)
4716 		crfree(ill->ill_credp);
4717 
4718 	mi_close_free((IDP)ill);
4719 	q->q_ptr = WR(q)->q_ptr = NULL;
4720 
4721 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4722 
4723 	return (0);
4724 }
4725 
4726 /*
4727  * This is called as part of close() for both IP and UDP
4728  * in order to quiesce the conn.
4729  */
4730 void
4731 ip_quiesce_conn(conn_t *connp)
4732 {
4733 	boolean_t	drain_cleanup_reqd = B_FALSE;
4734 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4735 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4736 
4737 	ASSERT(!IPCL_IS_TCP(connp));
4738 
4739 	/*
4740 	 * Mark the conn as closing, and this conn must not be
4741 	 * inserted in future into any list. Eg. conn_drain_insert(),
4742 	 * won't insert this conn into the conn_drain_list.
4743 	 * Similarly ill_pending_mp_add() will not add any mp to
4744 	 * the pending mp list, after this conn has started closing.
4745 	 *
4746 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4747 	 * cannot get set henceforth.
4748 	 */
4749 	mutex_enter(&connp->conn_lock);
4750 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4751 	connp->conn_state_flags |= CONN_CLOSING;
4752 	if (connp->conn_idl != NULL)
4753 		drain_cleanup_reqd = B_TRUE;
4754 	if (connp->conn_oper_pending_ill != NULL)
4755 		conn_ioctl_cleanup_reqd = B_TRUE;
4756 	if (connp->conn_ilg_inuse != 0)
4757 		ilg_cleanup_reqd = B_TRUE;
4758 	mutex_exit(&connp->conn_lock);
4759 
4760 	if (IPCL_IS_UDP(connp))
4761 		udp_quiesce_conn(connp);
4762 
4763 	if (conn_ioctl_cleanup_reqd)
4764 		conn_ioctl_cleanup(connp);
4765 
4766 	/*
4767 	 * Remove this conn from any fanout list it is on.
4768 	 * and then wait for any threads currently operating
4769 	 * on this endpoint to finish
4770 	 */
4771 	ipcl_hash_remove(connp);
4772 
4773 	/*
4774 	 * Remove this conn from the drain list, and do
4775 	 * any other cleanup that may be required.
4776 	 * (Only non-tcp streams may have a non-null conn_idl.
4777 	 * TCP streams are never flow controlled, and
4778 	 * conn_idl will be null)
4779 	 */
4780 	if (drain_cleanup_reqd)
4781 		conn_drain_tail(connp, B_TRUE);
4782 
4783 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4784 		(void) ip_mrouter_done(NULL);
4785 
4786 	if (ilg_cleanup_reqd)
4787 		ilg_delete_all(connp);
4788 
4789 	conn_delete_ire(connp, NULL);
4790 
4791 	/*
4792 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4793 	 * callers from write side can't be there now because close
4794 	 * is in progress. The only other caller is ipcl_walk
4795 	 * which checks for the condemned flag.
4796 	 */
4797 	mutex_enter(&connp->conn_lock);
4798 	connp->conn_state_flags |= CONN_CONDEMNED;
4799 	while (connp->conn_ref != 1)
4800 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4801 	connp->conn_state_flags |= CONN_QUIESCED;
4802 	mutex_exit(&connp->conn_lock);
4803 }
4804 
4805 /* ARGSUSED */
4806 int
4807 ip_close(queue_t *q, int flags)
4808 {
4809 	conn_t		*connp;
4810 
4811 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4812 
4813 	/*
4814 	 * Call the appropriate delete routine depending on whether this is
4815 	 * a module or device.
4816 	 */
4817 	if (WR(q)->q_next != NULL) {
4818 		/* This is a module close */
4819 		return (ip_modclose((ill_t *)q->q_ptr));
4820 	}
4821 
4822 	connp = q->q_ptr;
4823 	ip_quiesce_conn(connp);
4824 
4825 	qprocsoff(q);
4826 
4827 	/*
4828 	 * Now we are truly single threaded on this stream, and can
4829 	 * delete the things hanging off the connp, and finally the connp.
4830 	 * We removed this connp from the fanout list, it cannot be
4831 	 * accessed thru the fanouts, and we already waited for the
4832 	 * conn_ref to drop to 0. We are already in close, so
4833 	 * there cannot be any other thread from the top. qprocsoff
4834 	 * has completed, and service has completed or won't run in
4835 	 * future.
4836 	 */
4837 	ASSERT(connp->conn_ref == 1);
4838 
4839 	/*
4840 	 * A conn which was previously marked as IPCL_UDP cannot
4841 	 * retain the flag because it would have been cleared by
4842 	 * udp_close().
4843 	 */
4844 	ASSERT(!IPCL_IS_UDP(connp));
4845 
4846 	if (connp->conn_latch != NULL) {
4847 		IPLATCH_REFRELE(connp->conn_latch);
4848 		connp->conn_latch = NULL;
4849 	}
4850 	if (connp->conn_policy != NULL) {
4851 		IPPH_REFRELE(connp->conn_policy);
4852 		connp->conn_policy = NULL;
4853 	}
4854 	if (connp->conn_ipsec_opt_mp != NULL) {
4855 		freemsg(connp->conn_ipsec_opt_mp);
4856 		connp->conn_ipsec_opt_mp = NULL;
4857 	}
4858 	if (connp->conn_cred != NULL) {
4859 		crfree(connp->conn_cred);
4860 		connp->conn_cred = NULL;
4861 	}
4862 
4863 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4864 
4865 	connp->conn_ref--;
4866 	ipcl_conn_destroy(connp);
4867 
4868 	q->q_ptr = WR(q)->q_ptr = NULL;
4869 	return (0);
4870 }
4871 
4872 int
4873 ip_snmpmod_close(queue_t *q)
4874 {
4875 	conn_t *connp = Q_TO_CONN(q);
4876 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4877 
4878 	qprocsoff(q);
4879 
4880 	if (connp->conn_flags & IPCL_UDPMOD)
4881 		udp_close_free(connp);
4882 
4883 	if (connp->conn_cred != NULL) {
4884 		crfree(connp->conn_cred);
4885 		connp->conn_cred = NULL;
4886 	}
4887 	CONN_DEC_REF(connp);
4888 	q->q_ptr = WR(q)->q_ptr = NULL;
4889 	return (0);
4890 }
4891 
4892 /*
4893  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
4894  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
4895  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
4896  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
4897  * queues as we never enqueue messages there and we don't handle any ioctls.
4898  * Everything else is freed.
4899  */
4900 void
4901 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
4902 {
4903 	conn_t	*connp = q->q_ptr;
4904 	pfi_t	setfn;
4905 	pfi_t	getfn;
4906 
4907 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
4908 
4909 	switch (DB_TYPE(mp)) {
4910 	case M_PROTO:
4911 	case M_PCPROTO:
4912 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
4913 		    ((((union T_primitives *)mp->b_rptr)->type ==
4914 			T_SVR4_OPTMGMT_REQ) ||
4915 		    (((union T_primitives *)mp->b_rptr)->type ==
4916 			T_OPTMGMT_REQ))) {
4917 			/*
4918 			 * This is the only TPI primitive supported. Its
4919 			 * handling does not require tcp_t, but it does require
4920 			 * conn_t to check permissions.
4921 			 */
4922 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
4923 
4924 			if (connp->conn_flags & IPCL_TCPMOD) {
4925 				setfn = tcp_snmp_set;
4926 				getfn = tcp_snmp_get;
4927 			} else {
4928 				setfn = udp_snmp_set;
4929 				getfn = udp_snmp_get;
4930 			}
4931 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
4932 				freemsg(mp);
4933 				return;
4934 			}
4935 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
4936 		    != NULL)
4937 			qreply(q, mp);
4938 		break;
4939 	case M_FLUSH:
4940 	case M_IOCTL:
4941 		putnext(q, mp);
4942 		break;
4943 	default:
4944 		freemsg(mp);
4945 		break;
4946 	}
4947 }
4948 
4949 /* Return the IP checksum for the IP header at "iph". */
4950 uint16_t
4951 ip_csum_hdr(ipha_t *ipha)
4952 {
4953 	uint16_t	*uph;
4954 	uint32_t	sum;
4955 	int		opt_len;
4956 
4957 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4958 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4959 	uph = (uint16_t *)ipha;
4960 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4961 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4962 	if (opt_len > 0) {
4963 		do {
4964 			sum += uph[10];
4965 			sum += uph[11];
4966 			uph += 2;
4967 		} while (--opt_len);
4968 	}
4969 	sum = (sum & 0xFFFF) + (sum >> 16);
4970 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4971 	if (sum == 0xffff)
4972 		sum = 0;
4973 	return ((uint16_t)sum);
4974 }
4975 
4976 void
4977 ip_ddi_destroy(void)
4978 {
4979 	tcp_ddi_destroy();
4980 	sctp_ddi_destroy();
4981 	ipsec_loader_destroy();
4982 	ipsec_policy_destroy();
4983 	ipsec_kstat_destroy();
4984 	nd_free(&ip_g_nd);
4985 	mutex_destroy(&igmp_timer_lock);
4986 	mutex_destroy(&mld_timer_lock);
4987 	mutex_destroy(&igmp_slowtimeout_lock);
4988 	mutex_destroy(&mld_slowtimeout_lock);
4989 	mutex_destroy(&ip_mi_lock);
4990 	mutex_destroy(&rts_clients.connf_lock);
4991 	ip_ire_fini();
4992 	ip6_asp_free();
4993 	conn_drain_fini();
4994 	ipcl_destroy();
4995 	inet_minor_destroy(ip_minor_arena);
4996 	icmp_kstat_fini();
4997 	ip_kstat_fini();
4998 	rw_destroy(&ipsec_capab_ills_lock);
4999 	rw_destroy(&ill_g_usesrc_lock);
5000 	ip_drop_unregister(&ip_dropper);
5001 }
5002 
5003 
5004 void
5005 ip_ddi_init(void)
5006 {
5007 	TCP6_MAJ = ddi_name_to_major(TCP6);
5008 	TCP_MAJ	= ddi_name_to_major(TCP);
5009 	SCTP_MAJ = ddi_name_to_major(SCTP);
5010 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5011 
5012 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5013 
5014 	/* IP's IPsec code calls the packet dropper */
5015 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5016 
5017 	if (!ip_g_nd) {
5018 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5019 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5020 			nd_free(&ip_g_nd);
5021 		}
5022 	}
5023 
5024 	ipsec_loader_init();
5025 	ipsec_policy_init();
5026 	ipsec_kstat_init();
5027 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5028 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5029 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5030 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5031 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5032 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5033 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5034 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5035 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5036 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5037 
5038 	/*
5039 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5040 	 * initial devices: ip, ip6, tcp, tcp6.
5041 	 */
5042 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5043 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5044 		cmn_err(CE_PANIC,
5045 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5046 	}
5047 
5048 	ipcl_init();
5049 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5050 	ip_ire_init();
5051 	ip6_asp_init();
5052 	ipif_init();
5053 	conn_drain_init();
5054 	tcp_ddi_init();
5055 	sctp_ddi_init();
5056 
5057 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5058 
5059 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5060 		"net", KSTAT_TYPE_NAMED,
5061 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5062 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5063 		ip_kstat->ks_data = &ip_statistics;
5064 		kstat_install(ip_kstat);
5065 	}
5066 	ip_kstat_init();
5067 	ip6_kstat_init();
5068 	icmp_kstat_init();
5069 
5070 	ipsec_loader_start();
5071 }
5072 
5073 /*
5074  * Allocate and initialize a DLPI template of the specified length.  (May be
5075  * called as writer.)
5076  */
5077 mblk_t *
5078 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5079 {
5080 	mblk_t	*mp;
5081 
5082 	mp = allocb(len, BPRI_MED);
5083 	if (!mp)
5084 		return (NULL);
5085 
5086 	/*
5087 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5088 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5089 	 * that other DLPI are M_PROTO.
5090 	 */
5091 	if (prim == DL_INFO_REQ) {
5092 		mp->b_datap->db_type = M_PCPROTO;
5093 	} else {
5094 		mp->b_datap->db_type = M_PROTO;
5095 	}
5096 
5097 	mp->b_wptr = mp->b_rptr + len;
5098 	bzero(mp->b_rptr, len);
5099 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5100 	return (mp);
5101 }
5102 
5103 const char *
5104 dlpi_prim_str(int prim)
5105 {
5106 	switch (prim) {
5107 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5108 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5109 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5110 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5111 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5112 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5113 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5114 	case DL_OK_ACK:		return ("DL_OK_ACK");
5115 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5116 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5117 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5118 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5119 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5120 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5121 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5122 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5123 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5124 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5125 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5126 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5127 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5128 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5129 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5130 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5131 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5132 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5133 	default:		return ("<unknown primitive>");
5134 	}
5135 }
5136 
5137 const char *
5138 dlpi_err_str(int err)
5139 {
5140 	switch (err) {
5141 	case DL_ACCESS:		return ("DL_ACCESS");
5142 	case DL_BADADDR:	return ("DL_BADADDR");
5143 	case DL_BADCORR:	return ("DL_BADCORR");
5144 	case DL_BADDATA:	return ("DL_BADDATA");
5145 	case DL_BADPPA:		return ("DL_BADPPA");
5146 	case DL_BADPRIM:	return ("DL_BADPRIM");
5147 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5148 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5149 	case DL_BADSAP:		return ("DL_BADSAP");
5150 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5151 	case DL_BOUND:		return ("DL_BOUND");
5152 	case DL_INITFAILED:	return ("DL_INITFAILED");
5153 	case DL_NOADDR:		return ("DL_NOADDR");
5154 	case DL_NOTINIT:	return ("DL_NOTINIT");
5155 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5156 	case DL_SYSERR:		return ("DL_SYSERR");
5157 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5158 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5159 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5160 	case DL_TOOMANY:	return ("DL_TOOMANY");
5161 	case DL_NOTENAB:	return ("DL_NOTENAB");
5162 	case DL_BUSY:		return ("DL_BUSY");
5163 	case DL_NOAUTO:		return ("DL_NOAUTO");
5164 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5165 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5166 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5167 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5168 	case DL_PENDING:	return ("DL_PENDING");
5169 	default:		return ("<unknown error>");
5170 	}
5171 }
5172 
5173 /*
5174  * Debug formatting routine.  Returns a character string representation of the
5175  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5176  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5177  */
5178 char *
5179 ip_dot_addr(ipaddr_t addr, char *buf)
5180 {
5181 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5182 }
5183 
5184 /*
5185  * Debug formatting routine.  Returns a character string representation of the
5186  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5187  * as a pointer.  The "xxx" parts including left zero padding so the final
5188  * string will fit easily in tables.  It would be nice to take a padding
5189  * length argument instead.
5190  */
5191 static char *
5192 ip_dot_saddr(uchar_t *addr, char *buf)
5193 {
5194 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5195 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5196 	return (buf);
5197 }
5198 
5199 /*
5200  * Send an ICMP error after patching up the packet appropriately.  Returns
5201  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5202  */
5203 static boolean_t
5204 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5205     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5206 {
5207 	ipha_t *ipha;
5208 	mblk_t *first_mp;
5209 	boolean_t secure;
5210 	unsigned char db_type;
5211 
5212 	first_mp = mp;
5213 	if (mctl_present) {
5214 		mp = mp->b_cont;
5215 		secure = ipsec_in_is_secure(first_mp);
5216 		ASSERT(mp != NULL);
5217 	} else {
5218 		/*
5219 		 * If this is an ICMP error being reported - which goes
5220 		 * up as M_CTLs, we need to convert them to M_DATA till
5221 		 * we finish checking with global policy because
5222 		 * ipsec_check_global_policy() assumes M_DATA as clear
5223 		 * and M_CTL as secure.
5224 		 */
5225 		db_type = DB_TYPE(mp);
5226 		DB_TYPE(mp) = M_DATA;
5227 		secure = B_FALSE;
5228 	}
5229 	/*
5230 	 * We are generating an icmp error for some inbound packet.
5231 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5232 	 * Before we generate an error, check with global policy
5233 	 * to see whether this is allowed to enter the system. As
5234 	 * there is no "conn", we are checking with global policy.
5235 	 */
5236 	ipha = (ipha_t *)mp->b_rptr;
5237 	if (secure || ipsec_inbound_v4_policy_present) {
5238 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5239 		    ipha, NULL, mctl_present);
5240 		if (first_mp == NULL)
5241 			return (B_FALSE);
5242 	}
5243 
5244 	if (!mctl_present)
5245 		DB_TYPE(mp) = db_type;
5246 
5247 	if (flags & IP_FF_SEND_ICMP) {
5248 		if (flags & IP_FF_HDR_COMPLETE) {
5249 			if (ip_hdr_complete(ipha, zoneid)) {
5250 				freemsg(first_mp);
5251 				return (B_TRUE);
5252 			}
5253 		}
5254 		if (flags & IP_FF_CKSUM) {
5255 			/*
5256 			 * Have to correct checksum since
5257 			 * the packet might have been
5258 			 * fragmented and the reassembly code in ip_rput
5259 			 * does not restore the IP checksum.
5260 			 */
5261 			ipha->ipha_hdr_checksum = 0;
5262 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5263 		}
5264 		switch (icmp_type) {
5265 		case ICMP_DEST_UNREACHABLE:
5266 			icmp_unreachable(WR(q), first_mp, icmp_code);
5267 			break;
5268 		default:
5269 			freemsg(first_mp);
5270 			break;
5271 		}
5272 	} else {
5273 		freemsg(first_mp);
5274 		return (B_FALSE);
5275 	}
5276 
5277 	return (B_TRUE);
5278 }
5279 
5280 #ifdef DEBUG
5281 /*
5282  * Copy the header into the IPSEC_IN message.
5283  */
5284 static void
5285 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5286 {
5287 	mblk_t *data_mp = ipsec_mp->b_cont;
5288 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5289 	ipha_t *ipha;
5290 
5291 	if (ii->ipsec_in_type != IPSEC_IN)
5292 		return;
5293 	ASSERT(data_mp != NULL);
5294 
5295 	ipha = (ipha_t *)data_mp->b_rptr;
5296 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5297 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5298 	    sizeof (ipha_t) : sizeof (ip6_t));
5299 }
5300 #else
5301 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5302 #endif	/* DEBUG */
5303 
5304 /*
5305  * Used to send an ICMP error message when a packet is received for
5306  * a protocol that is not supported. The mblk passed as argument
5307  * is consumed by this function.
5308  */
5309 void
5310 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5311 {
5312 	mblk_t *mp;
5313 	ipha_t *ipha;
5314 	ill_t *ill;
5315 	ipsec_in_t *ii;
5316 
5317 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5318 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5319 
5320 	mp = ipsec_mp->b_cont;
5321 	ipsec_mp->b_cont = NULL;
5322 	ipha = (ipha_t *)mp->b_rptr;
5323 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5324 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5325 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5326 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5327 		}
5328 	} else {
5329 		/* Get ill from index in ipsec_in_t. */
5330 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5331 		    B_TRUE, NULL, NULL, NULL, NULL);
5332 		if (ill != NULL) {
5333 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5334 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5335 			    0, B_FALSE, zoneid)) {
5336 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5337 			}
5338 
5339 			ill_refrele(ill);
5340 		} else { /* re-link for the freemsg() below. */
5341 			ipsec_mp->b_cont = mp;
5342 		}
5343 	}
5344 
5345 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5346 	freemsg(ipsec_mp);
5347 }
5348 
5349 /*
5350  * See if the inbound datagram has had IPsec processing applied to it.
5351  */
5352 boolean_t
5353 ipsec_in_is_secure(mblk_t *ipsec_mp)
5354 {
5355 	ipsec_in_t *ii;
5356 
5357 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5358 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5359 
5360 	if (ii->ipsec_in_loopback) {
5361 		return (ii->ipsec_in_secure);
5362 	} else {
5363 		return (ii->ipsec_in_ah_sa != NULL ||
5364 		    ii->ipsec_in_esp_sa != NULL ||
5365 		    ii->ipsec_in_decaps);
5366 	}
5367 }
5368 
5369 /*
5370  * Handle protocols with which IP is less intimate.  There
5371  * can be more than one stream bound to a particular
5372  * protocol.  When this is the case, normally each one gets a copy
5373  * of any incoming packets.
5374  *
5375  * IPSEC NOTE :
5376  *
5377  * Don't allow a secure packet going up a non-secure connection.
5378  * We don't allow this because
5379  *
5380  * 1) Reply might go out in clear which will be dropped at
5381  *    the sending side.
5382  * 2) If the reply goes out in clear it will give the
5383  *    adversary enough information for getting the key in
5384  *    most of the cases.
5385  *
5386  * Moreover getting a secure packet when we expect clear
5387  * implies that SA's were added without checking for
5388  * policy on both ends. This should not happen once ISAKMP
5389  * is used to negotiate SAs as SAs will be added only after
5390  * verifying the policy.
5391  *
5392  * NOTE : If the packet was tunneled and not multicast we only send
5393  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5394  * back to delivering packets to AF_INET6 raw sockets.
5395  *
5396  * IPQoS Notes:
5397  * Once we have determined the client, invoke IPPF processing.
5398  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5399  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5400  * ip_policy will be false.
5401  *
5402  * Zones notes:
5403  * Currently only applications in the global zone can create raw sockets for
5404  * protocols other than ICMP. So unlike the broadcast / multicast case of
5405  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5406  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5407  */
5408 static void
5409 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5410     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5411     zoneid_t zoneid)
5412 {
5413 	queue_t	*rq;
5414 	mblk_t	*mp1, *first_mp1;
5415 	uint_t	protocol = ipha->ipha_protocol;
5416 	ipaddr_t dst;
5417 	boolean_t one_only;
5418 	mblk_t *first_mp = mp;
5419 	boolean_t secure;
5420 	uint32_t ill_index;
5421 	conn_t	*connp, *first_connp, *next_connp;
5422 	connf_t	*connfp;
5423 
5424 	if (mctl_present) {
5425 		mp = first_mp->b_cont;
5426 		secure = ipsec_in_is_secure(first_mp);
5427 		ASSERT(mp != NULL);
5428 	} else {
5429 		secure = B_FALSE;
5430 	}
5431 	dst = ipha->ipha_dst;
5432 	/*
5433 	 * If the packet was tunneled and not multicast we only send to it
5434 	 * the first match.
5435 	 */
5436 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5437 	    !CLASSD(dst));
5438 
5439 	connfp = &ipcl_proto_fanout[protocol];
5440 	mutex_enter(&connfp->connf_lock);
5441 	connp = connfp->connf_head;
5442 	for (connp = connfp->connf_head; connp != NULL;
5443 		connp = connp->conn_next) {
5444 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5445 			break;
5446 	}
5447 
5448 	if (connp == NULL || connp->conn_upq == NULL) {
5449 		/*
5450 		 * No one bound to these addresses.  Is
5451 		 * there a client that wants all
5452 		 * unclaimed datagrams?
5453 		 */
5454 		mutex_exit(&connfp->connf_lock);
5455 		/*
5456 		 * Check for IPPROTO_ENCAP...
5457 		 */
5458 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5459 			/*
5460 			 * XXX If an IPsec mblk is here on a multicast
5461 			 * tunnel (using ip_mroute stuff), what should
5462 			 * I do?
5463 			 *
5464 			 * For now, just free the IPsec mblk before
5465 			 * passing it up to the multicast routing
5466 			 * stuff.
5467 			 *
5468 			 * BTW,  If I match a configured IP-in-IP
5469 			 * tunnel, ip_mroute_decap will never be
5470 			 * called.
5471 			 */
5472 			if (mp != first_mp)
5473 				freeb(first_mp);
5474 			ip_mroute_decap(q, mp);
5475 		} else {
5476 			/*
5477 			 * Otherwise send an ICMP protocol unreachable.
5478 			 */
5479 			if (ip_fanout_send_icmp(q, first_mp, flags,
5480 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5481 			    mctl_present, zoneid)) {
5482 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5483 			}
5484 		}
5485 		return;
5486 	}
5487 	CONN_INC_REF(connp);
5488 	first_connp = connp;
5489 
5490 	/*
5491 	 * Only send message to one tunnel driver by immediately
5492 	 * terminating the loop.
5493 	 */
5494 	connp = one_only ? NULL : connp->conn_next;
5495 
5496 	for (;;) {
5497 		while (connp != NULL) {
5498 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5499 			    flags, zoneid))
5500 				break;
5501 			connp = connp->conn_next;
5502 		}
5503 
5504 		/*
5505 		 * Copy the packet.
5506 		 */
5507 		if (connp == NULL || connp->conn_upq == NULL ||
5508 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5509 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5510 			/*
5511 			 * No more interested clients or memory
5512 			 * allocation failed
5513 			 */
5514 			connp = first_connp;
5515 			break;
5516 		}
5517 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5518 		CONN_INC_REF(connp);
5519 		mutex_exit(&connfp->connf_lock);
5520 		rq = connp->conn_rq;
5521 		if (!canputnext(rq)) {
5522 			if (flags & IP_FF_RAWIP) {
5523 				BUMP_MIB(&ip_mib, rawipInOverflows);
5524 			} else {
5525 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5526 			}
5527 
5528 			freemsg(first_mp1);
5529 		} else {
5530 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5531 				first_mp1 = ipsec_check_inbound_policy
5532 				    (first_mp1, connp, ipha, NULL,
5533 				    mctl_present);
5534 			}
5535 			if (first_mp1 != NULL) {
5536 				/*
5537 				 * ip_fanout_proto also gets called from
5538 				 * icmp_inbound_error_fanout, in which case
5539 				 * the msg type is M_CTL.  Don't add info
5540 				 * in this case for the time being. In future
5541 				 * when there is a need for knowing the
5542 				 * inbound iface index for ICMP error msgs,
5543 				 * then this can be changed.
5544 				 */
5545 				if ((connp->conn_recvif != 0) &&
5546 				    (mp->b_datap->db_type != M_CTL)) {
5547 					/*
5548 					 * the actual data will be
5549 					 * contained in b_cont upon
5550 					 * successful return of the
5551 					 * following call else
5552 					 * original mblk is returned
5553 					 */
5554 					ASSERT(recv_ill != NULL);
5555 					mp1 = ip_add_info(mp1, recv_ill,
5556 						IPF_RECVIF);
5557 				}
5558 				BUMP_MIB(&ip_mib, ipInDelivers);
5559 				if (mctl_present)
5560 					freeb(first_mp1);
5561 				putnext(rq, mp1);
5562 			}
5563 		}
5564 		mutex_enter(&connfp->connf_lock);
5565 		/* Follow the next pointer before releasing the conn. */
5566 		next_connp = connp->conn_next;
5567 		CONN_DEC_REF(connp);
5568 		connp = next_connp;
5569 	}
5570 
5571 	/* Last one.  Send it upstream. */
5572 	mutex_exit(&connfp->connf_lock);
5573 
5574 	/*
5575 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5576 	 * will be set to false.
5577 	 */
5578 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5579 		ill_index = ill->ill_phyint->phyint_ifindex;
5580 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5581 		if (mp == NULL) {
5582 			CONN_DEC_REF(connp);
5583 			if (mctl_present) {
5584 				freeb(first_mp);
5585 			}
5586 			return;
5587 		}
5588 	}
5589 
5590 	rq = connp->conn_rq;
5591 	if (!canputnext(rq)) {
5592 		if (flags & IP_FF_RAWIP) {
5593 			BUMP_MIB(&ip_mib, rawipInOverflows);
5594 		} else {
5595 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5596 		}
5597 
5598 		freemsg(first_mp);
5599 	} else {
5600 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5601 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5602 			    ipha, NULL, mctl_present);
5603 		}
5604 		if (first_mp != NULL) {
5605 			/*
5606 			 * ip_fanout_proto also gets called
5607 			 * from icmp_inbound_error_fanout, in
5608 			 * which case the msg type is M_CTL.
5609 			 * Don't add info in this case for time
5610 			 * being. In future when there is a
5611 			 * need for knowing the inbound iface
5612 			 * index for ICMP error msgs, then this
5613 			 * can be changed
5614 			 */
5615 			if ((connp->conn_recvif != 0) &&
5616 			    (mp->b_datap->db_type != M_CTL)) {
5617 				/*
5618 				 * the actual data will be contained in
5619 				 * b_cont upon successful return
5620 				 * of the following call else original
5621 				 * mblk is returned
5622 				 */
5623 				ASSERT(recv_ill != NULL);
5624 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5625 			}
5626 			BUMP_MIB(&ip_mib, ipInDelivers);
5627 			putnext(rq, mp);
5628 			if (mctl_present)
5629 				freeb(first_mp);
5630 		}
5631 	}
5632 	CONN_DEC_REF(connp);
5633 }
5634 
5635 /*
5636  * Fanout for TCP packets
5637  * The caller puts <fport, lport> in the ports parameter.
5638  *
5639  * IPQoS Notes
5640  * Before sending it to the client, invoke IPPF processing.
5641  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5642  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5643  * ip_policy is false.
5644  */
5645 static void
5646 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5647     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5648 {
5649 	mblk_t  *first_mp;
5650 	boolean_t secure;
5651 	uint32_t ill_index;
5652 	int	ip_hdr_len;
5653 	tcph_t	*tcph;
5654 	boolean_t syn_present = B_FALSE;
5655 	conn_t	*connp;
5656 
5657 	first_mp = mp;
5658 	if (mctl_present) {
5659 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5660 		mp = first_mp->b_cont;
5661 		secure = ipsec_in_is_secure(first_mp);
5662 		ASSERT(mp != NULL);
5663 	} else {
5664 		secure = B_FALSE;
5665 	}
5666 
5667 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5668 
5669 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5670 	    NULL) {
5671 		/*
5672 		 * No connected connection or listener. Send a
5673 		 * TH_RST via tcp_xmit_listeners_reset.
5674 		 */
5675 
5676 		/* Initiate IPPf processing, if needed. */
5677 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5678 			uint32_t ill_index;
5679 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5680 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5681 			if (first_mp == NULL)
5682 				return;
5683 		}
5684 		BUMP_MIB(&ip_mib, ipInDelivers);
5685 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5686 		return;
5687 	}
5688 
5689 	/*
5690 	 * Allocate the SYN for the TCP connection here itself
5691 	 */
5692 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5693 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5694 		if (IPCL_IS_TCP(connp)) {
5695 			squeue_t *sqp;
5696 
5697 			/*
5698 			 * For fused tcp loopback, assign the eager's
5699 			 * squeue to be that of the active connect's.
5700 			 * Note that we don't check for IP_FF_LOOPBACK
5701 			 * here since this routine gets called only
5702 			 * for loopback (unlike the IPv6 counterpart).
5703 			 */
5704 			if (do_tcp_fusion &&
5705 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5706 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy) {
5707 				ASSERT(Q_TO_CONN(q) != NULL);
5708 				sqp = Q_TO_CONN(q)->conn_sqp;
5709 			} else {
5710 				sqp = IP_SQUEUE_GET(lbolt);
5711 			}
5712 
5713 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5714 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
5715 			syn_present = B_TRUE;
5716 		}
5717 	}
5718 
5719 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5720 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5721 		if ((flags & TH_RST) || (flags & TH_URG)) {
5722 			CONN_DEC_REF(connp);
5723 			freemsg(first_mp);
5724 			return;
5725 		}
5726 		if (flags & TH_ACK) {
5727 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5728 			CONN_DEC_REF(connp);
5729 			return;
5730 		}
5731 
5732 		CONN_DEC_REF(connp);
5733 		freemsg(first_mp);
5734 		return;
5735 	}
5736 
5737 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5738 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5739 		    NULL, mctl_present);
5740 		if (first_mp == NULL) {
5741 			CONN_DEC_REF(connp);
5742 			return;
5743 		}
5744 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5745 			ASSERT(syn_present);
5746 			if (mctl_present) {
5747 				ASSERT(first_mp != mp);
5748 				first_mp->b_datap->db_struioflag |=
5749 				    STRUIO_POLICY;
5750 			} else {
5751 				ASSERT(first_mp == mp);
5752 				mp->b_datap->db_struioflag &=
5753 				    ~STRUIO_EAGER;
5754 				mp->b_datap->db_struioflag |=
5755 				    STRUIO_POLICY;
5756 			}
5757 		} else {
5758 			/*
5759 			 * Discard first_mp early since we're dealing with a
5760 			 * fully-connected conn_t and tcp doesn't do policy in
5761 			 * this case.
5762 			 */
5763 			if (mctl_present) {
5764 				freeb(first_mp);
5765 				mctl_present = B_FALSE;
5766 			}
5767 			first_mp = mp;
5768 		}
5769 	}
5770 
5771 	/*
5772 	 * Initiate policy processing here if needed. If we get here from
5773 	 * icmp_inbound_error_fanout, ip_policy is false.
5774 	 */
5775 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5776 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5777 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5778 		if (mp == NULL) {
5779 			CONN_DEC_REF(connp);
5780 			if (mctl_present)
5781 				freeb(first_mp);
5782 			return;
5783 		} else if (mctl_present) {
5784 			ASSERT(first_mp != mp);
5785 			first_mp->b_cont = mp;
5786 		} else {
5787 			first_mp = mp;
5788 		}
5789 	}
5790 
5791 
5792 
5793 	/* Handle IPv6 socket options. */
5794 	if (!syn_present &&
5795 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5796 		/* Add header */
5797 		ASSERT(recv_ill != NULL);
5798 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5799 		if (mp == NULL) {
5800 			CONN_DEC_REF(connp);
5801 			if (mctl_present)
5802 				freeb(first_mp);
5803 			return;
5804 		} else if (mctl_present) {
5805 			/*
5806 			 * ip_add_info might return a new mp.
5807 			 */
5808 			ASSERT(first_mp != mp);
5809 			first_mp->b_cont = mp;
5810 		} else {
5811 			first_mp = mp;
5812 		}
5813 	}
5814 
5815 	BUMP_MIB(&ip_mib, ipInDelivers);
5816 	if (IPCL_IS_TCP(connp)) {
5817 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5818 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5819 	} else {
5820 		putnext(connp->conn_rq, first_mp);
5821 		CONN_DEC_REF(connp);
5822 	}
5823 }
5824 
5825 /*
5826  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5827  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5828  * Caller is responsible for dropping references to the conn, and freeing
5829  * first_mp.
5830  *
5831  * IPQoS Notes
5832  * Before sending it to the client, invoke IPPF processing. Policy processing
5833  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5834  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5835  * ip_wput_local, ip_policy is false.
5836  */
5837 static void
5838 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5839     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5840     boolean_t ip_policy)
5841 {
5842 	boolean_t	mctl_present = (first_mp != NULL);
5843 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5844 	uint32_t	ill_index;
5845 
5846 	if (mctl_present)
5847 		first_mp->b_cont = mp;
5848 	else
5849 		first_mp = mp;
5850 
5851 	if (CONN_UDP_FLOWCTLD(connp)) {
5852 		BUMP_MIB(&ip_mib, udpInOverflows);
5853 		freemsg(first_mp);
5854 		return;
5855 	}
5856 
5857 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5858 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5859 		    NULL, mctl_present);
5860 		if (first_mp == NULL)
5861 			return;	/* Freed by ipsec_check_inbound_policy(). */
5862 	}
5863 	if (mctl_present)
5864 		freeb(first_mp);
5865 
5866 	if (connp->conn_recvif)
5867 		in_flags = IPF_RECVIF;
5868 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5869 		in_flags |= IPF_RECVSLLA;
5870 
5871 	/* Handle IPv6 options. */
5872 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5873 		in_flags |= IPF_RECVIF;
5874 
5875 	/*
5876 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5877 	 * freed if the packet is dropped. The caller will do so.
5878 	 */
5879 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5880 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5881 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5882 		if (mp == NULL) {
5883 			return;
5884 		}
5885 	}
5886 	if ((in_flags != 0) &&
5887 	    (mp->b_datap->db_type != M_CTL)) {
5888 		/*
5889 		 * The actual data will be contained in b_cont
5890 		 * upon successful return of the following call
5891 		 * else original mblk is returned
5892 		 */
5893 		ASSERT(recv_ill != NULL);
5894 		mp = ip_add_info(mp, recv_ill, in_flags);
5895 	}
5896 	BUMP_MIB(&ip_mib, ipInDelivers);
5897 
5898 	/* Send it upstream */
5899 	CONN_UDP_RECV(connp, mp);
5900 }
5901 
5902 /*
5903  * Fanout for UDP packets.
5904  * The caller puts <fport, lport> in the ports parameter.
5905  *
5906  * If SO_REUSEADDR is set all multicast and broadcast packets
5907  * will be delivered to all streams bound to the same port.
5908  *
5909  * Zones notes:
5910  * Multicast and broadcast packets will be distributed to streams in all zones.
5911  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5912  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5913  * packets. To maintain this behavior with multiple zones, the conns are grouped
5914  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5915  * each zone. If unset, all the following conns in the same zone are skipped.
5916  */
5917 static void
5918 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5919     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5920     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5921 {
5922 	uint32_t	dstport, srcport;
5923 	ipaddr_t	dst;
5924 	mblk_t		*first_mp;
5925 	boolean_t	secure;
5926 	in6_addr_t	v6src;
5927 	conn_t		*connp;
5928 	connf_t		*connfp;
5929 	conn_t		*first_connp;
5930 	conn_t		*next_connp;
5931 	mblk_t		*mp1, *first_mp1;
5932 	ipaddr_t	src;
5933 	zoneid_t	last_zoneid;
5934 	boolean_t	reuseaddr;
5935 
5936 	first_mp = mp;
5937 	if (mctl_present) {
5938 		mp = first_mp->b_cont;
5939 		first_mp->b_cont = NULL;
5940 		secure = ipsec_in_is_secure(first_mp);
5941 		ASSERT(mp != NULL);
5942 	} else {
5943 		first_mp = NULL;
5944 		secure = B_FALSE;
5945 	}
5946 
5947 	/* Extract ports in net byte order */
5948 	dstport = htons(ntohl(ports) & 0xFFFF);
5949 	srcport = htons(ntohl(ports) >> 16);
5950 	dst = ipha->ipha_dst;
5951 	src = ipha->ipha_src;
5952 
5953 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5954 	mutex_enter(&connfp->connf_lock);
5955 	connp = connfp->connf_head;
5956 	if (!broadcast && !CLASSD(dst)) {
5957 		/*
5958 		 * Not broadcast or multicast. Send to the one (first)
5959 		 * client we find. No need to check conn_wantpacket()
5960 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5961 		 * IPv4 unicast packets.
5962 		 */
5963 		while ((connp != NULL) &&
5964 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5965 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5966 			connp = connp->conn_next;
5967 		}
5968 
5969 		if (connp == NULL || connp->conn_upq == NULL)
5970 			goto notfound;
5971 		CONN_INC_REF(connp);
5972 		mutex_exit(&connfp->connf_lock);
5973 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5974 		    recv_ill, ip_policy);
5975 		IP_STAT(ip_udp_fannorm);
5976 		CONN_DEC_REF(connp);
5977 		return;
5978 	}
5979 
5980 	/*
5981 	 * Broadcast and multicast case
5982 	 *
5983 	 * Need to check conn_wantpacket().
5984 	 * If SO_REUSEADDR has been set on the first we send the
5985 	 * packet to all clients that have joined the group and
5986 	 * match the port.
5987 	 */
5988 
5989 	while (connp != NULL) {
5990 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
5991 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5992 			break;
5993 		connp = connp->conn_next;
5994 	}
5995 
5996 	if (connp == NULL || connp->conn_upq == NULL)
5997 		goto notfound;
5998 
5999 	first_connp = connp;
6000 	/*
6001 	 * When SO_REUSEADDR is not set, send the packet only to the first
6002 	 * matching connection in its zone by keeping track of the zoneid.
6003 	 */
6004 	reuseaddr = first_connp->conn_reuseaddr;
6005 	last_zoneid = first_connp->conn_zoneid;
6006 
6007 	CONN_INC_REF(connp);
6008 	connp = connp->conn_next;
6009 	for (;;) {
6010 		while (connp != NULL) {
6011 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6012 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6013 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6014 				break;
6015 			connp = connp->conn_next;
6016 		}
6017 		/*
6018 		 * Just copy the data part alone. The mctl part is
6019 		 * needed just for verifying policy and it is never
6020 		 * sent up.
6021 		 */
6022 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6023 		    ((mp1 = copymsg(mp)) == NULL))) {
6024 			/*
6025 			 * No more interested clients or memory
6026 			 * allocation failed
6027 			 */
6028 			connp = first_connp;
6029 			break;
6030 		}
6031 		if (connp->conn_zoneid != last_zoneid) {
6032 			/*
6033 			 * Update the zoneid so that the packet isn't sent to
6034 			 * any more conns in the same zone unless SO_REUSEADDR
6035 			 * is set.
6036 			 */
6037 			reuseaddr = connp->conn_reuseaddr;
6038 			last_zoneid = connp->conn_zoneid;
6039 		}
6040 		if (first_mp != NULL) {
6041 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6042 			    ipsec_info_type == IPSEC_IN);
6043 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6044 			if (first_mp1 == NULL) {
6045 				freemsg(mp1);
6046 				connp = first_connp;
6047 				break;
6048 			}
6049 		} else {
6050 			first_mp1 = NULL;
6051 		}
6052 		CONN_INC_REF(connp);
6053 		mutex_exit(&connfp->connf_lock);
6054 		/*
6055 		 * IPQoS notes: We don't send the packet for policy
6056 		 * processing here, will do it for the last one (below).
6057 		 * i.e. we do it per-packet now, but if we do policy
6058 		 * processing per-conn, then we would need to do it
6059 		 * here too.
6060 		 */
6061 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6062 		    ipha, flags, recv_ill, B_FALSE);
6063 		mutex_enter(&connfp->connf_lock);
6064 		/* Follow the next pointer before releasing the conn. */
6065 		next_connp = connp->conn_next;
6066 		IP_STAT(ip_udp_fanmb);
6067 		CONN_DEC_REF(connp);
6068 		connp = next_connp;
6069 	}
6070 
6071 	/* Last one.  Send it upstream. */
6072 	mutex_exit(&connfp->connf_lock);
6073 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6074 	    ip_policy);
6075 	IP_STAT(ip_udp_fanmb);
6076 	CONN_DEC_REF(connp);
6077 	return;
6078 
6079 notfound:
6080 
6081 	mutex_exit(&connfp->connf_lock);
6082 	IP_STAT(ip_udp_fanothers);
6083 	/*
6084 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6085 	 * have already been matched above, since they live in the IPv4
6086 	 * fanout tables. This implies we only need to
6087 	 * check for IPv6 in6addr_any endpoints here.
6088 	 * Thus we compare using ipv6_all_zeros instead of the destination
6089 	 * address, except for the multicast group membership lookup which
6090 	 * uses the IPv4 destination.
6091 	 */
6092 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6093 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6094 	mutex_enter(&connfp->connf_lock);
6095 	connp = connfp->connf_head;
6096 	if (!broadcast && !CLASSD(dst)) {
6097 		while (connp != NULL) {
6098 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6099 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6100 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6101 			    !connp->conn_ipv6_v6only)
6102 				break;
6103 			connp = connp->conn_next;
6104 		}
6105 
6106 		if (connp == NULL || connp->conn_upq == NULL) {
6107 			/*
6108 			 * No one bound to this port.  Is
6109 			 * there a client that wants all
6110 			 * unclaimed datagrams?
6111 			 */
6112 			mutex_exit(&connfp->connf_lock);
6113 
6114 			if (mctl_present)
6115 				first_mp->b_cont = mp;
6116 			else
6117 				first_mp = mp;
6118 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6119 				ip_fanout_proto(q, first_mp, ill, ipha,
6120 				    flags | IP_FF_RAWIP, mctl_present,
6121 				    ip_policy, recv_ill, zoneid);
6122 			} else {
6123 				if (ip_fanout_send_icmp(q, first_mp, flags,
6124 				    ICMP_DEST_UNREACHABLE,
6125 				    ICMP_PORT_UNREACHABLE,
6126 				    mctl_present, zoneid)) {
6127 					BUMP_MIB(&ip_mib, udpNoPorts);
6128 				}
6129 			}
6130 			return;
6131 		}
6132 		CONN_INC_REF(connp);
6133 		mutex_exit(&connfp->connf_lock);
6134 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6135 		    recv_ill, ip_policy);
6136 		CONN_DEC_REF(connp);
6137 		return;
6138 	}
6139 	/*
6140 	 * IPv4 multicast packet being delivered to an AF_INET6
6141 	 * in6addr_any endpoint.
6142 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6143 	 * and not conn_wantpacket_v6() since any multicast membership is
6144 	 * for an IPv4-mapped multicast address.
6145 	 * The packet is sent to all clients in all zones that have joined the
6146 	 * group and match the port.
6147 	 */
6148 	while (connp != NULL) {
6149 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6150 		    srcport, v6src) &&
6151 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6152 			break;
6153 		connp = connp->conn_next;
6154 	}
6155 
6156 	if (connp == NULL || connp->conn_upq == NULL) {
6157 		/*
6158 		 * No one bound to this port.  Is
6159 		 * there a client that wants all
6160 		 * unclaimed datagrams?
6161 		 */
6162 		mutex_exit(&connfp->connf_lock);
6163 
6164 		if (mctl_present)
6165 			first_mp->b_cont = mp;
6166 		else
6167 			first_mp = mp;
6168 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6169 			ip_fanout_proto(q, first_mp, ill, ipha,
6170 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6171 			    recv_ill, zoneid);
6172 		} else {
6173 			/*
6174 			 * We used to attempt to send an icmp error here, but
6175 			 * since this is known to be a multicast packet
6176 			 * and we don't send icmp errors in response to
6177 			 * multicast, just drop the packet and give up sooner.
6178 			 */
6179 			BUMP_MIB(&ip_mib, udpNoPorts);
6180 			freemsg(first_mp);
6181 		}
6182 		return;
6183 	}
6184 
6185 	first_connp = connp;
6186 
6187 	CONN_INC_REF(connp);
6188 	connp = connp->conn_next;
6189 	for (;;) {
6190 		while (connp != NULL) {
6191 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6192 			    ipv6_all_zeros, srcport, v6src) &&
6193 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6194 				break;
6195 			connp = connp->conn_next;
6196 		}
6197 		/*
6198 		 * Just copy the data part alone. The mctl part is
6199 		 * needed just for verifying policy and it is never
6200 		 * sent up.
6201 		 */
6202 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6203 		    ((mp1 = copymsg(mp)) == NULL))) {
6204 			/*
6205 			 * No more intested clients or memory
6206 			 * allocation failed
6207 			 */
6208 			connp = first_connp;
6209 			break;
6210 		}
6211 		if (first_mp != NULL) {
6212 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6213 			    ipsec_info_type == IPSEC_IN);
6214 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6215 			if (first_mp1 == NULL) {
6216 				freemsg(mp1);
6217 				connp = first_connp;
6218 				break;
6219 			}
6220 		} else {
6221 			first_mp1 = NULL;
6222 		}
6223 		CONN_INC_REF(connp);
6224 		mutex_exit(&connfp->connf_lock);
6225 		/*
6226 		 * IPQoS notes: We don't send the packet for policy
6227 		 * processing here, will do it for the last one (below).
6228 		 * i.e. we do it per-packet now, but if we do policy
6229 		 * processing per-conn, then we would need to do it
6230 		 * here too.
6231 		 */
6232 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6233 		    ipha, flags, recv_ill, B_FALSE);
6234 		mutex_enter(&connfp->connf_lock);
6235 		/* Follow the next pointer before releasing the conn. */
6236 		next_connp = connp->conn_next;
6237 		CONN_DEC_REF(connp);
6238 		connp = next_connp;
6239 	}
6240 
6241 	/* Last one.  Send it upstream. */
6242 	mutex_exit(&connfp->connf_lock);
6243 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6244 	    ip_policy);
6245 	CONN_DEC_REF(connp);
6246 }
6247 
6248 /*
6249  * Complete the ip_wput header so that it
6250  * is possible to generate ICMP
6251  * errors.
6252  */
6253 static int
6254 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6255 {
6256 	ire_t *ire;
6257 
6258 	if (ipha->ipha_src == INADDR_ANY) {
6259 		ire = ire_lookup_local(zoneid);
6260 		if (ire == NULL) {
6261 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6262 			return (1);
6263 		}
6264 		ipha->ipha_src = ire->ire_addr;
6265 		ire_refrele(ire);
6266 	}
6267 	ipha->ipha_ttl = ip_def_ttl;
6268 	ipha->ipha_hdr_checksum = 0;
6269 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6270 	return (0);
6271 }
6272 
6273 /*
6274  * Nobody should be sending
6275  * packets up this stream
6276  */
6277 static void
6278 ip_lrput(queue_t *q, mblk_t *mp)
6279 {
6280 	mblk_t *mp1;
6281 
6282 	switch (mp->b_datap->db_type) {
6283 	case M_FLUSH:
6284 		/* Turn around */
6285 		if (*mp->b_rptr & FLUSHW) {
6286 			*mp->b_rptr &= ~FLUSHR;
6287 			qreply(q, mp);
6288 			return;
6289 		}
6290 		break;
6291 	}
6292 	/* Could receive messages that passed through ar_rput */
6293 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6294 		mp1->b_prev = mp1->b_next = NULL;
6295 	freemsg(mp);
6296 }
6297 
6298 /* Nobody should be sending packets down this stream */
6299 /* ARGSUSED */
6300 void
6301 ip_lwput(queue_t *q, mblk_t *mp)
6302 {
6303 	freemsg(mp);
6304 }
6305 
6306 /*
6307  * Move the first hop in any source route to ipha_dst and remove that part of
6308  * the source route.  Called by other protocols.  Errors in option formatting
6309  * are ignored - will be handled by ip_wput_options Return the final
6310  * destination (either ipha_dst or the last entry in a source route.)
6311  */
6312 ipaddr_t
6313 ip_massage_options(ipha_t *ipha)
6314 {
6315 	ipoptp_t	opts;
6316 	uchar_t		*opt;
6317 	uint8_t		optval;
6318 	uint8_t		optlen;
6319 	ipaddr_t	dst;
6320 	int		i;
6321 	ire_t		*ire;
6322 
6323 	ip2dbg(("ip_massage_options\n"));
6324 	dst = ipha->ipha_dst;
6325 	for (optval = ipoptp_first(&opts, ipha);
6326 	    optval != IPOPT_EOL;
6327 	    optval = ipoptp_next(&opts)) {
6328 		opt = opts.ipoptp_cur;
6329 		switch (optval) {
6330 			uint8_t off;
6331 		case IPOPT_SSRR:
6332 		case IPOPT_LSRR:
6333 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6334 				ip1dbg(("ip_massage_options: bad src route\n"));
6335 				break;
6336 			}
6337 			optlen = opts.ipoptp_len;
6338 			off = opt[IPOPT_OFFSET];
6339 			off--;
6340 		redo_srr:
6341 			if (optlen < IP_ADDR_LEN ||
6342 			    off > optlen - IP_ADDR_LEN) {
6343 				/* End of source route */
6344 				ip1dbg(("ip_massage_options: end of SR\n"));
6345 				break;
6346 			}
6347 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6348 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6349 			    ntohl(dst)));
6350 			/*
6351 			 * Check if our address is present more than
6352 			 * once as consecutive hops in source route.
6353 			 * XXX verify per-interface ip_forwarding
6354 			 * for source route?
6355 			 */
6356 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6357 			    ALL_ZONES, MATCH_IRE_TYPE);
6358 			if (ire != NULL) {
6359 				ire_refrele(ire);
6360 				off += IP_ADDR_LEN;
6361 				goto redo_srr;
6362 			}
6363 			if (dst == htonl(INADDR_LOOPBACK)) {
6364 				ip1dbg(("ip_massage_options: loopback addr in "
6365 				    "source route!\n"));
6366 				break;
6367 			}
6368 			/*
6369 			 * Update ipha_dst to be the first hop and remove the
6370 			 * first hop from the source route (by overwriting
6371 			 * part of the option with NOP options).
6372 			 */
6373 			ipha->ipha_dst = dst;
6374 			/* Put the last entry in dst */
6375 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6376 			    3;
6377 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6378 
6379 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6380 			    ntohl(dst)));
6381 			/* Move down and overwrite */
6382 			opt[IP_ADDR_LEN] = opt[0];
6383 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6384 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6385 			for (i = 0; i < IP_ADDR_LEN; i++)
6386 				opt[i] = IPOPT_NOP;
6387 			break;
6388 		}
6389 	}
6390 	return (dst);
6391 }
6392 
6393 /*
6394  * This function's job is to forward data to the reverse tunnel (FA->HA)
6395  * after doing a few checks. It is assumed that the incoming interface
6396  * of the packet is always different than the outgoing interface and the
6397  * ire_type of the found ire has to be a non-resolver type.
6398  *
6399  * IPQoS notes
6400  * IP policy is invoked twice for a forwarded packet, once on the read side
6401  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6402  * enabled.
6403  */
6404 static void
6405 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6406 {
6407 	ipha_t		*ipha;
6408 	queue_t		*q;
6409 	uint32_t 	pkt_len;
6410 #define	rptr    ((uchar_t *)ipha)
6411 	uint32_t 	sum;
6412 	uint32_t 	max_frag;
6413 	mblk_t		*first_mp;
6414 	uint32_t	ill_index;
6415 
6416 	ASSERT(ire != NULL);
6417 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6418 	ASSERT(ire->ire_stq != NULL);
6419 
6420 	/* Initiate read side IPPF processing */
6421 	if (IPP_ENABLED(IPP_FWD_IN)) {
6422 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6423 		ip_process(IPP_FWD_IN, &mp, ill_index);
6424 		if (mp == NULL) {
6425 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6426 			    "dropped during IPPF processing\n"));
6427 			return;
6428 		}
6429 	}
6430 
6431 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6432 		ILLF_ROUTER) == 0) ||
6433 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6434 		BUMP_MIB(&ip_mib, ipForwProhibits);
6435 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6436 		    "forwarding is not turned on\n"));
6437 		goto drop_pkt;
6438 	}
6439 
6440 	/*
6441 	 * Don't forward if the interface is down
6442 	 */
6443 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6444 		BUMP_MIB(&ip_mib, ipInDiscards);
6445 		goto drop_pkt;
6446 	}
6447 
6448 	ipha = (ipha_t *)mp->b_rptr;
6449 	pkt_len = ntohs(ipha->ipha_length);
6450 	/* Adjust the checksum to reflect the ttl decrement. */
6451 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6452 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6453 	if (ipha->ipha_ttl-- <= 1) {
6454 		if (ip_csum_hdr(ipha)) {
6455 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6456 			goto drop_pkt;
6457 		}
6458 		q = ire->ire_stq;
6459 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6460 		    BPRI_HI)) == NULL) {
6461 			goto drop_pkt;
6462 		}
6463 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6464 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6465 
6466 		return;
6467 	}
6468 
6469 	/* Get the ill_index of the ILL */
6470 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6471 
6472 	/*
6473 	 * ip_mrtun_forward is only used by foreign agent to reverse
6474 	 * tunnel the incoming packet. So it does not do any option
6475 	 * processing for source routing.
6476 	 */
6477 	max_frag = ire->ire_max_frag;
6478 	if (pkt_len > max_frag) {
6479 		/*
6480 		 * It needs fragging on its way out.  We haven't
6481 		 * verified the header checksum yet.  Since we
6482 		 * are going to put a surely good checksum in the
6483 		 * outgoing header, we have to make sure that it
6484 		 * was good coming in.
6485 		 */
6486 		if (ip_csum_hdr(ipha)) {
6487 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6488 			goto drop_pkt;
6489 		}
6490 
6491 		/* Initiate write side IPPF processing */
6492 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6493 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6494 			if (mp == NULL) {
6495 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6496 				    "dropped/deferred during ip policy "\
6497 				    "processing\n"));
6498 				return;
6499 			}
6500 		}
6501 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6502 		    BPRI_HI)) == NULL) {
6503 			goto drop_pkt;
6504 		}
6505 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6506 		mp = first_mp;
6507 
6508 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6509 		return;
6510 	}
6511 
6512 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6513 
6514 	ASSERT(ire->ire_ipif != NULL);
6515 
6516 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6517 	if (mp == NULL) {
6518 		BUMP_MIB(&ip_mib, ipInDiscards);
6519 		return;
6520 	}
6521 
6522 	/* Now send the packet to the tunnel interface */
6523 	q = ire->ire_stq;
6524 	UPDATE_IB_PKT_COUNT(ire);
6525 	ire->ire_last_used_time = lbolt;
6526 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6527 	putnext(q, mp);
6528 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6529 	return;
6530 
6531 drop_pkt:;
6532 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6533 	freemsg(mp);
6534 #undef	rptr
6535 }
6536 
6537 /*
6538  * Fills the ipsec_out_t data structure with appropriate fields and
6539  * prepends it to mp which contains the IP hdr + data that was meant
6540  * to be forwarded. Please note that ipsec_out_info data structure
6541  * is used here to communicate the outgoing ill path at ip_wput()
6542  * for the ICMP error packet. This has nothing to do with ipsec IP
6543  * security. ipsec_out_t is really used to pass the info to the module
6544  * IP where this information cannot be extracted from conn.
6545  * This functions is called by ip_mrtun_forward().
6546  */
6547 void
6548 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6549 {
6550 	ipsec_out_t	*io;
6551 
6552 	ASSERT(xmit_ill != NULL);
6553 	first_mp->b_datap->db_type = M_CTL;
6554 	first_mp->b_wptr += sizeof (ipsec_info_t);
6555 	/*
6556 	 * This is to pass info to ip_wput in absence of conn.
6557 	 * ipsec_out_secure will be B_FALSE because of this.
6558 	 * Thus ipsec_out_secure being B_FALSE indicates that
6559 	 * this is not IPSEC security related information.
6560 	 */
6561 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6562 	io = (ipsec_out_t *)first_mp->b_rptr;
6563 	io->ipsec_out_type = IPSEC_OUT;
6564 	io->ipsec_out_len = sizeof (ipsec_out_t);
6565 	first_mp->b_cont = mp;
6566 	io->ipsec_out_ill_index =
6567 	    xmit_ill->ill_phyint->phyint_ifindex;
6568 	io->ipsec_out_xmit_if = B_TRUE;
6569 }
6570 
6571 /*
6572  * Return the network mask
6573  * associated with the specified address.
6574  */
6575 ipaddr_t
6576 ip_net_mask(ipaddr_t addr)
6577 {
6578 	uchar_t	*up = (uchar_t *)&addr;
6579 	ipaddr_t mask = 0;
6580 	uchar_t	*maskp = (uchar_t *)&mask;
6581 
6582 #if defined(__i386) || defined(__amd64)
6583 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6584 #endif
6585 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6586 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6587 #endif
6588 	if (CLASSD(addr)) {
6589 		maskp[0] = 0xF0;
6590 		return (mask);
6591 	}
6592 	if (addr == 0)
6593 		return (0);
6594 	maskp[0] = 0xFF;
6595 	if ((up[0] & 0x80) == 0)
6596 		return (mask);
6597 
6598 	maskp[1] = 0xFF;
6599 	if ((up[0] & 0xC0) == 0x80)
6600 		return (mask);
6601 
6602 	maskp[2] = 0xFF;
6603 	if ((up[0] & 0xE0) == 0xC0)
6604 		return (mask);
6605 
6606 	/* Must be experimental or multicast, indicate as much */
6607 	return ((ipaddr_t)0);
6608 }
6609 
6610 /*
6611  * Select an ill for the packet by considering load spreading across
6612  * a different ill in the group if dst_ill is part of some group.
6613  */
6614 static ill_t *
6615 ip_newroute_get_dst_ill(ill_t *dst_ill)
6616 {
6617 	ill_t *ill;
6618 
6619 	/*
6620 	 * We schedule irrespective of whether the source address is
6621 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6622 	 */
6623 	ill = illgrp_scheduler(dst_ill);
6624 	if (ill == NULL)
6625 		return (NULL);
6626 
6627 	/*
6628 	 * For groups with names ip_sioctl_groupname ensures that all
6629 	 * ills are of same type. For groups without names, ifgrp_insert
6630 	 * ensures this.
6631 	 */
6632 	ASSERT(dst_ill->ill_type == ill->ill_type);
6633 
6634 	return (ill);
6635 }
6636 
6637 /*
6638  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6639  */
6640 ill_t *
6641 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6642 {
6643 	ill_t *ret_ill;
6644 
6645 	ASSERT(ifindex != 0);
6646 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6647 	if (ret_ill == NULL ||
6648 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6649 		if (isv6) {
6650 			if (ill != NULL) {
6651 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6652 			} else {
6653 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6654 			}
6655 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6656 			    "bad ifindex %d.\n", ifindex));
6657 		} else {
6658 			BUMP_MIB(&ip_mib, ipOutDiscards);
6659 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6660 			    "bad ifindex %d.\n", ifindex));
6661 		}
6662 		if (ret_ill != NULL)
6663 			ill_refrele(ret_ill);
6664 		freemsg(first_mp);
6665 		return (NULL);
6666 	}
6667 
6668 	return (ret_ill);
6669 }
6670 
6671 /*
6672  * IPv4 -
6673  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6674  * out a packet to a destination address for which we do not have specific
6675  * (or sufficient) routing information.
6676  *
6677  * NOTE : These are the scopes of some of the variables that point at IRE,
6678  *	  which needs to be followed while making any future modifications
6679  *	  to avoid memory leaks.
6680  *
6681  *	- ire and sire are the entries looked up initially by
6682  *	  ire_ftable_lookup.
6683  *	- ipif_ire is used to hold the interface ire associated with
6684  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6685  *	  it before branching out to error paths.
6686  *	- save_ire is initialized before ire_create, so that ire returned
6687  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6688  *	  before breaking out of the switch.
6689  *
6690  *	Thus on failures, we have to REFRELE only ire and sire, if they
6691  *	are not NULL.
6692  */
6693 void
6694 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6695 {
6696 	areq_t	*areq;
6697 	ipaddr_t gw = 0;
6698 	ire_t	*ire = NULL;
6699 	mblk_t	*res_mp;
6700 	ipaddr_t *addrp;
6701 	ipaddr_t nexthop_addr;
6702 	ipif_t  *src_ipif = NULL;
6703 	ill_t	*dst_ill = NULL;
6704 	ipha_t  *ipha;
6705 	ire_t	*sire = NULL;
6706 	mblk_t	*first_mp;
6707 	ire_t	*save_ire;
6708 	mblk_t	*dlureq_mp;
6709 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6710 	ushort_t ire_marks = 0;
6711 	boolean_t mctl_present;
6712 	ipsec_out_t *io;
6713 	mblk_t	*saved_mp;
6714 	ire_t	*first_sire = NULL;
6715 	mblk_t	*copy_mp = NULL;
6716 	mblk_t	*xmit_mp = NULL;
6717 	ipaddr_t save_dst;
6718 	uint32_t multirt_flags =
6719 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6720 	boolean_t multirt_is_resolvable;
6721 	boolean_t multirt_resolve_next;
6722 	boolean_t do_attach_ill = B_FALSE;
6723 	boolean_t ip_nexthop = B_FALSE;
6724 	zoneid_t zoneid;
6725 
6726 	if (ip_debug > 2) {
6727 		/* ip1dbg */
6728 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6729 	}
6730 
6731 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6732 	if (mctl_present) {
6733 		io = (ipsec_out_t *)first_mp->b_rptr;
6734 		zoneid = io->ipsec_out_zoneid;
6735 		ASSERT(zoneid != ALL_ZONES);
6736 	} else if (connp != NULL) {
6737 		zoneid = connp->conn_zoneid;
6738 	} else {
6739 		zoneid = GLOBAL_ZONEID;
6740 	}
6741 
6742 	ipha = (ipha_t *)mp->b_rptr;
6743 
6744 	/* All multicast lookups come through ip_newroute_ipif() */
6745 	if (CLASSD(dst)) {
6746 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6747 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6748 		freemsg(first_mp);
6749 		return;
6750 	}
6751 
6752 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6753 		goto icmp_err_ret;
6754 	}
6755 
6756 	if (mctl_present && io->ipsec_out_attach_if) {
6757 		/* ip_grab_attach_ill returns a held ill */
6758 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6759 		    io->ipsec_out_ill_index, B_FALSE);
6760 
6761 		/* Failure case frees things for us. */
6762 		if (attach_ill == NULL)
6763 			return;
6764 
6765 		/*
6766 		 * Check if we need an ire that will not be
6767 		 * looked up by anybody else i.e. HIDDEN.
6768 		 */
6769 		if (ill_is_probeonly(attach_ill))
6770 			ire_marks = IRE_MARK_HIDDEN;
6771 	}
6772 	if (mctl_present && io->ipsec_out_ip_nexthop) {
6773 		ip_nexthop = B_TRUE;
6774 		nexthop_addr = io->ipsec_out_nexthop_addr;
6775 	}
6776 	/*
6777 	 * If this IRE is created for forwarding or it is not for
6778 	 * traffic for congestion controlled protocols, mark it as temporary.
6779 	 */
6780 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6781 		ire_marks |= IRE_MARK_TEMPORARY;
6782 
6783 	/*
6784 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6785 	 * chain until it gets the most specific information available.
6786 	 * For example, we know that there is no IRE_CACHE for this dest,
6787 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6788 	 * ire_ftable_lookup will look up the gateway, etc.
6789 	 * Check if in_ill != NULL. If it is true, the packet must be
6790 	 * from an incoming interface where RTA_SRCIFP is set.
6791 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6792 	 * to the destination, of equal netmask length in the forward table,
6793 	 * will be recursively explored. If no information is available
6794 	 * for the final gateway of that route, we force the returned ire
6795 	 * to be equal to sire using MATCH_IRE_PARENT.
6796 	 * At least, in this case we have a starting point (in the buckets)
6797 	 * to look for other routes to the destination in the forward table.
6798 	 * This is actually used only for multirouting, where a list
6799 	 * of routes has to be processed in sequence.
6800 	 */
6801 	if (in_ill != NULL) {
6802 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6803 		    in_ill, MATCH_IRE_TYPE);
6804 	} else if (ip_nexthop) {
6805 		/*
6806 		 * The first time we come here, we look for an IRE_INTERFACE
6807 		 * entry for the specified nexthop, set the dst to be the
6808 		 * nexthop address and create an IRE_CACHE entry for the
6809 		 * nexthop. The next time around, we are able to find an
6810 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
6811 		 * nexthop address and create an IRE_CACHE entry for the
6812 		 * destination address via the specified nexthop.
6813 		 */
6814 		ire = ire_cache_lookup(nexthop_addr, zoneid);
6815 		if (ire != NULL) {
6816 			gw = nexthop_addr;
6817 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
6818 		} else {
6819 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
6820 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
6821 			    MATCH_IRE_TYPE);
6822 			if (ire != NULL) {
6823 				dst = nexthop_addr;
6824 			}
6825 		}
6826 	} else if (attach_ill == NULL) {
6827 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6828 		    NULL, &sire, zoneid, 0,
6829 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6830 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6831 	} else {
6832 		/*
6833 		 * attach_ill is set only for communicating with
6834 		 * on-link hosts. So, don't look for DEFAULT.
6835 		 */
6836 		ipif_t	*attach_ipif;
6837 
6838 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6839 		if (attach_ipif == NULL) {
6840 			ill_refrele(attach_ill);
6841 			goto icmp_err_ret;
6842 		}
6843 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6844 		    &sire, zoneid, 0,
6845 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6846 		ipif_refrele(attach_ipif);
6847 	}
6848 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6849 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6850 
6851 	/*
6852 	 * This loop is run only once in most cases.
6853 	 * We loop to resolve further routes only when the destination
6854 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6855 	 */
6856 	do {
6857 		/* Clear the previous iteration's values */
6858 		if (src_ipif != NULL) {
6859 			ipif_refrele(src_ipif);
6860 			src_ipif = NULL;
6861 		}
6862 		if (dst_ill != NULL) {
6863 			ill_refrele(dst_ill);
6864 			dst_ill = NULL;
6865 		}
6866 
6867 		multirt_resolve_next = B_FALSE;
6868 		/*
6869 		 * We check if packets have to be multirouted.
6870 		 * In this case, given the current <ire, sire> couple,
6871 		 * we look for the next suitable <ire, sire>.
6872 		 * This check is done in ire_multirt_lookup(),
6873 		 * which applies various criteria to find the next route
6874 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6875 		 * unchanged if it detects it has not been tried yet.
6876 		 */
6877 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6878 			ip3dbg(("ip_newroute: starting next_resolution "
6879 			    "with first_mp %p, tag %d\n",
6880 			    (void *)first_mp,
6881 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6882 
6883 			ASSERT(sire != NULL);
6884 			multirt_is_resolvable =
6885 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6886 
6887 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6888 			    "ire %p, sire %p\n",
6889 			    multirt_is_resolvable,
6890 			    (void *)ire, (void *)sire));
6891 
6892 			if (!multirt_is_resolvable) {
6893 				/*
6894 				 * No more multirt route to resolve; give up
6895 				 * (all routes resolved or no more
6896 				 * resolvable routes).
6897 				 */
6898 				if (ire != NULL) {
6899 					ire_refrele(ire);
6900 					ire = NULL;
6901 				}
6902 			} else {
6903 				ASSERT(sire != NULL);
6904 				ASSERT(ire != NULL);
6905 				/*
6906 				 * We simply use first_sire as a flag that
6907 				 * indicates if a resolvable multirt route
6908 				 * has already been found.
6909 				 * If it is not the case, we may have to send
6910 				 * an ICMP error to report that the
6911 				 * destination is unreachable.
6912 				 * We do not IRE_REFHOLD first_sire.
6913 				 */
6914 				if (first_sire == NULL) {
6915 					first_sire = sire;
6916 				}
6917 			}
6918 		}
6919 		if (ire == NULL) {
6920 			if (ip_debug > 3) {
6921 				/* ip2dbg */
6922 				pr_addr_dbg("ip_newroute: "
6923 				    "can't resolve %s\n", AF_INET, &dst);
6924 			}
6925 			ip3dbg(("ip_newroute: "
6926 			    "ire %p, sire %p, first_sire %p\n",
6927 			    (void *)ire, (void *)sire, (void *)first_sire));
6928 
6929 			if (sire != NULL) {
6930 				ire_refrele(sire);
6931 				sire = NULL;
6932 			}
6933 
6934 			if (first_sire != NULL) {
6935 				/*
6936 				 * At least one multirt route has been found
6937 				 * in the same call to ip_newroute();
6938 				 * there is no need to report an ICMP error.
6939 				 * first_sire was not IRE_REFHOLDed.
6940 				 */
6941 				MULTIRT_DEBUG_UNTAG(first_mp);
6942 				freemsg(first_mp);
6943 				return;
6944 			}
6945 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6946 			    RTA_DST);
6947 			if (attach_ill != NULL)
6948 				ill_refrele(attach_ill);
6949 			goto icmp_err_ret;
6950 		}
6951 
6952 		/*
6953 		 * When RTA_SRCIFP is used to add a route, then an interface
6954 		 * route is added in the source interface's routing table.
6955 		 * If the outgoing interface of this route is of type
6956 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6957 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6958 		 * first used for forwarding packet, ip_newroute() is called
6959 		 * to resolve the hardware address of the outgoing ipif.
6960 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6961 		 * source interface based table. We only come here if the
6962 		 * outgoing interface is a resolver interface and we don't
6963 		 * have the ire_dlureq_mp information yet.
6964 		 * If in_ill is not null that means it is called from
6965 		 * ip_rput.
6966 		 */
6967 
6968 		ASSERT(ire->ire_in_ill == NULL ||
6969 		    (ire->ire_type == IRE_IF_RESOLVER &&
6970 		    ire->ire_dlureq_mp == NULL));
6971 
6972 		/*
6973 		 * Verify that the returned IRE does not have either
6974 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6975 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6976 		 */
6977 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
6978 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
6979 			if (attach_ill != NULL)
6980 				ill_refrele(attach_ill);
6981 			goto icmp_err_ret;
6982 		}
6983 		/*
6984 		 * Increment the ire_ob_pkt_count field for ire if it is an
6985 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
6986 		 * increment the same for the parent IRE, sire, if it is some
6987 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
6988 		 * and HOST_REDIRECT).
6989 		 */
6990 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
6991 			UPDATE_OB_PKT_COUNT(ire);
6992 			ire->ire_last_used_time = lbolt;
6993 		}
6994 
6995 		if (sire != NULL) {
6996 			gw = sire->ire_gateway_addr;
6997 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
6998 			    IRE_INTERFACE)) == 0);
6999 			UPDATE_OB_PKT_COUNT(sire);
7000 			sire->ire_last_used_time = lbolt;
7001 		}
7002 		/*
7003 		 * We have a route to reach the destination.
7004 		 *
7005 		 * 1) If the interface is part of ill group, try to get a new
7006 		 *    ill taking load spreading into account.
7007 		 *
7008 		 * 2) After selecting the ill, get a source address that
7009 		 *    might create good inbound load spreading.
7010 		 *    ipif_select_source does this for us.
7011 		 *
7012 		 * If the application specified the ill (ifindex), we still
7013 		 * load spread. Only if the packets needs to go out
7014 		 * specifically on a given ill e.g. binding to
7015 		 * IPIF_NOFAILOVER address, then we don't try to use a
7016 		 * different ill for load spreading.
7017 		 */
7018 		if (attach_ill == NULL) {
7019 			/*
7020 			 * Don't perform outbound load spreading in the
7021 			 * case of an RTF_MULTIRT route, as we actually
7022 			 * typically want to replicate outgoing packets
7023 			 * through particular interfaces.
7024 			 */
7025 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7026 				dst_ill = ire->ire_ipif->ipif_ill;
7027 				/* for uniformity */
7028 				ill_refhold(dst_ill);
7029 			} else {
7030 				/*
7031 				 * If we are here trying to create an IRE_CACHE
7032 				 * for an offlink destination and have the
7033 				 * IRE_CACHE for the next hop and the latter is
7034 				 * using virtual IP source address selection i.e
7035 				 * it's ire->ire_ipif is pointing to a virtual
7036 				 * network interface (vni) then
7037 				 * ip_newroute_get_dst_ll() will return the vni
7038 				 * interface as the dst_ill. Since the vni is
7039 				 * virtual i.e not associated with any physical
7040 				 * interface, it cannot be the dst_ill, hence
7041 				 * in such a case call ip_newroute_get_dst_ll()
7042 				 * with the stq_ill instead of the ire_ipif ILL.
7043 				 * The function returns a refheld ill.
7044 				 */
7045 				if ((ire->ire_type == IRE_CACHE) &&
7046 				    IS_VNI(ire->ire_ipif->ipif_ill))
7047 					dst_ill = ip_newroute_get_dst_ill(
7048 						ire->ire_stq->q_ptr);
7049 				else
7050 					dst_ill = ip_newroute_get_dst_ill(
7051 						ire->ire_ipif->ipif_ill);
7052 			}
7053 			if (dst_ill == NULL) {
7054 				if (ip_debug > 2) {
7055 					pr_addr_dbg("ip_newroute: "
7056 					    "no dst ill for dst"
7057 					    " %s\n", AF_INET, &dst);
7058 				}
7059 				goto icmp_err_ret;
7060 			}
7061 		} else {
7062 			dst_ill = ire->ire_ipif->ipif_ill;
7063 			/* for uniformity */
7064 			ill_refhold(dst_ill);
7065 			/*
7066 			 * We should have found a route matching ill as we
7067 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7068 			 * Rather than asserting, when there is a mismatch,
7069 			 * we just drop the packet.
7070 			 */
7071 			if (dst_ill != attach_ill) {
7072 				ip0dbg(("ip_newroute: Packet dropped as "
7073 				    "IPIF_NOFAILOVER ill is %s, "
7074 				    "ire->ire_ipif->ipif_ill is %s\n",
7075 				    attach_ill->ill_name,
7076 				    dst_ill->ill_name));
7077 				ill_refrele(attach_ill);
7078 				goto icmp_err_ret;
7079 			}
7080 		}
7081 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7082 		if (attach_ill != NULL) {
7083 			ill_refrele(attach_ill);
7084 			attach_ill = NULL;
7085 			do_attach_ill = B_TRUE;
7086 		}
7087 		ASSERT(dst_ill != NULL);
7088 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7089 
7090 		/*
7091 		 * Pick the best source address from dst_ill.
7092 		 *
7093 		 * 1) If it is part of a multipathing group, we would
7094 		 *    like to spread the inbound packets across different
7095 		 *    interfaces. ipif_select_source picks a random source
7096 		 *    across the different ills in the group.
7097 		 *
7098 		 * 2) If it is not part of a multipathing group, we try
7099 		 *    to pick the source address from the destination
7100 		 *    route. Clustering assumes that when we have multiple
7101 		 *    prefixes hosted on an interface, the prefix of the
7102 		 *    source address matches the prefix of the destination
7103 		 *    route. We do this only if the address is not
7104 		 *    DEPRECATED.
7105 		 *
7106 		 * 3) If the conn is in a different zone than the ire, we
7107 		 *    need to pick a source address from the right zone.
7108 		 *
7109 		 * NOTE : If we hit case (1) above, the prefix of the source
7110 		 *	  address picked may not match the prefix of the
7111 		 *	  destination routes prefix as ipif_select_source
7112 		 *	  does not look at "dst" while picking a source
7113 		 *	  address.
7114 		 *	  If we want the same behavior as (2), we will need
7115 		 *	  to change the behavior of ipif_select_source.
7116 		 */
7117 		ASSERT(src_ipif == NULL);
7118 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7119 			/*
7120 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7121 			 * Check that the ipif matching the requested source
7122 			 * address still exists.
7123 			 */
7124 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7125 			    zoneid, NULL, NULL, NULL, NULL);
7126 		}
7127 		if (src_ipif == NULL) {
7128 			ire_marks |= IRE_MARK_USESRC_CHECK;
7129 			if ((dst_ill->ill_group != NULL) ||
7130 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7131 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
7132 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7133 				src_ipif = ipif_select_source(dst_ill, dst,
7134 				    zoneid);
7135 				if (src_ipif == NULL) {
7136 					if (ip_debug > 2) {
7137 						pr_addr_dbg("ip_newroute: "
7138 						    "no src for dst %s ",
7139 						    AF_INET, &dst);
7140 						printf("through interface %s\n",
7141 						    dst_ill->ill_name);
7142 					}
7143 					goto icmp_err_ret;
7144 				}
7145 			} else {
7146 				src_ipif = ire->ire_ipif;
7147 				ASSERT(src_ipif != NULL);
7148 				/* hold src_ipif for uniformity */
7149 				ipif_refhold(src_ipif);
7150 			}
7151 		}
7152 
7153 		/*
7154 		 * Assign a source address while we have the conn.
7155 		 * We can't have ip_wput_ire pick a source address when the
7156 		 * packet returns from arp since we need to look at
7157 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7158 		 * going through arp.
7159 		 *
7160 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7161 		 *	  it uses ip6i to store this information.
7162 		 */
7163 		if (ipha->ipha_src == INADDR_ANY &&
7164 		    (connp == NULL || !connp->conn_unspec_src)) {
7165 			ipha->ipha_src = src_ipif->ipif_src_addr;
7166 		}
7167 		if (ip_debug > 3) {
7168 			/* ip2dbg */
7169 			pr_addr_dbg("ip_newroute: first hop %s\n",
7170 			    AF_INET, &gw);
7171 		}
7172 		ip2dbg(("\tire type %s (%d)\n",
7173 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7174 
7175 		/*
7176 		 * The TTL of multirouted packets is bounded by the
7177 		 * ip_multirt_ttl ndd variable.
7178 		 */
7179 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7180 			/* Force TTL of multirouted packets */
7181 			if ((ip_multirt_ttl > 0) &&
7182 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7183 				ip2dbg(("ip_newroute: forcing multirt TTL "
7184 				    "to %d (was %d), dst 0x%08x\n",
7185 				    ip_multirt_ttl, ipha->ipha_ttl,
7186 				    ntohl(sire->ire_addr)));
7187 				ipha->ipha_ttl = ip_multirt_ttl;
7188 			}
7189 		}
7190 		/*
7191 		 * At this point in ip_newroute(), ire is either the
7192 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7193 		 * destination or an IRE_INTERFACE type that should be used
7194 		 * to resolve an on-subnet destination or an on-subnet
7195 		 * next-hop gateway.
7196 		 *
7197 		 * In the IRE_CACHE case, we have the following :
7198 		 *
7199 		 * 1) src_ipif - used for getting a source address.
7200 		 *
7201 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7202 		 *    means packets using this IRE_CACHE will go out on
7203 		 *    dst_ill.
7204 		 *
7205 		 * 3) The IRE sire will point to the prefix that is the
7206 		 *    longest  matching route for the destination. These
7207 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7208 		 *    and IRE_HOST_REDIRECT.
7209 		 *
7210 		 *    The newly created IRE_CACHE entry for the off-subnet
7211 		 *    destination is tied to both the prefix route and the
7212 		 *    interface route used to resolve the next-hop gateway
7213 		 *    via the ire_phandle and ire_ihandle fields,
7214 		 *    respectively.
7215 		 *
7216 		 * In the IRE_INTERFACE case, we have the following :
7217 		 *
7218 		 * 1) src_ipif - used for getting a source address.
7219 		 *
7220 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7221 		 *    means packets using the IRE_CACHE that we will build
7222 		 *    here will go out on dst_ill.
7223 		 *
7224 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7225 		 *    to be created will only be tied to the IRE_INTERFACE
7226 		 *    that was derived from the ire_ihandle field.
7227 		 *
7228 		 *    If sire is non-NULL, it means the destination is
7229 		 *    off-link and we will first create the IRE_CACHE for the
7230 		 *    gateway. Next time through ip_newroute, we will create
7231 		 *    the IRE_CACHE for the final destination as described
7232 		 *    above.
7233 		 *
7234 		 * In both cases, after the current resolution has been
7235 		 * completed (or possibly initialised, in the IRE_INTERFACE
7236 		 * case), the loop may be re-entered to attempt the resolution
7237 		 * of another RTF_MULTIRT route.
7238 		 *
7239 		 * When an IRE_CACHE entry for the off-subnet destination is
7240 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7241 		 * for further processing in emission loops.
7242 		 */
7243 		save_ire = ire;
7244 		switch (ire->ire_type) {
7245 		case IRE_CACHE: {
7246 			ire_t	*ipif_ire;
7247 			mblk_t	*ire_fp_mp;
7248 
7249 			if (gw == 0)
7250 				gw = ire->ire_gateway_addr;
7251 			/*
7252 			 * We need 3 ire's to create a new cache ire for an
7253 			 * off-link destination from the cache ire of the
7254 			 * gateway.
7255 			 *
7256 			 *	1. The prefix ire 'sire' (Note that this does
7257 			 *	   not apply to the conn_nexthop_set case)
7258 			 *	2. The cache ire of the gateway 'ire'
7259 			 *	3. The interface ire 'ipif_ire'
7260 			 *
7261 			 * We have (1) and (2). We lookup (3) below.
7262 			 *
7263 			 * If there is no interface route to the gateway,
7264 			 * it is a race condition, where we found the cache
7265 			 * but the interface route has been deleted.
7266 			 */
7267 			if (ip_nexthop) {
7268 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7269 			} else {
7270 				ipif_ire =
7271 				    ire_ihandle_lookup_offlink(ire, sire);
7272 			}
7273 			if (ipif_ire == NULL) {
7274 				ip1dbg(("ip_newroute: "
7275 				    "ire_ihandle_lookup_offlink failed\n"));
7276 				goto icmp_err_ret;
7277 			}
7278 			/*
7279 			 * XXX We are using the same dlureq_mp
7280 			 * (DL_UNITDATA_REQ) though the save_ire is not
7281 			 * pointing at the same ill.
7282 			 * This is incorrect. We need to send it up to the
7283 			 * resolver to get the right dlureq_mp. For ethernets
7284 			 * this may be okay (ill_type == DL_ETHER).
7285 			 */
7286 			dlureq_mp = save_ire->ire_dlureq_mp;
7287 			ire_fp_mp = NULL;
7288 			/*
7289 			 * save_ire's ire_fp_mp can't change since it is
7290 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7291 			 * LOCK_IRE_FP_MP does not do any useful work in
7292 			 * the case of IRE_CACHE. So we don't use it below.
7293 			 */
7294 			if (save_ire->ire_stq == dst_ill->ill_wq)
7295 				ire_fp_mp = save_ire->ire_fp_mp;
7296 
7297 			ire = ire_create(
7298 			    (uchar_t *)&dst,		/* dest address */
7299 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7300 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7301 			    (uchar_t *)&gw,		/* gateway address */
7302 			    NULL,
7303 			    &save_ire->ire_max_frag,
7304 			    ire_fp_mp,			/* Fast Path header */
7305 			    dst_ill->ill_rq,		/* recv-from queue */
7306 			    dst_ill->ill_wq,		/* send-to queue */
7307 			    IRE_CACHE,			/* IRE type */
7308 			    save_ire->ire_dlureq_mp,
7309 			    src_ipif,
7310 			    in_ill,			/* incoming ill */
7311 			    (sire != NULL) ?
7312 				sire->ire_mask : 0, 	/* Parent mask */
7313 			    (sire != NULL) ?
7314 				sire->ire_phandle : 0,  /* Parent handle */
7315 			    ipif_ire->ire_ihandle,	/* Interface handle */
7316 			    (sire != NULL) ? (sire->ire_flags &
7317 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7318 			    (sire != NULL) ?
7319 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo));
7320 
7321 			if (ire == NULL) {
7322 				ire_refrele(ipif_ire);
7323 				ire_refrele(save_ire);
7324 				break;
7325 			}
7326 			ire->ire_marks |= ire_marks;
7327 
7328 			/*
7329 			 * Prevent sire and ipif_ire from getting deleted.
7330 			 * The newly created ire is tied to both of them via
7331 			 * the phandle and ihandle respectively.
7332 			 */
7333 			if (sire != NULL) {
7334 				IRB_REFHOLD(sire->ire_bucket);
7335 				/* Has it been removed already ? */
7336 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7337 					IRB_REFRELE(sire->ire_bucket);
7338 					ire_refrele(ipif_ire);
7339 					ire_refrele(save_ire);
7340 					break;
7341 				}
7342 			}
7343 
7344 			IRB_REFHOLD(ipif_ire->ire_bucket);
7345 			/* Has it been removed already ? */
7346 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7347 				IRB_REFRELE(ipif_ire->ire_bucket);
7348 				if (sire != NULL)
7349 					IRB_REFRELE(sire->ire_bucket);
7350 				ire_refrele(ipif_ire);
7351 				ire_refrele(save_ire);
7352 				break;
7353 			}
7354 
7355 			xmit_mp = first_mp;
7356 			/*
7357 			 * In the case of multirouting, a copy
7358 			 * of the packet is done before its sending.
7359 			 * The copy is used to attempt another
7360 			 * route resolution, in a next loop.
7361 			 */
7362 			if (ire->ire_flags & RTF_MULTIRT) {
7363 				copy_mp = copymsg(first_mp);
7364 				if (copy_mp != NULL) {
7365 					xmit_mp = copy_mp;
7366 					MULTIRT_DEBUG_TAG(first_mp);
7367 				}
7368 			}
7369 			ire_add_then_send(q, ire, xmit_mp);
7370 			ire_refrele(save_ire);
7371 
7372 			/* Assert that sire is not deleted yet. */
7373 			if (sire != NULL) {
7374 				ASSERT(sire->ire_ptpn != NULL);
7375 				IRB_REFRELE(sire->ire_bucket);
7376 			}
7377 
7378 			/* Assert that ipif_ire is not deleted yet. */
7379 			ASSERT(ipif_ire->ire_ptpn != NULL);
7380 			IRB_REFRELE(ipif_ire->ire_bucket);
7381 			ire_refrele(ipif_ire);
7382 
7383 			/*
7384 			 * If copy_mp is not NULL, multirouting was
7385 			 * requested. We loop to initiate a next
7386 			 * route resolution attempt, starting from sire.
7387 			 */
7388 			if (copy_mp != NULL) {
7389 				/*
7390 				 * Search for the next unresolved
7391 				 * multirt route.
7392 				 */
7393 				copy_mp = NULL;
7394 				ipif_ire = NULL;
7395 				ire = NULL;
7396 				multirt_resolve_next = B_TRUE;
7397 				continue;
7398 			}
7399 			if (sire != NULL)
7400 				ire_refrele(sire);
7401 			ipif_refrele(src_ipif);
7402 			ill_refrele(dst_ill);
7403 			return;
7404 		}
7405 		case IRE_IF_NORESOLVER: {
7406 			/*
7407 			 * We have what we need to build an IRE_CACHE.
7408 			 *
7409 			 * Create a new dlureq_mp with the IP gateway address
7410 			 * in destination address in the DLPI hdr if the
7411 			 * physical length is exactly 4 bytes.
7412 			 */
7413 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7414 				uchar_t *addr;
7415 
7416 				if (gw)
7417 					addr = (uchar_t *)&gw;
7418 				else
7419 					addr = (uchar_t *)&dst;
7420 
7421 				dlureq_mp = ill_dlur_gen(addr,
7422 				    dst_ill->ill_phys_addr_length,
7423 				    dst_ill->ill_sap,
7424 				    dst_ill->ill_sap_length);
7425 			} else {
7426 				dlureq_mp = ire->ire_dlureq_mp;
7427 			}
7428 
7429 			if (dlureq_mp == NULL) {
7430 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7431 				break;
7432 			}
7433 
7434 			ire = ire_create(
7435 			    (uchar_t *)&dst,		/* dest address */
7436 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7437 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7438 			    (uchar_t *)&gw,		/* gateway address */
7439 			    NULL,
7440 			    &save_ire->ire_max_frag,
7441 			    NULL,			/* Fast Path header */
7442 			    dst_ill->ill_rq,		/* recv-from queue */
7443 			    dst_ill->ill_wq,		/* send-to queue */
7444 			    IRE_CACHE,
7445 			    dlureq_mp,
7446 			    src_ipif,
7447 			    in_ill,			/* Incoming ill */
7448 			    save_ire->ire_mask,		/* Parent mask */
7449 			    (sire != NULL) ?		/* Parent handle */
7450 				sire->ire_phandle : 0,
7451 			    save_ire->ire_ihandle,	/* Interface handle */
7452 			    (sire != NULL) ? sire->ire_flags &
7453 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7454 			    &(save_ire->ire_uinfo));
7455 
7456 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7457 				freeb(dlureq_mp);
7458 
7459 			if (ire == NULL) {
7460 				ire_refrele(save_ire);
7461 				break;
7462 			}
7463 
7464 			ire->ire_marks |= ire_marks;
7465 
7466 			/* Prevent save_ire from getting deleted */
7467 			IRB_REFHOLD(save_ire->ire_bucket);
7468 			/* Has it been removed already ? */
7469 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7470 				IRB_REFRELE(save_ire->ire_bucket);
7471 				ire_refrele(save_ire);
7472 				break;
7473 			}
7474 
7475 			/*
7476 			 * In the case of multirouting, a copy
7477 			 * of the packet is made before it is sent.
7478 			 * The copy is used in the next
7479 			 * loop to attempt another resolution.
7480 			 */
7481 			xmit_mp = first_mp;
7482 			if ((sire != NULL) &&
7483 			    (sire->ire_flags & RTF_MULTIRT)) {
7484 				copy_mp = copymsg(first_mp);
7485 				if (copy_mp != NULL) {
7486 					xmit_mp = copy_mp;
7487 					MULTIRT_DEBUG_TAG(first_mp);
7488 				}
7489 			}
7490 			ire_add_then_send(q, ire, xmit_mp);
7491 
7492 			/* Assert that it is not deleted yet. */
7493 			ASSERT(save_ire->ire_ptpn != NULL);
7494 			IRB_REFRELE(save_ire->ire_bucket);
7495 			ire_refrele(save_ire);
7496 
7497 			if (copy_mp != NULL) {
7498 				/*
7499 				 * If we found a (no)resolver, we ignore any
7500 				 * trailing top priority IRE_CACHE in further
7501 				 * loops. This ensures that we do not omit any
7502 				 * (no)resolver.
7503 				 * This IRE_CACHE, if any, will be processed
7504 				 * by another thread entering ip_newroute().
7505 				 * IRE_CACHE entries, if any, will be processed
7506 				 * by another thread entering ip_newroute(),
7507 				 * (upon resolver response, for instance).
7508 				 * This aims to force parallel multirt
7509 				 * resolutions as soon as a packet must be sent.
7510 				 * In the best case, after the tx of only one
7511 				 * packet, all reachable routes are resolved.
7512 				 * Otherwise, the resolution of all RTF_MULTIRT
7513 				 * routes would require several emissions.
7514 				 */
7515 				multirt_flags &= ~MULTIRT_CACHEGW;
7516 
7517 				/*
7518 				 * Search for the next unresolved multirt
7519 				 * route.
7520 				 */
7521 				copy_mp = NULL;
7522 				save_ire = NULL;
7523 				ire = NULL;
7524 				multirt_resolve_next = B_TRUE;
7525 				continue;
7526 			}
7527 
7528 			/*
7529 			 * Don't need sire anymore
7530 			 */
7531 			if (sire != NULL)
7532 				ire_refrele(sire);
7533 
7534 			ipif_refrele(src_ipif);
7535 			ill_refrele(dst_ill);
7536 			return;
7537 		}
7538 		case IRE_IF_RESOLVER:
7539 			/*
7540 			 * We can't build an IRE_CACHE yet, but at least we
7541 			 * found a resolver that can help.
7542 			 */
7543 			res_mp = dst_ill->ill_resolver_mp;
7544 			if (!OK_RESOLVER_MP(res_mp))
7545 				break;
7546 			/*
7547 			 * To be at this point in the code with a non-zero gw
7548 			 * means that dst is reachable through a gateway that
7549 			 * we have never resolved.  By changing dst to the gw
7550 			 * addr we resolve the gateway first.
7551 			 * When ire_add_then_send() tries to put the IP dg
7552 			 * to dst, it will reenter ip_newroute() at which
7553 			 * time we will find the IRE_CACHE for the gw and
7554 			 * create another IRE_CACHE in case IRE_CACHE above.
7555 			 */
7556 			if (gw != INADDR_ANY) {
7557 				/*
7558 				 * The source ipif that was determined above was
7559 				 * relative to the destination address, not the
7560 				 * gateway's. If src_ipif was not taken out of
7561 				 * the IRE_IF_RESOLVER entry, we'll need to call
7562 				 * ipif_select_source() again.
7563 				 */
7564 				if (src_ipif != ire->ire_ipif) {
7565 					ipif_refrele(src_ipif);
7566 					src_ipif = ipif_select_source(dst_ill,
7567 					    gw, zoneid);
7568 					if (src_ipif == NULL) {
7569 						if (ip_debug > 2) {
7570 							pr_addr_dbg(
7571 							    "ip_newroute: no "
7572 							    "src for gw %s ",
7573 							    AF_INET, &gw);
7574 							printf("through "
7575 							    "interface %s\n",
7576 							    dst_ill->ill_name);
7577 						}
7578 						goto icmp_err_ret;
7579 					}
7580 				}
7581 				save_dst = dst;
7582 				dst = gw;
7583 				gw = INADDR_ANY;
7584 			}
7585 			/*
7586 			 * We obtain a partial IRE_CACHE which we will pass
7587 			 * along with the resolver query.  When the response
7588 			 * comes back it will be there ready for us to add.
7589 			 * The ire_max_frag is atomically set under the
7590 			 * irebucket lock in ire_add_v[46].
7591 			 */
7592 			ire = ire_create_mp(
7593 			    (uchar_t *)&dst,		/* dest address */
7594 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7595 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7596 			    (uchar_t *)&gw,		/* gateway address */
7597 			    NULL,			/* no in_src_addr */
7598 			    NULL,			/* ire_max_frag */
7599 			    NULL,			/* Fast Path header */
7600 			    dst_ill->ill_rq,		/* recv-from queue */
7601 			    dst_ill->ill_wq,		/* send-to queue */
7602 			    IRE_CACHE,
7603 			    res_mp,
7604 			    src_ipif,			/* Interface ipif */
7605 			    in_ill,			/* Incoming ILL */
7606 			    save_ire->ire_mask,		/* Parent mask */
7607 			    0,
7608 			    save_ire->ire_ihandle,	/* Interface handle */
7609 			    0,				/* flags if any */
7610 			    &(save_ire->ire_uinfo));
7611 
7612 			if (ire == NULL) {
7613 				ire_refrele(save_ire);
7614 				break;
7615 			}
7616 
7617 			if ((sire != NULL) &&
7618 			    (sire->ire_flags & RTF_MULTIRT)) {
7619 				copy_mp = copymsg(first_mp);
7620 				if (copy_mp != NULL)
7621 					MULTIRT_DEBUG_TAG(copy_mp);
7622 			}
7623 
7624 			ire->ire_marks |= ire_marks;
7625 
7626 			/*
7627 			 * Construct message chain for the resolver
7628 			 * of the form:
7629 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7630 			 * Packet could contain a IPSEC_OUT mp.
7631 			 *
7632 			 * NOTE : ire will be added later when the response
7633 			 * comes back from ARP. If the response does not
7634 			 * come back, ARP frees the packet. For this reason,
7635 			 * we can't REFHOLD the bucket of save_ire to prevent
7636 			 * deletions. We may not be able to REFRELE the bucket
7637 			 * if the response never comes back. Thus, before
7638 			 * adding the ire, ire_add_v4 will make sure that the
7639 			 * interface route does not get deleted. This is the
7640 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7641 			 * where we can always prevent deletions because of
7642 			 * the synchronous nature of adding IRES i.e
7643 			 * ire_add_then_send is called after creating the IRE.
7644 			 */
7645 			ASSERT(ire->ire_mp != NULL);
7646 			ire->ire_mp->b_cont = first_mp;
7647 			/* Have saved_mp handy, for cleanup if canput fails */
7648 			saved_mp = mp;
7649 			mp = ire->ire_dlureq_mp;
7650 			ASSERT(mp != NULL);
7651 			ire->ire_dlureq_mp = NULL;
7652 			linkb(mp, ire->ire_mp);
7653 
7654 
7655 			/*
7656 			 * Fill in the source and dest addrs for the resolver.
7657 			 * NOTE: this depends on memory layouts imposed by
7658 			 * ill_init().
7659 			 */
7660 			areq = (areq_t *)mp->b_rptr;
7661 			addrp = (ipaddr_t *)((char *)areq +
7662 			    areq->areq_sender_addr_offset);
7663 			if (do_attach_ill) {
7664 				/*
7665 				 * This is bind to no failover case.
7666 				 * arp packet also must go out on attach_ill.
7667 				 */
7668 				ASSERT(ipha->ipha_src != NULL);
7669 				*addrp = ipha->ipha_src;
7670 			} else {
7671 				*addrp = save_ire->ire_src_addr;
7672 			}
7673 
7674 			ire_refrele(save_ire);
7675 			addrp = (ipaddr_t *)((char *)areq +
7676 			    areq->areq_target_addr_offset);
7677 			*addrp = dst;
7678 			/* Up to the resolver. */
7679 			if (canputnext(dst_ill->ill_rq)) {
7680 				putnext(dst_ill->ill_rq, mp);
7681 				ire = NULL;
7682 				if (copy_mp != NULL) {
7683 					/*
7684 					 * If we found a resolver, we ignore
7685 					 * any trailing top priority IRE_CACHE
7686 					 * in the further loops. This ensures
7687 					 * that we do not omit any resolver.
7688 					 * IRE_CACHE entries, if any, will be
7689 					 * processed next time we enter
7690 					 * ip_newroute().
7691 					 */
7692 					multirt_flags &= ~MULTIRT_CACHEGW;
7693 					/*
7694 					 * Search for the next unresolved
7695 					 * multirt route.
7696 					 */
7697 					first_mp = copy_mp;
7698 					copy_mp = NULL;
7699 					/* Prepare the next resolution loop. */
7700 					mp = first_mp;
7701 					EXTRACT_PKT_MP(mp, first_mp,
7702 					    mctl_present);
7703 					if (mctl_present)
7704 						io = (ipsec_out_t *)
7705 						    first_mp->b_rptr;
7706 					ipha = (ipha_t *)mp->b_rptr;
7707 
7708 					ASSERT(sire != NULL);
7709 
7710 					dst = save_dst;
7711 					multirt_resolve_next = B_TRUE;
7712 					continue;
7713 				}
7714 
7715 				if (sire != NULL)
7716 					ire_refrele(sire);
7717 
7718 				/*
7719 				 * The response will come back in ip_wput
7720 				 * with db_type IRE_DB_TYPE.
7721 				 */
7722 				ipif_refrele(src_ipif);
7723 				ill_refrele(dst_ill);
7724 				return;
7725 			} else {
7726 				/* Prepare for cleanup */
7727 				ire->ire_dlureq_mp = mp;
7728 				mp->b_cont = NULL;
7729 				ire_delete(ire);
7730 				mp = saved_mp;
7731 				ire = NULL;
7732 				if (copy_mp != NULL) {
7733 					MULTIRT_DEBUG_UNTAG(copy_mp);
7734 					freemsg(copy_mp);
7735 					copy_mp = NULL;
7736 				}
7737 				break;
7738 			}
7739 		default:
7740 			break;
7741 		}
7742 	} while (multirt_resolve_next);
7743 
7744 	ip1dbg(("ip_newroute: dropped\n"));
7745 	/* Did this packet originate externally? */
7746 	if (mp->b_prev) {
7747 		mp->b_next = NULL;
7748 		mp->b_prev = NULL;
7749 		BUMP_MIB(&ip_mib, ipInDiscards);
7750 	} else {
7751 		BUMP_MIB(&ip_mib, ipOutDiscards);
7752 	}
7753 	ASSERT(copy_mp == NULL);
7754 	MULTIRT_DEBUG_UNTAG(first_mp);
7755 	freemsg(first_mp);
7756 	if (ire != NULL)
7757 		ire_refrele(ire);
7758 	if (sire != NULL)
7759 		ire_refrele(sire);
7760 	if (src_ipif != NULL)
7761 		ipif_refrele(src_ipif);
7762 	if (dst_ill != NULL)
7763 		ill_refrele(dst_ill);
7764 	return;
7765 
7766 icmp_err_ret:
7767 	ip1dbg(("ip_newroute: no route\n"));
7768 	if (src_ipif != NULL)
7769 		ipif_refrele(src_ipif);
7770 	if (dst_ill != NULL)
7771 		ill_refrele(dst_ill);
7772 	if (sire != NULL)
7773 		ire_refrele(sire);
7774 	/* Did this packet originate externally? */
7775 	if (mp->b_prev) {
7776 		mp->b_next = NULL;
7777 		mp->b_prev = NULL;
7778 		/* XXX ipInNoRoutes */
7779 		q = WR(q);
7780 	} else {
7781 		/*
7782 		 * Since ip_wput() isn't close to finished, we fill
7783 		 * in enough of the header for credible error reporting.
7784 		 */
7785 		if (ip_hdr_complete(ipha, zoneid)) {
7786 			/* Failed */
7787 			MULTIRT_DEBUG_UNTAG(first_mp);
7788 			freemsg(first_mp);
7789 			if (ire != NULL)
7790 				ire_refrele(ire);
7791 			return;
7792 		}
7793 	}
7794 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7795 
7796 	/*
7797 	 * At this point we will have ire only if RTF_BLACKHOLE
7798 	 * or RTF_REJECT flags are set on the IRE. It will not
7799 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7800 	 */
7801 	if (ire != NULL) {
7802 		if (ire->ire_flags & RTF_BLACKHOLE) {
7803 			ire_refrele(ire);
7804 			MULTIRT_DEBUG_UNTAG(first_mp);
7805 			freemsg(first_mp);
7806 			return;
7807 		}
7808 		ire_refrele(ire);
7809 	}
7810 	if (ip_source_routed(ipha)) {
7811 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7812 		return;
7813 	}
7814 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7815 }
7816 
7817 /*
7818  * IPv4 -
7819  * ip_newroute_ipif is called by ip_wput_multicast and
7820  * ip_rput_forward_multicast whenever we need to send
7821  * out a packet to a destination address for which we do not have specific
7822  * routing information. It is used when the packet will be sent out
7823  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7824  * socket option is set or icmp error message wants to go out on a particular
7825  * interface for a unicast packet.
7826  *
7827  * In most cases, the destination address is resolved thanks to the ipif
7828  * intrinsic resolver. However, there are some cases where the call to
7829  * ip_newroute_ipif must take into account the potential presence of
7830  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7831  * that uses the interface. This is specified through flags,
7832  * which can be a combination of:
7833  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7834  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7835  *   and flags. Additionally, the packet source address has to be set to
7836  *   the specified address. The caller is thus expected to set this flag
7837  *   if the packet has no specific source address yet.
7838  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7839  *   flag, the resulting ire will inherit the flag. All unresolved routes
7840  *   to the destination must be explored in the same call to
7841  *   ip_newroute_ipif().
7842  */
7843 static void
7844 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7845     conn_t *connp, uint32_t flags)
7846 {
7847 	areq_t	*areq;
7848 	ire_t	*ire = NULL;
7849 	mblk_t	*res_mp;
7850 	ipaddr_t *addrp;
7851 	mblk_t *first_mp;
7852 	ire_t	*save_ire = NULL;
7853 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7854 	ipif_t	*src_ipif = NULL;
7855 	ushort_t ire_marks = 0;
7856 	ill_t	*dst_ill = NULL;
7857 	boolean_t mctl_present;
7858 	ipsec_out_t *io;
7859 	ipha_t *ipha;
7860 	int	ihandle = 0;
7861 	mblk_t	*saved_mp;
7862 	ire_t   *fire = NULL;
7863 	mblk_t  *copy_mp = NULL;
7864 	boolean_t multirt_resolve_next;
7865 	ipaddr_t ipha_dst;
7866 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7867 
7868 	/*
7869 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7870 	 * here for uniformity
7871 	 */
7872 	ipif_refhold(ipif);
7873 
7874 	/*
7875 	 * This loop is run only once in most cases.
7876 	 * We loop to resolve further routes only when the destination
7877 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7878 	 */
7879 	do {
7880 		if (dst_ill != NULL) {
7881 			ill_refrele(dst_ill);
7882 			dst_ill = NULL;
7883 		}
7884 		if (src_ipif != NULL) {
7885 			ipif_refrele(src_ipif);
7886 			src_ipif = NULL;
7887 		}
7888 		multirt_resolve_next = B_FALSE;
7889 
7890 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7891 		    ipif->ipif_ill->ill_name));
7892 
7893 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7894 		if (mctl_present)
7895 			io = (ipsec_out_t *)first_mp->b_rptr;
7896 
7897 		ipha = (ipha_t *)mp->b_rptr;
7898 
7899 		/*
7900 		 * Save the packet destination address, we may need it after
7901 		 * the packet has been consumed.
7902 		 */
7903 		ipha_dst = ipha->ipha_dst;
7904 
7905 		/*
7906 		 * If the interface is a pt-pt interface we look for an
7907 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7908 		 * local_address and the pt-pt destination address. Otherwise
7909 		 * we just match the local address.
7910 		 * NOTE: dst could be different than ipha->ipha_dst in case
7911 		 * of sending igmp multicast packets over a point-to-point
7912 		 * connection.
7913 		 * Thus we must be careful enough to check ipha_dst to be a
7914 		 * multicast address, otherwise it will take xmit_if path for
7915 		 * multicast packets resulting into kernel stack overflow by
7916 		 * repeated calls to ip_newroute_ipif from ire_send().
7917 		 */
7918 		if (CLASSD(ipha_dst) &&
7919 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7920 			goto err_ret;
7921 		}
7922 
7923 		/*
7924 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7925 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7926 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7927 		 * propagate its flags to the new ire.
7928 		 */
7929 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7930 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7931 			ip2dbg(("ip_newroute_ipif: "
7932 			    "ipif_lookup_multi_ire("
7933 			    "ipif %p, dst %08x) = fire %p\n",
7934 			    (void *)ipif, ntohl(dst), (void *)fire));
7935 		}
7936 
7937 		if (mctl_present && io->ipsec_out_attach_if) {
7938 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7939 			    io->ipsec_out_ill_index, B_FALSE);
7940 
7941 			/* Failure case frees things for us. */
7942 			if (attach_ill == NULL) {
7943 				ipif_refrele(ipif);
7944 				if (fire != NULL)
7945 					ire_refrele(fire);
7946 				return;
7947 			}
7948 
7949 			/*
7950 			 * Check if we need an ire that will not be
7951 			 * looked up by anybody else i.e. HIDDEN.
7952 			 */
7953 			if (ill_is_probeonly(attach_ill)) {
7954 				ire_marks = IRE_MARK_HIDDEN;
7955 			}
7956 			/*
7957 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
7958 			 * case.
7959 			 */
7960 			dst_ill = ipif->ipif_ill;
7961 			/* attach_ill has been refheld by ip_grab_attach_ill */
7962 			ASSERT(dst_ill == attach_ill);
7963 		} else {
7964 			/*
7965 			 * If this is set by IP_XMIT_IF, then make sure that
7966 			 * ipif is pointing to the same ill as the IP_XMIT_IF
7967 			 * specified ill.
7968 			 */
7969 			ASSERT((connp == NULL) ||
7970 			    (connp->conn_xmit_if_ill == NULL) ||
7971 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
7972 			/*
7973 			 * If the interface belongs to an interface group,
7974 			 * make sure the next possible interface in the group
7975 			 * is used.  This encourages load spreading among
7976 			 * peers in an interface group.
7977 			 * Note: load spreading is disabled for RTF_MULTIRT
7978 			 * routes.
7979 			 */
7980 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7981 			    (fire->ire_flags & RTF_MULTIRT)) {
7982 				/*
7983 				 * Don't perform outbound load spreading
7984 				 * in the case of an RTF_MULTIRT issued route,
7985 				 * we actually typically want to replicate
7986 				 * outgoing packets through particular
7987 				 * interfaces.
7988 				 */
7989 				dst_ill = ipif->ipif_ill;
7990 				ill_refhold(dst_ill);
7991 			} else {
7992 				dst_ill = ip_newroute_get_dst_ill(
7993 				    ipif->ipif_ill);
7994 			}
7995 			if (dst_ill == NULL) {
7996 				if (ip_debug > 2) {
7997 					pr_addr_dbg("ip_newroute_ipif: "
7998 					    "no dst ill for dst %s\n",
7999 					    AF_INET, &dst);
8000 				}
8001 				goto err_ret;
8002 			}
8003 		}
8004 
8005 		/*
8006 		 * Pick a source address preferring non-deprecated ones.
8007 		 * Unlike ip_newroute, we don't do any source address
8008 		 * selection here since for multicast it really does not help
8009 		 * in inbound load spreading as in the unicast case.
8010 		 */
8011 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8012 		    (fire->ire_flags & RTF_SETSRC)) {
8013 			/*
8014 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8015 			 * on that interface. This ire has RTF_SETSRC flag, so
8016 			 * the source address of the packet must be changed.
8017 			 * Check that the ipif matching the requested source
8018 			 * address still exists.
8019 			 */
8020 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8021 			    zoneid, NULL, NULL, NULL, NULL);
8022 		}
8023 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8024 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
8025 		    (src_ipif == NULL)) {
8026 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8027 			if (src_ipif == NULL) {
8028 				if (ip_debug > 2) {
8029 					/* ip1dbg */
8030 					pr_addr_dbg("ip_newroute_ipif: "
8031 					    "no src for dst %s",
8032 					    AF_INET, &dst);
8033 				}
8034 				ip1dbg((" through interface %s\n",
8035 				    dst_ill->ill_name));
8036 				goto err_ret;
8037 			}
8038 			ipif_refrele(ipif);
8039 			ipif = src_ipif;
8040 			ipif_refhold(ipif);
8041 		}
8042 		if (src_ipif == NULL) {
8043 			src_ipif = ipif;
8044 			ipif_refhold(src_ipif);
8045 		}
8046 
8047 		/*
8048 		 * Assign a source address while we have the conn.
8049 		 * We can't have ip_wput_ire pick a source address when the
8050 		 * packet returns from arp since conn_unspec_src might be set
8051 		 * and we loose the conn when going through arp.
8052 		 */
8053 		if (ipha->ipha_src == INADDR_ANY &&
8054 		    (connp == NULL || !connp->conn_unspec_src)) {
8055 			ipha->ipha_src = src_ipif->ipif_src_addr;
8056 		}
8057 
8058 		/*
8059 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8060 		 * interface does not have an interface ire.
8061 		 * Example: Thousands of mobileip PPP interfaces to mobile
8062 		 * nodes. We don't want to create interface ires because
8063 		 * packets from other mobile nodes must not take the route
8064 		 * via interface ires to the visiting mobile node without
8065 		 * going through the home agent, in absence of mobileip
8066 		 * route optimization.
8067 		 */
8068 		if (CLASSD(ipha_dst) && (connp == NULL ||
8069 		    connp->conn_xmit_if_ill == NULL)) {
8070 			/* ipif_to_ire returns an held ire */
8071 			ire = ipif_to_ire(ipif);
8072 			if (ire == NULL)
8073 				goto err_ret;
8074 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8075 				goto err_ret;
8076 			/*
8077 			 * ihandle is needed when the ire is added to
8078 			 * cache table.
8079 			 */
8080 			save_ire = ire;
8081 			ihandle = save_ire->ire_ihandle;
8082 
8083 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8084 			    "flags %04x\n",
8085 			    (void *)ire, (void *)ipif, flags));
8086 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8087 			    (fire->ire_flags & RTF_MULTIRT)) {
8088 				/*
8089 				 * As requested by flags, an IRE_OFFSUBNET was
8090 				 * looked up on that interface. This ire has
8091 				 * RTF_MULTIRT flag, so the resolution loop will
8092 				 * be re-entered to resolve additional routes on
8093 				 * other interfaces. For that purpose, a copy of
8094 				 * the packet is performed at this point.
8095 				 */
8096 				fire->ire_last_used_time = lbolt;
8097 				copy_mp = copymsg(first_mp);
8098 				if (copy_mp) {
8099 					MULTIRT_DEBUG_TAG(copy_mp);
8100 				}
8101 			}
8102 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8103 			    (fire->ire_flags & RTF_SETSRC)) {
8104 				/*
8105 				 * As requested by flags, an IRE_OFFSUBET was
8106 				 * looked up on that interface. This ire has
8107 				 * RTF_SETSRC flag, so the source address of the
8108 				 * packet must be changed.
8109 				 */
8110 				ipha->ipha_src = fire->ire_src_addr;
8111 			}
8112 		} else {
8113 			ASSERT((connp == NULL) ||
8114 			    (connp->conn_xmit_if_ill != NULL) ||
8115 			    (connp->conn_dontroute));
8116 			/*
8117 			 * The only ways we can come here are:
8118 			 * 1) IP_XMIT_IF socket option is set
8119 			 * 2) ICMP error message generated from
8120 			 *    ip_mrtun_forward() routine and it needs
8121 			 *    to go through the specified ill.
8122 			 * 3) SO_DONTROUTE socket option is set
8123 			 * In all cases, the new ire will not be added
8124 			 * into cache table.
8125 			 */
8126 			ire_marks |= IRE_MARK_NOADD;
8127 		}
8128 
8129 		switch (ipif->ipif_net_type) {
8130 		case IRE_IF_NORESOLVER: {
8131 			/* We have what we need to build an IRE_CACHE. */
8132 			mblk_t	*dlureq_mp;
8133 
8134 			/*
8135 			 * Create a new dlureq_mp with the
8136 			 * IP gateway address as destination address in the
8137 			 * DLPI hdr if the physical length is exactly 4 bytes.
8138 			 */
8139 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8140 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8141 				    dst_ill->ill_phys_addr_length,
8142 				    dst_ill->ill_sap,
8143 				    dst_ill->ill_sap_length);
8144 			} else {
8145 				/* use the value set in ip_ll_subnet_defaults */
8146 				dlureq_mp = ill_dlur_gen(NULL,
8147 				    dst_ill->ill_phys_addr_length,
8148 				    dst_ill->ill_sap,
8149 				    dst_ill->ill_sap_length);
8150 			}
8151 
8152 			if (dlureq_mp == NULL)
8153 				break;
8154 			/*
8155 			 * The new ire inherits the IRE_OFFSUBNET flags
8156 			 * and source address, if this was requested.
8157 			 */
8158 			ire = ire_create(
8159 			    (uchar_t *)&dst,		/* dest address */
8160 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8161 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8162 			    NULL,			/* gateway address */
8163 			    NULL,
8164 			    &ipif->ipif_mtu,
8165 			    NULL,			/* Fast Path header */
8166 			    dst_ill->ill_rq,		/* recv-from queue */
8167 			    dst_ill->ill_wq,		/* send-to queue */
8168 			    IRE_CACHE,
8169 			    dlureq_mp,
8170 			    src_ipif,
8171 			    NULL,
8172 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8173 			    (fire != NULL) ?		/* Parent handle */
8174 				fire->ire_phandle : 0,
8175 			    ihandle,			/* Interface handle */
8176 			    (fire != NULL) ?
8177 				(fire->ire_flags &
8178 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8179 			    (save_ire == NULL ? &ire_uinfo_null :
8180 				&save_ire->ire_uinfo));
8181 
8182 			freeb(dlureq_mp);
8183 
8184 			if (ire == NULL) {
8185 				if (save_ire != NULL)
8186 					ire_refrele(save_ire);
8187 				break;
8188 			}
8189 
8190 			ire->ire_marks |= ire_marks;
8191 
8192 			/* Prevent save_ire from getting deleted */
8193 			if (save_ire != NULL) {
8194 				IRB_REFHOLD(save_ire->ire_bucket);
8195 				/* Has it been removed already ? */
8196 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8197 					IRB_REFRELE(save_ire->ire_bucket);
8198 					ire_refrele(save_ire);
8199 					break;
8200 				}
8201 			}
8202 
8203 			ire_add_then_send(q, ire, first_mp);
8204 
8205 			/* Assert that save_ire is not deleted yet. */
8206 			if (save_ire != NULL) {
8207 				ASSERT(save_ire->ire_ptpn != NULL);
8208 				IRB_REFRELE(save_ire->ire_bucket);
8209 				ire_refrele(save_ire);
8210 				save_ire = NULL;
8211 			}
8212 			if (fire != NULL) {
8213 				ire_refrele(fire);
8214 				fire = NULL;
8215 			}
8216 
8217 			/*
8218 			 * the resolution loop is re-entered if this
8219 			 * was requested through flags and if we
8220 			 * actually are in a multirouting case.
8221 			 */
8222 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8223 				boolean_t need_resolve =
8224 				    ire_multirt_need_resolve(ipha_dst);
8225 				if (!need_resolve) {
8226 					MULTIRT_DEBUG_UNTAG(copy_mp);
8227 					freemsg(copy_mp);
8228 					copy_mp = NULL;
8229 				} else {
8230 					/*
8231 					 * ipif_lookup_group() calls
8232 					 * ire_lookup_multi() that uses
8233 					 * ire_ftable_lookup() to find
8234 					 * an IRE_INTERFACE for the group.
8235 					 * In the multirt case,
8236 					 * ire_lookup_multi() then invokes
8237 					 * ire_multirt_lookup() to find
8238 					 * the next resolvable ire.
8239 					 * As a result, we obtain an new
8240 					 * interface, derived from the
8241 					 * next ire.
8242 					 */
8243 					ipif_refrele(ipif);
8244 					ipif = ipif_lookup_group(ipha_dst,
8245 					    zoneid);
8246 					ip2dbg(("ip_newroute_ipif: "
8247 					    "multirt dst %08x, ipif %p\n",
8248 					    htonl(dst), (void *)ipif));
8249 					if (ipif != NULL) {
8250 						mp = copy_mp;
8251 						copy_mp = NULL;
8252 						multirt_resolve_next = B_TRUE;
8253 						continue;
8254 					} else {
8255 						freemsg(copy_mp);
8256 					}
8257 				}
8258 			}
8259 			if (ipif != NULL)
8260 				ipif_refrele(ipif);
8261 			ill_refrele(dst_ill);
8262 			ipif_refrele(src_ipif);
8263 			return;
8264 		}
8265 		case IRE_IF_RESOLVER:
8266 			/*
8267 			 * We can't build an IRE_CACHE yet, but at least
8268 			 * we found a resolver that can help.
8269 			 */
8270 			res_mp = dst_ill->ill_resolver_mp;
8271 			if (!OK_RESOLVER_MP(res_mp))
8272 				break;
8273 
8274 			/*
8275 			 * We obtain a partial IRE_CACHE which we will pass
8276 			 * along with the resolver query.  When the response
8277 			 * comes back it will be there ready for us to add.
8278 			 * The new ire inherits the IRE_OFFSUBNET flags
8279 			 * and source address, if this was requested.
8280 			 * The ire_max_frag is atomically set under the
8281 			 * irebucket lock in ire_add_v[46]. Only in the
8282 			 * case of IRE_MARK_NOADD, we set it here itself.
8283 			 */
8284 			ire = ire_create_mp(
8285 			    (uchar_t *)&dst,		/* dest address */
8286 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8287 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8288 			    NULL,			/* gateway address */
8289 			    NULL,			/* no in_src_addr */
8290 			    (ire_marks & IRE_MARK_NOADD) ?
8291 				ipif->ipif_mtu : 0,	/* max_frag */
8292 			    NULL,			/* Fast path header */
8293 			    dst_ill->ill_rq,		/* recv-from queue */
8294 			    dst_ill->ill_wq,		/* send-to queue */
8295 			    IRE_CACHE,
8296 			    res_mp,
8297 			    src_ipif,
8298 			    NULL,
8299 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8300 			    (fire != NULL) ?		/* Parent handle */
8301 				fire->ire_phandle : 0,
8302 			    ihandle,			/* Interface handle */
8303 			    (fire != NULL) ?		/* flags if any */
8304 				(fire->ire_flags &
8305 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8306 			    (save_ire == NULL ? &ire_uinfo_null :
8307 				&save_ire->ire_uinfo));
8308 
8309 			if (save_ire != NULL) {
8310 				ire_refrele(save_ire);
8311 				save_ire = NULL;
8312 			}
8313 			if (ire == NULL)
8314 				break;
8315 
8316 			ire->ire_marks |= ire_marks;
8317 			/*
8318 			 * Construct message chain for the resolver of the
8319 			 * form:
8320 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8321 			 *
8322 			 * NOTE : ire will be added later when the response
8323 			 * comes back from ARP. If the response does not
8324 			 * come back, ARP frees the packet. For this reason,
8325 			 * we can't REFHOLD the bucket of save_ire to prevent
8326 			 * deletions. We may not be able to REFRELE the
8327 			 * bucket if the response never comes back.
8328 			 * Thus, before adding the ire, ire_add_v4 will make
8329 			 * sure that the interface route does not get deleted.
8330 			 * This is the only case unlike ip_newroute_v6,
8331 			 * ip_newroute_ipif_v6 where we can always prevent
8332 			 * deletions because ire_add_then_send is called after
8333 			 * creating the IRE.
8334 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8335 			 * does not add this IRE into the IRE CACHE.
8336 			 */
8337 			ASSERT(ire->ire_mp != NULL);
8338 			ire->ire_mp->b_cont = first_mp;
8339 			/* Have saved_mp handy, for cleanup if canput fails */
8340 			saved_mp = mp;
8341 			mp = ire->ire_dlureq_mp;
8342 			ASSERT(mp != NULL);
8343 			ire->ire_dlureq_mp = NULL;
8344 			linkb(mp, ire->ire_mp);
8345 
8346 			/*
8347 			 * Fill in the source and dest addrs for the resolver.
8348 			 * NOTE: this depends on memory layouts imposed by
8349 			 * ill_init().
8350 			 */
8351 			areq = (areq_t *)mp->b_rptr;
8352 			addrp = (ipaddr_t *)((char *)areq +
8353 			    areq->areq_sender_addr_offset);
8354 			*addrp = ire->ire_src_addr;
8355 			addrp = (ipaddr_t *)((char *)areq +
8356 			    areq->areq_target_addr_offset);
8357 			*addrp = dst;
8358 			/* Up to the resolver. */
8359 			if (canputnext(dst_ill->ill_rq)) {
8360 				putnext(dst_ill->ill_rq, mp);
8361 				/*
8362 				 * The response will come back in ip_wput
8363 				 * with db_type IRE_DB_TYPE.
8364 				 */
8365 			} else {
8366 				ire->ire_dlureq_mp = mp;
8367 				mp->b_cont = NULL;
8368 				ire_delete(ire);
8369 				saved_mp->b_next = NULL;
8370 				saved_mp->b_prev = NULL;
8371 				freemsg(first_mp);
8372 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8373 			}
8374 
8375 			if (fire != NULL) {
8376 				ire_refrele(fire);
8377 				fire = NULL;
8378 			}
8379 
8380 
8381 			/*
8382 			 * The resolution loop is re-entered if this was
8383 			 * requested through flags and we actually are
8384 			 * in a multirouting case.
8385 			 */
8386 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8387 				boolean_t need_resolve =
8388 				    ire_multirt_need_resolve(ipha_dst);
8389 				if (!need_resolve) {
8390 					MULTIRT_DEBUG_UNTAG(copy_mp);
8391 					freemsg(copy_mp);
8392 					copy_mp = NULL;
8393 				} else {
8394 					/*
8395 					 * ipif_lookup_group() calls
8396 					 * ire_lookup_multi() that uses
8397 					 * ire_ftable_lookup() to find
8398 					 * an IRE_INTERFACE for the group.
8399 					 * In the multirt case,
8400 					 * ire_lookup_multi() then invokes
8401 					 * ire_multirt_lookup() to find
8402 					 * the next resolvable ire.
8403 					 * As a result, we obtain an new
8404 					 * interface, derived from the
8405 					 * next ire.
8406 					 */
8407 					ipif_refrele(ipif);
8408 					ipif = ipif_lookup_group(ipha_dst,
8409 					    zoneid);
8410 					if (ipif != NULL) {
8411 						mp = copy_mp;
8412 						copy_mp = NULL;
8413 						multirt_resolve_next = B_TRUE;
8414 						continue;
8415 					} else {
8416 						freemsg(copy_mp);
8417 					}
8418 				}
8419 			}
8420 			if (ipif != NULL)
8421 				ipif_refrele(ipif);
8422 			ill_refrele(dst_ill);
8423 			ipif_refrele(src_ipif);
8424 			return;
8425 		default:
8426 			break;
8427 		}
8428 	} while (multirt_resolve_next);
8429 
8430 err_ret:
8431 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8432 	if (fire != NULL)
8433 		ire_refrele(fire);
8434 	ipif_refrele(ipif);
8435 	/* Did this packet originate externally? */
8436 	if (dst_ill != NULL)
8437 		ill_refrele(dst_ill);
8438 	if (src_ipif != NULL)
8439 		ipif_refrele(src_ipif);
8440 	if (mp->b_prev || mp->b_next) {
8441 		mp->b_next = NULL;
8442 		mp->b_prev = NULL;
8443 	} else {
8444 		/*
8445 		 * Since ip_wput() isn't close to finished, we fill
8446 		 * in enough of the header for credible error reporting.
8447 		 */
8448 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8449 			/* Failed */
8450 			freemsg(first_mp);
8451 			if (ire != NULL)
8452 				ire_refrele(ire);
8453 			return;
8454 		}
8455 	}
8456 	/*
8457 	 * At this point we will have ire only if RTF_BLACKHOLE
8458 	 * or RTF_REJECT flags are set on the IRE. It will not
8459 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8460 	 */
8461 	if (ire != NULL) {
8462 		if (ire->ire_flags & RTF_BLACKHOLE) {
8463 			ire_refrele(ire);
8464 			freemsg(first_mp);
8465 			return;
8466 		}
8467 		ire_refrele(ire);
8468 	}
8469 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8470 }
8471 
8472 /* Name/Value Table Lookup Routine */
8473 char *
8474 ip_nv_lookup(nv_t *nv, int value)
8475 {
8476 	if (!nv)
8477 		return (NULL);
8478 	for (; nv->nv_name; nv++) {
8479 		if (nv->nv_value == value)
8480 			return (nv->nv_name);
8481 	}
8482 	return ("unknown");
8483 }
8484 
8485 /*
8486  * one day it can be patched to 1 from /etc/system for machines that have few
8487  * fast network interfaces feeding multiple cpus.
8488  */
8489 int ill_stream_putlocks = 0;
8490 
8491 /*
8492  * This is a module open, i.e. this is a control stream for access
8493  * to a DLPI device.  We allocate an ill_t as the instance data in
8494  * this case.
8495  */
8496 int
8497 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8498 {
8499 	uint32_t mem_cnt;
8500 	uint32_t cpu_cnt;
8501 	uint32_t min_cnt;
8502 	pgcnt_t mem_avail;
8503 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8504 	ill_t	*ill;
8505 	int	err;
8506 
8507 	/*
8508 	 * Prevent unprivileged processes from pushing IP so that
8509 	 * they can't send raw IP.
8510 	 */
8511 	if (secpolicy_net_rawaccess(credp) != 0)
8512 		return (EPERM);
8513 
8514 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8515 	q->q_ptr = WR(q)->q_ptr = ill;
8516 
8517 	/*
8518 	 * ill_init initializes the ill fields and then sends down
8519 	 * down a DL_INFO_REQ after calling qprocson.
8520 	 */
8521 	err = ill_init(q, ill);
8522 	if (err != 0) {
8523 		mi_free(ill);
8524 		q->q_ptr = NULL;
8525 		WR(q)->q_ptr = NULL;
8526 		return (err);
8527 	}
8528 
8529 	/* ill_init initializes the ipsq marking this thread as writer */
8530 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8531 	/* Wait for the DL_INFO_ACK */
8532 	mutex_enter(&ill->ill_lock);
8533 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8534 		/*
8535 		 * Return value of 0 indicates a pending signal.
8536 		 */
8537 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8538 		if (err == 0) {
8539 			mutex_exit(&ill->ill_lock);
8540 			(void) ip_close(q, 0);
8541 			return (EINTR);
8542 		}
8543 	}
8544 	mutex_exit(&ill->ill_lock);
8545 
8546 	/*
8547 	 * ip_rput_other could have set an error  in ill_error on
8548 	 * receipt of M_ERROR.
8549 	 */
8550 
8551 	err = ill->ill_error;
8552 	if (err != 0) {
8553 		(void) ip_close(q, 0);
8554 		return (err);
8555 	}
8556 
8557 	/*
8558 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8559 	 * size and the cpu speed of the machine. This is upper
8560 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8561 	 * and is lower bounded by the compile time value of
8562 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8563 	 * ip6_ire_max_bucket_cnt.
8564 	 */
8565 	mem_avail = kmem_avail();
8566 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8567 	    ip_cache_table_size / sizeof (ire_t);
8568 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8569 
8570 	min_cnt = MIN(cpu_cnt, mem_cnt);
8571 	if (min_cnt < ip_ire_min_bucket_cnt)
8572 		min_cnt = ip_ire_min_bucket_cnt;
8573 	if (ip_ire_max_bucket_cnt > min_cnt) {
8574 		ip_ire_max_bucket_cnt = min_cnt;
8575 	}
8576 
8577 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8578 	    ip6_cache_table_size / sizeof (ire_t);
8579 	min_cnt = MIN(cpu_cnt, mem_cnt);
8580 	if (min_cnt < ip6_ire_min_bucket_cnt)
8581 		min_cnt = ip6_ire_min_bucket_cnt;
8582 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8583 		ip6_ire_max_bucket_cnt = min_cnt;
8584 	}
8585 
8586 	ill->ill_credp = credp;
8587 	crhold(credp);
8588 
8589 	mutex_enter(&ip_mi_lock);
8590 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8591 	mutex_exit(&ip_mi_lock);
8592 	if (err) {
8593 		(void) ip_close(q, 0);
8594 		return (err);
8595 	}
8596 	return (0);
8597 }
8598 
8599 /* IP open routine. */
8600 int
8601 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8602 {
8603 	conn_t 		*connp;
8604 	major_t		maj;
8605 
8606 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8607 
8608 	/* Allow reopen. */
8609 	if (q->q_ptr != NULL)
8610 		return (0);
8611 
8612 	if (sflag & MODOPEN) {
8613 		/* This is a module open */
8614 		return (ip_modopen(q, devp, flag, sflag, credp));
8615 	}
8616 
8617 	/*
8618 	 * We are opening as a device. This is an IP client stream, and we
8619 	 * allocate an conn_t as the instance data.
8620 	 */
8621 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8622 	connp->conn_upq = q;
8623 	q->q_ptr = WR(q)->q_ptr = connp;
8624 
8625 	if (flag & SO_SOCKSTR)
8626 		connp->conn_flags |= IPCL_SOCKET;
8627 
8628 	/* Minor tells us which /dev entry was opened */
8629 	if (geteminor(*devp) == IPV6_MINOR) {
8630 		connp->conn_flags |= IPCL_ISV6;
8631 		connp->conn_af_isv6 = B_TRUE;
8632 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8633 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8634 	} else {
8635 		connp->conn_af_isv6 = B_FALSE;
8636 		connp->conn_pkt_isv6 = B_FALSE;
8637 	}
8638 
8639 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
8640 		q->q_ptr = WR(q)->q_ptr = NULL;
8641 		CONN_DEC_REF(connp);
8642 		return (EBUSY);
8643 	}
8644 
8645 	maj = getemajor(*devp);
8646 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8647 
8648 	/*
8649 	 * connp->conn_cred is crfree()ed in ip_close().
8650 	 */
8651 	connp->conn_cred = credp;
8652 	crhold(connp->conn_cred);
8653 
8654 	connp->conn_zoneid = getzoneid();
8655 
8656 	/*
8657 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8658 	 * administrative ops.  In these cases, we just need a normal conn_t
8659 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8660 	 * an error will be returned.
8661 	 */
8662 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8663 		connp->conn_rq = q;
8664 		connp->conn_wq = WR(q);
8665 	} else {
8666 		connp->conn_ulp = IPPROTO_SCTP;
8667 		connp->conn_rq = connp->conn_wq = NULL;
8668 	}
8669 	/* Non-zero default values */
8670 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8671 
8672 	/*
8673 	 * Make the conn globally visible to walkers
8674 	 */
8675 	mutex_enter(&connp->conn_lock);
8676 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8677 	mutex_exit(&connp->conn_lock);
8678 	ASSERT(connp->conn_ref == 1);
8679 
8680 	qprocson(q);
8681 
8682 	return (0);
8683 }
8684 
8685 /*
8686  * Change q_qinfo based on the value of isv6.
8687  * This can not called on an ill queue.
8688  * Note that there is no race since either q_qinfo works for conn queues - it
8689  * is just an optimization to enter the best wput routine directly.
8690  */
8691 void
8692 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8693 {
8694 	ASSERT(q->q_flag & QREADR);
8695 	ASSERT(WR(q)->q_next == NULL);
8696 	ASSERT(q->q_ptr != NULL);
8697 
8698 	if (minor == IPV6_MINOR)  {
8699 		if (bump_mib)
8700 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8701 		q->q_qinfo = &rinit_ipv6;
8702 		WR(q)->q_qinfo = &winit_ipv6;
8703 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8704 	} else {
8705 		if (bump_mib)
8706 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8707 		q->q_qinfo = &rinit;
8708 		WR(q)->q_qinfo = &winit;
8709 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8710 	}
8711 
8712 }
8713 
8714 /*
8715  * See if IPsec needs loading because of the options in mp.
8716  */
8717 static boolean_t
8718 ipsec_opt_present(mblk_t *mp)
8719 {
8720 	uint8_t *optcp, *next_optcp, *opt_endcp;
8721 	struct opthdr *opt;
8722 	struct T_opthdr *topt;
8723 	int opthdr_len;
8724 	t_uscalar_t optname, optlevel;
8725 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8726 	ipsec_req_t *ipsr;
8727 
8728 	/*
8729 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8730 	 * return TRUE.
8731 	 */
8732 
8733 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8734 	opt_endcp = optcp + tor->OPT_length;
8735 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8736 		opthdr_len = sizeof (struct T_opthdr);
8737 	} else {		/* O_OPTMGMT_REQ */
8738 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8739 		opthdr_len = sizeof (struct opthdr);
8740 	}
8741 	for (; optcp < opt_endcp; optcp = next_optcp) {
8742 		if (optcp + opthdr_len > opt_endcp)
8743 			return (B_FALSE);	/* Not enough option header. */
8744 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8745 			topt = (struct T_opthdr *)optcp;
8746 			optlevel = topt->level;
8747 			optname = topt->name;
8748 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8749 		} else {
8750 			opt = (struct opthdr *)optcp;
8751 			optlevel = opt->level;
8752 			optname = opt->name;
8753 			next_optcp = optcp + opthdr_len +
8754 			    _TPI_ALIGN_OPT(opt->len);
8755 		}
8756 		if ((next_optcp < optcp) || /* wraparound pointer space */
8757 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8758 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8759 			return (B_FALSE); /* bad option buffer */
8760 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8761 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8762 			/*
8763 			 * Check to see if it's an all-bypass or all-zeroes
8764 			 * IPsec request.  Don't bother loading IPsec if
8765 			 * the socket doesn't want to use it.  (A good example
8766 			 * is a bypass request.)
8767 			 *
8768 			 * Basically, if any of the non-NEVER bits are set,
8769 			 * load IPsec.
8770 			 */
8771 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8772 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8773 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8774 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8775 			    != 0)
8776 				return (B_TRUE);
8777 		}
8778 	}
8779 	return (B_FALSE);
8780 }
8781 
8782 /*
8783  * If conn is is waiting for ipsec to finish loading, kick it.
8784  */
8785 /* ARGSUSED */
8786 static void
8787 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8788 {
8789 	t_scalar_t	optreq_prim;
8790 	mblk_t		*mp;
8791 	cred_t		*cr;
8792 	int		err = 0;
8793 
8794 	/*
8795 	 * This function is called, after ipsec loading is complete.
8796 	 * Since IP checks exclusively and atomically (i.e it prevents
8797 	 * ipsec load from completing until ip_optcom_req completes)
8798 	 * whether ipsec load is complete, there cannot be a race with IP
8799 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8800 	 */
8801 	mutex_enter(&connp->conn_lock);
8802 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8803 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8804 		mp = connp->conn_ipsec_opt_mp;
8805 		connp->conn_ipsec_opt_mp = NULL;
8806 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8807 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8808 		mutex_exit(&connp->conn_lock);
8809 
8810 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8811 
8812 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8813 		if (optreq_prim == T_OPTMGMT_REQ) {
8814 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8815 			    &ip_opt_obj);
8816 		} else {
8817 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8818 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8819 			    &ip_opt_obj);
8820 		}
8821 		if (err != EINPROGRESS)
8822 			CONN_OPER_PENDING_DONE(connp);
8823 		return;
8824 	}
8825 	mutex_exit(&connp->conn_lock);
8826 }
8827 
8828 /*
8829  * Called from the ipsec_loader thread, outside any perimeter, to tell
8830  * ip qenable any of the queues waiting for the ipsec loader to
8831  * complete.
8832  *
8833  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8834  * are done with this lock held, so it's guaranteed that none of the
8835  * links will change along the way.
8836  */
8837 void
8838 ip_ipsec_load_complete()
8839 {
8840 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8841 }
8842 
8843 /*
8844  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8845  * determines the grp on which it has to become exclusive, queues the mp
8846  * and sq draining restarts the optmgmt
8847  */
8848 static boolean_t
8849 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8850 {
8851 	conn_t *connp;
8852 
8853 	/*
8854 	 * Take IPsec requests and treat them special.
8855 	 */
8856 	if (ipsec_opt_present(mp)) {
8857 		/* First check if IPsec is loaded. */
8858 		mutex_enter(&ipsec_loader_lock);
8859 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8860 			mutex_exit(&ipsec_loader_lock);
8861 			return (B_FALSE);
8862 		}
8863 		connp = Q_TO_CONN(q);
8864 		mutex_enter(&connp->conn_lock);
8865 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8866 
8867 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8868 		connp->conn_ipsec_opt_mp = mp;
8869 		mutex_exit(&connp->conn_lock);
8870 		mutex_exit(&ipsec_loader_lock);
8871 
8872 		ipsec_loader_loadnow();
8873 		return (B_TRUE);
8874 	}
8875 	return (B_FALSE);
8876 }
8877 
8878 /*
8879  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8880  * all of them are copied to the conn_t. If the req is "zero", the policy is
8881  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8882  * fields.
8883  * We keep only the latest setting of the policy and thus policy setting
8884  * is not incremental/cumulative.
8885  *
8886  * Requests to set policies with multiple alternative actions will
8887  * go through a different API.
8888  */
8889 int
8890 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8891 {
8892 	uint_t ah_req = 0;
8893 	uint_t esp_req = 0;
8894 	uint_t se_req = 0;
8895 	ipsec_selkey_t sel;
8896 	ipsec_act_t *actp = NULL;
8897 	uint_t nact;
8898 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8899 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8900 	ipsec_policy_root_t *pr;
8901 	ipsec_policy_head_t *ph;
8902 	int fam;
8903 	boolean_t is_pol_reset;
8904 	int error = 0;
8905 
8906 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8907 
8908 	/*
8909 	 * The IP_SEC_OPT option does not allow variable length parameters,
8910 	 * hence a request cannot be NULL.
8911 	 */
8912 	if (req == NULL)
8913 		return (EINVAL);
8914 
8915 	ah_req = req->ipsr_ah_req;
8916 	esp_req = req->ipsr_esp_req;
8917 	se_req = req->ipsr_self_encap_req;
8918 
8919 	/*
8920 	 * Are we dealing with a request to reset the policy (i.e.
8921 	 * zero requests).
8922 	 */
8923 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8924 	    (esp_req & REQ_MASK) == 0 &&
8925 	    (se_req & REQ_MASK) == 0);
8926 
8927 	if (!is_pol_reset) {
8928 		/*
8929 		 * If we couldn't load IPsec, fail with "protocol
8930 		 * not supported".
8931 		 * IPsec may not have been loaded for a request with zero
8932 		 * policies, so we don't fail in this case.
8933 		 */
8934 		mutex_enter(&ipsec_loader_lock);
8935 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8936 			mutex_exit(&ipsec_loader_lock);
8937 			return (EPROTONOSUPPORT);
8938 		}
8939 		mutex_exit(&ipsec_loader_lock);
8940 
8941 		/*
8942 		 * Test for valid requests. Invalid algorithms
8943 		 * need to be tested by IPSEC code because new
8944 		 * algorithms can be added dynamically.
8945 		 */
8946 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8947 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8948 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8949 			return (EINVAL);
8950 		}
8951 
8952 		/*
8953 		 * Only privileged users can issue these
8954 		 * requests.
8955 		 */
8956 		if (((ah_req & IPSEC_PREF_NEVER) ||
8957 		    (esp_req & IPSEC_PREF_NEVER) ||
8958 		    (se_req & IPSEC_PREF_NEVER)) &&
8959 		    secpolicy_net_config(cr, B_FALSE) != 0) {
8960 			return (EPERM);
8961 		}
8962 
8963 		/*
8964 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
8965 		 * are mutually exclusive.
8966 		 */
8967 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
8968 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
8969 		    ((se_req & REQ_MASK) == REQ_MASK)) {
8970 			/* Both of them are set */
8971 			return (EINVAL);
8972 		}
8973 	}
8974 
8975 	mutex_enter(&connp->conn_lock);
8976 
8977 	/*
8978 	 * If we have already cached policies in ip_bind_connected*(), don't
8979 	 * let them change now. We cache policies for connections
8980 	 * whose src,dst [addr, port] is known.  The exception to this is
8981 	 * tunnels.  Tunnels are allowed to change policies after having
8982 	 * become fully bound.
8983 	 */
8984 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
8985 		mutex_exit(&connp->conn_lock);
8986 		return (EINVAL);
8987 	}
8988 
8989 	/*
8990 	 * We have a zero policies, reset the connection policy if already
8991 	 * set. This will cause the connection to inherit the
8992 	 * global policy, if any.
8993 	 */
8994 	if (is_pol_reset) {
8995 		if (connp->conn_policy != NULL) {
8996 			IPPH_REFRELE(connp->conn_policy);
8997 			connp->conn_policy = NULL;
8998 		}
8999 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9000 		connp->conn_in_enforce_policy = B_FALSE;
9001 		connp->conn_out_enforce_policy = B_FALSE;
9002 		mutex_exit(&connp->conn_lock);
9003 		return (0);
9004 	}
9005 
9006 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9007 	if (ph == NULL)
9008 		goto enomem;
9009 
9010 	ipsec_actvec_from_req(req, &actp, &nact);
9011 	if (actp == NULL)
9012 		goto enomem;
9013 
9014 	/*
9015 	 * Always allocate IPv4 policy entries, since they can also
9016 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9017 	 */
9018 	bzero(&sel, sizeof (sel));
9019 	sel.ipsl_valid = IPSL_IPV4;
9020 
9021 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9022 	if (pin4 == NULL)
9023 		goto enomem;
9024 
9025 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9026 	if (pout4 == NULL)
9027 		goto enomem;
9028 
9029 	if (connp->conn_pkt_isv6) {
9030 		/*
9031 		 * We're looking at a v6 socket, also allocate the
9032 		 * v6-specific entries...
9033 		 */
9034 		sel.ipsl_valid = IPSL_IPV6;
9035 		pin6 = ipsec_policy_create(&sel, actp, nact,
9036 		    IPSEC_PRIO_SOCKET);
9037 		if (pin6 == NULL)
9038 			goto enomem;
9039 
9040 		pout6 = ipsec_policy_create(&sel, actp, nact,
9041 		    IPSEC_PRIO_SOCKET);
9042 		if (pout6 == NULL)
9043 			goto enomem;
9044 
9045 		/*
9046 		 * .. and file them away in the right place.
9047 		 */
9048 		fam = IPSEC_AF_V6;
9049 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9050 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9051 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9052 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9053 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9054 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9055 	}
9056 
9057 	ipsec_actvec_free(actp, nact);
9058 
9059 	/*
9060 	 * File the v4 policies.
9061 	 */
9062 	fam = IPSEC_AF_V4;
9063 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9064 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9065 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9066 
9067 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9068 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9069 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9070 
9071 	/*
9072 	 * If the requests need security, set enforce_policy.
9073 	 * If the requests are IPSEC_PREF_NEVER, one should
9074 	 * still set conn_out_enforce_policy so that an ipsec_out
9075 	 * gets attached in ip_wput. This is needed so that
9076 	 * for connections that we don't cache policy in ip_bind,
9077 	 * if global policy matches in ip_wput_attach_policy, we
9078 	 * don't wrongly inherit global policy. Similarly, we need
9079 	 * to set conn_in_enforce_policy also so that we don't verify
9080 	 * policy wrongly.
9081 	 */
9082 	if ((ah_req & REQ_MASK) != 0 ||
9083 	    (esp_req & REQ_MASK) != 0 ||
9084 	    (se_req & REQ_MASK) != 0) {
9085 		connp->conn_in_enforce_policy = B_TRUE;
9086 		connp->conn_out_enforce_policy = B_TRUE;
9087 		connp->conn_flags |= IPCL_CHECK_POLICY;
9088 	}
9089 
9090 	/*
9091 	 * Tunnels are allowed to set policy after having been fully bound.
9092 	 * If that's the case, cache policy here.
9093 	 */
9094 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9095 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9096 
9097 	mutex_exit(&connp->conn_lock);
9098 	return (error);
9099 #undef REQ_MASK
9100 
9101 	/*
9102 	 * Common memory-allocation-failure exit path.
9103 	 */
9104 enomem:
9105 	mutex_exit(&connp->conn_lock);
9106 	if (actp != NULL)
9107 		ipsec_actvec_free(actp, nact);
9108 	if (pin4 != NULL)
9109 		IPPOL_REFRELE(pin4);
9110 	if (pout4 != NULL)
9111 		IPPOL_REFRELE(pout4);
9112 	if (pin6 != NULL)
9113 		IPPOL_REFRELE(pin6);
9114 	if (pout6 != NULL)
9115 		IPPOL_REFRELE(pout6);
9116 	return (ENOMEM);
9117 }
9118 
9119 /*
9120  * Only for options that pass in an IP addr. Currently only V4 options
9121  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9122  * So this function assumes level is IPPROTO_IP
9123  */
9124 int
9125 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9126     mblk_t *first_mp)
9127 {
9128 	ipif_t *ipif = NULL;
9129 	int error;
9130 	ill_t *ill;
9131 
9132 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9133 
9134 	if (addr != INADDR_ANY || checkonly) {
9135 		ASSERT(connp != NULL);
9136 		if (option == IP_NEXTHOP) {
9137 			ipif =
9138 			    ipif_lookup_onlink_addr(addr, connp->conn_zoneid);
9139 		} else {
9140 			ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9141 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9142 			    &error);
9143 		}
9144 		if (ipif == NULL) {
9145 			if (error == EINPROGRESS)
9146 				return (error);
9147 			else if ((option == IP_MULTICAST_IF) ||
9148 			    (option == IP_NEXTHOP))
9149 				return (EHOSTUNREACH);
9150 			else
9151 				return (EINVAL);
9152 		} else if (checkonly) {
9153 			if (option == IP_MULTICAST_IF) {
9154 				ill = ipif->ipif_ill;
9155 				/* not supported by the virtual network iface */
9156 				if (IS_VNI(ill)) {
9157 					ipif_refrele(ipif);
9158 					return (EINVAL);
9159 				}
9160 			}
9161 			ipif_refrele(ipif);
9162 			return (0);
9163 		}
9164 		ill = ipif->ipif_ill;
9165 		mutex_enter(&connp->conn_lock);
9166 		mutex_enter(&ill->ill_lock);
9167 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9168 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9169 			mutex_exit(&ill->ill_lock);
9170 			mutex_exit(&connp->conn_lock);
9171 			ipif_refrele(ipif);
9172 			return (option == IP_MULTICAST_IF ?
9173 			    EHOSTUNREACH : EINVAL);
9174 		}
9175 	} else {
9176 		mutex_enter(&connp->conn_lock);
9177 	}
9178 
9179 	/* None of the options below are supported on the VNI */
9180 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9181 		mutex_exit(&ill->ill_lock);
9182 		mutex_exit(&connp->conn_lock);
9183 		ipif_refrele(ipif);
9184 		return (EINVAL);
9185 	}
9186 
9187 	switch (option) {
9188 	case IP_DONTFAILOVER_IF:
9189 		/*
9190 		 * This option is used by in.mpathd to ensure
9191 		 * that IPMP probe packets only go out on the
9192 		 * test interfaces. in.mpathd sets this option
9193 		 * on the non-failover interfaces.
9194 		 * For backward compatibility, this option
9195 		 * implicitly sets IP_MULTICAST_IF, as used
9196 		 * be done in bind(), so that ip_wput gets
9197 		 * this ipif to send mcast packets.
9198 		 */
9199 		if (ipif != NULL) {
9200 			ASSERT(addr != INADDR_ANY);
9201 			connp->conn_nofailover_ill = ipif->ipif_ill;
9202 			connp->conn_multicast_ipif = ipif;
9203 		} else {
9204 			ASSERT(addr == INADDR_ANY);
9205 			connp->conn_nofailover_ill = NULL;
9206 			connp->conn_multicast_ipif = NULL;
9207 		}
9208 		break;
9209 
9210 	case IP_MULTICAST_IF:
9211 		connp->conn_multicast_ipif = ipif;
9212 		break;
9213 	case IP_NEXTHOP:
9214 		connp->conn_nexthop_v4 = addr;
9215 		connp->conn_nexthop_set = B_TRUE;
9216 		break;
9217 	}
9218 
9219 	if (ipif != NULL) {
9220 		mutex_exit(&ill->ill_lock);
9221 		mutex_exit(&connp->conn_lock);
9222 		ipif_refrele(ipif);
9223 		return (0);
9224 	}
9225 	mutex_exit(&connp->conn_lock);
9226 	/* We succeded in cleared the option */
9227 	return (0);
9228 }
9229 
9230 /*
9231  * For options that pass in an ifindex specifying the ill. V6 options always
9232  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9233  */
9234 int
9235 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9236     int level, int option, mblk_t *first_mp)
9237 {
9238 	ill_t *ill = NULL;
9239 	int error = 0;
9240 
9241 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9242 	if (ifindex != 0) {
9243 		ASSERT(connp != NULL);
9244 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9245 		    first_mp, ip_restart_optmgmt, &error);
9246 		if (ill != NULL) {
9247 			if (checkonly) {
9248 				/* not supported by the virtual network iface */
9249 				if (IS_VNI(ill)) {
9250 					ill_refrele(ill);
9251 					return (EINVAL);
9252 				}
9253 				ill_refrele(ill);
9254 				return (0);
9255 			}
9256 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9257 			    0, NULL)) {
9258 				ill_refrele(ill);
9259 				ill = NULL;
9260 				mutex_enter(&connp->conn_lock);
9261 				goto setit;
9262 			}
9263 			mutex_enter(&connp->conn_lock);
9264 			mutex_enter(&ill->ill_lock);
9265 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9266 				mutex_exit(&ill->ill_lock);
9267 				mutex_exit(&connp->conn_lock);
9268 				ill_refrele(ill);
9269 				ill = NULL;
9270 				mutex_enter(&connp->conn_lock);
9271 			}
9272 			goto setit;
9273 		} else if (error == EINPROGRESS) {
9274 			return (error);
9275 		} else {
9276 			error = 0;
9277 		}
9278 	}
9279 	mutex_enter(&connp->conn_lock);
9280 setit:
9281 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9282 
9283 	/*
9284 	 * The options below assume that the ILL (if any) transmits and/or
9285 	 * receives traffic. Neither of which is true for the virtual network
9286 	 * interface, so fail setting these on a VNI.
9287 	 */
9288 	if (IS_VNI(ill)) {
9289 		ASSERT(ill != NULL);
9290 		mutex_exit(&ill->ill_lock);
9291 		mutex_exit(&connp->conn_lock);
9292 		ill_refrele(ill);
9293 		return (EINVAL);
9294 	}
9295 
9296 	if (level == IPPROTO_IP) {
9297 		switch (option) {
9298 		case IP_BOUND_IF:
9299 			connp->conn_incoming_ill = ill;
9300 			connp->conn_outgoing_ill = ill;
9301 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9302 			    0 : ifindex;
9303 			break;
9304 
9305 		case IP_XMIT_IF:
9306 			/*
9307 			 * Similar to IP_BOUND_IF, but this only
9308 			 * determines the outgoing interface for
9309 			 * unicast packets. Also no IRE_CACHE entry
9310 			 * is added for the destination of the
9311 			 * outgoing packets. This feature is needed
9312 			 * for mobile IP.
9313 			 */
9314 			connp->conn_xmit_if_ill = ill;
9315 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9316 			    0 : ifindex;
9317 			break;
9318 
9319 		case IP_MULTICAST_IF:
9320 			/*
9321 			 * This option is an internal special. The socket
9322 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9323 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9324 			 * specifies an ifindex and we try first on V6 ill's.
9325 			 * If we don't find one, we they try using on v4 ill's
9326 			 * intenally and we come here.
9327 			 */
9328 			if (!checkonly && ill != NULL) {
9329 				ipif_t	*ipif;
9330 				ipif = ill->ill_ipif;
9331 
9332 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9333 					mutex_exit(&ill->ill_lock);
9334 					mutex_exit(&connp->conn_lock);
9335 					ill_refrele(ill);
9336 					ill = NULL;
9337 					mutex_enter(&connp->conn_lock);
9338 				} else {
9339 					connp->conn_multicast_ipif = ipif;
9340 				}
9341 			}
9342 			break;
9343 		}
9344 	} else {
9345 		switch (option) {
9346 		case IPV6_BOUND_IF:
9347 			connp->conn_incoming_ill = ill;
9348 			connp->conn_outgoing_ill = ill;
9349 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9350 			    0 : ifindex;
9351 			break;
9352 
9353 		case IPV6_BOUND_PIF:
9354 			/*
9355 			 * Limit all transmit to this ill.
9356 			 * Unlike IPV6_BOUND_IF, using this option
9357 			 * prevents load spreading and failover from
9358 			 * happening when the interface is part of the
9359 			 * group. That's why we don't need to remember
9360 			 * the ifindex in orig_bound_ifindex as in
9361 			 * IPV6_BOUND_IF.
9362 			 */
9363 			connp->conn_outgoing_pill = ill;
9364 			break;
9365 
9366 		case IPV6_DONTFAILOVER_IF:
9367 			/*
9368 			 * This option is used by in.mpathd to ensure
9369 			 * that IPMP probe packets only go out on the
9370 			 * test interfaces. in.mpathd sets this option
9371 			 * on the non-failover interfaces.
9372 			 */
9373 			connp->conn_nofailover_ill = ill;
9374 			/*
9375 			 * For backward compatibility, this option
9376 			 * implicitly sets ip_multicast_ill as used in
9377 			 * IP_MULTICAST_IF so that ip_wput gets
9378 			 * this ipif to send mcast packets.
9379 			 */
9380 			connp->conn_multicast_ill = ill;
9381 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9382 			    0 : ifindex;
9383 			break;
9384 
9385 		case IPV6_MULTICAST_IF:
9386 			/*
9387 			 * Set conn_multicast_ill to be the IPv6 ill.
9388 			 * Set conn_multicast_ipif to be an IPv4 ipif
9389 			 * for ifindex to make IPv4 mapped addresses
9390 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9391 			 * Even if no IPv6 ill exists for the ifindex
9392 			 * we need to check for an IPv4 ifindex in order
9393 			 * for this to work with mapped addresses. In that
9394 			 * case only set conn_multicast_ipif.
9395 			 */
9396 			if (!checkonly) {
9397 				if (ifindex == 0) {
9398 					connp->conn_multicast_ill = NULL;
9399 					connp->conn_orig_multicast_ifindex = 0;
9400 					connp->conn_multicast_ipif = NULL;
9401 				} else if (ill != NULL) {
9402 					connp->conn_multicast_ill = ill;
9403 					connp->conn_orig_multicast_ifindex =
9404 					    ifindex;
9405 				}
9406 			}
9407 			break;
9408 		}
9409 	}
9410 
9411 	if (ill != NULL) {
9412 		mutex_exit(&ill->ill_lock);
9413 		mutex_exit(&connp->conn_lock);
9414 		ill_refrele(ill);
9415 		return (0);
9416 	}
9417 	mutex_exit(&connp->conn_lock);
9418 	/*
9419 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9420 	 * locate the ill and could not set the option (ifindex != 0)
9421 	 */
9422 	return (ifindex == 0 ? 0 : EINVAL);
9423 }
9424 
9425 /* This routine sets socket options. */
9426 /* ARGSUSED */
9427 int
9428 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9429     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9430     void *dummy, cred_t *cr, mblk_t *first_mp)
9431 {
9432 	int		*i1 = (int *)invalp;
9433 	conn_t		*connp = Q_TO_CONN(q);
9434 	int		error = 0;
9435 	boolean_t	checkonly;
9436 	ire_t		*ire;
9437 	boolean_t	found;
9438 
9439 	switch (optset_context) {
9440 
9441 	case SETFN_OPTCOM_CHECKONLY:
9442 		checkonly = B_TRUE;
9443 		/*
9444 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9445 		 * inlen != 0 implies value supplied and
9446 		 * 	we have to "pretend" to set it.
9447 		 * inlen == 0 implies that there is no
9448 		 * 	value part in T_CHECK request and just validation
9449 		 * done elsewhere should be enough, we just return here.
9450 		 */
9451 		if (inlen == 0) {
9452 			*outlenp = 0;
9453 			return (0);
9454 		}
9455 		break;
9456 	case SETFN_OPTCOM_NEGOTIATE:
9457 	case SETFN_UD_NEGOTIATE:
9458 	case SETFN_CONN_NEGOTIATE:
9459 		checkonly = B_FALSE;
9460 		break;
9461 	default:
9462 		/*
9463 		 * We should never get here
9464 		 */
9465 		*outlenp = 0;
9466 		return (EINVAL);
9467 	}
9468 
9469 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9470 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9471 
9472 	/*
9473 	 * For fixed length options, no sanity check
9474 	 * of passed in length is done. It is assumed *_optcom_req()
9475 	 * routines do the right thing.
9476 	 */
9477 
9478 	switch (level) {
9479 	case SOL_SOCKET:
9480 		/*
9481 		 * conn_lock protects the bitfields, and is used to
9482 		 * set the fields atomically.
9483 		 */
9484 		switch (name) {
9485 		case SO_BROADCAST:
9486 			if (!checkonly) {
9487 				/* TODO: use value someplace? */
9488 				mutex_enter(&connp->conn_lock);
9489 				connp->conn_broadcast = *i1 ? 1 : 0;
9490 				mutex_exit(&connp->conn_lock);
9491 			}
9492 			break;	/* goto sizeof (int) option return */
9493 		case SO_USELOOPBACK:
9494 			if (!checkonly) {
9495 				/* TODO: use value someplace? */
9496 				mutex_enter(&connp->conn_lock);
9497 				connp->conn_loopback = *i1 ? 1 : 0;
9498 				mutex_exit(&connp->conn_lock);
9499 			}
9500 			break;	/* goto sizeof (int) option return */
9501 		case SO_DONTROUTE:
9502 			if (!checkonly) {
9503 				mutex_enter(&connp->conn_lock);
9504 				connp->conn_dontroute = *i1 ? 1 : 0;
9505 				mutex_exit(&connp->conn_lock);
9506 			}
9507 			break;	/* goto sizeof (int) option return */
9508 		case SO_REUSEADDR:
9509 			if (!checkonly) {
9510 				mutex_enter(&connp->conn_lock);
9511 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9512 				mutex_exit(&connp->conn_lock);
9513 			}
9514 			break;	/* goto sizeof (int) option return */
9515 		case SO_PROTOTYPE:
9516 			if (!checkonly) {
9517 				mutex_enter(&connp->conn_lock);
9518 				connp->conn_proto = *i1;
9519 				mutex_exit(&connp->conn_lock);
9520 			}
9521 			break;	/* goto sizeof (int) option return */
9522 		default:
9523 			/*
9524 			 * "soft" error (negative)
9525 			 * option not handled at this level
9526 			 * Note: Do not modify *outlenp
9527 			 */
9528 			return (-EINVAL);
9529 		}
9530 		break;
9531 	case IPPROTO_IP:
9532 		switch (name) {
9533 		case IP_NEXTHOP:
9534 		case IP_MULTICAST_IF:
9535 		case IP_DONTFAILOVER_IF: {
9536 			ipaddr_t addr = *i1;
9537 
9538 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9539 			    first_mp);
9540 			if (error != 0)
9541 				return (error);
9542 			break;	/* goto sizeof (int) option return */
9543 		}
9544 
9545 		case IP_MULTICAST_TTL:
9546 			/* Recorded in transport above IP */
9547 			*outvalp = *invalp;
9548 			*outlenp = sizeof (uchar_t);
9549 			return (0);
9550 		case IP_MULTICAST_LOOP:
9551 			if (!checkonly) {
9552 				mutex_enter(&connp->conn_lock);
9553 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9554 				mutex_exit(&connp->conn_lock);
9555 			}
9556 			*outvalp = *invalp;
9557 			*outlenp = sizeof (uchar_t);
9558 			return (0);
9559 		case IP_ADD_MEMBERSHIP:
9560 		case MCAST_JOIN_GROUP:
9561 		case IP_DROP_MEMBERSHIP:
9562 		case MCAST_LEAVE_GROUP: {
9563 			struct ip_mreq *mreqp;
9564 			struct group_req *greqp;
9565 			ire_t *ire;
9566 			boolean_t done = B_FALSE;
9567 			ipaddr_t group, ifaddr;
9568 			struct sockaddr_in *sin;
9569 			uint32_t *ifindexp;
9570 			boolean_t mcast_opt = B_TRUE;
9571 			mcast_record_t fmode;
9572 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9573 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9574 
9575 			switch (name) {
9576 			case IP_ADD_MEMBERSHIP:
9577 				mcast_opt = B_FALSE;
9578 				/* FALLTHRU */
9579 			case MCAST_JOIN_GROUP:
9580 				fmode = MODE_IS_EXCLUDE;
9581 				optfn = ip_opt_add_group;
9582 				break;
9583 
9584 			case IP_DROP_MEMBERSHIP:
9585 				mcast_opt = B_FALSE;
9586 				/* FALLTHRU */
9587 			case MCAST_LEAVE_GROUP:
9588 				fmode = MODE_IS_INCLUDE;
9589 				optfn = ip_opt_delete_group;
9590 				break;
9591 			}
9592 
9593 			if (mcast_opt) {
9594 				greqp = (struct group_req *)i1;
9595 				sin = (struct sockaddr_in *)&greqp->gr_group;
9596 				if (sin->sin_family != AF_INET) {
9597 					*outlenp = 0;
9598 					return (ENOPROTOOPT);
9599 				}
9600 				group = (ipaddr_t)sin->sin_addr.s_addr;
9601 				ifaddr = INADDR_ANY;
9602 				ifindexp = &greqp->gr_interface;
9603 			} else {
9604 				mreqp = (struct ip_mreq *)i1;
9605 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9606 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9607 				ifindexp = NULL;
9608 			}
9609 
9610 			/*
9611 			 * In the multirouting case, we need to replicate
9612 			 * the request on all interfaces that will take part
9613 			 * in replication.  We do so because multirouting is
9614 			 * reflective, thus we will probably receive multi-
9615 			 * casts on those interfaces.
9616 			 * The ip_multirt_apply_membership() succeeds if the
9617 			 * operation succeeds on at least one interface.
9618 			 */
9619 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9620 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9621 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9622 			if (ire != NULL) {
9623 				if (ire->ire_flags & RTF_MULTIRT) {
9624 					error = ip_multirt_apply_membership(
9625 					    optfn, ire, connp, checkonly, group,
9626 					    fmode, INADDR_ANY, first_mp);
9627 					done = B_TRUE;
9628 				}
9629 				ire_refrele(ire);
9630 			}
9631 			if (!done) {
9632 				error = optfn(connp, checkonly, group, ifaddr,
9633 				    ifindexp, fmode, INADDR_ANY, first_mp);
9634 			}
9635 			if (error) {
9636 				/*
9637 				 * EINPROGRESS is a soft error, needs retry
9638 				 * so don't make *outlenp zero.
9639 				 */
9640 				if (error != EINPROGRESS)
9641 					*outlenp = 0;
9642 				return (error);
9643 			}
9644 			/* OK return - copy input buffer into output buffer */
9645 			if (invalp != outvalp) {
9646 				/* don't trust bcopy for identical src/dst */
9647 				bcopy(invalp, outvalp, inlen);
9648 			}
9649 			*outlenp = inlen;
9650 			return (0);
9651 		}
9652 		case IP_BLOCK_SOURCE:
9653 		case IP_UNBLOCK_SOURCE:
9654 		case IP_ADD_SOURCE_MEMBERSHIP:
9655 		case IP_DROP_SOURCE_MEMBERSHIP:
9656 		case MCAST_BLOCK_SOURCE:
9657 		case MCAST_UNBLOCK_SOURCE:
9658 		case MCAST_JOIN_SOURCE_GROUP:
9659 		case MCAST_LEAVE_SOURCE_GROUP: {
9660 			struct ip_mreq_source *imreqp;
9661 			struct group_source_req *gsreqp;
9662 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9663 			uint32_t ifindex = 0;
9664 			mcast_record_t fmode;
9665 			struct sockaddr_in *sin;
9666 			ire_t *ire;
9667 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9668 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9669 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9670 
9671 			switch (name) {
9672 			case IP_BLOCK_SOURCE:
9673 				mcast_opt = B_FALSE;
9674 				/* FALLTHRU */
9675 			case MCAST_BLOCK_SOURCE:
9676 				fmode = MODE_IS_EXCLUDE;
9677 				optfn = ip_opt_add_group;
9678 				break;
9679 
9680 			case IP_UNBLOCK_SOURCE:
9681 				mcast_opt = B_FALSE;
9682 				/* FALLTHRU */
9683 			case MCAST_UNBLOCK_SOURCE:
9684 				fmode = MODE_IS_EXCLUDE;
9685 				optfn = ip_opt_delete_group;
9686 				break;
9687 
9688 			case IP_ADD_SOURCE_MEMBERSHIP:
9689 				mcast_opt = B_FALSE;
9690 				/* FALLTHRU */
9691 			case MCAST_JOIN_SOURCE_GROUP:
9692 				fmode = MODE_IS_INCLUDE;
9693 				optfn = ip_opt_add_group;
9694 				break;
9695 
9696 			case IP_DROP_SOURCE_MEMBERSHIP:
9697 				mcast_opt = B_FALSE;
9698 				/* FALLTHRU */
9699 			case MCAST_LEAVE_SOURCE_GROUP:
9700 				fmode = MODE_IS_INCLUDE;
9701 				optfn = ip_opt_delete_group;
9702 				break;
9703 			}
9704 
9705 			if (mcast_opt) {
9706 				gsreqp = (struct group_source_req *)i1;
9707 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9708 					*outlenp = 0;
9709 					return (ENOPROTOOPT);
9710 				}
9711 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9712 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9713 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9714 				src = (ipaddr_t)sin->sin_addr.s_addr;
9715 				ifindex = gsreqp->gsr_interface;
9716 			} else {
9717 				imreqp = (struct ip_mreq_source *)i1;
9718 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9719 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9720 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9721 			}
9722 
9723 			/*
9724 			 * In the multirouting case, we need to replicate
9725 			 * the request as noted in the mcast cases above.
9726 			 */
9727 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9728 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9729 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9730 			if (ire != NULL) {
9731 				if (ire->ire_flags & RTF_MULTIRT) {
9732 					error = ip_multirt_apply_membership(
9733 					    optfn, ire, connp, checkonly, grp,
9734 					    fmode, src, first_mp);
9735 					done = B_TRUE;
9736 				}
9737 				ire_refrele(ire);
9738 			}
9739 			if (!done) {
9740 				error = optfn(connp, checkonly, grp, ifaddr,
9741 				    &ifindex, fmode, src, first_mp);
9742 			}
9743 			if (error != 0) {
9744 				/*
9745 				 * EINPROGRESS is a soft error, needs retry
9746 				 * so don't make *outlenp zero.
9747 				 */
9748 				if (error != EINPROGRESS)
9749 					*outlenp = 0;
9750 				return (error);
9751 			}
9752 			/* OK return - copy input buffer into output buffer */
9753 			if (invalp != outvalp) {
9754 				bcopy(invalp, outvalp, inlen);
9755 			}
9756 			*outlenp = inlen;
9757 			return (0);
9758 		}
9759 		case IP_SEC_OPT:
9760 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9761 			if (error != 0) {
9762 				*outlenp = 0;
9763 				return (error);
9764 			}
9765 			break;
9766 		case IP_HDRINCL:
9767 		case IP_OPTIONS:
9768 		case T_IP_OPTIONS:
9769 		case IP_TOS:
9770 		case T_IP_TOS:
9771 		case IP_TTL:
9772 		case IP_RECVDSTADDR:
9773 		case IP_RECVOPTS:
9774 			/* OK return - copy input buffer into output buffer */
9775 			if (invalp != outvalp) {
9776 				/* don't trust bcopy for identical src/dst */
9777 				bcopy(invalp, outvalp, inlen);
9778 			}
9779 			*outlenp = inlen;
9780 			return (0);
9781 		case IP_RECVIF:
9782 			/* Retrieve the inbound interface index */
9783 			if (!checkonly) {
9784 				mutex_enter(&connp->conn_lock);
9785 				connp->conn_recvif = *i1 ? 1 : 0;
9786 				mutex_exit(&connp->conn_lock);
9787 			}
9788 			break;	/* goto sizeof (int) option return */
9789 		case IP_RECVSLLA:
9790 			/* Retrieve the source link layer address */
9791 			if (!checkonly) {
9792 				mutex_enter(&connp->conn_lock);
9793 				connp->conn_recvslla = *i1 ? 1 : 0;
9794 				mutex_exit(&connp->conn_lock);
9795 			}
9796 			break;	/* goto sizeof (int) option return */
9797 		case MRT_INIT:
9798 		case MRT_DONE:
9799 		case MRT_ADD_VIF:
9800 		case MRT_DEL_VIF:
9801 		case MRT_ADD_MFC:
9802 		case MRT_DEL_MFC:
9803 		case MRT_ASSERT:
9804 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9805 				*outlenp = 0;
9806 				return (error);
9807 			}
9808 			error = ip_mrouter_set((int)name, q, checkonly,
9809 			    (uchar_t *)invalp, inlen, first_mp);
9810 			if (error) {
9811 				*outlenp = 0;
9812 				return (error);
9813 			}
9814 			/* OK return - copy input buffer into output buffer */
9815 			if (invalp != outvalp) {
9816 				/* don't trust bcopy for identical src/dst */
9817 				bcopy(invalp, outvalp, inlen);
9818 			}
9819 			*outlenp = inlen;
9820 			return (0);
9821 		case IP_BOUND_IF:
9822 		case IP_XMIT_IF:
9823 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9824 			    level, name, first_mp);
9825 			if (error != 0)
9826 				return (error);
9827 			break; 		/* goto sizeof (int) option return */
9828 
9829 		case IP_UNSPEC_SRC:
9830 			/* Allow sending with a zero source address */
9831 			if (!checkonly) {
9832 				mutex_enter(&connp->conn_lock);
9833 				connp->conn_unspec_src = *i1 ? 1 : 0;
9834 				mutex_exit(&connp->conn_lock);
9835 			}
9836 			break;	/* goto sizeof (int) option return */
9837 		default:
9838 			/*
9839 			 * "soft" error (negative)
9840 			 * option not handled at this level
9841 			 * Note: Do not modify *outlenp
9842 			 */
9843 			return (-EINVAL);
9844 		}
9845 		break;
9846 	case IPPROTO_IPV6:
9847 		switch (name) {
9848 		case IPV6_BOUND_IF:
9849 		case IPV6_BOUND_PIF:
9850 		case IPV6_DONTFAILOVER_IF:
9851 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9852 			    level, name, first_mp);
9853 			if (error != 0)
9854 				return (error);
9855 			break; 		/* goto sizeof (int) option return */
9856 
9857 		case IPV6_MULTICAST_IF:
9858 			/*
9859 			 * The only possible errors are EINPROGRESS and
9860 			 * EINVAL. EINPROGRESS will be restarted and is not
9861 			 * a hard error. We call this option on both V4 and V6
9862 			 * If both return EINVAL, then this call returns
9863 			 * EINVAL. If at least one of them succeeds we
9864 			 * return success.
9865 			 */
9866 			found = B_FALSE;
9867 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9868 			    level, name, first_mp);
9869 			if (error == EINPROGRESS)
9870 				return (error);
9871 			if (error == 0)
9872 				found = B_TRUE;
9873 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9874 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9875 			if (error == 0)
9876 				found = B_TRUE;
9877 			if (!found)
9878 				return (error);
9879 			break; 		/* goto sizeof (int) option return */
9880 
9881 		case IPV6_MULTICAST_HOPS:
9882 			/* Recorded in transport above IP */
9883 			break;	/* goto sizeof (int) option return */
9884 		case IPV6_MULTICAST_LOOP:
9885 			if (!checkonly) {
9886 				mutex_enter(&connp->conn_lock);
9887 				connp->conn_multicast_loop = *i1;
9888 				mutex_exit(&connp->conn_lock);
9889 			}
9890 			break;	/* goto sizeof (int) option return */
9891 		case IPV6_JOIN_GROUP:
9892 		case MCAST_JOIN_GROUP:
9893 		case IPV6_LEAVE_GROUP:
9894 		case MCAST_LEAVE_GROUP: {
9895 			struct ipv6_mreq *ip_mreqp;
9896 			struct group_req *greqp;
9897 			ire_t *ire;
9898 			boolean_t done = B_FALSE;
9899 			in6_addr_t groupv6;
9900 			uint32_t ifindex;
9901 			boolean_t mcast_opt = B_TRUE;
9902 			mcast_record_t fmode;
9903 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9904 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9905 
9906 			switch (name) {
9907 			case IPV6_JOIN_GROUP:
9908 				mcast_opt = B_FALSE;
9909 				/* FALLTHRU */
9910 			case MCAST_JOIN_GROUP:
9911 				fmode = MODE_IS_EXCLUDE;
9912 				optfn = ip_opt_add_group_v6;
9913 				break;
9914 
9915 			case IPV6_LEAVE_GROUP:
9916 				mcast_opt = B_FALSE;
9917 				/* FALLTHRU */
9918 			case MCAST_LEAVE_GROUP:
9919 				fmode = MODE_IS_INCLUDE;
9920 				optfn = ip_opt_delete_group_v6;
9921 				break;
9922 			}
9923 
9924 			if (mcast_opt) {
9925 				struct sockaddr_in *sin;
9926 				struct sockaddr_in6 *sin6;
9927 				greqp = (struct group_req *)i1;
9928 				if (greqp->gr_group.ss_family == AF_INET) {
9929 					sin = (struct sockaddr_in *)
9930 					    &(greqp->gr_group);
9931 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9932 					    &groupv6);
9933 				} else {
9934 					sin6 = (struct sockaddr_in6 *)
9935 					    &(greqp->gr_group);
9936 					groupv6 = sin6->sin6_addr;
9937 				}
9938 				ifindex = greqp->gr_interface;
9939 			} else {
9940 				ip_mreqp = (struct ipv6_mreq *)i1;
9941 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9942 				ifindex = ip_mreqp->ipv6mr_interface;
9943 			}
9944 			/*
9945 			 * In the multirouting case, we need to replicate
9946 			 * the request on all interfaces that will take part
9947 			 * in replication.  We do so because multirouting is
9948 			 * reflective, thus we will probably receive multi-
9949 			 * casts on those interfaces.
9950 			 * The ip_multirt_apply_membership_v6() succeeds if
9951 			 * the operation succeeds on at least one interface.
9952 			 */
9953 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9954 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9955 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9956 			if (ire != NULL) {
9957 				if (ire->ire_flags & RTF_MULTIRT) {
9958 					error = ip_multirt_apply_membership_v6(
9959 					    optfn, ire, connp, checkonly,
9960 					    &groupv6, fmode, &ipv6_all_zeros,
9961 					    first_mp);
9962 					done = B_TRUE;
9963 				}
9964 				ire_refrele(ire);
9965 			}
9966 			if (!done) {
9967 				error = optfn(connp, checkonly, &groupv6,
9968 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
9969 			}
9970 			if (error) {
9971 				/*
9972 				 * EINPROGRESS is a soft error, needs retry
9973 				 * so don't make *outlenp zero.
9974 				 */
9975 				if (error != EINPROGRESS)
9976 					*outlenp = 0;
9977 				return (error);
9978 			}
9979 			/* OK return - copy input buffer into output buffer */
9980 			if (invalp != outvalp) {
9981 				/* don't trust bcopy for identical src/dst */
9982 				bcopy(invalp, outvalp, inlen);
9983 			}
9984 			*outlenp = inlen;
9985 			return (0);
9986 		}
9987 		case MCAST_BLOCK_SOURCE:
9988 		case MCAST_UNBLOCK_SOURCE:
9989 		case MCAST_JOIN_SOURCE_GROUP:
9990 		case MCAST_LEAVE_SOURCE_GROUP: {
9991 			struct group_source_req *gsreqp;
9992 			in6_addr_t v6grp, v6src;
9993 			uint32_t ifindex;
9994 			mcast_record_t fmode;
9995 			ire_t *ire;
9996 			boolean_t done = B_FALSE;
9997 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9998 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9999 
10000 			switch (name) {
10001 			case MCAST_BLOCK_SOURCE:
10002 				fmode = MODE_IS_EXCLUDE;
10003 				optfn = ip_opt_add_group_v6;
10004 				break;
10005 			case MCAST_UNBLOCK_SOURCE:
10006 				fmode = MODE_IS_EXCLUDE;
10007 				optfn = ip_opt_delete_group_v6;
10008 				break;
10009 			case MCAST_JOIN_SOURCE_GROUP:
10010 				fmode = MODE_IS_INCLUDE;
10011 				optfn = ip_opt_add_group_v6;
10012 				break;
10013 			case MCAST_LEAVE_SOURCE_GROUP:
10014 				fmode = MODE_IS_INCLUDE;
10015 				optfn = ip_opt_delete_group_v6;
10016 				break;
10017 			}
10018 
10019 			gsreqp = (struct group_source_req *)i1;
10020 			ifindex = gsreqp->gsr_interface;
10021 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10022 				struct sockaddr_in *s;
10023 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10024 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10025 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10026 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10027 			} else {
10028 				struct sockaddr_in6 *s6;
10029 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10030 				v6grp = s6->sin6_addr;
10031 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10032 				v6src = s6->sin6_addr;
10033 			}
10034 
10035 			/*
10036 			 * In the multirouting case, we need to replicate
10037 			 * the request as noted in the mcast cases above.
10038 			 */
10039 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10040 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
10041 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10042 			if (ire != NULL) {
10043 				if (ire->ire_flags & RTF_MULTIRT) {
10044 					error = ip_multirt_apply_membership_v6(
10045 					    optfn, ire, connp, checkonly,
10046 					    &v6grp, fmode, &v6src, first_mp);
10047 					done = B_TRUE;
10048 				}
10049 				ire_refrele(ire);
10050 			}
10051 			if (!done) {
10052 				error = optfn(connp, checkonly, &v6grp,
10053 				    ifindex, fmode, &v6src, first_mp);
10054 			}
10055 			if (error != 0) {
10056 				/*
10057 				 * EINPROGRESS is a soft error, needs retry
10058 				 * so don't make *outlenp zero.
10059 				 */
10060 				if (error != EINPROGRESS)
10061 					*outlenp = 0;
10062 				return (error);
10063 			}
10064 			/* OK return - copy input buffer into output buffer */
10065 			if (invalp != outvalp) {
10066 				bcopy(invalp, outvalp, inlen);
10067 			}
10068 			*outlenp = inlen;
10069 			return (0);
10070 		}
10071 		case IPV6_UNICAST_HOPS:
10072 			/* Recorded in transport above IP */
10073 			break;	/* goto sizeof (int) option return */
10074 		case IPV6_UNSPEC_SRC:
10075 			/* Allow sending with a zero source address */
10076 			if (!checkonly) {
10077 				mutex_enter(&connp->conn_lock);
10078 				connp->conn_unspec_src = *i1 ? 1 : 0;
10079 				mutex_exit(&connp->conn_lock);
10080 			}
10081 			break;	/* goto sizeof (int) option return */
10082 		case IPV6_RECVPKTINFO:
10083 			if (!checkonly) {
10084 				mutex_enter(&connp->conn_lock);
10085 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10086 				mutex_exit(&connp->conn_lock);
10087 			}
10088 			break;	/* goto sizeof (int) option return */
10089 		case IPV6_RECVTCLASS:
10090 			if (!checkonly) {
10091 				if (*i1 < 0 || *i1 > 1) {
10092 					return (EINVAL);
10093 				}
10094 				mutex_enter(&connp->conn_lock);
10095 				connp->conn_ipv6_recvtclass = *i1;
10096 				mutex_exit(&connp->conn_lock);
10097 			}
10098 			break;
10099 		case IPV6_RECVPATHMTU:
10100 			if (!checkonly) {
10101 				if (*i1 < 0 || *i1 > 1) {
10102 					return (EINVAL);
10103 				}
10104 				mutex_enter(&connp->conn_lock);
10105 				connp->conn_ipv6_recvpathmtu = *i1;
10106 				mutex_exit(&connp->conn_lock);
10107 			}
10108 			break;
10109 		case IPV6_RECVHOPLIMIT:
10110 			if (!checkonly) {
10111 				mutex_enter(&connp->conn_lock);
10112 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10113 				mutex_exit(&connp->conn_lock);
10114 			}
10115 			break;	/* goto sizeof (int) option return */
10116 		case IPV6_RECVHOPOPTS:
10117 			if (!checkonly) {
10118 				mutex_enter(&connp->conn_lock);
10119 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10120 				mutex_exit(&connp->conn_lock);
10121 			}
10122 			break;	/* goto sizeof (int) option return */
10123 		case IPV6_RECVDSTOPTS:
10124 			if (!checkonly) {
10125 				mutex_enter(&connp->conn_lock);
10126 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10127 				mutex_exit(&connp->conn_lock);
10128 			}
10129 			break;	/* goto sizeof (int) option return */
10130 		case IPV6_RECVRTHDR:
10131 			if (!checkonly) {
10132 				mutex_enter(&connp->conn_lock);
10133 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10134 				mutex_exit(&connp->conn_lock);
10135 			}
10136 			break;	/* goto sizeof (int) option return */
10137 		case IPV6_RECVRTHDRDSTOPTS:
10138 			if (!checkonly) {
10139 				mutex_enter(&connp->conn_lock);
10140 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10141 				mutex_exit(&connp->conn_lock);
10142 			}
10143 			break;	/* goto sizeof (int) option return */
10144 		case IPV6_PKTINFO:
10145 			if (inlen == 0)
10146 				return (-EINVAL);	/* clearing option */
10147 			error = ip6_set_pktinfo(cr, connp,
10148 			    (struct in6_pktinfo *)invalp, first_mp);
10149 			if (error != 0)
10150 				*outlenp = 0;
10151 			else
10152 				*outlenp = inlen;
10153 			return (error);
10154 		case IPV6_NEXTHOP: {
10155 			struct sockaddr_in6 *sin6;
10156 
10157 			/* Verify that the nexthop is reachable */
10158 			if (inlen == 0)
10159 				return (-EINVAL);	/* clearing option */
10160 
10161 			sin6 = (struct sockaddr_in6 *)invalp;
10162 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10163 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10164 			    MATCH_IRE_DEFAULT);
10165 
10166 			if (ire == NULL) {
10167 				*outlenp = 0;
10168 				return (EHOSTUNREACH);
10169 			}
10170 			ire_refrele(ire);
10171 			return (-EINVAL);
10172 		}
10173 		case IPV6_SEC_OPT:
10174 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10175 			if (error != 0) {
10176 				*outlenp = 0;
10177 				return (error);
10178 			}
10179 			break;
10180 		case IPV6_SRC_PREFERENCES: {
10181 			/*
10182 			 * This is implemented strictly in the ip module
10183 			 * (here and in tcp_opt_*() to accomodate tcp
10184 			 * sockets).  Modules above ip pass this option
10185 			 * down here since ip is the only one that needs to
10186 			 * be aware of source address preferences.
10187 			 *
10188 			 * This socket option only affects connected
10189 			 * sockets that haven't already bound to a specific
10190 			 * IPv6 address.  In other words, sockets that
10191 			 * don't call bind() with an address other than the
10192 			 * unspecified address and that call connect().
10193 			 * ip_bind_connected_v6() passes these preferences
10194 			 * to the ipif_select_source_v6() function.
10195 			 */
10196 			if (inlen != sizeof (uint32_t))
10197 				return (EINVAL);
10198 			error = ip6_set_src_preferences(connp,
10199 			    *(uint32_t *)invalp);
10200 			if (error != 0) {
10201 				*outlenp = 0;
10202 				return (error);
10203 			} else {
10204 				*outlenp = sizeof (uint32_t);
10205 			}
10206 			break;
10207 		}
10208 		case IPV6_V6ONLY:
10209 			if (*i1 < 0 || *i1 > 1) {
10210 				return (EINVAL);
10211 			}
10212 			mutex_enter(&connp->conn_lock);
10213 			connp->conn_ipv6_v6only = *i1;
10214 			mutex_exit(&connp->conn_lock);
10215 			break;
10216 		default:
10217 			return (-EINVAL);
10218 		}
10219 		break;
10220 	default:
10221 		/*
10222 		 * "soft" error (negative)
10223 		 * option not handled at this level
10224 		 * Note: Do not modify *outlenp
10225 		 */
10226 		return (-EINVAL);
10227 	}
10228 	/*
10229 	 * Common case of return from an option that is sizeof (int)
10230 	 */
10231 	*(int *)outvalp = *i1;
10232 	*outlenp = sizeof (int);
10233 	return (0);
10234 }
10235 
10236 /*
10237  * This routine gets default values of certain options whose default
10238  * values are maintained by protocol specific code
10239  */
10240 /* ARGSUSED */
10241 int
10242 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10243 {
10244 	int *i1 = (int *)ptr;
10245 
10246 	switch (level) {
10247 	case IPPROTO_IP:
10248 		switch (name) {
10249 		case IP_MULTICAST_TTL:
10250 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10251 			return (sizeof (uchar_t));
10252 		case IP_MULTICAST_LOOP:
10253 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10254 			return (sizeof (uchar_t));
10255 		default:
10256 			return (-1);
10257 		}
10258 	case IPPROTO_IPV6:
10259 		switch (name) {
10260 		case IPV6_UNICAST_HOPS:
10261 			*i1 = ipv6_def_hops;
10262 			return (sizeof (int));
10263 		case IPV6_MULTICAST_HOPS:
10264 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10265 			return (sizeof (int));
10266 		case IPV6_MULTICAST_LOOP:
10267 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10268 			return (sizeof (int));
10269 		case IPV6_V6ONLY:
10270 			*i1 = 1;
10271 			return (sizeof (int));
10272 		default:
10273 			return (-1);
10274 		}
10275 	default:
10276 		return (-1);
10277 	}
10278 	/* NOTREACHED */
10279 }
10280 
10281 /*
10282  * Given a destination address and a pointer to where to put the information
10283  * this routine fills in the mtuinfo.
10284  */
10285 int
10286 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10287     struct ip6_mtuinfo *mtuinfo)
10288 {
10289 	ire_t *ire;
10290 
10291 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10292 		return (-1);
10293 
10294 	bzero(mtuinfo, sizeof (*mtuinfo));
10295 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10296 	mtuinfo->ip6m_addr.sin6_port = port;
10297 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10298 
10299 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10300 	if (ire != NULL) {
10301 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10302 		ire_refrele(ire);
10303 	} else {
10304 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10305 	}
10306 	return (sizeof (struct ip6_mtuinfo));
10307 }
10308 
10309 /*
10310  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10311  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10312  * isn't.  This doesn't matter as the error checking is done properly for the
10313  * other MRT options coming in through ip_opt_set.
10314  */
10315 int
10316 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10317 {
10318 	conn_t		*connp = Q_TO_CONN(q);
10319 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10320 
10321 	switch (level) {
10322 	case IPPROTO_IP:
10323 		switch (name) {
10324 		case MRT_VERSION:
10325 		case MRT_ASSERT:
10326 			(void) ip_mrouter_get(name, q, ptr);
10327 			return (sizeof (int));
10328 		case IP_SEC_OPT:
10329 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10330 		case IP_NEXTHOP:
10331 			if (connp->conn_nexthop_set) {
10332 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10333 				return (sizeof (ipaddr_t));
10334 			} else
10335 				return (0);
10336 		default:
10337 			break;
10338 		}
10339 		break;
10340 	case IPPROTO_IPV6:
10341 		switch (name) {
10342 		case IPV6_SEC_OPT:
10343 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10344 		case IPV6_SRC_PREFERENCES: {
10345 			return (ip6_get_src_preferences(connp,
10346 			    (uint32_t *)ptr));
10347 		}
10348 		case IPV6_V6ONLY:
10349 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10350 			return (sizeof (int));
10351 		case IPV6_PATHMTU:
10352 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10353 				(struct ip6_mtuinfo *)ptr));
10354 		default:
10355 			break;
10356 		}
10357 		break;
10358 	default:
10359 		break;
10360 	}
10361 	return (-1);
10362 }
10363 
10364 /* Named Dispatch routine to get a current value out of our parameter table. */
10365 /* ARGSUSED */
10366 static int
10367 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10368 {
10369 	ipparam_t *ippa = (ipparam_t *)cp;
10370 
10371 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10372 	return (0);
10373 }
10374 
10375 /* ARGSUSED */
10376 static int
10377 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10378 {
10379 
10380 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10381 	return (0);
10382 }
10383 
10384 /*
10385  * Set ip{,6}_forwarding values.  This means walking through all of the
10386  * ill's and toggling their forwarding values.
10387  */
10388 /* ARGSUSED */
10389 static int
10390 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10391 {
10392 	long new_value;
10393 	int *forwarding_value = (int *)cp;
10394 	ill_t *walker;
10395 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10396 	ill_walk_context_t ctx;
10397 
10398 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10399 	    new_value < 0 || new_value > 1) {
10400 		return (EINVAL);
10401 	}
10402 
10403 	*forwarding_value = new_value;
10404 
10405 	/*
10406 	 * Regardless of the current value of ip_forwarding, set all per-ill
10407 	 * values of ip_forwarding to the value being set.
10408 	 *
10409 	 * Bring all the ill's up to date with the new global value.
10410 	 */
10411 	rw_enter(&ill_g_lock, RW_READER);
10412 
10413 	if (isv6)
10414 		walker = ILL_START_WALK_V6(&ctx);
10415 	else
10416 		walker = ILL_START_WALK_V4(&ctx);
10417 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10418 		(void) ill_forward_set(q, mp, (new_value != 0),
10419 		    (caddr_t)walker);
10420 	}
10421 	rw_exit(&ill_g_lock);
10422 
10423 	return (0);
10424 }
10425 
10426 /*
10427  * Walk through the param array specified registering each element with the
10428  * Named Dispatch handler. This is called only during init. So it is ok
10429  * not to acquire any locks
10430  */
10431 static boolean_t
10432 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10433     ipndp_t *ipnd, size_t ipnd_cnt)
10434 {
10435 	for (; ippa_cnt-- > 0; ippa++) {
10436 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10437 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10438 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10439 				nd_free(&ip_g_nd);
10440 				return (B_FALSE);
10441 			}
10442 		}
10443 	}
10444 
10445 	for (; ipnd_cnt-- > 0; ipnd++) {
10446 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10447 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10448 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10449 			    ipnd->ip_ndp_data)) {
10450 				nd_free(&ip_g_nd);
10451 				return (B_FALSE);
10452 			}
10453 		}
10454 	}
10455 
10456 	return (B_TRUE);
10457 }
10458 
10459 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10460 /* ARGSUSED */
10461 static int
10462 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10463 {
10464 	long		new_value;
10465 	ipparam_t	*ippa = (ipparam_t *)cp;
10466 
10467 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10468 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10469 		return (EINVAL);
10470 	}
10471 	ippa->ip_param_value = new_value;
10472 	return (0);
10473 }
10474 
10475 /*
10476  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10477  * When an ipf is passed here for the first time, if
10478  * we already have in-order fragments on the queue, we convert from the fast-
10479  * path reassembly scheme to the hard-case scheme.  From then on, additional
10480  * fragments are reassembled here.  We keep track of the start and end offsets
10481  * of each piece, and the number of holes in the chain.  When the hole count
10482  * goes to zero, we are done!
10483  *
10484  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10485  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10486  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10487  * after the call to ip_reassemble().
10488  */
10489 int
10490 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10491     size_t msg_len)
10492 {
10493 	uint_t	end;
10494 	mblk_t	*next_mp;
10495 	mblk_t	*mp1;
10496 	uint_t	offset;
10497 	boolean_t incr_dups = B_TRUE;
10498 	boolean_t offset_zero_seen = B_FALSE;
10499 	boolean_t pkt_boundary_checked = B_FALSE;
10500 
10501 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10502 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10503 
10504 	/* Add in byte count */
10505 	ipf->ipf_count += msg_len;
10506 	if (ipf->ipf_end) {
10507 		/*
10508 		 * We were part way through in-order reassembly, but now there
10509 		 * is a hole.  We walk through messages already queued, and
10510 		 * mark them for hard case reassembly.  We know that up till
10511 		 * now they were in order starting from offset zero.
10512 		 */
10513 		offset = 0;
10514 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10515 			IP_REASS_SET_START(mp1, offset);
10516 			if (offset == 0) {
10517 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10518 				offset = -ipf->ipf_nf_hdr_len;
10519 			}
10520 			offset += mp1->b_wptr - mp1->b_rptr;
10521 			IP_REASS_SET_END(mp1, offset);
10522 		}
10523 		/* One hole at the end. */
10524 		ipf->ipf_hole_cnt = 1;
10525 		/* Brand it as a hard case, forever. */
10526 		ipf->ipf_end = 0;
10527 	}
10528 	/* Walk through all the new pieces. */
10529 	do {
10530 		end = start + (mp->b_wptr - mp->b_rptr);
10531 		/*
10532 		 * If start is 0, decrease 'end' only for the first mblk of
10533 		 * the fragment. Otherwise 'end' can get wrong value in the
10534 		 * second pass of the loop if first mblk is exactly the
10535 		 * size of ipf_nf_hdr_len.
10536 		 */
10537 		if (start == 0 && !offset_zero_seen) {
10538 			/* First segment */
10539 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10540 			end -= ipf->ipf_nf_hdr_len;
10541 			offset_zero_seen = B_TRUE;
10542 		}
10543 		next_mp = mp->b_cont;
10544 		/*
10545 		 * We are checking to see if there is any interesing data
10546 		 * to process.  If there isn't and the mblk isn't the
10547 		 * one which carries the unfragmentable header then we
10548 		 * drop it.  It's possible to have just the unfragmentable
10549 		 * header come through without any data.  That needs to be
10550 		 * saved.
10551 		 *
10552 		 * If the assert at the top of this function holds then the
10553 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10554 		 * is infrequently traveled enough that the test is left in
10555 		 * to protect against future code changes which break that
10556 		 * invariant.
10557 		 */
10558 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10559 			/* Empty.  Blast it. */
10560 			IP_REASS_SET_START(mp, 0);
10561 			IP_REASS_SET_END(mp, 0);
10562 			/*
10563 			 * If the ipf points to the mblk we are about to free,
10564 			 * update ipf to point to the next mblk (or NULL
10565 			 * if none).
10566 			 */
10567 			if (ipf->ipf_mp->b_cont == mp)
10568 				ipf->ipf_mp->b_cont = next_mp;
10569 			freeb(mp);
10570 			continue;
10571 		}
10572 		mp->b_cont = NULL;
10573 		IP_REASS_SET_START(mp, start);
10574 		IP_REASS_SET_END(mp, end);
10575 		if (!ipf->ipf_tail_mp) {
10576 			ipf->ipf_tail_mp = mp;
10577 			ipf->ipf_mp->b_cont = mp;
10578 			if (start == 0 || !more) {
10579 				ipf->ipf_hole_cnt = 1;
10580 				/*
10581 				 * if the first fragment comes in more than one
10582 				 * mblk, this loop will be executed for each
10583 				 * mblk. Need to adjust hole count so exiting
10584 				 * this routine will leave hole count at 1.
10585 				 */
10586 				if (next_mp)
10587 					ipf->ipf_hole_cnt++;
10588 			} else
10589 				ipf->ipf_hole_cnt = 2;
10590 			continue;
10591 		} else if (ipf->ipf_last_frag_seen && !more &&
10592 			    !pkt_boundary_checked) {
10593 			/*
10594 			 * We check datagram boundary only if this fragment
10595 			 * claims to be the last fragment and we have seen a
10596 			 * last fragment in the past too. We do this only
10597 			 * once for a given fragment.
10598 			 *
10599 			 * start cannot be 0 here as fragments with start=0
10600 			 * and MF=0 gets handled as a complete packet. These
10601 			 * fragments should not reach here.
10602 			 */
10603 
10604 			if (start + msgdsize(mp) !=
10605 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10606 				/*
10607 				 * We have two fragments both of which claim
10608 				 * to be the last fragment but gives conflicting
10609 				 * information about the whole datagram size.
10610 				 * Something fishy is going on. Drop the
10611 				 * fragment and free up the reassembly list.
10612 				 */
10613 				return (IP_REASS_FAILED);
10614 			}
10615 
10616 			/*
10617 			 * We shouldn't come to this code block again for this
10618 			 * particular fragment.
10619 			 */
10620 			pkt_boundary_checked = B_TRUE;
10621 		}
10622 
10623 		/* New stuff at or beyond tail? */
10624 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10625 		if (start >= offset) {
10626 			if (ipf->ipf_last_frag_seen) {
10627 				/* current fragment is beyond last fragment */
10628 				return (IP_REASS_FAILED);
10629 			}
10630 			/* Link it on end. */
10631 			ipf->ipf_tail_mp->b_cont = mp;
10632 			ipf->ipf_tail_mp = mp;
10633 			if (more) {
10634 				if (start != offset)
10635 					ipf->ipf_hole_cnt++;
10636 			} else if (start == offset && next_mp == NULL)
10637 					ipf->ipf_hole_cnt--;
10638 			continue;
10639 		}
10640 		mp1 = ipf->ipf_mp->b_cont;
10641 		offset = IP_REASS_START(mp1);
10642 		/* New stuff at the front? */
10643 		if (start < offset) {
10644 			if (start == 0) {
10645 				if (end >= offset) {
10646 					/* Nailed the hole at the begining. */
10647 					ipf->ipf_hole_cnt--;
10648 				}
10649 			} else if (end < offset) {
10650 				/*
10651 				 * A hole, stuff, and a hole where there used
10652 				 * to be just a hole.
10653 				 */
10654 				ipf->ipf_hole_cnt++;
10655 			}
10656 			mp->b_cont = mp1;
10657 			/* Check for overlap. */
10658 			while (end > offset) {
10659 				if (end < IP_REASS_END(mp1)) {
10660 					mp->b_wptr -= end - offset;
10661 					IP_REASS_SET_END(mp, offset);
10662 					if (ill->ill_isv6) {
10663 						BUMP_MIB(ill->ill_ip6_mib,
10664 						    ipv6ReasmPartDups);
10665 					} else {
10666 						BUMP_MIB(&ip_mib,
10667 						    ipReasmPartDups);
10668 					}
10669 					break;
10670 				}
10671 				/* Did we cover another hole? */
10672 				if ((mp1->b_cont &&
10673 				    IP_REASS_END(mp1) !=
10674 				    IP_REASS_START(mp1->b_cont) &&
10675 				    end >= IP_REASS_START(mp1->b_cont)) ||
10676 				    (!ipf->ipf_last_frag_seen && !more)) {
10677 					ipf->ipf_hole_cnt--;
10678 				}
10679 				/* Clip out mp1. */
10680 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10681 					/*
10682 					 * After clipping out mp1, this guy
10683 					 * is now hanging off the end.
10684 					 */
10685 					ipf->ipf_tail_mp = mp;
10686 				}
10687 				IP_REASS_SET_START(mp1, 0);
10688 				IP_REASS_SET_END(mp1, 0);
10689 				/* Subtract byte count */
10690 				ipf->ipf_count -= mp1->b_datap->db_lim -
10691 				    mp1->b_datap->db_base;
10692 				freeb(mp1);
10693 				if (ill->ill_isv6) {
10694 					BUMP_MIB(ill->ill_ip6_mib,
10695 					    ipv6ReasmPartDups);
10696 				} else {
10697 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10698 				}
10699 				mp1 = mp->b_cont;
10700 				if (!mp1)
10701 					break;
10702 				offset = IP_REASS_START(mp1);
10703 			}
10704 			ipf->ipf_mp->b_cont = mp;
10705 			continue;
10706 		}
10707 		/*
10708 		 * The new piece starts somewhere between the start of the head
10709 		 * and before the end of the tail.
10710 		 */
10711 		for (; mp1; mp1 = mp1->b_cont) {
10712 			offset = IP_REASS_END(mp1);
10713 			if (start < offset) {
10714 				if (end <= offset) {
10715 					/* Nothing new. */
10716 					IP_REASS_SET_START(mp, 0);
10717 					IP_REASS_SET_END(mp, 0);
10718 					/* Subtract byte count */
10719 					ipf->ipf_count -= mp->b_datap->db_lim -
10720 					    mp->b_datap->db_base;
10721 					if (incr_dups) {
10722 						ipf->ipf_num_dups++;
10723 						incr_dups = B_FALSE;
10724 					}
10725 					freeb(mp);
10726 					if (ill->ill_isv6) {
10727 						BUMP_MIB(ill->ill_ip6_mib,
10728 						    ipv6ReasmDuplicates);
10729 					} else {
10730 						BUMP_MIB(&ip_mib,
10731 						    ipReasmDuplicates);
10732 					}
10733 					break;
10734 				}
10735 				/*
10736 				 * Trim redundant stuff off beginning of new
10737 				 * piece.
10738 				 */
10739 				IP_REASS_SET_START(mp, offset);
10740 				mp->b_rptr += offset - start;
10741 				if (ill->ill_isv6) {
10742 					BUMP_MIB(ill->ill_ip6_mib,
10743 					    ipv6ReasmPartDups);
10744 				} else {
10745 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10746 				}
10747 				start = offset;
10748 				if (!mp1->b_cont) {
10749 					/*
10750 					 * After trimming, this guy is now
10751 					 * hanging off the end.
10752 					 */
10753 					mp1->b_cont = mp;
10754 					ipf->ipf_tail_mp = mp;
10755 					if (!more) {
10756 						ipf->ipf_hole_cnt--;
10757 					}
10758 					break;
10759 				}
10760 			}
10761 			if (start >= IP_REASS_START(mp1->b_cont))
10762 				continue;
10763 			/* Fill a hole */
10764 			if (start > offset)
10765 				ipf->ipf_hole_cnt++;
10766 			mp->b_cont = mp1->b_cont;
10767 			mp1->b_cont = mp;
10768 			mp1 = mp->b_cont;
10769 			offset = IP_REASS_START(mp1);
10770 			if (end >= offset) {
10771 				ipf->ipf_hole_cnt--;
10772 				/* Check for overlap. */
10773 				while (end > offset) {
10774 					if (end < IP_REASS_END(mp1)) {
10775 						mp->b_wptr -= end - offset;
10776 						IP_REASS_SET_END(mp, offset);
10777 						/*
10778 						 * TODO we might bump
10779 						 * this up twice if there is
10780 						 * overlap at both ends.
10781 						 */
10782 						if (ill->ill_isv6) {
10783 							BUMP_MIB(
10784 							    ill->ill_ip6_mib,
10785 							    ipv6ReasmPartDups);
10786 						} else {
10787 							BUMP_MIB(&ip_mib,
10788 							    ipReasmPartDups);
10789 						}
10790 						break;
10791 					}
10792 					/* Did we cover another hole? */
10793 					if ((mp1->b_cont &&
10794 					    IP_REASS_END(mp1)
10795 					    != IP_REASS_START(mp1->b_cont) &&
10796 					    end >=
10797 					    IP_REASS_START(mp1->b_cont)) ||
10798 					    (!ipf->ipf_last_frag_seen &&
10799 					    !more)) {
10800 						ipf->ipf_hole_cnt--;
10801 					}
10802 					/* Clip out mp1. */
10803 					if ((mp->b_cont = mp1->b_cont) ==
10804 					    NULL) {
10805 						/*
10806 						 * After clipping out mp1,
10807 						 * this guy is now hanging
10808 						 * off the end.
10809 						 */
10810 						ipf->ipf_tail_mp = mp;
10811 					}
10812 					IP_REASS_SET_START(mp1, 0);
10813 					IP_REASS_SET_END(mp1, 0);
10814 					/* Subtract byte count */
10815 					ipf->ipf_count -=
10816 					    mp1->b_datap->db_lim -
10817 					    mp1->b_datap->db_base;
10818 					freeb(mp1);
10819 					if (ill->ill_isv6) {
10820 						BUMP_MIB(ill->ill_ip6_mib,
10821 						    ipv6ReasmPartDups);
10822 					} else {
10823 						BUMP_MIB(&ip_mib,
10824 						    ipReasmPartDups);
10825 					}
10826 					mp1 = mp->b_cont;
10827 					if (!mp1)
10828 						break;
10829 					offset = IP_REASS_START(mp1);
10830 				}
10831 			}
10832 			break;
10833 		}
10834 	} while (start = end, mp = next_mp);
10835 
10836 	/* Fragment just processed could be the last one. Remember this fact */
10837 	if (!more)
10838 		ipf->ipf_last_frag_seen = B_TRUE;
10839 
10840 	/* Still got holes? */
10841 	if (ipf->ipf_hole_cnt)
10842 		return (IP_REASS_PARTIAL);
10843 	/* Clean up overloaded fields to avoid upstream disasters. */
10844 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10845 		IP_REASS_SET_START(mp1, 0);
10846 		IP_REASS_SET_END(mp1, 0);
10847 	}
10848 	return (IP_REASS_COMPLETE);
10849 }
10850 
10851 /*
10852  * ipsec processing for the fast path, used for input UDP Packets
10853  */
10854 static boolean_t
10855 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10856     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10857 {
10858 	uint32_t	ill_index;
10859 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10860 
10861 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10862 	/* The ill_index of the incoming ILL */
10863 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10864 
10865 	/* pass packet up to the transport */
10866 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10867 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10868 		    NULL, mctl_present);
10869 		if (*first_mpp == NULL) {
10870 			return (B_FALSE);
10871 		}
10872 	}
10873 
10874 	/* Initiate IPPF processing for fastpath UDP */
10875 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10876 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10877 		if (*mpp == NULL) {
10878 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10879 			    "deferred/dropped during IPPF processing\n"));
10880 			return (B_FALSE);
10881 		}
10882 	}
10883 	/*
10884 	 * We make the checks as below since we are in the fast path
10885 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10886 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10887 	 */
10888 	if (connp->conn_recvif || connp->conn_recvslla ||
10889 	    connp->conn_ipv6_recvpktinfo) {
10890 		if (connp->conn_recvif ||
10891 		    connp->conn_ipv6_recvpktinfo) {
10892 			in_flags = IPF_RECVIF;
10893 		}
10894 		if (connp->conn_recvslla) {
10895 			in_flags |= IPF_RECVSLLA;
10896 		}
10897 		/*
10898 		 * since in_flags are being set ill will be
10899 		 * referenced in ip_add_info, so it better not
10900 		 * be NULL.
10901 		 */
10902 		/*
10903 		 * the actual data will be contained in b_cont
10904 		 * upon successful return of the following call.
10905 		 * If the call fails then the original mblk is
10906 		 * returned.
10907 		 */
10908 		*mpp = ip_add_info(*mpp, ill, in_flags);
10909 	}
10910 
10911 	return (B_TRUE);
10912 }
10913 
10914 /*
10915  * Fragmentation reassembly.  Each ILL has a hash table for
10916  * queuing packets undergoing reassembly for all IPIFs
10917  * associated with the ILL.  The hash is based on the packet
10918  * IP ident field.  The ILL frag hash table was allocated
10919  * as a timer block at the time the ILL was created.  Whenever
10920  * there is anything on the reassembly queue, the timer will
10921  * be running.  Returns B_TRUE if successful else B_FALSE;
10922  * frees mp on failure.
10923  */
10924 static boolean_t
10925 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
10926     uint32_t *cksum_val, uint16_t *cksum_flags)
10927 {
10928 	uint32_t	frag_offset_flags;
10929 	ill_t		*ill = (ill_t *)q->q_ptr;
10930 	mblk_t		*mp = *mpp;
10931 	mblk_t		*t_mp;
10932 	ipaddr_t	dst;
10933 	uint8_t		proto = ipha->ipha_protocol;
10934 	uint32_t	sum_val;
10935 	uint16_t	sum_flags;
10936 	ipf_t		*ipf;
10937 	ipf_t		**ipfp;
10938 	ipfb_t		*ipfb;
10939 	uint16_t	ident;
10940 	uint32_t	offset;
10941 	ipaddr_t	src;
10942 	uint_t		hdr_length;
10943 	uint32_t	end;
10944 	mblk_t		*mp1;
10945 	mblk_t		*tail_mp;
10946 	size_t		count;
10947 	size_t		msg_len;
10948 	uint8_t		ecn_info = 0;
10949 	uint32_t	packet_size;
10950 	boolean_t	pruned = B_FALSE;
10951 
10952 	if (cksum_val != NULL)
10953 		*cksum_val = 0;
10954 	if (cksum_flags != NULL)
10955 		*cksum_flags = 0;
10956 
10957 	/*
10958 	 * Drop the fragmented as early as possible, if
10959 	 * we don't have resource(s) to re-assemble.
10960 	 */
10961 	if (ip_reass_queue_bytes == 0) {
10962 		freemsg(mp);
10963 		return (B_FALSE);
10964 	}
10965 
10966 	/* Check for fragmentation offset; return if there's none */
10967 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
10968 	    (IPH_MF | IPH_OFFSET)) == 0)
10969 		return (B_TRUE);
10970 
10971 	/*
10972 	 * We utilize hardware computed checksum info only for UDP since
10973 	 * IP fragmentation is a normal occurence for the protocol.  In
10974 	 * addition, checksum offload support for IP fragments carrying
10975 	 * UDP payload is commonly implemented across network adapters.
10976 	 */
10977 	ASSERT(ill != NULL);
10978 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
10979 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
10980 		mblk_t *mp1 = mp->b_cont;
10981 		int32_t len;
10982 
10983 		/* Record checksum information from the packet */
10984 		sum_val = (uint32_t)DB_CKSUM16(mp);
10985 		sum_flags = DB_CKSUMFLAGS(mp);
10986 
10987 		/* IP payload offset from beginning of mblk */
10988 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
10989 
10990 		if ((sum_flags & HCK_PARTIALCKSUM) &&
10991 		    (mp1 == NULL || mp1->b_cont == NULL) &&
10992 		    offset >= DB_CKSUMSTART(mp) &&
10993 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
10994 			uint32_t adj;
10995 			/*
10996 			 * Partial checksum has been calculated by hardware
10997 			 * and attached to the packet; in addition, any
10998 			 * prepended extraneous data is even byte aligned.
10999 			 * If any such data exists, we adjust the checksum;
11000 			 * this would also handle any postpended data.
11001 			 */
11002 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11003 			    mp, mp1, len, adj);
11004 
11005 			/* One's complement subtract extraneous checksum */
11006 			if (adj >= sum_val)
11007 				sum_val = ~(adj - sum_val) & 0xFFFF;
11008 			else
11009 				sum_val -= adj;
11010 		}
11011 	} else {
11012 		sum_val = 0;
11013 		sum_flags = 0;
11014 	}
11015 
11016 	/* Clear hardware checksumming flag */
11017 	DB_CKSUMFLAGS(mp) = 0;
11018 
11019 	ident = ipha->ipha_ident;
11020 	offset = (frag_offset_flags << 3) & 0xFFFF;
11021 	src = ipha->ipha_src;
11022 	dst = ipha->ipha_dst;
11023 	hdr_length = IPH_HDR_LENGTH(ipha);
11024 	end = ntohs(ipha->ipha_length) - hdr_length;
11025 
11026 	/* If end == 0 then we have a packet with no data, so just free it */
11027 	if (end == 0) {
11028 		freemsg(mp);
11029 		return (B_FALSE);
11030 	}
11031 
11032 	/* Record the ECN field info. */
11033 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11034 	if (offset != 0) {
11035 		/*
11036 		 * If this isn't the first piece, strip the header, and
11037 		 * add the offset to the end value.
11038 		 */
11039 		mp->b_rptr += hdr_length;
11040 		end += offset;
11041 	}
11042 
11043 	msg_len = MBLKSIZE(mp);
11044 	tail_mp = mp;
11045 	while (tail_mp->b_cont != NULL) {
11046 		tail_mp = tail_mp->b_cont;
11047 		msg_len += MBLKSIZE(tail_mp);
11048 	}
11049 
11050 	/* If the reassembly list for this ILL will get too big, prune it */
11051 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11052 	    ip_reass_queue_bytes) {
11053 		ill_frag_prune(ill,
11054 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11055 		    (ip_reass_queue_bytes - msg_len));
11056 		pruned = B_TRUE;
11057 	}
11058 
11059 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11060 	mutex_enter(&ipfb->ipfb_lock);
11061 
11062 	ipfp = &ipfb->ipfb_ipf;
11063 	/* Try to find an existing fragment queue for this packet. */
11064 	for (;;) {
11065 		ipf = ipfp[0];
11066 		if (ipf != NULL) {
11067 			/*
11068 			 * It has to match on ident and src/dst address.
11069 			 */
11070 			if (ipf->ipf_ident == ident &&
11071 			    ipf->ipf_src == src &&
11072 			    ipf->ipf_dst == dst &&
11073 			    ipf->ipf_protocol == proto) {
11074 				/*
11075 				 * If we have received too many
11076 				 * duplicate fragments for this packet
11077 				 * free it.
11078 				 */
11079 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11080 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11081 					freemsg(mp);
11082 					mutex_exit(&ipfb->ipfb_lock);
11083 					return (B_FALSE);
11084 				}
11085 				/* Found it. */
11086 				break;
11087 			}
11088 			ipfp = &ipf->ipf_hash_next;
11089 			continue;
11090 		}
11091 
11092 		/*
11093 		 * If we pruned the list, do we want to store this new
11094 		 * fragment?. We apply an optimization here based on the
11095 		 * fact that most fragments will be received in order.
11096 		 * So if the offset of this incoming fragment is zero,
11097 		 * it is the first fragment of a new packet. We will
11098 		 * keep it.  Otherwise drop the fragment, as we have
11099 		 * probably pruned the packet already (since the
11100 		 * packet cannot be found).
11101 		 */
11102 		if (pruned && offset != 0) {
11103 			mutex_exit(&ipfb->ipfb_lock);
11104 			freemsg(mp);
11105 			return (B_FALSE);
11106 		}
11107 
11108 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11109 			/*
11110 			 * Too many fragmented packets in this hash
11111 			 * bucket. Free the oldest.
11112 			 */
11113 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11114 		}
11115 
11116 		/* New guy.  Allocate a frag message. */
11117 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11118 		if (mp1 == NULL) {
11119 			BUMP_MIB(&ip_mib, ipInDiscards);
11120 			freemsg(mp);
11121 reass_done:
11122 			mutex_exit(&ipfb->ipfb_lock);
11123 			return (B_FALSE);
11124 		}
11125 
11126 
11127 		BUMP_MIB(&ip_mib, ipReasmReqds);
11128 		mp1->b_cont = mp;
11129 
11130 		/* Initialize the fragment header. */
11131 		ipf = (ipf_t *)mp1->b_rptr;
11132 		ipf->ipf_mp = mp1;
11133 		ipf->ipf_ptphn = ipfp;
11134 		ipfp[0] = ipf;
11135 		ipf->ipf_hash_next = NULL;
11136 		ipf->ipf_ident = ident;
11137 		ipf->ipf_protocol = proto;
11138 		ipf->ipf_src = src;
11139 		ipf->ipf_dst = dst;
11140 		ipf->ipf_nf_hdr_len = 0;
11141 		/* Record reassembly start time. */
11142 		ipf->ipf_timestamp = gethrestime_sec();
11143 		/* Record ipf generation and account for frag header */
11144 		ipf->ipf_gen = ill->ill_ipf_gen++;
11145 		ipf->ipf_count = MBLKSIZE(mp1);
11146 		ipf->ipf_last_frag_seen = B_FALSE;
11147 		ipf->ipf_ecn = ecn_info;
11148 		ipf->ipf_num_dups = 0;
11149 		ipfb->ipfb_frag_pkts++;
11150 		ipf->ipf_checksum = 0;
11151 		ipf->ipf_checksum_flags = 0;
11152 
11153 		/* Store checksum value in fragment header */
11154 		if (sum_flags != 0) {
11155 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11156 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11157 			ipf->ipf_checksum = sum_val;
11158 			ipf->ipf_checksum_flags = sum_flags;
11159 		}
11160 
11161 		/*
11162 		 * We handle reassembly two ways.  In the easy case,
11163 		 * where all the fragments show up in order, we do
11164 		 * minimal bookkeeping, and just clip new pieces on
11165 		 * the end.  If we ever see a hole, then we go off
11166 		 * to ip_reassemble which has to mark the pieces and
11167 		 * keep track of the number of holes, etc.  Obviously,
11168 		 * the point of having both mechanisms is so we can
11169 		 * handle the easy case as efficiently as possible.
11170 		 */
11171 		if (offset == 0) {
11172 			/* Easy case, in-order reassembly so far. */
11173 			ipf->ipf_count += msg_len;
11174 			ipf->ipf_tail_mp = tail_mp;
11175 			/*
11176 			 * Keep track of next expected offset in
11177 			 * ipf_end.
11178 			 */
11179 			ipf->ipf_end = end;
11180 			ipf->ipf_nf_hdr_len = hdr_length;
11181 		} else {
11182 			/* Hard case, hole at the beginning. */
11183 			ipf->ipf_tail_mp = NULL;
11184 			/*
11185 			 * ipf_end == 0 means that we have given up
11186 			 * on easy reassembly.
11187 			 */
11188 			ipf->ipf_end = 0;
11189 
11190 			/* Forget checksum offload from now on */
11191 			ipf->ipf_checksum_flags = 0;
11192 
11193 			/*
11194 			 * ipf_hole_cnt is set by ip_reassemble.
11195 			 * ipf_count is updated by ip_reassemble.
11196 			 * No need to check for return value here
11197 			 * as we don't expect reassembly to complete
11198 			 * or fail for the first fragment itself.
11199 			 */
11200 			(void) ip_reassemble(mp, ipf,
11201 			    (frag_offset_flags & IPH_OFFSET) << 3,
11202 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11203 		}
11204 		/* Update per ipfb and ill byte counts */
11205 		ipfb->ipfb_count += ipf->ipf_count;
11206 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11207 		ill->ill_frag_count += ipf->ipf_count;
11208 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11209 		/* If the frag timer wasn't already going, start it. */
11210 		mutex_enter(&ill->ill_lock);
11211 		ill_frag_timer_start(ill);
11212 		mutex_exit(&ill->ill_lock);
11213 		goto reass_done;
11214 	}
11215 
11216 	/*
11217 	 * If the packet's flag has changed (it could be coming up
11218 	 * from an interface different than the previous, therefore
11219 	 * possibly different checksum capability), then forget about
11220 	 * any stored checksum states.  Otherwise add the value to
11221 	 * the existing one stored in the fragment header.
11222 	 */
11223 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11224 		sum_val += ipf->ipf_checksum;
11225 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11226 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11227 		ipf->ipf_checksum = sum_val;
11228 	} else if (ipf->ipf_checksum_flags != 0) {
11229 		/* Forget checksum offload from now on */
11230 		ipf->ipf_checksum_flags = 0;
11231 	}
11232 
11233 	/*
11234 	 * We have a new piece of a datagram which is already being
11235 	 * reassembled.  Update the ECN info if all IP fragments
11236 	 * are ECN capable.  If there is one which is not, clear
11237 	 * all the info.  If there is at least one which has CE
11238 	 * code point, IP needs to report that up to transport.
11239 	 */
11240 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11241 		if (ecn_info == IPH_ECN_CE)
11242 			ipf->ipf_ecn = IPH_ECN_CE;
11243 	} else {
11244 		ipf->ipf_ecn = IPH_ECN_NECT;
11245 	}
11246 	if (offset && ipf->ipf_end == offset) {
11247 		/* The new fragment fits at the end */
11248 		ipf->ipf_tail_mp->b_cont = mp;
11249 		/* Update the byte count */
11250 		ipf->ipf_count += msg_len;
11251 		/* Update per ipfb and ill byte counts */
11252 		ipfb->ipfb_count += msg_len;
11253 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11254 		ill->ill_frag_count += msg_len;
11255 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11256 		if (frag_offset_flags & IPH_MF) {
11257 			/* More to come. */
11258 			ipf->ipf_end = end;
11259 			ipf->ipf_tail_mp = tail_mp;
11260 			goto reass_done;
11261 		}
11262 	} else {
11263 		/* Go do the hard cases. */
11264 		int ret;
11265 
11266 		if (offset == 0)
11267 			ipf->ipf_nf_hdr_len = hdr_length;
11268 
11269 		/* Save current byte count */
11270 		count = ipf->ipf_count;
11271 		ret = ip_reassemble(mp, ipf,
11272 		    (frag_offset_flags & IPH_OFFSET) << 3,
11273 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11274 		/* Count of bytes added and subtracted (freeb()ed) */
11275 		count = ipf->ipf_count - count;
11276 		if (count) {
11277 			/* Update per ipfb and ill byte counts */
11278 			ipfb->ipfb_count += count;
11279 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11280 			ill->ill_frag_count += count;
11281 			ASSERT(ill->ill_frag_count > 0);
11282 		}
11283 		if (ret == IP_REASS_PARTIAL) {
11284 			goto reass_done;
11285 		} else if (ret == IP_REASS_FAILED) {
11286 			/* Reassembly failed. Free up all resources */
11287 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11288 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11289 				IP_REASS_SET_START(t_mp, 0);
11290 				IP_REASS_SET_END(t_mp, 0);
11291 			}
11292 			freemsg(mp);
11293 			goto reass_done;
11294 		}
11295 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11296 	}
11297 	/*
11298 	 * We have completed reassembly.  Unhook the frag header from
11299 	 * the reassembly list.
11300 	 *
11301 	 * Before we free the frag header, record the ECN info
11302 	 * to report back to the transport.
11303 	 */
11304 	ecn_info = ipf->ipf_ecn;
11305 	BUMP_MIB(&ip_mib, ipReasmOKs);
11306 	ipfp = ipf->ipf_ptphn;
11307 
11308 	/* We need to supply these to caller */
11309 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11310 		sum_val = ipf->ipf_checksum;
11311 	else
11312 		sum_val = 0;
11313 
11314 	mp1 = ipf->ipf_mp;
11315 	count = ipf->ipf_count;
11316 	ipf = ipf->ipf_hash_next;
11317 	if (ipf != NULL)
11318 		ipf->ipf_ptphn = ipfp;
11319 	ipfp[0] = ipf;
11320 	ill->ill_frag_count -= count;
11321 	ASSERT(ipfb->ipfb_count >= count);
11322 	ipfb->ipfb_count -= count;
11323 	ipfb->ipfb_frag_pkts--;
11324 	mutex_exit(&ipfb->ipfb_lock);
11325 	/* Ditch the frag header. */
11326 	mp = mp1->b_cont;
11327 
11328 	freeb(mp1);
11329 
11330 	/* Restore original IP length in header. */
11331 	packet_size = (uint32_t)msgdsize(mp);
11332 	if (packet_size > IP_MAXPACKET) {
11333 		freemsg(mp);
11334 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11335 		return (B_FALSE);
11336 	}
11337 
11338 	if (DB_REF(mp) > 1) {
11339 		mblk_t *mp2 = copymsg(mp);
11340 
11341 		freemsg(mp);
11342 		if (mp2 == NULL) {
11343 			BUMP_MIB(&ip_mib, ipInDiscards);
11344 			return (B_FALSE);
11345 		}
11346 		mp = mp2;
11347 	}
11348 	ipha = (ipha_t *)mp->b_rptr;
11349 
11350 	ipha->ipha_length = htons((uint16_t)packet_size);
11351 	/* We're now complete, zip the frag state */
11352 	ipha->ipha_fragment_offset_and_flags = 0;
11353 	/* Record the ECN info. */
11354 	ipha->ipha_type_of_service &= 0xFC;
11355 	ipha->ipha_type_of_service |= ecn_info;
11356 	*mpp = mp;
11357 
11358 	/* Reassembly is successful; return checksum information if needed */
11359 	if (cksum_val != NULL)
11360 		*cksum_val = sum_val;
11361 	if (cksum_flags != NULL)
11362 		*cksum_flags = sum_flags;
11363 
11364 	return (B_TRUE);
11365 }
11366 
11367 /*
11368  * Perform ip header check sum update local options.
11369  * return B_TRUE if all is well, else return B_FALSE and release
11370  * the mp. caller is responsible for decrementing ire ref cnt.
11371  */
11372 static boolean_t
11373 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11374 {
11375 	mblk_t		*first_mp;
11376 	boolean_t	mctl_present;
11377 	uint16_t	sum;
11378 
11379 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11380 	/*
11381 	 * Don't do the checksum if it has gone through AH/ESP
11382 	 * processing.
11383 	 */
11384 	if (!mctl_present) {
11385 		sum = ip_csum_hdr(ipha);
11386 		if (sum != 0) {
11387 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11388 			freemsg(first_mp);
11389 			return (B_FALSE);
11390 		}
11391 	}
11392 
11393 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11394 		if (mctl_present)
11395 			freeb(first_mp);
11396 		return (B_FALSE);
11397 	}
11398 
11399 	return (B_TRUE);
11400 }
11401 
11402 /*
11403  * All udp packet are delivered to the local host via this routine.
11404  */
11405 void
11406 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11407     ill_t *recv_ill)
11408 {
11409 	uint32_t	sum;
11410 	uint32_t	u1;
11411 	boolean_t	mctl_present;
11412 	conn_t		*connp;
11413 	mblk_t		*first_mp;
11414 	uint16_t	*up;
11415 	ill_t		*ill = (ill_t *)q->q_ptr;
11416 	uint16_t	reass_hck_flags = 0;
11417 
11418 #define	rptr    ((uchar_t *)ipha)
11419 
11420 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11421 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11422 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11423 
11424 	/*
11425 	 * FAST PATH for udp packets
11426 	 */
11427 
11428 	/* u1 is # words of IP options */
11429 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11430 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11431 
11432 	/* IP options present */
11433 	if (u1 != 0)
11434 		goto ipoptions;
11435 
11436 	/* Check the IP header checksum.  */
11437 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11438 		/* Clear the IP header h/w cksum flag */
11439 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11440 	} else {
11441 #define	uph	((uint16_t *)ipha)
11442 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11443 		    uph[6] + uph[7] + uph[8] + uph[9];
11444 #undef	uph
11445 		/* finish doing IP checksum */
11446 		sum = (sum & 0xFFFF) + (sum >> 16);
11447 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11448 		/*
11449 		 * Don't verify header checksum if this packet is coming
11450 		 * back from AH/ESP as we already did it.
11451 		 */
11452 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
11453 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11454 			freemsg(first_mp);
11455 			return;
11456 		}
11457 	}
11458 
11459 	/*
11460 	 * Count for SNMP of inbound packets for ire.
11461 	 * if mctl is present this might be a secure packet and
11462 	 * has already been counted for in ip_proto_input().
11463 	 */
11464 	if (!mctl_present) {
11465 		UPDATE_IB_PKT_COUNT(ire);
11466 		ire->ire_last_used_time = lbolt;
11467 	}
11468 
11469 	/* packet part of fragmented IP packet? */
11470 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11471 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11472 		goto fragmented;
11473 	}
11474 
11475 	/* u1 = IP header length (20 bytes) */
11476 	u1 = IP_SIMPLE_HDR_LENGTH;
11477 
11478 	/* packet does not contain complete IP & UDP headers */
11479 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11480 		goto udppullup;
11481 
11482 	/* up points to UDP header */
11483 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11484 #define	iphs    ((uint16_t *)ipha)
11485 
11486 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11487 	if (up[3] != 0) {
11488 		mblk_t *mp1 = mp->b_cont;
11489 		boolean_t cksum_err;
11490 		uint16_t hck_flags = 0;
11491 
11492 		/* Pseudo-header checksum */
11493 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11494 		    iphs[9] + up[2];
11495 
11496 		/*
11497 		 * Revert to software checksum calculation if the interface
11498 		 * isn't capable of checksum offload or if IPsec is present.
11499 		 */
11500 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11501 			hck_flags = DB_CKSUMFLAGS(mp);
11502 
11503 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11504 			IP_STAT(ip_in_sw_cksum);
11505 
11506 		IP_CKSUM_RECV(hck_flags, u1,
11507 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11508 		    (int32_t)((uchar_t *)up - rptr),
11509 		    mp, mp1, cksum_err);
11510 
11511 		if (cksum_err) {
11512 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11513 
11514 			if (hck_flags & HCK_FULLCKSUM)
11515 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11516 			else if (hck_flags & HCK_PARTIALCKSUM)
11517 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11518 			else
11519 				IP_STAT(ip_udp_in_sw_cksum_err);
11520 
11521 			freemsg(first_mp);
11522 			return;
11523 		}
11524 	}
11525 
11526 	/* Non-fragmented broadcast or multicast packet? */
11527 	if (ire->ire_type == IRE_BROADCAST)
11528 		goto udpslowpath;
11529 
11530 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11531 	    ire->ire_zoneid)) != NULL) {
11532 		ASSERT(connp->conn_upq != NULL);
11533 		IP_STAT(ip_udp_fast_path);
11534 
11535 		if (CONN_UDP_FLOWCTLD(connp)) {
11536 			freemsg(mp);
11537 			BUMP_MIB(&ip_mib, udpInOverflows);
11538 		} else {
11539 			if (!mctl_present) {
11540 				BUMP_MIB(&ip_mib, ipInDelivers);
11541 			}
11542 			/*
11543 			 * mp and first_mp can change.
11544 			 */
11545 			if (ip_udp_check(q, connp, recv_ill,
11546 			    ipha, &mp, &first_mp, mctl_present)) {
11547 				/* Send it upstream */
11548 				CONN_UDP_RECV(connp, mp);
11549 			}
11550 		}
11551 		/*
11552 		 * freeb() cannot deal with null mblk being passed
11553 		 * in and first_mp can be set to null in the call
11554 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11555 		 */
11556 		if (mctl_present && first_mp != NULL) {
11557 			freeb(first_mp);
11558 		}
11559 		CONN_DEC_REF(connp);
11560 		return;
11561 	}
11562 
11563 	/*
11564 	 * if we got here we know the packet is not fragmented and
11565 	 * has no options. The classifier could not find a conn_t and
11566 	 * most likely its an icmp packet so send it through slow path.
11567 	 */
11568 
11569 	goto udpslowpath;
11570 
11571 ipoptions:
11572 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11573 		goto slow_done;
11574 	}
11575 
11576 	UPDATE_IB_PKT_COUNT(ire);
11577 	ire->ire_last_used_time = lbolt;
11578 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11579 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11580 fragmented:
11581 		/*
11582 		 * "sum" and "reass_hck_flags" are non-zero if the
11583 		 * reassembled packet has a valid hardware computed
11584 		 * checksum information associated with it.
11585 		 */
11586 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
11587 			goto slow_done;
11588 		/*
11589 		 * Make sure that first_mp points back to mp as
11590 		 * the mp we came in with could have changed in
11591 		 * ip_rput_fragment().
11592 		 */
11593 		ASSERT(!mctl_present);
11594 		ipha = (ipha_t *)mp->b_rptr;
11595 		first_mp = mp;
11596 	}
11597 
11598 	/* Now we have a complete datagram, destined for this machine. */
11599 	u1 = IPH_HDR_LENGTH(ipha);
11600 	/* Pull up the UDP header, if necessary. */
11601 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
11602 udppullup:
11603 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11604 			BUMP_MIB(&ip_mib, ipInDiscards);
11605 			freemsg(first_mp);
11606 			goto slow_done;
11607 		}
11608 		ipha = (ipha_t *)mp->b_rptr;
11609 	}
11610 
11611 	/*
11612 	 * Validate the checksum for the reassembled packet; for the
11613 	 * pullup case we calculate the payload checksum in software.
11614 	 */
11615 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11616 	if (up[3] != 0) {
11617 		boolean_t cksum_err;
11618 
11619 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11620 			IP_STAT(ip_in_sw_cksum);
11621 
11622 		IP_CKSUM_RECV_REASS(reass_hck_flags,
11623 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11624 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11625 		    iphs[9] + up[2], sum, cksum_err);
11626 
11627 		if (cksum_err) {
11628 			BUMP_MIB(&ip_mib, udpInCksumErrs);
11629 
11630 			if (reass_hck_flags & HCK_FULLCKSUM)
11631 				IP_STAT(ip_udp_in_full_hw_cksum_err);
11632 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
11633 				IP_STAT(ip_udp_in_part_hw_cksum_err);
11634 			else
11635 				IP_STAT(ip_udp_in_sw_cksum_err);
11636 
11637 			freemsg(first_mp);
11638 			goto slow_done;
11639 		}
11640 	}
11641 udpslowpath:
11642 
11643 	/* Clear hardware checksum flag to be safe */
11644 	DB_CKSUMFLAGS(mp) = 0;
11645 
11646 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
11647 	    (ire->ire_type == IRE_BROADCAST),
11648 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11649 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11650 
11651 slow_done:
11652 	IP_STAT(ip_udp_slow_path);
11653 	return;
11654 
11655 #undef  iphs
11656 #undef  rptr
11657 }
11658 
11659 /* ARGSUSED */
11660 static mblk_t *
11661 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11662     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11663     ill_rx_ring_t *ill_ring)
11664 {
11665 	conn_t		*connp;
11666 	uint32_t	sum;
11667 	uint32_t	u1;
11668 	uint16_t	*up;
11669 	int		offset;
11670 	ssize_t		len;
11671 	mblk_t		*mp1;
11672 	boolean_t	syn_present = B_FALSE;
11673 	tcph_t		*tcph;
11674 	uint_t		ip_hdr_len;
11675 	ill_t		*ill = (ill_t *)q->q_ptr;
11676 	zoneid_t	zoneid = ire->ire_zoneid;
11677 	boolean_t	cksum_err;
11678 	uint16_t	hck_flags = 0;
11679 
11680 #define	rptr	((uchar_t *)ipha)
11681 
11682 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11683 
11684 	/*
11685 	 * FAST PATH for tcp packets
11686 	 */
11687 
11688 	/* u1 is # words of IP options */
11689 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11690 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11691 
11692 	/* IP options present */
11693 	if (u1) {
11694 		goto ipoptions;
11695 	} else {
11696 		/* Check the IP header checksum.  */
11697 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11698 			/* Clear the IP header h/w cksum flag */
11699 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11700 		} else {
11701 #define	uph	((uint16_t *)ipha)
11702 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11703 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11704 #undef	uph
11705 			/* finish doing IP checksum */
11706 			sum = (sum & 0xFFFF) + (sum >> 16);
11707 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11708 			/*
11709 			 * Don't verify header checksum if this packet
11710 			 * is coming back from AH/ESP as we already did it.
11711 			 */
11712 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11713 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11714 				goto error;
11715 			}
11716 		}
11717 	}
11718 
11719 	if (!mctl_present) {
11720 		UPDATE_IB_PKT_COUNT(ire);
11721 		ire->ire_last_used_time = lbolt;
11722 	}
11723 
11724 	/* packet part of fragmented IP packet? */
11725 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11726 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11727 		goto fragmented;
11728 	}
11729 
11730 	/* u1 = IP header length (20 bytes) */
11731 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11732 
11733 	/* does packet contain IP+TCP headers? */
11734 	len = mp->b_wptr - rptr;
11735 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11736 		IP_STAT(ip_tcppullup);
11737 		goto tcppullup;
11738 	}
11739 
11740 	/* TCP options present? */
11741 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11742 
11743 	/*
11744 	 * If options need to be pulled up, then goto tcpoptions.
11745 	 * otherwise we are still in the fast path
11746 	 */
11747 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11748 		IP_STAT(ip_tcpoptions);
11749 		goto tcpoptions;
11750 	}
11751 
11752 	/* multiple mblks of tcp data? */
11753 	if ((mp1 = mp->b_cont) != NULL) {
11754 		/* more then two? */
11755 		if (mp1->b_cont != NULL) {
11756 			IP_STAT(ip_multipkttcp);
11757 			goto multipkttcp;
11758 		}
11759 		len += mp1->b_wptr - mp1->b_rptr;
11760 	}
11761 
11762 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11763 
11764 	/* part of pseudo checksum */
11765 
11766 	/* TCP datagram length */
11767 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11768 
11769 #define	iphs    ((uint16_t *)ipha)
11770 
11771 #ifdef	_BIG_ENDIAN
11772 	u1 += IPPROTO_TCP;
11773 #else
11774 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11775 #endif
11776 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11777 
11778 	/*
11779 	 * Revert to software checksum calculation if the interface
11780 	 * isn't capable of checksum offload or if IPsec is present.
11781 	 */
11782 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
11783 		hck_flags = DB_CKSUMFLAGS(mp);
11784 
11785 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
11786 		IP_STAT(ip_in_sw_cksum);
11787 
11788 	IP_CKSUM_RECV(hck_flags, u1,
11789 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
11790 	    (int32_t)((uchar_t *)up - rptr),
11791 	    mp, mp1, cksum_err);
11792 
11793 	if (cksum_err) {
11794 		BUMP_MIB(&ip_mib, tcpInErrs);
11795 
11796 		if (hck_flags & HCK_FULLCKSUM)
11797 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
11798 		else if (hck_flags & HCK_PARTIALCKSUM)
11799 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
11800 		else
11801 			IP_STAT(ip_tcp_in_sw_cksum_err);
11802 
11803 		goto error;
11804 	}
11805 
11806 try_again:
11807 
11808 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11809 	    NULL) {
11810 		/* Send the TH_RST */
11811 		goto no_conn;
11812 	}
11813 
11814 	/*
11815 	 * TCP FAST PATH for AF_INET socket.
11816 	 *
11817 	 * TCP fast path to avoid extra work. An AF_INET socket type
11818 	 * does not have facility to receive extra information via
11819 	 * ip_process or ip_add_info. Also, when the connection was
11820 	 * established, we made a check if this connection is impacted
11821 	 * by any global IPSec policy or per connection policy (a
11822 	 * policy that comes in effect later will not apply to this
11823 	 * connection). Since all this can be determined at the
11824 	 * connection establishment time, a quick check of flags
11825 	 * can avoid extra work.
11826 	 */
11827 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11828 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11829 		ASSERT(first_mp == mp);
11830 		SET_SQUEUE(mp, tcp_rput_data, connp);
11831 		return (mp);
11832 	}
11833 
11834 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11835 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11836 		if (IPCL_IS_TCP(connp)) {
11837 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11838 			DB_CKSUMSTART(mp) =
11839 			    (intptr_t)ip_squeue_get(ill_ring);
11840 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11841 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11842 				SET_SQUEUE(mp, connp->conn_recv, connp);
11843 				return (mp);
11844 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11845 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11846 				ip_squeue_enter_unbound++;
11847 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11848 				    connp);
11849 				return (mp);
11850 			}
11851 			syn_present = B_TRUE;
11852 		}
11853 
11854 	}
11855 
11856 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11857 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11858 
11859 		/* No need to send this packet to TCP */
11860 		if ((flags & TH_RST) || (flags & TH_URG)) {
11861 			CONN_DEC_REF(connp);
11862 			freemsg(first_mp);
11863 			return (NULL);
11864 		}
11865 		if (flags & TH_ACK) {
11866 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11867 			CONN_DEC_REF(connp);
11868 			return (NULL);
11869 		}
11870 
11871 		CONN_DEC_REF(connp);
11872 		freemsg(first_mp);
11873 		return (NULL);
11874 	}
11875 
11876 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11877 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11878 		    ipha, NULL, mctl_present);
11879 		if (first_mp == NULL) {
11880 			CONN_DEC_REF(connp);
11881 			return (NULL);
11882 		}
11883 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11884 			ASSERT(syn_present);
11885 			if (mctl_present) {
11886 				ASSERT(first_mp != mp);
11887 				first_mp->b_datap->db_struioflag |=
11888 				    STRUIO_POLICY;
11889 			} else {
11890 				ASSERT(first_mp == mp);
11891 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11892 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11893 			}
11894 		} else {
11895 			/*
11896 			 * Discard first_mp early since we're dealing with a
11897 			 * fully-connected conn_t and tcp doesn't do policy in
11898 			 * this case.
11899 			 */
11900 			if (mctl_present) {
11901 				freeb(first_mp);
11902 				mctl_present = B_FALSE;
11903 			}
11904 			first_mp = mp;
11905 		}
11906 	}
11907 
11908 	/* Initiate IPPF processing for fastpath */
11909 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11910 		uint32_t	ill_index;
11911 
11912 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11913 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11914 		if (mp == NULL) {
11915 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11916 			    "deferred/dropped during IPPF processing\n"));
11917 			CONN_DEC_REF(connp);
11918 			if (mctl_present)
11919 				freeb(first_mp);
11920 			return (NULL);
11921 		} else if (mctl_present) {
11922 			/*
11923 			 * ip_process might return a new mp.
11924 			 */
11925 			ASSERT(first_mp != mp);
11926 			first_mp->b_cont = mp;
11927 		} else {
11928 			first_mp = mp;
11929 		}
11930 
11931 	}
11932 
11933 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11934 		mp = ip_add_info(mp, recv_ill, flags);
11935 		if (mp == NULL) {
11936 			CONN_DEC_REF(connp);
11937 			if (mctl_present)
11938 				freeb(first_mp);
11939 			return (NULL);
11940 		} else if (mctl_present) {
11941 			/*
11942 			 * ip_add_info might return a new mp.
11943 			 */
11944 			ASSERT(first_mp != mp);
11945 			first_mp->b_cont = mp;
11946 		} else {
11947 			first_mp = mp;
11948 		}
11949 	}
11950 
11951 	if (IPCL_IS_TCP(connp)) {
11952 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11953 		return (first_mp);
11954 	} else {
11955 		putnext(connp->conn_rq, first_mp);
11956 		CONN_DEC_REF(connp);
11957 		return (NULL);
11958 	}
11959 
11960 no_conn:
11961 	/* Initiate IPPf processing, if needed. */
11962 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11963 		uint32_t ill_index;
11964 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11965 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
11966 		if (first_mp == NULL) {
11967 			return (NULL);
11968 		}
11969 	}
11970 	BUMP_MIB(&ip_mib, ipInDelivers);
11971 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
11972 	return (NULL);
11973 ipoptions:
11974 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
11975 		goto slow_done;
11976 	}
11977 
11978 	UPDATE_IB_PKT_COUNT(ire);
11979 	ire->ire_last_used_time = lbolt;
11980 
11981 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11982 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11983 fragmented:
11984 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
11985 			if (mctl_present)
11986 				freeb(first_mp);
11987 			goto slow_done;
11988 		}
11989 		/*
11990 		 * Make sure that first_mp points back to mp as
11991 		 * the mp we came in with could have changed in
11992 		 * ip_rput_fragment().
11993 		 */
11994 		ASSERT(!mctl_present);
11995 		ipha = (ipha_t *)mp->b_rptr;
11996 		first_mp = mp;
11997 	}
11998 
11999 tcp_slow:
12000 	/* Now we have a complete datagram, destined for this machine. */
12001 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12002 
12003 	len = mp->b_wptr - mp->b_rptr;
12004 	/* Pull up a minimal TCP header, if necessary. */
12005 	if (len < (u1 + 20)) {
12006 tcppullup:
12007 		if (!pullupmsg(mp, u1 + 20)) {
12008 			BUMP_MIB(&ip_mib, ipInDiscards);
12009 			goto error;
12010 		}
12011 		ipha = (ipha_t *)mp->b_rptr;
12012 		len = mp->b_wptr - mp->b_rptr;
12013 	}
12014 
12015 	/*
12016 	 * Extract the offset field from the TCP header.  As usual, we
12017 	 * try to help the compiler more than the reader.
12018 	 */
12019 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12020 	if (offset != 5) {
12021 tcpoptions:
12022 		if (offset < 5) {
12023 			BUMP_MIB(&ip_mib, ipInDiscards);
12024 			goto error;
12025 		}
12026 		/*
12027 		 * There must be TCP options.
12028 		 * Make sure we can grab them.
12029 		 */
12030 		offset <<= 2;
12031 		offset += u1;
12032 		if (len < offset) {
12033 			if (!pullupmsg(mp, offset)) {
12034 				BUMP_MIB(&ip_mib, ipInDiscards);
12035 				goto error;
12036 			}
12037 			ipha = (ipha_t *)mp->b_rptr;
12038 			len = mp->b_wptr - rptr;
12039 		}
12040 	}
12041 
12042 	/* Get the total packet length in len, including headers. */
12043 	if (mp->b_cont) {
12044 multipkttcp:
12045 		len = msgdsize(mp);
12046 	}
12047 
12048 	/*
12049 	 * Check the TCP checksum by pulling together the pseudo-
12050 	 * header checksum, and passing it to ip_csum to be added in
12051 	 * with the TCP datagram.
12052 	 *
12053 	 * Since we are not using the hwcksum if available we must
12054 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12055 	 * If either of these fails along the way the mblk is freed.
12056 	 * If this logic ever changes and mblk is reused to say send
12057 	 * ICMP's back, then this flag may need to be cleared in
12058 	 * other places as well.
12059 	 */
12060 	DB_CKSUMFLAGS(mp) = 0;
12061 
12062 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12063 
12064 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12065 #ifdef	_BIG_ENDIAN
12066 	u1 += IPPROTO_TCP;
12067 #else
12068 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12069 #endif
12070 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12071 	/*
12072 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12073 	 */
12074 	IP_STAT(ip_in_sw_cksum);
12075 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12076 		BUMP_MIB(&ip_mib, tcpInErrs);
12077 		goto error;
12078 	}
12079 
12080 	IP_STAT(ip_tcp_slow_path);
12081 	goto try_again;
12082 #undef  iphs
12083 #undef  rptr
12084 
12085 error:
12086 	freemsg(first_mp);
12087 slow_done:
12088 	return (NULL);
12089 }
12090 
12091 /* ARGSUSED */
12092 static void
12093 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12094     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12095 {
12096 	conn_t		*connp;
12097 	uint32_t	sum;
12098 	uint32_t	u1;
12099 	ssize_t		len;
12100 	sctp_hdr_t	*sctph;
12101 	zoneid_t	zoneid = ire->ire_zoneid;
12102 	uint32_t	pktsum;
12103 	uint32_t	calcsum;
12104 	uint32_t	ports;
12105 	uint_t		ipif_seqid;
12106 	in6_addr_t	map_src, map_dst;
12107 	ill_t		*ill = (ill_t *)q->q_ptr;
12108 
12109 #define	rptr	((uchar_t *)ipha)
12110 
12111 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12112 
12113 	/* u1 is # words of IP options */
12114 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12115 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12116 
12117 	/* IP options present */
12118 	if (u1 > 0) {
12119 		goto ipoptions;
12120 	} else {
12121 		/* Check the IP header checksum.  */
12122 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12123 			/*
12124 			 * Since there is no SCTP h/w cksum support yet, just
12125 			 * clear the flag.
12126 			 */
12127 			DB_CKSUMFLAGS(mp) = 0;
12128 		} else {
12129 #define	uph	((uint16_t *)ipha)
12130 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12131 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12132 #undef	uph
12133 			/* finish doing IP checksum */
12134 			sum = (sum & 0xFFFF) + (sum >> 16);
12135 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12136 			/*
12137 			 * Don't verify header checksum if this packet
12138 			 * is coming back from AH/ESP as we already did it.
12139 			 */
12140 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12141 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12142 				goto error;
12143 			}
12144 		}
12145 	}
12146 
12147 	/*
12148 	 * Don't verify header checksum if this packet is coming
12149 	 * back from AH/ESP as we already did it.
12150 	 */
12151 	if (!mctl_present) {
12152 		UPDATE_IB_PKT_COUNT(ire);
12153 		ire->ire_last_used_time = lbolt;
12154 	}
12155 
12156 	/* packet part of fragmented IP packet? */
12157 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12158 	if (u1 & (IPH_MF | IPH_OFFSET))
12159 		goto fragmented;
12160 
12161 	/* u1 = IP header length (20 bytes) */
12162 	u1 = IP_SIMPLE_HDR_LENGTH;
12163 
12164 find_sctp_client:
12165 	/* Pullup if we don't have the sctp common header. */
12166 	len = MBLKL(mp);
12167 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12168 		if (mp->b_cont == NULL ||
12169 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12170 			BUMP_MIB(&ip_mib, ipInDiscards);
12171 			goto error;
12172 		}
12173 		ipha = (ipha_t *)mp->b_rptr;
12174 		len = MBLKL(mp);
12175 	}
12176 
12177 	sctph = (sctp_hdr_t *)(rptr + u1);
12178 #ifdef	DEBUG
12179 	if (!skip_sctp_cksum) {
12180 #endif
12181 		pktsum = sctph->sh_chksum;
12182 		sctph->sh_chksum = 0;
12183 		calcsum = sctp_cksum(mp, u1);
12184 		if (calcsum != pktsum) {
12185 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12186 			goto error;
12187 		}
12188 		sctph->sh_chksum = pktsum;
12189 #ifdef	DEBUG	/* skip_sctp_cksum */
12190 	}
12191 #endif
12192 	/* get the ports */
12193 	ports = *(uint32_t *)&sctph->sh_sport;
12194 
12195 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12196 	IRE_REFRELE(ire);
12197 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12198 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12199 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12200 	    zoneid)) == NULL) {
12201 		/* Check for raw socket or OOTB handling */
12202 		goto no_conn;
12203 	}
12204 
12205 	/* Found a client; up it goes */
12206 	BUMP_MIB(&ip_mib, ipInDelivers);
12207 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12208 	return;
12209 
12210 no_conn:
12211 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12212 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12213 	return;
12214 
12215 ipoptions:
12216 	DB_CKSUMFLAGS(mp) = 0;
12217 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12218 		goto slow_done;
12219 
12220 	UPDATE_IB_PKT_COUNT(ire);
12221 	ire->ire_last_used_time = lbolt;
12222 
12223 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12224 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12225 fragmented:
12226 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12227 			goto slow_done;
12228 		/*
12229 		 * Make sure that first_mp points back to mp as
12230 		 * the mp we came in with could have changed in
12231 		 * ip_rput_fragment().
12232 		 */
12233 		ASSERT(!mctl_present);
12234 		ipha = (ipha_t *)mp->b_rptr;
12235 		first_mp = mp;
12236 	}
12237 
12238 	/* Now we have a complete datagram, destined for this machine. */
12239 	u1 = IPH_HDR_LENGTH(ipha);
12240 	goto find_sctp_client;
12241 #undef  iphs
12242 #undef  rptr
12243 
12244 error:
12245 	freemsg(first_mp);
12246 slow_done:
12247 	IRE_REFRELE(ire);
12248 }
12249 
12250 #define	VER_BITS	0xF0
12251 #define	VERSION_6	0x60
12252 
12253 static boolean_t
12254 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12255     ipaddr_t *dstp)
12256 {
12257 	uint_t	opt_len;
12258 	ipha_t *ipha;
12259 	ssize_t len;
12260 	uint_t	pkt_len;
12261 
12262 	IP_STAT(ip_ipoptions);
12263 	ipha = *iphapp;
12264 
12265 #define	rptr    ((uchar_t *)ipha)
12266 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12267 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12268 		BUMP_MIB(&ip_mib, ipInIPv6);
12269 		freemsg(mp);
12270 		return (B_FALSE);
12271 	}
12272 
12273 	/* multiple mblk or too short */
12274 	pkt_len = ntohs(ipha->ipha_length);
12275 
12276 	/* Get the number of words of IP options in the IP header. */
12277 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12278 	if (opt_len) {
12279 		/* IP Options present!  Validate and process. */
12280 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12281 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12282 			goto done;
12283 		}
12284 		/*
12285 		 * Recompute complete header length and make sure we
12286 		 * have access to all of it.
12287 		 */
12288 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12289 		if (len > (mp->b_wptr - rptr)) {
12290 			if (len > pkt_len) {
12291 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12292 				goto done;
12293 			}
12294 			if (!pullupmsg(mp, len)) {
12295 				BUMP_MIB(&ip_mib, ipInDiscards);
12296 				goto done;
12297 			}
12298 			ipha = (ipha_t *)mp->b_rptr;
12299 		}
12300 		/*
12301 		 * Go off to ip_rput_options which returns the next hop
12302 		 * destination address, which may have been affected
12303 		 * by source routing.
12304 		 */
12305 		IP_STAT(ip_opt);
12306 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12307 			return (B_FALSE);
12308 		}
12309 	}
12310 	*iphapp = ipha;
12311 	return (B_TRUE);
12312 done:
12313 	/* clear b_prev - used by ip_mroute_decap */
12314 	mp->b_prev = NULL;
12315 	freemsg(mp);
12316 	return (B_FALSE);
12317 #undef  rptr
12318 }
12319 
12320 /*
12321  * Deal with the fact that there is no ire for the destination.
12322  * The incoming ill (in_ill) is passed in to ip_newroute only
12323  * in the case of packets coming from mobile ip forward tunnel.
12324  * It must be null otherwise.
12325  */
12326 static void
12327 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12328     ipaddr_t dst)
12329 {
12330 	ipha_t	*ipha;
12331 	ill_t	*ill;
12332 
12333 	ipha = (ipha_t *)mp->b_rptr;
12334 	ill = (ill_t *)q->q_ptr;
12335 
12336 	ASSERT(ill != NULL);
12337 	/*
12338 	 * No IRE for this destination, so it can't be for us.
12339 	 * Unless we are forwarding, drop the packet.
12340 	 * We have to let source routed packets through
12341 	 * since we don't yet know if they are 'ping -l'
12342 	 * packets i.e. if they will go out over the
12343 	 * same interface as they came in on.
12344 	 */
12345 	if (ll_multicast) {
12346 		freemsg(mp);
12347 		return;
12348 	}
12349 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12350 		BUMP_MIB(&ip_mib, ipForwProhibits);
12351 		freemsg(mp);
12352 		return;
12353 	}
12354 
12355 	/* Check for Martian addresses */
12356 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12357 		freemsg(mp);
12358 		return;
12359 	}
12360 
12361 	/* Mark this packet as having originated externally */
12362 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12363 
12364 	/*
12365 	 * Clear the indication that this may have a hardware checksum
12366 	 * as we are not using it
12367 	 */
12368 	DB_CKSUMFLAGS(mp) = 0;
12369 
12370 	/*
12371 	 * Now hand the packet to ip_newroute.
12372 	 */
12373 	ip_newroute(q, mp, dst, in_ill, NULL);
12374 }
12375 
12376 /*
12377  * check ip header length and align it.
12378  */
12379 static boolean_t
12380 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12381 {
12382 	ssize_t len;
12383 	ill_t *ill;
12384 	ipha_t	*ipha;
12385 
12386 	len = MBLKL(mp);
12387 
12388 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12389 		if (!OK_32PTR(mp->b_rptr))
12390 			IP_STAT(ip_notaligned1);
12391 		else
12392 			IP_STAT(ip_notaligned2);
12393 		/* Guard against bogus device drivers */
12394 		if (len < 0) {
12395 			/* clear b_prev - used by ip_mroute_decap */
12396 			mp->b_prev = NULL;
12397 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12398 			freemsg(mp);
12399 			return (B_FALSE);
12400 		}
12401 
12402 		if (ip_rput_pullups++ == 0) {
12403 			ill = (ill_t *)q->q_ptr;
12404 			ipha = (ipha_t *)mp->b_rptr;
12405 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12406 			    "ip_check_and_align_header: %s forced us to "
12407 			    " pullup pkt, hdr len %ld, hdr addr %p",
12408 			    ill->ill_name, len, ipha);
12409 		}
12410 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12411 			/* clear b_prev - used by ip_mroute_decap */
12412 			mp->b_prev = NULL;
12413 			BUMP_MIB(&ip_mib, ipInDiscards);
12414 			freemsg(mp);
12415 			return (B_FALSE);
12416 		}
12417 	}
12418 	return (B_TRUE);
12419 }
12420 
12421 static boolean_t
12422 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12423 {
12424 	ill_group_t	*ill_group;
12425 	ill_group_t	*ire_group;
12426 	queue_t 	*q;
12427 	ill_t		*ire_ill;
12428 	uint_t		ill_ifindex;
12429 
12430 	q = *qp;
12431 	/*
12432 	 * We need to check to make sure the packet came in
12433 	 * on the queue associated with the destination IRE.
12434 	 * Note that for multicast packets and broadcast packets sent to
12435 	 * a broadcast address which is shared between multiple interfaces
12436 	 * we should not do this since we just got a random broadcast ire.
12437 	 */
12438 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12439 		boolean_t check_multi = B_TRUE;
12440 
12441 		/*
12442 		 * This packet came in on an interface other than the
12443 		 * one associated with the destination address.
12444 		 * "Gateway" it to the appropriate interface here.
12445 		 * As long as the ills belong to the same group,
12446 		 * we don't consider them to arriving on the wrong
12447 		 * interface. Thus, when the switch is doing inbound
12448 		 * load spreading, we won't drop packets when we
12449 		 * are doing strict multihoming checks. Note, the
12450 		 * same holds true for 'usesrc groups' where the
12451 		 * destination address may belong to another interface
12452 		 * to allow multipathing to happen
12453 		 */
12454 		ill_group = ill->ill_group;
12455 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12456 		ill_ifindex = ill->ill_usesrc_ifindex;
12457 		ire_group = ire_ill->ill_group;
12458 
12459 		/*
12460 		 * If it's part of the same IPMP group, or if it's a legal
12461 		 * address on the 'usesrc' interface, then bypass strict
12462 		 * checks.
12463 		 */
12464 		if (ill_group != NULL && ill_group == ire_group) {
12465 			check_multi = B_FALSE;
12466 		} else if (ill_ifindex != 0 &&
12467 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12468 			check_multi = B_FALSE;
12469 		}
12470 
12471 		if (check_multi &&
12472 		    ip_strict_dst_multihoming &&
12473 		    ((ill->ill_flags &
12474 		    ire->ire_ipif->ipif_ill->ill_flags &
12475 		    ILLF_ROUTER) == 0)) {
12476 			/* Drop packet */
12477 			BUMP_MIB(&ip_mib, ipForwProhibits);
12478 			freemsg(mp);
12479 			ire_refrele(ire);
12480 			return (B_TRUE);
12481 		}
12482 
12483 		/*
12484 		 * Change the queue (for non-virtual destination network
12485 		 * interfaces) and ip_rput_local will be called with the right
12486 		 * queue
12487 		 */
12488 		q = ire->ire_rfq;
12489 	}
12490 	/* Must be broadcast.  We'll take it. */
12491 	*qp = q;
12492 	return (B_FALSE);
12493 }
12494 
12495 static void
12496 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12497     ill_t *ill, int ll_multicast)
12498 {
12499 	ill_group_t	*ill_group;
12500 	ill_group_t	*ire_group;
12501 	queue_t	*dev_q;
12502 
12503 	ASSERT(ire->ire_stq != NULL);
12504 	if (ll_multicast != 0)
12505 		goto drop_pkt;
12506 
12507 	if (ip_no_forward(ipha, ill))
12508 		goto drop_pkt;
12509 
12510 	ill_group = ill->ill_group;
12511 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12512 	/*
12513 	 * Check if we want to forward this one at this time.
12514 	 * We allow source routed packets on a host provided that
12515 	 * they go out the same interface or same interface group
12516 	 * as they came in on.
12517 	 *
12518 	 * XXX To be quicker, we may wish to not chase pointers to
12519 	 * get the ILLF_ROUTER flag and instead store the
12520 	 * forwarding policy in the ire.  An unfortunate
12521 	 * side-effect of that would be requiring an ire flush
12522 	 * whenever the ILLF_ROUTER flag changes.
12523 	 */
12524 	if (((ill->ill_flags &
12525 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12526 	    ILLF_ROUTER) == 0) &&
12527 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12528 	    (ill_group != NULL && ill_group == ire_group)))) {
12529 		BUMP_MIB(&ip_mib, ipForwProhibits);
12530 		if (ip_source_routed(ipha)) {
12531 			q = WR(q);
12532 			/*
12533 			 * Clear the indication that this may have
12534 			 * hardware checksum as we are not using it.
12535 			 */
12536 			DB_CKSUMFLAGS(mp) = 0;
12537 			icmp_unreachable(q, mp,
12538 			    ICMP_SOURCE_ROUTE_FAILED);
12539 			ire_refrele(ire);
12540 			return;
12541 		}
12542 		goto drop_pkt;
12543 	}
12544 
12545 	/* Packet is being forwarded. Turning off hwcksum flag. */
12546 	DB_CKSUMFLAGS(mp) = 0;
12547 	if (ip_g_send_redirects) {
12548 		/*
12549 		 * Check whether the incoming interface and outgoing
12550 		 * interface is part of the same group. If so,
12551 		 * send redirects.
12552 		 *
12553 		 * Check the source address to see if it originated
12554 		 * on the same logical subnet it is going back out on.
12555 		 * If so, we should be able to send it a redirect.
12556 		 * Avoid sending a redirect if the destination
12557 		 * is directly connected (gw_addr == 0),
12558 		 * or if the packet was source routed out this
12559 		 * interface.
12560 		 */
12561 		ipaddr_t src;
12562 		mblk_t	*mp1;
12563 		ire_t	*src_ire = NULL;
12564 
12565 		/*
12566 		 * Check whether ire_rfq and q are from the same ill
12567 		 * or if they are not same, they at least belong
12568 		 * to the same group. If so, send redirects.
12569 		 */
12570 		if ((ire->ire_rfq == q ||
12571 		    (ill_group != NULL && ill_group == ire_group)) &&
12572 		    (ire->ire_gateway_addr != 0) &&
12573 		    !ip_source_routed(ipha)) {
12574 
12575 			src = ipha->ipha_src;
12576 			src_ire = ire_ftable_lookup(src, 0, 0,
12577 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12578 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12579 
12580 			if (src_ire != NULL) {
12581 				/*
12582 				 * The source is directly connected.
12583 				 * Just copy the ip header (which is
12584 				 * in the first mblk)
12585 				 */
12586 				mp1 = copyb(mp);
12587 				if (mp1 != NULL) {
12588 					icmp_send_redirect(WR(q), mp1,
12589 					    ire->ire_gateway_addr);
12590 				}
12591 				ire_refrele(src_ire);
12592 			}
12593 		}
12594 	}
12595 
12596 	dev_q = ire->ire_stq->q_next;
12597 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12598 		BUMP_MIB(&ip_mib, ipInDiscards);
12599 		freemsg(mp);
12600 		ire_refrele(ire);
12601 		return;
12602 	}
12603 
12604 	ip_rput_forward(ire, ipha, mp, ill);
12605 	IRE_REFRELE(ire);
12606 	return;
12607 
12608 drop_pkt:
12609 	ire_refrele(ire);
12610 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12611 	freemsg(mp);
12612 }
12613 
12614 static boolean_t
12615 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12616     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12617 {
12618 	queue_t		*q;
12619 	ire_t		*ire;
12620 	uint16_t	hcksumflags;
12621 
12622 	q = *qp;
12623 	ire = *irep;
12624 
12625 	/*
12626 	 * Clear the indication that this may have hardware
12627 	 * checksum as we are not using it for forwarding.
12628 	 */
12629 	hcksumflags = DB_CKSUMFLAGS(mp);
12630 	DB_CKSUMFLAGS(mp) = 0;
12631 
12632 	/*
12633 	 * Directed broadcast forwarding: if the packet came in over a
12634 	 * different interface then it is routed out over we can forward it.
12635 	 */
12636 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12637 		ire_refrele(ire);
12638 		freemsg(mp);
12639 		BUMP_MIB(&ip_mib, ipInDiscards);
12640 		return (B_TRUE);
12641 	}
12642 	/*
12643 	 * For multicast we have set dst to be INADDR_BROADCAST
12644 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12645 	 * only for broadcast packets.
12646 	 */
12647 	if (!CLASSD(ipha->ipha_dst)) {
12648 		ire_t *new_ire;
12649 		ipif_t *ipif;
12650 		/*
12651 		 * For ill groups, as the switch duplicates broadcasts
12652 		 * across all the ports, we need to filter out and
12653 		 * send up only one copy. There is one copy for every
12654 		 * broadcast address on each ill. Thus, we look for a
12655 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12656 		 * later to see whether this ill is eligible to receive
12657 		 * them or not. ill_nominate_bcast_rcv() nominates only
12658 		 * one set of IREs for receiving.
12659 		 */
12660 
12661 		ipif = ipif_get_next_ipif(NULL, ill);
12662 		if (ipif == NULL) {
12663 			ire_refrele(ire);
12664 			freemsg(mp);
12665 			BUMP_MIB(&ip_mib, ipInDiscards);
12666 			return (B_TRUE);
12667 		}
12668 		new_ire = ire_ctable_lookup(dst, 0, 0,
12669 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12670 		ipif_refrele(ipif);
12671 
12672 		if (new_ire != NULL) {
12673 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12674 				ire_refrele(ire);
12675 				ire_refrele(new_ire);
12676 				freemsg(mp);
12677 				BUMP_MIB(&ip_mib, ipInDiscards);
12678 				return (B_TRUE);
12679 			}
12680 			/*
12681 			 * In the special case of multirouted broadcast
12682 			 * packets, we unconditionally need to "gateway"
12683 			 * them to the appropriate interface here.
12684 			 * In the normal case, this cannot happen, because
12685 			 * there is no broadcast IRE tagged with the
12686 			 * RTF_MULTIRT flag.
12687 			 */
12688 			if (new_ire->ire_flags & RTF_MULTIRT) {
12689 				ire_refrele(new_ire);
12690 				if (ire->ire_rfq != NULL) {
12691 					q = ire->ire_rfq;
12692 					*qp = q;
12693 				}
12694 			} else {
12695 				ire_refrele(ire);
12696 				ire = new_ire;
12697 			}
12698 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12699 			if (!ip_g_forward_directed_bcast) {
12700 				/*
12701 				 * Free the message if
12702 				 * ip_g_forward_directed_bcast is turned
12703 				 * off for non-local broadcast.
12704 				 */
12705 				ire_refrele(ire);
12706 				freemsg(mp);
12707 				BUMP_MIB(&ip_mib, ipInDiscards);
12708 				return (B_TRUE);
12709 			}
12710 		} else {
12711 			/*
12712 			 * This CGTP packet successfully passed the
12713 			 * CGTP filter, but the related CGTP
12714 			 * broadcast IRE has not been found,
12715 			 * meaning that the redundant ipif is
12716 			 * probably down. However, if we discarded
12717 			 * this packet, its duplicate would be
12718 			 * filtered out by the CGTP filter so none
12719 			 * of them would get through. So we keep
12720 			 * going with this one.
12721 			 */
12722 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12723 			if (ire->ire_rfq != NULL) {
12724 				q = ire->ire_rfq;
12725 				*qp = q;
12726 			}
12727 		}
12728 	}
12729 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12730 		/*
12731 		 * Verify that there are not more then one
12732 		 * IRE_BROADCAST with this broadcast address which
12733 		 * has ire_stq set.
12734 		 * TODO: simplify, loop over all IRE's
12735 		 */
12736 		ire_t	*ire1;
12737 		int	num_stq = 0;
12738 		mblk_t	*mp1;
12739 
12740 		/* Find the first one with ire_stq set */
12741 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12742 		for (ire1 = ire; ire1 &&
12743 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12744 		    ire1 = ire1->ire_next)
12745 			;
12746 		if (ire1) {
12747 			ire_refrele(ire);
12748 			ire = ire1;
12749 			IRE_REFHOLD(ire);
12750 		}
12751 
12752 		/* Check if there are additional ones with stq set */
12753 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12754 			if (ire->ire_addr != ire1->ire_addr)
12755 				break;
12756 			if (ire1->ire_stq) {
12757 				num_stq++;
12758 				break;
12759 			}
12760 		}
12761 		rw_exit(&ire->ire_bucket->irb_lock);
12762 		if (num_stq == 1 && ire->ire_stq != NULL) {
12763 			ip1dbg(("ip_rput_process_broadcast: directed "
12764 			    "broadcast to 0x%x\n",
12765 			    ntohl(ire->ire_addr)));
12766 			mp1 = copymsg(mp);
12767 			if (mp1) {
12768 				switch (ipha->ipha_protocol) {
12769 				case IPPROTO_UDP:
12770 					ip_udp_input(q, mp1, ipha, ire, ill);
12771 					break;
12772 				default:
12773 					ip_proto_input(q, mp1, ipha, ire, ill);
12774 					break;
12775 				}
12776 			}
12777 			/*
12778 			 * Adjust ttl to 2 (1+1 - the forward engine
12779 			 * will decrement it by one.
12780 			 */
12781 			if (ip_csum_hdr(ipha)) {
12782 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12783 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12784 				freemsg(mp);
12785 				ire_refrele(ire);
12786 				return (B_TRUE);
12787 			}
12788 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12789 			ipha->ipha_hdr_checksum = 0;
12790 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12791 			ip_rput_process_forward(q, mp, ire, ipha,
12792 			    ill, ll_multicast);
12793 			return (B_TRUE);
12794 		}
12795 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12796 		    ntohl(ire->ire_addr)));
12797 	}
12798 
12799 	*irep = ire;
12800 
12801 	/* Restore any hardware checksum flags */
12802 	DB_CKSUMFLAGS(mp) = hcksumflags;
12803 	return (B_FALSE);
12804 }
12805 
12806 /* ARGSUSED */
12807 static boolean_t
12808 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12809     int *ll_multicast, ipaddr_t *dstp)
12810 {
12811 	/*
12812 	 * Forward packets only if we have joined the allmulti
12813 	 * group on this interface.
12814 	 */
12815 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12816 		int retval;
12817 
12818 		/*
12819 		 * Clear the indication that this may have hardware
12820 		 * checksum as we are not using it.
12821 		 */
12822 		DB_CKSUMFLAGS(mp) = 0;
12823 		retval = ip_mforward(ill, ipha, mp);
12824 		/* ip_mforward updates mib variables if needed */
12825 		/* clear b_prev - used by ip_mroute_decap */
12826 		mp->b_prev = NULL;
12827 
12828 		switch (retval) {
12829 		case 0:
12830 			/*
12831 			 * pkt is okay and arrived on phyint.
12832 			 *
12833 			 * If we are running as a multicast router
12834 			 * we need to see all IGMP and/or PIM packets.
12835 			 */
12836 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12837 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12838 				goto done;
12839 			}
12840 			break;
12841 		case -1:
12842 			/* pkt is mal-formed, toss it */
12843 			goto drop_pkt;
12844 		case 1:
12845 			/* pkt is okay and arrived on a tunnel */
12846 			/*
12847 			 * If we are running a multicast router
12848 			 *  we need to see all igmp packets.
12849 			 */
12850 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12851 				*dstp = INADDR_BROADCAST;
12852 				*ll_multicast = 1;
12853 				return (B_FALSE);
12854 			}
12855 
12856 			goto drop_pkt;
12857 		}
12858 	}
12859 
12860 	ILM_WALKER_HOLD(ill);
12861 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12862 		/*
12863 		 * This might just be caused by the fact that
12864 		 * multiple IP Multicast addresses map to the same
12865 		 * link layer multicast - no need to increment counter!
12866 		 */
12867 		ILM_WALKER_RELE(ill);
12868 		freemsg(mp);
12869 		return (B_TRUE);
12870 	}
12871 	ILM_WALKER_RELE(ill);
12872 done:
12873 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12874 	/*
12875 	 * This assumes the we deliver to all streams for multicast
12876 	 * and broadcast packets.
12877 	 */
12878 	*dstp = INADDR_BROADCAST;
12879 	*ll_multicast = 1;
12880 	return (B_FALSE);
12881 drop_pkt:
12882 	ip2dbg(("ip_rput: drop pkt\n"));
12883 	freemsg(mp);
12884 	return (B_TRUE);
12885 }
12886 
12887 static boolean_t
12888 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12889     int *ll_multicast, mblk_t **mpp)
12890 {
12891 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12892 	boolean_t must_copy = B_FALSE;
12893 	struct iocblk   *iocp;
12894 	ipha_t		*ipha;
12895 
12896 #define	rptr    ((uchar_t *)ipha)
12897 
12898 	first_mp = *first_mpp;
12899 	mp = *mpp;
12900 
12901 	ASSERT(first_mp == mp);
12902 
12903 	/*
12904 	 * if db_ref > 1 then copymsg and free original. Packet may be
12905 	 * changed and do not want other entity who has a reference to this
12906 	 * message to trip over the changes. This is a blind change because
12907 	 * trying to catch all places that might change packet is too
12908 	 * difficult (since it may be a module above this one)
12909 	 *
12910 	 * This corresponds to the non-fast path case. We walk down the full
12911 	 * chain in this case, and check the db_ref count of all the dblks,
12912 	 * and do a copymsg if required. It is possible that the db_ref counts
12913 	 * of the data blocks in the mblk chain can be different.
12914 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12915 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12916 	 * 'snoop' is running.
12917 	 */
12918 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12919 		if (mp1->b_datap->db_ref > 1) {
12920 			must_copy = B_TRUE;
12921 			break;
12922 		}
12923 	}
12924 
12925 	if (must_copy) {
12926 		mp1 = copymsg(mp);
12927 		if (mp1 == NULL) {
12928 			for (mp1 = mp; mp1 != NULL;
12929 			    mp1 = mp1->b_cont) {
12930 				mp1->b_next = NULL;
12931 				mp1->b_prev = NULL;
12932 			}
12933 			freemsg(mp);
12934 			BUMP_MIB(&ip_mib, ipInDiscards);
12935 			return (B_TRUE);
12936 		}
12937 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12938 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12939 			/* Copy b_next - used in M_BREAK messages */
12940 			to_mp->b_next = from_mp->b_next;
12941 			from_mp->b_next = NULL;
12942 			/* Copy b_prev - used by ip_mroute_decap */
12943 			to_mp->b_prev = from_mp->b_prev;
12944 			from_mp->b_prev = NULL;
12945 		}
12946 		*first_mpp = first_mp = mp1;
12947 		freemsg(mp);
12948 		mp = mp1;
12949 		*mpp = mp1;
12950 	}
12951 
12952 	ipha = (ipha_t *)mp->b_rptr;
12953 
12954 	/*
12955 	 * previous code has a case for M_DATA.
12956 	 * We want to check how that happens.
12957 	 */
12958 	ASSERT(first_mp->b_datap->db_type != M_DATA);
12959 	switch (first_mp->b_datap->db_type) {
12960 	case M_PROTO:
12961 	case M_PCPROTO:
12962 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
12963 		    DL_UNITDATA_IND) {
12964 			/* Go handle anything other than data elsewhere. */
12965 			ip_rput_dlpi(q, mp);
12966 			return (B_TRUE);
12967 		}
12968 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
12969 		/* Ditch the DLPI header. */
12970 		mp1 = mp->b_cont;
12971 		ASSERT(first_mp == mp);
12972 		*first_mpp = mp1;
12973 		freeb(mp);
12974 		*mpp = mp1;
12975 		return (B_FALSE);
12976 	case M_BREAK:
12977 		/*
12978 		 * A packet arrives as M_BREAK following a cycle through
12979 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
12980 		 * This is an IP datagram sans lower level header.
12981 		 * M_BREAK are also used to pass back in multicast packets
12982 		 * that are encapsulated with a source route.
12983 		 */
12984 		/* Ditch the M_BREAK mblk */
12985 		mp1 = mp->b_cont;
12986 		ASSERT(first_mp == mp);
12987 		*first_mpp = mp1;
12988 		freeb(mp);
12989 		mp = mp1;
12990 		mp->b_next = NULL;
12991 		*mpp = mp;
12992 		*ll_multicast = 0;
12993 		return (B_FALSE);
12994 	case M_IOCACK:
12995 		ip1dbg(("got iocack "));
12996 		iocp = (struct iocblk *)mp->b_rptr;
12997 		switch (iocp->ioc_cmd) {
12998 		case DL_IOC_HDR_INFO:
12999 			ill = (ill_t *)q->q_ptr;
13000 			ill_fastpath_ack(ill, mp);
13001 			return (B_TRUE);
13002 		case SIOCSTUNPARAM:
13003 		case OSIOCSTUNPARAM:
13004 			/* Go through qwriter_ip */
13005 			break;
13006 		case SIOCGTUNPARAM:
13007 		case OSIOCGTUNPARAM:
13008 			ip_rput_other(NULL, q, mp, NULL);
13009 			return (B_TRUE);
13010 		default:
13011 			putnext(q, mp);
13012 			return (B_TRUE);
13013 		}
13014 		/* FALLTHRU */
13015 	case M_ERROR:
13016 	case M_HANGUP:
13017 		/*
13018 		 * Since this is on the ill stream we unconditionally
13019 		 * bump up the refcount
13020 		 */
13021 		ill_refhold(ill);
13022 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13023 		    B_FALSE);
13024 		return (B_TRUE);
13025 	case M_CTL:
13026 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13027 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13028 			IPHADA_M_CTL)) {
13029 			/*
13030 			 * It's an IPsec accelerated packet.
13031 			 * Make sure that the ill from which we received the
13032 			 * packet has enabled IPsec hardware acceleration.
13033 			 */
13034 			if (!(ill->ill_capabilities &
13035 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13036 				/* IPsec kstats: bean counter */
13037 				freemsg(mp);
13038 				return (B_TRUE);
13039 			}
13040 
13041 			/*
13042 			 * Make mp point to the mblk following the M_CTL,
13043 			 * then process according to type of mp.
13044 			 * After this processing, first_mp will point to
13045 			 * the data-attributes and mp to the pkt following
13046 			 * the M_CTL.
13047 			 */
13048 			mp = first_mp->b_cont;
13049 			if (mp == NULL) {
13050 				freemsg(first_mp);
13051 				return (B_TRUE);
13052 			}
13053 			/*
13054 			 * A Hardware Accelerated packet can only be M_DATA
13055 			 * ESP or AH packet.
13056 			 */
13057 			if (mp->b_datap->db_type != M_DATA) {
13058 				/* non-M_DATA IPsec accelerated packet */
13059 				IPSECHW_DEBUG(IPSECHW_PKT,
13060 				    ("non-M_DATA IPsec accelerated pkt\n"));
13061 				freemsg(first_mp);
13062 				return (B_TRUE);
13063 			}
13064 			ipha = (ipha_t *)mp->b_rptr;
13065 			if (ipha->ipha_protocol != IPPROTO_AH &&
13066 			    ipha->ipha_protocol != IPPROTO_ESP) {
13067 				IPSECHW_DEBUG(IPSECHW_PKT,
13068 				    ("non-M_DATA IPsec accelerated pkt\n"));
13069 				freemsg(first_mp);
13070 				return (B_TRUE);
13071 			}
13072 			*mpp = mp;
13073 			return (B_FALSE);
13074 		}
13075 		putnext(q, mp);
13076 		return (B_TRUE);
13077 	case M_FLUSH:
13078 		if (*mp->b_rptr & FLUSHW) {
13079 			*mp->b_rptr &= ~FLUSHR;
13080 			qreply(q, mp);
13081 			return (B_TRUE);
13082 		}
13083 		freemsg(mp);
13084 		return (B_TRUE);
13085 	case M_IOCNAK:
13086 		ip1dbg(("got iocnak "));
13087 		iocp = (struct iocblk *)mp->b_rptr;
13088 		switch (iocp->ioc_cmd) {
13089 		case DL_IOC_HDR_INFO:
13090 		case SIOCSTUNPARAM:
13091 		case OSIOCSTUNPARAM:
13092 			/*
13093 			 * Since this is on the ill stream we unconditionally
13094 			 * bump up the refcount
13095 			 */
13096 			ill_refhold(ill);
13097 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13098 			    CUR_OP, B_FALSE);
13099 			return (B_TRUE);
13100 		case SIOCGTUNPARAM:
13101 		case OSIOCGTUNPARAM:
13102 			ip_rput_other(NULL, q, mp, NULL);
13103 			return (B_TRUE);
13104 		default:
13105 			break;
13106 		}
13107 		/* FALLTHRU */
13108 	default:
13109 		putnext(q, mp);
13110 		return (B_TRUE);
13111 	}
13112 }
13113 
13114 /* Read side put procedure.  Packets coming from the wire arrive here. */
13115 void
13116 ip_rput(queue_t *q, mblk_t *mp)
13117 {
13118 	ill_t		*ill;
13119 
13120 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13121 
13122 	ill = (ill_t *)q->q_ptr;
13123 
13124 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13125 		union DL_primitives *dl;
13126 
13127 		/*
13128 		 * Things are opening or closing. Only accept DLPI control
13129 		 * messages. In the open case, the ill->ill_ipif has not yet
13130 		 * been created. In the close case, things hanging off the
13131 		 * ill could have been freed already. In either case it
13132 		 * may not be safe to proceed further.
13133 		 */
13134 
13135 		dl = (union DL_primitives *)mp->b_rptr;
13136 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13137 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13138 			/*
13139 			 * Also SIOC[GS]TUN* ioctls can come here.
13140 			 */
13141 			inet_freemsg(mp);
13142 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13143 			    "ip_input_end: q %p (%S)", q, "uninit");
13144 			return;
13145 		}
13146 	}
13147 
13148 	/*
13149 	 * if db_ref > 1 then copymsg and free original. Packet may be
13150 	 * changed and we do not want the other entity who has a reference to
13151 	 * this message to trip over the changes. This is a blind change because
13152 	 * trying to catch all places that might change the packet is too
13153 	 * difficult.
13154 	 *
13155 	 * This corresponds to the fast path case, where we have a chain of
13156 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13157 	 * in the mblk chain. There doesn't seem to be a reason why a device
13158 	 * driver would send up data with varying db_ref counts in the mblk
13159 	 * chain. In any case the Fast path is a private interface, and our
13160 	 * drivers don't do such a thing. Given the above assumption, there is
13161 	 * no need to walk down the entire mblk chain (which could have a
13162 	 * potential performance problem)
13163 	 */
13164 	if (mp->b_datap->db_ref > 1) {
13165 		mblk_t  *mp1;
13166 		boolean_t adjusted = B_FALSE;
13167 		IP_STAT(ip_db_ref);
13168 
13169 		/*
13170 		 * The IP_RECVSLLA option depends on having the link layer
13171 		 * header. First check that:
13172 		 * a> the underlying device is of type ether, since this
13173 		 * option is currently supported only over ethernet.
13174 		 * b> there is enough room to copy over the link layer header.
13175 		 *
13176 		 * Once the checks are done, adjust rptr so that the link layer
13177 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13178 		 * be returned by some non-ethernet drivers but in this case the
13179 		 * second check will fail.
13180 		 */
13181 		if (ill->ill_type == IFT_ETHER &&
13182 		    (mp->b_rptr - mp->b_datap->db_base) >=
13183 		    sizeof (struct ether_header)) {
13184 			mp->b_rptr -= sizeof (struct ether_header);
13185 			adjusted = B_TRUE;
13186 		}
13187 		mp1 = copymsg(mp);
13188 		if (mp1 == NULL) {
13189 			/* Clear b_next - used in M_BREAK messages */
13190 			mp->b_next = NULL;
13191 			/* clear b_prev - used by ip_mroute_decap */
13192 			mp->b_prev = NULL;
13193 			freemsg(mp);
13194 			BUMP_MIB(&ip_mib, ipInDiscards);
13195 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13196 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13197 			return;
13198 		}
13199 		if (adjusted) {
13200 			/*
13201 			 * Copy is done. Restore the pointer in the _new_ mblk
13202 			 */
13203 			mp1->b_rptr += sizeof (struct ether_header);
13204 		}
13205 		/* Copy b_next - used in M_BREAK messages */
13206 		mp1->b_next = mp->b_next;
13207 		mp->b_next = NULL;
13208 		/* Copy b_prev - used by ip_mroute_decap */
13209 		mp1->b_prev = mp->b_prev;
13210 		mp->b_prev = NULL;
13211 		freemsg(mp);
13212 		mp = mp1;
13213 	}
13214 
13215 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13216 	    "ip_rput_end: q %p (%S)", q, "end");
13217 
13218 	ip_input(ill, NULL, mp, 0);
13219 }
13220 
13221 /*
13222  * Direct read side procedure capable of dealing with chains. GLDv3 based
13223  * drivers call this function directly with mblk chains while STREAMS
13224  * read side procedure ip_rput() calls this for single packet with ip_ring
13225  * set to NULL to process one packet at a time.
13226  *
13227  * The ill will always be valid if this function is called directly from
13228  * the driver.
13229  */
13230 /*ARGSUSED*/
13231 void
13232 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13233 {
13234 	ipaddr_t		dst;
13235 	ire_t			*ire;
13236 	ipha_t			*ipha;
13237 	uint_t			pkt_len;
13238 	ssize_t			len;
13239 	uint_t			opt_len;
13240 	int			ll_multicast;
13241 	int			cgtp_flt_pkt;
13242 	queue_t			*q = ill->ill_rq;
13243 	squeue_t		*curr_sqp = NULL;
13244 	mblk_t 			*head = NULL;
13245 	mblk_t			*tail = NULL;
13246 	mblk_t			*first_mp;
13247 	mblk_t 			*mp;
13248 	int			cnt = 0;
13249 
13250 	ASSERT(mp_chain != NULL);
13251 	ASSERT(ill != NULL);
13252 
13253 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13254 
13255 #define	rptr	((uchar_t *)ipha)
13256 
13257 	while (mp_chain != NULL) {
13258 		first_mp = mp = mp_chain;
13259 		mp_chain = mp_chain->b_next;
13260 		mp->b_next = NULL;
13261 		ll_multicast = 0;
13262 		ire = NULL;
13263 
13264 		/*
13265 		 * ip_input fast path
13266 		 */
13267 
13268 		/* mblk type is not M_DATA */
13269 		if (mp->b_datap->db_type != M_DATA) {
13270 			if (ip_rput_process_notdata(q, &first_mp, ill,
13271 			    &ll_multicast, &mp))
13272 				continue;
13273 		}
13274 
13275 		ASSERT(mp->b_datap->db_type == M_DATA);
13276 		ASSERT(mp->b_datap->db_ref == 1);
13277 
13278 		/*
13279 		 * Invoke the CGTP (multirouting) filtering module to process
13280 		 * the incoming packet. Packets identified as duplicates
13281 		 * must be discarded. Filtering is active only if the
13282 		 * the ip_cgtp_filter ndd variable is non-zero.
13283 		 */
13284 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13285 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13286 			cgtp_flt_pkt =
13287 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13288 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13289 				freemsg(first_mp);
13290 				continue;
13291 			}
13292 		}
13293 
13294 		ipha = (ipha_t *)mp->b_rptr;
13295 		len = mp->b_wptr - rptr;
13296 
13297 		BUMP_MIB(&ip_mib, ipInReceives);
13298 
13299 		/*
13300 		 * IP header ptr not aligned?
13301 		 * OR IP header not complete in first mblk
13302 		 */
13303 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13304 			if (!ip_check_and_align_header(q, mp))
13305 				continue;
13306 			ipha = (ipha_t *)mp->b_rptr;
13307 			len = mp->b_wptr - rptr;
13308 		}
13309 
13310 		/* multiple mblk or too short */
13311 		pkt_len = ntohs(ipha->ipha_length);
13312 		len -= pkt_len;
13313 		if (len != 0) {
13314 			/*
13315 			 * Make sure we have data length consistent
13316 			 * with the IP header.
13317 			 */
13318 			if (mp->b_cont == NULL) {
13319 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13320 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13321 					ip2dbg(("ip_input: drop pkt\n"));
13322 					freemsg(mp);
13323 					continue;
13324 				}
13325 				mp->b_wptr = rptr + pkt_len;
13326 			} else if (len += msgdsize(mp->b_cont)) {
13327 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13328 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13329 					ip2dbg(("ip_input: drop pkt\n"));
13330 					freemsg(mp);
13331 					continue;
13332 				}
13333 				(void) adjmsg(mp, -len);
13334 				IP_STAT(ip_multimblk3);
13335 			}
13336 		}
13337 
13338 		if (ip_loopback_src_or_dst(ipha, ill)) {
13339 			ip2dbg(("ip_input: drop pkt\n"));
13340 			freemsg(mp);
13341 			continue;
13342 		}
13343 
13344 		opt_len = ipha->ipha_version_and_hdr_length -
13345 		    IP_SIMPLE_HDR_VERSION;
13346 		/* IP version bad or there are IP options */
13347 		if (opt_len) {
13348 			if (len != 0)
13349 				IP_STAT(ip_multimblk4);
13350 			else
13351 				IP_STAT(ip_ipoptions);
13352 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13353 				continue;
13354 		} else {
13355 			dst = ipha->ipha_dst;
13356 		}
13357 
13358 		/*
13359 		 * If rsvpd is running, let RSVP daemon handle its processing
13360 		 * and forwarding of RSVP multicast/unicast packets.
13361 		 * If rsvpd is not running but mrouted is running, RSVP
13362 		 * multicast packets are forwarded as multicast traffic
13363 		 * and RSVP unicast packets are forwarded by unicast router.
13364 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13365 		 * packets are not forwarded, but the unicast packets are
13366 		 * forwarded like unicast traffic.
13367 		 */
13368 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13369 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13370 			/* RSVP packet and rsvpd running. Treat as ours */
13371 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13372 			/*
13373 			 * This assumes that we deliver to all streams for
13374 			 * multicast and broadcast packets.
13375 			 * We have to force ll_multicast to 1 to handle the
13376 			 * M_DATA messages passed in from ip_mroute_decap.
13377 			 */
13378 			dst = INADDR_BROADCAST;
13379 			ll_multicast = 1;
13380 		} else if (CLASSD(dst)) {
13381 			/* packet is multicast */
13382 			mp->b_next = NULL;
13383 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13384 			    &ll_multicast, &dst))
13385 				continue;
13386 		}
13387 
13388 
13389 		/*
13390 		 * Check if the packet is coming from the Mobile IP
13391 		 * forward tunnel interface
13392 		 */
13393 		if (ill->ill_srcif_refcnt > 0) {
13394 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13395 			    NULL, ill, MATCH_IRE_TYPE);
13396 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13397 			    ire->ire_ipif->ipif_net_type ==
13398 			    IRE_IF_RESOLVER) {
13399 				/* We need to resolve the link layer info */
13400 				ire_refrele(ire);
13401 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13402 				    ll_multicast, dst);
13403 				continue;
13404 			}
13405 		}
13406 
13407 		if (ire == NULL)
13408 			ire = ire_cache_lookup(dst, ALL_ZONES);
13409 
13410 		/*
13411 		 * If mipagent is running and reverse tunnel is created as per
13412 		 * mobile node request, then any packet coming through the
13413 		 * incoming interface from the mobile-node, should be reverse
13414 		 * tunneled to it's home agent except those that are destined
13415 		 * to foreign agent only.
13416 		 * This needs source address based ire lookup. The routing
13417 		 * entries for source address based lookup are only created by
13418 		 * mipagent program only when a reverse tunnel is created.
13419 		 * Reference : RFC2002, RFC2344
13420 		 */
13421 		if (ill->ill_mrtun_refcnt > 0) {
13422 			ipaddr_t	srcaddr;
13423 			ire_t		*tmp_ire;
13424 
13425 			tmp_ire = ire;	/* Save, we might need it later */
13426 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13427 			    ire->ire_type != IRE_BROADCAST)) {
13428 				srcaddr = ipha->ipha_src;
13429 				ire = ire_mrtun_lookup(srcaddr, ill);
13430 				if (ire != NULL) {
13431 					/*
13432 					 * Should not be getting iphada packet
13433 					 * here. we should only get those for
13434 					 * IRE_LOCAL traffic, excluded above.
13435 					 * Fail-safe (drop packet) in the event
13436 					 * hardware is misbehaving.
13437 					 */
13438 					if (first_mp != mp) {
13439 						/* IPsec KSTATS: beancount me */
13440 						freemsg(first_mp);
13441 					} else {
13442 						/*
13443 						 * This packet must be forwarded
13444 						 * to Reverse Tunnel
13445 						 */
13446 						ip_mrtun_forward(ire, ill, mp);
13447 					}
13448 					ire_refrele(ire);
13449 					if (tmp_ire != NULL)
13450 						ire_refrele(tmp_ire);
13451 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13452 					    "ip_input_end: q %p (%S)",
13453 					    q, "uninit");
13454 					continue;
13455 				}
13456 			}
13457 			/*
13458 			 * If this packet is from a non-mobilenode  or a
13459 			 * mobile-node which does not request reverse
13460 			 * tunnel service
13461 			 */
13462 			ire = tmp_ire;
13463 		}
13464 
13465 
13466 		/*
13467 		 * If we reach here that means the incoming packet satisfies
13468 		 * one of the following conditions:
13469 		 *   - packet is from a mobile node which does not request
13470 		 *	reverse tunnel
13471 		 *   - packet is from a non-mobile node, which is the most
13472 		 *	common case
13473 		 *   - packet is from a reverse tunnel enabled mobile node
13474 		 *	and destined to foreign agent only
13475 		 */
13476 
13477 		if (ire == NULL) {
13478 			/*
13479 			 * No IRE for this destination, so it can't be for us.
13480 			 * Unless we are forwarding, drop the packet.
13481 			 * We have to let source routed packets through
13482 			 * since we don't yet know if they are 'ping -l'
13483 			 * packets i.e. if they will go out over the
13484 			 * same interface as they came in on.
13485 			 */
13486 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13487 			continue;
13488 		}
13489 
13490 		/*
13491 		 * Broadcast IRE may indicate either broadcast or
13492 		 * multicast packet
13493 		 */
13494 		if (ire->ire_type == IRE_BROADCAST) {
13495 			/*
13496 			 * Skip broadcast checks if packet is UDP multicast;
13497 			 * we'd rather not enter ip_rput_process_broadcast()
13498 			 * unless the packet is broadcast for real, since
13499 			 * that routine is a no-op for multicast.
13500 			 */
13501 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
13502 			    !CLASSD(ipha->ipha_dst)) &&
13503 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13504 			    dst, cgtp_flt_pkt, ll_multicast)) {
13505 				continue;
13506 			}
13507 		} else if (ire->ire_stq != NULL) {
13508 			/* fowarding? */
13509 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13510 			    ll_multicast);
13511 			continue;
13512 		}
13513 
13514 		/* packet not for us */
13515 		if (ire->ire_rfq != q) {
13516 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13517 				continue;
13518 			}
13519 		}
13520 
13521 		switch (ipha->ipha_protocol) {
13522 		case IPPROTO_TCP:
13523 			ASSERT(first_mp == mp);
13524 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13525 				mp, 0, q, ip_ring)) != NULL) {
13526 				if (curr_sqp == NULL) {
13527 					curr_sqp = GET_SQUEUE(mp);
13528 					ASSERT(cnt == 0);
13529 					cnt++;
13530 					head = tail = mp;
13531 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13532 					ASSERT(tail != NULL);
13533 					cnt++;
13534 					tail->b_next = mp;
13535 					tail = mp;
13536 				} else {
13537 					/*
13538 					 * A different squeue. Send the
13539 					 * chain for the previous squeue on
13540 					 * its way. This shouldn't happen
13541 					 * often unless interrupt binding
13542 					 * changes.
13543 					 */
13544 					IP_STAT(ip_input_multi_squeue);
13545 					squeue_enter_chain(curr_sqp, head,
13546 					    tail, cnt, SQTAG_IP_INPUT);
13547 					curr_sqp = GET_SQUEUE(mp);
13548 					head = mp;
13549 					tail = mp;
13550 					cnt = 1;
13551 				}
13552 			}
13553 			IRE_REFRELE(ire);
13554 			continue;
13555 		case IPPROTO_UDP:
13556 			ASSERT(first_mp == mp);
13557 			ip_udp_input(q, mp, ipha, ire, ill);
13558 			IRE_REFRELE(ire);
13559 			continue;
13560 		case IPPROTO_SCTP:
13561 			ASSERT(first_mp == mp);
13562 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13563 			    q, dst);
13564 			continue;
13565 		default:
13566 			ip_proto_input(q, first_mp, ipha, ire, ill);
13567 			IRE_REFRELE(ire);
13568 			continue;
13569 		}
13570 	}
13571 
13572 	if (head != NULL)
13573 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13574 
13575 	/*
13576 	 * This code is there just to make netperf/ttcp look good.
13577 	 *
13578 	 * Its possible that after being in polling mode (and having cleared
13579 	 * the backlog), squeues have turned the interrupt frequency higher
13580 	 * to improve latency at the expense of more CPU utilization (less
13581 	 * packets per interrupts or more number of interrupts). Workloads
13582 	 * like ttcp/netperf do manage to tickle polling once in a while
13583 	 * but for the remaining time, stay in higher interrupt mode since
13584 	 * their packet arrival rate is pretty uniform and this shows up
13585 	 * as higher CPU utilization. Since people care about CPU utilization
13586 	 * while running netperf/ttcp, turn the interrupt frequency back to
13587 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13588 	 */
13589 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13590 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13591 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13592 			ip_ring->rr_blank(ip_ring->rr_handle,
13593 			    ip_ring->rr_normal_blank_time,
13594 			    ip_ring->rr_normal_pkt_cnt);
13595 		}
13596 	}
13597 
13598 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13599 	    "ip_input_end: q %p (%S)", q, "end");
13600 #undef	rptr
13601 }
13602 
13603 static void
13604 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13605     t_uscalar_t err)
13606 {
13607 	if (dl_err == DL_SYSERR) {
13608 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13609 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13610 		    ill->ill_name, dlpi_prim_str(prim), err);
13611 		return;
13612 	}
13613 
13614 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13615 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13616 	    dlpi_err_str(dl_err));
13617 }
13618 
13619 /*
13620  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13621  * than DL_UNITDATA_IND messages. If we need to process this message
13622  * exclusively, we call qwriter_ip, in which case we also need to call
13623  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13624  */
13625 void
13626 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13627 {
13628 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13629 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13630 	ill_t		*ill;
13631 
13632 	ip1dbg(("ip_rput_dlpi"));
13633 	ill = (ill_t *)q->q_ptr;
13634 	switch (dloa->dl_primitive) {
13635 	case DL_ERROR_ACK:
13636 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13637 		    "%s (0x%x), unix %u\n", ill->ill_name,
13638 		    dlpi_prim_str(dlea->dl_error_primitive),
13639 		    dlea->dl_error_primitive,
13640 		    dlpi_err_str(dlea->dl_errno),
13641 		    dlea->dl_errno,
13642 		    dlea->dl_unix_errno));
13643 		switch (dlea->dl_error_primitive) {
13644 		case DL_NOTIFY_REQ:
13645 		case DL_UNBIND_REQ:
13646 		case DL_ATTACH_REQ:
13647 		case DL_DETACH_REQ:
13648 		case DL_INFO_REQ:
13649 		case DL_BIND_REQ:
13650 		case DL_ENABMULTI_REQ:
13651 		case DL_PHYS_ADDR_REQ:
13652 		case DL_CAPABILITY_REQ:
13653 		case DL_CONTROL_REQ:
13654 			/*
13655 			 * Refhold the ill to match qwriter_ip which does a
13656 			 * refrele. Since this is on the ill stream we
13657 			 * unconditionally bump up the refcount without
13658 			 * checking for ILL_CAN_LOOKUP
13659 			 */
13660 			ill_refhold(ill);
13661 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13662 			    CUR_OP, B_FALSE);
13663 			return;
13664 		case DL_DISABMULTI_REQ:
13665 			freemsg(mp);	/* Don't want to pass this up */
13666 			return;
13667 		default:
13668 			break;
13669 		}
13670 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13671 		    dlea->dl_errno, dlea->dl_unix_errno);
13672 		freemsg(mp);
13673 		return;
13674 	case DL_INFO_ACK:
13675 	case DL_BIND_ACK:
13676 	case DL_PHYS_ADDR_ACK:
13677 	case DL_NOTIFY_ACK:
13678 	case DL_CAPABILITY_ACK:
13679 	case DL_CONTROL_ACK:
13680 		/*
13681 		 * Refhold the ill to match qwriter_ip which does a refrele
13682 		 * Since this is on the ill stream we unconditionally
13683 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13684 		 */
13685 		ill_refhold(ill);
13686 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13687 		    CUR_OP, B_FALSE);
13688 		return;
13689 	case DL_NOTIFY_IND:
13690 		ill_refhold(ill);
13691 		/*
13692 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13693 		 * relation to the current ioctl in progress (if any). Hence we
13694 		 * pass in NEW_OP in this case.
13695 		 */
13696 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13697 		    NEW_OP, B_FALSE);
13698 		return;
13699 	case DL_OK_ACK:
13700 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13701 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13702 		switch (dloa->dl_correct_primitive) {
13703 		case DL_UNBIND_REQ:
13704 			mutex_enter(&ill->ill_lock);
13705 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13706 			cv_signal(&ill->ill_cv);
13707 			mutex_exit(&ill->ill_lock);
13708 			/* FALLTHRU */
13709 		case DL_ATTACH_REQ:
13710 		case DL_DETACH_REQ:
13711 			/*
13712 			 * Refhold the ill to match qwriter_ip which does a
13713 			 * refrele. Since this is on the ill stream we
13714 			 * unconditionally bump up the refcount
13715 			 */
13716 			ill_refhold(ill);
13717 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13718 			    CUR_OP, B_FALSE);
13719 			return;
13720 		case DL_ENABMULTI_REQ:
13721 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13722 				ill->ill_dlpi_multicast_state = IDMS_OK;
13723 			break;
13724 
13725 		}
13726 		break;
13727 	default:
13728 		break;
13729 	}
13730 	freemsg(mp);
13731 }
13732 
13733 /*
13734  * Handling of DLPI messages that require exclusive access to the ipsq.
13735  *
13736  * Need to do ill_pending_mp_release on ioctl completion, which could
13737  * happen here. (along with mi_copy_done)
13738  */
13739 /* ARGSUSED */
13740 static void
13741 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13742 {
13743 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13744 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13745 	int		err = 0;
13746 	ill_t		*ill;
13747 	ipif_t		*ipif = NULL;
13748 	mblk_t		*mp1 = NULL;
13749 	conn_t		*connp = NULL;
13750 	t_uscalar_t	physaddr_req;
13751 	mblk_t		*mp_hw;
13752 	union DL_primitives *dlp;
13753 	boolean_t	success;
13754 	boolean_t	ioctl_aborted = B_FALSE;
13755 	boolean_t	log = B_TRUE;
13756 
13757 	ip1dbg(("ip_rput_dlpi_writer .."));
13758 	ill = (ill_t *)q->q_ptr;
13759 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13760 
13761 	ASSERT(IAM_WRITER_ILL(ill));
13762 
13763 	/*
13764 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13765 	 * both are null or non-null. However we can assert that only
13766 	 * after grabbing the ipsq_lock. So we don't make any assertion
13767 	 * here and in other places in the code.
13768 	 */
13769 	ipif = ipsq->ipsq_pending_ipif;
13770 	/*
13771 	 * The current ioctl could have been aborted by the user and a new
13772 	 * ioctl to bring up another ill could have started. We could still
13773 	 * get a response from the driver later.
13774 	 */
13775 	if (ipif != NULL && ipif->ipif_ill != ill)
13776 		ioctl_aborted = B_TRUE;
13777 
13778 	switch (dloa->dl_primitive) {
13779 	case DL_ERROR_ACK:
13780 		switch (dlea->dl_error_primitive) {
13781 		case DL_UNBIND_REQ:
13782 		case DL_ATTACH_REQ:
13783 		case DL_DETACH_REQ:
13784 		case DL_INFO_REQ:
13785 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13786 			break;
13787 		case DL_NOTIFY_REQ:
13788 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13789 			log = B_FALSE;
13790 			break;
13791 		case DL_PHYS_ADDR_REQ:
13792 			/*
13793 			 * For IPv6 only, there are two additional
13794 			 * phys_addr_req's sent to the driver to get the
13795 			 * IPv6 token and lla. This allows IP to acquire
13796 			 * the hardware address format for a given interface
13797 			 * without having built in knowledge of the hardware
13798 			 * address. ill_phys_addr_pend keeps track of the last
13799 			 * DL_PAR sent so we know which response we are
13800 			 * dealing with. ill_dlpi_done will update
13801 			 * ill_phys_addr_pend when it sends the next req.
13802 			 * We don't complete the IOCTL until all three DL_PARs
13803 			 * have been attempted, so set *_len to 0 and break.
13804 			 */
13805 			physaddr_req = ill->ill_phys_addr_pend;
13806 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13807 			if (physaddr_req == DL_IPV6_TOKEN) {
13808 				ill->ill_token_length = 0;
13809 				log = B_FALSE;
13810 				break;
13811 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13812 				ill->ill_nd_lla_len = 0;
13813 				log = B_FALSE;
13814 				break;
13815 			}
13816 			/*
13817 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13818 			 * We presumably have an IOCTL hanging out waiting
13819 			 * for completion. Find it and complete the IOCTL
13820 			 * with the error noted.
13821 			 * However, ill_dl_phys was called on an ill queue
13822 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13823 			 * set. But the ioctl is known to be pending on ill_wq.
13824 			 */
13825 			if (!ill->ill_ifname_pending)
13826 				break;
13827 			ill->ill_ifname_pending = 0;
13828 			if (!ioctl_aborted)
13829 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13830 			if (mp1 != NULL) {
13831 				/*
13832 				 * This operation (SIOCSLIFNAME) must have
13833 				 * happened on the ill. Assert there is no conn
13834 				 */
13835 				ASSERT(connp == NULL);
13836 				q = ill->ill_wq;
13837 			}
13838 			break;
13839 		case DL_BIND_REQ:
13840 			ill_dlpi_done(ill, DL_BIND_REQ);
13841 			if (ill->ill_ifname_pending)
13842 				break;
13843 			/*
13844 			 * Something went wrong with the bind.  We presumably
13845 			 * have an IOCTL hanging out waiting for completion.
13846 			 * Find it, take down the interface that was coming
13847 			 * up, and complete the IOCTL with the error noted.
13848 			 */
13849 			if (!ioctl_aborted)
13850 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13851 			if (mp1 != NULL) {
13852 				/*
13853 				 * This operation (SIOCSLIFFLAGS) must have
13854 				 * happened from a conn.
13855 				 */
13856 				ASSERT(connp != NULL);
13857 				q = CONNP_TO_WQ(connp);
13858 				if (ill->ill_move_in_progress) {
13859 					ILL_CLEAR_MOVE(ill);
13860 				}
13861 				(void) ipif_down(ipif, NULL, NULL);
13862 				/* error is set below the switch */
13863 			}
13864 			break;
13865 		case DL_ENABMULTI_REQ:
13866 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13867 
13868 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13869 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13870 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13871 				ipif_t *ipif;
13872 
13873 				log = B_FALSE;
13874 				printf("ip: joining multicasts failed (%d)"
13875 				    " on %s - will use link layer "
13876 				    "broadcasts for multicast\n",
13877 				    dlea->dl_errno, ill->ill_name);
13878 
13879 				/*
13880 				 * Set up the multicast mapping alone.
13881 				 * writer, so ok to access ill->ill_ipif
13882 				 * without any lock.
13883 				 */
13884 				ipif = ill->ill_ipif;
13885 				mutex_enter(&ill->ill_phyint->phyint_lock);
13886 				ill->ill_phyint->phyint_flags |=
13887 				    PHYI_MULTI_BCAST;
13888 				mutex_exit(&ill->ill_phyint->phyint_lock);
13889 
13890 				if (!ill->ill_isv6) {
13891 					(void) ipif_arp_setup_multicast(ipif,
13892 					    NULL);
13893 				} else {
13894 					(void) ipif_ndp_setup_multicast(ipif,
13895 					    NULL);
13896 				}
13897 			}
13898 			freemsg(mp);	/* Don't want to pass this up */
13899 			return;
13900 		case DL_CAPABILITY_REQ:
13901 		case DL_CONTROL_REQ:
13902 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13903 			    "DL_CAPABILITY/CONTROL REQ\n"));
13904 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13905 			ill->ill_capab_state = IDMS_FAILED;
13906 			freemsg(mp);
13907 			return;
13908 		}
13909 		/*
13910 		 * Note the error for IOCTL completion (mp1 is set when
13911 		 * ready to complete ioctl). If ill_ifname_pending_err is
13912 		 * set, an error occured during plumbing (ill_ifname_pending),
13913 		 * so we want to report that error.
13914 		 *
13915 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13916 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13917 		 * expected to get errack'd if the driver doesn't support
13918 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13919 		 * if these error conditions are encountered.
13920 		 */
13921 		if (mp1 != NULL) {
13922 			if (ill->ill_ifname_pending_err != 0)  {
13923 				err = ill->ill_ifname_pending_err;
13924 				ill->ill_ifname_pending_err = 0;
13925 			} else {
13926 				err = dlea->dl_unix_errno ?
13927 				    dlea->dl_unix_errno : ENXIO;
13928 			}
13929 		/*
13930 		 * If we're plumbing an interface and an error hasn't already
13931 		 * been saved, set ill_ifname_pending_err to the error passed
13932 		 * up. Ignore the error if log is B_FALSE (see comment above).
13933 		 */
13934 		} else if (log && ill->ill_ifname_pending &&
13935 		    ill->ill_ifname_pending_err == 0) {
13936 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13937 			dlea->dl_unix_errno : ENXIO;
13938 		}
13939 
13940 		if (log)
13941 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13942 			    dlea->dl_errno, dlea->dl_unix_errno);
13943 		break;
13944 	case DL_CAPABILITY_ACK: {
13945 		boolean_t reneg_flag = B_FALSE;
13946 		/* Call a routine to handle this one. */
13947 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13948 		/*
13949 		 * Check if the ACK is due to renegotiation case since we
13950 		 * will need to send a new CAPABILITY_REQ later.
13951 		 */
13952 		if (ill->ill_capab_state == IDMS_RENEG) {
13953 			/* This is the ack for a renogiation case */
13954 			reneg_flag = B_TRUE;
13955 			ill->ill_capab_state = IDMS_UNKNOWN;
13956 		}
13957 		ill_capability_ack(ill, mp);
13958 		if (reneg_flag)
13959 			ill_capability_probe(ill);
13960 		break;
13961 	}
13962 	case DL_CONTROL_ACK:
13963 		/* We treat all of these as "fire and forget" */
13964 		ill_dlpi_done(ill, DL_CONTROL_REQ);
13965 		break;
13966 	case DL_INFO_ACK:
13967 		/* Call a routine to handle this one. */
13968 		ill_dlpi_done(ill, DL_INFO_REQ);
13969 		ip_ll_subnet_defaults(ill, mp);
13970 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
13971 		return;
13972 	case DL_BIND_ACK:
13973 		/*
13974 		 * We should have an IOCTL waiting on this unless
13975 		 * sent by ill_dl_phys, in which case just return
13976 		 */
13977 		ill_dlpi_done(ill, DL_BIND_REQ);
13978 		if (ill->ill_ifname_pending)
13979 			break;
13980 
13981 		if (!ioctl_aborted)
13982 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
13983 		if (mp1 == NULL)
13984 			break;
13985 		ASSERT(connp != NULL);
13986 		q = CONNP_TO_WQ(connp);
13987 
13988 		/*
13989 		 * We are exclusive. So nothing can change even after
13990 		 * we get the pending mp. If need be we can put it back
13991 		 * and restart, as in calling ipif_arp_up()  below.
13992 		 */
13993 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
13994 
13995 		mutex_enter(&ill->ill_lock);
13996 		ill->ill_dl_up = 1;
13997 		mutex_exit(&ill->ill_lock);
13998 
13999 		/*
14000 		 * Now bring up the resolver, when that is
14001 		 * done we'll create IREs and we are done.
14002 		 */
14003 		if (ill->ill_isv6) {
14004 			/*
14005 			 * v6 interfaces.
14006 			 * Unlike ARP which has to do another bind
14007 			 * and attach, once we get here we are
14008 			 * done withh NDP. Except in the case of
14009 			 * ILLF_XRESOLV, in which case we send an
14010 			 * AR_INTERFACE_UP to the external resolver.
14011 			 * If all goes well, the ioctl will complete
14012 			 * in ip_rput(). If there's an error, we
14013 			 * complete it here.
14014 			 */
14015 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14016 			    B_FALSE);
14017 			if (err == 0) {
14018 				if (ill->ill_flags & ILLF_XRESOLV) {
14019 					mutex_enter(&connp->conn_lock);
14020 					mutex_enter(&ill->ill_lock);
14021 					success = ipsq_pending_mp_add(
14022 					    connp, ipif, q, mp1, 0);
14023 					mutex_exit(&ill->ill_lock);
14024 					mutex_exit(&connp->conn_lock);
14025 					if (success) {
14026 						err = ipif_resolver_up(ipif,
14027 						    B_FALSE);
14028 						if (err == EINPROGRESS) {
14029 							freemsg(mp);
14030 							return;
14031 						}
14032 						ASSERT(err != 0);
14033 						mp1 = ipsq_pending_mp_get(ipsq,
14034 						    &connp);
14035 						ASSERT(mp1 != NULL);
14036 					} else {
14037 						/* conn has started closing */
14038 						err = EINTR;
14039 					}
14040 				} else { /* Non XRESOLV interface */
14041 					err = ipif_up_done_v6(ipif);
14042 				}
14043 			}
14044 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14045 			/*
14046 			 * ARP and other v4 external resolvers.
14047 			 * Leave the pending mblk intact so that
14048 			 * the ioctl completes in ip_rput().
14049 			 */
14050 			mutex_enter(&connp->conn_lock);
14051 			mutex_enter(&ill->ill_lock);
14052 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14053 			mutex_exit(&ill->ill_lock);
14054 			mutex_exit(&connp->conn_lock);
14055 			if (success) {
14056 				err = ipif_resolver_up(ipif, B_FALSE);
14057 				if (err == EINPROGRESS) {
14058 					freemsg(mp);
14059 					return;
14060 				}
14061 				ASSERT(err != 0);
14062 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14063 			} else {
14064 				/* The conn has started closing */
14065 				err = EINTR;
14066 			}
14067 		} else {
14068 			/*
14069 			 * This one is complete. Reply to pending ioctl.
14070 			 */
14071 			err = ipif_up_done(ipif);
14072 		}
14073 
14074 		if ((err == 0) && (ill->ill_up_ipifs)) {
14075 			err = ill_up_ipifs(ill, q, mp1);
14076 			if (err == EINPROGRESS) {
14077 				freemsg(mp);
14078 				return;
14079 			}
14080 		}
14081 
14082 		if (ill->ill_up_ipifs) {
14083 			ill_group_cleanup(ill);
14084 		}
14085 
14086 		break;
14087 	case DL_NOTIFY_IND: {
14088 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14089 		ire_t *ire;
14090 		boolean_t need_ire_walk_v4 = B_FALSE;
14091 		boolean_t need_ire_walk_v6 = B_FALSE;
14092 
14093 		/*
14094 		 * Change the address everywhere we need to.
14095 		 * What we're getting here is a link-level addr or phys addr.
14096 		 * The new addr is at notify + notify->dl_addr_offset
14097 		 * The address length is notify->dl_addr_length;
14098 		 */
14099 		switch (notify->dl_notification) {
14100 		case DL_NOTE_PHYS_ADDR:
14101 			mp_hw = copyb(mp);
14102 			if (mp_hw == NULL) {
14103 				err = ENOMEM;
14104 				break;
14105 			}
14106 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14107 			/*
14108 			 * We currently don't support changing
14109 			 * the token via DL_NOTIFY_IND.
14110 			 * When we do support it, we have to consider
14111 			 * what the implications are with respect to
14112 			 * the token and the link local address.
14113 			 */
14114 			mutex_enter(&ill->ill_lock);
14115 			if (dlp->notify_ind.dl_data ==
14116 			    DL_IPV6_LINK_LAYER_ADDR) {
14117 				if (ill->ill_nd_lla_mp != NULL)
14118 					freemsg(ill->ill_nd_lla_mp);
14119 				ill->ill_nd_lla_mp = mp_hw;
14120 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14121 				    dlp->notify_ind.dl_addr_offset;
14122 				ill->ill_nd_lla_len =
14123 				    dlp->notify_ind.dl_addr_length -
14124 				    ABS(ill->ill_sap_length);
14125 				mutex_exit(&ill->ill_lock);
14126 				break;
14127 			} else if (dlp->notify_ind.dl_data ==
14128 			    DL_CURR_PHYS_ADDR) {
14129 				if (ill->ill_phys_addr_mp != NULL)
14130 					freemsg(ill->ill_phys_addr_mp);
14131 				ill->ill_phys_addr_mp = mp_hw;
14132 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14133 				    dlp->notify_ind.dl_addr_offset;
14134 				ill->ill_phys_addr_length =
14135 				    dlp->notify_ind.dl_addr_length -
14136 				    ABS(ill->ill_sap_length);
14137 				if (ill->ill_isv6 &&
14138 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14139 					if (ill->ill_nd_lla_mp != NULL)
14140 						freemsg(ill->ill_nd_lla_mp);
14141 					ill->ill_nd_lla_mp = copyb(mp_hw);
14142 					ill->ill_nd_lla = (uchar_t *)
14143 					    ill->ill_nd_lla_mp->b_rptr +
14144 					    dlp->notify_ind.dl_addr_offset;
14145 					ill->ill_nd_lla_len =
14146 					    ill->ill_phys_addr_length;
14147 				}
14148 			}
14149 			mutex_exit(&ill->ill_lock);
14150 			/*
14151 			 * Send out gratuitous arp request for our new
14152 			 * hardware address.
14153 			 */
14154 			for (ipif = ill->ill_ipif; ipif != NULL;
14155 			    ipif = ipif->ipif_next) {
14156 				if (!(ipif->ipif_flags & IPIF_UP))
14157 					continue;
14158 				if (ill->ill_isv6) {
14159 					ipif_ndp_down(ipif);
14160 					/*
14161 					 * Set B_TRUE to enable
14162 					 * ipif_ndp_up() to send out
14163 					 * unsolicited advertisements.
14164 					 */
14165 					err = ipif_ndp_up(ipif,
14166 					    &ipif->ipif_v6lcl_addr,
14167 					    B_TRUE);
14168 					if (err) {
14169 						ip1dbg((
14170 						    "ip_rput_dlpi_writer: "
14171 						    "Failed to update ndp "
14172 						    "err %d\n", err));
14173 					}
14174 				} else {
14175 					/*
14176 					 * IPv4 ARP case
14177 					 *
14178 					 * Set B_TRUE, as we only want
14179 					 * ipif_resolver_up to send an
14180 					 * AR_ENTRY_ADD request up to
14181 					 * ARP.
14182 					 */
14183 					err = ipif_resolver_up(ipif,
14184 					    B_TRUE);
14185 					if (err) {
14186 						ip1dbg((
14187 						    "ip_rput_dlpi_writer: "
14188 						    "Failed to update arp "
14189 						    "err %d\n", err));
14190 					}
14191 				}
14192 			}
14193 			/*
14194 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14195 			 * case so that all old fastpath information can be
14196 			 * purged from IRE caches.
14197 			 */
14198 		/* FALLTHRU */
14199 		case DL_NOTE_FASTPATH_FLUSH:
14200 			/*
14201 			 * Any fastpath probe sent henceforth will get the
14202 			 * new fp mp. So we first delete any ires that are
14203 			 * waiting for the fastpath. Then walk all ires and
14204 			 * delete the ire or delete the fp mp. In the case of
14205 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14206 			 * recreate the ire's without going through a complex
14207 			 * ipif up/down dance. So we don't delete the ire
14208 			 * itself, but just the ire_fp_mp for these 2 ire's
14209 			 * In the case of the other ire's we delete the ire's
14210 			 * themselves. Access to ire_fp_mp is completely
14211 			 * protected by ire_lock for IRE_MIPRTUN and
14212 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14213 			 * other cases for performance.
14214 			 */
14215 			if (ill->ill_isv6) {
14216 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14217 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14218 				    NULL);
14219 			} else {
14220 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14221 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14222 				    IRE_CACHE | IRE_BROADCAST,
14223 				    ire_fastpath_flush, NULL, ill);
14224 				mutex_enter(&ire_mrtun_lock);
14225 				if (ire_mrtun_count != 0) {
14226 					mutex_exit(&ire_mrtun_lock);
14227 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14228 					    IRE_MIPRTUN, ire_fastpath_flush,
14229 					    NULL, ill);
14230 				} else {
14231 					mutex_exit(&ire_mrtun_lock);
14232 				}
14233 			}
14234 			break;
14235 		case DL_NOTE_SDU_SIZE:
14236 			/*
14237 			 * Change the MTU size of the interface, of all
14238 			 * attached ipif's, and of all relevant ire's.  The
14239 			 * new value's a uint32_t at notify->dl_data.
14240 			 * Mtu change Vs. new ire creation - protocol below.
14241 			 *
14242 			 * a Mark the ipif as IPIF_CHANGING.
14243 			 * b Set the new mtu in the ipif.
14244 			 * c Change the ire_max_frag on all affected ires
14245 			 * d Unmark the IPIF_CHANGING
14246 			 *
14247 			 * To see how the protocol works, assume an interface
14248 			 * route is also being added simultaneously by
14249 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14250 			 * the ire. If the ire is created before step a,
14251 			 * it will be cleaned up by step c. If the ire is
14252 			 * created after step d, it will see the new value of
14253 			 * ipif_mtu. Any attempt to create the ire between
14254 			 * steps a to d will fail because of the IPIF_CHANGING
14255 			 * flag. Note that ire_create() is passed a pointer to
14256 			 * the ipif_mtu, and not the value. During ire_add
14257 			 * under the bucket lock, the ire_max_frag of the
14258 			 * new ire being created is set from the ipif/ire from
14259 			 * which it is being derived.
14260 			 */
14261 			mutex_enter(&ill->ill_lock);
14262 			ill->ill_max_frag = (uint_t)notify->dl_data;
14263 
14264 			/*
14265 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14266 			 * leave it alone
14267 			 */
14268 			if (ill->ill_mtu_userspecified) {
14269 				mutex_exit(&ill->ill_lock);
14270 				break;
14271 			}
14272 			ill->ill_max_mtu = ill->ill_max_frag;
14273 			if (ill->ill_isv6) {
14274 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14275 					ill->ill_max_mtu = IPV6_MIN_MTU;
14276 			} else {
14277 				if (ill->ill_max_mtu < IP_MIN_MTU)
14278 					ill->ill_max_mtu = IP_MIN_MTU;
14279 			}
14280 			for (ipif = ill->ill_ipif; ipif != NULL;
14281 			    ipif = ipif->ipif_next) {
14282 				/*
14283 				 * Don't override the mtu if the user
14284 				 * has explicitly set it.
14285 				 */
14286 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14287 					continue;
14288 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14289 				if (ipif->ipif_isv6)
14290 					ire = ipif_to_ire_v6(ipif);
14291 				else
14292 					ire = ipif_to_ire(ipif);
14293 				if (ire != NULL) {
14294 					ire->ire_max_frag = ipif->ipif_mtu;
14295 					ire_refrele(ire);
14296 				}
14297 				if (ipif->ipif_flags & IPIF_UP) {
14298 					if (ill->ill_isv6)
14299 						need_ire_walk_v6 = B_TRUE;
14300 					else
14301 						need_ire_walk_v4 = B_TRUE;
14302 				}
14303 			}
14304 			mutex_exit(&ill->ill_lock);
14305 			if (need_ire_walk_v4)
14306 				ire_walk_v4(ill_mtu_change, (char *)ill,
14307 				    ALL_ZONES);
14308 			if (need_ire_walk_v6)
14309 				ire_walk_v6(ill_mtu_change, (char *)ill,
14310 				    ALL_ZONES);
14311 			break;
14312 		case DL_NOTE_LINK_UP:
14313 		case DL_NOTE_LINK_DOWN: {
14314 			/*
14315 			 * We are writer. ill / phyint / ipsq assocs stable.
14316 			 * The RUNNING flag reflects the state of the link.
14317 			 */
14318 			phyint_t *phyint = ill->ill_phyint;
14319 			uint64_t new_phyint_flags;
14320 			boolean_t changed = B_FALSE;
14321 
14322 			mutex_enter(&phyint->phyint_lock);
14323 			new_phyint_flags =
14324 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14325 			    phyint->phyint_flags | PHYI_RUNNING :
14326 			    phyint->phyint_flags & ~PHYI_RUNNING;
14327 			if (new_phyint_flags != phyint->phyint_flags) {
14328 				phyint->phyint_flags = new_phyint_flags;
14329 				changed = B_TRUE;
14330 			}
14331 			mutex_exit(&phyint->phyint_lock);
14332 			/*
14333 			 * If the flags have changed, send a message to
14334 			 * the routing socket.
14335 			 */
14336 			if (changed) {
14337 				if (phyint->phyint_illv4 != NULL) {
14338 					ip_rts_ifmsg(
14339 					    phyint->phyint_illv4->ill_ipif);
14340 				}
14341 				if (phyint->phyint_illv6 != NULL) {
14342 					ip_rts_ifmsg(
14343 					    phyint->phyint_illv6->ill_ipif);
14344 				}
14345 			}
14346 			break;
14347 		}
14348 		case DL_NOTE_PROMISC_ON_PHYS:
14349 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14350 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14351 			mutex_enter(&ill->ill_lock);
14352 			ill->ill_promisc_on_phys = B_TRUE;
14353 			mutex_exit(&ill->ill_lock);
14354 			break;
14355 		case DL_NOTE_PROMISC_OFF_PHYS:
14356 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14357 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14358 			mutex_enter(&ill->ill_lock);
14359 			ill->ill_promisc_on_phys = B_FALSE;
14360 			mutex_exit(&ill->ill_lock);
14361 			break;
14362 		case DL_NOTE_CAPAB_RENEG:
14363 			/*
14364 			 * Something changed on the driver side.
14365 			 * It wants us to renegotiate the capabilities
14366 			 * on this ill. The most likely cause is the
14367 			 * aggregation interface under us where a
14368 			 * port got added or went away.
14369 			 *
14370 			 * We reset the capabilities and set the
14371 			 * state to IDMS_RENG so that when the ack
14372 			 * comes back, we can start the
14373 			 * renegotiation process.
14374 			 */
14375 			ill_capability_reset(ill);
14376 			ill->ill_capab_state = IDMS_RENEG;
14377 			break;
14378 		default:
14379 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14380 			    "type 0x%x for DL_NOTIFY_IND\n",
14381 			    notify->dl_notification));
14382 			break;
14383 		}
14384 
14385 		/*
14386 		 * As this is an asynchronous operation, we
14387 		 * should not call ill_dlpi_done
14388 		 */
14389 		break;
14390 	}
14391 	case DL_NOTIFY_ACK:
14392 		/*
14393 		 * Don't really need to check for what notifications
14394 		 * are supported; we'll process what gets sent upstream,
14395 		 * and we know it'll be something we support changing
14396 		 * based on our DL_NOTIFY_REQ.
14397 		 */
14398 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14399 		break;
14400 	case DL_PHYS_ADDR_ACK: {
14401 		/*
14402 		 * We should have an IOCTL waiting on this when request
14403 		 * sent by ill_dl_phys.
14404 		 * However, ill_dl_phys was called on an ill queue (from
14405 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14406 		 * ioctl is known to be pending on ill_wq.
14407 		 * There are two additional phys_addr_req's sent to the
14408 		 * driver to get the token and lla. ill_phys_addr_pend
14409 		 * keeps track of the last one sent so we know which
14410 		 * response we are dealing with. ill_dlpi_done will
14411 		 * update ill_phys_addr_pend when it sends the next req.
14412 		 * We don't complete the IOCTL until all three DL_PARs
14413 		 * have been attempted.
14414 		 *
14415 		 * We don't need any lock to update ill_nd_lla* fields,
14416 		 * since the ill is not yet up, We grab the lock just
14417 		 * for uniformity with other code that accesses ill_nd_lla.
14418 		 */
14419 		physaddr_req = ill->ill_phys_addr_pend;
14420 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14421 		if (physaddr_req == DL_IPV6_TOKEN ||
14422 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14423 			if (physaddr_req == DL_IPV6_TOKEN) {
14424 				/*
14425 				 * bcopy to low-order bits of ill_token
14426 				 *
14427 				 * XXX Temporary hack - currently,
14428 				 * all known tokens are 64 bits,
14429 				 * so I'll cheat for the moment.
14430 				 */
14431 				dlp = (union DL_primitives *)mp->b_rptr;
14432 
14433 				mutex_enter(&ill->ill_lock);
14434 				bcopy((uchar_t *)(mp->b_rptr +
14435 				dlp->physaddr_ack.dl_addr_offset),
14436 				(void *)&ill->ill_token.s6_addr32[2],
14437 				dlp->physaddr_ack.dl_addr_length);
14438 				ill->ill_token_length =
14439 					dlp->physaddr_ack.dl_addr_length;
14440 				mutex_exit(&ill->ill_lock);
14441 			} else {
14442 				ASSERT(ill->ill_nd_lla_mp == NULL);
14443 				mp_hw = copyb(mp);
14444 				if (mp_hw == NULL) {
14445 					err = ENOMEM;
14446 					break;
14447 				}
14448 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14449 				mutex_enter(&ill->ill_lock);
14450 				ill->ill_nd_lla_mp = mp_hw;
14451 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14452 				dlp->physaddr_ack.dl_addr_offset;
14453 				ill->ill_nd_lla_len =
14454 					dlp->physaddr_ack.dl_addr_length;
14455 				mutex_exit(&ill->ill_lock);
14456 			}
14457 			break;
14458 		}
14459 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14460 		ASSERT(ill->ill_phys_addr_mp == NULL);
14461 		if (!ill->ill_ifname_pending)
14462 			break;
14463 		ill->ill_ifname_pending = 0;
14464 		if (!ioctl_aborted)
14465 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14466 		if (mp1 != NULL) {
14467 			ASSERT(connp == NULL);
14468 			q = ill->ill_wq;
14469 		}
14470 		/*
14471 		 * If any error acks received during the plumbing sequence,
14472 		 * ill_ifname_pending_err will be set. Break out and send up
14473 		 * the error to the pending ioctl.
14474 		 */
14475 		if (ill->ill_ifname_pending_err != 0) {
14476 			err = ill->ill_ifname_pending_err;
14477 			ill->ill_ifname_pending_err = 0;
14478 			break;
14479 		}
14480 		/*
14481 		 * Get the interface token.  If the zeroth interface
14482 		 * address is zero then set the address to the link local
14483 		 * address
14484 		 */
14485 		mp_hw = copyb(mp);
14486 		if (mp_hw == NULL) {
14487 			err = ENOMEM;
14488 			break;
14489 		}
14490 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14491 		ill->ill_phys_addr_mp = mp_hw;
14492 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14493 				dlp->physaddr_ack.dl_addr_offset;
14494 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14495 		    ill->ill_phys_addr_length == 0 ||
14496 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14497 			/*
14498 			 * Compatibility: atun driver returns a length of 0.
14499 			 * ipdptp has an ill_phys_addr_length of zero(from
14500 			 * DL_BIND_ACK) but a non-zero length here.
14501 			 * ipd has an ill_phys_addr_length of 4(from
14502 			 * DL_BIND_ACK) but a non-zero length here.
14503 			 */
14504 			ill->ill_phys_addr = NULL;
14505 		} else if (dlp->physaddr_ack.dl_addr_length !=
14506 		    ill->ill_phys_addr_length) {
14507 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14508 			    "Address length mismatch %d %d\n",
14509 			    dlp->physaddr_ack.dl_addr_length,
14510 			    ill->ill_phys_addr_length));
14511 			err = EINVAL;
14512 			break;
14513 		}
14514 		mutex_enter(&ill->ill_lock);
14515 		if (ill->ill_nd_lla_mp == NULL) {
14516 			ill->ill_nd_lla_mp = copyb(mp_hw);
14517 			if (ill->ill_nd_lla_mp == NULL) {
14518 				err = ENOMEM;
14519 				mutex_exit(&ill->ill_lock);
14520 				break;
14521 			}
14522 			ill->ill_nd_lla =
14523 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14524 			    dlp->physaddr_ack.dl_addr_offset;
14525 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14526 		}
14527 		mutex_exit(&ill->ill_lock);
14528 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14529 			(void) ill_setdefaulttoken(ill);
14530 
14531 		/*
14532 		 * If the ill zero interface has a zero address assign
14533 		 * it the proper link local address.
14534 		 */
14535 		ASSERT(ill->ill_ipif->ipif_id == 0);
14536 		if (ipif != NULL &&
14537 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14538 			(void) ipif_setlinklocal(ipif);
14539 		break;
14540 	}
14541 	case DL_OK_ACK:
14542 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14543 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14544 		    dloa->dl_correct_primitive));
14545 		switch (dloa->dl_correct_primitive) {
14546 		case DL_UNBIND_REQ:
14547 		case DL_ATTACH_REQ:
14548 		case DL_DETACH_REQ:
14549 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14550 			break;
14551 		}
14552 		break;
14553 	default:
14554 		break;
14555 	}
14556 
14557 	freemsg(mp);
14558 	if (mp1) {
14559 		struct iocblk *iocp;
14560 		int mode;
14561 
14562 		/*
14563 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14564 		 * SIOCSLIFNAME do a copyout.
14565 		 */
14566 		iocp = (struct iocblk *)mp1->b_rptr;
14567 
14568 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14569 		    iocp->ioc_cmd == SIOCSLIFNAME)
14570 			mode = COPYOUT;
14571 		else
14572 			mode = NO_COPYOUT;
14573 		/*
14574 		 * The ioctl must complete now without EINPROGRESS
14575 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14576 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14577 		 * stuck for ever in the ipsq.
14578 		 */
14579 		ASSERT(err != EINPROGRESS);
14580 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14581 
14582 	}
14583 }
14584 
14585 /*
14586  * ip_rput_other is called by ip_rput to handle messages modifying the global
14587  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14588  */
14589 /* ARGSUSED */
14590 void
14591 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14592 {
14593 	ill_t		*ill;
14594 	struct iocblk	*iocp;
14595 	mblk_t		*mp1;
14596 	conn_t		*connp = NULL;
14597 
14598 	ip1dbg(("ip_rput_other "));
14599 	ill = (ill_t *)q->q_ptr;
14600 	/*
14601 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14602 	 * in which case ipsq is NULL.
14603 	 */
14604 	if (ipsq != NULL) {
14605 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14606 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14607 	}
14608 
14609 	switch (mp->b_datap->db_type) {
14610 	case M_ERROR:
14611 	case M_HANGUP:
14612 		/*
14613 		 * The device has a problem.  We force the ILL down.  It can
14614 		 * be brought up again manually using SIOCSIFFLAGS (via
14615 		 * ifconfig or equivalent).
14616 		 */
14617 		ASSERT(ipsq != NULL);
14618 		if (mp->b_rptr < mp->b_wptr)
14619 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14620 		if (ill->ill_error == 0)
14621 			ill->ill_error = ENXIO;
14622 		if (!ill_down_start(q, mp))
14623 			return;
14624 		ipif_all_down_tail(ipsq, q, mp, NULL);
14625 		break;
14626 	case M_IOCACK:
14627 		iocp = (struct iocblk *)mp->b_rptr;
14628 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14629 		switch (iocp->ioc_cmd) {
14630 		case SIOCSTUNPARAM:
14631 		case OSIOCSTUNPARAM:
14632 			ASSERT(ipsq != NULL);
14633 			/*
14634 			 * Finish socket ioctl passed through to tun.
14635 			 * We should have an IOCTL waiting on this.
14636 			 */
14637 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14638 			if (ill->ill_isv6) {
14639 				struct iftun_req *ta;
14640 
14641 				/*
14642 				 * if a source or destination is
14643 				 * being set, try and set the link
14644 				 * local address for the tunnel
14645 				 */
14646 				ta = (struct iftun_req *)mp->b_cont->
14647 				    b_cont->b_rptr;
14648 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14649 					ipif_set_tun_llink(ill, ta);
14650 				}
14651 
14652 			}
14653 			if (mp1 != NULL) {
14654 				/*
14655 				 * Now copy back the b_next/b_prev used by
14656 				 * mi code for the mi_copy* functions.
14657 				 * See ip_sioctl_tunparam() for the reason.
14658 				 * Also protect against missing b_cont.
14659 				 */
14660 				if (mp->b_cont != NULL) {
14661 					mp->b_cont->b_next =
14662 					    mp1->b_cont->b_next;
14663 					mp->b_cont->b_prev =
14664 					    mp1->b_cont->b_prev;
14665 				}
14666 				inet_freemsg(mp1);
14667 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14668 				ASSERT(connp != NULL);
14669 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14670 				    iocp->ioc_error, NO_COPYOUT,
14671 				    ipsq->ipsq_current_ipif, ipsq);
14672 			} else {
14673 				ASSERT(connp == NULL);
14674 				putnext(q, mp);
14675 			}
14676 			break;
14677 		case SIOCGTUNPARAM:
14678 		case OSIOCGTUNPARAM:
14679 			/*
14680 			 * This is really M_IOCDATA from the tunnel driver.
14681 			 * convert back and complete the ioctl.
14682 			 * We should have an IOCTL waiting on this.
14683 			 */
14684 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14685 			if (mp1) {
14686 				/*
14687 				 * Now copy back the b_next/b_prev used by
14688 				 * mi code for the mi_copy* functions.
14689 				 * See ip_sioctl_tunparam() for the reason.
14690 				 * Also protect against missing b_cont.
14691 				 */
14692 				if (mp->b_cont != NULL) {
14693 					mp->b_cont->b_next =
14694 					    mp1->b_cont->b_next;
14695 					mp->b_cont->b_prev =
14696 					    mp1->b_cont->b_prev;
14697 				}
14698 				inet_freemsg(mp1);
14699 				if (iocp->ioc_error == 0)
14700 					mp->b_datap->db_type = M_IOCDATA;
14701 				ASSERT(connp != NULL);
14702 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14703 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14704 			} else {
14705 				ASSERT(connp == NULL);
14706 				putnext(q, mp);
14707 			}
14708 			break;
14709 		default:
14710 			break;
14711 		}
14712 		break;
14713 	case M_IOCNAK:
14714 		iocp = (struct iocblk *)mp->b_rptr;
14715 
14716 		switch (iocp->ioc_cmd) {
14717 		int mode;
14718 		ipif_t	*ipif;
14719 
14720 		case DL_IOC_HDR_INFO:
14721 			/*
14722 			 * If this was the first attempt turn of the
14723 			 * fastpath probing.
14724 			 */
14725 			mutex_enter(&ill->ill_lock);
14726 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14727 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14728 				mutex_exit(&ill->ill_lock);
14729 				ill_fastpath_nack(ill);
14730 				ip1dbg(("ip_rput: DLPI fastpath off on "
14731 				    "interface %s\n",
14732 				    ill->ill_name));
14733 			} else {
14734 				mutex_exit(&ill->ill_lock);
14735 			}
14736 			freemsg(mp);
14737 			break;
14738 		case SIOCSTUNPARAM:
14739 		case OSIOCSTUNPARAM:
14740 			ASSERT(ipsq != NULL);
14741 			/*
14742 			 * Finish socket ioctl passed through to tun
14743 			 * We should have an IOCTL waiting on this.
14744 			 */
14745 			/* FALLTHRU */
14746 		case SIOCGTUNPARAM:
14747 		case OSIOCGTUNPARAM:
14748 			/*
14749 			 * This is really M_IOCDATA from the tunnel driver.
14750 			 * convert back and complete the ioctl.
14751 			 * We should have an IOCTL waiting on this.
14752 			 */
14753 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14754 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14755 				mp1 = ill_pending_mp_get(ill, &connp,
14756 				    iocp->ioc_id);
14757 				mode = COPYOUT;
14758 				ipsq = NULL;
14759 				ipif = NULL;
14760 			} else {
14761 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14762 				mode = NO_COPYOUT;
14763 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14764 				ipif = ipsq->ipsq_current_ipif;
14765 			}
14766 			if (mp1 != NULL) {
14767 				/*
14768 				 * Now copy back the b_next/b_prev used by
14769 				 * mi code for the mi_copy* functions.
14770 				 * See ip_sioctl_tunparam() for the reason.
14771 				 * Also protect against missing b_cont.
14772 				 */
14773 				if (mp->b_cont != NULL) {
14774 					mp->b_cont->b_next =
14775 					    mp1->b_cont->b_next;
14776 					mp->b_cont->b_prev =
14777 					    mp1->b_cont->b_prev;
14778 				}
14779 				inet_freemsg(mp1);
14780 				if (iocp->ioc_error == 0)
14781 					iocp->ioc_error = EINVAL;
14782 				ASSERT(connp != NULL);
14783 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14784 				    iocp->ioc_error, mode, ipif, ipsq);
14785 			} else {
14786 				ASSERT(connp == NULL);
14787 				putnext(q, mp);
14788 			}
14789 			break;
14790 		default:
14791 			break;
14792 		}
14793 	default:
14794 		break;
14795 	}
14796 }
14797 
14798 /*
14799  * NOTE : This function does not ire_refrele the ire argument passed in.
14800  *
14801  * IPQoS notes
14802  * IP policy is invoked twice for a forwarded packet, once on the read side
14803  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14804  * enabled. An additional parameter, in_ill, has been added for this purpose.
14805  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14806  * because ip_mroute drops this information.
14807  *
14808  */
14809 void
14810 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14811 {
14812 	uint32_t	pkt_len;
14813 	queue_t	*q;
14814 	uint32_t	sum;
14815 #define	rptr	((uchar_t *)ipha)
14816 	uint32_t	max_frag;
14817 	uint32_t	ill_index;
14818 
14819 	/* Get the ill_index of the incoming ILL */
14820 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14821 
14822 	/* Initiate Read side IPPF processing */
14823 	if (IPP_ENABLED(IPP_FWD_IN)) {
14824 		ip_process(IPP_FWD_IN, &mp, ill_index);
14825 		if (mp == NULL) {
14826 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14827 			    "during IPPF processing\n"));
14828 			return;
14829 		}
14830 	}
14831 	pkt_len = ntohs(ipha->ipha_length);
14832 
14833 	/* Adjust the checksum to reflect the ttl decrement. */
14834 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14835 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14836 
14837 	if (ipha->ipha_ttl-- <= 1) {
14838 		if (ip_csum_hdr(ipha)) {
14839 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14840 			goto drop_pkt;
14841 		}
14842 		/*
14843 		 * Note: ire_stq this will be NULL for multicast
14844 		 * datagrams using the long path through arp (the IRE
14845 		 * is not an IRE_CACHE). This should not cause
14846 		 * problems since we don't generate ICMP errors for
14847 		 * multicast packets.
14848 		 */
14849 		q = ire->ire_stq;
14850 		if (q)
14851 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14852 		else
14853 			freemsg(mp);
14854 		return;
14855 	}
14856 
14857 	/*
14858 	 * Don't forward if the interface is down
14859 	 */
14860 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14861 		BUMP_MIB(&ip_mib, ipInDiscards);
14862 		goto drop_pkt;
14863 	}
14864 
14865 	/* Get the ill_index of the outgoing ILL */
14866 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14867 
14868 	/* Check if there are options to update */
14869 	if (!IS_SIMPLE_IPH(ipha)) {
14870 		if (ip_csum_hdr(ipha)) {
14871 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14872 			goto drop_pkt;
14873 		}
14874 		if (ip_rput_forward_options(mp, ipha, ire)) {
14875 			return;
14876 		}
14877 
14878 		ipha->ipha_hdr_checksum = 0;
14879 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14880 	}
14881 	max_frag = ire->ire_max_frag;
14882 	if (pkt_len > max_frag) {
14883 		/*
14884 		 * It needs fragging on its way out.  We haven't
14885 		 * verified the header checksum yet.  Since we
14886 		 * are going to put a surely good checksum in the
14887 		 * outgoing header, we have to make sure that it
14888 		 * was good coming in.
14889 		 */
14890 		if (ip_csum_hdr(ipha)) {
14891 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14892 			goto drop_pkt;
14893 		}
14894 		/* Initiate Write side IPPF processing */
14895 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14896 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14897 			if (mp == NULL) {
14898 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14899 				    " during IPPF processing\n"));
14900 				return;
14901 			}
14902 		}
14903 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14904 		return;
14905 	}
14906 
14907 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14908 	if (mp == NULL) {
14909 		BUMP_MIB(&ip_mib, ipInDiscards);
14910 		return;
14911 	}
14912 
14913 	q = ire->ire_stq;
14914 	UPDATE_IB_PKT_COUNT(ire);
14915 	ire->ire_last_used_time = lbolt;
14916 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14917 	putnext(q, mp);
14918 	return;
14919 
14920 drop_pkt:;
14921 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14922 	freemsg(mp);
14923 #undef	rptr
14924 }
14925 
14926 void
14927 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14928 {
14929 	ire_t	*ire;
14930 
14931 	ASSERT(!ipif->ipif_isv6);
14932 	/*
14933 	 * Find an IRE which matches the destination and the outgoing
14934 	 * queue in the cache table. All we need is an IRE_CACHE which
14935 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14936 	 * then it is enough to have some IRE_CACHE in the group.
14937 	 */
14938 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14939 		dst = ipif->ipif_pp_dst_addr;
14940 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14941 	    MATCH_IRE_ILL_GROUP);
14942 	if (!ire) {
14943 		/*
14944 		 * Mark this packet to make it be delivered to
14945 		 * ip_rput_forward after the new ire has been
14946 		 * created.
14947 		 */
14948 		mp->b_prev = NULL;
14949 		mp->b_next = mp;
14950 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14951 		    NULL, 0);
14952 	} else {
14953 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14954 		IRE_REFRELE(ire);
14955 	}
14956 }
14957 
14958 /* Update any source route, record route or timestamp options */
14959 static int
14960 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
14961 {
14962 	ipoptp_t	opts;
14963 	uchar_t		*opt;
14964 	uint8_t		optval;
14965 	uint8_t		optlen;
14966 	ipaddr_t	dst;
14967 	uint32_t	ts;
14968 	ire_t		*dst_ire = NULL;
14969 	ire_t		*tmp_ire = NULL;
14970 	timestruc_t	now;
14971 
14972 	ip2dbg(("ip_rput_forward_options\n"));
14973 	dst = ipha->ipha_dst;
14974 	for (optval = ipoptp_first(&opts, ipha);
14975 	    optval != IPOPT_EOL;
14976 	    optval = ipoptp_next(&opts)) {
14977 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
14978 		opt = opts.ipoptp_cur;
14979 		optlen = opts.ipoptp_len;
14980 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
14981 		    optval, opts.ipoptp_len));
14982 		switch (optval) {
14983 			uint32_t off;
14984 		case IPOPT_SSRR:
14985 		case IPOPT_LSRR:
14986 			/* Check if adminstratively disabled */
14987 			if (!ip_forward_src_routed) {
14988 				BUMP_MIB(&ip_mib, ipForwProhibits);
14989 				if (ire->ire_stq)
14990 					icmp_unreachable(ire->ire_stq, mp,
14991 					    ICMP_SOURCE_ROUTE_FAILED);
14992 				else {
14993 					ip0dbg(("ip_rput_forward_options: "
14994 					    "unable to send unreach\n"));
14995 					freemsg(mp);
14996 				}
14997 				return (-1);
14998 			}
14999 
15000 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15001 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15002 			if (dst_ire == NULL) {
15003 				/*
15004 				 * Must be partial since ip_rput_options
15005 				 * checked for strict.
15006 				 */
15007 				break;
15008 			}
15009 			off = opt[IPOPT_OFFSET];
15010 			off--;
15011 		redo_srr:
15012 			if (optlen < IP_ADDR_LEN ||
15013 			    off > optlen - IP_ADDR_LEN) {
15014 				/* End of source route */
15015 				ip1dbg((
15016 				    "ip_rput_forward_options: end of SR\n"));
15017 				ire_refrele(dst_ire);
15018 				break;
15019 			}
15020 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15021 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15022 			    IP_ADDR_LEN);
15023 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15024 			    ntohl(dst)));
15025 
15026 			/*
15027 			 * Check if our address is present more than
15028 			 * once as consecutive hops in source route.
15029 			 */
15030 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15031 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15032 			if (tmp_ire != NULL) {
15033 				ire_refrele(tmp_ire);
15034 				off += IP_ADDR_LEN;
15035 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15036 				goto redo_srr;
15037 			}
15038 			ipha->ipha_dst = dst;
15039 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15040 			ire_refrele(dst_ire);
15041 			break;
15042 		case IPOPT_RR:
15043 			off = opt[IPOPT_OFFSET];
15044 			off--;
15045 			if (optlen < IP_ADDR_LEN ||
15046 			    off > optlen - IP_ADDR_LEN) {
15047 				/* No more room - ignore */
15048 				ip1dbg((
15049 				    "ip_rput_forward_options: end of RR\n"));
15050 				break;
15051 			}
15052 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15053 			    IP_ADDR_LEN);
15054 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15055 			break;
15056 		case IPOPT_TS:
15057 			/* Insert timestamp if there is room */
15058 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15059 			case IPOPT_TS_TSONLY:
15060 				off = IPOPT_TS_TIMELEN;
15061 				break;
15062 			case IPOPT_TS_PRESPEC:
15063 			case IPOPT_TS_PRESPEC_RFC791:
15064 				/* Verify that the address matched */
15065 				off = opt[IPOPT_OFFSET] - 1;
15066 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15067 				dst_ire = ire_ctable_lookup(dst, 0,
15068 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
15069 				if (dst_ire == NULL) {
15070 					/* Not for us */
15071 					break;
15072 				}
15073 				ire_refrele(dst_ire);
15074 				/* FALLTHRU */
15075 			case IPOPT_TS_TSANDADDR:
15076 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15077 				break;
15078 			default:
15079 				/*
15080 				 * ip_*put_options should have already
15081 				 * dropped this packet.
15082 				 */
15083 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15084 				    "unknown IT - bug in ip_rput_options?\n");
15085 				return (0);	/* Keep "lint" happy */
15086 			}
15087 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15088 				/* Increase overflow counter */
15089 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15090 				opt[IPOPT_POS_OV_FLG] =
15091 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15092 				    (off << 4));
15093 				break;
15094 			}
15095 			off = opt[IPOPT_OFFSET] - 1;
15096 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15097 			case IPOPT_TS_PRESPEC:
15098 			case IPOPT_TS_PRESPEC_RFC791:
15099 			case IPOPT_TS_TSANDADDR:
15100 				bcopy(&ire->ire_src_addr,
15101 				    (char *)opt + off, IP_ADDR_LEN);
15102 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15103 				/* FALLTHRU */
15104 			case IPOPT_TS_TSONLY:
15105 				off = opt[IPOPT_OFFSET] - 1;
15106 				/* Compute # of milliseconds since midnight */
15107 				gethrestime(&now);
15108 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15109 				    now.tv_nsec / (NANOSEC / MILLISEC);
15110 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15111 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15112 				break;
15113 			}
15114 			break;
15115 		}
15116 	}
15117 	return (0);
15118 }
15119 
15120 /*
15121  * This is called after processing at least one of AH/ESP headers.
15122  *
15123  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15124  * the actual, physical interface on which the packet was received,
15125  * but, when ip_strict_dst_multihoming is set to 1, could be the
15126  * interface which had the ipha_dst configured when the packet went
15127  * through ip_rput. The ill_index corresponding to the recv_ill
15128  * is saved in ipsec_in_rill_index
15129  */
15130 void
15131 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15132 {
15133 	mblk_t *mp;
15134 	ipaddr_t dst;
15135 	in6_addr_t *v6dstp;
15136 	ipha_t *ipha;
15137 	ip6_t *ip6h;
15138 	ipsec_in_t *ii;
15139 	boolean_t ill_need_rele = B_FALSE;
15140 	boolean_t rill_need_rele = B_FALSE;
15141 	boolean_t ire_need_rele = B_FALSE;
15142 
15143 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15144 	ASSERT(ii->ipsec_in_ill_index != 0);
15145 
15146 	mp = ipsec_mp->b_cont;
15147 	ASSERT(mp != NULL);
15148 
15149 
15150 	if (ill == NULL) {
15151 		ASSERT(recv_ill == NULL);
15152 		/*
15153 		 * We need to get the original queue on which ip_rput_local
15154 		 * or ip_rput_data_v6 was called.
15155 		 */
15156 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15157 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15158 		ill_need_rele = B_TRUE;
15159 
15160 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15161 			recv_ill = ill_lookup_on_ifindex(
15162 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15163 			    NULL, NULL, NULL, NULL);
15164 			rill_need_rele = B_TRUE;
15165 		} else {
15166 			recv_ill = ill;
15167 		}
15168 
15169 		if ((ill == NULL) || (recv_ill == NULL)) {
15170 			ip0dbg(("ip_fanout_proto_again: interface "
15171 			    "disappeared\n"));
15172 			if (ill != NULL)
15173 				ill_refrele(ill);
15174 			if (recv_ill != NULL)
15175 				ill_refrele(recv_ill);
15176 			freemsg(ipsec_mp);
15177 			return;
15178 		}
15179 	}
15180 
15181 	ASSERT(ill != NULL && recv_ill != NULL);
15182 
15183 	if (mp->b_datap->db_type == M_CTL) {
15184 		/*
15185 		 * AH/ESP is returning the ICMP message after
15186 		 * removing their headers. Fanout again till
15187 		 * it gets to the right protocol.
15188 		 */
15189 		if (ii->ipsec_in_v4) {
15190 			icmph_t *icmph;
15191 			int iph_hdr_length;
15192 			int hdr_length;
15193 
15194 			ipha = (ipha_t *)mp->b_rptr;
15195 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15196 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15197 			ipha = (ipha_t *)&icmph[1];
15198 			hdr_length = IPH_HDR_LENGTH(ipha);
15199 			/*
15200 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15201 			 * Reset the type to M_DATA.
15202 			 */
15203 			mp->b_datap->db_type = M_DATA;
15204 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15205 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15206 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15207 		} else {
15208 			icmp6_t *icmp6;
15209 			int hdr_length;
15210 
15211 			ip6h = (ip6_t *)mp->b_rptr;
15212 			/* Don't call hdr_length_v6() unless you have to. */
15213 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15214 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15215 			else
15216 				hdr_length = IPV6_HDR_LEN;
15217 
15218 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15219 			/*
15220 			 * icmp_inbound_error_fanout_v6 may need to do
15221 			 * pullupmsg.  Reset the type to M_DATA.
15222 			 */
15223 			mp->b_datap->db_type = M_DATA;
15224 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15225 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15226 		}
15227 		if (ill_need_rele)
15228 			ill_refrele(ill);
15229 		if (rill_need_rele)
15230 			ill_refrele(recv_ill);
15231 		return;
15232 	}
15233 
15234 	if (ii->ipsec_in_v4) {
15235 		ipha = (ipha_t *)mp->b_rptr;
15236 		dst = ipha->ipha_dst;
15237 		if (CLASSD(dst)) {
15238 			/*
15239 			 * Multicast has to be delivered to all streams.
15240 			 */
15241 			dst = INADDR_BROADCAST;
15242 		}
15243 
15244 		if (ire == NULL) {
15245 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15246 			if (ire == NULL) {
15247 				if (ill_need_rele)
15248 					ill_refrele(ill);
15249 				if (rill_need_rele)
15250 					ill_refrele(recv_ill);
15251 				ip1dbg(("ip_fanout_proto_again: "
15252 				    "IRE not found"));
15253 				freemsg(ipsec_mp);
15254 				return;
15255 			}
15256 			ire_need_rele = B_TRUE;
15257 		}
15258 
15259 		switch (ipha->ipha_protocol) {
15260 			case IPPROTO_UDP:
15261 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15262 				    recv_ill);
15263 				if (ire_need_rele)
15264 					ire_refrele(ire);
15265 				break;
15266 			case IPPROTO_TCP:
15267 				if (!ire_need_rele)
15268 					IRE_REFHOLD(ire);
15269 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15270 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15271 				IRE_REFRELE(ire);
15272 				if (mp != NULL)
15273 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15274 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15275 				break;
15276 			case IPPROTO_SCTP:
15277 				if (!ire_need_rele)
15278 					IRE_REFHOLD(ire);
15279 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15280 				    ipsec_mp, 0, ill->ill_rq, dst);
15281 				break;
15282 			default:
15283 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15284 				    recv_ill);
15285 				if (ire_need_rele)
15286 					ire_refrele(ire);
15287 				break;
15288 		}
15289 	} else {
15290 		uint32_t rput_flags = 0;
15291 
15292 		ip6h = (ip6_t *)mp->b_rptr;
15293 		v6dstp = &ip6h->ip6_dst;
15294 		/*
15295 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15296 		 * address.
15297 		 *
15298 		 * Currently, we don't store that state in the IPSEC_IN
15299 		 * message, and we may need to.
15300 		 */
15301 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15302 		    IP6_IN_LLMCAST : 0);
15303 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15304 		    NULL);
15305 	}
15306 	if (ill_need_rele)
15307 		ill_refrele(ill);
15308 	if (rill_need_rele)
15309 		ill_refrele(recv_ill);
15310 }
15311 
15312 /*
15313  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15314  * returns 'true' if there are still fragments left on the queue, in
15315  * which case we restart the timer.
15316  */
15317 void
15318 ill_frag_timer(void *arg)
15319 {
15320 	ill_t	*ill = (ill_t *)arg;
15321 	boolean_t frag_pending;
15322 
15323 	mutex_enter(&ill->ill_lock);
15324 	ASSERT(!ill->ill_fragtimer_executing);
15325 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15326 		ill->ill_frag_timer_id = 0;
15327 		mutex_exit(&ill->ill_lock);
15328 		return;
15329 	}
15330 	ill->ill_fragtimer_executing = 1;
15331 	mutex_exit(&ill->ill_lock);
15332 
15333 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15334 
15335 	/*
15336 	 * Restart the timer, if we have fragments pending or if someone
15337 	 * wanted us to be scheduled again.
15338 	 */
15339 	mutex_enter(&ill->ill_lock);
15340 	ill->ill_fragtimer_executing = 0;
15341 	ill->ill_frag_timer_id = 0;
15342 	if (frag_pending || ill->ill_fragtimer_needrestart)
15343 		ill_frag_timer_start(ill);
15344 	mutex_exit(&ill->ill_lock);
15345 }
15346 
15347 void
15348 ill_frag_timer_start(ill_t *ill)
15349 {
15350 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15351 
15352 	/* If the ill is closing or opening don't proceed */
15353 	if (ill->ill_state_flags & ILL_CONDEMNED)
15354 		return;
15355 
15356 	if (ill->ill_fragtimer_executing) {
15357 		/*
15358 		 * ill_frag_timer is currently executing. Just record the
15359 		 * the fact that we want the timer to be restarted.
15360 		 * ill_frag_timer will post a timeout before it returns,
15361 		 * ensuring it will be called again.
15362 		 */
15363 		ill->ill_fragtimer_needrestart = 1;
15364 		return;
15365 	}
15366 
15367 	if (ill->ill_frag_timer_id == 0) {
15368 		/*
15369 		 * The timer is neither running nor is the timeout handler
15370 		 * executing. Post a timeout so that ill_frag_timer will be
15371 		 * called
15372 		 */
15373 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15374 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15375 		ill->ill_fragtimer_needrestart = 0;
15376 	}
15377 }
15378 
15379 /*
15380  * This routine is needed for loopback when forwarding multicasts.
15381  *
15382  * IPQoS Notes:
15383  * IPPF processing is done in fanout routines.
15384  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15385  * processing for IPSec packets is done when it comes back in clear.
15386  * NOTE : The callers of this function need to do the ire_refrele for the
15387  *	  ire that is being passed in.
15388  */
15389 void
15390 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15391     ill_t *recv_ill)
15392 {
15393 	ill_t	*ill = (ill_t *)q->q_ptr;
15394 	uint32_t	sum;
15395 	uint32_t	u1;
15396 	uint32_t	u2;
15397 	int		hdr_length;
15398 	boolean_t	mctl_present;
15399 	mblk_t		*first_mp = mp;
15400 	mblk_t		*hada_mp = NULL;
15401 	ipha_t		*inner_ipha;
15402 
15403 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15404 	    "ip_rput_locl_start: q %p", q);
15405 
15406 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15407 
15408 
15409 #define	rptr	((uchar_t *)ipha)
15410 #define	iphs	((uint16_t *)ipha)
15411 
15412 	/*
15413 	 * no UDP or TCP packet should come here anymore.
15414 	 */
15415 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15416 	    (ipha->ipha_protocol != IPPROTO_UDP));
15417 
15418 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15419 	if (mctl_present &&
15420 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15421 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15422 
15423 		/*
15424 		 * It's an IPsec accelerated packet.
15425 		 * Keep a pointer to the data attributes around until
15426 		 * we allocate the ipsec_info_t.
15427 		 */
15428 		IPSECHW_DEBUG(IPSECHW_PKT,
15429 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15430 		hada_mp = first_mp;
15431 		hada_mp->b_cont = NULL;
15432 		/*
15433 		 * Since it is accelerated, it comes directly from
15434 		 * the ill and the data attributes is followed by
15435 		 * the packet data.
15436 		 */
15437 		ASSERT(mp->b_datap->db_type != M_CTL);
15438 		first_mp = mp;
15439 		mctl_present = B_FALSE;
15440 	}
15441 
15442 	/*
15443 	 * IF M_CTL is not present, then ipsec_in_is_secure
15444 	 * should return B_TRUE. There is a case where loopback
15445 	 * packets has an M_CTL in the front with all the
15446 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15447 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15448 	 * packets never comes here, it is safe to ASSERT the
15449 	 * following.
15450 	 */
15451 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15452 
15453 
15454 	/* u1 is # words of IP options */
15455 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15456 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15457 
15458 	if (u1) {
15459 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15460 			if (hada_mp != NULL)
15461 				freemsg(hada_mp);
15462 			return;
15463 		}
15464 	} else {
15465 		/* Check the IP header checksum.  */
15466 #define	uph	((uint16_t *)ipha)
15467 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15468 		    uph[6] + uph[7] + uph[8] + uph[9];
15469 #undef  uph
15470 		/* finish doing IP checksum */
15471 		sum = (sum & 0xFFFF) + (sum >> 16);
15472 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15473 		/*
15474 		 * Don't verify header checksum if this packet is coming
15475 		 * back from AH/ESP as we already did it.
15476 		 */
15477 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15478 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15479 			goto drop_pkt;
15480 		}
15481 	}
15482 
15483 	/*
15484 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15485 	 * might be called more than once for secure packets, count only
15486 	 * the first time.
15487 	 */
15488 	if (!mctl_present) {
15489 		UPDATE_IB_PKT_COUNT(ire);
15490 		ire->ire_last_used_time = lbolt;
15491 	}
15492 
15493 	/* Check for fragmentation offset. */
15494 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15495 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15496 	if (u1) {
15497 		/*
15498 		 * We re-assemble fragments before we do the AH/ESP
15499 		 * processing. Thus, M_CTL should not be present
15500 		 * while we are re-assembling.
15501 		 */
15502 		ASSERT(!mctl_present);
15503 		ASSERT(first_mp == mp);
15504 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
15505 			return;
15506 		}
15507 		/*
15508 		 * Make sure that first_mp points back to mp as
15509 		 * the mp we came in with could have changed in
15510 		 * ip_rput_fragment().
15511 		 */
15512 		ipha = (ipha_t *)mp->b_rptr;
15513 		first_mp = mp;
15514 	}
15515 
15516 	/*
15517 	 * Clear hardware checksumming flag as it is currently only
15518 	 * used by TCP and UDP.
15519 	 */
15520 	DB_CKSUMFLAGS(mp) = 0;
15521 
15522 	/* Now we have a complete datagram, destined for this machine. */
15523 	u1 = IPH_HDR_LENGTH(ipha);
15524 	switch (ipha->ipha_protocol) {
15525 	case IPPROTO_ICMP: {
15526 		ire_t		*ire_zone;
15527 		ilm_t		*ilm;
15528 		mblk_t		*mp1;
15529 		zoneid_t	last_zoneid;
15530 
15531 		if (CLASSD(ipha->ipha_dst) &&
15532 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15533 			ASSERT(ire->ire_type == IRE_BROADCAST);
15534 			/*
15535 			 * In the multicast case, applications may have joined
15536 			 * the group from different zones, so we need to deliver
15537 			 * the packet to each of them. Loop through the
15538 			 * multicast memberships structures (ilm) on the receive
15539 			 * ill and send a copy of the packet up each matching
15540 			 * one. However, we don't do this for multicasts sent on
15541 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15542 			 * they must stay in the sender's zone.
15543 			 *
15544 			 * ilm_add_v6() ensures that ilms in the same zone are
15545 			 * contiguous in the ill_ilm list. We use this property
15546 			 * to avoid sending duplicates needed when two
15547 			 * applications in the same zone join the same group on
15548 			 * different logical interfaces: we ignore the ilm if
15549 			 * its zoneid is the same as the last matching one.
15550 			 * In addition, the sending of the packet for
15551 			 * ire_zoneid is delayed until all of the other ilms
15552 			 * have been exhausted.
15553 			 */
15554 			last_zoneid = -1;
15555 			ILM_WALKER_HOLD(recv_ill);
15556 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15557 			    ilm = ilm->ilm_next) {
15558 				if ((ilm->ilm_flags & ILM_DELETED) ||
15559 				    ipha->ipha_dst != ilm->ilm_addr ||
15560 				    ilm->ilm_zoneid == last_zoneid ||
15561 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15562 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15563 					continue;
15564 				mp1 = ip_copymsg(first_mp);
15565 				if (mp1 == NULL)
15566 					continue;
15567 				icmp_inbound(q, mp1, B_TRUE, ill,
15568 				    0, sum, mctl_present, B_TRUE,
15569 				    recv_ill, ilm->ilm_zoneid);
15570 				last_zoneid = ilm->ilm_zoneid;
15571 			}
15572 			ILM_WALKER_RELE(recv_ill);
15573 		} else if (ire->ire_type == IRE_BROADCAST) {
15574 			/*
15575 			 * In the broadcast case, there may be many zones
15576 			 * which need a copy of the packet delivered to them.
15577 			 * There is one IRE_BROADCAST per broadcast address
15578 			 * and per zone; we walk those using a helper function.
15579 			 * In addition, the sending of the packet for ire is
15580 			 * delayed until all of the other ires have been
15581 			 * processed.
15582 			 */
15583 			IRB_REFHOLD(ire->ire_bucket);
15584 			ire_zone = NULL;
15585 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15586 			    ire)) != NULL) {
15587 				mp1 = ip_copymsg(first_mp);
15588 				if (mp1 == NULL)
15589 					continue;
15590 
15591 				UPDATE_IB_PKT_COUNT(ire_zone);
15592 				ire_zone->ire_last_used_time = lbolt;
15593 				icmp_inbound(q, mp1, B_TRUE, ill,
15594 				    0, sum, mctl_present, B_TRUE,
15595 				    recv_ill, ire_zone->ire_zoneid);
15596 			}
15597 			IRB_REFRELE(ire->ire_bucket);
15598 		}
15599 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15600 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15601 		    ire->ire_zoneid);
15602 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15603 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15604 		return;
15605 	}
15606 	case IPPROTO_IGMP:
15607 		/*
15608 		 * If we are not willing to accept IGMP packets in clear,
15609 		 * then check with global policy.
15610 		 */
15611 		if (igmp_accept_clear_messages == 0) {
15612 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15613 			    ipha, NULL, mctl_present);
15614 			if (first_mp == NULL)
15615 				return;
15616 		}
15617 		if (igmp_input(q, mp, ill)) {
15618 			/* Bad packet - discarded by igmp_input */
15619 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15620 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15621 			if (mctl_present)
15622 				freeb(first_mp);
15623 			return;
15624 		}
15625 		/*
15626 		 * igmp_input() may have pulled up the message so ipha needs to
15627 		 * be reinitialized.
15628 		 */
15629 		ipha = (ipha_t *)mp->b_rptr;
15630 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15631 			/* No user-level listener for IGMP packets */
15632 			goto drop_pkt;
15633 		}
15634 		/* deliver to local raw users */
15635 		break;
15636 	case IPPROTO_PIM:
15637 		/*
15638 		 * If we are not willing to accept PIM packets in clear,
15639 		 * then check with global policy.
15640 		 */
15641 		if (pim_accept_clear_messages == 0) {
15642 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15643 			    ipha, NULL, mctl_present);
15644 			if (first_mp == NULL)
15645 				return;
15646 		}
15647 		if (pim_input(q, mp) != 0) {
15648 			/* Bad packet - discarded by pim_input */
15649 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15650 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15651 			if (mctl_present)
15652 				freeb(first_mp);
15653 			return;
15654 		}
15655 
15656 		/*
15657 		 * pim_input() may have pulled up the message so ipha needs to
15658 		 * be reinitialized.
15659 		 */
15660 		ipha = (ipha_t *)mp->b_rptr;
15661 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15662 			/* No user-level listener for PIM packets */
15663 			goto drop_pkt;
15664 		}
15665 		/* deliver to local raw users */
15666 		break;
15667 	case IPPROTO_ENCAP:
15668 		/*
15669 		 * Handle self-encapsulated packets (IP-in-IP where
15670 		 * the inner addresses == the outer addresses).
15671 		 */
15672 		hdr_length = IPH_HDR_LENGTH(ipha);
15673 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15674 		    mp->b_wptr) {
15675 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15676 			    sizeof (ipha_t) - mp->b_rptr)) {
15677 				BUMP_MIB(&ip_mib, ipInDiscards);
15678 				freemsg(first_mp);
15679 				return;
15680 			}
15681 			ipha = (ipha_t *)mp->b_rptr;
15682 		}
15683 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15684 		/*
15685 		 * Check the sanity of the inner IP header.
15686 		 */
15687 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15688 			BUMP_MIB(&ip_mib, ipInDiscards);
15689 			freemsg(first_mp);
15690 			return;
15691 		}
15692 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15693 			BUMP_MIB(&ip_mib, ipInDiscards);
15694 			freemsg(first_mp);
15695 			return;
15696 		}
15697 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15698 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15699 			ipsec_in_t *ii;
15700 
15701 			/*
15702 			 * Self-encapsulated tunnel packet. Remove
15703 			 * the outer IP header and fanout again.
15704 			 * We also need to make sure that the inner
15705 			 * header is pulled up until options.
15706 			 */
15707 			mp->b_rptr = (uchar_t *)inner_ipha;
15708 			ipha = inner_ipha;
15709 			hdr_length = IPH_HDR_LENGTH(ipha);
15710 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15711 				if (!pullupmsg(mp, (uchar_t *)ipha +
15712 				    + hdr_length - mp->b_rptr)) {
15713 					freemsg(first_mp);
15714 					return;
15715 				}
15716 				ipha = (ipha_t *)mp->b_rptr;
15717 			}
15718 			if (!mctl_present) {
15719 				ASSERT(first_mp == mp);
15720 				/*
15721 				 * This means that somebody is sending
15722 				 * Self-encapsualted packets without AH/ESP.
15723 				 * If AH/ESP was present, we would have already
15724 				 * allocated the first_mp.
15725 				 */
15726 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15727 				    NULL) {
15728 					ip1dbg(("ip_proto_input: IPSEC_IN "
15729 					    "allocation failure.\n"));
15730 					BUMP_MIB(&ip_mib, ipInDiscards);
15731 					freemsg(mp);
15732 					return;
15733 				}
15734 				first_mp->b_cont = mp;
15735 			}
15736 			/*
15737 			 * We generally store the ill_index if we need to
15738 			 * do IPSEC processing as we lose the ill queue when
15739 			 * we come back. But in this case, we never should
15740 			 * have to store the ill_index here as it should have
15741 			 * been stored previously when we processed the
15742 			 * AH/ESP header in this routine or for non-ipsec
15743 			 * cases, we still have the queue. But for some bad
15744 			 * packets from the wire, we can get to IPSEC after
15745 			 * this and we better store the index for that case.
15746 			 */
15747 			ill = (ill_t *)q->q_ptr;
15748 			ii = (ipsec_in_t *)first_mp->b_rptr;
15749 			ii->ipsec_in_ill_index =
15750 			    ill->ill_phyint->phyint_ifindex;
15751 			ii->ipsec_in_rill_index =
15752 			    recv_ill->ill_phyint->phyint_ifindex;
15753 			if (ii->ipsec_in_decaps) {
15754 				/*
15755 				 * This packet is self-encapsulated multiple
15756 				 * times. We don't want to recurse infinitely.
15757 				 * To keep it simple, drop the packet.
15758 				 */
15759 				BUMP_MIB(&ip_mib, ipInDiscards);
15760 				freemsg(first_mp);
15761 				return;
15762 			}
15763 			ii->ipsec_in_decaps = B_TRUE;
15764 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15765 			return;
15766 		}
15767 		break;
15768 	case IPPROTO_AH:
15769 	case IPPROTO_ESP: {
15770 		/*
15771 		 * Fast path for AH/ESP. If this is the first time
15772 		 * we are sending a datagram to AH/ESP, allocate
15773 		 * a IPSEC_IN message and prepend it. Otherwise,
15774 		 * just fanout.
15775 		 */
15776 
15777 		int ipsec_rc;
15778 		ipsec_in_t *ii;
15779 
15780 		IP_STAT(ipsec_proto_ahesp);
15781 		if (!mctl_present) {
15782 			ASSERT(first_mp == mp);
15783 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15784 				ip1dbg(("ip_proto_input: IPSEC_IN "
15785 				    "allocation failure.\n"));
15786 				freemsg(hada_mp); /* okay ifnull */
15787 				BUMP_MIB(&ip_mib, ipInDiscards);
15788 				freemsg(mp);
15789 				return;
15790 			}
15791 			/*
15792 			 * Store the ill_index so that when we come back
15793 			 * from IPSEC we ride on the same queue.
15794 			 */
15795 			ill = (ill_t *)q->q_ptr;
15796 			ii = (ipsec_in_t *)first_mp->b_rptr;
15797 			ii->ipsec_in_ill_index =
15798 			    ill->ill_phyint->phyint_ifindex;
15799 			ii->ipsec_in_rill_index =
15800 			    recv_ill->ill_phyint->phyint_ifindex;
15801 			first_mp->b_cont = mp;
15802 			/*
15803 			 * Cache hardware acceleration info.
15804 			 */
15805 			if (hada_mp != NULL) {
15806 				IPSECHW_DEBUG(IPSECHW_PKT,
15807 				    ("ip_rput_local: caching data attr.\n"));
15808 				ii->ipsec_in_accelerated = B_TRUE;
15809 				ii->ipsec_in_da = hada_mp;
15810 				hada_mp = NULL;
15811 			}
15812 		} else {
15813 			ii = (ipsec_in_t *)first_mp->b_rptr;
15814 		}
15815 
15816 		if (!ipsec_loaded()) {
15817 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15818 			    ire->ire_zoneid);
15819 			return;
15820 		}
15821 
15822 		/* select inbound SA and have IPsec process the pkt */
15823 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15824 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15825 			if (esph == NULL)
15826 				return;
15827 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15828 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15829 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15830 			    first_mp, esph);
15831 		} else {
15832 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15833 			if (ah == NULL)
15834 				return;
15835 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15836 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15837 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15838 			    first_mp, ah);
15839 		}
15840 
15841 		switch (ipsec_rc) {
15842 		case IPSEC_STATUS_SUCCESS:
15843 			break;
15844 		case IPSEC_STATUS_FAILED:
15845 			BUMP_MIB(&ip_mib, ipInDiscards);
15846 			/* FALLTHRU */
15847 		case IPSEC_STATUS_PENDING:
15848 			return;
15849 		}
15850 		/* we're done with IPsec processing, send it up */
15851 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15852 		return;
15853 	}
15854 	default:
15855 		break;
15856 	}
15857 	/*
15858 	 * Handle protocols with which IP is less intimate.  There
15859 	 * can be more than one stream bound to a particular
15860 	 * protocol.  When this is the case, each one gets a copy
15861 	 * of any incoming packets.
15862 	 */
15863 	ip_fanout_proto(q, first_mp, ill, ipha,
15864 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15865 	    B_TRUE, recv_ill, ire->ire_zoneid);
15866 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15867 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15868 	return;
15869 
15870 drop_pkt:
15871 	freemsg(first_mp);
15872 	if (hada_mp != NULL)
15873 		freeb(hada_mp);
15874 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15875 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15876 #undef	rptr
15877 #undef  iphs
15878 
15879 }
15880 
15881 /*
15882  * Update any source route, record route or timestamp options.
15883  * Check that we are at end of strict source route.
15884  * The options have already been checked for sanity in ip_rput_options().
15885  */
15886 static boolean_t
15887 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15888 {
15889 	ipoptp_t	opts;
15890 	uchar_t		*opt;
15891 	uint8_t		optval;
15892 	uint8_t		optlen;
15893 	ipaddr_t	dst;
15894 	uint32_t	ts;
15895 	ire_t		*dst_ire;
15896 	timestruc_t	now;
15897 
15898 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15899 
15900 	ip2dbg(("ip_rput_local_options\n"));
15901 
15902 	for (optval = ipoptp_first(&opts, ipha);
15903 	    optval != IPOPT_EOL;
15904 	    optval = ipoptp_next(&opts)) {
15905 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15906 		opt = opts.ipoptp_cur;
15907 		optlen = opts.ipoptp_len;
15908 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15909 		    optval, optlen));
15910 		switch (optval) {
15911 			uint32_t off;
15912 		case IPOPT_SSRR:
15913 		case IPOPT_LSRR:
15914 			off = opt[IPOPT_OFFSET];
15915 			off--;
15916 			if (optlen < IP_ADDR_LEN ||
15917 			    off > optlen - IP_ADDR_LEN) {
15918 				/* End of source route */
15919 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15920 				break;
15921 			}
15922 			/*
15923 			 * This will only happen if two consecutive entries
15924 			 * in the source route contains our address or if
15925 			 * it is a packet with a loose source route which
15926 			 * reaches us before consuming the whole source route
15927 			 */
15928 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15929 			if (optval == IPOPT_SSRR) {
15930 				goto bad_src_route;
15931 			}
15932 			/*
15933 			 * Hack: instead of dropping the packet truncate the
15934 			 * source route to what has been used by filling the
15935 			 * rest with IPOPT_NOP.
15936 			 */
15937 			opt[IPOPT_OLEN] = (uint8_t)off;
15938 			while (off < optlen) {
15939 				opt[off++] = IPOPT_NOP;
15940 			}
15941 			break;
15942 		case IPOPT_RR:
15943 			off = opt[IPOPT_OFFSET];
15944 			off--;
15945 			if (optlen < IP_ADDR_LEN ||
15946 			    off > optlen - IP_ADDR_LEN) {
15947 				/* No more room - ignore */
15948 				ip1dbg((
15949 				    "ip_rput_local_options: end of RR\n"));
15950 				break;
15951 			}
15952 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15953 			    IP_ADDR_LEN);
15954 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15955 			break;
15956 		case IPOPT_TS:
15957 			/* Insert timestamp if there is romm */
15958 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15959 			case IPOPT_TS_TSONLY:
15960 				off = IPOPT_TS_TIMELEN;
15961 				break;
15962 			case IPOPT_TS_PRESPEC:
15963 			case IPOPT_TS_PRESPEC_RFC791:
15964 				/* Verify that the address matched */
15965 				off = opt[IPOPT_OFFSET] - 1;
15966 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15967 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15968 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15969 				if (dst_ire == NULL) {
15970 					/* Not for us */
15971 					break;
15972 				}
15973 				ire_refrele(dst_ire);
15974 				/* FALLTHRU */
15975 			case IPOPT_TS_TSANDADDR:
15976 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15977 				break;
15978 			default:
15979 				/*
15980 				 * ip_*put_options should have already
15981 				 * dropped this packet.
15982 				 */
15983 				cmn_err(CE_PANIC, "ip_rput_local_options: "
15984 				    "unknown IT - bug in ip_rput_options?\n");
15985 				return (B_TRUE);	/* Keep "lint" happy */
15986 			}
15987 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15988 				/* Increase overflow counter */
15989 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15990 				opt[IPOPT_POS_OV_FLG] =
15991 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15992 				    (off << 4));
15993 				break;
15994 			}
15995 			off = opt[IPOPT_OFFSET] - 1;
15996 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15997 			case IPOPT_TS_PRESPEC:
15998 			case IPOPT_TS_PRESPEC_RFC791:
15999 			case IPOPT_TS_TSANDADDR:
16000 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16001 				    IP_ADDR_LEN);
16002 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16003 				/* FALLTHRU */
16004 			case IPOPT_TS_TSONLY:
16005 				off = opt[IPOPT_OFFSET] - 1;
16006 				/* Compute # of milliseconds since midnight */
16007 				gethrestime(&now);
16008 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16009 				    now.tv_nsec / (NANOSEC / MILLISEC);
16010 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16011 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16012 				break;
16013 			}
16014 			break;
16015 		}
16016 	}
16017 	return (B_TRUE);
16018 
16019 bad_src_route:
16020 	q = WR(q);
16021 	/* make sure we clear any indication of a hardware checksum */
16022 	DB_CKSUMFLAGS(mp) = 0;
16023 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16024 	return (B_FALSE);
16025 
16026 }
16027 
16028 /*
16029  * Process IP options in an inbound packet.  If an option affects the
16030  * effective destination address, return the next hop address via dstp.
16031  * Returns -1 if something fails in which case an ICMP error has been sent
16032  * and mp freed.
16033  */
16034 static int
16035 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16036 {
16037 	ipoptp_t	opts;
16038 	uchar_t		*opt;
16039 	uint8_t		optval;
16040 	uint8_t		optlen;
16041 	ipaddr_t	dst;
16042 	intptr_t	code = 0;
16043 	ire_t		*ire = NULL;
16044 
16045 	ip2dbg(("ip_rput_options\n"));
16046 	dst = ipha->ipha_dst;
16047 	for (optval = ipoptp_first(&opts, ipha);
16048 	    optval != IPOPT_EOL;
16049 	    optval = ipoptp_next(&opts)) {
16050 		opt = opts.ipoptp_cur;
16051 		optlen = opts.ipoptp_len;
16052 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16053 		    optval, optlen));
16054 		/*
16055 		 * Note: we need to verify the checksum before we
16056 		 * modify anything thus this routine only extracts the next
16057 		 * hop dst from any source route.
16058 		 */
16059 		switch (optval) {
16060 			uint32_t off;
16061 		case IPOPT_SSRR:
16062 		case IPOPT_LSRR:
16063 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16064 			    ALL_ZONES, MATCH_IRE_TYPE);
16065 			if (ire == NULL) {
16066 				if (optval == IPOPT_SSRR) {
16067 					ip1dbg(("ip_rput_options: not next"
16068 					    " strict source route 0x%x\n",
16069 					    ntohl(dst)));
16070 					code = (char *)&ipha->ipha_dst -
16071 					    (char *)ipha;
16072 					goto param_prob; /* RouterReq's */
16073 				}
16074 				ip2dbg(("ip_rput_options: "
16075 				    "not next source route 0x%x\n",
16076 				    ntohl(dst)));
16077 				break;
16078 			}
16079 			ire_refrele(ire);
16080 
16081 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16082 				ip1dbg((
16083 				    "ip_rput_options: bad option offset\n"));
16084 				code = (char *)&opt[IPOPT_OLEN] -
16085 				    (char *)ipha;
16086 				goto param_prob;
16087 			}
16088 			off = opt[IPOPT_OFFSET];
16089 			off--;
16090 		redo_srr:
16091 			if (optlen < IP_ADDR_LEN ||
16092 			    off > optlen - IP_ADDR_LEN) {
16093 				/* End of source route */
16094 				ip1dbg(("ip_rput_options: end of SR\n"));
16095 				break;
16096 			}
16097 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16098 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16099 			    ntohl(dst)));
16100 
16101 			/*
16102 			 * Check if our address is present more than
16103 			 * once as consecutive hops in source route.
16104 			 * XXX verify per-interface ip_forwarding
16105 			 * for source route?
16106 			 */
16107 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16108 			    ALL_ZONES, MATCH_IRE_TYPE);
16109 
16110 			if (ire != NULL) {
16111 				ire_refrele(ire);
16112 				off += IP_ADDR_LEN;
16113 				goto redo_srr;
16114 			}
16115 
16116 			if (dst == htonl(INADDR_LOOPBACK)) {
16117 				ip1dbg(("ip_rput_options: loopback addr in "
16118 				    "source route!\n"));
16119 				goto bad_src_route;
16120 			}
16121 			/*
16122 			 * For strict: verify that dst is directly
16123 			 * reachable.
16124 			 */
16125 			if (optval == IPOPT_SSRR) {
16126 				ire = ire_ftable_lookup(dst, 0, 0,
16127 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16128 				    MATCH_IRE_TYPE);
16129 				if (ire == NULL) {
16130 					ip1dbg(("ip_rput_options: SSRR not "
16131 					    "directly reachable: 0x%x\n",
16132 					    ntohl(dst)));
16133 					goto bad_src_route;
16134 				}
16135 				ire_refrele(ire);
16136 			}
16137 			/*
16138 			 * Defer update of the offset and the record route
16139 			 * until the packet is forwarded.
16140 			 */
16141 			break;
16142 		case IPOPT_RR:
16143 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16144 				ip1dbg((
16145 				    "ip_rput_options: bad option offset\n"));
16146 				code = (char *)&opt[IPOPT_OLEN] -
16147 				    (char *)ipha;
16148 				goto param_prob;
16149 			}
16150 			break;
16151 		case IPOPT_TS:
16152 			/*
16153 			 * Verify that length >= 5 and that there is either
16154 			 * room for another timestamp or that the overflow
16155 			 * counter is not maxed out.
16156 			 */
16157 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16158 			if (optlen < IPOPT_MINLEN_IT) {
16159 				goto param_prob;
16160 			}
16161 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16162 				ip1dbg((
16163 				    "ip_rput_options: bad option offset\n"));
16164 				code = (char *)&opt[IPOPT_OFFSET] -
16165 				    (char *)ipha;
16166 				goto param_prob;
16167 			}
16168 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16169 			case IPOPT_TS_TSONLY:
16170 				off = IPOPT_TS_TIMELEN;
16171 				break;
16172 			case IPOPT_TS_TSANDADDR:
16173 			case IPOPT_TS_PRESPEC:
16174 			case IPOPT_TS_PRESPEC_RFC791:
16175 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16176 				break;
16177 			default:
16178 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16179 				    (char *)ipha;
16180 				goto param_prob;
16181 			}
16182 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16183 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16184 				/*
16185 				 * No room and the overflow counter is 15
16186 				 * already.
16187 				 */
16188 				goto param_prob;
16189 			}
16190 			break;
16191 		}
16192 	}
16193 
16194 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16195 		*dstp = dst;
16196 		return (0);
16197 	}
16198 
16199 	ip1dbg(("ip_rput_options: error processing IP options."));
16200 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16201 
16202 param_prob:
16203 	q = WR(q);
16204 	/* make sure we clear any indication of a hardware checksum */
16205 	DB_CKSUMFLAGS(mp) = 0;
16206 	icmp_param_problem(q, mp, (uint8_t)code);
16207 	return (-1);
16208 
16209 bad_src_route:
16210 	q = WR(q);
16211 	/* make sure we clear any indication of a hardware checksum */
16212 	DB_CKSUMFLAGS(mp) = 0;
16213 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16214 	return (-1);
16215 }
16216 
16217 /*
16218  * IP & ICMP info in >=14 msg's ...
16219  *  - ip fixed part (mib2_ip_t)
16220  *  - icmp fixed part (mib2_icmp_t)
16221  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16222  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16223  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16224  *  - ip multicast membership (ip_member_t)
16225  *  - ip multicast source filtering (ip_grpsrc_t)
16226  *  - igmp fixed part (struct igmpstat)
16227  *  - multicast routing stats (struct mrtstat)
16228  *  - multicast routing vifs (array of struct vifctl)
16229  *  - multicast routing routes (array of struct mfcctl)
16230  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16231  *					One per ill plus one generic
16232  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16233  *					One per ill plus one generic
16234  *  - ipv6RouteEntry			all IPv6 IREs
16235  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16236  *  - ipv6AddrEntry			all IPv6 ipifs
16237  *  - ipv6 multicast membership (ipv6_member_t)
16238  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16239  *
16240  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16241  * already present.
16242  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16243  * already filled in by caller.
16244  * Return value of 0 indicates that no messages were sent and caller
16245  * should free mpctl.
16246  */
16247 int
16248 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16249 {
16250 
16251 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16252 		return (0);
16253 	}
16254 
16255 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16256 		return (1);
16257 	}
16258 
16259 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16260 		return (1);
16261 	}
16262 
16263 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16264 		return (1);
16265 	}
16266 
16267 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16268 		return (1);
16269 	}
16270 
16271 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16272 		return (1);
16273 	}
16274 
16275 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16276 		return (1);
16277 	}
16278 
16279 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16280 		return (1);
16281 	}
16282 
16283 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16284 		return (1);
16285 	}
16286 
16287 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16288 		return (1);
16289 	}
16290 
16291 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16292 		return (1);
16293 	}
16294 
16295 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16296 		return (1);
16297 	}
16298 
16299 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16300 		return (1);
16301 	}
16302 
16303 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16304 		return (1);
16305 	}
16306 
16307 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16308 		return (1);
16309 	}
16310 
16311 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16312 		return (1);
16313 	}
16314 
16315 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16316 		return (1);
16317 	}
16318 
16319 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16320 		return (1);
16321 	}
16322 	freemsg(mpctl);
16323 	return (1);
16324 }
16325 
16326 
16327 /* Get global IPv4 statistics */
16328 static mblk_t *
16329 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16330 {
16331 	struct opthdr		*optp;
16332 	mblk_t			*mp2ctl;
16333 
16334 	/*
16335 	 * make a copy of the original message
16336 	 */
16337 	mp2ctl = copymsg(mpctl);
16338 
16339 	/* fixed length IP structure... */
16340 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16341 	optp->level = MIB2_IP;
16342 	optp->name = 0;
16343 	SET_MIB(ip_mib.ipForwarding,
16344 	    (WE_ARE_FORWARDING ? 1 : 2));
16345 	SET_MIB(ip_mib.ipDefaultTTL,
16346 	    (uint32_t)ip_def_ttl);
16347 	SET_MIB(ip_mib.ipReasmTimeout,
16348 	    ip_g_frag_timeout);
16349 	SET_MIB(ip_mib.ipAddrEntrySize,
16350 	    sizeof (mib2_ipAddrEntry_t));
16351 	SET_MIB(ip_mib.ipRouteEntrySize,
16352 	    sizeof (mib2_ipRouteEntry_t));
16353 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16354 	    sizeof (mib2_ipNetToMediaEntry_t));
16355 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16356 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16357 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16358 	    (int)sizeof (ip_mib))) {
16359 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16360 		    (uint_t)sizeof (ip_mib)));
16361 	}
16362 
16363 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16364 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16365 	    (int)optp->level, (int)optp->name, (int)optp->len));
16366 	qreply(q, mpctl);
16367 	return (mp2ctl);
16368 }
16369 
16370 /* Global IPv4 ICMP statistics */
16371 static mblk_t *
16372 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16373 {
16374 	struct opthdr		*optp;
16375 	mblk_t			*mp2ctl;
16376 
16377 	/*
16378 	 * Make a copy of the original message
16379 	 */
16380 	mp2ctl = copymsg(mpctl);
16381 
16382 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16383 	optp->level = MIB2_ICMP;
16384 	optp->name = 0;
16385 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16386 	    (int)sizeof (icmp_mib))) {
16387 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16388 		    (uint_t)sizeof (icmp_mib)));
16389 	}
16390 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16391 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16392 	    (int)optp->level, (int)optp->name, (int)optp->len));
16393 	qreply(q, mpctl);
16394 	return (mp2ctl);
16395 }
16396 
16397 /* Global IPv4 IGMP statistics */
16398 static mblk_t *
16399 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16400 {
16401 	struct opthdr		*optp;
16402 	mblk_t			*mp2ctl;
16403 
16404 	/*
16405 	 * make a copy of the original message
16406 	 */
16407 	mp2ctl = copymsg(mpctl);
16408 
16409 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16410 	optp->level = EXPER_IGMP;
16411 	optp->name = 0;
16412 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16413 	    (int)sizeof (igmpstat))) {
16414 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16415 		    (uint_t)sizeof (igmpstat)));
16416 	}
16417 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16418 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16419 	    (int)optp->level, (int)optp->name, (int)optp->len));
16420 	qreply(q, mpctl);
16421 	return (mp2ctl);
16422 }
16423 
16424 /* Global IPv4 Multicast Routing statistics */
16425 static mblk_t *
16426 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16427 {
16428 	struct opthdr		*optp;
16429 	mblk_t			*mp2ctl;
16430 
16431 	/*
16432 	 * make a copy of the original message
16433 	 */
16434 	mp2ctl = copymsg(mpctl);
16435 
16436 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16437 	optp->level = EXPER_DVMRP;
16438 	optp->name = 0;
16439 	if (!ip_mroute_stats(mpctl->b_cont)) {
16440 		ip0dbg(("ip_mroute_stats: failed\n"));
16441 	}
16442 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16443 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16444 	    (int)optp->level, (int)optp->name, (int)optp->len));
16445 	qreply(q, mpctl);
16446 	return (mp2ctl);
16447 }
16448 
16449 /* IPv4 address information */
16450 static mblk_t *
16451 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16452 {
16453 	struct opthdr		*optp;
16454 	mblk_t			*mp2ctl;
16455 	mblk_t			*mp_tail = NULL;
16456 	ill_t			*ill;
16457 	ipif_t			*ipif;
16458 	uint_t			bitval;
16459 	mib2_ipAddrEntry_t	mae;
16460 	zoneid_t		zoneid;
16461 	ill_walk_context_t ctx;
16462 
16463 	/*
16464 	 * make a copy of the original message
16465 	 */
16466 	mp2ctl = copymsg(mpctl);
16467 
16468 	/* ipAddrEntryTable */
16469 
16470 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16471 	optp->level = MIB2_IP;
16472 	optp->name = MIB2_IP_ADDR;
16473 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16474 
16475 	rw_enter(&ill_g_lock, RW_READER);
16476 	ill = ILL_START_WALK_V4(&ctx);
16477 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16478 		for (ipif = ill->ill_ipif; ipif != NULL;
16479 		    ipif = ipif->ipif_next) {
16480 			if (ipif->ipif_zoneid != zoneid)
16481 				continue;
16482 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16483 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16484 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16485 
16486 			(void) ipif_get_name(ipif,
16487 			    mae.ipAdEntIfIndex.o_bytes,
16488 			    OCTET_LENGTH);
16489 			mae.ipAdEntIfIndex.o_length =
16490 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16491 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16492 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16493 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16494 			mae.ipAdEntInfo.ae_subnet_len =
16495 			    ip_mask_to_plen(ipif->ipif_net_mask);
16496 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16497 			for (bitval = 1;
16498 			    bitval &&
16499 			    !(bitval & ipif->ipif_brd_addr);
16500 			    bitval <<= 1)
16501 				noop;
16502 			mae.ipAdEntBcastAddr = bitval;
16503 			mae.ipAdEntReasmMaxSize = 65535;
16504 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16505 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16506 			mae.ipAdEntInfo.ae_broadcast_addr =
16507 			    ipif->ipif_brd_addr;
16508 			mae.ipAdEntInfo.ae_pp_dst_addr =
16509 			    ipif->ipif_pp_dst_addr;
16510 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16511 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16512 
16513 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16514 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16515 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16516 				    "allocate %u bytes\n",
16517 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16518 			}
16519 		}
16520 	}
16521 	rw_exit(&ill_g_lock);
16522 
16523 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16524 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16525 	    (int)optp->level, (int)optp->name, (int)optp->len));
16526 	qreply(q, mpctl);
16527 	return (mp2ctl);
16528 }
16529 
16530 /* IPv6 address information */
16531 static mblk_t *
16532 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16533 {
16534 	struct opthdr		*optp;
16535 	mblk_t			*mp2ctl;
16536 	mblk_t			*mp_tail = NULL;
16537 	ill_t			*ill;
16538 	ipif_t			*ipif;
16539 	mib2_ipv6AddrEntry_t	mae6;
16540 	zoneid_t		zoneid;
16541 	ill_walk_context_t	ctx;
16542 
16543 	/*
16544 	 * make a copy of the original message
16545 	 */
16546 	mp2ctl = copymsg(mpctl);
16547 
16548 	/* ipv6AddrEntryTable */
16549 
16550 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16551 	optp->level = MIB2_IP6;
16552 	optp->name = MIB2_IP6_ADDR;
16553 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16554 
16555 	rw_enter(&ill_g_lock, RW_READER);
16556 	ill = ILL_START_WALK_V6(&ctx);
16557 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16558 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16559 			if (ipif->ipif_zoneid != zoneid)
16560 				continue;
16561 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16562 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16563 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16564 
16565 			(void) ipif_get_name(ipif,
16566 			    mae6.ipv6AddrIfIndex.o_bytes,
16567 			    OCTET_LENGTH);
16568 			mae6.ipv6AddrIfIndex.o_length =
16569 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16570 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16571 			mae6.ipv6AddrPfxLength =
16572 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16573 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16574 			mae6.ipv6AddrInfo.ae_subnet_len =
16575 			    mae6.ipv6AddrPfxLength;
16576 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16577 
16578 			/* Type: stateless(1), stateful(2), unknown(3) */
16579 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16580 				mae6.ipv6AddrType = 1;
16581 			else
16582 				mae6.ipv6AddrType = 2;
16583 			/* Anycast: true(1), false(2) */
16584 			if (ipif->ipif_flags & IPIF_ANYCAST)
16585 				mae6.ipv6AddrAnycastFlag = 1;
16586 			else
16587 				mae6.ipv6AddrAnycastFlag = 2;
16588 
16589 			/*
16590 			 * Address status: preferred(1), deprecated(2),
16591 			 * invalid(3), inaccessible(4), unknown(5)
16592 			 */
16593 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16594 				mae6.ipv6AddrStatus = 3;
16595 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16596 				mae6.ipv6AddrStatus = 2;
16597 			else
16598 				mae6.ipv6AddrStatus = 1;
16599 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16600 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16601 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16602 						ipif->ipif_v6pp_dst_addr;
16603 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16604 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16605 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16606 				(char *)&mae6,
16607 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16608 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16609 				    "allocate %u bytes\n",
16610 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16611 			}
16612 		}
16613 	}
16614 	rw_exit(&ill_g_lock);
16615 
16616 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16617 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16618 	    (int)optp->level, (int)optp->name, (int)optp->len));
16619 	qreply(q, mpctl);
16620 	return (mp2ctl);
16621 }
16622 
16623 /* IPv4 multicast group membership. */
16624 static mblk_t *
16625 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16626 {
16627 	struct opthdr		*optp;
16628 	mblk_t			*mp2ctl;
16629 	ill_t			*ill;
16630 	ipif_t			*ipif;
16631 	ilm_t			*ilm;
16632 	ip_member_t		ipm;
16633 	mblk_t			*mp_tail = NULL;
16634 	ill_walk_context_t	ctx;
16635 	zoneid_t		zoneid;
16636 
16637 	/*
16638 	 * make a copy of the original message
16639 	 */
16640 	mp2ctl = copymsg(mpctl);
16641 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16642 
16643 	/* ipGroupMember table */
16644 	optp = (struct opthdr *)&mpctl->b_rptr[
16645 	    sizeof (struct T_optmgmt_ack)];
16646 	optp->level = MIB2_IP;
16647 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16648 
16649 	rw_enter(&ill_g_lock, RW_READER);
16650 	ill = ILL_START_WALK_V4(&ctx);
16651 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16652 		ILM_WALKER_HOLD(ill);
16653 		for (ipif = ill->ill_ipif; ipif != NULL;
16654 		    ipif = ipif->ipif_next) {
16655 			if (ipif->ipif_zoneid != zoneid)
16656 				continue;	/* not this zone */
16657 			(void) ipif_get_name(ipif,
16658 			    ipm.ipGroupMemberIfIndex.o_bytes,
16659 			    OCTET_LENGTH);
16660 			ipm.ipGroupMemberIfIndex.o_length =
16661 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16662 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16663 				ASSERT(ilm->ilm_ipif != NULL);
16664 				ASSERT(ilm->ilm_ill == NULL);
16665 				if (ilm->ilm_ipif != ipif)
16666 					continue;
16667 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16668 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16669 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16670 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16671 				    (char *)&ipm, (int)sizeof (ipm))) {
16672 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16673 					    "failed to allocate %u bytes\n",
16674 						(uint_t)sizeof (ipm)));
16675 				}
16676 			}
16677 		}
16678 		ILM_WALKER_RELE(ill);
16679 	}
16680 	rw_exit(&ill_g_lock);
16681 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16682 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16683 	    (int)optp->level, (int)optp->name, (int)optp->len));
16684 	qreply(q, mpctl);
16685 	return (mp2ctl);
16686 }
16687 
16688 /* IPv6 multicast group membership. */
16689 static mblk_t *
16690 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16691 {
16692 	struct opthdr		*optp;
16693 	mblk_t			*mp2ctl;
16694 	ill_t			*ill;
16695 	ilm_t			*ilm;
16696 	ipv6_member_t		ipm6;
16697 	mblk_t			*mp_tail = NULL;
16698 	ill_walk_context_t	ctx;
16699 	zoneid_t		zoneid;
16700 
16701 	/*
16702 	 * make a copy of the original message
16703 	 */
16704 	mp2ctl = copymsg(mpctl);
16705 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16706 
16707 	/* ip6GroupMember table */
16708 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16709 	optp->level = MIB2_IP6;
16710 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16711 
16712 	rw_enter(&ill_g_lock, RW_READER);
16713 	ill = ILL_START_WALK_V6(&ctx);
16714 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16715 		ILM_WALKER_HOLD(ill);
16716 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16717 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16718 			ASSERT(ilm->ilm_ipif == NULL);
16719 			ASSERT(ilm->ilm_ill != NULL);
16720 			if (ilm->ilm_zoneid != zoneid)
16721 				continue;	/* not this zone */
16722 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16723 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16724 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16725 			if (!snmp_append_data2(mpctl->b_cont,
16726 			    &mp_tail,
16727 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16728 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16729 				    "failed to allocate %u bytes\n",
16730 				    (uint_t)sizeof (ipm6)));
16731 			}
16732 		}
16733 		ILM_WALKER_RELE(ill);
16734 	}
16735 	rw_exit(&ill_g_lock);
16736 
16737 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16738 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16739 	    (int)optp->level, (int)optp->name, (int)optp->len));
16740 	qreply(q, mpctl);
16741 	return (mp2ctl);
16742 }
16743 
16744 /* IP multicast filtered sources */
16745 static mblk_t *
16746 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16747 {
16748 	struct opthdr		*optp;
16749 	mblk_t			*mp2ctl;
16750 	ill_t			*ill;
16751 	ipif_t			*ipif;
16752 	ilm_t			*ilm;
16753 	ip_grpsrc_t		ips;
16754 	mblk_t			*mp_tail = NULL;
16755 	ill_walk_context_t	ctx;
16756 	zoneid_t		zoneid;
16757 	int			i;
16758 	slist_t			*sl;
16759 
16760 	/*
16761 	 * make a copy of the original message
16762 	 */
16763 	mp2ctl = copymsg(mpctl);
16764 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16765 
16766 	/* ipGroupSource table */
16767 	optp = (struct opthdr *)&mpctl->b_rptr[
16768 	    sizeof (struct T_optmgmt_ack)];
16769 	optp->level = MIB2_IP;
16770 	optp->name = EXPER_IP_GROUP_SOURCES;
16771 
16772 	rw_enter(&ill_g_lock, RW_READER);
16773 	ill = ILL_START_WALK_V4(&ctx);
16774 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16775 		ILM_WALKER_HOLD(ill);
16776 		for (ipif = ill->ill_ipif; ipif != NULL;
16777 		    ipif = ipif->ipif_next) {
16778 			if (ipif->ipif_zoneid != zoneid)
16779 				continue;	/* not this zone */
16780 			(void) ipif_get_name(ipif,
16781 			    ips.ipGroupSourceIfIndex.o_bytes,
16782 			    OCTET_LENGTH);
16783 			ips.ipGroupSourceIfIndex.o_length =
16784 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16785 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16786 				ASSERT(ilm->ilm_ipif != NULL);
16787 				ASSERT(ilm->ilm_ill == NULL);
16788 				sl = ilm->ilm_filter;
16789 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16790 					continue;
16791 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16792 				for (i = 0; i < sl->sl_numsrc; i++) {
16793 					if (!IN6_IS_ADDR_V4MAPPED(
16794 					    &sl->sl_addr[i]))
16795 						continue;
16796 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16797 					    ips.ipGroupSourceAddress);
16798 					if (snmp_append_data2(mpctl->b_cont,
16799 					    &mp_tail, (char *)&ips,
16800 					    (int)sizeof (ips)) == 0) {
16801 						ip1dbg(("ip_snmp_get_mib2_"
16802 						    "ip_group_src: failed to "
16803 						    "allocate %u bytes\n",
16804 						    (uint_t)sizeof (ips)));
16805 					}
16806 				}
16807 			}
16808 		}
16809 		ILM_WALKER_RELE(ill);
16810 	}
16811 	rw_exit(&ill_g_lock);
16812 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16813 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16814 	    (int)optp->level, (int)optp->name, (int)optp->len));
16815 	qreply(q, mpctl);
16816 	return (mp2ctl);
16817 }
16818 
16819 /* IPv6 multicast filtered sources. */
16820 static mblk_t *
16821 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16822 {
16823 	struct opthdr		*optp;
16824 	mblk_t			*mp2ctl;
16825 	ill_t			*ill;
16826 	ilm_t			*ilm;
16827 	ipv6_grpsrc_t		ips6;
16828 	mblk_t			*mp_tail = NULL;
16829 	ill_walk_context_t	ctx;
16830 	zoneid_t		zoneid;
16831 	int			i;
16832 	slist_t			*sl;
16833 
16834 	/*
16835 	 * make a copy of the original message
16836 	 */
16837 	mp2ctl = copymsg(mpctl);
16838 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16839 
16840 	/* ip6GroupMember table */
16841 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16842 	optp->level = MIB2_IP6;
16843 	optp->name = EXPER_IP6_GROUP_SOURCES;
16844 
16845 	rw_enter(&ill_g_lock, RW_READER);
16846 	ill = ILL_START_WALK_V6(&ctx);
16847 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16848 		ILM_WALKER_HOLD(ill);
16849 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16850 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16851 			ASSERT(ilm->ilm_ipif == NULL);
16852 			ASSERT(ilm->ilm_ill != NULL);
16853 			sl = ilm->ilm_filter;
16854 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16855 				continue;
16856 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16857 			for (i = 0; i < sl->sl_numsrc; i++) {
16858 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16859 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16860 				    (char *)&ips6, (int)sizeof (ips6))) {
16861 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16862 					    "group_src: failed to allocate "
16863 					    "%u bytes\n",
16864 					    (uint_t)sizeof (ips6)));
16865 				}
16866 			}
16867 		}
16868 		ILM_WALKER_RELE(ill);
16869 	}
16870 	rw_exit(&ill_g_lock);
16871 
16872 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16873 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16874 	    (int)optp->level, (int)optp->name, (int)optp->len));
16875 	qreply(q, mpctl);
16876 	return (mp2ctl);
16877 }
16878 
16879 /* Multicast routing virtual interface table. */
16880 static mblk_t *
16881 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16882 {
16883 	struct opthdr		*optp;
16884 	mblk_t			*mp2ctl;
16885 
16886 	/*
16887 	 * make a copy of the original message
16888 	 */
16889 	mp2ctl = copymsg(mpctl);
16890 
16891 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16892 	optp->level = EXPER_DVMRP;
16893 	optp->name = EXPER_DVMRP_VIF;
16894 	if (!ip_mroute_vif(mpctl->b_cont)) {
16895 		ip0dbg(("ip_mroute_vif: failed\n"));
16896 	}
16897 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16898 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16899 	    (int)optp->level, (int)optp->name, (int)optp->len));
16900 	qreply(q, mpctl);
16901 	return (mp2ctl);
16902 }
16903 
16904 /* Multicast routing table. */
16905 static mblk_t *
16906 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16907 {
16908 	struct opthdr		*optp;
16909 	mblk_t			*mp2ctl;
16910 
16911 	/*
16912 	 * make a copy of the original message
16913 	 */
16914 	mp2ctl = copymsg(mpctl);
16915 
16916 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16917 	optp->level = EXPER_DVMRP;
16918 	optp->name = EXPER_DVMRP_MRT;
16919 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16920 		ip0dbg(("ip_mroute_mrt: failed\n"));
16921 	}
16922 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16923 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16924 	    (int)optp->level, (int)optp->name, (int)optp->len));
16925 	qreply(q, mpctl);
16926 	return (mp2ctl);
16927 }
16928 
16929 /*
16930  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16931  * in one IRE walk.
16932  */
16933 static mblk_t *
16934 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16935 {
16936 	struct opthdr		*optp;
16937 	mblk_t			*mp2ctl;	/* Returned */
16938 	mblk_t			*mp3ctl;	/* nettomedia */
16939 	/*
16940 	 * We need two listptrs, for ipRouteEntryTable and
16941 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16942 	 */
16943 	listptr_t		re_ntme_v4[2];
16944 	zoneid_t		zoneid;
16945 
16946 	/*
16947 	 * make a copy of the original message
16948 	 */
16949 	mp2ctl = copymsg(mpctl);
16950 	mp3ctl = copymsg(mpctl);
16951 	if (mp3ctl == NULL) {
16952 		freemsg(mp2ctl);
16953 		freemsg(mpctl);
16954 		return (NULL);
16955 	}
16956 
16957 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
16958 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
16959 	/*
16960 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16961 	 * proper values when called.
16962 	 */
16963 	re_ntme_v4[0].lp_tail = NULL;
16964 	re_ntme_v4[1].lp_tail = NULL;
16965 
16966 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16967 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
16968 	if (zoneid == GLOBAL_ZONEID) {
16969 		/*
16970 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
16971 		 * the sys_net_config privilege, it can only run in the global
16972 		 * zone, so we don't display these IREs in the other zones.
16973 		 */
16974 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
16975 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
16976 		    NULL);
16977 	}
16978 
16979 	/* ipRouteEntryTable in mpctl */
16980 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16981 	optp->level = MIB2_IP;
16982 	optp->name = MIB2_IP_ROUTE;
16983 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
16984 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16985 	    (int)optp->level, (int)optp->name, (int)optp->len));
16986 	qreply(q, mpctl);
16987 
16988 	/* ipNetToMediaEntryTable in mp3ctl */
16989 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16990 	optp->level = MIB2_IP;
16991 	optp->name = MIB2_IP_MEDIA;
16992 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
16993 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16994 	    (int)optp->level, (int)optp->name, (int)optp->len));
16995 	qreply(q, mp3ctl);
16996 	return (mp2ctl);
16997 }
16998 
16999 /*
17000  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
17001  * in one IRE walk.
17002  */
17003 static mblk_t *
17004 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17005 {
17006 	struct opthdr		*optp;
17007 	mblk_t			*mp2ctl;	/* Returned */
17008 	mblk_t			*mp3ctl;	/* nettomedia */
17009 	listptr_t		re_ntme_v6;
17010 	zoneid_t		zoneid;
17011 
17012 	/*
17013 	 * make a copy of the original message
17014 	 */
17015 	mp2ctl = copymsg(mpctl);
17016 	mp3ctl = copymsg(mpctl);
17017 	if (mp3ctl == NULL) {
17018 		freemsg(mp2ctl);
17019 		freemsg(mpctl);
17020 		return (NULL);
17021 	}
17022 
17023 	/*
17024 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
17025 	 * proper values when called.  ipv6RouteEntryTable in is placed
17026 	 * in mpctl.
17027 	 */
17028 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
17029 	re_ntme_v6.lp_tail = NULL;
17030 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17031 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
17032 
17033 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17034 	optp->level = MIB2_IP6;
17035 	optp->name = MIB2_IP6_ROUTE;
17036 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17037 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17038 	    (int)optp->level, (int)optp->name, (int)optp->len));
17039 	qreply(q, mpctl);
17040 
17041 	/* ipv6NetToMediaEntryTable in mp3ctl */
17042 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
17043 	re_ntme_v6.lp_tail = NULL;
17044 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
17045 
17046 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17047 	optp->level = MIB2_IP6;
17048 	optp->name = MIB2_IP6_MEDIA;
17049 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
17050 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17051 	    (int)optp->level, (int)optp->name, (int)optp->len));
17052 	qreply(q, mp3ctl);
17053 	return (mp2ctl);
17054 }
17055 
17056 /*
17057  * ICMPv6 mib: One per ill
17058  */
17059 static mblk_t *
17060 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17061 {
17062 	struct opthdr		*optp;
17063 	mblk_t			*mp2ctl;
17064 	ill_t			*ill;
17065 	ill_walk_context_t	ctx;
17066 	mblk_t			*mp_tail = NULL;
17067 
17068 	/*
17069 	 * Make a copy of the original message
17070 	 */
17071 	mp2ctl = copymsg(mpctl);
17072 
17073 	/* fixed length IPv6 structure ... */
17074 
17075 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17076 	optp->level = MIB2_IP6;
17077 	optp->name = 0;
17078 	/* Include "unknown interface" ip6_mib */
17079 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17080 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17081 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17082 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17083 	    sizeof (mib2_ipv6IfStatsEntry_t));
17084 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17085 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17086 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17087 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17088 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17089 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17090 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17091 	    (int)sizeof (ip6_mib))) {
17092 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17093 		    (uint_t)sizeof (ip6_mib)));
17094 	}
17095 
17096 	rw_enter(&ill_g_lock, RW_READER);
17097 	ill = ILL_START_WALK_V6(&ctx);
17098 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17099 		ill->ill_ip6_mib->ipv6IfIndex =
17100 		    ill->ill_phyint->phyint_ifindex;
17101 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17102 		    ipv6_forward ? 1 : 2);
17103 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17104 		    ill->ill_max_hops);
17105 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17106 		    sizeof (mib2_ipv6IfStatsEntry_t));
17107 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17108 		    sizeof (mib2_ipv6AddrEntry_t));
17109 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17110 		    sizeof (mib2_ipv6RouteEntry_t));
17111 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17112 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17113 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17114 		    sizeof (ipv6_member_t));
17115 
17116 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17117 		    (char *)ill->ill_ip6_mib,
17118 		    (int)sizeof (*ill->ill_ip6_mib))) {
17119 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17120 				"%u bytes\n",
17121 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17122 		}
17123 	}
17124 	rw_exit(&ill_g_lock);
17125 
17126 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17127 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17128 	    (int)optp->level, (int)optp->name, (int)optp->len));
17129 	qreply(q, mpctl);
17130 	return (mp2ctl);
17131 }
17132 
17133 /*
17134  * ICMPv6 mib: One per ill
17135  */
17136 static mblk_t *
17137 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17138 {
17139 	struct opthdr		*optp;
17140 	mblk_t			*mp2ctl;
17141 	ill_t			*ill;
17142 	ill_walk_context_t	ctx;
17143 	mblk_t			*mp_tail = NULL;
17144 	/*
17145 	 * Make a copy of the original message
17146 	 */
17147 	mp2ctl = copymsg(mpctl);
17148 
17149 	/* fixed length ICMPv6 structure ... */
17150 
17151 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17152 	optp->level = MIB2_ICMP6;
17153 	optp->name = 0;
17154 	/* Include "unknown interface" icmp6_mib */
17155 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17156 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17157 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17158 	    (int)sizeof (icmp6_mib))) {
17159 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17160 		    (uint_t)sizeof (icmp6_mib)));
17161 	}
17162 
17163 	rw_enter(&ill_g_lock, RW_READER);
17164 	ill = ILL_START_WALK_V6(&ctx);
17165 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17166 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17167 		    ill->ill_phyint->phyint_ifindex;
17168 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17169 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17170 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17171 		    (char *)ill->ill_icmp6_mib,
17172 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17173 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17174 			    "%u bytes\n",
17175 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17176 		}
17177 	}
17178 	rw_exit(&ill_g_lock);
17179 
17180 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17181 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17182 	    (int)optp->level, (int)optp->name, (int)optp->len));
17183 	qreply(q, mpctl);
17184 	return (mp2ctl);
17185 }
17186 
17187 /*
17188  * ire_walk routine to create both ipRouteEntryTable and
17189  * ipNetToMediaEntryTable in one IRE walk
17190  */
17191 static void
17192 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17193 {
17194 	ill_t				*ill;
17195 	ipif_t				*ipif;
17196 	mblk_t				*llmp;
17197 	dl_unitdata_req_t		*dlup;
17198 	mib2_ipRouteEntry_t		re;
17199 	mib2_ipNetToMediaEntry_t	ntme;
17200 	ipaddr_t			gw_addr;
17201 
17202 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17203 
17204 	/*
17205 	 * Return all IRE types for route table... let caller pick and choose
17206 	 */
17207 	re.ipRouteDest = ire->ire_addr;
17208 	ipif = ire->ire_ipif;
17209 	re.ipRouteIfIndex.o_length = 0;
17210 	if (ire->ire_type == IRE_CACHE) {
17211 		ill = (ill_t *)ire->ire_stq->q_ptr;
17212 		re.ipRouteIfIndex.o_length =
17213 		    ill->ill_name_length == 0 ? 0 :
17214 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17215 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17216 		    re.ipRouteIfIndex.o_length);
17217 	} else if (ipif != NULL) {
17218 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17219 		    OCTET_LENGTH);
17220 		re.ipRouteIfIndex.o_length =
17221 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17222 	}
17223 	re.ipRouteMetric1 = -1;
17224 	re.ipRouteMetric2 = -1;
17225 	re.ipRouteMetric3 = -1;
17226 	re.ipRouteMetric4 = -1;
17227 
17228 	gw_addr = ire->ire_gateway_addr;
17229 
17230 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17231 		re.ipRouteNextHop = ire->ire_src_addr;
17232 	else
17233 		re.ipRouteNextHop = gw_addr;
17234 	/* indirect(4), direct(3), or invalid(2) */
17235 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17236 		re.ipRouteType = 2;
17237 	else
17238 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17239 	re.ipRouteProto = -1;
17240 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17241 	re.ipRouteMask = ire->ire_mask;
17242 	re.ipRouteMetric5 = -1;
17243 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17244 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17245 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17246 	llmp = ire->ire_dlureq_mp;
17247 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17248 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17249 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17250 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17251 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17252 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17253 	re.ipRouteInfo.re_in_ill.o_length = 0;
17254 	if (ire->ire_in_ill != NULL) {
17255 		re.ipRouteInfo.re_in_ill.o_length =
17256 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17257 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17258 		bcopy(ire->ire_in_ill->ill_name,
17259 		    re.ipRouteInfo.re_in_ill.o_bytes,
17260 		    re.ipRouteInfo.re_in_ill.o_length);
17261 	}
17262 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17263 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17264 	    (char *)&re, (int)sizeof (re))) {
17265 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17266 		    (uint_t)sizeof (re)));
17267 	}
17268 
17269 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17270 		return;
17271 	/*
17272 	 * only IRE_CACHE entries that are for a directly connected subnet
17273 	 * get appended to net -> phys addr table
17274 	 * (others in arp)
17275 	 */
17276 	ntme.ipNetToMediaIfIndex.o_length = 0;
17277 	ill = ire_to_ill(ire);
17278 	ASSERT(ill != NULL);
17279 	ntme.ipNetToMediaIfIndex.o_length =
17280 	    ill->ill_name_length == 0 ? 0 :
17281 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17282 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17283 		    ntme.ipNetToMediaIfIndex.o_length);
17284 
17285 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17286 	if (llmp) {
17287 		uchar_t *addr;
17288 
17289 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17290 		/* Remove sap from  address */
17291 		if (ill->ill_sap_length < 0)
17292 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17293 		else
17294 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17295 			    ill->ill_sap_length;
17296 
17297 		ntme.ipNetToMediaPhysAddress.o_length =
17298 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17299 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17300 		    ntme.ipNetToMediaPhysAddress.o_length);
17301 	}
17302 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17303 	/* assume dynamic (may be changed in arp) */
17304 	ntme.ipNetToMediaType = 3;
17305 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17306 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17307 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17308 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17309 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17310 	    (char *)&ntme, (int)sizeof (ntme))) {
17311 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17312 		    (uint_t)sizeof (ntme)));
17313 	}
17314 }
17315 
17316 /*
17317  * ire_walk routine to create ipv6RouteEntryTable.
17318  */
17319 static void
17320 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17321 {
17322 	ill_t				*ill;
17323 	ipif_t				*ipif;
17324 	mib2_ipv6RouteEntry_t		re;
17325 	in6_addr_t			gw_addr_v6;
17326 
17327 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17328 
17329 	/*
17330 	 * Return all IRE types for route table... let caller pick and choose
17331 	 */
17332 	re.ipv6RouteDest = ire->ire_addr_v6;
17333 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17334 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17335 	re.ipv6RouteIfIndex.o_length = 0;
17336 	ipif = ire->ire_ipif;
17337 	if (ire->ire_type == IRE_CACHE) {
17338 		ill = (ill_t *)ire->ire_stq->q_ptr;
17339 		re.ipv6RouteIfIndex.o_length =
17340 		    ill->ill_name_length == 0 ? 0 :
17341 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17342 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17343 		    re.ipv6RouteIfIndex.o_length);
17344 	} else if (ipif != NULL) {
17345 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17346 		    OCTET_LENGTH);
17347 		re.ipv6RouteIfIndex.o_length =
17348 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17349 	}
17350 
17351 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17352 
17353 	mutex_enter(&ire->ire_lock);
17354 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17355 	mutex_exit(&ire->ire_lock);
17356 
17357 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17358 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17359 	else
17360 		re.ipv6RouteNextHop = gw_addr_v6;
17361 
17362 	/* remote(4), local(3), or discard(2) */
17363 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17364 		re.ipv6RouteType = 2;
17365 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17366 		re.ipv6RouteType = 3;
17367 	else
17368 		re.ipv6RouteType = 4;
17369 
17370 	re.ipv6RouteProtocol		= -1;
17371 	re.ipv6RoutePolicy		= 0;
17372 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17373 	re.ipv6RouteNextHopRDI		= 0;
17374 	re.ipv6RouteWeight		= 0;
17375 	re.ipv6RouteMetric		= 0;
17376 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17377 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17378 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17379 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17380 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17381 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17382 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17383 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17384 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17385 
17386 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17387 	    (char *)&re, (int)sizeof (re))) {
17388 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17389 		    (uint_t)sizeof (re)));
17390 	}
17391 }
17392 
17393 /*
17394  * ndp_walk routine to create ipv6NetToMediaEntryTable
17395  */
17396 static int
17397 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17398 {
17399 	ill_t				*ill;
17400 	mib2_ipv6NetToMediaEntry_t	ntme;
17401 	dl_unitdata_req_t		*dl;
17402 
17403 	ill = nce->nce_ill;
17404 	ASSERT(ill->ill_isv6);
17405 
17406 	/*
17407 	 * Neighbor cache entry attached to IRE with on-link
17408 	 * destination.
17409 	 */
17410 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17411 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17412 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17413 	    (nce->nce_res_mp != NULL)) {
17414 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17415 		ntme.ipv6NetToMediaPhysAddress.o_length =
17416 		    dl->dl_dest_addr_length;
17417 	} else {
17418 		ntme.ipv6NetToMediaPhysAddress.o_length =
17419 		    ill->ill_phys_addr_length;
17420 	}
17421 	if (nce->nce_res_mp != NULL) {
17422 		bcopy((char *)nce->nce_res_mp->b_rptr +
17423 		    NCE_LL_ADDR_OFFSET(ill),
17424 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17425 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17426 	} else {
17427 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17428 		    ill->ill_phys_addr_length);
17429 	}
17430 	/*
17431 	 * Note: Returns ND_* states. Should be:
17432 	 * reachable(1), stale(2), delay(3), probe(4),
17433 	 * invalid(5), unknown(6)
17434 	 */
17435 	ntme.ipv6NetToMediaState = nce->nce_state;
17436 	ntme.ipv6NetToMediaLastUpdated = 0;
17437 
17438 	/* other(1), dynamic(2), static(3), local(4) */
17439 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17440 		ntme.ipv6NetToMediaType = 4;
17441 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17442 		ntme.ipv6NetToMediaType = 1;
17443 	} else {
17444 		ntme.ipv6NetToMediaType = 2;
17445 	}
17446 
17447 	if (!snmp_append_data2(re_ntme->lp_head,
17448 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17449 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17450 		    (uint_t)sizeof (ntme)));
17451 	}
17452 	return (0);
17453 }
17454 
17455 /*
17456  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17457  */
17458 /* ARGSUSED */
17459 int
17460 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17461 {
17462 	switch (level) {
17463 	case MIB2_IP:
17464 	case MIB2_ICMP:
17465 		switch (name) {
17466 		default:
17467 			break;
17468 		}
17469 		return (1);
17470 	default:
17471 		return (1);
17472 	}
17473 }
17474 
17475 /*
17476  * Called before the options are updated to check if this packet will
17477  * be source routed from here.
17478  * This routine assumes that the options are well formed i.e. that they
17479  * have already been checked.
17480  */
17481 static boolean_t
17482 ip_source_routed(ipha_t *ipha)
17483 {
17484 	ipoptp_t	opts;
17485 	uchar_t		*opt;
17486 	uint8_t		optval;
17487 	uint8_t		optlen;
17488 	ipaddr_t	dst;
17489 	ire_t		*ire;
17490 
17491 	if (IS_SIMPLE_IPH(ipha)) {
17492 		ip2dbg(("not source routed\n"));
17493 		return (B_FALSE);
17494 	}
17495 	dst = ipha->ipha_dst;
17496 	for (optval = ipoptp_first(&opts, ipha);
17497 	    optval != IPOPT_EOL;
17498 	    optval = ipoptp_next(&opts)) {
17499 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17500 		opt = opts.ipoptp_cur;
17501 		optlen = opts.ipoptp_len;
17502 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17503 		    optval, optlen));
17504 		switch (optval) {
17505 			uint32_t off;
17506 		case IPOPT_SSRR:
17507 		case IPOPT_LSRR:
17508 			/*
17509 			 * If dst is one of our addresses and there are some
17510 			 * entries left in the source route return (true).
17511 			 */
17512 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17513 			    ALL_ZONES, MATCH_IRE_TYPE);
17514 			if (ire == NULL) {
17515 				ip2dbg(("ip_source_routed: not next"
17516 				    " source route 0x%x\n",
17517 				    ntohl(dst)));
17518 				return (B_FALSE);
17519 			}
17520 			ire_refrele(ire);
17521 			off = opt[IPOPT_OFFSET];
17522 			off--;
17523 			if (optlen < IP_ADDR_LEN ||
17524 			    off > optlen - IP_ADDR_LEN) {
17525 				/* End of source route */
17526 				ip1dbg(("ip_source_routed: end of SR\n"));
17527 				return (B_FALSE);
17528 			}
17529 			return (B_TRUE);
17530 		}
17531 	}
17532 	ip2dbg(("not source routed\n"));
17533 	return (B_FALSE);
17534 }
17535 
17536 /*
17537  * Check if the packet contains any source route.
17538  */
17539 static boolean_t
17540 ip_source_route_included(ipha_t *ipha)
17541 {
17542 	ipoptp_t	opts;
17543 	uint8_t		optval;
17544 
17545 	if (IS_SIMPLE_IPH(ipha))
17546 		return (B_FALSE);
17547 	for (optval = ipoptp_first(&opts, ipha);
17548 	    optval != IPOPT_EOL;
17549 	    optval = ipoptp_next(&opts)) {
17550 		switch (optval) {
17551 		case IPOPT_SSRR:
17552 		case IPOPT_LSRR:
17553 			return (B_TRUE);
17554 		}
17555 	}
17556 	return (B_FALSE);
17557 }
17558 
17559 /*
17560  * Called when the IRE expiration timer fires.
17561  */
17562 /* ARGSUSED */
17563 void
17564 ip_trash_timer_expire(void *args)
17565 {
17566 	int	flush_flag = 0;
17567 
17568 	/*
17569 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17570 	 * This lock makes sure that a new invocation of this function
17571 	 * that occurs due to an almost immediate timer firing will not
17572 	 * progress beyond this point until the current invocation is done
17573 	 */
17574 	mutex_enter(&ip_trash_timer_lock);
17575 	ip_ire_expire_id = 0;
17576 	mutex_exit(&ip_trash_timer_lock);
17577 
17578 	/* Periodic timer */
17579 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17580 		/*
17581 		 * Remove all IRE_CACHE entries since they might
17582 		 * contain arp information.
17583 		 */
17584 		flush_flag |= FLUSH_ARP_TIME;
17585 		ip_ire_arp_time_elapsed = 0;
17586 		IP_STAT(ip_ire_arp_timer_expired);
17587 	}
17588 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17589 		/* Remove all redirects */
17590 		flush_flag |= FLUSH_REDIRECT_TIME;
17591 		ip_ire_rd_time_elapsed = 0;
17592 		IP_STAT(ip_ire_redirect_timer_expired);
17593 	}
17594 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17595 		/* Increase path mtu */
17596 		flush_flag |= FLUSH_MTU_TIME;
17597 		ip_ire_pmtu_time_elapsed = 0;
17598 		IP_STAT(ip_ire_pmtu_timer_expired);
17599 	}
17600 	if (flush_flag != 0) {
17601 		/* Walk all IPv4 IRE's and update them */
17602 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17603 		    ALL_ZONES);
17604 	}
17605 	if (flush_flag & FLUSH_MTU_TIME) {
17606 		/*
17607 		 * Walk all IPv6 IRE's and update them
17608 		 * Note that ARP and redirect timers are not
17609 		 * needed since NUD handles stale entries.
17610 		 */
17611 		flush_flag = FLUSH_MTU_TIME;
17612 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17613 		    ALL_ZONES);
17614 	}
17615 
17616 	ip_ire_arp_time_elapsed += ip_timer_interval;
17617 	ip_ire_rd_time_elapsed += ip_timer_interval;
17618 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17619 
17620 	/*
17621 	 * Hold the lock to serialize timeout calls and prevent
17622 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17623 	 * for the timer to fire and a new invocation of this function
17624 	 * to start before the return value of timeout has been stored
17625 	 * in ip_ire_expire_id by the current invocation.
17626 	 */
17627 	mutex_enter(&ip_trash_timer_lock);
17628 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17629 	    MSEC_TO_TICK(ip_timer_interval));
17630 	mutex_exit(&ip_trash_timer_lock);
17631 }
17632 
17633 /*
17634  * Called by the memory allocator subsystem directly, when the system
17635  * is running low on memory.
17636  */
17637 /* ARGSUSED */
17638 void
17639 ip_trash_ire_reclaim(void *args)
17640 {
17641 	ire_cache_count_t icc;
17642 	ire_cache_reclaim_t icr;
17643 	ncc_cache_count_t ncc;
17644 	nce_cache_reclaim_t ncr;
17645 	uint_t delete_cnt;
17646 	/*
17647 	 * Memory reclaim call back.
17648 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17649 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17650 	 * entries, determine what fraction to free for
17651 	 * each category of IRE_CACHE entries giving absolute priority
17652 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17653 	 * entry will be freed unless all offlink entries are freed).
17654 	 */
17655 	icc.icc_total = 0;
17656 	icc.icc_unused = 0;
17657 	icc.icc_offlink = 0;
17658 	icc.icc_pmtu = 0;
17659 	icc.icc_onlink = 0;
17660 	ire_walk(ire_cache_count, (char *)&icc);
17661 
17662 	/*
17663 	 * Free NCEs for IPv6 like the onlink ires.
17664 	 */
17665 	ncc.ncc_total = 0;
17666 	ncc.ncc_host = 0;
17667 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17668 
17669 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17670 	    icc.icc_pmtu + icc.icc_onlink);
17671 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17672 	IP_STAT(ip_trash_ire_reclaim_calls);
17673 	if (delete_cnt == 0)
17674 		return;
17675 	IP_STAT(ip_trash_ire_reclaim_success);
17676 	/* Always delete all unused offlink entries */
17677 	icr.icr_unused = 1;
17678 	if (delete_cnt <= icc.icc_unused) {
17679 		/*
17680 		 * Only need to free unused entries.  In other words,
17681 		 * there are enough unused entries to free to meet our
17682 		 * target number of freed ire cache entries.
17683 		 */
17684 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17685 		ncr.ncr_host = 0;
17686 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17687 		/*
17688 		 * Only need to free unused entries, plus a fraction of offlink
17689 		 * entries.  It follows from the first if statement that
17690 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17691 		 */
17692 		delete_cnt -= icc.icc_unused;
17693 		/* Round up # deleted by truncating fraction */
17694 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17695 		icr.icr_pmtu = icr.icr_onlink = 0;
17696 		ncr.ncr_host = 0;
17697 	} else if (delete_cnt <=
17698 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17699 		/*
17700 		 * Free all unused and offlink entries, plus a fraction of
17701 		 * pmtu entries.  It follows from the previous if statement
17702 		 * that icc_pmtu is non-zero, and that
17703 		 * delete_cnt != icc_unused + icc_offlink.
17704 		 */
17705 		icr.icr_offlink = 1;
17706 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17707 		/* Round up # deleted by truncating fraction */
17708 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17709 		icr.icr_onlink = 0;
17710 		ncr.ncr_host = 0;
17711 	} else {
17712 		/*
17713 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17714 		 * of onlink entries.  If we're here, then we know that
17715 		 * icc_onlink is non-zero, and that
17716 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17717 		 */
17718 		icr.icr_offlink = icr.icr_pmtu = 1;
17719 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17720 		    icc.icc_pmtu;
17721 		/* Round up # deleted by truncating fraction */
17722 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17723 		/* Using the same delete fraction as for onlink IREs */
17724 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17725 	}
17726 #ifdef DEBUG
17727 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17728 	    "fractions %d/%d/%d/%d\n",
17729 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17730 	    icc.icc_unused, icc.icc_offlink,
17731 	    icc.icc_pmtu, icc.icc_onlink,
17732 	    icr.icr_unused, icr.icr_offlink,
17733 	    icr.icr_pmtu, icr.icr_onlink));
17734 #endif
17735 	ire_walk(ire_cache_reclaim, (char *)&icr);
17736 	if (ncr.ncr_host != 0)
17737 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17738 		    (uchar_t *)&ncr);
17739 #ifdef DEBUG
17740 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17741 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17742 	ire_walk(ire_cache_count, (char *)&icc);
17743 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17744 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17745 	    icc.icc_pmtu, icc.icc_onlink));
17746 #endif
17747 }
17748 
17749 /*
17750  * ip_unbind is called when a copy of an unbind request is received from the
17751  * upper level protocol.  We remove this conn from any fanout hash list it is
17752  * on, and zero out the bind information.  No reply is expected up above.
17753  */
17754 mblk_t *
17755 ip_unbind(queue_t *q, mblk_t *mp)
17756 {
17757 	conn_t	*connp = Q_TO_CONN(q);
17758 
17759 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17760 
17761 	ipcl_hash_remove(connp);
17762 
17763 	ASSERT(mp->b_cont == NULL);
17764 	/*
17765 	 * Convert mp into a T_OK_ACK
17766 	 */
17767 	mp = mi_tpi_ok_ack_alloc(mp);
17768 
17769 	/*
17770 	 * should not happen in practice... T_OK_ACK is smaller than the
17771 	 * original message.
17772 	 */
17773 	if (mp == NULL)
17774 		return (NULL);
17775 
17776 	/*
17777 	 * Don't bzero the ports if its TCP since TCP still needs the
17778 	 * lport to remove it from its own bind hash. TCP will do the
17779 	 * cleanup.
17780 	 */
17781 	if (!IPCL_IS_TCP(connp))
17782 		bzero(&connp->u_port, sizeof (connp->u_port));
17783 
17784 	return (mp);
17785 }
17786 
17787 /*
17788  * Write side put procedure.  Outbound data, IOCTLs, responses from
17789  * resolvers, etc, come down through here.
17790  */
17791 void
17792 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17793 {
17794 	conn_t		*connp = NULL;
17795 	queue_t		*q = (queue_t *)arg2;
17796 	ipha_t		*ipha;
17797 #define	rptr	((uchar_t *)ipha)
17798 	ire_t		*ire = NULL;
17799 	ire_t		*sctp_ire = NULL;
17800 	uint32_t	v_hlen_tos_len;
17801 	ipaddr_t	dst;
17802 	mblk_t		*first_mp = NULL;
17803 	boolean_t	mctl_present;
17804 	ipsec_out_t	*io;
17805 	int		match_flags;
17806 	ill_t		*attach_ill = NULL;
17807 					/* Bind to IPIF_NOFAILOVER ill etc. */
17808 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17809 	ipif_t		*dst_ipif;
17810 	boolean_t	multirt_need_resolve = B_FALSE;
17811 	mblk_t		*copy_mp = NULL;
17812 	int		err;
17813 	zoneid_t	zoneid;
17814 	boolean_t	need_decref = B_FALSE;
17815 	boolean_t	ignore_dontroute = B_FALSE;
17816 	boolean_t	ignore_nexthop = B_FALSE;
17817 	boolean_t	ip_nexthop = B_FALSE;
17818 	ipaddr_t	nexthop_addr;
17819 
17820 #ifdef	_BIG_ENDIAN
17821 #define	V_HLEN	(v_hlen_tos_len >> 24)
17822 #else
17823 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17824 #endif
17825 
17826 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17827 	    "ip_wput_start: q %p", q);
17828 
17829 	/*
17830 	 * ip_wput fast path
17831 	 */
17832 
17833 	/* is packet from ARP ? */
17834 	if (q->q_next != NULL)
17835 		goto qnext;
17836 
17837 	connp = (conn_t *)arg;
17838 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17839 
17840 	/* is queue flow controlled? */
17841 	if ((q->q_first != NULL || connp->conn_draining) &&
17842 	    (caller == IP_WPUT)) {
17843 		ASSERT(!need_decref);
17844 		(void) putq(q, mp);
17845 		return;
17846 	}
17847 
17848 	/* Multidata transmit? */
17849 	if (DB_TYPE(mp) == M_MULTIDATA) {
17850 		/*
17851 		 * We should never get here, since all Multidata messages
17852 		 * originating from tcp should have been directed over to
17853 		 * tcp_multisend() in the first place.
17854 		 */
17855 		BUMP_MIB(&ip_mib, ipOutDiscards);
17856 		freemsg(mp);
17857 		return;
17858 	} else if (DB_TYPE(mp) != M_DATA)
17859 		goto notdata;
17860 	if (mp->b_flag & MSGHASREF) {
17861 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17862 		mp->b_flag &= ~MSGHASREF;
17863 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17864 		need_decref = B_TRUE;
17865 	}
17866 	ipha = (ipha_t *)mp->b_rptr;
17867 
17868 	/* is IP header non-aligned or mblk smaller than basic IP header */
17869 #ifndef SAFETY_BEFORE_SPEED
17870 	if (!OK_32PTR(rptr) ||
17871 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17872 		goto hdrtoosmall;
17873 #endif
17874 
17875 	/*
17876 	 * If there is a policy, try to attach an ipsec_out in
17877 	 * the front. At the end, first_mp either points to a
17878 	 * M_DATA message or IPSEC_OUT message linked to a
17879 	 * M_DATA message. We have to do it now as we might
17880 	 * lose the "conn" if we go through ip_newroute.
17881 	 */
17882 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17883 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17884 		    ipha->ipha_protocol)) == NULL)) {
17885 			if (need_decref)
17886 				CONN_DEC_REF(connp);
17887 			return;
17888 		} else {
17889 			ASSERT(mp->b_datap->db_type == M_CTL);
17890 			first_mp = mp;
17891 			mp = mp->b_cont;
17892 			mctl_present = B_TRUE;
17893 		}
17894 	} else {
17895 		first_mp = mp;
17896 		mctl_present = B_FALSE;
17897 	}
17898 
17899 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17900 
17901 	/* is wrong version or IP options present */
17902 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17903 		goto version_hdrlen_check;
17904 	dst = ipha->ipha_dst;
17905 
17906 	if (connp->conn_nofailover_ill != NULL) {
17907 		attach_ill = conn_get_held_ill(connp,
17908 		    &connp->conn_nofailover_ill, &err);
17909 		if (err == ILL_LOOKUP_FAILED) {
17910 			if (need_decref)
17911 				CONN_DEC_REF(connp);
17912 			freemsg(first_mp);
17913 			return;
17914 		}
17915 	}
17916 
17917 	/* is packet multicast? */
17918 	if (CLASSD(dst))
17919 		goto multicast;
17920 
17921 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
17922 	    (connp->conn_nexthop_set)) {
17923 		/*
17924 		 * If the destination is a broadcast or a loopback
17925 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
17926 		 * through the standard path. But in the case of local
17927 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
17928 		 * the standard path not IP_XMIT_IF.
17929 		 */
17930 		ire = ire_cache_lookup(dst, zoneid);
17931 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17932 		    (ire->ire_type != IRE_LOOPBACK))) {
17933 			if ((connp->conn_dontroute ||
17934 			    connp->conn_nexthop_set) && (ire != NULL) &&
17935 			    (ire->ire_type == IRE_LOCAL))
17936 				goto standard_path;
17937 
17938 			if (ire != NULL) {
17939 				ire_refrele(ire);
17940 				/* No more access to ire */
17941 				ire = NULL;
17942 			}
17943 			/*
17944 			 * bypass routing checks and go directly to
17945 			 * interface.
17946 			 */
17947 			if (connp->conn_dontroute) {
17948 				goto dontroute;
17949 			} else if (connp->conn_nexthop_set) {
17950 				ip_nexthop = B_TRUE;
17951 				nexthop_addr = connp->conn_nexthop_v4;
17952 				goto send_from_ill;
17953 			}
17954 
17955 			/*
17956 			 * If IP_XMIT_IF socket option is set,
17957 			 * then we allow unicast and multicast
17958 			 * packets to go through the ill. It is
17959 			 * quite possible that the destination
17960 			 * is not in the ire cache table and we
17961 			 * do not want to go to ip_newroute()
17962 			 * instead we call ip_newroute_ipif.
17963 			 */
17964 			xmit_ill = conn_get_held_ill(connp,
17965 			    &connp->conn_xmit_if_ill, &err);
17966 			if (err == ILL_LOOKUP_FAILED) {
17967 				if (attach_ill != NULL)
17968 					ill_refrele(attach_ill);
17969 				if (need_decref)
17970 					CONN_DEC_REF(connp);
17971 				freemsg(first_mp);
17972 				return;
17973 			}
17974 			goto send_from_ill;
17975 		}
17976 standard_path:
17977 		/* Must be a broadcast, a loopback or a local ire */
17978 		if (ire != NULL) {
17979 			ire_refrele(ire);
17980 			/* No more access to ire */
17981 			ire = NULL;
17982 		}
17983 	}
17984 
17985 	if (attach_ill != NULL)
17986 		goto send_from_ill;
17987 
17988 	/*
17989 	 * We cache IRE_CACHEs to avoid lookups. We don't do
17990 	 * this for the tcp global queue and listen end point
17991 	 * as it does not really have a real destination to
17992 	 * talk to.  This is also true for SCTP.
17993 	 */
17994 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
17995 	    !connp->conn_fully_bound) {
17996 		ire = ire_cache_lookup(dst, zoneid);
17997 		if (ire == NULL)
17998 			goto noirefound;
17999 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18000 		    "ip_wput_end: q %p (%S)", q, "end");
18001 
18002 		/*
18003 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18004 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18005 		 */
18006 		if (ire->ire_flags & RTF_MULTIRT) {
18007 
18008 			/*
18009 			 * Force the TTL of multirouted packets if required.
18010 			 * The TTL of such packets is bounded by the
18011 			 * ip_multirt_ttl ndd variable.
18012 			 */
18013 			if ((ip_multirt_ttl > 0) &&
18014 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18015 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18016 				    "(was %d), dst 0x%08x\n",
18017 				    ip_multirt_ttl, ipha->ipha_ttl,
18018 				    ntohl(ire->ire_addr)));
18019 				ipha->ipha_ttl = ip_multirt_ttl;
18020 			}
18021 			/*
18022 			 * We look at this point if there are pending
18023 			 * unresolved routes. ire_multirt_resolvable()
18024 			 * checks in O(n) that all IRE_OFFSUBNET ire
18025 			 * entries for the packet's destination and
18026 			 * flagged RTF_MULTIRT are currently resolved.
18027 			 * If some remain unresolved, we make a copy
18028 			 * of the current message. It will be used
18029 			 * to initiate additional route resolutions.
18030 			 */
18031 			multirt_need_resolve =
18032 			    ire_multirt_need_resolve(ire->ire_addr);
18033 			ip2dbg(("ip_wput[TCP]: ire %p, "
18034 			    "multirt_need_resolve %d, first_mp %p\n",
18035 			    (void *)ire, multirt_need_resolve,
18036 			    (void *)first_mp));
18037 			if (multirt_need_resolve) {
18038 				copy_mp = copymsg(first_mp);
18039 				if (copy_mp != NULL) {
18040 					MULTIRT_DEBUG_TAG(copy_mp);
18041 				}
18042 			}
18043 		}
18044 
18045 		ip_wput_ire(q, first_mp, ire, connp, caller);
18046 
18047 		/*
18048 		 * Try to resolve another multiroute if
18049 		 * ire_multirt_need_resolve() deemed it necessary.
18050 		 */
18051 		if (copy_mp != NULL) {
18052 			ip_newroute(q, copy_mp, dst, NULL, connp);
18053 		}
18054 		if (need_decref)
18055 			CONN_DEC_REF(connp);
18056 		return;
18057 	}
18058 
18059 	/*
18060 	 * Access to conn_ire_cache. (protected by conn_lock)
18061 	 *
18062 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18063 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18064 	 * send a packet or two with the IRE_CACHE that is going away.
18065 	 * Access to the ire requires an ire refhold on the ire prior to
18066 	 * its use since an interface unplumb thread may delete the cached
18067 	 * ire and release the refhold at any time.
18068 	 *
18069 	 * Caching an ire in the conn_ire_cache
18070 	 *
18071 	 * o Caching an ire pointer in the conn requires a strict check for
18072 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18073 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18074 	 * in the conn is done after making sure under the bucket lock that the
18075 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18076 	 * caching an ire after the unplumb thread has cleaned up the conn.
18077 	 * If the conn does not send a packet subsequently the unplumb thread
18078 	 * will be hanging waiting for the ire count to drop to zero.
18079 	 *
18080 	 * o We also need to atomically test for a null conn_ire_cache and
18081 	 * set the conn_ire_cache under the the protection of the conn_lock
18082 	 * to avoid races among concurrent threads trying to simultaneously
18083 	 * cache an ire in the conn_ire_cache.
18084 	 */
18085 	mutex_enter(&connp->conn_lock);
18086 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18087 
18088 	if (ire != NULL && ire->ire_addr == dst &&
18089 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18090 
18091 		IRE_REFHOLD(ire);
18092 		mutex_exit(&connp->conn_lock);
18093 
18094 	} else {
18095 		boolean_t cached = B_FALSE;
18096 		connp->conn_ire_cache = NULL;
18097 		mutex_exit(&connp->conn_lock);
18098 		/* Release the old ire */
18099 		if (ire != NULL && sctp_ire == NULL)
18100 			IRE_REFRELE_NOTR(ire);
18101 
18102 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
18103 		if (ire == NULL)
18104 			goto noirefound;
18105 		IRE_REFHOLD_NOTR(ire);
18106 
18107 		mutex_enter(&connp->conn_lock);
18108 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18109 		    connp->conn_ire_cache == NULL) {
18110 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18111 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18112 				connp->conn_ire_cache = ire;
18113 				cached = B_TRUE;
18114 			}
18115 			rw_exit(&ire->ire_bucket->irb_lock);
18116 		}
18117 		mutex_exit(&connp->conn_lock);
18118 
18119 		/*
18120 		 * We can continue to use the ire but since it was
18121 		 * not cached, we should drop the extra reference.
18122 		 */
18123 		if (!cached)
18124 			IRE_REFRELE_NOTR(ire);
18125 	}
18126 
18127 
18128 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18129 	    "ip_wput_end: q %p (%S)", q, "end");
18130 
18131 	/*
18132 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18133 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18134 	 */
18135 	if (ire->ire_flags & RTF_MULTIRT) {
18136 
18137 		/*
18138 		 * Force the TTL of multirouted packets if required.
18139 		 * The TTL of such packets is bounded by the
18140 		 * ip_multirt_ttl ndd variable.
18141 		 */
18142 		if ((ip_multirt_ttl > 0) &&
18143 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18144 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18145 			    "(was %d), dst 0x%08x\n",
18146 			    ip_multirt_ttl, ipha->ipha_ttl,
18147 			    ntohl(ire->ire_addr)));
18148 			ipha->ipha_ttl = ip_multirt_ttl;
18149 		}
18150 
18151 		/*
18152 		 * At this point, we check to see if there are any pending
18153 		 * unresolved routes. ire_multirt_resolvable()
18154 		 * checks in O(n) that all IRE_OFFSUBNET ire
18155 		 * entries for the packet's destination and
18156 		 * flagged RTF_MULTIRT are currently resolved.
18157 		 * If some remain unresolved, we make a copy
18158 		 * of the current message. It will be used
18159 		 * to initiate additional route resolutions.
18160 		 */
18161 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18162 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18163 		    "multirt_need_resolve %d, first_mp %p\n",
18164 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18165 		if (multirt_need_resolve) {
18166 			copy_mp = copymsg(first_mp);
18167 			if (copy_mp != NULL) {
18168 				MULTIRT_DEBUG_TAG(copy_mp);
18169 			}
18170 		}
18171 	}
18172 
18173 	ip_wput_ire(q, first_mp, ire, connp, caller);
18174 
18175 	/*
18176 	 * Try to resolve another multiroute if
18177 	 * ire_multirt_resolvable() deemed it necessary
18178 	 */
18179 	if (copy_mp != NULL) {
18180 		ip_newroute(q, copy_mp, dst, NULL, connp);
18181 	}
18182 	if (need_decref)
18183 		CONN_DEC_REF(connp);
18184 	return;
18185 
18186 qnext:
18187 	/*
18188 	 * Upper Level Protocols pass down complete IP datagrams
18189 	 * as M_DATA messages.	Everything else is a sideshow.
18190 	 *
18191 	 * 1) We could be re-entering ip_wput because of ip_neworute
18192 	 *    in which case we could have a IPSEC_OUT message. We
18193 	 *    need to pass through ip_wput like other datagrams and
18194 	 *    hence cannot branch to ip_wput_nondata.
18195 	 *
18196 	 * 2) ARP, AH, ESP, and other clients who are on the module
18197 	 *    instance of IP stream, give us something to deal with.
18198 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18199 	 *
18200 	 * 3) ICMP replies also could come here.
18201 	 */
18202 	if (DB_TYPE(mp) != M_DATA) {
18203 	    notdata:
18204 		if (DB_TYPE(mp) == M_CTL) {
18205 			/*
18206 			 * M_CTL messages are used by ARP, AH and ESP to
18207 			 * communicate with IP. We deal with IPSEC_IN and
18208 			 * IPSEC_OUT here. ip_wput_nondata handles other
18209 			 * cases.
18210 			 */
18211 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18212 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18213 				first_mp = mp->b_cont;
18214 				first_mp->b_flag &= ~MSGHASREF;
18215 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18216 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18217 				CONN_DEC_REF(connp);
18218 				connp = NULL;
18219 			}
18220 			if (ii->ipsec_info_type == IPSEC_IN) {
18221 				/*
18222 				 * Either this message goes back to
18223 				 * IPSEC for further processing or to
18224 				 * ULP after policy checks.
18225 				 */
18226 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18227 				return;
18228 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18229 				io = (ipsec_out_t *)ii;
18230 				if (io->ipsec_out_proc_begin) {
18231 					/*
18232 					 * IPSEC processing has already started.
18233 					 * Complete it.
18234 					 * IPQoS notes: We don't care what is
18235 					 * in ipsec_out_ill_index since this
18236 					 * won't be processed for IPQoS policies
18237 					 * in ipsec_out_process.
18238 					 */
18239 					ipsec_out_process(q, mp, NULL,
18240 					    io->ipsec_out_ill_index);
18241 					return;
18242 				} else {
18243 					connp = (q->q_next != NULL) ?
18244 					    NULL : Q_TO_CONN(q);
18245 					first_mp = mp;
18246 					mp = mp->b_cont;
18247 					mctl_present = B_TRUE;
18248 				}
18249 				zoneid = io->ipsec_out_zoneid;
18250 				ASSERT(zoneid != ALL_ZONES);
18251 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18252 				/*
18253 				 * It's an IPsec control message requesting
18254 				 * an SADB update to be sent to the IPsec
18255 				 * hardware acceleration capable ills.
18256 				 */
18257 				ipsec_ctl_t *ipsec_ctl =
18258 				    (ipsec_ctl_t *)mp->b_rptr;
18259 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18260 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18261 				mblk_t *cmp = mp->b_cont;
18262 
18263 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18264 				ASSERT(cmp != NULL);
18265 
18266 				freeb(mp);
18267 				ill_ipsec_capab_send_all(satype, cmp, sa);
18268 				return;
18269 			} else {
18270 				/*
18271 				 * This must be ARP.
18272 				 */
18273 				ip_wput_nondata(NULL, q, mp, NULL);
18274 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18275 				    "ip_wput_end: q %p (%S)", q, "nondata");
18276 				return;
18277 			}
18278 		} else {
18279 			/*
18280 			 * This must be non-(ARP/AH/ESP) messages.
18281 			 */
18282 			ASSERT(!need_decref);
18283 			ip_wput_nondata(NULL, q, mp, NULL);
18284 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18285 			    "ip_wput_end: q %p (%S)", q, "nondata");
18286 			return;
18287 		}
18288 	} else {
18289 		first_mp = mp;
18290 		mctl_present = B_FALSE;
18291 	}
18292 
18293 	ASSERT(first_mp != NULL);
18294 	/*
18295 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18296 	 * to make sure that this packet goes out on the same interface it
18297 	 * came in. We handle that here.
18298 	 */
18299 	if (mctl_present) {
18300 		uint_t ifindex;
18301 
18302 		io = (ipsec_out_t *)first_mp->b_rptr;
18303 		if (io->ipsec_out_attach_if ||
18304 		    io->ipsec_out_xmit_if ||
18305 		    io->ipsec_out_ip_nexthop) {
18306 			ill_t	*ill;
18307 
18308 			/*
18309 			 * We may have lost the conn context if we are
18310 			 * coming here from ip_newroute(). Copy the
18311 			 * nexthop information.
18312 			 */
18313 			if (io->ipsec_out_ip_nexthop) {
18314 				ip_nexthop = B_TRUE;
18315 				nexthop_addr = io->ipsec_out_nexthop_addr;
18316 
18317 				ipha = (ipha_t *)mp->b_rptr;
18318 				dst = ipha->ipha_dst;
18319 				goto send_from_ill;
18320 			} else {
18321 				ASSERT(io->ipsec_out_ill_index != 0);
18322 				ifindex = io->ipsec_out_ill_index;
18323 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18324 				    NULL, NULL, NULL, NULL);
18325 				/*
18326 				 * ipsec_out_xmit_if bit is used to tell
18327 				 * ip_wput to use the ill to send outgoing data
18328 				 * as we have no conn when data comes from ICMP
18329 				 * error msg routines. Currently this feature is
18330 				 * only used by ip_mrtun_forward routine.
18331 				 */
18332 				if (io->ipsec_out_xmit_if) {
18333 					xmit_ill = ill;
18334 					if (xmit_ill == NULL) {
18335 						ip1dbg(("ip_output:bad ifindex "
18336 						    "for xmit_ill %d\n",
18337 						    ifindex));
18338 						freemsg(first_mp);
18339 						BUMP_MIB(&ip_mib,
18340 						    ipOutDiscards);
18341 						ASSERT(!need_decref);
18342 						return;
18343 					}
18344 					/* Free up the ipsec_out_t mblk */
18345 					ASSERT(first_mp->b_cont == mp);
18346 					first_mp->b_cont = NULL;
18347 					freeb(first_mp);
18348 					/* Just send the IP header+ICMP+data */
18349 					first_mp = mp;
18350 					ipha = (ipha_t *)mp->b_rptr;
18351 					dst = ipha->ipha_dst;
18352 					goto send_from_ill;
18353 				} else {
18354 					attach_ill = ill;
18355 				}
18356 
18357 				if (attach_ill == NULL) {
18358 					ASSERT(xmit_ill == NULL);
18359 					ip1dbg(("ip_output: bad ifindex for "
18360 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
18361 					    ifindex));
18362 					freemsg(first_mp);
18363 					BUMP_MIB(&ip_mib, ipOutDiscards);
18364 					ASSERT(!need_decref);
18365 					return;
18366 				}
18367 			}
18368 		}
18369 	}
18370 
18371 	ASSERT(xmit_ill == NULL);
18372 
18373 	/* We have a complete IP datagram heading outbound. */
18374 	ipha = (ipha_t *)mp->b_rptr;
18375 
18376 #ifndef SPEED_BEFORE_SAFETY
18377 	/*
18378 	 * Make sure we have a full-word aligned message and that at least
18379 	 * a simple IP header is accessible in the first message.  If not,
18380 	 * try a pullup.
18381 	 */
18382 	if (!OK_32PTR(rptr) ||
18383 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18384 	    hdrtoosmall:
18385 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18386 			BUMP_MIB(&ip_mib, ipOutDiscards);
18387 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18388 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18389 			if (first_mp == NULL)
18390 				first_mp = mp;
18391 			goto drop_pkt;
18392 		}
18393 		ipha = (ipha_t *)mp->b_rptr;
18394 		if (first_mp == NULL) {
18395 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18396 			/*
18397 			 * If we got here because of "goto hdrtoosmall"
18398 			 * We need to attach a IPSEC_OUT.
18399 			 */
18400 			if (connp->conn_out_enforce_policy) {
18401 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18402 				    NULL, ipha->ipha_protocol)) == NULL)) {
18403 					if (need_decref)
18404 						CONN_DEC_REF(connp);
18405 					return;
18406 				} else {
18407 					ASSERT(mp->b_datap->db_type == M_CTL);
18408 					first_mp = mp;
18409 					mp = mp->b_cont;
18410 					mctl_present = B_TRUE;
18411 				}
18412 			} else {
18413 				first_mp = mp;
18414 				mctl_present = B_FALSE;
18415 			}
18416 		}
18417 	}
18418 #endif
18419 
18420 	/* Most of the code below is written for speed, not readability */
18421 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18422 
18423 	/*
18424 	 * If ip_newroute() fails, we're going to need a full
18425 	 * header for the icmp wraparound.
18426 	 */
18427 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18428 		uint_t	v_hlen;
18429 	    version_hdrlen_check:
18430 		ASSERT(first_mp != NULL);
18431 		v_hlen = V_HLEN;
18432 		/*
18433 		 * siphon off IPv6 packets coming down from transport
18434 		 * layer modules here.
18435 		 * Note: high-order bit carries NUD reachability confirmation
18436 		 */
18437 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18438 			/*
18439 			 * XXX implement a IPv4 and IPv6 packet counter per
18440 			 * conn and switch when ratio exceeds e.g. 10:1
18441 			 */
18442 #ifdef notyet
18443 			if (q->q_next == NULL) /* Avoid ill queue */
18444 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18445 #endif
18446 			BUMP_MIB(&ip_mib, ipOutIPv6);
18447 			ASSERT(xmit_ill == NULL);
18448 			if (attach_ill != NULL)
18449 				ill_refrele(attach_ill);
18450 			if (need_decref)
18451 				mp->b_flag |= MSGHASREF;
18452 			(void) ip_output_v6(connp, first_mp, q, caller);
18453 			return;
18454 		}
18455 
18456 		if ((v_hlen >> 4) != IP_VERSION) {
18457 			BUMP_MIB(&ip_mib, ipOutDiscards);
18458 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18459 			    "ip_wput_end: q %p (%S)", q, "badvers");
18460 			goto drop_pkt;
18461 		}
18462 		/*
18463 		 * Is the header length at least 20 bytes?
18464 		 *
18465 		 * Are there enough bytes accessible in the header?  If
18466 		 * not, try a pullup.
18467 		 */
18468 		v_hlen &= 0xF;
18469 		v_hlen <<= 2;
18470 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18471 			BUMP_MIB(&ip_mib, ipOutDiscards);
18472 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18473 			    "ip_wput_end: q %p (%S)", q, "badlen");
18474 			goto drop_pkt;
18475 		}
18476 		if (v_hlen > (mp->b_wptr - rptr)) {
18477 			if (!pullupmsg(mp, v_hlen)) {
18478 				BUMP_MIB(&ip_mib, ipOutDiscards);
18479 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18480 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18481 				goto drop_pkt;
18482 			}
18483 			ipha = (ipha_t *)mp->b_rptr;
18484 		}
18485 		/*
18486 		 * Move first entry from any source route into ipha_dst and
18487 		 * verify the options
18488 		 */
18489 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18490 			ASSERT(xmit_ill == NULL);
18491 			if (attach_ill != NULL)
18492 				ill_refrele(attach_ill);
18493 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18494 			    "ip_wput_end: q %p (%S)", q, "badopts");
18495 			if (need_decref)
18496 				CONN_DEC_REF(connp);
18497 			return;
18498 		}
18499 	}
18500 	dst = ipha->ipha_dst;
18501 
18502 	/*
18503 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18504 	 * we have to run the packet through ip_newroute which will take
18505 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18506 	 * a resolver, or assigning a default gateway, etc.
18507 	 */
18508 	if (CLASSD(dst)) {
18509 		ipif_t	*ipif;
18510 		uint32_t setsrc = 0;
18511 
18512 	    multicast:
18513 		ASSERT(first_mp != NULL);
18514 		ASSERT(xmit_ill == NULL);
18515 		ip2dbg(("ip_wput: CLASSD\n"));
18516 		if (connp == NULL) {
18517 			/*
18518 			 * Use the first good ipif on the ill.
18519 			 * XXX Should this ever happen? (Appears
18520 			 * to show up with just ppp and no ethernet due
18521 			 * to in.rdisc.)
18522 			 * However, ire_send should be able to
18523 			 * call ip_wput_ire directly.
18524 			 *
18525 			 * XXX Also, this can happen for ICMP and other packets
18526 			 * with multicast source addresses.  Perhaps we should
18527 			 * fix things so that we drop the packet in question,
18528 			 * but for now, just run with it.
18529 			 */
18530 			ill_t *ill = (ill_t *)q->q_ptr;
18531 
18532 			/*
18533 			 * Don't honor attach_if for this case. If ill
18534 			 * is part of the group, ipif could belong to
18535 			 * any ill and we cannot maintain attach_ill
18536 			 * and ipif_ill same anymore and the assert
18537 			 * below would fail.
18538 			 */
18539 			if (mctl_present) {
18540 				io->ipsec_out_ill_index = 0;
18541 				io->ipsec_out_attach_if = B_FALSE;
18542 				ASSERT(attach_ill != NULL);
18543 				ill_refrele(attach_ill);
18544 				attach_ill = NULL;
18545 			}
18546 
18547 			ASSERT(attach_ill == NULL);
18548 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18549 			if (ipif == NULL) {
18550 				if (need_decref)
18551 					CONN_DEC_REF(connp);
18552 				freemsg(first_mp);
18553 				return;
18554 			}
18555 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18556 			    ntohl(dst), ill->ill_name));
18557 		} else {
18558 			/*
18559 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18560 			 * IP_XMIT_IF is honoured.
18561 			 * Block comment above this function explains the
18562 			 * locking mechanism used here
18563 			 */
18564 			xmit_ill = conn_get_held_ill(connp,
18565 			    &connp->conn_xmit_if_ill, &err);
18566 			if (err == ILL_LOOKUP_FAILED) {
18567 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18568 				goto drop_pkt;
18569 			}
18570 			if (xmit_ill == NULL) {
18571 				ipif = conn_get_held_ipif(connp,
18572 				    &connp->conn_multicast_ipif, &err);
18573 				if (err == IPIF_LOOKUP_FAILED) {
18574 					ip1dbg(("ip_wput: No ipif for "
18575 					    "multicast\n"));
18576 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18577 					goto drop_pkt;
18578 				}
18579 			}
18580 			if (xmit_ill != NULL) {
18581 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18582 				if (ipif == NULL) {
18583 					ip1dbg(("ip_wput: No ipif for "
18584 					    "IP_XMIT_IF\n"));
18585 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18586 					goto drop_pkt;
18587 				}
18588 			} else if (ipif == NULL || ipif->ipif_isv6) {
18589 				/*
18590 				 * We must do this ipif determination here
18591 				 * else we could pass through ip_newroute
18592 				 * and come back here without the conn context.
18593 				 *
18594 				 * Note: we do late binding i.e. we bind to
18595 				 * the interface when the first packet is sent.
18596 				 * For performance reasons we do not rebind on
18597 				 * each packet but keep the binding until the
18598 				 * next IP_MULTICAST_IF option.
18599 				 *
18600 				 * conn_multicast_{ipif,ill} are shared between
18601 				 * IPv4 and IPv6 and AF_INET6 sockets can
18602 				 * send both IPv4 and IPv6 packets. Hence
18603 				 * we have to check that "isv6" matches above.
18604 				 */
18605 				if (ipif != NULL)
18606 					ipif_refrele(ipif);
18607 				ipif = ipif_lookup_group(dst, zoneid);
18608 				if (ipif == NULL) {
18609 					ip1dbg(("ip_wput: No ipif for "
18610 					    "multicast\n"));
18611 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18612 					goto drop_pkt;
18613 				}
18614 				err = conn_set_held_ipif(connp,
18615 				    &connp->conn_multicast_ipif, ipif);
18616 				if (err == IPIF_LOOKUP_FAILED) {
18617 					ipif_refrele(ipif);
18618 					ip1dbg(("ip_wput: No ipif for "
18619 					    "multicast\n"));
18620 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18621 					goto drop_pkt;
18622 				}
18623 			}
18624 		}
18625 		ASSERT(!ipif->ipif_isv6);
18626 		/*
18627 		 * As we may lose the conn by the time we reach ip_wput_ire,
18628 		 * we copy conn_multicast_loop and conn_dontroute on to an
18629 		 * ipsec_out. In case if this datagram goes out secure,
18630 		 * we need the ill_index also. Copy that also into the
18631 		 * ipsec_out.
18632 		 */
18633 		if (mctl_present) {
18634 			io = (ipsec_out_t *)first_mp->b_rptr;
18635 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18636 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18637 		} else {
18638 			ASSERT(mp == first_mp);
18639 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18640 			    BPRI_HI)) == NULL) {
18641 				ipif_refrele(ipif);
18642 				first_mp = mp;
18643 				goto drop_pkt;
18644 			}
18645 			first_mp->b_datap->db_type = M_CTL;
18646 			first_mp->b_wptr += sizeof (ipsec_info_t);
18647 			/* ipsec_out_secure is B_FALSE now */
18648 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18649 			io = (ipsec_out_t *)first_mp->b_rptr;
18650 			io->ipsec_out_type = IPSEC_OUT;
18651 			io->ipsec_out_len = sizeof (ipsec_out_t);
18652 			io->ipsec_out_use_global_policy = B_TRUE;
18653 			first_mp->b_cont = mp;
18654 			mctl_present = B_TRUE;
18655 		}
18656 		if (attach_ill != NULL) {
18657 			ASSERT(attach_ill == ipif->ipif_ill);
18658 			match_flags = MATCH_IRE_ILL;
18659 
18660 			/*
18661 			 * Check if we need an ire that will not be
18662 			 * looked up by anybody else i.e. HIDDEN.
18663 			 */
18664 			if (ill_is_probeonly(attach_ill)) {
18665 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18666 			}
18667 			io->ipsec_out_ill_index =
18668 			    attach_ill->ill_phyint->phyint_ifindex;
18669 			io->ipsec_out_attach_if = B_TRUE;
18670 		} else {
18671 			match_flags = MATCH_IRE_ILL_GROUP;
18672 			io->ipsec_out_ill_index =
18673 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18674 		}
18675 		if (connp != NULL) {
18676 			io->ipsec_out_multicast_loop =
18677 			    connp->conn_multicast_loop;
18678 			io->ipsec_out_dontroute = connp->conn_dontroute;
18679 			io->ipsec_out_zoneid = connp->conn_zoneid;
18680 		}
18681 		/*
18682 		 * If the application uses IP_MULTICAST_IF with
18683 		 * different logical addresses of the same ILL, we
18684 		 * need to make sure that the soruce address of
18685 		 * the packet matches the logical IP address used
18686 		 * in the option. We do it by initializing ipha_src
18687 		 * here. This should keep IPSEC also happy as
18688 		 * when we return from IPSEC processing, we don't
18689 		 * have to worry about getting the right address on
18690 		 * the packet. Thus it is sufficient to look for
18691 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18692 		 * MATCH_IRE_IPIF.
18693 		 *
18694 		 * NOTE : We need to do it for non-secure case also as
18695 		 * this might go out secure if there is a global policy
18696 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18697 		 * address, the source should be initialized already and
18698 		 * hence we won't be initializing here.
18699 		 *
18700 		 * As we do not have the ire yet, it is possible that
18701 		 * we set the source address here and then later discover
18702 		 * that the ire implies the source address to be assigned
18703 		 * through the RTF_SETSRC flag.
18704 		 * In that case, the setsrc variable will remind us
18705 		 * that overwritting the source address by the one
18706 		 * of the RTF_SETSRC-flagged ire is allowed.
18707 		 */
18708 		if (ipha->ipha_src == INADDR_ANY &&
18709 		    (connp == NULL || !connp->conn_unspec_src)) {
18710 			ipha->ipha_src = ipif->ipif_src_addr;
18711 			setsrc = RTF_SETSRC;
18712 		}
18713 		/*
18714 		 * Find an IRE which matches the destination and the outgoing
18715 		 * queue (i.e. the outgoing interface.)
18716 		 * For loopback use a unicast IP address for
18717 		 * the ire lookup.
18718 		 */
18719 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18720 		    PHYI_LOOPBACK) {
18721 			dst = ipif->ipif_lcl_addr;
18722 		}
18723 		/*
18724 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18725 		 * We don't need to lookup ire in ctable as the packet
18726 		 * needs to be sent to the destination through the specified
18727 		 * ill irrespective of ires in the cache table.
18728 		 */
18729 		ire = NULL;
18730 		if (xmit_ill == NULL) {
18731 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18732 			    zoneid, match_flags);
18733 		}
18734 
18735 		/*
18736 		 * refrele attach_ill as its not needed anymore.
18737 		 */
18738 		if (attach_ill != NULL) {
18739 			ill_refrele(attach_ill);
18740 			attach_ill = NULL;
18741 		}
18742 
18743 		if (ire == NULL) {
18744 			/*
18745 			 * Multicast loopback and multicast forwarding is
18746 			 * done in ip_wput_ire.
18747 			 *
18748 			 * Mark this packet to make it be delivered to
18749 			 * ip_wput_ire after the new ire has been
18750 			 * created.
18751 			 *
18752 			 * The call to ip_newroute_ipif takes into account
18753 			 * the setsrc reminder. In any case, we take care
18754 			 * of the RTF_MULTIRT flag.
18755 			 */
18756 			mp->b_prev = mp->b_next = NULL;
18757 			if (xmit_ill == NULL ||
18758 			    xmit_ill->ill_ipif_up_count > 0) {
18759 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18760 				    setsrc | RTF_MULTIRT);
18761 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18762 				    "ip_wput_end: q %p (%S)", q, "noire");
18763 			} else {
18764 				freemsg(first_mp);
18765 			}
18766 			ipif_refrele(ipif);
18767 			if (xmit_ill != NULL)
18768 				ill_refrele(xmit_ill);
18769 			if (need_decref)
18770 				CONN_DEC_REF(connp);
18771 			return;
18772 		}
18773 
18774 		ipif_refrele(ipif);
18775 		ipif = NULL;
18776 		ASSERT(xmit_ill == NULL);
18777 
18778 		/*
18779 		 * Honor the RTF_SETSRC flag for multicast packets,
18780 		 * if allowed by the setsrc reminder.
18781 		 */
18782 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18783 			ipha->ipha_src = ire->ire_src_addr;
18784 		}
18785 
18786 		/*
18787 		 * Unconditionally force the TTL to 1 for
18788 		 * multirouted multicast packets:
18789 		 * multirouted multicast should not cross
18790 		 * multicast routers.
18791 		 */
18792 		if (ire->ire_flags & RTF_MULTIRT) {
18793 			if (ipha->ipha_ttl > 1) {
18794 				ip2dbg(("ip_wput: forcing multicast "
18795 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18796 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18797 				ipha->ipha_ttl = 1;
18798 			}
18799 		}
18800 	} else {
18801 		ire = ire_cache_lookup(dst, zoneid);
18802 		if ((ire != NULL) && (ire->ire_type &
18803 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18804 			ignore_dontroute = B_TRUE;
18805 			ignore_nexthop = B_TRUE;
18806 		}
18807 		if (ire != NULL) {
18808 			ire_refrele(ire);
18809 			ire = NULL;
18810 		}
18811 		/*
18812 		 * Guard against coming in from arp in which case conn is NULL.
18813 		 * Also guard against non M_DATA with dontroute set but
18814 		 * destined to local, loopback or broadcast addresses.
18815 		 */
18816 		if (connp != NULL && connp->conn_dontroute &&
18817 		    !ignore_dontroute) {
18818 dontroute:
18819 			/*
18820 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18821 			 * routing protocols from seeing false direct
18822 			 * connectivity.
18823 			 */
18824 			ipha->ipha_ttl = 1;
18825 			/*
18826 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18827 			 * along with SO_DONTROUTE, higher precedence is
18828 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18829 			 */
18830 			if (connp->conn_xmit_if_ill == NULL) {
18831 				/* If suitable ipif not found, drop packet */
18832 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18833 				if (dst_ipif == NULL) {
18834 					ip1dbg(("ip_wput: no route for "
18835 					    "dst using SO_DONTROUTE\n"));
18836 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18837 					mp->b_prev = mp->b_next = NULL;
18838 					if (first_mp == NULL)
18839 						first_mp = mp;
18840 					goto drop_pkt;
18841 				} else {
18842 					/*
18843 					 * If suitable ipif has been found, set
18844 					 * xmit_ill to the corresponding
18845 					 * ipif_ill because we'll be following
18846 					 * the IP_XMIT_IF logic.
18847 					 */
18848 					ASSERT(xmit_ill == NULL);
18849 					xmit_ill = dst_ipif->ipif_ill;
18850 					mutex_enter(&xmit_ill->ill_lock);
18851 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18852 						mutex_exit(&xmit_ill->ill_lock);
18853 						xmit_ill = NULL;
18854 						ipif_refrele(dst_ipif);
18855 						ip1dbg(("ip_wput: no route for"
18856 						    " dst using"
18857 						    " SO_DONTROUTE\n"));
18858 						BUMP_MIB(&ip_mib,
18859 						    ipOutNoRoutes);
18860 						mp->b_prev = mp->b_next = NULL;
18861 						if (first_mp == NULL)
18862 							first_mp = mp;
18863 						goto drop_pkt;
18864 					}
18865 					ill_refhold_locked(xmit_ill);
18866 					mutex_exit(&xmit_ill->ill_lock);
18867 					ipif_refrele(dst_ipif);
18868 				}
18869 			}
18870 
18871 		}
18872 		/*
18873 		 * If we are bound to IPIF_NOFAILOVER address, look for
18874 		 * an IRE_CACHE matching the ill.
18875 		 */
18876 send_from_ill:
18877 		if (attach_ill != NULL) {
18878 			ipif_t	*attach_ipif;
18879 
18880 			match_flags = MATCH_IRE_ILL;
18881 
18882 			/*
18883 			 * Check if we need an ire that will not be
18884 			 * looked up by anybody else i.e. HIDDEN.
18885 			 */
18886 			if (ill_is_probeonly(attach_ill)) {
18887 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18888 			}
18889 
18890 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18891 			if (attach_ipif == NULL) {
18892 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18893 				goto drop_pkt;
18894 			}
18895 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18896 			    zoneid, match_flags);
18897 			ipif_refrele(attach_ipif);
18898 		} else if (xmit_ill != NULL || (connp != NULL &&
18899 			    connp->conn_xmit_if_ill != NULL)) {
18900 			/*
18901 			 * Mark this packet as originated locally
18902 			 */
18903 			mp->b_prev = mp->b_next = NULL;
18904 			/*
18905 			 * xmit_ill could be NULL if SO_DONTROUTE
18906 			 * is also set.
18907 			 */
18908 			if (xmit_ill == NULL) {
18909 				xmit_ill = conn_get_held_ill(connp,
18910 				    &connp->conn_xmit_if_ill, &err);
18911 				if (err == ILL_LOOKUP_FAILED) {
18912 					if (need_decref)
18913 						CONN_DEC_REF(connp);
18914 					freemsg(first_mp);
18915 					return;
18916 				}
18917 				if (xmit_ill == NULL) {
18918 					if (connp->conn_dontroute)
18919 						goto dontroute;
18920 					goto send_from_ill;
18921 				}
18922 			}
18923 			/*
18924 			 * could be SO_DONTROUTE case also.
18925 			 * check at least one interface is UP as
18926 			 * spcified by this ILL, and then call
18927 			 * ip_newroute_ipif()
18928 			 */
18929 			if (xmit_ill->ill_ipif_up_count > 0) {
18930 				ipif_t *ipif;
18931 
18932 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18933 				if (ipif != NULL) {
18934 					ip_newroute_ipif(q, first_mp, ipif,
18935 					    dst, connp, 0);
18936 					ipif_refrele(ipif);
18937 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18938 				}
18939 			} else {
18940 				freemsg(first_mp);
18941 			}
18942 			ill_refrele(xmit_ill);
18943 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18944 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18945 			if (need_decref)
18946 				CONN_DEC_REF(connp);
18947 			return;
18948 		} else if (ip_nexthop || (connp != NULL &&
18949 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
18950 			if (!ip_nexthop) {
18951 				ip_nexthop = B_TRUE;
18952 				nexthop_addr = connp->conn_nexthop_v4;
18953 			}
18954 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
18955 			    MATCH_IRE_GW;
18956 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
18957 			    NULL, zoneid, match_flags);
18958 		} else {
18959 			ire = ire_cache_lookup(dst, zoneid);
18960 		}
18961 		if (!ire) {
18962 			/*
18963 			 * Make sure we don't load spread if this
18964 			 * is IPIF_NOFAILOVER case.
18965 			 */
18966 			if ((attach_ill != NULL) ||
18967 			    (ip_nexthop && !ignore_nexthop)) {
18968 				if (mctl_present) {
18969 					io = (ipsec_out_t *)first_mp->b_rptr;
18970 					ASSERT(first_mp->b_datap->db_type ==
18971 					    M_CTL);
18972 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
18973 				} else {
18974 					ASSERT(mp == first_mp);
18975 					first_mp = allocb(
18976 					    sizeof (ipsec_info_t), BPRI_HI);
18977 					if (first_mp == NULL) {
18978 						first_mp = mp;
18979 						goto drop_pkt;
18980 					}
18981 					first_mp->b_datap->db_type = M_CTL;
18982 					first_mp->b_wptr +=
18983 					    sizeof (ipsec_info_t);
18984 					/* ipsec_out_secure is B_FALSE now */
18985 					bzero(first_mp->b_rptr,
18986 					    sizeof (ipsec_info_t));
18987 					io = (ipsec_out_t *)first_mp->b_rptr;
18988 					io->ipsec_out_type = IPSEC_OUT;
18989 					io->ipsec_out_len =
18990 					    sizeof (ipsec_out_t);
18991 					io->ipsec_out_use_global_policy =
18992 					    B_TRUE;
18993 					first_mp->b_cont = mp;
18994 					mctl_present = B_TRUE;
18995 				}
18996 				if (attach_ill != NULL) {
18997 					io->ipsec_out_ill_index = attach_ill->
18998 					    ill_phyint->phyint_ifindex;
18999 					io->ipsec_out_attach_if = B_TRUE;
19000 				} else {
19001 					io->ipsec_out_ip_nexthop = ip_nexthop;
19002 					io->ipsec_out_nexthop_addr =
19003 					    nexthop_addr;
19004 				}
19005 			}
19006 noirefound:
19007 			/*
19008 			 * Mark this packet as having originated on
19009 			 * this machine.  This will be noted in
19010 			 * ire_add_then_send, which needs to know
19011 			 * whether to run it back through ip_wput or
19012 			 * ip_rput following successful resolution.
19013 			 */
19014 			mp->b_prev = NULL;
19015 			mp->b_next = NULL;
19016 			ip_newroute(q, first_mp, dst, NULL, connp);
19017 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19018 			    "ip_wput_end: q %p (%S)", q, "newroute");
19019 			if (attach_ill != NULL)
19020 				ill_refrele(attach_ill);
19021 			if (xmit_ill != NULL)
19022 				ill_refrele(xmit_ill);
19023 			if (need_decref)
19024 				CONN_DEC_REF(connp);
19025 			return;
19026 		}
19027 	}
19028 
19029 	/* We now know where we are going with it. */
19030 
19031 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19032 	    "ip_wput_end: q %p (%S)", q, "end");
19033 
19034 	/*
19035 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19036 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19037 	 */
19038 	if (ire->ire_flags & RTF_MULTIRT) {
19039 		/*
19040 		 * Force the TTL of multirouted packets if required.
19041 		 * The TTL of such packets is bounded by the
19042 		 * ip_multirt_ttl ndd variable.
19043 		 */
19044 		if ((ip_multirt_ttl > 0) &&
19045 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19046 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19047 			    "(was %d), dst 0x%08x\n",
19048 			    ip_multirt_ttl, ipha->ipha_ttl,
19049 			    ntohl(ire->ire_addr)));
19050 			ipha->ipha_ttl = ip_multirt_ttl;
19051 		}
19052 		/*
19053 		 * At this point, we check to see if there are any pending
19054 		 * unresolved routes. ire_multirt_resolvable()
19055 		 * checks in O(n) that all IRE_OFFSUBNET ire
19056 		 * entries for the packet's destination and
19057 		 * flagged RTF_MULTIRT are currently resolved.
19058 		 * If some remain unresolved, we make a copy
19059 		 * of the current message. It will be used
19060 		 * to initiate additional route resolutions.
19061 		 */
19062 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
19063 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19064 		    "multirt_need_resolve %d, first_mp %p\n",
19065 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19066 		if (multirt_need_resolve) {
19067 			copy_mp = copymsg(first_mp);
19068 			if (copy_mp != NULL) {
19069 				MULTIRT_DEBUG_TAG(copy_mp);
19070 			}
19071 		}
19072 	}
19073 
19074 	ip_wput_ire(q, first_mp, ire, connp, caller);
19075 	/*
19076 	 * Try to resolve another multiroute if
19077 	 * ire_multirt_resolvable() deemed it necessary.
19078 	 * At this point, we need to distinguish
19079 	 * multicasts from other packets. For multicasts,
19080 	 * we call ip_newroute_ipif() and request that both
19081 	 * multirouting and setsrc flags are checked.
19082 	 */
19083 	if (copy_mp != NULL) {
19084 		if (CLASSD(dst)) {
19085 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19086 			if (ipif) {
19087 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19088 				    RTF_SETSRC | RTF_MULTIRT);
19089 				ipif_refrele(ipif);
19090 			} else {
19091 				MULTIRT_DEBUG_UNTAG(copy_mp);
19092 				freemsg(copy_mp);
19093 				copy_mp = NULL;
19094 			}
19095 		} else {
19096 			ip_newroute(q, copy_mp, dst, NULL, connp);
19097 		}
19098 	}
19099 	if (attach_ill != NULL)
19100 		ill_refrele(attach_ill);
19101 	if (xmit_ill != NULL)
19102 		ill_refrele(xmit_ill);
19103 	if (need_decref)
19104 		CONN_DEC_REF(connp);
19105 	return;
19106 
19107 drop_pkt:
19108 	ip1dbg(("ip_wput: dropped packet\n"));
19109 	if (ire != NULL)
19110 		ire_refrele(ire);
19111 	if (need_decref)
19112 		CONN_DEC_REF(connp);
19113 	freemsg(first_mp);
19114 	if (attach_ill != NULL)
19115 		ill_refrele(attach_ill);
19116 	if (xmit_ill != NULL)
19117 		ill_refrele(xmit_ill);
19118 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19119 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19120 }
19121 
19122 void
19123 ip_wput(queue_t *q, mblk_t *mp)
19124 {
19125 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19126 }
19127 
19128 /*
19129  *
19130  * The following rules must be observed when accessing any ipif or ill
19131  * that has been cached in the conn. Typically conn_nofailover_ill,
19132  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19133  *
19134  * Access: The ipif or ill pointed to from the conn can be accessed under
19135  * the protection of the conn_lock or after it has been refheld under the
19136  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19137  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19138  * The reason for this is that a concurrent unplumb could actually be
19139  * cleaning up these cached pointers by walking the conns and might have
19140  * finished cleaning up the conn in question. The macros check that an
19141  * unplumb has not yet started on the ipif or ill.
19142  *
19143  * Caching: An ipif or ill pointer may be cached in the conn only after
19144  * making sure that an unplumb has not started. So the caching is done
19145  * while holding both the conn_lock and the ill_lock and after using the
19146  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
19147  * flag before starting the cleanup of conns.
19148  *
19149  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
19150  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
19151  * or a reference to the ipif or a reference to an ire that references the
19152  * ipif. An ipif does not change its ill except for failover/failback. Since
19153  * failover/failback happens only after bringing down the ipif and making sure
19154  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
19155  * the above holds.
19156  */
19157 ipif_t *
19158 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
19159 {
19160 	ipif_t	*ipif;
19161 	ill_t	*ill;
19162 
19163 	*err = 0;
19164 	rw_enter(&ill_g_lock, RW_READER);
19165 	mutex_enter(&connp->conn_lock);
19166 	ipif = *ipifp;
19167 	if (ipif != NULL) {
19168 		ill = ipif->ipif_ill;
19169 		mutex_enter(&ill->ill_lock);
19170 		if (IPIF_CAN_LOOKUP(ipif)) {
19171 			ipif_refhold_locked(ipif);
19172 			mutex_exit(&ill->ill_lock);
19173 			mutex_exit(&connp->conn_lock);
19174 			rw_exit(&ill_g_lock);
19175 			return (ipif);
19176 		} else {
19177 			*err = IPIF_LOOKUP_FAILED;
19178 		}
19179 		mutex_exit(&ill->ill_lock);
19180 	}
19181 	mutex_exit(&connp->conn_lock);
19182 	rw_exit(&ill_g_lock);
19183 	return (NULL);
19184 }
19185 
19186 ill_t *
19187 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
19188 {
19189 	ill_t	*ill;
19190 
19191 	*err = 0;
19192 	mutex_enter(&connp->conn_lock);
19193 	ill = *illp;
19194 	if (ill != NULL) {
19195 		mutex_enter(&ill->ill_lock);
19196 		if (ILL_CAN_LOOKUP(ill)) {
19197 			ill_refhold_locked(ill);
19198 			mutex_exit(&ill->ill_lock);
19199 			mutex_exit(&connp->conn_lock);
19200 			return (ill);
19201 		} else {
19202 			*err = ILL_LOOKUP_FAILED;
19203 		}
19204 		mutex_exit(&ill->ill_lock);
19205 	}
19206 	mutex_exit(&connp->conn_lock);
19207 	return (NULL);
19208 }
19209 
19210 static int
19211 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
19212 {
19213 	ill_t	*ill;
19214 
19215 	ill = ipif->ipif_ill;
19216 	mutex_enter(&connp->conn_lock);
19217 	mutex_enter(&ill->ill_lock);
19218 	if (IPIF_CAN_LOOKUP(ipif)) {
19219 		*ipifp = ipif;
19220 		mutex_exit(&ill->ill_lock);
19221 		mutex_exit(&connp->conn_lock);
19222 		return (0);
19223 	}
19224 	mutex_exit(&ill->ill_lock);
19225 	mutex_exit(&connp->conn_lock);
19226 	return (IPIF_LOOKUP_FAILED);
19227 }
19228 
19229 /*
19230  * This is called if the outbound datagram needs fragmentation.
19231  *
19232  * NOTE : This function does not ire_refrele the ire argument passed in.
19233  */
19234 static void
19235 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19236 {
19237 	ipha_t		*ipha;
19238 	mblk_t		*mp;
19239 	uint32_t	v_hlen_tos_len;
19240 	uint32_t	max_frag;
19241 	uint32_t	frag_flag;
19242 	boolean_t	dont_use;
19243 
19244 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19245 		mp = ipsec_mp->b_cont;
19246 	} else {
19247 		mp = ipsec_mp;
19248 	}
19249 
19250 	ipha = (ipha_t *)mp->b_rptr;
19251 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19252 
19253 #ifdef	_BIG_ENDIAN
19254 #define	V_HLEN	(v_hlen_tos_len >> 24)
19255 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19256 #else
19257 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19258 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19259 #endif
19260 
19261 #ifndef SPEED_BEFORE_SAFETY
19262 	/*
19263 	 * Check that ipha_length is consistent with
19264 	 * the mblk length
19265 	 */
19266 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19267 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19268 		    LENGTH, msgdsize(mp)));
19269 		freemsg(ipsec_mp);
19270 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19271 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19272 		    "packet length mismatch");
19273 		return;
19274 	}
19275 #endif
19276 	/*
19277 	 * Don't use frag_flag if pre-built packet or source
19278 	 * routed or if multicast (since multicast packets do not solicit
19279 	 * ICMP "packet too big" messages). Get the values of
19280 	 * max_frag and frag_flag atomically by acquiring the
19281 	 * ire_lock.
19282 	 */
19283 	mutex_enter(&ire->ire_lock);
19284 	max_frag = ire->ire_max_frag;
19285 	frag_flag = ire->ire_frag_flag;
19286 	mutex_exit(&ire->ire_lock);
19287 
19288 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19289 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19290 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19291 
19292 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19293 	    (dont_use ? 0 : frag_flag));
19294 }
19295 
19296 /*
19297  * Used for deciding the MSS size for the upper layer. Thus
19298  * we need to check the outbound policy values in the conn.
19299  */
19300 int
19301 conn_ipsec_length(conn_t *connp)
19302 {
19303 	ipsec_latch_t *ipl;
19304 
19305 	ipl = connp->conn_latch;
19306 	if (ipl == NULL)
19307 		return (0);
19308 
19309 	if (ipl->ipl_out_policy == NULL)
19310 		return (0);
19311 
19312 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19313 }
19314 
19315 /*
19316  * Returns an estimate of the IPSEC headers size. This is used if
19317  * we don't want to call into IPSEC to get the exact size.
19318  */
19319 int
19320 ipsec_out_extra_length(mblk_t *ipsec_mp)
19321 {
19322 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19323 	ipsec_action_t *a;
19324 
19325 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19326 	if (!io->ipsec_out_secure)
19327 		return (0);
19328 
19329 	a = io->ipsec_out_act;
19330 
19331 	if (a == NULL) {
19332 		ASSERT(io->ipsec_out_policy != NULL);
19333 		a = io->ipsec_out_policy->ipsp_act;
19334 	}
19335 	ASSERT(a != NULL);
19336 
19337 	return (a->ipa_ovhd);
19338 }
19339 
19340 /*
19341  * Returns an estimate of the IPSEC headers size. This is used if
19342  * we don't want to call into IPSEC to get the exact size.
19343  */
19344 int
19345 ipsec_in_extra_length(mblk_t *ipsec_mp)
19346 {
19347 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19348 	ipsec_action_t *a;
19349 
19350 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19351 
19352 	a = ii->ipsec_in_action;
19353 	return (a == NULL ? 0 : a->ipa_ovhd);
19354 }
19355 
19356 /*
19357  * If there are any source route options, return the true final
19358  * destination. Otherwise, return the destination.
19359  */
19360 ipaddr_t
19361 ip_get_dst(ipha_t *ipha)
19362 {
19363 	ipoptp_t	opts;
19364 	uchar_t		*opt;
19365 	uint8_t		optval;
19366 	uint8_t		optlen;
19367 	ipaddr_t	dst;
19368 	uint32_t off;
19369 
19370 	dst = ipha->ipha_dst;
19371 
19372 	if (IS_SIMPLE_IPH(ipha))
19373 		return (dst);
19374 
19375 	for (optval = ipoptp_first(&opts, ipha);
19376 	    optval != IPOPT_EOL;
19377 	    optval = ipoptp_next(&opts)) {
19378 		opt = opts.ipoptp_cur;
19379 		optlen = opts.ipoptp_len;
19380 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19381 		switch (optval) {
19382 		case IPOPT_SSRR:
19383 		case IPOPT_LSRR:
19384 			off = opt[IPOPT_OFFSET];
19385 			/*
19386 			 * If one of the conditions is true, it means
19387 			 * end of options and dst already has the right
19388 			 * value.
19389 			 */
19390 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19391 				off = optlen - IP_ADDR_LEN;
19392 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19393 			}
19394 			return (dst);
19395 		default:
19396 			break;
19397 		}
19398 	}
19399 
19400 	return (dst);
19401 }
19402 
19403 mblk_t *
19404 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19405     conn_t *connp, boolean_t unspec_src)
19406 {
19407 	ipsec_out_t	*io;
19408 	mblk_t		*first_mp;
19409 	boolean_t policy_present;
19410 
19411 	first_mp = mp;
19412 	if (mp->b_datap->db_type == M_CTL) {
19413 		io = (ipsec_out_t *)first_mp->b_rptr;
19414 		/*
19415 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19416 		 *
19417 		 * 1) There is per-socket policy (including cached global
19418 		 *    policy).
19419 		 * 2) There is no per-socket policy, but it is
19420 		 *    a multicast packet that needs to go out
19421 		 *    on a specific interface. This is the case
19422 		 *    where (ip_wput and ip_wput_multicast) attaches
19423 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19424 		 *
19425 		 * In case (2) we check with global policy to
19426 		 * see if there is a match and set the ill_index
19427 		 * appropriately so that we can lookup the ire
19428 		 * properly in ip_wput_ipsec_out.
19429 		 */
19430 
19431 		/*
19432 		 * ipsec_out_use_global_policy is set to B_FALSE
19433 		 * in ipsec_in_to_out(). Refer to that function for
19434 		 * details.
19435 		 */
19436 		if ((io->ipsec_out_latch == NULL) &&
19437 		    (io->ipsec_out_use_global_policy)) {
19438 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19439 			    ire, connp, unspec_src));
19440 		}
19441 		if (!io->ipsec_out_secure) {
19442 			/*
19443 			 * If this is not a secure packet, drop
19444 			 * the IPSEC_OUT mp and treat it as a clear
19445 			 * packet. This happens when we are sending
19446 			 * a ICMP reply back to a clear packet. See
19447 			 * ipsec_in_to_out() for details.
19448 			 */
19449 			mp = first_mp->b_cont;
19450 			freeb(first_mp);
19451 		}
19452 		return (mp);
19453 	}
19454 	/*
19455 	 * See whether we need to attach a global policy here. We
19456 	 * don't depend on the conn (as it could be null) for deciding
19457 	 * what policy this datagram should go through because it
19458 	 * should have happened in ip_wput if there was some
19459 	 * policy. This normally happens for connections which are not
19460 	 * fully bound preventing us from caching policies in
19461 	 * ip_bind. Packets coming from the TCP listener/global queue
19462 	 * - which are non-hard_bound - could also be affected by
19463 	 * applying policy here.
19464 	 *
19465 	 * If this packet is coming from tcp global queue or listener,
19466 	 * we will be applying policy here.  This may not be *right*
19467 	 * if these packets are coming from the detached connection as
19468 	 * it could have gone in clear before. This happens only if a
19469 	 * TCP connection started when there is no policy and somebody
19470 	 * added policy before it became detached. Thus packets of the
19471 	 * detached connection could go out secure and the other end
19472 	 * would drop it because it will be expecting in clear. The
19473 	 * converse is not true i.e if somebody starts a TCP
19474 	 * connection and deletes the policy, all the packets will
19475 	 * still go out with the policy that existed before deleting
19476 	 * because ip_unbind sends up policy information which is used
19477 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19478 	 * TCP to attach a dummy IPSEC_OUT and set
19479 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19480 	 * affect performance for normal cases, we are not doing it.
19481 	 * Thus, set policy before starting any TCP connections.
19482 	 *
19483 	 * NOTE - We might apply policy even for a hard bound connection
19484 	 * - for which we cached policy in ip_bind - if somebody added
19485 	 * global policy after we inherited the policy in ip_bind.
19486 	 * This means that the packets that were going out in clear
19487 	 * previously would start going secure and hence get dropped
19488 	 * on the other side. To fix this, TCP attaches a dummy
19489 	 * ipsec_out and make sure that we don't apply global policy.
19490 	 */
19491 	if (ipha != NULL)
19492 		policy_present = ipsec_outbound_v4_policy_present;
19493 	else
19494 		policy_present = ipsec_outbound_v6_policy_present;
19495 	if (!policy_present)
19496 		return (mp);
19497 
19498 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19499 }
19500 
19501 ire_t *
19502 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19503 {
19504 	ipaddr_t addr;
19505 	ire_t *save_ire;
19506 	irb_t *irb;
19507 	ill_group_t *illgrp;
19508 	int	err;
19509 
19510 	save_ire = ire;
19511 	addr = ire->ire_addr;
19512 
19513 	ASSERT(ire->ire_type == IRE_BROADCAST);
19514 
19515 	illgrp = connp->conn_outgoing_ill->ill_group;
19516 	if (illgrp == NULL) {
19517 		*conn_outgoing_ill = conn_get_held_ill(connp,
19518 		    &connp->conn_outgoing_ill, &err);
19519 		if (err == ILL_LOOKUP_FAILED) {
19520 			ire_refrele(save_ire);
19521 			return (NULL);
19522 		}
19523 		return (save_ire);
19524 	}
19525 	/*
19526 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19527 	 * If it is part of the group, we need to send on the ire
19528 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19529 	 * to this group. This is okay as IP_BOUND_IF really means
19530 	 * any ill in the group. We depend on the fact that the
19531 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19532 	 * if such an ire exists. This is possible only if you have
19533 	 * at least one ill in the group that has not failed.
19534 	 *
19535 	 * First get to the ire that matches the address and group.
19536 	 *
19537 	 * We don't look for an ire with a matching zoneid because a given zone
19538 	 * won't always have broadcast ires on all ills in the group.
19539 	 */
19540 	irb = ire->ire_bucket;
19541 	rw_enter(&irb->irb_lock, RW_READER);
19542 	if (ire->ire_marks & IRE_MARK_NORECV) {
19543 		/*
19544 		 * If the current zone only has an ire broadcast for this
19545 		 * address marked NORECV, the ire we want is ahead in the
19546 		 * bucket, so we look it up deliberately ignoring the zoneid.
19547 		 */
19548 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19549 			if (ire->ire_addr != addr)
19550 				continue;
19551 			/* skip over deleted ires */
19552 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19553 				continue;
19554 		}
19555 	}
19556 	while (ire != NULL) {
19557 		/*
19558 		 * If a new interface is coming up, we could end up
19559 		 * seeing the loopback ire and the non-loopback ire
19560 		 * may not have been added yet. So check for ire_stq
19561 		 */
19562 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19563 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19564 			break;
19565 		}
19566 		ire = ire->ire_next;
19567 	}
19568 	if (ire != NULL && ire->ire_addr == addr &&
19569 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19570 		IRE_REFHOLD(ire);
19571 		rw_exit(&irb->irb_lock);
19572 		ire_refrele(save_ire);
19573 		*conn_outgoing_ill = ire_to_ill(ire);
19574 		/*
19575 		 * Refhold the ill to make the conn_outgoing_ill
19576 		 * independent of the ire. ip_wput_ire goes in a loop
19577 		 * and may refrele the ire. Since we have an ire at this
19578 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19579 		 */
19580 		ill_refhold(*conn_outgoing_ill);
19581 		return (ire);
19582 	}
19583 	rw_exit(&irb->irb_lock);
19584 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19585 	/*
19586 	 * If we can't find a suitable ire, return the original ire.
19587 	 */
19588 	return (save_ire);
19589 }
19590 
19591 /*
19592  * This function does the ire_refrele of the ire passed in as the
19593  * argument. As this function looks up more ires i.e broadcast ires,
19594  * it needs to REFRELE them. Currently, for simplicity we don't
19595  * differentiate the one passed in and looked up here. We always
19596  * REFRELE.
19597  * IPQoS Notes:
19598  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19599  * IPSec packets are done in ipsec_out_process.
19600  *
19601  */
19602 void
19603 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19604 {
19605 	ipha_t		*ipha;
19606 #define	rptr	((uchar_t *)ipha)
19607 	mblk_t		*mp1;
19608 	queue_t		*stq;
19609 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19610 	uint32_t	v_hlen_tos_len;
19611 	uint32_t	ttl_protocol;
19612 	ipaddr_t	src;
19613 	ipaddr_t	dst;
19614 	uint32_t	cksum;
19615 	ipaddr_t	orig_src;
19616 	ire_t		*ire1;
19617 	mblk_t		*next_mp;
19618 	uint_t		hlen;
19619 	uint16_t	*up;
19620 	uint32_t	max_frag = ire->ire_max_frag;
19621 	ill_t		*ill = ire_to_ill(ire);
19622 	int		clusterwide;
19623 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19624 	int		ipsec_len;
19625 	mblk_t		*first_mp;
19626 	ipsec_out_t	*io;
19627 	boolean_t	conn_dontroute;		/* conn value for multicast */
19628 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19629 	boolean_t	multicast_forward;	/* Should we forward ? */
19630 	boolean_t	unspec_src;
19631 	ill_t		*conn_outgoing_ill = NULL;
19632 	ill_t		*ire_ill;
19633 	ill_t		*ire1_ill;
19634 	uint32_t 	ill_index = 0;
19635 	boolean_t	multirt_send = B_FALSE;
19636 	int		err;
19637 	zoneid_t	zoneid;
19638 
19639 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19640 	    "ip_wput_ire_start: q %p", q);
19641 
19642 	multicast_forward = B_FALSE;
19643 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19644 
19645 	if (ire->ire_flags & RTF_MULTIRT) {
19646 		/*
19647 		 * Multirouting case. The bucket where ire is stored
19648 		 * probably holds other RTF_MULTIRT flagged ire
19649 		 * to the destination. In this call to ip_wput_ire,
19650 		 * we attempt to send the packet through all
19651 		 * those ires. Thus, we first ensure that ire is the
19652 		 * first RTF_MULTIRT ire in the bucket,
19653 		 * before walking the ire list.
19654 		 */
19655 		ire_t *first_ire;
19656 		irb_t *irb = ire->ire_bucket;
19657 		ASSERT(irb != NULL);
19658 
19659 		/* Make sure we do not omit any multiroute ire. */
19660 		IRB_REFHOLD(irb);
19661 		for (first_ire = irb->irb_ire;
19662 		    first_ire != NULL;
19663 		    first_ire = first_ire->ire_next) {
19664 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19665 			    (first_ire->ire_addr == ire->ire_addr) &&
19666 			    !(first_ire->ire_marks &
19667 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19668 				break;
19669 		}
19670 
19671 		if ((first_ire != NULL) && (first_ire != ire)) {
19672 			IRE_REFHOLD(first_ire);
19673 			ire_refrele(ire);
19674 			ire = first_ire;
19675 			ill = ire_to_ill(ire);
19676 		}
19677 		IRB_REFRELE(irb);
19678 	}
19679 
19680 	/*
19681 	 * conn_outgoing_ill is used only in the broadcast loop.
19682 	 * for performance we don't grab the mutexs in the fastpath
19683 	 */
19684 	if ((connp != NULL) &&
19685 	    (connp->conn_xmit_if_ill == NULL) &&
19686 	    (ire->ire_type == IRE_BROADCAST) &&
19687 	    ((connp->conn_nofailover_ill != NULL) ||
19688 	    (connp->conn_outgoing_ill != NULL))) {
19689 		/*
19690 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19691 		 * option. So, see if this endpoint is bound to a
19692 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19693 		 * that if the interface is failed, we will still send
19694 		 * the packet on the same ill which is what we want.
19695 		 */
19696 		conn_outgoing_ill = conn_get_held_ill(connp,
19697 		    &connp->conn_nofailover_ill, &err);
19698 		if (err == ILL_LOOKUP_FAILED) {
19699 			ire_refrele(ire);
19700 			freemsg(mp);
19701 			return;
19702 		}
19703 		if (conn_outgoing_ill == NULL) {
19704 			/*
19705 			 * Choose a good ill in the group to send the
19706 			 * packets on.
19707 			 */
19708 			ire = conn_set_outgoing_ill(connp, ire,
19709 			    &conn_outgoing_ill);
19710 			if (ire == NULL) {
19711 				freemsg(mp);
19712 				return;
19713 			}
19714 		}
19715 	}
19716 
19717 	if (mp->b_datap->db_type != M_CTL) {
19718 		ipha = (ipha_t *)mp->b_rptr;
19719 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19720 	} else {
19721 		io = (ipsec_out_t *)mp->b_rptr;
19722 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19723 		zoneid = io->ipsec_out_zoneid;
19724 		ASSERT(zoneid != ALL_ZONES);
19725 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19726 		dst = ipha->ipha_dst;
19727 		/*
19728 		 * For the multicast case, ipsec_out carries conn_dontroute and
19729 		 * conn_multicast_loop as conn may not be available here. We
19730 		 * need this for multicast loopback and forwarding which is done
19731 		 * later in the code.
19732 		 */
19733 		if (CLASSD(dst)) {
19734 			conn_dontroute = io->ipsec_out_dontroute;
19735 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19736 			/*
19737 			 * If conn_dontroute is not set or conn_multicast_loop
19738 			 * is set, we need to do forwarding/loopback. For
19739 			 * datagrams from ip_wput_multicast, conn_dontroute is
19740 			 * set to B_TRUE and conn_multicast_loop is set to
19741 			 * B_FALSE so that we neither do forwarding nor
19742 			 * loopback.
19743 			 */
19744 			if (!conn_dontroute || conn_multicast_loop)
19745 				multicast_forward = B_TRUE;
19746 		}
19747 	}
19748 
19749 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19750 		/*
19751 		 * When a zone sends a packet to another zone, we try to deliver
19752 		 * the packet under the same conditions as if the destination
19753 		 * was a real node on the network. To do so, we look for a
19754 		 * matching route in the forwarding table.
19755 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19756 		 * ip_newroute() does.
19757 		 */
19758 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19759 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19760 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19761 		if (src_ire != NULL &&
19762 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19763 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19764 				ipha->ipha_src = src_ire->ire_src_addr;
19765 			ire_refrele(src_ire);
19766 		} else {
19767 			ire_refrele(ire);
19768 			if (conn_outgoing_ill != NULL)
19769 				ill_refrele(conn_outgoing_ill);
19770 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19771 			if (src_ire != NULL) {
19772 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19773 					ire_refrele(src_ire);
19774 					freemsg(mp);
19775 					return;
19776 				}
19777 				ire_refrele(src_ire);
19778 			}
19779 			if (ip_hdr_complete(ipha, zoneid)) {
19780 				/* Failed */
19781 				freemsg(mp);
19782 				return;
19783 			}
19784 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19785 			return;
19786 		}
19787 	}
19788 
19789 	if (mp->b_datap->db_type == M_CTL ||
19790 	    ipsec_outbound_v4_policy_present) {
19791 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19792 		    unspec_src);
19793 		if (mp == NULL) {
19794 			ire_refrele(ire);
19795 			if (conn_outgoing_ill != NULL)
19796 				ill_refrele(conn_outgoing_ill);
19797 			return;
19798 		}
19799 	}
19800 
19801 	first_mp = mp;
19802 	ipsec_len = 0;
19803 
19804 	if (first_mp->b_datap->db_type == M_CTL) {
19805 		io = (ipsec_out_t *)first_mp->b_rptr;
19806 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19807 		mp = first_mp->b_cont;
19808 		ipsec_len = ipsec_out_extra_length(first_mp);
19809 		ASSERT(ipsec_len >= 0);
19810 		zoneid = io->ipsec_out_zoneid;
19811 		ASSERT(zoneid != ALL_ZONES);
19812 
19813 		/*
19814 		 * Drop M_CTL here if IPsec processing is not needed.
19815 		 * (Non-IPsec use of M_CTL extracted any information it
19816 		 * needed above).
19817 		 */
19818 		if (ipsec_len == 0) {
19819 			freeb(first_mp);
19820 			first_mp = mp;
19821 		}
19822 	}
19823 
19824 	/*
19825 	 * Fast path for ip_wput_ire
19826 	 */
19827 
19828 	ipha = (ipha_t *)mp->b_rptr;
19829 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19830 	dst = ipha->ipha_dst;
19831 
19832 	/*
19833 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19834 	 * if the socket is a SOCK_RAW type. The transport checksum should
19835 	 * be provided in the pre-built packet, so we don't need to compute it.
19836 	 * Also, other application set flags, like DF, should not be altered.
19837 	 * Other transport MUST pass down zero.
19838 	 */
19839 	ip_hdr_included = ipha->ipha_ident;
19840 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19841 
19842 	if (CLASSD(dst)) {
19843 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19844 		    ntohl(dst),
19845 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19846 		    ntohl(ire->ire_addr)));
19847 	}
19848 
19849 /* Macros to extract header fields from data already in registers */
19850 #ifdef	_BIG_ENDIAN
19851 #define	V_HLEN	(v_hlen_tos_len >> 24)
19852 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19853 #define	PROTO	(ttl_protocol & 0xFF)
19854 #else
19855 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19856 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19857 #define	PROTO	(ttl_protocol >> 8)
19858 #endif
19859 
19860 
19861 	orig_src = src = ipha->ipha_src;
19862 	/* (The loop back to "another" is explained down below.) */
19863 another:;
19864 	/*
19865 	 * Assign an ident value for this packet.  We assign idents on
19866 	 * a per destination basis out of the IRE.  There could be
19867 	 * other threads targeting the same destination, so we have to
19868 	 * arrange for a atomic increment.  Note that we use a 32-bit
19869 	 * atomic add because it has better performance than its
19870 	 * 16-bit sibling.
19871 	 *
19872 	 * If running in cluster mode and if the source address
19873 	 * belongs to a replicated service then vector through
19874 	 * cl_inet_ipident vector to allocate ip identifier
19875 	 * NOTE: This is a contract private interface with the
19876 	 * clustering group.
19877 	 */
19878 	clusterwide = 0;
19879 	if (cl_inet_ipident) {
19880 		ASSERT(cl_inet_isclusterwide);
19881 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19882 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19883 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19884 			    AF_INET, (uint8_t *)(uintptr_t)src,
19885 			    (uint8_t *)(uintptr_t)dst);
19886 			clusterwide = 1;
19887 		}
19888 	}
19889 	if (!clusterwide) {
19890 		ipha->ipha_ident =
19891 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19892 	}
19893 
19894 #ifndef _BIG_ENDIAN
19895 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19896 #endif
19897 
19898 	/*
19899 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19900 	 * This is needed to obey conn_unspec_src when packets go through
19901 	 * ip_newroute + arp.
19902 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19903 	 */
19904 	if (src == INADDR_ANY && !unspec_src) {
19905 		/*
19906 		 * Assign the appropriate source address from the IRE if none
19907 		 * was specified.
19908 		 */
19909 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19910 
19911 		/*
19912 		 * With IP multipathing, broadcast packets are sent on the ire
19913 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19914 		 * the group. However, this ire might not be in the same zone so
19915 		 * we can't always use its source address. We look for a
19916 		 * broadcast ire in the same group and in the right zone.
19917 		 */
19918 		if (ire->ire_type == IRE_BROADCAST &&
19919 		    ire->ire_zoneid != zoneid) {
19920 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19921 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19922 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19923 			if (src_ire != NULL) {
19924 				src = src_ire->ire_src_addr;
19925 				ire_refrele(src_ire);
19926 			} else {
19927 				ire_refrele(ire);
19928 				if (conn_outgoing_ill != NULL)
19929 					ill_refrele(conn_outgoing_ill);
19930 				freemsg(first_mp);
19931 				BUMP_MIB(&ip_mib, ipOutDiscards);
19932 				return;
19933 			}
19934 		} else {
19935 			src = ire->ire_src_addr;
19936 		}
19937 
19938 		if (connp == NULL) {
19939 			ip1dbg(("ip_wput_ire: no connp and no src "
19940 			    "address for dst 0x%x, using src 0x%x\n",
19941 			    ntohl(dst),
19942 			    ntohl(src)));
19943 		}
19944 		ipha->ipha_src = src;
19945 	}
19946 	stq = ire->ire_stq;
19947 
19948 	/*
19949 	 * We only allow ire chains for broadcasts since there will
19950 	 * be multiple IRE_CACHE entries for the same multicast
19951 	 * address (one per ipif).
19952 	 */
19953 	next_mp = NULL;
19954 
19955 	/* broadcast packet */
19956 	if (ire->ire_type == IRE_BROADCAST)
19957 		goto broadcast;
19958 
19959 	/* loopback ? */
19960 	if (stq == NULL)
19961 		goto nullstq;
19962 
19963 	/* The ill_index for outbound ILL */
19964 	ill_index = Q_TO_INDEX(stq);
19965 
19966 	BUMP_MIB(&ip_mib, ipOutRequests);
19967 	ttl_protocol = ((uint16_t *)ipha)[4];
19968 
19969 	/* pseudo checksum (do it in parts for IP header checksum) */
19970 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19971 
19972 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
19973 		queue_t *dev_q = stq->q_next;
19974 
19975 		/* flow controlled */
19976 		if ((dev_q->q_next || dev_q->q_first) &&
19977 		    !canput(dev_q))
19978 			goto blocked;
19979 		if ((PROTO == IPPROTO_UDP) &&
19980 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
19981 			hlen = (V_HLEN & 0xF) << 2;
19982 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
19983 			if (*up != 0) {
19984 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
19985 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
19986 				/* Software checksum? */
19987 				if (DB_CKSUMFLAGS(mp) == 0) {
19988 					IP_STAT(ip_out_sw_cksum);
19989 					IP_STAT_UPDATE(
19990 					    ip_udp_out_sw_cksum_bytes,
19991 					    LENGTH - hlen);
19992 				}
19993 			}
19994 		}
19995 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
19996 		hlen = (V_HLEN & 0xF) << 2;
19997 		if (PROTO == IPPROTO_TCP) {
19998 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
19999 			/*
20000 			 * The packet header is processed once and for all, even
20001 			 * in the multirouting case. We disable hardware
20002 			 * checksum if the packet is multirouted, as it will be
20003 			 * replicated via several interfaces, and not all of
20004 			 * them may have this capability.
20005 			 */
20006 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20007 			    LENGTH, max_frag, ipsec_len, cksum);
20008 			/* Software checksum? */
20009 			if (DB_CKSUMFLAGS(mp) == 0) {
20010 				IP_STAT(ip_out_sw_cksum);
20011 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20012 				    LENGTH - hlen);
20013 			}
20014 		} else {
20015 			sctp_hdr_t	*sctph;
20016 
20017 			ASSERT(PROTO == IPPROTO_SCTP);
20018 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20019 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20020 			/*
20021 			 * Zero out the checksum field to ensure proper
20022 			 * checksum calculation.
20023 			 */
20024 			sctph->sh_chksum = 0;
20025 #ifdef	DEBUG
20026 			if (!skip_sctp_cksum)
20027 #endif
20028 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20029 		}
20030 	}
20031 
20032 	/*
20033 	 * If this is a multicast packet and originated from ip_wput
20034 	 * we need to do loopback and forwarding checks. If it comes
20035 	 * from ip_wput_multicast, we SHOULD not do this.
20036 	 */
20037 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20038 
20039 	/* checksum */
20040 	cksum += ttl_protocol;
20041 
20042 	/* fragment the packet */
20043 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20044 		goto fragmentit;
20045 	/*
20046 	 * Don't use frag_flag if packet is pre-built or source
20047 	 * routed or if multicast (since multicast packets do
20048 	 * not solicit ICMP "packet too big" messages).
20049 	 */
20050 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20051 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20052 	    !ip_source_route_included(ipha)) &&
20053 	    !CLASSD(ipha->ipha_dst))
20054 		ipha->ipha_fragment_offset_and_flags |=
20055 		    htons(ire->ire_frag_flag);
20056 
20057 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20058 		/* calculate IP header checksum */
20059 		cksum += ipha->ipha_ident;
20060 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20061 		cksum += ipha->ipha_fragment_offset_and_flags;
20062 
20063 		/* IP options present */
20064 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20065 		if (hlen)
20066 			goto checksumoptions;
20067 
20068 		/* calculate hdr checksum */
20069 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20070 		cksum = ~(cksum + (cksum >> 16));
20071 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20072 	}
20073 	if (ipsec_len != 0) {
20074 		/*
20075 		 * We will do the rest of the processing after
20076 		 * we come back from IPSEC in ip_wput_ipsec_out().
20077 		 */
20078 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20079 
20080 		io = (ipsec_out_t *)first_mp->b_rptr;
20081 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20082 				ill_phyint->phyint_ifindex;
20083 
20084 		ipsec_out_process(q, first_mp, ire, ill_index);
20085 		ire_refrele(ire);
20086 		if (conn_outgoing_ill != NULL)
20087 			ill_refrele(conn_outgoing_ill);
20088 		return;
20089 	}
20090 
20091 	/*
20092 	 * In most cases, the emission loop below is entered only
20093 	 * once. Only in the case where the ire holds the
20094 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20095 	 * flagged ires in the bucket, and send the packet
20096 	 * through all crossed RTF_MULTIRT routes.
20097 	 */
20098 	if (ire->ire_flags & RTF_MULTIRT) {
20099 		multirt_send = B_TRUE;
20100 	}
20101 	do {
20102 		if (multirt_send) {
20103 			irb_t *irb;
20104 			/*
20105 			 * We are in a multiple send case, need to get
20106 			 * the next ire and make a duplicate of the packet.
20107 			 * ire1 holds here the next ire to process in the
20108 			 * bucket. If multirouting is expected,
20109 			 * any non-RTF_MULTIRT ire that has the
20110 			 * right destination address is ignored.
20111 			 */
20112 			irb = ire->ire_bucket;
20113 			ASSERT(irb != NULL);
20114 
20115 			IRB_REFHOLD(irb);
20116 			for (ire1 = ire->ire_next;
20117 			    ire1 != NULL;
20118 			    ire1 = ire1->ire_next) {
20119 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20120 					continue;
20121 				if (ire1->ire_addr != ire->ire_addr)
20122 					continue;
20123 				if (ire1->ire_marks &
20124 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20125 					continue;
20126 
20127 				/* Got one */
20128 				IRE_REFHOLD(ire1);
20129 				break;
20130 			}
20131 			IRB_REFRELE(irb);
20132 
20133 			if (ire1 != NULL) {
20134 				next_mp = copyb(mp);
20135 				if ((next_mp == NULL) ||
20136 				    ((mp->b_cont != NULL) &&
20137 				    ((next_mp->b_cont =
20138 				    dupmsg(mp->b_cont)) == NULL))) {
20139 					freemsg(next_mp);
20140 					next_mp = NULL;
20141 					ire_refrele(ire1);
20142 					ire1 = NULL;
20143 				}
20144 			}
20145 
20146 			/* Last multiroute ire; don't loop anymore. */
20147 			if (ire1 == NULL) {
20148 				multirt_send = B_FALSE;
20149 			}
20150 		}
20151 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20152 		if (mp == NULL) {
20153 			BUMP_MIB(&ip_mib, ipOutDiscards);
20154 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20155 			    "during IPPF processing\n"));
20156 			ire_refrele(ire);
20157 			if (next_mp != NULL) {
20158 				freemsg(next_mp);
20159 				ire_refrele(ire1);
20160 			}
20161 			if (conn_outgoing_ill != NULL)
20162 				ill_refrele(conn_outgoing_ill);
20163 			return;
20164 		}
20165 		UPDATE_OB_PKT_COUNT(ire);
20166 		ire->ire_last_used_time = lbolt;
20167 
20168 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20169 		    "ip_wput_ire_end: q %p (%S)",
20170 		    q, "last copy out");
20171 		putnext(stq, mp);
20172 		IRE_REFRELE(ire);
20173 
20174 		if (multirt_send) {
20175 			ASSERT(ire1);
20176 			/*
20177 			 * Proceed with the next RTF_MULTIRT ire,
20178 			 * Also set up the send-to queue accordingly.
20179 			 */
20180 			ire = ire1;
20181 			ire1 = NULL;
20182 			stq = ire->ire_stq;
20183 			mp = next_mp;
20184 			next_mp = NULL;
20185 			ipha = (ipha_t *)mp->b_rptr;
20186 			ill_index = Q_TO_INDEX(stq);
20187 		}
20188 	} while (multirt_send);
20189 	if (conn_outgoing_ill != NULL)
20190 		ill_refrele(conn_outgoing_ill);
20191 	return;
20192 
20193 	/*
20194 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20195 	 */
20196 broadcast:
20197 	{
20198 		/*
20199 		 * Avoid broadcast storms by setting the ttl to 1
20200 		 * for broadcasts. This parameter can be set
20201 		 * via ndd, so make sure that for the SO_DONTROUTE
20202 		 * case that ipha_ttl is always set to 1.
20203 		 * In the event that we are replying to incoming
20204 		 * ICMP packets, conn could be NULL.
20205 		 */
20206 		if ((connp != NULL) && connp->conn_dontroute)
20207 			ipha->ipha_ttl = 1;
20208 		else
20209 			ipha->ipha_ttl = ip_broadcast_ttl;
20210 
20211 		/*
20212 		 * Note that we are not doing a IRB_REFHOLD here.
20213 		 * Actually we don't care if the list changes i.e
20214 		 * if somebody deletes an IRE from the list while
20215 		 * we drop the lock, the next time we come around
20216 		 * ire_next will be NULL and hence we won't send
20217 		 * out multiple copies which is fine.
20218 		 */
20219 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20220 		ire1 = ire->ire_next;
20221 		if (conn_outgoing_ill != NULL) {
20222 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20223 				ASSERT(ire1 == ire->ire_next);
20224 				if (ire1 != NULL && ire1->ire_addr == dst) {
20225 					ire_refrele(ire);
20226 					ire = ire1;
20227 					IRE_REFHOLD(ire);
20228 					ire1 = ire->ire_next;
20229 					continue;
20230 				}
20231 				rw_exit(&ire->ire_bucket->irb_lock);
20232 				/* Did not find a matching ill */
20233 				ip1dbg(("ip_wput_ire: broadcast with no "
20234 				    "matching IP_BOUND_IF ill %s\n",
20235 				    conn_outgoing_ill->ill_name));
20236 				freemsg(first_mp);
20237 				if (ire != NULL)
20238 					ire_refrele(ire);
20239 				ill_refrele(conn_outgoing_ill);
20240 				return;
20241 			}
20242 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20243 			/*
20244 			 * If the next IRE has the same address and is not one
20245 			 * of the two copies that we need to send, try to see
20246 			 * whether this copy should be sent at all. This
20247 			 * assumes that we insert loopbacks first and then
20248 			 * non-loopbacks. This is acheived by inserting the
20249 			 * loopback always before non-loopback.
20250 			 * This is used to send a single copy of a broadcast
20251 			 * packet out all physical interfaces that have an
20252 			 * matching IRE_BROADCAST while also looping
20253 			 * back one copy (to ip_wput_local) for each
20254 			 * matching physical interface. However, we avoid
20255 			 * sending packets out different logical that match by
20256 			 * having ipif_up/ipif_down supress duplicate
20257 			 * IRE_BROADCASTS.
20258 			 *
20259 			 * This feature is currently used to get broadcasts
20260 			 * sent to multiple interfaces, when the broadcast
20261 			 * address being used applies to multiple interfaces.
20262 			 * For example, a whole net broadcast will be
20263 			 * replicated on every connected subnet of
20264 			 * the target net.
20265 			 *
20266 			 * Each zone has its own set of IRE_BROADCASTs, so that
20267 			 * we're able to distribute inbound packets to multiple
20268 			 * zones who share a broadcast address. We avoid looping
20269 			 * back outbound packets in different zones but on the
20270 			 * same ill, as the application would see duplicates.
20271 			 *
20272 			 * If the interfaces are part of the same group,
20273 			 * we would want to send only one copy out for
20274 			 * whole group.
20275 			 *
20276 			 * This logic assumes that ire_add_v4() groups the
20277 			 * IRE_BROADCAST entries so that those with the same
20278 			 * ire_addr and ill_group are kept together.
20279 			 */
20280 			ire_ill = ire->ire_ipif->ipif_ill;
20281 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20282 				if (ire_ill->ill_group != NULL &&
20283 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20284 					/*
20285 					 * If the current zone only has an ire
20286 					 * broadcast for this address marked
20287 					 * NORECV, the ire we want is ahead in
20288 					 * the bucket, so we look it up
20289 					 * deliberately ignoring the zoneid.
20290 					 */
20291 					for (ire1 = ire->ire_bucket->irb_ire;
20292 					    ire1 != NULL;
20293 					    ire1 = ire1->ire_next) {
20294 						ire1_ill =
20295 						    ire1->ire_ipif->ipif_ill;
20296 						if (ire1->ire_addr != dst)
20297 							continue;
20298 						/* skip over the current ire */
20299 						if (ire1 == ire)
20300 							continue;
20301 						/* skip over deleted ires */
20302 						if (ire1->ire_marks &
20303 						    IRE_MARK_CONDEMNED)
20304 							continue;
20305 						/*
20306 						 * non-loopback ire in our
20307 						 * group: use it for the next
20308 						 * pass in the loop
20309 						 */
20310 						if (ire1->ire_stq != NULL &&
20311 						    ire1_ill->ill_group ==
20312 						    ire_ill->ill_group)
20313 							break;
20314 					}
20315 				}
20316 			} else {
20317 				while (ire1 != NULL && ire1->ire_addr == dst) {
20318 					ire1_ill = ire1->ire_ipif->ipif_ill;
20319 					/*
20320 					 * We can have two broadcast ires on the
20321 					 * same ill in different zones; here
20322 					 * we'll send a copy of the packet on
20323 					 * each ill and the fanout code will
20324 					 * call conn_wantpacket() to check that
20325 					 * the zone has the broadcast address
20326 					 * configured on the ill. If the two
20327 					 * ires are in the same group we only
20328 					 * send one copy up.
20329 					 */
20330 					if (ire1_ill != ire_ill &&
20331 					    (ire1_ill->ill_group == NULL ||
20332 					    ire_ill->ill_group == NULL ||
20333 					    ire1_ill->ill_group !=
20334 					    ire_ill->ill_group)) {
20335 						break;
20336 					}
20337 					ire1 = ire1->ire_next;
20338 				}
20339 			}
20340 		}
20341 		ASSERT(multirt_send == B_FALSE);
20342 		if (ire1 != NULL && ire1->ire_addr == dst) {
20343 			if ((ire->ire_flags & RTF_MULTIRT) &&
20344 			    (ire1->ire_flags & RTF_MULTIRT)) {
20345 				/*
20346 				 * We are in the multirouting case.
20347 				 * The message must be sent at least
20348 				 * on both ires. These ires have been
20349 				 * inserted AFTER the standard ones
20350 				 * in ip_rt_add(). There are thus no
20351 				 * other ire entries for the destination
20352 				 * address in the rest of the bucket
20353 				 * that do not have the RTF_MULTIRT
20354 				 * flag. We don't process a copy
20355 				 * of the message here. This will be
20356 				 * done in the final sending loop.
20357 				 */
20358 				multirt_send = B_TRUE;
20359 			} else {
20360 				next_mp = ip_copymsg(first_mp);
20361 				if (next_mp != NULL)
20362 					IRE_REFHOLD(ire1);
20363 			}
20364 		}
20365 		rw_exit(&ire->ire_bucket->irb_lock);
20366 	}
20367 
20368 	if (stq) {
20369 		/*
20370 		 * A non-NULL send-to queue means this packet is going
20371 		 * out of this machine.
20372 		 */
20373 
20374 		BUMP_MIB(&ip_mib, ipOutRequests);
20375 		ttl_protocol = ((uint16_t *)ipha)[4];
20376 		/*
20377 		 * We accumulate the pseudo header checksum in cksum.
20378 		 * This is pretty hairy code, so watch close.  One
20379 		 * thing to keep in mind is that UDP and TCP have
20380 		 * stored their respective datagram lengths in their
20381 		 * checksum fields.  This lines things up real nice.
20382 		 */
20383 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20384 		    (src >> 16) + (src & 0xFFFF);
20385 		/*
20386 		 * We assume the udp checksum field contains the
20387 		 * length, so to compute the pseudo header checksum,
20388 		 * all we need is the protocol number and src/dst.
20389 		 */
20390 		/* Provide the checksums for UDP and TCP. */
20391 		if ((PROTO == IPPROTO_TCP) &&
20392 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20393 			/* hlen gets the number of uchar_ts in the IP header */
20394 			hlen = (V_HLEN & 0xF) << 2;
20395 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20396 			IP_STAT(ip_out_sw_cksum);
20397 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20398 			    LENGTH - hlen);
20399 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20400 			if (*up == 0)
20401 				*up = 0xFFFF;
20402 		} else if (PROTO == IPPROTO_SCTP &&
20403 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20404 			sctp_hdr_t	*sctph;
20405 
20406 			hlen = (V_HLEN & 0xF) << 2;
20407 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20408 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20409 			sctph->sh_chksum = 0;
20410 #ifdef	DEBUG
20411 			if (!skip_sctp_cksum)
20412 #endif
20413 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20414 		} else {
20415 			queue_t *dev_q = stq->q_next;
20416 
20417 			if ((dev_q->q_next || dev_q->q_first) &&
20418 			    !canput(dev_q)) {
20419 			    blocked:
20420 				ipha->ipha_ident = ip_hdr_included;
20421 				/*
20422 				 * If we don't have a conn to apply
20423 				 * backpressure, free the message.
20424 				 * In the ire_send path, we don't know
20425 				 * the position to requeue the packet. Rather
20426 				 * than reorder packets, we just drop this
20427 				 * packet.
20428 				 */
20429 				if (ip_output_queue && connp != NULL &&
20430 				    caller != IRE_SEND) {
20431 					if (caller == IP_WSRV) {
20432 						connp->conn_did_putbq = 1;
20433 						(void) putbq(connp->conn_wq,
20434 						    first_mp);
20435 						conn_drain_insert(connp);
20436 						/*
20437 						 * This is the service thread,
20438 						 * and the queue is already
20439 						 * noenabled. The check for
20440 						 * canput and the putbq is not
20441 						 * atomic. So we need to check
20442 						 * again.
20443 						 */
20444 						if (canput(stq->q_next))
20445 							connp->conn_did_putbq
20446 							    = 0;
20447 						IP_STAT(ip_conn_flputbq);
20448 					} else {
20449 						/*
20450 						 * We are not the service proc.
20451 						 * ip_wsrv will be scheduled or
20452 						 * is already running.
20453 						 */
20454 						(void) putq(connp->conn_wq,
20455 						    first_mp);
20456 					}
20457 				} else {
20458 					BUMP_MIB(&ip_mib, ipOutDiscards);
20459 					freemsg(first_mp);
20460 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20461 					    "ip_wput_ire_end: q %p (%S)",
20462 					    q, "discard");
20463 				}
20464 				ire_refrele(ire);
20465 				if (next_mp) {
20466 					ire_refrele(ire1);
20467 					freemsg(next_mp);
20468 				}
20469 				if (conn_outgoing_ill != NULL)
20470 					ill_refrele(conn_outgoing_ill);
20471 				return;
20472 			}
20473 			if ((PROTO == IPPROTO_UDP) &&
20474 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20475 				/*
20476 				 * hlen gets the number of uchar_ts in the
20477 				 * IP header
20478 				 */
20479 				hlen = (V_HLEN & 0xF) << 2;
20480 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20481 				max_frag = ire->ire_max_frag;
20482 				if (*up != 0) {
20483 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
20484 					    up, PROTO, hlen, LENGTH, max_frag,
20485 					    ipsec_len, cksum);
20486 					/* Software checksum? */
20487 					if (DB_CKSUMFLAGS(mp) == 0) {
20488 						IP_STAT(ip_out_sw_cksum);
20489 						IP_STAT_UPDATE(
20490 						    ip_udp_out_sw_cksum_bytes,
20491 						    LENGTH - hlen);
20492 					}
20493 				}
20494 			}
20495 		}
20496 		/*
20497 		 * Need to do this even when fragmenting. The local
20498 		 * loopback can be done without computing checksums
20499 		 * but forwarding out other interface must be done
20500 		 * after the IP checksum (and ULP checksums) have been
20501 		 * computed.
20502 		 *
20503 		 * NOTE : multicast_forward is set only if this packet
20504 		 * originated from ip_wput. For packets originating from
20505 		 * ip_wput_multicast, it is not set.
20506 		 */
20507 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20508 		    multi_loopback:
20509 			ip2dbg(("ip_wput: multicast, loop %d\n",
20510 			    conn_multicast_loop));
20511 
20512 			/*  Forget header checksum offload */
20513 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
20514 
20515 			/*
20516 			 * Local loopback of multicasts?  Check the
20517 			 * ill.
20518 			 *
20519 			 * Note that the loopback function will not come
20520 			 * in through ip_rput - it will only do the
20521 			 * client fanout thus we need to do an mforward
20522 			 * as well.  The is different from the BSD
20523 			 * logic.
20524 			 */
20525 			if (ill != NULL) {
20526 				ilm_t	*ilm;
20527 
20528 				ILM_WALKER_HOLD(ill);
20529 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20530 				    ALL_ZONES);
20531 				ILM_WALKER_RELE(ill);
20532 				if (ilm != NULL) {
20533 					/*
20534 					 * Pass along the virtual output q.
20535 					 * ip_wput_local() will distribute the
20536 					 * packet to all the matching zones,
20537 					 * except the sending zone when
20538 					 * IP_MULTICAST_LOOP is false.
20539 					 */
20540 					ip_multicast_loopback(q, ill, first_mp,
20541 					    conn_multicast_loop ? 0 :
20542 					    IP_FF_NO_MCAST_LOOP, zoneid);
20543 				}
20544 			}
20545 			if (ipha->ipha_ttl == 0) {
20546 				/*
20547 				 * 0 => only to this host i.e. we are
20548 				 * done. We are also done if this was the
20549 				 * loopback interface since it is sufficient
20550 				 * to loopback one copy of a multicast packet.
20551 				 */
20552 				freemsg(first_mp);
20553 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20554 				    "ip_wput_ire_end: q %p (%S)",
20555 				    q, "loopback");
20556 				ire_refrele(ire);
20557 				if (conn_outgoing_ill != NULL)
20558 					ill_refrele(conn_outgoing_ill);
20559 				return;
20560 			}
20561 			/*
20562 			 * ILLF_MULTICAST is checked in ip_newroute
20563 			 * i.e. we don't need to check it here since
20564 			 * all IRE_CACHEs come from ip_newroute.
20565 			 * For multicast traffic, SO_DONTROUTE is interpreted
20566 			 * to mean only send the packet out the interface
20567 			 * (optionally specified with IP_MULTICAST_IF)
20568 			 * and do not forward it out additional interfaces.
20569 			 * RSVP and the rsvp daemon is an example of a
20570 			 * protocol and user level process that
20571 			 * handles it's own routing. Hence, it uses the
20572 			 * SO_DONTROUTE option to accomplish this.
20573 			 */
20574 
20575 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20576 				/* Unconditionally redo the checksum */
20577 				ipha->ipha_hdr_checksum = 0;
20578 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20579 
20580 				/*
20581 				 * If this needs to go out secure, we need
20582 				 * to wait till we finish the IPSEC
20583 				 * processing.
20584 				 */
20585 				if (ipsec_len == 0 &&
20586 				    ip_mforward(ill, ipha, mp)) {
20587 					freemsg(first_mp);
20588 					ip1dbg(("ip_wput: mforward failed\n"));
20589 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20590 					    "ip_wput_ire_end: q %p (%S)",
20591 					    q, "mforward failed");
20592 					ire_refrele(ire);
20593 					if (conn_outgoing_ill != NULL)
20594 						ill_refrele(conn_outgoing_ill);
20595 					return;
20596 				}
20597 			}
20598 		}
20599 		max_frag = ire->ire_max_frag;
20600 		cksum += ttl_protocol;
20601 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
20602 			/* No fragmentation required for this one. */
20603 			/*
20604 			 * Don't use frag_flag if packet is pre-built or source
20605 			 * routed or if multicast (since multicast packets do
20606 			 * not solicit ICMP "packet too big" messages).
20607 			 */
20608 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20609 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20610 			    !ip_source_route_included(ipha)) &&
20611 			    !CLASSD(ipha->ipha_dst))
20612 				ipha->ipha_fragment_offset_and_flags |=
20613 				    htons(ire->ire_frag_flag);
20614 
20615 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20616 				/* Complete the IP header checksum. */
20617 				cksum += ipha->ipha_ident;
20618 				cksum += (v_hlen_tos_len >> 16)+
20619 				    (v_hlen_tos_len & 0xFFFF);
20620 				cksum += ipha->ipha_fragment_offset_and_flags;
20621 				hlen = (V_HLEN & 0xF) -
20622 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20623 				if (hlen) {
20624 				    checksumoptions:
20625 					/*
20626 					 * Account for the IP Options in the IP
20627 					 * header checksum.
20628 					 */
20629 					up = (uint16_t *)(rptr+
20630 					    IP_SIMPLE_HDR_LENGTH);
20631 					do {
20632 						cksum += up[0];
20633 						cksum += up[1];
20634 						up += 2;
20635 					} while (--hlen);
20636 				}
20637 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20638 				cksum = ~(cksum + (cksum >> 16));
20639 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
20640 			}
20641 			if (ipsec_len != 0) {
20642 				ipsec_out_process(q, first_mp, ire, ill_index);
20643 				if (!next_mp) {
20644 					ire_refrele(ire);
20645 					if (conn_outgoing_ill != NULL)
20646 						ill_refrele(conn_outgoing_ill);
20647 					return;
20648 				}
20649 				goto next;
20650 			}
20651 
20652 			/*
20653 			 * multirt_send has already been handled
20654 			 * for broadcast, but not yet for multicast
20655 			 * or IP options.
20656 			 */
20657 			if (next_mp == NULL) {
20658 				if (ire->ire_flags & RTF_MULTIRT) {
20659 					multirt_send = B_TRUE;
20660 				}
20661 			}
20662 
20663 			/*
20664 			 * In most cases, the emission loop below is
20665 			 * entered only once. Only in the case where
20666 			 * the ire holds the RTF_MULTIRT flag, do we loop
20667 			 * to process all RTF_MULTIRT ires in the bucket,
20668 			 * and send the packet through all crossed
20669 			 * RTF_MULTIRT routes.
20670 			 */
20671 			do {
20672 				if (multirt_send) {
20673 					irb_t *irb;
20674 
20675 					irb = ire->ire_bucket;
20676 					ASSERT(irb != NULL);
20677 					/*
20678 					 * We are in a multiple send case,
20679 					 * need to get the next IRE and make
20680 					 * a duplicate of the packet.
20681 					 */
20682 					IRB_REFHOLD(irb);
20683 					for (ire1 = ire->ire_next;
20684 					    ire1 != NULL;
20685 					    ire1 = ire1->ire_next) {
20686 						if (!(ire1->ire_flags &
20687 						    RTF_MULTIRT))
20688 							continue;
20689 						if (ire1->ire_addr !=
20690 						    ire->ire_addr)
20691 							continue;
20692 						if (ire1->ire_marks &
20693 						    (IRE_MARK_CONDEMNED|
20694 							IRE_MARK_HIDDEN))
20695 							continue;
20696 
20697 						/* Got one */
20698 						IRE_REFHOLD(ire1);
20699 						break;
20700 					}
20701 					IRB_REFRELE(irb);
20702 
20703 					if (ire1 != NULL) {
20704 						next_mp = copyb(mp);
20705 						if ((next_mp == NULL) ||
20706 						    ((mp->b_cont != NULL) &&
20707 						    ((next_mp->b_cont =
20708 						    dupmsg(mp->b_cont))
20709 						    == NULL))) {
20710 							freemsg(next_mp);
20711 							next_mp = NULL;
20712 							ire_refrele(ire1);
20713 							ire1 = NULL;
20714 						}
20715 					}
20716 
20717 					/*
20718 					 * Last multiroute ire; don't loop
20719 					 * anymore. The emission is over
20720 					 * and next_mp is NULL.
20721 					 */
20722 					if (ire1 == NULL) {
20723 						multirt_send = B_FALSE;
20724 					}
20725 				}
20726 
20727 			noprepend:
20728 				ASSERT(ipsec_len == 0);
20729 				mp1 = ip_wput_attach_llhdr(mp, ire,
20730 				    IPP_LOCAL_OUT, ill_index);
20731 				if (mp1 == NULL) {
20732 					BUMP_MIB(&ip_mib, ipOutDiscards);
20733 					if (next_mp) {
20734 						freemsg(next_mp);
20735 						ire_refrele(ire1);
20736 					}
20737 					ire_refrele(ire);
20738 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20739 					    "ip_wput_ire_end: q %p (%S)",
20740 					    q, "discard MDATA");
20741 					if (conn_outgoing_ill != NULL)
20742 						ill_refrele(conn_outgoing_ill);
20743 					return;
20744 				}
20745 				UPDATE_OB_PKT_COUNT(ire);
20746 				ire->ire_last_used_time = lbolt;
20747 
20748 				if (multirt_send) {
20749 					/*
20750 					 * We are in a multiple send case,
20751 					 * need to re-enter the sending loop
20752 					 * using the next ire.
20753 					 */
20754 					putnext(stq, mp1);
20755 					ire_refrele(ire);
20756 					ire = ire1;
20757 					stq = ire->ire_stq;
20758 					mp = next_mp;
20759 					next_mp = NULL;
20760 					ipha = (ipha_t *)mp->b_rptr;
20761 					ill_index = Q_TO_INDEX(stq);
20762 				}
20763 			} while (multirt_send);
20764 
20765 			if (!next_mp) {
20766 				/*
20767 				 * Last copy going out (the ultra-common
20768 				 * case).  Note that we intentionally replicate
20769 				 * the putnext rather than calling it before
20770 				 * the next_mp check in hopes of a little
20771 				 * tail-call action out of the compiler.
20772 				 */
20773 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20774 				    "ip_wput_ire_end: q %p (%S)",
20775 				    q, "last copy out(1)");
20776 				putnext(stq, mp1);
20777 				ire_refrele(ire);
20778 				if (conn_outgoing_ill != NULL)
20779 					ill_refrele(conn_outgoing_ill);
20780 				return;
20781 			}
20782 			/* More copies going out below. */
20783 			putnext(stq, mp1);
20784 		} else {
20785 			int offset;
20786 		    fragmentit:
20787 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20788 			/*
20789 			 * If this would generate a icmp_frag_needed message,
20790 			 * we need to handle it before we do the IPSEC
20791 			 * processing. Otherwise, we need to strip the IPSEC
20792 			 * headers before we send up the message to the ULPs
20793 			 * which becomes messy and difficult.
20794 			 */
20795 			if (ipsec_len != 0) {
20796 				if ((max_frag < (unsigned int)(LENGTH +
20797 				    ipsec_len)) && (offset & IPH_DF)) {
20798 
20799 					BUMP_MIB(&ip_mib, ipFragFails);
20800 					ipha->ipha_hdr_checksum = 0;
20801 					ipha->ipha_hdr_checksum =
20802 					    (uint16_t)ip_csum_hdr(ipha);
20803 					icmp_frag_needed(ire->ire_stq, first_mp,
20804 					    max_frag);
20805 					if (!next_mp) {
20806 						ire_refrele(ire);
20807 						if (conn_outgoing_ill != NULL) {
20808 							ill_refrele(
20809 							    conn_outgoing_ill);
20810 						}
20811 						return;
20812 					}
20813 				} else {
20814 					/*
20815 					 * This won't cause a icmp_frag_needed
20816 					 * message. to be gnerated. Send it on
20817 					 * the wire. Note that this could still
20818 					 * cause fragmentation and all we
20819 					 * do is the generation of the message
20820 					 * to the ULP if needed before IPSEC.
20821 					 */
20822 					if (!next_mp) {
20823 						ipsec_out_process(q, first_mp,
20824 						    ire, ill_index);
20825 						TRACE_2(TR_FAC_IP,
20826 						    TR_IP_WPUT_IRE_END,
20827 						    "ip_wput_ire_end: q %p "
20828 						    "(%S)", q,
20829 						    "last ipsec_out_process");
20830 						ire_refrele(ire);
20831 						if (conn_outgoing_ill != NULL) {
20832 							ill_refrele(
20833 							    conn_outgoing_ill);
20834 						}
20835 						return;
20836 					}
20837 					ipsec_out_process(q, first_mp,
20838 					    ire, ill_index);
20839 				}
20840 			} else {
20841 				/* Initiate IPPF processing */
20842 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20843 					ip_process(IPP_LOCAL_OUT, &mp,
20844 					    ill_index);
20845 					if (mp == NULL) {
20846 						BUMP_MIB(&ip_mib,
20847 						    ipOutDiscards);
20848 						if (next_mp != NULL) {
20849 							freemsg(next_mp);
20850 							ire_refrele(ire1);
20851 						}
20852 						ire_refrele(ire);
20853 						TRACE_2(TR_FAC_IP,
20854 						    TR_IP_WPUT_IRE_END,
20855 						    "ip_wput_ire: q %p (%S)",
20856 						    q, "discard MDATA");
20857 						if (conn_outgoing_ill != NULL) {
20858 							ill_refrele(
20859 							    conn_outgoing_ill);
20860 						}
20861 						return;
20862 					}
20863 				}
20864 				if (!next_mp) {
20865 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20866 					    "ip_wput_ire_end: q %p (%S)",
20867 					    q, "last fragmentation");
20868 					ip_wput_ire_fragmentit(mp, ire);
20869 					ire_refrele(ire);
20870 					if (conn_outgoing_ill != NULL)
20871 						ill_refrele(conn_outgoing_ill);
20872 					return;
20873 				}
20874 				ip_wput_ire_fragmentit(mp, ire);
20875 			}
20876 		}
20877 	} else {
20878 	    nullstq:
20879 		/* A NULL stq means the destination address is local. */
20880 		UPDATE_OB_PKT_COUNT(ire);
20881 		ire->ire_last_used_time = lbolt;
20882 		ASSERT(ire->ire_ipif != NULL);
20883 		if (!next_mp) {
20884 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20885 			    "ip_wput_ire_end: q %p (%S)",
20886 			    q, "local address");
20887 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20888 			    first_mp, ire, 0, ire->ire_zoneid);
20889 			ire_refrele(ire);
20890 			if (conn_outgoing_ill != NULL)
20891 				ill_refrele(conn_outgoing_ill);
20892 			return;
20893 		}
20894 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20895 		    ire, 0, ire->ire_zoneid);
20896 	}
20897 next:
20898 	/*
20899 	 * More copies going out to additional interfaces.
20900 	 * ire1 has already been held. We don't need the
20901 	 * "ire" anymore.
20902 	 */
20903 	ire_refrele(ire);
20904 	ire = ire1;
20905 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20906 	mp = next_mp;
20907 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20908 	ill = ire_to_ill(ire);
20909 	first_mp = mp;
20910 	if (ipsec_len != 0) {
20911 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20912 		mp = mp->b_cont;
20913 	}
20914 	dst = ire->ire_addr;
20915 	ipha = (ipha_t *)mp->b_rptr;
20916 	/*
20917 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20918 	 * Restore ipha_ident "no checksum" flag.
20919 	 */
20920 	src = orig_src;
20921 	ipha->ipha_ident = ip_hdr_included;
20922 	goto another;
20923 
20924 #undef	rptr
20925 #undef	Q_TO_INDEX
20926 }
20927 
20928 /*
20929  * Routine to allocate a message that is used to notify the ULP about MDT.
20930  * The caller may provide a pointer to the link-layer MDT capabilities,
20931  * or NULL if MDT is to be disabled on the stream.
20932  */
20933 mblk_t *
20934 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20935 {
20936 	mblk_t *mp;
20937 	ip_mdt_info_t *mdti;
20938 	ill_mdt_capab_t *idst;
20939 
20940 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20941 		DB_TYPE(mp) = M_CTL;
20942 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20943 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20944 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20945 		idst = &(mdti->mdt_capab);
20946 
20947 		/*
20948 		 * If the caller provides us with the capability, copy
20949 		 * it over into our notification message; otherwise
20950 		 * we zero out the capability portion.
20951 		 */
20952 		if (isrc != NULL)
20953 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20954 		else
20955 			bzero((caddr_t)idst, sizeof (*idst));
20956 	}
20957 	return (mp);
20958 }
20959 
20960 /*
20961  * Routine which determines whether MDT can be enabled on the destination
20962  * IRE and IPC combination, and if so, allocates and returns the MDT
20963  * notification mblk that may be used by ULP.  We also check if we need to
20964  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
20965  * MDT usage in the past have been lifted.  This gets called during IP
20966  * and ULP binding.
20967  */
20968 mblk_t *
20969 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
20970     ill_mdt_capab_t *mdt_cap)
20971 {
20972 	mblk_t *mp;
20973 	boolean_t rc = B_FALSE;
20974 
20975 	ASSERT(dst_ire != NULL);
20976 	ASSERT(connp != NULL);
20977 	ASSERT(mdt_cap != NULL);
20978 
20979 	/*
20980 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
20981 	 * Multidata, which is handled in tcp_multisend().  This
20982 	 * is the reason why we do all these checks here, to ensure
20983 	 * that we don't enable Multidata for the cases which we
20984 	 * can't handle at the moment.
20985 	 */
20986 	do {
20987 		/* Only do TCP at the moment */
20988 		if (connp->conn_ulp != IPPROTO_TCP)
20989 			break;
20990 
20991 		/*
20992 		 * IPSEC outbound policy present?  Note that we get here
20993 		 * after calling ipsec_conn_cache_policy() where the global
20994 		 * policy checking is performed.  conn_latch will be
20995 		 * non-NULL as long as there's a policy defined,
20996 		 * i.e. conn_out_enforce_policy may be NULL in such case
20997 		 * when the connection is non-secure, and hence we check
20998 		 * further if the latch refers to an outbound policy.
20999 		 */
21000 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21001 			break;
21002 
21003 		/* CGTP (multiroute) is enabled? */
21004 		if (dst_ire->ire_flags & RTF_MULTIRT)
21005 			break;
21006 
21007 		/* Outbound IPQoS enabled? */
21008 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21009 			/*
21010 			 * In this case, we disable MDT for this and all
21011 			 * future connections going over the interface.
21012 			 */
21013 			mdt_cap->ill_mdt_on = 0;
21014 			break;
21015 		}
21016 
21017 		/* socket option(s) present? */
21018 		if (!CONN_IS_MD_FASTPATH(connp))
21019 			break;
21020 
21021 		rc = B_TRUE;
21022 	/* CONSTCOND */
21023 	} while (0);
21024 
21025 	/* Remember the result */
21026 	connp->conn_mdt_ok = rc;
21027 
21028 	if (!rc)
21029 		return (NULL);
21030 	else if (!mdt_cap->ill_mdt_on) {
21031 		/*
21032 		 * If MDT has been previously turned off in the past, and we
21033 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21034 		 * then enable it for this interface.
21035 		 */
21036 		mdt_cap->ill_mdt_on = 1;
21037 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21038 		    "interface %s\n", ill_name));
21039 	}
21040 
21041 	/* Allocate the MDT info mblk */
21042 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21043 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21044 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21045 		return (NULL);
21046 	}
21047 	return (mp);
21048 }
21049 
21050 /*
21051  * Create destination address attribute, and fill it with the physical
21052  * destination address and SAP taken from the template DL_UNITDATA_REQ
21053  * message block.
21054  */
21055 boolean_t
21056 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21057 {
21058 	dl_unitdata_req_t *dlurp;
21059 	pattr_t *pa;
21060 	pattrinfo_t pa_info;
21061 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21062 	uint_t das_len, das_off;
21063 
21064 	ASSERT(dlmp != NULL);
21065 
21066 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21067 	das_len = dlurp->dl_dest_addr_length;
21068 	das_off = dlurp->dl_dest_addr_offset;
21069 
21070 	pa_info.type = PATTR_DSTADDRSAP;
21071 	pa_info.len = sizeof (**das) + das_len - 1;
21072 
21073 	/* create and associate the attribute */
21074 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21075 	if (pa != NULL) {
21076 		ASSERT(*das != NULL);
21077 		(*das)->addr_is_group = 0;
21078 		(*das)->addr_len = (uint8_t)das_len;
21079 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21080 	}
21081 
21082 	return (pa != NULL);
21083 }
21084 
21085 /*
21086  * Create hardware checksum attribute and fill it with the values passed.
21087  */
21088 boolean_t
21089 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21090     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21091 {
21092 	pattr_t *pa;
21093 	pattrinfo_t pa_info;
21094 
21095 	ASSERT(mmd != NULL);
21096 
21097 	pa_info.type = PATTR_HCKSUM;
21098 	pa_info.len = sizeof (pattr_hcksum_t);
21099 
21100 	/* create and associate the attribute */
21101 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21102 	if (pa != NULL) {
21103 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21104 
21105 		hck->hcksum_start_offset = start_offset;
21106 		hck->hcksum_stuff_offset = stuff_offset;
21107 		hck->hcksum_end_offset = end_offset;
21108 		hck->hcksum_flags = flags;
21109 	}
21110 	return (pa != NULL);
21111 }
21112 
21113 /*
21114  * Create zerocopy attribute and fill it with the specified flags
21115  */
21116 boolean_t
21117 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21118 {
21119 	pattr_t *pa;
21120 	pattrinfo_t pa_info;
21121 
21122 	ASSERT(mmd != NULL);
21123 	pa_info.type = PATTR_ZCOPY;
21124 	pa_info.len = sizeof (pattr_zcopy_t);
21125 
21126 	/* create and associate the attribute */
21127 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21128 	if (pa != NULL) {
21129 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21130 
21131 		zcopy->zcopy_flags = flags;
21132 	}
21133 	return (pa != NULL);
21134 }
21135 
21136 /*
21137  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21138  * block chain. We could rewrite to handle arbitrary message block chains but
21139  * that would make the code complicated and slow. Right now there three
21140  * restrictions:
21141  *
21142  *   1. The first message block must contain the complete IP header and
21143  *	at least 1 byte of payload data.
21144  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
21145  *	so that we can use a single Multidata message.
21146  *   3. No frag must be distributed over two or more message blocks so
21147  *	that we don't need more than two packet descriptors per frag.
21148  *
21149  * The above restrictions allow us to support userland applications (which
21150  * will send down a single message block) and NFS over UDP (which will
21151  * send down a chain of at most three message blocks).
21152  *
21153  * We also don't use MDT for payloads with less than or equal to
21154  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
21155  */
21156 boolean_t
21157 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
21158 {
21159 	int	blocks;
21160 	ssize_t	total, missing, size;
21161 
21162 	ASSERT(mp != NULL);
21163 	ASSERT(hdr_len > 0);
21164 
21165 	size = MBLKL(mp) - hdr_len;
21166 	if (size <= 0)
21167 		return (B_FALSE);
21168 
21169 	/* The first mblk contains the header and some payload. */
21170 	blocks = 1;
21171 	total = size;
21172 	size %= len;
21173 	missing = (size == 0) ? 0 : (len - size);
21174 	mp = mp->b_cont;
21175 
21176 	while (mp != NULL) {
21177 		/*
21178 		 * Give up if we encounter a zero length message block.
21179 		 * In practice, this should rarely happen and therefore
21180 		 * not worth the trouble of freeing and re-linking the
21181 		 * mblk from the chain to handle such case.
21182 		 */
21183 		if ((size = MBLKL(mp)) == 0)
21184 			return (B_FALSE);
21185 
21186 		/* Too many payload buffers for a single Multidata message? */
21187 		if (++blocks > MULTIDATA_MAX_PBUFS)
21188 			return (B_FALSE);
21189 
21190 		total += size;
21191 		/* Is a frag distributed over two or more message blocks? */
21192 		if (missing > size)
21193 			return (B_FALSE);
21194 		size -= missing;
21195 
21196 		size %= len;
21197 		missing = (size == 0) ? 0 : (len - size);
21198 
21199 		mp = mp->b_cont;
21200 	}
21201 
21202 	return (total > ip_wput_frag_mdt_min);
21203 }
21204 
21205 /*
21206  * Outbound IPv4 fragmentation routine using MDT.
21207  */
21208 static void
21209 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
21210     uint32_t frag_flag, int offset)
21211 {
21212 	ipha_t		*ipha_orig;
21213 	int		i1, ip_data_end;
21214 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
21215 	mblk_t		*hdr_mp, *md_mp = NULL;
21216 	unsigned char	*hdr_ptr, *pld_ptr;
21217 	multidata_t	*mmd;
21218 	ip_pdescinfo_t	pdi;
21219 
21220 	ASSERT(DB_TYPE(mp) == M_DATA);
21221 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
21222 
21223 	ipha_orig = (ipha_t *)mp->b_rptr;
21224 	mp->b_rptr += sizeof (ipha_t);
21225 
21226 	/* Calculate how many packets we will send out */
21227 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
21228 	pkts = (i1 + len - 1) / len;
21229 	ASSERT(pkts > 1);
21230 
21231 	/* Allocate a message block which will hold all the IP Headers. */
21232 	wroff = ip_wroff_extra;
21233 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
21234 
21235 	i1 = pkts * hdr_chunk_len;
21236 	/*
21237 	 * Create the header buffer, Multidata and destination address
21238 	 * and SAP attribute that should be associated with it.
21239 	 */
21240 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
21241 	    ((hdr_mp->b_wptr += i1),
21242 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
21243 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
21244 		freemsg(mp);
21245 		if (md_mp == NULL) {
21246 			freemsg(hdr_mp);
21247 		} else {
21248 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
21249 			freemsg(md_mp);
21250 		}
21251 		IP_STAT(ip_frag_mdt_allocfail);
21252 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
21253 		return;
21254 	}
21255 	IP_STAT(ip_frag_mdt_allocd);
21256 
21257 	/*
21258 	 * Add a payload buffer to the Multidata; this operation must not
21259 	 * fail, or otherwise our logic in this routine is broken.  There
21260 	 * is no memory allocation done by the routine, so any returned
21261 	 * failure simply tells us that we've done something wrong.
21262 	 *
21263 	 * A failure tells us that either we're adding the same payload
21264 	 * buffer more than once, or we're trying to add more buffers than
21265 	 * allowed.  None of the above cases should happen, and we panic
21266 	 * because either there's horrible heap corruption, and/or
21267 	 * programming mistake.
21268 	 */
21269 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21270 		goto pbuf_panic;
21271 
21272 	hdr_ptr = hdr_mp->b_rptr;
21273 	pld_ptr = mp->b_rptr;
21274 
21275 	/* Establish the ending byte offset, based on the starting offset. */
21276 	offset <<= 3;
21277 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
21278 	    IP_SIMPLE_HDR_LENGTH;
21279 
21280 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
21281 
21282 	while (pld_ptr < mp->b_wptr) {
21283 		ipha_t		*ipha;
21284 		uint16_t	offset_and_flags;
21285 		uint16_t	ip_len;
21286 		int		error;
21287 
21288 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
21289 		ipha = (ipha_t *)(hdr_ptr + wroff);
21290 		ASSERT(OK_32PTR(ipha));
21291 		*ipha = *ipha_orig;
21292 
21293 		if (ip_data_end - offset > len) {
21294 			offset_and_flags = IPH_MF;
21295 		} else {
21296 			/*
21297 			 * Last frag. Set len to the length of this last piece.
21298 			 */
21299 			len = ip_data_end - offset;
21300 			/* A frag of a frag might have IPH_MF non-zero */
21301 			offset_and_flags =
21302 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21303 			    IPH_MF;
21304 		}
21305 		offset_and_flags |= (uint16_t)(offset >> 3);
21306 		offset_and_flags |= (uint16_t)frag_flag;
21307 		/* Store the offset and flags in the IP header. */
21308 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21309 
21310 		/* Store the length in the IP header. */
21311 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
21312 		ipha->ipha_length = htons(ip_len);
21313 
21314 		/*
21315 		 * Set the IP header checksum.  Note that mp is just
21316 		 * the header, so this is easy to pass to ip_csum.
21317 		 */
21318 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21319 
21320 		/*
21321 		 * Record offset and size of header and data of the next packet
21322 		 * in the multidata message.
21323 		 */
21324 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
21325 		PDESC_PLD_INIT(&pdi);
21326 		i1 = MIN(mp->b_wptr - pld_ptr, len);
21327 		ASSERT(i1 > 0);
21328 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
21329 		if (i1 == len) {
21330 			pld_ptr += len;
21331 		} else {
21332 			i1 = len - i1;
21333 			mp = mp->b_cont;
21334 			ASSERT(mp != NULL);
21335 			ASSERT(MBLKL(mp) >= i1);
21336 			/*
21337 			 * Attach the next payload message block to the
21338 			 * multidata message.
21339 			 */
21340 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21341 				goto pbuf_panic;
21342 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
21343 			pld_ptr = mp->b_rptr + i1;
21344 		}
21345 
21346 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
21347 		    KM_NOSLEEP)) == NULL) {
21348 			/*
21349 			 * Any failure other than ENOMEM indicates that we
21350 			 * have passed in invalid pdesc info or parameters
21351 			 * to mmd_addpdesc, which must not happen.
21352 			 *
21353 			 * EINVAL is a result of failure on boundary checks
21354 			 * against the pdesc info contents.  It should not
21355 			 * happen, and we panic because either there's
21356 			 * horrible heap corruption, and/or programming
21357 			 * mistake.
21358 			 */
21359 			if (error != ENOMEM) {
21360 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
21361 				    "pdesc logic error detected for "
21362 				    "mmd %p pinfo %p (%d)\n",
21363 				    (void *)mmd, (void *)&pdi, error);
21364 				/* NOTREACHED */
21365 			}
21366 			IP_STAT(ip_frag_mdt_addpdescfail);
21367 			/* Free unattached payload message blocks as well */
21368 			md_mp->b_cont = mp->b_cont;
21369 			goto free_mmd;
21370 		}
21371 
21372 		/* Advance fragment offset. */
21373 		offset += len;
21374 
21375 		/* Advance to location for next header in the buffer. */
21376 		hdr_ptr += hdr_chunk_len;
21377 
21378 		/* Did we reach the next payload message block? */
21379 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
21380 			mp = mp->b_cont;
21381 			/*
21382 			 * Attach the next message block with payload
21383 			 * data to the multidata message.
21384 			 */
21385 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
21386 				goto pbuf_panic;
21387 			pld_ptr = mp->b_rptr;
21388 		}
21389 	}
21390 
21391 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
21392 	ASSERT(mp->b_wptr == pld_ptr);
21393 
21394 	/* Update IP statistics */
21395 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
21396 	BUMP_MIB(&ip_mib, ipFragOKs);
21397 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
21398 
21399 	if (pkt_type == OB_PKT) {
21400 		ire->ire_ob_pkt_count += pkts;
21401 		if (ire->ire_ipif != NULL)
21402 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
21403 	} else {
21404 		/*
21405 		 * The type is IB_PKT in the forwarding path and in
21406 		 * the mobile IP case when the packet is being reverse-
21407 		 * tunneled to the home agent.
21408 		 */
21409 		ire->ire_ib_pkt_count += pkts;
21410 		ASSERT(!IRE_IS_LOCAL(ire));
21411 		if (ire->ire_type & IRE_BROADCAST)
21412 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
21413 		else
21414 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
21415 	}
21416 	ire->ire_last_used_time = lbolt;
21417 	/* Send it down */
21418 	putnext(ire->ire_stq, md_mp);
21419 	return;
21420 
21421 pbuf_panic:
21422 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
21423 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
21424 	    pbuf_idx);
21425 	/* NOTREACHED */
21426 }
21427 
21428 /*
21429  * Outbound IP fragmentation routine.
21430  *
21431  * NOTE : This routine does not ire_refrele the ire that is passed in
21432  * as the argument.
21433  */
21434 static void
21435 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21436     uint32_t frag_flag)
21437 {
21438 	int		i1;
21439 	mblk_t		*ll_hdr_mp;
21440 	int 		ll_hdr_len;
21441 	int		hdr_len;
21442 	mblk_t		*hdr_mp;
21443 	ipha_t		*ipha;
21444 	int		ip_data_end;
21445 	int		len;
21446 	mblk_t		*mp = mp_orig;
21447 	int		offset;
21448 	queue_t		*q;
21449 	uint32_t	v_hlen_tos_len;
21450 	mblk_t		*first_mp;
21451 	boolean_t	mctl_present;
21452 	ill_t		*ill;
21453 	mblk_t		*xmit_mp;
21454 	mblk_t		*carve_mp;
21455 	ire_t		*ire1 = NULL;
21456 	ire_t		*save_ire = NULL;
21457 	mblk_t  	*next_mp = NULL;
21458 	boolean_t	last_frag = B_FALSE;
21459 	boolean_t	multirt_send = B_FALSE;
21460 	ire_t		*first_ire = NULL;
21461 	irb_t		*irb = NULL;
21462 
21463 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21464 	    "ip_wput_frag_start:");
21465 
21466 	if (mp->b_datap->db_type == M_CTL) {
21467 		first_mp = mp;
21468 		mp_orig = mp = mp->b_cont;
21469 		mctl_present = B_TRUE;
21470 	} else {
21471 		first_mp = mp;
21472 		mctl_present = B_FALSE;
21473 	}
21474 
21475 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
21476 	ipha = (ipha_t *)mp->b_rptr;
21477 
21478 	/*
21479 	 * If the Don't Fragment flag is on, generate an ICMP destination
21480 	 * unreachable, fragmentation needed.
21481 	 */
21482 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21483 	if (offset & IPH_DF) {
21484 		BUMP_MIB(&ip_mib, ipFragFails);
21485 		/*
21486 		 * Need to compute hdr checksum if called from ip_wput_ire.
21487 		 * Note that ip_rput_forward verifies the checksum before
21488 		 * calling this routine so in that case this is a noop.
21489 		 */
21490 		ipha->ipha_hdr_checksum = 0;
21491 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21492 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21493 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21494 		    "ip_wput_frag_end:(%S)",
21495 		    "don't fragment");
21496 		return;
21497 	}
21498 	if (mctl_present)
21499 		freeb(first_mp);
21500 	/*
21501 	 * Establish the starting offset.  May not be zero if we are fragging
21502 	 * a fragment that is being forwarded.
21503 	 */
21504 	offset = offset & IPH_OFFSET;
21505 
21506 	/* TODO why is this test needed? */
21507 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21508 	if (((max_frag - LENGTH) & ~7) < 8) {
21509 		/* TODO: notify ulp somehow */
21510 		BUMP_MIB(&ip_mib, ipFragFails);
21511 		freemsg(mp);
21512 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21513 		    "ip_wput_frag_end:(%S)",
21514 		    "len < 8");
21515 		return;
21516 	}
21517 
21518 	hdr_len = (V_HLEN & 0xF) << 2;
21519 
21520 	ipha->ipha_hdr_checksum = 0;
21521 
21522 	/*
21523 	 * Establish the number of bytes maximum per frag, after putting
21524 	 * in the header.
21525 	 */
21526 	len = (max_frag - hdr_len) & ~7;
21527 
21528 	/* Check if we can use MDT to send out the frags. */
21529 	ASSERT(!IRE_IS_LOCAL(ire));
21530 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
21531 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
21532 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
21533 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
21534 		ASSERT(ill->ill_mdt_capab != NULL);
21535 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21536 			/*
21537 			 * If MDT has been previously turned off in the past,
21538 			 * and we currently can do MDT (due to IPQoS policy
21539 			 * removal, etc.) then enable it for this interface.
21540 			 */
21541 			ill->ill_mdt_capab->ill_mdt_on = 1;
21542 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
21543 			    ill->ill_name));
21544 		}
21545 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
21546 		    offset);
21547 		return;
21548 	}
21549 
21550 	/* Get a copy of the header for the trailing frags */
21551 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21552 	if (!hdr_mp) {
21553 		BUMP_MIB(&ip_mib, ipOutDiscards);
21554 		freemsg(mp);
21555 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21556 		    "ip_wput_frag_end:(%S)",
21557 		    "couldn't copy hdr");
21558 		return;
21559 	}
21560 
21561 	/* Store the starting offset, with the MoreFrags flag. */
21562 	i1 = offset | IPH_MF | frag_flag;
21563 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21564 
21565 	/* Establish the ending byte offset, based on the starting offset. */
21566 	offset <<= 3;
21567 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21568 
21569 	/* Store the length of the first fragment in the IP header. */
21570 	i1 = len + hdr_len;
21571 	ASSERT(i1 <= IP_MAXPACKET);
21572 	ipha->ipha_length = htons((uint16_t)i1);
21573 
21574 	/*
21575 	 * Compute the IP header checksum for the first frag.  We have to
21576 	 * watch out that we stop at the end of the header.
21577 	 */
21578 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21579 
21580 	/*
21581 	 * Now carve off the first frag.  Note that this will include the
21582 	 * original IP header.
21583 	 */
21584 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21585 		BUMP_MIB(&ip_mib, ipOutDiscards);
21586 		freeb(hdr_mp);
21587 		freemsg(mp_orig);
21588 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21589 		    "ip_wput_frag_end:(%S)",
21590 		    "couldn't carve first");
21591 		return;
21592 	}
21593 
21594 	/*
21595 	 * Multirouting case. Each fragment is replicated
21596 	 * via all non-condemned RTF_MULTIRT routes
21597 	 * currently resolved.
21598 	 * We ensure that first_ire is the first RTF_MULTIRT
21599 	 * ire in the bucket.
21600 	 */
21601 	if (ire->ire_flags & RTF_MULTIRT) {
21602 		irb = ire->ire_bucket;
21603 		ASSERT(irb != NULL);
21604 
21605 		multirt_send = B_TRUE;
21606 
21607 		/* Make sure we do not omit any multiroute ire. */
21608 		IRB_REFHOLD(irb);
21609 		for (first_ire = irb->irb_ire;
21610 		    first_ire != NULL;
21611 		    first_ire = first_ire->ire_next) {
21612 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21613 			    (first_ire->ire_addr == ire->ire_addr) &&
21614 			    !(first_ire->ire_marks &
21615 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21616 				break;
21617 		}
21618 
21619 		if (first_ire != NULL) {
21620 			if (first_ire != ire) {
21621 				IRE_REFHOLD(first_ire);
21622 				/*
21623 				 * Do not release the ire passed in
21624 				 * as the argument.
21625 				 */
21626 				ire = first_ire;
21627 			} else {
21628 				first_ire = NULL;
21629 			}
21630 		}
21631 		IRB_REFRELE(irb);
21632 
21633 		/*
21634 		 * Save the first ire; we will need to restore it
21635 		 * for the trailing frags.
21636 		 * We REFHOLD save_ire, as each iterated ire will be
21637 		 * REFRELEd.
21638 		 */
21639 		save_ire = ire;
21640 		IRE_REFHOLD(save_ire);
21641 	}
21642 
21643 	/*
21644 	 * First fragment emission loop.
21645 	 * In most cases, the emission loop below is entered only
21646 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21647 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21648 	 * bucket, and send the fragment through all crossed
21649 	 * RTF_MULTIRT routes.
21650 	 */
21651 	do {
21652 		if (ire->ire_flags & RTF_MULTIRT) {
21653 			/*
21654 			 * We are in a multiple send case, need to get
21655 			 * the next ire and make a copy of the packet.
21656 			 * ire1 holds here the next ire to process in the
21657 			 * bucket. If multirouting is expected,
21658 			 * any non-RTF_MULTIRT ire that has the
21659 			 * right destination address is ignored.
21660 			 *
21661 			 * We have to take into account the MTU of
21662 			 * each walked ire. max_frag is set by the
21663 			 * the caller and generally refers to
21664 			 * the primary ire entry. Here we ensure that
21665 			 * no route with a lower MTU will be used, as
21666 			 * fragments are carved once for all ires,
21667 			 * then replicated.
21668 			 */
21669 			ASSERT(irb != NULL);
21670 			IRB_REFHOLD(irb);
21671 			for (ire1 = ire->ire_next;
21672 			    ire1 != NULL;
21673 			    ire1 = ire1->ire_next) {
21674 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21675 					continue;
21676 				if (ire1->ire_addr != ire->ire_addr)
21677 					continue;
21678 				if (ire1->ire_marks &
21679 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21680 					continue;
21681 				/*
21682 				 * Ensure we do not exceed the MTU
21683 				 * of the next route.
21684 				 */
21685 				if (ire1->ire_max_frag < max_frag) {
21686 					ip_multirt_bad_mtu(ire1, max_frag);
21687 					continue;
21688 				}
21689 
21690 				/* Got one. */
21691 				IRE_REFHOLD(ire1);
21692 				break;
21693 			}
21694 			IRB_REFRELE(irb);
21695 
21696 			if (ire1 != NULL) {
21697 				next_mp = copyb(mp);
21698 				if ((next_mp == NULL) ||
21699 				    ((mp->b_cont != NULL) &&
21700 				    ((next_mp->b_cont =
21701 				    dupmsg(mp->b_cont)) == NULL))) {
21702 					freemsg(next_mp);
21703 					next_mp = NULL;
21704 					ire_refrele(ire1);
21705 					ire1 = NULL;
21706 				}
21707 			}
21708 
21709 			/* Last multiroute ire; don't loop anymore. */
21710 			if (ire1 == NULL) {
21711 				multirt_send = B_FALSE;
21712 			}
21713 		}
21714 
21715 		ll_hdr_len = 0;
21716 		LOCK_IRE_FP_MP(ire);
21717 		ll_hdr_mp = ire->ire_fp_mp;
21718 		if (ll_hdr_mp != NULL) {
21719 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21720 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21721 		} else {
21722 			ll_hdr_mp = ire->ire_dlureq_mp;
21723 		}
21724 
21725 		/* If there is a transmit header, get a copy for this frag. */
21726 		/*
21727 		 * TODO: should check db_ref before calling ip_carve_mp since
21728 		 * it might give us a dup.
21729 		 */
21730 		if (!ll_hdr_mp) {
21731 			/* No xmit header. */
21732 			xmit_mp = mp;
21733 		} else if (mp->b_datap->db_ref == 1 &&
21734 		    ll_hdr_len != 0 &&
21735 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21736 			/* M_DATA fastpath */
21737 			mp->b_rptr -= ll_hdr_len;
21738 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21739 			xmit_mp = mp;
21740 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21741 			UNLOCK_IRE_FP_MP(ire);
21742 			BUMP_MIB(&ip_mib, ipOutDiscards);
21743 			freeb(hdr_mp);
21744 			freemsg(mp);
21745 			freemsg(mp_orig);
21746 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21747 			    "ip_wput_frag_end:(%S)",
21748 			    "discard");
21749 
21750 			if (multirt_send) {
21751 				ASSERT(ire1);
21752 				ASSERT(next_mp);
21753 
21754 				freemsg(next_mp);
21755 				ire_refrele(ire1);
21756 			}
21757 			if (save_ire != NULL)
21758 				IRE_REFRELE(save_ire);
21759 
21760 			if (first_ire != NULL)
21761 				ire_refrele(first_ire);
21762 			return;
21763 		} else {
21764 			xmit_mp->b_cont = mp;
21765 			/* Get priority marking, if any. */
21766 			if (DB_TYPE(xmit_mp) == M_DATA)
21767 				xmit_mp->b_band = mp->b_band;
21768 		}
21769 		UNLOCK_IRE_FP_MP(ire);
21770 		q = ire->ire_stq;
21771 		BUMP_MIB(&ip_mib, ipFragCreates);
21772 		putnext(q, xmit_mp);
21773 		if (pkt_type != OB_PKT) {
21774 			/*
21775 			 * Update the packet count of trailing
21776 			 * RTF_MULTIRT ires.
21777 			 */
21778 			UPDATE_OB_PKT_COUNT(ire);
21779 		}
21780 
21781 		if (multirt_send) {
21782 			/*
21783 			 * We are in a multiple send case; look for
21784 			 * the next ire and re-enter the loop.
21785 			 */
21786 			ASSERT(ire1);
21787 			ASSERT(next_mp);
21788 			/* REFRELE the current ire before looping */
21789 			ire_refrele(ire);
21790 			ire = ire1;
21791 			ire1 = NULL;
21792 			mp = next_mp;
21793 			next_mp = NULL;
21794 		}
21795 	} while (multirt_send);
21796 
21797 	ASSERT(ire1 == NULL);
21798 
21799 	/* Restore the original ire; we need it for the trailing frags */
21800 	if (save_ire != NULL) {
21801 		/* REFRELE the last iterated ire */
21802 		ire_refrele(ire);
21803 		/* save_ire has been REFHOLDed */
21804 		ire = save_ire;
21805 		save_ire = NULL;
21806 		q = ire->ire_stq;
21807 	}
21808 
21809 	if (pkt_type == OB_PKT) {
21810 		UPDATE_OB_PKT_COUNT(ire);
21811 	} else {
21812 		UPDATE_IB_PKT_COUNT(ire);
21813 	}
21814 
21815 	/* Advance the offset to the second frag starting point. */
21816 	offset += len;
21817 	/*
21818 	 * Update hdr_len from the copied header - there might be less options
21819 	 * in the later fragments.
21820 	 */
21821 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21822 	/* Loop until done. */
21823 	for (;;) {
21824 		uint16_t	offset_and_flags;
21825 		uint16_t	ip_len;
21826 
21827 		if (ip_data_end - offset > len) {
21828 			/*
21829 			 * Carve off the appropriate amount from the original
21830 			 * datagram.
21831 			 */
21832 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21833 				mp = NULL;
21834 				break;
21835 			}
21836 			/*
21837 			 * More frags after this one.  Get another copy
21838 			 * of the header.
21839 			 */
21840 			if (carve_mp->b_datap->db_ref == 1 &&
21841 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21842 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21843 				/* Inline IP header */
21844 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21845 				    hdr_mp->b_rptr;
21846 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21847 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21848 				mp = carve_mp;
21849 			} else {
21850 				if (!(mp = copyb(hdr_mp))) {
21851 					freemsg(carve_mp);
21852 					break;
21853 				}
21854 				/* Get priority marking, if any. */
21855 				mp->b_band = carve_mp->b_band;
21856 				mp->b_cont = carve_mp;
21857 			}
21858 			ipha = (ipha_t *)mp->b_rptr;
21859 			offset_and_flags = IPH_MF;
21860 		} else {
21861 			/*
21862 			 * Last frag.  Consume the header. Set len to
21863 			 * the length of this last piece.
21864 			 */
21865 			len = ip_data_end - offset;
21866 
21867 			/*
21868 			 * Carve off the appropriate amount from the original
21869 			 * datagram.
21870 			 */
21871 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21872 				mp = NULL;
21873 				break;
21874 			}
21875 			if (carve_mp->b_datap->db_ref == 1 &&
21876 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21877 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21878 				/* Inline IP header */
21879 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21880 				    hdr_mp->b_rptr;
21881 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21882 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21883 				mp = carve_mp;
21884 				freeb(hdr_mp);
21885 				hdr_mp = mp;
21886 			} else {
21887 				mp = hdr_mp;
21888 				/* Get priority marking, if any. */
21889 				mp->b_band = carve_mp->b_band;
21890 				mp->b_cont = carve_mp;
21891 			}
21892 			ipha = (ipha_t *)mp->b_rptr;
21893 			/* A frag of a frag might have IPH_MF non-zero */
21894 			offset_and_flags =
21895 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21896 			    IPH_MF;
21897 		}
21898 		offset_and_flags |= (uint16_t)(offset >> 3);
21899 		offset_and_flags |= (uint16_t)frag_flag;
21900 		/* Store the offset and flags in the IP header. */
21901 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21902 
21903 		/* Store the length in the IP header. */
21904 		ip_len = (uint16_t)(len + hdr_len);
21905 		ipha->ipha_length = htons(ip_len);
21906 
21907 		/*
21908 		 * Set the IP header checksum.	Note that mp is just
21909 		 * the header, so this is easy to pass to ip_csum.
21910 		 */
21911 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21912 
21913 		/* Attach a transmit header, if any, and ship it. */
21914 		if (pkt_type == OB_PKT) {
21915 			UPDATE_OB_PKT_COUNT(ire);
21916 		} else {
21917 			UPDATE_IB_PKT_COUNT(ire);
21918 		}
21919 
21920 		if (ire->ire_flags & RTF_MULTIRT) {
21921 			irb = ire->ire_bucket;
21922 			ASSERT(irb != NULL);
21923 
21924 			multirt_send = B_TRUE;
21925 
21926 			/*
21927 			 * Save the original ire; we will need to restore it
21928 			 * for the tailing frags.
21929 			 */
21930 			save_ire = ire;
21931 			IRE_REFHOLD(save_ire);
21932 		}
21933 		/*
21934 		 * Emission loop for this fragment, similar
21935 		 * to what is done for the first fragment.
21936 		 */
21937 		do {
21938 			if (multirt_send) {
21939 				/*
21940 				 * We are in a multiple send case, need to get
21941 				 * the next ire and make a copy of the packet.
21942 				 */
21943 				ASSERT(irb != NULL);
21944 				IRB_REFHOLD(irb);
21945 				for (ire1 = ire->ire_next;
21946 				    ire1 != NULL;
21947 				    ire1 = ire1->ire_next) {
21948 					if (!(ire1->ire_flags & RTF_MULTIRT))
21949 						continue;
21950 					if (ire1->ire_addr != ire->ire_addr)
21951 						continue;
21952 					if (ire1->ire_marks &
21953 					    (IRE_MARK_CONDEMNED|
21954 						IRE_MARK_HIDDEN))
21955 						continue;
21956 					/*
21957 					 * Ensure we do not exceed the MTU
21958 					 * of the next route.
21959 					 */
21960 					if (ire1->ire_max_frag < max_frag) {
21961 						ip_multirt_bad_mtu(ire1,
21962 						    max_frag);
21963 						continue;
21964 					}
21965 
21966 					/* Got one. */
21967 					IRE_REFHOLD(ire1);
21968 					break;
21969 				}
21970 				IRB_REFRELE(irb);
21971 
21972 				if (ire1 != NULL) {
21973 					next_mp = copyb(mp);
21974 					if ((next_mp == NULL) ||
21975 					    ((mp->b_cont != NULL) &&
21976 					    ((next_mp->b_cont =
21977 					    dupmsg(mp->b_cont)) == NULL))) {
21978 						freemsg(next_mp);
21979 						next_mp = NULL;
21980 						ire_refrele(ire1);
21981 						ire1 = NULL;
21982 					}
21983 				}
21984 
21985 				/* Last multiroute ire; don't loop anymore. */
21986 				if (ire1 == NULL) {
21987 					multirt_send = B_FALSE;
21988 				}
21989 			}
21990 
21991 			/* Update transmit header */
21992 			ll_hdr_len = 0;
21993 			LOCK_IRE_FP_MP(ire);
21994 			ll_hdr_mp = ire->ire_fp_mp;
21995 			if (ll_hdr_mp != NULL) {
21996 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21997 				ll_hdr_len = MBLKL(ll_hdr_mp);
21998 			} else {
21999 				ll_hdr_mp = ire->ire_dlureq_mp;
22000 			}
22001 
22002 			if (!ll_hdr_mp) {
22003 				xmit_mp = mp;
22004 			} else if (mp->b_datap->db_ref == 1 &&
22005 			    ll_hdr_len != 0 &&
22006 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22007 				/* M_DATA fastpath */
22008 				mp->b_rptr -= ll_hdr_len;
22009 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22010 				    ll_hdr_len);
22011 				xmit_mp = mp;
22012 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22013 				xmit_mp->b_cont = mp;
22014 				/* Get priority marking, if any. */
22015 				if (DB_TYPE(xmit_mp) == M_DATA)
22016 					xmit_mp->b_band = mp->b_band;
22017 			} else {
22018 				/*
22019 				 * Exit both the replication and
22020 				 * fragmentation loops.
22021 				 */
22022 				UNLOCK_IRE_FP_MP(ire);
22023 				goto drop_pkt;
22024 			}
22025 			UNLOCK_IRE_FP_MP(ire);
22026 			BUMP_MIB(&ip_mib, ipFragCreates);
22027 			putnext(q, xmit_mp);
22028 
22029 			if (pkt_type != OB_PKT) {
22030 				/*
22031 				 * Update the packet count of trailing
22032 				 * RTF_MULTIRT ires.
22033 				 */
22034 				UPDATE_OB_PKT_COUNT(ire);
22035 			}
22036 
22037 			/* All done if we just consumed the hdr_mp. */
22038 			if (mp == hdr_mp) {
22039 				last_frag = B_TRUE;
22040 			}
22041 
22042 			if (multirt_send) {
22043 				/*
22044 				 * We are in a multiple send case; look for
22045 				 * the next ire and re-enter the loop.
22046 				 */
22047 				ASSERT(ire1);
22048 				ASSERT(next_mp);
22049 				/* REFRELE the current ire before looping */
22050 				ire_refrele(ire);
22051 				ire = ire1;
22052 				ire1 = NULL;
22053 				q = ire->ire_stq;
22054 				mp = next_mp;
22055 				next_mp = NULL;
22056 			}
22057 		} while (multirt_send);
22058 		/*
22059 		 * Restore the original ire; we need it for the
22060 		 * trailing frags
22061 		 */
22062 		if (save_ire != NULL) {
22063 			ASSERT(ire1 == NULL);
22064 			/* REFRELE the last iterated ire */
22065 			ire_refrele(ire);
22066 			/* save_ire has been REFHOLDed */
22067 			ire = save_ire;
22068 			q = ire->ire_stq;
22069 			save_ire = NULL;
22070 		}
22071 
22072 		if (last_frag) {
22073 			BUMP_MIB(&ip_mib, ipFragOKs);
22074 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22075 			    "ip_wput_frag_end:(%S)",
22076 			    "consumed hdr_mp");
22077 
22078 			if (first_ire != NULL)
22079 				ire_refrele(first_ire);
22080 			return;
22081 		}
22082 		/* Otherwise, advance and loop. */
22083 		offset += len;
22084 	}
22085 
22086 drop_pkt:
22087 	/* Clean up following allocation failure. */
22088 	BUMP_MIB(&ip_mib, ipOutDiscards);
22089 	freemsg(mp);
22090 	if (mp != hdr_mp)
22091 		freeb(hdr_mp);
22092 	if (mp != mp_orig)
22093 		freemsg(mp_orig);
22094 
22095 	if (save_ire != NULL)
22096 		IRE_REFRELE(save_ire);
22097 	if (first_ire != NULL)
22098 		ire_refrele(first_ire);
22099 
22100 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22101 	    "ip_wput_frag_end:(%S)",
22102 	    "end--alloc failure");
22103 }
22104 
22105 /*
22106  * Copy the header plus those options which have the copy bit set
22107  */
22108 static mblk_t *
22109 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22110 {
22111 	mblk_t	*mp;
22112 	uchar_t	*up;
22113 
22114 	/*
22115 	 * Quick check if we need to look for options without the copy bit
22116 	 * set
22117 	 */
22118 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22119 	if (!mp)
22120 		return (mp);
22121 	mp->b_rptr += ip_wroff_extra;
22122 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22123 		bcopy(rptr, mp->b_rptr, hdr_len);
22124 		mp->b_wptr += hdr_len + ip_wroff_extra;
22125 		return (mp);
22126 	}
22127 	up  = mp->b_rptr;
22128 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22129 	up += IP_SIMPLE_HDR_LENGTH;
22130 	rptr += IP_SIMPLE_HDR_LENGTH;
22131 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22132 	while (hdr_len > 0) {
22133 		uint32_t optval;
22134 		uint32_t optlen;
22135 
22136 		optval = *rptr;
22137 		if (optval == IPOPT_EOL)
22138 			break;
22139 		if (optval == IPOPT_NOP)
22140 			optlen = 1;
22141 		else
22142 			optlen = rptr[1];
22143 		if (optval & IPOPT_COPY) {
22144 			bcopy(rptr, up, optlen);
22145 			up += optlen;
22146 		}
22147 		rptr += optlen;
22148 		hdr_len -= optlen;
22149 	}
22150 	/*
22151 	 * Make sure that we drop an even number of words by filling
22152 	 * with EOL to the next word boundary.
22153 	 */
22154 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
22155 	    hdr_len & 0x3; hdr_len++)
22156 		*up++ = IPOPT_EOL;
22157 	mp->b_wptr = up;
22158 	/* Update header length */
22159 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
22160 	return (mp);
22161 }
22162 
22163 /*
22164  * Delivery to local recipients including fanout to multiple recipients.
22165  * Does not do checksumming of UDP/TCP.
22166  * Note: q should be the read side queue for either the ill or conn.
22167  * Note: rq should be the read side q for the lower (ill) stream.
22168  * We don't send packets to IPPF processing, thus the last argument
22169  * to all the fanout calls are B_FALSE.
22170  */
22171 void
22172 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
22173     int fanout_flags, zoneid_t zoneid)
22174 {
22175 	uint32_t	protocol;
22176 	mblk_t		*first_mp;
22177 	boolean_t	mctl_present;
22178 	int		ire_type;
22179 #define	rptr	((uchar_t *)ipha)
22180 
22181 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
22182 	    "ip_wput_local_start: q %p", q);
22183 
22184 	if (ire != NULL) {
22185 		ire_type = ire->ire_type;
22186 	} else {
22187 		/*
22188 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
22189 		 * packet is not multicast, we can't tell the ire type.
22190 		 */
22191 		ASSERT(CLASSD(ipha->ipha_dst));
22192 		ire_type = IRE_BROADCAST;
22193 	}
22194 
22195 	first_mp = mp;
22196 	if (first_mp->b_datap->db_type == M_CTL) {
22197 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
22198 		if (!io->ipsec_out_secure) {
22199 			/*
22200 			 * This ipsec_out_t was allocated in ip_wput
22201 			 * for multicast packets to store the ill_index.
22202 			 * As this is being delivered locally, we don't
22203 			 * need this anymore.
22204 			 */
22205 			mp = first_mp->b_cont;
22206 			freeb(first_mp);
22207 			first_mp = mp;
22208 			mctl_present = B_FALSE;
22209 		} else {
22210 			mctl_present = B_TRUE;
22211 			mp = first_mp->b_cont;
22212 			ASSERT(mp != NULL);
22213 			ipsec_out_to_in(first_mp);
22214 		}
22215 	} else {
22216 		mctl_present = B_FALSE;
22217 	}
22218 
22219 	loopback_packets++;
22220 
22221 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
22222 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
22223 	if (!IS_SIMPLE_IPH(ipha)) {
22224 		ip_wput_local_options(ipha);
22225 	}
22226 
22227 	protocol = ipha->ipha_protocol;
22228 	switch (protocol) {
22229 	case IPPROTO_ICMP: {
22230 		ire_t		*ire_zone;
22231 		ilm_t		*ilm;
22232 		mblk_t		*mp1;
22233 		zoneid_t	last_zoneid;
22234 
22235 		if (CLASSD(ipha->ipha_dst) &&
22236 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
22237 			ASSERT(ire_type == IRE_BROADCAST);
22238 			/*
22239 			 * In the multicast case, applications may have joined
22240 			 * the group from different zones, so we need to deliver
22241 			 * the packet to each of them. Loop through the
22242 			 * multicast memberships structures (ilm) on the receive
22243 			 * ill and send a copy of the packet up each matching
22244 			 * one. However, we don't do this for multicasts sent on
22245 			 * the loopback interface (PHYI_LOOPBACK flag set) as
22246 			 * they must stay in the sender's zone.
22247 			 *
22248 			 * ilm_add_v6() ensures that ilms in the same zone are
22249 			 * contiguous in the ill_ilm list. We use this property
22250 			 * to avoid sending duplicates needed when two
22251 			 * applications in the same zone join the same group on
22252 			 * different logical interfaces: we ignore the ilm if
22253 			 * its zoneid is the same as the last matching one.
22254 			 * In addition, the sending of the packet for
22255 			 * ire_zoneid is delayed until all of the other ilms
22256 			 * have been exhausted.
22257 			 */
22258 			last_zoneid = -1;
22259 			ILM_WALKER_HOLD(ill);
22260 			for (ilm = ill->ill_ilm; ilm != NULL;
22261 			    ilm = ilm->ilm_next) {
22262 				if ((ilm->ilm_flags & ILM_DELETED) ||
22263 				    ipha->ipha_dst != ilm->ilm_addr ||
22264 				    ilm->ilm_zoneid == last_zoneid ||
22265 				    ilm->ilm_zoneid == zoneid ||
22266 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
22267 					continue;
22268 				mp1 = ip_copymsg(first_mp);
22269 				if (mp1 == NULL)
22270 					continue;
22271 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22272 				    mctl_present, B_FALSE, ill,
22273 				    ilm->ilm_zoneid);
22274 				last_zoneid = ilm->ilm_zoneid;
22275 			}
22276 			ILM_WALKER_RELE(ill);
22277 			/*
22278 			 * Loopback case: the sending endpoint has
22279 			 * IP_MULTICAST_LOOP disabled, therefore we don't
22280 			 * dispatch the multicast packet to the sending zone.
22281 			 */
22282 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
22283 				freemsg(first_mp);
22284 				return;
22285 			}
22286 		} else if (ire_type == IRE_BROADCAST) {
22287 			/*
22288 			 * In the broadcast case, there may be many zones
22289 			 * which need a copy of the packet delivered to them.
22290 			 * There is one IRE_BROADCAST per broadcast address
22291 			 * and per zone; we walk those using a helper function.
22292 			 * In addition, the sending of the packet for zoneid is
22293 			 * delayed until all of the other ires have been
22294 			 * processed.
22295 			 */
22296 			IRB_REFHOLD(ire->ire_bucket);
22297 			ire_zone = NULL;
22298 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
22299 			    ire)) != NULL) {
22300 				mp1 = ip_copymsg(first_mp);
22301 				if (mp1 == NULL)
22302 					continue;
22303 
22304 				UPDATE_IB_PKT_COUNT(ire_zone);
22305 				ire_zone->ire_last_used_time = lbolt;
22306 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
22307 				    mctl_present, B_FALSE, ill,
22308 				    ire_zone->ire_zoneid);
22309 			}
22310 			IRB_REFRELE(ire->ire_bucket);
22311 		}
22312 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
22313 		    0, mctl_present, B_FALSE, ill, zoneid);
22314 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22315 		    "ip_wput_local_end: q %p (%S)",
22316 		    q, "icmp");
22317 		return;
22318 	}
22319 	case IPPROTO_IGMP:
22320 		if (igmp_input(q, mp, ill)) {
22321 			/* Bad packet - discarded by igmp_input */
22322 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22323 			    "ip_wput_local_end: q %p (%S)",
22324 			    q, "igmp_input--bad packet");
22325 			if (mctl_present)
22326 				freeb(first_mp);
22327 			return;
22328 		}
22329 		/*
22330 		 * igmp_input() may have pulled up the message so ipha needs to
22331 		 * be reinitialized.
22332 		 */
22333 		ipha = (ipha_t *)mp->b_rptr;
22334 		/* deliver to local raw users */
22335 		break;
22336 	case IPPROTO_ENCAP:
22337 		/*
22338 		 * This case is covered by either ip_fanout_proto, or by
22339 		 * the above security processing for self-tunneled packets.
22340 		 */
22341 		break;
22342 	case IPPROTO_UDP: {
22343 		uint16_t	*up;
22344 		uint32_t	ports;
22345 
22346 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
22347 		    UDP_PORTS_OFFSET);
22348 		/* Force a 'valid' checksum. */
22349 		up[3] = 0;
22350 
22351 		ports = *(uint32_t *)up;
22352 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
22353 		    (ire_type == IRE_BROADCAST),
22354 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22355 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
22356 		    ill, zoneid);
22357 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22358 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
22359 		return;
22360 	}
22361 	case IPPROTO_TCP: {
22362 
22363 		/*
22364 		 * For TCP, discard broadcast packets.
22365 		 */
22366 		if ((ushort_t)ire_type == IRE_BROADCAST) {
22367 			freemsg(first_mp);
22368 			BUMP_MIB(&ip_mib, ipInDiscards);
22369 			return;
22370 		}
22371 
22372 		if (mp->b_datap->db_type == M_DATA) {
22373 			/*
22374 			 * M_DATA mblk, so init mblk (chain) for no struio().
22375 			 */
22376 			mblk_t	*mp1 = mp;
22377 
22378 			do
22379 				mp1->b_datap->db_struioflag = 0;
22380 			while ((mp1 = mp1->b_cont) != NULL);
22381 		}
22382 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
22383 		    <= mp->b_wptr);
22384 		ip_fanout_tcp(q, first_mp, ill, ipha,
22385 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22386 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
22387 		    mctl_present, B_FALSE, zoneid);
22388 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22389 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
22390 		return;
22391 	}
22392 	case IPPROTO_SCTP:
22393 	{
22394 		uint32_t	ports;
22395 
22396 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
22397 		ip_fanout_sctp(first_mp, ill, ipha, ports,
22398 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
22399 		    IP_FF_IP6INFO,
22400 		    mctl_present, B_FALSE, 0, zoneid);
22401 		return;
22402 	}
22403 
22404 	default:
22405 		break;
22406 	}
22407 	/*
22408 	 * Find a client for some other protocol.  We give
22409 	 * copies to multiple clients, if more than one is
22410 	 * bound.
22411 	 */
22412 	ip_fanout_proto(q, first_mp, ill, ipha,
22413 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
22414 	    mctl_present, B_FALSE, ill, zoneid);
22415 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
22416 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
22417 #undef	rptr
22418 }
22419 
22420 /*
22421  * Update any source route, record route, or timestamp options.
22422  * Check that we are at end of strict source route.
22423  * The options have been sanity checked by ip_wput_options().
22424  */
22425 static void
22426 ip_wput_local_options(ipha_t *ipha)
22427 {
22428 	ipoptp_t	opts;
22429 	uchar_t		*opt;
22430 	uint8_t		optval;
22431 	uint8_t		optlen;
22432 	ipaddr_t	dst;
22433 	uint32_t	ts;
22434 	ire_t		*ire;
22435 	timestruc_t	now;
22436 
22437 	ip2dbg(("ip_wput_local_options\n"));
22438 	for (optval = ipoptp_first(&opts, ipha);
22439 	    optval != IPOPT_EOL;
22440 	    optval = ipoptp_next(&opts)) {
22441 		opt = opts.ipoptp_cur;
22442 		optlen = opts.ipoptp_len;
22443 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22444 		switch (optval) {
22445 			uint32_t off;
22446 		case IPOPT_SSRR:
22447 		case IPOPT_LSRR:
22448 			off = opt[IPOPT_OFFSET];
22449 			off--;
22450 			if (optlen < IP_ADDR_LEN ||
22451 			    off > optlen - IP_ADDR_LEN) {
22452 				/* End of source route */
22453 				break;
22454 			}
22455 			/*
22456 			 * This will only happen if two consecutive entries
22457 			 * in the source route contains our address or if
22458 			 * it is a packet with a loose source route which
22459 			 * reaches us before consuming the whole source route
22460 			 */
22461 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22462 			if (optval == IPOPT_SSRR) {
22463 				return;
22464 			}
22465 			/*
22466 			 * Hack: instead of dropping the packet truncate the
22467 			 * source route to what has been used by filling the
22468 			 * rest with IPOPT_NOP.
22469 			 */
22470 			opt[IPOPT_OLEN] = (uint8_t)off;
22471 			while (off < optlen) {
22472 				opt[off++] = IPOPT_NOP;
22473 			}
22474 			break;
22475 		case IPOPT_RR:
22476 			off = opt[IPOPT_OFFSET];
22477 			off--;
22478 			if (optlen < IP_ADDR_LEN ||
22479 			    off > optlen - IP_ADDR_LEN) {
22480 				/* No more room - ignore */
22481 				ip1dbg((
22482 				    "ip_wput_forward_options: end of RR\n"));
22483 				break;
22484 			}
22485 			dst = htonl(INADDR_LOOPBACK);
22486 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22487 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22488 			break;
22489 		case IPOPT_TS:
22490 			/* Insert timestamp if there is romm */
22491 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22492 			case IPOPT_TS_TSONLY:
22493 				off = IPOPT_TS_TIMELEN;
22494 				break;
22495 			case IPOPT_TS_PRESPEC:
22496 			case IPOPT_TS_PRESPEC_RFC791:
22497 				/* Verify that the address matched */
22498 				off = opt[IPOPT_OFFSET] - 1;
22499 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22500 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22501 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22502 				if (ire == NULL) {
22503 					/* Not for us */
22504 					break;
22505 				}
22506 				ire_refrele(ire);
22507 				/* FALLTHRU */
22508 			case IPOPT_TS_TSANDADDR:
22509 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22510 				break;
22511 			default:
22512 				/*
22513 				 * ip_*put_options should have already
22514 				 * dropped this packet.
22515 				 */
22516 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22517 				    "unknown IT - bug in ip_wput_options?\n");
22518 				return;	/* Keep "lint" happy */
22519 			}
22520 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22521 				/* Increase overflow counter */
22522 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22523 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22524 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22525 				    (off << 4);
22526 				break;
22527 			}
22528 			off = opt[IPOPT_OFFSET] - 1;
22529 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22530 			case IPOPT_TS_PRESPEC:
22531 			case IPOPT_TS_PRESPEC_RFC791:
22532 			case IPOPT_TS_TSANDADDR:
22533 				dst = htonl(INADDR_LOOPBACK);
22534 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22535 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22536 				/* FALLTHRU */
22537 			case IPOPT_TS_TSONLY:
22538 				off = opt[IPOPT_OFFSET] - 1;
22539 				/* Compute # of milliseconds since midnight */
22540 				gethrestime(&now);
22541 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22542 				    now.tv_nsec / (NANOSEC / MILLISEC);
22543 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22544 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22545 				break;
22546 			}
22547 			break;
22548 		}
22549 	}
22550 }
22551 
22552 /*
22553  * Send out a multicast packet on interface ipif.
22554  * The sender does not have an conn.
22555  * Caller verifies that this isn't a PHYI_LOOPBACK.
22556  */
22557 void
22558 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22559 {
22560 	ipha_t	*ipha;
22561 	ire_t	*ire;
22562 	ipaddr_t	dst;
22563 	mblk_t		*first_mp;
22564 
22565 	/* igmp_sendpkt always allocates a ipsec_out_t */
22566 	ASSERT(mp->b_datap->db_type == M_CTL);
22567 	ASSERT(!ipif->ipif_isv6);
22568 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22569 
22570 	first_mp = mp;
22571 	mp = first_mp->b_cont;
22572 	ASSERT(mp->b_datap->db_type == M_DATA);
22573 	ipha = (ipha_t *)mp->b_rptr;
22574 
22575 	/*
22576 	 * Find an IRE which matches the destination and the outgoing
22577 	 * queue (i.e. the outgoing interface.)
22578 	 */
22579 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22580 		dst = ipif->ipif_pp_dst_addr;
22581 	else
22582 		dst = ipha->ipha_dst;
22583 	/*
22584 	 * The source address has already been initialized by the
22585 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22586 	 * be sufficient rather than MATCH_IRE_IPIF.
22587 	 *
22588 	 * This function is used for sending IGMP packets. We need
22589 	 * to make sure that we send the packet out of the interface
22590 	 * (ipif->ipif_ill) where we joined the group. This is to
22591 	 * prevent from switches doing IGMP snooping to send us multicast
22592 	 * packets for a given group on the interface we have joined.
22593 	 * If we can't find an ire, igmp_sendpkt has already initialized
22594 	 * ipsec_out_attach_if so that this will not be load spread in
22595 	 * ip_newroute_ipif.
22596 	 */
22597 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22598 	if (!ire) {
22599 		/*
22600 		 * Mark this packet to make it be delivered to
22601 		 * ip_wput_ire after the new ire has been
22602 		 * created.
22603 		 */
22604 		mp->b_prev = NULL;
22605 		mp->b_next = NULL;
22606 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22607 		return;
22608 	}
22609 
22610 	/*
22611 	 * Honor the RTF_SETSRC flag; this is the only case
22612 	 * where we force this addr whatever the current src addr is,
22613 	 * because this address is set by igmp_sendpkt(), and
22614 	 * cannot be specified by any user.
22615 	 */
22616 	if (ire->ire_flags & RTF_SETSRC) {
22617 		ipha->ipha_src = ire->ire_src_addr;
22618 	}
22619 
22620 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22621 }
22622 
22623 /*
22624  * NOTE : This function does not ire_refrele the ire argument passed in.
22625  *
22626  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22627  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22628  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22629  * the ire_lock to access the ire_fp_mp in this case.
22630  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22631  * prepending a fastpath message IPQoS processing must precede it, we also set
22632  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22633  * (IPQoS might have set the b_band for CoS marking).
22634  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22635  * must follow it so that IPQoS can mark the dl_priority field for CoS
22636  * marking, if needed.
22637  */
22638 static mblk_t *
22639 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22640 {
22641 	uint_t	hlen;
22642 	ipha_t *ipha;
22643 	mblk_t *mp1;
22644 	boolean_t qos_done = B_FALSE;
22645 	uchar_t	*ll_hdr;
22646 
22647 #define	rptr	((uchar_t *)ipha)
22648 
22649 	ipha = (ipha_t *)mp->b_rptr;
22650 	hlen = 0;
22651 	LOCK_IRE_FP_MP(ire);
22652 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22653 		ASSERT(DB_TYPE(mp1) == M_DATA);
22654 		/* Initiate IPPF processing */
22655 		if ((proc != 0) && IPP_ENABLED(proc)) {
22656 			UNLOCK_IRE_FP_MP(ire);
22657 			ip_process(proc, &mp, ill_index);
22658 			if (mp == NULL)
22659 				return (NULL);
22660 
22661 			ipha = (ipha_t *)mp->b_rptr;
22662 			LOCK_IRE_FP_MP(ire);
22663 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22664 				qos_done = B_TRUE;
22665 				goto no_fp_mp;
22666 			}
22667 			ASSERT(DB_TYPE(mp1) == M_DATA);
22668 		}
22669 		hlen = MBLKL(mp1);
22670 		/*
22671 		 * Check if we have enough room to prepend fastpath
22672 		 * header
22673 		 */
22674 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22675 			ll_hdr = rptr - hlen;
22676 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22677 			/* XXX ipha is not aligned here */
22678 			ipha = (ipha_t *)(rptr - hlen);
22679 			/*
22680 			 * Set the b_rptr to the start of the link layer
22681 			 * header
22682 			 */
22683 			mp->b_rptr = rptr;
22684 			mp1 = mp;
22685 		} else {
22686 			mp1 = copyb(mp1);
22687 			if (mp1 == NULL)
22688 				goto unlock_err;
22689 			mp1->b_band = mp->b_band;
22690 			mp1->b_cont = mp;
22691 			/*
22692 			 * XXX disable ICK_VALID and compute checksum
22693 			 * here; can happen if ire_fp_mp changes and
22694 			 * it can't be copied now due to insufficient
22695 			 * space. (unlikely, fp mp can change, but it
22696 			 * does not increase in length)
22697 			 */
22698 		}
22699 		UNLOCK_IRE_FP_MP(ire);
22700 	} else {
22701 no_fp_mp:
22702 		mp1 = copyb(ire->ire_dlureq_mp);
22703 		if (mp1 == NULL) {
22704 unlock_err:
22705 			UNLOCK_IRE_FP_MP(ire);
22706 			freemsg(mp);
22707 			return (NULL);
22708 		}
22709 		UNLOCK_IRE_FP_MP(ire);
22710 		mp1->b_cont = mp;
22711 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22712 			ip_process(proc, &mp1, ill_index);
22713 			if (mp1 == NULL)
22714 				return (NULL);
22715 		}
22716 	}
22717 	return (mp1);
22718 #undef rptr
22719 }
22720 
22721 /*
22722  * Finish the outbound IPsec processing for an IPv6 packet. This function
22723  * is called from ipsec_out_process() if the IPsec packet was processed
22724  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22725  * asynchronously.
22726  */
22727 void
22728 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22729     ire_t *ire_arg)
22730 {
22731 	in6_addr_t *v6dstp;
22732 	ire_t *ire;
22733 	mblk_t *mp;
22734 	uint_t	ill_index;
22735 	ipsec_out_t *io;
22736 	boolean_t attach_if, hwaccel;
22737 	uint32_t flags = IP6_NO_IPPOLICY;
22738 	int match_flags;
22739 	zoneid_t zoneid;
22740 	boolean_t ill_need_rele = B_FALSE;
22741 	boolean_t ire_need_rele = B_FALSE;
22742 
22743 	mp = ipsec_mp->b_cont;
22744 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22745 	ill_index = io->ipsec_out_ill_index;
22746 	if (io->ipsec_out_reachable) {
22747 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22748 	}
22749 	attach_if = io->ipsec_out_attach_if;
22750 	hwaccel = io->ipsec_out_accelerated;
22751 	zoneid = io->ipsec_out_zoneid;
22752 	ASSERT(zoneid != ALL_ZONES);
22753 	match_flags = MATCH_IRE_ILL_GROUP;
22754 	/* Multicast addresses should have non-zero ill_index. */
22755 	v6dstp = &ip6h->ip6_dst;
22756 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22757 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22758 	ASSERT(!attach_if || ill_index != 0);
22759 	if (ill_index != 0) {
22760 		if (ill == NULL) {
22761 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22762 			    B_TRUE);
22763 
22764 			/* Failure case frees things for us. */
22765 			if (ill == NULL)
22766 				return;
22767 
22768 			ill_need_rele = B_TRUE;
22769 		}
22770 		/*
22771 		 * If this packet needs to go out on a particular interface
22772 		 * honor it.
22773 		 */
22774 		if (attach_if) {
22775 			match_flags = MATCH_IRE_ILL;
22776 
22777 			/*
22778 			 * Check if we need an ire that will not be
22779 			 * looked up by anybody else i.e. HIDDEN.
22780 			 */
22781 			if (ill_is_probeonly(ill)) {
22782 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22783 			}
22784 		}
22785 	}
22786 	ASSERT(mp != NULL);
22787 
22788 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22789 		boolean_t unspec_src;
22790 		ipif_t	*ipif;
22791 
22792 		/*
22793 		 * Use the ill_index to get the right ill.
22794 		 */
22795 		unspec_src = io->ipsec_out_unspec_src;
22796 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22797 		if (ipif == NULL) {
22798 			if (ill_need_rele)
22799 				ill_refrele(ill);
22800 			freemsg(ipsec_mp);
22801 			return;
22802 		}
22803 
22804 		if (ire_arg != NULL) {
22805 			ire = ire_arg;
22806 		} else {
22807 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22808 			    zoneid, match_flags);
22809 			ire_need_rele = B_TRUE;
22810 		}
22811 		if (ire != NULL) {
22812 			ipif_refrele(ipif);
22813 			/*
22814 			 * XXX Do the multicast forwarding now, as the IPSEC
22815 			 * processing has been done.
22816 			 */
22817 			goto send;
22818 		}
22819 
22820 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22821 		mp->b_prev = NULL;
22822 		mp->b_next = NULL;
22823 
22824 		/*
22825 		 * If the IPsec packet was processed asynchronously,
22826 		 * drop it now.
22827 		 */
22828 		if (q == NULL) {
22829 			if (ill_need_rele)
22830 				ill_refrele(ill);
22831 			freemsg(ipsec_mp);
22832 			return;
22833 		}
22834 
22835 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22836 		    unspec_src, zoneid);
22837 		ipif_refrele(ipif);
22838 	} else {
22839 		if (attach_if) {
22840 			ipif_t	*ipif;
22841 
22842 			ipif = ipif_get_next_ipif(NULL, ill);
22843 			if (ipif == NULL) {
22844 				if (ill_need_rele)
22845 					ill_refrele(ill);
22846 				freemsg(ipsec_mp);
22847 				return;
22848 			}
22849 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22850 			    zoneid, match_flags);
22851 			ire_need_rele = B_TRUE;
22852 			ipif_refrele(ipif);
22853 		} else {
22854 			if (ire_arg != NULL) {
22855 				ire = ire_arg;
22856 			} else {
22857 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22858 				ire_need_rele = B_TRUE;
22859 			}
22860 		}
22861 		if (ire != NULL)
22862 			goto send;
22863 		/*
22864 		 * ire disappeared underneath.
22865 		 *
22866 		 * What we need to do here is the ip_newroute
22867 		 * logic to get the ire without doing the IPSEC
22868 		 * processing. Follow the same old path. But this
22869 		 * time, ip_wput or ire_add_then_send will call us
22870 		 * directly as all the IPSEC operations are done.
22871 		 */
22872 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22873 		mp->b_prev = NULL;
22874 		mp->b_next = NULL;
22875 
22876 		/*
22877 		 * If the IPsec packet was processed asynchronously,
22878 		 * drop it now.
22879 		 */
22880 		if (q == NULL) {
22881 			if (ill_need_rele)
22882 				ill_refrele(ill);
22883 			freemsg(ipsec_mp);
22884 			return;
22885 		}
22886 
22887 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22888 		    zoneid);
22889 	}
22890 	if (ill != NULL && ill_need_rele)
22891 		ill_refrele(ill);
22892 	return;
22893 send:
22894 	if (ill != NULL && ill_need_rele)
22895 		ill_refrele(ill);
22896 
22897 	/* Local delivery */
22898 	if (ire->ire_stq == NULL) {
22899 		ASSERT(q != NULL);
22900 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22901 		    ire, 0);
22902 		if (ire_need_rele)
22903 			ire_refrele(ire);
22904 		return;
22905 	}
22906 	/*
22907 	 * Everything is done. Send it out on the wire.
22908 	 * We force the insertion of a fragment header using the
22909 	 * IPH_FRAG_HDR flag in two cases:
22910 	 * - after reception of an ICMPv6 "packet too big" message
22911 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22912 	 * - for multirouted IPv6 packets, so that the receiver can
22913 	 *   discard duplicates according to their fragment identifier
22914 	 */
22915 	/* XXX fix flow control problems. */
22916 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22917 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22918 		if (hwaccel) {
22919 			/*
22920 			 * hardware acceleration does not handle these
22921 			 * "slow path" cases.
22922 			 */
22923 			/* IPsec KSTATS: should bump bean counter here. */
22924 			if (ire_need_rele)
22925 				ire_refrele(ire);
22926 			freemsg(ipsec_mp);
22927 			return;
22928 		}
22929 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22930 		    (mp->b_cont ? msgdsize(mp) :
22931 		    mp->b_wptr - (uchar_t *)ip6h)) {
22932 			/* IPsec KSTATS: should bump bean counter here. */
22933 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22934 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22935 			    msgdsize(mp)));
22936 			if (ire_need_rele)
22937 				ire_refrele(ire);
22938 			freemsg(ipsec_mp);
22939 			return;
22940 		}
22941 		ASSERT(mp->b_prev == NULL);
22942 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22943 		    ntohs(ip6h->ip6_plen) +
22944 		    IPV6_HDR_LEN, ire->ire_max_frag));
22945 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22946 		    ire->ire_max_frag);
22947 	} else {
22948 		UPDATE_OB_PKT_COUNT(ire);
22949 		ire->ire_last_used_time = lbolt;
22950 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22951 	}
22952 	if (ire_need_rele)
22953 		ire_refrele(ire);
22954 	freeb(ipsec_mp);
22955 }
22956 
22957 void
22958 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
22959 {
22960 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
22961 	da_ipsec_t *hada;	/* data attributes */
22962 	ill_t *ill = (ill_t *)q->q_ptr;
22963 
22964 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
22965 
22966 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
22967 		/* IPsec KSTATS: Bump lose counter here! */
22968 		freemsg(mp);
22969 		return;
22970 	}
22971 
22972 	/*
22973 	 * It's an IPsec packet that must be
22974 	 * accelerated by the Provider, and the
22975 	 * outbound ill is IPsec acceleration capable.
22976 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
22977 	 * to the ill.
22978 	 * IPsec KSTATS: should bump packet counter here.
22979 	 */
22980 
22981 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
22982 	if (hada_mp == NULL) {
22983 		/* IPsec KSTATS: should bump packet counter here. */
22984 		freemsg(mp);
22985 		return;
22986 	}
22987 
22988 	hada_mp->b_datap->db_type = M_CTL;
22989 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
22990 	hada_mp->b_cont = mp;
22991 
22992 	hada = (da_ipsec_t *)hada_mp->b_rptr;
22993 	bzero(hada, sizeof (da_ipsec_t));
22994 	hada->da_type = IPHADA_M_CTL;
22995 
22996 	putnext(q, hada_mp);
22997 }
22998 
22999 /*
23000  * Finish the outbound IPsec processing. This function is called from
23001  * ipsec_out_process() if the IPsec packet was processed
23002  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23003  * asynchronously.
23004  */
23005 void
23006 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23007     ire_t *ire_arg)
23008 {
23009 	uint32_t v_hlen_tos_len;
23010 	ipaddr_t	dst;
23011 	ipif_t	*ipif = NULL;
23012 	ire_t *ire;
23013 	ire_t *ire1 = NULL;
23014 	mblk_t *next_mp = NULL;
23015 	uint32_t max_frag;
23016 	boolean_t multirt_send = B_FALSE;
23017 	mblk_t *mp;
23018 	mblk_t *mp1;
23019 	uint_t	ill_index;
23020 	ipsec_out_t *io;
23021 	boolean_t attach_if;
23022 	int match_flags, offset;
23023 	irb_t *irb = NULL;
23024 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23025 	zoneid_t zoneid;
23026 	uint32_t cksum;
23027 	uint16_t *up;
23028 #ifdef	_BIG_ENDIAN
23029 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23030 #else
23031 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23032 #endif
23033 
23034 	mp = ipsec_mp->b_cont;
23035 	ASSERT(mp != NULL);
23036 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23037 	dst = ipha->ipha_dst;
23038 
23039 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23040 	ill_index = io->ipsec_out_ill_index;
23041 	attach_if = io->ipsec_out_attach_if;
23042 	zoneid = io->ipsec_out_zoneid;
23043 	ASSERT(zoneid != ALL_ZONES);
23044 	match_flags = MATCH_IRE_ILL_GROUP;
23045 	if (ill_index != 0) {
23046 		if (ill == NULL) {
23047 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23048 			    ill_index, B_FALSE);
23049 
23050 			/* Failure case frees things for us. */
23051 			if (ill == NULL)
23052 				return;
23053 
23054 			ill_need_rele = B_TRUE;
23055 		}
23056 		/*
23057 		 * If this packet needs to go out on a particular interface
23058 		 * honor it.
23059 		 */
23060 		if (attach_if) {
23061 			match_flags = MATCH_IRE_ILL;
23062 
23063 			/*
23064 			 * Check if we need an ire that will not be
23065 			 * looked up by anybody else i.e. HIDDEN.
23066 			 */
23067 			if (ill_is_probeonly(ill)) {
23068 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23069 			}
23070 		}
23071 	}
23072 
23073 	if (CLASSD(dst)) {
23074 		boolean_t conn_dontroute;
23075 		/*
23076 		 * Use the ill_index to get the right ipif.
23077 		 */
23078 		conn_dontroute = io->ipsec_out_dontroute;
23079 		if (ill_index == 0)
23080 			ipif = ipif_lookup_group(dst, zoneid);
23081 		else
23082 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23083 		if (ipif == NULL) {
23084 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23085 			    " multicast\n"));
23086 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23087 			freemsg(ipsec_mp);
23088 			goto done;
23089 		}
23090 		/*
23091 		 * ipha_src has already been intialized with the
23092 		 * value of the ipif in ip_wput. All we need now is
23093 		 * an ire to send this downstream.
23094 		 */
23095 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
23096 		if (ire != NULL) {
23097 			ill_t *ill1;
23098 			/*
23099 			 * Do the multicast forwarding now, as the IPSEC
23100 			 * processing has been done.
23101 			 */
23102 			if (ip_g_mrouter && !conn_dontroute &&
23103 			    (ill1 = ire_to_ill(ire))) {
23104 				if (ip_mforward(ill1, ipha, mp)) {
23105 					freemsg(ipsec_mp);
23106 					ip1dbg(("ip_wput_ipsec_out: mforward "
23107 					    "failed\n"));
23108 					ire_refrele(ire);
23109 					goto done;
23110 				}
23111 			}
23112 			goto send;
23113 		}
23114 
23115 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23116 		mp->b_prev = NULL;
23117 		mp->b_next = NULL;
23118 
23119 		/*
23120 		 * If the IPsec packet was processed asynchronously,
23121 		 * drop it now.
23122 		 */
23123 		if (q == NULL) {
23124 			freemsg(ipsec_mp);
23125 			goto done;
23126 		}
23127 
23128 		/*
23129 		 * We may be using a wrong ipif to create the ire.
23130 		 * But it is okay as the source address is assigned
23131 		 * for the packet already. Next outbound packet would
23132 		 * create the IRE with the right IPIF in ip_wput.
23133 		 *
23134 		 * Also handle RTF_MULTIRT routes.
23135 		 */
23136 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
23137 	} else {
23138 		if (attach_if) {
23139 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
23140 			    zoneid, match_flags);
23141 		} else {
23142 			if (ire_arg != NULL) {
23143 				ire = ire_arg;
23144 				ire_need_rele = B_FALSE;
23145 			} else {
23146 				ire = ire_cache_lookup(dst, zoneid);
23147 			}
23148 		}
23149 		if (ire != NULL) {
23150 			goto send;
23151 		}
23152 
23153 		/*
23154 		 * ire disappeared underneath.
23155 		 *
23156 		 * What we need to do here is the ip_newroute
23157 		 * logic to get the ire without doing the IPSEC
23158 		 * processing. Follow the same old path. But this
23159 		 * time, ip_wput or ire_add_then_put will call us
23160 		 * directly as all the IPSEC operations are done.
23161 		 */
23162 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
23163 		mp->b_prev = NULL;
23164 		mp->b_next = NULL;
23165 
23166 		/*
23167 		 * If the IPsec packet was processed asynchronously,
23168 		 * drop it now.
23169 		 */
23170 		if (q == NULL) {
23171 			freemsg(ipsec_mp);
23172 			goto done;
23173 		}
23174 
23175 		/*
23176 		 * Since we're going through ip_newroute() again, we
23177 		 * need to make sure we don't:
23178 		 *
23179 		 *	1.) Trigger the ASSERT() with the ipha_ident
23180 		 *	    overloading.
23181 		 *	2.) Redo transport-layer checksumming, since we've
23182 		 *	    already done all that to get this far.
23183 		 *
23184 		 * The easiest way not do either of the above is to set
23185 		 * the ipha_ident field to IP_HDR_INCLUDED.
23186 		 */
23187 		ipha->ipha_ident = IP_HDR_INCLUDED;
23188 		ip_newroute(q, ipsec_mp, dst, NULL,
23189 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
23190 	}
23191 	goto done;
23192 send:
23193 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
23194 		/*
23195 		 * ESP NAT-Traversal packet.
23196 		 *
23197 		 * Just do software checksum for now.
23198 		 */
23199 
23200 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
23201 		IP_STAT(ip_out_sw_cksum);
23202 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
23203 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
23204 #define	iphs	((uint16_t *)ipha)
23205 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
23206 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
23207 		    IP_SIMPLE_HDR_LENGTH);
23208 #undef iphs
23209 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
23210 			cksum = 0xFFFF;
23211 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
23212 			if (mp1->b_wptr - mp1->b_rptr >=
23213 			    offset + sizeof (uint16_t)) {
23214 				up = (uint16_t *)(mp1->b_rptr + offset);
23215 				*up = cksum;
23216 				break;	/* out of for loop */
23217 			} else {
23218 				offset -= (mp->b_wptr - mp->b_rptr);
23219 			}
23220 	} /* Otherwise, just keep the all-zero checksum. */
23221 
23222 	if (ire->ire_stq == NULL) {
23223 		/*
23224 		 * Loopbacks go through ip_wput_local except for one case.
23225 		 * We come here if we generate a icmp_frag_needed message
23226 		 * after IPSEC processing is over. When this function calls
23227 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
23228 		 * icmp_frag_needed. The message generated comes back here
23229 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
23230 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
23231 		 * source address as it is usually set in ip_wput_ire. As
23232 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
23233 		 * and we end up here. We can't enter ip_wput_ire once the
23234 		 * IPSEC processing is over and hence we need to do it here.
23235 		 */
23236 		ASSERT(q != NULL);
23237 		UPDATE_OB_PKT_COUNT(ire);
23238 		ire->ire_last_used_time = lbolt;
23239 		if (ipha->ipha_src == 0)
23240 			ipha->ipha_src = ire->ire_src_addr;
23241 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
23242 		    ire, 0, zoneid);
23243 		if (ire_need_rele)
23244 			ire_refrele(ire);
23245 		goto done;
23246 	}
23247 
23248 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
23249 		/*
23250 		 * We are through with IPSEC processing.
23251 		 * Fragment this and send it on the wire.
23252 		 */
23253 		if (io->ipsec_out_accelerated) {
23254 			/*
23255 			 * The packet has been accelerated but must
23256 			 * be fragmented. This should not happen
23257 			 * since AH and ESP must not accelerate
23258 			 * packets that need fragmentation, however
23259 			 * the configuration could have changed
23260 			 * since the AH or ESP processing.
23261 			 * Drop packet.
23262 			 * IPsec KSTATS: bump bean counter here.
23263 			 */
23264 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
23265 			    "fragmented accelerated packet!\n"));
23266 			freemsg(ipsec_mp);
23267 		} else {
23268 			ip_wput_ire_fragmentit(ipsec_mp, ire);
23269 		}
23270 		if (ire_need_rele)
23271 			ire_refrele(ire);
23272 		goto done;
23273 	}
23274 
23275 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
23276 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
23277 	    (void *)ire->ire_ipif, (void *)ipif));
23278 
23279 	/*
23280 	 * Multiroute the secured packet, unless IPsec really
23281 	 * requires the packet to go out only through a particular
23282 	 * interface.
23283 	 */
23284 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
23285 		ire_t *first_ire;
23286 		irb = ire->ire_bucket;
23287 		ASSERT(irb != NULL);
23288 		/*
23289 		 * This ire has been looked up as the one that
23290 		 * goes through the given ipif;
23291 		 * make sure we do not omit any other multiroute ire
23292 		 * that may be present in the bucket before this one.
23293 		 */
23294 		IRB_REFHOLD(irb);
23295 		for (first_ire = irb->irb_ire;
23296 		    first_ire != NULL;
23297 		    first_ire = first_ire->ire_next) {
23298 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23299 			    (first_ire->ire_addr == ire->ire_addr) &&
23300 			    !(first_ire->ire_marks &
23301 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23302 				break;
23303 		}
23304 
23305 		if ((first_ire != NULL) && (first_ire != ire)) {
23306 			/*
23307 			 * Don't change the ire if the packet must
23308 			 * be fragmented if sent via this new one.
23309 			 */
23310 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
23311 				IRE_REFHOLD(first_ire);
23312 				if (ire_need_rele)
23313 					ire_refrele(ire);
23314 				else
23315 					ire_need_rele = B_TRUE;
23316 				ire = first_ire;
23317 			}
23318 		}
23319 		IRB_REFRELE(irb);
23320 
23321 		multirt_send = B_TRUE;
23322 		max_frag = ire->ire_max_frag;
23323 	} else {
23324 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
23325 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
23326 			    "flag, attach_if %d\n", attach_if));
23327 		}
23328 	}
23329 
23330 	/*
23331 	 * In most cases, the emission loop below is entered only once.
23332 	 * Only in the case where the ire holds the RTF_MULTIRT
23333 	 * flag, we loop to process all RTF_MULTIRT ires in the
23334 	 * bucket, and send the packet through all crossed
23335 	 * RTF_MULTIRT routes.
23336 	 */
23337 	do {
23338 		if (multirt_send) {
23339 			/*
23340 			 * ire1 holds here the next ire to process in the
23341 			 * bucket. If multirouting is expected,
23342 			 * any non-RTF_MULTIRT ire that has the
23343 			 * right destination address is ignored.
23344 			 */
23345 			ASSERT(irb != NULL);
23346 			IRB_REFHOLD(irb);
23347 			for (ire1 = ire->ire_next;
23348 			    ire1 != NULL;
23349 			    ire1 = ire1->ire_next) {
23350 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23351 					continue;
23352 				if (ire1->ire_addr != ire->ire_addr)
23353 					continue;
23354 				if (ire1->ire_marks &
23355 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23356 					continue;
23357 				/* No loopback here */
23358 				if (ire1->ire_stq == NULL)
23359 					continue;
23360 				/*
23361 				 * Ensure we do not exceed the MTU
23362 				 * of the next route.
23363 				 */
23364 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
23365 					ip_multirt_bad_mtu(ire1, max_frag);
23366 					continue;
23367 				}
23368 
23369 				IRE_REFHOLD(ire1);
23370 				break;
23371 			}
23372 			IRB_REFRELE(irb);
23373 			if (ire1 != NULL) {
23374 				/*
23375 				 * We are in a multiple send case, need to
23376 				 * make a copy of the packet.
23377 				 */
23378 				next_mp = copymsg(ipsec_mp);
23379 				if (next_mp == NULL) {
23380 					ire_refrele(ire1);
23381 					ire1 = NULL;
23382 				}
23383 			}
23384 		}
23385 
23386 		/* Everything is done. Send it out on the wire */
23387 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
23388 		if (mp1 == NULL) {
23389 			BUMP_MIB(&ip_mib, ipOutDiscards);
23390 			freemsg(ipsec_mp);
23391 			if (ire_need_rele)
23392 				ire_refrele(ire);
23393 			if (ire1 != NULL) {
23394 				ire_refrele(ire1);
23395 				freemsg(next_mp);
23396 			}
23397 			goto done;
23398 		}
23399 		UPDATE_OB_PKT_COUNT(ire);
23400 		ire->ire_last_used_time = lbolt;
23401 		if (!io->ipsec_out_accelerated) {
23402 			putnext(ire->ire_stq, mp1);
23403 		} else {
23404 			/*
23405 			 * Safety Pup says: make sure this is going to
23406 			 * the right interface!
23407 			 */
23408 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
23409 			int ifindex = ill1->ill_phyint->phyint_ifindex;
23410 
23411 			if (ifindex != io->ipsec_out_capab_ill_index) {
23412 				/* IPsec kstats: bump lose counter */
23413 				freemsg(mp1);
23414 			} else {
23415 				ipsec_hw_putnext(ire->ire_stq, mp1);
23416 			}
23417 		}
23418 
23419 		freeb(ipsec_mp);
23420 		if (ire_need_rele)
23421 			ire_refrele(ire);
23422 
23423 		if (ire1 != NULL) {
23424 			ire = ire1;
23425 			ire_need_rele = B_TRUE;
23426 			ASSERT(next_mp);
23427 			ipsec_mp = next_mp;
23428 			mp = ipsec_mp->b_cont;
23429 			ire1 = NULL;
23430 			next_mp = NULL;
23431 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
23432 		} else {
23433 			multirt_send = B_FALSE;
23434 		}
23435 	} while (multirt_send);
23436 done:
23437 	if (ill != NULL && ill_need_rele)
23438 		ill_refrele(ill);
23439 	if (ipif != NULL)
23440 		ipif_refrele(ipif);
23441 }
23442 
23443 /*
23444  * Get the ill corresponding to the specified ire, and compare its
23445  * capabilities with the protocol and algorithms specified by the
23446  * the SA obtained from ipsec_out. If they match, annotate the
23447  * ipsec_out structure to indicate that the packet needs acceleration.
23448  *
23449  *
23450  * A packet is eligible for outbound hardware acceleration if the
23451  * following conditions are satisfied:
23452  *
23453  * 1. the packet will not be fragmented
23454  * 2. the provider supports the algorithm
23455  * 3. there is no pending control message being exchanged
23456  * 4. snoop is not attached
23457  * 5. the destination address is not a broadcast or multicast address.
23458  *
23459  * Rationale:
23460  *	- Hardware drivers do not support fragmentation with
23461  *	  the current interface.
23462  *	- snoop, multicast, and broadcast may result in exposure of
23463  *	  a cleartext datagram.
23464  * We check all five of these conditions here.
23465  *
23466  * XXX would like to nuke "ire_t *" parameter here; problem is that
23467  * IRE is only way to figure out if a v4 address is a broadcast and
23468  * thus ineligible for acceleration...
23469  */
23470 static void
23471 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23472 {
23473 	ipsec_out_t *io;
23474 	mblk_t *data_mp;
23475 	uint_t plen, overhead;
23476 
23477 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23478 		return;
23479 
23480 	if (ill == NULL)
23481 		return;
23482 
23483 	/*
23484 	 * Destination address is a broadcast or multicast.  Punt.
23485 	 */
23486 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23487 	    IRE_LOCAL)))
23488 		return;
23489 
23490 	data_mp = ipsec_mp->b_cont;
23491 
23492 	if (ill->ill_isv6) {
23493 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23494 
23495 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23496 			return;
23497 
23498 		plen = ip6h->ip6_plen;
23499 	} else {
23500 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23501 
23502 		if (CLASSD(ipha->ipha_dst))
23503 			return;
23504 
23505 		plen = ipha->ipha_length;
23506 	}
23507 	/*
23508 	 * Is there a pending DLPI control message being exchanged
23509 	 * between IP/IPsec and the DLS Provider? If there is, it
23510 	 * could be a SADB update, and the state of the DLS Provider
23511 	 * SADB might not be in sync with the SADB maintained by
23512 	 * IPsec. To avoid dropping packets or using the wrong keying
23513 	 * material, we do not accelerate this packet.
23514 	 */
23515 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23516 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23517 		    "ill_dlpi_pending! don't accelerate packet\n"));
23518 		return;
23519 	}
23520 
23521 	/*
23522 	 * Is the Provider in promiscous mode? If it does, we don't
23523 	 * accelerate the packet since it will bounce back up to the
23524 	 * listeners in the clear.
23525 	 */
23526 	if (ill->ill_promisc_on_phys) {
23527 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23528 		    "ill in promiscous mode, don't accelerate packet\n"));
23529 		return;
23530 	}
23531 
23532 	/*
23533 	 * Will the packet require fragmentation?
23534 	 */
23535 
23536 	/*
23537 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23538 	 * as is used elsewhere.
23539 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23540 	 *	+ 2-byte trailer
23541 	 */
23542 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23543 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23544 
23545 	if ((plen + overhead) > ill->ill_max_mtu)
23546 		return;
23547 
23548 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23549 
23550 	/*
23551 	 * Can the ill accelerate this IPsec protocol and algorithm
23552 	 * specified by the SA?
23553 	 */
23554 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23555 	    ill->ill_isv6, sa)) {
23556 		return;
23557 	}
23558 
23559 	/*
23560 	 * Tell AH or ESP that the outbound ill is capable of
23561 	 * accelerating this packet.
23562 	 */
23563 	io->ipsec_out_is_capab_ill = B_TRUE;
23564 }
23565 
23566 /*
23567  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23568  *
23569  * If this function returns B_TRUE, the requested SA's have been filled
23570  * into the ipsec_out_*_sa pointers.
23571  *
23572  * If the function returns B_FALSE, the packet has been "consumed", most
23573  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23574  *
23575  * The SA references created by the protocol-specific "select"
23576  * function will be released when the ipsec_mp is freed, thanks to the
23577  * ipsec_out_free destructor -- see spd.c.
23578  */
23579 static boolean_t
23580 ipsec_out_select_sa(mblk_t *ipsec_mp)
23581 {
23582 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23583 	ipsec_out_t *io;
23584 	ipsec_policy_t *pp;
23585 	ipsec_action_t *ap;
23586 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23587 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23588 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23589 
23590 	if (!io->ipsec_out_secure) {
23591 		/*
23592 		 * We came here by mistake.
23593 		 * Don't bother with ipsec processing
23594 		 * We should "discourage" this path in the future.
23595 		 */
23596 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23597 		return (B_FALSE);
23598 	}
23599 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23600 	ASSERT((io->ipsec_out_policy != NULL) ||
23601 	    (io->ipsec_out_act != NULL));
23602 
23603 	ASSERT(io->ipsec_out_failed == B_FALSE);
23604 
23605 	/*
23606 	 * IPSEC processing has started.
23607 	 */
23608 	io->ipsec_out_proc_begin = B_TRUE;
23609 	ap = io->ipsec_out_act;
23610 	if (ap == NULL) {
23611 		pp = io->ipsec_out_policy;
23612 		ASSERT(pp != NULL);
23613 		ap = pp->ipsp_act;
23614 		ASSERT(ap != NULL);
23615 	}
23616 
23617 	/*
23618 	 * We have an action.  now, let's select SA's.
23619 	 * (In the future, we can cache this in the conn_t..)
23620 	 */
23621 	if (ap->ipa_want_esp) {
23622 		if (io->ipsec_out_esp_sa == NULL) {
23623 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23624 			    IPPROTO_ESP);
23625 		}
23626 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23627 	}
23628 
23629 	if (ap->ipa_want_ah) {
23630 		if (io->ipsec_out_ah_sa == NULL) {
23631 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23632 			    IPPROTO_AH);
23633 		}
23634 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23635 		/*
23636 		 * The ESP and AH processing order needs to be preserved
23637 		 * when both protocols are required (ESP should be applied
23638 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23639 		 * when both ESP and AH are required, and an AH ACQUIRE
23640 		 * is needed.
23641 		 */
23642 		if (ap->ipa_want_esp && need_ah_acquire)
23643 			need_esp_acquire = B_TRUE;
23644 	}
23645 
23646 	/*
23647 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23648 	 * Release SAs that got referenced, but will not be used until we
23649 	 * acquire _all_ of the SAs we need.
23650 	 */
23651 	if (need_ah_acquire || need_esp_acquire) {
23652 		if (io->ipsec_out_ah_sa != NULL) {
23653 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23654 			io->ipsec_out_ah_sa = NULL;
23655 		}
23656 		if (io->ipsec_out_esp_sa != NULL) {
23657 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23658 			io->ipsec_out_esp_sa = NULL;
23659 		}
23660 
23661 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23662 		return (B_FALSE);
23663 	}
23664 
23665 	return (B_TRUE);
23666 }
23667 
23668 /*
23669  * Process an IPSEC_OUT message and see what you can
23670  * do with it.
23671  * IPQoS Notes:
23672  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23673  * IPSec.
23674  * XXX would like to nuke ire_t.
23675  * XXX ill_index better be "real"
23676  */
23677 void
23678 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23679 {
23680 	ipsec_out_t *io;
23681 	ipsec_policy_t *pp;
23682 	ipsec_action_t *ap;
23683 	ipha_t *ipha;
23684 	ip6_t *ip6h;
23685 	mblk_t *mp;
23686 	ill_t *ill;
23687 	zoneid_t zoneid;
23688 	ipsec_status_t ipsec_rc;
23689 	boolean_t ill_need_rele = B_FALSE;
23690 
23691 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23692 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23693 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23694 	mp = ipsec_mp->b_cont;
23695 
23696 	/*
23697 	 * Initiate IPPF processing. We do it here to account for packets
23698 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23699 	 * We can check for ipsec_out_proc_begin even for such packets, as
23700 	 * they will always be false (asserted below).
23701 	 */
23702 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23703 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23704 		    io->ipsec_out_ill_index : ill_index);
23705 		if (mp == NULL) {
23706 			ip2dbg(("ipsec_out_process: packet dropped "\
23707 			    "during IPPF processing\n"));
23708 			freeb(ipsec_mp);
23709 			BUMP_MIB(&ip_mib, ipOutDiscards);
23710 			return;
23711 		}
23712 	}
23713 
23714 	if (!io->ipsec_out_secure) {
23715 		/*
23716 		 * We came here by mistake.
23717 		 * Don't bother with ipsec processing
23718 		 * Should "discourage" this path in the future.
23719 		 */
23720 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23721 		goto done;
23722 	}
23723 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23724 	ASSERT((io->ipsec_out_policy != NULL) ||
23725 	    (io->ipsec_out_act != NULL));
23726 	ASSERT(io->ipsec_out_failed == B_FALSE);
23727 
23728 	if (!ipsec_loaded()) {
23729 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23730 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23731 			BUMP_MIB(&ip_mib, ipOutDiscards);
23732 		} else {
23733 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23734 		}
23735 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23736 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23737 		return;
23738 	}
23739 
23740 	/*
23741 	 * IPSEC processing has started.
23742 	 */
23743 	io->ipsec_out_proc_begin = B_TRUE;
23744 	ap = io->ipsec_out_act;
23745 	if (ap == NULL) {
23746 		pp = io->ipsec_out_policy;
23747 		ASSERT(pp != NULL);
23748 		ap = pp->ipsp_act;
23749 		ASSERT(ap != NULL);
23750 	}
23751 
23752 	/*
23753 	 * Save the outbound ill index. When the packet comes back
23754 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23755 	 * before sending it the accelerated packet.
23756 	 */
23757 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23758 		int ifindex;
23759 		ill = ire_to_ill(ire);
23760 		ifindex = ill->ill_phyint->phyint_ifindex;
23761 		io->ipsec_out_capab_ill_index = ifindex;
23762 	}
23763 
23764 	/*
23765 	 * The order of processing is first insert a IP header if needed.
23766 	 * Then insert the ESP header and then the AH header.
23767 	 */
23768 	if ((io->ipsec_out_se_done == B_FALSE) &&
23769 	    (ap->ipa_want_se)) {
23770 		/*
23771 		 * First get the outer IP header before sending
23772 		 * it to ESP.
23773 		 */
23774 		ipha_t *oipha, *iipha;
23775 		mblk_t *outer_mp, *inner_mp;
23776 
23777 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23778 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23779 			    "ipsec_out_process: "
23780 			    "Self-Encapsulation failed: Out of memory\n");
23781 			freemsg(ipsec_mp);
23782 			BUMP_MIB(&ip_mib, ipOutDiscards);
23783 			return;
23784 		}
23785 		inner_mp = ipsec_mp->b_cont;
23786 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23787 		oipha = (ipha_t *)outer_mp->b_rptr;
23788 		iipha = (ipha_t *)inner_mp->b_rptr;
23789 		*oipha = *iipha;
23790 		outer_mp->b_wptr += sizeof (ipha_t);
23791 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23792 		    sizeof (ipha_t));
23793 		oipha->ipha_protocol = IPPROTO_ENCAP;
23794 		oipha->ipha_version_and_hdr_length =
23795 		    IP_SIMPLE_HDR_VERSION;
23796 		oipha->ipha_hdr_checksum = 0;
23797 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23798 		outer_mp->b_cont = inner_mp;
23799 		ipsec_mp->b_cont = outer_mp;
23800 
23801 		io->ipsec_out_se_done = B_TRUE;
23802 		io->ipsec_out_encaps = B_TRUE;
23803 	}
23804 
23805 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23806 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23807 	    !ipsec_out_select_sa(ipsec_mp))
23808 		return;
23809 
23810 	/*
23811 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23812 	 * to do the heavy lifting.
23813 	 */
23814 	zoneid = io->ipsec_out_zoneid;
23815 	ASSERT(zoneid != ALL_ZONES);
23816 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23817 		ASSERT(io->ipsec_out_esp_sa != NULL);
23818 		io->ipsec_out_esp_done = B_TRUE;
23819 		/*
23820 		 * Note that since hw accel can only apply one transform,
23821 		 * not two, we skip hw accel for ESP if we also have AH
23822 		 * This is an design limitation of the interface
23823 		 * which should be revisited.
23824 		 */
23825 		ASSERT(ire != NULL);
23826 		if (io->ipsec_out_ah_sa == NULL) {
23827 			ill = (ill_t *)ire->ire_stq->q_ptr;
23828 			ipsec_out_is_accelerated(ipsec_mp,
23829 			    io->ipsec_out_esp_sa, ill, ire);
23830 		}
23831 
23832 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23833 		switch (ipsec_rc) {
23834 		case IPSEC_STATUS_SUCCESS:
23835 			break;
23836 		case IPSEC_STATUS_FAILED:
23837 			BUMP_MIB(&ip_mib, ipOutDiscards);
23838 			/* FALLTHRU */
23839 		case IPSEC_STATUS_PENDING:
23840 			return;
23841 		}
23842 	}
23843 
23844 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23845 		ASSERT(io->ipsec_out_ah_sa != NULL);
23846 		io->ipsec_out_ah_done = B_TRUE;
23847 		if (ire == NULL) {
23848 			int idx = io->ipsec_out_capab_ill_index;
23849 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23850 			    NULL, NULL, NULL, NULL);
23851 			ill_need_rele = B_TRUE;
23852 		} else {
23853 			ill = (ill_t *)ire->ire_stq->q_ptr;
23854 		}
23855 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23856 		    ire);
23857 
23858 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23859 		switch (ipsec_rc) {
23860 		case IPSEC_STATUS_SUCCESS:
23861 			break;
23862 		case IPSEC_STATUS_FAILED:
23863 			BUMP_MIB(&ip_mib, ipOutDiscards);
23864 			/* FALLTHRU */
23865 		case IPSEC_STATUS_PENDING:
23866 			if (ill != NULL && ill_need_rele)
23867 				ill_refrele(ill);
23868 			return;
23869 		}
23870 	}
23871 	/*
23872 	 * We are done with IPSEC processing. Send it over
23873 	 * the wire.
23874 	 */
23875 done:
23876 	mp = ipsec_mp->b_cont;
23877 	ipha = (ipha_t *)mp->b_rptr;
23878 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23879 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23880 	} else {
23881 		ip6h = (ip6_t *)ipha;
23882 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23883 	}
23884 	if (ill != NULL && ill_need_rele)
23885 		ill_refrele(ill);
23886 }
23887 
23888 /* ARGSUSED */
23889 void
23890 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23891 {
23892 	opt_restart_t	*or;
23893 	int	err;
23894 	conn_t	*connp;
23895 
23896 	ASSERT(CONN_Q(q));
23897 	connp = Q_TO_CONN(q);
23898 
23899 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23900 	or = (opt_restart_t *)first_mp->b_rptr;
23901 	/*
23902 	 * We don't need to pass any credentials here since this is just
23903 	 * a restart. The credentials are passed in when svr4_optcom_req
23904 	 * is called the first time (from ip_wput_nondata).
23905 	 */
23906 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23907 		err = svr4_optcom_req(q, first_mp, NULL,
23908 		    &ip_opt_obj);
23909 	} else {
23910 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23911 		err = tpi_optcom_req(q, first_mp, NULL,
23912 		    &ip_opt_obj);
23913 	}
23914 	if (err != EINPROGRESS) {
23915 		/* operation is done */
23916 		CONN_OPER_PENDING_DONE(connp);
23917 	}
23918 }
23919 
23920 /*
23921  * ioctls that go through a down/up sequence may need to wait for the down
23922  * to complete. This involves waiting for the ire and ipif refcnts to go down
23923  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23924  */
23925 /* ARGSUSED */
23926 void
23927 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23928 {
23929 	struct iocblk *iocp;
23930 	mblk_t *mp1;
23931 	ipif_t	*ipif;
23932 	ip_ioctl_cmd_t *ipip;
23933 	int err;
23934 	sin_t	*sin;
23935 	struct lifreq *lifr;
23936 	struct ifreq *ifr;
23937 
23938 	iocp = (struct iocblk *)mp->b_rptr;
23939 	ASSERT(ipsq != NULL);
23940 	/* Existence of mp1 verified in ip_wput_nondata */
23941 	mp1 = mp->b_cont->b_cont;
23942 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23943 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23944 		ill_t *ill;
23945 		/*
23946 		 * Special case where ipsq_current_ipif may not be set.
23947 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23948 		 * ill could also have become part of a ipmp group in the
23949 		 * process, we are here as were not able to complete the
23950 		 * operation in ipif_set_values because we could not become
23951 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23952 		 * will not be set so we need to set it.
23953 		 */
23954 		ill = (ill_t *)q->q_ptr;
23955 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23956 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23957 	}
23958 
23959 	ipif = ipsq->ipsq_current_ipif;
23960 	ASSERT(ipif != NULL);
23961 	if (ipip->ipi_cmd_type == IF_CMD) {
23962 		/* This a old style SIOC[GS]IF* command */
23963 		ifr = (struct ifreq *)mp1->b_rptr;
23964 		sin = (sin_t *)&ifr->ifr_addr;
23965 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
23966 		/* This a new style SIOC[GS]LIF* command */
23967 		lifr = (struct lifreq *)mp1->b_rptr;
23968 		sin = (sin_t *)&lifr->lifr_addr;
23969 	} else {
23970 		sin = NULL;
23971 	}
23972 
23973 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
23974 	    (void *)mp1->b_rptr);
23975 
23976 	/* SIOCLIFREMOVEIF could have removed the ipif */
23977 	ip_ioctl_finish(q, mp, err,
23978 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23979 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
23980 }
23981 
23982 /*
23983  * ioctl processing
23984  *
23985  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
23986  * the ioctl command in the ioctl tables and determines the copyin data size
23987  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
23988  * size.
23989  *
23990  * ioctl processing then continues when the M_IOCDATA makes its way down.
23991  * Now the ioctl is looked up again in the ioctl table, and its properties are
23992  * extracted. The associated 'conn' is then refheld till the end of the ioctl
23993  * and the general ioctl processing function ip_process_ioctl is called.
23994  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
23995  * so goes thru the serialization primitive ipsq_try_enter. Then the
23996  * appropriate function to handle the ioctl is called based on the entry in
23997  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
23998  * which also refreleases the 'conn' that was refheld at the start of the
23999  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24000  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24001  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24002  *
24003  * Many exclusive ioctls go thru an internal down up sequence as part of
24004  * the operation. For example an attempt to change the IP address of an
24005  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24006  * does all the cleanup such as deleting all ires that use this address.
24007  * Then we need to wait till all references to the interface go away.
24008  */
24009 void
24010 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24011 {
24012 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24013 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24014 	cmd_info_t ci;
24015 	int err;
24016 	boolean_t entered_ipsq = B_FALSE;
24017 
24018 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24019 
24020 	if (ipip == NULL)
24021 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24022 
24023 	/*
24024 	 * SIOCLIFADDIF needs to go thru a special path since the
24025 	 * ill may not exist yet. This happens in the case of lo0
24026 	 * which is created using this ioctl.
24027 	 */
24028 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24029 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24030 		ip_ioctl_finish(q, mp, err,
24031 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24032 		    NULL, NULL);
24033 		return;
24034 	}
24035 
24036 	ci.ci_ipif = NULL;
24037 	switch (ipip->ipi_cmd_type) {
24038 	case IF_CMD:
24039 	case LIF_CMD:
24040 		/*
24041 		 * ioctls that pass in a [l]ifreq appear here.
24042 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24043 		 * ci.ci_ipif
24044 		 */
24045 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24046 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24047 		if (err != 0) {
24048 			ip_ioctl_finish(q, mp, err,
24049 			    ipip->ipi_flags & IPI_GET_CMD ?
24050 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24051 			return;
24052 		}
24053 		ASSERT(ci.ci_ipif != NULL);
24054 		break;
24055 
24056 	case TUN_CMD:
24057 		/*
24058 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24059 		 * a refheld ipif in ci.ci_ipif
24060 		 */
24061 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24062 		if (err != 0) {
24063 			ip_ioctl_finish(q, mp, err,
24064 			    ipip->ipi_flags & IPI_GET_CMD ?
24065 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24066 			return;
24067 		}
24068 		ASSERT(ci.ci_ipif != NULL);
24069 		break;
24070 
24071 	case MISC_CMD:
24072 		/*
24073 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24074 		 * For eg. SIOCGLIFCONF will appear here.
24075 		 */
24076 		switch (ipip->ipi_cmd) {
24077 		case IF_UNITSEL:
24078 			/* ioctl comes down the ill */
24079 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24080 			ipif_refhold(ci.ci_ipif);
24081 			break;
24082 		case SIOCGMSFILTER:
24083 		case SIOCSMSFILTER:
24084 		case SIOCGIPMSFILTER:
24085 		case SIOCSIPMSFILTER:
24086 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24087 			    ip_process_ioctl);
24088 			if (err != 0) {
24089 				ip_ioctl_finish(q, mp, err,
24090 				    ipip->ipi_flags & IPI_GET_CMD ?
24091 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24092 				return;
24093 			}
24094 			break;
24095 		}
24096 		err = 0;
24097 		ci.ci_sin = NULL;
24098 		ci.ci_sin6 = NULL;
24099 		ci.ci_lifr = NULL;
24100 		break;
24101 	}
24102 
24103 	/*
24104 	 * If ipsq is non-null, we are already being called exclusively
24105 	 */
24106 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24107 	if (!(ipip->ipi_flags & IPI_WR)) {
24108 		/*
24109 		 * A return value of EINPROGRESS means the ioctl is
24110 		 * either queued and waiting for some reason or has
24111 		 * already completed.
24112 		 */
24113 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24114 		    ci.ci_lifr);
24115 		if (ci.ci_ipif != NULL)
24116 			ipif_refrele(ci.ci_ipif);
24117 		ip_ioctl_finish(q, mp, err,
24118 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24119 		    NULL, NULL);
24120 		return;
24121 	}
24122 
24123 	ASSERT(ci.ci_ipif != NULL);
24124 
24125 	if (ipsq == NULL) {
24126 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
24127 		    ip_process_ioctl, NEW_OP, B_TRUE);
24128 		entered_ipsq = B_TRUE;
24129 	}
24130 	/*
24131 	 * Release the ipif so that ipif_down and friends that wait for
24132 	 * references to go away are not misled about the current ipif_refcnt
24133 	 * values. We are writer so we can access the ipif even after releasing
24134 	 * the ipif.
24135 	 */
24136 	ipif_refrele(ci.ci_ipif);
24137 	if (ipsq == NULL)
24138 		return;
24139 
24140 	mutex_enter(&ipsq->ipsq_lock);
24141 	ASSERT(ipsq->ipsq_current_ipif == NULL);
24142 	ipsq->ipsq_current_ipif = ci.ci_ipif;
24143 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24144 	mutex_exit(&ipsq->ipsq_lock);
24145 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
24146 	/*
24147 	 * For most set ioctls that come here, this serves as a single point
24148 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
24149 	 * be any new references to the ipif. This helps functions that go
24150 	 * through this path and end up trying to wait for the refcnts
24151 	 * associated with the ipif to go down to zero. Some exceptions are
24152 	 * Failover, Failback, and Groupname commands that operate on more than
24153 	 * just the ci.ci_ipif. These commands internally determine the
24154 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
24155 	 * flags on that set. Another exception is the Removeif command that
24156 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
24157 	 * ipif to operate on.
24158 	 */
24159 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
24160 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
24161 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
24162 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
24163 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
24164 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
24165 
24166 	/*
24167 	 * A return value of EINPROGRESS means the ioctl is
24168 	 * either queued and waiting for some reason or has
24169 	 * already completed.
24170 	 */
24171 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24172 	    ci.ci_lifr);
24173 
24174 	/* SIOCLIFREMOVEIF could have removed the ipif */
24175 	ip_ioctl_finish(q, mp, err,
24176 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24177 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
24178 
24179 	if (entered_ipsq)
24180 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
24181 }
24182 
24183 /*
24184  * Complete the ioctl. Typically ioctls use the mi package and need to
24185  * do mi_copyout/mi_copy_done.
24186  */
24187 void
24188 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
24189     ipif_t *ipif, ipsq_t *ipsq)
24190 {
24191 	conn_t	*connp = NULL;
24192 
24193 	if (err == EINPROGRESS)
24194 		return;
24195 
24196 	if (CONN_Q(q)) {
24197 		connp = Q_TO_CONN(q);
24198 		ASSERT(connp->conn_ref >= 2);
24199 	}
24200 
24201 	switch (mode) {
24202 	case COPYOUT:
24203 		if (err == 0)
24204 			mi_copyout(q, mp);
24205 		else
24206 			mi_copy_done(q, mp, err);
24207 		break;
24208 
24209 	case NO_COPYOUT:
24210 		mi_copy_done(q, mp, err);
24211 		break;
24212 
24213 	default:
24214 		/* An ioctl aborted through a conn close would take this path */
24215 		break;
24216 	}
24217 
24218 	/*
24219 	 * The refhold placed at the start of the ioctl is released here.
24220 	 */
24221 	if (connp != NULL)
24222 		CONN_OPER_PENDING_DONE(connp);
24223 
24224 	/*
24225 	 * If the ioctl were an exclusive ioctl it would have set
24226 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
24227 	 */
24228 	if (ipif != NULL) {
24229 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
24230 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
24231 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
24232 	}
24233 
24234 	/*
24235 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
24236 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
24237 	 * entering the ipsq
24238 	 */
24239 	if (ipsq != NULL) {
24240 		mutex_enter(&ipsq->ipsq_lock);
24241 		ipsq->ipsq_current_ipif = NULL;
24242 		mutex_exit(&ipsq->ipsq_lock);
24243 	}
24244 }
24245 
24246 /*
24247  * This is called from ip_wput_nondata to resume a deferred TCP bind.
24248  */
24249 /* ARGSUSED */
24250 void
24251 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
24252 {
24253 	conn_t *connp = arg;
24254 	tcp_t	*tcp;
24255 
24256 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
24257 	tcp = connp->conn_tcp;
24258 
24259 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
24260 		freemsg(mp);
24261 	else
24262 		tcp_rput_other(tcp, mp);
24263 	CONN_OPER_PENDING_DONE(connp);
24264 }
24265 
24266 /* Called from ip_wput for all non data messages */
24267 /* ARGSUSED */
24268 void
24269 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24270 {
24271 	mblk_t		*mp1;
24272 	ire_t		*ire;
24273 	ill_t		*ill;
24274 	struct iocblk	*iocp;
24275 	ip_ioctl_cmd_t	*ipip;
24276 	cred_t		*cr;
24277 	conn_t		*connp = NULL;
24278 	int		cmd, err;
24279 
24280 	if (CONN_Q(q))
24281 		connp = Q_TO_CONN(q);
24282 
24283 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
24284 
24285 	/* Check if it is a queue to /dev/sctp. */
24286 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
24287 	    connp->conn_rq == NULL) {
24288 		sctp_wput(q, mp);
24289 		return;
24290 	}
24291 
24292 	switch (DB_TYPE(mp)) {
24293 	case M_IOCTL:
24294 		/*
24295 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
24296 		 * will arrange to copy in associated control structures.
24297 		 */
24298 		ip_sioctl_copyin_setup(q, mp);
24299 		return;
24300 	case M_IOCDATA:
24301 		/*
24302 		 * Ensure that this is associated with one of our trans-
24303 		 * parent ioctls.  If it's not ours, discard it if we're
24304 		 * running as a driver, or pass it on if we're a module.
24305 		 */
24306 		iocp = (struct iocblk *)mp->b_rptr;
24307 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24308 		if (ipip == NULL) {
24309 			if (q->q_next == NULL) {
24310 				goto nak;
24311 			} else {
24312 				putnext(q, mp);
24313 			}
24314 			return;
24315 		} else if ((q->q_next != NULL) &&
24316 		    !(ipip->ipi_flags & IPI_MODOK)) {
24317 			/*
24318 			 * the ioctl is one we recognise, but is not
24319 			 * consumed by IP as a module, pass M_IOCDATA
24320 			 * for processing downstream, but only for
24321 			 * common Streams ioctls.
24322 			 */
24323 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
24324 				putnext(q, mp);
24325 				return;
24326 			} else {
24327 				goto nak;
24328 			}
24329 		}
24330 
24331 		/* IOCTL continuation following copyin or copyout. */
24332 		if (mi_copy_state(q, mp, NULL) == -1) {
24333 			/*
24334 			 * The copy operation failed.  mi_copy_state already
24335 			 * cleaned up, so we're out of here.
24336 			 */
24337 			return;
24338 		}
24339 		/*
24340 		 * If we just completed a copy in, we become writer and
24341 		 * continue processing in ip_sioctl_copyin_done.  If it
24342 		 * was a copy out, we call mi_copyout again.  If there is
24343 		 * nothing more to copy out, it will complete the IOCTL.
24344 		 */
24345 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
24346 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
24347 				mi_copy_done(q, mp, EPROTO);
24348 				return;
24349 			}
24350 			/*
24351 			 * Check for cases that need more copying.  A return
24352 			 * value of 0 means a second copyin has been started,
24353 			 * so we return; a return value of 1 means no more
24354 			 * copying is needed, so we continue.
24355 			 */
24356 			cmd = iocp->ioc_cmd;
24357 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
24358 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
24359 			    MI_COPY_COUNT(mp) == 1) {
24360 				if (ip_copyin_msfilter(q, mp) == 0)
24361 					return;
24362 			}
24363 			/*
24364 			 * Refhold the conn, till the ioctl completes. This is
24365 			 * needed in case the ioctl ends up in the pending mp
24366 			 * list. Every mp in the ill_pending_mp list and
24367 			 * the ipsq_pending_mp must have a refhold on the conn
24368 			 * to resume processing. The refhold is released when
24369 			 * the ioctl completes. (normally or abnormally)
24370 			 * In all cases ip_ioctl_finish is called to finish
24371 			 * the ioctl.
24372 			 */
24373 			if (connp != NULL) {
24374 				/* This is not a reentry */
24375 				ASSERT(ipsq == NULL);
24376 				CONN_INC_REF(connp);
24377 			} else {
24378 				if (!(ipip->ipi_flags & IPI_MODOK)) {
24379 					mi_copy_done(q, mp, EINVAL);
24380 					return;
24381 				}
24382 			}
24383 
24384 			ip_process_ioctl(ipsq, q, mp, ipip);
24385 
24386 		} else {
24387 			mi_copyout(q, mp);
24388 		}
24389 		return;
24390 nak:
24391 		iocp->ioc_error = EINVAL;
24392 		mp->b_datap->db_type = M_IOCNAK;
24393 		iocp->ioc_count = 0;
24394 		qreply(q, mp);
24395 		return;
24396 
24397 	case M_IOCNAK:
24398 		/*
24399 		 * The only way we could get here is if a resolver didn't like
24400 		 * an IOCTL we sent it.	 This shouldn't happen.
24401 		 */
24402 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
24403 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
24404 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
24405 		freemsg(mp);
24406 		return;
24407 	case M_IOCACK:
24408 		/* Finish socket ioctls passed through to ARP. */
24409 		ip_sioctl_iocack(q, mp);
24410 		return;
24411 	case M_FLUSH:
24412 		if (*mp->b_rptr & FLUSHW)
24413 			flushq(q, FLUSHALL);
24414 		if (q->q_next) {
24415 			/*
24416 			 * M_FLUSH is sent up to IP by some drivers during
24417 			 * unbind. ip_rput has already replied to it. We are
24418 			 * here for the M_FLUSH that we originated in IP
24419 			 * before sending the unbind request to the driver.
24420 			 * Just free it as we don't queue packets in IP
24421 			 * on the write side of the device instance.
24422 			 */
24423 			freemsg(mp);
24424 			return;
24425 		}
24426 		if (*mp->b_rptr & FLUSHR) {
24427 			*mp->b_rptr &= ~FLUSHW;
24428 			qreply(q, mp);
24429 			return;
24430 		}
24431 		freemsg(mp);
24432 		return;
24433 	case IRE_DB_REQ_TYPE:
24434 		/* An Upper Level Protocol wants a copy of an IRE. */
24435 		ip_ire_req(q, mp);
24436 		return;
24437 	case M_CTL:
24438 		/* M_CTL messages are used by ARP to tell us things. */
24439 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
24440 			break;
24441 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
24442 		case AR_ENTRY_SQUERY:
24443 			ip_wput_ctl(q, mp);
24444 			return;
24445 		case AR_CLIENT_NOTIFY:
24446 			ip_arp_news(q, mp);
24447 			return;
24448 		case AR_DLPIOP_DONE:
24449 			ASSERT(q->q_next != NULL);
24450 			ill = (ill_t *)q->q_ptr;
24451 			/* qwriter_ip releases the refhold */
24452 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24453 			ill_refhold(ill);
24454 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24455 			    CUR_OP, B_FALSE);
24456 			return;
24457 		case AR_ARP_CLOSING:
24458 			/*
24459 			 * ARP (above us) is closing. If no ARP bringup is
24460 			 * currently pending, ack the message so that ARP
24461 			 * can complete its close. Also mark ill_arp_closing
24462 			 * so that new ARP bringups will fail. If any
24463 			 * ARP bringup is currently in progress, we will
24464 			 * ack this when the current ARP bringup completes.
24465 			 */
24466 			ASSERT(q->q_next != NULL);
24467 			ill = (ill_t *)q->q_ptr;
24468 			mutex_enter(&ill->ill_lock);
24469 			ill->ill_arp_closing = 1;
24470 			if (!ill->ill_arp_bringup_pending) {
24471 				mutex_exit(&ill->ill_lock);
24472 				qreply(q, mp);
24473 			} else {
24474 				mutex_exit(&ill->ill_lock);
24475 				freemsg(mp);
24476 			}
24477 			return;
24478 		default:
24479 			break;
24480 		}
24481 		break;
24482 	case M_PROTO:
24483 	case M_PCPROTO:
24484 		/*
24485 		 * The only PROTO messages we expect are ULP binds and
24486 		 * copies of option negotiation acknowledgements.
24487 		 */
24488 		switch (((union T_primitives *)mp->b_rptr)->type) {
24489 		case O_T_BIND_REQ:
24490 		case T_BIND_REQ: {
24491 			/* Request can get queued in bind */
24492 			ASSERT(connp != NULL);
24493 			/*
24494 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
24495 			 * instead of going through this path.  We only get
24496 			 * here in the following cases:
24497 			 *
24498 			 * a. Bind retries, where ipsq is non-NULL.
24499 			 * b. T_BIND_REQ is issued from non TCP/UDP
24500 			 *    transport, e.g. icmp for raw socket,
24501 			 *    in which case ipsq will be NULL.
24502 			 */
24503 			ASSERT(ipsq != NULL ||
24504 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
24505 
24506 			/* Don't increment refcnt if this is a re-entry */
24507 			if (ipsq == NULL)
24508 				CONN_INC_REF(connp);
24509 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
24510 			    connp, NULL) : ip_bind_v4(q, mp, connp);
24511 			if (mp == NULL)
24512 				return;
24513 			if (IPCL_IS_TCP(connp)) {
24514 				/*
24515 				 * In the case of TCP endpoint we
24516 				 * come here only for bind retries
24517 				 */
24518 				ASSERT(ipsq != NULL);
24519 				CONN_INC_REF(connp);
24520 				squeue_fill(connp->conn_sqp, mp,
24521 				    ip_resume_tcp_bind, connp,
24522 				    SQTAG_BIND_RETRY);
24523 				return;
24524 			} else if (IPCL_IS_UDP(connp)) {
24525 				/*
24526 				 * In the case of UDP endpoint we
24527 				 * come here only for bind retries
24528 				 */
24529 				ASSERT(ipsq != NULL);
24530 				udp_resume_bind(connp, mp);
24531 				return;
24532 			}
24533 			qreply(q, mp);
24534 			CONN_OPER_PENDING_DONE(connp);
24535 			return;
24536 		}
24537 		case T_SVR4_OPTMGMT_REQ:
24538 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24539 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24540 
24541 			ASSERT(connp != NULL);
24542 			if (!snmpcom_req(q, mp, ip_snmp_set,
24543 			    ip_snmp_get, cr)) {
24544 				/*
24545 				 * Call svr4_optcom_req so that it can
24546 				 * generate the ack. We don't come here
24547 				 * if this operation is being restarted.
24548 				 * ip_restart_optmgmt will drop the conn ref.
24549 				 * In the case of ipsec option after the ipsec
24550 				 * load is complete conn_restart_ipsec_waiter
24551 				 * drops the conn ref.
24552 				 */
24553 				ASSERT(ipsq == NULL);
24554 				CONN_INC_REF(connp);
24555 				if (ip_check_for_ipsec_opt(q, mp))
24556 					return;
24557 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24558 				if (err != EINPROGRESS) {
24559 					/* Operation is done */
24560 					CONN_OPER_PENDING_DONE(connp);
24561 				}
24562 			}
24563 			return;
24564 		case T_OPTMGMT_REQ:
24565 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24566 			/*
24567 			 * Note: No snmpcom_req support through new
24568 			 * T_OPTMGMT_REQ.
24569 			 * Call tpi_optcom_req so that it can
24570 			 * generate the ack.
24571 			 */
24572 			ASSERT(connp != NULL);
24573 			ASSERT(ipsq == NULL);
24574 			/*
24575 			 * We don't come here for restart. ip_restart_optmgmt
24576 			 * will drop the conn ref. In the case of ipsec option
24577 			 * after the ipsec load is complete
24578 			 * conn_restart_ipsec_waiter drops the conn ref.
24579 			 */
24580 			CONN_INC_REF(connp);
24581 			if (ip_check_for_ipsec_opt(q, mp))
24582 				return;
24583 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24584 			if (err != EINPROGRESS) {
24585 				/* Operation is done */
24586 				CONN_OPER_PENDING_DONE(connp);
24587 			}
24588 			return;
24589 		case T_UNBIND_REQ:
24590 			mp = ip_unbind(q, mp);
24591 			qreply(q, mp);
24592 			return;
24593 		default:
24594 			/*
24595 			 * Have to drop any DLPI messages coming down from
24596 			 * arp (such as an info_req which would cause ip
24597 			 * to receive an extra info_ack if it was passed
24598 			 * through.
24599 			 */
24600 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24601 			    (int)*(uint_t *)mp->b_rptr));
24602 			freemsg(mp);
24603 			return;
24604 		}
24605 		/* NOTREACHED */
24606 	case IRE_DB_TYPE: {
24607 		nce_t		*nce;
24608 		ill_t		*ill;
24609 		in6_addr_t	gw_addr_v6;
24610 
24611 
24612 		/*
24613 		 * This is a response back from a resolver.  It
24614 		 * consists of a message chain containing:
24615 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24616 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24617 		 * The LL_HDR_MBLK is the DLPI header to use to get
24618 		 * the attached packet, and subsequent ones for the
24619 		 * same destination, transmitted.
24620 		 */
24621 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24622 			break;
24623 		/*
24624 		 * First, check to make sure the resolution succeeded.
24625 		 * If it failed, the second mblk will be empty.
24626 		 * If it is, free the chain, dropping the packet.
24627 		 * (We must ire_delete the ire; that frees the ire mblk)
24628 		 * We're doing this now to support PVCs for ATM; it's
24629 		 * a partial xresolv implementation. When we fully implement
24630 		 * xresolv interfaces, instead of freeing everything here
24631 		 * we'll initiate neighbor discovery.
24632 		 *
24633 		 * For v4 (ARP and other external resolvers) the resolver
24634 		 * frees the message, so no check is needed. This check
24635 		 * is required, though, for a full xresolve implementation.
24636 		 * Including this code here now both shows how external
24637 		 * resolvers can NACK a resolution request using an
24638 		 * existing design that has no specific provisions for NACKs,
24639 		 * and also takes into account that the current non-ARP
24640 		 * external resolver has been coded to use this method of
24641 		 * NACKing for all IPv6 (xresolv) cases,
24642 		 * whether our xresolv implementation is complete or not.
24643 		 *
24644 		 */
24645 		ire = (ire_t *)mp->b_rptr;
24646 		ill = ire_to_ill(ire);
24647 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24648 		if (mp1->b_rptr == mp1->b_wptr) {
24649 			if (ire->ire_ipversion == IPV6_VERSION) {
24650 				/*
24651 				 * XRESOLV interface.
24652 				 */
24653 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24654 				mutex_enter(&ire->ire_lock);
24655 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24656 				mutex_exit(&ire->ire_lock);
24657 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24658 					nce = ndp_lookup(ill,
24659 					    &ire->ire_addr_v6, B_FALSE);
24660 				} else {
24661 					nce = ndp_lookup(ill, &gw_addr_v6,
24662 					    B_FALSE);
24663 				}
24664 				if (nce != NULL) {
24665 					nce_resolv_failed(nce);
24666 					ndp_delete(nce);
24667 					NCE_REFRELE(nce);
24668 				}
24669 			}
24670 			mp->b_cont = NULL;
24671 			freemsg(mp1);		/* frees the pkt as well */
24672 			ire_delete((ire_t *)mp->b_rptr);
24673 			return;
24674 		}
24675 		/*
24676 		 * Split them into IRE_MBLK and pkt and feed it into
24677 		 * ire_add_then_send. Then in ire_add_then_send
24678 		 * the IRE will be added, and then the packet will be
24679 		 * run back through ip_wput. This time it will make
24680 		 * it to the wire.
24681 		 */
24682 		mp->b_cont = NULL;
24683 		mp = mp1->b_cont;		/* now, mp points to pkt */
24684 		mp1->b_cont = NULL;
24685 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24686 		if (ire->ire_ipversion == IPV6_VERSION) {
24687 			/*
24688 			 * XRESOLV interface. Find the nce and put a copy
24689 			 * of the dl_unitdata_req in nce_res_mp
24690 			 */
24691 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24692 			mutex_enter(&ire->ire_lock);
24693 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24694 			mutex_exit(&ire->ire_lock);
24695 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24696 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24697 				    B_FALSE);
24698 			} else {
24699 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24700 			}
24701 			if (nce != NULL) {
24702 				/*
24703 				 * We have to protect nce_res_mp here
24704 				 * from being accessed by other threads
24705 				 * while we change the mblk pointer.
24706 				 * Other functions will also lock the nce when
24707 				 * accessing nce_res_mp.
24708 				 *
24709 				 * The reason we change the mblk pointer
24710 				 * here rather than copying the resolved address
24711 				 * into the template is that, unlike with
24712 				 * ethernet, we have no guarantee that the
24713 				 * resolved address length will be
24714 				 * smaller than or equal to the lla length
24715 				 * with which the template was allocated,
24716 				 * (for ethernet, they're equal)
24717 				 * so we have to use the actual resolved
24718 				 * address mblk - which holds the real
24719 				 * dl_unitdata_req with the resolved address.
24720 				 *
24721 				 * Doing this is the same behavior as was
24722 				 * previously used in the v4 ARP case.
24723 				 */
24724 				mutex_enter(&nce->nce_lock);
24725 				if (nce->nce_res_mp != NULL)
24726 					freemsg(nce->nce_res_mp);
24727 				nce->nce_res_mp = mp1;
24728 				mutex_exit(&nce->nce_lock);
24729 				/*
24730 				 * We do a fastpath probe here because
24731 				 * we have resolved the address without
24732 				 * using Neighbor Discovery.
24733 				 * In the non-XRESOLV v6 case, the fastpath
24734 				 * probe is done right after neighbor
24735 				 * discovery completes.
24736 				 */
24737 				if (nce->nce_res_mp != NULL) {
24738 					int res;
24739 					nce_fastpath_list_add(nce);
24740 					res = ill_fastpath_probe(ill,
24741 					    nce->nce_res_mp);
24742 					if (res != 0 && res != EAGAIN)
24743 						nce_fastpath_list_delete(nce);
24744 				}
24745 
24746 				ire_add_then_send(q, ire, mp);
24747 				/*
24748 				 * Now we have to clean out any packets
24749 				 * that may have been queued on the nce
24750 				 * while it was waiting for address resolution
24751 				 * to complete.
24752 				 */
24753 				mutex_enter(&nce->nce_lock);
24754 				mp1 = nce->nce_qd_mp;
24755 				nce->nce_qd_mp = NULL;
24756 				mutex_exit(&nce->nce_lock);
24757 				while (mp1 != NULL) {
24758 					mblk_t *nxt_mp;
24759 					queue_t *fwdq = NULL;
24760 					ill_t   *inbound_ill;
24761 					uint_t ifindex;
24762 
24763 					nxt_mp = mp1->b_next;
24764 					mp1->b_next = NULL;
24765 					/*
24766 					 * Retrieve ifindex stored in
24767 					 * ip_rput_data_v6()
24768 					 */
24769 					ifindex =
24770 					    (uint_t)(uintptr_t)mp1->b_prev;
24771 					inbound_ill =
24772 						ill_lookup_on_ifindex(ifindex,
24773 						    B_TRUE, NULL, NULL, NULL,
24774 						    NULL);
24775 					mp1->b_prev = NULL;
24776 					if (inbound_ill != NULL)
24777 						fwdq = inbound_ill->ill_rq;
24778 
24779 					if (fwdq != NULL) {
24780 						put(fwdq, mp1);
24781 						ill_refrele(inbound_ill);
24782 					} else
24783 						put(WR(ill->ill_rq), mp1);
24784 					mp1 = nxt_mp;
24785 				}
24786 				NCE_REFRELE(nce);
24787 			} else {	/* nce is NULL; clean up */
24788 				ire_delete(ire);
24789 				freemsg(mp);
24790 				freemsg(mp1);
24791 				return;
24792 			}
24793 		} else {
24794 			ire->ire_dlureq_mp = mp1;
24795 			ire_add_then_send(q, ire, mp);
24796 		}
24797 		return;	/* All is well, the packet has been sent. */
24798 	}
24799 	default:
24800 		break;
24801 	}
24802 	if (q->q_next) {
24803 		putnext(q, mp);
24804 	} else
24805 		freemsg(mp);
24806 }
24807 
24808 /*
24809  * Process IP options in an outbound packet.  Modify the destination if there
24810  * is a source route option.
24811  * Returns non-zero if something fails in which case an ICMP error has been
24812  * sent and mp freed.
24813  */
24814 static int
24815 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24816     boolean_t mctl_present, zoneid_t zoneid)
24817 {
24818 	ipoptp_t	opts;
24819 	uchar_t		*opt;
24820 	uint8_t		optval;
24821 	uint8_t		optlen;
24822 	ipaddr_t	dst;
24823 	intptr_t	code = 0;
24824 	mblk_t		*mp;
24825 	ire_t		*ire = NULL;
24826 
24827 	ip2dbg(("ip_wput_options\n"));
24828 	mp = ipsec_mp;
24829 	if (mctl_present) {
24830 		mp = ipsec_mp->b_cont;
24831 	}
24832 
24833 	dst = ipha->ipha_dst;
24834 	for (optval = ipoptp_first(&opts, ipha);
24835 	    optval != IPOPT_EOL;
24836 	    optval = ipoptp_next(&opts)) {
24837 		opt = opts.ipoptp_cur;
24838 		optlen = opts.ipoptp_len;
24839 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24840 		    optval, optlen));
24841 		switch (optval) {
24842 			uint32_t off;
24843 		case IPOPT_SSRR:
24844 		case IPOPT_LSRR:
24845 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24846 				ip1dbg((
24847 				    "ip_wput_options: bad option offset\n"));
24848 				code = (char *)&opt[IPOPT_OLEN] -
24849 				    (char *)ipha;
24850 				goto param_prob;
24851 			}
24852 			off = opt[IPOPT_OFFSET];
24853 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24854 			    ntohl(dst)));
24855 			/*
24856 			 * For strict: verify that dst is directly
24857 			 * reachable.
24858 			 */
24859 			if (optval == IPOPT_SSRR) {
24860 				ire = ire_ftable_lookup(dst, 0, 0,
24861 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24862 				    MATCH_IRE_TYPE);
24863 				if (ire == NULL) {
24864 					ip1dbg(("ip_wput_options: SSRR not"
24865 					    " directly reachable: 0x%x\n",
24866 					    ntohl(dst)));
24867 					goto bad_src_route;
24868 				}
24869 				ire_refrele(ire);
24870 			}
24871 			break;
24872 		case IPOPT_RR:
24873 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24874 				ip1dbg((
24875 				    "ip_wput_options: bad option offset\n"));
24876 				code = (char *)&opt[IPOPT_OLEN] -
24877 				    (char *)ipha;
24878 				goto param_prob;
24879 			}
24880 			break;
24881 		case IPOPT_TS:
24882 			/*
24883 			 * Verify that length >=5 and that there is either
24884 			 * room for another timestamp or that the overflow
24885 			 * counter is not maxed out.
24886 			 */
24887 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24888 			if (optlen < IPOPT_MINLEN_IT) {
24889 				goto param_prob;
24890 			}
24891 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24892 				ip1dbg((
24893 				    "ip_wput_options: bad option offset\n"));
24894 				code = (char *)&opt[IPOPT_OFFSET] -
24895 				    (char *)ipha;
24896 				goto param_prob;
24897 			}
24898 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24899 			case IPOPT_TS_TSONLY:
24900 				off = IPOPT_TS_TIMELEN;
24901 				break;
24902 			case IPOPT_TS_TSANDADDR:
24903 			case IPOPT_TS_PRESPEC:
24904 			case IPOPT_TS_PRESPEC_RFC791:
24905 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24906 				break;
24907 			default:
24908 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24909 				    (char *)ipha;
24910 				goto param_prob;
24911 			}
24912 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24913 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24914 				/*
24915 				 * No room and the overflow counter is 15
24916 				 * already.
24917 				 */
24918 				goto param_prob;
24919 			}
24920 			break;
24921 		}
24922 	}
24923 
24924 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24925 		return (0);
24926 
24927 	ip1dbg(("ip_wput_options: error processing IP options."));
24928 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24929 
24930 param_prob:
24931 	/*
24932 	 * Since ip_wput() isn't close to finished, we fill
24933 	 * in enough of the header for credible error reporting.
24934 	 */
24935 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24936 		/* Failed */
24937 		freemsg(ipsec_mp);
24938 		return (-1);
24939 	}
24940 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24941 	return (-1);
24942 
24943 bad_src_route:
24944 	/*
24945 	 * Since ip_wput() isn't close to finished, we fill
24946 	 * in enough of the header for credible error reporting.
24947 	 */
24948 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24949 		/* Failed */
24950 		freemsg(ipsec_mp);
24951 		return (-1);
24952 	}
24953 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24954 	return (-1);
24955 }
24956 
24957 /*
24958  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
24959  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
24960  * thru /etc/system.
24961  */
24962 #define	CONN_MAXDRAINCNT	64
24963 
24964 static void
24965 conn_drain_init(void)
24966 {
24967 	int i;
24968 
24969 	conn_drain_list_cnt = conn_drain_nthreads;
24970 
24971 	if ((conn_drain_list_cnt == 0) ||
24972 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
24973 		/*
24974 		 * Default value of the number of drainers is the
24975 		 * number of cpus, subject to maximum of 8 drainers.
24976 		 */
24977 		if (boot_max_ncpus != -1)
24978 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
24979 		else
24980 			conn_drain_list_cnt = MIN(max_ncpus, 8);
24981 	}
24982 
24983 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
24984 	    KM_SLEEP);
24985 
24986 	for (i = 0; i < conn_drain_list_cnt; i++) {
24987 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
24988 		    MUTEX_DEFAULT, NULL);
24989 	}
24990 }
24991 
24992 static void
24993 conn_drain_fini(void)
24994 {
24995 	int i;
24996 
24997 	for (i = 0; i < conn_drain_list_cnt; i++)
24998 		mutex_destroy(&conn_drain_list[i].idl_lock);
24999 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25000 	conn_drain_list = NULL;
25001 }
25002 
25003 /*
25004  * Note: For an overview of how flowcontrol is handled in IP please see the
25005  * IP Flowcontrol notes at the top of this file.
25006  *
25007  * Flow control has blocked us from proceeding. Insert the given conn in one
25008  * of the conn drain lists. These conn wq's will be qenabled later on when
25009  * STREAMS flow control does a backenable. conn_walk_drain will enable
25010  * the first conn in each of these drain lists. Each of these qenabled conns
25011  * in turn enables the next in the list, after it runs, or when it closes,
25012  * thus sustaining the drain process.
25013  *
25014  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25015  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25016  * running at any time, on a given conn, since there can be only 1 service proc
25017  * running on a queue at any time.
25018  */
25019 void
25020 conn_drain_insert(conn_t *connp)
25021 {
25022 	idl_t	*idl;
25023 	uint_t	index;
25024 
25025 	mutex_enter(&connp->conn_lock);
25026 	if (connp->conn_state_flags & CONN_CLOSING) {
25027 		/*
25028 		 * The conn is closing as a result of which CONN_CLOSING
25029 		 * is set. Return.
25030 		 */
25031 		mutex_exit(&connp->conn_lock);
25032 		return;
25033 	} else if (connp->conn_idl == NULL) {
25034 		/*
25035 		 * Assign the next drain list round robin. We dont' use
25036 		 * a lock, and thus it may not be strictly round robin.
25037 		 * Atomicity of load/stores is enough to make sure that
25038 		 * conn_drain_list_index is always within bounds.
25039 		 */
25040 		index = conn_drain_list_index;
25041 		ASSERT(index < conn_drain_list_cnt);
25042 		connp->conn_idl = &conn_drain_list[index];
25043 		index++;
25044 		if (index == conn_drain_list_cnt)
25045 			index = 0;
25046 		conn_drain_list_index = index;
25047 	}
25048 	mutex_exit(&connp->conn_lock);
25049 
25050 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25051 	if ((connp->conn_drain_prev != NULL) ||
25052 	    (connp->conn_state_flags & CONN_CLOSING)) {
25053 		/*
25054 		 * The conn is already in the drain list, OR
25055 		 * the conn is closing. We need to check again for
25056 		 * the closing case again since close can happen
25057 		 * after we drop the conn_lock, and before we
25058 		 * acquire the CONN_DRAIN_LIST_LOCK.
25059 		 */
25060 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25061 		return;
25062 	} else {
25063 		idl = connp->conn_idl;
25064 	}
25065 
25066 	/*
25067 	 * The conn is not in the drain list. Insert it at the
25068 	 * tail of the drain list. The drain list is circular
25069 	 * and doubly linked. idl_conn points to the 1st element
25070 	 * in the list.
25071 	 */
25072 	if (idl->idl_conn == NULL) {
25073 		idl->idl_conn = connp;
25074 		connp->conn_drain_next = connp;
25075 		connp->conn_drain_prev = connp;
25076 	} else {
25077 		conn_t *head = idl->idl_conn;
25078 
25079 		connp->conn_drain_next = head;
25080 		connp->conn_drain_prev = head->conn_drain_prev;
25081 		head->conn_drain_prev->conn_drain_next = connp;
25082 		head->conn_drain_prev = connp;
25083 	}
25084 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25085 }
25086 
25087 /*
25088  * This conn is closing, and we are called from ip_close. OR
25089  * This conn has been serviced by ip_wsrv, and we need to do the tail
25090  * processing.
25091  * If this conn is part of the drain list, we may need to sustain the drain
25092  * process by qenabling the next conn in the drain list. We may also need to
25093  * remove this conn from the list, if it is done.
25094  */
25095 static void
25096 conn_drain_tail(conn_t *connp, boolean_t closing)
25097 {
25098 	idl_t *idl;
25099 
25100 	/*
25101 	 * connp->conn_idl is stable at this point, and no lock is needed
25102 	 * to check it. If we are called from ip_close, close has already
25103 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
25104 	 * called us only because conn_idl is non-null. If we are called thru
25105 	 * service, conn_idl could be null, but it cannot change because
25106 	 * service is single-threaded per queue, and there cannot be another
25107 	 * instance of service trying to call conn_drain_insert on this conn
25108 	 * now.
25109 	 */
25110 	ASSERT(!closing || (connp->conn_idl != NULL));
25111 
25112 	/*
25113 	 * If connp->conn_idl is null, the conn has not been inserted into any
25114 	 * drain list even once since creation of the conn. Just return.
25115 	 */
25116 	if (connp->conn_idl == NULL)
25117 		return;
25118 
25119 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25120 
25121 	if (connp->conn_drain_prev == NULL) {
25122 		/* This conn is currently not in the drain list.  */
25123 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25124 		return;
25125 	}
25126 	idl = connp->conn_idl;
25127 	if (idl->idl_conn_draining == connp) {
25128 		/*
25129 		 * This conn is the current drainer. If this is the last conn
25130 		 * in the drain list, we need to do more checks, in the 'if'
25131 		 * below. Otherwwise we need to just qenable the next conn,
25132 		 * to sustain the draining, and is handled in the 'else'
25133 		 * below.
25134 		 */
25135 		if (connp->conn_drain_next == idl->idl_conn) {
25136 			/*
25137 			 * This conn is the last in this list. This round
25138 			 * of draining is complete. If idl_repeat is set,
25139 			 * it means another flow enabling has happened from
25140 			 * the driver/streams and we need to another round
25141 			 * of draining.
25142 			 * If there are more than 2 conns in the drain list,
25143 			 * do a left rotate by 1, so that all conns except the
25144 			 * conn at the head move towards the head by 1, and the
25145 			 * the conn at the head goes to the tail. This attempts
25146 			 * a more even share for all queues that are being
25147 			 * drained.
25148 			 */
25149 			if ((connp->conn_drain_next != connp) &&
25150 			    (idl->idl_conn->conn_drain_next != connp)) {
25151 				idl->idl_conn = idl->idl_conn->conn_drain_next;
25152 			}
25153 			if (idl->idl_repeat) {
25154 				qenable(idl->idl_conn->conn_wq);
25155 				idl->idl_conn_draining = idl->idl_conn;
25156 				idl->idl_repeat = 0;
25157 			} else {
25158 				idl->idl_conn_draining = NULL;
25159 			}
25160 		} else {
25161 			/*
25162 			 * If the next queue that we are now qenable'ing,
25163 			 * is closing, it will remove itself from this list
25164 			 * and qenable the subsequent queue in ip_close().
25165 			 * Serialization is acheived thru idl_lock.
25166 			 */
25167 			qenable(connp->conn_drain_next->conn_wq);
25168 			idl->idl_conn_draining = connp->conn_drain_next;
25169 		}
25170 	}
25171 	if (!connp->conn_did_putbq || closing) {
25172 		/*
25173 		 * Remove ourself from the drain list, if we did not do
25174 		 * a putbq, or if the conn is closing.
25175 		 * Note: It is possible that q->q_first is non-null. It means
25176 		 * that these messages landed after we did a enableok() in
25177 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
25178 		 * service them.
25179 		 */
25180 		if (connp->conn_drain_next == connp) {
25181 			/* Singleton in the list */
25182 			ASSERT(connp->conn_drain_prev == connp);
25183 			idl->idl_conn = NULL;
25184 			idl->idl_conn_draining = NULL;
25185 		} else {
25186 			connp->conn_drain_prev->conn_drain_next =
25187 			    connp->conn_drain_next;
25188 			connp->conn_drain_next->conn_drain_prev =
25189 			    connp->conn_drain_prev;
25190 			if (idl->idl_conn == connp)
25191 				idl->idl_conn = connp->conn_drain_next;
25192 			ASSERT(idl->idl_conn_draining != connp);
25193 
25194 		}
25195 		connp->conn_drain_next = NULL;
25196 		connp->conn_drain_prev = NULL;
25197 	}
25198 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25199 }
25200 
25201 /*
25202  * Write service routine. Shared perimeter entry point.
25203  * ip_wsrv can be called in any of the following ways.
25204  * 1. The device queue's messages has fallen below the low water mark
25205  *    and STREAMS has backenabled the ill_wq. We walk thru all the
25206  *    the drain lists and backenable the first conn in each list.
25207  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
25208  *    qenabled non-tcp upper layers. We start dequeing messages and call
25209  *    ip_wput for each message.
25210  */
25211 
25212 void
25213 ip_wsrv(queue_t *q)
25214 {
25215 	conn_t	*connp;
25216 	ill_t	*ill;
25217 	mblk_t	*mp;
25218 
25219 	if (q->q_next) {
25220 		ill = (ill_t *)q->q_ptr;
25221 		if (ill->ill_state_flags == 0) {
25222 			/*
25223 			 * The device flow control has opened up.
25224 			 * Walk through conn drain lists and qenable the
25225 			 * first conn in each list. This makes sense only
25226 			 * if the stream is fully plumbed and setup.
25227 			 * Hence the if check above.
25228 			 */
25229 			ip1dbg(("ip_wsrv: walking\n"));
25230 			conn_walk_drain();
25231 		}
25232 		return;
25233 	}
25234 
25235 	connp = Q_TO_CONN(q);
25236 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
25237 
25238 	/*
25239 	 * 1. Set conn_draining flag to signal that service is active.
25240 	 *
25241 	 * 2. ip_output determines whether it has been called from service,
25242 	 *    based on the last parameter. If it is IP_WSRV it concludes it
25243 	 *    has been called from service.
25244 	 *
25245 	 * 3. Message ordering is preserved by the following logic.
25246 	 *    i. A directly called ip_output (i.e. not thru service) will queue
25247 	 *    the message at the tail, if conn_draining is set (i.e. service
25248 	 *    is running) or if q->q_first is non-null.
25249 	 *
25250 	 *    ii. If ip_output is called from service, and if ip_output cannot
25251 	 *    putnext due to flow control, it does a putbq.
25252 	 *
25253 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
25254 	 *    (causing an infinite loop).
25255 	 */
25256 	ASSERT(!connp->conn_did_putbq);
25257 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
25258 		connp->conn_draining = 1;
25259 		noenable(q);
25260 		while ((mp = getq(q)) != NULL) {
25261 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
25262 			if (connp->conn_did_putbq) {
25263 				/* ip_wput did a putbq */
25264 				break;
25265 			}
25266 		}
25267 		/*
25268 		 * At this point, a thread coming down from top, calling
25269 		 * ip_wput, may end up queueing the message. We have not yet
25270 		 * enabled the queue, so ip_wsrv won't be called again.
25271 		 * To avoid this race, check q->q_first again (in the loop)
25272 		 * If the other thread queued the message before we call
25273 		 * enableok(), we will catch it in the q->q_first check.
25274 		 * If the other thread queues the message after we call
25275 		 * enableok(), ip_wsrv will be called again by STREAMS.
25276 		 */
25277 		connp->conn_draining = 0;
25278 		enableok(q);
25279 	}
25280 
25281 	/* Enable the next conn for draining */
25282 	conn_drain_tail(connp, B_FALSE);
25283 
25284 	connp->conn_did_putbq = 0;
25285 }
25286 
25287 /*
25288  * Walk the list of all conn's calling the function provided with the
25289  * specified argument for each.	 Note that this only walks conn's that
25290  * have been bound.
25291  * Applies to both IPv4 and IPv6.
25292  */
25293 static void
25294 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
25295 {
25296 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
25297 	    func, arg, zoneid);
25298 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
25299 	    func, arg, zoneid);
25300 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
25301 	    func, arg, zoneid);
25302 	conn_walk_fanout_table(ipcl_proto_fanout,
25303 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
25304 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
25305 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
25306 }
25307 
25308 /*
25309  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
25310  * of conns that need to be drained, check if drain is already in progress.
25311  * If so set the idl_repeat bit, indicating that the last conn in the list
25312  * needs to reinitiate the drain once again, for the list. If drain is not
25313  * in progress for the list, initiate the draining, by qenabling the 1st
25314  * conn in the list. The drain is self-sustaining, each qenabled conn will
25315  * in turn qenable the next conn, when it is done/blocked/closing.
25316  */
25317 static void
25318 conn_walk_drain(void)
25319 {
25320 	int i;
25321 	idl_t *idl;
25322 
25323 	IP_STAT(ip_conn_walk_drain);
25324 
25325 	for (i = 0; i < conn_drain_list_cnt; i++) {
25326 		idl = &conn_drain_list[i];
25327 		mutex_enter(&idl->idl_lock);
25328 		if (idl->idl_conn == NULL) {
25329 			mutex_exit(&idl->idl_lock);
25330 			continue;
25331 		}
25332 		/*
25333 		 * If this list is not being drained currently by
25334 		 * an ip_wsrv thread, start the process.
25335 		 */
25336 		if (idl->idl_conn_draining == NULL) {
25337 			ASSERT(idl->idl_repeat == 0);
25338 			qenable(idl->idl_conn->conn_wq);
25339 			idl->idl_conn_draining = idl->idl_conn;
25340 		} else {
25341 			idl->idl_repeat = 1;
25342 		}
25343 		mutex_exit(&idl->idl_lock);
25344 	}
25345 }
25346 
25347 /*
25348  * Walk an conn hash table of `count' buckets, calling func for each entry.
25349  */
25350 static void
25351 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
25352     zoneid_t zoneid)
25353 {
25354 	conn_t	*connp;
25355 
25356 	while (count-- > 0) {
25357 		mutex_enter(&connfp->connf_lock);
25358 		for (connp = connfp->connf_head; connp != NULL;
25359 		    connp = connp->conn_next) {
25360 			if (zoneid == GLOBAL_ZONEID ||
25361 			    zoneid == connp->conn_zoneid) {
25362 				CONN_INC_REF(connp);
25363 				mutex_exit(&connfp->connf_lock);
25364 				(*func)(connp, arg);
25365 				mutex_enter(&connfp->connf_lock);
25366 				CONN_DEC_REF(connp);
25367 			}
25368 		}
25369 		mutex_exit(&connfp->connf_lock);
25370 		connfp++;
25371 	}
25372 }
25373 
25374 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
25375 static void
25376 conn_report1(conn_t *connp, void *mp)
25377 {
25378 	char	buf1[INET6_ADDRSTRLEN];
25379 	char	buf2[INET6_ADDRSTRLEN];
25380 	uint_t	print_len, buf_len;
25381 
25382 	ASSERT(connp != NULL);
25383 
25384 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
25385 	if (buf_len <= 0)
25386 		return;
25387 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
25388 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
25389 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
25390 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
25391 	    "%5d %s/%05d %s/%05d\n",
25392 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
25393 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
25394 	    buf1, connp->conn_lport,
25395 	    buf2, connp->conn_fport);
25396 	if (print_len < buf_len) {
25397 		((mblk_t *)mp)->b_wptr += print_len;
25398 	} else {
25399 		((mblk_t *)mp)->b_wptr += buf_len;
25400 	}
25401 }
25402 
25403 /*
25404  * Named Dispatch routine to produce a formatted report on all conns
25405  * that are listed in one of the fanout tables.
25406  * This report is accessed by using the ndd utility to "get" ND variable
25407  * "ip_conn_status".
25408  */
25409 /* ARGSUSED */
25410 static int
25411 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
25412 {
25413 	(void) mi_mpprintf(mp,
25414 	    "CONN      " MI_COL_HDRPAD_STR
25415 	    "rfq      " MI_COL_HDRPAD_STR
25416 	    "stq      " MI_COL_HDRPAD_STR
25417 	    " zone local                 remote");
25418 
25419 	/*
25420 	 * Because of the ndd constraint, at most we can have 64K buffer
25421 	 * to put in all conn info.  So to be more efficient, just
25422 	 * allocate a 64K buffer here, assuming we need that large buffer.
25423 	 * This should be OK as only privileged processes can do ndd /dev/ip.
25424 	 */
25425 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
25426 		/* The following may work even if we cannot get a large buf. */
25427 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
25428 		return (0);
25429 	}
25430 
25431 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
25432 	return (0);
25433 }
25434 
25435 /*
25436  * Determine if the ill and multicast aspects of that packets
25437  * "matches" the conn.
25438  */
25439 boolean_t
25440 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
25441     zoneid_t zoneid)
25442 {
25443 	ill_t *in_ill;
25444 	boolean_t found;
25445 	ipif_t *ipif;
25446 	ire_t *ire;
25447 	ipaddr_t dst, src;
25448 
25449 	dst = ipha->ipha_dst;
25450 	src = ipha->ipha_src;
25451 
25452 	/*
25453 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
25454 	 * unicast, broadcast and multicast reception to
25455 	 * conn_incoming_ill. conn_wantpacket itself is called
25456 	 * only for BROADCAST and multicast.
25457 	 *
25458 	 * 1) ip_rput supresses duplicate broadcasts if the ill
25459 	 *    is part of a group. Hence, we should be receiving
25460 	 *    just one copy of broadcast for the whole group.
25461 	 *    Thus, if it is part of the group the packet could
25462 	 *    come on any ill of the group and hence we need a
25463 	 *    match on the group. Otherwise, match on ill should
25464 	 *    be sufficient.
25465 	 *
25466 	 * 2) ip_rput does not suppress duplicate multicast packets.
25467 	 *    If there are two interfaces in a ill group and we have
25468 	 *    2 applications (conns) joined a multicast group G on
25469 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25470 	 *    will give us two packets because we join G on both the
25471 	 *    interfaces rather than nominating just one interface
25472 	 *    for receiving multicast like broadcast above. So,
25473 	 *    we have to call ilg_lookup_ill to filter out duplicate
25474 	 *    copies, if ill is part of a group.
25475 	 */
25476 	in_ill = connp->conn_incoming_ill;
25477 	if (in_ill != NULL) {
25478 		if (in_ill->ill_group == NULL) {
25479 			if (in_ill != ill)
25480 				return (B_FALSE);
25481 		} else if (in_ill->ill_group != ill->ill_group) {
25482 			return (B_FALSE);
25483 		}
25484 	}
25485 
25486 	if (!CLASSD(dst)) {
25487 		if (connp->conn_zoneid == zoneid)
25488 			return (B_TRUE);
25489 		/*
25490 		 * The conn is in a different zone; we need to check that this
25491 		 * broadcast address is configured in the application's zone and
25492 		 * on one ill in the group.
25493 		 */
25494 		ipif = ipif_get_next_ipif(NULL, ill);
25495 		if (ipif == NULL)
25496 			return (B_FALSE);
25497 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25498 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25499 		ipif_refrele(ipif);
25500 		if (ire != NULL) {
25501 			ire_refrele(ire);
25502 			return (B_TRUE);
25503 		} else {
25504 			return (B_FALSE);
25505 		}
25506 	}
25507 
25508 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25509 	    connp->conn_zoneid == zoneid) {
25510 		/*
25511 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25512 		 * disabled, therefore we don't dispatch the multicast packet to
25513 		 * the sending zone.
25514 		 */
25515 		return (B_FALSE);
25516 	}
25517 
25518 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25519 	    connp->conn_zoneid != zoneid) {
25520 		/*
25521 		 * Multicast packet on the loopback interface: we only match
25522 		 * conns who joined the group in the specified zone.
25523 		 */
25524 		return (B_FALSE);
25525 	}
25526 
25527 	if (connp->conn_multi_router) {
25528 		/* multicast packet and multicast router socket: send up */
25529 		return (B_TRUE);
25530 	}
25531 
25532 	mutex_enter(&connp->conn_lock);
25533 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25534 	mutex_exit(&connp->conn_lock);
25535 	return (found);
25536 }
25537 
25538 /*
25539  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25540  */
25541 /* ARGSUSED */
25542 static void
25543 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25544 {
25545 	ill_t *ill = (ill_t *)q->q_ptr;
25546 	mblk_t	*mp1, *mp2;
25547 	ipif_t  *ipif;
25548 	int err = 0;
25549 	conn_t *connp = NULL;
25550 	ipsq_t	*ipsq;
25551 	arc_t	*arc;
25552 
25553 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25554 
25555 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25556 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25557 
25558 	ASSERT(IAM_WRITER_ILL(ill));
25559 	mp2 = mp->b_cont;
25560 	mp->b_cont = NULL;
25561 
25562 	/*
25563 	 * We have now received the arp bringup completion message
25564 	 * from ARP. Mark the arp bringup as done. Also if the arp
25565 	 * stream has already started closing, send up the AR_ARP_CLOSING
25566 	 * ack now since ARP is waiting in close for this ack.
25567 	 */
25568 	mutex_enter(&ill->ill_lock);
25569 	ill->ill_arp_bringup_pending = 0;
25570 	if (ill->ill_arp_closing) {
25571 		mutex_exit(&ill->ill_lock);
25572 		/* Let's reuse the mp for sending the ack */
25573 		arc = (arc_t *)mp->b_rptr;
25574 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25575 		arc->arc_cmd = AR_ARP_CLOSING;
25576 		qreply(q, mp);
25577 	} else {
25578 		mutex_exit(&ill->ill_lock);
25579 		freeb(mp);
25580 	}
25581 
25582 	/* We should have an IOCTL waiting on this. */
25583 	ipsq = ill->ill_phyint->phyint_ipsq;
25584 	ipif = ipsq->ipsq_pending_ipif;
25585 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25586 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25587 	if (mp1 == NULL) {
25588 		/* bringup was aborted by the user */
25589 		freemsg(mp2);
25590 		return;
25591 	}
25592 	ASSERT(connp != NULL);
25593 	q = CONNP_TO_WQ(connp);
25594 	/*
25595 	 * If the DL_BIND_REQ fails, it is noted
25596 	 * in arc_name_offset.
25597 	 */
25598 	err = *((int *)mp2->b_rptr);
25599 	if (err == 0) {
25600 		if (ipif->ipif_isv6) {
25601 			if ((err = ipif_up_done_v6(ipif)) != 0)
25602 				ip0dbg(("ip_arp_done: init failed\n"));
25603 		} else {
25604 			if ((err = ipif_up_done(ipif)) != 0)
25605 				ip0dbg(("ip_arp_done: init failed\n"));
25606 		}
25607 	} else {
25608 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25609 	}
25610 
25611 	freemsg(mp2);
25612 
25613 	if ((err == 0) && (ill->ill_up_ipifs)) {
25614 		err = ill_up_ipifs(ill, q, mp1);
25615 		if (err == EINPROGRESS)
25616 			return;
25617 	}
25618 
25619 	if (ill->ill_up_ipifs) {
25620 		ill_group_cleanup(ill);
25621 	}
25622 
25623 	/*
25624 	 * The ioctl must complete now without EINPROGRESS
25625 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25626 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25627 	 * stuck for ever in the ipsq.
25628 	 */
25629 	ASSERT(err != EINPROGRESS);
25630 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25631 }
25632 
25633 /* Allocate the private structure */
25634 static int
25635 ip_priv_alloc(void **bufp)
25636 {
25637 	void	*buf;
25638 
25639 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25640 		return (ENOMEM);
25641 
25642 	*bufp = buf;
25643 	return (0);
25644 }
25645 
25646 /* Function to delete the private structure */
25647 void
25648 ip_priv_free(void *buf)
25649 {
25650 	ASSERT(buf != NULL);
25651 	kmem_free(buf, sizeof (ip_priv_t));
25652 }
25653 
25654 /*
25655  * The entry point for IPPF processing.
25656  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25657  * routine just returns.
25658  *
25659  * When called, ip_process generates an ipp_packet_t structure
25660  * which holds the state information for this packet and invokes the
25661  * the classifier (via ipp_packet_process). The classification, depending on
25662  * configured filters, results in a list of actions for this packet. Invoking
25663  * an action may cause the packet to be dropped, in which case the resulting
25664  * mblk (*mpp) is NULL. proc indicates the callout position for
25665  * this packet and ill_index is the interface this packet on or will leave
25666  * on (inbound and outbound resp.).
25667  */
25668 void
25669 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25670 {
25671 	mblk_t		*mp;
25672 	ip_priv_t	*priv;
25673 	ipp_action_id_t	aid;
25674 	int		rc = 0;
25675 	ipp_packet_t	*pp;
25676 #define	IP_CLASS	"ip"
25677 
25678 	/* If the classifier is not loaded, return  */
25679 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25680 		return;
25681 	}
25682 
25683 	mp = *mpp;
25684 	ASSERT(mp != NULL);
25685 
25686 	/* Allocate the packet structure */
25687 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25688 	if (rc != 0) {
25689 		*mpp = NULL;
25690 		freemsg(mp);
25691 		return;
25692 	}
25693 
25694 	/* Allocate the private structure */
25695 	rc = ip_priv_alloc((void **)&priv);
25696 	if (rc != 0) {
25697 		*mpp = NULL;
25698 		freemsg(mp);
25699 		ipp_packet_free(pp);
25700 		return;
25701 	}
25702 	priv->proc = proc;
25703 	priv->ill_index = ill_index;
25704 	ipp_packet_set_private(pp, priv, ip_priv_free);
25705 	ipp_packet_set_data(pp, mp);
25706 
25707 	/* Invoke the classifier */
25708 	rc = ipp_packet_process(&pp);
25709 	if (pp != NULL) {
25710 		mp = ipp_packet_get_data(pp);
25711 		ipp_packet_free(pp);
25712 		if (rc != 0) {
25713 			freemsg(mp);
25714 			*mpp = NULL;
25715 		}
25716 	} else {
25717 		*mpp = NULL;
25718 	}
25719 #undef	IP_CLASS
25720 }
25721 
25722 /*
25723  * Propagate a multicast group membership operation (add/drop) on
25724  * all the interfaces crossed by the related multirt routes.
25725  * The call is considered successful if the operation succeeds
25726  * on at least one interface.
25727  */
25728 static int
25729 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25730     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25731     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25732     mblk_t *first_mp)
25733 {
25734 	ire_t		*ire_gw;
25735 	irb_t		*irb;
25736 	int		error = 0;
25737 	opt_restart_t	*or;
25738 
25739 	irb = ire->ire_bucket;
25740 	ASSERT(irb != NULL);
25741 
25742 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25743 
25744 	or = (opt_restart_t *)first_mp->b_rptr;
25745 	IRB_REFHOLD(irb);
25746 	for (; ire != NULL; ire = ire->ire_next) {
25747 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25748 			continue;
25749 		if (ire->ire_addr != group)
25750 			continue;
25751 
25752 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25753 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25754 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25755 		/* No resolver exists for the gateway; skip this ire. */
25756 		if (ire_gw == NULL)
25757 			continue;
25758 
25759 		/*
25760 		 * This function can return EINPROGRESS. If so the operation
25761 		 * will be restarted from ip_restart_optmgmt which will
25762 		 * call ip_opt_set and option processing will restart for
25763 		 * this option. So we may end up calling 'fn' more than once.
25764 		 * This requires that 'fn' is idempotent except for the
25765 		 * return value. The operation is considered a success if
25766 		 * it succeeds at least once on any one interface.
25767 		 */
25768 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25769 		    NULL, fmode, src, first_mp);
25770 		if (error == 0)
25771 			or->or_private = CGTP_MCAST_SUCCESS;
25772 
25773 		if (ip_debug > 0) {
25774 			ulong_t	off;
25775 			char	*ksym;
25776 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25777 			ip2dbg(("ip_multirt_apply_membership: "
25778 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25779 			    "error %d [success %u]\n",
25780 			    ksym ? ksym : "?",
25781 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25782 			    error, or->or_private));
25783 		}
25784 
25785 		ire_refrele(ire_gw);
25786 		if (error == EINPROGRESS) {
25787 			IRB_REFRELE(irb);
25788 			return (error);
25789 		}
25790 	}
25791 	IRB_REFRELE(irb);
25792 	/*
25793 	 * Consider the call as successful if we succeeded on at least
25794 	 * one interface. Otherwise, return the last encountered error.
25795 	 */
25796 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25797 }
25798 
25799 
25800 /*
25801  * Issue a warning regarding a route crossing an interface with an
25802  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25803  * amount of time is logged.
25804  */
25805 static void
25806 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25807 {
25808 	hrtime_t	current = gethrtime();
25809 	char		buf[16];
25810 
25811 	/* Convert interval in ms to hrtime in ns */
25812 	if (multirt_bad_mtu_last_time +
25813 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25814 	    current) {
25815 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25816 		    "to %s, incorrect MTU %u (expected %u)\n",
25817 		    ip_dot_addr(ire->ire_addr, buf),
25818 		    ire->ire_max_frag, max_frag);
25819 
25820 		multirt_bad_mtu_last_time = current;
25821 	}
25822 }
25823 
25824 
25825 /*
25826  * Get the CGTP (multirouting) filtering status.
25827  * If 0, the CGTP hooks are transparent.
25828  */
25829 /* ARGSUSED */
25830 static int
25831 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25832 {
25833 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25834 
25835 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25836 	return (0);
25837 }
25838 
25839 
25840 /*
25841  * Set the CGTP (multirouting) filtering status.
25842  * If the status is changed from active to transparent
25843  * or from transparent to active, forward the new status
25844  * to the filtering module (if loaded).
25845  */
25846 /* ARGSUSED */
25847 static int
25848 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25849     cred_t *ioc_cr)
25850 {
25851 	long		new_value;
25852 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25853 
25854 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25855 	    new_value < 0 || new_value > 1) {
25856 		return (EINVAL);
25857 	}
25858 
25859 	/*
25860 	 * Do not enable CGTP filtering - thus preventing the hooks
25861 	 * from being invoked - if the version number of the
25862 	 * filtering module hooks does not match.
25863 	 */
25864 	if ((ip_cgtp_filter_ops != NULL) &&
25865 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25866 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25867 		    "(module hooks version %d, expecting %d)\n",
25868 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25869 		return (ENOTSUP);
25870 	}
25871 
25872 	if ((!*ip_cgtp_filter_value) && new_value) {
25873 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25874 		    ip_cgtp_filter_ops == NULL ?
25875 		    " (module not loaded)" : "");
25876 	}
25877 	if (*ip_cgtp_filter_value && (!new_value)) {
25878 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25879 		    ip_cgtp_filter_ops == NULL ?
25880 		    " (module not loaded)" : "");
25881 	}
25882 
25883 	if (ip_cgtp_filter_ops != NULL) {
25884 		int	res;
25885 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25886 			return (res);
25887 		}
25888 	}
25889 
25890 	*ip_cgtp_filter_value = (boolean_t)new_value;
25891 
25892 	return (0);
25893 }
25894 
25895 
25896 /*
25897  * Return the expected CGTP hooks version number.
25898  */
25899 int
25900 ip_cgtp_filter_supported(void)
25901 {
25902 	return (ip_cgtp_filter_rev);
25903 }
25904 
25905 
25906 /*
25907  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25908  * or by invoking this function. In the first case, the version number
25909  * of the registered structure is checked at hooks activation time
25910  * in ip_cgtp_filter_set().
25911  */
25912 int
25913 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25914 {
25915 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25916 		return (ENOTSUP);
25917 
25918 	ip_cgtp_filter_ops = ops;
25919 	return (0);
25920 }
25921 
25922 static squeue_func_t
25923 ip_squeue_switch(int val)
25924 {
25925 	squeue_func_t rval = squeue_fill;
25926 
25927 	switch (val) {
25928 	case IP_SQUEUE_ENTER_NODRAIN:
25929 		rval = squeue_enter_nodrain;
25930 		break;
25931 	case IP_SQUEUE_ENTER:
25932 		rval = squeue_enter;
25933 		break;
25934 	default:
25935 		break;
25936 	}
25937 	return (rval);
25938 }
25939 
25940 /* ARGSUSED */
25941 static int
25942 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25943     caddr_t addr, cred_t *cr)
25944 {
25945 	int *v = (int *)addr;
25946 	long new_value;
25947 
25948 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25949 		return (EINVAL);
25950 
25951 	ip_input_proc = ip_squeue_switch(new_value);
25952 	*v = new_value;
25953 	return (0);
25954 }
25955 
25956 /* ARGSUSED */
25957 static int
25958 ip_fanout_set(queue_t *q, mblk_t *mp, char *value,
25959     caddr_t addr, cred_t *cr)
25960 {
25961 	int *v = (int *)addr;
25962 	long new_value;
25963 
25964 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25965 		return (EINVAL);
25966 
25967 	*v = new_value;
25968 	return (0);
25969 }
25970 
25971 
25972 static void
25973 ip_kstat_init(void)
25974 {
25975 	ip_named_kstat_t template = {
25976 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
25977 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
25978 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
25979 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
25980 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
25981 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
25982 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
25983 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
25984 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
25985 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
25986 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
25987 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
25988 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
25989 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
25990 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
25991 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
25992 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
25993 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
25994 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
25995 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
25996 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
25997 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
25998 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
25999 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26000 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26001 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26002 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26003 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26004 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26005 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26006 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26007 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26008 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26009 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26010 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26011 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26012 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26013 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26014 	};
26015 
26016 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26017 					NUM_OF_FIELDS(ip_named_kstat_t),
26018 					0);
26019 	if (!ip_mibkp)
26020 		return;
26021 
26022 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26023 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26024 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26025 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26026 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26027 
26028 	template.netToMediaEntrySize.value.i32 =
26029 		sizeof (mib2_ipNetToMediaEntry_t);
26030 
26031 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26032 
26033 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26034 
26035 	ip_mibkp->ks_update = ip_kstat_update;
26036 
26037 	kstat_install(ip_mibkp);
26038 }
26039 
26040 static void
26041 ip_kstat_fini(void)
26042 {
26043 
26044 	if (ip_mibkp != NULL) {
26045 		kstat_delete(ip_mibkp);
26046 		ip_mibkp = NULL;
26047 	}
26048 }
26049 
26050 static int
26051 ip_kstat_update(kstat_t *kp, int rw)
26052 {
26053 	ip_named_kstat_t *ipkp;
26054 
26055 	if (!kp || !kp->ks_data)
26056 		return (EIO);
26057 
26058 	if (rw == KSTAT_WRITE)
26059 		return (EACCES);
26060 
26061 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26062 
26063 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26064 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26065 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26066 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26067 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26068 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26069 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26070 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26071 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26072 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26073 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26074 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26075 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26076 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26077 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26078 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26079 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26080 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26081 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26082 
26083 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26084 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26085 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26086 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26087 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26088 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26089 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26090 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26091 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26092 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26093 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26094 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26095 
26096 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
26097 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
26098 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
26099 
26100 	return (0);
26101 }
26102 
26103 static void
26104 icmp_kstat_init(void)
26105 {
26106 	icmp_named_kstat_t template = {
26107 		{ "inMsgs",		KSTAT_DATA_UINT32 },
26108 		{ "inErrors",		KSTAT_DATA_UINT32 },
26109 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
26110 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
26111 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
26112 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
26113 		{ "inRedirects",	KSTAT_DATA_UINT32 },
26114 		{ "inEchos",		KSTAT_DATA_UINT32 },
26115 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
26116 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
26117 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
26118 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
26119 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
26120 		{ "outMsgs",		KSTAT_DATA_UINT32 },
26121 		{ "outErrors",		KSTAT_DATA_UINT32 },
26122 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
26123 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
26124 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
26125 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
26126 		{ "outRedirects",	KSTAT_DATA_UINT32 },
26127 		{ "outEchos",		KSTAT_DATA_UINT32 },
26128 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
26129 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
26130 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
26131 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
26132 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
26133 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
26134 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
26135 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
26136 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
26137 		{ "outDrops",		KSTAT_DATA_UINT32 },
26138 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
26139 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
26140 	};
26141 
26142 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
26143 					NUM_OF_FIELDS(icmp_named_kstat_t),
26144 					0);
26145 	if (icmp_mibkp == NULL)
26146 		return;
26147 
26148 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
26149 
26150 	icmp_mibkp->ks_update = icmp_kstat_update;
26151 
26152 	kstat_install(icmp_mibkp);
26153 }
26154 
26155 static void
26156 icmp_kstat_fini(void)
26157 {
26158 
26159 	if (icmp_mibkp != NULL) {
26160 		kstat_delete(icmp_mibkp);
26161 		icmp_mibkp = NULL;
26162 	}
26163 }
26164 
26165 static int
26166 icmp_kstat_update(kstat_t *kp, int rw)
26167 {
26168 	icmp_named_kstat_t *icmpkp;
26169 
26170 	if ((kp == NULL) || (kp->ks_data == NULL))
26171 		return (EIO);
26172 
26173 	if (rw == KSTAT_WRITE)
26174 		return (EACCES);
26175 
26176 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
26177 
26178 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
26179 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
26180 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
26181 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
26182 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
26183 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
26184 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
26185 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
26186 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
26187 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
26188 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
26189 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
26190 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
26191 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
26192 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
26193 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
26194 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
26195 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
26196 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
26197 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
26198 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
26199 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
26200 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
26201 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
26202 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
26203 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
26204 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
26205 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
26206 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
26207 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
26208 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
26209 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
26210 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
26211 
26212 	return (0);
26213 }
26214 
26215 /*
26216  * This is the fanout function for raw socket opened for SCTP.  Note
26217  * that it is called after SCTP checks that there is no socket which
26218  * wants a packet.  Then before SCTP handles this out of the blue packet,
26219  * this function is called to see if there is any raw socket for SCTP.
26220  * If there is and it is bound to the correct address, the packet will
26221  * be sent to that socket.  Note that only one raw socket can be bound to
26222  * a port.  This is assured in ipcl_sctp_hash_insert();
26223  */
26224 void
26225 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
26226     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
26227     uint_t ipif_seqid, zoneid_t zoneid)
26228 {
26229 	conn_t		*connp;
26230 	queue_t		*rq;
26231 	mblk_t		*first_mp;
26232 	boolean_t	secure;
26233 	ip6_t		*ip6h;
26234 
26235 	first_mp = mp;
26236 	if (mctl_present) {
26237 		mp = first_mp->b_cont;
26238 		secure = ipsec_in_is_secure(first_mp);
26239 		ASSERT(mp != NULL);
26240 	} else {
26241 		secure = B_FALSE;
26242 	}
26243 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
26244 
26245 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
26246 	if (connp == NULL) {
26247 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
26248 		    mctl_present);
26249 		return;
26250 	}
26251 	rq = connp->conn_rq;
26252 	if (!canputnext(rq)) {
26253 		CONN_DEC_REF(connp);
26254 		BUMP_MIB(&ip_mib, rawipInOverflows);
26255 		freemsg(first_mp);
26256 		return;
26257 	}
26258 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
26259 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
26260 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
26261 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
26262 		if (first_mp == NULL) {
26263 			CONN_DEC_REF(connp);
26264 			return;
26265 		}
26266 	}
26267 	/*
26268 	 * We probably should not send M_CTL message up to
26269 	 * raw socket.
26270 	 */
26271 	if (mctl_present)
26272 		freeb(first_mp);
26273 
26274 	/* Initiate IPPF processing here if needed. */
26275 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
26276 	    (!isv4 && IP6_IN_IPP(flags))) {
26277 		ip_process(IPP_LOCAL_IN, &mp,
26278 		    recv_ill->ill_phyint->phyint_ifindex);
26279 		if (mp == NULL) {
26280 			CONN_DEC_REF(connp);
26281 			return;
26282 		}
26283 	}
26284 
26285 	if (connp->conn_recvif || connp->conn_recvslla ||
26286 	    ((connp->conn_ipv6_recvpktinfo ||
26287 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
26288 	    (flags & IP_FF_IP6INFO))) {
26289 		int in_flags = 0;
26290 
26291 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
26292 			in_flags = IPF_RECVIF;
26293 		}
26294 		if (connp->conn_recvslla) {
26295 			in_flags |= IPF_RECVSLLA;
26296 		}
26297 		if (isv4) {
26298 			mp = ip_add_info(mp, recv_ill, in_flags);
26299 		} else {
26300 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
26301 			if (mp == NULL) {
26302 				CONN_DEC_REF(connp);
26303 				return;
26304 			}
26305 		}
26306 	}
26307 
26308 	BUMP_MIB(&ip_mib, ipInDelivers);
26309 	/*
26310 	 * We are sending the IPSEC_IN message also up. Refer
26311 	 * to comments above this function.
26312 	 */
26313 	putnext(rq, mp);
26314 	CONN_DEC_REF(connp);
26315 }
26316 
26317 /*
26318  * Martian Address Filtering [RFC 1812, Section 5.3.7]
26319  */
26320 static boolean_t
26321 ip_no_forward(ipha_t *ipha, ill_t *ill)
26322 {
26323 	ipaddr_t ip_src, ip_dst;
26324 	ire_t *src_ire = NULL;
26325 
26326 	ip_src = ntohl(ipha->ipha_src);
26327 	ip_dst = ntohl(ipha->ipha_dst);
26328 
26329 	if (ip_dst == INADDR_ANY)
26330 		goto dont_forward;
26331 
26332 	if (IN_CLASSD(ip_src))
26333 		goto dont_forward;
26334 
26335 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
26336 		goto dont_forward;
26337 
26338 	if (IN_BADCLASS(ip_dst))
26339 		goto dont_forward;
26340 
26341 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
26342 	    ALL_ZONES, MATCH_IRE_TYPE);
26343 	if (src_ire != NULL) {
26344 		ire_refrele(src_ire);
26345 		goto dont_forward;
26346 	}
26347 
26348 	return (B_FALSE);
26349 
26350 dont_forward:
26351 	if (ip_debug > 2) {
26352 		printf("ip_no_forward: dropping packet received on %s\n",
26353 		    ill->ill_name);
26354 		pr_addr_dbg("ip_no_forward: from src %s\n",
26355 		    AF_INET, &ipha->ipha_src);
26356 		pr_addr_dbg("ip_no_forward: to dst %s\n",
26357 		    AF_INET, &ipha->ipha_dst);
26358 	}
26359 	BUMP_MIB(&ip_mib, ipForwProhibits);
26360 	return (B_TRUE);
26361 }
26362 
26363 static boolean_t
26364 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
26365 {
26366 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
26367 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
26368 		if (ip_debug > 2) {
26369 			if (ill != NULL) {
26370 				printf("ip_loopback_src_or_dst: "
26371 				    "dropping packet received on %s\n",
26372 				    ill->ill_name);
26373 			} else {
26374 				printf("ip_loopback_src_or_dst: "
26375 				    "dropping packet\n");
26376 			}
26377 
26378 			pr_addr_dbg(
26379 			    "ip_loopback_src_or_dst: from src %s\n",
26380 			    AF_INET, &ipha->ipha_src);
26381 			pr_addr_dbg(
26382 			    "ip_loopback_src_or_dst: to dst %s\n",
26383 			    AF_INET, &ipha->ipha_dst);
26384 		}
26385 
26386 		BUMP_MIB(&ip_mib, ipInAddrErrors);
26387 		return (B_TRUE);
26388 	}
26389 	return (B_FALSE);
26390 }
26391