xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision a7872406)
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/ip6.h>
79 #include <inet/ip6_asp.h>
80 #include <inet/tcp.h>
81 #include <inet/ip_multi.h>
82 #include <inet/ip_if.h>
83 #include <inet/ip_ire.h>
84 #include <inet/ip_rts.h>
85 #include <inet/optcom.h>
86 #include <inet/ip_ndp.h>
87 #include <inet/ip_listutils.h>
88 #include <netinet/igmp.h>
89 #include <netinet/ip_mroute.h>
90 #include <inet/ipp_common.h>
91 
92 #include <net/pfkeyv2.h>
93 #include <inet/ipsec_info.h>
94 #include <inet/sadb.h>
95 #include <inet/ipsec_impl.h>
96 /* EXPORT DELETE START */
97 #include <sys/iphada.h>
98 /* EXPORT DELETE END */
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 
116 /*
117  * Values for squeue switch:
118  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
119  * IP_SQUEUE_ENTER: squeue_enter
120  * IP_SQUEUE_FILL: squeue_fill
121  */
122 int ip_squeue_enter = 2;
123 squeue_func_t ip_input_proc;
124 /*
125  * IP statistics.
126  */
127 #define	IP_STAT(x)	(ip_statistics.x.value.ui64++)
128 
129 typedef struct ip_stat {
130 	kstat_named_t	ipsec_fanout_proto;
131 	kstat_named_t	ip_udp_fannorm;
132 	kstat_named_t	ip_udp_fanmb;
133 	kstat_named_t	ip_udp_fanothers;
134 	kstat_named_t	ip_udp_fast_path;
135 	kstat_named_t	ip_udp_slow_path;
136 	kstat_named_t	ip_udp_input_err;
137 	kstat_named_t	ip_tcppullup;
138 	kstat_named_t	ip_tcpoptions;
139 	kstat_named_t	ip_multipkttcp;
140 	kstat_named_t	ip_tcp_fast_path;
141 	kstat_named_t	ip_tcp_slow_path;
142 	kstat_named_t	ip_tcp_input_error;
143 	kstat_named_t	ip_db_ref;
144 	kstat_named_t	ip_notaligned1;
145 	kstat_named_t	ip_notaligned2;
146 	kstat_named_t	ip_multimblk3;
147 	kstat_named_t	ip_multimblk4;
148 	kstat_named_t	ip_ipoptions;
149 	kstat_named_t	ip_classify_fail;
150 	kstat_named_t	ip_opt;
151 	kstat_named_t	ip_udp_rput_local;
152 	kstat_named_t	ipsec_proto_ahesp;
153 	kstat_named_t	ip_conn_flputbq;
154 	kstat_named_t	ip_conn_walk_drain;
155 	kstat_named_t   ip_out_sw_cksum;
156 	kstat_named_t   ip_in_sw_cksum;
157 	kstat_named_t   ip_trash_ire_reclaim_calls;
158 	kstat_named_t   ip_trash_ire_reclaim_success;
159 	kstat_named_t   ip_ire_arp_timer_expired;
160 	kstat_named_t   ip_ire_redirect_timer_expired;
161 	kstat_named_t	ip_ire_pmtu_timer_expired;
162 	kstat_named_t	ip_input_multi_squeue;
163 } ip_stat_t;
164 
165 static ip_stat_t ip_statistics = {
166 	{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
167 	{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
168 	{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
169 	{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
170 	{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
171 	{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
172 	{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
173 	{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
174 	{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
175 	{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
176 	{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
177 	{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
178 	{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
179 	{ "ip_db_ref",			KSTAT_DATA_UINT64 },
180 	{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
181 	{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
182 	{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
183 	{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
184 	{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
185 	{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
186 	{ "ip_opt",			KSTAT_DATA_UINT64 },
187 	{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
188 	{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
189 	{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
190 	{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
191 	{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
192 	{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
193 	{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
194 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
195 	{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
196 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
197 	{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
198 	{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
199 };
200 
201 static kstat_t *ip_kstat;
202 
203 #define	TCP6 "tcp6"
204 #define	TCP "tcp"
205 #define	SCTP "sctp"
206 #define	SCTP6 "sctp6"
207 
208 major_t TCP6_MAJ;
209 major_t TCP_MAJ;
210 major_t SCTP_MAJ;
211 major_t SCTP6_MAJ;
212 
213 int ip_poll_normal_ms = 100;
214 int ip_poll_normal_ticks = 0;
215 
216 /*
217  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
218  */
219 
220 struct listptr_s {
221 	mblk_t	*lp_head;	/* pointer to the head of the list */
222 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
223 };
224 
225 typedef struct listptr_s listptr_t;
226 
227 /*
228  * Cluster specific hooks. These should be NULL when booted as a non-cluster
229  */
230 
231 /*
232  * Hook functions to enable cluster networking
233  * On non-clustered systems these vectors must always be NULL.
234  *
235  * Hook function to Check ip specified ip address is a shared ip address
236  * in the cluster
237  *
238  */
239 int (*cl_inet_isclusterwide)(uint8_t protocol,
240     sa_family_t addr_family, uint8_t *laddrp) = NULL;
241 
242 /*
243  * Hook function to generate cluster wide ip fragment identifier
244  */
245 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
246     uint8_t *laddrp, uint8_t *faddrp) = NULL;
247 
248 /*
249  * Synchronization notes:
250  *
251  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
252  * MT level protection given by STREAMS. IP uses a combination of its own
253  * internal serialization mechanism and standard Solaris locking techniques.
254  * The internal serialization is per phyint (no IPMP) or per IPMP group.
255  * This is used to serialize plumbing operations, IPMP operations, certain
256  * multicast operations, most set ioctls, igmp/mld timers etc.
257  *
258  * Plumbing is a long sequence of operations involving message
259  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
260  * involved in plumbing operations. A natural model is to serialize these
261  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
262  * parallel without any interference. But various set ioctls on hme0 are best
263  * serialized. However if the system uses IPMP, the operations are easier if
264  * they are serialized on a per IPMP group basis since IPMP operations
265  * happen across ill's of a group. Thus the lowest common denominator is to
266  * serialize most set ioctls, multicast join/leave operations, IPMP operations
267  * igmp/mld timer operations, and processing of DLPI control messages received
268  * from drivers on a per IPMP group basis. If the system does not employ
269  * IPMP the serialization is on a per phyint basis. This serialization is
270  * provided by the ipsq_t and primitives operating on this. Details can
271  * be found in ip_if.c above the core primitives operating on ipsq_t.
272  *
273  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
274  * Simiarly lookup of an ire by a thread also returns a refheld ire.
275  * In addition ipif's and ill's referenced by the ire are also indirectly
276  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
277  * the ipif's address or netmask change as long as an ipif is refheld
278  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
279  * address of an ipif has to go through the ipsq_t. This ensures that only
280  * 1 such exclusive operation proceeds at any time on the ipif. It then
281  * deletes all ires associated with this ipif, and waits for all refcnts
282  * associated with this ipif to come down to zero. The address is changed
283  * only after the ipif has been quiesced. Then the ipif is brought up again.
284  * More details are described above the comment in ip_sioctl_flags.
285  *
286  * Packet processing is based mostly on IREs and are fully multi-threaded
287  * using standard Solaris MT techniques.
288  *
289  * There are explicit locks in IP to handle:
290  * - The ip_g_head list maintained by mi_open_link() and friends.
291  *
292  * - The reassembly data structures (one lock per hash bucket)
293  *
294  * - conn_lock is meant to protect conn_t fields. The fields actually
295  *   protected by conn_lock are documented in the conn_t definition.
296  *
297  * - ire_lock to protect some of the fields of the ire, IRE tables
298  *   (one lock per hash bucket). Refer to ip_ire.c for details.
299  *
300  * - ndp_g_lock and nce_lock for protecting NCEs.
301  *
302  * - ill_lock protects fields of the ill and ipif. Details in ip.h
303  *
304  * - ill_g_lock: This is a global reader/writer lock. Protects the following
305  *	* The AVL tree based global multi list of all ills.
306  *	* The linked list of all ipifs of an ill
307  *	* The <ill-ipsq> mapping
308  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
309  *	* The illgroup list threaded by ill_group_next.
310  *	* <ill-phyint> association
311  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
312  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
313  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
314  *   will all have to hold the ill_g_lock as writer for the actual duration
315  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
316  *   may be found in the IPMP section.
317  *
318  * - ill_lock:  This is a per ill mutex.
319  *   It protects some members of the ill and is documented below.
320  *   It also protects the <ill-ipsq> mapping
321  *   It also protects the illgroup list threaded by ill_group_next.
322  *   It also protects the <ill-phyint> assoc.
323  *   It also protects the list of ipifs hanging off the ill.
324  *
325  * - ipsq_lock: This is a per ipsq_t mutex lock.
326  *   This protects all the other members of the ipsq struct except
327  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
328  *
329  * - illgrp_lock: This is a per ill_group mutex lock.
330  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
331  *   which dictates which is the next ill in an ill_group that is to be chosen
332  *   for sending outgoing packets, through creation of an IRE_CACHE that
333  *   references this ill.
334  *
335  * - phyint_lock: This is a per phyint mutex lock. Protects just the
336  *   phyint_flags
337  *
338  * - ip_g_nd_lock: This is a global reader/writer lock.
339  *   Any call to nd_load to load a new parameter to the ND table must hold the
340  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
341  *   as reader.
342  *
343  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
344  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
345  *   uniqueness check also done atomically.
346  *
347  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
348  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
349  *   as a writer when adding or deleting elements from these lists, and
350  *   as a reader when walking these lists to send a SADB update to the
351  *   IPsec capable ills.
352  *
353  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
354  *   group list linked by ill_usesrc_grp_next. It also protects the
355  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
356  *   group is being added or deleted.  This lock is taken as a reader when
357  *   walking the list/group(eg: to get the number of members in a usesrc group).
358  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
359  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
360  *   example, it is not necessary to take this lock in the initial portion
361  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
362  *   ip_sioctl_flags since the these operations are executed exclusively and
363  *   that ensures that the "usesrc group state" cannot change. The "usesrc
364  *   group state" change can happen only in the latter part of
365  *   ip_sioctl_slifusesrc and in ill_delete.
366  *
367  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
368  *
369  * To change the <ill-phyint> association, the ill_g_lock must be held
370  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
371  * must be held.
372  *
373  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
374  * and the ill_lock of the ill in question must be held.
375  *
376  * To change the <ill-illgroup> association the ill_g_lock must be held as
377  * writer and the ill_lock of the ill in question must be held.
378  *
379  * To add or delete an ipif from the list of ipifs hanging off the ill,
380  * ill_g_lock (writer) and ill_lock must be held and the thread must be
381  * a writer on the associated ipsq,.
382  *
383  * To add or delete an ill to the system, the ill_g_lock must be held as
384  * writer and the thread must be a writer on the associated ipsq.
385  *
386  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
387  * must be a writer on the associated ipsq.
388  *
389  * Lock hierarchy
390  *
391  * Some lock hierarchy scenarios are listed below.
392  *
393  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
394  * ill_g_lock -> illgrp_lock -> ill_lock
395  * ill_g_lock -> ill_lock(s) -> phyint_lock
396  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
397  * ill_g_lock -> ip_addr_avail_lock
398  * conn_lock -> irb_lock -> ill_lock -> ire_lock
399  * ipsa_lock -> ill_g_lock -> ill_lock
400  * ill_g_lock -> ip_g_nd_lock
401  * irb_lock -> ill_lock -> ire_mrtun_lock
402  * irb_lock -> ill_lock -> ire_srcif_table_lock
403  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
404  * ipsec_capab_ills_lock -> ipsa_lock
405  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
406  *
407  * When more than 1 ill lock is needed to be held, all ill lock addresses
408  * are sorted on address and locked starting from highest addressed lock
409  * downward.
410  *
411  * IPSEC notes :
412  *
413  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
414  * in front of the actual packet. For outbound datagrams, the M_CTL
415  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
416  * information used by the IPSEC code for applying the right level of
417  * protection. The information initialized by IP in the ipsec_out_t
418  * is determined by the per-socket policy or global policy in the system.
419  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
420  * ipsec_info.h) which starts out with nothing in it. It gets filled
421  * with the right information if it goes through the AH/ESP code, which
422  * happens if the incoming packet is secure. The information initialized
423  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
424  * the policy requirements needed by per-socket policy or global policy
425  * is met or not.
426  *
427  * If there is both per-socket policy (set using setsockopt) and there
428  * is also global policy match for the 5 tuples of the socket,
429  * ipsec_override_policy() makes the decision of which one to use.
430  *
431  * For fully connected sockets i.e dst, src [addr, port] is known,
432  * conn_policy_cached is set indicating that policy has been cached.
433  * conn_in_enforce_policy may or may not be set depending on whether
434  * there is a global policy match or per-socket policy match.
435  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
436  * Once the right policy is set on the conn_t, policy cannot change for
437  * this socket. This makes life simpler for TCP (UDP ?) where
438  * re-transmissions go out with the same policy. For symmetry, policy
439  * is cached for fully connected UDP sockets also. Thus if policy is cached,
440  * it also implies that policy is latched i.e policy cannot change
441  * on these sockets. As we have the right policy on the conn, we don't
442  * have to lookup global policy for every outbound and inbound datagram
443  * and thus serving as an optimization. Note that a global policy change
444  * does not affect fully connected sockets if they have policy. If fully
445  * connected sockets did not have any policy associated with it, global
446  * policy change may affect them.
447  *
448  * IP Flow control notes:
449  *
450  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
451  * cannot be sent down to the driver by IP, because of a canput failure, IP
452  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
453  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
454  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
455  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
456  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
457  * the queued messages, and removes the conn from the drain list, if all
458  * messages were drained. It also qenables the next conn in the drain list to
459  * continue the drain process.
460  *
461  * In reality the drain list is not a single list, but a configurable number
462  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
463  * list. If the ip_wsrv of the next qenabled conn does not run, because the
464  * stream closes, ip_close takes responsibility to qenable the next conn in
465  * the drain list. The directly called ip_wput path always does a putq, if
466  * it cannot putnext. Thus synchronization problems are handled between
467  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
468  * functions that manipulate this drain list. Furthermore conn_drain_insert
469  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
470  * running on a queue at any time. conn_drain_tail can be simultaneously called
471  * from both ip_wsrv and ip_close.
472  *
473  * IPQOS notes:
474  *
475  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
476  * and IPQoS modules. IPPF includes hooks in IP at different control points
477  * (callout positions) which direct packets to IPQoS modules for policy
478  * processing. Policies, if present, are global.
479  *
480  * The callout positions are located in the following paths:
481  *		o local_in (packets destined for this host)
482  *		o local_out (packets orginating from this host )
483  *		o fwd_in  (packets forwarded by this m/c - inbound)
484  *		o fwd_out (packets forwarded by this m/c - outbound)
485  * Hooks at these callout points can be enabled/disabled using the ndd variable
486  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
487  * By default all the callout positions are enabled.
488  *
489  * Outbound (local_out)
490  * Hooks are placed in ip_wput_ire and ipsec_out_process.
491  *
492  * Inbound (local_in)
493  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
494  * TCP and UDP fanout routines.
495  *
496  * Forwarding (in and out)
497  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
498  *
499  * IP Policy Framework processing (IPPF processing)
500  * Policy processing for a packet is initiated by ip_process, which ascertains
501  * that the classifier (ipgpc) is loaded and configured, failing which the
502  * packet resumes normal processing in IP. If the clasifier is present, the
503  * packet is acted upon by one or more IPQoS modules (action instances), per
504  * filters configured in ipgpc and resumes normal IP processing thereafter.
505  * An action instance can drop a packet in course of its processing.
506  *
507  * A boolean variable, ip_policy, is used in all the fanout routines that can
508  * invoke ip_process for a packet. This variable indicates if the packet should
509  * to be sent for policy processing. The variable is set to B_TRUE by default,
510  * i.e. when the routines are invoked in the normal ip procesing path for a
511  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
512  * ip_policy is set to B_FALSE for all the routines called in these two
513  * functions because, in the former case,  we don't process loopback traffic
514  * currently while in the latter, the packets have already been processed in
515  * icmp_inbound.
516  *
517  * Zones notes:
518  *
519  * The partitioning rules for networking are as follows:
520  * 1) Packets coming from a zone must have a source address belonging to that
521  * zone.
522  * 2) Packets coming from a zone can only be sent on a physical interface on
523  * which the zone has an IP address.
524  * 3) Between two zones on the same machine, packet delivery is only allowed if
525  * there's a matching route for the destination and zone in the forwarding
526  * table.
527  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
528  * different zones can bind to the same port with the wildcard address
529  * (INADDR_ANY).
530  *
531  * The granularity of interface partitioning is at the logical interface level.
532  * Therefore, every zone has its own IP addresses, and incoming packets can be
533  * attributed to a zone unambiguously. A logical interface is placed into a zone
534  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
535  * structure. Rule (1) is implemented by modifying the source address selection
536  * algorithm so that the list of eligible addresses is filtered based on the
537  * sending process zone.
538  *
539  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
540  * across all zones, depending on their type. Here is the break-up:
541  *
542  * IRE type				Shared/exclusive
543  * --------				----------------
544  * IRE_BROADCAST			Exclusive
545  * IRE_DEFAULT (default routes)		Shared (*)
546  * IRE_LOCAL				Exclusive
547  * IRE_LOOPBACK				Exclusive
548  * IRE_PREFIX (net routes)		Shared (*)
549  * IRE_CACHE				Exclusive
550  * IRE_IF_NORESOLVER (interface routes)	Exclusive
551  * IRE_IF_RESOLVER (interface routes)	Exclusive
552  * IRE_HOST (host routes)		Shared (*)
553  *
554  * (*) A zone can only use a default or off-subnet route if the gateway is
555  * directly reachable from the zone, that is, if the gateway's address matches
556  * one of the zone's logical interfaces.
557  *
558  * Multiple zones can share a common broadcast address; typically all zones
559  * share the 255.255.255.255 address. Incoming as well as locally originated
560  * broadcast packets must be dispatched to all the zones on the broadcast
561  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
562  * since some zones may not be on the 10.16.72/24 network. To handle this, each
563  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
564  * sent to every zone that has an IRE_BROADCAST entry for the destination
565  * address on the input ill, see conn_wantpacket().
566  *
567  * Applications in different zones can join the same multicast group address.
568  * For IPv4, group memberships are per-logical interface, so they're already
569  * inherently part of a zone. For IPv6, group memberships are per-physical
570  * interface, so we distinguish IPv6 group memberships based on group address,
571  * interface and zoneid. In both cases, received multicast packets are sent to
572  * every zone for which a group membership entry exists. On IPv6 we need to
573  * check that the target zone still has an address on the receiving physical
574  * interface; it could have been removed since the application issued the
575  * IPV6_JOIN_GROUP.
576  */
577 
578 /*
579  * Squeue Fanout flags:
580  *	0: No fanout.
581  *	1: Fanout across all squeues
582  */
583 boolean_t	ip_squeue_fanout = 0;
584 
585 /*
586  * Maximum dups allowed per packet.
587  */
588 uint_t ip_max_frag_dups = 10;
589 
590 #define	IS_SIMPLE_IPH(ipha)						\
591 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
592 
593 /* RFC1122 Conformance */
594 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
595 
596 #ifdef	_BIG_ENDIAN
597 #define	IP_HDR_CSUM_TTL_ADJUST	256
598 #define	IP_TCP_CSUM_COMP	IPPROTO_TCP
599 #define	IP_UDP_CSUM_COMP	IPPROTO_UDP
600 #else
601 #define	IP_HDR_CSUM_TTL_ADJUST	1
602 #define	IP_TCP_CSUM_COMP	(IPPROTO_TCP << 8)
603 #define	IP_UDP_CSUM_COMP	(IPPROTO_UDP << 8)
604 #endif
605 
606 #define	TCP_CHECKSUM_OFFSET		16
607 #define	UDP_CHECKSUM_OFFSET		6
608 
609 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
610 
611 #define	UDPH_SIZE	8
612 
613 /* Leave room for ip_newroute to tack on the src and target addresses */
614 #define	OK_RESOLVER_MP(mp)						\
615 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
616 
617 static ipif_t	*conn_get_held_ipif(conn_t *, ipif_t **, int *);
618 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
619 
620 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
621 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
622 
623 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
624 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
625     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
626 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
627 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
628 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
629 		    ill_t *, zoneid_t);
630 static void	icmp_options_update(ipha_t *);
631 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
632 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
633 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
634 static void	icmp_redirect(mblk_t *);
635 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
636 
637 static void	ip_arp_news(queue_t *, mblk_t *);
638 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
639 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
640 char		*ip_dot_addr(ipaddr_t, char *);
641 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
642 int		ip_close(queue_t *, int);
643 static char	*ip_dot_saddr(uchar_t *, char *);
644 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
645 		    boolean_t, boolean_t, ill_t *, zoneid_t);
646 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
647 		    boolean_t, boolean_t, zoneid_t);
648 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
649 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
650 static void	ip_lrput(queue_t *, mblk_t *);
651 ipaddr_t	ip_massage_options(ipha_t *);
652 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
653 ipaddr_t	ip_net_mask(ipaddr_t);
654 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
655 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
656 		    conn_t *, uint32_t);
657 static int	ip_hdr_complete(ipha_t *, zoneid_t);
658 char		*ip_nv_lookup(nv_t *, int);
659 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
660 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
661 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
662 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
663 			    size_t);
664 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
665 void	ip_rput(queue_t *, mblk_t *);
666 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
667 		    void *dummy_arg);
668 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
669 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
670 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
671 			    ire_t *);
672 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
673 int		ip_snmp_get(queue_t *, mblk_t *);
674 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
681 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
682 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
683 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
685 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
686 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
687 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
689 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
690 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
691 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
692 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
693 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
694 static boolean_t	ip_source_routed(ipha_t *);
695 static boolean_t	ip_source_route_included(ipha_t *);
696 
697 static void	ip_unbind(queue_t *, mblk_t *);
698 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
699 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
700 static void	ip_wput_local_options(ipha_t *);
701 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
702     zoneid_t);
703 
704 static void	conn_drain_init(void);
705 static void	conn_drain_fini(void);
706 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
707 
708 static void	conn_walk_drain(void);
709 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
710     zoneid_t);
711 
712 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
713     zoneid_t);
714 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
715     void *dummy_arg);
716 
717 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
718 
719 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
720     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
721     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
722 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
723 
724 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
725 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
726     caddr_t, cred_t *);
727 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
728     caddr_t cp, cred_t *cr);
729 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
730     cred_t *);
731 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
732     caddr_t cp, cred_t *cr);
733 static int	ip_fanout_set(queue_t *, mblk_t *, char *, caddr_t,
734     cred_t *);
735 static squeue_func_t ip_squeue_switch(int);
736 
737 static void	ip_kstat_init(void);
738 static void	ip_kstat_fini(void);
739 static int	ip_kstat_update(kstat_t *kp, int rw);
740 static void	icmp_kstat_init(void);
741 static void	icmp_kstat_fini(void);
742 static int	icmp_kstat_update(kstat_t *kp, int rw);
743 
744 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
745 
746 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
747 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
748 
749 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
750     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
751 
752 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
753 
754 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
755 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
756 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
757 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
758 
759 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
760 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
761 
762 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
763 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
764 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
765 
766 /* How long, in seconds, we allow frags to hang around. */
767 #define	IP_FRAG_TIMEOUT	60
768 
769 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
770 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
771 
772 /* Protected by ip_mi_lock */
773 static void	*ip_g_head;		/* Instance Data List Head */
774 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
775 
776 /* Only modified during _init and _fini thus no locking is needed. */
777 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
778 
779 
780 static long ip_rput_pullups;
781 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
782 
783 vmem_t *ip_minor_arena;
784 
785 /*
786  * MIB-2 stuff for SNMP (both IP and ICMP)
787  */
788 mib2_ip_t	ip_mib;
789 mib2_icmp_t	icmp_mib;
790 
791 #ifdef DEBUG
792 uint32_t ipsechw_debug = 0;
793 #endif
794 
795 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
796 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
797 
798 uint_t	loopback_packets = 0;
799 
800 /*
801  * Multirouting/CGTP stuff
802  */
803 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
804 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
805 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
806 /* Interval (in ms) between consecutive 'bad MTU' warnings */
807 hrtime_t ip_multirt_log_interval = 1000;
808 /* Time since last warning issued. */
809 static hrtime_t	multirt_bad_mtu_last_time = 0;
810 
811 kmutex_t ip_trash_timer_lock;
812 krwlock_t ip_g_nd_lock;
813 
814 /*
815  * XXX following really should only be in a header. Would need more
816  * header and .c clean up first.
817  */
818 extern optdb_obj_t	ip_opt_obj;
819 
820 ulong_t ip_squeue_enter_unbound = 0;
821 
822 /*
823  * Named Dispatch Parameter Table.
824  * All of these are alterable, within the min/max values given, at run time.
825  */
826 static ipparam_t	lcl_param_arr[] = {
827 	/* min	max	value	name */
828 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
829 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
830 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
831 	{  0,	1,	0,	"ip_respond_to_timestamp"},
832 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
833 	{  0,	1,	1,	"ip_send_redirects"},
834 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
835 	{  0,	10,	0,	"ip_debug"},
836 	{  0,	10,	0,	"ip_mrtdebug"},
837 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
838 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
839 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
840 	{  1,	255,	255,	"ip_def_ttl" },
841 	{  0,	1,	0,	"ip_forward_src_routed"},
842 	{  0,	256,	32,	"ip_wroff_extra" },
843 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
844 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
845 	{  0,	1,	1,	"ip_path_mtu_discovery" },
846 	{  0,	240,	30,	"ip_ignore_delete_time" },
847 	{  0,	1,	0,	"ip_ignore_redirect" },
848 	{  0,	1,	1,	"ip_output_queue" },
849 	{  1,	254,	1,	"ip_broadcast_ttl" },
850 	{  0,	99999,	100,	"ip_icmp_err_interval" },
851 	{  1,	99999,	10,	"ip_icmp_err_burst" },
852 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
853 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
854 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
855 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
856 	{  0,	1,	1,	"icmp_accept_clear_messages" },
857 	{  0,	1,	1,	"igmp_accept_clear_messages" },
858 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
859 				"ip_ndp_delay_first_probe_time"},
860 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
861 				"ip_ndp_max_unicast_solicit"},
862 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
863 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
864 	{  0,	1,	0,	"ip6_forward_src_routed"},
865 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
866 	{  0,	1,	1,	"ip6_send_redirects"},
867 	{  0,	1,	0,	"ip6_ignore_redirect" },
868 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
869 
870 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
871 
872 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
873 
874 	{  0,	1,	1,	"pim_accept_clear_messages" },
875 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
876 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
877 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
878 	{  0,	15,	0,	"ip_policy_mask" },
879 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
880 	{  0,	255,	1,	"ip_multirt_ttl" },
881 	{  0,	1,	1,	"ip_multidata_outbound" },
882 #ifdef DEBUG
883 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
884 #endif
885 };
886 
887 ipparam_t	*ip_param_arr = lcl_param_arr;
888 
889 /* Extended NDP table */
890 static ipndp_t	lcl_ndp_arr[] = {
891 	/* getf			setf		data			name */
892 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
893 	    "ip_forwarding" },
894 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
895 	    "ip6_forwarding" },
896 	{  ip_ill_report,	NULL,		NULL,
897 	    "ip_ill_status" },
898 	{  ip_ipif_report,	NULL,		NULL,
899 	    "ip_ipif_status" },
900 	{  ip_ire_report,	NULL,		NULL,
901 	    "ipv4_ire_status" },
902 	{  ip_ire_report_mrtun,	NULL,		NULL,
903 	    "ipv4_mrtun_ire_status" },
904 	{  ip_ire_report_srcif,	NULL,		NULL,
905 	    "ipv4_srcif_ire_status" },
906 	{  ip_ire_report_v6,	NULL,		NULL,
907 	    "ipv6_ire_status" },
908 	{  ip_conn_report,	NULL,		NULL,
909 	    "ip_conn_status" },
910 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
911 	    "ip_rput_pullups" },
912 	{  ndp_report,		NULL,		NULL,
913 	    "ip_ndp_cache_report" },
914 	{  ip_srcid_report,	NULL,		NULL,
915 	    "ip_srcid_status" },
916 	{ ip_param_generic_get, ip_squeue_profile_set,
917 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
918 	{ ip_param_generic_get, ip_squeue_bind_set,
919 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
920 	{ ip_param_generic_get, ip_input_proc_set,
921 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
922 	{ ip_param_generic_get, ip_fanout_set,
923 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
924 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
925 	    "ip_cgtp_filter" }
926 };
927 
928 /*
929  * ip_g_forward controls IP forwarding.  It takes two values:
930  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
931  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
932  *
933  * RFC1122 says there must be a configuration switch to control forwarding,
934  * but that the default MUST be to not forward packets ever.  Implicit
935  * control based on configuration of multiple interfaces MUST NOT be
936  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
937  * and, in fact, it was the default.  That capability is now provided in the
938  * /etc/rc2.d/S69inet script.
939  */
940 int ip_g_forward = IP_FORWARD_DEFAULT;
941 
942 /* It also has an IPv6 counterpart. */
943 
944 int ipv6_forward = IP_FORWARD_DEFAULT;
945 
946 /* Following line is external, and in ip.h.  Normally marked with * *. */
947 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
948 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
949 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
950 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
951 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
952 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
953 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
954 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
955 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
956 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
957 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
958 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
959 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
960 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
961 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
962 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
963 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
964 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
965 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
966 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
967 #define	ip_output_queue			ip_param_arr[20].ip_param_value
968 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
969 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
970 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
971 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
972 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
973 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
974 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
975 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
976 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
977 
978 /* IPv6 configuration knobs */
979 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
980 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
981 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
982 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
983 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
984 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
985 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
986 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
987 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
988 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
989 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
990 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
991 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
992 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
993 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
994 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
995 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
996 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
997 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
998 #ifdef DEBUG
999 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1000 #else
1001 #define	ipv6_drop_inbound_icmpv6	0
1002 #endif
1003 
1004 
1005 /*
1006  * Table of IP ioctls encoding the various properties of the ioctl and
1007  * indexed based on the last byte of the ioctl command. Occasionally there
1008  * is a clash, and there is more than 1 ioctl with the same last byte.
1009  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1010  * ioctls are encoded in the misc table. An entry in the ndx table is
1011  * retrieved by indexing on the last byte of the ioctl command and comparing
1012  * the ioctl command with the value in the ndx table. In the event of a
1013  * mismatch the misc table is then searched sequentially for the desired
1014  * ioctl command.
1015  *
1016  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1017  */
1018 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1019 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 
1030 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1031 			MISC_CMD, ip_siocaddrt, NULL },
1032 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1033 			MISC_CMD, ip_siocdelrt, NULL },
1034 
1035 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1036 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1037 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1038 			IF_CMD, ip_sioctl_get_addr, NULL },
1039 
1040 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1041 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1042 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1043 			IPI_GET_CMD | IPI_REPL,
1044 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1045 
1046 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1047 			IPI_PRIV | IPI_WR | IPI_REPL,
1048 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1049 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1050 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1051 			IF_CMD, ip_sioctl_get_flags, NULL },
1052 
1053 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 
1056 	/* copyin size cannot be coded for SIOCGIFCONF */
1057 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1058 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1059 
1060 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1061 			IF_CMD, ip_sioctl_mtu, NULL },
1062 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1063 			IF_CMD, ip_sioctl_get_mtu, NULL },
1064 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1065 			IPI_GET_CMD | IPI_REPL,
1066 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1067 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1068 			IF_CMD, ip_sioctl_brdaddr, NULL },
1069 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1070 			IPI_GET_CMD | IPI_REPL,
1071 			IF_CMD, ip_sioctl_get_netmask, NULL },
1072 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1073 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1074 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1075 			IPI_GET_CMD | IPI_REPL,
1076 			IF_CMD, ip_sioctl_get_metric, NULL },
1077 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1078 			IF_CMD, ip_sioctl_metric, NULL },
1079 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 
1081 	/* See 166-168 below for extended SIOC*XARP ioctls */
1082 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1083 			MISC_CMD, ip_sioctl_arp, NULL },
1084 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1085 			MISC_CMD, ip_sioctl_arp, NULL },
1086 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1087 			MISC_CMD, ip_sioctl_arp, NULL },
1088 
1089 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 
1111 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1112 			MISC_CMD, if_unitsel, if_unitsel_restart },
1113 
1114 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 
1133 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1134 			IPI_PRIV | IPI_WR | IPI_MODOK,
1135 			IF_CMD, ip_sioctl_sifname, NULL },
1136 
1137 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 
1151 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1152 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1153 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1154 			IF_CMD, ip_sioctl_get_muxid, NULL },
1155 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1156 			IPI_PRIV | IPI_WR | IPI_REPL,
1157 			IF_CMD, ip_sioctl_muxid, NULL },
1158 
1159 	/* Both if and lif variants share same func */
1160 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1161 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1162 	/* Both if and lif variants share same func */
1163 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1164 			IPI_PRIV | IPI_WR | IPI_REPL,
1165 			IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_removeif,
1191 			ip_sioctl_removeif_restart },
1192 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_addif, NULL },
1195 #define	SIOCLIFADDR_NDX 112
1196 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1197 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1198 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1199 			IPI_GET_CMD | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_get_addr, NULL },
1201 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1202 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1203 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1204 			IPI_GET_CMD | IPI_REPL,
1205 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1206 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_PRIV | IPI_WR | IPI_REPL,
1208 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1209 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1210 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1211 			LIF_CMD, ip_sioctl_get_flags, NULL },
1212 
1213 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1214 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1215 
1216 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1217 			ip_sioctl_get_lifconf, NULL },
1218 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1219 			LIF_CMD, ip_sioctl_mtu, NULL },
1220 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1221 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1222 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1223 			IPI_GET_CMD | IPI_REPL,
1224 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1225 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1227 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1228 			IPI_GET_CMD | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1230 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1231 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1232 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1233 			IPI_GET_CMD | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_get_metric, NULL },
1235 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1236 			LIF_CMD, ip_sioctl_metric, NULL },
1237 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1238 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_slifname,
1240 			ip_sioctl_slifname_restart },
1241 
1242 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1243 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1244 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1247 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1248 			IPI_PRIV | IPI_WR | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_muxid, NULL },
1250 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1253 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_slifindex, 0 },
1256 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1257 			LIF_CMD, ip_sioctl_token, NULL },
1258 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1259 			IPI_GET_CMD | IPI_REPL,
1260 			LIF_CMD, ip_sioctl_get_token, NULL },
1261 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1262 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1263 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1264 			IPI_GET_CMD | IPI_REPL,
1265 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1266 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1267 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1268 
1269 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1272 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1273 			LIF_CMD, ip_siocdelndp_v6, NULL },
1274 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1275 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1276 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1277 			LIF_CMD, ip_siocsetndp_v6, NULL },
1278 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1279 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1280 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1281 			MISC_CMD, ip_sioctl_tonlink, NULL },
1282 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1283 			MISC_CMD, ip_sioctl_tmysite, NULL },
1284 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1285 			TUN_CMD, ip_sioctl_tunparam, NULL },
1286 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1287 			IPI_PRIV | IPI_WR,
1288 			TUN_CMD, ip_sioctl_tunparam, NULL },
1289 
1290 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1291 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1292 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1293 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1294 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1295 
1296 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1297 			IPI_PRIV | IPI_WR | IPI_REPL,
1298 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1299 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1300 			IPI_PRIV | IPI_WR | IPI_REPL,
1301 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1302 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1303 			IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1305 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1306 			IPI_GET_CMD | IPI_REPL,
1307 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1308 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1309 			IPI_GET_CMD | IPI_REPL,
1310 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1311 
1312 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1313 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1314 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1315 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1316 
1317 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1318 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1319 
1320 	/* These are handled in ip_sioctl_copyin_setup itself */
1321 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1322 			MISC_CMD, NULL, NULL },
1323 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1324 			MISC_CMD, NULL, NULL },
1325 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1326 
1327 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1328 			ip_sioctl_get_lifconf, NULL },
1329 
1330 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1331 			MISC_CMD, ip_sioctl_xarp, NULL },
1332 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1333 			MISC_CMD, ip_sioctl_xarp, NULL },
1334 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1335 			MISC_CMD, ip_sioctl_xarp, NULL },
1336 
1337 	/* SIOCPOPSOCKFS is not handled by IP */
1338 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1339 
1340 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1341 			IPI_GET_CMD | IPI_REPL,
1342 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1343 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_slifzone,
1346 			ip_sioctl_slifzone_restart },
1347 	/* 172-174 are SCTP ioctls and not handled by IP */
1348 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1350 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1351 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1352 			IPI_GET_CMD, LIF_CMD,
1353 			ip_sioctl_get_lifusesrc, 0 },
1354 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1355 			IPI_PRIV | IPI_WR,
1356 			LIF_CMD, ip_sioctl_slifusesrc,
1357 			NULL },
1358 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1359 			ip_sioctl_get_lifsrcof, NULL },
1360 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1361 			MISC_CMD, ip_sioctl_msfilter, NULL },
1362 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1363 			MISC_CMD, ip_sioctl_msfilter, NULL },
1364 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1365 			MISC_CMD, ip_sioctl_msfilter, NULL },
1366 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1367 			MISC_CMD, ip_sioctl_msfilter, NULL }
1368 };
1369 
1370 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1371 
1372 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1373 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1374 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1375 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1376 		TUN_CMD, ip_sioctl_tunparam, NULL },
1377 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1378 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1379 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1380 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1381 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1382 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1383 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1384 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1385 		MISC_CMD, mrt_ioctl},
1386 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1387 		MISC_CMD, mrt_ioctl},
1388 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1389 		MISC_CMD, mrt_ioctl}
1390 };
1391 
1392 int ip_misc_ioctl_count =
1393     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1394 
1395 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1396 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1397 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1398 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1399 					/* Settable in /etc/system */
1400 
1401 /* Defined in ip_ire.c */
1402 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1403 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1404 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1405 
1406 static nv_t	ire_nv_arr[] = {
1407 	{ IRE_BROADCAST, "BROADCAST" },
1408 	{ IRE_LOCAL, "LOCAL" },
1409 	{ IRE_LOOPBACK, "LOOPBACK" },
1410 	{ IRE_CACHE, "CACHE" },
1411 	{ IRE_DEFAULT, "DEFAULT" },
1412 	{ IRE_PREFIX, "PREFIX" },
1413 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1414 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1415 	{ IRE_HOST, "HOST" },
1416 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1417 	{ 0 }
1418 };
1419 
1420 nv_t	*ire_nv_tbl = ire_nv_arr;
1421 
1422 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1423 extern krwlock_t ipsec_capab_ills_lock;
1424 
1425 /* Packet dropper for IP IPsec processing failures */
1426 ipdropper_t ip_dropper;
1427 
1428 /* Simple ICMP IP Header Template */
1429 static ipha_t icmp_ipha = {
1430 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1431 };
1432 
1433 struct module_info ip_mod_info = {
1434 	5701, "ip", 1, INFPSZ, 65536, 1024
1435 };
1436 
1437 static struct qinit rinit = {
1438 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1439 	&ip_mod_info
1440 };
1441 
1442 static struct qinit winit = {
1443 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1444 	&ip_mod_info
1445 };
1446 
1447 static struct qinit lrinit = {
1448 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1449 	&ip_mod_info
1450 };
1451 
1452 static struct qinit lwinit = {
1453 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1454 	&ip_mod_info
1455 };
1456 
1457 struct streamtab ipinfo = {
1458 	&rinit, &winit, &lrinit, &lwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 /*
1465  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1466  */
1467 mblk_t *
1468 ip_copymsg(mblk_t *mp)
1469 {
1470 	mblk_t *nmp;
1471 	ipsec_info_t *in;
1472 
1473 	if (mp->b_datap->db_type != M_CTL)
1474 		return (copymsg(mp));
1475 
1476 	in = (ipsec_info_t *)mp->b_rptr;
1477 
1478 	/*
1479 	 * Note that M_CTL is also used for delivering ICMP error messages
1480 	 * upstream to transport layers.
1481 	 */
1482 	if (in->ipsec_info_type != IPSEC_OUT &&
1483 	    in->ipsec_info_type != IPSEC_IN)
1484 		return (copymsg(mp));
1485 
1486 	nmp = copymsg(mp->b_cont);
1487 
1488 	if (in->ipsec_info_type == IPSEC_OUT)
1489 		return (ipsec_out_tag(mp, nmp));
1490 	else
1491 		return (ipsec_in_tag(mp, nmp));
1492 }
1493 
1494 /* Generate an ICMP fragmentation needed message. */
1495 static void
1496 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1497 {
1498 	icmph_t	icmph;
1499 	mblk_t *first_mp;
1500 	boolean_t mctl_present;
1501 
1502 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1503 
1504 	if (!(mp = icmp_pkt_err_ok(mp))) {
1505 		if (mctl_present)
1506 			freeb(first_mp);
1507 		return;
1508 	}
1509 
1510 	bzero(&icmph, sizeof (icmph_t));
1511 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1512 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1513 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1514 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1515 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1516 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1517 }
1518 
1519 /*
1520  * icmp_inbound deals with ICMP messages in the following ways.
1521  *
1522  * 1) It needs to send a reply back and possibly delivering it
1523  *    to the "interested" upper clients.
1524  * 2) It needs to send it to the upper clients only.
1525  * 3) It needs to change some values in IP only.
1526  * 4) It needs to change some values in IP and upper layers e.g TCP.
1527  *
1528  * We need to accomodate icmp messages coming in clear until we get
1529  * everything secure from the wire. If icmp_accept_clear_messages
1530  * is zero we check with the global policy and act accordingly. If
1531  * it is non-zero, we accept the message without any checks. But
1532  * *this does not mean* that this will be delivered to the upper
1533  * clients. By accepting we might send replies back, change our MTU
1534  * value etc. but delivery to the ULP/clients depends on their policy
1535  * dispositions.
1536  *
1537  * We handle the above 4 cases in the context of IPSEC in the
1538  * following way :
1539  *
1540  * 1) Send the reply back in the same way as the request came in.
1541  *    If it came in encrypted, it goes out encrypted. If it came in
1542  *    clear, it goes out in clear. Thus, this will prevent chosen
1543  *    plain text attack.
1544  * 2) The client may or may not expect things to come in secure.
1545  *    If it comes in secure, the policy constraints are checked
1546  *    before delivering it to the upper layers. If it comes in
1547  *    clear, ipsec_inbound_accept_clear will decide whether to
1548  *    accept this in clear or not. In both the cases, if the returned
1549  *    message (IP header + 8 bytes) that caused the icmp message has
1550  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1551  *    sending up. If there are only 8 bytes of returned message, then
1552  *    upper client will not be notified.
1553  * 3) Check with global policy to see whether it matches the constaints.
1554  *    But this will be done only if icmp_accept_messages_in_clear is
1555  *    zero.
1556  * 4) If we need to change both in IP and ULP, then the decision taken
1557  *    while affecting the values in IP and while delivering up to TCP
1558  *    should be the same.
1559  *
1560  * 	There are two cases.
1561  *
1562  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1563  *	   failed), we will not deliver it to the ULP, even though they
1564  *	   are *willing* to accept in *clear*. This is fine as our global
1565  *	   disposition to icmp messages asks us reject the datagram.
1566  *
1567  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1568  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1569  *	   to deliver it to ULP (policy failed), it can lead to
1570  *	   consistency problems. The cases known at this time are
1571  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1572  *	   values :
1573  *
1574  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1575  *	     and Upper layer rejects. Then the communication will
1576  *	     come to a stop. This is solved by making similar decisions
1577  *	     at both levels. Currently, when we are unable to deliver
1578  *	     to the Upper Layer (due to policy failures) while IP has
1579  *	     adjusted ire_max_frag, the next outbound datagram would
1580  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1581  *	     will be with the right level of protection. Thus the right
1582  *	     value will be communicated even if we are not able to
1583  *	     communicate when we get from the wire initially. But this
1584  *	     assumes there would be at least one outbound datagram after
1585  *	     IP has adjusted its ire_max_frag value. To make things
1586  *	     simpler, we accept in clear after the validation of
1587  *	     AH/ESP headers.
1588  *
1589  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1590  *	     upper layer depending on the level of protection the upper
1591  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1592  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1593  *	     should be accepted in clear when the Upper layer expects secure.
1594  *	     Thus the communication may get aborted by some bad ICMP
1595  *	     packets.
1596  *
1597  * IPQoS Notes:
1598  * The only instance when a packet is sent for processing is when there
1599  * isn't an ICMP client and if we are interested in it.
1600  * If there is a client, IPPF processing will take place in the
1601  * ip_fanout_proto routine.
1602  *
1603  * Zones notes:
1604  * The packet is only processed in the context of the specified zone: typically
1605  * only this zone will reply to an echo request, and only interested clients in
1606  * this zone will receive a copy of the packet. This means that the caller must
1607  * call icmp_inbound() for each relevant zone.
1608  */
1609 static void
1610 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1611     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1612     ill_t *recv_ill, zoneid_t zoneid)
1613 {
1614 	icmph_t	*icmph;
1615 	ipha_t	*ipha;
1616 	int	iph_hdr_length;
1617 	int	hdr_length;
1618 	boolean_t	interested;
1619 	uint32_t	ts;
1620 	uchar_t	*wptr;
1621 	ipif_t	*ipif;
1622 	mblk_t *first_mp;
1623 	ipsec_in_t *ii;
1624 	ire_t *src_ire;
1625 	boolean_t onlink;
1626 	timestruc_t now;
1627 	uint32_t ill_index;
1628 
1629 	ASSERT(ill != NULL);
1630 
1631 	first_mp = mp;
1632 	if (mctl_present) {
1633 		mp = first_mp->b_cont;
1634 		ASSERT(mp != NULL);
1635 	}
1636 
1637 	ipha = (ipha_t *)mp->b_rptr;
1638 	if (icmp_accept_clear_messages == 0) {
1639 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1640 		    ipha, NULL, mctl_present);
1641 		if (first_mp == NULL)
1642 			return;
1643 	}
1644 	/*
1645 	 * We have accepted the ICMP message. It means that we will
1646 	 * respond to the packet if needed. It may not be delivered
1647 	 * to the upper client depending on the policy constraints
1648 	 * and the disposition in ipsec_inbound_accept_clear.
1649 	 */
1650 
1651 	ASSERT(ill != NULL);
1652 
1653 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1654 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1655 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1656 		/* Last chance to get real. */
1657 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1658 			BUMP_MIB(&icmp_mib, icmpInErrors);
1659 			freemsg(first_mp);
1660 			return;
1661 		}
1662 		/* Refresh iph following the pullup. */
1663 		ipha = (ipha_t *)mp->b_rptr;
1664 	}
1665 	/* ICMP header checksum, including checksum field, should be zero. */
1666 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1667 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1668 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1669 		freemsg(first_mp);
1670 		return;
1671 	}
1672 	/* The IP header will always be a multiple of four bytes */
1673 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1674 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1675 	    icmph->icmph_code));
1676 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1677 	/* We will set "interested" to "true" if we want a copy */
1678 	interested = B_FALSE;
1679 	switch (icmph->icmph_type) {
1680 	case ICMP_ECHO_REPLY:
1681 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1682 		break;
1683 	case ICMP_DEST_UNREACHABLE:
1684 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1685 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1686 		interested = B_TRUE;	/* Pass up to transport */
1687 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1688 		break;
1689 	case ICMP_SOURCE_QUENCH:
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1692 		break;
1693 	case ICMP_REDIRECT:
1694 		if (!ip_ignore_redirect)
1695 			interested = B_TRUE;
1696 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1697 		break;
1698 	case ICMP_ECHO_REQUEST:
1699 		/*
1700 		 * Whether to respond to echo requests that come in as IP
1701 		 * broadcasts or as IP multicast is subject to debate
1702 		 * (what isn't?).  We aim to please, you pick it.
1703 		 * Default is do it.
1704 		 */
1705 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1706 			/* unicast: always respond */
1707 			interested = B_TRUE;
1708 		} else if (CLASSD(ipha->ipha_dst)) {
1709 			/* multicast: respond based on tunable */
1710 			interested = ip_g_resp_to_echo_mcast;
1711 		} else if (broadcast) {
1712 			/* broadcast: respond based on tunable */
1713 			interested = ip_g_resp_to_echo_bcast;
1714 		}
1715 		BUMP_MIB(&icmp_mib, icmpInEchos);
1716 		break;
1717 	case ICMP_ROUTER_ADVERTISEMENT:
1718 	case ICMP_ROUTER_SOLICITATION:
1719 		break;
1720 	case ICMP_TIME_EXCEEDED:
1721 		interested = B_TRUE;	/* Pass up to transport */
1722 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1723 		break;
1724 	case ICMP_PARAM_PROBLEM:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1727 		break;
1728 	case ICMP_TIME_STAMP_REQUEST:
1729 		/* Response to Time Stamp Requests is local policy. */
1730 		if (ip_g_resp_to_timestamp &&
1731 		    /* So is whether to respond if it was an IP broadcast. */
1732 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1733 			int tstamp_len = 3 * sizeof (uint32_t);
1734 
1735 			if (wptr +  tstamp_len > mp->b_wptr) {
1736 				if (!pullupmsg(mp, wptr + tstamp_len -
1737 				    mp->b_rptr)) {
1738 					BUMP_MIB(&ip_mib, ipInDiscards);
1739 					freemsg(first_mp);
1740 					return;
1741 				}
1742 				/* Refresh ipha following the pullup. */
1743 				ipha = (ipha_t *)mp->b_rptr;
1744 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1745 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1746 			}
1747 			interested = B_TRUE;
1748 		}
1749 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1750 		break;
1751 	case ICMP_TIME_STAMP_REPLY:
1752 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1753 		break;
1754 	case ICMP_INFO_REQUEST:
1755 		/* Per RFC 1122 3.2.2.7, ignore this. */
1756 	case ICMP_INFO_REPLY:
1757 		break;
1758 	case ICMP_ADDRESS_MASK_REQUEST:
1759 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1760 		    /* TODO m_pullup of complete header? */
1761 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1762 			interested = B_TRUE;
1763 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1764 		break;
1765 	case ICMP_ADDRESS_MASK_REPLY:
1766 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1767 		break;
1768 	default:
1769 		interested = B_TRUE;	/* Pass up to transport */
1770 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1771 		break;
1772 	}
1773 	/* See if there is an ICMP client. */
1774 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1775 		/* If there is an ICMP client and we want one too, copy it. */
1776 		mblk_t *first_mp1;
1777 
1778 		if (!interested) {
1779 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1780 			    ip_policy, recv_ill, zoneid);
1781 			return;
1782 		}
1783 		first_mp1 = ip_copymsg(first_mp);
1784 		if (first_mp1 != NULL) {
1785 			ip_fanout_proto(q, first_mp1, ill, ipha,
1786 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1787 		}
1788 	} else if (!interested) {
1789 		freemsg(first_mp);
1790 		return;
1791 	} else {
1792 		/*
1793 		 * Initiate policy processing for this packet if ip_policy
1794 		 * is true.
1795 		 */
1796 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1797 			ill_index = ill->ill_phyint->phyint_ifindex;
1798 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1799 			if (mp == NULL) {
1800 				if (mctl_present) {
1801 					freeb(first_mp);
1802 				}
1803 				BUMP_MIB(&icmp_mib, icmpInErrors);
1804 				return;
1805 			}
1806 		}
1807 	}
1808 	/* We want to do something with it. */
1809 	/* Check db_ref to make sure we can modify the packet. */
1810 	if (mp->b_datap->db_ref > 1) {
1811 		mblk_t	*first_mp1;
1812 
1813 		first_mp1 = ip_copymsg(first_mp);
1814 		freemsg(first_mp);
1815 		if (!first_mp1) {
1816 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1817 			return;
1818 		}
1819 		first_mp = first_mp1;
1820 		if (mctl_present) {
1821 			mp = first_mp->b_cont;
1822 			ASSERT(mp != NULL);
1823 		} else {
1824 			mp = first_mp;
1825 		}
1826 		ipha = (ipha_t *)mp->b_rptr;
1827 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1828 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1829 	}
1830 	switch (icmph->icmph_type) {
1831 	case ICMP_ADDRESS_MASK_REQUEST:
1832 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1833 		if (ipif == NULL) {
1834 			freemsg(first_mp);
1835 			return;
1836 		}
1837 		/*
1838 		 * outging interface must be IPv4
1839 		 */
1840 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1841 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1842 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1843 		ipif_refrele(ipif);
1844 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1845 		break;
1846 	case ICMP_ECHO_REQUEST:
1847 		icmph->icmph_type = ICMP_ECHO_REPLY;
1848 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1849 		break;
1850 	case ICMP_TIME_STAMP_REQUEST: {
1851 		uint32_t *tsp;
1852 
1853 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1854 		tsp = (uint32_t *)wptr;
1855 		tsp++;		/* Skip past 'originate time' */
1856 		/* Compute # of milliseconds since midnight */
1857 		gethrestime(&now);
1858 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1859 		    now.tv_nsec / (NANOSEC / MILLISEC);
1860 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1861 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1862 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1863 		break;
1864 	}
1865 	default:
1866 		ipha = (ipha_t *)&icmph[1];
1867 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1868 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1869 				BUMP_MIB(&ip_mib, ipInDiscards);
1870 				freemsg(first_mp);
1871 				return;
1872 			}
1873 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1874 			ipha = (ipha_t *)&icmph[1];
1875 		}
1876 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1877 			BUMP_MIB(&ip_mib, ipInDiscards);
1878 			freemsg(first_mp);
1879 			return;
1880 		}
1881 		hdr_length = IPH_HDR_LENGTH(ipha);
1882 		if (hdr_length < sizeof (ipha_t)) {
1883 			BUMP_MIB(&ip_mib, ipInDiscards);
1884 			freemsg(first_mp);
1885 			return;
1886 		}
1887 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1888 			if (!pullupmsg(mp,
1889 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1890 				BUMP_MIB(&ip_mib, ipInDiscards);
1891 				freemsg(first_mp);
1892 				return;
1893 			}
1894 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1895 			ipha = (ipha_t *)&icmph[1];
1896 		}
1897 		switch (icmph->icmph_type) {
1898 		case ICMP_REDIRECT:
1899 			/*
1900 			 * As there is no upper client to deliver, we don't
1901 			 * need the first_mp any more.
1902 			 */
1903 			if (mctl_present) {
1904 				freeb(first_mp);
1905 			}
1906 			icmp_redirect(mp);
1907 			return;
1908 		case ICMP_DEST_UNREACHABLE:
1909 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1910 				if (!icmp_inbound_too_big(icmph, ipha)) {
1911 					freemsg(first_mp);
1912 					return;
1913 				}
1914 			}
1915 			/* FALLTHRU */
1916 		default :
1917 			/*
1918 			 * IPQoS notes: Since we have already done IPQoS
1919 			 * processing we don't want to do it again in
1920 			 * the fanout routines called by
1921 			 * icmp_inbound_error_fanout, hence the last
1922 			 * argument, ip_policy, is B_FALSE.
1923 			 */
1924 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1925 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1926 			    B_FALSE, recv_ill, zoneid);
1927 		}
1928 		return;
1929 	}
1930 	/* Send out an ICMP packet */
1931 	icmph->icmph_checksum = 0;
1932 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1933 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1934 		ipif_t	*ipif_chosen;
1935 		/*
1936 		 * Make it look like it was directed to us, so we don't look
1937 		 * like a fool with a broadcast or multicast source address.
1938 		 */
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		/*
1941 		 * Make sure that we haven't grabbed an interface that's DOWN.
1942 		 */
1943 		if (ipif != NULL) {
1944 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1945 			    ipha->ipha_src, zoneid);
1946 			if (ipif_chosen != NULL) {
1947 				ipif_refrele(ipif);
1948 				ipif = ipif_chosen;
1949 			}
1950 		}
1951 		if (ipif == NULL) {
1952 			ip0dbg(("icmp_inbound: "
1953 			    "No source for broadcast/multicast:\n"
1954 			    "\tsrc 0x%x dst 0x%x ill %p "
1955 			    "ipif_lcl_addr 0x%x\n",
1956 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1957 			    (void *)ill,
1958 			    ill->ill_ipif->ipif_lcl_addr));
1959 			freemsg(first_mp);
1960 			return;
1961 		}
1962 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1963 		ipha->ipha_dst = ipif->ipif_src_addr;
1964 		ipif_refrele(ipif);
1965 	}
1966 	/* Reset time to live. */
1967 	ipha->ipha_ttl = ip_def_ttl;
1968 	{
1969 		/* Swap source and destination addresses */
1970 		ipaddr_t tmp;
1971 
1972 		tmp = ipha->ipha_src;
1973 		ipha->ipha_src = ipha->ipha_dst;
1974 		ipha->ipha_dst = tmp;
1975 	}
1976 	ipha->ipha_ident = 0;
1977 	if (!IS_SIMPLE_IPH(ipha))
1978 		icmp_options_update(ipha);
1979 
1980 	/*
1981 	 * ICMP echo replies should go out on the same interface
1982 	 * the request came on as probes used by in.mpathd for detecting
1983 	 * NIC failures are ECHO packets. We turn-off load spreading
1984 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1985 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1986 	 * function. This is in turn handled by ip_wput and ip_newroute
1987 	 * to make sure that the packet goes out on the interface it came
1988 	 * in on. If we don't turnoff load spreading, the packets might get
1989 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1990 	 * to go out and in.mpathd would wrongly detect a failure or
1991 	 * mis-detect a NIC failure for link failure. As load spreading
1992 	 * can happen only if ill_group is not NULL, we do only for
1993 	 * that case and this does not affect the normal case.
1994 	 *
1995 	 * We turn off load spreading only on echo packets that came from
1996 	 * on-link hosts. If the interface route has been deleted, this will
1997 	 * not be enforced as we can't do much. For off-link hosts, as the
1998 	 * default routes in IPv4 does not typically have an ire_ipif
1999 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2000 	 * Moreover, expecting a default route through this interface may
2001 	 * not be correct. We use ipha_dst because of the swap above.
2002 	 */
2003 	onlink = B_FALSE;
2004 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2005 		/*
2006 		 * First, we need to make sure that it is not one of our
2007 		 * local addresses. If we set onlink when it is one of
2008 		 * our local addresses, we will end up creating IRE_CACHES
2009 		 * for one of our local addresses. Then, we will never
2010 		 * accept packets for them afterwards.
2011 		 */
2012 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2013 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2014 		if (src_ire == NULL) {
2015 			ipif = ipif_get_next_ipif(NULL, ill);
2016 			if (ipif == NULL) {
2017 				BUMP_MIB(&ip_mib, ipInDiscards);
2018 				freemsg(mp);
2019 				return;
2020 			}
2021 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2022 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2023 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2024 			ipif_refrele(ipif);
2025 			if (src_ire != NULL) {
2026 				onlink = B_TRUE;
2027 				ire_refrele(src_ire);
2028 			}
2029 		} else {
2030 			ire_refrele(src_ire);
2031 		}
2032 	}
2033 	if (!mctl_present) {
2034 		/*
2035 		 * This packet should go out the same way as it
2036 		 * came in i.e in clear. To make sure that global
2037 		 * policy will not be applied to this in ip_wput_ire,
2038 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2039 		 */
2040 		ASSERT(first_mp == mp);
2041 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2042 			BUMP_MIB(&ip_mib, ipInDiscards);
2043 			freemsg(mp);
2044 			return;
2045 		}
2046 		ii = (ipsec_in_t *)first_mp->b_rptr;
2047 
2048 		/* This is not a secure packet */
2049 		ii->ipsec_in_secure = B_FALSE;
2050 		if (onlink) {
2051 			ii->ipsec_in_attach_if = B_TRUE;
2052 			ii->ipsec_in_ill_index =
2053 			    ill->ill_phyint->phyint_ifindex;
2054 			ii->ipsec_in_rill_index =
2055 			    recv_ill->ill_phyint->phyint_ifindex;
2056 		}
2057 		first_mp->b_cont = mp;
2058 	} else if (onlink) {
2059 		ii = (ipsec_in_t *)first_mp->b_rptr;
2060 		ii->ipsec_in_attach_if = B_TRUE;
2061 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2062 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 	}
2066 	ii->ipsec_in_zoneid = zoneid;
2067 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2068 		BUMP_MIB(&ip_mib, ipInDiscards);
2069 		return;
2070 	}
2071 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2072 	put(WR(q), first_mp);
2073 }
2074 
2075 /* Table from RFC 1191 */
2076 static int icmp_frag_size_table[] =
2077 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2078 
2079 /*
2080  * Process received ICMP Packet too big.
2081  * After updating any IRE it does the fanout to any matching transport streams.
2082  * Assumes the message has been pulled up till the IP header that caused
2083  * the error.
2084  *
2085  * Returns B_FALSE on failure and B_TRUE on success.
2086  */
2087 static boolean_t
2088 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2089 {
2090 	ire_t	*ire, *first_ire;
2091 	int	mtu;
2092 	int	hdr_length;
2093 
2094 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2095 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2096 
2097 	hdr_length = IPH_HDR_LENGTH(ipha);
2098 
2099 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2100 	    ALL_ZONES, MATCH_IRE_TYPE);
2101 
2102 	if (!first_ire) {
2103 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2104 		    ntohl(ipha->ipha_dst)));
2105 		return (B_FALSE);
2106 	}
2107 	/* Drop if the original packet contained a source route */
2108 	if (ip_source_route_included(ipha)) {
2109 		ire_refrele(first_ire);
2110 		return (B_FALSE);
2111 	}
2112 	/* Check for MTU discovery advice as described in RFC 1191 */
2113 	mtu = ntohs(icmph->icmph_du_mtu);
2114 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2115 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2116 	    ire = ire->ire_next) {
2117 		mutex_enter(&ire->ire_lock);
2118 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2119 			/* Reduce the IRE max frag value as advised. */
2120 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2121 			ip1dbg(("Received mtu from router: %d\n", mtu));
2122 		} else {
2123 			uint32_t length;
2124 			int	i;
2125 
2126 			/*
2127 			 * Use the table from RFC 1191 to figure out
2128 			 * the next "plateau" based on the length in
2129 			 * the original IP packet.
2130 			 */
2131 			length = ntohs(ipha->ipha_length);
2132 			if (ire->ire_max_frag <= length &&
2133 			    ire->ire_max_frag >= length - hdr_length) {
2134 				/*
2135 				 * Handle broken BSD 4.2 systems that
2136 				 * return the wrong iph_length in ICMP
2137 				 * errors.
2138 				 */
2139 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2140 				    length, ire->ire_max_frag));
2141 				length -= hdr_length;
2142 			}
2143 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2144 				if (length > icmp_frag_size_table[i])
2145 					break;
2146 			}
2147 			if (i == A_CNT(icmp_frag_size_table)) {
2148 				/* Smaller than 68! */
2149 				ip1dbg(("Too big for packet size %d\n",
2150 				    length));
2151 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2152 				ire->ire_frag_flag = 0;
2153 			} else {
2154 				mtu = icmp_frag_size_table[i];
2155 				ip1dbg(("Calculated mtu %d, packet size %d, "
2156 				    "before %d", mtu, length,
2157 				    ire->ire_max_frag));
2158 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2159 				ip1dbg((", after %d\n", ire->ire_max_frag));
2160 			}
2161 			/* Record the new max frag size for the ULP. */
2162 			icmph->icmph_du_zero = 0;
2163 			icmph->icmph_du_mtu =
2164 			    htons((uint16_t)ire->ire_max_frag);
2165 		}
2166 		mutex_exit(&ire->ire_lock);
2167 	}
2168 	rw_exit(&first_ire->ire_bucket->irb_lock);
2169 	ire_refrele(first_ire);
2170 	return (B_TRUE);
2171 }
2172 
2173 /*
2174  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2175  * calls this function.
2176  */
2177 static mblk_t *
2178 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2179 {
2180 	ipha_t *ipha;
2181 	icmph_t *icmph;
2182 	ipha_t *in_ipha;
2183 	int length;
2184 
2185 	ASSERT(mp->b_datap->db_type == M_DATA);
2186 
2187 	/*
2188 	 * For Self-encapsulated packets, we added an extra IP header
2189 	 * without the options. Inner IP header is the one from which
2190 	 * the outer IP header was formed. Thus, we need to remove the
2191 	 * outer IP header. To do this, we pullup the whole message
2192 	 * and overlay whatever follows the outer IP header over the
2193 	 * outer IP header.
2194 	 */
2195 
2196 	if (!pullupmsg(mp, -1)) {
2197 		BUMP_MIB(&ip_mib, ipInDiscards);
2198 		return (NULL);
2199 	}
2200 
2201 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2202 	ipha = (ipha_t *)&icmph[1];
2203 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2204 
2205 	/*
2206 	 * The length that we want to overlay is following the inner
2207 	 * IP header. Subtracting the IP header + icmp header + outer
2208 	 * IP header's length should give us the length that we want to
2209 	 * overlay.
2210 	 */
2211 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2212 	    hdr_length;
2213 	/*
2214 	 * Overlay whatever follows the inner header over the
2215 	 * outer header.
2216 	 */
2217 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2218 
2219 	/* Set the wptr to account for the outer header */
2220 	mp->b_wptr -= hdr_length;
2221 	return (mp);
2222 }
2223 
2224 /*
2225  * Try to pass the ICMP message upstream in case the ULP cares.
2226  *
2227  * If the packet that caused the ICMP error is secure, we send
2228  * it to AH/ESP to make sure that the attached packet has a
2229  * valid association. ipha in the code below points to the
2230  * IP header of the packet that caused the error.
2231  *
2232  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2233  * in the context of IPSEC. Normally we tell the upper layer
2234  * whenever we send the ire (including ip_bind), the IPSEC header
2235  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2236  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2237  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2238  * same thing. As TCP has the IPSEC options size that needs to be
2239  * adjusted, we just pass the MTU unchanged.
2240  *
2241  * IFN could have been generated locally or by some router.
2242  *
2243  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2244  *	    This happens because IP adjusted its value of MTU on an
2245  *	    earlier IFN message and could not tell the upper layer,
2246  *	    the new adjusted value of MTU e.g. Packet was encrypted
2247  *	    or there was not enough information to fanout to upper
2248  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2249  *	    generates the IFN, where IPSEC processing has *not* been
2250  *	    done.
2251  *
2252  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2253  *	    could have generated this. This happens because ire_max_frag
2254  *	    value in IP was set to a new value, while the IPSEC processing
2255  *	    was being done and after we made the fragmentation check in
2256  *	    ip_wput_ire. Thus on return from IPSEC processing,
2257  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2258  *	    and generates the IFN. As IPSEC processing is over, we fanout
2259  *	    to AH/ESP to remove the header.
2260  *
2261  *	    In both these cases, ipsec_in_loopback will be set indicating
2262  *	    that IFN was generated locally.
2263  *
2264  * ROUTER : IFN could be secure or non-secure.
2265  *
2266  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2267  *	      packet in error has AH/ESP headers to validate the AH/ESP
2268  *	      headers. AH/ESP will verify whether there is a valid SA or
2269  *	      not and send it back. We will fanout again if we have more
2270  *	      data in the packet.
2271  *
2272  *	      If the packet in error does not have AH/ESP, we handle it
2273  *	      like any other case.
2274  *
2275  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2276  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2277  *	      for validation. AH/ESP will verify whether there is a
2278  *	      valid SA or not and send it back. We will fanout again if
2279  *	      we have more data in the packet.
2280  *
2281  *	      If the packet in error does not have AH/ESP, we handle it
2282  *	      like any other case.
2283  */
2284 static void
2285 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2286     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2287     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2288     zoneid_t zoneid)
2289 {
2290 	uint16_t *up;	/* Pointer to ports in ULP header */
2291 	uint32_t ports;	/* reversed ports for fanout */
2292 	ipha_t ripha;	/* With reversed addresses */
2293 	mblk_t *first_mp;
2294 	ipsec_in_t *ii;
2295 	tcph_t	*tcph;
2296 	conn_t	*connp;
2297 
2298 	first_mp = mp;
2299 	if (mctl_present) {
2300 		mp = first_mp->b_cont;
2301 		ASSERT(mp != NULL);
2302 
2303 		ii = (ipsec_in_t *)first_mp->b_rptr;
2304 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2305 	} else {
2306 		ii = NULL;
2307 	}
2308 
2309 	switch (ipha->ipha_protocol) {
2310 	case IPPROTO_UDP:
2311 		/*
2312 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2313 		 * transport header.
2314 		 */
2315 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2316 		    mp->b_wptr) {
2317 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2318 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2319 				BUMP_MIB(&ip_mib, ipInDiscards);
2320 				goto drop_pkt;
2321 			}
2322 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2323 			ipha = (ipha_t *)&icmph[1];
2324 		}
2325 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2326 
2327 		/*
2328 		 * Attempt to find a client stream based on port.
2329 		 * Note that we do a reverse lookup since the header is
2330 		 * in the form we sent it out.
2331 		 * The ripha header is only used for the IP_UDP_MATCH and we
2332 		 * only set the src and dst addresses and protocol.
2333 		 */
2334 		ripha.ipha_src = ipha->ipha_dst;
2335 		ripha.ipha_dst = ipha->ipha_src;
2336 		ripha.ipha_protocol = ipha->ipha_protocol;
2337 		((uint16_t *)&ports)[0] = up[1];
2338 		((uint16_t *)&ports)[1] = up[0];
2339 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2340 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2341 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2342 		    icmph->icmph_type, icmph->icmph_code));
2343 
2344 		/* Have to change db_type after any pullupmsg */
2345 		DB_TYPE(mp) = M_CTL;
2346 
2347 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2348 		    mctl_present, ip_policy, recv_ill, zoneid);
2349 		return;
2350 
2351 	case IPPROTO_TCP:
2352 		/*
2353 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2354 		 * transport header.
2355 		 */
2356 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2357 		    mp->b_wptr) {
2358 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2359 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2360 				BUMP_MIB(&ip_mib, ipInDiscards);
2361 				goto drop_pkt;
2362 			}
2363 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2364 			ipha = (ipha_t *)&icmph[1];
2365 		}
2366 		/*
2367 		 * Find a TCP client stream for this packet.
2368 		 * Note that we do a reverse lookup since the header is
2369 		 * in the form we sent it out.
2370 		 */
2371 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2372 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2373 		if (connp == NULL) {
2374 			BUMP_MIB(&ip_mib, ipInDiscards);
2375 			goto drop_pkt;
2376 		}
2377 
2378 		/* Have to change db_type after any pullupmsg */
2379 		DB_TYPE(mp) = M_CTL;
2380 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2381 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2382 		return;
2383 
2384 	case IPPROTO_SCTP:
2385 		/*
2386 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2387 		 * transport header.
2388 		 */
2389 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2390 		    mp->b_wptr) {
2391 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2392 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2393 				BUMP_MIB(&ip_mib, ipInDiscards);
2394 				goto drop_pkt;
2395 			}
2396 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2397 			ipha = (ipha_t *)&icmph[1];
2398 		}
2399 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2400 		/*
2401 		 * Find a SCTP client stream for this packet.
2402 		 * Note that we do a reverse lookup since the header is
2403 		 * in the form we sent it out.
2404 		 * The ripha header is only used for the matching and we
2405 		 * only set the src and dst addresses, protocol, and version.
2406 		 */
2407 		ripha.ipha_src = ipha->ipha_dst;
2408 		ripha.ipha_dst = ipha->ipha_src;
2409 		ripha.ipha_protocol = ipha->ipha_protocol;
2410 		ripha.ipha_version_and_hdr_length =
2411 		    ipha->ipha_version_and_hdr_length;
2412 		((uint16_t *)&ports)[0] = up[1];
2413 		((uint16_t *)&ports)[1] = up[0];
2414 
2415 		/* Have to change db_type after any pullupmsg */
2416 		DB_TYPE(mp) = M_CTL;
2417 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2418 		    mctl_present, ip_policy, 0, zoneid);
2419 		return;
2420 
2421 	case IPPROTO_ESP:
2422 	case IPPROTO_AH: {
2423 		int ipsec_rc;
2424 
2425 		/*
2426 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2427 		 * We will re-use the IPSEC_IN if it is already present as
2428 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2429 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2430 		 * one and attach it in the front.
2431 		 */
2432 		if (ii != NULL) {
2433 			/*
2434 			 * ip_fanout_proto_again converts the ICMP errors
2435 			 * that come back from AH/ESP to M_DATA so that
2436 			 * if it is non-AH/ESP and we do a pullupmsg in
2437 			 * this function, it would work. Convert it back
2438 			 * to M_CTL before we send up as this is a ICMP
2439 			 * error. This could have been generated locally or
2440 			 * by some router. Validate the inner IPSEC
2441 			 * headers.
2442 			 *
2443 			 * NOTE : ill_index is used by ip_fanout_proto_again
2444 			 * to locate the ill.
2445 			 */
2446 			ASSERT(ill != NULL);
2447 			ii->ipsec_in_ill_index =
2448 			    ill->ill_phyint->phyint_ifindex;
2449 			ii->ipsec_in_rill_index =
2450 			    recv_ill->ill_phyint->phyint_ifindex;
2451 			DB_TYPE(first_mp->b_cont) = M_CTL;
2452 		} else {
2453 			/*
2454 			 * IPSEC_IN is not present. We attach a ipsec_in
2455 			 * message and send up to IPSEC for validating
2456 			 * and removing the IPSEC headers. Clear
2457 			 * ipsec_in_secure so that when we return
2458 			 * from IPSEC, we don't mistakenly think that this
2459 			 * is a secure packet came from the network.
2460 			 *
2461 			 * NOTE : ill_index is used by ip_fanout_proto_again
2462 			 * to locate the ill.
2463 			 */
2464 			ASSERT(first_mp == mp);
2465 			first_mp = ipsec_in_alloc(B_TRUE);
2466 			if (first_mp == NULL) {
2467 				freemsg(mp);
2468 				BUMP_MIB(&ip_mib, ipInDiscards);
2469 				return;
2470 			}
2471 			ii = (ipsec_in_t *)first_mp->b_rptr;
2472 
2473 			/* This is not a secure packet */
2474 			ii->ipsec_in_secure = B_FALSE;
2475 			first_mp->b_cont = mp;
2476 			DB_TYPE(mp) = M_CTL;
2477 			ASSERT(ill != NULL);
2478 			ii->ipsec_in_ill_index =
2479 			    ill->ill_phyint->phyint_ifindex;
2480 			ii->ipsec_in_rill_index =
2481 			    recv_ill->ill_phyint->phyint_ifindex;
2482 		}
2483 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2484 
2485 		if (!ipsec_loaded()) {
2486 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2487 			return;
2488 		}
2489 
2490 		if (ipha->ipha_protocol == IPPROTO_ESP)
2491 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2492 		else
2493 			ipsec_rc = ipsecah_icmp_error(first_mp);
2494 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2495 			return;
2496 
2497 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2498 		return;
2499 	}
2500 	default:
2501 		/*
2502 		 * The ripha header is only used for the lookup and we
2503 		 * only set the src and dst addresses and protocol.
2504 		 */
2505 		ripha.ipha_src = ipha->ipha_dst;
2506 		ripha.ipha_dst = ipha->ipha_src;
2507 		ripha.ipha_protocol = ipha->ipha_protocol;
2508 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2509 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2510 		    ntohl(ipha->ipha_dst),
2511 		    icmph->icmph_type, icmph->icmph_code));
2512 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2513 			ipha_t *in_ipha;
2514 
2515 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2516 			    mp->b_wptr) {
2517 				if (!pullupmsg(mp, (uchar_t *)ipha +
2518 				    hdr_length + sizeof (ipha_t) -
2519 				    mp->b_rptr)) {
2520 
2521 					BUMP_MIB(&ip_mib, ipInDiscards);
2522 					goto drop_pkt;
2523 				}
2524 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2525 				ipha = (ipha_t *)&icmph[1];
2526 			}
2527 			/*
2528 			 * Caller has verified that length has to be
2529 			 * at least the size of IP header.
2530 			 */
2531 			ASSERT(hdr_length >= sizeof (ipha_t));
2532 			/*
2533 			 * Check the sanity of the inner IP header like
2534 			 * we did for the outer header.
2535 			 */
2536 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2537 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2538 				BUMP_MIB(&ip_mib, ipInDiscards);
2539 				goto drop_pkt;
2540 			}
2541 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2542 				BUMP_MIB(&ip_mib, ipInDiscards);
2543 				goto drop_pkt;
2544 			}
2545 			/* Check for Self-encapsulated tunnels */
2546 			if (in_ipha->ipha_src == ipha->ipha_src &&
2547 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2548 
2549 				mp = icmp_inbound_self_encap_error(mp,
2550 				    iph_hdr_length, hdr_length);
2551 				if (mp == NULL)
2552 					goto drop_pkt;
2553 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2554 				ipha = (ipha_t *)&icmph[1];
2555 				hdr_length = IPH_HDR_LENGTH(ipha);
2556 				/*
2557 				 * The packet in error is self-encapsualted.
2558 				 * And we are finding it further encapsulated
2559 				 * which we could not have possibly generated.
2560 				 */
2561 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2562 					BUMP_MIB(&ip_mib, ipInDiscards);
2563 					goto drop_pkt;
2564 				}
2565 				icmp_inbound_error_fanout(q, ill, first_mp,
2566 				    icmph, ipha, iph_hdr_length, hdr_length,
2567 				    mctl_present, ip_policy, recv_ill, zoneid);
2568 				return;
2569 			}
2570 		}
2571 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2572 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2573 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2574 		    ii != NULL &&
2575 		    ii->ipsec_in_loopback &&
2576 		    ii->ipsec_in_secure) {
2577 			/*
2578 			 * For IP tunnels that get a looped-back
2579 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2580 			 * reported new MTU to take into account the IPsec
2581 			 * headers protecting this configured tunnel.
2582 			 *
2583 			 * This allows the tunnel module (tun.c) to blindly
2584 			 * accept the MTU reported in an ICMP "too big"
2585 			 * message.
2586 			 *
2587 			 * Non-looped back ICMP messages will just be
2588 			 * handled by the security protocols (if needed),
2589 			 * and the first subsequent packet will hit this
2590 			 * path.
2591 			 */
2592 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2593 			    ipsec_in_extra_length(first_mp));
2594 		}
2595 		/* Have to change db_type after any pullupmsg */
2596 		DB_TYPE(mp) = M_CTL;
2597 
2598 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2599 		    ip_policy, recv_ill, zoneid);
2600 		return;
2601 	}
2602 	/* NOTREACHED */
2603 drop_pkt:;
2604 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2605 	freemsg(first_mp);
2606 }
2607 
2608 /*
2609  * Common IP options parser.
2610  *
2611  * Setup routine: fill in *optp with options-parsing state, then
2612  * tail-call ipoptp_next to return the first option.
2613  */
2614 uint8_t
2615 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2616 {
2617 	uint32_t totallen; /* total length of all options */
2618 
2619 	totallen = ipha->ipha_version_and_hdr_length -
2620 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2621 	totallen <<= 2;
2622 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2623 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2624 	optp->ipoptp_flags = 0;
2625 	return (ipoptp_next(optp));
2626 }
2627 
2628 /*
2629  * Common IP options parser: extract next option.
2630  */
2631 uint8_t
2632 ipoptp_next(ipoptp_t *optp)
2633 {
2634 	uint8_t *end = optp->ipoptp_end;
2635 	uint8_t *cur = optp->ipoptp_next;
2636 	uint8_t opt, len, pointer;
2637 
2638 	/*
2639 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2640 	 * has been corrupted.
2641 	 */
2642 	ASSERT(cur <= end);
2643 
2644 	if (cur == end)
2645 		return (IPOPT_EOL);
2646 
2647 	opt = cur[IPOPT_OPTVAL];
2648 
2649 	/*
2650 	 * Skip any NOP options.
2651 	 */
2652 	while (opt == IPOPT_NOP) {
2653 		cur++;
2654 		if (cur == end)
2655 			return (IPOPT_EOL);
2656 		opt = cur[IPOPT_OPTVAL];
2657 	}
2658 
2659 	if (opt == IPOPT_EOL)
2660 		return (IPOPT_EOL);
2661 
2662 	/*
2663 	 * Option requiring a length.
2664 	 */
2665 	if ((cur + 1) >= end) {
2666 		optp->ipoptp_flags |= IPOPTP_ERROR;
2667 		return (IPOPT_EOL);
2668 	}
2669 	len = cur[IPOPT_OLEN];
2670 	if (len < 2) {
2671 		optp->ipoptp_flags |= IPOPTP_ERROR;
2672 		return (IPOPT_EOL);
2673 	}
2674 	optp->ipoptp_cur = cur;
2675 	optp->ipoptp_len = len;
2676 	optp->ipoptp_next = cur + len;
2677 	if (cur + len > end) {
2678 		optp->ipoptp_flags |= IPOPTP_ERROR;
2679 		return (IPOPT_EOL);
2680 	}
2681 
2682 	/*
2683 	 * For the options which require a pointer field, make sure
2684 	 * its there, and make sure it points to either something
2685 	 * inside this option, or the end of the option.
2686 	 */
2687 	switch (opt) {
2688 	case IPOPT_RR:
2689 	case IPOPT_TS:
2690 	case IPOPT_LSRR:
2691 	case IPOPT_SSRR:
2692 		if (len <= IPOPT_OFFSET) {
2693 			optp->ipoptp_flags |= IPOPTP_ERROR;
2694 			return (opt);
2695 		}
2696 		pointer = cur[IPOPT_OFFSET];
2697 		if (pointer - 1 > len) {
2698 			optp->ipoptp_flags |= IPOPTP_ERROR;
2699 			return (opt);
2700 		}
2701 		break;
2702 	}
2703 
2704 	/*
2705 	 * Sanity check the pointer field based on the type of the
2706 	 * option.
2707 	 */
2708 	switch (opt) {
2709 	case IPOPT_RR:
2710 	case IPOPT_SSRR:
2711 	case IPOPT_LSRR:
2712 		if (pointer < IPOPT_MINOFF_SR)
2713 			optp->ipoptp_flags |= IPOPTP_ERROR;
2714 		break;
2715 	case IPOPT_TS:
2716 		if (pointer < IPOPT_MINOFF_IT)
2717 			optp->ipoptp_flags |= IPOPTP_ERROR;
2718 		/*
2719 		 * Note that the Internet Timestamp option also
2720 		 * contains two four bit fields (the Overflow field,
2721 		 * and the Flag field), which follow the pointer
2722 		 * field.  We don't need to check that these fields
2723 		 * fall within the length of the option because this
2724 		 * was implicitely done above.  We've checked that the
2725 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2726 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2727 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2728 		 */
2729 		ASSERT(len > IPOPT_POS_OV_FLG);
2730 		break;
2731 	}
2732 
2733 	return (opt);
2734 }
2735 
2736 /*
2737  * Update any record route or timestamp options to include this host.
2738  * Reverse any source route option.
2739  * This routine assumes that the options are well formed i.e. that they
2740  * have already been checked.
2741  */
2742 static void
2743 icmp_options_update(ipha_t *ipha)
2744 {
2745 	ipoptp_t	opts;
2746 	uchar_t		*opt;
2747 	uint8_t		optval;
2748 	ipaddr_t	src;		/* Our local address */
2749 	ipaddr_t	dst;
2750 
2751 	ip2dbg(("icmp_options_update\n"));
2752 	src = ipha->ipha_src;
2753 	dst = ipha->ipha_dst;
2754 
2755 	for (optval = ipoptp_first(&opts, ipha);
2756 	    optval != IPOPT_EOL;
2757 	    optval = ipoptp_next(&opts)) {
2758 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2759 		opt = opts.ipoptp_cur;
2760 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2761 		    optval, opts.ipoptp_len));
2762 		switch (optval) {
2763 			int off1, off2;
2764 		case IPOPT_SSRR:
2765 		case IPOPT_LSRR:
2766 			/*
2767 			 * Reverse the source route.  The first entry
2768 			 * should be the next to last one in the current
2769 			 * source route (the last entry is our address).
2770 			 * The last entry should be the final destination.
2771 			 */
2772 			off1 = IPOPT_MINOFF_SR - 1;
2773 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2774 			if (off2 < 0) {
2775 				/* No entries in source route */
2776 				ip1dbg((
2777 				    "icmp_options_update: bad src route\n"));
2778 				break;
2779 			}
2780 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2781 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2782 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2783 			off2 -= IP_ADDR_LEN;
2784 
2785 			while (off1 < off2) {
2786 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2787 				bcopy((char *)opt + off2, (char *)opt + off1,
2788 				    IP_ADDR_LEN);
2789 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2790 				off1 += IP_ADDR_LEN;
2791 				off2 -= IP_ADDR_LEN;
2792 			}
2793 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2794 			break;
2795 		}
2796 	}
2797 }
2798 
2799 /*
2800  * Process received ICMP Redirect messages.
2801  */
2802 /* ARGSUSED */
2803 static void
2804 icmp_redirect(mblk_t *mp)
2805 {
2806 	ipha_t	*ipha;
2807 	int	iph_hdr_length;
2808 	icmph_t	*icmph;
2809 	ipha_t	*ipha_err;
2810 	ire_t	*ire;
2811 	ire_t	*prev_ire;
2812 	ire_t	*save_ire;
2813 	ipaddr_t  src, dst, gateway;
2814 	iulp_t	ulp_info = { 0 };
2815 	int	error;
2816 
2817 	ipha = (ipha_t *)mp->b_rptr;
2818 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2819 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2820 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2821 		BUMP_MIB(&icmp_mib, icmpInErrors);
2822 		freemsg(mp);
2823 		return;
2824 	}
2825 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2826 	ipha_err = (ipha_t *)&icmph[1];
2827 	src = ipha->ipha_src;
2828 	dst = ipha_err->ipha_dst;
2829 	gateway = icmph->icmph_rd_gateway;
2830 	/* Make sure the new gateway is reachable somehow. */
2831 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2832 	    ALL_ZONES, MATCH_IRE_TYPE);
2833 	/*
2834 	 * Make sure we had a route for the dest in question and that
2835 	 * that route was pointing to the old gateway (the source of the
2836 	 * redirect packet.)
2837 	 */
2838 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2839 	    MATCH_IRE_GW);
2840 	/*
2841 	 * Check that
2842 	 *	the redirect was not from ourselves
2843 	 *	the new gateway and the old gateway are directly reachable
2844 	 */
2845 	if (!prev_ire ||
2846 	    !ire ||
2847 	    ire->ire_type == IRE_LOCAL) {
2848 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2849 		freemsg(mp);
2850 		if (ire != NULL)
2851 			ire_refrele(ire);
2852 		if (prev_ire != NULL)
2853 			ire_refrele(prev_ire);
2854 		return;
2855 	}
2856 
2857 	/*
2858 	 * Should we use the old ULP info to create the new gateway?  From
2859 	 * a user's perspective, we should inherit the info so that it
2860 	 * is a "smooth" transition.  If we do not do that, then new
2861 	 * connections going thru the new gateway will have no route metrics,
2862 	 * which is counter-intuitive to user.  From a network point of
2863 	 * view, this may or may not make sense even though the new gateway
2864 	 * is still directly connected to us so the route metrics should not
2865 	 * change much.
2866 	 *
2867 	 * But if the old ire_uinfo is not initialized, we do another
2868 	 * recursive lookup on the dest using the new gateway.  There may
2869 	 * be a route to that.  If so, use it to initialize the redirect
2870 	 * route.
2871 	 */
2872 	if (prev_ire->ire_uinfo.iulp_set) {
2873 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2874 	} else {
2875 		ire_t *tmp_ire;
2876 		ire_t *sire;
2877 
2878 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2879 		    ALL_ZONES, 0,
2880 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2881 		if (sire != NULL) {
2882 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2883 			/*
2884 			 * If sire != NULL, ire_ftable_lookup() should not
2885 			 * return a NULL value.
2886 			 */
2887 			ASSERT(tmp_ire != NULL);
2888 			ire_refrele(tmp_ire);
2889 			ire_refrele(sire);
2890 		} else if (tmp_ire != NULL) {
2891 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2892 			    sizeof (iulp_t));
2893 			ire_refrele(tmp_ire);
2894 		}
2895 	}
2896 	if (prev_ire->ire_type == IRE_CACHE)
2897 		ire_delete(prev_ire);
2898 	ire_refrele(prev_ire);
2899 	/*
2900 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2901 	 * require TOS routing
2902 	 */
2903 	switch (icmph->icmph_code) {
2904 	case 0:
2905 	case 1:
2906 		/* TODO: TOS specificity for cases 2 and 3 */
2907 	case 2:
2908 	case 3:
2909 		break;
2910 	default:
2911 		freemsg(mp);
2912 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2913 		ire_refrele(ire);
2914 		return;
2915 	}
2916 	/*
2917 	 * Create a Route Association.  This will allow us to remember that
2918 	 * someone we believe told us to use the particular gateway.
2919 	 */
2920 	save_ire = ire;
2921 	ire = ire_create(
2922 		(uchar_t *)&dst,			/* dest addr */
2923 		(uchar_t *)&ip_g_all_ones,		/* mask */
2924 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2925 		(uchar_t *)&gateway,			/* gateway addr */
2926 		NULL,					/* no in_srcaddr */
2927 		&save_ire->ire_max_frag,		/* max frag */
2928 		NULL,					/* Fast Path header */
2929 		NULL,					/* no rfq */
2930 		NULL,					/* no stq */
2931 		IRE_HOST_REDIRECT,
2932 		NULL,
2933 		NULL,
2934 		NULL,
2935 		0,
2936 		0,
2937 		0,
2938 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2939 		&ulp_info);
2940 
2941 	if (ire == NULL) {
2942 		freemsg(mp);
2943 		ire_refrele(save_ire);
2944 		return;
2945 	}
2946 	error = ire_add(&ire, NULL, NULL, NULL);
2947 	ire_refrele(save_ire);
2948 	if (error == 0) {
2949 		ire_refrele(ire);		/* Held in ire_add_v4 */
2950 		/* tell routing sockets that we received a redirect */
2951 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2952 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2953 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2954 	}
2955 
2956 	/*
2957 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2958 	 * This together with the added IRE has the effect of
2959 	 * modifying an existing redirect.
2960 	 */
2961 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2962 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2963 	if (prev_ire) {
2964 		ire_delete(prev_ire);
2965 		ire_refrele(prev_ire);
2966 	}
2967 
2968 	freemsg(mp);
2969 }
2970 
2971 /*
2972  * Generate an ICMP parameter problem message.
2973  */
2974 static void
2975 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
2976 {
2977 	icmph_t	icmph;
2978 	boolean_t mctl_present;
2979 	mblk_t *first_mp;
2980 
2981 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
2982 
2983 	if (!(mp = icmp_pkt_err_ok(mp))) {
2984 		if (mctl_present)
2985 			freeb(first_mp);
2986 		return;
2987 	}
2988 
2989 	bzero(&icmph, sizeof (icmph_t));
2990 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2991 	icmph.icmph_pp_ptr = ptr;
2992 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
2993 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
2994 }
2995 
2996 /*
2997  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2998  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2999  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3000  * an icmp error packet can be sent.
3001  * Assigns an appropriate source address to the packet. If ipha_dst is
3002  * one of our addresses use it for source. Otherwise pick a source based
3003  * on a route lookup back to ipha_src.
3004  * Note that ipha_src must be set here since the
3005  * packet is likely to arrive on an ill queue in ip_wput() which will
3006  * not set a source address.
3007  */
3008 static void
3009 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3010     boolean_t mctl_present)
3011 {
3012 	ipaddr_t dst;
3013 	icmph_t	*icmph;
3014 	ipha_t	*ipha;
3015 	uint_t	len_needed;
3016 	size_t	msg_len;
3017 	mblk_t	*mp1;
3018 	ipaddr_t src;
3019 	ire_t	*ire;
3020 	mblk_t *ipsec_mp;
3021 	ipsec_out_t	*io = NULL;
3022 	boolean_t xmit_if_on = B_FALSE;
3023 	zoneid_t	zoneid;
3024 
3025 	if (mctl_present) {
3026 		/*
3027 		 * If it is :
3028 		 *
3029 		 * 1) a IPSEC_OUT, then this is caused by outbound
3030 		 *    datagram originating on this host. IPSEC processing
3031 		 *    may or may not have been done. Refer to comments above
3032 		 *    icmp_inbound_error_fanout for details.
3033 		 *
3034 		 * 2) a IPSEC_IN if we are generating a icmp_message
3035 		 *    for an incoming datagram destined for us i.e called
3036 		 *    from ip_fanout_send_icmp.
3037 		 */
3038 		ipsec_info_t *in;
3039 		ipsec_mp = mp;
3040 		mp = ipsec_mp->b_cont;
3041 
3042 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3043 		ipha = (ipha_t *)mp->b_rptr;
3044 
3045 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3046 		    in->ipsec_info_type == IPSEC_IN);
3047 
3048 		if (in->ipsec_info_type == IPSEC_IN) {
3049 			/*
3050 			 * Convert the IPSEC_IN to IPSEC_OUT.
3051 			 */
3052 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3053 				BUMP_MIB(&ip_mib, ipOutDiscards);
3054 				return;
3055 			}
3056 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3057 		} else {
3058 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3059 			io = (ipsec_out_t *)in;
3060 			if (io->ipsec_out_xmit_if)
3061 				xmit_if_on = B_TRUE;
3062 			/*
3063 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3064 			 * ire lookup.
3065 			 */
3066 			io->ipsec_out_proc_begin = B_FALSE;
3067 		}
3068 		zoneid = io->ipsec_out_zoneid;
3069 		ASSERT(zoneid != ALL_ZONES);
3070 	} else {
3071 		/*
3072 		 * This is in clear. The icmp message we are building
3073 		 * here should go out in clear.
3074 		 *
3075 		 * Pardon the convolution of it all, but it's easier to
3076 		 * allocate a "use cleartext" IPSEC_IN message and convert
3077 		 * it than it is to allocate a new one.
3078 		 */
3079 		ipsec_in_t *ii;
3080 		ASSERT(DB_TYPE(mp) == M_DATA);
3081 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3082 			freemsg(mp);
3083 			BUMP_MIB(&ip_mib, ipOutDiscards);
3084 			return;
3085 		}
3086 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3087 
3088 		/* This is not a secure packet */
3089 		ii->ipsec_in_secure = B_FALSE;
3090 		if (CONN_Q(q)) {
3091 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3092 		} else {
3093 			zoneid = GLOBAL_ZONEID;
3094 		}
3095 		ii->ipsec_in_zoneid = zoneid;
3096 		ipsec_mp->b_cont = mp;
3097 		ipha = (ipha_t *)mp->b_rptr;
3098 		/*
3099 		 * Convert the IPSEC_IN to IPSEC_OUT.
3100 		 */
3101 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3102 			BUMP_MIB(&ip_mib, ipOutDiscards);
3103 			return;
3104 		}
3105 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3106 	}
3107 
3108 	/* Remember our eventual destination */
3109 	dst = ipha->ipha_src;
3110 
3111 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3112 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3113 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3114 		src = ipha->ipha_dst;
3115 	} else if (!xmit_if_on) {
3116 		if (ire != NULL)
3117 			ire_refrele(ire);
3118 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3119 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3120 		if (ire == NULL) {
3121 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3122 			freemsg(ipsec_mp);
3123 			return;
3124 		}
3125 		src = ire->ire_src_addr;
3126 	} else {
3127 		ipif_t	*ipif = NULL;
3128 		ill_t	*ill;
3129 		/*
3130 		 * This must be an ICMP error coming from
3131 		 * ip_mrtun_forward(). The src addr should
3132 		 * be equal to the IP-addr of the outgoing
3133 		 * interface.
3134 		 */
3135 		if (io == NULL) {
3136 			/* This is not a IPSEC_OUT type control msg */
3137 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3138 			freemsg(ipsec_mp);
3139 			return;
3140 		}
3141 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3142 		    NULL, NULL, NULL, NULL);
3143 		if (ill != NULL) {
3144 			ipif = ipif_get_next_ipif(NULL, ill);
3145 			ill_refrele(ill);
3146 		}
3147 		if (ipif == NULL) {
3148 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3149 			freemsg(ipsec_mp);
3150 			return;
3151 		}
3152 		src = ipif->ipif_src_addr;
3153 		ipif_refrele(ipif);
3154 	}
3155 
3156 	if (ire != NULL)
3157 		ire_refrele(ire);
3158 
3159 	/*
3160 	 * Check if we can send back more then 8 bytes in addition
3161 	 * to the IP header. We will include as much as 64 bytes.
3162 	 */
3163 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3164 	msg_len = msgdsize(mp);
3165 	if (msg_len > len_needed) {
3166 		(void) adjmsg(mp, len_needed - msg_len);
3167 		msg_len = len_needed;
3168 	}
3169 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3170 	if (!mp1) {
3171 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3172 		freemsg(ipsec_mp);
3173 		return;
3174 	}
3175 	mp1->b_cont = mp;
3176 	mp = mp1;
3177 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3178 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3179 	    io->ipsec_out_type == IPSEC_OUT);
3180 	ipsec_mp->b_cont = mp;
3181 
3182 	/*
3183 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3184 	 * node generates be accepted in peace by all on-host destinations.
3185 	 * If we do NOT assume that all on-host destinations trust
3186 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3187 	 * (Look for ipsec_out_icmp_loopback).
3188 	 */
3189 	io->ipsec_out_icmp_loopback = B_TRUE;
3190 
3191 	ipha = (ipha_t *)mp->b_rptr;
3192 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3193 	*ipha = icmp_ipha;
3194 	ipha->ipha_src = src;
3195 	ipha->ipha_dst = dst;
3196 	ipha->ipha_ttl = ip_def_ttl;
3197 	msg_len += sizeof (icmp_ipha) + len;
3198 	if (msg_len > IP_MAXPACKET) {
3199 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3200 		msg_len = IP_MAXPACKET;
3201 	}
3202 	ipha->ipha_length = htons((uint16_t)msg_len);
3203 	icmph = (icmph_t *)&ipha[1];
3204 	bcopy(stuff, icmph, len);
3205 	icmph->icmph_checksum = 0;
3206 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3207 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3208 	put(q, ipsec_mp);
3209 }
3210 
3211 /*
3212  * Determine if an ICMP error packet can be sent given the rate limit.
3213  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3214  * in milliseconds) and a burst size. Burst size number of packets can
3215  * be sent arbitrarely closely spaced.
3216  * The state is tracked using two variables to implement an approximate
3217  * token bucket filter:
3218  *	icmp_pkt_err_last - lbolt value when the last burst started
3219  *	icmp_pkt_err_sent - number of packets sent in current burst
3220  */
3221 boolean_t
3222 icmp_err_rate_limit(void)
3223 {
3224 	clock_t now = TICK_TO_MSEC(lbolt);
3225 	uint_t refilled; /* Number of packets refilled in tbf since last */
3226 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3227 
3228 	if (err_interval == 0)
3229 		return (B_FALSE);
3230 
3231 	if (icmp_pkt_err_last > now) {
3232 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3233 		icmp_pkt_err_last = 0;
3234 		icmp_pkt_err_sent = 0;
3235 	}
3236 	/*
3237 	 * If we are in a burst update the token bucket filter.
3238 	 * Update the "last" time to be close to "now" but make sure
3239 	 * we don't loose precision.
3240 	 */
3241 	if (icmp_pkt_err_sent != 0) {
3242 		refilled = (now - icmp_pkt_err_last)/err_interval;
3243 		if (refilled > icmp_pkt_err_sent) {
3244 			icmp_pkt_err_sent = 0;
3245 		} else {
3246 			icmp_pkt_err_sent -= refilled;
3247 			icmp_pkt_err_last += refilled * err_interval;
3248 		}
3249 	}
3250 	if (icmp_pkt_err_sent == 0) {
3251 		/* Start of new burst */
3252 		icmp_pkt_err_last = now;
3253 	}
3254 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3255 		icmp_pkt_err_sent++;
3256 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3257 		    icmp_pkt_err_sent));
3258 		return (B_FALSE);
3259 	}
3260 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3261 	return (B_TRUE);
3262 }
3263 
3264 /*
3265  * Check if it is ok to send an IPv4 ICMP error packet in
3266  * response to the IPv4 packet in mp.
3267  * Free the message and return null if no
3268  * ICMP error packet should be sent.
3269  */
3270 static mblk_t *
3271 icmp_pkt_err_ok(mblk_t *mp)
3272 {
3273 	icmph_t	*icmph;
3274 	ipha_t	*ipha;
3275 	uint_t	len_needed;
3276 	ire_t	*src_ire;
3277 	ire_t	*dst_ire;
3278 
3279 	if (!mp)
3280 		return (NULL);
3281 	ipha = (ipha_t *)mp->b_rptr;
3282 	if (ip_csum_hdr(ipha)) {
3283 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3284 		freemsg(mp);
3285 		return (NULL);
3286 	}
3287 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3288 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3289 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3290 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3291 	if (src_ire != NULL || dst_ire != NULL ||
3292 	    CLASSD(ipha->ipha_dst) ||
3293 	    CLASSD(ipha->ipha_src) ||
3294 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3295 		/* Note: only errors to the fragment with offset 0 */
3296 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3297 		freemsg(mp);
3298 		if (src_ire != NULL)
3299 			ire_refrele(src_ire);
3300 		if (dst_ire != NULL)
3301 			ire_refrele(dst_ire);
3302 		return (NULL);
3303 	}
3304 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3305 		/*
3306 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3307 		 * errors in response to any ICMP errors.
3308 		 */
3309 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3310 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3311 			if (!pullupmsg(mp, len_needed)) {
3312 				BUMP_MIB(&icmp_mib, icmpInErrors);
3313 				freemsg(mp);
3314 				return (NULL);
3315 			}
3316 			ipha = (ipha_t *)mp->b_rptr;
3317 		}
3318 		icmph = (icmph_t *)
3319 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3320 		switch (icmph->icmph_type) {
3321 		case ICMP_DEST_UNREACHABLE:
3322 		case ICMP_SOURCE_QUENCH:
3323 		case ICMP_TIME_EXCEEDED:
3324 		case ICMP_PARAM_PROBLEM:
3325 		case ICMP_REDIRECT:
3326 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3327 			freemsg(mp);
3328 			return (NULL);
3329 		default:
3330 			break;
3331 		}
3332 	}
3333 	if (icmp_err_rate_limit()) {
3334 		/*
3335 		 * Only send ICMP error packets every so often.
3336 		 * This should be done on a per port/source basis,
3337 		 * but for now this will suffice.
3338 		 */
3339 		freemsg(mp);
3340 		return (NULL);
3341 	}
3342 	return (mp);
3343 }
3344 
3345 /*
3346  * Generate an ICMP redirect message.
3347  */
3348 static void
3349 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3350 {
3351 	icmph_t	icmph;
3352 
3353 	/*
3354 	 * We are called from ip_rput where we could
3355 	 * not have attached an IPSEC_IN.
3356 	 */
3357 	ASSERT(mp->b_datap->db_type == M_DATA);
3358 
3359 	if (!(mp = icmp_pkt_err_ok(mp))) {
3360 		return;
3361 	}
3362 
3363 	bzero(&icmph, sizeof (icmph_t));
3364 	icmph.icmph_type = ICMP_REDIRECT;
3365 	icmph.icmph_code = 1;
3366 	icmph.icmph_rd_gateway = gateway;
3367 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3368 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3369 }
3370 
3371 /*
3372  * Generate an ICMP time exceeded message.
3373  */
3374 void
3375 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3376 {
3377 	icmph_t	icmph;
3378 	boolean_t mctl_present;
3379 	mblk_t *first_mp;
3380 
3381 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3382 
3383 	if (!(mp = icmp_pkt_err_ok(mp))) {
3384 		if (mctl_present)
3385 			freeb(first_mp);
3386 		return;
3387 	}
3388 
3389 	bzero(&icmph, sizeof (icmph_t));
3390 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3391 	icmph.icmph_code = code;
3392 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3393 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3394 }
3395 
3396 /*
3397  * Generate an ICMP unreachable message.
3398  */
3399 void
3400 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3401 {
3402 	icmph_t	icmph;
3403 	mblk_t *first_mp;
3404 	boolean_t mctl_present;
3405 
3406 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3407 
3408 	if (!(mp = icmp_pkt_err_ok(mp))) {
3409 		if (mctl_present)
3410 			freeb(first_mp);
3411 		return;
3412 	}
3413 
3414 	bzero(&icmph, sizeof (icmph_t));
3415 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3416 	icmph.icmph_code = code;
3417 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3418 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3419 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3420 }
3421 
3422 /*
3423  * News from ARP.  ARP sends notification of interesting events down
3424  * to its clients using M_CTL messages with the interesting ARP packet
3425  * attached via b_cont.
3426  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3427  * queue as opposed to ARP sending the message to all the clients, i.e. all
3428  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3429  * table if a cache IRE is found to delete all the entries for the address in
3430  * the packet.
3431  */
3432 static void
3433 ip_arp_news(queue_t *q, mblk_t *mp)
3434 {
3435 	arcn_t		*arcn;
3436 	arh_t		*arh;
3437 	char		*cp1;
3438 	uchar_t		*cp2;
3439 	ire_t		*ire = NULL;
3440 	int		i1;
3441 	char		hbuf[128];
3442 	char		sbuf[16];
3443 	ipaddr_t	src;
3444 	in6_addr_t	v6src;
3445 	boolean_t	isv6 = B_FALSE;
3446 
3447 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3448 		if (q->q_next) {
3449 			putnext(q, mp);
3450 		} else
3451 			freemsg(mp);
3452 		return;
3453 	}
3454 	arh = (arh_t *)mp->b_cont->b_rptr;
3455 	/* Is it one we are interested in? */
3456 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3457 		isv6 = B_TRUE;
3458 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3459 		    IPV6_ADDR_LEN);
3460 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3461 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3462 		    IP_ADDR_LEN);
3463 	} else {
3464 		freemsg(mp);
3465 		return;
3466 	}
3467 
3468 	arcn = (arcn_t *)mp->b_rptr;
3469 	switch (arcn->arcn_code) {
3470 	case AR_CN_BOGON:
3471 		/*
3472 		 * Someone is sending ARP packets with a source protocol
3473 		 * address which we have published.  Either they are
3474 		 * pretending to be us, or we have been asked to proxy
3475 		 * for a machine that can do fine for itself, or two
3476 		 * different machines are providing proxy service for the
3477 		 * same protocol address, or something.  We try and do
3478 		 * something appropriate here.
3479 		 */
3480 		cp2 = (uchar_t *)&arh[1];
3481 		cp1 = hbuf;
3482 		*cp1 = '\0';
3483 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3484 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3485 		if (cp1 != hbuf)
3486 			cp1[-1] = '\0';
3487 		(void) ip_dot_addr(src, sbuf);
3488 		if (isv6)
3489 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3490 		else
3491 			ire = ire_cache_lookup(src, ALL_ZONES);
3492 
3493 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3494 			cmn_err(CE_WARN,
3495 			    "IP: Hardware address '%s' trying"
3496 			    " to be our address %s!",
3497 			    hbuf, sbuf);
3498 		} else {
3499 			cmn_err(CE_WARN,
3500 			    "IP: Proxy ARP problem?  "
3501 			    "Hardware address '%s' thinks it is %s",
3502 			    hbuf, sbuf);
3503 		}
3504 		if (ire != NULL)
3505 			ire_refrele(ire);
3506 		break;
3507 	case AR_CN_ANNOUNCE:
3508 		if (isv6) {
3509 			/*
3510 			 * For XRESOLV interfaces.
3511 			 * Delete the IRE cache entry and NCE for this
3512 			 * v6 address
3513 			 */
3514 			ip_ire_clookup_and_delete_v6(&v6src);
3515 			/*
3516 			 * If v6src is a non-zero, it's a router address
3517 			 * as below. Do the same sort of thing to clean
3518 			 * out off-net IRE_CACHE entries that go through
3519 			 * the router.
3520 			 */
3521 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3522 				ire_walk_v6(ire_delete_cache_gw_v6,
3523 				    (char *)&v6src, ALL_ZONES);
3524 			}
3525 			break;
3526 		}
3527 		/*
3528 		 * ARP gives us a copy of any broadcast packet with identical
3529 		 * sender and receiver protocol address, in
3530 		 * case we want to intuit something from it.  Such a packet
3531 		 * usually means that a machine has just come up on the net.
3532 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3533 		 * immediately pick up the rare case of a host changing
3534 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3535 		 *
3536 		 * The address in "src" may be an entry for a router.
3537 		 * (Default router, or non-default router.)  If
3538 		 * that's true, then any off-net IRE_CACHE entries
3539 		 * that go through the router with address "src"
3540 		 * must be clobbered.  Use ire_walk to achieve this
3541 		 * goal.
3542 		 *
3543 		 * It should be possible to determine if the address
3544 		 * in src is or is not for a router.  This way,
3545 		 * the ire_walk() isn't called all of the time here.
3546 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3547 		 * as it would remove all IRE_CACHE entries for onlink
3548 		 * destinations. All onlink destinations have
3549 		 * ire_gateway_addr == 0.
3550 		 */
3551 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3552 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3553 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3554 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3555 			    ALL_ZONES);
3556 		}
3557 		/* From ire_ftable_lookup */
3558 		if (ire != NULL)
3559 			ire_refrele(ire);
3560 		break;
3561 	default:
3562 		if (ire != NULL)
3563 			ire_refrele(ire);
3564 		break;
3565 	}
3566 	freemsg(mp);
3567 }
3568 
3569 /*
3570  * Create a mblk suitable for carrying the interface index and/or source link
3571  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3572  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3573  * application.
3574  */
3575 mblk_t *
3576 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3577 {
3578 	mblk_t		*mp;
3579 	in_pktinfo_t	*pinfo;
3580 	ipha_t *ipha;
3581 	struct ether_header *pether;
3582 
3583 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3584 	if (mp == NULL) {
3585 		ip1dbg(("ip_add_info: allocation failure.\n"));
3586 		return (data_mp);
3587 	}
3588 
3589 	ipha	= (ipha_t *)data_mp->b_rptr;
3590 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3591 	bzero(pinfo, sizeof (in_pktinfo_t));
3592 	pinfo->in_pkt_flags = (uchar_t)flags;
3593 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3594 
3595 	if (flags & IPF_RECVIF)
3596 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3597 
3598 	pether = (struct ether_header *)((char *)ipha
3599 	    - sizeof (struct ether_header));
3600 	/*
3601 	 * Make sure the interface is an ethernet type, since this option
3602 	 * is currently supported only on this type of interface. Also make
3603 	 * sure we are pointing correctly above db_base.
3604 	 */
3605 
3606 	if ((flags & IPF_RECVSLLA) &&
3607 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3608 	    (ill->ill_type == IFT_ETHER) &&
3609 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3610 
3611 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3612 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3613 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3614 	} else {
3615 		/*
3616 		 * Clear the bit. Indicate to upper layer that IP is not
3617 		 * sending this ancillary info.
3618 		 */
3619 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3620 	}
3621 
3622 	mp->b_datap->db_type = M_CTL;
3623 	mp->b_wptr += sizeof (in_pktinfo_t);
3624 	mp->b_cont = data_mp;
3625 
3626 	return (mp);
3627 }
3628 
3629 /*
3630  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3631  * part of the bind request.
3632  */
3633 
3634 boolean_t
3635 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3636 {
3637 	ipsec_in_t *ii;
3638 
3639 	ASSERT(policy_mp != NULL);
3640 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3641 
3642 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3643 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3644 
3645 	connp->conn_policy = ii->ipsec_in_policy;
3646 	ii->ipsec_in_policy = NULL;
3647 
3648 	if (ii->ipsec_in_action != NULL) {
3649 		if (connp->conn_latch == NULL) {
3650 			connp->conn_latch = iplatch_create();
3651 			if (connp->conn_latch == NULL)
3652 				return (B_FALSE);
3653 		}
3654 		ipsec_latch_inbound(connp->conn_latch, ii);
3655 	}
3656 	return (B_TRUE);
3657 }
3658 
3659 /*
3660  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3661  * and to arrange for power-fanout assist.  The ULP is identified by
3662  * adding a single byte at the end of the original bind message.
3663  * A ULP other than UDP or TCP that wishes to be recognized passes
3664  * down a bind with a zero length address.
3665  *
3666  * The binding works as follows:
3667  * - A zero byte address means just bind to the protocol.
3668  * - A four byte address is treated as a request to validate
3669  *   that the address is a valid local address, appropriate for
3670  *   an application to bind to. This does not affect any fanout
3671  *   information in IP.
3672  * - A sizeof sin_t byte address is used to bind to only the local address
3673  *   and port.
3674  * - A sizeof ipa_conn_t byte address contains complete fanout information
3675  *   consisting of local and remote addresses and ports.  In
3676  *   this case, the addresses are both validated as appropriate
3677  *   for this operation, and, if so, the information is retained
3678  *   for use in the inbound fanout.
3679  *
3680  * The ULP (except in the zero-length bind) can append an
3681  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3682  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3683  * a copy of the source or destination IRE (source for local bind;
3684  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3685  * policy information contained should be copied on to the conn.
3686  *
3687  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3688  */
3689 mblk_t *
3690 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3691 {
3692 	ssize_t		len;
3693 	struct T_bind_req	*tbr;
3694 	sin_t		*sin;
3695 	ipa_conn_t	*ac;
3696 	uchar_t		*ucp;
3697 	mblk_t		*mp1;
3698 	boolean_t	ire_requested;
3699 	boolean_t	ipsec_policy_set = B_FALSE;
3700 	int		error = 0;
3701 	int		protocol;
3702 	ipa_conn_x_t	*acx;
3703 
3704 	ASSERT(!connp->conn_af_isv6);
3705 	connp->conn_pkt_isv6 = B_FALSE;
3706 
3707 	len = mp->b_wptr - mp->b_rptr;
3708 	if (len < (sizeof (*tbr) + 1)) {
3709 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3710 		    "ip_bind: bogus msg, len %ld", len);
3711 		/* XXX: Need to return something better */
3712 		goto bad_addr;
3713 	}
3714 	/* Back up and extract the protocol identifier. */
3715 	mp->b_wptr--;
3716 	protocol = *mp->b_wptr & 0xFF;
3717 	tbr = (struct T_bind_req *)mp->b_rptr;
3718 	/* Reset the message type in preparation for shipping it back. */
3719 	mp->b_datap->db_type = M_PCPROTO;
3720 
3721 	connp->conn_ulp = (uint8_t)protocol;
3722 
3723 	/*
3724 	 * Check for a zero length address.  This is from a protocol that
3725 	 * wants to register to receive all packets of its type.
3726 	 */
3727 	if (tbr->ADDR_length == 0) {
3728 		/*
3729 		 * These protocols are now intercepted in ip_bind_v6().
3730 		 * Reject protocol-level binds here for now.
3731 		 *
3732 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3733 		 * so that the protocol type cannot be SCTP.
3734 		 */
3735 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3736 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3737 			goto bad_addr;
3738 		}
3739 
3740 		/* No hash here really.  The table is big enough. */
3741 		connp->conn_srcv6 = ipv6_all_zeros;
3742 
3743 		ipcl_proto_insert(connp, protocol);
3744 
3745 		tbr->PRIM_type = T_BIND_ACK;
3746 		return (mp);
3747 	}
3748 
3749 	/* Extract the address pointer from the message. */
3750 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3751 	    tbr->ADDR_length);
3752 	if (ucp == NULL) {
3753 		ip1dbg(("ip_bind: no address\n"));
3754 		goto bad_addr;
3755 	}
3756 	if (!OK_32PTR(ucp)) {
3757 		ip1dbg(("ip_bind: unaligned address\n"));
3758 		goto bad_addr;
3759 	}
3760 	/*
3761 	 * Check for trailing mps.
3762 	 */
3763 
3764 	mp1 = mp->b_cont;
3765 	ire_requested = (mp1 && mp1->b_datap->db_type == IRE_DB_REQ_TYPE);
3766 	ipsec_policy_set = (mp1 && mp1->b_datap->db_type == IPSEC_POLICY_SET);
3767 
3768 	switch (tbr->ADDR_length) {
3769 	default:
3770 		ip1dbg(("ip_bind: bad address length %d\n",
3771 		    (int)tbr->ADDR_length));
3772 		goto bad_addr;
3773 
3774 	case IP_ADDR_LEN:
3775 		/* Verification of local address only */
3776 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3777 		    ire_requested, ipsec_policy_set, B_FALSE);
3778 		break;
3779 
3780 	case sizeof (sin_t):
3781 		sin = (sin_t *)ucp;
3782 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3783 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3784 		if (protocol == IPPROTO_TCP)
3785 			connp->conn_recv = tcp_conn_request;
3786 		break;
3787 
3788 	case sizeof (ipa_conn_t):
3789 		ac = (ipa_conn_t *)ucp;
3790 		/* For raw socket, the local port is not set. */
3791 		if (ac->ac_lport == 0)
3792 			ac->ac_lport = connp->conn_lport;
3793 		/* Always verify destination reachability. */
3794 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3795 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3796 		    ipsec_policy_set, B_TRUE, B_TRUE);
3797 		if (protocol == IPPROTO_TCP)
3798 			connp->conn_recv = tcp_input;
3799 		break;
3800 
3801 	case sizeof (ipa_conn_x_t):
3802 		acx = (ipa_conn_x_t *)ucp;
3803 		/*
3804 		 * Whether or not to verify destination reachability depends
3805 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3806 		 */
3807 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3808 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3809 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3810 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3811 		if (protocol == IPPROTO_TCP)
3812 			connp->conn_recv = tcp_input;
3813 		break;
3814 	}
3815 	if (error == EINPROGRESS)
3816 		return (NULL);
3817 	else if (error != 0)
3818 		goto bad_addr;
3819 	/*
3820 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3821 	 * We can't do this in ip_bind_insert_ire because the policy
3822 	 * may not have been inherited at that point in time and hence
3823 	 * conn_out_enforce_policy may not be set.
3824 	 */
3825 	mp1 = mp->b_cont;
3826 	if (ire_requested && connp->conn_out_enforce_policy &&
3827 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3828 		ire_t *ire = (ire_t *)mp1->b_rptr;
3829 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3830 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3831 	}
3832 
3833 	/* Send it home. */
3834 	mp->b_datap->db_type = M_PCPROTO;
3835 	tbr->PRIM_type = T_BIND_ACK;
3836 	return (mp);
3837 
3838 bad_addr:
3839 	/*
3840 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3841 	 * a unix errno.
3842 	 */
3843 	if (error > 0)
3844 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3845 	else
3846 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3847 	return (mp);
3848 }
3849 
3850 /*
3851  * Here address is verified to be a valid local address.
3852  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3853  * address is also considered a valid local address.
3854  * In the case of a broadcast/multicast address, however, the
3855  * upper protocol is expected to reset the src address
3856  * to 0 if it sees a IRE_BROADCAST type returned so that
3857  * no packets are emitted with broadcast/multicast address as
3858  * source address (that violates hosts requirements RFC1122)
3859  * The addresses valid for bind are:
3860  *	(1) - INADDR_ANY (0)
3861  *	(2) - IP address of an UP interface
3862  *	(3) - IP address of a DOWN interface
3863  *	(4) - valid local IP broadcast addresses. In this case
3864  *	the conn will only receive packets destined to
3865  *	the specified broadcast address.
3866  *	(5) - a multicast address. In this case
3867  *	the conn will only receive packets destined to
3868  *	the specified multicast address. Note: the
3869  *	application still has to issue an
3870  *	IP_ADD_MEMBERSHIP socket option.
3871  *
3872  * On error, return -1 for TBADADDR otherwise pass the
3873  * errno with TSYSERR reply.
3874  *
3875  * In all the above cases, the bound address must be valid in the current zone.
3876  * When the address is loopback, multicast or broadcast, there might be many
3877  * matching IREs so bind has to look up based on the zone.
3878  */
3879 int
3880 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3881     boolean_t ire_requested, boolean_t ipsec_policy_set,
3882     boolean_t fanout_insert)
3883 {
3884 	int		error = 0;
3885 	ire_t		*src_ire;
3886 	mblk_t		*policy_mp;
3887 	ipif_t		*ipif;
3888 	zoneid_t	zoneid;
3889 
3890 	if (ipsec_policy_set) {
3891 		policy_mp = mp->b_cont;
3892 	}
3893 
3894 	/*
3895 	 * If it was previously connected, conn_fully_bound would have
3896 	 * been set.
3897 	 */
3898 	connp->conn_fully_bound = B_FALSE;
3899 
3900 	src_ire = NULL;
3901 	ipif = NULL;
3902 
3903 	zoneid = connp->conn_zoneid;
3904 
3905 	if (src_addr) {
3906 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3907 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3908 		/*
3909 		 * If an address other than 0.0.0.0 is requested,
3910 		 * we verify that it is a valid address for bind
3911 		 * Note: Following code is in if-else-if form for
3912 		 * readability compared to a condition check.
3913 		 */
3914 		/* LINTED - statement has no consequent */
3915 		if (IRE_IS_LOCAL(src_ire)) {
3916 			/*
3917 			 * (2) Bind to address of local UP interface
3918 			 */
3919 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3920 			/*
3921 			 * (4) Bind to broadcast address
3922 			 * Note: permitted only from transports that
3923 			 * request IRE
3924 			 */
3925 			if (!ire_requested)
3926 				error = EADDRNOTAVAIL;
3927 		} else {
3928 			/*
3929 			 * (3) Bind to address of local DOWN interface
3930 			 * (ipif_lookup_addr() looks up all interfaces
3931 			 * but we do not get here for UP interfaces
3932 			 * - case (2) above)
3933 			 * We put the protocol byte back into the mblk
3934 			 * since we may come back via ip_wput_nondata()
3935 			 * later with this mblk if ipif_lookup_addr chooses
3936 			 * to defer processing.
3937 			 */
3938 			*mp->b_wptr++ = (char)connp->conn_ulp;
3939 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3940 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3941 			    &error)) != NULL) {
3942 				ipif_refrele(ipif);
3943 			} else if (error == EINPROGRESS) {
3944 				if (src_ire != NULL)
3945 					ire_refrele(src_ire);
3946 				return (EINPROGRESS);
3947 			} else if (CLASSD(src_addr)) {
3948 				error = 0;
3949 				if (src_ire != NULL)
3950 					ire_refrele(src_ire);
3951 				/*
3952 				 * (5) bind to multicast address.
3953 				 * Fake out the IRE returned to upper
3954 				 * layer to be a broadcast IRE.
3955 				 */
3956 				src_ire = ire_ctable_lookup(
3957 				    INADDR_BROADCAST, INADDR_ANY,
3958 				    IRE_BROADCAST, NULL, zoneid,
3959 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3960 				if (src_ire == NULL || !ire_requested)
3961 					error = EADDRNOTAVAIL;
3962 			} else {
3963 				/*
3964 				 * Not a valid address for bind
3965 				 */
3966 				error = EADDRNOTAVAIL;
3967 			}
3968 			/*
3969 			 * Just to keep it consistent with the processing in
3970 			 * ip_bind_v4()
3971 			 */
3972 			mp->b_wptr--;
3973 		}
3974 		if (error) {
3975 			/* Red Alert!  Attempting to be a bogon! */
3976 			ip1dbg(("ip_bind: bad src address 0x%x\n",
3977 			    ntohl(src_addr)));
3978 			goto bad_addr;
3979 		}
3980 	}
3981 
3982 	/*
3983 	 * Allow setting new policies. For example, disconnects come
3984 	 * down as ipa_t bind. As we would have set conn_policy_cached
3985 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3986 	 * can change after the disconnect.
3987 	 */
3988 	connp->conn_policy_cached = B_FALSE;
3989 
3990 	/*
3991 	 * If not fanout_insert this was just an address verification
3992 	 */
3993 	if (fanout_insert) {
3994 		/*
3995 		 * The addresses have been verified. Time to insert in
3996 		 * the correct fanout list.
3997 		 */
3998 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
3999 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4000 		connp->conn_lport = lport;
4001 		connp->conn_fport = 0;
4002 		/*
4003 		 * Do we need to add a check to reject Multicast packets
4004 		 */
4005 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4006 	}
4007 done:
4008 	if (error == 0) {
4009 		if (ire_requested) {
4010 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4011 				error = -1;
4012 				/* Falls through to bad_addr */
4013 			}
4014 		} else if (ipsec_policy_set) {
4015 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4016 				error = -1;
4017 				/* Falls through to bad_addr */
4018 			}
4019 		}
4020 	}
4021 bad_addr:
4022 	if (src_ire != NULL)
4023 		IRE_REFRELE(src_ire);
4024 	if (ipsec_policy_set) {
4025 		ASSERT(policy_mp == mp->b_cont);
4026 		ASSERT(policy_mp != NULL);
4027 		freeb(policy_mp);
4028 		/*
4029 		 * As of now assume that nothing else accompanies
4030 		 * IPSEC_POLICY_SET.
4031 		 */
4032 		mp->b_cont = NULL;
4033 	}
4034 	return (error);
4035 }
4036 
4037 /*
4038  * Verify that both the source and destination addresses
4039  * are valid.  If verify_dst is false, then the destination address may be
4040  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4041  * destination reachability, while tunnels do not.
4042  * Note that we allow connect to broadcast and multicast
4043  * addresses when ire_requested is set. Thus the ULP
4044  * has to check for IRE_BROADCAST and multicast.
4045  *
4046  * Returns zero if ok.
4047  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4048  * (for use with TSYSERR reply).
4049  */
4050 int
4051 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4052     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4053     boolean_t ire_requested, boolean_t ipsec_policy_set,
4054     boolean_t fanout_insert, boolean_t verify_dst)
4055 {
4056 	ire_t		*src_ire;
4057 	ire_t		*dst_ire;
4058 	int		error = 0;
4059 	int 		protocol;
4060 	mblk_t		*policy_mp;
4061 	ire_t		*sire = NULL;
4062 	ire_t		*md_dst_ire = NULL;
4063 	ill_t		*md_ill = NULL;
4064 	zoneid_t	zoneid;
4065 	ipaddr_t	src_addr = *src_addrp;
4066 
4067 	src_ire = dst_ire = NULL;
4068 	protocol = *mp->b_wptr & 0xFF;
4069 
4070 	/*
4071 	 * If we never got a disconnect before, clear it now.
4072 	 */
4073 	connp->conn_fully_bound = B_FALSE;
4074 
4075 	if (ipsec_policy_set) {
4076 		policy_mp = mp->b_cont;
4077 	}
4078 
4079 	zoneid = connp->conn_zoneid;
4080 
4081 	if (CLASSD(dst_addr)) {
4082 		/* Pick up an IRE_BROADCAST */
4083 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4084 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4085 		    MATCH_IRE_RJ_BHOLE));
4086 	} else {
4087 		/*
4088 		 * If conn_dontroute is set, and onlink ipif is not found
4089 		 * set ENETUNREACH error
4090 		 */
4091 		if (connp->conn_dontroute) {
4092 			ipif_t *ipif;
4093 
4094 			ipif = ipif_lookup_onlink_addr(dst_addr, zoneid);
4095 			if (ipif == NULL) {
4096 				error = ENETUNREACH;
4097 				goto bad_addr;
4098 			}
4099 			ipif_refrele(ipif);
4100 		}
4101 		dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL, &sire,
4102 		    zoneid,
4103 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4104 		    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4105 	}
4106 	/*
4107 	 * dst_ire can't be a broadcast when not ire_requested.
4108 	 * We also prevent ire's with src address INADDR_ANY to
4109 	 * be used, which are created temporarily for
4110 	 * sending out packets from endpoints that have
4111 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4112 	 * reachable.  If verify_dst is false, the destination needn't be
4113 	 * reachable.
4114 	 *
4115 	 * If we match on a reject or black hole, then we've got a
4116 	 * local failure.  May as well fail out the connect() attempt,
4117 	 * since it's never going to succeed.
4118 	 */
4119 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4120 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4121 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4122 		/*
4123 		 * If we're verifying destination reachability, we always want
4124 		 * to complain here.
4125 		 *
4126 		 * If we're not verifying destination reachability but the
4127 		 * destination has a route, we still want to fail on the
4128 		 * temporary address and broadcast address tests.
4129 		 */
4130 		if (verify_dst || (dst_ire != NULL)) {
4131 			if (ip_debug > 2) {
4132 				pr_addr_dbg("ip_bind_connected: bad connected "
4133 				    "dst %s\n", AF_INET, &dst_addr);
4134 			}
4135 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4136 				error = ENETUNREACH;
4137 			else
4138 				error = EHOSTUNREACH;
4139 			goto bad_addr;
4140 		}
4141 	}
4142 	/*
4143 	 * If the app does a connect(), it means that it will most likely
4144 	 * send more than 1 packet to the destination.  It makes sense
4145 	 * to clear the temporary flag.
4146 	 */
4147 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4148 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4149 		irb_t *irb = dst_ire->ire_bucket;
4150 
4151 		rw_enter(&irb->irb_lock, RW_WRITER);
4152 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4153 		irb->irb_tmp_ire_cnt--;
4154 		rw_exit(&irb->irb_lock);
4155 	}
4156 
4157 	/*
4158 	 * See if we should notify ULP about MDT; we do this whether or not
4159 	 * ire_requested is TRUE, in order to handle active connects; MDT
4160 	 * eligibility tests for passive connects are handled separately
4161 	 * through tcp_adapt_ire().  We do this before the source address
4162 	 * selection, because dst_ire may change after a call to
4163 	 * ipif_select_source().  This is a best-effort check, as the
4164 	 * packet for this connection may not actually go through
4165 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4166 	 * calling ip_newroute().  This is why we further check on the
4167 	 * IRE during Multidata packet transmission in tcp_multisend().
4168 	 */
4169 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4170 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4171 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4172 	    (md_ill->ill_capabilities & ILL_CAPAB_MDT)) {
4173 		md_dst_ire = dst_ire;
4174 		IRE_REFHOLD(md_dst_ire);
4175 	}
4176 
4177 	if (dst_ire != NULL &&
4178 	    dst_ire->ire_type == IRE_LOCAL &&
4179 	    dst_ire->ire_zoneid != zoneid) {
4180 		/*
4181 		 * If the IRE belongs to a different zone, look for a matching
4182 		 * route in the forwarding table and use the source address from
4183 		 * that route.
4184 		 */
4185 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4186 		    zoneid, 0,
4187 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4188 		    MATCH_IRE_RJ_BHOLE);
4189 		if (src_ire == NULL) {
4190 			error = EHOSTUNREACH;
4191 			goto bad_addr;
4192 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4193 			if (!(src_ire->ire_type & IRE_HOST))
4194 				error = ENETUNREACH;
4195 			else
4196 				error = EHOSTUNREACH;
4197 			goto bad_addr;
4198 		}
4199 		if (src_addr == INADDR_ANY)
4200 			src_addr = src_ire->ire_src_addr;
4201 		ire_refrele(src_ire);
4202 		src_ire = NULL;
4203 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4204 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4205 			src_addr = sire->ire_src_addr;
4206 			ire_refrele(dst_ire);
4207 			dst_ire = sire;
4208 			sire = NULL;
4209 		} else {
4210 			/*
4211 			 * Pick a source address so that a proper inbound
4212 			 * load spreading would happen.
4213 			 */
4214 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4215 			ipif_t *src_ipif = NULL;
4216 			ire_t *ipif_ire;
4217 
4218 			/*
4219 			 * Supply a local source address such that inbound
4220 			 * load spreading happens.
4221 			 *
4222 			 * Determine the best source address on this ill for
4223 			 * the destination.
4224 			 *
4225 			 * 1) For broadcast, we should return a broadcast ire
4226 			 *    found above so that upper layers know that the
4227 			 *    destination address is a broadcast address.
4228 			 *
4229 			 * 2) If this is part of a group, select a better
4230 			 *    source address so that better inbound load
4231 			 *    balancing happens. Do the same if the ipif
4232 			 *    is DEPRECATED.
4233 			 *
4234 			 * 3) If the outgoing interface is part of a usesrc
4235 			 *    group, then try selecting a source address from
4236 			 *    the usesrc ILL.
4237 			 */
4238 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4239 			    ((dst_ill->ill_group != NULL) ||
4240 			    (dst_ire->ire_ipif->ipif_flags &
4241 			    IPIF_DEPRECATED) ||
4242 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4243 				src_ipif = ipif_select_source(dst_ill,
4244 				    dst_addr, zoneid);
4245 				if (src_ipif != NULL) {
4246 					if (IS_VNI(src_ipif->ipif_ill)) {
4247 						/*
4248 						 * For VNI there is no
4249 						 * interface route
4250 						 */
4251 						src_addr =
4252 						    src_ipif->ipif_src_addr;
4253 					} else {
4254 						ipif_ire =
4255 						    ipif_to_ire(src_ipif);
4256 						if (ipif_ire != NULL) {
4257 							IRE_REFRELE(dst_ire);
4258 							dst_ire = ipif_ire;
4259 						}
4260 						src_addr =
4261 						    dst_ire->ire_src_addr;
4262 					}
4263 					ipif_refrele(src_ipif);
4264 				} else {
4265 					src_addr = dst_ire->ire_src_addr;
4266 				}
4267 			} else {
4268 				src_addr = dst_ire->ire_src_addr;
4269 			}
4270 		}
4271 	}
4272 
4273 	/*
4274 	 * We do ire_route_lookup() here (and not
4275 	 * interface lookup as we assert that
4276 	 * src_addr should only come from an
4277 	 * UP interface for hard binding.
4278 	 */
4279 	ASSERT(src_ire == NULL);
4280 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4281 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4282 	/* src_ire must be a local|loopback */
4283 	if (!IRE_IS_LOCAL(src_ire)) {
4284 		if (ip_debug > 2) {
4285 			pr_addr_dbg("ip_bind_connected: bad connected "
4286 			    "src %s\n", AF_INET, &src_addr);
4287 		}
4288 		error = EADDRNOTAVAIL;
4289 		goto bad_addr;
4290 	}
4291 
4292 	/*
4293 	 * If the source address is a loopback address, the
4294 	 * destination had best be local or multicast.
4295 	 * The transports that can't handle multicast will reject
4296 	 * those addresses.
4297 	 */
4298 	if (src_ire->ire_type == IRE_LOOPBACK &&
4299 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4300 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4301 		error = -1;
4302 		goto bad_addr;
4303 	}
4304 
4305 	/*
4306 	 * Allow setting new policies. For example, disconnects come
4307 	 * down as ipa_t bind. As we would have set conn_policy_cached
4308 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4309 	 * can change after the disconnect.
4310 	 */
4311 	connp->conn_policy_cached = B_FALSE;
4312 
4313 	/*
4314 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4315 	 * can handle their passed-in conn's.
4316 	 */
4317 
4318 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4319 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4320 	connp->conn_lport = lport;
4321 	connp->conn_fport = fport;
4322 	*src_addrp = src_addr;
4323 
4324 	ASSERT(!(ipsec_policy_set && ire_requested));
4325 	if (ire_requested) {
4326 		iulp_t *ulp_info = NULL;
4327 
4328 		/*
4329 		 * Note that sire will not be NULL if this is an off-link
4330 		 * connection and there is not cache for that dest yet.
4331 		 *
4332 		 * XXX Because of an existing bug, if there are multiple
4333 		 * default routes, the IRE returned now may not be the actual
4334 		 * default route used (default routes are chosen in a
4335 		 * round robin fashion).  So if the metrics for different
4336 		 * default routes are different, we may return the wrong
4337 		 * metrics.  This will not be a problem if the existing
4338 		 * bug is fixed.
4339 		 */
4340 		if (sire != NULL) {
4341 			ulp_info = &(sire->ire_uinfo);
4342 		}
4343 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4344 			error = -1;
4345 			goto bad_addr;
4346 		}
4347 	} else if (ipsec_policy_set) {
4348 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4349 			error = -1;
4350 			goto bad_addr;
4351 		}
4352 	}
4353 
4354 	/*
4355 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4356 	 * we'll cache that.  If we don't, we'll inherit global policy.
4357 	 *
4358 	 * We can't insert until the conn reflects the policy. Note that
4359 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4360 	 * connections where we don't have a policy. This is to prevent
4361 	 * global policy lookups in the inbound path.
4362 	 *
4363 	 * If we insert before we set conn_policy_cached,
4364 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4365 	 * because global policy cound be non-empty. We normally call
4366 	 * ipsec_check_policy() for conn_policy_cached connections only if
4367 	 * ipc_in_enforce_policy is set. But in this case,
4368 	 * conn_policy_cached can get set anytime since we made the
4369 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4370 	 * called, which will make the above assumption false.  Thus, we
4371 	 * need to insert after we set conn_policy_cached.
4372 	 */
4373 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4374 		goto bad_addr;
4375 
4376 	if (fanout_insert) {
4377 		/*
4378 		 * The addresses have been verified. Time to insert in
4379 		 * the correct fanout list.
4380 		 */
4381 		error = ipcl_conn_insert(connp, protocol, src_addr,
4382 		    dst_addr, connp->conn_ports);
4383 	}
4384 
4385 	if (error == 0) {
4386 		connp->conn_fully_bound = B_TRUE;
4387 		/*
4388 		 * Our initial checks for MDT have passed; the IRE is not
4389 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4390 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4391 		 * ip_mdinfo_return(), which performs further checks
4392 		 * against them and upon success, returns the MDT info
4393 		 * mblk which we will attach to the bind acknowledgment.
4394 		 */
4395 		if (md_dst_ire != NULL) {
4396 			mblk_t *mdinfo_mp;
4397 
4398 			ASSERT(md_ill != NULL);
4399 			ASSERT(md_ill->ill_mdt_capab != NULL);
4400 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4401 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4402 				linkb(mp, mdinfo_mp);
4403 		}
4404 	}
4405 bad_addr:
4406 	if (ipsec_policy_set) {
4407 		ASSERT(policy_mp == mp->b_cont);
4408 		ASSERT(policy_mp != NULL);
4409 		freeb(policy_mp);
4410 		/*
4411 		 * As of now assume that nothing else accompanies
4412 		 * IPSEC_POLICY_SET.
4413 		 */
4414 		mp->b_cont = NULL;
4415 	}
4416 	if (src_ire != NULL)
4417 		IRE_REFRELE(src_ire);
4418 	if (dst_ire != NULL)
4419 		IRE_REFRELE(dst_ire);
4420 	if (sire != NULL)
4421 		IRE_REFRELE(sire);
4422 	if (md_dst_ire != NULL)
4423 		IRE_REFRELE(md_dst_ire);
4424 	return (error);
4425 }
4426 
4427 /*
4428  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4429  * Prefers dst_ire over src_ire.
4430  */
4431 static boolean_t
4432 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4433 {
4434 	mblk_t	*mp1;
4435 	ire_t *ret_ire = NULL;
4436 
4437 	mp1 = mp->b_cont;
4438 	ASSERT(mp1 != NULL);
4439 
4440 	if (ire != NULL) {
4441 		/*
4442 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4443 		 * appended mblk. Its <upper protocol>'s
4444 		 * job to make sure there is room.
4445 		 */
4446 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4447 			return (0);
4448 
4449 		mp1->b_datap->db_type = IRE_DB_TYPE;
4450 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4451 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4452 		ret_ire = (ire_t *)mp1->b_rptr;
4453 		/*
4454 		 * Pass the latest setting of the ip_path_mtu_discovery and
4455 		 * copy the ulp info if any.
4456 		 */
4457 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4458 		    IPH_DF : 0;
4459 		if (ulp_info != NULL) {
4460 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4461 			    sizeof (iulp_t));
4462 		}
4463 		ret_ire->ire_mp = mp1;
4464 	} else {
4465 		/*
4466 		 * No IRE was found. Remove IRE mblk.
4467 		 */
4468 		mp->b_cont = mp1->b_cont;
4469 		freeb(mp1);
4470 	}
4471 
4472 	return (1);
4473 }
4474 
4475 /*
4476  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4477  * the final piece where we don't.  Return a pointer to the first mblk in the
4478  * result, and update the pointer to the next mblk to chew on.  If anything
4479  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4480  * NULL pointer.
4481  */
4482 mblk_t *
4483 ip_carve_mp(mblk_t **mpp, ssize_t len)
4484 {
4485 	mblk_t	*mp0;
4486 	mblk_t	*mp1;
4487 	mblk_t	*mp2;
4488 
4489 	if (!len || !mpp || !(mp0 = *mpp))
4490 		return (NULL);
4491 	/* If we aren't going to consume the first mblk, we need a dup. */
4492 	if (mp0->b_wptr - mp0->b_rptr > len) {
4493 		mp1 = dupb(mp0);
4494 		if (mp1) {
4495 			/* Partition the data between the two mblks. */
4496 			mp1->b_wptr = mp1->b_rptr + len;
4497 			mp0->b_rptr = mp1->b_wptr;
4498 			/*
4499 			 * after adjustments if mblk not consumed is now
4500 			 * unaligned, try to align it. If this fails free
4501 			 * all messages and let upper layer recover.
4502 			 */
4503 			if (!OK_32PTR(mp0->b_rptr)) {
4504 				if (!pullupmsg(mp0, -1)) {
4505 					freemsg(mp0);
4506 					freemsg(mp1);
4507 					*mpp = NULL;
4508 					return (NULL);
4509 				}
4510 			}
4511 		}
4512 		return (mp1);
4513 	}
4514 	/* Eat through as many mblks as we need to get len bytes. */
4515 	len -= mp0->b_wptr - mp0->b_rptr;
4516 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4517 		if (mp2->b_wptr - mp2->b_rptr > len) {
4518 			/*
4519 			 * We won't consume the entire last mblk.  Like
4520 			 * above, dup and partition it.
4521 			 */
4522 			mp1->b_cont = dupb(mp2);
4523 			mp1 = mp1->b_cont;
4524 			if (!mp1) {
4525 				/*
4526 				 * Trouble.  Rather than go to a lot of
4527 				 * trouble to clean up, we free the messages.
4528 				 * This won't be any worse than losing it on
4529 				 * the wire.
4530 				 */
4531 				freemsg(mp0);
4532 				freemsg(mp2);
4533 				*mpp = NULL;
4534 				return (NULL);
4535 			}
4536 			mp1->b_wptr = mp1->b_rptr + len;
4537 			mp2->b_rptr = mp1->b_wptr;
4538 			/*
4539 			 * after adjustments if mblk not consumed is now
4540 			 * unaligned, try to align it. If this fails free
4541 			 * all messages and let upper layer recover.
4542 			 */
4543 			if (!OK_32PTR(mp2->b_rptr)) {
4544 				if (!pullupmsg(mp2, -1)) {
4545 					freemsg(mp0);
4546 					freemsg(mp2);
4547 					*mpp = NULL;
4548 					return (NULL);
4549 				}
4550 			}
4551 			*mpp = mp2;
4552 			return (mp0);
4553 		}
4554 		/* Decrement len by the amount we just got. */
4555 		len -= mp2->b_wptr - mp2->b_rptr;
4556 	}
4557 	/*
4558 	 * len should be reduced to zero now.  If not our caller has
4559 	 * screwed up.
4560 	 */
4561 	if (len) {
4562 		/* Shouldn't happen! */
4563 		freemsg(mp0);
4564 		*mpp = NULL;
4565 		return (NULL);
4566 	}
4567 	/*
4568 	 * We consumed up to exactly the end of an mblk.  Detach the part
4569 	 * we are returning from the rest of the chain.
4570 	 */
4571 	mp1->b_cont = NULL;
4572 	*mpp = mp2;
4573 	return (mp0);
4574 }
4575 
4576 /* The ill stream is being unplumbed. Called from ip_close */
4577 int
4578 ip_modclose(ill_t *ill)
4579 {
4580 
4581 	boolean_t success;
4582 	ipsq_t	*ipsq;
4583 	ipif_t	*ipif;
4584 	queue_t	*q = ill->ill_rq;
4585 
4586 	/*
4587 	 * Forcibly enter the ipsq after some delay. This is to take
4588 	 * care of the case when some ioctl does not complete because
4589 	 * we sent a control message to the driver and it did not
4590 	 * send us a reply. We want to be able to at least unplumb
4591 	 * and replumb rather than force the user to reboot the system.
4592 	 */
4593 	success = ipsq_enter(ill, B_FALSE);
4594 
4595 	/*
4596 	 * Open/close/push/pop is guaranteed to be single threaded
4597 	 * per stream by STREAMS. FS guarantees that all references
4598 	 * from top are gone before close is called. So there can't
4599 	 * be another close thread that has set CONDEMNED on this ill.
4600 	 * and cause ipsq_enter to return failure.
4601 	 */
4602 	ASSERT(success);
4603 	ipsq = ill->ill_phyint->phyint_ipsq;
4604 
4605 	/*
4606 	 * Mark it condemned. No new reference will be made to this ill.
4607 	 * Lookup functions will return an error. Threads that try to
4608 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4609 	 * that the refcnt will drop down to zero.
4610 	 */
4611 	mutex_enter(&ill->ill_lock);
4612 	ill->ill_state_flags |= ILL_CONDEMNED;
4613 	for (ipif = ill->ill_ipif; ipif != NULL;
4614 	    ipif = ipif->ipif_next) {
4615 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4616 	}
4617 	/*
4618 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4619 	 * returns  error if ILL_CONDEMNED is set
4620 	 */
4621 	cv_broadcast(&ill->ill_cv);
4622 	mutex_exit(&ill->ill_lock);
4623 
4624 	/*
4625 	 * Shut down fragmentation reassembly.
4626 	 * ill_frag_timer won't start a timer again.
4627 	 * Now cancel any existing timer
4628 	 */
4629 	(void) untimeout(ill->ill_frag_timer_id);
4630 	(void) ill_frag_timeout(ill, 0);
4631 
4632 	/*
4633 	 * If MOVE was in progress, clear the
4634 	 * move_in_progress fields also.
4635 	 */
4636 	if (ill->ill_move_in_progress) {
4637 		ILL_CLEAR_MOVE(ill);
4638 	}
4639 
4640 	/*
4641 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4642 	 * this ill. Then wait for the refcnts to drop to zero.
4643 	 * ill_is_quiescent checks whether the ill is really quiescent.
4644 	 * Then make sure that threads that are waiting to enter the
4645 	 * ipsq have seen the error returned by ipsq_enter and have
4646 	 * gone away. Then we call ill_delete_tail which does the
4647 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4648 	 */
4649 	ill_delete(ill);
4650 	mutex_enter(&ill->ill_lock);
4651 	while (!ill_is_quiescent(ill))
4652 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4653 	while (ill->ill_waiters)
4654 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4655 
4656 	mutex_exit(&ill->ill_lock);
4657 
4658 	/* qprocsoff is called in ill_delete_tail */
4659 	ill_delete_tail(ill);
4660 
4661 	/*
4662 	 * Walk through all upper (conn) streams and qenable
4663 	 * those that have queued data.
4664 	 * close synchronization needs this to
4665 	 * be done to ensure that all upper layers blocked
4666 	 * due to flow control to the closing device
4667 	 * get unblocked.
4668 	 */
4669 	ip1dbg(("ip_wsrv: walking\n"));
4670 	conn_walk_drain();
4671 
4672 	mutex_enter(&ip_mi_lock);
4673 	mi_close_unlink(&ip_g_head, (IDP)ill);
4674 	mutex_exit(&ip_mi_lock);
4675 
4676 	/*
4677 	 * credp could be null if the open didn't succeed and ip_modopen
4678 	 * itself calls ip_close.
4679 	 */
4680 	if (ill->ill_credp != NULL)
4681 		crfree(ill->ill_credp);
4682 
4683 	mi_close_free((IDP)ill);
4684 	q->q_ptr = WR(q)->q_ptr = NULL;
4685 
4686 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4687 
4688 	return (0);
4689 }
4690 
4691 /*
4692  * IP has been configured as _D_QNEXTLESS for the client side i.e the driver
4693  * instance. This implies that
4694  * 1. IP cannot access the read side q_next pointer directly - it must
4695  *    use routines like putnext and canputnext.
4696  * 2. ip_close must ensure that all sources of messages being putnext upstream
4697  *    are gone before qprocsoff is called.
4698  *
4699  * #2 is handled by having ip_close do the ipcl_hash_remove and wait for
4700  * conn_ref to drop to zero before calling qprocsoff.
4701  */
4702 
4703 /* ARGSUSED */
4704 int
4705 ip_close(queue_t *q, int flags)
4706 {
4707 	conn_t		*connp;
4708 	boolean_t	drain_cleanup_reqd = B_FALSE;
4709 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4710 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4711 
4712 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4713 
4714 	/*
4715 	 * Call the appropriate delete routine depending on whether this is
4716 	 * a module or device.
4717 	 */
4718 	if (WR(q)->q_next != NULL) {
4719 		/* This is a module close */
4720 		return (ip_modclose((ill_t *)q->q_ptr));
4721 	}
4722 
4723 	connp = Q_TO_CONN(q);
4724 	ASSERT(connp->conn_tcp == NULL);
4725 
4726 	/*
4727 	 * We are being closed as /dev/ip or /dev/ip6.
4728 	 *
4729 	 * Mark the conn as closing, and this conn must not be
4730 	 * inserted in future into any list. Eg. conn_drain_insert(),
4731 	 * won't insert this conn into the conn_drain_list.
4732 	 * Similarly ill_pending_mp_add() will not add any mp to
4733 	 * the pending mp list, after this conn has started closing.
4734 	 *
4735 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4736 	 * cannot get set henceforth.
4737 	 */
4738 	mutex_enter(&connp->conn_lock);
4739 	connp->conn_state_flags |= CONN_CLOSING;
4740 	if (connp->conn_idl != NULL)
4741 		drain_cleanup_reqd = B_TRUE;
4742 	if (connp->conn_oper_pending_ill != NULL)
4743 		conn_ioctl_cleanup_reqd = B_TRUE;
4744 	if (connp->conn_ilg_inuse != 0)
4745 		ilg_cleanup_reqd = B_TRUE;
4746 	mutex_exit(&connp->conn_lock);
4747 
4748 	if (conn_ioctl_cleanup_reqd)
4749 		conn_ioctl_cleanup(connp);
4750 
4751 	/*
4752 	 * Remove this conn from any fanout list it is on.
4753 	 * Then wait until the number of pending putnexts from
4754 	 * the fanout code drops to zero, before calling qprocsoff.
4755 	 * This is the guarantee a QNEXTLESS driver provides to
4756 	 * STREAMS, and is mentioned at the top of this function.
4757 	 */
4758 
4759 	ipcl_hash_remove(connp);
4760 
4761 	/*
4762 	 * Remove this conn from the drain list, and do
4763 	 * any other cleanup that may be required.
4764 	 * (Only non-tcp streams may have a non-null conn_idl.
4765 	 * TCP streams are never flow controlled, and
4766 	 * conn_idl will be null)
4767 	 */
4768 	if (drain_cleanup_reqd)
4769 		conn_drain_tail(connp, B_TRUE);
4770 
4771 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4772 		(void) ip_mrouter_done(NULL);
4773 
4774 	if (ilg_cleanup_reqd)
4775 		ilg_delete_all(connp);
4776 
4777 	conn_delete_ire(connp, NULL);
4778 
4779 
4780 	/*
4781 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4782 	 * callers from write side can't be there now because close
4783 	 * is in progress. The only other caller is ipcl_walk
4784 	 * which checks for the condemned flag.
4785 	 */
4786 	mutex_enter(&connp->conn_lock);
4787 	connp->conn_state_flags |= CONN_CONDEMNED;
4788 	while (connp->conn_ref != 1)
4789 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4790 	mutex_exit(&connp->conn_lock);
4791 
4792 	qprocsoff(q);
4793 
4794 	/*
4795 	 * Now we are truly single threaded on this stream, and can
4796 	 * delete the things hanging off the connp, and finally the connp.
4797 	 * We removed this connp from the fanout list, it cannot be
4798 	 * accessed thru the fanouts, and we already waited for the
4799 	 * conn_ref to drop to 0. We are already in close, so
4800 	 * there cannot be any other thread from the top. qprocsoff
4801 	 * has completed, and service has completed or won't run in
4802 	 * future.
4803 	 */
4804 	if (connp->conn_latch != NULL) {
4805 		IPLATCH_REFRELE(connp->conn_latch);
4806 		connp->conn_latch = NULL;
4807 	}
4808 	if (connp->conn_policy != NULL) {
4809 		IPPH_REFRELE(connp->conn_policy);
4810 		connp->conn_policy = NULL;
4811 	}
4812 	if (connp->conn_ipsec_opt_mp != NULL) {
4813 		freemsg(connp->conn_ipsec_opt_mp);
4814 		connp->conn_ipsec_opt_mp = NULL;
4815 	}
4816 	if (connp->conn_cred != NULL) {
4817 		crfree(connp->conn_cred);
4818 		connp->conn_cred = NULL;
4819 	}
4820 
4821 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4822 
4823 	connp->conn_ref--;
4824 	ipcl_conn_destroy(connp);
4825 
4826 	q->q_ptr = WR(q)->q_ptr = NULL;
4827 	return (0);
4828 }
4829 
4830 /* Return the IP checksum for the IP header at "iph". */
4831 uint16_t
4832 ip_csum_hdr(ipha_t *ipha)
4833 {
4834 	uint16_t	*uph;
4835 	uint32_t	sum;
4836 	int		opt_len;
4837 
4838 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4839 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4840 	uph = (uint16_t *)ipha;
4841 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4842 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4843 	if (opt_len > 0) {
4844 		do {
4845 			sum += uph[10];
4846 			sum += uph[11];
4847 			uph += 2;
4848 		} while (--opt_len);
4849 	}
4850 	sum = (sum & 0xFFFF) + (sum >> 16);
4851 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4852 	if (sum == 0xffff)
4853 		sum = 0;
4854 	return ((uint16_t)sum);
4855 }
4856 
4857 void
4858 ip_ddi_destroy(void)
4859 {
4860 	tcp_ddi_destroy();
4861 	sctp_ddi_destroy();
4862 	ipsec_loader_destroy();
4863 	ipsec_policy_destroy();
4864 	ipsec_kstat_destroy();
4865 	nd_free(&ip_g_nd);
4866 	mutex_destroy(&igmp_timer_lock);
4867 	mutex_destroy(&mld_timer_lock);
4868 	mutex_destroy(&igmp_slowtimeout_lock);
4869 	mutex_destroy(&mld_slowtimeout_lock);
4870 	mutex_destroy(&ip_mi_lock);
4871 	mutex_destroy(&rts_clients.connf_lock);
4872 	ip_ire_fini();
4873 	ip6_asp_free();
4874 	conn_drain_fini();
4875 	ipcl_destroy();
4876 	inet_minor_destroy(ip_minor_arena);
4877 	icmp_kstat_fini();
4878 	ip_kstat_fini();
4879 	rw_destroy(&ipsec_capab_ills_lock);
4880 	rw_destroy(&ill_g_usesrc_lock);
4881 	ip_drop_unregister(&ip_dropper);
4882 }
4883 
4884 
4885 void
4886 ip_ddi_init(void)
4887 {
4888 	TCP6_MAJ = ddi_name_to_major(TCP6);
4889 	TCP_MAJ	= ddi_name_to_major(TCP);
4890 	SCTP_MAJ = ddi_name_to_major(SCTP);
4891 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
4892 
4893 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
4894 
4895 	/* IP's IPsec code calls the packet dropper */
4896 	ip_drop_register(&ip_dropper, "IP IPsec processing");
4897 
4898 	if (!ip_g_nd) {
4899 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
4900 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
4901 			nd_free(&ip_g_nd);
4902 		}
4903 	}
4904 
4905 	ipsec_loader_init();
4906 	ipsec_policy_init();
4907 	ipsec_kstat_init();
4908 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
4909 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4910 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4911 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4912 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4913 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4914 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4915 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
4916 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
4917 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4918 
4919 	/*
4920 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4921 	 * initial devices: ip, ip6, tcp, tcp6.
4922 	 */
4923 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
4924 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
4925 		cmn_err(CE_PANIC,
4926 		    "ip_ddi_init: ip_minor_arena creation failed\n");
4927 	}
4928 
4929 	ipcl_init();
4930 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
4931 	ip_ire_init();
4932 	ip6_asp_init();
4933 	ipif_init();
4934 	conn_drain_init();
4935 	tcp_ddi_init();
4936 	sctp_ddi_init();
4937 
4938 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4939 
4940 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
4941 		"net", KSTAT_TYPE_NAMED,
4942 		sizeof (ip_statistics) / sizeof (kstat_named_t),
4943 		KSTAT_FLAG_VIRTUAL)) != NULL) {
4944 		ip_kstat->ks_data = &ip_statistics;
4945 		kstat_install(ip_kstat);
4946 	}
4947 	ip_kstat_init();
4948 	ip6_kstat_init();
4949 	icmp_kstat_init();
4950 
4951 	ipsec_loader_start();
4952 }
4953 
4954 /*
4955  * Allocate and initialize a DLPI template of the specified length.  (May be
4956  * called as writer.)
4957  */
4958 mblk_t *
4959 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4960 {
4961 	mblk_t	*mp;
4962 
4963 	mp = allocb(len, BPRI_MED);
4964 	if (!mp)
4965 		return (NULL);
4966 
4967 	/*
4968 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4969 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4970 	 * that other DLPI are M_PROTO.
4971 	 */
4972 	if (prim == DL_INFO_REQ) {
4973 		mp->b_datap->db_type = M_PCPROTO;
4974 	} else {
4975 		mp->b_datap->db_type = M_PROTO;
4976 	}
4977 
4978 	mp->b_wptr = mp->b_rptr + len;
4979 	bzero(mp->b_rptr, len);
4980 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4981 	return (mp);
4982 }
4983 
4984 const char *
4985 dlpi_prim_str(int prim)
4986 {
4987 	switch (prim) {
4988 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
4989 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
4990 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
4991 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
4992 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
4993 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
4994 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
4995 	case DL_OK_ACK:		return ("DL_OK_ACK");
4996 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
4997 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
4998 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
4999 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5000 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5001 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5002 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5003 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5004 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5005 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5006 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5007 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5008 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5009 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5010 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5011 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5012 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5013 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5014 	default:		return ("<unknown primitive>");
5015 	}
5016 }
5017 
5018 const char *
5019 dlpi_err_str(int err)
5020 {
5021 	switch (err) {
5022 	case DL_ACCESS:		return ("DL_ACCESS");
5023 	case DL_BADADDR:	return ("DL_BADADDR");
5024 	case DL_BADCORR:	return ("DL_BADCORR");
5025 	case DL_BADDATA:	return ("DL_BADDATA");
5026 	case DL_BADPPA:		return ("DL_BADPPA");
5027 	case DL_BADPRIM:	return ("DL_BADPRIM");
5028 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5029 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5030 	case DL_BADSAP:		return ("DL_BADSAP");
5031 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5032 	case DL_BOUND:		return ("DL_BOUND");
5033 	case DL_INITFAILED:	return ("DL_INITFAILED");
5034 	case DL_NOADDR:		return ("DL_NOADDR");
5035 	case DL_NOTINIT:	return ("DL_NOTINIT");
5036 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5037 	case DL_SYSERR:		return ("DL_SYSERR");
5038 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5039 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5040 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5041 	case DL_TOOMANY:	return ("DL_TOOMANY");
5042 	case DL_NOTENAB:	return ("DL_NOTENAB");
5043 	case DL_BUSY:		return ("DL_BUSY");
5044 	case DL_NOAUTO:		return ("DL_NOAUTO");
5045 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5046 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5047 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5048 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5049 	case DL_PENDING:	return ("DL_PENDING");
5050 	default:		return ("<unknown error>");
5051 	}
5052 }
5053 
5054 /*
5055  * Debug formatting routine.  Returns a character string representation of the
5056  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5057  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5058  */
5059 char *
5060 ip_dot_addr(ipaddr_t addr, char *buf)
5061 {
5062 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5063 }
5064 
5065 /*
5066  * Debug formatting routine.  Returns a character string representation of the
5067  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5068  * as a pointer.  The "xxx" parts including left zero padding so the final
5069  * string will fit easily in tables.  It would be nice to take a padding
5070  * length argument instead.
5071  */
5072 static char *
5073 ip_dot_saddr(uchar_t *addr, char *buf)
5074 {
5075 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5076 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5077 	return (buf);
5078 }
5079 
5080 /*
5081  * Send an ICMP error after patching up the packet appropriately.  Returns
5082  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5083  */
5084 static int
5085 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5086     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5087 {
5088 	ipha_t *ipha;
5089 	mblk_t *first_mp;
5090 	boolean_t secure;
5091 	unsigned char db_type;
5092 
5093 	first_mp = mp;
5094 	if (mctl_present) {
5095 		mp = mp->b_cont;
5096 		secure = ipsec_in_is_secure(first_mp);
5097 		ASSERT(mp != NULL);
5098 	} else {
5099 		/*
5100 		 * If this is an ICMP error being reported - which goes
5101 		 * up as M_CTLs, we need to convert them to M_DATA till
5102 		 * we finish checking with global policy because
5103 		 * ipsec_check_global_policy() assumes M_DATA as clear
5104 		 * and M_CTL as secure.
5105 		 */
5106 		db_type = mp->b_datap->db_type;
5107 		mp->b_datap->db_type = M_DATA;
5108 		secure = B_FALSE;
5109 	}
5110 	/*
5111 	 * We are generating an icmp error for some inbound packet.
5112 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5113 	 * Before we generate an error, check with global policy
5114 	 * to see whether this is allowed to enter the system. As
5115 	 * there is no "conn", we are checking with global policy.
5116 	 */
5117 	ipha = (ipha_t *)mp->b_rptr;
5118 	if (secure || ipsec_inbound_v4_policy_present) {
5119 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5120 		    ipha, NULL, mctl_present);
5121 		if (first_mp == NULL)
5122 			return (0);
5123 	}
5124 
5125 	if (!mctl_present)
5126 		mp->b_datap->db_type = db_type;
5127 
5128 	if (flags & IP_FF_SEND_ICMP) {
5129 		if (flags & IP_FF_HDR_COMPLETE) {
5130 			if (ip_hdr_complete(ipha, zoneid)) {
5131 				freemsg(first_mp);
5132 				return (1);
5133 			}
5134 		}
5135 		if (flags & IP_FF_CKSUM) {
5136 			/*
5137 			 * Have to correct checksum since
5138 			 * the packet might have been
5139 			 * fragmented and the reassembly code in ip_rput
5140 			 * does not restore the IP checksum.
5141 			 */
5142 			ipha->ipha_hdr_checksum = 0;
5143 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5144 		}
5145 		switch (icmp_type) {
5146 		case ICMP_DEST_UNREACHABLE:
5147 			icmp_unreachable(WR(q), first_mp, icmp_code);
5148 			break;
5149 		default:
5150 			freemsg(first_mp);
5151 			break;
5152 		}
5153 	} else {
5154 		freemsg(first_mp);
5155 		return (0);
5156 	}
5157 
5158 	return (1);
5159 }
5160 
5161 #ifdef DEBUG
5162 /*
5163  * Copy the header into the IPSEC_IN message.
5164  */
5165 static void
5166 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5167 {
5168 	mblk_t *data_mp = ipsec_mp->b_cont;
5169 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5170 	ipha_t *ipha;
5171 
5172 	if (ii->ipsec_in_type != IPSEC_IN)
5173 		return;
5174 	ASSERT(data_mp != NULL);
5175 
5176 	ipha = (ipha_t *)data_mp->b_rptr;
5177 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5178 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5179 	    sizeof (ipha_t) : sizeof (ip6_t));
5180 }
5181 #else
5182 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5183 #endif	/* DEBUG */
5184 
5185 /*
5186  * Used to send an ICMP error message when a packet is received for
5187  * a protocol that is not supported. The mblk passed as argument
5188  * is consumed by this function.
5189  */
5190 void
5191 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5192 {
5193 	mblk_t *mp;
5194 	ipha_t *ipha;
5195 	ill_t *ill;
5196 	ipsec_in_t *ii;
5197 
5198 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5199 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5200 
5201 	mp = ipsec_mp->b_cont;
5202 	ipsec_mp->b_cont = NULL;
5203 	ipha = (ipha_t *)mp->b_rptr;
5204 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5205 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5206 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5207 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5208 		}
5209 	} else {
5210 		/* Get ill from index in ipsec_in_t. */
5211 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5212 		    B_TRUE, NULL, NULL, NULL, NULL);
5213 		if (ill != NULL) {
5214 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5215 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5216 			    0, B_FALSE, zoneid)) {
5217 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5218 			}
5219 
5220 			ill_refrele(ill);
5221 		} else { /* re-link for the freemsg() below. */
5222 			ipsec_mp->b_cont = mp;
5223 		}
5224 	}
5225 
5226 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5227 	freemsg(ipsec_mp);
5228 }
5229 
5230 /*
5231  * See if the inbound datagram has had IPsec processing applied to it.
5232  */
5233 boolean_t
5234 ipsec_in_is_secure(mblk_t *ipsec_mp)
5235 {
5236 	ipsec_in_t *ii;
5237 
5238 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5239 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5240 
5241 	if (ii->ipsec_in_loopback) {
5242 		return (ii->ipsec_in_secure);
5243 	} else {
5244 		return (ii->ipsec_in_ah_sa != NULL ||
5245 		    ii->ipsec_in_esp_sa != NULL ||
5246 		    ii->ipsec_in_decaps);
5247 	}
5248 }
5249 
5250 /*
5251  * Handle protocols with which IP is less intimate.  There
5252  * can be more than one stream bound to a particular
5253  * protocol.  When this is the case, normally each one gets a copy
5254  * of any incoming packets.
5255  *
5256  * IPSEC NOTE :
5257  *
5258  * Don't allow a secure packet going up a non-secure connection.
5259  * We don't allow this because
5260  *
5261  * 1) Reply might go out in clear which will be dropped at
5262  *    the sending side.
5263  * 2) If the reply goes out in clear it will give the
5264  *    adversary enough information for getting the key in
5265  *    most of the cases.
5266  *
5267  * Moreover getting a secure packet when we expect clear
5268  * implies that SA's were added without checking for
5269  * policy on both ends. This should not happen once ISAKMP
5270  * is used to negotiate SAs as SAs will be added only after
5271  * verifying the policy.
5272  *
5273  * NOTE : If the packet was tunneled and not multicast we only send
5274  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5275  * back to delivering packets to AF_INET6 raw sockets.
5276  *
5277  * IPQoS Notes:
5278  * Once we have determined the client, invoke IPPF processing.
5279  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5280  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5281  * ip_policy will be false.
5282  *
5283  * Zones notes:
5284  * Currently only applications in the global zone can create raw sockets for
5285  * protocols other than ICMP. So unlike the broadcast / multicast case of
5286  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5287  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5288  */
5289 static void
5290 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5291     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5292     zoneid_t zoneid)
5293 {
5294 	queue_t	*rq;
5295 	mblk_t	*mp1, *first_mp1;
5296 	uint_t	protocol = ipha->ipha_protocol;
5297 	ipaddr_t dst;
5298 	boolean_t one_only;
5299 	mblk_t *first_mp = mp;
5300 	boolean_t secure;
5301 	uint32_t ill_index;
5302 	conn_t	*connp, *first_connp, *next_connp;
5303 	connf_t	*connfp;
5304 
5305 	if (mctl_present) {
5306 		mp = first_mp->b_cont;
5307 		secure = ipsec_in_is_secure(first_mp);
5308 		ASSERT(mp != NULL);
5309 	} else {
5310 		secure = B_FALSE;
5311 	}
5312 	dst = ipha->ipha_dst;
5313 	/*
5314 	 * If the packet was tunneled and not multicast we only send to it
5315 	 * the first match.
5316 	 */
5317 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5318 	    !CLASSD(dst));
5319 
5320 	connfp = &ipcl_proto_fanout[protocol];
5321 	mutex_enter(&connfp->connf_lock);
5322 	connp = connfp->connf_head;
5323 	for (connp = connfp->connf_head; connp != NULL;
5324 		connp = connp->conn_next) {
5325 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5326 			break;
5327 	}
5328 
5329 	if (connp == NULL || connp->conn_upq == NULL) {
5330 		/*
5331 		 * No one bound to these addresses.  Is
5332 		 * there a client that wants all
5333 		 * unclaimed datagrams?
5334 		 */
5335 		mutex_exit(&connfp->connf_lock);
5336 		/*
5337 		 * Check for IPPROTO_ENCAP...
5338 		 */
5339 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5340 			/*
5341 			 * XXX If an IPsec mblk is here on a multicast
5342 			 * tunnel (using ip_mroute stuff), what should
5343 			 * I do?
5344 			 *
5345 			 * For now, just free the IPsec mblk before
5346 			 * passing it up to the multicast routing
5347 			 * stuff.
5348 			 *
5349 			 * BTW,  If I match a configured IP-in-IP
5350 			 * tunnel, ip_mroute_decap will never be
5351 			 * called.
5352 			 */
5353 			if (mp != first_mp)
5354 				freeb(first_mp);
5355 			ip_mroute_decap(q, mp);
5356 		} else {
5357 			/*
5358 			 * Otherwise send an ICMP protocol unreachable.
5359 			 */
5360 			if (ip_fanout_send_icmp(q, first_mp, flags,
5361 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5362 			    mctl_present, zoneid)) {
5363 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5364 			}
5365 		}
5366 		return;
5367 	}
5368 	CONN_INC_REF(connp);
5369 	first_connp = connp;
5370 
5371 	/*
5372 	 * Only send message to one tunnel driver by immediately
5373 	 * terminating the loop.
5374 	 */
5375 	connp = one_only ? NULL : connp->conn_next;
5376 
5377 	for (;;) {
5378 		while (connp != NULL) {
5379 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5380 			    flags, zoneid))
5381 				break;
5382 			connp = connp->conn_next;
5383 		}
5384 
5385 		/*
5386 		 * Copy the packet.
5387 		 */
5388 		if (connp == NULL || connp->conn_upq == NULL ||
5389 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5390 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5391 			/*
5392 			 * No more interested clients or memory
5393 			 * allocation failed
5394 			 */
5395 			connp = first_connp;
5396 			break;
5397 		}
5398 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5399 		CONN_INC_REF(connp);
5400 		mutex_exit(&connfp->connf_lock);
5401 		rq = connp->conn_rq;
5402 		if (!canputnext(rq)) {
5403 			if (flags & IP_FF_RAWIP) {
5404 				BUMP_MIB(&ip_mib, rawipInOverflows);
5405 			} else {
5406 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5407 			}
5408 
5409 			freemsg(first_mp1);
5410 		} else {
5411 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5412 				first_mp1 = ipsec_check_inbound_policy
5413 				    (first_mp1, connp, ipha, NULL,
5414 				    mctl_present);
5415 			}
5416 			if (first_mp1 != NULL) {
5417 				/*
5418 				 * ip_fanout_proto also gets called from
5419 				 * icmp_inbound_error_fanout, in which case
5420 				 * the msg type is M_CTL.  Don't add info
5421 				 * in this case for the time being. In future
5422 				 * when there is a need for knowing the
5423 				 * inbound iface index for ICMP error msgs,
5424 				 * then this can be changed.
5425 				 */
5426 				if ((connp->conn_recvif != 0) &&
5427 				    (mp->b_datap->db_type != M_CTL)) {
5428 					/*
5429 					 * the actual data will be
5430 					 * contained in b_cont upon
5431 					 * successful return of the
5432 					 * following call else
5433 					 * original mblk is returned
5434 					 */
5435 					ASSERT(recv_ill != NULL);
5436 					mp1 = ip_add_info(mp1, recv_ill,
5437 						IPF_RECVIF);
5438 				}
5439 				BUMP_MIB(&ip_mib, ipInDelivers);
5440 				if (mctl_present)
5441 					freeb(first_mp1);
5442 				putnext(rq, mp1);
5443 			}
5444 		}
5445 		mutex_enter(&connfp->connf_lock);
5446 		/* Follow the next pointer before releasing the conn. */
5447 		next_connp = connp->conn_next;
5448 		CONN_DEC_REF(connp);
5449 		connp = next_connp;
5450 	}
5451 
5452 	/* Last one.  Send it upstream. */
5453 	mutex_exit(&connfp->connf_lock);
5454 
5455 	/*
5456 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5457 	 * will be set to false.
5458 	 */
5459 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5460 		ill_index = ill->ill_phyint->phyint_ifindex;
5461 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5462 		if (mp == NULL) {
5463 			CONN_DEC_REF(connp);
5464 			if (mctl_present) {
5465 				freeb(first_mp);
5466 			}
5467 			return;
5468 		}
5469 	}
5470 
5471 	rq = connp->conn_rq;
5472 	if (!canputnext(rq)) {
5473 		if (flags & IP_FF_RAWIP) {
5474 			BUMP_MIB(&ip_mib, rawipInOverflows);
5475 		} else {
5476 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5477 		}
5478 
5479 		freemsg(first_mp);
5480 	} else {
5481 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5482 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5483 			    ipha, NULL, mctl_present);
5484 		}
5485 		if (first_mp != NULL) {
5486 			/*
5487 			 * ip_fanout_proto also gets called
5488 			 * from icmp_inbound_error_fanout, in
5489 			 * which case the msg type is M_CTL.
5490 			 * Don't add info in this case for time
5491 			 * being. In future when there is a
5492 			 * need for knowing the inbound iface
5493 			 * index for ICMP error msgs, then this
5494 			 * can be changed
5495 			 */
5496 			if ((connp->conn_recvif != 0) &&
5497 			    (mp->b_datap->db_type != M_CTL)) {
5498 				/*
5499 				 * the actual data will be contained in
5500 				 * b_cont upon successful return
5501 				 * of the following call else original
5502 				 * mblk is returned
5503 				 */
5504 				ASSERT(recv_ill != NULL);
5505 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5506 			}
5507 			BUMP_MIB(&ip_mib, ipInDelivers);
5508 			putnext(rq, mp);
5509 			if (mctl_present)
5510 				freeb(first_mp);
5511 		}
5512 	}
5513 	CONN_DEC_REF(connp);
5514 }
5515 
5516 /*
5517  * Fanout for TCP packets
5518  * The caller puts <fport, lport> in the ports parameter.
5519  *
5520  * IPQoS Notes
5521  * Before sending it to the client, invoke IPPF processing.
5522  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5523  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5524  * ip_policy is false.
5525  */
5526 static void
5527 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5528     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5529 {
5530 	mblk_t  *first_mp;
5531 	boolean_t secure;
5532 	uint32_t ill_index;
5533 	int	ip_hdr_len;
5534 	tcph_t	*tcph;
5535 	boolean_t syn_present = B_FALSE;
5536 	conn_t	*connp;
5537 
5538 	first_mp = mp;
5539 	if (mctl_present) {
5540 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5541 		mp = first_mp->b_cont;
5542 		secure = ipsec_in_is_secure(first_mp);
5543 		ASSERT(mp != NULL);
5544 	} else {
5545 		secure = B_FALSE;
5546 	}
5547 
5548 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5549 
5550 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5551 	    NULL) {
5552 		/*
5553 		 * No connected connection or listener. Send a
5554 		 * TH_RST via tcp_xmit_listeners_reset.
5555 		 */
5556 
5557 		/* Initiate IPPf processing, if needed. */
5558 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5559 			uint32_t ill_index;
5560 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5561 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5562 			if (first_mp == NULL)
5563 				return;
5564 		}
5565 		BUMP_MIB(&ip_mib, ipInDelivers);
5566 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5567 		return;
5568 	}
5569 
5570 	/*
5571 	 * Allocate the SYN for the TCP connection here itself
5572 	 */
5573 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5574 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5575 		if (IPCL_IS_TCP(connp)) {
5576 			squeue_t *sqp;
5577 
5578 			/*
5579 			 * For fused tcp loopback, assign the eager's
5580 			 * squeue to be that of the active connect's.
5581 			 * Note that we don't check for IP_FF_LOOPBACK
5582 			 * here since this routine gets called only
5583 			 * for loopback (unlike the IPv6 counterpart).
5584 			 */
5585 			if (do_tcp_fusion &&
5586 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5587 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy) {
5588 				ASSERT(Q_TO_CONN(q) != NULL);
5589 				sqp = Q_TO_CONN(q)->conn_sqp;
5590 			} else {
5591 				sqp = IP_SQUEUE_GET(lbolt);
5592 			}
5593 
5594 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5595 			mp->b_datap->db_cksumstart = (intptr_t)sqp;
5596 			syn_present = B_TRUE;
5597 		}
5598 	}
5599 
5600 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5601 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5602 		if ((flags & TH_RST) || (flags & TH_URG)) {
5603 			CONN_DEC_REF(connp);
5604 			freemsg(first_mp);
5605 			return;
5606 		}
5607 		if (flags & TH_ACK) {
5608 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5609 			CONN_DEC_REF(connp);
5610 			return;
5611 		}
5612 
5613 		CONN_DEC_REF(connp);
5614 		freemsg(first_mp);
5615 		return;
5616 	}
5617 
5618 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5619 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5620 		    NULL, mctl_present);
5621 		if (first_mp == NULL) {
5622 			CONN_DEC_REF(connp);
5623 			return;
5624 		}
5625 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5626 			ASSERT(syn_present);
5627 			if (mctl_present) {
5628 				ASSERT(first_mp != mp);
5629 				first_mp->b_datap->db_struioflag |=
5630 				    STRUIO_POLICY;
5631 			} else {
5632 				ASSERT(first_mp == mp);
5633 				mp->b_datap->db_struioflag &=
5634 				    ~STRUIO_EAGER;
5635 				mp->b_datap->db_struioflag |=
5636 				    STRUIO_POLICY;
5637 			}
5638 		} else {
5639 			/*
5640 			 * Discard first_mp early since we're dealing with a
5641 			 * fully-connected conn_t and tcp doesn't do policy in
5642 			 * this case.
5643 			 */
5644 			if (mctl_present) {
5645 				freeb(first_mp);
5646 				mctl_present = B_FALSE;
5647 			}
5648 			first_mp = mp;
5649 		}
5650 	}
5651 
5652 	/*
5653 	 * Initiate policy processing here if needed. If we get here from
5654 	 * icmp_inbound_error_fanout, ip_policy is false.
5655 	 */
5656 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5657 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5659 		if (mp == NULL) {
5660 			CONN_DEC_REF(connp);
5661 			if (mctl_present)
5662 				freeb(first_mp);
5663 			return;
5664 		} else if (mctl_present) {
5665 			ASSERT(first_mp != mp);
5666 			first_mp->b_cont = mp;
5667 		} else {
5668 			first_mp = mp;
5669 		}
5670 	}
5671 
5672 
5673 
5674 	/* Handle IPv6 socket options. */
5675 	if (!syn_present &&
5676 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5677 		/* Add header */
5678 		ASSERT(recv_ill != NULL);
5679 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5680 		if (mp == NULL) {
5681 			CONN_DEC_REF(connp);
5682 			if (mctl_present)
5683 				freeb(first_mp);
5684 			return;
5685 		} else if (mctl_present) {
5686 			/*
5687 			 * ip_add_info might return a new mp.
5688 			 */
5689 			ASSERT(first_mp != mp);
5690 			first_mp->b_cont = mp;
5691 		} else {
5692 			first_mp = mp;
5693 		}
5694 	}
5695 
5696 	BUMP_MIB(&ip_mib, ipInDelivers);
5697 	if (IPCL_IS_TCP(connp)) {
5698 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5699 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5700 	} else {
5701 		putnext(connp->conn_rq, first_mp);
5702 		CONN_DEC_REF(connp);
5703 	}
5704 }
5705 
5706 /*
5707  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5708  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5709  * Caller is responsible for dropping references to the conn, and freeing
5710  * first_mp.
5711  *
5712  * IPQoS Notes
5713  * Before sending it to the client, invoke IPPF processing. Policy processing
5714  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5715  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5716  * ip_wput_local, ip_policy is false.
5717  */
5718 static void
5719 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5720     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5721     boolean_t ip_policy)
5722 {
5723 	queue_t		*rq = connp->conn_rq;
5724 	boolean_t	mctl_present = (first_mp != NULL);
5725 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5726 	uint32_t	ill_index;
5727 
5728 	if (mctl_present)
5729 		first_mp->b_cont = mp;
5730 	else
5731 		first_mp = mp;
5732 
5733 	if (!canputnext(rq)) {
5734 		BUMP_MIB(&ip_mib, udpInOverflows);
5735 		freemsg(first_mp);
5736 		return;
5737 	}
5738 
5739 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5740 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5741 		    NULL, mctl_present);
5742 		if (first_mp == NULL)
5743 			return;	/* Freed by ipsec_check_inbound_policy(). */
5744 	}
5745 	if (mctl_present)
5746 		freeb(first_mp);
5747 
5748 	if (connp->conn_recvif)
5749 		in_flags = IPF_RECVIF;
5750 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5751 		in_flags |= IPF_RECVSLLA;
5752 
5753 	/* Handle IPv6 options. */
5754 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5755 		in_flags |= IPF_RECVIF;
5756 
5757 	/*
5758 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5759 	 * freed if the packet is dropped. The caller will do so.
5760 	 */
5761 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5762 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5763 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5764 		if (mp == NULL) {
5765 			return;
5766 		}
5767 	}
5768 	if ((in_flags != 0) &&
5769 	    (mp->b_datap->db_type != M_CTL)) {
5770 		/*
5771 		 * The actual data will be contained in b_cont
5772 		 * upon successful return of the following call
5773 		 * else original mblk is returned
5774 		 */
5775 		ASSERT(recv_ill != NULL);
5776 		mp = ip_add_info(mp, recv_ill, in_flags);
5777 	}
5778 	BUMP_MIB(&ip_mib, ipInDelivers);
5779 	putnext(rq, mp);
5780 }
5781 
5782 /*
5783  * Fanout for UDP packets.
5784  * The caller puts <fport, lport> in the ports parameter.
5785  *
5786  * If SO_REUSEADDR is set all multicast and broadcast packets
5787  * will be delivered to all streams bound to the same port.
5788  *
5789  * Zones notes:
5790  * Multicast and broadcast packets will be distributed to streams in all zones.
5791  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5792  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5793  * packets. To maintain this behavior with multiple zones, the conns are grouped
5794  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5795  * each zone. If unset, all the following conns in the same zone are skipped.
5796  */
5797 static void
5798 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5799     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5800     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5801 {
5802 	uint32_t	dstport, srcport;
5803 	ipaddr_t	dst;
5804 	mblk_t		*first_mp;
5805 	boolean_t	secure;
5806 	in6_addr_t	v6src;
5807 	conn_t		*connp;
5808 	connf_t		*connfp;
5809 	conn_t		*first_connp;
5810 	conn_t		*next_connp;
5811 	mblk_t		*mp1, *first_mp1;
5812 	ipaddr_t	src;
5813 	zoneid_t	last_zoneid;
5814 	boolean_t	reuseaddr;
5815 
5816 	first_mp = mp;
5817 	if (mctl_present) {
5818 		mp = first_mp->b_cont;
5819 		first_mp->b_cont = NULL;
5820 		secure = ipsec_in_is_secure(first_mp);
5821 		ASSERT(mp != NULL);
5822 	} else {
5823 		first_mp = NULL;
5824 		secure = B_FALSE;
5825 	}
5826 
5827 	/* Extract ports in net byte order */
5828 	dstport = htons(ntohl(ports) & 0xFFFF);
5829 	srcport = htons(ntohl(ports) >> 16);
5830 	dst = ipha->ipha_dst;
5831 	src = ipha->ipha_src;
5832 
5833 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5834 	mutex_enter(&connfp->connf_lock);
5835 	connp = connfp->connf_head;
5836 	if (!broadcast && !CLASSD(dst)) {
5837 		/*
5838 		 * Not broadcast or multicast. Send to the one (first)
5839 		 * client we find. No need to check conn_wantpacket()
5840 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5841 		 * IPv4 unicast packets.
5842 		 */
5843 		while ((connp != NULL) &&
5844 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5845 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5846 			connp = connp->conn_next;
5847 		}
5848 
5849 		if (connp == NULL || connp->conn_upq == NULL)
5850 			goto notfound;
5851 		CONN_INC_REF(connp);
5852 		mutex_exit(&connfp->connf_lock);
5853 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5854 		    recv_ill, ip_policy);
5855 		IP_STAT(ip_udp_fannorm);
5856 		CONN_DEC_REF(connp);
5857 		return;
5858 	}
5859 
5860 	/*
5861 	 * Broadcast and multicast case
5862 	 *
5863 	 * Need to check conn_wantpacket().
5864 	 * If SO_REUSEADDR has been set on the first we send the
5865 	 * packet to all clients that have joined the group and
5866 	 * match the port.
5867 	 */
5868 
5869 	while (connp != NULL) {
5870 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
5871 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5872 			break;
5873 		connp = connp->conn_next;
5874 	}
5875 
5876 	if (connp == NULL || connp->conn_upq == NULL)
5877 		goto notfound;
5878 
5879 	first_connp = connp;
5880 	/*
5881 	 * When SO_REUSEADDR is not set, send the packet only to the first
5882 	 * matching connection in its zone by keeping track of the zoneid.
5883 	 */
5884 	reuseaddr = first_connp->conn_reuseaddr;
5885 	last_zoneid = first_connp->conn_zoneid;
5886 
5887 	CONN_INC_REF(connp);
5888 	connp = connp->conn_next;
5889 	for (;;) {
5890 		while (connp != NULL) {
5891 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
5892 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
5893 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5894 				break;
5895 			connp = connp->conn_next;
5896 		}
5897 		/*
5898 		 * Just copy the data part alone. The mctl part is
5899 		 * needed just for verifying policy and it is never
5900 		 * sent up.
5901 		 */
5902 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
5903 		    ((mp1 = copymsg(mp)) == NULL))) {
5904 			/*
5905 			 * No more interested clients or memory
5906 			 * allocation failed
5907 			 */
5908 			connp = first_connp;
5909 			break;
5910 		}
5911 		if (connp->conn_zoneid != last_zoneid) {
5912 			/*
5913 			 * Update the zoneid so that the packet isn't sent to
5914 			 * any more conns in the same zone unless SO_REUSEADDR
5915 			 * is set.
5916 			 */
5917 			reuseaddr = connp->conn_reuseaddr;
5918 			last_zoneid = connp->conn_zoneid;
5919 		}
5920 		if (first_mp != NULL) {
5921 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
5922 			    ipsec_info_type == IPSEC_IN);
5923 			first_mp1 = ipsec_in_tag(first_mp, NULL);
5924 			if (first_mp1 == NULL) {
5925 				freemsg(mp1);
5926 				connp = first_connp;
5927 				break;
5928 			}
5929 		} else {
5930 			first_mp1 = NULL;
5931 		}
5932 		CONN_INC_REF(connp);
5933 		mutex_exit(&connfp->connf_lock);
5934 		/*
5935 		 * IPQoS notes: We don't send the packet for policy
5936 		 * processing here, will do it for the last one (below).
5937 		 * i.e. we do it per-packet now, but if we do policy
5938 		 * processing per-conn, then we would need to do it
5939 		 * here too.
5940 		 */
5941 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
5942 		    ipha, flags, recv_ill, B_FALSE);
5943 		mutex_enter(&connfp->connf_lock);
5944 		/* Follow the next pointer before releasing the conn. */
5945 		next_connp = connp->conn_next;
5946 		IP_STAT(ip_udp_fanmb);
5947 		CONN_DEC_REF(connp);
5948 		connp = next_connp;
5949 	}
5950 
5951 	/* Last one.  Send it upstream. */
5952 	mutex_exit(&connfp->connf_lock);
5953 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
5954 	    ip_policy);
5955 	IP_STAT(ip_udp_fanmb);
5956 	CONN_DEC_REF(connp);
5957 	return;
5958 
5959 notfound:
5960 
5961 	mutex_exit(&connfp->connf_lock);
5962 	IP_STAT(ip_udp_fanothers);
5963 	/*
5964 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
5965 	 * have already been matched above, since they live in the IPv4
5966 	 * fanout tables. This implies we only need to
5967 	 * check for IPv6 in6addr_any endpoints here.
5968 	 * Thus we compare using ipv6_all_zeros instead of the destination
5969 	 * address, except for the multicast group membership lookup which
5970 	 * uses the IPv4 destination.
5971 	 */
5972 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
5973 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5974 	mutex_enter(&connfp->connf_lock);
5975 	connp = connfp->connf_head;
5976 	if (!broadcast && !CLASSD(dst)) {
5977 		while (connp != NULL) {
5978 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
5979 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
5980 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
5981 			    !connp->conn_ipv6_v6only)
5982 				break;
5983 			connp = connp->conn_next;
5984 		}
5985 
5986 		if (connp == NULL || connp->conn_upq == NULL) {
5987 			/*
5988 			 * No one bound to this port.  Is
5989 			 * there a client that wants all
5990 			 * unclaimed datagrams?
5991 			 */
5992 			mutex_exit(&connfp->connf_lock);
5993 
5994 			if (mctl_present)
5995 				first_mp->b_cont = mp;
5996 			else
5997 				first_mp = mp;
5998 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
5999 				ip_fanout_proto(q, first_mp, ill, ipha,
6000 				    flags | IP_FF_RAWIP, mctl_present,
6001 				    ip_policy, recv_ill, zoneid);
6002 			} else {
6003 				if (ip_fanout_send_icmp(q, first_mp, flags,
6004 				    ICMP_DEST_UNREACHABLE,
6005 				    ICMP_PORT_UNREACHABLE,
6006 				    mctl_present, zoneid)) {
6007 					BUMP_MIB(&ip_mib, udpNoPorts);
6008 				}
6009 			}
6010 			return;
6011 		}
6012 		CONN_INC_REF(connp);
6013 		mutex_exit(&connfp->connf_lock);
6014 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6015 		    recv_ill, ip_policy);
6016 		CONN_DEC_REF(connp);
6017 		return;
6018 	}
6019 	/*
6020 	 * IPv4 multicast packet being delivered to an AF_INET6
6021 	 * in6addr_any endpoint.
6022 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6023 	 * and not conn_wantpacket_v6() since any multicast membership is
6024 	 * for an IPv4-mapped multicast address.
6025 	 * The packet is sent to all clients in all zones that have joined the
6026 	 * group and match the port.
6027 	 */
6028 	while (connp != NULL) {
6029 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6030 		    srcport, v6src) &&
6031 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6032 			break;
6033 		connp = connp->conn_next;
6034 	}
6035 
6036 	if (connp == NULL || connp->conn_upq == NULL) {
6037 		/*
6038 		 * No one bound to this port.  Is
6039 		 * there a client that wants all
6040 		 * unclaimed datagrams?
6041 		 */
6042 		mutex_exit(&connfp->connf_lock);
6043 
6044 		if (mctl_present)
6045 			first_mp->b_cont = mp;
6046 		else
6047 			first_mp = mp;
6048 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6049 			ip_fanout_proto(q, first_mp, ill, ipha,
6050 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6051 			    recv_ill, zoneid);
6052 		} else {
6053 			/*
6054 			 * We used to attempt to send an icmp error here, but
6055 			 * since this is known to be a multicast packet
6056 			 * and we don't send icmp errors in response to
6057 			 * multicast, just drop the packet and give up sooner.
6058 			 */
6059 			BUMP_MIB(&ip_mib, udpNoPorts);
6060 			freemsg(first_mp);
6061 		}
6062 		return;
6063 	}
6064 
6065 	first_connp = connp;
6066 
6067 	CONN_INC_REF(connp);
6068 	connp = connp->conn_next;
6069 	for (;;) {
6070 		while (connp != NULL) {
6071 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6072 			    ipv6_all_zeros, srcport, v6src) &&
6073 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6074 				break;
6075 			connp = connp->conn_next;
6076 		}
6077 		/*
6078 		 * Just copy the data part alone. The mctl part is
6079 		 * needed just for verifying policy and it is never
6080 		 * sent up.
6081 		 */
6082 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6083 		    ((mp1 = copymsg(mp)) == NULL))) {
6084 			/*
6085 			 * No more intested clients or memory
6086 			 * allocation failed
6087 			 */
6088 			connp = first_connp;
6089 			break;
6090 		}
6091 		if (first_mp != NULL) {
6092 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6093 			    ipsec_info_type == IPSEC_IN);
6094 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6095 			if (first_mp1 == NULL) {
6096 				freemsg(mp1);
6097 				connp = first_connp;
6098 				break;
6099 			}
6100 		} else {
6101 			first_mp1 = NULL;
6102 		}
6103 		CONN_INC_REF(connp);
6104 		mutex_exit(&connfp->connf_lock);
6105 		/*
6106 		 * IPQoS notes: We don't send the packet for policy
6107 		 * processing here, will do it for the last one (below).
6108 		 * i.e. we do it per-packet now, but if we do policy
6109 		 * processing per-conn, then we would need to do it
6110 		 * here too.
6111 		 */
6112 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6113 		    ipha, flags, recv_ill, B_FALSE);
6114 		mutex_enter(&connfp->connf_lock);
6115 		/* Follow the next pointer before releasing the conn. */
6116 		next_connp = connp->conn_next;
6117 		CONN_DEC_REF(connp);
6118 		connp = next_connp;
6119 	}
6120 
6121 	/* Last one.  Send it upstream. */
6122 	mutex_exit(&connfp->connf_lock);
6123 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6124 	    ip_policy);
6125 	CONN_DEC_REF(connp);
6126 }
6127 
6128 /*
6129  * Complete the ip_wput header so that it
6130  * is possible to generate ICMP
6131  * errors.
6132  */
6133 static int
6134 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6135 {
6136 	ire_t *ire;
6137 
6138 	if (ipha->ipha_src == INADDR_ANY) {
6139 		ire = ire_lookup_local(zoneid);
6140 		if (ire == NULL) {
6141 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6142 			return (1);
6143 		}
6144 		ipha->ipha_src = ire->ire_addr;
6145 		ire_refrele(ire);
6146 	}
6147 	ipha->ipha_ttl = ip_def_ttl;
6148 	ipha->ipha_hdr_checksum = 0;
6149 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6150 	return (0);
6151 }
6152 
6153 /*
6154  * Nobody should be sending
6155  * packets up this stream
6156  */
6157 static void
6158 ip_lrput(queue_t *q, mblk_t *mp)
6159 {
6160 	mblk_t *mp1;
6161 
6162 	switch (mp->b_datap->db_type) {
6163 	case M_FLUSH:
6164 		/* Turn around */
6165 		if (*mp->b_rptr & FLUSHW) {
6166 			*mp->b_rptr &= ~FLUSHR;
6167 			qreply(q, mp);
6168 			return;
6169 		}
6170 		break;
6171 	}
6172 	/* Could receive messages that passed through ar_rput */
6173 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6174 		mp1->b_prev = mp1->b_next = NULL;
6175 	freemsg(mp);
6176 }
6177 
6178 /* Nobody should be sending packets down this stream */
6179 /* ARGSUSED */
6180 void
6181 ip_lwput(queue_t *q, mblk_t *mp)
6182 {
6183 	freemsg(mp);
6184 }
6185 
6186 /*
6187  * Move the first hop in any source route to ipha_dst and remove that part of
6188  * the source route.  Called by other protocols.  Errors in option formatting
6189  * are ignored - will be handled by ip_wput_options Return the final
6190  * destination (either ipha_dst or the last entry in a source route.)
6191  */
6192 ipaddr_t
6193 ip_massage_options(ipha_t *ipha)
6194 {
6195 	ipoptp_t	opts;
6196 	uchar_t		*opt;
6197 	uint8_t		optval;
6198 	uint8_t		optlen;
6199 	ipaddr_t	dst;
6200 	int		i;
6201 	ire_t		*ire;
6202 
6203 	ip2dbg(("ip_massage_options\n"));
6204 	dst = ipha->ipha_dst;
6205 	for (optval = ipoptp_first(&opts, ipha);
6206 	    optval != IPOPT_EOL;
6207 	    optval = ipoptp_next(&opts)) {
6208 		opt = opts.ipoptp_cur;
6209 		switch (optval) {
6210 			uint8_t off;
6211 		case IPOPT_SSRR:
6212 		case IPOPT_LSRR:
6213 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6214 				ip1dbg(("ip_massage_options: bad src route\n"));
6215 				break;
6216 			}
6217 			optlen = opts.ipoptp_len;
6218 			off = opt[IPOPT_OFFSET];
6219 			off--;
6220 		redo_srr:
6221 			if (optlen < IP_ADDR_LEN ||
6222 			    off > optlen - IP_ADDR_LEN) {
6223 				/* End of source route */
6224 				ip1dbg(("ip_massage_options: end of SR\n"));
6225 				break;
6226 			}
6227 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6228 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6229 			    ntohl(dst)));
6230 			/*
6231 			 * Check if our address is present more than
6232 			 * once as consecutive hops in source route.
6233 			 * XXX verify per-interface ip_forwarding
6234 			 * for source route?
6235 			 */
6236 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6237 			    ALL_ZONES, MATCH_IRE_TYPE);
6238 			if (ire != NULL) {
6239 				ire_refrele(ire);
6240 				off += IP_ADDR_LEN;
6241 				goto redo_srr;
6242 			}
6243 			if (dst == htonl(INADDR_LOOPBACK)) {
6244 				ip1dbg(("ip_massage_options: loopback addr in "
6245 				    "source route!\n"));
6246 				break;
6247 			}
6248 			/*
6249 			 * Update ipha_dst to be the first hop and remove the
6250 			 * first hop from the source route (by overwriting
6251 			 * part of the option with NOP options).
6252 			 */
6253 			ipha->ipha_dst = dst;
6254 			/* Put the last entry in dst */
6255 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6256 			    3;
6257 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6258 
6259 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6260 			    ntohl(dst)));
6261 			/* Move down and overwrite */
6262 			opt[IP_ADDR_LEN] = opt[0];
6263 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6264 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6265 			for (i = 0; i < IP_ADDR_LEN; i++)
6266 				opt[i] = IPOPT_NOP;
6267 			break;
6268 		}
6269 	}
6270 	return (dst);
6271 }
6272 
6273 /*
6274  * This function's job is to forward data to the reverse tunnel (FA->HA)
6275  * after doing a few checks. It is assumed that the incoming interface
6276  * of the packet is always different than the outgoing interface and the
6277  * ire_type of the found ire has to be a non-resolver type.
6278  *
6279  * IPQoS notes
6280  * IP policy is invoked twice for a forwarded packet, once on the read side
6281  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6282  * enabled.
6283  */
6284 static void
6285 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6286 {
6287 	ipha_t		*ipha;
6288 	queue_t		*q;
6289 	uint32_t 	pkt_len;
6290 #define	rptr    ((uchar_t *)ipha)
6291 	uint32_t 	sum;
6292 	uint32_t 	max_frag;
6293 	mblk_t		*first_mp;
6294 	uint32_t	ill_index;
6295 
6296 	ASSERT(ire != NULL);
6297 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6298 	ASSERT(ire->ire_stq != NULL);
6299 
6300 	/* Initiate read side IPPF processing */
6301 	if (IPP_ENABLED(IPP_FWD_IN)) {
6302 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6303 		ip_process(IPP_FWD_IN, &mp, ill_index);
6304 		if (mp == NULL) {
6305 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6306 			    "dropped during IPPF processing\n"));
6307 			return;
6308 		}
6309 	}
6310 
6311 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6312 		ILLF_ROUTER) == 0) ||
6313 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6314 		BUMP_MIB(&ip_mib, ipForwProhibits);
6315 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6316 		    "forwarding is not turned on\n"));
6317 		goto drop_pkt;
6318 	}
6319 
6320 	/*
6321 	 * Don't forward if the interface is down
6322 	 */
6323 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6324 		BUMP_MIB(&ip_mib, ipInDiscards);
6325 		goto drop_pkt;
6326 	}
6327 
6328 	ipha = (ipha_t *)mp->b_rptr;
6329 	pkt_len = ntohs(ipha->ipha_length);
6330 	/* Adjust the checksum to reflect the ttl decrement. */
6331 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6332 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6333 	if (ipha->ipha_ttl-- <= 1) {
6334 		if (ip_csum_hdr(ipha)) {
6335 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6336 			goto drop_pkt;
6337 		}
6338 		q = ire->ire_stq;
6339 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6340 		    BPRI_HI)) == NULL) {
6341 			goto drop_pkt;
6342 		}
6343 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6344 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6345 
6346 		return;
6347 	}
6348 
6349 	/* Get the ill_index of the ILL */
6350 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6351 
6352 	/*
6353 	 * ip_mrtun_forward is only used by foreign agent to reverse
6354 	 * tunnel the incoming packet. So it does not do any option
6355 	 * processing for source routing.
6356 	 */
6357 	max_frag = ire->ire_max_frag;
6358 	if (pkt_len > max_frag) {
6359 		/*
6360 		 * It needs fragging on its way out.  We haven't
6361 		 * verified the header checksum yet.  Since we
6362 		 * are going to put a surely good checksum in the
6363 		 * outgoing header, we have to make sure that it
6364 		 * was good coming in.
6365 		 */
6366 		if (ip_csum_hdr(ipha)) {
6367 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6368 			goto drop_pkt;
6369 		}
6370 
6371 		/* Initiate write side IPPF processing */
6372 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6373 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6374 			if (mp == NULL) {
6375 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6376 				    "dropped/deferred during ip policy "\
6377 				    "processing\n"));
6378 				return;
6379 			}
6380 		}
6381 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6382 		    BPRI_HI)) == NULL) {
6383 			goto drop_pkt;
6384 		}
6385 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6386 		mp = first_mp;
6387 
6388 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6389 		return;
6390 	}
6391 
6392 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6393 
6394 	ASSERT(ire->ire_ipif != NULL);
6395 
6396 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6397 	if (mp == NULL) {
6398 		BUMP_MIB(&ip_mib, ipInDiscards);
6399 		return;
6400 	}
6401 
6402 	/* Now send the packet to the tunnel interface */
6403 	q = ire->ire_stq;
6404 	UPDATE_IB_PKT_COUNT(ire);
6405 	ire->ire_last_used_time = lbolt;
6406 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6407 	putnext(q, mp);
6408 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6409 	return;
6410 
6411 drop_pkt:;
6412 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6413 	freemsg(mp);
6414 #undef	rptr
6415 }
6416 
6417 /*
6418  * Fills the ipsec_out_t data structure with appropriate fields and
6419  * prepends it to mp which contains the IP hdr + data that was meant
6420  * to be forwarded. Please note that ipsec_out_info data structure
6421  * is used here to communicate the outgoing ill path at ip_wput()
6422  * for the ICMP error packet. This has nothing to do with ipsec IP
6423  * security. ipsec_out_t is really used to pass the info to the module
6424  * IP where this information cannot be extracted from conn.
6425  * This functions is called by ip_mrtun_forward().
6426  */
6427 void
6428 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6429 {
6430 	ipsec_out_t	*io;
6431 
6432 	ASSERT(xmit_ill != NULL);
6433 	first_mp->b_datap->db_type = M_CTL;
6434 	first_mp->b_wptr += sizeof (ipsec_info_t);
6435 	/*
6436 	 * This is to pass info to ip_wput in absence of conn.
6437 	 * ipsec_out_secure will be B_FALSE because of this.
6438 	 * Thus ipsec_out_secure being B_FALSE indicates that
6439 	 * this is not IPSEC security related information.
6440 	 */
6441 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6442 	io = (ipsec_out_t *)first_mp->b_rptr;
6443 	io->ipsec_out_type = IPSEC_OUT;
6444 	io->ipsec_out_len = sizeof (ipsec_out_t);
6445 	first_mp->b_cont = mp;
6446 	io->ipsec_out_ill_index =
6447 	    xmit_ill->ill_phyint->phyint_ifindex;
6448 	io->ipsec_out_xmit_if = B_TRUE;
6449 }
6450 
6451 /*
6452  * Return the network mask
6453  * associated with the specified address.
6454  */
6455 ipaddr_t
6456 ip_net_mask(ipaddr_t addr)
6457 {
6458 	uchar_t	*up = (uchar_t *)&addr;
6459 	ipaddr_t mask = 0;
6460 	uchar_t	*maskp = (uchar_t *)&mask;
6461 
6462 #if defined(__i386) || defined(__amd64)
6463 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6464 #endif
6465 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6466 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6467 #endif
6468 	if (CLASSD(addr)) {
6469 		maskp[0] = 0xF0;
6470 		return (mask);
6471 	}
6472 	if (addr == 0)
6473 		return (0);
6474 	maskp[0] = 0xFF;
6475 	if ((up[0] & 0x80) == 0)
6476 		return (mask);
6477 
6478 	maskp[1] = 0xFF;
6479 	if ((up[0] & 0xC0) == 0x80)
6480 		return (mask);
6481 
6482 	maskp[2] = 0xFF;
6483 	if ((up[0] & 0xE0) == 0xC0)
6484 		return (mask);
6485 
6486 	/* Must be experimental or multicast, indicate as much */
6487 	return ((ipaddr_t)0);
6488 }
6489 
6490 /*
6491  * Select an ill for the packet by considering load spreading across
6492  * a different ill in the group if dst_ill is part of some group.
6493  */
6494 static ill_t *
6495 ip_newroute_get_dst_ill(ill_t *dst_ill)
6496 {
6497 	ill_t *ill;
6498 
6499 	/*
6500 	 * We schedule irrespective of whether the source address is
6501 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6502 	 */
6503 	ill = illgrp_scheduler(dst_ill);
6504 	if (ill == NULL)
6505 		return (NULL);
6506 
6507 	/*
6508 	 * For groups with names ip_sioctl_groupname ensures that all
6509 	 * ills are of same type. For groups without names, ifgrp_insert
6510 	 * ensures this.
6511 	 */
6512 	ASSERT(dst_ill->ill_type == ill->ill_type);
6513 
6514 	return (ill);
6515 }
6516 
6517 /*
6518  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6519  */
6520 ill_t *
6521 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6522 {
6523 	ill_t *ret_ill;
6524 
6525 	ASSERT(ifindex != 0);
6526 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6527 	if (ret_ill == NULL ||
6528 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6529 		if (isv6) {
6530 			if (ill != NULL) {
6531 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6532 			} else {
6533 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6534 			}
6535 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6536 			    "bad ifindex %d.\n", ifindex));
6537 		} else {
6538 			BUMP_MIB(&ip_mib, ipOutDiscards);
6539 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6540 			    "bad ifindex %d.\n", ifindex));
6541 		}
6542 		if (ret_ill != NULL)
6543 			ill_refrele(ret_ill);
6544 		freemsg(first_mp);
6545 		return (NULL);
6546 	}
6547 
6548 	return (ret_ill);
6549 }
6550 
6551 /*
6552  * IPv4 -
6553  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6554  * out a packet to a destination address for which we do not have specific
6555  * (or sufficient) routing information.
6556  *
6557  * NOTE : These are the scopes of some of the variables that point at IRE,
6558  *	  which needs to be followed while making any future modifications
6559  *	  to avoid memory leaks.
6560  *
6561  *	- ire and sire are the entries looked up initially by
6562  *	  ire_ftable_lookup.
6563  *	- ipif_ire is used to hold the interface ire associated with
6564  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6565  *	  it before branching out to error paths.
6566  *	- save_ire is initialized before ire_create, so that ire returned
6567  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6568  *	  before breaking out of the switch.
6569  *
6570  *	Thus on failures, we have to REFRELE only ire and sire, if they
6571  *	are not NULL.
6572  */
6573 void
6574 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6575 {
6576 	areq_t	*areq;
6577 	ipaddr_t gw = 0;
6578 	ire_t	*ire = NULL;
6579 	mblk_t	*res_mp;
6580 	ipaddr_t *addrp;
6581 	ipif_t  *src_ipif = NULL;
6582 	ill_t	*dst_ill = NULL;
6583 	ipha_t  *ipha;
6584 	ire_t	*sire = NULL;
6585 	mblk_t	*first_mp;
6586 	ire_t	*save_ire;
6587 	mblk_t	*dlureq_mp;
6588 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6589 	ushort_t ire_marks = 0;
6590 	boolean_t mctl_present;
6591 	ipsec_out_t *io;
6592 	mblk_t	*saved_mp;
6593 	ire_t	*first_sire = NULL;
6594 	mblk_t	*copy_mp = NULL;
6595 	mblk_t	*xmit_mp = NULL;
6596 	ipaddr_t save_dst;
6597 	uint32_t multirt_flags =
6598 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6599 	boolean_t multirt_is_resolvable;
6600 	boolean_t multirt_resolve_next;
6601 	boolean_t do_attach_ill = B_FALSE;
6602 	zoneid_t zoneid;
6603 
6604 	if (ip_debug > 2) {
6605 		/* ip1dbg */
6606 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6607 	}
6608 
6609 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6610 	if (mctl_present) {
6611 		io = (ipsec_out_t *)first_mp->b_rptr;
6612 		zoneid = io->ipsec_out_zoneid;
6613 		ASSERT(zoneid != ALL_ZONES);
6614 	} else if (connp != NULL) {
6615 		zoneid = connp->conn_zoneid;
6616 	} else {
6617 		zoneid = GLOBAL_ZONEID;
6618 	}
6619 
6620 	ipha = (ipha_t *)mp->b_rptr;
6621 
6622 	/* All multicast lookups come through ip_newroute_ipif() */
6623 	if (CLASSD(dst)) {
6624 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6625 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6626 		freemsg(first_mp);
6627 		return;
6628 	}
6629 
6630 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6631 		goto icmp_err_ret;
6632 	}
6633 
6634 	if (mctl_present && io->ipsec_out_attach_if) {
6635 		/* ip_grab_attach_ill returns a held ill */
6636 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6637 		    io->ipsec_out_ill_index, B_FALSE);
6638 
6639 		/* Failure case frees things for us. */
6640 		if (attach_ill == NULL)
6641 			return;
6642 
6643 		/*
6644 		 * Check if we need an ire that will not be
6645 		 * looked up by anybody else i.e. HIDDEN.
6646 		 */
6647 		if (ill_is_probeonly(attach_ill))
6648 			ire_marks = IRE_MARK_HIDDEN;
6649 	}
6650 	/*
6651 	 * If this IRE is created for forwarding or it is not for
6652 	 * traffic for congestion controlled protocols, mark it as temporary.
6653 	 */
6654 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6655 		ire_marks |= IRE_MARK_TEMPORARY;
6656 
6657 	/*
6658 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6659 	 * chain until it gets the most specific information available.
6660 	 * For example, we know that there is no IRE_CACHE for this dest,
6661 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6662 	 * ire_ftable_lookup will look up the gateway, etc.
6663 	 * Check if in_ill != NULL. If it is true, the packet must be
6664 	 * from an incoming interface where RTA_SRCIFP is set.
6665 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6666 	 * to the destination, of equal netmask length in the forward table,
6667 	 * will be recursively explored. If no information is available
6668 	 * for the final gateway of that route, we force the returned ire
6669 	 * to be equal to sire using MATCH_IRE_PARENT.
6670 	 * At least, in this case we have a starting point (in the buckets)
6671 	 * to look for other routes to the destination in the forward table.
6672 	 * This is actually used only for multirouting, where a list
6673 	 * of routes has to be processed in sequence.
6674 	 */
6675 	if (in_ill != NULL) {
6676 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6677 		    in_ill, MATCH_IRE_TYPE);
6678 	} else if (attach_ill == NULL) {
6679 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6680 		    NULL, &sire, zoneid, 0,
6681 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6682 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6683 	} else {
6684 		/*
6685 		 * attach_ill is set only for communicating with
6686 		 * on-link hosts. So, don't look for DEFAULT.
6687 		 */
6688 		ipif_t	*attach_ipif;
6689 
6690 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6691 		if (attach_ipif == NULL) {
6692 			ill_refrele(attach_ill);
6693 			goto icmp_err_ret;
6694 		}
6695 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6696 		    &sire, zoneid, 0,
6697 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6698 		ipif_refrele(attach_ipif);
6699 	}
6700 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6701 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6702 
6703 	/*
6704 	 * This loop is run only once in most cases.
6705 	 * We loop to resolve further routes only when the destination
6706 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6707 	 */
6708 	do {
6709 		/* Clear the previous iteration's values */
6710 		if (src_ipif != NULL) {
6711 			ipif_refrele(src_ipif);
6712 			src_ipif = NULL;
6713 		}
6714 		if (dst_ill != NULL) {
6715 			ill_refrele(dst_ill);
6716 			dst_ill = NULL;
6717 		}
6718 
6719 		multirt_resolve_next = B_FALSE;
6720 		/*
6721 		 * We check if packets have to be multirouted.
6722 		 * In this case, given the current <ire, sire> couple,
6723 		 * we look for the next suitable <ire, sire>.
6724 		 * This check is done in ire_multirt_lookup(),
6725 		 * which applies various criteria to find the next route
6726 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6727 		 * unchanged if it detects it has not been tried yet.
6728 		 */
6729 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6730 			ip3dbg(("ip_newroute: starting next_resolution "
6731 			    "with first_mp %p, tag %d\n",
6732 			    (void *)first_mp,
6733 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6734 
6735 			ASSERT(sire != NULL);
6736 			multirt_is_resolvable =
6737 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6738 
6739 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6740 			    "ire %p, sire %p\n",
6741 			    multirt_is_resolvable,
6742 			    (void *)ire, (void *)sire));
6743 
6744 			if (!multirt_is_resolvable) {
6745 				/*
6746 				 * No more multirt route to resolve; give up
6747 				 * (all routes resolved or no more
6748 				 * resolvable routes).
6749 				 */
6750 				if (ire != NULL) {
6751 					ire_refrele(ire);
6752 					ire = NULL;
6753 				}
6754 			} else {
6755 				ASSERT(sire != NULL);
6756 				ASSERT(ire != NULL);
6757 				/*
6758 				 * We simply use first_sire as a flag that
6759 				 * indicates if a resolvable multirt route
6760 				 * has already been found.
6761 				 * If it is not the case, we may have to send
6762 				 * an ICMP error to report that the
6763 				 * destination is unreachable.
6764 				 * We do not IRE_REFHOLD first_sire.
6765 				 */
6766 				if (first_sire == NULL) {
6767 					first_sire = sire;
6768 				}
6769 			}
6770 		}
6771 		if (ire == NULL) {
6772 			if (ip_debug > 3) {
6773 				/* ip2dbg */
6774 				pr_addr_dbg("ip_newroute: "
6775 				    "can't resolve %s\n", AF_INET, &dst);
6776 			}
6777 			ip3dbg(("ip_newroute: "
6778 			    "ire %p, sire %p, first_sire %p\n",
6779 			    (void *)ire, (void *)sire, (void *)first_sire));
6780 
6781 			if (sire != NULL) {
6782 				ire_refrele(sire);
6783 				sire = NULL;
6784 			}
6785 
6786 			if (first_sire != NULL) {
6787 				/*
6788 				 * At least one multirt route has been found
6789 				 * in the same call to ip_newroute();
6790 				 * there is no need to report an ICMP error.
6791 				 * first_sire was not IRE_REFHOLDed.
6792 				 */
6793 				MULTIRT_DEBUG_UNTAG(first_mp);
6794 				freemsg(first_mp);
6795 				return;
6796 			}
6797 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6798 			    RTA_DST);
6799 			if (attach_ill != NULL)
6800 				ill_refrele(attach_ill);
6801 			goto icmp_err_ret;
6802 		}
6803 
6804 		/*
6805 		 * When RTA_SRCIFP is used to add a route, then an interface
6806 		 * route is added in the source interface's routing table.
6807 		 * If the outgoing interface of this route is of type
6808 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6809 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6810 		 * first used for forwarding packet, ip_newroute() is called
6811 		 * to resolve the hardware address of the outgoing ipif.
6812 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6813 		 * source interface based table. We only come here if the
6814 		 * outgoing interface is a resolver interface and we don't
6815 		 * have the ire_dlureq_mp information yet.
6816 		 * If in_ill is not null that means it is called from
6817 		 * ip_rput.
6818 		 */
6819 
6820 		ASSERT(ire->ire_in_ill == NULL ||
6821 		    (ire->ire_type == IRE_IF_RESOLVER &&
6822 		    ire->ire_dlureq_mp == NULL));
6823 
6824 		/*
6825 		 * Verify that the returned IRE does not have either
6826 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6827 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6828 		 */
6829 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
6830 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
6831 			if (attach_ill != NULL)
6832 				ill_refrele(attach_ill);
6833 			goto icmp_err_ret;
6834 		}
6835 		/*
6836 		 * Increment the ire_ob_pkt_count field for ire if it is an
6837 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
6838 		 * increment the same for the parent IRE, sire, if it is some
6839 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
6840 		 * and HOST_REDIRECT).
6841 		 */
6842 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
6843 			UPDATE_OB_PKT_COUNT(ire);
6844 			ire->ire_last_used_time = lbolt;
6845 		}
6846 
6847 		if (sire != NULL) {
6848 			gw = sire->ire_gateway_addr;
6849 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
6850 			    IRE_INTERFACE)) == 0);
6851 			UPDATE_OB_PKT_COUNT(sire);
6852 			sire->ire_last_used_time = lbolt;
6853 		}
6854 		/*
6855 		 * We have a route to reach the destination.
6856 		 *
6857 		 * 1) If the interface is part of ill group, try to get a new
6858 		 *    ill taking load spreading into account.
6859 		 *
6860 		 * 2) After selecting the ill, get a source address that
6861 		 *    might create good inbound load spreading.
6862 		 *    ipif_select_source does this for us.
6863 		 *
6864 		 * If the application specified the ill (ifindex), we still
6865 		 * load spread. Only if the packets needs to go out
6866 		 * specifically on a given ill e.g. binding to
6867 		 * IPIF_NOFAILOVER address, then we don't try to use a
6868 		 * different ill for load spreading.
6869 		 */
6870 		if (attach_ill == NULL) {
6871 			/*
6872 			 * Don't perform outbound load spreading in the
6873 			 * case of an RTF_MULTIRT route, as we actually
6874 			 * typically want to replicate outgoing packets
6875 			 * through particular interfaces.
6876 			 */
6877 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6878 				dst_ill = ire->ire_ipif->ipif_ill;
6879 				/* for uniformity */
6880 				ill_refhold(dst_ill);
6881 			} else {
6882 				/*
6883 				 * If we are here trying to create an IRE_CACHE
6884 				 * for an offlink destination and have the
6885 				 * IRE_CACHE for the next hop and the latter is
6886 				 * using virtual IP source address selection i.e
6887 				 * it's ire->ire_ipif is pointing to a virtual
6888 				 * network interface (vni) then
6889 				 * ip_newroute_get_dst_ll() will return the vni
6890 				 * interface as the dst_ill. Since the vni is
6891 				 * virtual i.e not associated with any physical
6892 				 * interface, it cannot be the dst_ill, hence
6893 				 * in such a case call ip_newroute_get_dst_ll()
6894 				 * with the stq_ill instead of the ire_ipif ILL.
6895 				 * The function returns a refheld ill.
6896 				 */
6897 				if ((ire->ire_type == IRE_CACHE) &&
6898 				    IS_VNI(ire->ire_ipif->ipif_ill))
6899 					dst_ill = ip_newroute_get_dst_ill(
6900 						ire->ire_stq->q_ptr);
6901 				else
6902 					dst_ill = ip_newroute_get_dst_ill(
6903 						ire->ire_ipif->ipif_ill);
6904 			}
6905 			if (dst_ill == NULL) {
6906 				if (ip_debug > 2) {
6907 					pr_addr_dbg("ip_newroute: "
6908 					    "no dst ill for dst"
6909 					    " %s\n", AF_INET, &dst);
6910 				}
6911 				goto icmp_err_ret;
6912 			}
6913 		} else {
6914 			dst_ill = ire->ire_ipif->ipif_ill;
6915 			/* for uniformity */
6916 			ill_refhold(dst_ill);
6917 			/*
6918 			 * We should have found a route matching ill as we
6919 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
6920 			 * Rather than asserting, when there is a mismatch,
6921 			 * we just drop the packet.
6922 			 */
6923 			if (dst_ill != attach_ill) {
6924 				ip0dbg(("ip_newroute: Packet dropped as "
6925 				    "IPIF_NOFAILOVER ill is %s, "
6926 				    "ire->ire_ipif->ipif_ill is %s\n",
6927 				    attach_ill->ill_name,
6928 				    dst_ill->ill_name));
6929 				ill_refrele(attach_ill);
6930 				goto icmp_err_ret;
6931 			}
6932 		}
6933 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
6934 		if (attach_ill != NULL) {
6935 			ill_refrele(attach_ill);
6936 			attach_ill = NULL;
6937 			do_attach_ill = B_TRUE;
6938 		}
6939 		ASSERT(dst_ill != NULL);
6940 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
6941 
6942 		/*
6943 		 * Pick the best source address from dst_ill.
6944 		 *
6945 		 * 1) If it is part of a multipathing group, we would
6946 		 *    like to spread the inbound packets across different
6947 		 *    interfaces. ipif_select_source picks a random source
6948 		 *    across the different ills in the group.
6949 		 *
6950 		 * 2) If it is not part of a multipathing group, we try
6951 		 *    to pick the source address from the destination
6952 		 *    route. Clustering assumes that when we have multiple
6953 		 *    prefixes hosted on an interface, the prefix of the
6954 		 *    source address matches the prefix of the destination
6955 		 *    route. We do this only if the address is not
6956 		 *    DEPRECATED.
6957 		 *
6958 		 * 3) If the conn is in a different zone than the ire, we
6959 		 *    need to pick a source address from the right zone.
6960 		 *
6961 		 * NOTE : If we hit case (1) above, the prefix of the source
6962 		 *	  address picked may not match the prefix of the
6963 		 *	  destination routes prefix as ipif_select_source
6964 		 *	  does not look at "dst" while picking a source
6965 		 *	  address.
6966 		 *	  If we want the same behavior as (2), we will need
6967 		 *	  to change the behavior of ipif_select_source.
6968 		 */
6969 		ASSERT(src_ipif == NULL);
6970 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
6971 			/*
6972 			 * The RTF_SETSRC flag is set in the parent ire (sire).
6973 			 * Check that the ipif matching the requested source
6974 			 * address still exists.
6975 			 */
6976 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
6977 			    zoneid, NULL, NULL, NULL, NULL);
6978 		}
6979 		if (src_ipif == NULL) {
6980 			ire_marks |= IRE_MARK_USESRC_CHECK;
6981 			if ((dst_ill->ill_group != NULL) ||
6982 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
6983 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
6984 			    (dst_ill->ill_usesrc_ifindex != 0)) {
6985 				src_ipif = ipif_select_source(dst_ill, dst,
6986 				    zoneid);
6987 				if (src_ipif == NULL) {
6988 					if (ip_debug > 2) {
6989 						pr_addr_dbg("ip_newroute: "
6990 						    "no src for dst %s ",
6991 						    AF_INET, &dst);
6992 						printf("through interface %s\n",
6993 						    dst_ill->ill_name);
6994 					}
6995 					goto icmp_err_ret;
6996 				}
6997 			} else {
6998 				src_ipif = ire->ire_ipif;
6999 				ASSERT(src_ipif != NULL);
7000 				/* hold src_ipif for uniformity */
7001 				ipif_refhold(src_ipif);
7002 			}
7003 		}
7004 
7005 		/*
7006 		 * Assign a source address while we have the conn.
7007 		 * We can't have ip_wput_ire pick a source address when the
7008 		 * packet returns from arp since we need to look at
7009 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7010 		 * going through arp.
7011 		 *
7012 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7013 		 *	  it uses ip6i to store this information.
7014 		 */
7015 		if (ipha->ipha_src == INADDR_ANY &&
7016 		    (connp == NULL || !connp->conn_unspec_src)) {
7017 			ipha->ipha_src = src_ipif->ipif_src_addr;
7018 		}
7019 		if (ip_debug > 3) {
7020 			/* ip2dbg */
7021 			pr_addr_dbg("ip_newroute: first hop %s\n",
7022 			    AF_INET, &gw);
7023 		}
7024 		ip2dbg(("\tire type %s (%d)\n",
7025 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7026 
7027 		/*
7028 		 * The TTL of multirouted packets is bounded by the
7029 		 * ip_multirt_ttl ndd variable.
7030 		 */
7031 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7032 			/* Force TTL of multirouted packets */
7033 			if ((ip_multirt_ttl > 0) &&
7034 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7035 				ip2dbg(("ip_newroute: forcing multirt TTL "
7036 				    "to %d (was %d), dst 0x%08x\n",
7037 				    ip_multirt_ttl, ipha->ipha_ttl,
7038 				    ntohl(sire->ire_addr)));
7039 				ipha->ipha_ttl = ip_multirt_ttl;
7040 			}
7041 		}
7042 		/*
7043 		 * At this point in ip_newroute(), ire is either the
7044 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7045 		 * destination or an IRE_INTERFACE type that should be used
7046 		 * to resolve an on-subnet destination or an on-subnet
7047 		 * next-hop gateway.
7048 		 *
7049 		 * In the IRE_CACHE case, we have the following :
7050 		 *
7051 		 * 1) src_ipif - used for getting a source address.
7052 		 *
7053 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7054 		 *    means packets using this IRE_CACHE will go out on
7055 		 *    dst_ill.
7056 		 *
7057 		 * 3) The IRE sire will point to the prefix that is the
7058 		 *    longest  matching route for the destination. These
7059 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7060 		 *    and IRE_HOST_REDIRECT.
7061 		 *
7062 		 *    The newly created IRE_CACHE entry for the off-subnet
7063 		 *    destination is tied to both the prefix route and the
7064 		 *    interface route used to resolve the next-hop gateway
7065 		 *    via the ire_phandle and ire_ihandle fields,
7066 		 *    respectively.
7067 		 *
7068 		 * In the IRE_INTERFACE case, we have the following :
7069 		 *
7070 		 * 1) src_ipif - used for getting a source address.
7071 		 *
7072 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7073 		 *    means packets using the IRE_CACHE that we will build
7074 		 *    here will go out on dst_ill.
7075 		 *
7076 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7077 		 *    to be created will only be tied to the IRE_INTERFACE
7078 		 *    that was derived from the ire_ihandle field.
7079 		 *
7080 		 *    If sire is non-NULL, it means the destination is
7081 		 *    off-link and we will first create the IRE_CACHE for the
7082 		 *    gateway. Next time through ip_newroute, we will create
7083 		 *    the IRE_CACHE for the final destination as described
7084 		 *    above.
7085 		 *
7086 		 * In both cases, after the current resolution has been
7087 		 * completed (or possibly initialised, in the IRE_INTERFACE
7088 		 * case), the loop may be re-entered to attempt the resolution
7089 		 * of another RTF_MULTIRT route.
7090 		 *
7091 		 * When an IRE_CACHE entry for the off-subnet destination is
7092 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7093 		 * for further processing in emission loops.
7094 		 */
7095 		save_ire = ire;
7096 		switch (ire->ire_type) {
7097 		case IRE_CACHE: {
7098 			ire_t	*ipif_ire;
7099 			mblk_t	*ire_fp_mp;
7100 
7101 			ASSERT(sire != NULL);
7102 			if (gw == 0)
7103 				gw = ire->ire_gateway_addr;
7104 			/*
7105 			 * We need 3 ire's to create a new cache ire for an
7106 			 * off-link destination from the cache ire of the
7107 			 * gateway.
7108 			 *
7109 			 *	1. The prefix ire 'sire'
7110 			 *	2. The cache ire of the gateway 'ire'
7111 			 *	3. The interface ire 'ipif_ire'
7112 			 *
7113 			 * We have (1) and (2). We lookup (3) below.
7114 			 *
7115 			 * If there is no interface route to the gateway,
7116 			 * it is a race condition, where we found the cache
7117 			 * but the inteface route has been deleted.
7118 			 */
7119 			ipif_ire = ire_ihandle_lookup_offlink(ire, sire);
7120 			if (ipif_ire == NULL) {
7121 				ip1dbg(("ip_newroute: "
7122 				    "ire_ihandle_lookup_offlink failed\n"));
7123 				goto icmp_err_ret;
7124 			}
7125 			/*
7126 			 * XXX We are using the same dlureq_mp
7127 			 * (DL_UNITDATA_REQ) though the save_ire is not
7128 			 * pointing at the same ill.
7129 			 * This is incorrect. We need to send it up to the
7130 			 * resolver to get the right dlureq_mp. For ethernets
7131 			 * this may be okay (ill_type == DL_ETHER).
7132 			 */
7133 			dlureq_mp = save_ire->ire_dlureq_mp;
7134 			ire_fp_mp = NULL;
7135 			/*
7136 			 * save_ire's ire_fp_mp can't change since it is
7137 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7138 			 * LOCK_IRE_FP_MP does not do any useful work in
7139 			 * the case of IRE_CACHE. So we don't use it below.
7140 			 */
7141 			if (save_ire->ire_stq == dst_ill->ill_wq)
7142 				ire_fp_mp = save_ire->ire_fp_mp;
7143 
7144 			ire = ire_create(
7145 			    (uchar_t *)&dst,		/* dest address */
7146 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7147 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7148 			    (uchar_t *)&gw,		/* gateway address */
7149 			    NULL,
7150 			    &save_ire->ire_max_frag,
7151 			    ire_fp_mp,			/* Fast Path header */
7152 			    dst_ill->ill_rq,		/* recv-from queue */
7153 			    dst_ill->ill_wq,		/* send-to queue */
7154 			    IRE_CACHE,			/* IRE type */
7155 			    save_ire->ire_dlureq_mp,
7156 			    src_ipif,
7157 			    in_ill,			/* incoming ill */
7158 			    sire->ire_mask,		/* Parent mask */
7159 			    sire->ire_phandle,		/* Parent handle */
7160 			    ipif_ire->ire_ihandle,	/* Interface handle */
7161 			    sire->ire_flags &
7162 				(RTF_SETSRC | RTF_MULTIRT), /* flags if any */
7163 			    &(sire->ire_uinfo));
7164 
7165 			if (ire == NULL) {
7166 				ire_refrele(ipif_ire);
7167 				ire_refrele(save_ire);
7168 				break;
7169 			}
7170 
7171 			ire->ire_marks |= ire_marks;
7172 
7173 			/*
7174 			 * Prevent sire and ipif_ire from getting deleted.
7175 			 * The newly created ire is tied to both of them via
7176 			 * the phandle and ihandle respectively.
7177 			 */
7178 			IRB_REFHOLD(sire->ire_bucket);
7179 			/* Has it been removed already ? */
7180 			if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7181 				IRB_REFRELE(sire->ire_bucket);
7182 				ire_refrele(ipif_ire);
7183 				ire_refrele(save_ire);
7184 				break;
7185 			}
7186 
7187 			IRB_REFHOLD(ipif_ire->ire_bucket);
7188 			/* Has it been removed already ? */
7189 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7190 				IRB_REFRELE(ipif_ire->ire_bucket);
7191 				IRB_REFRELE(sire->ire_bucket);
7192 				ire_refrele(ipif_ire);
7193 				ire_refrele(save_ire);
7194 				break;
7195 			}
7196 
7197 			xmit_mp = first_mp;
7198 			/*
7199 			 * In the case of multirouting, a copy
7200 			 * of the packet is done before its sending.
7201 			 * The copy is used to attempt another
7202 			 * route resolution, in a next loop.
7203 			 */
7204 			if (ire->ire_flags & RTF_MULTIRT) {
7205 				copy_mp = copymsg(first_mp);
7206 				if (copy_mp != NULL) {
7207 					xmit_mp = copy_mp;
7208 					MULTIRT_DEBUG_TAG(first_mp);
7209 				}
7210 			}
7211 			ire_add_then_send(q, ire, xmit_mp);
7212 			ire_refrele(save_ire);
7213 
7214 			/* Assert that sire is not deleted yet. */
7215 			ASSERT(sire->ire_ptpn != NULL);
7216 			IRB_REFRELE(sire->ire_bucket);
7217 
7218 			/* Assert that ipif_ire is not deleted yet. */
7219 			ASSERT(ipif_ire->ire_ptpn != NULL);
7220 			IRB_REFRELE(ipif_ire->ire_bucket);
7221 			ire_refrele(ipif_ire);
7222 
7223 			/*
7224 			 * If copy_mp is not NULL, multirouting was
7225 			 * requested. We loop to initiate a next
7226 			 * route resolution attempt, starting from sire.
7227 			 */
7228 			if (copy_mp != NULL) {
7229 				/*
7230 				 * Search for the next unresolved
7231 				 * multirt route.
7232 				 */
7233 				copy_mp = NULL;
7234 				ipif_ire = NULL;
7235 				ire = NULL;
7236 				multirt_resolve_next = B_TRUE;
7237 				continue;
7238 			}
7239 
7240 			ire_refrele(sire);
7241 			ipif_refrele(src_ipif);
7242 			ill_refrele(dst_ill);
7243 			return;
7244 		}
7245 		case IRE_IF_NORESOLVER: {
7246 			/*
7247 			 * We have what we need to build an IRE_CACHE.
7248 			 *
7249 			 * Create a new dlureq_mp with the IP gateway address
7250 			 * in destination address in the DLPI hdr if the
7251 			 * physical length is exactly 4 bytes.
7252 			 */
7253 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7254 				uchar_t *addr;
7255 
7256 				if (gw)
7257 					addr = (uchar_t *)&gw;
7258 				else
7259 					addr = (uchar_t *)&dst;
7260 
7261 				dlureq_mp = ill_dlur_gen(addr,
7262 				    dst_ill->ill_phys_addr_length,
7263 				    dst_ill->ill_sap,
7264 				    dst_ill->ill_sap_length);
7265 			} else {
7266 				dlureq_mp = ire->ire_dlureq_mp;
7267 			}
7268 
7269 			if (dlureq_mp == NULL) {
7270 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7271 				break;
7272 			}
7273 
7274 			ire = ire_create(
7275 			    (uchar_t *)&dst,		/* dest address */
7276 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7277 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7278 			    (uchar_t *)&gw,		/* gateway address */
7279 			    NULL,
7280 			    &save_ire->ire_max_frag,
7281 			    NULL,			/* Fast Path header */
7282 			    dst_ill->ill_rq,		/* recv-from queue */
7283 			    dst_ill->ill_wq,		/* send-to queue */
7284 			    IRE_CACHE,
7285 			    dlureq_mp,
7286 			    src_ipif,
7287 			    in_ill,			/* Incoming ill */
7288 			    save_ire->ire_mask,		/* Parent mask */
7289 			    (sire != NULL) ?		/* Parent handle */
7290 				sire->ire_phandle : 0,
7291 			    save_ire->ire_ihandle,	/* Interface handle */
7292 			    (sire != NULL) ? sire->ire_flags &
7293 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7294 			    &(save_ire->ire_uinfo));
7295 
7296 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7297 				freeb(dlureq_mp);
7298 
7299 			if (ire == NULL) {
7300 				ire_refrele(save_ire);
7301 				break;
7302 			}
7303 
7304 			ire->ire_marks |= ire_marks;
7305 
7306 			/* Prevent save_ire from getting deleted */
7307 			IRB_REFHOLD(save_ire->ire_bucket);
7308 			/* Has it been removed already ? */
7309 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7310 				IRB_REFRELE(save_ire->ire_bucket);
7311 				ire_refrele(save_ire);
7312 				break;
7313 			}
7314 
7315 			/*
7316 			 * In the case of multirouting, a copy
7317 			 * of the packet is made before it is sent.
7318 			 * The copy is used in the next
7319 			 * loop to attempt another resolution.
7320 			 */
7321 			xmit_mp = first_mp;
7322 			if ((sire != NULL) &&
7323 			    (sire->ire_flags & RTF_MULTIRT)) {
7324 				copy_mp = copymsg(first_mp);
7325 				if (copy_mp != NULL) {
7326 					xmit_mp = copy_mp;
7327 					MULTIRT_DEBUG_TAG(first_mp);
7328 				}
7329 			}
7330 			ire_add_then_send(q, ire, xmit_mp);
7331 
7332 			/* Assert that it is not deleted yet. */
7333 			ASSERT(save_ire->ire_ptpn != NULL);
7334 			IRB_REFRELE(save_ire->ire_bucket);
7335 			ire_refrele(save_ire);
7336 
7337 			if (copy_mp != NULL) {
7338 				/*
7339 				 * If we found a (no)resolver, we ignore any
7340 				 * trailing top priority IRE_CACHE in further
7341 				 * loops. This ensures that we do not omit any
7342 				 * (no)resolver.
7343 				 * This IRE_CACHE, if any, will be processed
7344 				 * by another thread entering ip_newroute().
7345 				 * IRE_CACHE entries, if any, will be processed
7346 				 * by another thread entering ip_newroute(),
7347 				 * (upon resolver response, for instance).
7348 				 * This aims to force parallel multirt
7349 				 * resolutions as soon as a packet must be sent.
7350 				 * In the best case, after the tx of only one
7351 				 * packet, all reachable routes are resolved.
7352 				 * Otherwise, the resolution of all RTF_MULTIRT
7353 				 * routes would require several emissions.
7354 				 */
7355 				multirt_flags &= ~MULTIRT_CACHEGW;
7356 
7357 				/*
7358 				 * Search for the next unresolved multirt
7359 				 * route.
7360 				 */
7361 				copy_mp = NULL;
7362 				save_ire = NULL;
7363 				ire = NULL;
7364 				multirt_resolve_next = B_TRUE;
7365 				continue;
7366 			}
7367 
7368 			/*
7369 			 * Don't need sire anymore
7370 			 */
7371 			if (sire != NULL)
7372 				ire_refrele(sire);
7373 
7374 			ipif_refrele(src_ipif);
7375 			ill_refrele(dst_ill);
7376 			return;
7377 		}
7378 		case IRE_IF_RESOLVER:
7379 			/*
7380 			 * We can't build an IRE_CACHE yet, but at least we
7381 			 * found a resolver that can help.
7382 			 */
7383 			res_mp = dst_ill->ill_resolver_mp;
7384 			if (!OK_RESOLVER_MP(res_mp))
7385 				break;
7386 			/*
7387 			 * To be at this point in the code with a non-zero gw
7388 			 * means that dst is reachable through a gateway that
7389 			 * we have never resolved.  By changing dst to the gw
7390 			 * addr we resolve the gateway first.
7391 			 * When ire_add_then_send() tries to put the IP dg
7392 			 * to dst, it will reenter ip_newroute() at which
7393 			 * time we will find the IRE_CACHE for the gw and
7394 			 * create another IRE_CACHE in case IRE_CACHE above.
7395 			 */
7396 			if (gw != INADDR_ANY) {
7397 				/*
7398 				 * The source ipif that was determined above was
7399 				 * relative to the destination address, not the
7400 				 * gateway's. If src_ipif was not taken out of
7401 				 * the IRE_IF_RESOLVER entry, we'll need to call
7402 				 * ipif_select_source() again.
7403 				 */
7404 				if (src_ipif != ire->ire_ipif) {
7405 					ipif_refrele(src_ipif);
7406 					src_ipif = ipif_select_source(dst_ill,
7407 					    gw, zoneid);
7408 					if (src_ipif == NULL) {
7409 						if (ip_debug > 2) {
7410 							pr_addr_dbg(
7411 							    "ip_newroute: no "
7412 							    "src for gw %s ",
7413 							    AF_INET, &gw);
7414 							printf("through "
7415 							    "interface %s\n",
7416 							    dst_ill->ill_name);
7417 						}
7418 						goto icmp_err_ret;
7419 					}
7420 				}
7421 				save_dst = dst;
7422 				dst = gw;
7423 				gw = INADDR_ANY;
7424 			}
7425 			/*
7426 			 * We obtain a partial IRE_CACHE which we will pass
7427 			 * along with the resolver query.  When the response
7428 			 * comes back it will be there ready for us to add.
7429 			 * The ire_max_frag is atomically set under the
7430 			 * irebucket lock in ire_add_v[46].
7431 			 */
7432 			ire = ire_create_mp(
7433 			    (uchar_t *)&dst,		/* dest address */
7434 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7435 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7436 			    (uchar_t *)&gw,		/* gateway address */
7437 			    NULL,			/* no in_src_addr */
7438 			    NULL,			/* ire_max_frag */
7439 			    NULL,			/* Fast Path header */
7440 			    dst_ill->ill_rq,		/* recv-from queue */
7441 			    dst_ill->ill_wq,		/* send-to queue */
7442 			    IRE_CACHE,
7443 			    res_mp,
7444 			    src_ipif,			/* Interface ipif */
7445 			    in_ill,			/* Incoming ILL */
7446 			    save_ire->ire_mask,		/* Parent mask */
7447 			    0,
7448 			    save_ire->ire_ihandle,	/* Interface handle */
7449 			    0,				/* flags if any */
7450 			    &(save_ire->ire_uinfo));
7451 
7452 			if (ire == NULL) {
7453 				ire_refrele(save_ire);
7454 				break;
7455 			}
7456 
7457 			if ((sire != NULL) &&
7458 			    (sire->ire_flags & RTF_MULTIRT)) {
7459 				copy_mp = copymsg(first_mp);
7460 				if (copy_mp != NULL)
7461 					MULTIRT_DEBUG_TAG(copy_mp);
7462 			}
7463 
7464 			ire->ire_marks |= ire_marks;
7465 
7466 			/*
7467 			 * Construct message chain for the resolver
7468 			 * of the form:
7469 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7470 			 * Packet could contain a IPSEC_OUT mp.
7471 			 *
7472 			 * NOTE : ire will be added later when the response
7473 			 * comes back from ARP. If the response does not
7474 			 * come back, ARP frees the packet. For this reason,
7475 			 * we can't REFHOLD the bucket of save_ire to prevent
7476 			 * deletions. We may not be able to REFRELE the bucket
7477 			 * if the response never comes back. Thus, before
7478 			 * adding the ire, ire_add_v4 will make sure that the
7479 			 * interface route does not get deleted. This is the
7480 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7481 			 * where we can always prevent deletions because of
7482 			 * the synchronous nature of adding IRES i.e
7483 			 * ire_add_then_send is called after creating the IRE.
7484 			 */
7485 			ASSERT(ire->ire_mp != NULL);
7486 			ire->ire_mp->b_cont = first_mp;
7487 			/* Have saved_mp handy, for cleanup if canput fails */
7488 			saved_mp = mp;
7489 			mp = ire->ire_dlureq_mp;
7490 			ASSERT(mp != NULL);
7491 			ire->ire_dlureq_mp = NULL;
7492 			linkb(mp, ire->ire_mp);
7493 
7494 
7495 			/*
7496 			 * Fill in the source and dest addrs for the resolver.
7497 			 * NOTE: this depends on memory layouts imposed by
7498 			 * ill_init().
7499 			 */
7500 			areq = (areq_t *)mp->b_rptr;
7501 			addrp = (ipaddr_t *)((char *)areq +
7502 			    areq->areq_sender_addr_offset);
7503 			if (do_attach_ill) {
7504 				/*
7505 				 * This is bind to no failover case.
7506 				 * arp packet also must go out on attach_ill.
7507 				 */
7508 				ASSERT(ipha->ipha_src != NULL);
7509 				*addrp = ipha->ipha_src;
7510 			} else {
7511 				*addrp = save_ire->ire_src_addr;
7512 			}
7513 
7514 			ire_refrele(save_ire);
7515 			addrp = (ipaddr_t *)((char *)areq +
7516 			    areq->areq_target_addr_offset);
7517 			*addrp = dst;
7518 			/* Up to the resolver. */
7519 			if (canputnext(dst_ill->ill_rq)) {
7520 				putnext(dst_ill->ill_rq, mp);
7521 				ire = NULL;
7522 				if (copy_mp != NULL) {
7523 					/*
7524 					 * If we found a resolver, we ignore
7525 					 * any trailing top priority IRE_CACHE
7526 					 * in the further loops. This ensures
7527 					 * that we do not omit any resolver.
7528 					 * IRE_CACHE entries, if any, will be
7529 					 * processed next time we enter
7530 					 * ip_newroute().
7531 					 */
7532 					multirt_flags &= ~MULTIRT_CACHEGW;
7533 					/*
7534 					 * Search for the next unresolved
7535 					 * multirt route.
7536 					 */
7537 					first_mp = copy_mp;
7538 					copy_mp = NULL;
7539 					/* Prepare the next resolution loop. */
7540 					mp = first_mp;
7541 					EXTRACT_PKT_MP(mp, first_mp,
7542 					    mctl_present);
7543 					if (mctl_present)
7544 						io = (ipsec_out_t *)
7545 						    first_mp->b_rptr;
7546 					ipha = (ipha_t *)mp->b_rptr;
7547 
7548 					ASSERT(sire != NULL);
7549 
7550 					dst = save_dst;
7551 					multirt_resolve_next = B_TRUE;
7552 					continue;
7553 				}
7554 
7555 				if (sire != NULL)
7556 					ire_refrele(sire);
7557 
7558 				/*
7559 				 * The response will come back in ip_wput
7560 				 * with db_type IRE_DB_TYPE.
7561 				 */
7562 				ipif_refrele(src_ipif);
7563 				ill_refrele(dst_ill);
7564 				return;
7565 			} else {
7566 				/* Prepare for cleanup */
7567 				ire->ire_dlureq_mp = mp;
7568 				mp->b_cont = NULL;
7569 				ire_delete(ire);
7570 				mp = saved_mp;
7571 				ire = NULL;
7572 				if (copy_mp != NULL) {
7573 					MULTIRT_DEBUG_UNTAG(copy_mp);
7574 					freemsg(copy_mp);
7575 					copy_mp = NULL;
7576 				}
7577 				break;
7578 			}
7579 		default:
7580 			break;
7581 		}
7582 	} while (multirt_resolve_next);
7583 
7584 	ip1dbg(("ip_newroute: dropped\n"));
7585 	/* Did this packet originate externally? */
7586 	if (mp->b_prev) {
7587 		mp->b_next = NULL;
7588 		mp->b_prev = NULL;
7589 		BUMP_MIB(&ip_mib, ipInDiscards);
7590 	} else {
7591 		BUMP_MIB(&ip_mib, ipOutDiscards);
7592 	}
7593 	ASSERT(copy_mp == NULL);
7594 	MULTIRT_DEBUG_UNTAG(first_mp);
7595 	freemsg(first_mp);
7596 	if (ire != NULL)
7597 		ire_refrele(ire);
7598 	if (sire != NULL)
7599 		ire_refrele(sire);
7600 	if (src_ipif != NULL)
7601 		ipif_refrele(src_ipif);
7602 	if (dst_ill != NULL)
7603 		ill_refrele(dst_ill);
7604 	return;
7605 
7606 icmp_err_ret:
7607 	ip1dbg(("ip_newroute: no route\n"));
7608 	if (src_ipif != NULL)
7609 		ipif_refrele(src_ipif);
7610 	if (dst_ill != NULL)
7611 		ill_refrele(dst_ill);
7612 	if (sire != NULL)
7613 		ire_refrele(sire);
7614 	/* Did this packet originate externally? */
7615 	if (mp->b_prev) {
7616 		mp->b_next = NULL;
7617 		mp->b_prev = NULL;
7618 		/* XXX ipInNoRoutes */
7619 		q = WR(q);
7620 	} else {
7621 		/*
7622 		 * Since ip_wput() isn't close to finished, we fill
7623 		 * in enough of the header for credible error reporting.
7624 		 */
7625 		if (ip_hdr_complete(ipha, zoneid)) {
7626 			/* Failed */
7627 			MULTIRT_DEBUG_UNTAG(first_mp);
7628 			freemsg(first_mp);
7629 			if (ire != NULL)
7630 				ire_refrele(ire);
7631 			return;
7632 		}
7633 	}
7634 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7635 
7636 	/*
7637 	 * At this point we will have ire only if RTF_BLACKHOLE
7638 	 * or RTF_REJECT flags are set on the IRE. It will not
7639 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7640 	 */
7641 	if (ire != NULL) {
7642 		if (ire->ire_flags & RTF_BLACKHOLE) {
7643 			ire_refrele(ire);
7644 			MULTIRT_DEBUG_UNTAG(first_mp);
7645 			freemsg(first_mp);
7646 			return;
7647 		}
7648 		ire_refrele(ire);
7649 	}
7650 	if (ip_source_routed(ipha)) {
7651 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7652 		return;
7653 	}
7654 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7655 }
7656 
7657 /*
7658  * IPv4 -
7659  * ip_newroute_ipif is called by ip_wput_multicast and
7660  * ip_rput_forward_multicast whenever we need to send
7661  * out a packet to a destination address for which we do not have specific
7662  * routing information. It is used when the packet will be sent out
7663  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7664  * socket option is set or icmp error message wants to go out on a particular
7665  * interface for a unicast packet.
7666  *
7667  * In most cases, the destination address is resolved thanks to the ipif
7668  * intrinsic resolver. However, there are some cases where the call to
7669  * ip_newroute_ipif must take into account the potential presence of
7670  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7671  * that uses the interface. This is specified through flags,
7672  * which can be a combination of:
7673  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7674  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7675  *   and flags. Additionally, the packet source address has to be set to
7676  *   the specified address. The caller is thus expected to set this flag
7677  *   if the packet has no specific source address yet.
7678  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7679  *   flag, the resulting ire will inherit the flag. All unresolved routes
7680  *   to the destination must be explored in the same call to
7681  *   ip_newroute_ipif().
7682  */
7683 static void
7684 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7685     conn_t *connp, uint32_t flags)
7686 {
7687 	areq_t	*areq;
7688 	ire_t	*ire = NULL;
7689 	mblk_t	*res_mp;
7690 	ipaddr_t *addrp;
7691 	mblk_t *first_mp;
7692 	ire_t	*save_ire = NULL;
7693 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7694 	ipif_t	*src_ipif = NULL;
7695 	ushort_t ire_marks = 0;
7696 	ill_t	*dst_ill = NULL;
7697 	boolean_t mctl_present;
7698 	ipsec_out_t *io;
7699 	ipha_t *ipha;
7700 	int	ihandle = 0;
7701 	mblk_t	*saved_mp;
7702 	ire_t   *fire = NULL;
7703 	mblk_t  *copy_mp = NULL;
7704 	boolean_t multirt_resolve_next;
7705 	ipaddr_t ipha_dst;
7706 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7707 
7708 	/*
7709 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7710 	 * here for uniformity
7711 	 */
7712 	ipif_refhold(ipif);
7713 
7714 	/*
7715 	 * This loop is run only once in most cases.
7716 	 * We loop to resolve further routes only when the destination
7717 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7718 	 */
7719 	do {
7720 		if (dst_ill != NULL) {
7721 			ill_refrele(dst_ill);
7722 			dst_ill = NULL;
7723 		}
7724 		if (src_ipif != NULL) {
7725 			ipif_refrele(src_ipif);
7726 			src_ipif = NULL;
7727 		}
7728 		multirt_resolve_next = B_FALSE;
7729 
7730 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7731 		    ipif->ipif_ill->ill_name));
7732 
7733 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7734 		if (mctl_present)
7735 			io = (ipsec_out_t *)first_mp->b_rptr;
7736 
7737 		ipha = (ipha_t *)mp->b_rptr;
7738 
7739 		/*
7740 		 * Save the packet destination address, we may need it after
7741 		 * the packet has been consumed.
7742 		 */
7743 		ipha_dst = ipha->ipha_dst;
7744 
7745 		/*
7746 		 * If the interface is a pt-pt interface we look for an
7747 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7748 		 * local_address and the pt-pt destination address. Otherwise
7749 		 * we just match the local address.
7750 		 * NOTE: dst could be different than ipha->ipha_dst in case
7751 		 * of sending igmp multicast packets over a point-to-point
7752 		 * connection.
7753 		 * Thus we must be careful enough to check ipha_dst to be a
7754 		 * multicast address, otherwise it will take xmit_if path for
7755 		 * multicast packets resulting into kernel stack overflow by
7756 		 * repeated calls to ip_newroute_ipif from ire_send().
7757 		 */
7758 		if (CLASSD(ipha_dst) &&
7759 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7760 			goto err_ret;
7761 		}
7762 
7763 		/*
7764 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7765 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7766 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7767 		 * propagate its flags to the new ire.
7768 		 */
7769 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7770 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7771 			ip2dbg(("ip_newroute_ipif: "
7772 			    "ipif_lookup_multi_ire("
7773 			    "ipif %p, dst %08x) = fire %p\n",
7774 			    (void *)ipif, ntohl(dst), (void *)fire));
7775 		}
7776 
7777 		if (mctl_present && io->ipsec_out_attach_if) {
7778 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7779 			    io->ipsec_out_ill_index, B_FALSE);
7780 
7781 			/* Failure case frees things for us. */
7782 			if (attach_ill == NULL) {
7783 				ipif_refrele(ipif);
7784 				if (fire != NULL)
7785 					ire_refrele(fire);
7786 				return;
7787 			}
7788 
7789 			/*
7790 			 * Check if we need an ire that will not be
7791 			 * looked up by anybody else i.e. HIDDEN.
7792 			 */
7793 			if (ill_is_probeonly(attach_ill)) {
7794 				ire_marks = IRE_MARK_HIDDEN;
7795 			}
7796 			/*
7797 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
7798 			 * case.
7799 			 */
7800 			dst_ill = ipif->ipif_ill;
7801 			/* attach_ill has been refheld by ip_grab_attach_ill */
7802 			ASSERT(dst_ill == attach_ill);
7803 		} else {
7804 			/*
7805 			 * If this is set by IP_XMIT_IF, then make sure that
7806 			 * ipif is pointing to the same ill as the IP_XMIT_IF
7807 			 * specified ill.
7808 			 */
7809 			ASSERT((connp == NULL) ||
7810 			    (connp->conn_xmit_if_ill == NULL) ||
7811 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
7812 			/*
7813 			 * If the interface belongs to an interface group,
7814 			 * make sure the next possible interface in the group
7815 			 * is used.  This encourages load spreading among
7816 			 * peers in an interface group.
7817 			 * Note: load spreading is disabled for RTF_MULTIRT
7818 			 * routes.
7819 			 */
7820 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7821 			    (fire->ire_flags & RTF_MULTIRT)) {
7822 				/*
7823 				 * Don't perform outbound load spreading
7824 				 * in the case of an RTF_MULTIRT issued route,
7825 				 * we actually typically want to replicate
7826 				 * outgoing packets through particular
7827 				 * interfaces.
7828 				 */
7829 				dst_ill = ipif->ipif_ill;
7830 				ill_refhold(dst_ill);
7831 			} else {
7832 				dst_ill = ip_newroute_get_dst_ill(
7833 				    ipif->ipif_ill);
7834 			}
7835 			if (dst_ill == NULL) {
7836 				if (ip_debug > 2) {
7837 					pr_addr_dbg("ip_newroute_ipif: "
7838 					    "no dst ill for dst %s\n",
7839 					    AF_INET, &dst);
7840 				}
7841 				goto err_ret;
7842 			}
7843 		}
7844 
7845 		/*
7846 		 * Pick a source address preferring non-deprecated ones.
7847 		 * Unlike ip_newroute, we don't do any source address
7848 		 * selection here since for multicast it really does not help
7849 		 * in inbound load spreading as in the unicast case.
7850 		 */
7851 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
7852 		    (fire->ire_flags & RTF_SETSRC)) {
7853 			/*
7854 			 * As requested by flags, an IRE_OFFSUBNET was looked up
7855 			 * on that interface. This ire has RTF_SETSRC flag, so
7856 			 * the source address of the packet must be changed.
7857 			 * Check that the ipif matching the requested source
7858 			 * address still exists.
7859 			 */
7860 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
7861 			    zoneid, NULL, NULL, NULL, NULL);
7862 		}
7863 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
7864 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
7865 		    (src_ipif == NULL)) {
7866 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
7867 			if (src_ipif == NULL) {
7868 				if (ip_debug > 2) {
7869 					/* ip1dbg */
7870 					pr_addr_dbg("ip_newroute_ipif: "
7871 					    "no src for dst %s",
7872 					    AF_INET, &dst);
7873 				}
7874 				ip1dbg((" through interface %s\n",
7875 				    dst_ill->ill_name));
7876 				goto err_ret;
7877 			}
7878 			ipif_refrele(ipif);
7879 			ipif = src_ipif;
7880 			ipif_refhold(ipif);
7881 		}
7882 		if (src_ipif == NULL) {
7883 			src_ipif = ipif;
7884 			ipif_refhold(src_ipif);
7885 		}
7886 
7887 		/*
7888 		 * Assign a source address while we have the conn.
7889 		 * We can't have ip_wput_ire pick a source address when the
7890 		 * packet returns from arp since conn_unspec_src might be set
7891 		 * and we loose the conn when going through arp.
7892 		 */
7893 		if (ipha->ipha_src == INADDR_ANY &&
7894 		    (connp == NULL || !connp->conn_unspec_src)) {
7895 			ipha->ipha_src = src_ipif->ipif_src_addr;
7896 		}
7897 
7898 		/*
7899 		 * In case of IP_XMIT_IF, it is possible that the outgoing
7900 		 * interface does not have an interface ire.
7901 		 * Example: Thousands of mobileip PPP interfaces to mobile
7902 		 * nodes. We don't want to create interface ires because
7903 		 * packets from other mobile nodes must not take the route
7904 		 * via interface ires to the visiting mobile node without
7905 		 * going through the home agent, in absence of mobileip
7906 		 * route optimization.
7907 		 */
7908 		if (CLASSD(ipha_dst) && (connp == NULL ||
7909 		    connp->conn_xmit_if_ill == NULL)) {
7910 			/* ipif_to_ire returns an held ire */
7911 			ire = ipif_to_ire(ipif);
7912 			if (ire == NULL)
7913 				goto err_ret;
7914 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
7915 				goto err_ret;
7916 			/*
7917 			 * ihandle is needed when the ire is added to
7918 			 * cache table.
7919 			 */
7920 			save_ire = ire;
7921 			ihandle = save_ire->ire_ihandle;
7922 
7923 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
7924 			    "flags %04x\n",
7925 			    (void *)ire, (void *)ipif, flags));
7926 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7927 			    (fire->ire_flags & RTF_MULTIRT)) {
7928 				/*
7929 				 * As requested by flags, an IRE_OFFSUBNET was
7930 				 * looked up on that interface. This ire has
7931 				 * RTF_MULTIRT flag, so the resolution loop will
7932 				 * be re-entered to resolve additional routes on
7933 				 * other interfaces. For that purpose, a copy of
7934 				 * the packet is performed at this point.
7935 				 */
7936 				fire->ire_last_used_time = lbolt;
7937 				copy_mp = copymsg(first_mp);
7938 				if (copy_mp) {
7939 					MULTIRT_DEBUG_TAG(copy_mp);
7940 				}
7941 			}
7942 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
7943 			    (fire->ire_flags & RTF_SETSRC)) {
7944 				/*
7945 				 * As requested by flags, an IRE_OFFSUBET was
7946 				 * looked up on that interface. This ire has
7947 				 * RTF_SETSRC flag, so the source address of the
7948 				 * packet must be changed.
7949 				 */
7950 				ipha->ipha_src = fire->ire_src_addr;
7951 			}
7952 		} else {
7953 			ASSERT((connp == NULL) ||
7954 			    (connp->conn_xmit_if_ill != NULL) ||
7955 			    (connp->conn_dontroute));
7956 			/*
7957 			 * The only ways we can come here are:
7958 			 * 1) IP_XMIT_IF socket option is set
7959 			 * 2) ICMP error message generated from
7960 			 *    ip_mrtun_forward() routine and it needs
7961 			 *    to go through the specified ill.
7962 			 * 3) SO_DONTROUTE socket option is set
7963 			 * In all cases, the new ire will not be added
7964 			 * into cache table.
7965 			 */
7966 			ire_marks |= IRE_MARK_NOADD;
7967 		}
7968 
7969 		switch (ipif->ipif_net_type) {
7970 		case IRE_IF_NORESOLVER: {
7971 			/* We have what we need to build an IRE_CACHE. */
7972 			mblk_t	*dlureq_mp;
7973 
7974 			/*
7975 			 * Create a new dlureq_mp with the
7976 			 * IP gateway address as destination address in the
7977 			 * DLPI hdr if the physical length is exactly 4 bytes.
7978 			 */
7979 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7980 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
7981 				    dst_ill->ill_phys_addr_length,
7982 				    dst_ill->ill_sap,
7983 				    dst_ill->ill_sap_length);
7984 			} else {
7985 				/* use the value set in ip_ll_subnet_defaults */
7986 				dlureq_mp = ill_dlur_gen(NULL,
7987 				    dst_ill->ill_phys_addr_length,
7988 				    dst_ill->ill_sap,
7989 				    dst_ill->ill_sap_length);
7990 			}
7991 
7992 			if (dlureq_mp == NULL)
7993 				break;
7994 			/*
7995 			 * The new ire inherits the IRE_OFFSUBNET flags
7996 			 * and source address, if this was requested.
7997 			 */
7998 			ire = ire_create(
7999 			    (uchar_t *)&dst,		/* dest address */
8000 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8001 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8002 			    NULL,			/* gateway address */
8003 			    NULL,
8004 			    &ipif->ipif_mtu,
8005 			    NULL,			/* Fast Path header */
8006 			    dst_ill->ill_rq,		/* recv-from queue */
8007 			    dst_ill->ill_wq,		/* send-to queue */
8008 			    IRE_CACHE,
8009 			    dlureq_mp,
8010 			    src_ipif,
8011 			    NULL,
8012 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8013 			    (fire != NULL) ?		/* Parent handle */
8014 				fire->ire_phandle : 0,
8015 			    ihandle,			/* Interface handle */
8016 			    (fire != NULL) ?
8017 				(fire->ire_flags &
8018 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8019 			    (save_ire == NULL ? &ire_uinfo_null :
8020 				&save_ire->ire_uinfo));
8021 
8022 			freeb(dlureq_mp);
8023 
8024 			if (ire == NULL) {
8025 				if (save_ire != NULL)
8026 					ire_refrele(save_ire);
8027 				break;
8028 			}
8029 
8030 			ire->ire_marks |= ire_marks;
8031 
8032 			/* Prevent save_ire from getting deleted */
8033 			if (save_ire != NULL) {
8034 				IRB_REFHOLD(save_ire->ire_bucket);
8035 				/* Has it been removed already ? */
8036 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8037 					IRB_REFRELE(save_ire->ire_bucket);
8038 					ire_refrele(save_ire);
8039 					break;
8040 				}
8041 			}
8042 
8043 			ire_add_then_send(q, ire, first_mp);
8044 
8045 			/* Assert that save_ire is not deleted yet. */
8046 			if (save_ire != NULL) {
8047 				ASSERT(save_ire->ire_ptpn != NULL);
8048 				IRB_REFRELE(save_ire->ire_bucket);
8049 				ire_refrele(save_ire);
8050 				save_ire = NULL;
8051 			}
8052 			if (fire != NULL) {
8053 				ire_refrele(fire);
8054 				fire = NULL;
8055 			}
8056 
8057 			/*
8058 			 * the resolution loop is re-entered if this
8059 			 * was requested through flags and if we
8060 			 * actually are in a multirouting case.
8061 			 */
8062 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8063 				boolean_t need_resolve =
8064 				    ire_multirt_need_resolve(ipha_dst);
8065 				if (!need_resolve) {
8066 					MULTIRT_DEBUG_UNTAG(copy_mp);
8067 					freemsg(copy_mp);
8068 					copy_mp = NULL;
8069 				} else {
8070 					/*
8071 					 * ipif_lookup_group() calls
8072 					 * ire_lookup_multi() that uses
8073 					 * ire_ftable_lookup() to find
8074 					 * an IRE_INTERFACE for the group.
8075 					 * In the multirt case,
8076 					 * ire_lookup_multi() then invokes
8077 					 * ire_multirt_lookup() to find
8078 					 * the next resolvable ire.
8079 					 * As a result, we obtain an new
8080 					 * interface, derived from the
8081 					 * next ire.
8082 					 */
8083 					ipif_refrele(ipif);
8084 					ipif = ipif_lookup_group(ipha_dst,
8085 					    zoneid);
8086 					ip2dbg(("ip_newroute_ipif: "
8087 					    "multirt dst %08x, ipif %p\n",
8088 					    htonl(dst), (void *)ipif));
8089 					if (ipif != NULL) {
8090 						mp = copy_mp;
8091 						copy_mp = NULL;
8092 						multirt_resolve_next = B_TRUE;
8093 						continue;
8094 					} else {
8095 						freemsg(copy_mp);
8096 					}
8097 				}
8098 			}
8099 			if (ipif != NULL)
8100 				ipif_refrele(ipif);
8101 			ill_refrele(dst_ill);
8102 			ipif_refrele(src_ipif);
8103 			return;
8104 		}
8105 		case IRE_IF_RESOLVER:
8106 			/*
8107 			 * We can't build an IRE_CACHE yet, but at least
8108 			 * we found a resolver that can help.
8109 			 */
8110 			res_mp = dst_ill->ill_resolver_mp;
8111 			if (!OK_RESOLVER_MP(res_mp))
8112 				break;
8113 
8114 			/*
8115 			 * We obtain a partial IRE_CACHE which we will pass
8116 			 * along with the resolver query.  When the response
8117 			 * comes back it will be there ready for us to add.
8118 			 * The new ire inherits the IRE_OFFSUBNET flags
8119 			 * and source address, if this was requested.
8120 			 * The ire_max_frag is atomically set under the
8121 			 * irebucket lock in ire_add_v[46]. Only in the
8122 			 * case of IRE_MARK_NOADD, we set it here itself.
8123 			 */
8124 			ire = ire_create_mp(
8125 			    (uchar_t *)&dst,		/* dest address */
8126 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8127 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8128 			    NULL,			/* gateway address */
8129 			    NULL,			/* no in_src_addr */
8130 			    (ire_marks & IRE_MARK_NOADD) ?
8131 				ipif->ipif_mtu : 0,	/* max_frag */
8132 			    NULL,			/* Fast path header */
8133 			    dst_ill->ill_rq,		/* recv-from queue */
8134 			    dst_ill->ill_wq,		/* send-to queue */
8135 			    IRE_CACHE,
8136 			    res_mp,
8137 			    src_ipif,
8138 			    NULL,
8139 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8140 			    (fire != NULL) ?		/* Parent handle */
8141 				fire->ire_phandle : 0,
8142 			    ihandle,			/* Interface handle */
8143 			    (fire != NULL) ?		/* flags if any */
8144 				(fire->ire_flags &
8145 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8146 			    (save_ire == NULL ? &ire_uinfo_null :
8147 				&save_ire->ire_uinfo));
8148 
8149 			if (save_ire != NULL) {
8150 				ire_refrele(save_ire);
8151 				save_ire = NULL;
8152 			}
8153 			if (ire == NULL)
8154 				break;
8155 
8156 			ire->ire_marks |= ire_marks;
8157 			/*
8158 			 * Construct message chain for the resolver of the
8159 			 * form:
8160 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8161 			 *
8162 			 * NOTE : ire will be added later when the response
8163 			 * comes back from ARP. If the response does not
8164 			 * come back, ARP frees the packet. For this reason,
8165 			 * we can't REFHOLD the bucket of save_ire to prevent
8166 			 * deletions. We may not be able to REFRELE the
8167 			 * bucket if the response never comes back.
8168 			 * Thus, before adding the ire, ire_add_v4 will make
8169 			 * sure that the interface route does not get deleted.
8170 			 * This is the only case unlike ip_newroute_v6,
8171 			 * ip_newroute_ipif_v6 where we can always prevent
8172 			 * deletions because ire_add_then_send is called after
8173 			 * creating the IRE.
8174 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8175 			 * does not add this IRE into the IRE CACHE.
8176 			 */
8177 			ASSERT(ire->ire_mp != NULL);
8178 			ire->ire_mp->b_cont = first_mp;
8179 			/* Have saved_mp handy, for cleanup if canput fails */
8180 			saved_mp = mp;
8181 			mp = ire->ire_dlureq_mp;
8182 			ASSERT(mp != NULL);
8183 			ire->ire_dlureq_mp = NULL;
8184 			linkb(mp, ire->ire_mp);
8185 
8186 			/*
8187 			 * Fill in the source and dest addrs for the resolver.
8188 			 * NOTE: this depends on memory layouts imposed by
8189 			 * ill_init().
8190 			 */
8191 			areq = (areq_t *)mp->b_rptr;
8192 			addrp = (ipaddr_t *)((char *)areq +
8193 			    areq->areq_sender_addr_offset);
8194 			*addrp = ire->ire_src_addr;
8195 			addrp = (ipaddr_t *)((char *)areq +
8196 			    areq->areq_target_addr_offset);
8197 			*addrp = dst;
8198 			/* Up to the resolver. */
8199 			if (canputnext(dst_ill->ill_rq)) {
8200 				putnext(dst_ill->ill_rq, mp);
8201 				/*
8202 				 * The response will come back in ip_wput
8203 				 * with db_type IRE_DB_TYPE.
8204 				 */
8205 			} else {
8206 				ire->ire_dlureq_mp = mp;
8207 				mp->b_cont = NULL;
8208 				ire_delete(ire);
8209 				saved_mp->b_next = NULL;
8210 				saved_mp->b_prev = NULL;
8211 				freemsg(first_mp);
8212 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8213 			}
8214 
8215 			if (fire != NULL) {
8216 				ire_refrele(fire);
8217 				fire = NULL;
8218 			}
8219 
8220 
8221 			/*
8222 			 * The resolution loop is re-entered if this was
8223 			 * requested through flags and we actually are
8224 			 * in a multirouting case.
8225 			 */
8226 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8227 				boolean_t need_resolve =
8228 				    ire_multirt_need_resolve(ipha_dst);
8229 				if (!need_resolve) {
8230 					MULTIRT_DEBUG_UNTAG(copy_mp);
8231 					freemsg(copy_mp);
8232 					copy_mp = NULL;
8233 				} else {
8234 					/*
8235 					 * ipif_lookup_group() calls
8236 					 * ire_lookup_multi() that uses
8237 					 * ire_ftable_lookup() to find
8238 					 * an IRE_INTERFACE for the group.
8239 					 * In the multirt case,
8240 					 * ire_lookup_multi() then invokes
8241 					 * ire_multirt_lookup() to find
8242 					 * the next resolvable ire.
8243 					 * As a result, we obtain an new
8244 					 * interface, derived from the
8245 					 * next ire.
8246 					 */
8247 					ipif_refrele(ipif);
8248 					ipif = ipif_lookup_group(ipha_dst,
8249 					    zoneid);
8250 					if (ipif != NULL) {
8251 						mp = copy_mp;
8252 						copy_mp = NULL;
8253 						multirt_resolve_next = B_TRUE;
8254 						continue;
8255 					} else {
8256 						freemsg(copy_mp);
8257 					}
8258 				}
8259 			}
8260 			if (ipif != NULL)
8261 				ipif_refrele(ipif);
8262 			ill_refrele(dst_ill);
8263 			ipif_refrele(src_ipif);
8264 			return;
8265 		default:
8266 			break;
8267 		}
8268 	} while (multirt_resolve_next);
8269 
8270 err_ret:
8271 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8272 	if (fire != NULL)
8273 		ire_refrele(fire);
8274 	ipif_refrele(ipif);
8275 	/* Did this packet originate externally? */
8276 	if (dst_ill != NULL)
8277 		ill_refrele(dst_ill);
8278 	if (src_ipif != NULL)
8279 		ipif_refrele(src_ipif);
8280 	if (mp->b_prev || mp->b_next) {
8281 		mp->b_next = NULL;
8282 		mp->b_prev = NULL;
8283 	} else {
8284 		/*
8285 		 * Since ip_wput() isn't close to finished, we fill
8286 		 * in enough of the header for credible error reporting.
8287 		 */
8288 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8289 			/* Failed */
8290 			freemsg(first_mp);
8291 			if (ire != NULL)
8292 				ire_refrele(ire);
8293 			return;
8294 		}
8295 	}
8296 	/*
8297 	 * At this point we will have ire only if RTF_BLACKHOLE
8298 	 * or RTF_REJECT flags are set on the IRE. It will not
8299 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8300 	 */
8301 	if (ire != NULL) {
8302 		if (ire->ire_flags & RTF_BLACKHOLE) {
8303 			ire_refrele(ire);
8304 			freemsg(first_mp);
8305 			return;
8306 		}
8307 		ire_refrele(ire);
8308 	}
8309 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8310 }
8311 
8312 /* Name/Value Table Lookup Routine */
8313 char *
8314 ip_nv_lookup(nv_t *nv, int value)
8315 {
8316 	if (!nv)
8317 		return (NULL);
8318 	for (; nv->nv_name; nv++) {
8319 		if (nv->nv_value == value)
8320 			return (nv->nv_name);
8321 	}
8322 	return ("unknown");
8323 }
8324 
8325 /*
8326  * one day it can be patched to 1 from /etc/system for machines that have few
8327  * fast network interfaces feeding multiple cpus.
8328  */
8329 int ill_stream_putlocks = 0;
8330 
8331 /*
8332  * This is a module open, i.e. this is a control stream for access
8333  * to a DLPI device.  We allocate an ill_t as the instance data in
8334  * this case.
8335  */
8336 int
8337 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8338 {
8339 	uint32_t mem_cnt;
8340 	uint32_t cpu_cnt;
8341 	uint32_t min_cnt;
8342 	pgcnt_t mem_avail;
8343 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8344 	ill_t	*ill;
8345 	int	err;
8346 
8347 	/*
8348 	 * Prevent unprivileged processes from pushing IP so that
8349 	 * they can't send raw IP.
8350 	 */
8351 	if (secpolicy_net_rawaccess(credp) != 0)
8352 		return (EPERM);
8353 
8354 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8355 	q->q_ptr = WR(q)->q_ptr = ill;
8356 
8357 	/*
8358 	 * ill_init initializes the ill fields and then sends down
8359 	 * down a DL_INFO_REQ after calling qprocson.
8360 	 */
8361 	err = ill_init(q, ill);
8362 	if (err != 0) {
8363 		mi_free(ill);
8364 		q->q_ptr = NULL;
8365 		WR(q)->q_ptr = NULL;
8366 		return (err);
8367 	}
8368 
8369 	/* ill_init initializes the ipsq marking this thread as writer */
8370 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8371 	/* Wait for the DL_INFO_ACK */
8372 	mutex_enter(&ill->ill_lock);
8373 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8374 		/*
8375 		 * Return value of 0 indicates a pending signal.
8376 		 */
8377 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8378 		if (err == 0) {
8379 			mutex_exit(&ill->ill_lock);
8380 			(void) ip_close(q, 0);
8381 			return (EINTR);
8382 		}
8383 	}
8384 	mutex_exit(&ill->ill_lock);
8385 
8386 	/*
8387 	 * ip_rput_other could have set an error  in ill_error on
8388 	 * receipt of M_ERROR.
8389 	 */
8390 
8391 	err = ill->ill_error;
8392 	if (err != 0) {
8393 		(void) ip_close(q, 0);
8394 		return (err);
8395 	}
8396 
8397 	/*
8398 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8399 	 * size and the cpu speed of the machine. This is upper
8400 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8401 	 * and is lower bounded by the compile time value of
8402 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8403 	 * ip6_ire_max_bucket_cnt.
8404 	 */
8405 	mem_avail = kmem_avail();
8406 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8407 	    ip_cache_table_size / sizeof (ire_t);
8408 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8409 
8410 	min_cnt = MIN(cpu_cnt, mem_cnt);
8411 	if (min_cnt < ip_ire_min_bucket_cnt)
8412 		min_cnt = ip_ire_min_bucket_cnt;
8413 	if (ip_ire_max_bucket_cnt > min_cnt) {
8414 		ip_ire_max_bucket_cnt = min_cnt;
8415 	}
8416 
8417 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8418 	    ip6_cache_table_size / sizeof (ire_t);
8419 	min_cnt = MIN(cpu_cnt, mem_cnt);
8420 	if (min_cnt < ip6_ire_min_bucket_cnt)
8421 		min_cnt = ip6_ire_min_bucket_cnt;
8422 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8423 		ip6_ire_max_bucket_cnt = min_cnt;
8424 	}
8425 
8426 	ill->ill_credp = credp;
8427 	crhold(credp);
8428 
8429 	mutex_enter(&ip_mi_lock);
8430 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8431 	mutex_exit(&ip_mi_lock);
8432 	if (err) {
8433 		(void) ip_close(q, 0);
8434 		return (err);
8435 	}
8436 	return (0);
8437 }
8438 
8439 /* IP open routine. */
8440 int
8441 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8442 {
8443 	conn_t 		*connp;
8444 	major_t		maj;
8445 
8446 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8447 
8448 	/* Allow reopen. */
8449 	if (q->q_ptr != NULL)
8450 		return (0);
8451 
8452 	if (sflag & MODOPEN) {
8453 		/* This is a module open */
8454 		return (ip_modopen(q, devp, flag, sflag, credp));
8455 	}
8456 
8457 
8458 	/*
8459 	 * We are opening as a device. This is an IP client stream, and we
8460 	 * allocate an conn_t as the instance data.
8461 	 */
8462 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8463 	connp->conn_upq = q;
8464 	q->q_ptr = WR(q)->q_ptr = connp;
8465 
8466 	/* Minor tells us which /dev entry was opened */
8467 	if (geteminor(*devp) == IPV6_MINOR) {
8468 		connp->conn_flags |= IPCL_ISV6;
8469 		connp->conn_af_isv6 = B_TRUE;
8470 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8471 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8472 	} else {
8473 		connp->conn_af_isv6 = B_FALSE;
8474 		connp->conn_pkt_isv6 = B_FALSE;
8475 	}
8476 
8477 
8478 	if ((connp->conn_dev =
8479 	    inet_minor_alloc(ip_minor_arena)) == 0) {
8480 		q->q_ptr = WR(q)->q_ptr = NULL;
8481 		CONN_DEC_REF(connp);
8482 		return (EBUSY);
8483 	}
8484 
8485 	maj = getemajor(*devp);
8486 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8487 
8488 	/*
8489 	 * connp->conn_cred is crfree()ed in ip_close().
8490 	 */
8491 	connp->conn_cred = credp;
8492 	crhold(connp->conn_cred);
8493 
8494 	connp->conn_zoneid = getzoneid();
8495 
8496 	/*
8497 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8498 	 * administrative ops.  In these cases, we just need a normal conn_t
8499 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8500 	 * an error will be returned.
8501 	 */
8502 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8503 		connp->conn_rq = q;
8504 		connp->conn_wq = WR(q);
8505 	} else {
8506 		connp->conn_ulp = IPPROTO_SCTP;
8507 		connp->conn_rq = connp->conn_wq = NULL;
8508 	}
8509 	/* Non-zero default values */
8510 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8511 
8512 	/*
8513 	 * Make the conn globally visible to walkers
8514 	 */
8515 	mutex_enter(&connp->conn_lock);
8516 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8517 	mutex_exit(&connp->conn_lock);
8518 	ASSERT(connp->conn_ref == 1);
8519 
8520 	qprocson(q);
8521 
8522 	return (0);
8523 }
8524 
8525 /*
8526  * Change q_qinfo based on the value of isv6.
8527  * This can not called on an ill queue.
8528  * Note that there is no race since either q_qinfo works for conn queues - it
8529  * is just an optimization to enter the best wput routine directly.
8530  */
8531 void
8532 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8533 {
8534 	ASSERT(q->q_flag & QREADR);
8535 	ASSERT(WR(q)->q_next == NULL);
8536 	ASSERT(q->q_ptr != NULL);
8537 
8538 	if (minor == IPV6_MINOR)  {
8539 		if (bump_mib)
8540 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8541 		q->q_qinfo = &rinit_ipv6;
8542 		WR(q)->q_qinfo = &winit_ipv6;
8543 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8544 	} else {
8545 		if (bump_mib)
8546 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8547 		q->q_qinfo = &rinit;
8548 		WR(q)->q_qinfo = &winit;
8549 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8550 	}
8551 
8552 }
8553 
8554 /*
8555  * See if IPsec needs loading because of the options in mp.
8556  */
8557 static boolean_t
8558 ipsec_opt_present(mblk_t *mp)
8559 {
8560 	uint8_t *optcp, *next_optcp, *opt_endcp;
8561 	struct opthdr *opt;
8562 	struct T_opthdr *topt;
8563 	int opthdr_len;
8564 	t_uscalar_t optname, optlevel;
8565 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8566 	ipsec_req_t *ipsr;
8567 
8568 	/*
8569 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8570 	 * return TRUE.
8571 	 */
8572 
8573 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8574 	opt_endcp = optcp + tor->OPT_length;
8575 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8576 		opthdr_len = sizeof (struct T_opthdr);
8577 	} else {		/* O_OPTMGMT_REQ */
8578 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8579 		opthdr_len = sizeof (struct opthdr);
8580 	}
8581 	for (; optcp < opt_endcp; optcp = next_optcp) {
8582 		if (optcp + opthdr_len > opt_endcp)
8583 			return (B_FALSE);	/* Not enough option header. */
8584 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8585 			topt = (struct T_opthdr *)optcp;
8586 			optlevel = topt->level;
8587 			optname = topt->name;
8588 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8589 		} else {
8590 			opt = (struct opthdr *)optcp;
8591 			optlevel = opt->level;
8592 			optname = opt->name;
8593 			next_optcp = optcp + opthdr_len +
8594 			    _TPI_ALIGN_OPT(opt->len);
8595 		}
8596 		if ((next_optcp < optcp) || /* wraparound pointer space */
8597 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8598 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8599 			return (B_FALSE); /* bad option buffer */
8600 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8601 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8602 			/*
8603 			 * Check to see if it's an all-bypass or all-zeroes
8604 			 * IPsec request.  Don't bother loading IPsec if
8605 			 * the socket doesn't want to use it.  (A good example
8606 			 * is a bypass request.)
8607 			 *
8608 			 * Basically, if any of the non-NEVER bits are set,
8609 			 * load IPsec.
8610 			 */
8611 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8612 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8613 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8614 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8615 			    != 0)
8616 				return (B_TRUE);
8617 		}
8618 	}
8619 	return (B_FALSE);
8620 }
8621 
8622 /*
8623  * If conn is is waiting for ipsec to finish loading, kick it.
8624  */
8625 /* ARGSUSED */
8626 static void
8627 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8628 {
8629 	t_scalar_t	optreq_prim;
8630 	mblk_t		*mp;
8631 	cred_t		*cr;
8632 	int		err = 0;
8633 
8634 	/*
8635 	 * This function is called, after ipsec loading is complete.
8636 	 * Since IP checks exclusively and atomically (i.e it prevents
8637 	 * ipsec load from completing until ip_optcom_req completes)
8638 	 * whether ipsec load is complete, there cannot be a race with IP
8639 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8640 	 */
8641 	mutex_enter(&connp->conn_lock);
8642 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8643 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8644 		mp = connp->conn_ipsec_opt_mp;
8645 		connp->conn_ipsec_opt_mp = NULL;
8646 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8647 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8648 		mutex_exit(&connp->conn_lock);
8649 
8650 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8651 
8652 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8653 		if (optreq_prim == T_OPTMGMT_REQ) {
8654 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8655 			    &ip_opt_obj);
8656 		} else {
8657 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8658 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8659 			    &ip_opt_obj);
8660 		}
8661 		if (err != EINPROGRESS)
8662 			CONN_OPER_PENDING_DONE(connp);
8663 		return;
8664 	}
8665 	mutex_exit(&connp->conn_lock);
8666 }
8667 
8668 /*
8669  * Called from the ipsec_loader thread, outside any perimeter, to tell
8670  * ip qenable any of the queues waiting for the ipsec loader to
8671  * complete.
8672  *
8673  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8674  * are done with this lock held, so it's guaranteed that none of the
8675  * links will change along the way.
8676  */
8677 void
8678 ip_ipsec_load_complete()
8679 {
8680 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8681 }
8682 
8683 /*
8684  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8685  * determines the grp on which it has to become exclusive, queues the mp
8686  * and sq draining restarts the optmgmt
8687  */
8688 static boolean_t
8689 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8690 {
8691 	conn_t *connp;
8692 
8693 	/*
8694 	 * Take IPsec requests and treat them special.
8695 	 */
8696 	if (ipsec_opt_present(mp)) {
8697 		/* First check if IPsec is loaded. */
8698 		mutex_enter(&ipsec_loader_lock);
8699 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8700 			mutex_exit(&ipsec_loader_lock);
8701 			return (B_FALSE);
8702 		}
8703 		connp = Q_TO_CONN(q);
8704 		mutex_enter(&connp->conn_lock);
8705 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8706 
8707 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8708 		connp->conn_ipsec_opt_mp = mp;
8709 		mutex_exit(&connp->conn_lock);
8710 		mutex_exit(&ipsec_loader_lock);
8711 
8712 		ipsec_loader_loadnow();
8713 		return (B_TRUE);
8714 	}
8715 	return (B_FALSE);
8716 }
8717 
8718 /*
8719  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8720  * all of them are copied to the conn_t. If the req is "zero", the policy is
8721  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8722  * fields.
8723  * We keep only the latest setting of the policy and thus policy setting
8724  * is not incremental/cumulative.
8725  *
8726  * Requests to set policies with multiple alternative actions will
8727  * go through a different API.
8728  */
8729 int
8730 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8731 {
8732 	uint_t ah_req = 0;
8733 	uint_t esp_req = 0;
8734 	uint_t se_req = 0;
8735 	ipsec_selkey_t sel;
8736 	ipsec_act_t *actp = NULL;
8737 	uint_t nact;
8738 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8739 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8740 	ipsec_policy_root_t *pr;
8741 	ipsec_policy_head_t *ph;
8742 	int fam;
8743 	boolean_t is_pol_reset;
8744 	int error = 0;
8745 
8746 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8747 
8748 	/*
8749 	 * The IP_SEC_OPT option does not allow variable length parameters,
8750 	 * hence a request cannot be NULL.
8751 	 */
8752 	if (req == NULL)
8753 		return (EINVAL);
8754 
8755 	ah_req = req->ipsr_ah_req;
8756 	esp_req = req->ipsr_esp_req;
8757 	se_req = req->ipsr_self_encap_req;
8758 
8759 	/*
8760 	 * Are we dealing with a request to reset the policy (i.e.
8761 	 * zero requests).
8762 	 */
8763 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8764 	    (esp_req & REQ_MASK) == 0 &&
8765 	    (se_req & REQ_MASK) == 0);
8766 
8767 	if (!is_pol_reset) {
8768 		/*
8769 		 * If we couldn't load IPsec, fail with "protocol
8770 		 * not supported".
8771 		 * IPsec may not have been loaded for a request with zero
8772 		 * policies, so we don't fail in this case.
8773 		 */
8774 		mutex_enter(&ipsec_loader_lock);
8775 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8776 			mutex_exit(&ipsec_loader_lock);
8777 			return (EPROTONOSUPPORT);
8778 		}
8779 		mutex_exit(&ipsec_loader_lock);
8780 
8781 		/*
8782 		 * Test for valid requests. Invalid algorithms
8783 		 * need to be tested by IPSEC code because new
8784 		 * algorithms can be added dynamically.
8785 		 */
8786 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8787 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8788 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8789 			return (EINVAL);
8790 		}
8791 
8792 		/*
8793 		 * Only privileged users can issue these
8794 		 * requests.
8795 		 */
8796 		if (((ah_req & IPSEC_PREF_NEVER) ||
8797 		    (esp_req & IPSEC_PREF_NEVER) ||
8798 		    (se_req & IPSEC_PREF_NEVER)) &&
8799 		    secpolicy_net_config(cr, B_FALSE) != 0) {
8800 			return (EPERM);
8801 		}
8802 
8803 		/*
8804 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
8805 		 * are mutually exclusive.
8806 		 */
8807 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
8808 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
8809 		    ((se_req & REQ_MASK) == REQ_MASK)) {
8810 			/* Both of them are set */
8811 			return (EINVAL);
8812 		}
8813 	}
8814 
8815 	mutex_enter(&connp->conn_lock);
8816 
8817 	/*
8818 	 * If we have already cached policies in ip_bind_connected*(), don't
8819 	 * let them change now. We cache policies for connections
8820 	 * whose src,dst [addr, port] is known.  The exception to this is
8821 	 * tunnels.  Tunnels are allowed to change policies after having
8822 	 * become fully bound.
8823 	 */
8824 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
8825 		mutex_exit(&connp->conn_lock);
8826 		return (EINVAL);
8827 	}
8828 
8829 	/*
8830 	 * We have a zero policies, reset the connection policy if already
8831 	 * set. This will cause the connection to inherit the
8832 	 * global policy, if any.
8833 	 */
8834 	if (is_pol_reset) {
8835 		if (connp->conn_policy != NULL) {
8836 			IPPH_REFRELE(connp->conn_policy);
8837 			connp->conn_policy = NULL;
8838 		}
8839 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
8840 		connp->conn_in_enforce_policy = B_FALSE;
8841 		connp->conn_out_enforce_policy = B_FALSE;
8842 		mutex_exit(&connp->conn_lock);
8843 		return (0);
8844 	}
8845 
8846 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
8847 	if (ph == NULL)
8848 		goto enomem;
8849 
8850 	ipsec_actvec_from_req(req, &actp, &nact);
8851 	if (actp == NULL)
8852 		goto enomem;
8853 
8854 	/*
8855 	 * Always allocate IPv4 policy entries, since they can also
8856 	 * apply to ipv6 sockets being used in ipv4-compat mode.
8857 	 */
8858 	bzero(&sel, sizeof (sel));
8859 	sel.ipsl_valid = IPSL_IPV4;
8860 
8861 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8862 	if (pin4 == NULL)
8863 		goto enomem;
8864 
8865 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8866 	if (pout4 == NULL)
8867 		goto enomem;
8868 
8869 	if (connp->conn_pkt_isv6) {
8870 		/*
8871 		 * We're looking at a v6 socket, also allocate the
8872 		 * v6-specific entries...
8873 		 */
8874 		sel.ipsl_valid = IPSL_IPV6;
8875 		pin6 = ipsec_policy_create(&sel, actp, nact,
8876 		    IPSEC_PRIO_SOCKET);
8877 		if (pin6 == NULL)
8878 			goto enomem;
8879 
8880 		pout6 = ipsec_policy_create(&sel, actp, nact,
8881 		    IPSEC_PRIO_SOCKET);
8882 		if (pout6 == NULL)
8883 			goto enomem;
8884 
8885 		/*
8886 		 * .. and file them away in the right place.
8887 		 */
8888 		fam = IPSEC_AF_V6;
8889 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8890 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
8891 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
8892 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8893 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
8894 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
8895 	}
8896 
8897 	ipsec_actvec_free(actp, nact);
8898 
8899 	/*
8900 	 * File the v4 policies.
8901 	 */
8902 	fam = IPSEC_AF_V4;
8903 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8904 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
8905 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
8906 
8907 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8908 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
8909 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
8910 
8911 	/*
8912 	 * If the requests need security, set enforce_policy.
8913 	 * If the requests are IPSEC_PREF_NEVER, one should
8914 	 * still set conn_out_enforce_policy so that an ipsec_out
8915 	 * gets attached in ip_wput. This is needed so that
8916 	 * for connections that we don't cache policy in ip_bind,
8917 	 * if global policy matches in ip_wput_attach_policy, we
8918 	 * don't wrongly inherit global policy. Similarly, we need
8919 	 * to set conn_in_enforce_policy also so that we don't verify
8920 	 * policy wrongly.
8921 	 */
8922 	if ((ah_req & REQ_MASK) != 0 ||
8923 	    (esp_req & REQ_MASK) != 0 ||
8924 	    (se_req & REQ_MASK) != 0) {
8925 		connp->conn_in_enforce_policy = B_TRUE;
8926 		connp->conn_out_enforce_policy = B_TRUE;
8927 		connp->conn_flags |= IPCL_CHECK_POLICY;
8928 	}
8929 
8930 	/*
8931 	 * Tunnels are allowed to set policy after having been fully bound.
8932 	 * If that's the case, cache policy here.
8933 	 */
8934 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
8935 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
8936 
8937 	mutex_exit(&connp->conn_lock);
8938 	return (error);
8939 #undef REQ_MASK
8940 
8941 	/*
8942 	 * Common memory-allocation-failure exit path.
8943 	 */
8944 enomem:
8945 	mutex_exit(&connp->conn_lock);
8946 	if (actp != NULL)
8947 		ipsec_actvec_free(actp, nact);
8948 	if (pin4 != NULL)
8949 		IPPOL_REFRELE(pin4);
8950 	if (pout4 != NULL)
8951 		IPPOL_REFRELE(pout4);
8952 	if (pin6 != NULL)
8953 		IPPOL_REFRELE(pin6);
8954 	if (pout6 != NULL)
8955 		IPPOL_REFRELE(pout6);
8956 	return (ENOMEM);
8957 }
8958 
8959 /*
8960  * Only for options that pass in an IP addr. Currently only V4 options
8961  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
8962  * So this function assumes level is IPPROTO_IP
8963  */
8964 int
8965 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
8966     mblk_t *first_mp)
8967 {
8968 	ipif_t *ipif = NULL;
8969 	int error;
8970 	ill_t *ill;
8971 
8972 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
8973 
8974 	if (addr != INADDR_ANY || checkonly) {
8975 		ASSERT(connp != NULL);
8976 		ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
8977 		    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt, &error);
8978 		if (ipif == NULL) {
8979 			if (error == EINPROGRESS)
8980 				return (error);
8981 			else if (option == IP_MULTICAST_IF)
8982 				return (EHOSTUNREACH);
8983 			else
8984 				return (EINVAL);
8985 		} else if (checkonly) {
8986 			if (option == IP_MULTICAST_IF) {
8987 				ill = ipif->ipif_ill;
8988 				/* not supported by the virtual network iface */
8989 				if (IS_VNI(ill)) {
8990 					ipif_refrele(ipif);
8991 					return (EINVAL);
8992 				}
8993 			}
8994 			ipif_refrele(ipif);
8995 			return (0);
8996 		}
8997 		ill = ipif->ipif_ill;
8998 		mutex_enter(&connp->conn_lock);
8999 		mutex_enter(&ill->ill_lock);
9000 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9001 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9002 			mutex_exit(&ill->ill_lock);
9003 			mutex_exit(&connp->conn_lock);
9004 			ipif_refrele(ipif);
9005 			return (option == IP_MULTICAST_IF ?
9006 			    EHOSTUNREACH : EINVAL);
9007 		}
9008 	} else {
9009 		mutex_enter(&connp->conn_lock);
9010 	}
9011 
9012 	/* None of the options below are supported on the VNI */
9013 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9014 		mutex_exit(&ill->ill_lock);
9015 		mutex_exit(&connp->conn_lock);
9016 		ipif_refrele(ipif);
9017 		return (EINVAL);
9018 	}
9019 
9020 	switch (option) {
9021 	case IP_DONTFAILOVER_IF:
9022 		/*
9023 		 * This option is used by in.mpathd to ensure
9024 		 * that IPMP probe packets only go out on the
9025 		 * test interfaces. in.mpathd sets this option
9026 		 * on the non-failover interfaces.
9027 		 * For backward compatibility, this option
9028 		 * implicitly sets IP_MULTICAST_IF, as used
9029 		 * be done in bind(), so that ip_wput gets
9030 		 * this ipif to send mcast packets.
9031 		 */
9032 		if (ipif != NULL) {
9033 			ASSERT(addr != INADDR_ANY);
9034 			connp->conn_nofailover_ill = ipif->ipif_ill;
9035 			connp->conn_multicast_ipif = ipif;
9036 		} else {
9037 			ASSERT(addr == INADDR_ANY);
9038 			connp->conn_nofailover_ill = NULL;
9039 			connp->conn_multicast_ipif = NULL;
9040 		}
9041 		break;
9042 
9043 	case IP_MULTICAST_IF:
9044 		connp->conn_multicast_ipif = ipif;
9045 		break;
9046 	}
9047 
9048 	if (ipif != NULL) {
9049 		mutex_exit(&ill->ill_lock);
9050 		mutex_exit(&connp->conn_lock);
9051 		ipif_refrele(ipif);
9052 		return (0);
9053 	}
9054 	mutex_exit(&connp->conn_lock);
9055 	/* We succeded in cleared the option */
9056 	return (0);
9057 }
9058 
9059 /*
9060  * For options that pass in an ifindex specifying the ill. V6 options always
9061  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9062  */
9063 int
9064 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9065     int level, int option, mblk_t *first_mp)
9066 {
9067 	ill_t *ill = NULL;
9068 	int error = 0;
9069 
9070 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9071 	if (ifindex != 0) {
9072 		ASSERT(connp != NULL);
9073 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9074 		    first_mp, ip_restart_optmgmt, &error);
9075 		if (ill != NULL) {
9076 			if (checkonly) {
9077 				/* not supported by the virtual network iface */
9078 				if (IS_VNI(ill)) {
9079 					ill_refrele(ill);
9080 					return (EINVAL);
9081 				}
9082 				ill_refrele(ill);
9083 				return (0);
9084 			}
9085 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9086 			    0, NULL)) {
9087 				ill_refrele(ill);
9088 				ill = NULL;
9089 				mutex_enter(&connp->conn_lock);
9090 				goto setit;
9091 			}
9092 			mutex_enter(&connp->conn_lock);
9093 			mutex_enter(&ill->ill_lock);
9094 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9095 				mutex_exit(&ill->ill_lock);
9096 				mutex_exit(&connp->conn_lock);
9097 				ill_refrele(ill);
9098 				ill = NULL;
9099 				mutex_enter(&connp->conn_lock);
9100 			}
9101 			goto setit;
9102 		} else if (error == EINPROGRESS) {
9103 			return (error);
9104 		} else {
9105 			error = 0;
9106 		}
9107 	}
9108 	mutex_enter(&connp->conn_lock);
9109 setit:
9110 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9111 
9112 	/*
9113 	 * The options below assume that the ILL (if any) transmits and/or
9114 	 * receives traffic. Neither of which is true for the virtual network
9115 	 * interface, so fail setting these on a VNI.
9116 	 */
9117 	if (IS_VNI(ill)) {
9118 		ASSERT(ill != NULL);
9119 		mutex_exit(&ill->ill_lock);
9120 		mutex_exit(&connp->conn_lock);
9121 		ill_refrele(ill);
9122 		return (EINVAL);
9123 	}
9124 
9125 	if (level == IPPROTO_IP) {
9126 		switch (option) {
9127 		case IP_BOUND_IF:
9128 			connp->conn_incoming_ill = ill;
9129 			connp->conn_outgoing_ill = ill;
9130 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9131 			    0 : ifindex;
9132 			break;
9133 
9134 		case IP_XMIT_IF:
9135 			/*
9136 			 * Similar to IP_BOUND_IF, but this only
9137 			 * determines the outgoing interface for
9138 			 * unicast packets. Also no IRE_CACHE entry
9139 			 * is added for the destination of the
9140 			 * outgoing packets. This feature is needed
9141 			 * for mobile IP.
9142 			 */
9143 			connp->conn_xmit_if_ill = ill;
9144 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9145 			    0 : ifindex;
9146 			break;
9147 
9148 		case IP_MULTICAST_IF:
9149 			/*
9150 			 * This option is an internal special. The socket
9151 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9152 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9153 			 * specifies an ifindex and we try first on V6 ill's.
9154 			 * If we don't find one, we they try using on v4 ill's
9155 			 * intenally and we come here.
9156 			 */
9157 			if (!checkonly && ill != NULL) {
9158 				ipif_t	*ipif;
9159 				ipif = ill->ill_ipif;
9160 
9161 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9162 					mutex_exit(&ill->ill_lock);
9163 					mutex_exit(&connp->conn_lock);
9164 					ill_refrele(ill);
9165 					ill = NULL;
9166 					mutex_enter(&connp->conn_lock);
9167 				} else {
9168 					connp->conn_multicast_ipif = ipif;
9169 				}
9170 			}
9171 			break;
9172 		}
9173 	} else {
9174 		switch (option) {
9175 		case IPV6_BOUND_IF:
9176 			connp->conn_incoming_ill = ill;
9177 			connp->conn_outgoing_ill = ill;
9178 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9179 			    0 : ifindex;
9180 			break;
9181 
9182 		case IPV6_BOUND_PIF:
9183 			/*
9184 			 * Limit all transmit to this ill.
9185 			 * Unlike IPV6_BOUND_IF, using this option
9186 			 * prevents load spreading and failover from
9187 			 * happening when the interface is part of the
9188 			 * group. That's why we don't need to remember
9189 			 * the ifindex in orig_bound_ifindex as in
9190 			 * IPV6_BOUND_IF.
9191 			 */
9192 			connp->conn_outgoing_pill = ill;
9193 			break;
9194 
9195 		case IPV6_DONTFAILOVER_IF:
9196 			/*
9197 			 * This option is used by in.mpathd to ensure
9198 			 * that IPMP probe packets only go out on the
9199 			 * test interfaces. in.mpathd sets this option
9200 			 * on the non-failover interfaces.
9201 			 */
9202 			connp->conn_nofailover_ill = ill;
9203 			/*
9204 			 * For backward compatibility, this option
9205 			 * implicitly sets ip_multicast_ill as used in
9206 			 * IP_MULTICAST_IF so that ip_wput gets
9207 			 * this ipif to send mcast packets.
9208 			 */
9209 			connp->conn_multicast_ill = ill;
9210 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9211 			    0 : ifindex;
9212 			break;
9213 
9214 		case IPV6_MULTICAST_IF:
9215 			/*
9216 			 * Set conn_multicast_ill to be the IPv6 ill.
9217 			 * Set conn_multicast_ipif to be an IPv4 ipif
9218 			 * for ifindex to make IPv4 mapped addresses
9219 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9220 			 * Even if no IPv6 ill exists for the ifindex
9221 			 * we need to check for an IPv4 ifindex in order
9222 			 * for this to work with mapped addresses. In that
9223 			 * case only set conn_multicast_ipif.
9224 			 */
9225 			if (!checkonly) {
9226 				if (ifindex == 0) {
9227 					connp->conn_multicast_ill = NULL;
9228 					connp->conn_orig_multicast_ifindex = 0;
9229 					connp->conn_multicast_ipif = NULL;
9230 				} else if (ill != NULL) {
9231 					connp->conn_multicast_ill = ill;
9232 					connp->conn_orig_multicast_ifindex =
9233 					    ifindex;
9234 				}
9235 			}
9236 			break;
9237 		}
9238 	}
9239 
9240 	if (ill != NULL) {
9241 		mutex_exit(&ill->ill_lock);
9242 		mutex_exit(&connp->conn_lock);
9243 		ill_refrele(ill);
9244 		return (0);
9245 	}
9246 	mutex_exit(&connp->conn_lock);
9247 	/*
9248 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9249 	 * locate the ill and could not set the option (ifindex != 0)
9250 	 */
9251 	return (ifindex == 0 ? 0 : EINVAL);
9252 }
9253 
9254 /* This routine sets socket options. */
9255 /* ARGSUSED */
9256 int
9257 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9258     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9259     void *dummy, cred_t *cr, mblk_t *first_mp)
9260 {
9261 	int		*i1 = (int *)invalp;
9262 	conn_t		*connp = Q_TO_CONN(q);
9263 	int		error = 0;
9264 	boolean_t	checkonly;
9265 	ire_t		*ire;
9266 	boolean_t	found;
9267 
9268 	switch (optset_context) {
9269 
9270 	case SETFN_OPTCOM_CHECKONLY:
9271 		checkonly = B_TRUE;
9272 		/*
9273 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9274 		 * inlen != 0 implies value supplied and
9275 		 * 	we have to "pretend" to set it.
9276 		 * inlen == 0 implies that there is no
9277 		 * 	value part in T_CHECK request and just validation
9278 		 * done elsewhere should be enough, we just return here.
9279 		 */
9280 		if (inlen == 0) {
9281 			*outlenp = 0;
9282 			return (0);
9283 		}
9284 		break;
9285 	case SETFN_OPTCOM_NEGOTIATE:
9286 	case SETFN_UD_NEGOTIATE:
9287 	case SETFN_CONN_NEGOTIATE:
9288 		checkonly = B_FALSE;
9289 		break;
9290 	default:
9291 		/*
9292 		 * We should never get here
9293 		 */
9294 		*outlenp = 0;
9295 		return (EINVAL);
9296 	}
9297 
9298 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9299 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9300 
9301 	/*
9302 	 * For fixed length options, no sanity check
9303 	 * of passed in length is done. It is assumed *_optcom_req()
9304 	 * routines do the right thing.
9305 	 */
9306 
9307 	switch (level) {
9308 	case SOL_SOCKET:
9309 		/*
9310 		 * conn_lock protects the bitfields, and is used to
9311 		 * set the fields atomically.
9312 		 */
9313 		switch (name) {
9314 		case SO_BROADCAST:
9315 			if (!checkonly) {
9316 				/* TODO: use value someplace? */
9317 				mutex_enter(&connp->conn_lock);
9318 				connp->conn_broadcast = *i1 ? 1 : 0;
9319 				mutex_exit(&connp->conn_lock);
9320 			}
9321 			break;	/* goto sizeof (int) option return */
9322 		case SO_USELOOPBACK:
9323 			if (!checkonly) {
9324 				/* TODO: use value someplace? */
9325 				mutex_enter(&connp->conn_lock);
9326 				connp->conn_loopback = *i1 ? 1 : 0;
9327 				mutex_exit(&connp->conn_lock);
9328 			}
9329 			break;	/* goto sizeof (int) option return */
9330 		case SO_DONTROUTE:
9331 			if (!checkonly) {
9332 				mutex_enter(&connp->conn_lock);
9333 				connp->conn_dontroute = *i1 ? 1 : 0;
9334 				mutex_exit(&connp->conn_lock);
9335 			}
9336 			break;	/* goto sizeof (int) option return */
9337 		case SO_REUSEADDR:
9338 			if (!checkonly) {
9339 				mutex_enter(&connp->conn_lock);
9340 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9341 				mutex_exit(&connp->conn_lock);
9342 			}
9343 			break;	/* goto sizeof (int) option return */
9344 		case SO_PROTOTYPE:
9345 			if (!checkonly) {
9346 				mutex_enter(&connp->conn_lock);
9347 				connp->conn_proto = *i1;
9348 				mutex_exit(&connp->conn_lock);
9349 			}
9350 			break;	/* goto sizeof (int) option return */
9351 		default:
9352 			/*
9353 			 * "soft" error (negative)
9354 			 * option not handled at this level
9355 			 * Note: Do not modify *outlenp
9356 			 */
9357 			return (-EINVAL);
9358 		}
9359 		break;
9360 	case IPPROTO_IP:
9361 		switch (name) {
9362 		case IP_MULTICAST_IF:
9363 		case IP_DONTFAILOVER_IF: {
9364 			ipaddr_t addr = *i1;
9365 
9366 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9367 			    first_mp);
9368 			if (error != 0)
9369 				return (error);
9370 			break;	/* goto sizeof (int) option return */
9371 		}
9372 
9373 		case IP_MULTICAST_TTL:
9374 			/* Recorded in transport above IP */
9375 			*outvalp = *invalp;
9376 			*outlenp = sizeof (uchar_t);
9377 			return (0);
9378 		case IP_MULTICAST_LOOP:
9379 			if (!checkonly) {
9380 				mutex_enter(&connp->conn_lock);
9381 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9382 				mutex_exit(&connp->conn_lock);
9383 			}
9384 			*outvalp = *invalp;
9385 			*outlenp = sizeof (uchar_t);
9386 			return (0);
9387 		case IP_ADD_MEMBERSHIP:
9388 		case MCAST_JOIN_GROUP:
9389 		case IP_DROP_MEMBERSHIP:
9390 		case MCAST_LEAVE_GROUP: {
9391 			struct ip_mreq *mreqp;
9392 			struct group_req *greqp;
9393 			ire_t *ire;
9394 			boolean_t done = B_FALSE;
9395 			ipaddr_t group, ifaddr;
9396 			struct sockaddr_in *sin;
9397 			uint32_t *ifindexp;
9398 			boolean_t mcast_opt = B_TRUE;
9399 			mcast_record_t fmode;
9400 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9401 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9402 
9403 			switch (name) {
9404 			case IP_ADD_MEMBERSHIP:
9405 				mcast_opt = B_FALSE;
9406 				/* FALLTHRU */
9407 			case MCAST_JOIN_GROUP:
9408 				fmode = MODE_IS_EXCLUDE;
9409 				optfn = ip_opt_add_group;
9410 				break;
9411 
9412 			case IP_DROP_MEMBERSHIP:
9413 				mcast_opt = B_FALSE;
9414 				/* FALLTHRU */
9415 			case MCAST_LEAVE_GROUP:
9416 				fmode = MODE_IS_INCLUDE;
9417 				optfn = ip_opt_delete_group;
9418 				break;
9419 			}
9420 
9421 			if (mcast_opt) {
9422 				greqp = (struct group_req *)i1;
9423 				sin = (struct sockaddr_in *)&greqp->gr_group;
9424 				if (sin->sin_family != AF_INET) {
9425 					*outlenp = 0;
9426 					return (ENOPROTOOPT);
9427 				}
9428 				group = (ipaddr_t)sin->sin_addr.s_addr;
9429 				ifaddr = INADDR_ANY;
9430 				ifindexp = &greqp->gr_interface;
9431 			} else {
9432 				mreqp = (struct ip_mreq *)i1;
9433 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9434 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9435 				ifindexp = NULL;
9436 			}
9437 
9438 			/*
9439 			 * In the multirouting case, we need to replicate
9440 			 * the request on all interfaces that will take part
9441 			 * in replication.  We do so because multirouting is
9442 			 * reflective, thus we will probably receive multi-
9443 			 * casts on those interfaces.
9444 			 * The ip_multirt_apply_membership() succeeds if the
9445 			 * operation succeeds on at least one interface.
9446 			 */
9447 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9448 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9449 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9450 			if (ire != NULL) {
9451 				if (ire->ire_flags & RTF_MULTIRT) {
9452 					error = ip_multirt_apply_membership(
9453 					    optfn, ire, connp, checkonly, group,
9454 					    fmode, INADDR_ANY, first_mp);
9455 					done = B_TRUE;
9456 				}
9457 				ire_refrele(ire);
9458 			}
9459 			if (!done) {
9460 				error = optfn(connp, checkonly, group, ifaddr,
9461 				    ifindexp, fmode, INADDR_ANY, first_mp);
9462 			}
9463 			if (error) {
9464 				/*
9465 				 * EINPROGRESS is a soft error, needs retry
9466 				 * so don't make *outlenp zero.
9467 				 */
9468 				if (error != EINPROGRESS)
9469 					*outlenp = 0;
9470 				return (error);
9471 			}
9472 			/* OK return - copy input buffer into output buffer */
9473 			if (invalp != outvalp) {
9474 				/* don't trust bcopy for identical src/dst */
9475 				bcopy(invalp, outvalp, inlen);
9476 			}
9477 			*outlenp = inlen;
9478 			return (0);
9479 		}
9480 		case IP_BLOCK_SOURCE:
9481 		case IP_UNBLOCK_SOURCE:
9482 		case IP_ADD_SOURCE_MEMBERSHIP:
9483 		case IP_DROP_SOURCE_MEMBERSHIP:
9484 		case MCAST_BLOCK_SOURCE:
9485 		case MCAST_UNBLOCK_SOURCE:
9486 		case MCAST_JOIN_SOURCE_GROUP:
9487 		case MCAST_LEAVE_SOURCE_GROUP: {
9488 			struct ip_mreq_source *imreqp;
9489 			struct group_source_req *gsreqp;
9490 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9491 			uint32_t ifindex = 0;
9492 			mcast_record_t fmode;
9493 			struct sockaddr_in *sin;
9494 			ire_t *ire;
9495 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9496 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9497 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9498 
9499 			switch (name) {
9500 			case IP_BLOCK_SOURCE:
9501 				mcast_opt = B_FALSE;
9502 				/* FALLTHRU */
9503 			case MCAST_BLOCK_SOURCE:
9504 				fmode = MODE_IS_EXCLUDE;
9505 				optfn = ip_opt_add_group;
9506 				break;
9507 
9508 			case IP_UNBLOCK_SOURCE:
9509 				mcast_opt = B_FALSE;
9510 				/* FALLTHRU */
9511 			case MCAST_UNBLOCK_SOURCE:
9512 				fmode = MODE_IS_EXCLUDE;
9513 				optfn = ip_opt_delete_group;
9514 				break;
9515 
9516 			case IP_ADD_SOURCE_MEMBERSHIP:
9517 				mcast_opt = B_FALSE;
9518 				/* FALLTHRU */
9519 			case MCAST_JOIN_SOURCE_GROUP:
9520 				fmode = MODE_IS_INCLUDE;
9521 				optfn = ip_opt_add_group;
9522 				break;
9523 
9524 			case IP_DROP_SOURCE_MEMBERSHIP:
9525 				mcast_opt = B_FALSE;
9526 				/* FALLTHRU */
9527 			case MCAST_LEAVE_SOURCE_GROUP:
9528 				fmode = MODE_IS_INCLUDE;
9529 				optfn = ip_opt_delete_group;
9530 				break;
9531 			}
9532 
9533 			if (mcast_opt) {
9534 				gsreqp = (struct group_source_req *)i1;
9535 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9536 					*outlenp = 0;
9537 					return (ENOPROTOOPT);
9538 				}
9539 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9540 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9541 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9542 				src = (ipaddr_t)sin->sin_addr.s_addr;
9543 				ifindex = gsreqp->gsr_interface;
9544 			} else {
9545 				imreqp = (struct ip_mreq_source *)i1;
9546 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9547 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9548 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9549 			}
9550 
9551 			/*
9552 			 * In the multirouting case, we need to replicate
9553 			 * the request as noted in the mcast cases above.
9554 			 */
9555 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9556 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9557 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9558 			if (ire != NULL) {
9559 				if (ire->ire_flags & RTF_MULTIRT) {
9560 					error = ip_multirt_apply_membership(
9561 					    optfn, ire, connp, checkonly, grp,
9562 					    fmode, src, first_mp);
9563 					done = B_TRUE;
9564 				}
9565 				ire_refrele(ire);
9566 			}
9567 			if (!done) {
9568 				error = optfn(connp, checkonly, grp, ifaddr,
9569 				    &ifindex, fmode, src, first_mp);
9570 			}
9571 			if (error != 0) {
9572 				/*
9573 				 * EINPROGRESS is a soft error, needs retry
9574 				 * so don't make *outlenp zero.
9575 				 */
9576 				if (error != EINPROGRESS)
9577 					*outlenp = 0;
9578 				return (error);
9579 			}
9580 			/* OK return - copy input buffer into output buffer */
9581 			if (invalp != outvalp) {
9582 				bcopy(invalp, outvalp, inlen);
9583 			}
9584 			*outlenp = inlen;
9585 			return (0);
9586 		}
9587 		case IP_SEC_OPT:
9588 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9589 			if (error != 0) {
9590 				*outlenp = 0;
9591 				return (error);
9592 			}
9593 			break;
9594 		case IP_HDRINCL:
9595 		case IP_OPTIONS:
9596 		case T_IP_OPTIONS:
9597 		case IP_TOS:
9598 		case T_IP_TOS:
9599 		case IP_TTL:
9600 		case IP_RECVDSTADDR:
9601 		case IP_RECVOPTS:
9602 			/* OK return - copy input buffer into output buffer */
9603 			if (invalp != outvalp) {
9604 				/* don't trust bcopy for identical src/dst */
9605 				bcopy(invalp, outvalp, inlen);
9606 			}
9607 			*outlenp = inlen;
9608 			return (0);
9609 		case IP_RECVIF:
9610 			/* Retrieve the inbound interface index */
9611 			if (!checkonly) {
9612 				mutex_enter(&connp->conn_lock);
9613 				connp->conn_recvif = *i1 ? 1 : 0;
9614 				mutex_exit(&connp->conn_lock);
9615 			}
9616 			break;	/* goto sizeof (int) option return */
9617 		case IP_RECVSLLA:
9618 			/* Retrieve the source link layer address */
9619 			if (!checkonly) {
9620 				mutex_enter(&connp->conn_lock);
9621 				connp->conn_recvslla = *i1 ? 1 : 0;
9622 				mutex_exit(&connp->conn_lock);
9623 			}
9624 			break;	/* goto sizeof (int) option return */
9625 		case MRT_INIT:
9626 		case MRT_DONE:
9627 		case MRT_ADD_VIF:
9628 		case MRT_DEL_VIF:
9629 		case MRT_ADD_MFC:
9630 		case MRT_DEL_MFC:
9631 		case MRT_ASSERT:
9632 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9633 				*outlenp = 0;
9634 				return (error);
9635 			}
9636 			error = ip_mrouter_set((int)name, q, checkonly,
9637 			    (uchar_t *)invalp, inlen, first_mp);
9638 			if (error) {
9639 				*outlenp = 0;
9640 				return (error);
9641 			}
9642 			/* OK return - copy input buffer into output buffer */
9643 			if (invalp != outvalp) {
9644 				/* don't trust bcopy for identical src/dst */
9645 				bcopy(invalp, outvalp, inlen);
9646 			}
9647 			*outlenp = inlen;
9648 			return (0);
9649 		case IP_BOUND_IF:
9650 		case IP_XMIT_IF:
9651 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9652 			    level, name, first_mp);
9653 			if (error != 0)
9654 				return (error);
9655 			break; 		/* goto sizeof (int) option return */
9656 
9657 		case IP_UNSPEC_SRC:
9658 			/* Allow sending with a zero source address */
9659 			if (!checkonly) {
9660 				mutex_enter(&connp->conn_lock);
9661 				connp->conn_unspec_src = *i1 ? 1 : 0;
9662 				mutex_exit(&connp->conn_lock);
9663 			}
9664 			break;	/* goto sizeof (int) option return */
9665 		default:
9666 			/*
9667 			 * "soft" error (negative)
9668 			 * option not handled at this level
9669 			 * Note: Do not modify *outlenp
9670 			 */
9671 			return (-EINVAL);
9672 		}
9673 		break;
9674 	case IPPROTO_IPV6:
9675 		switch (name) {
9676 		case IPV6_BOUND_IF:
9677 		case IPV6_BOUND_PIF:
9678 		case IPV6_DONTFAILOVER_IF:
9679 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9680 			    level, name, first_mp);
9681 			if (error != 0)
9682 				return (error);
9683 			break; 		/* goto sizeof (int) option return */
9684 
9685 		case IPV6_MULTICAST_IF:
9686 			/*
9687 			 * The only possible errors are EINPROGRESS and
9688 			 * EINVAL. EINPROGRESS will be restarted and is not
9689 			 * a hard error. We call this option on both V4 and V6
9690 			 * If both return EINVAL, then this call returns
9691 			 * EINVAL. If at least one of them succeeds we
9692 			 * return success.
9693 			 */
9694 			found = B_FALSE;
9695 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9696 			    level, name, first_mp);
9697 			if (error == EINPROGRESS)
9698 				return (error);
9699 			if (error == 0)
9700 				found = B_TRUE;
9701 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9702 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9703 			if (error == 0)
9704 				found = B_TRUE;
9705 			if (!found)
9706 				return (error);
9707 			break; 		/* goto sizeof (int) option return */
9708 
9709 		case IPV6_MULTICAST_HOPS:
9710 			/* Recorded in transport above IP */
9711 			break;	/* goto sizeof (int) option return */
9712 		case IPV6_MULTICAST_LOOP:
9713 			if (!checkonly) {
9714 				mutex_enter(&connp->conn_lock);
9715 				connp->conn_multicast_loop = *i1;
9716 				mutex_exit(&connp->conn_lock);
9717 			}
9718 			break;	/* goto sizeof (int) option return */
9719 		case IPV6_JOIN_GROUP:
9720 		case MCAST_JOIN_GROUP:
9721 		case IPV6_LEAVE_GROUP:
9722 		case MCAST_LEAVE_GROUP: {
9723 			struct ipv6_mreq *ip_mreqp;
9724 			struct group_req *greqp;
9725 			ire_t *ire;
9726 			boolean_t done = B_FALSE;
9727 			in6_addr_t groupv6;
9728 			uint32_t ifindex;
9729 			boolean_t mcast_opt = B_TRUE;
9730 			mcast_record_t fmode;
9731 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9732 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9733 
9734 			switch (name) {
9735 			case IPV6_JOIN_GROUP:
9736 				mcast_opt = B_FALSE;
9737 				/* FALLTHRU */
9738 			case MCAST_JOIN_GROUP:
9739 				fmode = MODE_IS_EXCLUDE;
9740 				optfn = ip_opt_add_group_v6;
9741 				break;
9742 
9743 			case IPV6_LEAVE_GROUP:
9744 				mcast_opt = B_FALSE;
9745 				/* FALLTHRU */
9746 			case MCAST_LEAVE_GROUP:
9747 				fmode = MODE_IS_INCLUDE;
9748 				optfn = ip_opt_delete_group_v6;
9749 				break;
9750 			}
9751 
9752 			if (mcast_opt) {
9753 				struct sockaddr_in *sin;
9754 				struct sockaddr_in6 *sin6;
9755 				greqp = (struct group_req *)i1;
9756 				if (greqp->gr_group.ss_family == AF_INET) {
9757 					sin = (struct sockaddr_in *)
9758 					    &(greqp->gr_group);
9759 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9760 					    &groupv6);
9761 				} else {
9762 					sin6 = (struct sockaddr_in6 *)
9763 					    &(greqp->gr_group);
9764 					groupv6 = sin6->sin6_addr;
9765 				}
9766 				ifindex = greqp->gr_interface;
9767 			} else {
9768 				ip_mreqp = (struct ipv6_mreq *)i1;
9769 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9770 				ifindex = ip_mreqp->ipv6mr_interface;
9771 			}
9772 			/*
9773 			 * In the multirouting case, we need to replicate
9774 			 * the request on all interfaces that will take part
9775 			 * in replication.  We do so because multirouting is
9776 			 * reflective, thus we will probably receive multi-
9777 			 * casts on those interfaces.
9778 			 * The ip_multirt_apply_membership_v6() succeeds if
9779 			 * the operation succeeds on at least one interface.
9780 			 */
9781 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9782 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9783 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9784 			if (ire != NULL) {
9785 				if (ire->ire_flags & RTF_MULTIRT) {
9786 					error = ip_multirt_apply_membership_v6(
9787 					    optfn, ire, connp, checkonly,
9788 					    &groupv6, fmode, &ipv6_all_zeros,
9789 					    first_mp);
9790 					done = B_TRUE;
9791 				}
9792 				ire_refrele(ire);
9793 			}
9794 			if (!done) {
9795 				error = optfn(connp, checkonly, &groupv6,
9796 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
9797 			}
9798 			if (error) {
9799 				/*
9800 				 * EINPROGRESS is a soft error, needs retry
9801 				 * so don't make *outlenp zero.
9802 				 */
9803 				if (error != EINPROGRESS)
9804 					*outlenp = 0;
9805 				return (error);
9806 			}
9807 			/* OK return - copy input buffer into output buffer */
9808 			if (invalp != outvalp) {
9809 				/* don't trust bcopy for identical src/dst */
9810 				bcopy(invalp, outvalp, inlen);
9811 			}
9812 			*outlenp = inlen;
9813 			return (0);
9814 		}
9815 		case MCAST_BLOCK_SOURCE:
9816 		case MCAST_UNBLOCK_SOURCE:
9817 		case MCAST_JOIN_SOURCE_GROUP:
9818 		case MCAST_LEAVE_SOURCE_GROUP: {
9819 			struct group_source_req *gsreqp;
9820 			in6_addr_t v6grp, v6src;
9821 			uint32_t ifindex;
9822 			mcast_record_t fmode;
9823 			ire_t *ire;
9824 			boolean_t done = B_FALSE;
9825 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9826 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9827 
9828 			switch (name) {
9829 			case MCAST_BLOCK_SOURCE:
9830 				fmode = MODE_IS_EXCLUDE;
9831 				optfn = ip_opt_add_group_v6;
9832 				break;
9833 			case MCAST_UNBLOCK_SOURCE:
9834 				fmode = MODE_IS_EXCLUDE;
9835 				optfn = ip_opt_delete_group_v6;
9836 				break;
9837 			case MCAST_JOIN_SOURCE_GROUP:
9838 				fmode = MODE_IS_INCLUDE;
9839 				optfn = ip_opt_add_group_v6;
9840 				break;
9841 			case MCAST_LEAVE_SOURCE_GROUP:
9842 				fmode = MODE_IS_INCLUDE;
9843 				optfn = ip_opt_delete_group_v6;
9844 				break;
9845 			}
9846 
9847 			gsreqp = (struct group_source_req *)i1;
9848 			ifindex = gsreqp->gsr_interface;
9849 			if (gsreqp->gsr_group.ss_family == AF_INET) {
9850 				struct sockaddr_in *s;
9851 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
9852 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
9853 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
9854 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
9855 			} else {
9856 				struct sockaddr_in6 *s6;
9857 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
9858 				v6grp = s6->sin6_addr;
9859 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
9860 				v6src = s6->sin6_addr;
9861 			}
9862 
9863 			/*
9864 			 * In the multirouting case, we need to replicate
9865 			 * the request as noted in the mcast cases above.
9866 			 */
9867 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
9868 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9869 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9870 			if (ire != NULL) {
9871 				if (ire->ire_flags & RTF_MULTIRT) {
9872 					error = ip_multirt_apply_membership_v6(
9873 					    optfn, ire, connp, checkonly,
9874 					    &v6grp, fmode, &v6src, first_mp);
9875 					done = B_TRUE;
9876 				}
9877 				ire_refrele(ire);
9878 			}
9879 			if (!done) {
9880 				error = optfn(connp, checkonly, &v6grp,
9881 				    ifindex, fmode, &v6src, first_mp);
9882 			}
9883 			if (error != 0) {
9884 				/*
9885 				 * EINPROGRESS is a soft error, needs retry
9886 				 * so don't make *outlenp zero.
9887 				 */
9888 				if (error != EINPROGRESS)
9889 					*outlenp = 0;
9890 				return (error);
9891 			}
9892 			/* OK return - copy input buffer into output buffer */
9893 			if (invalp != outvalp) {
9894 				bcopy(invalp, outvalp, inlen);
9895 			}
9896 			*outlenp = inlen;
9897 			return (0);
9898 		}
9899 		case IPV6_UNICAST_HOPS:
9900 			/* Recorded in transport above IP */
9901 			break;	/* goto sizeof (int) option return */
9902 		case IPV6_UNSPEC_SRC:
9903 			/* Allow sending with a zero source address */
9904 			if (!checkonly) {
9905 				mutex_enter(&connp->conn_lock);
9906 				connp->conn_unspec_src = *i1 ? 1 : 0;
9907 				mutex_exit(&connp->conn_lock);
9908 			}
9909 			break;	/* goto sizeof (int) option return */
9910 		case IPV6_RECVPKTINFO:
9911 			if (!checkonly) {
9912 				mutex_enter(&connp->conn_lock);
9913 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
9914 				mutex_exit(&connp->conn_lock);
9915 			}
9916 			break;	/* goto sizeof (int) option return */
9917 		case IPV6_RECVTCLASS:
9918 			if (!checkonly) {
9919 				if (*i1 < 0 || *i1 > 1) {
9920 					return (EINVAL);
9921 				}
9922 				mutex_enter(&connp->conn_lock);
9923 				connp->conn_ipv6_recvtclass = *i1;
9924 				mutex_exit(&connp->conn_lock);
9925 			}
9926 			break;
9927 		case IPV6_RECVPATHMTU:
9928 			if (!checkonly) {
9929 				if (*i1 < 0 || *i1 > 1) {
9930 					return (EINVAL);
9931 				}
9932 				mutex_enter(&connp->conn_lock);
9933 				connp->conn_ipv6_recvpathmtu = *i1;
9934 				mutex_exit(&connp->conn_lock);
9935 			}
9936 			break;
9937 		case IPV6_RECVHOPLIMIT:
9938 			if (!checkonly) {
9939 				mutex_enter(&connp->conn_lock);
9940 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
9941 				mutex_exit(&connp->conn_lock);
9942 			}
9943 			break;	/* goto sizeof (int) option return */
9944 		case IPV6_RECVHOPOPTS:
9945 			if (!checkonly) {
9946 				mutex_enter(&connp->conn_lock);
9947 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
9948 				mutex_exit(&connp->conn_lock);
9949 			}
9950 			break;	/* goto sizeof (int) option return */
9951 		case IPV6_RECVDSTOPTS:
9952 			if (!checkonly) {
9953 				mutex_enter(&connp->conn_lock);
9954 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
9955 				mutex_exit(&connp->conn_lock);
9956 			}
9957 			break;	/* goto sizeof (int) option return */
9958 		case IPV6_RECVRTHDR:
9959 			if (!checkonly) {
9960 				mutex_enter(&connp->conn_lock);
9961 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
9962 				mutex_exit(&connp->conn_lock);
9963 			}
9964 			break;	/* goto sizeof (int) option return */
9965 		case IPV6_RECVRTHDRDSTOPTS:
9966 			if (!checkonly) {
9967 				mutex_enter(&connp->conn_lock);
9968 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
9969 				mutex_exit(&connp->conn_lock);
9970 			}
9971 			break;	/* goto sizeof (int) option return */
9972 		case IPV6_PKTINFO:
9973 			if (inlen == 0)
9974 				return (-EINVAL);	/* clearing option */
9975 			error = ip6_set_pktinfo(cr, connp,
9976 			    (struct in6_pktinfo *)invalp, first_mp);
9977 			if (error != 0)
9978 				*outlenp = 0;
9979 			else
9980 				*outlenp = inlen;
9981 			return (error);
9982 		case IPV6_NEXTHOP: {
9983 			struct sockaddr_in6 *sin6;
9984 
9985 			/* Verify that the nexthop is reachable */
9986 			if (inlen == 0)
9987 				return (-EINVAL);	/* clearing option */
9988 
9989 			sin6 = (struct sockaddr_in6 *)invalp;
9990 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
9991 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
9992 			    MATCH_IRE_DEFAULT);
9993 
9994 			if (ire == NULL) {
9995 				*outlenp = 0;
9996 				return (EHOSTUNREACH);
9997 			}
9998 			ire_refrele(ire);
9999 			return (-EINVAL);
10000 		}
10001 		case IPV6_SEC_OPT:
10002 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10003 			if (error != 0) {
10004 				*outlenp = 0;
10005 				return (error);
10006 			}
10007 			break;
10008 		case IPV6_SRC_PREFERENCES: {
10009 			/*
10010 			 * This is implemented strictly in the ip module
10011 			 * (here and in tcp_opt_*() to accomodate tcp
10012 			 * sockets).  Modules above ip pass this option
10013 			 * down here since ip is the only one that needs to
10014 			 * be aware of source address preferences.
10015 			 *
10016 			 * This socket option only affects connected
10017 			 * sockets that haven't already bound to a specific
10018 			 * IPv6 address.  In other words, sockets that
10019 			 * don't call bind() with an address other than the
10020 			 * unspecified address and that call connect().
10021 			 * ip_bind_connected_v6() passes these preferences
10022 			 * to the ipif_select_source_v6() function.
10023 			 */
10024 			if (inlen != sizeof (uint32_t))
10025 				return (EINVAL);
10026 			error = ip6_set_src_preferences(connp,
10027 			    *(uint32_t *)invalp);
10028 			if (error != 0) {
10029 				*outlenp = 0;
10030 				return (error);
10031 			} else {
10032 				*outlenp = sizeof (uint32_t);
10033 			}
10034 			break;
10035 		}
10036 		case IPV6_V6ONLY:
10037 			if (*i1 < 0 || *i1 > 1) {
10038 				return (EINVAL);
10039 			}
10040 			mutex_enter(&connp->conn_lock);
10041 			connp->conn_ipv6_v6only = *i1;
10042 			mutex_exit(&connp->conn_lock);
10043 			break;
10044 		default:
10045 			return (-EINVAL);
10046 		}
10047 		break;
10048 	default:
10049 		/*
10050 		 * "soft" error (negative)
10051 		 * option not handled at this level
10052 		 * Note: Do not modify *outlenp
10053 		 */
10054 		return (-EINVAL);
10055 	}
10056 	/*
10057 	 * Common case of return from an option that is sizeof (int)
10058 	 */
10059 	*(int *)outvalp = *i1;
10060 	*outlenp = sizeof (int);
10061 	return (0);
10062 }
10063 
10064 /*
10065  * This routine gets default values of certain options whose default
10066  * values are maintained by protocol specific code
10067  */
10068 /* ARGSUSED */
10069 int
10070 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10071 {
10072 	int *i1 = (int *)ptr;
10073 
10074 	switch (level) {
10075 	case IPPROTO_IP:
10076 		switch (name) {
10077 		case IP_MULTICAST_TTL:
10078 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10079 			return (sizeof (uchar_t));
10080 		case IP_MULTICAST_LOOP:
10081 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10082 			return (sizeof (uchar_t));
10083 		default:
10084 			return (-1);
10085 		}
10086 	case IPPROTO_IPV6:
10087 		switch (name) {
10088 		case IPV6_UNICAST_HOPS:
10089 			*i1 = ipv6_def_hops;
10090 			return (sizeof (int));
10091 		case IPV6_MULTICAST_HOPS:
10092 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10093 			return (sizeof (int));
10094 		case IPV6_MULTICAST_LOOP:
10095 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10096 			return (sizeof (int));
10097 		case IPV6_V6ONLY:
10098 			*i1 = 1;
10099 			return (sizeof (int));
10100 		default:
10101 			return (-1);
10102 		}
10103 	default:
10104 		return (-1);
10105 	}
10106 	/* NOTREACHED */
10107 }
10108 
10109 /*
10110  * Given a destination address and a pointer to where to put the information
10111  * this routine fills in the mtuinfo.
10112  */
10113 int
10114 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10115     struct ip6_mtuinfo *mtuinfo)
10116 {
10117 	ire_t *ire;
10118 
10119 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10120 		return (-1);
10121 
10122 	bzero(mtuinfo, sizeof (*mtuinfo));
10123 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10124 	mtuinfo->ip6m_addr.sin6_port = port;
10125 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10126 
10127 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10128 	if (ire != NULL) {
10129 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10130 		ire_refrele(ire);
10131 	} else {
10132 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10133 	}
10134 	return (sizeof (struct ip6_mtuinfo));
10135 }
10136 
10137 /*
10138  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10139  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10140  * isn't.  This doesn't matter as the error checking is done properly for the
10141  * other MRT options coming in through ip_opt_set.
10142  */
10143 int
10144 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10145 {
10146 	conn_t		*connp = Q_TO_CONN(q);
10147 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10148 
10149 	switch (level) {
10150 	case IPPROTO_IP:
10151 		switch (name) {
10152 		case MRT_VERSION:
10153 		case MRT_ASSERT:
10154 			(void) ip_mrouter_get(name, q, ptr);
10155 			return (sizeof (int));
10156 		case IP_SEC_OPT:
10157 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10158 		default:
10159 			break;
10160 		}
10161 		break;
10162 	case IPPROTO_IPV6:
10163 		switch (name) {
10164 		case IPV6_SEC_OPT:
10165 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10166 		case IPV6_SRC_PREFERENCES: {
10167 			return (ip6_get_src_preferences(connp,
10168 			    (uint32_t *)ptr));
10169 		}
10170 		case IPV6_V6ONLY:
10171 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10172 			return (sizeof (int));
10173 		case IPV6_PATHMTU:
10174 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10175 				(struct ip6_mtuinfo *)ptr));
10176 		default:
10177 			break;
10178 		}
10179 		break;
10180 	default:
10181 		break;
10182 	}
10183 	return (-1);
10184 }
10185 
10186 /* Named Dispatch routine to get a current value out of our parameter table. */
10187 /* ARGSUSED */
10188 static int
10189 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10190 {
10191 	ipparam_t *ippa = (ipparam_t *)cp;
10192 
10193 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10194 	return (0);
10195 }
10196 
10197 /* ARGSUSED */
10198 static int
10199 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10200 {
10201 
10202 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10203 	return (0);
10204 }
10205 
10206 /*
10207  * Set ip{,6}_forwarding values.  This means walking through all of the
10208  * ill's and toggling their forwarding values.
10209  */
10210 /* ARGSUSED */
10211 static int
10212 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10213 {
10214 	long new_value;
10215 	int *forwarding_value = (int *)cp;
10216 	ill_t *walker;
10217 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10218 	ill_walk_context_t ctx;
10219 
10220 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10221 	    new_value < 0 || new_value > 1) {
10222 		return (EINVAL);
10223 	}
10224 
10225 	*forwarding_value = new_value;
10226 
10227 	/*
10228 	 * Regardless of the current value of ip_forwarding, set all per-ill
10229 	 * values of ip_forwarding to the value being set.
10230 	 *
10231 	 * Bring all the ill's up to date with the new global value.
10232 	 */
10233 	rw_enter(&ill_g_lock, RW_READER);
10234 
10235 	if (isv6)
10236 		walker = ILL_START_WALK_V6(&ctx);
10237 	else
10238 		walker = ILL_START_WALK_V4(&ctx);
10239 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10240 		(void) ill_forward_set(q, mp, (new_value != 0),
10241 		    (caddr_t)walker);
10242 	}
10243 	rw_exit(&ill_g_lock);
10244 
10245 	return (0);
10246 }
10247 
10248 /*
10249  * Walk through the param array specified registering each element with the
10250  * Named Dispatch handler. This is called only during init. So it is ok
10251  * not to acquire any locks
10252  */
10253 static boolean_t
10254 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10255     ipndp_t *ipnd, size_t ipnd_cnt)
10256 {
10257 	for (; ippa_cnt-- > 0; ippa++) {
10258 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10259 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10260 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10261 				nd_free(&ip_g_nd);
10262 				return (B_FALSE);
10263 			}
10264 		}
10265 	}
10266 
10267 	for (; ipnd_cnt-- > 0; ipnd++) {
10268 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10269 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10270 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10271 			    ipnd->ip_ndp_data)) {
10272 				nd_free(&ip_g_nd);
10273 				return (B_FALSE);
10274 			}
10275 		}
10276 	}
10277 
10278 	return (B_TRUE);
10279 }
10280 
10281 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10282 /* ARGSUSED */
10283 static int
10284 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10285 {
10286 	long		new_value;
10287 	ipparam_t	*ippa = (ipparam_t *)cp;
10288 
10289 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10290 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10291 		return (EINVAL);
10292 	}
10293 	ippa->ip_param_value = new_value;
10294 	return (0);
10295 }
10296 
10297 /*
10298  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10299  * When an ipf is passed here for the first time, if
10300  * we already have in-order fragments on the queue, we convert from the fast-
10301  * path reassembly scheme to the hard-case scheme.  From then on, additional
10302  * fragments are reassembled here.  We keep track of the start and end offsets
10303  * of each piece, and the number of holes in the chain.  When the hole count
10304  * goes to zero, we are done!
10305  *
10306  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10307  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10308  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10309  * after the call to ip_reassemble().
10310  */
10311 int
10312 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10313     size_t msg_len)
10314 {
10315 	uint_t	end;
10316 	mblk_t	*next_mp;
10317 	mblk_t	*mp1;
10318 	uint_t	offset;
10319 	boolean_t incr_dups = B_TRUE;
10320 	boolean_t offset_zero_seen = B_FALSE;
10321 	boolean_t pkt_boundary_checked = B_FALSE;
10322 
10323 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10324 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10325 
10326 	/* Add in byte count */
10327 	ipf->ipf_count += msg_len;
10328 	if (ipf->ipf_end) {
10329 		/*
10330 		 * We were part way through in-order reassembly, but now there
10331 		 * is a hole.  We walk through messages already queued, and
10332 		 * mark them for hard case reassembly.  We know that up till
10333 		 * now they were in order starting from offset zero.
10334 		 */
10335 		offset = 0;
10336 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10337 			IP_REASS_SET_START(mp1, offset);
10338 			if (offset == 0) {
10339 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10340 				offset = -ipf->ipf_nf_hdr_len;
10341 			}
10342 			offset += mp1->b_wptr - mp1->b_rptr;
10343 			IP_REASS_SET_END(mp1, offset);
10344 		}
10345 		/* One hole at the end. */
10346 		ipf->ipf_hole_cnt = 1;
10347 		/* Brand it as a hard case, forever. */
10348 		ipf->ipf_end = 0;
10349 	}
10350 	/* Walk through all the new pieces. */
10351 	do {
10352 		end = start + (mp->b_wptr - mp->b_rptr);
10353 		/*
10354 		 * If start is 0, decrease 'end' only for the first mblk of
10355 		 * the fragment. Otherwise 'end' can get wrong value in the
10356 		 * second pass of the loop if first mblk is exactly the
10357 		 * size of ipf_nf_hdr_len.
10358 		 */
10359 		if (start == 0 && !offset_zero_seen) {
10360 			/* First segment */
10361 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10362 			end -= ipf->ipf_nf_hdr_len;
10363 			offset_zero_seen = B_TRUE;
10364 		}
10365 		next_mp = mp->b_cont;
10366 		/*
10367 		 * We are checking to see if there is any interesing data
10368 		 * to process.  If there isn't and the mblk isn't the
10369 		 * one which carries the unfragmentable header then we
10370 		 * drop it.  It's possible to have just the unfragmentable
10371 		 * header come through without any data.  That needs to be
10372 		 * saved.
10373 		 *
10374 		 * If the assert at the top of this function holds then the
10375 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10376 		 * is infrequently traveled enough that the test is left in
10377 		 * to protect against future code changes which break that
10378 		 * invariant.
10379 		 */
10380 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10381 			/* Empty.  Blast it. */
10382 			IP_REASS_SET_START(mp, 0);
10383 			IP_REASS_SET_END(mp, 0);
10384 			/*
10385 			 * If the ipf points to the mblk we are about to free,
10386 			 * update ipf to point to the next mblk (or NULL
10387 			 * if none).
10388 			 */
10389 			if (ipf->ipf_mp->b_cont == mp)
10390 				ipf->ipf_mp->b_cont = next_mp;
10391 			freeb(mp);
10392 			continue;
10393 		}
10394 		mp->b_cont = NULL;
10395 		IP_REASS_SET_START(mp, start);
10396 		IP_REASS_SET_END(mp, end);
10397 		if (!ipf->ipf_tail_mp) {
10398 			ipf->ipf_tail_mp = mp;
10399 			ipf->ipf_mp->b_cont = mp;
10400 			if (start == 0 || !more) {
10401 				ipf->ipf_hole_cnt = 1;
10402 				/*
10403 				 * if the first fragment comes in more than one
10404 				 * mblk, this loop will be executed for each
10405 				 * mblk. Need to adjust hole count so exiting
10406 				 * this routine will leave hole count at 1.
10407 				 */
10408 				if (next_mp)
10409 					ipf->ipf_hole_cnt++;
10410 			} else
10411 				ipf->ipf_hole_cnt = 2;
10412 			continue;
10413 		} else if (ipf->ipf_last_frag_seen && !more &&
10414 			    !pkt_boundary_checked) {
10415 			/*
10416 			 * We check datagram boundary only if this fragment
10417 			 * claims to be the last fragment and we have seen a
10418 			 * last fragment in the past too. We do this only
10419 			 * once for a given fragment.
10420 			 *
10421 			 * start cannot be 0 here as fragments with start=0
10422 			 * and MF=0 gets handled as a complete packet. These
10423 			 * fragments should not reach here.
10424 			 */
10425 
10426 			if (start + msgdsize(mp) !=
10427 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10428 				/*
10429 				 * We have two fragments both of which claim
10430 				 * to be the last fragment but gives conflicting
10431 				 * information about the whole datagram size.
10432 				 * Something fishy is going on. Drop the
10433 				 * fragment and free up the reassembly list.
10434 				 */
10435 				return (IP_REASS_FAILED);
10436 			}
10437 
10438 			/*
10439 			 * We shouldn't come to this code block again for this
10440 			 * particular fragment.
10441 			 */
10442 			pkt_boundary_checked = B_TRUE;
10443 		}
10444 
10445 		/* New stuff at or beyond tail? */
10446 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10447 		if (start >= offset) {
10448 			if (ipf->ipf_last_frag_seen) {
10449 				/* current fragment is beyond last fragment */
10450 				return (IP_REASS_FAILED);
10451 			}
10452 			/* Link it on end. */
10453 			ipf->ipf_tail_mp->b_cont = mp;
10454 			ipf->ipf_tail_mp = mp;
10455 			if (more) {
10456 				if (start != offset)
10457 					ipf->ipf_hole_cnt++;
10458 			} else if (start == offset && next_mp == NULL)
10459 					ipf->ipf_hole_cnt--;
10460 			continue;
10461 		}
10462 		mp1 = ipf->ipf_mp->b_cont;
10463 		offset = IP_REASS_START(mp1);
10464 		/* New stuff at the front? */
10465 		if (start < offset) {
10466 			if (start == 0) {
10467 				if (end >= offset) {
10468 					/* Nailed the hole at the begining. */
10469 					ipf->ipf_hole_cnt--;
10470 				}
10471 			} else if (end < offset) {
10472 				/*
10473 				 * A hole, stuff, and a hole where there used
10474 				 * to be just a hole.
10475 				 */
10476 				ipf->ipf_hole_cnt++;
10477 			}
10478 			mp->b_cont = mp1;
10479 			/* Check for overlap. */
10480 			while (end > offset) {
10481 				if (end < IP_REASS_END(mp1)) {
10482 					mp->b_wptr -= end - offset;
10483 					IP_REASS_SET_END(mp, offset);
10484 					if (ill->ill_isv6) {
10485 						BUMP_MIB(ill->ill_ip6_mib,
10486 						    ipv6ReasmPartDups);
10487 					} else {
10488 						BUMP_MIB(&ip_mib,
10489 						    ipReasmPartDups);
10490 					}
10491 					break;
10492 				}
10493 				/* Did we cover another hole? */
10494 				if ((mp1->b_cont &&
10495 				    IP_REASS_END(mp1) !=
10496 				    IP_REASS_START(mp1->b_cont) &&
10497 				    end >= IP_REASS_START(mp1->b_cont)) ||
10498 				    (!ipf->ipf_last_frag_seen && !more)) {
10499 					ipf->ipf_hole_cnt--;
10500 				}
10501 				/* Clip out mp1. */
10502 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10503 					/*
10504 					 * After clipping out mp1, this guy
10505 					 * is now hanging off the end.
10506 					 */
10507 					ipf->ipf_tail_mp = mp;
10508 				}
10509 				IP_REASS_SET_START(mp1, 0);
10510 				IP_REASS_SET_END(mp1, 0);
10511 				/* Subtract byte count */
10512 				ipf->ipf_count -= mp1->b_datap->db_lim -
10513 				    mp1->b_datap->db_base;
10514 				freeb(mp1);
10515 				if (ill->ill_isv6) {
10516 					BUMP_MIB(ill->ill_ip6_mib,
10517 					    ipv6ReasmPartDups);
10518 				} else {
10519 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10520 				}
10521 				mp1 = mp->b_cont;
10522 				if (!mp1)
10523 					break;
10524 				offset = IP_REASS_START(mp1);
10525 			}
10526 			ipf->ipf_mp->b_cont = mp;
10527 			continue;
10528 		}
10529 		/*
10530 		 * The new piece starts somewhere between the start of the head
10531 		 * and before the end of the tail.
10532 		 */
10533 		for (; mp1; mp1 = mp1->b_cont) {
10534 			offset = IP_REASS_END(mp1);
10535 			if (start < offset) {
10536 				if (end <= offset) {
10537 					/* Nothing new. */
10538 					IP_REASS_SET_START(mp, 0);
10539 					IP_REASS_SET_END(mp, 0);
10540 					/* Subtract byte count */
10541 					ipf->ipf_count -= mp->b_datap->db_lim -
10542 					    mp->b_datap->db_base;
10543 					if (incr_dups) {
10544 						ipf->ipf_num_dups++;
10545 						incr_dups = B_FALSE;
10546 					}
10547 					freeb(mp);
10548 					if (ill->ill_isv6) {
10549 						BUMP_MIB(ill->ill_ip6_mib,
10550 						    ipv6ReasmDuplicates);
10551 					} else {
10552 						BUMP_MIB(&ip_mib,
10553 						    ipReasmDuplicates);
10554 					}
10555 					break;
10556 				}
10557 				/*
10558 				 * Trim redundant stuff off beginning of new
10559 				 * piece.
10560 				 */
10561 				IP_REASS_SET_START(mp, offset);
10562 				mp->b_rptr += offset - start;
10563 				if (ill->ill_isv6) {
10564 					BUMP_MIB(ill->ill_ip6_mib,
10565 					    ipv6ReasmPartDups);
10566 				} else {
10567 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10568 				}
10569 				start = offset;
10570 				if (!mp1->b_cont) {
10571 					/*
10572 					 * After trimming, this guy is now
10573 					 * hanging off the end.
10574 					 */
10575 					mp1->b_cont = mp;
10576 					ipf->ipf_tail_mp = mp;
10577 					if (!more) {
10578 						ipf->ipf_hole_cnt--;
10579 					}
10580 					break;
10581 				}
10582 			}
10583 			if (start >= IP_REASS_START(mp1->b_cont))
10584 				continue;
10585 			/* Fill a hole */
10586 			if (start > offset)
10587 				ipf->ipf_hole_cnt++;
10588 			mp->b_cont = mp1->b_cont;
10589 			mp1->b_cont = mp;
10590 			mp1 = mp->b_cont;
10591 			offset = IP_REASS_START(mp1);
10592 			if (end >= offset) {
10593 				ipf->ipf_hole_cnt--;
10594 				/* Check for overlap. */
10595 				while (end > offset) {
10596 					if (end < IP_REASS_END(mp1)) {
10597 						mp->b_wptr -= end - offset;
10598 						IP_REASS_SET_END(mp, offset);
10599 						/*
10600 						 * TODO we might bump
10601 						 * this up twice if there is
10602 						 * overlap at both ends.
10603 						 */
10604 						if (ill->ill_isv6) {
10605 							BUMP_MIB(
10606 							    ill->ill_ip6_mib,
10607 							    ipv6ReasmPartDups);
10608 						} else {
10609 							BUMP_MIB(&ip_mib,
10610 							    ipReasmPartDups);
10611 						}
10612 						break;
10613 					}
10614 					/* Did we cover another hole? */
10615 					if ((mp1->b_cont &&
10616 					    IP_REASS_END(mp1)
10617 					    != IP_REASS_START(mp1->b_cont) &&
10618 					    end >=
10619 					    IP_REASS_START(mp1->b_cont)) ||
10620 					    (!ipf->ipf_last_frag_seen &&
10621 					    !more)) {
10622 						ipf->ipf_hole_cnt--;
10623 					}
10624 					/* Clip out mp1. */
10625 					if ((mp->b_cont = mp1->b_cont) ==
10626 					    NULL) {
10627 						/*
10628 						 * After clipping out mp1,
10629 						 * this guy is now hanging
10630 						 * off the end.
10631 						 */
10632 						ipf->ipf_tail_mp = mp;
10633 					}
10634 					IP_REASS_SET_START(mp1, 0);
10635 					IP_REASS_SET_END(mp1, 0);
10636 					/* Subtract byte count */
10637 					ipf->ipf_count -=
10638 					    mp1->b_datap->db_lim -
10639 					    mp1->b_datap->db_base;
10640 					freeb(mp1);
10641 					if (ill->ill_isv6) {
10642 						BUMP_MIB(ill->ill_ip6_mib,
10643 						    ipv6ReasmPartDups);
10644 					} else {
10645 						BUMP_MIB(&ip_mib,
10646 						    ipReasmPartDups);
10647 					}
10648 					mp1 = mp->b_cont;
10649 					if (!mp1)
10650 						break;
10651 					offset = IP_REASS_START(mp1);
10652 				}
10653 			}
10654 			break;
10655 		}
10656 	} while (start = end, mp = next_mp);
10657 
10658 	/* Fragment just processed could be the last one. Remember this fact */
10659 	if (!more)
10660 		ipf->ipf_last_frag_seen = B_TRUE;
10661 
10662 	/* Still got holes? */
10663 	if (ipf->ipf_hole_cnt)
10664 		return (IP_REASS_PARTIAL);
10665 	/* Clean up overloaded fields to avoid upstream disasters. */
10666 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10667 		IP_REASS_SET_START(mp1, 0);
10668 		IP_REASS_SET_END(mp1, 0);
10669 	}
10670 	return (IP_REASS_COMPLETE);
10671 }
10672 
10673 /*
10674  * ipsec processing for the fast path, used for input UDP Packets
10675  */
10676 static boolean_t
10677 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10678     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10679 {
10680 	uint32_t	ill_index;
10681 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10682 
10683 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10684 	/* The ill_index of the incoming ILL */
10685 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10686 
10687 	/* pass packet up to the transport */
10688 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10689 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10690 		    NULL, mctl_present);
10691 		if (*first_mpp == NULL) {
10692 			return (B_FALSE);
10693 		}
10694 	}
10695 
10696 	/* Initiate IPPF processing for fastpath UDP */
10697 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10698 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10699 		if (*mpp == NULL) {
10700 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10701 			    "deferred/dropped during IPPF processing\n"));
10702 			return (B_FALSE);
10703 		}
10704 	}
10705 	/*
10706 	 * We make the checks as below since we are in the fast path
10707 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10708 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10709 	 */
10710 	if (connp->conn_recvif || connp->conn_recvslla ||
10711 	    connp->conn_ipv6_recvpktinfo) {
10712 		if (connp->conn_recvif ||
10713 		    connp->conn_ipv6_recvpktinfo) {
10714 			in_flags = IPF_RECVIF;
10715 		}
10716 		if (connp->conn_recvslla) {
10717 			in_flags |= IPF_RECVSLLA;
10718 		}
10719 		/*
10720 		 * since in_flags are being set ill will be
10721 		 * referenced in ip_add_info, so it better not
10722 		 * be NULL.
10723 		 */
10724 		/*
10725 		 * the actual data will be contained in b_cont
10726 		 * upon successful return of the following call.
10727 		 * If the call fails then the original mblk is
10728 		 * returned.
10729 		 */
10730 		*mpp = ip_add_info(*mpp, ill, in_flags);
10731 	}
10732 
10733 	return (B_TRUE);
10734 }
10735 
10736 /*
10737  * Do fragmentation reassembly.
10738  * returns B_TRUE if successful else B_FALSE.
10739  * frees mp on failure.
10740  */
10741 static boolean_t
10742 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha)
10743 {
10744 	uint32_t	frag_offset_flags;
10745 	ill_t   *ill = (ill_t *)q->q_ptr;
10746 	mblk_t *mp = *mpp;
10747 	mblk_t *t_mp;
10748 	ipaddr_t	dst;
10749 
10750 	/*
10751 	 * Drop the fragmented as early as possible, if
10752 	 * we don't have resource(s) to re-assemble.
10753 	 */
10754 
10755 	if (ip_reass_queue_bytes == 0) {
10756 		freemsg(mp);
10757 		return (B_FALSE);
10758 	}
10759 
10760 	dst = ipha->ipha_dst;
10761 
10762 	/* Clear hardware checksumming flag if set */
10763 	mp->b_datap->db_struioun.cksum.flags = 0;
10764 
10765 	/* Check for fragmentation offset. */
10766 	frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
10767 	    (IPH_MF | IPH_OFFSET);
10768 	if (frag_offset_flags) {
10769 		ipf_t		*ipf;
10770 		ipf_t		**ipfp;
10771 		ipfb_t		*ipfb;
10772 		uint16_t	ident;
10773 		uint32_t	offset;
10774 		ipaddr_t	src;
10775 		uint_t		hdr_length;
10776 		uint32_t	end;
10777 		uint8_t		proto;
10778 		mblk_t		*mp1;
10779 		mblk_t		*tail_mp;
10780 		size_t		count;
10781 		size_t		msg_len;
10782 		uint8_t		ecn_info = 0;
10783 		uint32_t	packet_size;
10784 		boolean_t 	pruned = B_FALSE;
10785 
10786 		ident = ipha->ipha_ident;
10787 		offset = (frag_offset_flags << 3) & 0xFFFF;
10788 		src = ipha->ipha_src;
10789 		hdr_length = IPH_HDR_LENGTH(ipha);
10790 		end = ntohs(ipha->ipha_length) - hdr_length;
10791 
10792 		/*
10793 		 * if end == 0 then we have a packet with no data, so just
10794 		 * free it.
10795 		 */
10796 		if (end == 0) {
10797 			freemsg(mp);
10798 			return (B_FALSE);
10799 		}
10800 		proto = ipha->ipha_protocol;
10801 
10802 		/*
10803 		 * Fragmentation reassembly.  Each ILL has a hash table for
10804 		 * queuing packets undergoing reassembly for all IPIFs
10805 		 * associated with the ILL.  The hash is based on the packet
10806 		 * IP ident field.  The ILL frag hash table was allocated
10807 		 * as a timer block at the time the ILL was created.  Whenever
10808 		 * there is anything on the reassembly queue, the timer will
10809 		 * be running.
10810 		 */
10811 		ASSERT(ill != NULL);
10812 
10813 		/* Record the ECN field info. */
10814 		ecn_info = (ipha->ipha_type_of_service & 0x3);
10815 		if (offset != 0) {
10816 			/*
10817 			 * If this isn't the first piece, strip the header, and
10818 			 * add the offset to the end value.
10819 			 */
10820 			mp->b_rptr += hdr_length;
10821 			end += offset;
10822 		}
10823 
10824 		msg_len = mp->b_datap->db_lim - mp->b_datap->db_base;
10825 		tail_mp = mp;
10826 		while (tail_mp->b_cont != NULL) {
10827 			tail_mp = tail_mp->b_cont;
10828 			msg_len += tail_mp->b_datap->db_lim -
10829 			    tail_mp->b_datap->db_base;
10830 		}
10831 
10832 		/*
10833 		 * If the reassembly list for this ILL will get too big
10834 		 * prune it.
10835 		 */
10836 		if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
10837 		    ip_reass_queue_bytes) {
10838 			ill_frag_prune(ill,
10839 			    (ip_reass_queue_bytes < msg_len) ? 0 :
10840 			    (ip_reass_queue_bytes - msg_len));
10841 			pruned = B_TRUE;
10842 		}
10843 
10844 		ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
10845 		mutex_enter(&ipfb->ipfb_lock);
10846 
10847 		ipfp = &ipfb->ipfb_ipf;
10848 		/* Try to find an existing fragment queue for this packet. */
10849 		for (;;) {
10850 			ipf = ipfp[0];
10851 			if (ipf != NULL) {
10852 				/*
10853 				 * It has to match on ident and src/dst address.
10854 				 */
10855 				if (ipf->ipf_ident == ident &&
10856 				    ipf->ipf_src == src &&
10857 				    ipf->ipf_dst == dst &&
10858 				    ipf->ipf_protocol == proto) {
10859 					/*
10860 					 * If we have received too many
10861 					 * duplicate fragments for this packet
10862 					 * free it.
10863 					 */
10864 					if (ipf->ipf_num_dups >
10865 					    ip_max_frag_dups) {
10866 						ill_frag_free_pkts(ill, ipfb,
10867 						    ipf, 1);
10868 						freemsg(mp);
10869 						mutex_exit(&ipfb->ipfb_lock);
10870 						return (B_FALSE);
10871 					}
10872 					/* Found it. */
10873 					break;
10874 				}
10875 				ipfp = &ipf->ipf_hash_next;
10876 				continue;
10877 			}
10878 
10879 			/*
10880 			 * If we pruned the list, do we want to store this new
10881 			 * fragment?. We apply an optimization here based on the
10882 			 * fact that most fragments will be received in order.
10883 			 * So if the offset of this incoming fragment is zero,
10884 			 * it is the first fragment of a new packet. We will
10885 			 * keep it.  Otherwise drop the fragment, as we have
10886 			 * probably pruned the packet already (since the
10887 			 * packet cannot be found).
10888 			 */
10889 			if (pruned && offset != 0) {
10890 				mutex_exit(&ipfb->ipfb_lock);
10891 				freemsg(mp);
10892 				return (B_FALSE);
10893 			}
10894 
10895 			if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
10896 				/*
10897 				 * Too many fragmented packets in this hash
10898 				 * bucket. Free the oldest.
10899 				 */
10900 				ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf,
10901 				    1);
10902 			}
10903 
10904 			/* New guy.  Allocate a frag message. */
10905 			mp1 = allocb(sizeof (*ipf), BPRI_MED);
10906 			if (mp1 == NULL) {
10907 				BUMP_MIB(&ip_mib, ipInDiscards);
10908 				freemsg(mp);
10909 reass_done:
10910 				mutex_exit(&ipfb->ipfb_lock);
10911 				return (B_FALSE);
10912 			}
10913 
10914 
10915 			BUMP_MIB(&ip_mib, ipReasmReqds);
10916 			mp1->b_cont = mp;
10917 
10918 			/* Initialize the fragment header. */
10919 			ipf = (ipf_t *)mp1->b_rptr;
10920 			ipf->ipf_mp = mp1;
10921 			ipf->ipf_ptphn = ipfp;
10922 			ipfp[0] = ipf;
10923 			ipf->ipf_hash_next = NULL;
10924 			ipf->ipf_ident = ident;
10925 			ipf->ipf_protocol = proto;
10926 			ipf->ipf_src = src;
10927 			ipf->ipf_dst = dst;
10928 			ipf->ipf_nf_hdr_len = 0;
10929 			/* Record reassembly start time. */
10930 			ipf->ipf_timestamp = gethrestime_sec();
10931 			/* Record ipf generation and account for frag header */
10932 			ipf->ipf_gen = ill->ill_ipf_gen++;
10933 			ipf->ipf_count = mp1->b_datap->db_lim -
10934 			    mp1->b_datap->db_base;
10935 			ipf->ipf_last_frag_seen = B_FALSE;
10936 			ipf->ipf_ecn = ecn_info;
10937 			ipf->ipf_num_dups = 0;
10938 			ipfb->ipfb_frag_pkts++;
10939 
10940 			/*
10941 			 * We handle reassembly two ways.  In the easy case,
10942 			 * where all the fragments show up in order, we do
10943 			 * minimal bookkeeping, and just clip new pieces on
10944 			 * the end.  If we ever see a hole, then we go off
10945 			 * to ip_reassemble which has to mark the pieces and
10946 			 * keep track of the number of holes, etc.  Obviously,
10947 			 * the point of having both mechanisms is so we can
10948 			 * handle the easy case as efficiently as possible.
10949 			 */
10950 			if (offset == 0) {
10951 				/* Easy case, in-order reassembly so far. */
10952 				ipf->ipf_count += msg_len;
10953 				ipf->ipf_tail_mp = tail_mp;
10954 				/*
10955 				 * Keep track of next expected offset in
10956 				 * ipf_end.
10957 				 */
10958 				ipf->ipf_end = end;
10959 				ipf->ipf_nf_hdr_len = hdr_length;
10960 			} else {
10961 				/* Hard case, hole at the beginning. */
10962 				ipf->ipf_tail_mp = NULL;
10963 				/*
10964 				 * ipf_end == 0 means that we have given up
10965 				 * on easy reassembly.
10966 				 */
10967 				ipf->ipf_end = 0;
10968 				/*
10969 				 * ipf_hole_cnt is set by ip_reassemble.
10970 				 * ipf_count is updated by ip_reassemble.
10971 				 * No need to check for return value here
10972 				 * as we don't expect reassembly to complete
10973 				 * or fail for the first fragment itself.
10974 				 */
10975 				(void) ip_reassemble(mp, ipf,
10976 				    (frag_offset_flags & IPH_OFFSET) << 3,
10977 				    (frag_offset_flags & IPH_MF), ill, msg_len);
10978 			}
10979 			/* Update per ipfb and ill byte counts */
10980 			ipfb->ipfb_count += ipf->ipf_count;
10981 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
10982 			ill->ill_frag_count += ipf->ipf_count;
10983 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
10984 			/* If the frag timer wasn't already going, start it. */
10985 			mutex_enter(&ill->ill_lock);
10986 			ill_frag_timer_start(ill);
10987 			mutex_exit(&ill->ill_lock);
10988 			goto reass_done;
10989 		}
10990 
10991 		/*
10992 		 * We have a new piece of a datagram which is already being
10993 		 * reassembled.  Update the ECN info if all IP fragments
10994 		 * are ECN capable.  If there is one which is not, clear
10995 		 * all the info.  If there is at least one which has CE
10996 		 * code point, IP needs to report that up to transport.
10997 		 */
10998 		if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
10999 			if (ecn_info == IPH_ECN_CE)
11000 				ipf->ipf_ecn = IPH_ECN_CE;
11001 		} else {
11002 			ipf->ipf_ecn = IPH_ECN_NECT;
11003 		}
11004 		if (offset && ipf->ipf_end == offset) {
11005 			/* The new fragment fits at the end */
11006 			ipf->ipf_tail_mp->b_cont = mp;
11007 			/* Update the byte count */
11008 			ipf->ipf_count += msg_len;
11009 			/* Update per ipfb and ill byte counts */
11010 			ipfb->ipfb_count += msg_len;
11011 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11012 			ill->ill_frag_count += msg_len;
11013 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11014 			if (frag_offset_flags & IPH_MF) {
11015 				/* More to come. */
11016 				ipf->ipf_end = end;
11017 				ipf->ipf_tail_mp = tail_mp;
11018 				goto reass_done;
11019 			}
11020 		} else {
11021 			/* Go do the hard cases. */
11022 			int ret;
11023 
11024 			if (offset == 0)
11025 				ipf->ipf_nf_hdr_len = hdr_length;
11026 
11027 			/* Save current byte count */
11028 			count = ipf->ipf_count;
11029 			ret = ip_reassemble(mp, ipf,
11030 			    (frag_offset_flags & IPH_OFFSET) << 3,
11031 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11032 			/* Count of bytes added and subtracted (freeb()ed) */
11033 			count = ipf->ipf_count - count;
11034 			if (count) {
11035 				/* Update per ipfb and ill byte counts */
11036 				ipfb->ipfb_count += count;
11037 				ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11038 				ill->ill_frag_count += count;
11039 				ASSERT(ill->ill_frag_count > 0);
11040 			}
11041 			if (ret == IP_REASS_PARTIAL) {
11042 				goto reass_done;
11043 			} else if (ret == IP_REASS_FAILED) {
11044 				/* Reassembly failed. Free up all resources */
11045 				ill_frag_free_pkts(ill, ipfb, ipf, 1);
11046 				for (t_mp = mp; t_mp != NULL;
11047 				    t_mp = t_mp->b_cont) {
11048 					IP_REASS_SET_START(t_mp, 0);
11049 					IP_REASS_SET_END(t_mp, 0);
11050 				}
11051 				freemsg(mp);
11052 				goto reass_done;
11053 			}
11054 			/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11055 		}
11056 		/*
11057 		 * We have completed reassembly.  Unhook the frag header from
11058 		 * the reassembly list.
11059 		 *
11060 		 * Before we free the frag header, record the ECN info
11061 		 * to report back to the transport.
11062 		 */
11063 		ecn_info = ipf->ipf_ecn;
11064 		BUMP_MIB(&ip_mib, ipReasmOKs);
11065 		ipfp = ipf->ipf_ptphn;
11066 		mp1 = ipf->ipf_mp;
11067 		count = ipf->ipf_count;
11068 		ipf = ipf->ipf_hash_next;
11069 		if (ipf)
11070 			ipf->ipf_ptphn = ipfp;
11071 		ipfp[0] = ipf;
11072 		ill->ill_frag_count -= count;
11073 		ASSERT(ipfb->ipfb_count >= count);
11074 		ipfb->ipfb_count -= count;
11075 		ipfb->ipfb_frag_pkts--;
11076 		mutex_exit(&ipfb->ipfb_lock);
11077 		/* Ditch the frag header. */
11078 		mp = mp1->b_cont;
11079 
11080 		freeb(mp1);
11081 
11082 		/* Restore original IP length in header. */
11083 		packet_size = (uint32_t)msgdsize(mp);
11084 		if (packet_size > IP_MAXPACKET) {
11085 			freemsg(mp);
11086 			BUMP_MIB(&ip_mib, ipInHdrErrors);
11087 			return (B_FALSE);
11088 		}
11089 
11090 		if (mp->b_datap->db_ref > 1) {
11091 			mblk_t *mp2;
11092 
11093 			mp2 = copymsg(mp);
11094 			freemsg(mp);
11095 			if (!mp2) {
11096 				BUMP_MIB(&ip_mib, ipInDiscards);
11097 				return (B_FALSE);
11098 			}
11099 			mp = mp2;
11100 		}
11101 		ipha = (ipha_t *)mp->b_rptr;
11102 
11103 		ipha->ipha_length = htons((uint16_t)packet_size);
11104 		/* We're now complete, zip the frag state */
11105 		ipha->ipha_fragment_offset_and_flags = 0;
11106 		/* Record the ECN info. */
11107 		ipha->ipha_type_of_service &= 0xFC;
11108 		ipha->ipha_type_of_service |= ecn_info;
11109 		*mpp = mp;
11110 
11111 	}
11112 	return (B_TRUE);
11113 }
11114 
11115 /*
11116  * Perform ip header check sum update local options.
11117  * return B_TRUE if all is well, else return B_FALSE and release
11118  * the mp. caller is responsible for decrementing ire ref cnt.
11119  */
11120 static boolean_t
11121 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11122 {
11123 	mblk_t		*first_mp;
11124 	boolean_t	mctl_present;
11125 	uint16_t	sum;
11126 
11127 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11128 	/*
11129 	 * Don't do the checksum if it has gone through AH/ESP
11130 	 * processing.
11131 	 */
11132 	if (!mctl_present) {
11133 		sum = ip_csum_hdr(ipha);
11134 		if (sum != 0) {
11135 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11136 			freemsg(first_mp);
11137 			return (B_FALSE);
11138 		}
11139 	}
11140 
11141 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11142 		if (mctl_present)
11143 			freeb(first_mp);
11144 		return (B_FALSE);
11145 	}
11146 
11147 	return (B_TRUE);
11148 }
11149 
11150 /*
11151  * All udp packet are delivered to the local host via this routine.
11152  */
11153 void
11154 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11155     ill_t *recv_ill)
11156 {
11157 	uint32_t	sum;
11158 	uint32_t	u1;
11159 	uint32_t	u2;
11160 	boolean_t	mctl_present;
11161 	conn_t		*connp;
11162 	mblk_t		*first_mp;
11163 	mblk_t		*mp1;
11164 	dblk_t		*dp;
11165 	uint16_t	*up;
11166 	ill_t		*ill = (ill_t *)q->q_ptr;
11167 	uint32_t	ports;
11168 	boolean_t	cksum_computed = B_FALSE;
11169 
11170 #define	rptr    ((uchar_t *)ipha)
11171 
11172 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11173 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11174 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11175 
11176 	/*
11177 	 * FAST PATH for udp packets
11178 	 */
11179 
11180 	/* u1 is # words of IP options */
11181 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11182 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11183 
11184 	/* IP options present */
11185 	if (u1)
11186 		goto ipoptions;
11187 
11188 #define	IS_IPHDR_HWCKSUM(mctl_present, mp, ill)				\
11189 	((!mctl_present) && (mp->b_datap->db_struioun.cksum.flags &	\
11190 	HCK_IPV4_HDRCKSUM) && (ill->ill_capabilities &			\
11191 	ILL_CAPAB_HCKSUM) && dohwcksum)
11192 
11193 	/* Check the IP header checksum.  */
11194 	if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11195 		/* Clear the IP header h/w cksum flag */
11196 		mp->b_datap->db_struioun.cksum.flags &=
11197 		    ~HCK_IPV4_HDRCKSUM;
11198 	} else {
11199 #define	uph	((uint16_t *)ipha)
11200 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11201 		    uph[6] + uph[7] + uph[8] + uph[9];
11202 #undef	uph
11203 		/* finish doing IP checksum */
11204 		sum = (sum & 0xFFFF) + (sum >> 16);
11205 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11206 		/*
11207 		 * Don't verify header checksum if this packet is coming
11208 		 * back from AH/ESP as we already did it.
11209 		 */
11210 		if (!mctl_present && (sum && sum != 0xFFFF)) {
11211 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11212 			freemsg(first_mp);
11213 			return;
11214 		}
11215 	}
11216 
11217 	/*
11218 	 * Count for SNMP of inbound packets for ire.
11219 	 * if mctl is present this might be a secure packet and
11220 	 * has already been counted for in ip_proto_input().
11221 	 */
11222 	if (!mctl_present) {
11223 		UPDATE_IB_PKT_COUNT(ire);
11224 		ire->ire_last_used_time = lbolt;
11225 	}
11226 
11227 	/* packet part of fragmented IP packet? */
11228 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11229 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11230 		goto fragmented;
11231 	}
11232 
11233 	/* u1 = IP header length (20 bytes) */
11234 	u1 = IP_SIMPLE_HDR_LENGTH;
11235 
11236 	/* packet does not contain complete IP & UDP headers */
11237 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11238 		goto udppullup;
11239 	/* up points to UDP header */
11240 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11241 #define	iphs    ((uint16_t *)ipha)
11242 
11243 #define	IP_CKSUM_RECV(len, u1, u2, mp, mp1, error, dp) {		\
11244 	boolean_t	doswcksum = B_TRUE;				\
11245 	uint_t		hcksumflags = 0;				\
11246 									\
11247 	hcksumflags = dp->db_struioun.cksum.flags;			\
11248 									\
11249 	/* Clear the hardware checksum flags; they have been consumed */\
11250 	dp->db_struioun.cksum.flags = 0;				\
11251 	if (hcksumflags && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&\
11252 		dohwcksum) {						\
11253 		if (hcksumflags & HCK_FULLCKSUM) {			\
11254 			/* 						\
11255 			 * Full checksum has been computed by the	\
11256 			 * hardware and has been attached. 		\
11257 			 */						\
11258 			doswcksum = B_FALSE;				\
11259 			if (!(hcksumflags & HCK_FULLCKSUM_OK) &&	\
11260 			    (dp->db_cksum16 != 0xffff)) {		\
11261 				ipcsumdbg("full hwcksumerr\n", mp);	\
11262 				goto error;				\
11263 			}						\
11264 		} else if ((hcksumflags & HCK_PARTIALCKSUM) &&		\
11265 		    (((len = (IP_SIMPLE_HDR_LENGTH - dp->db_cksumstart))\
11266 		    & 1) == 0)) {					\
11267 			uint32_t	tot_len = 0;			\
11268 									\
11269 			doswcksum = B_FALSE;				\
11270 			/* Partial checksum computed */			\
11271 			u1 += dp->db_cksum16;				\
11272 			tot_len = mp->b_wptr - mp->b_rptr;		\
11273 			if (!mp1)					\
11274 				mp1 = mp;				\
11275 			else						\
11276 				tot_len += mp1->b_wptr - mp1->b_rptr;	\
11277 			if (len > 0) {					\
11278 				/* 					\
11279 				 * Prepended extraneous data. Adjust	\
11280 				 * checksum.				\
11281 				 */					\
11282 				u2 = IP_BCSUM_PARTIAL((uchar_t *)(rptr +\
11283 				    dp->db_cksumstart),	(int32_t)len, 	\
11284 				    0);					\
11285 			} else						\
11286 				u2 = 0;					\
11287 			if ((len = (dp->db_cksumend - tot_len)) > 0) {	\
11288 				/* 					\
11289 				 * Postpended extraneous data. Adjust	\
11290 				 * checksum.				\
11291 				 */					\
11292 				uint32_t	u3;			\
11293 									\
11294 				u3 = IP_BCSUM_PARTIAL(mp1->b_wptr, 	\
11295 				    (int32_t)len, 0);			\
11296 				if ((uintptr_t)mp1->b_wptr & 1)		\
11297 					/*				\
11298 					 * Postpended extraneous data	\
11299 					 * was odd byte aligned, so 	\
11300 					 * swap resulting checksum 	\
11301 					 * bytes.			\
11302 					 */				\
11303 					u2 += ((u3 << 8) & 0xffff) | 	\
11304 					    (u3 >> 8);			\
11305 				else					\
11306 					u2 += u3;			\
11307 				u2 = (u2 & 0xFFFF) + ((int)(u2) >> 16);	\
11308 			}						\
11309 			/*						\
11310 			 * One's complement subtract extraneous checksum\
11311 			 */						\
11312 			if (u2 >= u1)					\
11313 				u1 = ~(u2 - u1) & 0xFFFF;		\
11314 			else						\
11315 				u1 -= u2;				\
11316 			u1 = (u1 & 0xFFFF) + ((int)u1 >> 16);		\
11317 			if (~(u1) & 0xFFFF) {				\
11318 				ipcsumdbg("partial hwcksumerr\n", mp);	\
11319 				goto error;				\
11320 			}						\
11321 		} 							\
11322 	} 								\
11323 	if (doswcksum) {						\
11324 		IP_STAT(ip_in_sw_cksum);				\
11325 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -		\
11326 		    (uchar_t *)ipha), u1)) != 0) {			\
11327 			ipcsumdbg("swcksumerr\n", mp);			\
11328 			goto error;					\
11329 		}							\
11330 	}								\
11331 }
11332 
11333 	dp = mp->b_datap;
11334 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11335 	if (up[3]) {
11336 		cksum_computed = B_TRUE;
11337 		/* multiple mblks of udp data? */
11338 		if ((mp1 = mp->b_cont) != NULL) {
11339 			/* more than two? */
11340 			if (mp1->b_cont)
11341 				goto multipktudp;
11342 		}
11343 
11344 		/* Pseudo-header checksum */
11345 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11346 		    iphs[9] + up[2];
11347 		if (!mctl_present) {
11348 			ssize_t len = 0;
11349 
11350 			IP_CKSUM_RECV(len, u1, u2, mp, mp1, udpcksumerr, dp);
11351 		} else {
11352 multipktudp:
11353 			IP_STAT(ip_in_sw_cksum);
11354 			if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -
11355 			    (uchar_t *)ipha), u1)) != 0) {
11356 udpcksumerr:
11357 				ip1dbg(("ip_udp_input: bad udp checksum\n"));
11358 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11359 				freemsg(first_mp);
11360 				return;
11361 			}
11362 		}
11363 	}
11364 
11365 	/* broadcast IP packet? */
11366 	if (ire->ire_type == IRE_BROADCAST)
11367 		goto udpslowpath;
11368 
11369 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11370 	    ire->ire_zoneid)) != NULL) {
11371 		ASSERT(connp->conn_upq != NULL);
11372 		IP_STAT(ip_udp_fast_path);
11373 
11374 		if (!canputnext(connp->conn_upq)) {
11375 			freemsg(mp);
11376 			BUMP_MIB(&ip_mib, udpInOverflows);
11377 		} else {
11378 			if (!mctl_present) {
11379 				BUMP_MIB(&ip_mib, ipInDelivers);
11380 			}
11381 			/*
11382 			 * mp and first_mp can change.
11383 			 */
11384 			if (ip_udp_check(q, connp, recv_ill,
11385 			    ipha, &mp, &first_mp, mctl_present)) {
11386 				putnext(connp->conn_upq, mp);
11387 			}
11388 		}
11389 		/*
11390 		 * freeb() cannot deal with null mblk being passed
11391 		 * in and first_mp can be set to null in the call
11392 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11393 		 */
11394 		if (mctl_present && first_mp != NULL) {
11395 			freeb(first_mp);
11396 		}
11397 		CONN_DEC_REF(connp);
11398 		return;
11399 	}
11400 
11401 	/*
11402 	 * if we got here we know the packet is not fragmented and
11403 	 * has no options. The classifier could not find a conn_t and
11404 	 * most likely its an icmp packet so send it through slow path.
11405 	 */
11406 
11407 	goto udpslowpath;
11408 
11409 ipoptions:
11410 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11411 		goto slow_done;
11412 	}
11413 
11414 	UPDATE_IB_PKT_COUNT(ire);
11415 	ire->ire_last_used_time = lbolt;
11416 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11417 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11418 fragmented:
11419 		if (!ip_rput_fragment(q, &mp, ipha)) {
11420 			goto slow_done;
11421 		}
11422 		/*
11423 		 * Make sure that first_mp points back to mp as
11424 		 * the mp we came in with could have changed in
11425 		 * ip_rput_fragment().
11426 		 */
11427 		ASSERT(!mctl_present);
11428 		ipha = (ipha_t *)mp->b_rptr;
11429 		first_mp = mp;
11430 	}
11431 
11432 	/* Now we have a complete datagram, destined for this machine. */
11433 	u1 = IPH_HDR_LENGTH(ipha);
11434 	/* Pull up the UDP header, if necessary. */
11435 	if ((mp->b_wptr - mp->b_rptr) < (u1 + UDPH_SIZE)) {
11436 udppullup:
11437 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11438 			BUMP_MIB(&ip_mib, ipInDiscards);
11439 			freemsg(first_mp);
11440 			goto slow_done;
11441 		}
11442 		ipha = (ipha_t *)mp->b_rptr;
11443 	}
11444 	/*
11445 	 * Validate the checksum.  This code is a bit funny looking
11446 	 * but may help out the compiler in this crucial spot.
11447 	 */
11448 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11449 	if (!cksum_computed && up[3]) {
11450 		IP_STAT(ip_in_sw_cksum);
11451 		sum = IP_CSUM(mp, (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11452 		    IP_UDP_CSUM_COMP + iphs[6] +
11453 		    iphs[7] + iphs[8] +
11454 		    iphs[9] + up[2]);
11455 		if (sum != 0) {
11456 			ip1dbg(("ip_udp_input: bad udp checksum\n"));
11457 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11458 				freemsg(first_mp);
11459 				goto slow_done;
11460 		}
11461 	}
11462 udpslowpath:
11463 
11464 	ports = *(uint32_t *)up;
11465 	/* Clear hardware checksum flag */
11466 	mp->b_datap->db_struioun.cksum.flags = 0;
11467 	ip_fanout_udp(q, first_mp, ill, ipha, ports,
11468 	    (ire->ire_type == IRE_BROADCAST),
11469 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11470 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11471 
11472 slow_done:
11473 	IP_STAT(ip_udp_slow_path);
11474 	return;
11475 
11476 #undef  rptr
11477 }
11478 
11479 /* ARGSUSED */
11480 static mblk_t *
11481 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11482     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11483     ill_rx_ring_t *ill_ring)
11484 {
11485 	conn_t		*connp;
11486 	uint32_t	sum;
11487 	uint32_t	u1;
11488 	uint32_t	u2;
11489 	uint16_t	*up;
11490 	int		offset;
11491 	ssize_t		len;
11492 	mblk_t		*mp1;
11493 	dblk_t		*dp;
11494 	boolean_t	syn_present = B_FALSE;
11495 	tcph_t		*tcph;
11496 	uint_t		ip_hdr_len;
11497 	ill_t		*ill = (ill_t *)q->q_ptr;
11498 	zoneid_t	zoneid = ire->ire_zoneid;
11499 
11500 #define	rptr	((uchar_t *)ipha)
11501 
11502 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11503 
11504 	/*
11505 	 * FAST PATH for tcp packets
11506 	 */
11507 
11508 	/* u1 is # words of IP options */
11509 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11510 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11511 
11512 	/* IP options present */
11513 	if (u1) {
11514 		goto ipoptions;
11515 	} else {
11516 		/* Check the IP header checksum.  */
11517 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11518 			/* Clear the IP header h/w cksum flag */
11519 			mp->b_datap->db_struioun.cksum.flags &=
11520 			    ~HCK_IPV4_HDRCKSUM;
11521 		} else {
11522 #define	uph	((uint16_t *)ipha)
11523 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11524 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11525 #undef	uph
11526 			/* finish doing IP checksum */
11527 			sum = (sum & 0xFFFF) + (sum >> 16);
11528 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11529 			/*
11530 			 * Don't verify header checksum if this packet
11531 			 * is coming back from AH/ESP as we already did it.
11532 			 */
11533 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11534 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11535 				goto error;
11536 			}
11537 		}
11538 	}
11539 
11540 	if (!mctl_present) {
11541 		UPDATE_IB_PKT_COUNT(ire);
11542 		ire->ire_last_used_time = lbolt;
11543 	}
11544 
11545 	/* packet part of fragmented IP packet? */
11546 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11547 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11548 		goto fragmented;
11549 	}
11550 
11551 	/* u1 = IP header length (20 bytes) */
11552 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11553 
11554 	/* does packet contain IP+TCP headers? */
11555 	len = mp->b_wptr - rptr;
11556 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11557 		IP_STAT(ip_tcppullup);
11558 		goto tcppullup;
11559 	}
11560 
11561 	/* TCP options present? */
11562 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11563 
11564 	/*
11565 	 * If options need to be pulled up, then goto tcpoptions.
11566 	 * otherwise we are still in the fast path
11567 	 */
11568 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11569 		IP_STAT(ip_tcpoptions);
11570 		goto tcpoptions;
11571 	}
11572 
11573 	/* multiple mblks of tcp data? */
11574 	if ((mp1 = mp->b_cont) != NULL) {
11575 		/* more then two? */
11576 		if (mp1->b_cont != NULL) {
11577 			IP_STAT(ip_multipkttcp);
11578 			goto multipkttcp;
11579 		}
11580 		len += mp1->b_wptr - mp1->b_rptr;
11581 	}
11582 
11583 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11584 
11585 	/* part of pseudo checksum */
11586 
11587 	/* TCP datagram length */
11588 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11589 
11590 #define	iphs    ((uint16_t *)ipha)
11591 
11592 #ifdef	_BIG_ENDIAN
11593 	u1 += IPPROTO_TCP;
11594 #else
11595 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11596 #endif
11597 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11598 
11599 
11600 	/*
11601 	 * If the packet has gone through AH/ESP, do the checksum here
11602 	 * itself.
11603 	 *
11604 	 * If it has not gone through IPSEC processing and not a duped
11605 	 * mblk, then look for driver checksummed mblk. We validate or
11606 	 * postpone the checksum to TCP for single copy checksum.
11607 	 *
11608 	 * Note that we only honor HW cksum in the fastpath.
11609 	 */
11610 	dp = mp->b_datap;
11611 	if (!mctl_present) {
11612 		IP_CKSUM_RECV(len, u1, u2, mp, mp1, tcpcksumerr, dp);
11613 	} else {
11614 		IP_STAT(ip_in_sw_cksum);
11615 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr),
11616 		    u1)) != 0) {
11617 tcpcksumerr:
11618 			BUMP_MIB(&ip_mib, tcpInErrs);
11619 			ip1dbg(("ip_tcp_input: bad tcp checksum \n"));
11620 			freemsg(first_mp);
11621 			goto slow_done;
11622 		}
11623 	}
11624 
11625 try_again:
11626 
11627 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11628 	    NULL) {
11629 		/* Send the TH_RST */
11630 		goto no_conn;
11631 	}
11632 
11633 	/*
11634 	 * TCP FAST PATH for AF_INET socket.
11635 	 *
11636 	 * TCP fast path to avoid extra work. An AF_INET socket type
11637 	 * does not have facility to receive extra information via
11638 	 * ip_process or ip_add_info. Also, when the connection was
11639 	 * established, we made a check if this connection is impacted
11640 	 * by any global IPSec policy or per connection policy (a
11641 	 * policy that comes in effect later will not apply to this
11642 	 * connection). Since all this can be determined at the
11643 	 * connection establishment time, a quick check of flags
11644 	 * can avoid extra work.
11645 	 */
11646 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11647 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11648 		ASSERT(first_mp == mp);
11649 		SET_SQUEUE(mp, tcp_rput_data, connp);
11650 		return (mp);
11651 	}
11652 
11653 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11654 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11655 		if (IPCL_IS_TCP(connp)) {
11656 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11657 			mp->b_datap->db_cksumstart =
11658 			    (intptr_t)ip_squeue_get(ill_ring);
11659 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11660 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11661 				SET_SQUEUE(mp, connp->conn_recv, connp);
11662 				return (mp);
11663 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11664 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11665 				ip_squeue_enter_unbound++;
11666 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11667 				    connp);
11668 				return (mp);
11669 			}
11670 			syn_present = B_TRUE;
11671 		}
11672 
11673 	}
11674 
11675 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11676 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11677 
11678 		/* No need to send this packet to TCP */
11679 		if ((flags & TH_RST) || (flags & TH_URG)) {
11680 			CONN_DEC_REF(connp);
11681 			freemsg(first_mp);
11682 			return (NULL);
11683 		}
11684 		if (flags & TH_ACK) {
11685 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11686 			CONN_DEC_REF(connp);
11687 			return (NULL);
11688 		}
11689 
11690 		CONN_DEC_REF(connp);
11691 		freemsg(first_mp);
11692 		return (NULL);
11693 	}
11694 
11695 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11696 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11697 		    ipha, NULL, mctl_present);
11698 		if (first_mp == NULL) {
11699 			CONN_DEC_REF(connp);
11700 			return (NULL);
11701 		}
11702 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11703 			ASSERT(syn_present);
11704 			if (mctl_present) {
11705 				ASSERT(first_mp != mp);
11706 				first_mp->b_datap->db_struioflag |=
11707 				    STRUIO_POLICY;
11708 			} else {
11709 				ASSERT(first_mp == mp);
11710 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11711 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11712 			}
11713 		} else {
11714 			/*
11715 			 * Discard first_mp early since we're dealing with a
11716 			 * fully-connected conn_t and tcp doesn't do policy in
11717 			 * this case.
11718 			 */
11719 			if (mctl_present) {
11720 				freeb(first_mp);
11721 				mctl_present = B_FALSE;
11722 			}
11723 			first_mp = mp;
11724 		}
11725 	}
11726 
11727 	/* Initiate IPPF processing for fastpath */
11728 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11729 		uint32_t	ill_index;
11730 
11731 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11732 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11733 		if (mp == NULL) {
11734 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11735 			    "deferred/dropped during IPPF processing\n"));
11736 			CONN_DEC_REF(connp);
11737 			if (mctl_present)
11738 				freeb(first_mp);
11739 			return (NULL);
11740 		} else if (mctl_present) {
11741 			/*
11742 			 * ip_process might return a new mp.
11743 			 */
11744 			ASSERT(first_mp != mp);
11745 			first_mp->b_cont = mp;
11746 		} else {
11747 			first_mp = mp;
11748 		}
11749 
11750 	}
11751 
11752 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11753 		mp = ip_add_info(mp, recv_ill, flags);
11754 		if (mp == NULL) {
11755 			CONN_DEC_REF(connp);
11756 			if (mctl_present)
11757 				freeb(first_mp);
11758 			return (NULL);
11759 		} else if (mctl_present) {
11760 			/*
11761 			 * ip_add_info might return a new mp.
11762 			 */
11763 			ASSERT(first_mp != mp);
11764 			first_mp->b_cont = mp;
11765 		} else {
11766 			first_mp = mp;
11767 		}
11768 	}
11769 
11770 	if (IPCL_IS_TCP(connp)) {
11771 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11772 		return (first_mp);
11773 	} else {
11774 		putnext(connp->conn_rq, first_mp);
11775 		CONN_DEC_REF(connp);
11776 		return (NULL);
11777 	}
11778 
11779 no_conn:
11780 	/* Initiate IPPf processing, if needed. */
11781 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11782 		uint32_t ill_index;
11783 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11784 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
11785 		if (first_mp == NULL) {
11786 			return (NULL);
11787 		}
11788 	}
11789 	BUMP_MIB(&ip_mib, ipInDelivers);
11790 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
11791 	return (NULL);
11792 ipoptions:
11793 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
11794 		goto slow_done;
11795 	}
11796 
11797 	UPDATE_IB_PKT_COUNT(ire);
11798 	ire->ire_last_used_time = lbolt;
11799 
11800 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11801 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11802 fragmented:
11803 		if (!ip_rput_fragment(q, &mp, ipha)) {
11804 			if (mctl_present)
11805 				freeb(first_mp);
11806 			goto slow_done;
11807 		}
11808 		/*
11809 		 * Make sure that first_mp points back to mp as
11810 		 * the mp we came in with could have changed in
11811 		 * ip_rput_fragment().
11812 		 */
11813 		ASSERT(!mctl_present);
11814 		ipha = (ipha_t *)mp->b_rptr;
11815 		first_mp = mp;
11816 	}
11817 
11818 tcp_slow:
11819 	/* Now we have a complete datagram, destined for this machine. */
11820 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
11821 
11822 	len = mp->b_wptr - mp->b_rptr;
11823 	/* Pull up a minimal TCP header, if necessary. */
11824 	if (len < (u1 + 20)) {
11825 tcppullup:
11826 		if (!pullupmsg(mp, u1 + 20)) {
11827 			BUMP_MIB(&ip_mib, ipInDiscards);
11828 			goto error;
11829 		}
11830 		ipha = (ipha_t *)mp->b_rptr;
11831 		len = mp->b_wptr - mp->b_rptr;
11832 	}
11833 
11834 	/*
11835 	 * Extract the offset field from the TCP header.  As usual, we
11836 	 * try to help the compiler more than the reader.
11837 	 */
11838 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
11839 	if (offset != 5) {
11840 tcpoptions:
11841 		if (offset < 5) {
11842 			BUMP_MIB(&ip_mib, ipInDiscards);
11843 			goto error;
11844 		}
11845 		/*
11846 		 * There must be TCP options.
11847 		 * Make sure we can grab them.
11848 		 */
11849 		offset <<= 2;
11850 		offset += u1;
11851 		if (len < offset) {
11852 			if (!pullupmsg(mp, offset)) {
11853 				BUMP_MIB(&ip_mib, ipInDiscards);
11854 				goto error;
11855 			}
11856 			ipha = (ipha_t *)mp->b_rptr;
11857 			len = mp->b_wptr - rptr;
11858 		}
11859 	}
11860 
11861 	/* Get the total packet length in len, including headers. */
11862 	if (mp->b_cont) {
11863 multipkttcp:
11864 		len = msgdsize(mp);
11865 	}
11866 
11867 	/*
11868 	 * Check the TCP checksum by pulling together the pseudo-
11869 	 * header checksum, and passing it to ip_csum to be added in
11870 	 * with the TCP datagram.
11871 	 *
11872 	 * Since we are not using the hwcksum if available we must
11873 	 * clear the flag. We may come here via tcppullup or tcpoptions.
11874 	 * If either of these fails along the way the mblk is freed.
11875 	 * If this logic ever changes and mblk is reused to say send
11876 	 * ICMP's back, then this flag may need to be cleared in
11877 	 * other places as well.
11878 	 */
11879 	mp->b_datap->db_struioun.cksum.flags = 0;
11880 
11881 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
11882 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
11883 #ifdef	_BIG_ENDIAN
11884 	u1 += IPPROTO_TCP;
11885 #else
11886 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11887 #endif
11888 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11889 	/*
11890 	 * Not M_DATA mblk or its a dup, so do the checksum now.
11891 	 */
11892 	IP_STAT(ip_in_sw_cksum);
11893 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1)) {
11894 		BUMP_MIB(&ip_mib, tcpInErrs);
11895 		goto error;
11896 	}
11897 
11898 	IP_STAT(ip_tcp_slow_path);
11899 	goto try_again;
11900 #undef  iphs
11901 #undef  rptr
11902 
11903 error:
11904 	freemsg(first_mp);
11905 slow_done:
11906 	return (NULL);
11907 }
11908 
11909 /* ARGSUSED */
11910 static void
11911 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11912     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
11913 {
11914 	conn_t		*connp;
11915 	uint32_t	sum;
11916 	uint32_t	u1;
11917 	ssize_t		len;
11918 	sctp_hdr_t	*sctph;
11919 	zoneid_t	zoneid = ire->ire_zoneid;
11920 	uint32_t	pktsum;
11921 	uint32_t	calcsum;
11922 	uint32_t	ports;
11923 	uint_t		ipif_seqid;
11924 	in6_addr_t	map_src, map_dst;
11925 	ill_t		*ill = (ill_t *)q->q_ptr;
11926 
11927 #define	rptr	((uchar_t *)ipha)
11928 
11929 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
11930 
11931 	/* u1 is # words of IP options */
11932 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11933 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11934 
11935 	/* IP options present */
11936 	if (u1 > 0) {
11937 		goto ipoptions;
11938 	} else {
11939 		/* Check the IP header checksum.  */
11940 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11941 			/*
11942 			 * Since there is no SCTP h/w cksum support yet, just
11943 			 * clear the flag.
11944 			 */
11945 			mp->b_datap->db_struioun.cksum.flags = 0;
11946 		} else {
11947 #define	uph	((uint16_t *)ipha)
11948 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11949 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11950 #undef	uph
11951 			/* finish doing IP checksum */
11952 			sum = (sum & 0xFFFF) + (sum >> 16);
11953 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11954 			/*
11955 			 * Don't verify header checksum if this packet
11956 			 * is coming back from AH/ESP as we already did it.
11957 			 */
11958 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11959 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11960 				goto error;
11961 			}
11962 		}
11963 	}
11964 
11965 	/*
11966 	 * Don't verify header checksum if this packet is coming
11967 	 * back from AH/ESP as we already did it.
11968 	 */
11969 	if (!mctl_present) {
11970 		UPDATE_IB_PKT_COUNT(ire);
11971 		ire->ire_last_used_time = lbolt;
11972 	}
11973 
11974 	/* packet part of fragmented IP packet? */
11975 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11976 	if (u1 & (IPH_MF | IPH_OFFSET))
11977 		goto fragmented;
11978 
11979 	/* u1 = IP header length (20 bytes) */
11980 	u1 = IP_SIMPLE_HDR_LENGTH;
11981 
11982 find_sctp_client:
11983 	/* Pullup if we don't have the sctp common header. */
11984 	len = MBLKL(mp);
11985 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
11986 		if (mp->b_cont == NULL ||
11987 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
11988 			BUMP_MIB(&ip_mib, ipInDiscards);
11989 			goto error;
11990 		}
11991 		ipha = (ipha_t *)mp->b_rptr;
11992 		len = MBLKL(mp);
11993 	}
11994 
11995 	sctph = (sctp_hdr_t *)(rptr + u1);
11996 #ifdef	DEBUG
11997 	if (!skip_sctp_cksum) {
11998 #endif
11999 		pktsum = sctph->sh_chksum;
12000 		sctph->sh_chksum = 0;
12001 		calcsum = sctp_cksum(mp, u1);
12002 		if (calcsum != pktsum) {
12003 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12004 			goto error;
12005 		}
12006 		sctph->sh_chksum = pktsum;
12007 #ifdef	DEBUG	/* skip_sctp_cksum */
12008 	}
12009 #endif
12010 	/* get the ports */
12011 	ports = *(uint32_t *)&sctph->sh_sport;
12012 
12013 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12014 	IRE_REFRELE(ire);
12015 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12016 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12017 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12018 	    zoneid)) == NULL) {
12019 		/* Check for raw socket or OOTB handling */
12020 		goto no_conn;
12021 	}
12022 
12023 	/* Found a client; up it goes */
12024 	BUMP_MIB(&ip_mib, ipInDelivers);
12025 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12026 	return;
12027 
12028 no_conn:
12029 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12030 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12031 	return;
12032 
12033 ipoptions:
12034 	mp->b_datap->db_struioun.cksum.flags = 0;
12035 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12036 		goto slow_done;
12037 
12038 	UPDATE_IB_PKT_COUNT(ire);
12039 	ire->ire_last_used_time = lbolt;
12040 
12041 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12042 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12043 fragmented:
12044 		if (!ip_rput_fragment(q, &mp, ipha))
12045 			goto slow_done;
12046 		/*
12047 		 * Make sure that first_mp points back to mp as
12048 		 * the mp we came in with could have changed in
12049 		 * ip_rput_fragment().
12050 		 */
12051 		ASSERT(!mctl_present);
12052 		ipha = (ipha_t *)mp->b_rptr;
12053 		first_mp = mp;
12054 	}
12055 
12056 	/* Now we have a complete datagram, destined for this machine. */
12057 	u1 = IPH_HDR_LENGTH(ipha);
12058 	goto find_sctp_client;
12059 #undef  iphs
12060 #undef  rptr
12061 
12062 error:
12063 	freemsg(first_mp);
12064 slow_done:
12065 	IRE_REFRELE(ire);
12066 }
12067 
12068 #define	VER_BITS	0xF0
12069 #define	VERSION_6	0x60
12070 
12071 static boolean_t
12072 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12073     ipaddr_t *dstp)
12074 {
12075 	uint_t	opt_len;
12076 	ipha_t *ipha;
12077 	ssize_t len;
12078 	uint_t	pkt_len;
12079 
12080 	IP_STAT(ip_ipoptions);
12081 	ipha = *iphapp;
12082 
12083 #define	rptr    ((uchar_t *)ipha)
12084 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12085 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12086 		BUMP_MIB(&ip_mib, ipInIPv6);
12087 		freemsg(mp);
12088 		return (B_FALSE);
12089 	}
12090 
12091 	/* multiple mblk or too short */
12092 	pkt_len = ntohs(ipha->ipha_length);
12093 
12094 	/* Get the number of words of IP options in the IP header. */
12095 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12096 	if (opt_len) {
12097 		/* IP Options present!  Validate and process. */
12098 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12099 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12100 			goto done;
12101 		}
12102 		/*
12103 		 * Recompute complete header length and make sure we
12104 		 * have access to all of it.
12105 		 */
12106 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12107 		if (len > (mp->b_wptr - rptr)) {
12108 			if (len > pkt_len) {
12109 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12110 				goto done;
12111 			}
12112 			if (!pullupmsg(mp, len)) {
12113 				BUMP_MIB(&ip_mib, ipInDiscards);
12114 				goto done;
12115 			}
12116 			ipha = (ipha_t *)mp->b_rptr;
12117 		}
12118 		/*
12119 		 * Go off to ip_rput_options which returns the next hop
12120 		 * destination address, which may have been affected
12121 		 * by source routing.
12122 		 */
12123 		IP_STAT(ip_opt);
12124 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12125 			return (B_FALSE);
12126 		}
12127 	}
12128 	*iphapp = ipha;
12129 	return (B_TRUE);
12130 done:
12131 	/* clear b_prev - used by ip_mroute_decap */
12132 	mp->b_prev = NULL;
12133 	freemsg(mp);
12134 	return (B_FALSE);
12135 #undef  rptr
12136 }
12137 
12138 /*
12139  * Deal with the fact that there is no ire for the destination.
12140  * The incoming ill (in_ill) is passed in to ip_newroute only
12141  * in the case of packets coming from mobile ip forward tunnel.
12142  * It must be null otherwise.
12143  */
12144 static void
12145 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12146     ipaddr_t dst)
12147 {
12148 	ipha_t	*ipha;
12149 	ill_t	*ill;
12150 
12151 	ipha = (ipha_t *)mp->b_rptr;
12152 	ill = (ill_t *)q->q_ptr;
12153 
12154 	ASSERT(ill != NULL);
12155 	/*
12156 	 * No IRE for this destination, so it can't be for us.
12157 	 * Unless we are forwarding, drop the packet.
12158 	 * We have to let source routed packets through
12159 	 * since we don't yet know if they are 'ping -l'
12160 	 * packets i.e. if they will go out over the
12161 	 * same interface as they came in on.
12162 	 */
12163 	if (ll_multicast) {
12164 		freemsg(mp);
12165 		return;
12166 	}
12167 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12168 		BUMP_MIB(&ip_mib, ipForwProhibits);
12169 		freemsg(mp);
12170 		return;
12171 	}
12172 
12173 	/* Check for Martian addresses */
12174 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12175 		freemsg(mp);
12176 		return;
12177 	}
12178 
12179 	/* Mark this packet as having originated externally */
12180 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12181 
12182 	/*
12183 	 * Clear the indication that this may have a hardware checksum
12184 	 * as we are not using it
12185 	 */
12186 	mp->b_datap->db_struioun.cksum.flags = 0;
12187 
12188 	/*
12189 	 * Now hand the packet to ip_newroute.
12190 	 */
12191 	ip_newroute(q, mp, dst, in_ill, NULL);
12192 }
12193 
12194 /*
12195  * check ip header length and align it.
12196  */
12197 static boolean_t
12198 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12199 {
12200 	ssize_t len;
12201 	ill_t *ill;
12202 	ipha_t	*ipha;
12203 
12204 	len = MBLKL(mp);
12205 
12206 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12207 		if (!OK_32PTR(mp->b_rptr))
12208 			IP_STAT(ip_notaligned1);
12209 		else
12210 			IP_STAT(ip_notaligned2);
12211 		/* Guard against bogus device drivers */
12212 		if (len < 0) {
12213 			/* clear b_prev - used by ip_mroute_decap */
12214 			mp->b_prev = NULL;
12215 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12216 			freemsg(mp);
12217 			return (B_FALSE);
12218 		}
12219 
12220 		if (ip_rput_pullups++ == 0) {
12221 			ill = (ill_t *)q->q_ptr;
12222 			ipha = (ipha_t *)mp->b_rptr;
12223 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12224 			    "ip_check_and_align_header: %s forced us to "
12225 			    " pullup pkt, hdr len %ld, hdr addr %p",
12226 			    ill->ill_name, len, ipha);
12227 		}
12228 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12229 			/* clear b_prev - used by ip_mroute_decap */
12230 			mp->b_prev = NULL;
12231 			BUMP_MIB(&ip_mib, ipInDiscards);
12232 			freemsg(mp);
12233 			return (B_FALSE);
12234 		}
12235 	}
12236 	return (B_TRUE);
12237 }
12238 
12239 static boolean_t
12240 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12241 {
12242 	ill_group_t	*ill_group;
12243 	ill_group_t	*ire_group;
12244 	queue_t 	*q;
12245 	ill_t		*ire_ill;
12246 	uint_t		ill_ifindex;
12247 
12248 	q = *qp;
12249 	/*
12250 	 * We need to check to make sure the packet came in
12251 	 * on the queue associated with the destination IRE.
12252 	 * Note that for multicast packets and broadcast packets sent to
12253 	 * a broadcast address which is shared between multiple interfaces
12254 	 * we should not do this since we just got a random broadcast ire.
12255 	 */
12256 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12257 		boolean_t check_multi = B_TRUE;
12258 
12259 		/*
12260 		 * This packet came in on an interface other than the
12261 		 * one associated with the destination address.
12262 		 * "Gateway" it to the appropriate interface here.
12263 		 * As long as the ills belong to the same group,
12264 		 * we don't consider them to arriving on the wrong
12265 		 * interface. Thus, when the switch is doing inbound
12266 		 * load spreading, we won't drop packets when we
12267 		 * are doing strict multihoming checks. Note, the
12268 		 * same holds true for 'usesrc groups' where the
12269 		 * destination address may belong to another interface
12270 		 * to allow multipathing to happen
12271 		 */
12272 		ill_group = ill->ill_group;
12273 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12274 		ill_ifindex = ill->ill_usesrc_ifindex;
12275 		ire_group = ire_ill->ill_group;
12276 
12277 		/*
12278 		 * If it's part of the same IPMP group, or if it's a legal
12279 		 * address on the 'usesrc' interface, then bypass strict
12280 		 * checks.
12281 		 */
12282 		if (ill_group != NULL && ill_group == ire_group) {
12283 			check_multi = B_FALSE;
12284 		} else if (ill_ifindex != 0 &&
12285 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12286 			check_multi = B_FALSE;
12287 		}
12288 
12289 		if (check_multi &&
12290 		    ip_strict_dst_multihoming &&
12291 		    ((ill->ill_flags &
12292 		    ire->ire_ipif->ipif_ill->ill_flags &
12293 		    ILLF_ROUTER) == 0)) {
12294 			/* Drop packet */
12295 			BUMP_MIB(&ip_mib, ipForwProhibits);
12296 			freemsg(mp);
12297 			ire_refrele(ire);
12298 			return (B_TRUE);
12299 		}
12300 
12301 		/*
12302 		 * Change the queue (for non-virtual destination network
12303 		 * interfaces) and ip_rput_local will be called with the right
12304 		 * queue
12305 		 */
12306 		q = ire->ire_rfq;
12307 	}
12308 	/* Must be broadcast.  We'll take it. */
12309 	*qp = q;
12310 	return (B_FALSE);
12311 }
12312 
12313 static void
12314 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12315     ill_t *ill, int ll_multicast)
12316 {
12317 	ill_group_t	*ill_group;
12318 	ill_group_t	*ire_group;
12319 	queue_t	*dev_q;
12320 
12321 	ASSERT(ire->ire_stq != NULL);
12322 	if (ll_multicast != 0)
12323 		goto drop_pkt;
12324 
12325 	if (ip_no_forward(ipha, ill))
12326 		goto drop_pkt;
12327 
12328 	ill_group = ill->ill_group;
12329 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12330 	/*
12331 	 * Check if we want to forward this one at this time.
12332 	 * We allow source routed packets on a host provided that
12333 	 * they go out the same interface or same interface group
12334 	 * as they came in on.
12335 	 *
12336 	 * XXX To be quicker, we may wish to not chase pointers to
12337 	 * get the ILLF_ROUTER flag and instead store the
12338 	 * forwarding policy in the ire.  An unfortunate
12339 	 * side-effect of that would be requiring an ire flush
12340 	 * whenever the ILLF_ROUTER flag changes.
12341 	 */
12342 	if (((ill->ill_flags &
12343 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12344 	    ILLF_ROUTER) == 0) &&
12345 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12346 	    (ill_group != NULL && ill_group == ire_group)))) {
12347 		BUMP_MIB(&ip_mib, ipForwProhibits);
12348 		if (ip_source_routed(ipha)) {
12349 			q = WR(q);
12350 			/*
12351 			 * Clear the indication that this may have
12352 			 * hardware checksum as we are not using it.
12353 			 */
12354 			mp->b_datap->db_struioun.cksum.flags = 0;
12355 			icmp_unreachable(q, mp,
12356 			    ICMP_SOURCE_ROUTE_FAILED);
12357 			ire_refrele(ire);
12358 			return;
12359 		}
12360 		goto drop_pkt;
12361 	}
12362 
12363 	/* Packet is being forwarded. Turning off hwcksum flag. */
12364 	mp->b_datap->db_struioun.cksum.flags = 0;
12365 	if (ip_g_send_redirects) {
12366 		/*
12367 		 * Check whether the incoming interface and outgoing
12368 		 * interface is part of the same group. If so,
12369 		 * send redirects.
12370 		 *
12371 		 * Check the source address to see if it originated
12372 		 * on the same logical subnet it is going back out on.
12373 		 * If so, we should be able to send it a redirect.
12374 		 * Avoid sending a redirect if the destination
12375 		 * is directly connected (gw_addr == 0),
12376 		 * or if the packet was source routed out this
12377 		 * interface.
12378 		 */
12379 		ipaddr_t src;
12380 		mblk_t	*mp1;
12381 		ire_t	*src_ire = NULL;
12382 
12383 		/*
12384 		 * Check whether ire_rfq and q are from the same ill
12385 		 * or if they are not same, they at least belong
12386 		 * to the same group. If so, send redirects.
12387 		 */
12388 		if ((ire->ire_rfq == q ||
12389 		    (ill_group != NULL && ill_group == ire_group)) &&
12390 		    (ire->ire_gateway_addr != 0) &&
12391 		    !ip_source_routed(ipha)) {
12392 
12393 			src = ipha->ipha_src;
12394 			src_ire = ire_ftable_lookup(src, 0, 0,
12395 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12396 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12397 
12398 			if (src_ire != NULL) {
12399 				/*
12400 				 * The source is directly connected.
12401 				 * Just copy the ip header (which is
12402 				 * in the first mblk)
12403 				 */
12404 				mp1 = copyb(mp);
12405 				if (mp1 != NULL) {
12406 					icmp_send_redirect(WR(q), mp1,
12407 					    ire->ire_gateway_addr);
12408 				}
12409 				ire_refrele(src_ire);
12410 			}
12411 		}
12412 	}
12413 
12414 	dev_q = ire->ire_stq->q_next;
12415 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12416 		BUMP_MIB(&ip_mib, ipInDiscards);
12417 		freemsg(mp);
12418 		ire_refrele(ire);
12419 		return;
12420 	}
12421 
12422 	ip_rput_forward(ire, ipha, mp, ill);
12423 	IRE_REFRELE(ire);
12424 	return;
12425 
12426 drop_pkt:
12427 	ire_refrele(ire);
12428 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12429 	freemsg(mp);
12430 }
12431 
12432 static boolean_t
12433 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12434     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12435 {
12436 	queue_t		*q;
12437 	ire_t		*ire;
12438 
12439 	q = *qp;
12440 	ire = *irep;
12441 
12442 	/*
12443 	 * Clear the indication that this may have hardware
12444 	 * checksum as we are not using it.
12445 	 */
12446 	mp->b_datap->db_struioun.cksum.flags = 0;
12447 
12448 	/*
12449 	 * Directed broadcast forwarding: if the packet came in over a
12450 	 * different interface then it is routed out over we can forward it.
12451 	 */
12452 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12453 		ire_refrele(ire);
12454 		freemsg(mp);
12455 		BUMP_MIB(&ip_mib, ipInDiscards);
12456 		return (B_TRUE);
12457 	}
12458 	/*
12459 	 * For multicast we have set dst to be INADDR_BROADCAST
12460 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12461 	 * only for broadcast packets.
12462 	 */
12463 	if (!CLASSD(ipha->ipha_dst)) {
12464 		ire_t *new_ire;
12465 		ipif_t *ipif;
12466 		/*
12467 		 * For ill groups, as the switch duplicates broadcasts
12468 		 * across all the ports, we need to filter out and
12469 		 * send up only one copy. There is one copy for every
12470 		 * broadcast address on each ill. Thus, we look for a
12471 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12472 		 * later to see whether this ill is eligible to receive
12473 		 * them or not. ill_nominate_bcast_rcv() nominates only
12474 		 * one set of IREs for receiving.
12475 		 */
12476 
12477 		ipif = ipif_get_next_ipif(NULL, ill);
12478 		if (ipif == NULL) {
12479 			ire_refrele(ire);
12480 			freemsg(mp);
12481 			BUMP_MIB(&ip_mib, ipInDiscards);
12482 			return (B_TRUE);
12483 		}
12484 		new_ire = ire_ctable_lookup(dst, 0, 0,
12485 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12486 		ipif_refrele(ipif);
12487 
12488 		if (new_ire != NULL) {
12489 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12490 				ire_refrele(ire);
12491 				ire_refrele(new_ire);
12492 				freemsg(mp);
12493 				BUMP_MIB(&ip_mib, ipInDiscards);
12494 				return (B_TRUE);
12495 			}
12496 			/*
12497 			 * In the special case of multirouted broadcast
12498 			 * packets, we unconditionally need to "gateway"
12499 			 * them to the appropriate interface here.
12500 			 * In the normal case, this cannot happen, because
12501 			 * there is no broadcast IRE tagged with the
12502 			 * RTF_MULTIRT flag.
12503 			 */
12504 			if (new_ire->ire_flags & RTF_MULTIRT) {
12505 				ire_refrele(new_ire);
12506 				if (ire->ire_rfq != NULL) {
12507 					q = ire->ire_rfq;
12508 					*qp = q;
12509 				}
12510 			} else {
12511 				ire_refrele(ire);
12512 				ire = new_ire;
12513 			}
12514 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12515 			if (!ip_g_forward_directed_bcast) {
12516 				/*
12517 				 * Free the message if
12518 				 * ip_g_forward_directed_bcast is turned
12519 				 * off for non-local broadcast.
12520 				 */
12521 				ire_refrele(ire);
12522 				freemsg(mp);
12523 				BUMP_MIB(&ip_mib, ipInDiscards);
12524 				return (B_TRUE);
12525 			}
12526 		} else {
12527 			/*
12528 			 * This CGTP packet successfully passed the
12529 			 * CGTP filter, but the related CGTP
12530 			 * broadcast IRE has not been found,
12531 			 * meaning that the redundant ipif is
12532 			 * probably down. However, if we discarded
12533 			 * this packet, its duplicate would be
12534 			 * filtered out by the CGTP filter so none
12535 			 * of them would get through. So we keep
12536 			 * going with this one.
12537 			 */
12538 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12539 			if (ire->ire_rfq != NULL) {
12540 				q = ire->ire_rfq;
12541 				*qp = q;
12542 			}
12543 		}
12544 	}
12545 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12546 		/*
12547 		 * Verify that there are not more then one
12548 		 * IRE_BROADCAST with this broadcast address which
12549 		 * has ire_stq set.
12550 		 * TODO: simplify, loop over all IRE's
12551 		 */
12552 		ire_t	*ire1;
12553 		int	num_stq = 0;
12554 		mblk_t	*mp1;
12555 
12556 		/* Find the first one with ire_stq set */
12557 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12558 		for (ire1 = ire; ire1 &&
12559 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12560 		    ire1 = ire1->ire_next)
12561 			;
12562 		if (ire1) {
12563 			ire_refrele(ire);
12564 			ire = ire1;
12565 			IRE_REFHOLD(ire);
12566 		}
12567 
12568 		/* Check if there are additional ones with stq set */
12569 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12570 			if (ire->ire_addr != ire1->ire_addr)
12571 				break;
12572 			if (ire1->ire_stq) {
12573 				num_stq++;
12574 				break;
12575 			}
12576 		}
12577 		rw_exit(&ire->ire_bucket->irb_lock);
12578 		if (num_stq == 1 && ire->ire_stq != NULL) {
12579 			ip1dbg(("ip_rput_process_broadcast: directed "
12580 			    "broadcast to 0x%x\n",
12581 			    ntohl(ire->ire_addr)));
12582 			mp1 = copymsg(mp);
12583 			if (mp1) {
12584 				switch (ipha->ipha_protocol) {
12585 				case IPPROTO_UDP:
12586 					ip_udp_input(q, mp1, ipha, ire, ill);
12587 					break;
12588 				default:
12589 					ip_proto_input(q, mp1, ipha, ire, ill);
12590 					break;
12591 				}
12592 			}
12593 			/*
12594 			 * Adjust ttl to 2 (1+1 - the forward engine
12595 			 * will decrement it by one.
12596 			 */
12597 			if (ip_csum_hdr(ipha)) {
12598 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12599 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12600 				freemsg(mp);
12601 				ire_refrele(ire);
12602 				return (B_TRUE);
12603 			}
12604 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12605 			ipha->ipha_hdr_checksum = 0;
12606 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12607 			ip_rput_process_forward(q, mp, ire, ipha,
12608 			    ill, ll_multicast);
12609 			return (B_TRUE);
12610 		}
12611 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12612 		    ntohl(ire->ire_addr)));
12613 	}
12614 
12615 	*irep = ire;
12616 	return (B_FALSE);
12617 }
12618 
12619 /* ARGSUSED */
12620 static boolean_t
12621 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12622     int *ll_multicast, ipaddr_t *dstp)
12623 {
12624 	/*
12625 	 * Forward packets only if we have joined the allmulti
12626 	 * group on this interface.
12627 	 */
12628 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12629 		int retval;
12630 
12631 		/*
12632 		 * Clear the indication that this may have hardware
12633 		 * checksum as we are not using it.
12634 		 */
12635 		mp->b_datap->db_struioun.cksum.flags = 0;
12636 		retval = ip_mforward(ill, ipha, mp);
12637 		/* ip_mforward updates mib variables if needed */
12638 		/* clear b_prev - used by ip_mroute_decap */
12639 		mp->b_prev = NULL;
12640 
12641 		switch (retval) {
12642 		case 0:
12643 			/*
12644 			 * pkt is okay and arrived on phyint.
12645 			 *
12646 			 * If we are running as a multicast router
12647 			 * we need to see all IGMP and/or PIM packets.
12648 			 */
12649 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12650 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12651 				goto done;
12652 			}
12653 			break;
12654 		case -1:
12655 			/* pkt is mal-formed, toss it */
12656 			goto drop_pkt;
12657 		case 1:
12658 			/* pkt is okay and arrived on a tunnel */
12659 			/*
12660 			 * If we are running a multicast router
12661 			 *  we need to see all igmp packets.
12662 			 */
12663 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12664 				*dstp = INADDR_BROADCAST;
12665 				*ll_multicast = 1;
12666 				return (B_FALSE);
12667 			}
12668 
12669 			goto drop_pkt;
12670 		}
12671 	}
12672 
12673 	ILM_WALKER_HOLD(ill);
12674 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12675 		/*
12676 		 * This might just be caused by the fact that
12677 		 * multiple IP Multicast addresses map to the same
12678 		 * link layer multicast - no need to increment counter!
12679 		 */
12680 		ILM_WALKER_RELE(ill);
12681 		freemsg(mp);
12682 		return (B_TRUE);
12683 	}
12684 	ILM_WALKER_RELE(ill);
12685 done:
12686 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12687 	/*
12688 	 * This assumes the we deliver to all streams for multicast
12689 	 * and broadcast packets.
12690 	 */
12691 	*dstp = INADDR_BROADCAST;
12692 	*ll_multicast = 1;
12693 	return (B_FALSE);
12694 drop_pkt:
12695 	ip2dbg(("ip_rput: drop pkt\n"));
12696 	freemsg(mp);
12697 	return (B_TRUE);
12698 }
12699 
12700 static boolean_t
12701 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12702     int *ll_multicast, mblk_t **mpp)
12703 {
12704 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12705 	boolean_t must_copy = B_FALSE;
12706 	struct iocblk   *iocp;
12707 	ipha_t		*ipha;
12708 
12709 #define	rptr    ((uchar_t *)ipha)
12710 
12711 	first_mp = *first_mpp;
12712 	mp = *mpp;
12713 
12714 	ASSERT(first_mp == mp);
12715 
12716 	/*
12717 	 * if db_ref > 1 then copymsg and free original. Packet may be
12718 	 * changed and do not want other entity who has a reference to this
12719 	 * message to trip over the changes. This is a blind change because
12720 	 * trying to catch all places that might change packet is too
12721 	 * difficult (since it may be a module above this one)
12722 	 *
12723 	 * This corresponds to the non-fast path case. We walk down the full
12724 	 * chain in this case, and check the db_ref count of all the dblks,
12725 	 * and do a copymsg if required. It is possible that the db_ref counts
12726 	 * of the data blocks in the mblk chain can be different.
12727 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12728 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12729 	 * 'snoop' is running.
12730 	 */
12731 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12732 		if (mp1->b_datap->db_ref > 1) {
12733 			must_copy = B_TRUE;
12734 			break;
12735 		}
12736 	}
12737 
12738 	if (must_copy) {
12739 		mp1 = copymsg(mp);
12740 		if (mp1 == NULL) {
12741 			for (mp1 = mp; mp1 != NULL;
12742 			    mp1 = mp1->b_cont) {
12743 				mp1->b_next = NULL;
12744 				mp1->b_prev = NULL;
12745 			}
12746 			freemsg(mp);
12747 			BUMP_MIB(&ip_mib, ipInDiscards);
12748 			return (B_TRUE);
12749 		}
12750 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12751 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12752 			/* Copy b_next - used in M_BREAK messages */
12753 			to_mp->b_next = from_mp->b_next;
12754 			from_mp->b_next = NULL;
12755 			/* Copy b_prev - used by ip_mroute_decap */
12756 			to_mp->b_prev = from_mp->b_prev;
12757 			from_mp->b_prev = NULL;
12758 		}
12759 		*first_mpp = first_mp = mp1;
12760 		freemsg(mp);
12761 		mp = mp1;
12762 		*mpp = mp1;
12763 	}
12764 
12765 	ipha = (ipha_t *)mp->b_rptr;
12766 
12767 	/*
12768 	 * previous code has a case for M_DATA.
12769 	 * We want to check how that happens.
12770 	 */
12771 	ASSERT(first_mp->b_datap->db_type != M_DATA);
12772 	switch (first_mp->b_datap->db_type) {
12773 	case M_PROTO:
12774 	case M_PCPROTO:
12775 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
12776 		    DL_UNITDATA_IND) {
12777 			/* Go handle anything other than data elsewhere. */
12778 			ip_rput_dlpi(q, mp);
12779 			return (B_TRUE);
12780 		}
12781 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
12782 		/* Ditch the DLPI header. */
12783 		mp1 = mp->b_cont;
12784 		ASSERT(first_mp == mp);
12785 		*first_mpp = mp1;
12786 		freeb(mp);
12787 		*mpp = mp1;
12788 		return (B_FALSE);
12789 	case M_BREAK:
12790 		/*
12791 		 * A packet arrives as M_BREAK following a cycle through
12792 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
12793 		 * This is an IP datagram sans lower level header.
12794 		 * M_BREAK are also used to pass back in multicast packets
12795 		 * that are encapsulated with a source route.
12796 		 */
12797 		/* Ditch the M_BREAK mblk */
12798 		mp1 = mp->b_cont;
12799 		ASSERT(first_mp == mp);
12800 		*first_mpp = mp1;
12801 		freeb(mp);
12802 		mp = mp1;
12803 		mp->b_next = NULL;
12804 		*mpp = mp;
12805 		*ll_multicast = 0;
12806 		return (B_FALSE);
12807 	case M_IOCACK:
12808 		ip1dbg(("got iocack "));
12809 		iocp = (struct iocblk *)mp->b_rptr;
12810 		switch (iocp->ioc_cmd) {
12811 		case DL_IOC_HDR_INFO:
12812 			ill = (ill_t *)q->q_ptr;
12813 			ill_fastpath_ack(ill, mp);
12814 			return (B_TRUE);
12815 		case SIOCSTUNPARAM:
12816 		case OSIOCSTUNPARAM:
12817 			/* Go through qwriter_ip */
12818 			break;
12819 		case SIOCGTUNPARAM:
12820 		case OSIOCGTUNPARAM:
12821 			ip_rput_other(NULL, q, mp, NULL);
12822 			return (B_TRUE);
12823 		default:
12824 			putnext(q, mp);
12825 			return (B_TRUE);
12826 		}
12827 		/* FALLTHRU */
12828 	case M_ERROR:
12829 	case M_HANGUP:
12830 		/*
12831 		 * Since this is on the ill stream we unconditionally
12832 		 * bump up the refcount
12833 		 */
12834 		ill_refhold(ill);
12835 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
12836 		    B_FALSE);
12837 		return (B_TRUE);
12838 	case M_CTL:
12839 /* EXPORT DELETE START */
12840 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
12841 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
12842 			IPHADA_M_CTL)) {
12843 			/*
12844 			 * It's an IPsec accelerated packet.
12845 			 * Make sure that the ill from which we received the
12846 			 * packet has enabled IPsec hardware acceleration.
12847 			 */
12848 			if (!(ill->ill_capabilities &
12849 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
12850 				/* IPsec kstats: bean counter */
12851 				freemsg(mp);
12852 				return (B_TRUE);
12853 			}
12854 
12855 			/*
12856 			 * Make mp point to the mblk following the M_CTL,
12857 			 * then process according to type of mp.
12858 			 * After this processing, first_mp will point to
12859 			 * the data-attributes and mp to the pkt following
12860 			 * the M_CTL.
12861 			 */
12862 			mp = first_mp->b_cont;
12863 			if (mp == NULL) {
12864 				freemsg(first_mp);
12865 				return (B_TRUE);
12866 			}
12867 			/*
12868 			 * A Hardware Accelerated packet can only be M_DATA
12869 			 * ESP or AH packet.
12870 			 */
12871 			if (mp->b_datap->db_type != M_DATA) {
12872 				/* non-M_DATA IPsec accelerated packet */
12873 				IPSECHW_DEBUG(IPSECHW_PKT,
12874 				    ("non-M_DATA IPsec accelerated pkt\n"));
12875 				freemsg(first_mp);
12876 				return (B_TRUE);
12877 			}
12878 			ipha = (ipha_t *)mp->b_rptr;
12879 			if (ipha->ipha_protocol != IPPROTO_AH &&
12880 			    ipha->ipha_protocol != IPPROTO_ESP) {
12881 				IPSECHW_DEBUG(IPSECHW_PKT,
12882 				    ("non-M_DATA IPsec accelerated pkt\n"));
12883 				freemsg(first_mp);
12884 				return (B_TRUE);
12885 			}
12886 			*mpp = mp;
12887 			return (B_FALSE);
12888 		}
12889 /* EXPORT DELETE END */
12890 		putnext(q, mp);
12891 		return (B_TRUE);
12892 	case M_FLUSH:
12893 		if (*mp->b_rptr & FLUSHW) {
12894 			*mp->b_rptr &= ~FLUSHR;
12895 			qreply(q, mp);
12896 			return (B_TRUE);
12897 		}
12898 		freemsg(mp);
12899 		return (B_TRUE);
12900 	case M_IOCNAK:
12901 		ip1dbg(("got iocnak "));
12902 		iocp = (struct iocblk *)mp->b_rptr;
12903 		switch (iocp->ioc_cmd) {
12904 		case DL_IOC_HDR_INFO:
12905 		case SIOCSTUNPARAM:
12906 		case OSIOCSTUNPARAM:
12907 			/*
12908 			 * Since this is on the ill stream we unconditionally
12909 			 * bump up the refcount
12910 			 */
12911 			ill_refhold(ill);
12912 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
12913 			    CUR_OP, B_FALSE);
12914 			return (B_TRUE);
12915 		case SIOCGTUNPARAM:
12916 		case OSIOCGTUNPARAM:
12917 			ip_rput_other(NULL, q, mp, NULL);
12918 			return (B_TRUE);
12919 		default:
12920 			break;
12921 		}
12922 		/* FALLTHRU */
12923 	default:
12924 		putnext(q, mp);
12925 		return (B_TRUE);
12926 	}
12927 }
12928 
12929 /* Read side put procedure.  Packets coming from the wire arrive here. */
12930 void
12931 ip_rput(queue_t *q, mblk_t *mp)
12932 {
12933 	ill_t		*ill;
12934 
12935 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
12936 
12937 	ill = (ill_t *)q->q_ptr;
12938 
12939 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
12940 		union DL_primitives *dl;
12941 
12942 		/*
12943 		 * Things are opening or closing. Only accept DLPI control
12944 		 * messages. In the open case, the ill->ill_ipif has not yet
12945 		 * been created. In the close case, things hanging off the
12946 		 * ill could have been freed already. In either case it
12947 		 * may not be safe to proceed further.
12948 		 */
12949 
12950 		dl = (union DL_primitives *)mp->b_rptr;
12951 		if ((mp->b_datap->db_type != M_PCPROTO) ||
12952 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
12953 			/*
12954 			 * Also SIOC[GS]TUN* ioctls can come here.
12955 			 */
12956 			ip_ioctl_freemsg(mp);
12957 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
12958 			    "ip_input_end: q %p (%S)", q, "uninit");
12959 			return;
12960 		}
12961 	}
12962 
12963 	/*
12964 	 * if db_ref > 1 then copymsg and free original. Packet may be
12965 	 * changed and we do not want the other entity who has a reference to
12966 	 * this message to trip over the changes. This is a blind change because
12967 	 * trying to catch all places that might change the packet is too
12968 	 * difficult.
12969 	 *
12970 	 * This corresponds to the fast path case, where we have a chain of
12971 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
12972 	 * in the mblk chain. There doesn't seem to be a reason why a device
12973 	 * driver would send up data with varying db_ref counts in the mblk
12974 	 * chain. In any case the Fast path is a private interface, and our
12975 	 * drivers don't do such a thing. Given the above assumption, there is
12976 	 * no need to walk down the entire mblk chain (which could have a
12977 	 * potential performance problem)
12978 	 */
12979 	if (mp->b_datap->db_ref > 1) {
12980 		mblk_t  *mp1;
12981 		boolean_t adjusted = B_FALSE;
12982 		IP_STAT(ip_db_ref);
12983 
12984 		/*
12985 		 * The IP_RECVSLLA option depends on having the link layer
12986 		 * header. First check that:
12987 		 * a> the underlying device is of type ether, since this
12988 		 * option is currently supported only over ethernet.
12989 		 * b> there is enough room to copy over the link layer header.
12990 		 *
12991 		 * Once the checks are done, adjust rptr so that the link layer
12992 		 * header will be copied via copymsg. Note that, IFT_ETHER may
12993 		 * be returned by some non-ethernet drivers but in this case the
12994 		 * second check will fail.
12995 		 */
12996 		if (ill->ill_type == IFT_ETHER &&
12997 		    (mp->b_rptr - mp->b_datap->db_base) >=
12998 		    sizeof (struct ether_header)) {
12999 			mp->b_rptr -= sizeof (struct ether_header);
13000 			adjusted = B_TRUE;
13001 		}
13002 		mp1 = copymsg(mp);
13003 		if (mp1 == NULL) {
13004 			/* Clear b_next - used in M_BREAK messages */
13005 			mp->b_next = NULL;
13006 			/* clear b_prev - used by ip_mroute_decap */
13007 			mp->b_prev = NULL;
13008 			freemsg(mp);
13009 			BUMP_MIB(&ip_mib, ipInDiscards);
13010 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13011 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13012 			return;
13013 		}
13014 		if (adjusted) {
13015 			/*
13016 			 * Copy is done. Restore the pointer in the _new_ mblk
13017 			 */
13018 			mp1->b_rptr += sizeof (struct ether_header);
13019 		}
13020 		/* Copy b_next - used in M_BREAK messages */
13021 		mp1->b_next = mp->b_next;
13022 		mp->b_next = NULL;
13023 		/* Copy b_prev - used by ip_mroute_decap */
13024 		mp1->b_prev = mp->b_prev;
13025 		mp->b_prev = NULL;
13026 		freemsg(mp);
13027 		mp = mp1;
13028 	}
13029 
13030 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13031 	    "ip_rput_end: q %p (%S)", q, "end");
13032 
13033 	ip_input(ill, NULL, mp, 0);
13034 }
13035 
13036 /*
13037  * Direct read side procedure capable of dealing with chains. GLDv3 based
13038  * drivers call this function directly with mblk chains while STREAMS
13039  * read side procedure ip_rput() calls this for single packet with ip_ring
13040  * set to NULL to process one packet at a time.
13041  *
13042  * The ill will always be valid if this function is called directly from
13043  * the driver.
13044  */
13045 /*ARGSUSED*/
13046 void
13047 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13048 {
13049 	ipaddr_t		dst;
13050 	ire_t			*ire;
13051 	ipha_t			*ipha;
13052 	uint_t			pkt_len;
13053 	ssize_t			len;
13054 	uint_t			opt_len;
13055 	int			ll_multicast;
13056 	int			cgtp_flt_pkt;
13057 	queue_t			*q = ill->ill_rq;
13058 	squeue_t		*curr_sqp = NULL;
13059 	mblk_t 			*head = NULL;
13060 	mblk_t			*tail = NULL;
13061 	mblk_t			*first_mp;
13062 	mblk_t 			*mp;
13063 	int			cnt = 0;
13064 
13065 	ASSERT(mp_chain != NULL);
13066 	ASSERT(ill != NULL);
13067 
13068 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13069 
13070 #define	rptr	((uchar_t *)ipha)
13071 
13072 	while (mp_chain != NULL) {
13073 		first_mp = mp = mp_chain;
13074 		mp_chain = mp_chain->b_next;
13075 		mp->b_next = NULL;
13076 		ll_multicast = 0;
13077 		ire = NULL;
13078 
13079 		/*
13080 		 * ip_input fast path
13081 		 */
13082 
13083 		/* mblk type is not M_DATA */
13084 		if (mp->b_datap->db_type != M_DATA) {
13085 			if (ip_rput_process_notdata(q, &first_mp, ill,
13086 			    &ll_multicast, &mp))
13087 				continue;
13088 		}
13089 
13090 		ASSERT(mp->b_datap->db_type == M_DATA);
13091 		ASSERT(mp->b_datap->db_ref == 1);
13092 
13093 		/*
13094 		 * Invoke the CGTP (multirouting) filtering module to process
13095 		 * the incoming packet. Packets identified as duplicates
13096 		 * must be discarded. Filtering is active only if the
13097 		 * the ip_cgtp_filter ndd variable is non-zero.
13098 		 */
13099 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13100 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13101 			cgtp_flt_pkt =
13102 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13103 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13104 				freemsg(first_mp);
13105 				continue;
13106 			}
13107 		}
13108 
13109 		ipha = (ipha_t *)mp->b_rptr;
13110 		len = mp->b_wptr - rptr;
13111 
13112 		BUMP_MIB(&ip_mib, ipInReceives);
13113 
13114 		/*
13115 		 * IP header ptr not aligned?
13116 		 * OR IP header not complete in first mblk
13117 		 */
13118 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13119 			if (!ip_check_and_align_header(q, mp))
13120 				continue;
13121 			ipha = (ipha_t *)mp->b_rptr;
13122 			len = mp->b_wptr - rptr;
13123 		}
13124 
13125 		/* multiple mblk or too short */
13126 		pkt_len = ntohs(ipha->ipha_length);
13127 		len -= pkt_len;
13128 		if (len != 0) {
13129 			/*
13130 			 * Make sure we have data length consistent
13131 			 * with the IP header.
13132 			 */
13133 			if (mp->b_cont == NULL) {
13134 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13135 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13136 					ip2dbg(("ip_input: drop pkt\n"));
13137 					freemsg(mp);
13138 					continue;
13139 				}
13140 				mp->b_wptr = rptr + pkt_len;
13141 			} else if (len += msgdsize(mp->b_cont)) {
13142 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13143 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13144 					ip2dbg(("ip_input: drop pkt\n"));
13145 					freemsg(mp);
13146 					continue;
13147 				}
13148 				(void) adjmsg(mp, -len);
13149 				IP_STAT(ip_multimblk3);
13150 			}
13151 		}
13152 
13153 		if (ip_loopback_src_or_dst(ipha, ill)) {
13154 			ip2dbg(("ip_input: drop pkt\n"));
13155 			freemsg(mp);
13156 			continue;
13157 		}
13158 
13159 		opt_len = ipha->ipha_version_and_hdr_length -
13160 		    IP_SIMPLE_HDR_VERSION;
13161 		/* IP version bad or there are IP options */
13162 		if (opt_len) {
13163 			if (len != 0)
13164 				IP_STAT(ip_multimblk4);
13165 			else
13166 				IP_STAT(ip_ipoptions);
13167 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13168 				continue;
13169 		} else {
13170 			dst = ipha->ipha_dst;
13171 		}
13172 
13173 		/*
13174 		 * If rsvpd is running, let RSVP daemon handle its processing
13175 		 * and forwarding of RSVP multicast/unicast packets.
13176 		 * If rsvpd is not running but mrouted is running, RSVP
13177 		 * multicast packets are forwarded as multicast traffic
13178 		 * and RSVP unicast packets are forwarded by unicast router.
13179 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13180 		 * packets are not forwarded, but the unicast packets are
13181 		 * forwarded like unicast traffic.
13182 		 */
13183 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13184 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13185 			/* RSVP packet and rsvpd running. Treat as ours */
13186 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13187 			/*
13188 			 * This assumes that we deliver to all streams for
13189 			 * multicast and broadcast packets.
13190 			 * We have to force ll_multicast to 1 to handle the
13191 			 * M_DATA messages passed in from ip_mroute_decap.
13192 			 */
13193 			dst = INADDR_BROADCAST;
13194 			ll_multicast = 1;
13195 		} else if (CLASSD(dst)) {
13196 			/* packet is multicast */
13197 			mp->b_next = NULL;
13198 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13199 			    &ll_multicast, &dst))
13200 				continue;
13201 		}
13202 
13203 
13204 		/*
13205 		 * Check if the packet is coming from the Mobile IP
13206 		 * forward tunnel interface
13207 		 */
13208 		if (ill->ill_srcif_refcnt > 0) {
13209 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13210 			    NULL, ill, MATCH_IRE_TYPE);
13211 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13212 			    ire->ire_ipif->ipif_net_type ==
13213 			    IRE_IF_RESOLVER) {
13214 				/* We need to resolve the link layer info */
13215 				ire_refrele(ire);
13216 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13217 				    ll_multicast, dst);
13218 				continue;
13219 			}
13220 		}
13221 
13222 		if (ire == NULL)
13223 			ire = ire_cache_lookup(dst, ALL_ZONES);
13224 
13225 		/*
13226 		 * If mipagent is running and reverse tunnel is created as per
13227 		 * mobile node request, then any packet coming through the
13228 		 * incoming interface from the mobile-node, should be reverse
13229 		 * tunneled to it's home agent except those that are destined
13230 		 * to foreign agent only.
13231 		 * This needs source address based ire lookup. The routing
13232 		 * entries for source address based lookup are only created by
13233 		 * mipagent program only when a reverse tunnel is created.
13234 		 * Reference : RFC2002, RFC2344
13235 		 */
13236 		if (ill->ill_mrtun_refcnt > 0) {
13237 			ipaddr_t	srcaddr;
13238 			ire_t		*tmp_ire;
13239 
13240 			tmp_ire = ire;	/* Save, we might need it later */
13241 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13242 			    ire->ire_type != IRE_BROADCAST)) {
13243 				srcaddr = ipha->ipha_src;
13244 				ire = ire_mrtun_lookup(srcaddr, ill);
13245 				if (ire != NULL) {
13246 					/*
13247 					 * Should not be getting iphada packet
13248 					 * here. we should only get those for
13249 					 * IRE_LOCAL traffic, excluded above.
13250 					 * Fail-safe (drop packet) in the event
13251 					 * hardware is misbehaving.
13252 					 */
13253 					if (first_mp != mp) {
13254 						/* IPsec KSTATS: beancount me */
13255 						freemsg(first_mp);
13256 					} else {
13257 						/*
13258 						 * This packet must be forwarded
13259 						 * to Reverse Tunnel
13260 						 */
13261 						ip_mrtun_forward(ire, ill, mp);
13262 					}
13263 					ire_refrele(ire);
13264 					if (tmp_ire != NULL)
13265 						ire_refrele(tmp_ire);
13266 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13267 					    "ip_input_end: q %p (%S)",
13268 					    q, "uninit");
13269 					continue;
13270 				}
13271 			}
13272 			/*
13273 			 * If this packet is from a non-mobilenode  or a
13274 			 * mobile-node which does not request reverse
13275 			 * tunnel service
13276 			 */
13277 			ire = tmp_ire;
13278 		}
13279 
13280 
13281 		/*
13282 		 * If we reach here that means the incoming packet satisfies
13283 		 * one of the following conditions:
13284 		 *   - packet is from a mobile node which does not request
13285 		 *	reverse tunnel
13286 		 *   - packet is from a non-mobile node, which is the most
13287 		 *	common case
13288 		 *   - packet is from a reverse tunnel enabled mobile node
13289 		 *	and destined to foreign agent only
13290 		 */
13291 
13292 		if (ire == NULL) {
13293 			/*
13294 			 * No IRE for this destination, so it can't be for us.
13295 			 * Unless we are forwarding, drop the packet.
13296 			 * We have to let source routed packets through
13297 			 * since we don't yet know if they are 'ping -l'
13298 			 * packets i.e. if they will go out over the
13299 			 * same interface as they came in on.
13300 			 */
13301 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13302 			continue;
13303 		}
13304 
13305 		/* broadcast? */
13306 		if (ire->ire_type == IRE_BROADCAST) {
13307 			if (ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13308 			    dst, cgtp_flt_pkt, ll_multicast)) {
13309 				continue;
13310 			}
13311 		} else if (ire->ire_stq != NULL) {
13312 			/* fowarding? */
13313 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13314 			    ll_multicast);
13315 			continue;
13316 		}
13317 
13318 		/* packet not for us */
13319 		if (ire->ire_rfq != q) {
13320 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13321 				continue;
13322 			}
13323 		}
13324 
13325 		switch (ipha->ipha_protocol) {
13326 		case IPPROTO_TCP:
13327 			ASSERT(first_mp == mp);
13328 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13329 				mp, 0, q, ip_ring)) != NULL) {
13330 				if (curr_sqp == NULL) {
13331 					curr_sqp = GET_SQUEUE(mp);
13332 					ASSERT(cnt == 0);
13333 					cnt++;
13334 					head = tail = mp;
13335 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13336 					ASSERT(tail != NULL);
13337 					cnt++;
13338 					tail->b_next = mp;
13339 					tail = mp;
13340 				} else {
13341 					/*
13342 					 * A different squeue. Send the
13343 					 * chain for the previous squeue on
13344 					 * its way. This shouldn't happen
13345 					 * often unless interrupt binding
13346 					 * changes.
13347 					 */
13348 					IP_STAT(ip_input_multi_squeue);
13349 					squeue_enter_chain(curr_sqp, head,
13350 					    tail, cnt, SQTAG_IP_INPUT);
13351 					curr_sqp = GET_SQUEUE(mp);
13352 					head = mp;
13353 					tail = mp;
13354 					cnt = 1;
13355 				}
13356 			}
13357 			IRE_REFRELE(ire);
13358 			continue;
13359 		case IPPROTO_UDP:
13360 			ASSERT(first_mp == mp);
13361 			ip_udp_input(q, mp, ipha, ire, ill);
13362 			IRE_REFRELE(ire);
13363 			continue;
13364 		case IPPROTO_SCTP:
13365 			ASSERT(first_mp == mp);
13366 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13367 			    q, dst);
13368 			continue;
13369 		default:
13370 			ip_proto_input(q, first_mp, ipha, ire, ill);
13371 			IRE_REFRELE(ire);
13372 			continue;
13373 		}
13374 	}
13375 
13376 	if (head != NULL)
13377 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13378 
13379 	/*
13380 	 * This code is there just to make netperf/ttcp look good.
13381 	 *
13382 	 * Its possible that after being in polling mode (and having cleared
13383 	 * the backlog), squeues have turned the interrupt frequency higher
13384 	 * to improve latency at the expense of more CPU utilization (less
13385 	 * packets per interrupts or more number of interrupts). Workloads
13386 	 * like ttcp/netperf do manage to tickle polling once in a while
13387 	 * but for the remaining time, stay in higher interrupt mode since
13388 	 * their packet arrival rate is pretty uniform and this shows up
13389 	 * as higher CPU utilization. Since people care about CPU utilization
13390 	 * while running netperf/ttcp, turn the interrupt frequency back to
13391 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13392 	 */
13393 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13394 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13395 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13396 			ip_ring->rr_blank(ip_ring->rr_handle,
13397 			    ip_ring->rr_normal_blank_time,
13398 			    ip_ring->rr_normal_pkt_cnt);
13399 		}
13400 	}
13401 
13402 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13403 	    "ip_input_end: q %p (%S)", q, "end");
13404 #undef	rptr
13405 }
13406 
13407 static void
13408 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13409     t_uscalar_t err)
13410 {
13411 	if (dl_err == DL_SYSERR) {
13412 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13413 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13414 		    ill->ill_name, dlpi_prim_str(prim), err);
13415 		return;
13416 	}
13417 
13418 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13419 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13420 	    dlpi_err_str(dl_err));
13421 }
13422 
13423 /*
13424  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13425  * than DL_UNITDATA_IND messages. If we need to process this message
13426  * exclusively, we call qwriter_ip, in which case we also need to call
13427  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13428  */
13429 void
13430 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13431 {
13432 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13433 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13434 	ill_t		*ill;
13435 
13436 	ip1dbg(("ip_rput_dlpi"));
13437 	ill = (ill_t *)q->q_ptr;
13438 	switch (dloa->dl_primitive) {
13439 	case DL_ERROR_ACK:
13440 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13441 		    "%s (0x%x), unix %u\n", ill->ill_name,
13442 		    dlpi_prim_str(dlea->dl_error_primitive),
13443 		    dlea->dl_error_primitive,
13444 		    dlpi_err_str(dlea->dl_errno),
13445 		    dlea->dl_errno,
13446 		    dlea->dl_unix_errno));
13447 		switch (dlea->dl_error_primitive) {
13448 		case DL_NOTIFY_REQ:
13449 		case DL_UNBIND_REQ:
13450 		case DL_ATTACH_REQ:
13451 		case DL_DETACH_REQ:
13452 		case DL_INFO_REQ:
13453 		case DL_BIND_REQ:
13454 		case DL_ENABMULTI_REQ:
13455 		case DL_PHYS_ADDR_REQ:
13456 		case DL_CAPABILITY_REQ:
13457 		case DL_CONTROL_REQ:
13458 			/*
13459 			 * Refhold the ill to match qwriter_ip which does a
13460 			 * refrele. Since this is on the ill stream we
13461 			 * unconditionally bump up the refcount without
13462 			 * checking for ILL_CAN_LOOKUP
13463 			 */
13464 			ill_refhold(ill);
13465 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13466 			    CUR_OP, B_FALSE);
13467 			return;
13468 		case DL_DISABMULTI_REQ:
13469 			freemsg(mp);	/* Don't want to pass this up */
13470 			return;
13471 		default:
13472 			break;
13473 		}
13474 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13475 		    dlea->dl_errno, dlea->dl_unix_errno);
13476 		freemsg(mp);
13477 		return;
13478 	case DL_INFO_ACK:
13479 	case DL_BIND_ACK:
13480 	case DL_PHYS_ADDR_ACK:
13481 	case DL_NOTIFY_ACK:
13482 	case DL_CAPABILITY_ACK:
13483 	case DL_CONTROL_ACK:
13484 		/*
13485 		 * Refhold the ill to match qwriter_ip which does a refrele
13486 		 * Since this is on the ill stream we unconditionally
13487 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13488 		 */
13489 		ill_refhold(ill);
13490 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13491 		    CUR_OP, B_FALSE);
13492 		return;
13493 	case DL_NOTIFY_IND:
13494 		ill_refhold(ill);
13495 		/*
13496 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13497 		 * relation to the current ioctl in progress (if any). Hence we
13498 		 * pass in NEW_OP in this case.
13499 		 */
13500 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13501 		    NEW_OP, B_FALSE);
13502 		return;
13503 	case DL_OK_ACK:
13504 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13505 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13506 		switch (dloa->dl_correct_primitive) {
13507 		case DL_UNBIND_REQ:
13508 			mutex_enter(&ill->ill_lock);
13509 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13510 			cv_signal(&ill->ill_cv);
13511 			mutex_exit(&ill->ill_lock);
13512 			/* FALLTHRU */
13513 		case DL_ATTACH_REQ:
13514 		case DL_DETACH_REQ:
13515 			/*
13516 			 * Refhold the ill to match qwriter_ip which does a
13517 			 * refrele. Since this is on the ill stream we
13518 			 * unconditionally bump up the refcount
13519 			 */
13520 			ill_refhold(ill);
13521 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13522 			    CUR_OP, B_FALSE);
13523 			return;
13524 		case DL_ENABMULTI_REQ:
13525 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13526 				ill->ill_dlpi_multicast_state = IDMS_OK;
13527 			break;
13528 
13529 		}
13530 		break;
13531 	default:
13532 		break;
13533 	}
13534 	freemsg(mp);
13535 }
13536 
13537 /*
13538  * This function is used to free a message that has gone through
13539  * mi_copyin processing which modifies the M_IOCTL mblk's b_next
13540  * and b_prev pointers. We use this function to set b_next/b_prev
13541  * to NULL and free them.
13542  */
13543 void
13544 ip_ioctl_freemsg(mblk_t *mp)
13545 {
13546 	mblk_t	*bp = mp;
13547 
13548 	for (; bp != NULL; bp = bp->b_cont) {
13549 		bp->b_prev = NULL;
13550 		bp->b_next = NULL;
13551 	}
13552 	freemsg(mp);
13553 }
13554 
13555 /*
13556  * Handling of DLPI messages that require exclusive access to the ipsq.
13557  *
13558  * Need to do ill_pending_mp_release on ioctl completion, which could
13559  * happen here. (along with mi_copy_done)
13560  */
13561 /* ARGSUSED */
13562 static void
13563 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13564 {
13565 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13566 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13567 	int		err = 0;
13568 	ill_t		*ill;
13569 	ipif_t		*ipif = NULL;
13570 	mblk_t		*mp1 = NULL;
13571 	conn_t		*connp = NULL;
13572 	t_uscalar_t	physaddr_req;
13573 	mblk_t		*mp_hw;
13574 	union DL_primitives *dlp;
13575 	boolean_t	success;
13576 	boolean_t	ioctl_aborted = B_FALSE;
13577 	boolean_t	log = B_TRUE;
13578 
13579 	ip1dbg(("ip_rput_dlpi_writer .."));
13580 	ill = (ill_t *)q->q_ptr;
13581 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13582 
13583 	ASSERT(IAM_WRITER_ILL(ill));
13584 
13585 	/*
13586 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13587 	 * both are null or non-null. However we can assert that only
13588 	 * after grabbing the ipsq_lock. So we don't make any assertion
13589 	 * here and in other places in the code.
13590 	 */
13591 	ipif = ipsq->ipsq_pending_ipif;
13592 	/*
13593 	 * The current ioctl could have been aborted by the user and a new
13594 	 * ioctl to bring up another ill could have started. We could still
13595 	 * get a response from the driver later.
13596 	 */
13597 	if (ipif != NULL && ipif->ipif_ill != ill)
13598 		ioctl_aborted = B_TRUE;
13599 
13600 	switch (dloa->dl_primitive) {
13601 	case DL_ERROR_ACK:
13602 		switch (dlea->dl_error_primitive) {
13603 		case DL_UNBIND_REQ:
13604 		case DL_ATTACH_REQ:
13605 		case DL_DETACH_REQ:
13606 		case DL_INFO_REQ:
13607 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13608 			break;
13609 		case DL_NOTIFY_REQ:
13610 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13611 			log = B_FALSE;
13612 			break;
13613 		case DL_PHYS_ADDR_REQ:
13614 			/*
13615 			 * For IPv6 only, there are two additional
13616 			 * phys_addr_req's sent to the driver to get the
13617 			 * IPv6 token and lla. This allows IP to acquire
13618 			 * the hardware address format for a given interface
13619 			 * without having built in knowledge of the hardware
13620 			 * address. ill_phys_addr_pend keeps track of the last
13621 			 * DL_PAR sent so we know which response we are
13622 			 * dealing with. ill_dlpi_done will update
13623 			 * ill_phys_addr_pend when it sends the next req.
13624 			 * We don't complete the IOCTL until all three DL_PARs
13625 			 * have been attempted, so set *_len to 0 and break.
13626 			 */
13627 			physaddr_req = ill->ill_phys_addr_pend;
13628 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13629 			if (physaddr_req == DL_IPV6_TOKEN) {
13630 				ill->ill_token_length = 0;
13631 				log = B_FALSE;
13632 				break;
13633 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13634 				ill->ill_nd_lla_len = 0;
13635 				log = B_FALSE;
13636 				break;
13637 			}
13638 			/*
13639 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13640 			 * We presumably have an IOCTL hanging out waiting
13641 			 * for completion. Find it and complete the IOCTL
13642 			 * with the error noted.
13643 			 * However, ill_dl_phys was called on an ill queue
13644 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13645 			 * set. But the ioctl is known to be pending on ill_wq.
13646 			 */
13647 			if (!ill->ill_ifname_pending)
13648 				break;
13649 			ill->ill_ifname_pending = 0;
13650 			if (!ioctl_aborted)
13651 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13652 			if (mp1 != NULL) {
13653 				/*
13654 				 * This operation (SIOCSLIFNAME) must have
13655 				 * happened on the ill. Assert there is no conn
13656 				 */
13657 				ASSERT(connp == NULL);
13658 				q = ill->ill_wq;
13659 			}
13660 			break;
13661 		case DL_BIND_REQ:
13662 			ill_dlpi_done(ill, DL_BIND_REQ);
13663 			if (ill->ill_ifname_pending)
13664 				break;
13665 			/*
13666 			 * Something went wrong with the bind.  We presumably
13667 			 * have an IOCTL hanging out waiting for completion.
13668 			 * Find it, take down the interface that was coming
13669 			 * up, and complete the IOCTL with the error noted.
13670 			 */
13671 			if (!ioctl_aborted)
13672 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13673 			if (mp1 != NULL) {
13674 				/*
13675 				 * This operation (SIOCSLIFFLAGS) must have
13676 				 * happened from a conn.
13677 				 */
13678 				ASSERT(connp != NULL);
13679 				q = CONNP_TO_WQ(connp);
13680 				if (ill->ill_move_in_progress) {
13681 					ILL_CLEAR_MOVE(ill);
13682 				}
13683 				(void) ipif_down(ipif, NULL, NULL);
13684 				/* error is set below the switch */
13685 			}
13686 			break;
13687 		case DL_ENABMULTI_REQ:
13688 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13689 
13690 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13691 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13692 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13693 				ipif_t *ipif;
13694 
13695 				log = B_FALSE;
13696 				printf("ip: joining multicasts failed (%d)"
13697 				    " on %s - will use link layer "
13698 				    "broadcasts for multicast\n",
13699 				    dlea->dl_errno, ill->ill_name);
13700 
13701 				/*
13702 				 * Set up the multicast mapping alone.
13703 				 * writer, so ok to access ill->ill_ipif
13704 				 * without any lock.
13705 				 */
13706 				ipif = ill->ill_ipif;
13707 				mutex_enter(&ill->ill_phyint->phyint_lock);
13708 				ill->ill_phyint->phyint_flags |=
13709 				    PHYI_MULTI_BCAST;
13710 				mutex_exit(&ill->ill_phyint->phyint_lock);
13711 
13712 				if (!ill->ill_isv6) {
13713 					(void) ipif_arp_setup_multicast(ipif,
13714 					    NULL);
13715 				} else {
13716 					(void) ipif_ndp_setup_multicast(ipif,
13717 					    NULL);
13718 				}
13719 			}
13720 			freemsg(mp);	/* Don't want to pass this up */
13721 			return;
13722 		case DL_CAPABILITY_REQ:
13723 		case DL_CONTROL_REQ:
13724 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13725 			    "DL_CAPABILITY/CONTROL REQ\n"));
13726 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13727 			ill->ill_capab_state = IDMS_FAILED;
13728 			freemsg(mp);
13729 			return;
13730 		}
13731 		/*
13732 		 * Note the error for IOCTL completion (mp1 is set when
13733 		 * ready to complete ioctl). If ill_ifname_pending_err is
13734 		 * set, an error occured during plumbing (ill_ifname_pending),
13735 		 * so we want to report that error.
13736 		 *
13737 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13738 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13739 		 * expected to get errack'd if the driver doesn't support
13740 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13741 		 * if these error conditions are encountered.
13742 		 */
13743 		if (mp1 != NULL) {
13744 			if (ill->ill_ifname_pending_err != 0)  {
13745 				err = ill->ill_ifname_pending_err;
13746 				ill->ill_ifname_pending_err = 0;
13747 			} else {
13748 				err = dlea->dl_unix_errno ?
13749 				    dlea->dl_unix_errno : ENXIO;
13750 			}
13751 		/*
13752 		 * If we're plumbing an interface and an error hasn't already
13753 		 * been saved, set ill_ifname_pending_err to the error passed
13754 		 * up. Ignore the error if log is B_FALSE (see comment above).
13755 		 */
13756 		} else if (log && ill->ill_ifname_pending &&
13757 		    ill->ill_ifname_pending_err == 0) {
13758 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13759 			dlea->dl_unix_errno : ENXIO;
13760 		}
13761 
13762 		if (log)
13763 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13764 			    dlea->dl_errno, dlea->dl_unix_errno);
13765 		break;
13766 	case DL_CAPABILITY_ACK: {
13767 		boolean_t reneg_flag = B_FALSE;
13768 		/* Call a routine to handle this one. */
13769 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13770 		/*
13771 		 * Check if the ACK is due to renegotiation case since we
13772 		 * will need to send a new CAPABILITY_REQ later.
13773 		 */
13774 		if (ill->ill_capab_state == IDMS_RENEG) {
13775 			/* This is the ack for a renogiation case */
13776 			reneg_flag = B_TRUE;
13777 			ill->ill_capab_state = IDMS_UNKNOWN;
13778 		}
13779 		ill_capability_ack(ill, mp);
13780 		if (reneg_flag)
13781 			ill_capability_probe(ill);
13782 		break;
13783 	}
13784 	case DL_CONTROL_ACK:
13785 		/* We treat all of these as "fire and forget" */
13786 		ill_dlpi_done(ill, DL_CONTROL_REQ);
13787 		break;
13788 	case DL_INFO_ACK:
13789 		/* Call a routine to handle this one. */
13790 		ill_dlpi_done(ill, DL_INFO_REQ);
13791 		ip_ll_subnet_defaults(ill, mp);
13792 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
13793 		return;
13794 	case DL_BIND_ACK:
13795 		/*
13796 		 * We should have an IOCTL waiting on this unless
13797 		 * sent by ill_dl_phys, in which case just return
13798 		 */
13799 		ill_dlpi_done(ill, DL_BIND_REQ);
13800 		if (ill->ill_ifname_pending)
13801 			break;
13802 
13803 		if (!ioctl_aborted)
13804 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
13805 		if (mp1 == NULL)
13806 			break;
13807 		ASSERT(connp != NULL);
13808 		q = CONNP_TO_WQ(connp);
13809 
13810 		/*
13811 		 * We are exclusive. So nothing can change even after
13812 		 * we get the pending mp. If need be we can put it back
13813 		 * and restart, as in calling ipif_arp_up()  below.
13814 		 */
13815 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
13816 
13817 		mutex_enter(&ill->ill_lock);
13818 		ill->ill_dl_up = 1;
13819 		mutex_exit(&ill->ill_lock);
13820 
13821 		/*
13822 		 * Now bring up the resolver, when that is
13823 		 * done we'll create IREs and we are done.
13824 		 */
13825 		if (ill->ill_isv6) {
13826 			/*
13827 			 * v6 interfaces.
13828 			 * Unlike ARP which has to do another bind
13829 			 * and attach, once we get here we are
13830 			 * done withh NDP. Except in the case of
13831 			 * ILLF_XRESOLV, in which case we send an
13832 			 * AR_INTERFACE_UP to the external resolver.
13833 			 * If all goes well, the ioctl will complete
13834 			 * in ip_rput(). If there's an error, we
13835 			 * complete it here.
13836 			 */
13837 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
13838 			    B_FALSE);
13839 			if (err == 0) {
13840 				if (ill->ill_flags & ILLF_XRESOLV) {
13841 					mutex_enter(&connp->conn_lock);
13842 					mutex_enter(&ill->ill_lock);
13843 					success = ipsq_pending_mp_add(
13844 					    connp, ipif, q, mp1, 0);
13845 					mutex_exit(&ill->ill_lock);
13846 					mutex_exit(&connp->conn_lock);
13847 					if (success) {
13848 						err = ipif_resolver_up(ipif,
13849 						    B_FALSE);
13850 						if (err == EINPROGRESS) {
13851 							freemsg(mp);
13852 							return;
13853 						}
13854 						ASSERT(err != 0);
13855 						mp1 = ipsq_pending_mp_get(ipsq,
13856 						    &connp);
13857 						ASSERT(mp1 != NULL);
13858 					} else {
13859 						/* conn has started closing */
13860 						err = EINTR;
13861 					}
13862 				} else { /* Non XRESOLV interface */
13863 					err = ipif_up_done_v6(ipif);
13864 				}
13865 			}
13866 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
13867 			/*
13868 			 * ARP and other v4 external resolvers.
13869 			 * Leave the pending mblk intact so that
13870 			 * the ioctl completes in ip_rput().
13871 			 */
13872 			mutex_enter(&connp->conn_lock);
13873 			mutex_enter(&ill->ill_lock);
13874 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
13875 			mutex_exit(&ill->ill_lock);
13876 			mutex_exit(&connp->conn_lock);
13877 			if (success) {
13878 				err = ipif_resolver_up(ipif, B_FALSE);
13879 				if (err == EINPROGRESS) {
13880 					freemsg(mp);
13881 					return;
13882 				}
13883 				ASSERT(err != 0);
13884 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13885 			} else {
13886 				/* The conn has started closing */
13887 				err = EINTR;
13888 			}
13889 		} else {
13890 			/*
13891 			 * This one is complete. Reply to pending ioctl.
13892 			 */
13893 			err = ipif_up_done(ipif);
13894 		}
13895 
13896 		if ((err == 0) && (ill->ill_up_ipifs)) {
13897 			err = ill_up_ipifs(ill, q, mp1);
13898 			if (err == EINPROGRESS) {
13899 				freemsg(mp);
13900 				return;
13901 			}
13902 		}
13903 
13904 		if (ill->ill_up_ipifs) {
13905 			ill_group_cleanup(ill);
13906 		}
13907 
13908 		break;
13909 	case DL_NOTIFY_IND: {
13910 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
13911 		ire_t *ire;
13912 		boolean_t need_ire_walk_v4 = B_FALSE;
13913 		boolean_t need_ire_walk_v6 = B_FALSE;
13914 
13915 		/*
13916 		 * Change the address everywhere we need to.
13917 		 * What we're getting here is a link-level addr or phys addr.
13918 		 * The new addr is at notify + notify->dl_addr_offset
13919 		 * The address length is notify->dl_addr_length;
13920 		 */
13921 		switch (notify->dl_notification) {
13922 		case DL_NOTE_PHYS_ADDR:
13923 			mp_hw = copyb(mp);
13924 			if (mp_hw == NULL) {
13925 				err = ENOMEM;
13926 				break;
13927 			}
13928 			dlp = (union DL_primitives *)mp_hw->b_rptr;
13929 			/*
13930 			 * We currently don't support changing
13931 			 * the token via DL_NOTIFY_IND.
13932 			 * When we do support it, we have to consider
13933 			 * what the implications are with respect to
13934 			 * the token and the link local address.
13935 			 */
13936 			mutex_enter(&ill->ill_lock);
13937 			if (dlp->notify_ind.dl_data ==
13938 			    DL_IPV6_LINK_LAYER_ADDR) {
13939 				if (ill->ill_nd_lla_mp != NULL)
13940 					freemsg(ill->ill_nd_lla_mp);
13941 				ill->ill_nd_lla_mp = mp_hw;
13942 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
13943 				    dlp->notify_ind.dl_addr_offset;
13944 				ill->ill_nd_lla_len =
13945 				    dlp->notify_ind.dl_addr_length -
13946 				    ABS(ill->ill_sap_length);
13947 				mutex_exit(&ill->ill_lock);
13948 				break;
13949 			} else if (dlp->notify_ind.dl_data ==
13950 			    DL_CURR_PHYS_ADDR) {
13951 				if (ill->ill_phys_addr_mp != NULL)
13952 					freemsg(ill->ill_phys_addr_mp);
13953 				ill->ill_phys_addr_mp = mp_hw;
13954 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
13955 				    dlp->notify_ind.dl_addr_offset;
13956 				ill->ill_phys_addr_length =
13957 				    dlp->notify_ind.dl_addr_length -
13958 				    ABS(ill->ill_sap_length);
13959 				if (ill->ill_isv6 &&
13960 				    !(ill->ill_flags & ILLF_XRESOLV)) {
13961 					if (ill->ill_nd_lla_mp != NULL)
13962 						freemsg(ill->ill_nd_lla_mp);
13963 					ill->ill_nd_lla_mp = copyb(mp_hw);
13964 					ill->ill_nd_lla = (uchar_t *)
13965 					    ill->ill_nd_lla_mp->b_rptr +
13966 					    dlp->notify_ind.dl_addr_offset;
13967 					ill->ill_nd_lla_len =
13968 					    ill->ill_phys_addr_length;
13969 				}
13970 			}
13971 			mutex_exit(&ill->ill_lock);
13972 			/*
13973 			 * Send out gratuitous arp request for our new
13974 			 * hardware address.
13975 			 */
13976 			for (ipif = ill->ill_ipif; ipif != NULL;
13977 			    ipif = ipif->ipif_next) {
13978 				if (!(ipif->ipif_flags & IPIF_UP))
13979 					continue;
13980 				if (ill->ill_isv6) {
13981 					ipif_ndp_down(ipif);
13982 					/*
13983 					 * Set B_TRUE to enable
13984 					 * ipif_ndp_up() to send out
13985 					 * unsolicited advertisements.
13986 					 */
13987 					err = ipif_ndp_up(ipif,
13988 					    &ipif->ipif_v6lcl_addr,
13989 					    B_TRUE);
13990 					if (err) {
13991 						ip1dbg((
13992 						    "ip_rput_dlpi_writer: "
13993 						    "Failed to update ndp "
13994 						    "err %d\n", err));
13995 					}
13996 				} else {
13997 					/*
13998 					 * IPv4 ARP case
13999 					 *
14000 					 * Set B_TRUE, as we only want
14001 					 * ipif_resolver_up to send an
14002 					 * AR_ENTRY_ADD request up to
14003 					 * ARP.
14004 					 */
14005 					err = ipif_resolver_up(ipif,
14006 					    B_TRUE);
14007 					if (err) {
14008 						ip1dbg((
14009 						    "ip_rput_dlpi_writer: "
14010 						    "Failed to update arp "
14011 						    "err %d\n", err));
14012 					}
14013 				}
14014 			}
14015 			/*
14016 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14017 			 * case so that all old fastpath information can be
14018 			 * purged from IRE caches.
14019 			 */
14020 		/* FALLTHRU */
14021 		case DL_NOTE_FASTPATH_FLUSH:
14022 			/*
14023 			 * Any fastpath probe sent henceforth will get the
14024 			 * new fp mp. So we first delete any ires that are
14025 			 * waiting for the fastpath. Then walk all ires and
14026 			 * delete the ire or delete the fp mp. In the case of
14027 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14028 			 * recreate the ire's without going through a complex
14029 			 * ipif up/down dance. So we don't delete the ire
14030 			 * itself, but just the ire_fp_mp for these 2 ire's
14031 			 * In the case of the other ire's we delete the ire's
14032 			 * themselves. Access to ire_fp_mp is completely
14033 			 * protected by ire_lock for IRE_MIPRTUN and
14034 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14035 			 * other cases for performance.
14036 			 */
14037 			if (ill->ill_isv6) {
14038 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14039 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14040 				    NULL);
14041 			} else {
14042 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14043 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14044 				    IRE_CACHE | IRE_BROADCAST,
14045 				    ire_fastpath_flush, NULL, ill);
14046 				mutex_enter(&ire_mrtun_lock);
14047 				if (ire_mrtun_count != 0) {
14048 					mutex_exit(&ire_mrtun_lock);
14049 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14050 					    IRE_MIPRTUN, ire_fastpath_flush,
14051 					    NULL, ill);
14052 				} else {
14053 					mutex_exit(&ire_mrtun_lock);
14054 				}
14055 			}
14056 			break;
14057 		case DL_NOTE_SDU_SIZE:
14058 			/*
14059 			 * Change the MTU size of the interface, of all
14060 			 * attached ipif's, and of all relevant ire's.  The
14061 			 * new value's a uint32_t at notify->dl_data.
14062 			 * Mtu change Vs. new ire creation - protocol below.
14063 			 *
14064 			 * a Mark the ipif as IPIF_CHANGING.
14065 			 * b Set the new mtu in the ipif.
14066 			 * c Change the ire_max_frag on all affected ires
14067 			 * d Unmark the IPIF_CHANGING
14068 			 *
14069 			 * To see how the protocol works, assume an interface
14070 			 * route is also being added simultaneously by
14071 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14072 			 * the ire. If the ire is created before step a,
14073 			 * it will be cleaned up by step c. If the ire is
14074 			 * created after step d, it will see the new value of
14075 			 * ipif_mtu. Any attempt to create the ire between
14076 			 * steps a to d will fail because of the IPIF_CHANGING
14077 			 * flag. Note that ire_create() is passed a pointer to
14078 			 * the ipif_mtu, and not the value. During ire_add
14079 			 * under the bucket lock, the ire_max_frag of the
14080 			 * new ire being created is set from the ipif/ire from
14081 			 * which it is being derived.
14082 			 */
14083 			mutex_enter(&ill->ill_lock);
14084 			ill->ill_max_frag = (uint_t)notify->dl_data;
14085 
14086 			/*
14087 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14088 			 * leave it alone
14089 			 */
14090 			if (ill->ill_mtu_userspecified) {
14091 				mutex_exit(&ill->ill_lock);
14092 				break;
14093 			}
14094 			ill->ill_max_mtu = ill->ill_max_frag;
14095 			if (ill->ill_isv6) {
14096 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14097 					ill->ill_max_mtu = IPV6_MIN_MTU;
14098 			} else {
14099 				if (ill->ill_max_mtu < IP_MIN_MTU)
14100 					ill->ill_max_mtu = IP_MIN_MTU;
14101 			}
14102 			for (ipif = ill->ill_ipif; ipif != NULL;
14103 			    ipif = ipif->ipif_next) {
14104 				/*
14105 				 * Don't override the mtu if the user
14106 				 * has explicitly set it.
14107 				 */
14108 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14109 					continue;
14110 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14111 				if (ipif->ipif_isv6)
14112 					ire = ipif_to_ire_v6(ipif);
14113 				else
14114 					ire = ipif_to_ire(ipif);
14115 				if (ire != NULL) {
14116 					ire->ire_max_frag = ipif->ipif_mtu;
14117 					ire_refrele(ire);
14118 				}
14119 				if (ipif->ipif_flags & IPIF_UP) {
14120 					if (ill->ill_isv6)
14121 						need_ire_walk_v6 = B_TRUE;
14122 					else
14123 						need_ire_walk_v4 = B_TRUE;
14124 				}
14125 			}
14126 			mutex_exit(&ill->ill_lock);
14127 			if (need_ire_walk_v4)
14128 				ire_walk_v4(ill_mtu_change, (char *)ill,
14129 				    ALL_ZONES);
14130 			if (need_ire_walk_v6)
14131 				ire_walk_v6(ill_mtu_change, (char *)ill,
14132 				    ALL_ZONES);
14133 			break;
14134 		case DL_NOTE_LINK_UP:
14135 		case DL_NOTE_LINK_DOWN: {
14136 			/*
14137 			 * We are writer. ill / phyint / ipsq assocs stable.
14138 			 * The RUNNING flag reflects the state of the link.
14139 			 */
14140 			phyint_t *phyint = ill->ill_phyint;
14141 			uint64_t new_phyint_flags;
14142 			boolean_t changed = B_FALSE;
14143 
14144 			mutex_enter(&phyint->phyint_lock);
14145 			new_phyint_flags =
14146 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14147 			    phyint->phyint_flags | PHYI_RUNNING :
14148 			    phyint->phyint_flags & ~PHYI_RUNNING;
14149 			if (new_phyint_flags != phyint->phyint_flags) {
14150 				phyint->phyint_flags = new_phyint_flags;
14151 				changed = B_TRUE;
14152 			}
14153 			mutex_exit(&phyint->phyint_lock);
14154 			/*
14155 			 * If the flags have changed, send a message to
14156 			 * the routing socket.
14157 			 */
14158 			if (changed) {
14159 				if (phyint->phyint_illv4 != NULL) {
14160 					ip_rts_ifmsg(
14161 					    phyint->phyint_illv4->ill_ipif);
14162 				}
14163 				if (phyint->phyint_illv6 != NULL) {
14164 					ip_rts_ifmsg(
14165 					    phyint->phyint_illv6->ill_ipif);
14166 				}
14167 			}
14168 			break;
14169 		}
14170 		case DL_NOTE_PROMISC_ON_PHYS:
14171 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14172 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14173 			mutex_enter(&ill->ill_lock);
14174 			ill->ill_promisc_on_phys = B_TRUE;
14175 			mutex_exit(&ill->ill_lock);
14176 			break;
14177 		case DL_NOTE_PROMISC_OFF_PHYS:
14178 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14179 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14180 			mutex_enter(&ill->ill_lock);
14181 			ill->ill_promisc_on_phys = B_FALSE;
14182 			mutex_exit(&ill->ill_lock);
14183 			break;
14184 		case DL_NOTE_CAPAB_RENEG:
14185 			/*
14186 			 * Something changed on the driver side.
14187 			 * It wants us to renegotiate the capabilities
14188 			 * on this ill. The most likely cause is the
14189 			 * aggregation interface under us where a
14190 			 * port got added or went away.
14191 			 *
14192 			 * We reset the capabilities and set the
14193 			 * state to IDMS_RENG so that when the ack
14194 			 * comes back, we can start the
14195 			 * renegotiation process.
14196 			 */
14197 			ill_capability_reset(ill);
14198 			ill->ill_capab_state = IDMS_RENEG;
14199 			break;
14200 		default:
14201 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14202 			    "type 0x%x for DL_NOTIFY_IND\n",
14203 			    notify->dl_notification));
14204 			break;
14205 		}
14206 
14207 		/*
14208 		 * As this is an asynchronous operation, we
14209 		 * should not call ill_dlpi_done
14210 		 */
14211 		break;
14212 	}
14213 	case DL_NOTIFY_ACK:
14214 		/*
14215 		 * Don't really need to check for what notifications
14216 		 * are supported; we'll process what gets sent upstream,
14217 		 * and we know it'll be something we support changing
14218 		 * based on our DL_NOTIFY_REQ.
14219 		 */
14220 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14221 		break;
14222 	case DL_PHYS_ADDR_ACK: {
14223 		/*
14224 		 * We should have an IOCTL waiting on this when request
14225 		 * sent by ill_dl_phys.
14226 		 * However, ill_dl_phys was called on an ill queue (from
14227 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14228 		 * ioctl is known to be pending on ill_wq.
14229 		 * There are two additional phys_addr_req's sent to the
14230 		 * driver to get the token and lla. ill_phys_addr_pend
14231 		 * keeps track of the last one sent so we know which
14232 		 * response we are dealing with. ill_dlpi_done will
14233 		 * update ill_phys_addr_pend when it sends the next req.
14234 		 * We don't complete the IOCTL until all three DL_PARs
14235 		 * have been attempted.
14236 		 *
14237 		 * We don't need any lock to update ill_nd_lla* fields,
14238 		 * since the ill is not yet up, We grab the lock just
14239 		 * for uniformity with other code that accesses ill_nd_lla.
14240 		 */
14241 		physaddr_req = ill->ill_phys_addr_pend;
14242 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14243 		if (physaddr_req == DL_IPV6_TOKEN ||
14244 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14245 			if (physaddr_req == DL_IPV6_TOKEN) {
14246 				/*
14247 				 * bcopy to low-order bits of ill_token
14248 				 *
14249 				 * XXX Temporary hack - currently,
14250 				 * all known tokens are 64 bits,
14251 				 * so I'll cheat for the moment.
14252 				 */
14253 				dlp = (union DL_primitives *)mp->b_rptr;
14254 
14255 				mutex_enter(&ill->ill_lock);
14256 				bcopy((uchar_t *)(mp->b_rptr +
14257 				dlp->physaddr_ack.dl_addr_offset),
14258 				(void *)&ill->ill_token.s6_addr32[2],
14259 				dlp->physaddr_ack.dl_addr_length);
14260 				ill->ill_token_length =
14261 					dlp->physaddr_ack.dl_addr_length;
14262 				mutex_exit(&ill->ill_lock);
14263 			} else {
14264 				ASSERT(ill->ill_nd_lla_mp == NULL);
14265 				mp_hw = copyb(mp);
14266 				if (mp_hw == NULL) {
14267 					err = ENOMEM;
14268 					break;
14269 				}
14270 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14271 				mutex_enter(&ill->ill_lock);
14272 				ill->ill_nd_lla_mp = mp_hw;
14273 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14274 				dlp->physaddr_ack.dl_addr_offset;
14275 				ill->ill_nd_lla_len =
14276 					dlp->physaddr_ack.dl_addr_length;
14277 				mutex_exit(&ill->ill_lock);
14278 			}
14279 			break;
14280 		}
14281 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14282 		ASSERT(ill->ill_phys_addr_mp == NULL);
14283 		if (!ill->ill_ifname_pending)
14284 			break;
14285 		ill->ill_ifname_pending = 0;
14286 		if (!ioctl_aborted)
14287 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14288 		if (mp1 != NULL) {
14289 			ASSERT(connp == NULL);
14290 			q = ill->ill_wq;
14291 		}
14292 		/*
14293 		 * If any error acks received during the plumbing sequence,
14294 		 * ill_ifname_pending_err will be set. Break out and send up
14295 		 * the error to the pending ioctl.
14296 		 */
14297 		if (ill->ill_ifname_pending_err != 0) {
14298 			err = ill->ill_ifname_pending_err;
14299 			ill->ill_ifname_pending_err = 0;
14300 			break;
14301 		}
14302 		/*
14303 		 * Get the interface token.  If the zeroth interface
14304 		 * address is zero then set the address to the link local
14305 		 * address
14306 		 */
14307 		mp_hw = copyb(mp);
14308 		if (mp_hw == NULL) {
14309 			err = ENOMEM;
14310 			break;
14311 		}
14312 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14313 		ill->ill_phys_addr_mp = mp_hw;
14314 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14315 				dlp->physaddr_ack.dl_addr_offset;
14316 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14317 		    ill->ill_phys_addr_length == 0 ||
14318 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14319 			/*
14320 			 * Compatibility: atun driver returns a length of 0.
14321 			 * ipdptp has an ill_phys_addr_length of zero(from
14322 			 * DL_BIND_ACK) but a non-zero length here.
14323 			 * ipd has an ill_phys_addr_length of 4(from
14324 			 * DL_BIND_ACK) but a non-zero length here.
14325 			 */
14326 			ill->ill_phys_addr = NULL;
14327 		} else if (dlp->physaddr_ack.dl_addr_length !=
14328 		    ill->ill_phys_addr_length) {
14329 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14330 			    "Address length mismatch %d %d\n",
14331 			    dlp->physaddr_ack.dl_addr_length,
14332 			    ill->ill_phys_addr_length));
14333 			err = EINVAL;
14334 			break;
14335 		}
14336 		mutex_enter(&ill->ill_lock);
14337 		if (ill->ill_nd_lla_mp == NULL) {
14338 			ill->ill_nd_lla_mp = copyb(mp_hw);
14339 			if (ill->ill_nd_lla_mp == NULL) {
14340 				err = ENOMEM;
14341 				mutex_exit(&ill->ill_lock);
14342 				break;
14343 			}
14344 			ill->ill_nd_lla =
14345 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14346 			    dlp->physaddr_ack.dl_addr_offset;
14347 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14348 		}
14349 		mutex_exit(&ill->ill_lock);
14350 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14351 			(void) ill_setdefaulttoken(ill);
14352 
14353 		/*
14354 		 * If the ill zero interface has a zero address assign
14355 		 * it the proper link local address.
14356 		 */
14357 		ASSERT(ill->ill_ipif->ipif_id == 0);
14358 		if (ipif != NULL &&
14359 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14360 			(void) ipif_setlinklocal(ipif);
14361 		break;
14362 	}
14363 	case DL_OK_ACK:
14364 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14365 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14366 		    dloa->dl_correct_primitive));
14367 		switch (dloa->dl_correct_primitive) {
14368 		case DL_UNBIND_REQ:
14369 		case DL_ATTACH_REQ:
14370 		case DL_DETACH_REQ:
14371 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14372 			break;
14373 		}
14374 		break;
14375 	default:
14376 		break;
14377 	}
14378 
14379 	freemsg(mp);
14380 	if (mp1) {
14381 		struct iocblk *iocp;
14382 		int mode;
14383 
14384 		/*
14385 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14386 		 * SIOCSLIFNAME do a copyout.
14387 		 */
14388 		iocp = (struct iocblk *)mp1->b_rptr;
14389 
14390 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14391 		    iocp->ioc_cmd == SIOCSLIFNAME)
14392 			mode = COPYOUT;
14393 		else
14394 			mode = NO_COPYOUT;
14395 		/*
14396 		 * The ioctl must complete now without EINPROGRESS
14397 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14398 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14399 		 * stuck for ever in the ipsq.
14400 		 */
14401 		ASSERT(err != EINPROGRESS);
14402 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14403 
14404 	}
14405 }
14406 
14407 /*
14408  * ip_rput_other is called by ip_rput to handle messages modifying the global
14409  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14410  */
14411 /* ARGSUSED */
14412 void
14413 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14414 {
14415 	ill_t		*ill;
14416 	struct iocblk	*iocp;
14417 	mblk_t		*mp1;
14418 	conn_t		*connp = NULL;
14419 
14420 	ip1dbg(("ip_rput_other "));
14421 	ill = (ill_t *)q->q_ptr;
14422 	/*
14423 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14424 	 * in which case ipsq is NULL.
14425 	 */
14426 	if (ipsq != NULL) {
14427 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14428 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14429 	}
14430 
14431 	switch (mp->b_datap->db_type) {
14432 	case M_ERROR:
14433 	case M_HANGUP:
14434 		/*
14435 		 * The device has a problem.  We force the ILL down.  It can
14436 		 * be brought up again manually using SIOCSIFFLAGS (via
14437 		 * ifconfig or equivalent).
14438 		 */
14439 		ASSERT(ipsq != NULL);
14440 		if (mp->b_rptr < mp->b_wptr)
14441 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14442 		if (ill->ill_error == 0)
14443 			ill->ill_error = ENXIO;
14444 		if (!ill_down_start(q, mp))
14445 			return;
14446 		ipif_all_down_tail(ipsq, q, mp, NULL);
14447 		break;
14448 	case M_IOCACK:
14449 		iocp = (struct iocblk *)mp->b_rptr;
14450 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14451 		switch (iocp->ioc_cmd) {
14452 		case SIOCSTUNPARAM:
14453 		case OSIOCSTUNPARAM:
14454 			ASSERT(ipsq != NULL);
14455 			/*
14456 			 * Finish socket ioctl passed through to tun.
14457 			 * We should have an IOCTL waiting on this.
14458 			 */
14459 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14460 			if (ill->ill_isv6) {
14461 				struct iftun_req *ta;
14462 
14463 				/*
14464 				 * if a source or destination is
14465 				 * being set, try and set the link
14466 				 * local address for the tunnel
14467 				 */
14468 				ta = (struct iftun_req *)mp->b_cont->
14469 				    b_cont->b_rptr;
14470 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14471 					ipif_set_tun_llink(ill, ta);
14472 				}
14473 
14474 			}
14475 			if (mp1 != NULL) {
14476 				/*
14477 				 * Now copy back the b_next/b_prev used by
14478 				 * mi code for the mi_copy* functions.
14479 				 * See ip_sioctl_tunparam() for the reason.
14480 				 * Also protect against missing b_cont.
14481 				 */
14482 				if (mp->b_cont != NULL) {
14483 					mp->b_cont->b_next =
14484 					    mp1->b_cont->b_next;
14485 					mp->b_cont->b_prev =
14486 					    mp1->b_cont->b_prev;
14487 				}
14488 				ip_ioctl_freemsg(mp1);
14489 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14490 				ASSERT(connp != NULL);
14491 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14492 				    iocp->ioc_error, NO_COPYOUT,
14493 				    ipsq->ipsq_current_ipif, ipsq);
14494 			} else {
14495 				ASSERT(connp == NULL);
14496 				putnext(q, mp);
14497 			}
14498 			break;
14499 		case SIOCGTUNPARAM:
14500 		case OSIOCGTUNPARAM:
14501 			/*
14502 			 * This is really M_IOCDATA from the tunnel driver.
14503 			 * convert back and complete the ioctl.
14504 			 * We should have an IOCTL waiting on this.
14505 			 */
14506 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14507 			if (mp1) {
14508 				/*
14509 				 * Now copy back the b_next/b_prev used by
14510 				 * mi code for the mi_copy* functions.
14511 				 * See ip_sioctl_tunparam() for the reason.
14512 				 * Also protect against missing b_cont.
14513 				 */
14514 				if (mp->b_cont != NULL) {
14515 					mp->b_cont->b_next =
14516 					    mp1->b_cont->b_next;
14517 					mp->b_cont->b_prev =
14518 					    mp1->b_cont->b_prev;
14519 				}
14520 				ip_ioctl_freemsg(mp1);
14521 				if (iocp->ioc_error == 0)
14522 					mp->b_datap->db_type = M_IOCDATA;
14523 				ASSERT(connp != NULL);
14524 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14525 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14526 			} else {
14527 				ASSERT(connp == NULL);
14528 				putnext(q, mp);
14529 			}
14530 			break;
14531 		default:
14532 			break;
14533 		}
14534 		break;
14535 	case M_IOCNAK:
14536 		iocp = (struct iocblk *)mp->b_rptr;
14537 
14538 		switch (iocp->ioc_cmd) {
14539 		int mode;
14540 		ipif_t	*ipif;
14541 
14542 		case DL_IOC_HDR_INFO:
14543 			/*
14544 			 * If this was the first attempt turn of the
14545 			 * fastpath probing.
14546 			 */
14547 			mutex_enter(&ill->ill_lock);
14548 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14549 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14550 				mutex_exit(&ill->ill_lock);
14551 				ill_fastpath_nack(ill);
14552 				ip1dbg(("ip_rput: DLPI fastpath off on "
14553 				    "interface %s\n",
14554 				    ill->ill_name));
14555 			} else {
14556 				mutex_exit(&ill->ill_lock);
14557 			}
14558 			freemsg(mp);
14559 			break;
14560 		case SIOCSTUNPARAM:
14561 		case OSIOCSTUNPARAM:
14562 			ASSERT(ipsq != NULL);
14563 			/*
14564 			 * Finish socket ioctl passed through to tun
14565 			 * We should have an IOCTL waiting on this.
14566 			 */
14567 			/* FALLTHRU */
14568 		case SIOCGTUNPARAM:
14569 		case OSIOCGTUNPARAM:
14570 			/*
14571 			 * This is really M_IOCDATA from the tunnel driver.
14572 			 * convert back and complete the ioctl.
14573 			 * We should have an IOCTL waiting on this.
14574 			 */
14575 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14576 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14577 				mp1 = ill_pending_mp_get(ill, &connp,
14578 				    iocp->ioc_id);
14579 				mode = COPYOUT;
14580 				ipsq = NULL;
14581 				ipif = NULL;
14582 			} else {
14583 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14584 				mode = NO_COPYOUT;
14585 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14586 				ipif = ipsq->ipsq_current_ipif;
14587 			}
14588 			if (mp1 != NULL) {
14589 				/*
14590 				 * Now copy back the b_next/b_prev used by
14591 				 * mi code for the mi_copy* functions.
14592 				 * See ip_sioctl_tunparam() for the reason.
14593 				 * Also protect against missing b_cont.
14594 				 */
14595 				if (mp->b_cont != NULL) {
14596 					mp->b_cont->b_next =
14597 					    mp1->b_cont->b_next;
14598 					mp->b_cont->b_prev =
14599 					    mp1->b_cont->b_prev;
14600 				}
14601 				ip_ioctl_freemsg(mp1);
14602 				if (iocp->ioc_error == 0)
14603 					iocp->ioc_error = EINVAL;
14604 				ASSERT(connp != NULL);
14605 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14606 				    iocp->ioc_error, mode, ipif, ipsq);
14607 			} else {
14608 				ASSERT(connp == NULL);
14609 				putnext(q, mp);
14610 			}
14611 			break;
14612 		default:
14613 			break;
14614 		}
14615 	default:
14616 		break;
14617 	}
14618 }
14619 
14620 /*
14621  * NOTE : This function does not ire_refrele the ire argument passed in.
14622  *
14623  * IPQoS notes
14624  * IP policy is invoked twice for a forwarded packet, once on the read side
14625  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14626  * enabled. An additional parameter, in_ill, has been added for this purpose.
14627  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14628  * because ip_mroute drops this information.
14629  *
14630  */
14631 void
14632 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14633 {
14634 	uint32_t	pkt_len;
14635 	queue_t	*q;
14636 	uint32_t	sum;
14637 #define	rptr	((uchar_t *)ipha)
14638 	uint32_t	max_frag;
14639 	uint32_t	ill_index;
14640 
14641 	/* Get the ill_index of the incoming ILL */
14642 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14643 
14644 	/* Initiate Read side IPPF processing */
14645 	if (IPP_ENABLED(IPP_FWD_IN)) {
14646 		ip_process(IPP_FWD_IN, &mp, ill_index);
14647 		if (mp == NULL) {
14648 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14649 			    "during IPPF processing\n"));
14650 			return;
14651 		}
14652 	}
14653 	pkt_len = ntohs(ipha->ipha_length);
14654 
14655 	/* Adjust the checksum to reflect the ttl decrement. */
14656 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14657 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14658 
14659 	if (ipha->ipha_ttl-- <= 1) {
14660 		if (ip_csum_hdr(ipha)) {
14661 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14662 			goto drop_pkt;
14663 		}
14664 		/*
14665 		 * Note: ire_stq this will be NULL for multicast
14666 		 * datagrams using the long path through arp (the IRE
14667 		 * is not an IRE_CACHE). This should not cause
14668 		 * problems since we don't generate ICMP errors for
14669 		 * multicast packets.
14670 		 */
14671 		q = ire->ire_stq;
14672 		if (q)
14673 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14674 		else
14675 			freemsg(mp);
14676 		return;
14677 	}
14678 
14679 	/*
14680 	 * Don't forward if the interface is down
14681 	 */
14682 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14683 		BUMP_MIB(&ip_mib, ipInDiscards);
14684 		goto drop_pkt;
14685 	}
14686 
14687 	/* Get the ill_index of the outgoing ILL */
14688 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14689 
14690 	/* Check if there are options to update */
14691 	if (!IS_SIMPLE_IPH(ipha)) {
14692 		if (ip_csum_hdr(ipha)) {
14693 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14694 			goto drop_pkt;
14695 		}
14696 		if (ip_rput_forward_options(mp, ipha, ire)) {
14697 			return;
14698 		}
14699 
14700 		ipha->ipha_hdr_checksum = 0;
14701 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14702 	}
14703 	max_frag = ire->ire_max_frag;
14704 	if (pkt_len > max_frag) {
14705 		/*
14706 		 * It needs fragging on its way out.  We haven't
14707 		 * verified the header checksum yet.  Since we
14708 		 * are going to put a surely good checksum in the
14709 		 * outgoing header, we have to make sure that it
14710 		 * was good coming in.
14711 		 */
14712 		if (ip_csum_hdr(ipha)) {
14713 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14714 			goto drop_pkt;
14715 		}
14716 		/* Initiate Write side IPPF processing */
14717 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14718 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14719 			if (mp == NULL) {
14720 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14721 				    " during IPPF processing\n"));
14722 				return;
14723 			}
14724 		}
14725 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14726 		return;
14727 	}
14728 
14729 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14730 	if (mp == NULL) {
14731 		BUMP_MIB(&ip_mib, ipInDiscards);
14732 		return;
14733 	}
14734 
14735 	q = ire->ire_stq;
14736 	UPDATE_IB_PKT_COUNT(ire);
14737 	ire->ire_last_used_time = lbolt;
14738 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14739 	putnext(q, mp);
14740 	return;
14741 
14742 drop_pkt:;
14743 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14744 	freemsg(mp);
14745 #undef	rptr
14746 }
14747 
14748 void
14749 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14750 {
14751 	ire_t	*ire;
14752 
14753 	ASSERT(!ipif->ipif_isv6);
14754 	/*
14755 	 * Find an IRE which matches the destination and the outgoing
14756 	 * queue in the cache table. All we need is an IRE_CACHE which
14757 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14758 	 * then it is enough to have some IRE_CACHE in the group.
14759 	 */
14760 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14761 		dst = ipif->ipif_pp_dst_addr;
14762 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14763 	    MATCH_IRE_ILL_GROUP);
14764 	if (!ire) {
14765 		/*
14766 		 * Mark this packet to make it be delivered to
14767 		 * ip_rput_forward after the new ire has been
14768 		 * created.
14769 		 */
14770 		mp->b_prev = NULL;
14771 		mp->b_next = mp;
14772 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14773 		    NULL, 0);
14774 	} else {
14775 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14776 		IRE_REFRELE(ire);
14777 	}
14778 }
14779 
14780 /* Update any source route, record route or timestamp options */
14781 static int
14782 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
14783 {
14784 	ipoptp_t	opts;
14785 	uchar_t		*opt;
14786 	uint8_t		optval;
14787 	uint8_t		optlen;
14788 	ipaddr_t	dst;
14789 	uint32_t	ts;
14790 	ire_t		*dst_ire = NULL;
14791 	ire_t		*tmp_ire = NULL;
14792 	timestruc_t	now;
14793 
14794 	ip2dbg(("ip_rput_forward_options\n"));
14795 	dst = ipha->ipha_dst;
14796 	for (optval = ipoptp_first(&opts, ipha);
14797 	    optval != IPOPT_EOL;
14798 	    optval = ipoptp_next(&opts)) {
14799 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
14800 		opt = opts.ipoptp_cur;
14801 		optlen = opts.ipoptp_len;
14802 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
14803 		    optval, opts.ipoptp_len));
14804 		switch (optval) {
14805 			uint32_t off;
14806 		case IPOPT_SSRR:
14807 		case IPOPT_LSRR:
14808 			/* Check if adminstratively disabled */
14809 			if (!ip_forward_src_routed) {
14810 				BUMP_MIB(&ip_mib, ipForwProhibits);
14811 				if (ire->ire_stq)
14812 					icmp_unreachable(ire->ire_stq, mp,
14813 					    ICMP_SOURCE_ROUTE_FAILED);
14814 				else {
14815 					ip0dbg(("ip_rput_forward_options: "
14816 					    "unable to send unreach\n"));
14817 					freemsg(mp);
14818 				}
14819 				return (-1);
14820 			}
14821 
14822 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14823 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14824 			if (dst_ire == NULL) {
14825 				/*
14826 				 * Must be partial since ip_rput_options
14827 				 * checked for strict.
14828 				 */
14829 				break;
14830 			}
14831 			off = opt[IPOPT_OFFSET];
14832 			off--;
14833 		redo_srr:
14834 			if (optlen < IP_ADDR_LEN ||
14835 			    off > optlen - IP_ADDR_LEN) {
14836 				/* End of source route */
14837 				ip1dbg((
14838 				    "ip_rput_forward_options: end of SR\n"));
14839 				ire_refrele(dst_ire);
14840 				break;
14841 			}
14842 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14843 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14844 			    IP_ADDR_LEN);
14845 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
14846 			    ntohl(dst)));
14847 
14848 			/*
14849 			 * Check if our address is present more than
14850 			 * once as consecutive hops in source route.
14851 			 */
14852 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14853 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14854 			if (tmp_ire != NULL) {
14855 				ire_refrele(tmp_ire);
14856 				off += IP_ADDR_LEN;
14857 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14858 				goto redo_srr;
14859 			}
14860 			ipha->ipha_dst = dst;
14861 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14862 			ire_refrele(dst_ire);
14863 			break;
14864 		case IPOPT_RR:
14865 			off = opt[IPOPT_OFFSET];
14866 			off--;
14867 			if (optlen < IP_ADDR_LEN ||
14868 			    off > optlen - IP_ADDR_LEN) {
14869 				/* No more room - ignore */
14870 				ip1dbg((
14871 				    "ip_rput_forward_options: end of RR\n"));
14872 				break;
14873 			}
14874 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14875 			    IP_ADDR_LEN);
14876 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14877 			break;
14878 		case IPOPT_TS:
14879 			/* Insert timestamp if there is room */
14880 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14881 			case IPOPT_TS_TSONLY:
14882 				off = IPOPT_TS_TIMELEN;
14883 				break;
14884 			case IPOPT_TS_PRESPEC:
14885 			case IPOPT_TS_PRESPEC_RFC791:
14886 				/* Verify that the address matched */
14887 				off = opt[IPOPT_OFFSET] - 1;
14888 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14889 				dst_ire = ire_ctable_lookup(dst, 0,
14890 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
14891 				if (dst_ire == NULL) {
14892 					/* Not for us */
14893 					break;
14894 				}
14895 				ire_refrele(dst_ire);
14896 				/* FALLTHRU */
14897 			case IPOPT_TS_TSANDADDR:
14898 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
14899 				break;
14900 			default:
14901 				/*
14902 				 * ip_*put_options should have already
14903 				 * dropped this packet.
14904 				 */
14905 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
14906 				    "unknown IT - bug in ip_rput_options?\n");
14907 				return (0);	/* Keep "lint" happy */
14908 			}
14909 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
14910 				/* Increase overflow counter */
14911 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
14912 				opt[IPOPT_POS_OV_FLG] =
14913 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
14914 				    (off << 4));
14915 				break;
14916 			}
14917 			off = opt[IPOPT_OFFSET] - 1;
14918 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14919 			case IPOPT_TS_PRESPEC:
14920 			case IPOPT_TS_PRESPEC_RFC791:
14921 			case IPOPT_TS_TSANDADDR:
14922 				bcopy(&ire->ire_src_addr,
14923 				    (char *)opt + off, IP_ADDR_LEN);
14924 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14925 				/* FALLTHRU */
14926 			case IPOPT_TS_TSONLY:
14927 				off = opt[IPOPT_OFFSET] - 1;
14928 				/* Compute # of milliseconds since midnight */
14929 				gethrestime(&now);
14930 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
14931 				    now.tv_nsec / (NANOSEC / MILLISEC);
14932 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
14933 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
14934 				break;
14935 			}
14936 			break;
14937 		}
14938 	}
14939 	return (0);
14940 }
14941 
14942 /*
14943  * This is called after processing at least one of AH/ESP headers.
14944  *
14945  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
14946  * the actual, physical interface on which the packet was received,
14947  * but, when ip_strict_dst_multihoming is set to 1, could be the
14948  * interface which had the ipha_dst configured when the packet went
14949  * through ip_rput. The ill_index corresponding to the recv_ill
14950  * is saved in ipsec_in_rill_index
14951  */
14952 void
14953 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
14954 {
14955 	mblk_t *mp;
14956 	ipaddr_t dst;
14957 	in6_addr_t *v6dstp;
14958 	ipha_t *ipha;
14959 	ip6_t *ip6h;
14960 	ipsec_in_t *ii;
14961 	boolean_t ill_need_rele = B_FALSE;
14962 	boolean_t rill_need_rele = B_FALSE;
14963 	boolean_t ire_need_rele = B_FALSE;
14964 
14965 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
14966 	ASSERT(ii->ipsec_in_ill_index != 0);
14967 
14968 	mp = ipsec_mp->b_cont;
14969 	ASSERT(mp != NULL);
14970 
14971 
14972 	if (ill == NULL) {
14973 		ASSERT(recv_ill == NULL);
14974 		/*
14975 		 * We need to get the original queue on which ip_rput_local
14976 		 * or ip_rput_data_v6 was called.
14977 		 */
14978 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
14979 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
14980 		ill_need_rele = B_TRUE;
14981 
14982 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
14983 			recv_ill = ill_lookup_on_ifindex(
14984 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
14985 			    NULL, NULL, NULL, NULL);
14986 			rill_need_rele = B_TRUE;
14987 		} else {
14988 			recv_ill = ill;
14989 		}
14990 
14991 		if ((ill == NULL) || (recv_ill == NULL)) {
14992 			ip0dbg(("ip_fanout_proto_again: interface "
14993 			    "disappeared\n"));
14994 			if (ill != NULL)
14995 				ill_refrele(ill);
14996 			if (recv_ill != NULL)
14997 				ill_refrele(recv_ill);
14998 			freemsg(ipsec_mp);
14999 			return;
15000 		}
15001 	}
15002 
15003 	ASSERT(ill != NULL && recv_ill != NULL);
15004 
15005 	if (mp->b_datap->db_type == M_CTL) {
15006 		/*
15007 		 * AH/ESP is returning the ICMP message after
15008 		 * removing their headers. Fanout again till
15009 		 * it gets to the right protocol.
15010 		 */
15011 		if (ii->ipsec_in_v4) {
15012 			icmph_t *icmph;
15013 			int iph_hdr_length;
15014 			int hdr_length;
15015 
15016 			ipha = (ipha_t *)mp->b_rptr;
15017 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15018 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15019 			ipha = (ipha_t *)&icmph[1];
15020 			hdr_length = IPH_HDR_LENGTH(ipha);
15021 			/*
15022 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15023 			 * Reset the type to M_DATA.
15024 			 */
15025 			mp->b_datap->db_type = M_DATA;
15026 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15027 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15028 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15029 		} else {
15030 			icmp6_t *icmp6;
15031 			int hdr_length;
15032 
15033 			ip6h = (ip6_t *)mp->b_rptr;
15034 			/* Don't call hdr_length_v6() unless you have to. */
15035 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15036 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15037 			else
15038 				hdr_length = IPV6_HDR_LEN;
15039 
15040 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15041 			/*
15042 			 * icmp_inbound_error_fanout_v6 may need to do
15043 			 * pullupmsg.  Reset the type to M_DATA.
15044 			 */
15045 			mp->b_datap->db_type = M_DATA;
15046 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15047 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15048 		}
15049 		if (ill_need_rele)
15050 			ill_refrele(ill);
15051 		if (rill_need_rele)
15052 			ill_refrele(recv_ill);
15053 		return;
15054 	}
15055 
15056 	if (ii->ipsec_in_v4) {
15057 		ipha = (ipha_t *)mp->b_rptr;
15058 		dst = ipha->ipha_dst;
15059 		if (CLASSD(dst)) {
15060 			/*
15061 			 * Multicast has to be delivered to all streams.
15062 			 */
15063 			dst = INADDR_BROADCAST;
15064 		}
15065 
15066 		if (ire == NULL) {
15067 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15068 			if (ire == NULL) {
15069 				if (ill_need_rele)
15070 					ill_refrele(ill);
15071 				if (rill_need_rele)
15072 					ill_refrele(recv_ill);
15073 				ip1dbg(("ip_fanout_proto_again: "
15074 				    "IRE not found"));
15075 				freemsg(ipsec_mp);
15076 				return;
15077 			}
15078 			ire_need_rele = B_TRUE;
15079 		}
15080 
15081 		switch (ipha->ipha_protocol) {
15082 			case IPPROTO_UDP:
15083 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15084 				    recv_ill);
15085 				if (ire_need_rele)
15086 					ire_refrele(ire);
15087 				break;
15088 			case IPPROTO_TCP:
15089 				if (!ire_need_rele)
15090 					IRE_REFHOLD(ire);
15091 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15092 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15093 				IRE_REFRELE(ire);
15094 				if (mp != NULL)
15095 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15096 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15097 				break;
15098 			case IPPROTO_SCTP:
15099 				if (!ire_need_rele)
15100 					IRE_REFHOLD(ire);
15101 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15102 				    ipsec_mp, 0, ill->ill_rq, dst);
15103 				break;
15104 			default:
15105 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15106 				    recv_ill);
15107 				if (ire_need_rele)
15108 					ire_refrele(ire);
15109 				break;
15110 		}
15111 	} else {
15112 		uint32_t rput_flags = 0;
15113 
15114 		ip6h = (ip6_t *)mp->b_rptr;
15115 		v6dstp = &ip6h->ip6_dst;
15116 		/*
15117 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15118 		 * address.
15119 		 *
15120 		 * Currently, we don't store that state in the IPSEC_IN
15121 		 * message, and we may need to.
15122 		 */
15123 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15124 		    IP6_IN_LLMCAST : 0);
15125 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15126 		    NULL);
15127 	}
15128 	if (ill_need_rele)
15129 		ill_refrele(ill);
15130 	if (rill_need_rele)
15131 		ill_refrele(recv_ill);
15132 }
15133 
15134 /*
15135  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15136  * returns 'true' if there are still fragments left on the queue, in
15137  * which case we restart the timer.
15138  */
15139 void
15140 ill_frag_timer(void *arg)
15141 {
15142 	ill_t	*ill = (ill_t *)arg;
15143 	boolean_t frag_pending;
15144 
15145 	mutex_enter(&ill->ill_lock);
15146 	ASSERT(!ill->ill_fragtimer_executing);
15147 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15148 		ill->ill_frag_timer_id = 0;
15149 		mutex_exit(&ill->ill_lock);
15150 		return;
15151 	}
15152 	ill->ill_fragtimer_executing = 1;
15153 	mutex_exit(&ill->ill_lock);
15154 
15155 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15156 
15157 	/*
15158 	 * Restart the timer, if we have fragments pending or if someone
15159 	 * wanted us to be scheduled again.
15160 	 */
15161 	mutex_enter(&ill->ill_lock);
15162 	ill->ill_fragtimer_executing = 0;
15163 	ill->ill_frag_timer_id = 0;
15164 	if (frag_pending || ill->ill_fragtimer_needrestart)
15165 		ill_frag_timer_start(ill);
15166 	mutex_exit(&ill->ill_lock);
15167 }
15168 
15169 void
15170 ill_frag_timer_start(ill_t *ill)
15171 {
15172 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15173 
15174 	/* If the ill is closing or opening don't proceed */
15175 	if (ill->ill_state_flags & ILL_CONDEMNED)
15176 		return;
15177 
15178 	if (ill->ill_fragtimer_executing) {
15179 		/*
15180 		 * ill_frag_timer is currently executing. Just record the
15181 		 * the fact that we want the timer to be restarted.
15182 		 * ill_frag_timer will post a timeout before it returns,
15183 		 * ensuring it will be called again.
15184 		 */
15185 		ill->ill_fragtimer_needrestart = 1;
15186 		return;
15187 	}
15188 
15189 	if (ill->ill_frag_timer_id == 0) {
15190 		/*
15191 		 * The timer is neither running nor is the timeout handler
15192 		 * executing. Post a timeout so that ill_frag_timer will be
15193 		 * called
15194 		 */
15195 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15196 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15197 		ill->ill_fragtimer_needrestart = 0;
15198 	}
15199 }
15200 
15201 /*
15202  * This routine is needed for loopback when forwarding multicasts.
15203  *
15204  * IPQoS Notes:
15205  * IPPF processing is done in fanout routines.
15206  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15207  * processing for IPSec packets is done when it comes back in clear.
15208  * NOTE : The callers of this function need to do the ire_refrele for the
15209  *	  ire that is being passed in.
15210  */
15211 void
15212 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15213     ill_t *recv_ill)
15214 {
15215 	ill_t	*ill = (ill_t *)q->q_ptr;
15216 	uint32_t	sum;
15217 	uint32_t	u1;
15218 	uint32_t	u2;
15219 	int		hdr_length;
15220 	boolean_t	mctl_present;
15221 	mblk_t		*first_mp = mp;
15222 	mblk_t		*hada_mp = NULL;
15223 	ipha_t		*inner_ipha;
15224 
15225 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15226 	    "ip_rput_locl_start: q %p", q);
15227 
15228 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15229 
15230 
15231 #define	rptr	((uchar_t *)ipha)
15232 #define	iphs	((uint16_t *)ipha)
15233 
15234 	/*
15235 	 * no UDP or TCP packet should come here anymore.
15236 	 */
15237 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15238 	    (ipha->ipha_protocol != IPPROTO_UDP));
15239 
15240 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15241 /* EXPORT DELETE START */
15242 	if (mctl_present &&
15243 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15244 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15245 
15246 		/*
15247 		 * It's an IPsec accelerated packet.
15248 		 * Keep a pointer to the data attributes around until
15249 		 * we allocate the ipsec_info_t.
15250 		 */
15251 		IPSECHW_DEBUG(IPSECHW_PKT,
15252 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15253 		hada_mp = first_mp;
15254 		hada_mp->b_cont = NULL;
15255 		/*
15256 		 * Since it is accelerated, it comes directly from
15257 		 * the ill and the data attributes is followed by
15258 		 * the packet data.
15259 		 */
15260 		ASSERT(mp->b_datap->db_type != M_CTL);
15261 		first_mp = mp;
15262 		mctl_present = B_FALSE;
15263 	}
15264 /* EXPORT DELETE END */
15265 
15266 	/*
15267 	 * IF M_CTL is not present, then ipsec_in_is_secure
15268 	 * should return B_TRUE. There is a case where loopback
15269 	 * packets has an M_CTL in the front with all the
15270 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15271 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15272 	 * packets never comes here, it is safe to ASSERT the
15273 	 * following.
15274 	 */
15275 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15276 
15277 
15278 	/* u1 is # words of IP options */
15279 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15280 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15281 
15282 	if (u1) {
15283 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15284 			if (hada_mp != NULL)
15285 				freemsg(hada_mp);
15286 			return;
15287 		}
15288 	} else {
15289 		/* Check the IP header checksum.  */
15290 #define	uph	((uint16_t *)ipha)
15291 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15292 		    uph[6] + uph[7] + uph[8] + uph[9];
15293 #undef  uph
15294 		/* finish doing IP checksum */
15295 		sum = (sum & 0xFFFF) + (sum >> 16);
15296 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15297 		/*
15298 		 * Don't verify header checksum if this packet is coming
15299 		 * back from AH/ESP as we already did it.
15300 		 */
15301 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15302 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15303 			goto drop_pkt;
15304 		}
15305 	}
15306 
15307 	/*
15308 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15309 	 * might be called more than once for secure packets, count only
15310 	 * the first time.
15311 	 */
15312 	if (!mctl_present) {
15313 		UPDATE_IB_PKT_COUNT(ire);
15314 		ire->ire_last_used_time = lbolt;
15315 	}
15316 
15317 	/* Check for fragmentation offset. */
15318 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15319 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15320 	if (u1) {
15321 		/*
15322 		 * We re-assemble fragments before we do the AH/ESP
15323 		 * processing. Thus, M_CTL should not be present
15324 		 * while we are re-assembling.
15325 		 */
15326 		ASSERT(!mctl_present);
15327 		ASSERT(first_mp == mp);
15328 		if (!ip_rput_fragment(q, &mp, ipha)) {
15329 			return;
15330 		}
15331 		/*
15332 		 * Make sure that first_mp points back to mp as
15333 		 * the mp we came in with could have changed in
15334 		 * ip_rput_fragment().
15335 		 */
15336 		ipha = (ipha_t *)mp->b_rptr;
15337 		first_mp = mp;
15338 	}
15339 
15340 	/*
15341 	 * Clear hardware checksumming flag as it is currently only
15342 	 * used by TCP and UDP.
15343 	 */
15344 	mp->b_datap->db_struioun.cksum.flags = 0;
15345 
15346 	/* Now we have a complete datagram, destined for this machine. */
15347 	u1 = IPH_HDR_LENGTH(ipha);
15348 	switch (ipha->ipha_protocol) {
15349 	case IPPROTO_ICMP: {
15350 		ire_t		*ire_zone;
15351 		ilm_t		*ilm;
15352 		mblk_t		*mp1;
15353 		zoneid_t	last_zoneid;
15354 
15355 		if (CLASSD(ipha->ipha_dst) &&
15356 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15357 			ASSERT(ire->ire_type == IRE_BROADCAST);
15358 			/*
15359 			 * In the multicast case, applications may have joined
15360 			 * the group from different zones, so we need to deliver
15361 			 * the packet to each of them. Loop through the
15362 			 * multicast memberships structures (ilm) on the receive
15363 			 * ill and send a copy of the packet up each matching
15364 			 * one. However, we don't do this for multicasts sent on
15365 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15366 			 * they must stay in the sender's zone.
15367 			 *
15368 			 * ilm_add_v6() ensures that ilms in the same zone are
15369 			 * contiguous in the ill_ilm list. We use this property
15370 			 * to avoid sending duplicates needed when two
15371 			 * applications in the same zone join the same group on
15372 			 * different logical interfaces: we ignore the ilm if
15373 			 * its zoneid is the same as the last matching one.
15374 			 * In addition, the sending of the packet for
15375 			 * ire_zoneid is delayed until all of the other ilms
15376 			 * have been exhausted.
15377 			 */
15378 			last_zoneid = -1;
15379 			ILM_WALKER_HOLD(recv_ill);
15380 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15381 			    ilm = ilm->ilm_next) {
15382 				if ((ilm->ilm_flags & ILM_DELETED) ||
15383 				    ipha->ipha_dst != ilm->ilm_addr ||
15384 				    ilm->ilm_zoneid == last_zoneid ||
15385 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15386 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15387 					continue;
15388 				mp1 = ip_copymsg(first_mp);
15389 				if (mp1 == NULL)
15390 					continue;
15391 				icmp_inbound(q, mp1, B_TRUE, ill,
15392 				    0, sum, mctl_present, B_TRUE,
15393 				    recv_ill, ilm->ilm_zoneid);
15394 				last_zoneid = ilm->ilm_zoneid;
15395 			}
15396 			ILM_WALKER_RELE(recv_ill);
15397 		} else if (ire->ire_type == IRE_BROADCAST) {
15398 			/*
15399 			 * In the broadcast case, there may be many zones
15400 			 * which need a copy of the packet delivered to them.
15401 			 * There is one IRE_BROADCAST per broadcast address
15402 			 * and per zone; we walk those using a helper function.
15403 			 * In addition, the sending of the packet for ire is
15404 			 * delayed until all of the other ires have been
15405 			 * processed.
15406 			 */
15407 			IRB_REFHOLD(ire->ire_bucket);
15408 			ire_zone = NULL;
15409 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15410 			    ire)) != NULL) {
15411 				mp1 = ip_copymsg(first_mp);
15412 				if (mp1 == NULL)
15413 					continue;
15414 
15415 				UPDATE_IB_PKT_COUNT(ire_zone);
15416 				ire_zone->ire_last_used_time = lbolt;
15417 				icmp_inbound(q, mp1, B_TRUE, ill,
15418 				    0, sum, mctl_present, B_TRUE,
15419 				    recv_ill, ire_zone->ire_zoneid);
15420 			}
15421 			IRB_REFRELE(ire->ire_bucket);
15422 		}
15423 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15424 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15425 		    ire->ire_zoneid);
15426 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15427 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15428 		return;
15429 	}
15430 	case IPPROTO_IGMP:
15431 		/*
15432 		 * If we are not willing to accept IGMP packets in clear,
15433 		 * then check with global policy.
15434 		 */
15435 		if (igmp_accept_clear_messages == 0) {
15436 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15437 			    ipha, NULL, mctl_present);
15438 			if (first_mp == NULL)
15439 				return;
15440 		}
15441 		if (igmp_input(q, mp, ill)) {
15442 			/* Bad packet - discarded by igmp_input */
15443 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15444 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15445 			if (mctl_present)
15446 				freeb(first_mp);
15447 			return;
15448 		}
15449 		/*
15450 		 * igmp_input() may have pulled up the message so ipha needs to
15451 		 * be reinitialized.
15452 		 */
15453 		ipha = (ipha_t *)mp->b_rptr;
15454 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15455 			/* No user-level listener for IGMP packets */
15456 			goto drop_pkt;
15457 		}
15458 		/* deliver to local raw users */
15459 		break;
15460 	case IPPROTO_PIM:
15461 		/*
15462 		 * If we are not willing to accept PIM packets in clear,
15463 		 * then check with global policy.
15464 		 */
15465 		if (pim_accept_clear_messages == 0) {
15466 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15467 			    ipha, NULL, mctl_present);
15468 			if (first_mp == NULL)
15469 				return;
15470 		}
15471 		if (pim_input(q, mp) != 0) {
15472 			/* Bad packet - discarded by pim_input */
15473 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15474 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15475 			if (mctl_present)
15476 				freeb(first_mp);
15477 			return;
15478 		}
15479 
15480 		/*
15481 		 * pim_input() may have pulled up the message so ipha needs to
15482 		 * be reinitialized.
15483 		 */
15484 		ipha = (ipha_t *)mp->b_rptr;
15485 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15486 			/* No user-level listener for PIM packets */
15487 			goto drop_pkt;
15488 		}
15489 		/* deliver to local raw users */
15490 		break;
15491 	case IPPROTO_ENCAP:
15492 		/*
15493 		 * Handle self-encapsulated packets (IP-in-IP where
15494 		 * the inner addresses == the outer addresses).
15495 		 */
15496 		hdr_length = IPH_HDR_LENGTH(ipha);
15497 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15498 		    mp->b_wptr) {
15499 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15500 			    sizeof (ipha_t) - mp->b_rptr)) {
15501 				BUMP_MIB(&ip_mib, ipInDiscards);
15502 				freemsg(first_mp);
15503 				return;
15504 			}
15505 			ipha = (ipha_t *)mp->b_rptr;
15506 		}
15507 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15508 		/*
15509 		 * Check the sanity of the inner IP header.
15510 		 */
15511 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15512 			BUMP_MIB(&ip_mib, ipInDiscards);
15513 			freemsg(first_mp);
15514 			return;
15515 		}
15516 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15517 			BUMP_MIB(&ip_mib, ipInDiscards);
15518 			freemsg(first_mp);
15519 			return;
15520 		}
15521 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15522 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15523 			ipsec_in_t *ii;
15524 
15525 			/*
15526 			 * Self-encapsulated tunnel packet. Remove
15527 			 * the outer IP header and fanout again.
15528 			 * We also need to make sure that the inner
15529 			 * header is pulled up until options.
15530 			 */
15531 			mp->b_rptr = (uchar_t *)inner_ipha;
15532 			ipha = inner_ipha;
15533 			hdr_length = IPH_HDR_LENGTH(ipha);
15534 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15535 				if (!pullupmsg(mp, (uchar_t *)ipha +
15536 				    + hdr_length - mp->b_rptr)) {
15537 					freemsg(first_mp);
15538 					return;
15539 				}
15540 				ipha = (ipha_t *)mp->b_rptr;
15541 			}
15542 			if (!mctl_present) {
15543 				ASSERT(first_mp == mp);
15544 				/*
15545 				 * This means that somebody is sending
15546 				 * Self-encapsualted packets without AH/ESP.
15547 				 * If AH/ESP was present, we would have already
15548 				 * allocated the first_mp.
15549 				 */
15550 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15551 				    NULL) {
15552 					ip1dbg(("ip_proto_input: IPSEC_IN "
15553 					    "allocation failure.\n"));
15554 					BUMP_MIB(&ip_mib, ipInDiscards);
15555 					freemsg(mp);
15556 					return;
15557 				}
15558 				first_mp->b_cont = mp;
15559 			}
15560 			/*
15561 			 * We generally store the ill_index if we need to
15562 			 * do IPSEC processing as we lose the ill queue when
15563 			 * we come back. But in this case, we never should
15564 			 * have to store the ill_index here as it should have
15565 			 * been stored previously when we processed the
15566 			 * AH/ESP header in this routine or for non-ipsec
15567 			 * cases, we still have the queue. But for some bad
15568 			 * packets from the wire, we can get to IPSEC after
15569 			 * this and we better store the index for that case.
15570 			 */
15571 			ill = (ill_t *)q->q_ptr;
15572 			ii = (ipsec_in_t *)first_mp->b_rptr;
15573 			ii->ipsec_in_ill_index =
15574 			    ill->ill_phyint->phyint_ifindex;
15575 			ii->ipsec_in_rill_index =
15576 			    recv_ill->ill_phyint->phyint_ifindex;
15577 			if (ii->ipsec_in_decaps) {
15578 				/*
15579 				 * This packet is self-encapsulated multiple
15580 				 * times. We don't want to recurse infinitely.
15581 				 * To keep it simple, drop the packet.
15582 				 */
15583 				BUMP_MIB(&ip_mib, ipInDiscards);
15584 				freemsg(first_mp);
15585 				return;
15586 			}
15587 			ii->ipsec_in_decaps = B_TRUE;
15588 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15589 			return;
15590 		}
15591 		break;
15592 	case IPPROTO_AH:
15593 	case IPPROTO_ESP: {
15594 		/*
15595 		 * Fast path for AH/ESP. If this is the first time
15596 		 * we are sending a datagram to AH/ESP, allocate
15597 		 * a IPSEC_IN message and prepend it. Otherwise,
15598 		 * just fanout.
15599 		 */
15600 
15601 		int ipsec_rc;
15602 		ipsec_in_t *ii;
15603 
15604 		IP_STAT(ipsec_proto_ahesp);
15605 		if (!mctl_present) {
15606 			ASSERT(first_mp == mp);
15607 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15608 				ip1dbg(("ip_proto_input: IPSEC_IN "
15609 				    "allocation failure.\n"));
15610 				freemsg(hada_mp); /* okay ifnull */
15611 				BUMP_MIB(&ip_mib, ipInDiscards);
15612 				freemsg(mp);
15613 				return;
15614 			}
15615 			/*
15616 			 * Store the ill_index so that when we come back
15617 			 * from IPSEC we ride on the same queue.
15618 			 */
15619 			ill = (ill_t *)q->q_ptr;
15620 			ii = (ipsec_in_t *)first_mp->b_rptr;
15621 			ii->ipsec_in_ill_index =
15622 			    ill->ill_phyint->phyint_ifindex;
15623 			ii->ipsec_in_rill_index =
15624 			    recv_ill->ill_phyint->phyint_ifindex;
15625 			first_mp->b_cont = mp;
15626 			/*
15627 			 * Cache hardware acceleration info.
15628 			 */
15629 			if (hada_mp != NULL) {
15630 				IPSECHW_DEBUG(IPSECHW_PKT,
15631 				    ("ip_rput_local: caching data attr.\n"));
15632 				ii->ipsec_in_accelerated = B_TRUE;
15633 				ii->ipsec_in_da = hada_mp;
15634 				hada_mp = NULL;
15635 			}
15636 		} else {
15637 			ii = (ipsec_in_t *)first_mp->b_rptr;
15638 		}
15639 
15640 		if (!ipsec_loaded()) {
15641 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15642 			    ire->ire_zoneid);
15643 			return;
15644 		}
15645 
15646 		/* select inbound SA and have IPsec process the pkt */
15647 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15648 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15649 			if (esph == NULL)
15650 				return;
15651 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15652 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15653 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15654 			    first_mp, esph);
15655 		} else {
15656 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15657 			if (ah == NULL)
15658 				return;
15659 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15660 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15661 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15662 			    first_mp, ah);
15663 		}
15664 
15665 		switch (ipsec_rc) {
15666 		case IPSEC_STATUS_SUCCESS:
15667 			break;
15668 		case IPSEC_STATUS_FAILED:
15669 			BUMP_MIB(&ip_mib, ipInDiscards);
15670 			/* FALLTHRU */
15671 		case IPSEC_STATUS_PENDING:
15672 			return;
15673 		}
15674 		/* we're done with IPsec processing, send it up */
15675 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15676 		return;
15677 	}
15678 	default:
15679 		break;
15680 	}
15681 	/*
15682 	 * Handle protocols with which IP is less intimate.  There
15683 	 * can be more than one stream bound to a particular
15684 	 * protocol.  When this is the case, each one gets a copy
15685 	 * of any incoming packets.
15686 	 */
15687 	ip_fanout_proto(q, first_mp, ill, ipha,
15688 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15689 	    B_TRUE, recv_ill, ire->ire_zoneid);
15690 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15691 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15692 	return;
15693 
15694 drop_pkt:
15695 	freemsg(first_mp);
15696 	if (hada_mp != NULL)
15697 		freeb(hada_mp);
15698 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15699 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15700 #undef	rptr
15701 #undef  iphs
15702 
15703 }
15704 
15705 /*
15706  * Update any source route, record route or timestamp options.
15707  * Check that we are at end of strict source route.
15708  * The options have already been checked for sanity in ip_rput_options().
15709  */
15710 static boolean_t
15711 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15712 {
15713 	ipoptp_t	opts;
15714 	uchar_t		*opt;
15715 	uint8_t		optval;
15716 	uint8_t		optlen;
15717 	ipaddr_t	dst;
15718 	uint32_t	ts;
15719 	ire_t		*dst_ire;
15720 	timestruc_t	now;
15721 
15722 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15723 
15724 	ip2dbg(("ip_rput_local_options\n"));
15725 
15726 	for (optval = ipoptp_first(&opts, ipha);
15727 	    optval != IPOPT_EOL;
15728 	    optval = ipoptp_next(&opts)) {
15729 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15730 		opt = opts.ipoptp_cur;
15731 		optlen = opts.ipoptp_len;
15732 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15733 		    optval, optlen));
15734 		switch (optval) {
15735 			uint32_t off;
15736 		case IPOPT_SSRR:
15737 		case IPOPT_LSRR:
15738 			off = opt[IPOPT_OFFSET];
15739 			off--;
15740 			if (optlen < IP_ADDR_LEN ||
15741 			    off > optlen - IP_ADDR_LEN) {
15742 				/* End of source route */
15743 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15744 				break;
15745 			}
15746 			/*
15747 			 * This will only happen if two consecutive entries
15748 			 * in the source route contains our address or if
15749 			 * it is a packet with a loose source route which
15750 			 * reaches us before consuming the whole source route
15751 			 */
15752 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15753 			if (optval == IPOPT_SSRR) {
15754 				goto bad_src_route;
15755 			}
15756 			/*
15757 			 * Hack: instead of dropping the packet truncate the
15758 			 * source route to what has been used by filling the
15759 			 * rest with IPOPT_NOP.
15760 			 */
15761 			opt[IPOPT_OLEN] = (uint8_t)off;
15762 			while (off < optlen) {
15763 				opt[off++] = IPOPT_NOP;
15764 			}
15765 			break;
15766 		case IPOPT_RR:
15767 			off = opt[IPOPT_OFFSET];
15768 			off--;
15769 			if (optlen < IP_ADDR_LEN ||
15770 			    off > optlen - IP_ADDR_LEN) {
15771 				/* No more room - ignore */
15772 				ip1dbg((
15773 				    "ip_rput_local_options: end of RR\n"));
15774 				break;
15775 			}
15776 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15777 			    IP_ADDR_LEN);
15778 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15779 			break;
15780 		case IPOPT_TS:
15781 			/* Insert timestamp if there is romm */
15782 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15783 			case IPOPT_TS_TSONLY:
15784 				off = IPOPT_TS_TIMELEN;
15785 				break;
15786 			case IPOPT_TS_PRESPEC:
15787 			case IPOPT_TS_PRESPEC_RFC791:
15788 				/* Verify that the address matched */
15789 				off = opt[IPOPT_OFFSET] - 1;
15790 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15791 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15792 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15793 				if (dst_ire == NULL) {
15794 					/* Not for us */
15795 					break;
15796 				}
15797 				ire_refrele(dst_ire);
15798 				/* FALLTHRU */
15799 			case IPOPT_TS_TSANDADDR:
15800 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15801 				break;
15802 			default:
15803 				/*
15804 				 * ip_*put_options should have already
15805 				 * dropped this packet.
15806 				 */
15807 				cmn_err(CE_PANIC, "ip_rput_local_options: "
15808 				    "unknown IT - bug in ip_rput_options?\n");
15809 				return (B_TRUE);	/* Keep "lint" happy */
15810 			}
15811 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15812 				/* Increase overflow counter */
15813 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15814 				opt[IPOPT_POS_OV_FLG] =
15815 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15816 				    (off << 4));
15817 				break;
15818 			}
15819 			off = opt[IPOPT_OFFSET] - 1;
15820 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15821 			case IPOPT_TS_PRESPEC:
15822 			case IPOPT_TS_PRESPEC_RFC791:
15823 			case IPOPT_TS_TSANDADDR:
15824 				bcopy(&ire->ire_src_addr, (char *)opt + off,
15825 				    IP_ADDR_LEN);
15826 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15827 				/* FALLTHRU */
15828 			case IPOPT_TS_TSONLY:
15829 				off = opt[IPOPT_OFFSET] - 1;
15830 				/* Compute # of milliseconds since midnight */
15831 				gethrestime(&now);
15832 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15833 				    now.tv_nsec / (NANOSEC / MILLISEC);
15834 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15835 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15836 				break;
15837 			}
15838 			break;
15839 		}
15840 	}
15841 	return (B_TRUE);
15842 
15843 bad_src_route:
15844 	q = WR(q);
15845 	/* make sure we clear any indication of a hardware checksum */
15846 	mp->b_datap->db_struioun.cksum.flags = 0;
15847 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
15848 	return (B_FALSE);
15849 
15850 }
15851 
15852 /*
15853  * Process IP options in an inbound packet.  If an option affects the
15854  * effective destination address, return the next hop address via dstp.
15855  * Returns -1 if something fails in which case an ICMP error has been sent
15856  * and mp freed.
15857  */
15858 static int
15859 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
15860 {
15861 	ipoptp_t	opts;
15862 	uchar_t		*opt;
15863 	uint8_t		optval;
15864 	uint8_t		optlen;
15865 	ipaddr_t	dst;
15866 	intptr_t	code = 0;
15867 	ire_t		*ire = NULL;
15868 
15869 	ip2dbg(("ip_rput_options\n"));
15870 	dst = ipha->ipha_dst;
15871 	for (optval = ipoptp_first(&opts, ipha);
15872 	    optval != IPOPT_EOL;
15873 	    optval = ipoptp_next(&opts)) {
15874 		opt = opts.ipoptp_cur;
15875 		optlen = opts.ipoptp_len;
15876 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
15877 		    optval, optlen));
15878 		/*
15879 		 * Note: we need to verify the checksum before we
15880 		 * modify anything thus this routine only extracts the next
15881 		 * hop dst from any source route.
15882 		 */
15883 		switch (optval) {
15884 			uint32_t off;
15885 		case IPOPT_SSRR:
15886 		case IPOPT_LSRR:
15887 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15888 			    ALL_ZONES, MATCH_IRE_TYPE);
15889 			if (ire == NULL) {
15890 				if (optval == IPOPT_SSRR) {
15891 					ip1dbg(("ip_rput_options: not next"
15892 					    " strict source route 0x%x\n",
15893 					    ntohl(dst)));
15894 					code = (char *)&ipha->ipha_dst -
15895 					    (char *)ipha;
15896 					goto param_prob; /* RouterReq's */
15897 				}
15898 				ip2dbg(("ip_rput_options: "
15899 				    "not next source route 0x%x\n",
15900 				    ntohl(dst)));
15901 				break;
15902 			}
15903 			ire_refrele(ire);
15904 
15905 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15906 				ip1dbg((
15907 				    "ip_rput_options: bad option offset\n"));
15908 				code = (char *)&opt[IPOPT_OLEN] -
15909 				    (char *)ipha;
15910 				goto param_prob;
15911 			}
15912 			off = opt[IPOPT_OFFSET];
15913 			off--;
15914 		redo_srr:
15915 			if (optlen < IP_ADDR_LEN ||
15916 			    off > optlen - IP_ADDR_LEN) {
15917 				/* End of source route */
15918 				ip1dbg(("ip_rput_options: end of SR\n"));
15919 				break;
15920 			}
15921 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15922 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
15923 			    ntohl(dst)));
15924 
15925 			/*
15926 			 * Check if our address is present more than
15927 			 * once as consecutive hops in source route.
15928 			 * XXX verify per-interface ip_forwarding
15929 			 * for source route?
15930 			 */
15931 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15932 			    ALL_ZONES, MATCH_IRE_TYPE);
15933 
15934 			if (ire != NULL) {
15935 				ire_refrele(ire);
15936 				off += IP_ADDR_LEN;
15937 				goto redo_srr;
15938 			}
15939 
15940 			if (dst == htonl(INADDR_LOOPBACK)) {
15941 				ip1dbg(("ip_rput_options: loopback addr in "
15942 				    "source route!\n"));
15943 				goto bad_src_route;
15944 			}
15945 			/*
15946 			 * For strict: verify that dst is directly
15947 			 * reachable.
15948 			 */
15949 			if (optval == IPOPT_SSRR) {
15950 				ire = ire_ftable_lookup(dst, 0, 0,
15951 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
15952 				    MATCH_IRE_TYPE);
15953 				if (ire == NULL) {
15954 					ip1dbg(("ip_rput_options: SSRR not "
15955 					    "directly reachable: 0x%x\n",
15956 					    ntohl(dst)));
15957 					goto bad_src_route;
15958 				}
15959 				ire_refrele(ire);
15960 			}
15961 			/*
15962 			 * Defer update of the offset and the record route
15963 			 * until the packet is forwarded.
15964 			 */
15965 			break;
15966 		case IPOPT_RR:
15967 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15968 				ip1dbg((
15969 				    "ip_rput_options: bad option offset\n"));
15970 				code = (char *)&opt[IPOPT_OLEN] -
15971 				    (char *)ipha;
15972 				goto param_prob;
15973 			}
15974 			break;
15975 		case IPOPT_TS:
15976 			/*
15977 			 * Verify that length >= 5 and that there is either
15978 			 * room for another timestamp or that the overflow
15979 			 * counter is not maxed out.
15980 			 */
15981 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
15982 			if (optlen < IPOPT_MINLEN_IT) {
15983 				goto param_prob;
15984 			}
15985 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15986 				ip1dbg((
15987 				    "ip_rput_options: bad option offset\n"));
15988 				code = (char *)&opt[IPOPT_OFFSET] -
15989 				    (char *)ipha;
15990 				goto param_prob;
15991 			}
15992 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15993 			case IPOPT_TS_TSONLY:
15994 				off = IPOPT_TS_TIMELEN;
15995 				break;
15996 			case IPOPT_TS_TSANDADDR:
15997 			case IPOPT_TS_PRESPEC:
15998 			case IPOPT_TS_PRESPEC_RFC791:
15999 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16000 				break;
16001 			default:
16002 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16003 				    (char *)ipha;
16004 				goto param_prob;
16005 			}
16006 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16007 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16008 				/*
16009 				 * No room and the overflow counter is 15
16010 				 * already.
16011 				 */
16012 				goto param_prob;
16013 			}
16014 			break;
16015 		}
16016 	}
16017 
16018 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16019 		*dstp = dst;
16020 		return (0);
16021 	}
16022 
16023 	ip1dbg(("ip_rput_options: error processing IP options."));
16024 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16025 
16026 param_prob:
16027 	q = WR(q);
16028 	/* make sure we clear any indication of a hardware checksum */
16029 	mp->b_datap->db_struioun.cksum.flags = 0;
16030 	icmp_param_problem(q, mp, (uint8_t)code);
16031 	return (-1);
16032 
16033 bad_src_route:
16034 	q = WR(q);
16035 	/* make sure we clear any indication of a hardware checksum */
16036 	mp->b_datap->db_struioun.cksum.flags = 0;
16037 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16038 	return (-1);
16039 }
16040 
16041 /*
16042  * IP & ICMP info in >=14 msg's ...
16043  *  - ip fixed part (mib2_ip_t)
16044  *  - icmp fixed part (mib2_icmp_t)
16045  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16046  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16047  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16048  *  - ip multicast membership (ip_member_t)
16049  *  - ip multicast source filtering (ip_grpsrc_t)
16050  *  - igmp fixed part (struct igmpstat)
16051  *  - multicast routing stats (struct mrtstat)
16052  *  - multicast routing vifs (array of struct vifctl)
16053  *  - multicast routing routes (array of struct mfcctl)
16054  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16055  *					One per ill plus one generic
16056  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16057  *					One per ill plus one generic
16058  *  - ipv6RouteEntry			all IPv6 IREs
16059  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16060  *  - ipv6AddrEntry			all IPv6 ipifs
16061  *  - ipv6 multicast membership (ipv6_member_t)
16062  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16063  *
16064  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16065  * already present.
16066  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16067  * already filled in by caller.
16068  * Return value of 0 indicates that no messages were sent and caller
16069  * should free mpctl.
16070  */
16071 int
16072 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16073 {
16074 
16075 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16076 		return (0);
16077 	}
16078 
16079 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16080 		return (1);
16081 	}
16082 
16083 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16084 		return (1);
16085 	}
16086 
16087 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16088 		return (1);
16089 	}
16090 
16091 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16092 		return (1);
16093 	}
16094 
16095 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16096 		return (1);
16097 	}
16098 
16099 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16100 		return (1);
16101 	}
16102 
16103 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16104 		return (1);
16105 	}
16106 
16107 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16108 		return (1);
16109 	}
16110 
16111 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16112 		return (1);
16113 	}
16114 
16115 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16116 		return (1);
16117 	}
16118 
16119 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16120 		return (1);
16121 	}
16122 
16123 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16124 		return (1);
16125 	}
16126 
16127 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16128 		return (1);
16129 	}
16130 
16131 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16132 		return (1);
16133 	}
16134 
16135 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16136 		return (1);
16137 	}
16138 
16139 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16140 		return (1);
16141 	}
16142 
16143 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16144 		return (1);
16145 	}
16146 	freemsg(mpctl);
16147 	return (1);
16148 }
16149 
16150 
16151 /* Get global IPv4 statistics */
16152 static mblk_t *
16153 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16154 {
16155 	struct opthdr		*optp;
16156 	mblk_t			*mp2ctl;
16157 
16158 	/*
16159 	 * make a copy of the original message
16160 	 */
16161 	mp2ctl = copymsg(mpctl);
16162 
16163 	/* fixed length IP structure... */
16164 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16165 	optp->level = MIB2_IP;
16166 	optp->name = 0;
16167 	SET_MIB(ip_mib.ipForwarding,
16168 	    (WE_ARE_FORWARDING ? 1 : 2));
16169 	SET_MIB(ip_mib.ipDefaultTTL,
16170 	    (uint32_t)ip_def_ttl);
16171 	SET_MIB(ip_mib.ipReasmTimeout,
16172 	    ip_g_frag_timeout);
16173 	SET_MIB(ip_mib.ipAddrEntrySize,
16174 	    sizeof (mib2_ipAddrEntry_t));
16175 	SET_MIB(ip_mib.ipRouteEntrySize,
16176 	    sizeof (mib2_ipRouteEntry_t));
16177 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16178 	    sizeof (mib2_ipNetToMediaEntry_t));
16179 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16180 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16181 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16182 	    (int)sizeof (ip_mib))) {
16183 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16184 		    (uint_t)sizeof (ip_mib)));
16185 	}
16186 
16187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16188 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16189 	    (int)optp->level, (int)optp->name, (int)optp->len));
16190 	qreply(q, mpctl);
16191 	return (mp2ctl);
16192 }
16193 
16194 /* Global IPv4 ICMP statistics */
16195 static mblk_t *
16196 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16197 {
16198 	struct opthdr		*optp;
16199 	mblk_t			*mp2ctl;
16200 
16201 	/*
16202 	 * Make a copy of the original message
16203 	 */
16204 	mp2ctl = copymsg(mpctl);
16205 
16206 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16207 	optp->level = MIB2_ICMP;
16208 	optp->name = 0;
16209 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16210 	    (int)sizeof (icmp_mib))) {
16211 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16212 		    (uint_t)sizeof (icmp_mib)));
16213 	}
16214 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16215 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16216 	    (int)optp->level, (int)optp->name, (int)optp->len));
16217 	qreply(q, mpctl);
16218 	return (mp2ctl);
16219 }
16220 
16221 /* Global IPv4 IGMP statistics */
16222 static mblk_t *
16223 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16224 {
16225 	struct opthdr		*optp;
16226 	mblk_t			*mp2ctl;
16227 
16228 	/*
16229 	 * make a copy of the original message
16230 	 */
16231 	mp2ctl = copymsg(mpctl);
16232 
16233 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16234 	optp->level = EXPER_IGMP;
16235 	optp->name = 0;
16236 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16237 	    (int)sizeof (igmpstat))) {
16238 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16239 		    (uint_t)sizeof (igmpstat)));
16240 	}
16241 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16242 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16243 	    (int)optp->level, (int)optp->name, (int)optp->len));
16244 	qreply(q, mpctl);
16245 	return (mp2ctl);
16246 }
16247 
16248 /* Global IPv4 Multicast Routing statistics */
16249 static mblk_t *
16250 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16251 {
16252 	struct opthdr		*optp;
16253 	mblk_t			*mp2ctl;
16254 
16255 	/*
16256 	 * make a copy of the original message
16257 	 */
16258 	mp2ctl = copymsg(mpctl);
16259 
16260 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16261 	optp->level = EXPER_DVMRP;
16262 	optp->name = 0;
16263 	if (!ip_mroute_stats(mpctl->b_cont)) {
16264 		ip0dbg(("ip_mroute_stats: failed\n"));
16265 	}
16266 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16267 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16268 	    (int)optp->level, (int)optp->name, (int)optp->len));
16269 	qreply(q, mpctl);
16270 	return (mp2ctl);
16271 }
16272 
16273 /* IPv4 address information */
16274 static mblk_t *
16275 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16276 {
16277 	struct opthdr		*optp;
16278 	mblk_t			*mp2ctl;
16279 	mblk_t			*mp_tail = NULL;
16280 	ill_t			*ill;
16281 	ipif_t			*ipif;
16282 	uint_t			bitval;
16283 	mib2_ipAddrEntry_t	mae;
16284 	zoneid_t		zoneid;
16285 	ill_walk_context_t ctx;
16286 
16287 	/*
16288 	 * make a copy of the original message
16289 	 */
16290 	mp2ctl = copymsg(mpctl);
16291 
16292 	/* ipAddrEntryTable */
16293 
16294 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16295 	optp->level = MIB2_IP;
16296 	optp->name = MIB2_IP_ADDR;
16297 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16298 
16299 	rw_enter(&ill_g_lock, RW_READER);
16300 	ill = ILL_START_WALK_V4(&ctx);
16301 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16302 		for (ipif = ill->ill_ipif; ipif != NULL;
16303 		    ipif = ipif->ipif_next) {
16304 			if (ipif->ipif_zoneid != zoneid)
16305 				continue;
16306 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16307 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16308 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16309 
16310 			(void) ipif_get_name(ipif,
16311 			    mae.ipAdEntIfIndex.o_bytes,
16312 			    OCTET_LENGTH);
16313 			mae.ipAdEntIfIndex.o_length =
16314 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16315 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16316 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16317 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16318 			mae.ipAdEntInfo.ae_subnet_len =
16319 			    ip_mask_to_plen(ipif->ipif_net_mask);
16320 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16321 			for (bitval = 1;
16322 			    bitval &&
16323 			    !(bitval & ipif->ipif_brd_addr);
16324 			    bitval <<= 1)
16325 				noop;
16326 			mae.ipAdEntBcastAddr = bitval;
16327 			mae.ipAdEntReasmMaxSize = 65535;
16328 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16329 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16330 			mae.ipAdEntInfo.ae_broadcast_addr =
16331 			    ipif->ipif_brd_addr;
16332 			mae.ipAdEntInfo.ae_pp_dst_addr =
16333 			    ipif->ipif_pp_dst_addr;
16334 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16335 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16336 
16337 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16338 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16339 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16340 				    "allocate %u bytes\n",
16341 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16342 			}
16343 		}
16344 	}
16345 	rw_exit(&ill_g_lock);
16346 
16347 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16348 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16349 	    (int)optp->level, (int)optp->name, (int)optp->len));
16350 	qreply(q, mpctl);
16351 	return (mp2ctl);
16352 }
16353 
16354 /* IPv6 address information */
16355 static mblk_t *
16356 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16357 {
16358 	struct opthdr		*optp;
16359 	mblk_t			*mp2ctl;
16360 	mblk_t			*mp_tail = NULL;
16361 	ill_t			*ill;
16362 	ipif_t			*ipif;
16363 	mib2_ipv6AddrEntry_t	mae6;
16364 	zoneid_t		zoneid;
16365 	ill_walk_context_t	ctx;
16366 
16367 	/*
16368 	 * make a copy of the original message
16369 	 */
16370 	mp2ctl = copymsg(mpctl);
16371 
16372 	/* ipv6AddrEntryTable */
16373 
16374 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16375 	optp->level = MIB2_IP6;
16376 	optp->name = MIB2_IP6_ADDR;
16377 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16378 
16379 	rw_enter(&ill_g_lock, RW_READER);
16380 	ill = ILL_START_WALK_V6(&ctx);
16381 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16382 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16383 			if (ipif->ipif_zoneid != zoneid)
16384 				continue;
16385 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16386 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16387 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16388 
16389 			(void) ipif_get_name(ipif,
16390 			    mae6.ipv6AddrIfIndex.o_bytes,
16391 			    OCTET_LENGTH);
16392 			mae6.ipv6AddrIfIndex.o_length =
16393 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16394 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16395 			mae6.ipv6AddrPfxLength =
16396 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16397 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16398 			mae6.ipv6AddrInfo.ae_subnet_len =
16399 			    mae6.ipv6AddrPfxLength;
16400 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16401 
16402 			/* Type: stateless(1), stateful(2), unknown(3) */
16403 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16404 				mae6.ipv6AddrType = 1;
16405 			else
16406 				mae6.ipv6AddrType = 2;
16407 			/* Anycast: true(1), false(2) */
16408 			if (ipif->ipif_flags & IPIF_ANYCAST)
16409 				mae6.ipv6AddrAnycastFlag = 1;
16410 			else
16411 				mae6.ipv6AddrAnycastFlag = 2;
16412 
16413 			/*
16414 			 * Address status: preferred(1), deprecated(2),
16415 			 * invalid(3), inaccessible(4), unknown(5)
16416 			 */
16417 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16418 				mae6.ipv6AddrStatus = 3;
16419 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16420 				mae6.ipv6AddrStatus = 2;
16421 			else
16422 				mae6.ipv6AddrStatus = 1;
16423 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16424 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16425 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16426 						ipif->ipif_v6pp_dst_addr;
16427 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16428 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16429 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16430 				(char *)&mae6,
16431 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16432 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16433 				    "allocate %u bytes\n",
16434 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16435 			}
16436 		}
16437 	}
16438 	rw_exit(&ill_g_lock);
16439 
16440 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16441 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16442 	    (int)optp->level, (int)optp->name, (int)optp->len));
16443 	qreply(q, mpctl);
16444 	return (mp2ctl);
16445 }
16446 
16447 /* IPv4 multicast group membership. */
16448 static mblk_t *
16449 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16450 {
16451 	struct opthdr		*optp;
16452 	mblk_t			*mp2ctl;
16453 	ill_t			*ill;
16454 	ipif_t			*ipif;
16455 	ilm_t			*ilm;
16456 	ip_member_t		ipm;
16457 	mblk_t			*mp_tail = NULL;
16458 	ill_walk_context_t	ctx;
16459 	zoneid_t		zoneid;
16460 
16461 	/*
16462 	 * make a copy of the original message
16463 	 */
16464 	mp2ctl = copymsg(mpctl);
16465 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16466 
16467 	/* ipGroupMember table */
16468 	optp = (struct opthdr *)&mpctl->b_rptr[
16469 	    sizeof (struct T_optmgmt_ack)];
16470 	optp->level = MIB2_IP;
16471 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16472 
16473 	rw_enter(&ill_g_lock, RW_READER);
16474 	ill = ILL_START_WALK_V4(&ctx);
16475 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16476 		ILM_WALKER_HOLD(ill);
16477 		for (ipif = ill->ill_ipif; ipif != NULL;
16478 		    ipif = ipif->ipif_next) {
16479 			if (ipif->ipif_zoneid != zoneid)
16480 				continue;	/* not this zone */
16481 			(void) ipif_get_name(ipif,
16482 			    ipm.ipGroupMemberIfIndex.o_bytes,
16483 			    OCTET_LENGTH);
16484 			ipm.ipGroupMemberIfIndex.o_length =
16485 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16486 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16487 				ASSERT(ilm->ilm_ipif != NULL);
16488 				ASSERT(ilm->ilm_ill == NULL);
16489 				if (ilm->ilm_ipif != ipif)
16490 					continue;
16491 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16492 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16493 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16494 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16495 				    (char *)&ipm, (int)sizeof (ipm))) {
16496 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16497 					    "failed to allocate %u bytes\n",
16498 						(uint_t)sizeof (ipm)));
16499 				}
16500 			}
16501 		}
16502 		ILM_WALKER_RELE(ill);
16503 	}
16504 	rw_exit(&ill_g_lock);
16505 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16506 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16507 	    (int)optp->level, (int)optp->name, (int)optp->len));
16508 	qreply(q, mpctl);
16509 	return (mp2ctl);
16510 }
16511 
16512 /* IPv6 multicast group membership. */
16513 static mblk_t *
16514 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16515 {
16516 	struct opthdr		*optp;
16517 	mblk_t			*mp2ctl;
16518 	ill_t			*ill;
16519 	ilm_t			*ilm;
16520 	ipv6_member_t		ipm6;
16521 	mblk_t			*mp_tail = NULL;
16522 	ill_walk_context_t	ctx;
16523 	zoneid_t		zoneid;
16524 
16525 	/*
16526 	 * make a copy of the original message
16527 	 */
16528 	mp2ctl = copymsg(mpctl);
16529 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16530 
16531 	/* ip6GroupMember table */
16532 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16533 	optp->level = MIB2_IP6;
16534 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16535 
16536 	rw_enter(&ill_g_lock, RW_READER);
16537 	ill = ILL_START_WALK_V6(&ctx);
16538 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16539 		ILM_WALKER_HOLD(ill);
16540 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16541 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16542 			ASSERT(ilm->ilm_ipif == NULL);
16543 			ASSERT(ilm->ilm_ill != NULL);
16544 			if (ilm->ilm_zoneid != zoneid)
16545 				continue;	/* not this zone */
16546 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16547 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16548 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16549 			if (!snmp_append_data2(mpctl->b_cont,
16550 			    &mp_tail,
16551 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16552 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16553 				    "failed to allocate %u bytes\n",
16554 				    (uint_t)sizeof (ipm6)));
16555 			}
16556 		}
16557 		ILM_WALKER_RELE(ill);
16558 	}
16559 	rw_exit(&ill_g_lock);
16560 
16561 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16562 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16563 	    (int)optp->level, (int)optp->name, (int)optp->len));
16564 	qreply(q, mpctl);
16565 	return (mp2ctl);
16566 }
16567 
16568 /* IP multicast filtered sources */
16569 static mblk_t *
16570 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16571 {
16572 	struct opthdr		*optp;
16573 	mblk_t			*mp2ctl;
16574 	ill_t			*ill;
16575 	ipif_t			*ipif;
16576 	ilm_t			*ilm;
16577 	ip_grpsrc_t		ips;
16578 	mblk_t			*mp_tail = NULL;
16579 	ill_walk_context_t	ctx;
16580 	zoneid_t		zoneid;
16581 	int			i;
16582 	slist_t			*sl;
16583 
16584 	/*
16585 	 * make a copy of the original message
16586 	 */
16587 	mp2ctl = copymsg(mpctl);
16588 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16589 
16590 	/* ipGroupSource table */
16591 	optp = (struct opthdr *)&mpctl->b_rptr[
16592 	    sizeof (struct T_optmgmt_ack)];
16593 	optp->level = MIB2_IP;
16594 	optp->name = EXPER_IP_GROUP_SOURCES;
16595 
16596 	rw_enter(&ill_g_lock, RW_READER);
16597 	ill = ILL_START_WALK_V4(&ctx);
16598 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16599 		ILM_WALKER_HOLD(ill);
16600 		for (ipif = ill->ill_ipif; ipif != NULL;
16601 		    ipif = ipif->ipif_next) {
16602 			if (ipif->ipif_zoneid != zoneid)
16603 				continue;	/* not this zone */
16604 			(void) ipif_get_name(ipif,
16605 			    ips.ipGroupSourceIfIndex.o_bytes,
16606 			    OCTET_LENGTH);
16607 			ips.ipGroupSourceIfIndex.o_length =
16608 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16609 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16610 				ASSERT(ilm->ilm_ipif != NULL);
16611 				ASSERT(ilm->ilm_ill == NULL);
16612 				sl = ilm->ilm_filter;
16613 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16614 					continue;
16615 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16616 				for (i = 0; i < sl->sl_numsrc; i++) {
16617 					if (!IN6_IS_ADDR_V4MAPPED(
16618 					    &sl->sl_addr[i]))
16619 						continue;
16620 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16621 					    ips.ipGroupSourceAddress);
16622 					if (snmp_append_data2(mpctl->b_cont,
16623 					    &mp_tail, (char *)&ips,
16624 					    (int)sizeof (ips)) == 0) {
16625 						ip1dbg(("ip_snmp_get_mib2_"
16626 						    "ip_group_src: failed to "
16627 						    "allocate %u bytes\n",
16628 						    (uint_t)sizeof (ips)));
16629 					}
16630 				}
16631 			}
16632 		}
16633 		ILM_WALKER_RELE(ill);
16634 	}
16635 	rw_exit(&ill_g_lock);
16636 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16637 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16638 	    (int)optp->level, (int)optp->name, (int)optp->len));
16639 	qreply(q, mpctl);
16640 	return (mp2ctl);
16641 }
16642 
16643 /* IPv6 multicast filtered sources. */
16644 static mblk_t *
16645 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16646 {
16647 	struct opthdr		*optp;
16648 	mblk_t			*mp2ctl;
16649 	ill_t			*ill;
16650 	ilm_t			*ilm;
16651 	ipv6_grpsrc_t		ips6;
16652 	mblk_t			*mp_tail = NULL;
16653 	ill_walk_context_t	ctx;
16654 	zoneid_t		zoneid;
16655 	int			i;
16656 	slist_t			*sl;
16657 
16658 	/*
16659 	 * make a copy of the original message
16660 	 */
16661 	mp2ctl = copymsg(mpctl);
16662 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16663 
16664 	/* ip6GroupMember table */
16665 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16666 	optp->level = MIB2_IP6;
16667 	optp->name = EXPER_IP6_GROUP_SOURCES;
16668 
16669 	rw_enter(&ill_g_lock, RW_READER);
16670 	ill = ILL_START_WALK_V6(&ctx);
16671 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16672 		ILM_WALKER_HOLD(ill);
16673 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16674 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16675 			ASSERT(ilm->ilm_ipif == NULL);
16676 			ASSERT(ilm->ilm_ill != NULL);
16677 			sl = ilm->ilm_filter;
16678 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16679 				continue;
16680 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16681 			for (i = 0; i < sl->sl_numsrc; i++) {
16682 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16683 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16684 				    (char *)&ips6, (int)sizeof (ips6))) {
16685 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16686 					    "group_src: failed to allocate "
16687 					    "%u bytes\n",
16688 					    (uint_t)sizeof (ips6)));
16689 				}
16690 			}
16691 		}
16692 		ILM_WALKER_RELE(ill);
16693 	}
16694 	rw_exit(&ill_g_lock);
16695 
16696 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16697 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16698 	    (int)optp->level, (int)optp->name, (int)optp->len));
16699 	qreply(q, mpctl);
16700 	return (mp2ctl);
16701 }
16702 
16703 /* Multicast routing virtual interface table. */
16704 static mblk_t *
16705 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16706 {
16707 	struct opthdr		*optp;
16708 	mblk_t			*mp2ctl;
16709 
16710 	/*
16711 	 * make a copy of the original message
16712 	 */
16713 	mp2ctl = copymsg(mpctl);
16714 
16715 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16716 	optp->level = EXPER_DVMRP;
16717 	optp->name = EXPER_DVMRP_VIF;
16718 	if (!ip_mroute_vif(mpctl->b_cont)) {
16719 		ip0dbg(("ip_mroute_vif: failed\n"));
16720 	}
16721 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16722 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16723 	    (int)optp->level, (int)optp->name, (int)optp->len));
16724 	qreply(q, mpctl);
16725 	return (mp2ctl);
16726 }
16727 
16728 /* Multicast routing table. */
16729 static mblk_t *
16730 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16731 {
16732 	struct opthdr		*optp;
16733 	mblk_t			*mp2ctl;
16734 
16735 	/*
16736 	 * make a copy of the original message
16737 	 */
16738 	mp2ctl = copymsg(mpctl);
16739 
16740 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16741 	optp->level = EXPER_DVMRP;
16742 	optp->name = EXPER_DVMRP_MRT;
16743 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16744 		ip0dbg(("ip_mroute_mrt: failed\n"));
16745 	}
16746 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16747 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16748 	    (int)optp->level, (int)optp->name, (int)optp->len));
16749 	qreply(q, mpctl);
16750 	return (mp2ctl);
16751 }
16752 
16753 /*
16754  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16755  * in one IRE walk.
16756  */
16757 static mblk_t *
16758 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16759 {
16760 	struct opthdr		*optp;
16761 	mblk_t			*mp2ctl;	/* Returned */
16762 	mblk_t			*mp3ctl;	/* nettomedia */
16763 	/*
16764 	 * We need two listptrs, for ipRouteEntryTable and
16765 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16766 	 */
16767 	listptr_t		re_ntme_v4[2];
16768 	zoneid_t		zoneid;
16769 
16770 	/*
16771 	 * make a copy of the original message
16772 	 */
16773 	mp2ctl = copymsg(mpctl);
16774 	mp3ctl = copymsg(mpctl);
16775 	if (mp3ctl == NULL) {
16776 		freemsg(mp2ctl);
16777 		freemsg(mpctl);
16778 		return (NULL);
16779 	}
16780 
16781 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
16782 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
16783 	/*
16784 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16785 	 * proper values when called.
16786 	 */
16787 	re_ntme_v4[0].lp_tail = NULL;
16788 	re_ntme_v4[1].lp_tail = NULL;
16789 
16790 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16791 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
16792 	if (zoneid == GLOBAL_ZONEID) {
16793 		/*
16794 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
16795 		 * the sys_net_config privilege, it can only run in the global
16796 		 * zone, so we don't display these IREs in the other zones.
16797 		 */
16798 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
16799 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
16800 		    NULL);
16801 	}
16802 
16803 	/* ipRouteEntryTable in mpctl */
16804 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16805 	optp->level = MIB2_IP;
16806 	optp->name = MIB2_IP_ROUTE;
16807 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
16808 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16809 	    (int)optp->level, (int)optp->name, (int)optp->len));
16810 	qreply(q, mpctl);
16811 
16812 	/* ipNetToMediaEntryTable in mp3ctl */
16813 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16814 	optp->level = MIB2_IP;
16815 	optp->name = MIB2_IP_MEDIA;
16816 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
16817 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16818 	    (int)optp->level, (int)optp->name, (int)optp->len));
16819 	qreply(q, mp3ctl);
16820 	return (mp2ctl);
16821 }
16822 
16823 /*
16824  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
16825  * in one IRE walk.
16826  */
16827 static mblk_t *
16828 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
16829 {
16830 	struct opthdr		*optp;
16831 	mblk_t			*mp2ctl;	/* Returned */
16832 	mblk_t			*mp3ctl;	/* nettomedia */
16833 	listptr_t		re_ntme_v6;
16834 	zoneid_t		zoneid;
16835 
16836 	/*
16837 	 * make a copy of the original message
16838 	 */
16839 	mp2ctl = copymsg(mpctl);
16840 	mp3ctl = copymsg(mpctl);
16841 	if (mp3ctl == NULL) {
16842 		freemsg(mp2ctl);
16843 		freemsg(mpctl);
16844 		return (NULL);
16845 	}
16846 
16847 	/*
16848 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16849 	 * proper values when called.  ipv6RouteEntryTable in is placed
16850 	 * in mpctl.
16851 	 */
16852 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
16853 	re_ntme_v6.lp_tail = NULL;
16854 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16855 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
16856 
16857 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16858 	optp->level = MIB2_IP6;
16859 	optp->name = MIB2_IP6_ROUTE;
16860 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16861 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16862 	    (int)optp->level, (int)optp->name, (int)optp->len));
16863 	qreply(q, mpctl);
16864 
16865 	/* ipv6NetToMediaEntryTable in mp3ctl */
16866 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
16867 	re_ntme_v6.lp_tail = NULL;
16868 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
16869 
16870 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16871 	optp->level = MIB2_IP6;
16872 	optp->name = MIB2_IP6_MEDIA;
16873 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16874 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16875 	    (int)optp->level, (int)optp->name, (int)optp->len));
16876 	qreply(q, mp3ctl);
16877 	return (mp2ctl);
16878 }
16879 
16880 /*
16881  * ICMPv6 mib: One per ill
16882  */
16883 static mblk_t *
16884 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
16885 {
16886 	struct opthdr		*optp;
16887 	mblk_t			*mp2ctl;
16888 	ill_t			*ill;
16889 	ill_walk_context_t	ctx;
16890 	mblk_t			*mp_tail = NULL;
16891 
16892 	/*
16893 	 * Make a copy of the original message
16894 	 */
16895 	mp2ctl = copymsg(mpctl);
16896 
16897 	/* fixed length IPv6 structure ... */
16898 
16899 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16900 	optp->level = MIB2_IP6;
16901 	optp->name = 0;
16902 	/* Include "unknown interface" ip6_mib */
16903 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
16904 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
16905 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
16906 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
16907 	    sizeof (mib2_ipv6IfStatsEntry_t));
16908 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
16909 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
16910 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
16911 	    sizeof (mib2_ipv6NetToMediaEntry_t));
16912 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
16913 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
16914 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
16915 	    (int)sizeof (ip6_mib))) {
16916 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
16917 		    (uint_t)sizeof (ip6_mib)));
16918 	}
16919 
16920 	rw_enter(&ill_g_lock, RW_READER);
16921 	ill = ILL_START_WALK_V6(&ctx);
16922 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16923 		ill->ill_ip6_mib->ipv6IfIndex =
16924 		    ill->ill_phyint->phyint_ifindex;
16925 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
16926 		    ipv6_forward ? 1 : 2);
16927 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
16928 		    ill->ill_max_hops);
16929 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
16930 		    sizeof (mib2_ipv6IfStatsEntry_t));
16931 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
16932 		    sizeof (mib2_ipv6AddrEntry_t));
16933 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
16934 		    sizeof (mib2_ipv6RouteEntry_t));
16935 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
16936 		    sizeof (mib2_ipv6NetToMediaEntry_t));
16937 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
16938 		    sizeof (ipv6_member_t));
16939 
16940 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16941 		    (char *)ill->ill_ip6_mib,
16942 		    (int)sizeof (*ill->ill_ip6_mib))) {
16943 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
16944 				"%u bytes\n",
16945 				(uint_t)sizeof (*ill->ill_ip6_mib)));
16946 		}
16947 	}
16948 	rw_exit(&ill_g_lock);
16949 
16950 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16951 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
16952 	    (int)optp->level, (int)optp->name, (int)optp->len));
16953 	qreply(q, mpctl);
16954 	return (mp2ctl);
16955 }
16956 
16957 /*
16958  * ICMPv6 mib: One per ill
16959  */
16960 static mblk_t *
16961 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
16962 {
16963 	struct opthdr		*optp;
16964 	mblk_t			*mp2ctl;
16965 	ill_t			*ill;
16966 	ill_walk_context_t	ctx;
16967 	mblk_t			*mp_tail = NULL;
16968 	/*
16969 	 * Make a copy of the original message
16970 	 */
16971 	mp2ctl = copymsg(mpctl);
16972 
16973 	/* fixed length ICMPv6 structure ... */
16974 
16975 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16976 	optp->level = MIB2_ICMP6;
16977 	optp->name = 0;
16978 	/* Include "unknown interface" icmp6_mib */
16979 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
16980 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
16981 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
16982 	    (int)sizeof (icmp6_mib))) {
16983 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
16984 		    (uint_t)sizeof (icmp6_mib)));
16985 	}
16986 
16987 	rw_enter(&ill_g_lock, RW_READER);
16988 	ill = ILL_START_WALK_V6(&ctx);
16989 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16990 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
16991 		    ill->ill_phyint->phyint_ifindex;
16992 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
16993 		    sizeof (mib2_ipv6IfIcmpEntry_t);
16994 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16995 		    (char *)ill->ill_icmp6_mib,
16996 		    (int)sizeof (*ill->ill_icmp6_mib))) {
16997 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
16998 			    "%u bytes\n",
16999 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17000 		}
17001 	}
17002 	rw_exit(&ill_g_lock);
17003 
17004 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17005 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17006 	    (int)optp->level, (int)optp->name, (int)optp->len));
17007 	qreply(q, mpctl);
17008 	return (mp2ctl);
17009 }
17010 
17011 /*
17012  * ire_walk routine to create both ipRouteEntryTable and
17013  * ipNetToMediaEntryTable in one IRE walk
17014  */
17015 static void
17016 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17017 {
17018 	ill_t				*ill;
17019 	ipif_t				*ipif;
17020 	mblk_t				*llmp;
17021 	dl_unitdata_req_t		*dlup;
17022 	mib2_ipRouteEntry_t		re;
17023 	mib2_ipNetToMediaEntry_t	ntme;
17024 	ipaddr_t			gw_addr;
17025 
17026 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17027 
17028 	/*
17029 	 * Return all IRE types for route table... let caller pick and choose
17030 	 */
17031 	re.ipRouteDest = ire->ire_addr;
17032 	ipif = ire->ire_ipif;
17033 	re.ipRouteIfIndex.o_length = 0;
17034 	if (ire->ire_type == IRE_CACHE) {
17035 		ill = (ill_t *)ire->ire_stq->q_ptr;
17036 		re.ipRouteIfIndex.o_length =
17037 		    ill->ill_name_length == 0 ? 0 :
17038 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17039 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17040 		    re.ipRouteIfIndex.o_length);
17041 	} else if (ipif != NULL) {
17042 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17043 		    OCTET_LENGTH);
17044 		re.ipRouteIfIndex.o_length =
17045 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17046 	}
17047 	re.ipRouteMetric1 = -1;
17048 	re.ipRouteMetric2 = -1;
17049 	re.ipRouteMetric3 = -1;
17050 	re.ipRouteMetric4 = -1;
17051 
17052 	gw_addr = ire->ire_gateway_addr;
17053 
17054 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17055 		re.ipRouteNextHop = ire->ire_src_addr;
17056 	else
17057 		re.ipRouteNextHop = gw_addr;
17058 	/* indirect(4), direct(3), or invalid(2) */
17059 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17060 		re.ipRouteType = 2;
17061 	else
17062 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17063 	re.ipRouteProto = -1;
17064 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17065 	re.ipRouteMask = ire->ire_mask;
17066 	re.ipRouteMetric5 = -1;
17067 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17068 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17069 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17070 	llmp = ire->ire_dlureq_mp;
17071 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17072 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17073 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17074 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17075 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17076 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17077 	re.ipRouteInfo.re_in_ill.o_length = 0;
17078 	if (ire->ire_in_ill != NULL) {
17079 		re.ipRouteInfo.re_in_ill.o_length =
17080 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17081 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17082 		bcopy(ire->ire_in_ill->ill_name,
17083 		    re.ipRouteInfo.re_in_ill.o_bytes,
17084 		    re.ipRouteInfo.re_in_ill.o_length);
17085 	}
17086 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17087 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17088 	    (char *)&re, (int)sizeof (re))) {
17089 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17090 		    (uint_t)sizeof (re)));
17091 	}
17092 
17093 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17094 		return;
17095 	/*
17096 	 * only IRE_CACHE entries that are for a directly connected subnet
17097 	 * get appended to net -> phys addr table
17098 	 * (others in arp)
17099 	 */
17100 	ntme.ipNetToMediaIfIndex.o_length = 0;
17101 	ill = ire_to_ill(ire);
17102 	ASSERT(ill != NULL);
17103 	ntme.ipNetToMediaIfIndex.o_length =
17104 	    ill->ill_name_length == 0 ? 0 :
17105 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17106 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17107 		    ntme.ipNetToMediaIfIndex.o_length);
17108 
17109 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17110 	if (llmp) {
17111 		uchar_t *addr;
17112 
17113 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17114 		/* Remove sap from  address */
17115 		if (ill->ill_sap_length < 0)
17116 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17117 		else
17118 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17119 			    ill->ill_sap_length;
17120 
17121 		ntme.ipNetToMediaPhysAddress.o_length =
17122 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17123 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17124 		    ntme.ipNetToMediaPhysAddress.o_length);
17125 	}
17126 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17127 	/* assume dynamic (may be changed in arp) */
17128 	ntme.ipNetToMediaType = 3;
17129 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17130 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17131 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17132 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17133 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17134 	    (char *)&ntme, (int)sizeof (ntme))) {
17135 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17136 		    (uint_t)sizeof (ntme)));
17137 	}
17138 }
17139 
17140 /*
17141  * ire_walk routine to create ipv6RouteEntryTable.
17142  */
17143 static void
17144 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17145 {
17146 	ill_t				*ill;
17147 	ipif_t				*ipif;
17148 	mib2_ipv6RouteEntry_t		re;
17149 	in6_addr_t			gw_addr_v6;
17150 
17151 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17152 
17153 	/*
17154 	 * Return all IRE types for route table... let caller pick and choose
17155 	 */
17156 	re.ipv6RouteDest = ire->ire_addr_v6;
17157 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17158 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17159 	re.ipv6RouteIfIndex.o_length = 0;
17160 	ipif = ire->ire_ipif;
17161 	if (ire->ire_type == IRE_CACHE) {
17162 		ill = (ill_t *)ire->ire_stq->q_ptr;
17163 		re.ipv6RouteIfIndex.o_length =
17164 		    ill->ill_name_length == 0 ? 0 :
17165 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17166 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17167 		    re.ipv6RouteIfIndex.o_length);
17168 	} else if (ipif != NULL) {
17169 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17170 		    OCTET_LENGTH);
17171 		re.ipv6RouteIfIndex.o_length =
17172 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17173 	}
17174 
17175 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17176 
17177 	mutex_enter(&ire->ire_lock);
17178 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17179 	mutex_exit(&ire->ire_lock);
17180 
17181 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17182 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17183 	else
17184 		re.ipv6RouteNextHop = gw_addr_v6;
17185 
17186 	/* remote(4), local(3), or discard(2) */
17187 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17188 		re.ipv6RouteType = 2;
17189 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17190 		re.ipv6RouteType = 3;
17191 	else
17192 		re.ipv6RouteType = 4;
17193 
17194 	re.ipv6RouteProtocol		= -1;
17195 	re.ipv6RoutePolicy		= 0;
17196 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17197 	re.ipv6RouteNextHopRDI		= 0;
17198 	re.ipv6RouteWeight		= 0;
17199 	re.ipv6RouteMetric		= 0;
17200 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17201 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17202 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17203 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17204 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17205 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17206 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17207 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17208 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17209 
17210 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17211 	    (char *)&re, (int)sizeof (re))) {
17212 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17213 		    (uint_t)sizeof (re)));
17214 	}
17215 }
17216 
17217 /*
17218  * ndp_walk routine to create ipv6NetToMediaEntryTable
17219  */
17220 static int
17221 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17222 {
17223 	ill_t				*ill;
17224 	mib2_ipv6NetToMediaEntry_t	ntme;
17225 	dl_unitdata_req_t		*dl;
17226 
17227 	ill = nce->nce_ill;
17228 	ASSERT(ill->ill_isv6);
17229 
17230 	/*
17231 	 * Neighbor cache entry attached to IRE with on-link
17232 	 * destination.
17233 	 */
17234 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17235 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17236 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17237 	    (nce->nce_res_mp != NULL)) {
17238 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17239 		ntme.ipv6NetToMediaPhysAddress.o_length =
17240 		    dl->dl_dest_addr_length;
17241 	} else {
17242 		ntme.ipv6NetToMediaPhysAddress.o_length =
17243 		    ill->ill_phys_addr_length;
17244 	}
17245 	if (nce->nce_res_mp != NULL) {
17246 		bcopy((char *)nce->nce_res_mp->b_rptr +
17247 		    NCE_LL_ADDR_OFFSET(ill),
17248 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17249 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17250 	} else {
17251 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17252 		    ill->ill_phys_addr_length);
17253 	}
17254 	/*
17255 	 * Note: Returns ND_* states. Should be:
17256 	 * reachable(1), stale(2), delay(3), probe(4),
17257 	 * invalid(5), unknown(6)
17258 	 */
17259 	ntme.ipv6NetToMediaState = nce->nce_state;
17260 	ntme.ipv6NetToMediaLastUpdated = 0;
17261 
17262 	/* other(1), dynamic(2), static(3), local(4) */
17263 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17264 		ntme.ipv6NetToMediaType = 4;
17265 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17266 		ntme.ipv6NetToMediaType = 1;
17267 	} else {
17268 		ntme.ipv6NetToMediaType = 2;
17269 	}
17270 
17271 	if (!snmp_append_data2(re_ntme->lp_head,
17272 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17273 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17274 		    (uint_t)sizeof (ntme)));
17275 	}
17276 	return (0);
17277 }
17278 
17279 /*
17280  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17281  */
17282 /* ARGSUSED */
17283 int
17284 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17285 {
17286 	switch (level) {
17287 	case MIB2_IP:
17288 	case MIB2_ICMP:
17289 		switch (name) {
17290 		default:
17291 			break;
17292 		}
17293 		return (1);
17294 	default:
17295 		return (1);
17296 	}
17297 }
17298 
17299 /*
17300  * Called before the options are updated to check if this packet will
17301  * be source routed from here.
17302  * This routine assumes that the options are well formed i.e. that they
17303  * have already been checked.
17304  */
17305 static boolean_t
17306 ip_source_routed(ipha_t *ipha)
17307 {
17308 	ipoptp_t	opts;
17309 	uchar_t		*opt;
17310 	uint8_t		optval;
17311 	uint8_t		optlen;
17312 	ipaddr_t	dst;
17313 	ire_t		*ire;
17314 
17315 	if (IS_SIMPLE_IPH(ipha)) {
17316 		ip2dbg(("not source routed\n"));
17317 		return (B_FALSE);
17318 	}
17319 	dst = ipha->ipha_dst;
17320 	for (optval = ipoptp_first(&opts, ipha);
17321 	    optval != IPOPT_EOL;
17322 	    optval = ipoptp_next(&opts)) {
17323 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17324 		opt = opts.ipoptp_cur;
17325 		optlen = opts.ipoptp_len;
17326 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17327 		    optval, optlen));
17328 		switch (optval) {
17329 			uint32_t off;
17330 		case IPOPT_SSRR:
17331 		case IPOPT_LSRR:
17332 			/*
17333 			 * If dst is one of our addresses and there are some
17334 			 * entries left in the source route return (true).
17335 			 */
17336 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17337 			    ALL_ZONES, MATCH_IRE_TYPE);
17338 			if (ire == NULL) {
17339 				ip2dbg(("ip_source_routed: not next"
17340 				    " source route 0x%x\n",
17341 				    ntohl(dst)));
17342 				return (B_FALSE);
17343 			}
17344 			ire_refrele(ire);
17345 			off = opt[IPOPT_OFFSET];
17346 			off--;
17347 			if (optlen < IP_ADDR_LEN ||
17348 			    off > optlen - IP_ADDR_LEN) {
17349 				/* End of source route */
17350 				ip1dbg(("ip_source_routed: end of SR\n"));
17351 				return (B_FALSE);
17352 			}
17353 			return (B_TRUE);
17354 		}
17355 	}
17356 	ip2dbg(("not source routed\n"));
17357 	return (B_FALSE);
17358 }
17359 
17360 /*
17361  * Check if the packet contains any source route.
17362  */
17363 static boolean_t
17364 ip_source_route_included(ipha_t *ipha)
17365 {
17366 	ipoptp_t	opts;
17367 	uint8_t		optval;
17368 
17369 	if (IS_SIMPLE_IPH(ipha))
17370 		return (B_FALSE);
17371 	for (optval = ipoptp_first(&opts, ipha);
17372 	    optval != IPOPT_EOL;
17373 	    optval = ipoptp_next(&opts)) {
17374 		switch (optval) {
17375 		case IPOPT_SSRR:
17376 		case IPOPT_LSRR:
17377 			return (B_TRUE);
17378 		}
17379 	}
17380 	return (B_FALSE);
17381 }
17382 
17383 /*
17384  * Called when the IRE expiration timer fires.
17385  */
17386 /* ARGSUSED */
17387 void
17388 ip_trash_timer_expire(void *args)
17389 {
17390 	int	flush_flag = 0;
17391 
17392 	/*
17393 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17394 	 * This lock makes sure that a new invocation of this function
17395 	 * that occurs due to an almost immediate timer firing will not
17396 	 * progress beyond this point until the current invocation is done
17397 	 */
17398 	mutex_enter(&ip_trash_timer_lock);
17399 	ip_ire_expire_id = 0;
17400 	mutex_exit(&ip_trash_timer_lock);
17401 
17402 	/* Periodic timer */
17403 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17404 		/*
17405 		 * Remove all IRE_CACHE entries since they might
17406 		 * contain arp information.
17407 		 */
17408 		flush_flag |= FLUSH_ARP_TIME;
17409 		ip_ire_arp_time_elapsed = 0;
17410 		IP_STAT(ip_ire_arp_timer_expired);
17411 	}
17412 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17413 		/* Remove all redirects */
17414 		flush_flag |= FLUSH_REDIRECT_TIME;
17415 		ip_ire_rd_time_elapsed = 0;
17416 		IP_STAT(ip_ire_redirect_timer_expired);
17417 	}
17418 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17419 		/* Increase path mtu */
17420 		flush_flag |= FLUSH_MTU_TIME;
17421 		ip_ire_pmtu_time_elapsed = 0;
17422 		IP_STAT(ip_ire_pmtu_timer_expired);
17423 	}
17424 	if (flush_flag != 0) {
17425 		/* Walk all IPv4 IRE's and update them */
17426 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17427 		    ALL_ZONES);
17428 	}
17429 	if (flush_flag & FLUSH_MTU_TIME) {
17430 		/*
17431 		 * Walk all IPv6 IRE's and update them
17432 		 * Note that ARP and redirect timers are not
17433 		 * needed since NUD handles stale entries.
17434 		 */
17435 		flush_flag = FLUSH_MTU_TIME;
17436 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17437 		    ALL_ZONES);
17438 	}
17439 
17440 	ip_ire_arp_time_elapsed += ip_timer_interval;
17441 	ip_ire_rd_time_elapsed += ip_timer_interval;
17442 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17443 
17444 	/*
17445 	 * Hold the lock to serialize timeout calls and prevent
17446 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17447 	 * for the timer to fire and a new invocation of this function
17448 	 * to start before the return value of timeout has been stored
17449 	 * in ip_ire_expire_id by the current invocation.
17450 	 */
17451 	mutex_enter(&ip_trash_timer_lock);
17452 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17453 	    MSEC_TO_TICK(ip_timer_interval));
17454 	mutex_exit(&ip_trash_timer_lock);
17455 }
17456 
17457 /*
17458  * Called by the memory allocator subsystem directly, when the system
17459  * is running low on memory.
17460  */
17461 /* ARGSUSED */
17462 void
17463 ip_trash_ire_reclaim(void *args)
17464 {
17465 	ire_cache_count_t icc;
17466 	ire_cache_reclaim_t icr;
17467 	ncc_cache_count_t ncc;
17468 	nce_cache_reclaim_t ncr;
17469 	uint_t delete_cnt;
17470 	/*
17471 	 * Memory reclaim call back.
17472 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17473 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17474 	 * entries, determine what fraction to free for
17475 	 * each category of IRE_CACHE entries giving absolute priority
17476 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17477 	 * entry will be freed unless all offlink entries are freed).
17478 	 */
17479 	icc.icc_total = 0;
17480 	icc.icc_unused = 0;
17481 	icc.icc_offlink = 0;
17482 	icc.icc_pmtu = 0;
17483 	icc.icc_onlink = 0;
17484 	ire_walk(ire_cache_count, (char *)&icc);
17485 
17486 	/*
17487 	 * Free NCEs for IPv6 like the onlink ires.
17488 	 */
17489 	ncc.ncc_total = 0;
17490 	ncc.ncc_host = 0;
17491 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17492 
17493 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17494 	    icc.icc_pmtu + icc.icc_onlink);
17495 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17496 	IP_STAT(ip_trash_ire_reclaim_calls);
17497 	if (delete_cnt == 0)
17498 		return;
17499 	IP_STAT(ip_trash_ire_reclaim_success);
17500 	/* Always delete all unused offlink entries */
17501 	icr.icr_unused = 1;
17502 	if (delete_cnt <= icc.icc_unused) {
17503 		/*
17504 		 * Only need to free unused entries.  In other words,
17505 		 * there are enough unused entries to free to meet our
17506 		 * target number of freed ire cache entries.
17507 		 */
17508 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17509 		ncr.ncr_host = 0;
17510 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17511 		/*
17512 		 * Only need to free unused entries, plus a fraction of offlink
17513 		 * entries.  It follows from the first if statement that
17514 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17515 		 */
17516 		delete_cnt -= icc.icc_unused;
17517 		/* Round up # deleted by truncating fraction */
17518 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17519 		icr.icr_pmtu = icr.icr_onlink = 0;
17520 		ncr.ncr_host = 0;
17521 	} else if (delete_cnt <=
17522 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17523 		/*
17524 		 * Free all unused and offlink entries, plus a fraction of
17525 		 * pmtu entries.  It follows from the previous if statement
17526 		 * that icc_pmtu is non-zero, and that
17527 		 * delete_cnt != icc_unused + icc_offlink.
17528 		 */
17529 		icr.icr_offlink = 1;
17530 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17531 		/* Round up # deleted by truncating fraction */
17532 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17533 		icr.icr_onlink = 0;
17534 		ncr.ncr_host = 0;
17535 	} else {
17536 		/*
17537 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17538 		 * of onlink entries.  If we're here, then we know that
17539 		 * icc_onlink is non-zero, and that
17540 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17541 		 */
17542 		icr.icr_offlink = icr.icr_pmtu = 1;
17543 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17544 		    icc.icc_pmtu;
17545 		/* Round up # deleted by truncating fraction */
17546 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17547 		/* Using the same delete fraction as for onlink IREs */
17548 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17549 	}
17550 #ifdef DEBUG
17551 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17552 	    "fractions %d/%d/%d/%d\n",
17553 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17554 	    icc.icc_unused, icc.icc_offlink,
17555 	    icc.icc_pmtu, icc.icc_onlink,
17556 	    icr.icr_unused, icr.icr_offlink,
17557 	    icr.icr_pmtu, icr.icr_onlink));
17558 #endif
17559 	ire_walk(ire_cache_reclaim, (char *)&icr);
17560 	if (ncr.ncr_host != 0)
17561 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17562 		    (uchar_t *)&ncr);
17563 #ifdef DEBUG
17564 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17565 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17566 	ire_walk(ire_cache_count, (char *)&icc);
17567 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17568 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17569 	    icc.icc_pmtu, icc.icc_onlink));
17570 #endif
17571 }
17572 
17573 /*
17574  * ip_unbind is called when a copy of an unbind request is received from the
17575  * upper level protocol.  We remove this conn from any fanout hash list it is
17576  * on, and zero out the bind information.  No reply is expected up above.
17577  */
17578 static void
17579 ip_unbind(queue_t *q, mblk_t *mp)
17580 {
17581 	conn_t	*connp = Q_TO_CONN(q);
17582 
17583 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17584 
17585 	ipcl_hash_remove(connp);
17586 
17587 	ASSERT(mp->b_cont == NULL);
17588 	/*
17589 	 * Convert mp into a T_OK_ACK
17590 	 */
17591 	mp = mi_tpi_ok_ack_alloc(mp);
17592 
17593 	/*
17594 	 * should not happen in practice... T_OK_ACK is smaller than the
17595 	 * original message.
17596 	 */
17597 	if (mp == NULL)
17598 		return;
17599 
17600 	/*
17601 	 * Don't bzero the ports if its TCP since TCP still needs the
17602 	 * lport to remove it from its own bind hash. TCP will do the
17603 	 * cleanup.
17604 	 */
17605 	if (!IPCL_IS_TCP(connp))
17606 		bzero(&connp->u_port, sizeof (connp->u_port));
17607 
17608 	qreply(q, mp);
17609 }
17610 
17611 /*
17612  * Write side put procedure.  Outbound data, IOCTLs, responses from
17613  * resolvers, etc, come down through here.
17614  */
17615 void
17616 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17617 {
17618 	conn_t		*connp = NULL;
17619 	queue_t		*q = (queue_t *)arg2;
17620 	ipha_t		*ipha;
17621 #define	rptr	((uchar_t *)ipha)
17622 	ire_t		*ire = NULL;
17623 	ire_t		*sctp_ire = NULL;
17624 	uint32_t	v_hlen_tos_len;
17625 	ipaddr_t	dst;
17626 	mblk_t		*first_mp = NULL;
17627 	boolean_t	mctl_present;
17628 	ipsec_out_t	*io;
17629 	int		match_flags;
17630 	ill_t		*attach_ill = NULL;
17631 					/* Bind to IPIF_NOFAILOVER ill etc. */
17632 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17633 	ipif_t		*dst_ipif;
17634 	boolean_t	multirt_need_resolve = B_FALSE;
17635 	mblk_t		*copy_mp = NULL;
17636 	int		err;
17637 	zoneid_t	zoneid;
17638 	boolean_t	need_decref = B_FALSE;
17639 	boolean_t	ignore_dontroute = B_FALSE;
17640 
17641 #ifdef	_BIG_ENDIAN
17642 #define	V_HLEN	(v_hlen_tos_len >> 24)
17643 #else
17644 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17645 #endif
17646 
17647 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17648 	    "ip_wput_start: q %p", q);
17649 
17650 	/*
17651 	 * ip_wput fast path
17652 	 */
17653 
17654 	/* is packet from ARP ? */
17655 	if (q->q_next != NULL)
17656 		goto qnext;
17657 
17658 	connp = (conn_t *)arg;
17659 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17660 
17661 	/* is queue flow controlled? */
17662 	if ((q->q_first != NULL || connp->conn_draining) &&
17663 	    (caller == IP_WPUT)) {
17664 		goto doputq;
17665 	}
17666 
17667 	/* Multidata transmit? */
17668 	if (DB_TYPE(mp) == M_MULTIDATA) {
17669 		/*
17670 		 * We should never get here, since all Multidata messages
17671 		 * originating from tcp should have been directed over to
17672 		 * tcp_multisend() in the first place.
17673 		 */
17674 		BUMP_MIB(&ip_mib, ipOutDiscards);
17675 		freemsg(mp);
17676 		return;
17677 	} else if (DB_TYPE(mp) != M_DATA)
17678 		goto notdata;
17679 	if (mp->b_flag & MSGHASREF) {
17680 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17681 		mp->b_flag &= ~MSGHASREF;
17682 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17683 		need_decref = B_TRUE;
17684 	}
17685 	ipha = (ipha_t *)mp->b_rptr;
17686 
17687 	/* is IP header non-aligned or mblk smaller than basic IP header */
17688 #ifndef SAFETY_BEFORE_SPEED
17689 	if (!OK_32PTR(rptr) ||
17690 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17691 		goto hdrtoosmall;
17692 #endif
17693 
17694 	/*
17695 	 * If there is a policy, try to attach an ipsec_out in
17696 	 * the front. At the end, first_mp either points to a
17697 	 * M_DATA message or IPSEC_OUT message linked to a
17698 	 * M_DATA message. We have to do it now as we might
17699 	 * lose the "conn" if we go through ip_newroute.
17700 	 */
17701 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17702 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17703 		    ipha->ipha_protocol)) == NULL)) {
17704 			if (need_decref)
17705 				CONN_DEC_REF(connp);
17706 			return;
17707 		} else {
17708 			ASSERT(mp->b_datap->db_type == M_CTL);
17709 			first_mp = mp;
17710 			mp = mp->b_cont;
17711 			mctl_present = B_TRUE;
17712 		}
17713 	} else {
17714 		first_mp = mp;
17715 		mctl_present = B_FALSE;
17716 	}
17717 
17718 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17719 
17720 	/* is wrong version or IP options present */
17721 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17722 		goto version_hdrlen_check;
17723 	dst = ipha->ipha_dst;
17724 
17725 	if (connp->conn_nofailover_ill != NULL) {
17726 		attach_ill = conn_get_held_ill(connp,
17727 		    &connp->conn_nofailover_ill, &err);
17728 		if (err == ILL_LOOKUP_FAILED) {
17729 			if (need_decref)
17730 				CONN_DEC_REF(connp);
17731 			freemsg(first_mp);
17732 			return;
17733 		}
17734 	}
17735 
17736 	/* is packet multicast? */
17737 	if (CLASSD(dst))
17738 		goto multicast;
17739 
17740 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL)) {
17741 		/*
17742 		 * If the destination is a broadcast or a loopback
17743 		 * address, both SO_DONTROUTE and IP_XMIT_IF go
17744 		 * through the standard path. But in the case of local
17745 		 * destination only SO_DONTROUTE goes through the
17746 		 * standard path not IP_XMIT_IF.
17747 		 */
17748 		ire = ire_cache_lookup(dst, zoneid);
17749 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17750 		    (ire->ire_type != IRE_LOOPBACK))) {
17751 
17752 			if ((connp->conn_dontroute) && (ire != NULL) &&
17753 				(ire->ire_type == IRE_LOCAL))
17754 				goto standard_path;
17755 
17756 			if (ire != NULL) {
17757 				ire_refrele(ire);
17758 				/* No more access to ire */
17759 				ire = NULL;
17760 			}
17761 			/*
17762 			 * bypass routing checks and go directly to
17763 			 * interface.
17764 			 */
17765 			if (connp->conn_dontroute)
17766 				goto dontroute;
17767 
17768 			/*
17769 			 * If IP_XMIT_IF socket option is set,
17770 			 * then we allow unicast and multicast
17771 			 * packets to go through the ill. It is
17772 			 * quite possible that the destination
17773 			 * is not in the ire cache table and we
17774 			 * do not want to go to ip_newroute()
17775 			 * instead we call ip_newroute_ipif.
17776 			 */
17777 			xmit_ill = conn_get_held_ill(connp,
17778 			    &connp->conn_xmit_if_ill, &err);
17779 			if (err == ILL_LOOKUP_FAILED) {
17780 				if (attach_ill != NULL)
17781 					ill_refrele(attach_ill);
17782 				if (need_decref)
17783 					CONN_DEC_REF(connp);
17784 				freemsg(first_mp);
17785 				return;
17786 			}
17787 			goto send_from_ill;
17788 		}
17789 standard_path:
17790 		/* Must be a broadcast, a loopback or a local ire */
17791 		if (ire != NULL) {
17792 			ire_refrele(ire);
17793 			/* No more access to ire */
17794 			ire = NULL;
17795 		}
17796 	}
17797 
17798 	if (attach_ill != NULL)
17799 		goto send_from_ill;
17800 
17801 	/*
17802 	 * We cache IRE_CACHEs to avoid lookups. We don't do
17803 	 * this for the tcp global queue and listen end point
17804 	 * as it does not really have a real destination to
17805 	 * talk to.  This is also true for SCTP.
17806 	 */
17807 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
17808 	    !connp->conn_fully_bound) {
17809 		ire = ire_cache_lookup(dst, zoneid);
17810 		if (ire == NULL)
17811 			goto noirefound;
17812 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17813 		    "ip_wput_end: q %p (%S)", q, "end");
17814 
17815 		/*
17816 		 * Check if the ire has the RTF_MULTIRT flag, inherited
17817 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17818 		 */
17819 		if (ire->ire_flags & RTF_MULTIRT) {
17820 
17821 			/*
17822 			 * Force the TTL of multirouted packets if required.
17823 			 * The TTL of such packets is bounded by the
17824 			 * ip_multirt_ttl ndd variable.
17825 			 */
17826 			if ((ip_multirt_ttl > 0) &&
17827 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
17828 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
17829 				    "(was %d), dst 0x%08x\n",
17830 				    ip_multirt_ttl, ipha->ipha_ttl,
17831 				    ntohl(ire->ire_addr)));
17832 				ipha->ipha_ttl = ip_multirt_ttl;
17833 			}
17834 			/*
17835 			 * We look at this point if there are pending
17836 			 * unresolved routes. ire_multirt_resolvable()
17837 			 * checks in O(n) that all IRE_OFFSUBNET ire
17838 			 * entries for the packet's destination and
17839 			 * flagged RTF_MULTIRT are currently resolved.
17840 			 * If some remain unresolved, we make a copy
17841 			 * of the current message. It will be used
17842 			 * to initiate additional route resolutions.
17843 			 */
17844 			multirt_need_resolve =
17845 			    ire_multirt_need_resolve(ire->ire_addr);
17846 			ip2dbg(("ip_wput[TCP]: ire %p, "
17847 			    "multirt_need_resolve %d, first_mp %p\n",
17848 			    (void *)ire, multirt_need_resolve,
17849 			    (void *)first_mp));
17850 			if (multirt_need_resolve) {
17851 				copy_mp = copymsg(first_mp);
17852 				if (copy_mp != NULL) {
17853 					MULTIRT_DEBUG_TAG(copy_mp);
17854 				}
17855 			}
17856 		}
17857 
17858 		ip_wput_ire(q, first_mp, ire, connp, caller);
17859 
17860 		/*
17861 		 * Try to resolve another multiroute if
17862 		 * ire_multirt_need_resolve() deemed it necessary.
17863 		 */
17864 		if (copy_mp != NULL) {
17865 			ip_newroute(q, copy_mp, dst, NULL, connp);
17866 		}
17867 		if (need_decref)
17868 			CONN_DEC_REF(connp);
17869 		return;
17870 	}
17871 
17872 	/*
17873 	 * Access to conn_ire_cache. (protected by conn_lock)
17874 	 *
17875 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
17876 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
17877 	 * send a packet or two with the IRE_CACHE that is going away.
17878 	 * Access to the ire requires an ire refhold on the ire prior to
17879 	 * its use since an interface unplumb thread may delete the cached
17880 	 * ire and release the refhold at any time.
17881 	 *
17882 	 * Caching an ire in the conn_ire_cache
17883 	 *
17884 	 * o Caching an ire pointer in the conn requires a strict check for
17885 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
17886 	 * ires  before cleaning up the conns. So the caching of an ire pointer
17887 	 * in the conn is done after making sure under the bucket lock that the
17888 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
17889 	 * caching an ire after the unplumb thread has cleaned up the conn.
17890 	 * If the conn does not send a packet subsequently the unplumb thread
17891 	 * will be hanging waiting for the ire count to drop to zero.
17892 	 *
17893 	 * o We also need to atomically test for a null conn_ire_cache and
17894 	 * set the conn_ire_cache under the the protection of the conn_lock
17895 	 * to avoid races among concurrent threads trying to simultaneously
17896 	 * cache an ire in the conn_ire_cache.
17897 	 */
17898 	mutex_enter(&connp->conn_lock);
17899 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
17900 
17901 	if (ire != NULL && ire->ire_addr == dst &&
17902 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17903 
17904 		IRE_REFHOLD(ire);
17905 		mutex_exit(&connp->conn_lock);
17906 
17907 	} else {
17908 		boolean_t cached = B_FALSE;
17909 		connp->conn_ire_cache = NULL;
17910 		mutex_exit(&connp->conn_lock);
17911 		/* Release the old ire */
17912 		if (ire != NULL && sctp_ire == NULL)
17913 			IRE_REFRELE_NOTR(ire);
17914 
17915 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
17916 		if (ire == NULL)
17917 			goto noirefound;
17918 		IRE_REFHOLD_NOTR(ire);
17919 
17920 		mutex_enter(&connp->conn_lock);
17921 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
17922 		    connp->conn_ire_cache == NULL) {
17923 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17924 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17925 				connp->conn_ire_cache = ire;
17926 				cached = B_TRUE;
17927 			}
17928 			rw_exit(&ire->ire_bucket->irb_lock);
17929 		}
17930 		mutex_exit(&connp->conn_lock);
17931 
17932 		/*
17933 		 * We can continue to use the ire but since it was
17934 		 * not cached, we should drop the extra reference.
17935 		 */
17936 		if (!cached)
17937 			IRE_REFRELE_NOTR(ire);
17938 	}
17939 
17940 
17941 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17942 	    "ip_wput_end: q %p (%S)", q, "end");
17943 
17944 	/*
17945 	 * Check if the ire has the RTF_MULTIRT flag, inherited
17946 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17947 	 */
17948 	if (ire->ire_flags & RTF_MULTIRT) {
17949 
17950 		/*
17951 		 * Force the TTL of multirouted packets if required.
17952 		 * The TTL of such packets is bounded by the
17953 		 * ip_multirt_ttl ndd variable.
17954 		 */
17955 		if ((ip_multirt_ttl > 0) &&
17956 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
17957 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
17958 			    "(was %d), dst 0x%08x\n",
17959 			    ip_multirt_ttl, ipha->ipha_ttl,
17960 			    ntohl(ire->ire_addr)));
17961 			ipha->ipha_ttl = ip_multirt_ttl;
17962 		}
17963 
17964 		/*
17965 		 * At this point, we check to see if there are any pending
17966 		 * unresolved routes. ire_multirt_resolvable()
17967 		 * checks in O(n) that all IRE_OFFSUBNET ire
17968 		 * entries for the packet's destination and
17969 		 * flagged RTF_MULTIRT are currently resolved.
17970 		 * If some remain unresolved, we make a copy
17971 		 * of the current message. It will be used
17972 		 * to initiate additional route resolutions.
17973 		 */
17974 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
17975 		ip2dbg(("ip_wput[not TCP]: ire %p, "
17976 		    "multirt_need_resolve %d, first_mp %p\n",
17977 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
17978 		if (multirt_need_resolve) {
17979 			copy_mp = copymsg(first_mp);
17980 			if (copy_mp != NULL) {
17981 				MULTIRT_DEBUG_TAG(copy_mp);
17982 			}
17983 		}
17984 	}
17985 
17986 	ip_wput_ire(q, first_mp, ire, connp, caller);
17987 
17988 	/*
17989 	 * Try to resolve another multiroute if
17990 	 * ire_multirt_resolvable() deemed it necessary
17991 	 */
17992 	if (copy_mp != NULL) {
17993 		ip_newroute(q, copy_mp, dst, NULL, connp);
17994 	}
17995 	if (need_decref)
17996 		CONN_DEC_REF(connp);
17997 	return;
17998 
17999 doputq:
18000 	ASSERT(!need_decref);
18001 	(void) putq(q, mp);
18002 	return;
18003 
18004 qnext:
18005 	/*
18006 	 * Upper Level Protocols pass down complete IP datagrams
18007 	 * as M_DATA messages.	Everything else is a sideshow.
18008 	 *
18009 	 * 1) We could be re-entering ip_wput because of ip_neworute
18010 	 *    in which case we could have a IPSEC_OUT message. We
18011 	 *    need to pass through ip_wput like other datagrams and
18012 	 *    hence cannot branch to ip_wput_nondata.
18013 	 *
18014 	 * 2) ARP, AH, ESP, and other clients who are on the module
18015 	 *    instance of IP stream, give us something to deal with.
18016 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18017 	 *
18018 	 * 3) ICMP replies also could come here.
18019 	 */
18020 	if (DB_TYPE(mp) != M_DATA) {
18021 	    notdata:
18022 		if (DB_TYPE(mp) == M_CTL) {
18023 			/*
18024 			 * M_CTL messages are used by ARP, AH and ESP to
18025 			 * communicate with IP. We deal with IPSEC_IN and
18026 			 * IPSEC_OUT here. ip_wput_nondata handles other
18027 			 * cases.
18028 			 */
18029 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18030 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18031 				first_mp = mp->b_cont;
18032 				first_mp->b_flag &= ~MSGHASREF;
18033 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18034 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18035 				CONN_DEC_REF(connp);
18036 				connp = NULL;
18037 			}
18038 			if (ii->ipsec_info_type == IPSEC_IN) {
18039 				/*
18040 				 * Either this message goes back to
18041 				 * IPSEC for further processing or to
18042 				 * ULP after policy checks.
18043 				 */
18044 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18045 				return;
18046 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18047 				io = (ipsec_out_t *)ii;
18048 				if (io->ipsec_out_proc_begin) {
18049 					/*
18050 					 * IPSEC processing has already started.
18051 					 * Complete it.
18052 					 * IPQoS notes: We don't care what is
18053 					 * in ipsec_out_ill_index since this
18054 					 * won't be processed for IPQoS policies
18055 					 * in ipsec_out_process.
18056 					 */
18057 					ipsec_out_process(q, mp, NULL,
18058 					    io->ipsec_out_ill_index);
18059 					return;
18060 				} else {
18061 					connp = (q->q_next != NULL) ?
18062 					    NULL : Q_TO_CONN(q);
18063 					first_mp = mp;
18064 					mp = mp->b_cont;
18065 					mctl_present = B_TRUE;
18066 				}
18067 				zoneid = io->ipsec_out_zoneid;
18068 				ASSERT(zoneid != ALL_ZONES);
18069 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18070 				/*
18071 				 * It's an IPsec control message requesting
18072 				 * an SADB update to be sent to the IPsec
18073 				 * hardware acceleration capable ills.
18074 				 */
18075 				ipsec_ctl_t *ipsec_ctl =
18076 				    (ipsec_ctl_t *)mp->b_rptr;
18077 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18078 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18079 				mblk_t *cmp = mp->b_cont;
18080 
18081 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18082 				ASSERT(cmp != NULL);
18083 
18084 				freeb(mp);
18085 				ill_ipsec_capab_send_all(satype, cmp, sa);
18086 				return;
18087 			} else {
18088 				/*
18089 				 * This must be ARP.
18090 				 */
18091 				ip_wput_nondata(NULL, q, mp, NULL);
18092 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18093 				    "ip_wput_end: q %p (%S)", q, "nondata");
18094 				return;
18095 			}
18096 		} else {
18097 			/*
18098 			 * This must be non-(ARP/AH/ESP) messages.
18099 			 */
18100 			ASSERT(!need_decref);
18101 			ip_wput_nondata(NULL, q, mp, NULL);
18102 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18103 			    "ip_wput_end: q %p (%S)", q, "nondata");
18104 			return;
18105 		}
18106 	} else {
18107 		first_mp = mp;
18108 		mctl_present = B_FALSE;
18109 	}
18110 
18111 	ASSERT(first_mp != NULL);
18112 	/*
18113 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18114 	 * to make sure that this packet goes out on the same interface it
18115 	 * came in. We handle that here.
18116 	 */
18117 	if (mctl_present) {
18118 		uint_t ifindex;
18119 
18120 		io = (ipsec_out_t *)first_mp->b_rptr;
18121 		if (io->ipsec_out_attach_if ||
18122 		    io->ipsec_out_xmit_if) {
18123 			ill_t	*ill;
18124 
18125 			ASSERT(io->ipsec_out_ill_index != 0);
18126 			ifindex = io->ipsec_out_ill_index;
18127 			ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18128 			    NULL, NULL, NULL, NULL);
18129 			/*
18130 			 * ipsec_out_xmit_if bit is used to tell
18131 			 * ip_wput to use the ill to send outgoing data
18132 			 * as we have no conn when data comes from ICMP
18133 			 * error msg routines. Currently this feature is
18134 			 * only used by ip_mrtun_forward routine.
18135 			 */
18136 			if (io->ipsec_out_xmit_if) {
18137 				xmit_ill = ill;
18138 				if (xmit_ill == NULL) {
18139 					ip1dbg(("ip_wput: bad ifindex for"
18140 					    "xmit_ill %d\n", ifindex));
18141 					freemsg(first_mp);
18142 					BUMP_MIB(&ip_mib, ipOutDiscards);
18143 					ASSERT(!need_decref);
18144 					return;
18145 				}
18146 				/* Free up the ipsec_out_t mblk */
18147 				ASSERT(first_mp->b_cont == mp);
18148 				first_mp->b_cont = NULL;
18149 				freeb(first_mp);
18150 				/* Just send the IP header+ICMP+data */
18151 				first_mp = mp;
18152 				ipha = (ipha_t *)mp->b_rptr;
18153 				dst = ipha->ipha_dst;
18154 				goto send_from_ill;
18155 
18156 			} else {
18157 				attach_ill = ill;
18158 			}
18159 
18160 			if (attach_ill == NULL) {
18161 				ASSERT(xmit_ill == NULL);
18162 				ip1dbg(("ip_wput : bad ifindex for "
18163 				    "(BIND TO IPIF_NOFAILOVER) %d\n", ifindex));
18164 				freemsg(first_mp);
18165 				BUMP_MIB(&ip_mib, ipOutDiscards);
18166 				ASSERT(!need_decref);
18167 				return;
18168 			}
18169 		}
18170 	}
18171 
18172 	ASSERT(xmit_ill == NULL);
18173 
18174 	/* We have a complete IP datagram heading outbound. */
18175 	ipha = (ipha_t *)mp->b_rptr;
18176 
18177 #ifndef SPEED_BEFORE_SAFETY
18178 	/*
18179 	 * Make sure we have a full-word aligned message and that at least
18180 	 * a simple IP header is accessible in the first message.  If not,
18181 	 * try a pullup.
18182 	 */
18183 	if (!OK_32PTR(rptr) ||
18184 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18185 	    hdrtoosmall:
18186 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18187 			BUMP_MIB(&ip_mib, ipOutDiscards);
18188 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18189 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18190 			if (first_mp == NULL)
18191 				first_mp = mp;
18192 			goto drop_pkt;
18193 		}
18194 		ipha = (ipha_t *)mp->b_rptr;
18195 		if (first_mp == NULL) {
18196 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18197 			/*
18198 			 * If we got here because of "goto hdrtoosmall"
18199 			 * We need to attach a IPSEC_OUT.
18200 			 */
18201 			if (connp->conn_out_enforce_policy) {
18202 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18203 				    NULL, ipha->ipha_protocol)) == NULL)) {
18204 					if (need_decref)
18205 						CONN_DEC_REF(connp);
18206 					return;
18207 				} else {
18208 					ASSERT(mp->b_datap->db_type == M_CTL);
18209 					first_mp = mp;
18210 					mp = mp->b_cont;
18211 					mctl_present = B_TRUE;
18212 				}
18213 			} else {
18214 				first_mp = mp;
18215 				mctl_present = B_FALSE;
18216 			}
18217 		}
18218 	}
18219 #endif
18220 
18221 	/* Most of the code below is written for speed, not readability */
18222 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18223 
18224 	/*
18225 	 * If ip_newroute() fails, we're going to need a full
18226 	 * header for the icmp wraparound.
18227 	 */
18228 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18229 		uint_t	v_hlen;
18230 	    version_hdrlen_check:
18231 		ASSERT(first_mp != NULL);
18232 		v_hlen = V_HLEN;
18233 		/*
18234 		 * siphon off IPv6 packets coming down from transport
18235 		 * layer modules here.
18236 		 * Note: high-order bit carries NUD reachability confirmation
18237 		 */
18238 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18239 			/*
18240 			 * XXX implement a IPv4 and IPv6 packet counter per
18241 			 * conn and switch when ratio exceeds e.g. 10:1
18242 			 */
18243 #ifdef notyet
18244 			if (q->q_next == NULL) /* Avoid ill queue */
18245 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18246 #endif
18247 			BUMP_MIB(&ip_mib, ipOutIPv6);
18248 			ASSERT(xmit_ill == NULL);
18249 			if (attach_ill != NULL)
18250 				ill_refrele(attach_ill);
18251 			if (need_decref)
18252 				mp->b_flag |= MSGHASREF;
18253 			(void) ip_output_v6(connp, first_mp, q, caller);
18254 			return;
18255 		}
18256 
18257 		if ((v_hlen >> 4) != IP_VERSION) {
18258 			BUMP_MIB(&ip_mib, ipOutDiscards);
18259 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18260 			    "ip_wput_end: q %p (%S)", q, "badvers");
18261 			goto drop_pkt;
18262 		}
18263 		/*
18264 		 * Is the header length at least 20 bytes?
18265 		 *
18266 		 * Are there enough bytes accessible in the header?  If
18267 		 * not, try a pullup.
18268 		 */
18269 		v_hlen &= 0xF;
18270 		v_hlen <<= 2;
18271 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18272 			BUMP_MIB(&ip_mib, ipOutDiscards);
18273 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18274 			    "ip_wput_end: q %p (%S)", q, "badlen");
18275 			goto drop_pkt;
18276 		}
18277 		if (v_hlen > (mp->b_wptr - rptr)) {
18278 			if (!pullupmsg(mp, v_hlen)) {
18279 				BUMP_MIB(&ip_mib, ipOutDiscards);
18280 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18281 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18282 				goto drop_pkt;
18283 			}
18284 			ipha = (ipha_t *)mp->b_rptr;
18285 		}
18286 		/*
18287 		 * Move first entry from any source route into ipha_dst and
18288 		 * verify the options
18289 		 */
18290 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18291 			ASSERT(xmit_ill == NULL);
18292 			if (attach_ill != NULL)
18293 				ill_refrele(attach_ill);
18294 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18295 			    "ip_wput_end: q %p (%S)", q, "badopts");
18296 			if (need_decref)
18297 				CONN_DEC_REF(connp);
18298 			return;
18299 		}
18300 	}
18301 	dst = ipha->ipha_dst;
18302 
18303 	/*
18304 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18305 	 * we have to run the packet through ip_newroute which will take
18306 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18307 	 * a resolver, or assigning a default gateway, etc.
18308 	 */
18309 	if (CLASSD(dst)) {
18310 		ipif_t	*ipif;
18311 		uint32_t setsrc = 0;
18312 
18313 	    multicast:
18314 		ASSERT(first_mp != NULL);
18315 		ASSERT(xmit_ill == NULL);
18316 		ip2dbg(("ip_wput: CLASSD\n"));
18317 		if (connp == NULL) {
18318 			/*
18319 			 * Use the first good ipif on the ill.
18320 			 * XXX Should this ever happen? (Appears
18321 			 * to show up with just ppp and no ethernet due
18322 			 * to in.rdisc.)
18323 			 * However, ire_send should be able to
18324 			 * call ip_wput_ire directly.
18325 			 *
18326 			 * XXX Also, this can happen for ICMP and other packets
18327 			 * with multicast source addresses.  Perhaps we should
18328 			 * fix things so that we drop the packet in question,
18329 			 * but for now, just run with it.
18330 			 */
18331 			ill_t *ill = (ill_t *)q->q_ptr;
18332 
18333 			/*
18334 			 * Don't honor attach_if for this case. If ill
18335 			 * is part of the group, ipif could belong to
18336 			 * any ill and we cannot maintain attach_ill
18337 			 * and ipif_ill same anymore and the assert
18338 			 * below would fail.
18339 			 */
18340 			if (mctl_present) {
18341 				io->ipsec_out_ill_index = 0;
18342 				io->ipsec_out_attach_if = B_FALSE;
18343 				ASSERT(attach_ill != NULL);
18344 				ill_refrele(attach_ill);
18345 				attach_ill = NULL;
18346 			}
18347 
18348 			ASSERT(attach_ill == NULL);
18349 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18350 			if (ipif == NULL) {
18351 				if (need_decref)
18352 					CONN_DEC_REF(connp);
18353 				freemsg(first_mp);
18354 				return;
18355 			}
18356 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18357 			    ntohl(dst), ill->ill_name));
18358 		} else {
18359 			/*
18360 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18361 			 * IP_XMIT_IF is honoured.
18362 			 * Block comment above this function explains the
18363 			 * locking mechanism used here
18364 			 */
18365 			xmit_ill = conn_get_held_ill(connp,
18366 			    &connp->conn_xmit_if_ill, &err);
18367 			if (err == ILL_LOOKUP_FAILED) {
18368 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18369 				goto drop_pkt;
18370 			}
18371 			if (xmit_ill == NULL) {
18372 				ipif = conn_get_held_ipif(connp,
18373 				    &connp->conn_multicast_ipif, &err);
18374 				if (err == IPIF_LOOKUP_FAILED) {
18375 					ip1dbg(("ip_wput: No ipif for "
18376 					    "multicast\n"));
18377 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18378 					goto drop_pkt;
18379 				}
18380 			}
18381 			if (xmit_ill != NULL) {
18382 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18383 				if (ipif == NULL) {
18384 					ip1dbg(("ip_wput: No ipif for "
18385 					    "IP_XMIT_IF\n"));
18386 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18387 					goto drop_pkt;
18388 				}
18389 			} else if (ipif == NULL || ipif->ipif_isv6) {
18390 				/*
18391 				 * We must do this ipif determination here
18392 				 * else we could pass through ip_newroute
18393 				 * and come back here without the conn context.
18394 				 *
18395 				 * Note: we do late binding i.e. we bind to
18396 				 * the interface when the first packet is sent.
18397 				 * For performance reasons we do not rebind on
18398 				 * each packet but keep the binding until the
18399 				 * next IP_MULTICAST_IF option.
18400 				 *
18401 				 * conn_multicast_{ipif,ill} are shared between
18402 				 * IPv4 and IPv6 and AF_INET6 sockets can
18403 				 * send both IPv4 and IPv6 packets. Hence
18404 				 * we have to check that "isv6" matches above.
18405 				 */
18406 				if (ipif != NULL)
18407 					ipif_refrele(ipif);
18408 				ipif = ipif_lookup_group(dst, zoneid);
18409 				if (ipif == NULL) {
18410 					ip1dbg(("ip_wput: No ipif for "
18411 					    "multicast\n"));
18412 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18413 					goto drop_pkt;
18414 				}
18415 				err = conn_set_held_ipif(connp,
18416 				    &connp->conn_multicast_ipif, ipif);
18417 				if (err == IPIF_LOOKUP_FAILED) {
18418 					ipif_refrele(ipif);
18419 					ip1dbg(("ip_wput: No ipif for "
18420 					    "multicast\n"));
18421 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18422 					goto drop_pkt;
18423 				}
18424 			}
18425 		}
18426 		ASSERT(!ipif->ipif_isv6);
18427 		/*
18428 		 * As we may lose the conn by the time we reach ip_wput_ire,
18429 		 * we copy conn_multicast_loop and conn_dontroute on to an
18430 		 * ipsec_out. In case if this datagram goes out secure,
18431 		 * we need the ill_index also. Copy that also into the
18432 		 * ipsec_out.
18433 		 */
18434 		if (mctl_present) {
18435 			io = (ipsec_out_t *)first_mp->b_rptr;
18436 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18437 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18438 		} else {
18439 			ASSERT(mp == first_mp);
18440 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18441 			    BPRI_HI)) == NULL) {
18442 				ipif_refrele(ipif);
18443 				first_mp = mp;
18444 				goto drop_pkt;
18445 			}
18446 			first_mp->b_datap->db_type = M_CTL;
18447 			first_mp->b_wptr += sizeof (ipsec_info_t);
18448 			/* ipsec_out_secure is B_FALSE now */
18449 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18450 			io = (ipsec_out_t *)first_mp->b_rptr;
18451 			io->ipsec_out_type = IPSEC_OUT;
18452 			io->ipsec_out_len = sizeof (ipsec_out_t);
18453 			io->ipsec_out_use_global_policy = B_TRUE;
18454 			first_mp->b_cont = mp;
18455 			mctl_present = B_TRUE;
18456 		}
18457 		if (attach_ill != NULL) {
18458 			ASSERT(attach_ill == ipif->ipif_ill);
18459 			match_flags = MATCH_IRE_ILL;
18460 
18461 			/*
18462 			 * Check if we need an ire that will not be
18463 			 * looked up by anybody else i.e. HIDDEN.
18464 			 */
18465 			if (ill_is_probeonly(attach_ill)) {
18466 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18467 			}
18468 			io->ipsec_out_ill_index =
18469 			    attach_ill->ill_phyint->phyint_ifindex;
18470 			io->ipsec_out_attach_if = B_TRUE;
18471 		} else {
18472 			match_flags = MATCH_IRE_ILL_GROUP;
18473 			io->ipsec_out_ill_index =
18474 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18475 		}
18476 		if (connp != NULL) {
18477 			io->ipsec_out_multicast_loop =
18478 			    connp->conn_multicast_loop;
18479 			io->ipsec_out_dontroute = connp->conn_dontroute;
18480 			io->ipsec_out_zoneid = connp->conn_zoneid;
18481 		}
18482 		/*
18483 		 * If the application uses IP_MULTICAST_IF with
18484 		 * different logical addresses of the same ILL, we
18485 		 * need to make sure that the soruce address of
18486 		 * the packet matches the logical IP address used
18487 		 * in the option. We do it by initializing ipha_src
18488 		 * here. This should keep IPSEC also happy as
18489 		 * when we return from IPSEC processing, we don't
18490 		 * have to worry about getting the right address on
18491 		 * the packet. Thus it is sufficient to look for
18492 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18493 		 * MATCH_IRE_IPIF.
18494 		 *
18495 		 * NOTE : We need to do it for non-secure case also as
18496 		 * this might go out secure if there is a global policy
18497 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18498 		 * address, the source should be initialized already and
18499 		 * hence we won't be initializing here.
18500 		 *
18501 		 * As we do not have the ire yet, it is possible that
18502 		 * we set the source address here and then later discover
18503 		 * that the ire implies the source address to be assigned
18504 		 * through the RTF_SETSRC flag.
18505 		 * In that case, the setsrc variable will remind us
18506 		 * that overwritting the source address by the one
18507 		 * of the RTF_SETSRC-flagged ire is allowed.
18508 		 */
18509 		if (ipha->ipha_src == INADDR_ANY &&
18510 		    (connp == NULL || !connp->conn_unspec_src)) {
18511 			ipha->ipha_src = ipif->ipif_src_addr;
18512 			setsrc = RTF_SETSRC;
18513 		}
18514 		/*
18515 		 * Find an IRE which matches the destination and the outgoing
18516 		 * queue (i.e. the outgoing interface.)
18517 		 * For loopback use a unicast IP address for
18518 		 * the ire lookup.
18519 		 */
18520 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18521 		    PHYI_LOOPBACK) {
18522 			dst = ipif->ipif_lcl_addr;
18523 		}
18524 		/*
18525 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18526 		 * We don't need to lookup ire in ctable as the packet
18527 		 * needs to be sent to the destination through the specified
18528 		 * ill irrespective of ires in the cache table.
18529 		 */
18530 		ire = NULL;
18531 		if (xmit_ill == NULL) {
18532 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18533 			    zoneid, match_flags);
18534 		}
18535 
18536 		/*
18537 		 * refrele attach_ill as its not needed anymore.
18538 		 */
18539 		if (attach_ill != NULL) {
18540 			ill_refrele(attach_ill);
18541 			attach_ill = NULL;
18542 		}
18543 
18544 		if (ire == NULL) {
18545 			/*
18546 			 * Multicast loopback and multicast forwarding is
18547 			 * done in ip_wput_ire.
18548 			 *
18549 			 * Mark this packet to make it be delivered to
18550 			 * ip_wput_ire after the new ire has been
18551 			 * created.
18552 			 *
18553 			 * The call to ip_newroute_ipif takes into account
18554 			 * the setsrc reminder. In any case, we take care
18555 			 * of the RTF_MULTIRT flag.
18556 			 */
18557 			mp->b_prev = mp->b_next = NULL;
18558 			if (xmit_ill == NULL ||
18559 			    xmit_ill->ill_ipif_up_count > 0) {
18560 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18561 				    setsrc | RTF_MULTIRT);
18562 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18563 				    "ip_wput_end: q %p (%S)", q, "noire");
18564 			} else {
18565 				freemsg(first_mp);
18566 			}
18567 			ipif_refrele(ipif);
18568 			if (xmit_ill != NULL)
18569 				ill_refrele(xmit_ill);
18570 			if (need_decref)
18571 				CONN_DEC_REF(connp);
18572 			return;
18573 		}
18574 
18575 		ipif_refrele(ipif);
18576 		ipif = NULL;
18577 		ASSERT(xmit_ill == NULL);
18578 
18579 		/*
18580 		 * Honor the RTF_SETSRC flag for multicast packets,
18581 		 * if allowed by the setsrc reminder.
18582 		 */
18583 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18584 			ipha->ipha_src = ire->ire_src_addr;
18585 		}
18586 
18587 		/*
18588 		 * Unconditionally force the TTL to 1 for
18589 		 * multirouted multicast packets:
18590 		 * multirouted multicast should not cross
18591 		 * multicast routers.
18592 		 */
18593 		if (ire->ire_flags & RTF_MULTIRT) {
18594 			if (ipha->ipha_ttl > 1) {
18595 				ip2dbg(("ip_wput: forcing multicast "
18596 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18597 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18598 				ipha->ipha_ttl = 1;
18599 			}
18600 		}
18601 	} else {
18602 		ire = ire_cache_lookup(dst, zoneid);
18603 		if ((ire != NULL) && (ire->ire_type &
18604 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18605 			ignore_dontroute = B_TRUE;
18606 		}
18607 		if (ire != NULL) {
18608 			ire_refrele(ire);
18609 			ire = NULL;
18610 		}
18611 		/*
18612 		 * Guard against coming in from arp in which case conn is NULL.
18613 		 * Also guard against non M_DATA with dontroute set but
18614 		 * destined to local, loopback or broadcast addresses.
18615 		 */
18616 		if (connp != NULL && connp->conn_dontroute &&
18617 		    !ignore_dontroute) {
18618 dontroute:
18619 			/*
18620 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18621 			 * routing protocols from seeing false direct
18622 			 * connectivity.
18623 			 */
18624 			ipha->ipha_ttl = 1;
18625 			/*
18626 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18627 			 * along with SO_DONTROUTE, higher precedence is
18628 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18629 			 */
18630 			if (connp->conn_xmit_if_ill == NULL) {
18631 				/* If suitable ipif not found, drop packet */
18632 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18633 				if (dst_ipif == NULL) {
18634 					ip1dbg(("ip_wput: no route for "
18635 					    "dst using SO_DONTROUTE\n"));
18636 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18637 					mp->b_prev = mp->b_next = NULL;
18638 					if (first_mp == NULL)
18639 						first_mp = mp;
18640 					goto drop_pkt;
18641 				} else {
18642 					/*
18643 					 * If suitable ipif has been found, set
18644 					 * xmit_ill to the corresponding
18645 					 * ipif_ill because we'll be following
18646 					 * the IP_XMIT_IF logic.
18647 					 */
18648 					ASSERT(xmit_ill == NULL);
18649 					xmit_ill = dst_ipif->ipif_ill;
18650 					mutex_enter(&xmit_ill->ill_lock);
18651 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18652 						mutex_exit(&xmit_ill->ill_lock);
18653 						xmit_ill = NULL;
18654 						ipif_refrele(dst_ipif);
18655 						ip1dbg(("ip_wput: no route for"
18656 						    " dst using"
18657 						    " SO_DONTROUTE\n"));
18658 						BUMP_MIB(&ip_mib,
18659 						    ipOutNoRoutes);
18660 						mp->b_prev = mp->b_next = NULL;
18661 						if (first_mp == NULL)
18662 							first_mp = mp;
18663 						goto drop_pkt;
18664 					}
18665 					ill_refhold_locked(xmit_ill);
18666 					mutex_exit(&xmit_ill->ill_lock);
18667 					ipif_refrele(dst_ipif);
18668 				}
18669 			}
18670 
18671 		}
18672 		/*
18673 		 * If we are bound to IPIF_NOFAILOVER address, look for
18674 		 * an IRE_CACHE matching the ill.
18675 		 */
18676 send_from_ill:
18677 		if (attach_ill != NULL) {
18678 			ipif_t	*attach_ipif;
18679 
18680 			match_flags = MATCH_IRE_ILL;
18681 
18682 			/*
18683 			 * Check if we need an ire that will not be
18684 			 * looked up by anybody else i.e. HIDDEN.
18685 			 */
18686 			if (ill_is_probeonly(attach_ill)) {
18687 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18688 			}
18689 
18690 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18691 			if (attach_ipif == NULL) {
18692 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18693 				goto drop_pkt;
18694 			}
18695 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18696 			    zoneid, match_flags);
18697 			ipif_refrele(attach_ipif);
18698 		} else if (xmit_ill != NULL || (connp != NULL &&
18699 			    connp->conn_xmit_if_ill != NULL)) {
18700 			/*
18701 			 * Mark this packet as originated locally
18702 			 */
18703 			mp->b_prev = mp->b_next = NULL;
18704 			/*
18705 			 * xmit_ill could be NULL if SO_DONTROUTE
18706 			 * is also set.
18707 			 */
18708 			if (xmit_ill == NULL) {
18709 				xmit_ill = conn_get_held_ill(connp,
18710 				    &connp->conn_xmit_if_ill, &err);
18711 				if (err == ILL_LOOKUP_FAILED) {
18712 					if (need_decref)
18713 						CONN_DEC_REF(connp);
18714 					freemsg(first_mp);
18715 					return;
18716 				}
18717 				if (xmit_ill == NULL) {
18718 					if (connp->conn_dontroute)
18719 						goto dontroute;
18720 					goto send_from_ill;
18721 				}
18722 			}
18723 			/*
18724 			 * could be SO_DONTROUTE case also.
18725 			 * check at least one interface is UP as
18726 			 * spcified by this ILL, and then call
18727 			 * ip_newroute_ipif()
18728 			 */
18729 			if (xmit_ill->ill_ipif_up_count > 0) {
18730 				ipif_t *ipif;
18731 
18732 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18733 				if (ipif != NULL) {
18734 					ip_newroute_ipif(q, first_mp, ipif,
18735 					    dst, connp, 0);
18736 					ipif_refrele(ipif);
18737 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18738 				}
18739 			} else {
18740 				freemsg(first_mp);
18741 			}
18742 			ill_refrele(xmit_ill);
18743 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18744 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18745 			if (need_decref)
18746 				CONN_DEC_REF(connp);
18747 			return;
18748 		} else {
18749 			ire = ire_cache_lookup(dst, zoneid);
18750 		}
18751 		if (!ire) {
18752 			/*
18753 			 * Make sure we don't load spread if this
18754 			 * is IPIF_NOFAILOVER case.
18755 			 */
18756 			if (attach_ill != NULL) {
18757 				if (mctl_present) {
18758 					io = (ipsec_out_t *)first_mp->b_rptr;
18759 					ASSERT(first_mp->b_datap->db_type ==
18760 					    M_CTL);
18761 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
18762 				} else {
18763 					ASSERT(mp == first_mp);
18764 					first_mp = allocb(
18765 					    sizeof (ipsec_info_t), BPRI_HI);
18766 					if (first_mp == NULL) {
18767 						first_mp = mp;
18768 						goto drop_pkt;
18769 					}
18770 					first_mp->b_datap->db_type = M_CTL;
18771 					first_mp->b_wptr +=
18772 					    sizeof (ipsec_info_t);
18773 					/* ipsec_out_secure is B_FALSE now */
18774 					bzero(first_mp->b_rptr,
18775 					    sizeof (ipsec_info_t));
18776 					io = (ipsec_out_t *)first_mp->b_rptr;
18777 					io->ipsec_out_type = IPSEC_OUT;
18778 					io->ipsec_out_len =
18779 					    sizeof (ipsec_out_t);
18780 					io->ipsec_out_use_global_policy =
18781 					    B_TRUE;
18782 					first_mp->b_cont = mp;
18783 					mctl_present = B_TRUE;
18784 				}
18785 				io->ipsec_out_ill_index = attach_ill->
18786 				    ill_phyint->phyint_ifindex;
18787 				io->ipsec_out_attach_if = B_TRUE;
18788 			}
18789 noirefound:
18790 			/*
18791 			 * Mark this packet as having originated on
18792 			 * this machine.  This will be noted in
18793 			 * ire_add_then_send, which needs to know
18794 			 * whether to run it back through ip_wput or
18795 			 * ip_rput following successful resolution.
18796 			 */
18797 			mp->b_prev = NULL;
18798 			mp->b_next = NULL;
18799 			ip_newroute(q, first_mp, dst, NULL, connp);
18800 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18801 			    "ip_wput_end: q %p (%S)", q, "newroute");
18802 			if (attach_ill != NULL)
18803 				ill_refrele(attach_ill);
18804 			if (xmit_ill != NULL)
18805 				ill_refrele(xmit_ill);
18806 			if (need_decref)
18807 				CONN_DEC_REF(connp);
18808 			return;
18809 		}
18810 	}
18811 
18812 	/* We now know where we are going with it. */
18813 
18814 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18815 	    "ip_wput_end: q %p (%S)", q, "end");
18816 
18817 	/*
18818 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18819 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
18820 	 */
18821 	if (ire->ire_flags & RTF_MULTIRT) {
18822 		/*
18823 		 * Force the TTL of multirouted packets if required.
18824 		 * The TTL of such packets is bounded by the
18825 		 * ip_multirt_ttl ndd variable.
18826 		 */
18827 		if ((ip_multirt_ttl > 0) &&
18828 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18829 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18830 			    "(was %d), dst 0x%08x\n",
18831 			    ip_multirt_ttl, ipha->ipha_ttl,
18832 			    ntohl(ire->ire_addr)));
18833 			ipha->ipha_ttl = ip_multirt_ttl;
18834 		}
18835 		/*
18836 		 * At this point, we check to see if there are any pending
18837 		 * unresolved routes. ire_multirt_resolvable()
18838 		 * checks in O(n) that all IRE_OFFSUBNET ire
18839 		 * entries for the packet's destination and
18840 		 * flagged RTF_MULTIRT are currently resolved.
18841 		 * If some remain unresolved, we make a copy
18842 		 * of the current message. It will be used
18843 		 * to initiate additional route resolutions.
18844 		 */
18845 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18846 		ip2dbg(("ip_wput[noirefound]: ire %p, "
18847 		    "multirt_need_resolve %d, first_mp %p\n",
18848 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18849 		if (multirt_need_resolve) {
18850 			copy_mp = copymsg(first_mp);
18851 			if (copy_mp != NULL) {
18852 				MULTIRT_DEBUG_TAG(copy_mp);
18853 			}
18854 		}
18855 	}
18856 
18857 	ip_wput_ire(q, first_mp, ire, connp, caller);
18858 	/*
18859 	 * Try to resolve another multiroute if
18860 	 * ire_multirt_resolvable() deemed it necessary.
18861 	 * At this point, we need to distinguish
18862 	 * multicasts from other packets. For multicasts,
18863 	 * we call ip_newroute_ipif() and request that both
18864 	 * multirouting and setsrc flags are checked.
18865 	 */
18866 	if (copy_mp != NULL) {
18867 		if (CLASSD(dst)) {
18868 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
18869 			if (ipif) {
18870 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
18871 				    RTF_SETSRC | RTF_MULTIRT);
18872 				ipif_refrele(ipif);
18873 			} else {
18874 				MULTIRT_DEBUG_UNTAG(copy_mp);
18875 				freemsg(copy_mp);
18876 				copy_mp = NULL;
18877 			}
18878 		} else {
18879 			ip_newroute(q, copy_mp, dst, NULL, connp);
18880 		}
18881 	}
18882 	if (attach_ill != NULL)
18883 		ill_refrele(attach_ill);
18884 	if (xmit_ill != NULL)
18885 		ill_refrele(xmit_ill);
18886 	if (need_decref)
18887 		CONN_DEC_REF(connp);
18888 	return;
18889 
18890 drop_pkt:
18891 	ip1dbg(("ip_wput: dropped packet\n"));
18892 	if (ire != NULL)
18893 		ire_refrele(ire);
18894 	if (need_decref)
18895 		CONN_DEC_REF(connp);
18896 	freemsg(first_mp);
18897 	if (attach_ill != NULL)
18898 		ill_refrele(attach_ill);
18899 	if (xmit_ill != NULL)
18900 		ill_refrele(xmit_ill);
18901 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18902 	    "ip_wput_end: q %p (%S)", q, "droppkt");
18903 }
18904 
18905 void
18906 ip_wput(queue_t *q, mblk_t *mp)
18907 {
18908 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
18909 }
18910 
18911 /*
18912  *
18913  * The following rules must be observed when accessing any ipif or ill
18914  * that has been cached in the conn. Typically conn_nofailover_ill,
18915  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
18916  *
18917  * Access: The ipif or ill pointed to from the conn can be accessed under
18918  * the protection of the conn_lock or after it has been refheld under the
18919  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
18920  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
18921  * The reason for this is that a concurrent unplumb could actually be
18922  * cleaning up these cached pointers by walking the conns and might have
18923  * finished cleaning up the conn in question. The macros check that an
18924  * unplumb has not yet started on the ipif or ill.
18925  *
18926  * Caching: An ipif or ill pointer may be cached in the conn only after
18927  * making sure that an unplumb has not started. So the caching is done
18928  * while holding both the conn_lock and the ill_lock and after using the
18929  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
18930  * flag before starting the cleanup of conns.
18931  *
18932  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
18933  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
18934  * or a reference to the ipif or a reference to an ire that references the
18935  * ipif. An ipif does not change its ill except for failover/failback. Since
18936  * failover/failback happens only after bringing down the ipif and making sure
18937  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
18938  * the above holds.
18939  */
18940 static ipif_t *
18941 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
18942 {
18943 	ipif_t	*ipif;
18944 	ill_t	*ill;
18945 
18946 	*err = 0;
18947 	rw_enter(&ill_g_lock, RW_READER);
18948 	mutex_enter(&connp->conn_lock);
18949 	ipif = *ipifp;
18950 	if (ipif != NULL) {
18951 		ill = ipif->ipif_ill;
18952 		mutex_enter(&ill->ill_lock);
18953 		if (IPIF_CAN_LOOKUP(ipif)) {
18954 			ipif_refhold_locked(ipif);
18955 			mutex_exit(&ill->ill_lock);
18956 			mutex_exit(&connp->conn_lock);
18957 			rw_exit(&ill_g_lock);
18958 			return (ipif);
18959 		} else {
18960 			*err = IPIF_LOOKUP_FAILED;
18961 		}
18962 		mutex_exit(&ill->ill_lock);
18963 	}
18964 	mutex_exit(&connp->conn_lock);
18965 	rw_exit(&ill_g_lock);
18966 	return (NULL);
18967 }
18968 
18969 ill_t *
18970 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
18971 {
18972 	ill_t	*ill;
18973 
18974 	*err = 0;
18975 	mutex_enter(&connp->conn_lock);
18976 	ill = *illp;
18977 	if (ill != NULL) {
18978 		mutex_enter(&ill->ill_lock);
18979 		if (ILL_CAN_LOOKUP(ill)) {
18980 			ill_refhold_locked(ill);
18981 			mutex_exit(&ill->ill_lock);
18982 			mutex_exit(&connp->conn_lock);
18983 			return (ill);
18984 		} else {
18985 			*err = ILL_LOOKUP_FAILED;
18986 		}
18987 		mutex_exit(&ill->ill_lock);
18988 	}
18989 	mutex_exit(&connp->conn_lock);
18990 	return (NULL);
18991 }
18992 
18993 static int
18994 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
18995 {
18996 	ill_t	*ill;
18997 
18998 	ill = ipif->ipif_ill;
18999 	mutex_enter(&connp->conn_lock);
19000 	mutex_enter(&ill->ill_lock);
19001 	if (IPIF_CAN_LOOKUP(ipif)) {
19002 		*ipifp = ipif;
19003 		mutex_exit(&ill->ill_lock);
19004 		mutex_exit(&connp->conn_lock);
19005 		return (0);
19006 	}
19007 	mutex_exit(&ill->ill_lock);
19008 	mutex_exit(&connp->conn_lock);
19009 	return (IPIF_LOOKUP_FAILED);
19010 }
19011 
19012 /*
19013  * This is called if the outbound datagram needs fragmentation.
19014  *
19015  * NOTE : This function does not ire_refrele the ire argument passed in.
19016  */
19017 static void
19018 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19019 {
19020 	ipha_t		*ipha;
19021 	mblk_t		*mp;
19022 	uint32_t	v_hlen_tos_len;
19023 	uint32_t	max_frag;
19024 	uint32_t	frag_flag;
19025 	boolean_t	dont_use;
19026 
19027 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19028 		mp = ipsec_mp->b_cont;
19029 	} else {
19030 		mp = ipsec_mp;
19031 	}
19032 
19033 	ipha = (ipha_t *)mp->b_rptr;
19034 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19035 
19036 #ifdef	_BIG_ENDIAN
19037 #define	V_HLEN	(v_hlen_tos_len >> 24)
19038 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19039 #else
19040 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19041 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19042 #endif
19043 
19044 #ifndef SPEED_BEFORE_SAFETY
19045 	/*
19046 	 * Check that ipha_length is consistent with
19047 	 * the mblk length
19048 	 */
19049 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19050 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19051 		    LENGTH, msgdsize(mp)));
19052 		freemsg(ipsec_mp);
19053 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19054 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19055 		    "packet length mismatch");
19056 		return;
19057 	}
19058 #endif
19059 	/*
19060 	 * Don't use frag_flag if pre-built packet or source
19061 	 * routed or if multicast (since multicast packets do not solicit
19062 	 * ICMP "packet too big" messages). Get the values of
19063 	 * max_frag and frag_flag atomically by acquiring the
19064 	 * ire_lock.
19065 	 */
19066 	mutex_enter(&ire->ire_lock);
19067 	max_frag = ire->ire_max_frag;
19068 	frag_flag = ire->ire_frag_flag;
19069 	mutex_exit(&ire->ire_lock);
19070 
19071 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19072 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19073 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19074 
19075 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19076 	    (dont_use ? 0 : frag_flag));
19077 }
19078 
19079 /*
19080  * Used for deciding the MSS size for the upper layer. Thus
19081  * we need to check the outbound policy values in the conn.
19082  */
19083 int
19084 conn_ipsec_length(conn_t *connp)
19085 {
19086 	ipsec_latch_t *ipl;
19087 
19088 	ipl = connp->conn_latch;
19089 	if (ipl == NULL)
19090 		return (0);
19091 
19092 	if (ipl->ipl_out_policy == NULL)
19093 		return (0);
19094 
19095 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19096 }
19097 
19098 /*
19099  * Returns an estimate of the IPSEC headers size. This is used if
19100  * we don't want to call into IPSEC to get the exact size.
19101  */
19102 int
19103 ipsec_out_extra_length(mblk_t *ipsec_mp)
19104 {
19105 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19106 	ipsec_action_t *a;
19107 
19108 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19109 	if (!io->ipsec_out_secure)
19110 		return (0);
19111 
19112 	a = io->ipsec_out_act;
19113 
19114 	if (a == NULL) {
19115 		ASSERT(io->ipsec_out_policy != NULL);
19116 		a = io->ipsec_out_policy->ipsp_act;
19117 	}
19118 	ASSERT(a != NULL);
19119 
19120 	return (a->ipa_ovhd);
19121 }
19122 
19123 /*
19124  * Returns an estimate of the IPSEC headers size. This is used if
19125  * we don't want to call into IPSEC to get the exact size.
19126  */
19127 int
19128 ipsec_in_extra_length(mblk_t *ipsec_mp)
19129 {
19130 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19131 	ipsec_action_t *a;
19132 
19133 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19134 
19135 	a = ii->ipsec_in_action;
19136 	return (a == NULL ? 0 : a->ipa_ovhd);
19137 }
19138 
19139 /*
19140  * If there are any source route options, return the true final
19141  * destination. Otherwise, return the destination.
19142  */
19143 ipaddr_t
19144 ip_get_dst(ipha_t *ipha)
19145 {
19146 	ipoptp_t	opts;
19147 	uchar_t		*opt;
19148 	uint8_t		optval;
19149 	uint8_t		optlen;
19150 	ipaddr_t	dst;
19151 	uint32_t off;
19152 
19153 	dst = ipha->ipha_dst;
19154 
19155 	if (IS_SIMPLE_IPH(ipha))
19156 		return (dst);
19157 
19158 	for (optval = ipoptp_first(&opts, ipha);
19159 	    optval != IPOPT_EOL;
19160 	    optval = ipoptp_next(&opts)) {
19161 		opt = opts.ipoptp_cur;
19162 		optlen = opts.ipoptp_len;
19163 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19164 		switch (optval) {
19165 		case IPOPT_SSRR:
19166 		case IPOPT_LSRR:
19167 			off = opt[IPOPT_OFFSET];
19168 			/*
19169 			 * If one of the conditions is true, it means
19170 			 * end of options and dst already has the right
19171 			 * value.
19172 			 */
19173 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19174 				off = optlen - IP_ADDR_LEN;
19175 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19176 			}
19177 			return (dst);
19178 		default:
19179 			break;
19180 		}
19181 	}
19182 
19183 	return (dst);
19184 }
19185 
19186 mblk_t *
19187 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19188     conn_t *connp, boolean_t unspec_src)
19189 {
19190 	ipsec_out_t	*io;
19191 	mblk_t		*first_mp;
19192 	boolean_t policy_present;
19193 
19194 	first_mp = mp;
19195 	if (mp->b_datap->db_type == M_CTL) {
19196 		io = (ipsec_out_t *)first_mp->b_rptr;
19197 		/*
19198 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19199 		 *
19200 		 * 1) There is per-socket policy (including cached global
19201 		 *    policy).
19202 		 * 2) There is no per-socket policy, but it is
19203 		 *    a multicast packet that needs to go out
19204 		 *    on a specific interface. This is the case
19205 		 *    where (ip_wput and ip_wput_multicast) attaches
19206 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19207 		 *
19208 		 * In case (2) we check with global policy to
19209 		 * see if there is a match and set the ill_index
19210 		 * appropriately so that we can lookup the ire
19211 		 * properly in ip_wput_ipsec_out.
19212 		 */
19213 
19214 		/*
19215 		 * ipsec_out_use_global_policy is set to B_FALSE
19216 		 * in ipsec_in_to_out(). Refer to that function for
19217 		 * details.
19218 		 */
19219 		if ((io->ipsec_out_latch == NULL) &&
19220 		    (io->ipsec_out_use_global_policy)) {
19221 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19222 			    ire, connp, unspec_src));
19223 		}
19224 		if (!io->ipsec_out_secure) {
19225 			/*
19226 			 * If this is not a secure packet, drop
19227 			 * the IPSEC_OUT mp and treat it as a clear
19228 			 * packet. This happens when we are sending
19229 			 * a ICMP reply back to a clear packet. See
19230 			 * ipsec_in_to_out() for details.
19231 			 */
19232 			mp = first_mp->b_cont;
19233 			freeb(first_mp);
19234 		}
19235 		return (mp);
19236 	}
19237 	/*
19238 	 * See whether we need to attach a global policy here. We
19239 	 * don't depend on the conn (as it could be null) for deciding
19240 	 * what policy this datagram should go through because it
19241 	 * should have happened in ip_wput if there was some
19242 	 * policy. This normally happens for connections which are not
19243 	 * fully bound preventing us from caching policies in
19244 	 * ip_bind. Packets coming from the TCP listener/global queue
19245 	 * - which are non-hard_bound - could also be affected by
19246 	 * applying policy here.
19247 	 *
19248 	 * If this packet is coming from tcp global queue or listener,
19249 	 * we will be applying policy here.  This may not be *right*
19250 	 * if these packets are coming from the detached connection as
19251 	 * it could have gone in clear before. This happens only if a
19252 	 * TCP connection started when there is no policy and somebody
19253 	 * added policy before it became detached. Thus packets of the
19254 	 * detached connection could go out secure and the other end
19255 	 * would drop it because it will be expecting in clear. The
19256 	 * converse is not true i.e if somebody starts a TCP
19257 	 * connection and deletes the policy, all the packets will
19258 	 * still go out with the policy that existed before deleting
19259 	 * because ip_unbind sends up policy information which is used
19260 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19261 	 * TCP to attach a dummy IPSEC_OUT and set
19262 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19263 	 * affect performance for normal cases, we are not doing it.
19264 	 * Thus, set policy before starting any TCP connections.
19265 	 *
19266 	 * NOTE - We might apply policy even for a hard bound connection
19267 	 * - for which we cached policy in ip_bind - if somebody added
19268 	 * global policy after we inherited the policy in ip_bind.
19269 	 * This means that the packets that were going out in clear
19270 	 * previously would start going secure and hence get dropped
19271 	 * on the other side. To fix this, TCP attaches a dummy
19272 	 * ipsec_out and make sure that we don't apply global policy.
19273 	 */
19274 	if (ipha != NULL)
19275 		policy_present = ipsec_outbound_v4_policy_present;
19276 	else
19277 		policy_present = ipsec_outbound_v6_policy_present;
19278 	if (!policy_present)
19279 		return (mp);
19280 
19281 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19282 }
19283 
19284 ire_t *
19285 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19286 {
19287 	ipaddr_t addr;
19288 	ire_t *save_ire;
19289 	irb_t *irb;
19290 	ill_group_t *illgrp;
19291 	int	err;
19292 
19293 	save_ire = ire;
19294 	addr = ire->ire_addr;
19295 
19296 	ASSERT(ire->ire_type == IRE_BROADCAST);
19297 
19298 	illgrp = connp->conn_outgoing_ill->ill_group;
19299 	if (illgrp == NULL) {
19300 		*conn_outgoing_ill = conn_get_held_ill(connp,
19301 		    &connp->conn_outgoing_ill, &err);
19302 		if (err == ILL_LOOKUP_FAILED) {
19303 			ire_refrele(save_ire);
19304 			return (NULL);
19305 		}
19306 		return (save_ire);
19307 	}
19308 	/*
19309 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19310 	 * If it is part of the group, we need to send on the ire
19311 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19312 	 * to this group. This is okay as IP_BOUND_IF really means
19313 	 * any ill in the group. We depend on the fact that the
19314 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19315 	 * if such an ire exists. This is possible only if you have
19316 	 * at least one ill in the group that has not failed.
19317 	 *
19318 	 * First get to the ire that matches the address and group.
19319 	 *
19320 	 * We don't look for an ire with a matching zoneid because a given zone
19321 	 * won't always have broadcast ires on all ills in the group.
19322 	 */
19323 	irb = ire->ire_bucket;
19324 	rw_enter(&irb->irb_lock, RW_READER);
19325 	if (ire->ire_marks & IRE_MARK_NORECV) {
19326 		/*
19327 		 * If the current zone only has an ire broadcast for this
19328 		 * address marked NORECV, the ire we want is ahead in the
19329 		 * bucket, so we look it up deliberately ignoring the zoneid.
19330 		 */
19331 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19332 			if (ire->ire_addr != addr)
19333 				continue;
19334 			/* skip over deleted ires */
19335 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19336 				continue;
19337 		}
19338 	}
19339 	while (ire != NULL) {
19340 		/*
19341 		 * If a new interface is coming up, we could end up
19342 		 * seeing the loopback ire and the non-loopback ire
19343 		 * may not have been added yet. So check for ire_stq
19344 		 */
19345 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19346 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19347 			break;
19348 		}
19349 		ire = ire->ire_next;
19350 	}
19351 	if (ire != NULL && ire->ire_addr == addr &&
19352 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19353 		IRE_REFHOLD(ire);
19354 		rw_exit(&irb->irb_lock);
19355 		ire_refrele(save_ire);
19356 		*conn_outgoing_ill = ire_to_ill(ire);
19357 		/*
19358 		 * Refhold the ill to make the conn_outgoing_ill
19359 		 * independent of the ire. ip_wput_ire goes in a loop
19360 		 * and may refrele the ire. Since we have an ire at this
19361 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19362 		 */
19363 		ill_refhold(*conn_outgoing_ill);
19364 		return (ire);
19365 	}
19366 	rw_exit(&irb->irb_lock);
19367 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19368 	/*
19369 	 * If we can't find a suitable ire, return the original ire.
19370 	 */
19371 	return (save_ire);
19372 }
19373 
19374 /*
19375  * This function does the ire_refrele of the ire passed in as the
19376  * argument. As this function looks up more ires i.e broadcast ires,
19377  * it needs to REFRELE them. Currently, for simplicity we don't
19378  * differentiate the one passed in and looked up here. We always
19379  * REFRELE.
19380  * IPQoS Notes:
19381  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19382  * IPSec packets are done in ipsec_out_process.
19383  *
19384  */
19385 void
19386 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19387 {
19388 	ipha_t		*ipha;
19389 #define	rptr	((uchar_t *)ipha)
19390 	mblk_t		*mp1;
19391 	queue_t		*stq;
19392 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19393 	uint32_t	v_hlen_tos_len;
19394 	uint32_t	ttl_protocol;
19395 	ipaddr_t	src;
19396 	ipaddr_t	dst;
19397 	uint32_t	cksum;
19398 	ipaddr_t	orig_src;
19399 	ire_t		*ire1;
19400 	mblk_t		*next_mp;
19401 	uint_t		hlen;
19402 	uint16_t	*up;
19403 	uint32_t	max_frag = ire->ire_max_frag;
19404 	ill_t		*ill = ire_to_ill(ire);
19405 	int		clusterwide;
19406 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19407 	int		ipsec_len;
19408 	mblk_t		*first_mp;
19409 	ipsec_out_t	*io;
19410 	boolean_t	conn_dontroute;		/* conn value for multicast */
19411 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19412 	boolean_t	multicast_forward;	/* Should we forward ? */
19413 	boolean_t	unspec_src;
19414 	ill_t		*conn_outgoing_ill = NULL;
19415 	ill_t		*ire_ill;
19416 	ill_t		*ire1_ill;
19417 	uint32_t 	ill_index = 0;
19418 	boolean_t	multirt_send = B_FALSE;
19419 	int		err;
19420 	zoneid_t	zoneid;
19421 	boolean_t	iphdrhwcksum = B_FALSE;
19422 
19423 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19424 	    "ip_wput_ire_start: q %p", q);
19425 
19426 	multicast_forward = B_FALSE;
19427 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19428 
19429 	if (ire->ire_flags & RTF_MULTIRT) {
19430 		/*
19431 		 * Multirouting case. The bucket where ire is stored
19432 		 * probably holds other RTF_MULTIRT flagged ire
19433 		 * to the destination. In this call to ip_wput_ire,
19434 		 * we attempt to send the packet through all
19435 		 * those ires. Thus, we first ensure that ire is the
19436 		 * first RTF_MULTIRT ire in the bucket,
19437 		 * before walking the ire list.
19438 		 */
19439 		ire_t *first_ire;
19440 		irb_t *irb = ire->ire_bucket;
19441 		ASSERT(irb != NULL);
19442 
19443 		/* Make sure we do not omit any multiroute ire. */
19444 		IRB_REFHOLD(irb);
19445 		for (first_ire = irb->irb_ire;
19446 		    first_ire != NULL;
19447 		    first_ire = first_ire->ire_next) {
19448 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19449 			    (first_ire->ire_addr == ire->ire_addr) &&
19450 			    !(first_ire->ire_marks &
19451 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19452 				break;
19453 		}
19454 
19455 		if ((first_ire != NULL) && (first_ire != ire)) {
19456 			IRE_REFHOLD(first_ire);
19457 			ire_refrele(ire);
19458 			ire = first_ire;
19459 			ill = ire_to_ill(ire);
19460 		}
19461 		IRB_REFRELE(irb);
19462 	}
19463 
19464 	/*
19465 	 * conn_outgoing_ill is used only in the broadcast loop.
19466 	 * for performance we don't grab the mutexs in the fastpath
19467 	 */
19468 	if ((connp != NULL) &&
19469 	    (connp->conn_xmit_if_ill == NULL) &&
19470 	    (ire->ire_type == IRE_BROADCAST) &&
19471 	    ((connp->conn_nofailover_ill != NULL) ||
19472 	    (connp->conn_outgoing_ill != NULL))) {
19473 		/*
19474 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19475 		 * option. So, see if this endpoint is bound to a
19476 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19477 		 * that if the interface is failed, we will still send
19478 		 * the packet on the same ill which is what we want.
19479 		 */
19480 		conn_outgoing_ill = conn_get_held_ill(connp,
19481 		    &connp->conn_nofailover_ill, &err);
19482 		if (err == ILL_LOOKUP_FAILED) {
19483 			ire_refrele(ire);
19484 			freemsg(mp);
19485 			return;
19486 		}
19487 		if (conn_outgoing_ill == NULL) {
19488 			/*
19489 			 * Choose a good ill in the group to send the
19490 			 * packets on.
19491 			 */
19492 			ire = conn_set_outgoing_ill(connp, ire,
19493 			    &conn_outgoing_ill);
19494 			if (ire == NULL) {
19495 				freemsg(mp);
19496 				return;
19497 			}
19498 		}
19499 	}
19500 
19501 	if (mp->b_datap->db_type != M_CTL) {
19502 		ipha = (ipha_t *)mp->b_rptr;
19503 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19504 	} else {
19505 		io = (ipsec_out_t *)mp->b_rptr;
19506 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19507 		zoneid = io->ipsec_out_zoneid;
19508 		ASSERT(zoneid != ALL_ZONES);
19509 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19510 		dst = ipha->ipha_dst;
19511 		/*
19512 		 * For the multicast case, ipsec_out carries conn_dontroute and
19513 		 * conn_multicast_loop as conn may not be available here. We
19514 		 * need this for multicast loopback and forwarding which is done
19515 		 * later in the code.
19516 		 */
19517 		if (CLASSD(dst)) {
19518 			conn_dontroute = io->ipsec_out_dontroute;
19519 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19520 			/*
19521 			 * If conn_dontroute is not set or conn_multicast_loop
19522 			 * is set, we need to do forwarding/loopback. For
19523 			 * datagrams from ip_wput_multicast, conn_dontroute is
19524 			 * set to B_TRUE and conn_multicast_loop is set to
19525 			 * B_FALSE so that we neither do forwarding nor
19526 			 * loopback.
19527 			 */
19528 			if (!conn_dontroute || conn_multicast_loop)
19529 				multicast_forward = B_TRUE;
19530 		}
19531 	}
19532 
19533 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19534 		/*
19535 		 * When a zone sends a packet to another zone, we try to deliver
19536 		 * the packet under the same conditions as if the destination
19537 		 * was a real node on the network. To do so, we look for a
19538 		 * matching route in the forwarding table.
19539 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19540 		 * ip_newroute() does.
19541 		 */
19542 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19543 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19544 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19545 		if (src_ire != NULL &&
19546 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19547 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19548 				ipha->ipha_src = src_ire->ire_src_addr;
19549 			ire_refrele(src_ire);
19550 		} else {
19551 			ire_refrele(ire);
19552 			if (conn_outgoing_ill != NULL)
19553 				ill_refrele(conn_outgoing_ill);
19554 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19555 			if (src_ire != NULL) {
19556 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19557 					ire_refrele(src_ire);
19558 					freemsg(mp);
19559 					return;
19560 				}
19561 				ire_refrele(src_ire);
19562 			}
19563 			if (ip_hdr_complete(ipha, zoneid)) {
19564 				/* Failed */
19565 				freemsg(mp);
19566 				return;
19567 			}
19568 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19569 			return;
19570 		}
19571 	}
19572 
19573 	if (mp->b_datap->db_type == M_CTL ||
19574 	    ipsec_outbound_v4_policy_present) {
19575 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19576 		    unspec_src);
19577 		if (mp == NULL) {
19578 			ire_refrele(ire);
19579 			if (conn_outgoing_ill != NULL)
19580 				ill_refrele(conn_outgoing_ill);
19581 			return;
19582 		}
19583 	}
19584 
19585 	first_mp = mp;
19586 	ipsec_len = 0;
19587 
19588 	if (first_mp->b_datap->db_type == M_CTL) {
19589 		io = (ipsec_out_t *)first_mp->b_rptr;
19590 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19591 		mp = first_mp->b_cont;
19592 		ipsec_len = ipsec_out_extra_length(first_mp);
19593 		ASSERT(ipsec_len >= 0);
19594 		zoneid = io->ipsec_out_zoneid;
19595 		ASSERT(zoneid != ALL_ZONES);
19596 
19597 		/*
19598 		 * Drop M_CTL here if IPsec processing is not needed.
19599 		 * (Non-IPsec use of M_CTL extracted any information it
19600 		 * needed above).
19601 		 */
19602 		if (ipsec_len == 0) {
19603 			freeb(first_mp);
19604 			first_mp = mp;
19605 		}
19606 	}
19607 
19608 	/*
19609 	 * Fast path for ip_wput_ire
19610 	 */
19611 
19612 	ipha = (ipha_t *)mp->b_rptr;
19613 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19614 	dst = ipha->ipha_dst;
19615 
19616 	/*
19617 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19618 	 * if the socket is a SOCK_RAW type. The transport checksum should
19619 	 * be provided in the pre-built packet, so we don't need to compute it.
19620 	 * Also, other application set flags, like DF, should not be altered.
19621 	 * Other transport MUST pass down zero.
19622 	 */
19623 	ip_hdr_included = ipha->ipha_ident;
19624 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19625 
19626 	if (CLASSD(dst)) {
19627 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19628 		    ntohl(dst),
19629 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19630 		    ntohl(ire->ire_addr)));
19631 	}
19632 
19633 /* Macros to extract header fields from data already in registers */
19634 #ifdef	_BIG_ENDIAN
19635 #define	V_HLEN	(v_hlen_tos_len >> 24)
19636 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19637 #define	PROTO	(ttl_protocol & 0xFF)
19638 #else
19639 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19640 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19641 #define	PROTO	(ttl_protocol >> 8)
19642 #endif
19643 
19644 
19645 	orig_src = src = ipha->ipha_src;
19646 	/* (The loop back to "another" is explained down below.) */
19647 another:;
19648 	/*
19649 	 * Assign an ident value for this packet.  We assign idents on
19650 	 * a per destination basis out of the IRE.  There could be
19651 	 * other threads targeting the same destination, so we have to
19652 	 * arrange for a atomic increment.  Note that we use a 32-bit
19653 	 * atomic add because it has better performance than its
19654 	 * 16-bit sibling.
19655 	 *
19656 	 * If running in cluster mode and if the source address
19657 	 * belongs to a replicated service then vector through
19658 	 * cl_inet_ipident vector to allocate ip identifier
19659 	 * NOTE: This is a contract private interface with the
19660 	 * clustering group.
19661 	 */
19662 	clusterwide = 0;
19663 	if (cl_inet_ipident) {
19664 		ASSERT(cl_inet_isclusterwide);
19665 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19666 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19667 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19668 			    AF_INET, (uint8_t *)(uintptr_t)src,
19669 			    (uint8_t *)(uintptr_t)dst);
19670 			clusterwide = 1;
19671 		}
19672 	}
19673 	if (!clusterwide) {
19674 		ipha->ipha_ident =
19675 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19676 	}
19677 
19678 #ifndef _BIG_ENDIAN
19679 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19680 #endif
19681 
19682 	/*
19683 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19684 	 * This is needed to obey conn_unspec_src when packets go through
19685 	 * ip_newroute + arp.
19686 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19687 	 */
19688 	if (src == INADDR_ANY && !unspec_src) {
19689 		/*
19690 		 * Assign the appropriate source address from the IRE if none
19691 		 * was specified.
19692 		 */
19693 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19694 
19695 		/*
19696 		 * With IP multipathing, broadcast packets are sent on the ire
19697 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19698 		 * the group. However, this ire might not be in the same zone so
19699 		 * we can't always use its source address. We look for a
19700 		 * broadcast ire in the same group and in the right zone.
19701 		 */
19702 		if (ire->ire_type == IRE_BROADCAST &&
19703 		    ire->ire_zoneid != zoneid) {
19704 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19705 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19706 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19707 			if (src_ire != NULL) {
19708 				src = src_ire->ire_src_addr;
19709 				ire_refrele(src_ire);
19710 			} else {
19711 				ire_refrele(ire);
19712 				if (conn_outgoing_ill != NULL)
19713 					ill_refrele(conn_outgoing_ill);
19714 				freemsg(first_mp);
19715 				BUMP_MIB(&ip_mib, ipOutDiscards);
19716 				return;
19717 			}
19718 		} else {
19719 			src = ire->ire_src_addr;
19720 		}
19721 
19722 		if (connp == NULL) {
19723 			ip1dbg(("ip_wput_ire: no connp and no src "
19724 			    "address for dst 0x%x, using src 0x%x\n",
19725 			    ntohl(dst),
19726 			    ntohl(src)));
19727 		}
19728 		ipha->ipha_src = src;
19729 	}
19730 	stq = ire->ire_stq;
19731 
19732 	/*
19733 	 * We only allow ire chains for broadcasts since there will
19734 	 * be multiple IRE_CACHE entries for the same multicast
19735 	 * address (one per ipif).
19736 	 */
19737 	next_mp = NULL;
19738 
19739 	/* broadcast packet */
19740 	if (ire->ire_type == IRE_BROADCAST)
19741 		goto broadcast;
19742 
19743 	/* loopback ? */
19744 	if (stq == NULL)
19745 		goto nullstq;
19746 
19747 	/* The ill_index for outbound ILL */
19748 	ill_index = Q_TO_INDEX(stq);
19749 
19750 	BUMP_MIB(&ip_mib, ipOutRequests);
19751 	ttl_protocol = ((uint16_t *)ipha)[4];
19752 
19753 	/* pseudo checksum (do it in parts for IP header checksum) */
19754 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19755 
19756 #define	FRAGMENT_NEEDED(mtu, size)	\
19757 	(((mtu) < (unsigned int)(size)) ? B_TRUE : B_FALSE)
19758 
19759 #define	IS_FASTPATH(ire, bp) 					\
19760 	((ire)->ire_fp_mp != NULL &&				\
19761 	(MBLKHEAD((bp)) >= (MBLKL((ire)->ire_fp_mp))))		\
19762 
19763 #define	IPH_UDPH_CHECKSUMP(ipha, hlen) \
19764 	((uint16_t *)(((uchar_t *)ipha)+(hlen + UDP_CHECKSUM_OFFSET)))
19765 #define	IPH_TCPH_CHECKSUMP(ipha, hlen) \
19766 	    ((uint16_t *)(((uchar_t *)ipha)+(hlen+TCP_CHECKSUM_OFFSET)))
19767 
19768 #define	IP_CKSUM_XMIT(ill, ire, mp, up, proto, hlen, max_frag,		\
19769 	    ipsec_len) { 						\
19770 	uint32_t	sum;						\
19771 	uint32_t	xmit_capab = HCKSUM_INET_FULL_V4 |		\
19772 			    HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM;	\
19773 	boolean_t	cksum_offload = B_FALSE;			\
19774 									\
19775 	/*								\
19776 	 * The ire fp mp can change due to the arrival of a		\
19777 	 * DL_NOTE_FASTPATH_FLUSH in the case of IRE_BROADCAST		\
19778 	 * and IRE_MIPRTUN. Hence the ire_fp_mp has to be accessed	\
19779 	 * only under the ire_lock in such cases.			\
19780 	 */								\
19781 	LOCK_IRE_FP_MP(ire);						\
19782 	if ((ill) && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&	\
19783 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &		\
19784 	    xmit_capab) && (!FRAGMENT_NEEDED(max_frag, 			\
19785 	    (LENGTH + ipsec_len))) && (!(ire->ire_flags & 		\
19786 	    RTF_MULTIRT)) && (ipsec_len == 0) && 			\
19787 	    IS_FASTPATH((ire), (mp)) &&	(dohwcksum)) { 			\
19788 		/*							\
19789 		 * Underlying interface supports hardware checksumming.	\
19790 		 * So postpone the checksum to the interface driver	\
19791 		 */							\
19792 									\
19793 		if ((hlen) == IP_SIMPLE_HDR_LENGTH) {			       \
19794 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19795 			    HCKSUM_IPHDRCKSUM) {			       \
19796 				mp->b_datap->db_struioun.cksum.flags |=	       \
19797 				    HCK_IPV4_HDRCKSUM;			       \
19798 				/* seed the cksum field to 0 */		       \
19799 				ipha->ipha_hdr_checksum = 0;		       \
19800 				iphdrhwcksum = B_TRUE;			       \
19801 			}						       \
19802 			/*						       \
19803 			 * If underlying h/w supports full h/w checksumming    \
19804 			 * and no IP options are present, then offload	       \
19805 			 * full checksumming to the hardware.		       \
19806 			 *						       \
19807 			 * If h/w can do partial checksumming then offload     \
19808 			 * unless the startpoint offset, including mac-header, \
19809 			 * is too big for the interface to some of our	       \
19810 			 * hardware (CE and ERI) which have 6 bit fields.      \
19811 			 * Sigh.					       \
19812 			 * Unhappily we don't have the mac-header size here    \
19813 			 * so punt for any options.			       \
19814 			 */						       \
19815 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19816 			    HCKSUM_INET_FULL_V4) {			       \
19817 				UNLOCK_IRE_FP_MP(ire);			       \
19818 				/* Seed the checksum field to 0 */	       \
19819 				*up = 0;				       \
19820 				mp->b_datap->db_struioun.cksum.flags |=	       \
19821 				    HCK_FULLCKSUM;			       \
19822 				cksum_offload = B_TRUE;			       \
19823 			} else if (ill->ill_hcksum_capab->ill_hcksum_txflags & \
19824 			    HCKSUM_INET_PARTIAL) {			       \
19825 				UNLOCK_IRE_FP_MP(ire);			       \
19826 				sum = *up + cksum + proto;		       \
19827 				sum = (sum & 0xFFFF) + (sum >> 16);	       \
19828 				*up = (sum & 0xFFFF) + (sum >> 16);	       \
19829 				/*					       \
19830 				 * All offsets are relative to the beginning   \
19831 				 * of the IP header.			       \
19832 				 */					       \
19833 				mp->b_datap->db_cksumstart = hlen;	       \
19834 				mp->b_datap->db_cksumstuff = 		       \
19835 				    (PROTO == IPPROTO_UDP) ?		       \
19836 				    (hlen) + UDP_CHECKSUM_OFFSET :	       \
19837 				    (hlen) + TCP_CHECKSUM_OFFSET;	       \
19838 				mp->b_datap->db_cksumend = ipha->ipha_length;  \
19839 				mp->b_datap->db_struioun.cksum.flags |=	       \
19840 				    HCK_PARTIALCKSUM;			       \
19841 				cksum_offload = B_TRUE;			       \
19842 			}						       \
19843 		}							\
19844 	} 								\
19845 	if (!cksum_offload) {						\
19846 		UNLOCK_IRE_FP_MP(ire);					\
19847 		IP_STAT(ip_out_sw_cksum);				\
19848 		(sum) = IP_CSUM((mp), (hlen), cksum + proto);		\
19849 		*(up) = (uint16_t)((sum) ? (sum) : ~(sum));		\
19850 	}								\
19851 }
19852 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
19853 		queue_t *dev_q = stq->q_next;
19854 
19855 		/* flow controlled */
19856 		if ((dev_q->q_next || dev_q->q_first) &&
19857 		    !canput(dev_q))
19858 			goto blocked;
19859 		if ((PROTO == IPPROTO_UDP) &&
19860 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
19861 			hlen = (V_HLEN & 0xF) << 2;
19862 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
19863 			if (*up) {
19864 				IP_CKSUM_XMIT(ill, ire, mp, up,
19865 				    IP_UDP_CSUM_COMP, hlen, max_frag,
19866 				    ipsec_len);
19867 			}
19868 		}
19869 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
19870 		hlen = (V_HLEN & 0xF) << 2;
19871 		if (PROTO == IPPROTO_TCP) {
19872 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
19873 			/*
19874 			 * The packet header is processed once and for all, even
19875 			 * in the multirouting case. We disable hardware
19876 			 * checksum if the packet is multirouted, as it will be
19877 			 * replicated via several interfaces, and not all of
19878 			 * them may have this capability.
19879 			 */
19880 			IP_CKSUM_XMIT(ill, ire, mp, up,
19881 			    IP_TCP_CSUM_COMP, hlen, max_frag, ipsec_len);
19882 		} else {
19883 			sctp_hdr_t	*sctph;
19884 
19885 			ASSERT(PROTO == IPPROTO_SCTP);
19886 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
19887 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
19888 			/*
19889 			 * Zero out the checksum field to ensure proper
19890 			 * checksum calculation.
19891 			 */
19892 			sctph->sh_chksum = 0;
19893 #ifdef	DEBUG
19894 			if (!skip_sctp_cksum)
19895 #endif
19896 				sctph->sh_chksum = sctp_cksum(mp, hlen);
19897 		}
19898 	}
19899 
19900 	/*
19901 	 * If this is a multicast packet and originated from ip_wput
19902 	 * we need to do loopback and forwarding checks. If it comes
19903 	 * from ip_wput_multicast, we SHOULD not do this.
19904 	 */
19905 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
19906 
19907 	/* checksum */
19908 	cksum += ttl_protocol;
19909 
19910 	/* fragment the packet */
19911 	if (FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len)))
19912 		goto fragmentit;
19913 	/*
19914 	 * Don't use frag_flag if packet is pre-built or source
19915 	 * routed or if multicast (since multicast packets do
19916 	 * not solicit ICMP "packet too big" messages).
19917 	 */
19918 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
19919 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
19920 	    !ip_source_route_included(ipha)) &&
19921 	    !CLASSD(ipha->ipha_dst))
19922 		ipha->ipha_fragment_offset_and_flags |=
19923 		    htons(ire->ire_frag_flag);
19924 
19925 	if (!iphdrhwcksum) {
19926 		/* checksum */
19927 		cksum += ipha->ipha_ident;
19928 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
19929 		cksum += ipha->ipha_fragment_offset_and_flags;
19930 
19931 		/* IP options present */
19932 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
19933 		if (hlen)
19934 			goto checksumoptions;
19935 
19936 		/* calculate hdr checksum */
19937 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
19938 		cksum = ~(cksum + (cksum >> 16));
19939 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
19940 	}
19941 	if (ipsec_len != 0) {
19942 		/*
19943 		 * We will do the rest of the processing after
19944 		 * we come back from IPSEC in ip_wput_ipsec_out().
19945 		 */
19946 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
19947 
19948 		io = (ipsec_out_t *)first_mp->b_rptr;
19949 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
19950 				ill_phyint->phyint_ifindex;
19951 
19952 		ipsec_out_process(q, first_mp, ire, ill_index);
19953 		ire_refrele(ire);
19954 		if (conn_outgoing_ill != NULL)
19955 			ill_refrele(conn_outgoing_ill);
19956 		return;
19957 	}
19958 
19959 	/*
19960 	 * In most cases, the emission loop below is entered only
19961 	 * once. Only in the case where the ire holds the
19962 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
19963 	 * flagged ires in the bucket, and send the packet
19964 	 * through all crossed RTF_MULTIRT routes.
19965 	 */
19966 	if (ire->ire_flags & RTF_MULTIRT) {
19967 		multirt_send = B_TRUE;
19968 	}
19969 	do {
19970 		if (multirt_send) {
19971 			irb_t *irb;
19972 			/*
19973 			 * We are in a multiple send case, need to get
19974 			 * the next ire and make a duplicate of the packet.
19975 			 * ire1 holds here the next ire to process in the
19976 			 * bucket. If multirouting is expected,
19977 			 * any non-RTF_MULTIRT ire that has the
19978 			 * right destination address is ignored.
19979 			 */
19980 			irb = ire->ire_bucket;
19981 			ASSERT(irb != NULL);
19982 
19983 			IRB_REFHOLD(irb);
19984 			for (ire1 = ire->ire_next;
19985 			    ire1 != NULL;
19986 			    ire1 = ire1->ire_next) {
19987 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
19988 					continue;
19989 				if (ire1->ire_addr != ire->ire_addr)
19990 					continue;
19991 				if (ire1->ire_marks &
19992 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
19993 					continue;
19994 
19995 				/* Got one */
19996 				IRE_REFHOLD(ire1);
19997 				break;
19998 			}
19999 			IRB_REFRELE(irb);
20000 
20001 			if (ire1 != NULL) {
20002 				next_mp = copyb(mp);
20003 				if ((next_mp == NULL) ||
20004 				    ((mp->b_cont != NULL) &&
20005 				    ((next_mp->b_cont =
20006 				    dupmsg(mp->b_cont)) == NULL))) {
20007 					freemsg(next_mp);
20008 					next_mp = NULL;
20009 					ire_refrele(ire1);
20010 					ire1 = NULL;
20011 				}
20012 			}
20013 
20014 			/* Last multiroute ire; don't loop anymore. */
20015 			if (ire1 == NULL) {
20016 				multirt_send = B_FALSE;
20017 			}
20018 		}
20019 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20020 		if (mp == NULL) {
20021 			BUMP_MIB(&ip_mib, ipOutDiscards);
20022 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20023 			    "during IPPF processing\n"));
20024 			ire_refrele(ire);
20025 			if (next_mp != NULL) {
20026 				freemsg(next_mp);
20027 				ire_refrele(ire1);
20028 			}
20029 			if (conn_outgoing_ill != NULL)
20030 				ill_refrele(conn_outgoing_ill);
20031 			return;
20032 		}
20033 		UPDATE_OB_PKT_COUNT(ire);
20034 		ire->ire_last_used_time = lbolt;
20035 
20036 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20037 		    "ip_wput_ire_end: q %p (%S)",
20038 		    q, "last copy out");
20039 		putnext(stq, mp);
20040 		IRE_REFRELE(ire);
20041 
20042 		if (multirt_send) {
20043 			ASSERT(ire1);
20044 			/*
20045 			 * Proceed with the next RTF_MULTIRT ire,
20046 			 * Also set up the send-to queue accordingly.
20047 			 */
20048 			ire = ire1;
20049 			ire1 = NULL;
20050 			stq = ire->ire_stq;
20051 			mp = next_mp;
20052 			next_mp = NULL;
20053 			ipha = (ipha_t *)mp->b_rptr;
20054 			ill_index = Q_TO_INDEX(stq);
20055 		}
20056 	} while (multirt_send);
20057 	if (conn_outgoing_ill != NULL)
20058 		ill_refrele(conn_outgoing_ill);
20059 	return;
20060 
20061 	/*
20062 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20063 	 */
20064 broadcast:
20065 	{
20066 		/*
20067 		 * Avoid broadcast storms by setting the ttl to 1
20068 		 * for broadcasts. This parameter can be set
20069 		 * via ndd, so make sure that for the SO_DONTROUTE
20070 		 * case that ipha_ttl is always set to 1.
20071 		 * In the event that we are replying to incoming
20072 		 * ICMP packets, conn could be NULL.
20073 		 */
20074 		if ((connp != NULL) && connp->conn_dontroute)
20075 			ipha->ipha_ttl = 1;
20076 		else
20077 			ipha->ipha_ttl = ip_broadcast_ttl;
20078 
20079 		/*
20080 		 * Note that we are not doing a IRB_REFHOLD here.
20081 		 * Actually we don't care if the list changes i.e
20082 		 * if somebody deletes an IRE from the list while
20083 		 * we drop the lock, the next time we come around
20084 		 * ire_next will be NULL and hence we won't send
20085 		 * out multiple copies which is fine.
20086 		 */
20087 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20088 		ire1 = ire->ire_next;
20089 		if (conn_outgoing_ill != NULL) {
20090 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20091 				ASSERT(ire1 == ire->ire_next);
20092 				if (ire1 != NULL && ire1->ire_addr == dst) {
20093 					ire_refrele(ire);
20094 					ire = ire1;
20095 					IRE_REFHOLD(ire);
20096 					ire1 = ire->ire_next;
20097 					continue;
20098 				}
20099 				rw_exit(&ire->ire_bucket->irb_lock);
20100 				/* Did not find a matching ill */
20101 				ip1dbg(("ip_wput_ire: broadcast with no "
20102 				    "matching IP_BOUND_IF ill %s\n",
20103 				    conn_outgoing_ill->ill_name));
20104 				freemsg(first_mp);
20105 				if (ire != NULL)
20106 					ire_refrele(ire);
20107 				ill_refrele(conn_outgoing_ill);
20108 				return;
20109 			}
20110 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20111 			/*
20112 			 * If the next IRE has the same address and is not one
20113 			 * of the two copies that we need to send, try to see
20114 			 * whether this copy should be sent at all. This
20115 			 * assumes that we insert loopbacks first and then
20116 			 * non-loopbacks. This is acheived by inserting the
20117 			 * loopback always before non-loopback.
20118 			 * This is used to send a single copy of a broadcast
20119 			 * packet out all physical interfaces that have an
20120 			 * matching IRE_BROADCAST while also looping
20121 			 * back one copy (to ip_wput_local) for each
20122 			 * matching physical interface. However, we avoid
20123 			 * sending packets out different logical that match by
20124 			 * having ipif_up/ipif_down supress duplicate
20125 			 * IRE_BROADCASTS.
20126 			 *
20127 			 * This feature is currently used to get broadcasts
20128 			 * sent to multiple interfaces, when the broadcast
20129 			 * address being used applies to multiple interfaces.
20130 			 * For example, a whole net broadcast will be
20131 			 * replicated on every connected subnet of
20132 			 * the target net.
20133 			 *
20134 			 * Each zone has its own set of IRE_BROADCASTs, so that
20135 			 * we're able to distribute inbound packets to multiple
20136 			 * zones who share a broadcast address. We avoid looping
20137 			 * back outbound packets in different zones but on the
20138 			 * same ill, as the application would see duplicates.
20139 			 *
20140 			 * If the interfaces are part of the same group,
20141 			 * we would want to send only one copy out for
20142 			 * whole group.
20143 			 *
20144 			 * This logic assumes that ire_add_v4() groups the
20145 			 * IRE_BROADCAST entries so that those with the same
20146 			 * ire_addr and ill_group are kept together.
20147 			 */
20148 			ire_ill = ire->ire_ipif->ipif_ill;
20149 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20150 				if (ire_ill->ill_group != NULL &&
20151 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20152 					/*
20153 					 * If the current zone only has an ire
20154 					 * broadcast for this address marked
20155 					 * NORECV, the ire we want is ahead in
20156 					 * the bucket, so we look it up
20157 					 * deliberately ignoring the zoneid.
20158 					 */
20159 					for (ire1 = ire->ire_bucket->irb_ire;
20160 					    ire1 != NULL;
20161 					    ire1 = ire1->ire_next) {
20162 						ire1_ill =
20163 						    ire1->ire_ipif->ipif_ill;
20164 						if (ire1->ire_addr != dst)
20165 							continue;
20166 						/* skip over the current ire */
20167 						if (ire1 == ire)
20168 							continue;
20169 						/* skip over deleted ires */
20170 						if (ire1->ire_marks &
20171 						    IRE_MARK_CONDEMNED)
20172 							continue;
20173 						/*
20174 						 * non-loopback ire in our
20175 						 * group: use it for the next
20176 						 * pass in the loop
20177 						 */
20178 						if (ire1->ire_stq != NULL &&
20179 						    ire1_ill->ill_group ==
20180 						    ire_ill->ill_group)
20181 							break;
20182 					}
20183 				}
20184 			} else {
20185 				while (ire1 != NULL && ire1->ire_addr == dst) {
20186 					ire1_ill = ire1->ire_ipif->ipif_ill;
20187 					/*
20188 					 * We can have two broadcast ires on the
20189 					 * same ill in different zones; here
20190 					 * we'll send a copy of the packet on
20191 					 * each ill and the fanout code will
20192 					 * call conn_wantpacket() to check that
20193 					 * the zone has the broadcast address
20194 					 * configured on the ill. If the two
20195 					 * ires are in the same group we only
20196 					 * send one copy up.
20197 					 */
20198 					if (ire1_ill != ire_ill &&
20199 					    (ire1_ill->ill_group == NULL ||
20200 					    ire_ill->ill_group == NULL ||
20201 					    ire1_ill->ill_group !=
20202 					    ire_ill->ill_group)) {
20203 						break;
20204 					}
20205 					ire1 = ire1->ire_next;
20206 				}
20207 			}
20208 		}
20209 		ASSERT(multirt_send == B_FALSE);
20210 		if (ire1 != NULL && ire1->ire_addr == dst) {
20211 			if ((ire->ire_flags & RTF_MULTIRT) &&
20212 			    (ire1->ire_flags & RTF_MULTIRT)) {
20213 				/*
20214 				 * We are in the multirouting case.
20215 				 * The message must be sent at least
20216 				 * on both ires. These ires have been
20217 				 * inserted AFTER the standard ones
20218 				 * in ip_rt_add(). There are thus no
20219 				 * other ire entries for the destination
20220 				 * address in the rest of the bucket
20221 				 * that do not have the RTF_MULTIRT
20222 				 * flag. We don't process a copy
20223 				 * of the message here. This will be
20224 				 * done in the final sending loop.
20225 				 */
20226 				multirt_send = B_TRUE;
20227 			} else {
20228 				next_mp = ip_copymsg(first_mp);
20229 				if (next_mp != NULL)
20230 					IRE_REFHOLD(ire1);
20231 			}
20232 		}
20233 		rw_exit(&ire->ire_bucket->irb_lock);
20234 	}
20235 
20236 	if (stq) {
20237 		/*
20238 		 * A non-NULL send-to queue means this packet is going
20239 		 * out of this machine.
20240 		 */
20241 
20242 		BUMP_MIB(&ip_mib, ipOutRequests);
20243 		ttl_protocol = ((uint16_t *)ipha)[4];
20244 		/*
20245 		 * We accumulate the pseudo header checksum in cksum.
20246 		 * This is pretty hairy code, so watch close.  One
20247 		 * thing to keep in mind is that UDP and TCP have
20248 		 * stored their respective datagram lengths in their
20249 		 * checksum fields.  This lines things up real nice.
20250 		 */
20251 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20252 		    (src >> 16) + (src & 0xFFFF);
20253 		/*
20254 		 * We assume the udp checksum field contains the
20255 		 * length, so to compute the pseudo header checksum,
20256 		 * all we need is the protocol number and src/dst.
20257 		 */
20258 		/* Provide the checksums for UDP and TCP. */
20259 		if ((PROTO == IPPROTO_TCP) &&
20260 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20261 			/* hlen gets the number of uchar_ts in the IP header */
20262 			hlen = (V_HLEN & 0xF) << 2;
20263 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20264 			IP_STAT(ip_out_sw_cksum);
20265 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20266 		} else if (PROTO == IPPROTO_SCTP &&
20267 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20268 			sctp_hdr_t	*sctph;
20269 
20270 			hlen = (V_HLEN & 0xF) << 2;
20271 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20272 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20273 			sctph->sh_chksum = 0;
20274 #ifdef	DEBUG
20275 			if (!skip_sctp_cksum)
20276 #endif
20277 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20278 		} else {
20279 			queue_t *dev_q = stq->q_next;
20280 
20281 			if ((dev_q->q_next || dev_q->q_first) &&
20282 			    !canput(dev_q)) {
20283 			    blocked:
20284 				ipha->ipha_ident = ip_hdr_included;
20285 				/*
20286 				 * If we don't have a conn to apply
20287 				 * backpressure, free the message.
20288 				 * In the ire_send path, we don't know
20289 				 * the position to requeue the packet. Rather
20290 				 * than reorder packets, we just drop this
20291 				 * packet.
20292 				 */
20293 				if (ip_output_queue && connp != NULL &&
20294 				    caller != IRE_SEND) {
20295 					if (caller == IP_WSRV) {
20296 						connp->conn_did_putbq = 1;
20297 						(void) putbq(connp->conn_wq,
20298 						    first_mp);
20299 						conn_drain_insert(connp);
20300 						/*
20301 						 * This is the service thread,
20302 						 * and the queue is already
20303 						 * noenabled. The check for
20304 						 * canput and the putbq is not
20305 						 * atomic. So we need to check
20306 						 * again.
20307 						 */
20308 						if (canput(stq->q_next))
20309 							connp->conn_did_putbq
20310 							    = 0;
20311 						IP_STAT(ip_conn_flputbq);
20312 					} else {
20313 						/*
20314 						 * We are not the service proc.
20315 						 * ip_wsrv will be scheduled or
20316 						 * is already running.
20317 						 */
20318 						(void) putq(connp->conn_wq,
20319 						    first_mp);
20320 					}
20321 				} else {
20322 					BUMP_MIB(&ip_mib, ipOutDiscards);
20323 					freemsg(first_mp);
20324 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20325 					    "ip_wput_ire_end: q %p (%S)",
20326 					    q, "discard");
20327 				}
20328 				ire_refrele(ire);
20329 				if (next_mp) {
20330 					ire_refrele(ire1);
20331 					freemsg(next_mp);
20332 				}
20333 				if (conn_outgoing_ill != NULL)
20334 					ill_refrele(conn_outgoing_ill);
20335 				return;
20336 			}
20337 			if ((PROTO == IPPROTO_UDP) &&
20338 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20339 				/*
20340 				 * hlen gets the number of uchar_ts in the
20341 				 * IP header
20342 				 */
20343 				hlen = (V_HLEN & 0xF) << 2;
20344 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20345 				if (*up) {
20346 					uint_t	sum;
20347 
20348 					/*
20349 					 * NOTE: watch out for compiler high
20350 					 * bits
20351 					 */
20352 					IP_STAT(ip_out_sw_cksum);
20353 					sum = IP_CSUM(mp, hlen,
20354 					    cksum + IP_UDP_CSUM_COMP);
20355 					*up = (uint16_t)(sum ? sum : ~sum);
20356 				}
20357 			}
20358 		}
20359 		/*
20360 		 * Need to do this even when fragmenting. The local
20361 		 * loopback can be done without computing checksums
20362 		 * but forwarding out other interface must be done
20363 		 * after the IP checksum (and ULP checksums) have been
20364 		 * computed.
20365 		 *
20366 		 * NOTE : multicast_forward is set only if this packet
20367 		 * originated from ip_wput. For packets originating from
20368 		 * ip_wput_multicast, it is not set.
20369 		 */
20370 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20371 		    multi_loopback:
20372 			ip2dbg(("ip_wput: multicast, loop %d\n",
20373 			    conn_multicast_loop));
20374 
20375 			/*  Forget header checksum offload */
20376 			mp->b_datap->db_struioun.cksum.flags &=
20377 			    ~HCK_IPV4_HDRCKSUM;
20378 			iphdrhwcksum = B_FALSE;
20379 
20380 			/*
20381 			 * Local loopback of multicasts?  Check the
20382 			 * ill.
20383 			 *
20384 			 * Note that the loopback function will not come
20385 			 * in through ip_rput - it will only do the
20386 			 * client fanout thus we need to do an mforward
20387 			 * as well.  The is different from the BSD
20388 			 * logic.
20389 			 */
20390 			if (ill != NULL) {
20391 				ilm_t	*ilm;
20392 
20393 				ILM_WALKER_HOLD(ill);
20394 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20395 				    ALL_ZONES);
20396 				ILM_WALKER_RELE(ill);
20397 				if (ilm != NULL) {
20398 					/*
20399 					 * Pass along the virtual output q.
20400 					 * ip_wput_local() will distribute the
20401 					 * packet to all the matching zones,
20402 					 * except the sending zone when
20403 					 * IP_MULTICAST_LOOP is false.
20404 					 */
20405 					ip_multicast_loopback(q, ill, first_mp,
20406 					    conn_multicast_loop ? 0 :
20407 					    IP_FF_NO_MCAST_LOOP, zoneid);
20408 				}
20409 			}
20410 			if (ipha->ipha_ttl == 0) {
20411 				/*
20412 				 * 0 => only to this host i.e. we are
20413 				 * done. We are also done if this was the
20414 				 * loopback interface since it is sufficient
20415 				 * to loopback one copy of a multicast packet.
20416 				 */
20417 				freemsg(first_mp);
20418 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20419 				    "ip_wput_ire_end: q %p (%S)",
20420 				    q, "loopback");
20421 				ire_refrele(ire);
20422 				if (conn_outgoing_ill != NULL)
20423 					ill_refrele(conn_outgoing_ill);
20424 				return;
20425 			}
20426 			/*
20427 			 * ILLF_MULTICAST is checked in ip_newroute
20428 			 * i.e. we don't need to check it here since
20429 			 * all IRE_CACHEs come from ip_newroute.
20430 			 * For multicast traffic, SO_DONTROUTE is interpreted
20431 			 * to mean only send the packet out the interface
20432 			 * (optionally specified with IP_MULTICAST_IF)
20433 			 * and do not forward it out additional interfaces.
20434 			 * RSVP and the rsvp daemon is an example of a
20435 			 * protocol and user level process that
20436 			 * handles it's own routing. Hence, it uses the
20437 			 * SO_DONTROUTE option to accomplish this.
20438 			 */
20439 
20440 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20441 				/* Unconditionally redo the checksum */
20442 				ipha->ipha_hdr_checksum = 0;
20443 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20444 
20445 				/*
20446 				 * If this needs to go out secure, we need
20447 				 * to wait till we finish the IPSEC
20448 				 * processing.
20449 				 */
20450 				if (ipsec_len == 0 &&
20451 				    ip_mforward(ill, ipha, mp)) {
20452 					freemsg(first_mp);
20453 					ip1dbg(("ip_wput: mforward failed\n"));
20454 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20455 					    "ip_wput_ire_end: q %p (%S)",
20456 					    q, "mforward failed");
20457 					ire_refrele(ire);
20458 					if (conn_outgoing_ill != NULL)
20459 						ill_refrele(conn_outgoing_ill);
20460 					return;
20461 				}
20462 			}
20463 		}
20464 		max_frag = ire->ire_max_frag;
20465 		cksum += ttl_protocol;
20466 		if (!FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len))) {
20467 			/* No fragmentation required for this one. */
20468 			/* Complete the IP header checksum. */
20469 			cksum += ipha->ipha_ident;
20470 			/*
20471 			 * Don't use frag_flag if packet is pre-built or source
20472 			 * routed or if multicast (since multicast packets do
20473 			 * not solicit ICMP "packet too big" messages).
20474 			 */
20475 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20476 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20477 			    !ip_source_route_included(ipha)) &&
20478 			    !CLASSD(ipha->ipha_dst))
20479 				ipha->ipha_fragment_offset_and_flags |=
20480 				    htons(ire->ire_frag_flag);
20481 
20482 			cksum += (v_hlen_tos_len >> 16)+
20483 			    (v_hlen_tos_len & 0xFFFF);
20484 			cksum += ipha->ipha_fragment_offset_and_flags;
20485 			hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20486 			if (hlen) {
20487 			    checksumoptions:
20488 				/*
20489 				 * Account for the IP Options in the IP
20490 				 * header checksum.
20491 				 */
20492 				up = (uint16_t *)(rptr+IP_SIMPLE_HDR_LENGTH);
20493 				do {
20494 					cksum += up[0];
20495 					cksum += up[1];
20496 					up += 2;
20497 				} while (--hlen);
20498 			}
20499 			cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20500 			cksum = ~(cksum + (cksum >> 16));
20501 			ipha->ipha_hdr_checksum = (uint16_t)cksum;
20502 			if (ipsec_len != 0) {
20503 				ipsec_out_process(q, first_mp, ire, ill_index);
20504 				if (!next_mp) {
20505 					ire_refrele(ire);
20506 					if (conn_outgoing_ill != NULL)
20507 						ill_refrele(conn_outgoing_ill);
20508 					return;
20509 				}
20510 				goto next;
20511 			}
20512 
20513 			/*
20514 			 * multirt_send has already been handled
20515 			 * for broadcast, but not yet for multicast
20516 			 * or IP options.
20517 			 */
20518 			if (next_mp == NULL) {
20519 				if (ire->ire_flags & RTF_MULTIRT) {
20520 					multirt_send = B_TRUE;
20521 				}
20522 			}
20523 
20524 			/*
20525 			 * In most cases, the emission loop below is
20526 			 * entered only once. Only in the case where
20527 			 * the ire holds the RTF_MULTIRT flag, do we loop
20528 			 * to process all RTF_MULTIRT ires in the bucket,
20529 			 * and send the packet through all crossed
20530 			 * RTF_MULTIRT routes.
20531 			 */
20532 			do {
20533 				if (multirt_send) {
20534 					irb_t *irb;
20535 
20536 					irb = ire->ire_bucket;
20537 					ASSERT(irb != NULL);
20538 					/*
20539 					 * We are in a multiple send case,
20540 					 * need to get the next IRE and make
20541 					 * a duplicate of the packet.
20542 					 */
20543 					IRB_REFHOLD(irb);
20544 					for (ire1 = ire->ire_next;
20545 					    ire1 != NULL;
20546 					    ire1 = ire1->ire_next) {
20547 						if (!(ire1->ire_flags &
20548 						    RTF_MULTIRT))
20549 							continue;
20550 						if (ire1->ire_addr !=
20551 						    ire->ire_addr)
20552 							continue;
20553 						if (ire1->ire_marks &
20554 						    (IRE_MARK_CONDEMNED|
20555 							IRE_MARK_HIDDEN))
20556 							continue;
20557 
20558 						/* Got one */
20559 						IRE_REFHOLD(ire1);
20560 						break;
20561 					}
20562 					IRB_REFRELE(irb);
20563 
20564 					if (ire1 != NULL) {
20565 						next_mp = copyb(mp);
20566 						if ((next_mp == NULL) ||
20567 						    ((mp->b_cont != NULL) &&
20568 						    ((next_mp->b_cont =
20569 						    dupmsg(mp->b_cont))
20570 						    == NULL))) {
20571 							freemsg(next_mp);
20572 							next_mp = NULL;
20573 							ire_refrele(ire1);
20574 							ire1 = NULL;
20575 						}
20576 					}
20577 
20578 					/*
20579 					 * Last multiroute ire; don't loop
20580 					 * anymore. The emission is over
20581 					 * and next_mp is NULL.
20582 					 */
20583 					if (ire1 == NULL) {
20584 						multirt_send = B_FALSE;
20585 					}
20586 				}
20587 
20588 			noprepend:
20589 				ASSERT(ipsec_len == 0);
20590 				mp1 = ip_wput_attach_llhdr(mp, ire,
20591 				    IPP_LOCAL_OUT, ill_index);
20592 				if (mp1 == NULL) {
20593 					BUMP_MIB(&ip_mib, ipOutDiscards);
20594 					if (next_mp) {
20595 						freemsg(next_mp);
20596 						ire_refrele(ire1);
20597 					}
20598 					ire_refrele(ire);
20599 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20600 					    "ip_wput_ire_end: q %p (%S)",
20601 					    q, "discard MDATA");
20602 					if (conn_outgoing_ill != NULL)
20603 						ill_refrele(conn_outgoing_ill);
20604 					return;
20605 				}
20606 				UPDATE_OB_PKT_COUNT(ire);
20607 				ire->ire_last_used_time = lbolt;
20608 
20609 				if (multirt_send) {
20610 					/*
20611 					 * We are in a multiple send case,
20612 					 * need to re-enter the sending loop
20613 					 * using the next ire.
20614 					 */
20615 					putnext(stq, mp1);
20616 					ire_refrele(ire);
20617 					ire = ire1;
20618 					stq = ire->ire_stq;
20619 					mp = next_mp;
20620 					next_mp = NULL;
20621 					ipha = (ipha_t *)mp->b_rptr;
20622 					ill_index = Q_TO_INDEX(stq);
20623 				}
20624 			} while (multirt_send);
20625 
20626 			if (!next_mp) {
20627 				/*
20628 				 * Last copy going out (the ultra-common
20629 				 * case).  Note that we intentionally replicate
20630 				 * the putnext rather than calling it before
20631 				 * the next_mp check in hopes of a little
20632 				 * tail-call action out of the compiler.
20633 				 */
20634 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20635 				    "ip_wput_ire_end: q %p (%S)",
20636 				    q, "last copy out(1)");
20637 				putnext(stq, mp1);
20638 				ire_refrele(ire);
20639 				if (conn_outgoing_ill != NULL)
20640 					ill_refrele(conn_outgoing_ill);
20641 				return;
20642 			}
20643 			/* More copies going out below. */
20644 			putnext(stq, mp1);
20645 		} else {
20646 			int offset;
20647 		    fragmentit:
20648 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20649 			/*
20650 			 * If this would generate a icmp_frag_needed message,
20651 			 * we need to handle it before we do the IPSEC
20652 			 * processing. Otherwise, we need to strip the IPSEC
20653 			 * headers before we send up the message to the ULPs
20654 			 * which becomes messy and difficult.
20655 			 */
20656 			if (ipsec_len != 0) {
20657 				if ((max_frag < (unsigned int)(LENGTH +
20658 				    ipsec_len)) && (offset & IPH_DF)) {
20659 
20660 					BUMP_MIB(&ip_mib, ipFragFails);
20661 					ipha->ipha_hdr_checksum = 0;
20662 					ipha->ipha_hdr_checksum =
20663 					    (uint16_t)ip_csum_hdr(ipha);
20664 					icmp_frag_needed(ire->ire_stq, first_mp,
20665 					    max_frag);
20666 					if (!next_mp) {
20667 						ire_refrele(ire);
20668 						if (conn_outgoing_ill != NULL) {
20669 							ill_refrele(
20670 							    conn_outgoing_ill);
20671 						}
20672 						return;
20673 					}
20674 				} else {
20675 					/*
20676 					 * This won't cause a icmp_frag_needed
20677 					 * message. to be gnerated. Send it on
20678 					 * the wire. Note that this could still
20679 					 * cause fragmentation and all we
20680 					 * do is the generation of the message
20681 					 * to the ULP if needed before IPSEC.
20682 					 */
20683 					if (!next_mp) {
20684 						ipsec_out_process(q, first_mp,
20685 						    ire, ill_index);
20686 						TRACE_2(TR_FAC_IP,
20687 						    TR_IP_WPUT_IRE_END,
20688 						    "ip_wput_ire_end: q %p "
20689 						    "(%S)", q,
20690 						    "last ipsec_out_process");
20691 						ire_refrele(ire);
20692 						if (conn_outgoing_ill != NULL) {
20693 							ill_refrele(
20694 							    conn_outgoing_ill);
20695 						}
20696 						return;
20697 					}
20698 					ipsec_out_process(q, first_mp,
20699 					    ire, ill_index);
20700 				}
20701 			} else {
20702 				/* Initiate IPPF processing */
20703 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20704 					ip_process(IPP_LOCAL_OUT, &mp,
20705 					    ill_index);
20706 					if (mp == NULL) {
20707 						BUMP_MIB(&ip_mib,
20708 						    ipOutDiscards);
20709 						if (next_mp != NULL) {
20710 							freemsg(next_mp);
20711 							ire_refrele(ire1);
20712 						}
20713 						ire_refrele(ire);
20714 						TRACE_2(TR_FAC_IP,
20715 						    TR_IP_WPUT_IRE_END,
20716 						    "ip_wput_ire: q %p (%S)",
20717 						    q, "discard MDATA");
20718 						if (conn_outgoing_ill != NULL) {
20719 							ill_refrele(
20720 							    conn_outgoing_ill);
20721 						}
20722 						return;
20723 					}
20724 				}
20725 				if (!next_mp) {
20726 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20727 					    "ip_wput_ire_end: q %p (%S)",
20728 					    q, "last fragmentation");
20729 					ip_wput_ire_fragmentit(mp, ire);
20730 					ire_refrele(ire);
20731 					if (conn_outgoing_ill != NULL)
20732 						ill_refrele(conn_outgoing_ill);
20733 					return;
20734 				}
20735 				ip_wput_ire_fragmentit(mp, ire);
20736 			}
20737 		}
20738 	} else {
20739 	    nullstq:
20740 		/* A NULL stq means the destination address is local. */
20741 		UPDATE_OB_PKT_COUNT(ire);
20742 		ire->ire_last_used_time = lbolt;
20743 		ASSERT(ire->ire_ipif != NULL);
20744 		if (!next_mp) {
20745 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20746 			    "ip_wput_ire_end: q %p (%S)",
20747 			    q, "local address");
20748 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20749 			    first_mp, ire, 0, ire->ire_zoneid);
20750 			ire_refrele(ire);
20751 			if (conn_outgoing_ill != NULL)
20752 				ill_refrele(conn_outgoing_ill);
20753 			return;
20754 		}
20755 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20756 		    ire, 0, ire->ire_zoneid);
20757 	}
20758 next:
20759 	/*
20760 	 * More copies going out to additional interfaces.
20761 	 * ire1 has already been held. We don't need the
20762 	 * "ire" anymore.
20763 	 */
20764 	ire_refrele(ire);
20765 	ire = ire1;
20766 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20767 	mp = next_mp;
20768 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20769 	ill = ire_to_ill(ire);
20770 	first_mp = mp;
20771 	if (ipsec_len != 0) {
20772 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20773 		mp = mp->b_cont;
20774 	}
20775 	dst = ire->ire_addr;
20776 	ipha = (ipha_t *)mp->b_rptr;
20777 	/*
20778 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20779 	 * Restore ipha_ident "no checksum" flag.
20780 	 */
20781 	src = orig_src;
20782 	ipha->ipha_ident = ip_hdr_included;
20783 	goto another;
20784 
20785 #undef	rptr
20786 #undef	Q_TO_INDEX
20787 }
20788 
20789 /*
20790  * Routine to allocate a message that is used to notify the ULP about MDT.
20791  * The caller may provide a pointer to the link-layer MDT capabilities,
20792  * or NULL if MDT is to be disabled on the stream.
20793  */
20794 mblk_t *
20795 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20796 {
20797 	mblk_t *mp;
20798 	ip_mdt_info_t *mdti;
20799 	ill_mdt_capab_t *idst;
20800 
20801 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20802 		DB_TYPE(mp) = M_CTL;
20803 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20804 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20805 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20806 		idst = &(mdti->mdt_capab);
20807 
20808 		/*
20809 		 * If the caller provides us with the capability, copy
20810 		 * it over into our notification message; otherwise
20811 		 * we zero out the capability portion.
20812 		 */
20813 		if (isrc != NULL)
20814 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20815 		else
20816 			bzero((caddr_t)idst, sizeof (*idst));
20817 	}
20818 	return (mp);
20819 }
20820 
20821 /*
20822  * Routine which determines whether MDT can be enabled on the destination
20823  * IRE and IPC combination, and if so, allocates and returns the MDT
20824  * notification mblk that may be used by ULP.  We also check if we need to
20825  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
20826  * MDT usage in the past have been lifted.  This gets called during IP
20827  * and ULP binding.
20828  */
20829 mblk_t *
20830 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
20831     ill_mdt_capab_t *mdt_cap)
20832 {
20833 	mblk_t *mp;
20834 	boolean_t rc = B_FALSE;
20835 
20836 	ASSERT(dst_ire != NULL);
20837 	ASSERT(connp != NULL);
20838 	ASSERT(mdt_cap != NULL);
20839 
20840 	/*
20841 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
20842 	 * Multidata, which is handled in tcp_multisend().  This
20843 	 * is the reason why we do all these checks here, to ensure
20844 	 * that we don't enable Multidata for the cases which we
20845 	 * can't handle at the moment.
20846 	 */
20847 	do {
20848 		/* Only do TCP at the moment */
20849 		if (connp->conn_ulp != IPPROTO_TCP)
20850 			break;
20851 
20852 		/*
20853 		 * IPSEC outbound policy present?  Note that we get here
20854 		 * after calling ipsec_conn_cache_policy() where the global
20855 		 * policy checking is performed.  conn_latch will be
20856 		 * non-NULL as long as there's a policy defined,
20857 		 * i.e. conn_out_enforce_policy may be NULL in such case
20858 		 * when the connection is non-secure, and hence we check
20859 		 * further if the latch refers to an outbound policy.
20860 		 */
20861 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
20862 			break;
20863 
20864 		/* CGTP (multiroute) is enabled? */
20865 		if (dst_ire->ire_flags & RTF_MULTIRT)
20866 			break;
20867 
20868 		/* Outbound IPQoS enabled? */
20869 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20870 			/*
20871 			 * In this case, we disable MDT for this and all
20872 			 * future connections going over the interface.
20873 			 */
20874 			mdt_cap->ill_mdt_on = 0;
20875 			break;
20876 		}
20877 
20878 		/* socket option(s) present? */
20879 		if (!CONN_IS_MD_FASTPATH(connp))
20880 			break;
20881 
20882 		rc = B_TRUE;
20883 	/* CONSTCOND */
20884 	} while (0);
20885 
20886 	/* Remember the result */
20887 	connp->conn_mdt_ok = rc;
20888 
20889 	if (!rc)
20890 		return (NULL);
20891 	else if (!mdt_cap->ill_mdt_on) {
20892 		/*
20893 		 * If MDT has been previously turned off in the past, and we
20894 		 * currently can do MDT (due to IPQoS policy removal, etc.)
20895 		 * then enable it for this interface.
20896 		 */
20897 		mdt_cap->ill_mdt_on = 1;
20898 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
20899 		    "interface %s\n", ill_name));
20900 	}
20901 
20902 	/* Allocate the MDT info mblk */
20903 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
20904 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
20905 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
20906 		return (NULL);
20907 	}
20908 	return (mp);
20909 }
20910 
20911 /*
20912  * Create destination address attribute, and fill it with the physical
20913  * destination address and SAP taken from the template DL_UNITDATA_REQ
20914  * message block.
20915  */
20916 boolean_t
20917 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
20918 {
20919 	dl_unitdata_req_t *dlurp;
20920 	pattr_t *pa;
20921 	pattrinfo_t pa_info;
20922 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
20923 	uint_t das_len, das_off;
20924 
20925 	ASSERT(dlmp != NULL);
20926 
20927 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
20928 	das_len = dlurp->dl_dest_addr_length;
20929 	das_off = dlurp->dl_dest_addr_offset;
20930 
20931 	pa_info.type = PATTR_DSTADDRSAP;
20932 	pa_info.len = sizeof (**das) + das_len - 1;
20933 
20934 	/* create and associate the attribute */
20935 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20936 	if (pa != NULL) {
20937 		ASSERT(*das != NULL);
20938 		(*das)->addr_is_group = 0;
20939 		(*das)->addr_len = (uint8_t)das_len;
20940 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
20941 	}
20942 
20943 	return (pa != NULL);
20944 }
20945 
20946 /*
20947  * Create hardware checksum attribute and fill it with the values passed.
20948  */
20949 boolean_t
20950 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
20951     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
20952 {
20953 	pattr_t *pa;
20954 	pattrinfo_t pa_info;
20955 
20956 	ASSERT(mmd != NULL);
20957 
20958 	pa_info.type = PATTR_HCKSUM;
20959 	pa_info.len = sizeof (pattr_hcksum_t);
20960 
20961 	/* create and associate the attribute */
20962 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20963 	if (pa != NULL) {
20964 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
20965 
20966 		hck->hcksum_start_offset = start_offset;
20967 		hck->hcksum_stuff_offset = stuff_offset;
20968 		hck->hcksum_end_offset = end_offset;
20969 		hck->hcksum_flags = flags;
20970 	}
20971 	return (pa != NULL);
20972 }
20973 
20974 /*
20975  * Create zerocopy attribute and fill it with the specified flags
20976  */
20977 boolean_t
20978 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
20979 {
20980 	pattr_t *pa;
20981 	pattrinfo_t pa_info;
20982 
20983 	ASSERT(mmd != NULL);
20984 	pa_info.type = PATTR_ZCOPY;
20985 	pa_info.len = sizeof (pattr_zcopy_t);
20986 
20987 	/* create and associate the attribute */
20988 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20989 	if (pa != NULL) {
20990 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
20991 
20992 		zcopy->zcopy_flags = flags;
20993 	}
20994 	return (pa != NULL);
20995 }
20996 
20997 /*
20998  * Outbound IP fragmentation routine.
20999  *
21000  * NOTE : This routine does not ire_refrele the ire that is passed in
21001  * as the argument.
21002  */
21003 static void
21004 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21005     uint32_t frag_flag)
21006 {
21007 	int	i1;
21008 	mblk_t	*ll_hdr_mp;
21009 	int 	ll_hdr_len;
21010 	int	hdr_len;
21011 	mblk_t	*hdr_mp;
21012 	ipha_t	*ipha;
21013 	int	ip_data_end;
21014 	int	len;
21015 	mblk_t	*mp = mp_orig;
21016 	int	offset;
21017 	queue_t	*q;
21018 	uint32_t	v_hlen_tos_len;
21019 	mblk_t	*first_mp;
21020 	boolean_t mctl_present;
21021 	mblk_t	*xmit_mp;
21022 	mblk_t	*carve_mp;
21023 	ire_t   *ire1 = NULL;
21024 	ire_t   *save_ire = NULL;
21025 	mblk_t  *next_mp = NULL;
21026 	boolean_t last_frag = B_FALSE;
21027 	boolean_t multirt_send = B_FALSE;
21028 	ire_t *first_ire = NULL;
21029 	irb_t *irb = NULL;
21030 
21031 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21032 	    "ip_wput_frag_start:");
21033 
21034 	if (mp->b_datap->db_type == M_CTL) {
21035 		first_mp = mp;
21036 		mp_orig = mp = mp->b_cont;
21037 		mctl_present = B_TRUE;
21038 	} else {
21039 		first_mp = mp;
21040 		mctl_present = B_FALSE;
21041 	}
21042 
21043 	ipha = (ipha_t *)mp->b_rptr;
21044 
21045 	/*
21046 	 * If the Don't Fragment flag is on, generate an ICMP destination
21047 	 * unreachable, fragmentation needed.
21048 	 */
21049 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21050 	if (offset & IPH_DF) {
21051 		BUMP_MIB(&ip_mib, ipFragFails);
21052 		/*
21053 		 * Need to compute hdr checksum if called from ip_wput_ire.
21054 		 * Note that ip_rput_forward verifies the checksum before
21055 		 * calling this routine so in that case this is a noop.
21056 		 */
21057 		ipha->ipha_hdr_checksum = 0;
21058 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21059 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21060 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21061 		    "ip_wput_frag_end:(%S)",
21062 		    "don't fragment");
21063 		return;
21064 	}
21065 	if (mctl_present)
21066 		freeb(first_mp);
21067 	/*
21068 	 * Establish the starting offset.  May not be zero if we are fragging
21069 	 * a fragment that is being forwarded.
21070 	 */
21071 	offset = offset & IPH_OFFSET;
21072 
21073 	/* TODO why is this test needed? */
21074 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21075 	if (((max_frag - LENGTH) & ~7) < 8) {
21076 		/* TODO: notify ulp somehow */
21077 		BUMP_MIB(&ip_mib, ipFragFails);
21078 		freemsg(mp);
21079 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21080 		    "ip_wput_frag_end:(%S)",
21081 		    "len < 8");
21082 		return;
21083 	}
21084 
21085 	hdr_len = (V_HLEN & 0xF) << 2;
21086 	ipha->ipha_hdr_checksum = 0;
21087 
21088 	/* Get a copy of the header for the trailing frags */
21089 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21090 	if (!hdr_mp) {
21091 		BUMP_MIB(&ip_mib, ipOutDiscards);
21092 		freemsg(mp);
21093 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21094 		    "ip_wput_frag_end:(%S)",
21095 		    "couldn't copy hdr");
21096 		return;
21097 	}
21098 
21099 	/* Store the starting offset, with the MoreFrags flag. */
21100 	i1 = offset | IPH_MF | frag_flag;
21101 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21102 
21103 	/* Establish the ending byte offset, based on the starting offset. */
21104 	offset <<= 3;
21105 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21106 
21107 	/*
21108 	 * Establish the number of bytes maximum per frag, after putting
21109 	 * in the header.
21110 	 */
21111 	len = (max_frag - hdr_len) & ~7;
21112 
21113 	/* Store the length of the first fragment in the IP header. */
21114 	i1 = len + hdr_len;
21115 	ASSERT(i1 <= IP_MAXPACKET);
21116 	ipha->ipha_length = htons((uint16_t)i1);
21117 
21118 	/*
21119 	 * Compute the IP header checksum for the first frag.  We have to
21120 	 * watch out that we stop at the end of the header.
21121 	 */
21122 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21123 
21124 	/*
21125 	 * Now carve off the first frag.  Note that this will include the
21126 	 * original IP header.
21127 	 */
21128 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21129 		BUMP_MIB(&ip_mib, ipOutDiscards);
21130 		freeb(hdr_mp);
21131 		freemsg(mp_orig);
21132 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21133 		    "ip_wput_frag_end:(%S)",
21134 		    "couldn't carve first");
21135 		return;
21136 	}
21137 
21138 	/*
21139 	 * Multirouting case. Each fragment is replicated
21140 	 * via all non-condemned RTF_MULTIRT routes
21141 	 * currently resolved.
21142 	 * We ensure that first_ire is the first RTF_MULTIRT
21143 	 * ire in the bucket.
21144 	 */
21145 	if (ire->ire_flags & RTF_MULTIRT) {
21146 		irb = ire->ire_bucket;
21147 		ASSERT(irb != NULL);
21148 
21149 		multirt_send = B_TRUE;
21150 
21151 		/* Make sure we do not omit any multiroute ire. */
21152 		IRB_REFHOLD(irb);
21153 		for (first_ire = irb->irb_ire;
21154 		    first_ire != NULL;
21155 		    first_ire = first_ire->ire_next) {
21156 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21157 			    (first_ire->ire_addr == ire->ire_addr) &&
21158 			    !(first_ire->ire_marks &
21159 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21160 				break;
21161 		}
21162 
21163 		if (first_ire != NULL) {
21164 			if (first_ire != ire) {
21165 				IRE_REFHOLD(first_ire);
21166 				/*
21167 				 * Do not release the ire passed in
21168 				 * as the argument.
21169 				 */
21170 				ire = first_ire;
21171 			} else {
21172 				first_ire = NULL;
21173 			}
21174 		}
21175 		IRB_REFRELE(irb);
21176 
21177 		/*
21178 		 * Save the first ire; we will need to restore it
21179 		 * for the trailing frags.
21180 		 * We REFHOLD save_ire, as each iterated ire will be
21181 		 * REFRELEd.
21182 		 */
21183 		save_ire = ire;
21184 		IRE_REFHOLD(save_ire);
21185 	}
21186 
21187 	/*
21188 	 * First fragment emission loop.
21189 	 * In most cases, the emission loop below is entered only
21190 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21191 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21192 	 * bucket, and send the fragment through all crossed
21193 	 * RTF_MULTIRT routes.
21194 	 */
21195 	do {
21196 		if (ire->ire_flags & RTF_MULTIRT) {
21197 			/*
21198 			 * We are in a multiple send case, need to get
21199 			 * the next ire and make a copy of the packet.
21200 			 * ire1 holds here the next ire to process in the
21201 			 * bucket. If multirouting is expected,
21202 			 * any non-RTF_MULTIRT ire that has the
21203 			 * right destination address is ignored.
21204 			 *
21205 			 * We have to take into account the MTU of
21206 			 * each walked ire. max_frag is set by the
21207 			 * the caller and generally refers to
21208 			 * the primary ire entry. Here we ensure that
21209 			 * no route with a lower MTU will be used, as
21210 			 * fragments are carved once for all ires,
21211 			 * then replicated.
21212 			 */
21213 			ASSERT(irb != NULL);
21214 			IRB_REFHOLD(irb);
21215 			for (ire1 = ire->ire_next;
21216 			    ire1 != NULL;
21217 			    ire1 = ire1->ire_next) {
21218 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21219 					continue;
21220 				if (ire1->ire_addr != ire->ire_addr)
21221 					continue;
21222 				if (ire1->ire_marks &
21223 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21224 					continue;
21225 				/*
21226 				 * Ensure we do not exceed the MTU
21227 				 * of the next route.
21228 				 */
21229 				if (ire1->ire_max_frag < max_frag) {
21230 					ip_multirt_bad_mtu(ire1, max_frag);
21231 					continue;
21232 				}
21233 
21234 				/* Got one. */
21235 				IRE_REFHOLD(ire1);
21236 				break;
21237 			}
21238 			IRB_REFRELE(irb);
21239 
21240 			if (ire1 != NULL) {
21241 				next_mp = copyb(mp);
21242 				if ((next_mp == NULL) ||
21243 				    ((mp->b_cont != NULL) &&
21244 				    ((next_mp->b_cont =
21245 				    dupmsg(mp->b_cont)) == NULL))) {
21246 					freemsg(next_mp);
21247 					next_mp = NULL;
21248 					ire_refrele(ire1);
21249 					ire1 = NULL;
21250 				}
21251 			}
21252 
21253 			/* Last multiroute ire; don't loop anymore. */
21254 			if (ire1 == NULL) {
21255 				multirt_send = B_FALSE;
21256 			}
21257 		}
21258 
21259 		ll_hdr_len = 0;
21260 		LOCK_IRE_FP_MP(ire);
21261 		ll_hdr_mp = ire->ire_fp_mp;
21262 		if (ll_hdr_mp != NULL) {
21263 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21264 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21265 		} else {
21266 			ll_hdr_mp = ire->ire_dlureq_mp;
21267 		}
21268 
21269 		/* If there is a transmit header, get a copy for this frag. */
21270 		/*
21271 		 * TODO: should check db_ref before calling ip_carve_mp since
21272 		 * it might give us a dup.
21273 		 */
21274 		if (!ll_hdr_mp) {
21275 			/* No xmit header. */
21276 			xmit_mp = mp;
21277 		} else if (mp->b_datap->db_ref == 1 &&
21278 		    ll_hdr_len != 0 &&
21279 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21280 			/* M_DATA fastpath */
21281 			mp->b_rptr -= ll_hdr_len;
21282 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21283 			xmit_mp = mp;
21284 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21285 			UNLOCK_IRE_FP_MP(ire);
21286 			BUMP_MIB(&ip_mib, ipOutDiscards);
21287 			freeb(hdr_mp);
21288 			freemsg(mp);
21289 			freemsg(mp_orig);
21290 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21291 			    "ip_wput_frag_end:(%S)",
21292 			    "discard");
21293 
21294 			if (multirt_send) {
21295 				ASSERT(ire1);
21296 				ASSERT(next_mp);
21297 
21298 				freemsg(next_mp);
21299 				ire_refrele(ire1);
21300 			}
21301 			if (save_ire != NULL)
21302 				IRE_REFRELE(save_ire);
21303 
21304 			if (first_ire != NULL)
21305 				ire_refrele(first_ire);
21306 			return;
21307 		} else {
21308 			xmit_mp->b_cont = mp;
21309 			/* Get priority marking, if any. */
21310 			if (DB_TYPE(xmit_mp) == M_DATA)
21311 				xmit_mp->b_band = mp->b_band;
21312 		}
21313 		UNLOCK_IRE_FP_MP(ire);
21314 		q = ire->ire_stq;
21315 		BUMP_MIB(&ip_mib, ipFragCreates);
21316 		putnext(q, xmit_mp);
21317 		if (pkt_type != OB_PKT) {
21318 			/*
21319 			 * Update the packet count of trailing
21320 			 * RTF_MULTIRT ires.
21321 			 */
21322 			UPDATE_OB_PKT_COUNT(ire);
21323 		}
21324 
21325 		if (multirt_send) {
21326 			/*
21327 			 * We are in a multiple send case; look for
21328 			 * the next ire and re-enter the loop.
21329 			 */
21330 			ASSERT(ire1);
21331 			ASSERT(next_mp);
21332 			/* REFRELE the current ire before looping */
21333 			ire_refrele(ire);
21334 			ire = ire1;
21335 			ire1 = NULL;
21336 			mp = next_mp;
21337 			next_mp = NULL;
21338 		}
21339 	} while (multirt_send);
21340 
21341 	ASSERT(ire1 == NULL);
21342 
21343 	/* Restore the original ire; we need it for the trailing frags */
21344 	if (save_ire != NULL) {
21345 		/* REFRELE the last iterated ire */
21346 		ire_refrele(ire);
21347 		/* save_ire has been REFHOLDed */
21348 		ire = save_ire;
21349 		save_ire = NULL;
21350 		q = ire->ire_stq;
21351 	}
21352 
21353 	if (pkt_type == OB_PKT) {
21354 		UPDATE_OB_PKT_COUNT(ire);
21355 	} else {
21356 		UPDATE_IB_PKT_COUNT(ire);
21357 	}
21358 
21359 	/* Advance the offset to the second frag starting point. */
21360 	offset += len;
21361 	/*
21362 	 * Update hdr_len from the copied header - there might be less options
21363 	 * in the later fragments.
21364 	 */
21365 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21366 	/* Loop until done. */
21367 	for (;;) {
21368 		uint16_t	offset_and_flags;
21369 		uint16_t	ip_len;
21370 
21371 		if (ip_data_end - offset > len) {
21372 			/*
21373 			 * Carve off the appropriate amount from the original
21374 			 * datagram.
21375 			 */
21376 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21377 				mp = NULL;
21378 				break;
21379 			}
21380 			/*
21381 			 * More frags after this one.  Get another copy
21382 			 * of the header.
21383 			 */
21384 			if (carve_mp->b_datap->db_ref == 1 &&
21385 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21386 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21387 				/* Inline IP header */
21388 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21389 				    hdr_mp->b_rptr;
21390 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21391 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21392 				mp = carve_mp;
21393 			} else {
21394 				if (!(mp = copyb(hdr_mp))) {
21395 					freemsg(carve_mp);
21396 					break;
21397 				}
21398 				/* Get priority marking, if any. */
21399 				mp->b_band = carve_mp->b_band;
21400 				mp->b_cont = carve_mp;
21401 			}
21402 			ipha = (ipha_t *)mp->b_rptr;
21403 			offset_and_flags = IPH_MF;
21404 		} else {
21405 			/*
21406 			 * Last frag.  Consume the header. Set len to
21407 			 * the length of this last piece.
21408 			 */
21409 			len = ip_data_end - offset;
21410 
21411 			/*
21412 			 * Carve off the appropriate amount from the original
21413 			 * datagram.
21414 			 */
21415 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21416 				mp = NULL;
21417 				break;
21418 			}
21419 			if (carve_mp->b_datap->db_ref == 1 &&
21420 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21421 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21422 				/* Inline IP header */
21423 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21424 				    hdr_mp->b_rptr;
21425 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21426 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21427 				mp = carve_mp;
21428 				freeb(hdr_mp);
21429 				hdr_mp = mp;
21430 			} else {
21431 				mp = hdr_mp;
21432 				/* Get priority marking, if any. */
21433 				mp->b_band = carve_mp->b_band;
21434 				mp->b_cont = carve_mp;
21435 			}
21436 			ipha = (ipha_t *)mp->b_rptr;
21437 			/* A frag of a frag might have IPH_MF non-zero */
21438 			offset_and_flags =
21439 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21440 			    IPH_MF;
21441 		}
21442 		offset_and_flags |= (uint16_t)(offset >> 3);
21443 		offset_and_flags |= (uint16_t)frag_flag;
21444 		/* Store the offset and flags in the IP header. */
21445 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21446 
21447 		/* Store the length in the IP header. */
21448 		ip_len = (uint16_t)(len + hdr_len);
21449 		ipha->ipha_length = htons(ip_len);
21450 
21451 		/*
21452 		 * Set the IP header checksum.	Note that mp is just
21453 		 * the header, so this is easy to pass to ip_csum.
21454 		 */
21455 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21456 
21457 		/* Attach a transmit header, if any, and ship it. */
21458 		if (pkt_type == OB_PKT) {
21459 			UPDATE_OB_PKT_COUNT(ire);
21460 		} else {
21461 			UPDATE_IB_PKT_COUNT(ire);
21462 		}
21463 
21464 		if (ire->ire_flags & RTF_MULTIRT) {
21465 			irb = ire->ire_bucket;
21466 			ASSERT(irb != NULL);
21467 
21468 			multirt_send = B_TRUE;
21469 
21470 			/*
21471 			 * Save the original ire; we will need to restore it
21472 			 * for the tailing frags.
21473 			 */
21474 			save_ire = ire;
21475 			IRE_REFHOLD(save_ire);
21476 		}
21477 		/*
21478 		 * Emission loop for this fragment, similar
21479 		 * to what is done for the first fragment.
21480 		 */
21481 		do {
21482 			if (multirt_send) {
21483 				/*
21484 				 * We are in a multiple send case, need to get
21485 				 * the next ire and make a copy of the packet.
21486 				 */
21487 				ASSERT(irb != NULL);
21488 				IRB_REFHOLD(irb);
21489 				for (ire1 = ire->ire_next;
21490 				    ire1 != NULL;
21491 				    ire1 = ire1->ire_next) {
21492 					if (!(ire1->ire_flags & RTF_MULTIRT))
21493 						continue;
21494 					if (ire1->ire_addr != ire->ire_addr)
21495 						continue;
21496 					if (ire1->ire_marks &
21497 					    (IRE_MARK_CONDEMNED|
21498 						IRE_MARK_HIDDEN))
21499 						continue;
21500 					/*
21501 					 * Ensure we do not exceed the MTU
21502 					 * of the next route.
21503 					 */
21504 					if (ire1->ire_max_frag < max_frag) {
21505 						ip_multirt_bad_mtu(ire1,
21506 						    max_frag);
21507 						continue;
21508 					}
21509 
21510 					/* Got one. */
21511 					IRE_REFHOLD(ire1);
21512 					break;
21513 				}
21514 				IRB_REFRELE(irb);
21515 
21516 				if (ire1 != NULL) {
21517 					next_mp = copyb(mp);
21518 					if ((next_mp == NULL) ||
21519 					    ((mp->b_cont != NULL) &&
21520 					    ((next_mp->b_cont =
21521 					    dupmsg(mp->b_cont)) == NULL))) {
21522 						freemsg(next_mp);
21523 						next_mp = NULL;
21524 						ire_refrele(ire1);
21525 						ire1 = NULL;
21526 					}
21527 				}
21528 
21529 				/* Last multiroute ire; don't loop anymore. */
21530 				if (ire1 == NULL) {
21531 					multirt_send = B_FALSE;
21532 				}
21533 			}
21534 
21535 			/* Update transmit header */
21536 			ll_hdr_len = 0;
21537 			LOCK_IRE_FP_MP(ire);
21538 			ll_hdr_mp = ire->ire_fp_mp;
21539 			if (ll_hdr_mp != NULL) {
21540 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21541 				ll_hdr_len = MBLKL(ll_hdr_mp);
21542 			} else {
21543 				ll_hdr_mp = ire->ire_dlureq_mp;
21544 			}
21545 
21546 			if (!ll_hdr_mp) {
21547 				xmit_mp = mp;
21548 			} else if (mp->b_datap->db_ref == 1 &&
21549 			    ll_hdr_len != 0 &&
21550 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21551 				/* M_DATA fastpath */
21552 				mp->b_rptr -= ll_hdr_len;
21553 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
21554 				    ll_hdr_len);
21555 				xmit_mp = mp;
21556 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
21557 				xmit_mp->b_cont = mp;
21558 				/* Get priority marking, if any. */
21559 				if (DB_TYPE(xmit_mp) == M_DATA)
21560 					xmit_mp->b_band = mp->b_band;
21561 			} else {
21562 				/*
21563 				 * Exit both the replication and
21564 				 * fragmentation loops.
21565 				 */
21566 				UNLOCK_IRE_FP_MP(ire);
21567 				goto drop_pkt;
21568 			}
21569 			UNLOCK_IRE_FP_MP(ire);
21570 			BUMP_MIB(&ip_mib, ipFragCreates);
21571 			putnext(q, xmit_mp);
21572 
21573 			if (pkt_type != OB_PKT) {
21574 				/*
21575 				 * Update the packet count of trailing
21576 				 * RTF_MULTIRT ires.
21577 				 */
21578 				UPDATE_OB_PKT_COUNT(ire);
21579 			}
21580 
21581 			/* All done if we just consumed the hdr_mp. */
21582 			if (mp == hdr_mp) {
21583 				last_frag = B_TRUE;
21584 			}
21585 
21586 			if (multirt_send) {
21587 				/*
21588 				 * We are in a multiple send case; look for
21589 				 * the next ire and re-enter the loop.
21590 				 */
21591 				ASSERT(ire1);
21592 				ASSERT(next_mp);
21593 				/* REFRELE the current ire before looping */
21594 				ire_refrele(ire);
21595 				ire = ire1;
21596 				ire1 = NULL;
21597 				q = ire->ire_stq;
21598 				mp = next_mp;
21599 				next_mp = NULL;
21600 			}
21601 		} while (multirt_send);
21602 		/*
21603 		 * Restore the original ire; we need it for the
21604 		 * trailing frags
21605 		 */
21606 		if (save_ire != NULL) {
21607 			ASSERT(ire1 == NULL);
21608 			/* REFRELE the last iterated ire */
21609 			ire_refrele(ire);
21610 			/* save_ire has been REFHOLDed */
21611 			ire = save_ire;
21612 			q = ire->ire_stq;
21613 			save_ire = NULL;
21614 		}
21615 
21616 		if (last_frag) {
21617 			BUMP_MIB(&ip_mib, ipFragOKs);
21618 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21619 			    "ip_wput_frag_end:(%S)",
21620 			    "consumed hdr_mp");
21621 
21622 			if (first_ire != NULL)
21623 				ire_refrele(first_ire);
21624 			return;
21625 		}
21626 		/* Otherwise, advance and loop. */
21627 		offset += len;
21628 	}
21629 
21630 drop_pkt:
21631 	/* Clean up following allocation failure. */
21632 	BUMP_MIB(&ip_mib, ipOutDiscards);
21633 	freemsg(mp);
21634 	if (mp != hdr_mp)
21635 		freeb(hdr_mp);
21636 	if (mp != mp_orig)
21637 		freemsg(mp_orig);
21638 
21639 	if (save_ire != NULL)
21640 		IRE_REFRELE(save_ire);
21641 	if (first_ire != NULL)
21642 		ire_refrele(first_ire);
21643 
21644 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21645 	    "ip_wput_frag_end:(%S)",
21646 	    "end--alloc failure");
21647 }
21648 
21649 /*
21650  * Copy the header plus those options which have the copy bit set
21651  */
21652 static mblk_t *
21653 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
21654 {
21655 	mblk_t	*mp;
21656 	uchar_t	*up;
21657 
21658 	/*
21659 	 * Quick check if we need to look for options without the copy bit
21660 	 * set
21661 	 */
21662 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
21663 	if (!mp)
21664 		return (mp);
21665 	mp->b_rptr += ip_wroff_extra;
21666 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
21667 		bcopy(rptr, mp->b_rptr, hdr_len);
21668 		mp->b_wptr += hdr_len + ip_wroff_extra;
21669 		return (mp);
21670 	}
21671 	up  = mp->b_rptr;
21672 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
21673 	up += IP_SIMPLE_HDR_LENGTH;
21674 	rptr += IP_SIMPLE_HDR_LENGTH;
21675 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
21676 	while (hdr_len > 0) {
21677 		uint32_t optval;
21678 		uint32_t optlen;
21679 
21680 		optval = *rptr;
21681 		if (optval == IPOPT_EOL)
21682 			break;
21683 		if (optval == IPOPT_NOP)
21684 			optlen = 1;
21685 		else
21686 			optlen = rptr[1];
21687 		if (optval & IPOPT_COPY) {
21688 			bcopy(rptr, up, optlen);
21689 			up += optlen;
21690 		}
21691 		rptr += optlen;
21692 		hdr_len -= optlen;
21693 	}
21694 	/*
21695 	 * Make sure that we drop an even number of words by filling
21696 	 * with EOL to the next word boundary.
21697 	 */
21698 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
21699 	    hdr_len & 0x3; hdr_len++)
21700 		*up++ = IPOPT_EOL;
21701 	mp->b_wptr = up;
21702 	/* Update header length */
21703 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
21704 	return (mp);
21705 }
21706 
21707 /*
21708  * Delivery to local recipients including fanout to multiple recipients.
21709  * Does not do checksumming of UDP/TCP.
21710  * Note: q should be the read side queue for either the ill or conn.
21711  * Note: rq should be the read side q for the lower (ill) stream.
21712  * We don't send packets to IPPF processing, thus the last argument
21713  * to all the fanout calls are B_FALSE.
21714  */
21715 void
21716 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
21717     int fanout_flags, zoneid_t zoneid)
21718 {
21719 	uint32_t	protocol;
21720 	mblk_t		*first_mp;
21721 	boolean_t	mctl_present;
21722 	int		ire_type;
21723 #define	rptr	((uchar_t *)ipha)
21724 
21725 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
21726 	    "ip_wput_local_start: q %p", q);
21727 
21728 	if (ire != NULL) {
21729 		ire_type = ire->ire_type;
21730 	} else {
21731 		/*
21732 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
21733 		 * packet is not multicast, we can't tell the ire type.
21734 		 */
21735 		ASSERT(CLASSD(ipha->ipha_dst));
21736 		ire_type = IRE_BROADCAST;
21737 	}
21738 
21739 	first_mp = mp;
21740 	if (first_mp->b_datap->db_type == M_CTL) {
21741 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
21742 		if (!io->ipsec_out_secure) {
21743 			/*
21744 			 * This ipsec_out_t was allocated in ip_wput
21745 			 * for multicast packets to store the ill_index.
21746 			 * As this is being delivered locally, we don't
21747 			 * need this anymore.
21748 			 */
21749 			mp = first_mp->b_cont;
21750 			freeb(first_mp);
21751 			first_mp = mp;
21752 			mctl_present = B_FALSE;
21753 		} else {
21754 			mctl_present = B_TRUE;
21755 			mp = first_mp->b_cont;
21756 			ASSERT(mp != NULL);
21757 			ipsec_out_to_in(first_mp);
21758 		}
21759 	} else {
21760 		mctl_present = B_FALSE;
21761 	}
21762 
21763 	loopback_packets++;
21764 
21765 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
21766 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
21767 	if (!IS_SIMPLE_IPH(ipha)) {
21768 		ip_wput_local_options(ipha);
21769 	}
21770 
21771 	protocol = ipha->ipha_protocol;
21772 	switch (protocol) {
21773 	case IPPROTO_ICMP: {
21774 		ire_t		*ire_zone;
21775 		ilm_t		*ilm;
21776 		mblk_t		*mp1;
21777 		zoneid_t	last_zoneid;
21778 
21779 		if (CLASSD(ipha->ipha_dst) &&
21780 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
21781 			ASSERT(ire_type == IRE_BROADCAST);
21782 			/*
21783 			 * In the multicast case, applications may have joined
21784 			 * the group from different zones, so we need to deliver
21785 			 * the packet to each of them. Loop through the
21786 			 * multicast memberships structures (ilm) on the receive
21787 			 * ill and send a copy of the packet up each matching
21788 			 * one. However, we don't do this for multicasts sent on
21789 			 * the loopback interface (PHYI_LOOPBACK flag set) as
21790 			 * they must stay in the sender's zone.
21791 			 *
21792 			 * ilm_add_v6() ensures that ilms in the same zone are
21793 			 * contiguous in the ill_ilm list. We use this property
21794 			 * to avoid sending duplicates needed when two
21795 			 * applications in the same zone join the same group on
21796 			 * different logical interfaces: we ignore the ilm if
21797 			 * its zoneid is the same as the last matching one.
21798 			 * In addition, the sending of the packet for
21799 			 * ire_zoneid is delayed until all of the other ilms
21800 			 * have been exhausted.
21801 			 */
21802 			last_zoneid = -1;
21803 			ILM_WALKER_HOLD(ill);
21804 			for (ilm = ill->ill_ilm; ilm != NULL;
21805 			    ilm = ilm->ilm_next) {
21806 				if ((ilm->ilm_flags & ILM_DELETED) ||
21807 				    ipha->ipha_dst != ilm->ilm_addr ||
21808 				    ilm->ilm_zoneid == last_zoneid ||
21809 				    ilm->ilm_zoneid == zoneid ||
21810 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
21811 					continue;
21812 				mp1 = ip_copymsg(first_mp);
21813 				if (mp1 == NULL)
21814 					continue;
21815 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21816 				    mctl_present, B_FALSE, ill,
21817 				    ilm->ilm_zoneid);
21818 				last_zoneid = ilm->ilm_zoneid;
21819 			}
21820 			ILM_WALKER_RELE(ill);
21821 			/*
21822 			 * Loopback case: the sending endpoint has
21823 			 * IP_MULTICAST_LOOP disabled, therefore we don't
21824 			 * dispatch the multicast packet to the sending zone.
21825 			 */
21826 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
21827 				freemsg(first_mp);
21828 				return;
21829 			}
21830 		} else if (ire_type == IRE_BROADCAST) {
21831 			/*
21832 			 * In the broadcast case, there may be many zones
21833 			 * which need a copy of the packet delivered to them.
21834 			 * There is one IRE_BROADCAST per broadcast address
21835 			 * and per zone; we walk those using a helper function.
21836 			 * In addition, the sending of the packet for zoneid is
21837 			 * delayed until all of the other ires have been
21838 			 * processed.
21839 			 */
21840 			IRB_REFHOLD(ire->ire_bucket);
21841 			ire_zone = NULL;
21842 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
21843 			    ire)) != NULL) {
21844 				mp1 = ip_copymsg(first_mp);
21845 				if (mp1 == NULL)
21846 					continue;
21847 
21848 				UPDATE_IB_PKT_COUNT(ire_zone);
21849 				ire_zone->ire_last_used_time = lbolt;
21850 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21851 				    mctl_present, B_FALSE, ill,
21852 				    ire_zone->ire_zoneid);
21853 			}
21854 			IRB_REFRELE(ire->ire_bucket);
21855 		}
21856 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
21857 		    0, mctl_present, B_FALSE, ill, zoneid);
21858 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21859 		    "ip_wput_local_end: q %p (%S)",
21860 		    q, "icmp");
21861 		return;
21862 	}
21863 	case IPPROTO_IGMP:
21864 		if (igmp_input(q, mp, ill)) {
21865 			/* Bad packet - discarded by igmp_input */
21866 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21867 			    "ip_wput_local_end: q %p (%S)",
21868 			    q, "igmp_input--bad packet");
21869 			if (mctl_present)
21870 				freeb(first_mp);
21871 			return;
21872 		}
21873 		/*
21874 		 * igmp_input() may have pulled up the message so ipha needs to
21875 		 * be reinitialized.
21876 		 */
21877 		ipha = (ipha_t *)mp->b_rptr;
21878 		/* deliver to local raw users */
21879 		break;
21880 	case IPPROTO_ENCAP:
21881 		/*
21882 		 * This case is covered by either ip_fanout_proto, or by
21883 		 * the above security processing for self-tunneled packets.
21884 		 */
21885 		break;
21886 	case IPPROTO_UDP: {
21887 		uint16_t	*up;
21888 		uint32_t	ports;
21889 
21890 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
21891 		    UDP_PORTS_OFFSET);
21892 		/* Force a 'valid' checksum. */
21893 		up[3] = 0;
21894 
21895 		ports = *(uint32_t *)up;
21896 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
21897 		    (ire_type == IRE_BROADCAST),
21898 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21899 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
21900 		    ill, zoneid);
21901 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21902 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
21903 		return;
21904 	}
21905 	case IPPROTO_TCP: {
21906 
21907 		/*
21908 		 * For TCP, discard broadcast packets.
21909 		 */
21910 		if ((ushort_t)ire_type == IRE_BROADCAST) {
21911 			freemsg(first_mp);
21912 			BUMP_MIB(&ip_mib, ipInDiscards);
21913 			return;
21914 		}
21915 
21916 		if (mp->b_datap->db_type == M_DATA) {
21917 			/*
21918 			 * M_DATA mblk, so init mblk (chain) for no struio().
21919 			 */
21920 			mblk_t	*mp1 = mp;
21921 
21922 			do
21923 				mp1->b_datap->db_struioflag = 0;
21924 			while ((mp1 = mp1->b_cont) != NULL);
21925 		}
21926 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
21927 		    <= mp->b_wptr);
21928 		ip_fanout_tcp(q, first_mp, ill, ipha,
21929 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21930 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
21931 		    mctl_present, B_FALSE, zoneid);
21932 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21933 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
21934 		return;
21935 	}
21936 	case IPPROTO_SCTP:
21937 	{
21938 		uint32_t	ports;
21939 
21940 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
21941 		ip_fanout_sctp(first_mp, ill, ipha, ports,
21942 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21943 		    IP_FF_IP6INFO,
21944 		    mctl_present, B_FALSE, 0, zoneid);
21945 		return;
21946 	}
21947 
21948 	default:
21949 		break;
21950 	}
21951 	/*
21952 	 * Find a client for some other protocol.  We give
21953 	 * copies to multiple clients, if more than one is
21954 	 * bound.
21955 	 */
21956 	ip_fanout_proto(q, first_mp, ill, ipha,
21957 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
21958 	    mctl_present, B_FALSE, ill, zoneid);
21959 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21960 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
21961 #undef	rptr
21962 }
21963 
21964 /*
21965  * Update any source route, record route, or timestamp options.
21966  * Check that we are at end of strict source route.
21967  * The options have been sanity checked by ip_wput_options().
21968  */
21969 static void
21970 ip_wput_local_options(ipha_t *ipha)
21971 {
21972 	ipoptp_t	opts;
21973 	uchar_t		*opt;
21974 	uint8_t		optval;
21975 	uint8_t		optlen;
21976 	ipaddr_t	dst;
21977 	uint32_t	ts;
21978 	ire_t		*ire;
21979 	timestruc_t	now;
21980 
21981 	ip2dbg(("ip_wput_local_options\n"));
21982 	for (optval = ipoptp_first(&opts, ipha);
21983 	    optval != IPOPT_EOL;
21984 	    optval = ipoptp_next(&opts)) {
21985 		opt = opts.ipoptp_cur;
21986 		optlen = opts.ipoptp_len;
21987 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21988 		switch (optval) {
21989 			uint32_t off;
21990 		case IPOPT_SSRR:
21991 		case IPOPT_LSRR:
21992 			off = opt[IPOPT_OFFSET];
21993 			off--;
21994 			if (optlen < IP_ADDR_LEN ||
21995 			    off > optlen - IP_ADDR_LEN) {
21996 				/* End of source route */
21997 				break;
21998 			}
21999 			/*
22000 			 * This will only happen if two consecutive entries
22001 			 * in the source route contains our address or if
22002 			 * it is a packet with a loose source route which
22003 			 * reaches us before consuming the whole source route
22004 			 */
22005 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22006 			if (optval == IPOPT_SSRR) {
22007 				return;
22008 			}
22009 			/*
22010 			 * Hack: instead of dropping the packet truncate the
22011 			 * source route to what has been used by filling the
22012 			 * rest with IPOPT_NOP.
22013 			 */
22014 			opt[IPOPT_OLEN] = (uint8_t)off;
22015 			while (off < optlen) {
22016 				opt[off++] = IPOPT_NOP;
22017 			}
22018 			break;
22019 		case IPOPT_RR:
22020 			off = opt[IPOPT_OFFSET];
22021 			off--;
22022 			if (optlen < IP_ADDR_LEN ||
22023 			    off > optlen - IP_ADDR_LEN) {
22024 				/* No more room - ignore */
22025 				ip1dbg((
22026 				    "ip_wput_forward_options: end of RR\n"));
22027 				break;
22028 			}
22029 			dst = htonl(INADDR_LOOPBACK);
22030 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22031 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22032 			break;
22033 		case IPOPT_TS:
22034 			/* Insert timestamp if there is romm */
22035 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22036 			case IPOPT_TS_TSONLY:
22037 				off = IPOPT_TS_TIMELEN;
22038 				break;
22039 			case IPOPT_TS_PRESPEC:
22040 			case IPOPT_TS_PRESPEC_RFC791:
22041 				/* Verify that the address matched */
22042 				off = opt[IPOPT_OFFSET] - 1;
22043 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22044 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22045 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22046 				if (ire == NULL) {
22047 					/* Not for us */
22048 					break;
22049 				}
22050 				ire_refrele(ire);
22051 				/* FALLTHRU */
22052 			case IPOPT_TS_TSANDADDR:
22053 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22054 				break;
22055 			default:
22056 				/*
22057 				 * ip_*put_options should have already
22058 				 * dropped this packet.
22059 				 */
22060 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22061 				    "unknown IT - bug in ip_wput_options?\n");
22062 				return;	/* Keep "lint" happy */
22063 			}
22064 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22065 				/* Increase overflow counter */
22066 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22067 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22068 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22069 				    (off << 4);
22070 				break;
22071 			}
22072 			off = opt[IPOPT_OFFSET] - 1;
22073 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22074 			case IPOPT_TS_PRESPEC:
22075 			case IPOPT_TS_PRESPEC_RFC791:
22076 			case IPOPT_TS_TSANDADDR:
22077 				dst = htonl(INADDR_LOOPBACK);
22078 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22079 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22080 				/* FALLTHRU */
22081 			case IPOPT_TS_TSONLY:
22082 				off = opt[IPOPT_OFFSET] - 1;
22083 				/* Compute # of milliseconds since midnight */
22084 				gethrestime(&now);
22085 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22086 				    now.tv_nsec / (NANOSEC / MILLISEC);
22087 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22088 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22089 				break;
22090 			}
22091 			break;
22092 		}
22093 	}
22094 }
22095 
22096 /*
22097  * Send out a multicast packet on interface ipif.
22098  * The sender does not have an conn.
22099  * Caller verifies that this isn't a PHYI_LOOPBACK.
22100  */
22101 void
22102 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22103 {
22104 	ipha_t	*ipha;
22105 	ire_t	*ire;
22106 	ipaddr_t	dst;
22107 	mblk_t		*first_mp;
22108 
22109 	/* igmp_sendpkt always allocates a ipsec_out_t */
22110 	ASSERT(mp->b_datap->db_type == M_CTL);
22111 	ASSERT(!ipif->ipif_isv6);
22112 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22113 
22114 	first_mp = mp;
22115 	mp = first_mp->b_cont;
22116 	ASSERT(mp->b_datap->db_type == M_DATA);
22117 	ipha = (ipha_t *)mp->b_rptr;
22118 
22119 	/*
22120 	 * Find an IRE which matches the destination and the outgoing
22121 	 * queue (i.e. the outgoing interface.)
22122 	 */
22123 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22124 		dst = ipif->ipif_pp_dst_addr;
22125 	else
22126 		dst = ipha->ipha_dst;
22127 	/*
22128 	 * The source address has already been initialized by the
22129 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22130 	 * be sufficient rather than MATCH_IRE_IPIF.
22131 	 *
22132 	 * This function is used for sending IGMP packets. We need
22133 	 * to make sure that we send the packet out of the interface
22134 	 * (ipif->ipif_ill) where we joined the group. This is to
22135 	 * prevent from switches doing IGMP snooping to send us multicast
22136 	 * packets for a given group on the interface we have joined.
22137 	 * If we can't find an ire, igmp_sendpkt has already initialized
22138 	 * ipsec_out_attach_if so that this will not be load spread in
22139 	 * ip_newroute_ipif.
22140 	 */
22141 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22142 	if (!ire) {
22143 		/*
22144 		 * Mark this packet to make it be delivered to
22145 		 * ip_wput_ire after the new ire has been
22146 		 * created.
22147 		 */
22148 		mp->b_prev = NULL;
22149 		mp->b_next = NULL;
22150 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22151 		return;
22152 	}
22153 
22154 	/*
22155 	 * Honor the RTF_SETSRC flag; this is the only case
22156 	 * where we force this addr whatever the current src addr is,
22157 	 * because this address is set by igmp_sendpkt(), and
22158 	 * cannot be specified by any user.
22159 	 */
22160 	if (ire->ire_flags & RTF_SETSRC) {
22161 		ipha->ipha_src = ire->ire_src_addr;
22162 	}
22163 
22164 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22165 }
22166 
22167 /*
22168  * NOTE : This function does not ire_refrele the ire argument passed in.
22169  *
22170  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22171  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22172  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22173  * the ire_lock to access the ire_fp_mp in this case.
22174  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22175  * prepending a fastpath message IPQoS processing must precede it, we also set
22176  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22177  * (IPQoS might have set the b_band for CoS marking).
22178  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22179  * must follow it so that IPQoS can mark the dl_priority field for CoS
22180  * marking, if needed.
22181  */
22182 static mblk_t *
22183 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22184 {
22185 	uint_t	hlen;
22186 	ipha_t *ipha;
22187 	mblk_t *mp1;
22188 	boolean_t qos_done = B_FALSE;
22189 	uchar_t	*ll_hdr;
22190 
22191 #define	rptr	((uchar_t *)ipha)
22192 
22193 	ipha = (ipha_t *)mp->b_rptr;
22194 	hlen = 0;
22195 	LOCK_IRE_FP_MP(ire);
22196 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22197 		ASSERT(DB_TYPE(mp1) == M_DATA);
22198 		/* Initiate IPPF processing */
22199 		if ((proc != 0) && IPP_ENABLED(proc)) {
22200 			UNLOCK_IRE_FP_MP(ire);
22201 			ip_process(proc, &mp, ill_index);
22202 			if (mp == NULL)
22203 				return (NULL);
22204 
22205 			ipha = (ipha_t *)mp->b_rptr;
22206 			LOCK_IRE_FP_MP(ire);
22207 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22208 				qos_done = B_TRUE;
22209 				goto no_fp_mp;
22210 			}
22211 			ASSERT(DB_TYPE(mp1) == M_DATA);
22212 		}
22213 		hlen = MBLKL(mp1);
22214 		/*
22215 		 * Check if we have enough room to prepend fastpath
22216 		 * header
22217 		 */
22218 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22219 			ll_hdr = rptr - hlen;
22220 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22221 			/* XXX ipha is not aligned here */
22222 			ipha = (ipha_t *)(rptr - hlen);
22223 			/*
22224 			 * Set the b_rptr to the start of the link layer
22225 			 * header
22226 			 */
22227 			mp->b_rptr = rptr;
22228 			mp1 = mp;
22229 		} else {
22230 			mp1 = copyb(mp1);
22231 			if (mp1 == NULL)
22232 				goto unlock_err;
22233 			mp1->b_band = mp->b_band;
22234 			mp1->b_cont = mp;
22235 			/*
22236 			 * XXX disable ICK_VALID and compute checksum
22237 			 * here; can happen if ire_fp_mp changes and
22238 			 * it can't be copied now due to insufficient
22239 			 * space. (unlikely, fp mp can change, but it
22240 			 * does not increase in length)
22241 			 */
22242 		}
22243 		UNLOCK_IRE_FP_MP(ire);
22244 	} else {
22245 no_fp_mp:
22246 		mp1 = copyb(ire->ire_dlureq_mp);
22247 		if (mp1 == NULL) {
22248 unlock_err:
22249 			UNLOCK_IRE_FP_MP(ire);
22250 			freemsg(mp);
22251 			return (NULL);
22252 		}
22253 		UNLOCK_IRE_FP_MP(ire);
22254 		mp1->b_cont = mp;
22255 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22256 			ip_process(proc, &mp1, ill_index);
22257 			if (mp1 == NULL)
22258 				return (NULL);
22259 		}
22260 	}
22261 	return (mp1);
22262 #undef rptr
22263 }
22264 
22265 /*
22266  * Finish the outbound IPsec processing for an IPv6 packet. This function
22267  * is called from ipsec_out_process() if the IPsec packet was processed
22268  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22269  * asynchronously.
22270  */
22271 void
22272 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22273     ire_t *ire_arg)
22274 {
22275 	in6_addr_t *v6dstp;
22276 	ire_t *ire;
22277 	mblk_t *mp;
22278 	uint_t	ill_index;
22279 	ipsec_out_t *io;
22280 	boolean_t attach_if, hwaccel;
22281 	uint32_t flags = IP6_NO_IPPOLICY;
22282 	int match_flags;
22283 	zoneid_t zoneid;
22284 	boolean_t ill_need_rele = B_FALSE;
22285 	boolean_t ire_need_rele = B_FALSE;
22286 
22287 	mp = ipsec_mp->b_cont;
22288 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22289 	ill_index = io->ipsec_out_ill_index;
22290 	if (io->ipsec_out_reachable) {
22291 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22292 	}
22293 	attach_if = io->ipsec_out_attach_if;
22294 	hwaccel = io->ipsec_out_accelerated;
22295 	zoneid = io->ipsec_out_zoneid;
22296 	ASSERT(zoneid != ALL_ZONES);
22297 	match_flags = MATCH_IRE_ILL_GROUP;
22298 	/* Multicast addresses should have non-zero ill_index. */
22299 	v6dstp = &ip6h->ip6_dst;
22300 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22301 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22302 	ASSERT(!attach_if || ill_index != 0);
22303 	if (ill_index != 0) {
22304 		if (ill == NULL) {
22305 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22306 			    B_TRUE);
22307 
22308 			/* Failure case frees things for us. */
22309 			if (ill == NULL)
22310 				return;
22311 
22312 			ill_need_rele = B_TRUE;
22313 		}
22314 		/*
22315 		 * If this packet needs to go out on a particular interface
22316 		 * honor it.
22317 		 */
22318 		if (attach_if) {
22319 			match_flags = MATCH_IRE_ILL;
22320 
22321 			/*
22322 			 * Check if we need an ire that will not be
22323 			 * looked up by anybody else i.e. HIDDEN.
22324 			 */
22325 			if (ill_is_probeonly(ill)) {
22326 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22327 			}
22328 		}
22329 	}
22330 	ASSERT(mp != NULL);
22331 
22332 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22333 		boolean_t unspec_src;
22334 		ipif_t	*ipif;
22335 
22336 		/*
22337 		 * Use the ill_index to get the right ill.
22338 		 */
22339 		unspec_src = io->ipsec_out_unspec_src;
22340 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22341 		if (ipif == NULL) {
22342 			if (ill_need_rele)
22343 				ill_refrele(ill);
22344 			freemsg(ipsec_mp);
22345 			return;
22346 		}
22347 
22348 		if (ire_arg != NULL) {
22349 			ire = ire_arg;
22350 		} else {
22351 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22352 			    zoneid, match_flags);
22353 			ire_need_rele = B_TRUE;
22354 		}
22355 		if (ire != NULL) {
22356 			ipif_refrele(ipif);
22357 			/*
22358 			 * XXX Do the multicast forwarding now, as the IPSEC
22359 			 * processing has been done.
22360 			 */
22361 			goto send;
22362 		}
22363 
22364 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22365 		mp->b_prev = NULL;
22366 		mp->b_next = NULL;
22367 
22368 		/*
22369 		 * If the IPsec packet was processed asynchronously,
22370 		 * drop it now.
22371 		 */
22372 		if (q == NULL) {
22373 			if (ill_need_rele)
22374 				ill_refrele(ill);
22375 			freemsg(ipsec_mp);
22376 			return;
22377 		}
22378 
22379 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22380 		    unspec_src, zoneid);
22381 		ipif_refrele(ipif);
22382 	} else {
22383 		if (attach_if) {
22384 			ipif_t	*ipif;
22385 
22386 			ipif = ipif_get_next_ipif(NULL, ill);
22387 			if (ipif == NULL) {
22388 				if (ill_need_rele)
22389 					ill_refrele(ill);
22390 				freemsg(ipsec_mp);
22391 				return;
22392 			}
22393 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22394 			    zoneid, match_flags);
22395 			ire_need_rele = B_TRUE;
22396 			ipif_refrele(ipif);
22397 		} else {
22398 			if (ire_arg != NULL) {
22399 				ire = ire_arg;
22400 			} else {
22401 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22402 				ire_need_rele = B_TRUE;
22403 			}
22404 		}
22405 		if (ire != NULL)
22406 			goto send;
22407 		/*
22408 		 * ire disappeared underneath.
22409 		 *
22410 		 * What we need to do here is the ip_newroute
22411 		 * logic to get the ire without doing the IPSEC
22412 		 * processing. Follow the same old path. But this
22413 		 * time, ip_wput or ire_add_then_send will call us
22414 		 * directly as all the IPSEC operations are done.
22415 		 */
22416 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22417 		mp->b_prev = NULL;
22418 		mp->b_next = NULL;
22419 
22420 		/*
22421 		 * If the IPsec packet was processed asynchronously,
22422 		 * drop it now.
22423 		 */
22424 		if (q == NULL) {
22425 			if (ill_need_rele)
22426 				ill_refrele(ill);
22427 			freemsg(ipsec_mp);
22428 			return;
22429 		}
22430 
22431 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22432 		    zoneid);
22433 	}
22434 	if (ill != NULL && ill_need_rele)
22435 		ill_refrele(ill);
22436 	return;
22437 send:
22438 	if (ill != NULL && ill_need_rele)
22439 		ill_refrele(ill);
22440 
22441 	/* Local delivery */
22442 	if (ire->ire_stq == NULL) {
22443 		ASSERT(q != NULL);
22444 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22445 		    ire, 0);
22446 		if (ire_need_rele)
22447 			ire_refrele(ire);
22448 		return;
22449 	}
22450 	/*
22451 	 * Everything is done. Send it out on the wire.
22452 	 * We force the insertion of a fragment header using the
22453 	 * IPH_FRAG_HDR flag in two cases:
22454 	 * - after reception of an ICMPv6 "packet too big" message
22455 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22456 	 * - for multirouted IPv6 packets, so that the receiver can
22457 	 *   discard duplicates according to their fragment identifier
22458 	 */
22459 	/* XXX fix flow control problems. */
22460 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22461 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22462 		if (hwaccel) {
22463 			/*
22464 			 * hardware acceleration does not handle these
22465 			 * "slow path" cases.
22466 			 */
22467 			/* IPsec KSTATS: should bump bean counter here. */
22468 			if (ire_need_rele)
22469 				ire_refrele(ire);
22470 			freemsg(ipsec_mp);
22471 			return;
22472 		}
22473 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22474 		    (mp->b_cont ? msgdsize(mp) :
22475 		    mp->b_wptr - (uchar_t *)ip6h)) {
22476 			/* IPsec KSTATS: should bump bean counter here. */
22477 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22478 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22479 			    msgdsize(mp)));
22480 			if (ire_need_rele)
22481 				ire_refrele(ire);
22482 			freemsg(ipsec_mp);
22483 			return;
22484 		}
22485 		ASSERT(mp->b_prev == NULL);
22486 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22487 		    ntohs(ip6h->ip6_plen) +
22488 		    IPV6_HDR_LEN, ire->ire_max_frag));
22489 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22490 		    ire->ire_max_frag);
22491 	} else {
22492 		UPDATE_OB_PKT_COUNT(ire);
22493 		ire->ire_last_used_time = lbolt;
22494 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22495 	}
22496 	if (ire_need_rele)
22497 		ire_refrele(ire);
22498 	freeb(ipsec_mp);
22499 }
22500 
22501 void
22502 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
22503 {
22504 /* EXPORT DELETE START */
22505 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
22506 	da_ipsec_t *hada;	/* data attributes */
22507 	ill_t *ill = (ill_t *)q->q_ptr;
22508 
22509 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
22510 
22511 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
22512 		/* IPsec KSTATS: Bump lose counter here! */
22513 /* EXPORT DELETE END */
22514 		freemsg(mp);
22515 /* EXPORT DELETE START */
22516 		return;
22517 	}
22518 
22519 	/*
22520 	 * It's an IPsec packet that must be
22521 	 * accelerated by the Provider, and the
22522 	 * outbound ill is IPsec acceleration capable.
22523 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
22524 	 * to the ill.
22525 	 * IPsec KSTATS: should bump packet counter here.
22526 	 */
22527 
22528 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
22529 	if (hada_mp == NULL) {
22530 		/* IPsec KSTATS: should bump packet counter here. */
22531 		freemsg(mp);
22532 		return;
22533 	}
22534 
22535 	hada_mp->b_datap->db_type = M_CTL;
22536 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
22537 	hada_mp->b_cont = mp;
22538 
22539 	hada = (da_ipsec_t *)hada_mp->b_rptr;
22540 	bzero(hada, sizeof (da_ipsec_t));
22541 	hada->da_type = IPHADA_M_CTL;
22542 
22543 	putnext(q, hada_mp);
22544 /* EXPORT DELETE END */
22545 }
22546 
22547 /*
22548  * Finish the outbound IPsec processing. This function is called from
22549  * ipsec_out_process() if the IPsec packet was processed
22550  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22551  * asynchronously.
22552  */
22553 void
22554 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
22555     ire_t *ire_arg)
22556 {
22557 	uint32_t v_hlen_tos_len;
22558 	ipaddr_t	dst;
22559 	ipif_t	*ipif = NULL;
22560 	ire_t *ire;
22561 	ire_t *ire1 = NULL;
22562 	mblk_t *next_mp = NULL;
22563 	uint32_t max_frag;
22564 	boolean_t multirt_send = B_FALSE;
22565 	mblk_t *mp;
22566 	mblk_t *mp1;
22567 	uint_t	ill_index;
22568 	ipsec_out_t *io;
22569 	boolean_t attach_if;
22570 	int match_flags, offset;
22571 	irb_t *irb = NULL;
22572 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
22573 	zoneid_t zoneid;
22574 	uint32_t cksum;
22575 	uint16_t *up;
22576 	/* Hack until the UDP merge into IP happens. */
22577 	extern boolean_t udp_compute_checksum(void);
22578 #ifdef	_BIG_ENDIAN
22579 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22580 #else
22581 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22582 #endif
22583 
22584 	mp = ipsec_mp->b_cont;
22585 	ASSERT(mp != NULL);
22586 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22587 	dst = ipha->ipha_dst;
22588 
22589 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22590 	ill_index = io->ipsec_out_ill_index;
22591 	attach_if = io->ipsec_out_attach_if;
22592 	zoneid = io->ipsec_out_zoneid;
22593 	ASSERT(zoneid != ALL_ZONES);
22594 	match_flags = MATCH_IRE_ILL_GROUP;
22595 	if (ill_index != 0) {
22596 		if (ill == NULL) {
22597 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
22598 			    ill_index, B_FALSE);
22599 
22600 			/* Failure case frees things for us. */
22601 			if (ill == NULL)
22602 				return;
22603 
22604 			ill_need_rele = B_TRUE;
22605 		}
22606 		/*
22607 		 * If this packet needs to go out on a particular interface
22608 		 * honor it.
22609 		 */
22610 		if (attach_if) {
22611 			match_flags = MATCH_IRE_ILL;
22612 
22613 			/*
22614 			 * Check if we need an ire that will not be
22615 			 * looked up by anybody else i.e. HIDDEN.
22616 			 */
22617 			if (ill_is_probeonly(ill)) {
22618 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22619 			}
22620 		}
22621 	}
22622 
22623 	if (CLASSD(dst)) {
22624 		boolean_t conn_dontroute;
22625 		/*
22626 		 * Use the ill_index to get the right ipif.
22627 		 */
22628 		conn_dontroute = io->ipsec_out_dontroute;
22629 		if (ill_index == 0)
22630 			ipif = ipif_lookup_group(dst, zoneid);
22631 		else
22632 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22633 		if (ipif == NULL) {
22634 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
22635 			    " multicast\n"));
22636 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
22637 			freemsg(ipsec_mp);
22638 			goto done;
22639 		}
22640 		/*
22641 		 * ipha_src has already been intialized with the
22642 		 * value of the ipif in ip_wput. All we need now is
22643 		 * an ire to send this downstream.
22644 		 */
22645 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
22646 		if (ire != NULL) {
22647 			ill_t *ill1;
22648 			/*
22649 			 * Do the multicast forwarding now, as the IPSEC
22650 			 * processing has been done.
22651 			 */
22652 			if (ip_g_mrouter && !conn_dontroute &&
22653 			    (ill1 = ire_to_ill(ire))) {
22654 				if (ip_mforward(ill1, ipha, mp)) {
22655 					freemsg(ipsec_mp);
22656 					ip1dbg(("ip_wput_ipsec_out: mforward "
22657 					    "failed\n"));
22658 					ire_refrele(ire);
22659 					goto done;
22660 				}
22661 			}
22662 			goto send;
22663 		}
22664 
22665 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
22666 		mp->b_prev = NULL;
22667 		mp->b_next = NULL;
22668 
22669 		/*
22670 		 * If the IPsec packet was processed asynchronously,
22671 		 * drop it now.
22672 		 */
22673 		if (q == NULL) {
22674 			freemsg(ipsec_mp);
22675 			goto done;
22676 		}
22677 
22678 		/*
22679 		 * We may be using a wrong ipif to create the ire.
22680 		 * But it is okay as the source address is assigned
22681 		 * for the packet already. Next outbound packet would
22682 		 * create the IRE with the right IPIF in ip_wput.
22683 		 *
22684 		 * Also handle RTF_MULTIRT routes.
22685 		 */
22686 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
22687 	} else {
22688 		if (attach_if) {
22689 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
22690 			    zoneid, match_flags);
22691 		} else {
22692 			if (ire_arg != NULL) {
22693 				ire = ire_arg;
22694 				ire_need_rele = B_FALSE;
22695 			} else {
22696 				ire = ire_cache_lookup(dst, zoneid);
22697 			}
22698 		}
22699 		if (ire != NULL) {
22700 			goto send;
22701 		}
22702 
22703 		/*
22704 		 * ire disappeared underneath.
22705 		 *
22706 		 * What we need to do here is the ip_newroute
22707 		 * logic to get the ire without doing the IPSEC
22708 		 * processing. Follow the same old path. But this
22709 		 * time, ip_wput or ire_add_then_put will call us
22710 		 * directly as all the IPSEC operations are done.
22711 		 */
22712 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
22713 		mp->b_prev = NULL;
22714 		mp->b_next = NULL;
22715 
22716 		/*
22717 		 * If the IPsec packet was processed asynchronously,
22718 		 * drop it now.
22719 		 */
22720 		if (q == NULL) {
22721 			freemsg(ipsec_mp);
22722 			goto done;
22723 		}
22724 
22725 		/*
22726 		 * Since we're going through ip_newroute() again, we
22727 		 * need to make sure we don't:
22728 		 *
22729 		 *	1.) Trigger the ASSERT() with the ipha_ident
22730 		 *	    overloading.
22731 		 *	2.) Redo transport-layer checksumming, since we've
22732 		 *	    already done all that to get this far.
22733 		 *
22734 		 * The easiest way not do either of the above is to set
22735 		 * the ipha_ident field to IP_HDR_INCLUDED.
22736 		 */
22737 		ipha->ipha_ident = IP_HDR_INCLUDED;
22738 		ip_newroute(q, ipsec_mp, dst, NULL,
22739 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
22740 	}
22741 	goto done;
22742 send:
22743 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
22744 		/*
22745 		 * ESP NAT-Traversal packet.
22746 		 *
22747 		 * Just do software checksum for now.
22748 		 */
22749 
22750 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
22751 		IP_STAT(ip_out_sw_cksum);
22752 #define	iphs	((uint16_t *)ipha)
22753 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
22754 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
22755 		    IP_SIMPLE_HDR_LENGTH);
22756 #undef iphs
22757 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
22758 			cksum = 0xFFFF;
22759 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
22760 			if (mp1->b_wptr - mp1->b_rptr >=
22761 			    offset + sizeof (uint16_t)) {
22762 				up = (uint16_t *)(mp1->b_rptr + offset);
22763 				*up = cksum;
22764 				break;	/* out of for loop */
22765 			} else {
22766 				offset -= (mp->b_wptr - mp->b_rptr);
22767 			}
22768 	} /* Otherwise, just keep the all-zero checksum. */
22769 
22770 	if (ire->ire_stq == NULL) {
22771 		/*
22772 		 * Loopbacks go through ip_wput_local except for one case.
22773 		 * We come here if we generate a icmp_frag_needed message
22774 		 * after IPSEC processing is over. When this function calls
22775 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
22776 		 * icmp_frag_needed. The message generated comes back here
22777 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
22778 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
22779 		 * source address as it is usually set in ip_wput_ire. As
22780 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
22781 		 * and we end up here. We can't enter ip_wput_ire once the
22782 		 * IPSEC processing is over and hence we need to do it here.
22783 		 */
22784 		ASSERT(q != NULL);
22785 		UPDATE_OB_PKT_COUNT(ire);
22786 		ire->ire_last_used_time = lbolt;
22787 		if (ipha->ipha_src == 0)
22788 			ipha->ipha_src = ire->ire_src_addr;
22789 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
22790 		    ire, 0, zoneid);
22791 		if (ire_need_rele)
22792 			ire_refrele(ire);
22793 		goto done;
22794 	}
22795 
22796 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
22797 		/*
22798 		 * We are through with IPSEC processing.
22799 		 * Fragment this and send it on the wire.
22800 		 */
22801 		if (io->ipsec_out_accelerated) {
22802 			/*
22803 			 * The packet has been accelerated but must
22804 			 * be fragmented. This should not happen
22805 			 * since AH and ESP must not accelerate
22806 			 * packets that need fragmentation, however
22807 			 * the configuration could have changed
22808 			 * since the AH or ESP processing.
22809 			 * Drop packet.
22810 			 * IPsec KSTATS: bump bean counter here.
22811 			 */
22812 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
22813 			    "fragmented accelerated packet!\n"));
22814 			freemsg(ipsec_mp);
22815 		} else {
22816 			ip_wput_ire_fragmentit(ipsec_mp, ire);
22817 		}
22818 		if (ire_need_rele)
22819 			ire_refrele(ire);
22820 		goto done;
22821 	}
22822 
22823 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
22824 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
22825 	    (void *)ire->ire_ipif, (void *)ipif));
22826 
22827 	/*
22828 	 * Multiroute the secured packet, unless IPsec really
22829 	 * requires the packet to go out only through a particular
22830 	 * interface.
22831 	 */
22832 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
22833 		ire_t *first_ire;
22834 		irb = ire->ire_bucket;
22835 		ASSERT(irb != NULL);
22836 		/*
22837 		 * This ire has been looked up as the one that
22838 		 * goes through the given ipif;
22839 		 * make sure we do not omit any other multiroute ire
22840 		 * that may be present in the bucket before this one.
22841 		 */
22842 		IRB_REFHOLD(irb);
22843 		for (first_ire = irb->irb_ire;
22844 		    first_ire != NULL;
22845 		    first_ire = first_ire->ire_next) {
22846 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22847 			    (first_ire->ire_addr == ire->ire_addr) &&
22848 			    !(first_ire->ire_marks &
22849 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22850 				break;
22851 		}
22852 
22853 		if ((first_ire != NULL) && (first_ire != ire)) {
22854 			/*
22855 			 * Don't change the ire if the packet must
22856 			 * be fragmented if sent via this new one.
22857 			 */
22858 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
22859 				IRE_REFHOLD(first_ire);
22860 				if (ire_need_rele)
22861 					ire_refrele(ire);
22862 				else
22863 					ire_need_rele = B_TRUE;
22864 				ire = first_ire;
22865 			}
22866 		}
22867 		IRB_REFRELE(irb);
22868 
22869 		multirt_send = B_TRUE;
22870 		max_frag = ire->ire_max_frag;
22871 	} else {
22872 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
22873 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
22874 			    "flag, attach_if %d\n", attach_if));
22875 		}
22876 	}
22877 
22878 	/*
22879 	 * In most cases, the emission loop below is entered only once.
22880 	 * Only in the case where the ire holds the RTF_MULTIRT
22881 	 * flag, we loop to process all RTF_MULTIRT ires in the
22882 	 * bucket, and send the packet through all crossed
22883 	 * RTF_MULTIRT routes.
22884 	 */
22885 	do {
22886 		if (multirt_send) {
22887 			/*
22888 			 * ire1 holds here the next ire to process in the
22889 			 * bucket. If multirouting is expected,
22890 			 * any non-RTF_MULTIRT ire that has the
22891 			 * right destination address is ignored.
22892 			 */
22893 			ASSERT(irb != NULL);
22894 			IRB_REFHOLD(irb);
22895 			for (ire1 = ire->ire_next;
22896 			    ire1 != NULL;
22897 			    ire1 = ire1->ire_next) {
22898 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22899 					continue;
22900 				if (ire1->ire_addr != ire->ire_addr)
22901 					continue;
22902 				if (ire1->ire_marks &
22903 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22904 					continue;
22905 				/* No loopback here */
22906 				if (ire1->ire_stq == NULL)
22907 					continue;
22908 				/*
22909 				 * Ensure we do not exceed the MTU
22910 				 * of the next route.
22911 				 */
22912 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
22913 					ip_multirt_bad_mtu(ire1, max_frag);
22914 					continue;
22915 				}
22916 
22917 				IRE_REFHOLD(ire1);
22918 				break;
22919 			}
22920 			IRB_REFRELE(irb);
22921 			if (ire1 != NULL) {
22922 				/*
22923 				 * We are in a multiple send case, need to
22924 				 * make a copy of the packet.
22925 				 */
22926 				next_mp = copymsg(ipsec_mp);
22927 				if (next_mp == NULL) {
22928 					ire_refrele(ire1);
22929 					ire1 = NULL;
22930 				}
22931 			}
22932 		}
22933 
22934 		/* Everything is done. Send it out on the wire */
22935 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
22936 		if (mp1 == NULL) {
22937 			BUMP_MIB(&ip_mib, ipOutDiscards);
22938 			freemsg(ipsec_mp);
22939 			if (ire_need_rele)
22940 				ire_refrele(ire);
22941 			if (ire1 != NULL) {
22942 				ire_refrele(ire1);
22943 				freemsg(next_mp);
22944 			}
22945 			goto done;
22946 		}
22947 		UPDATE_OB_PKT_COUNT(ire);
22948 		ire->ire_last_used_time = lbolt;
22949 		if (!io->ipsec_out_accelerated) {
22950 			putnext(ire->ire_stq, mp1);
22951 		} else {
22952 			/*
22953 			 * Safety Pup says: make sure this is going to
22954 			 * the right interface!
22955 			 */
22956 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
22957 			int ifindex = ill1->ill_phyint->phyint_ifindex;
22958 
22959 			if (ifindex != io->ipsec_out_capab_ill_index) {
22960 				/* IPsec kstats: bump lose counter */
22961 				freemsg(mp1);
22962 			} else {
22963 				ipsec_hw_putnext(ire->ire_stq, mp1);
22964 			}
22965 		}
22966 
22967 		freeb(ipsec_mp);
22968 		if (ire_need_rele)
22969 			ire_refrele(ire);
22970 
22971 		if (ire1 != NULL) {
22972 			ire = ire1;
22973 			ire_need_rele = B_TRUE;
22974 			ASSERT(next_mp);
22975 			ipsec_mp = next_mp;
22976 			mp = ipsec_mp->b_cont;
22977 			ire1 = NULL;
22978 			next_mp = NULL;
22979 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
22980 		} else {
22981 			multirt_send = B_FALSE;
22982 		}
22983 	} while (multirt_send);
22984 done:
22985 	if (ill != NULL && ill_need_rele)
22986 		ill_refrele(ill);
22987 	if (ipif != NULL)
22988 		ipif_refrele(ipif);
22989 }
22990 
22991 /*
22992  * Get the ill corresponding to the specified ire, and compare its
22993  * capabilities with the protocol and algorithms specified by the
22994  * the SA obtained from ipsec_out. If they match, annotate the
22995  * ipsec_out structure to indicate that the packet needs acceleration.
22996  *
22997  *
22998  * A packet is eligible for outbound hardware acceleration if the
22999  * following conditions are satisfied:
23000  *
23001  * 1. the packet will not be fragmented
23002  * 2. the provider supports the algorithm
23003  * 3. there is no pending control message being exchanged
23004  * 4. snoop is not attached
23005  * 5. the destination address is not a broadcast or multicast address.
23006  *
23007  * Rationale:
23008  *	- Hardware drivers do not support fragmentation with
23009  *	  the current interface.
23010  *	- snoop, multicast, and broadcast may result in exposure of
23011  *	  a cleartext datagram.
23012  * We check all five of these conditions here.
23013  *
23014  * XXX would like to nuke "ire_t *" parameter here; problem is that
23015  * IRE is only way to figure out if a v4 address is a broadcast and
23016  * thus ineligible for acceleration...
23017  */
23018 static void
23019 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23020 {
23021 	ipsec_out_t *io;
23022 	mblk_t *data_mp;
23023 	uint_t plen, overhead;
23024 
23025 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23026 		return;
23027 
23028 	if (ill == NULL)
23029 		return;
23030 
23031 	/*
23032 	 * Destination address is a broadcast or multicast.  Punt.
23033 	 */
23034 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23035 	    IRE_LOCAL)))
23036 		return;
23037 
23038 	data_mp = ipsec_mp->b_cont;
23039 
23040 	if (ill->ill_isv6) {
23041 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23042 
23043 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23044 			return;
23045 
23046 		plen = ip6h->ip6_plen;
23047 	} else {
23048 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23049 
23050 		if (CLASSD(ipha->ipha_dst))
23051 			return;
23052 
23053 		plen = ipha->ipha_length;
23054 	}
23055 	/*
23056 	 * Is there a pending DLPI control message being exchanged
23057 	 * between IP/IPsec and the DLS Provider? If there is, it
23058 	 * could be a SADB update, and the state of the DLS Provider
23059 	 * SADB might not be in sync with the SADB maintained by
23060 	 * IPsec. To avoid dropping packets or using the wrong keying
23061 	 * material, we do not accelerate this packet.
23062 	 */
23063 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23064 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23065 		    "ill_dlpi_pending! don't accelerate packet\n"));
23066 		return;
23067 	}
23068 
23069 	/*
23070 	 * Is the Provider in promiscous mode? If it does, we don't
23071 	 * accelerate the packet since it will bounce back up to the
23072 	 * listeners in the clear.
23073 	 */
23074 	if (ill->ill_promisc_on_phys) {
23075 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23076 		    "ill in promiscous mode, don't accelerate packet\n"));
23077 		return;
23078 	}
23079 
23080 	/*
23081 	 * Will the packet require fragmentation?
23082 	 */
23083 
23084 	/*
23085 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23086 	 * as is used elsewhere.
23087 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23088 	 *	+ 2-byte trailer
23089 	 */
23090 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23091 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23092 
23093 	if ((plen + overhead) > ill->ill_max_mtu)
23094 		return;
23095 
23096 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23097 
23098 	/*
23099 	 * Can the ill accelerate this IPsec protocol and algorithm
23100 	 * specified by the SA?
23101 	 */
23102 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23103 	    ill->ill_isv6, sa)) {
23104 		return;
23105 	}
23106 
23107 	/*
23108 	 * Tell AH or ESP that the outbound ill is capable of
23109 	 * accelerating this packet.
23110 	 */
23111 	io->ipsec_out_is_capab_ill = B_TRUE;
23112 }
23113 
23114 /*
23115  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23116  *
23117  * If this function returns B_TRUE, the requested SA's have been filled
23118  * into the ipsec_out_*_sa pointers.
23119  *
23120  * If the function returns B_FALSE, the packet has been "consumed", most
23121  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23122  *
23123  * The SA references created by the protocol-specific "select"
23124  * function will be released when the ipsec_mp is freed, thanks to the
23125  * ipsec_out_free destructor -- see spd.c.
23126  */
23127 static boolean_t
23128 ipsec_out_select_sa(mblk_t *ipsec_mp)
23129 {
23130 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23131 	ipsec_out_t *io;
23132 	ipsec_policy_t *pp;
23133 	ipsec_action_t *ap;
23134 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23135 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23136 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23137 
23138 	if (!io->ipsec_out_secure) {
23139 		/*
23140 		 * We came here by mistake.
23141 		 * Don't bother with ipsec processing
23142 		 * We should "discourage" this path in the future.
23143 		 */
23144 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23145 		return (B_FALSE);
23146 	}
23147 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23148 	ASSERT((io->ipsec_out_policy != NULL) ||
23149 	    (io->ipsec_out_act != NULL));
23150 
23151 	ASSERT(io->ipsec_out_failed == B_FALSE);
23152 
23153 	/*
23154 	 * IPSEC processing has started.
23155 	 */
23156 	io->ipsec_out_proc_begin = B_TRUE;
23157 	ap = io->ipsec_out_act;
23158 	if (ap == NULL) {
23159 		pp = io->ipsec_out_policy;
23160 		ASSERT(pp != NULL);
23161 		ap = pp->ipsp_act;
23162 		ASSERT(ap != NULL);
23163 	}
23164 
23165 	/*
23166 	 * We have an action.  now, let's select SA's.
23167 	 * (In the future, we can cache this in the conn_t..)
23168 	 */
23169 	if (ap->ipa_want_esp) {
23170 		if (io->ipsec_out_esp_sa == NULL) {
23171 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23172 			    IPPROTO_ESP);
23173 		}
23174 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23175 	}
23176 
23177 	if (ap->ipa_want_ah) {
23178 		if (io->ipsec_out_ah_sa == NULL) {
23179 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23180 			    IPPROTO_AH);
23181 		}
23182 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23183 		/*
23184 		 * The ESP and AH processing order needs to be preserved
23185 		 * when both protocols are required (ESP should be applied
23186 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23187 		 * when both ESP and AH are required, and an AH ACQUIRE
23188 		 * is needed.
23189 		 */
23190 		if (ap->ipa_want_esp && need_ah_acquire)
23191 			need_esp_acquire = B_TRUE;
23192 	}
23193 
23194 	/*
23195 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23196 	 * Release SAs that got referenced, but will not be used until we
23197 	 * acquire _all_ of the SAs we need.
23198 	 */
23199 	if (need_ah_acquire || need_esp_acquire) {
23200 		if (io->ipsec_out_ah_sa != NULL) {
23201 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23202 			io->ipsec_out_ah_sa = NULL;
23203 		}
23204 		if (io->ipsec_out_esp_sa != NULL) {
23205 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23206 			io->ipsec_out_esp_sa = NULL;
23207 		}
23208 
23209 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23210 		return (B_FALSE);
23211 	}
23212 
23213 	return (B_TRUE);
23214 }
23215 
23216 /*
23217  * Process an IPSEC_OUT message and see what you can
23218  * do with it.
23219  * IPQoS Notes:
23220  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23221  * IPSec.
23222  * XXX would like to nuke ire_t.
23223  * XXX ill_index better be "real"
23224  */
23225 void
23226 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23227 {
23228 	ipsec_out_t *io;
23229 	ipsec_policy_t *pp;
23230 	ipsec_action_t *ap;
23231 	ipha_t *ipha;
23232 	ip6_t *ip6h;
23233 	mblk_t *mp;
23234 	ill_t *ill;
23235 	zoneid_t zoneid;
23236 	ipsec_status_t ipsec_rc;
23237 	boolean_t ill_need_rele = B_FALSE;
23238 
23239 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23240 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23241 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23242 	mp = ipsec_mp->b_cont;
23243 
23244 	/*
23245 	 * Initiate IPPF processing. We do it here to account for packets
23246 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23247 	 * We can check for ipsec_out_proc_begin even for such packets, as
23248 	 * they will always be false (asserted below).
23249 	 */
23250 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23251 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23252 		    io->ipsec_out_ill_index : ill_index);
23253 		if (mp == NULL) {
23254 			ip2dbg(("ipsec_out_process: packet dropped "\
23255 			    "during IPPF processing\n"));
23256 			freeb(ipsec_mp);
23257 			BUMP_MIB(&ip_mib, ipOutDiscards);
23258 			return;
23259 		}
23260 	}
23261 
23262 	if (!io->ipsec_out_secure) {
23263 		/*
23264 		 * We came here by mistake.
23265 		 * Don't bother with ipsec processing
23266 		 * Should "discourage" this path in the future.
23267 		 */
23268 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23269 		goto done;
23270 	}
23271 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23272 	ASSERT((io->ipsec_out_policy != NULL) ||
23273 	    (io->ipsec_out_act != NULL));
23274 	ASSERT(io->ipsec_out_failed == B_FALSE);
23275 
23276 	if (!ipsec_loaded()) {
23277 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23278 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23279 			BUMP_MIB(&ip_mib, ipOutDiscards);
23280 		} else {
23281 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23282 		}
23283 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23284 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23285 		return;
23286 	}
23287 
23288 	/*
23289 	 * IPSEC processing has started.
23290 	 */
23291 	io->ipsec_out_proc_begin = B_TRUE;
23292 	ap = io->ipsec_out_act;
23293 	if (ap == NULL) {
23294 		pp = io->ipsec_out_policy;
23295 		ASSERT(pp != NULL);
23296 		ap = pp->ipsp_act;
23297 		ASSERT(ap != NULL);
23298 	}
23299 
23300 	/*
23301 	 * Save the outbound ill index. When the packet comes back
23302 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23303 	 * before sending it the accelerated packet.
23304 	 */
23305 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23306 		int ifindex;
23307 		ill = ire_to_ill(ire);
23308 		ifindex = ill->ill_phyint->phyint_ifindex;
23309 		io->ipsec_out_capab_ill_index = ifindex;
23310 	}
23311 
23312 	/*
23313 	 * The order of processing is first insert a IP header if needed.
23314 	 * Then insert the ESP header and then the AH header.
23315 	 */
23316 	if ((io->ipsec_out_se_done == B_FALSE) &&
23317 	    (ap->ipa_want_se)) {
23318 		/*
23319 		 * First get the outer IP header before sending
23320 		 * it to ESP.
23321 		 */
23322 		ipha_t *oipha, *iipha;
23323 		mblk_t *outer_mp, *inner_mp;
23324 
23325 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23326 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23327 			    "ipsec_out_process: "
23328 			    "Self-Encapsulation failed: Out of memory\n");
23329 			freemsg(ipsec_mp);
23330 			BUMP_MIB(&ip_mib, ipOutDiscards);
23331 			return;
23332 		}
23333 		inner_mp = ipsec_mp->b_cont;
23334 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23335 		oipha = (ipha_t *)outer_mp->b_rptr;
23336 		iipha = (ipha_t *)inner_mp->b_rptr;
23337 		*oipha = *iipha;
23338 		outer_mp->b_wptr += sizeof (ipha_t);
23339 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23340 		    sizeof (ipha_t));
23341 		oipha->ipha_protocol = IPPROTO_ENCAP;
23342 		oipha->ipha_version_and_hdr_length =
23343 		    IP_SIMPLE_HDR_VERSION;
23344 		oipha->ipha_hdr_checksum = 0;
23345 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23346 		outer_mp->b_cont = inner_mp;
23347 		ipsec_mp->b_cont = outer_mp;
23348 
23349 		io->ipsec_out_se_done = B_TRUE;
23350 		io->ipsec_out_encaps = B_TRUE;
23351 	}
23352 
23353 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23354 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23355 	    !ipsec_out_select_sa(ipsec_mp))
23356 		return;
23357 
23358 	/*
23359 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23360 	 * to do the heavy lifting.
23361 	 */
23362 	zoneid = io->ipsec_out_zoneid;
23363 	ASSERT(zoneid != ALL_ZONES);
23364 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23365 		ASSERT(io->ipsec_out_esp_sa != NULL);
23366 		io->ipsec_out_esp_done = B_TRUE;
23367 		/*
23368 		 * Note that since hw accel can only apply one transform,
23369 		 * not two, we skip hw accel for ESP if we also have AH
23370 		 * This is an design limitation of the interface
23371 		 * which should be revisited.
23372 		 */
23373 		ASSERT(ire != NULL);
23374 		if (io->ipsec_out_ah_sa == NULL) {
23375 			ill = (ill_t *)ire->ire_stq->q_ptr;
23376 			ipsec_out_is_accelerated(ipsec_mp,
23377 			    io->ipsec_out_esp_sa, ill, ire);
23378 		}
23379 
23380 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23381 		switch (ipsec_rc) {
23382 		case IPSEC_STATUS_SUCCESS:
23383 			break;
23384 		case IPSEC_STATUS_FAILED:
23385 			BUMP_MIB(&ip_mib, ipOutDiscards);
23386 			/* FALLTHRU */
23387 		case IPSEC_STATUS_PENDING:
23388 			return;
23389 		}
23390 	}
23391 
23392 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23393 		ASSERT(io->ipsec_out_ah_sa != NULL);
23394 		io->ipsec_out_ah_done = B_TRUE;
23395 		if (ire == NULL) {
23396 			int idx = io->ipsec_out_capab_ill_index;
23397 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23398 			    NULL, NULL, NULL, NULL);
23399 			ill_need_rele = B_TRUE;
23400 		} else {
23401 			ill = (ill_t *)ire->ire_stq->q_ptr;
23402 		}
23403 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23404 		    ire);
23405 
23406 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23407 		switch (ipsec_rc) {
23408 		case IPSEC_STATUS_SUCCESS:
23409 			break;
23410 		case IPSEC_STATUS_FAILED:
23411 			BUMP_MIB(&ip_mib, ipOutDiscards);
23412 			/* FALLTHRU */
23413 		case IPSEC_STATUS_PENDING:
23414 			if (ill != NULL && ill_need_rele)
23415 				ill_refrele(ill);
23416 			return;
23417 		}
23418 	}
23419 	/*
23420 	 * We are done with IPSEC processing. Send it over
23421 	 * the wire.
23422 	 */
23423 done:
23424 	mp = ipsec_mp->b_cont;
23425 	ipha = (ipha_t *)mp->b_rptr;
23426 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23427 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23428 	} else {
23429 		ip6h = (ip6_t *)ipha;
23430 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23431 	}
23432 	if (ill != NULL && ill_need_rele)
23433 		ill_refrele(ill);
23434 }
23435 
23436 /* ARGSUSED */
23437 void
23438 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23439 {
23440 	opt_restart_t	*or;
23441 	int	err;
23442 	conn_t	*connp;
23443 
23444 	ASSERT(CONN_Q(q));
23445 	connp = Q_TO_CONN(q);
23446 
23447 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23448 	or = (opt_restart_t *)first_mp->b_rptr;
23449 	/*
23450 	 * We don't need to pass any credentials here since this is just
23451 	 * a restart. The credentials are passed in when svr4_optcom_req
23452 	 * is called the first time (from ip_wput_nondata).
23453 	 */
23454 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23455 		err = svr4_optcom_req(q, first_mp, NULL,
23456 		    &ip_opt_obj);
23457 	} else {
23458 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23459 		err = tpi_optcom_req(q, first_mp, NULL,
23460 		    &ip_opt_obj);
23461 	}
23462 	if (err != EINPROGRESS) {
23463 		/* operation is done */
23464 		CONN_OPER_PENDING_DONE(connp);
23465 	}
23466 }
23467 
23468 /*
23469  * ioctls that go through a down/up sequence may need to wait for the down
23470  * to complete. This involves waiting for the ire and ipif refcnts to go down
23471  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23472  */
23473 /* ARGSUSED */
23474 void
23475 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23476 {
23477 	struct iocblk *iocp;
23478 	mblk_t *mp1;
23479 	ipif_t	*ipif;
23480 	ip_ioctl_cmd_t *ipip;
23481 	int err;
23482 	sin_t	*sin;
23483 	struct lifreq *lifr;
23484 	struct ifreq *ifr;
23485 
23486 	iocp = (struct iocblk *)mp->b_rptr;
23487 	ASSERT(ipsq != NULL);
23488 	/* Existence of mp1 verified in ip_wput_nondata */
23489 	mp1 = mp->b_cont->b_cont;
23490 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23491 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23492 		ill_t *ill;
23493 		/*
23494 		 * Special case where ipsq_current_ipif may not be set.
23495 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23496 		 * ill could also have become part of a ipmp group in the
23497 		 * process, we are here as were not able to complete the
23498 		 * operation in ipif_set_values because we could not become
23499 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23500 		 * will not be set so we need to set it.
23501 		 */
23502 		ill = (ill_t *)q->q_ptr;
23503 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23504 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23505 	}
23506 
23507 	ipif = ipsq->ipsq_current_ipif;
23508 	ASSERT(ipif != NULL);
23509 	if (ipip->ipi_cmd_type == IF_CMD) {
23510 		/* This a old style SIOC[GS]IF* command */
23511 		ifr = (struct ifreq *)mp1->b_rptr;
23512 		sin = (sin_t *)&ifr->ifr_addr;
23513 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
23514 		/* This a new style SIOC[GS]LIF* command */
23515 		lifr = (struct lifreq *)mp1->b_rptr;
23516 		sin = (sin_t *)&lifr->lifr_addr;
23517 	} else {
23518 		sin = NULL;
23519 	}
23520 
23521 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
23522 	    (void *)mp1->b_rptr);
23523 
23524 	/* SIOCLIFREMOVEIF could have removed the ipif */
23525 	ip_ioctl_finish(q, mp, err,
23526 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23527 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
23528 }
23529 
23530 /*
23531  * ioctl processing
23532  *
23533  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
23534  * the ioctl command in the ioctl tables and determines the copyin data size
23535  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
23536  * size.
23537  *
23538  * ioctl processing then continues when the M_IOCDATA makes its way down.
23539  * Now the ioctl is looked up again in the ioctl table, and its properties are
23540  * extracted. The associated 'conn' is then refheld till the end of the ioctl
23541  * and the general ioctl processing function ip_process_ioctl is called.
23542  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
23543  * so goes thru the serialization primitive ipsq_try_enter. Then the
23544  * appropriate function to handle the ioctl is called based on the entry in
23545  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
23546  * which also refreleases the 'conn' that was refheld at the start of the
23547  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
23548  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
23549  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
23550  *
23551  * Many exclusive ioctls go thru an internal down up sequence as part of
23552  * the operation. For example an attempt to change the IP address of an
23553  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
23554  * does all the cleanup such as deleting all ires that use this address.
23555  * Then we need to wait till all references to the interface go away.
23556  */
23557 void
23558 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
23559 {
23560 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
23561 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
23562 	cmd_info_t ci;
23563 	int err;
23564 	boolean_t entered_ipsq = B_FALSE;
23565 
23566 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
23567 
23568 	if (ipip == NULL)
23569 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23570 
23571 	/*
23572 	 * SIOCLIFADDIF needs to go thru a special path since the
23573 	 * ill may not exist yet. This happens in the case of lo0
23574 	 * which is created using this ioctl.
23575 	 */
23576 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
23577 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
23578 		ip_ioctl_finish(q, mp, err,
23579 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23580 		    NULL, NULL);
23581 		return;
23582 	}
23583 
23584 	ci.ci_ipif = NULL;
23585 	switch (ipip->ipi_cmd_type) {
23586 	case IF_CMD:
23587 	case LIF_CMD:
23588 		/*
23589 		 * ioctls that pass in a [l]ifreq appear here.
23590 		 * ip_extract_lifreq_cmn returns a refheld ipif in
23591 		 * ci.ci_ipif
23592 		 */
23593 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
23594 		    ipip->ipi_flags, &ci, ip_process_ioctl);
23595 		if (err != 0) {
23596 			ip_ioctl_finish(q, mp, err,
23597 			    ipip->ipi_flags & IPI_GET_CMD ?
23598 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23599 			return;
23600 		}
23601 		ASSERT(ci.ci_ipif != NULL);
23602 		break;
23603 
23604 	case TUN_CMD:
23605 		/*
23606 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
23607 		 * a refheld ipif in ci.ci_ipif
23608 		 */
23609 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
23610 		if (err != 0) {
23611 			ip_ioctl_finish(q, mp, err,
23612 			    ipip->ipi_flags & IPI_GET_CMD ?
23613 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23614 			return;
23615 		}
23616 		ASSERT(ci.ci_ipif != NULL);
23617 		break;
23618 
23619 	case MISC_CMD:
23620 		/*
23621 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
23622 		 * For eg. SIOCGLIFCONF will appear here.
23623 		 */
23624 		switch (ipip->ipi_cmd) {
23625 		case IF_UNITSEL:
23626 			/* ioctl comes down the ill */
23627 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
23628 			ipif_refhold(ci.ci_ipif);
23629 			break;
23630 		case SIOCGMSFILTER:
23631 		case SIOCSMSFILTER:
23632 		case SIOCGIPMSFILTER:
23633 		case SIOCSIPMSFILTER:
23634 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
23635 			    ip_process_ioctl);
23636 			if (err != 0) {
23637 				ip_ioctl_finish(q, mp, err,
23638 				    ipip->ipi_flags & IPI_GET_CMD ?
23639 				    COPYOUT : NO_COPYOUT, NULL, NULL);
23640 				return;
23641 			}
23642 			break;
23643 		}
23644 		err = 0;
23645 		ci.ci_sin = NULL;
23646 		ci.ci_sin6 = NULL;
23647 		ci.ci_lifr = NULL;
23648 		break;
23649 	}
23650 
23651 	/*
23652 	 * If ipsq is non-null, we are already being called exclusively
23653 	 */
23654 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
23655 	if (!(ipip->ipi_flags & IPI_WR)) {
23656 		/*
23657 		 * A return value of EINPROGRESS means the ioctl is
23658 		 * either queued and waiting for some reason or has
23659 		 * already completed.
23660 		 */
23661 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23662 		    ci.ci_lifr);
23663 		if (ci.ci_ipif != NULL)
23664 			ipif_refrele(ci.ci_ipif);
23665 		ip_ioctl_finish(q, mp, err,
23666 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23667 		    NULL, NULL);
23668 		return;
23669 	}
23670 
23671 	ASSERT(ci.ci_ipif != NULL);
23672 
23673 	if (ipsq == NULL) {
23674 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
23675 		    ip_process_ioctl, NEW_OP, B_TRUE);
23676 		entered_ipsq = B_TRUE;
23677 	}
23678 	/*
23679 	 * Release the ipif so that ipif_down and friends that wait for
23680 	 * references to go away are not misled about the current ipif_refcnt
23681 	 * values. We are writer so we can access the ipif even after releasing
23682 	 * the ipif.
23683 	 */
23684 	ipif_refrele(ci.ci_ipif);
23685 	if (ipsq == NULL)
23686 		return;
23687 
23688 	mutex_enter(&ipsq->ipsq_lock);
23689 	ASSERT(ipsq->ipsq_current_ipif == NULL);
23690 	ipsq->ipsq_current_ipif = ci.ci_ipif;
23691 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23692 	mutex_exit(&ipsq->ipsq_lock);
23693 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
23694 	/*
23695 	 * For most set ioctls that come here, this serves as a single point
23696 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
23697 	 * be any new references to the ipif. This helps functions that go
23698 	 * through this path and end up trying to wait for the refcnts
23699 	 * associated with the ipif to go down to zero. Some exceptions are
23700 	 * Failover, Failback, and Groupname commands that operate on more than
23701 	 * just the ci.ci_ipif. These commands internally determine the
23702 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
23703 	 * flags on that set. Another exception is the Removeif command that
23704 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
23705 	 * ipif to operate on.
23706 	 */
23707 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
23708 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
23709 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
23710 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
23711 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
23712 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
23713 
23714 	/*
23715 	 * A return value of EINPROGRESS means the ioctl is
23716 	 * either queued and waiting for some reason or has
23717 	 * already completed.
23718 	 */
23719 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23720 	    ci.ci_lifr);
23721 
23722 	/* SIOCLIFREMOVEIF could have removed the ipif */
23723 	ip_ioctl_finish(q, mp, err,
23724 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23725 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
23726 
23727 	if (entered_ipsq)
23728 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
23729 }
23730 
23731 /*
23732  * Complete the ioctl. Typically ioctls use the mi package and need to
23733  * do mi_copyout/mi_copy_done.
23734  */
23735 void
23736 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
23737     ipif_t *ipif, ipsq_t *ipsq)
23738 {
23739 	conn_t	*connp = NULL;
23740 
23741 	if (err == EINPROGRESS)
23742 		return;
23743 
23744 	if (CONN_Q(q)) {
23745 		connp = Q_TO_CONN(q);
23746 		ASSERT(connp->conn_ref >= 2);
23747 	}
23748 
23749 	switch (mode) {
23750 	case COPYOUT:
23751 		if (err == 0)
23752 			mi_copyout(q, mp);
23753 		else
23754 			mi_copy_done(q, mp, err);
23755 		break;
23756 
23757 	case NO_COPYOUT:
23758 		mi_copy_done(q, mp, err);
23759 		break;
23760 
23761 	default:
23762 		/* An ioctl aborted through a conn close would take this path */
23763 		break;
23764 	}
23765 
23766 	/*
23767 	 * The refhold placed at the start of the ioctl is released here.
23768 	 */
23769 	if (connp != NULL)
23770 		CONN_OPER_PENDING_DONE(connp);
23771 
23772 	/*
23773 	 * If the ioctl were an exclusive ioctl it would have set
23774 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
23775 	 */
23776 	if (ipif != NULL) {
23777 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
23778 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
23779 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
23780 	}
23781 
23782 	/*
23783 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
23784 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
23785 	 * entering the ipsq
23786 	 */
23787 	if (ipsq != NULL) {
23788 		mutex_enter(&ipsq->ipsq_lock);
23789 		ipsq->ipsq_current_ipif = NULL;
23790 		mutex_exit(&ipsq->ipsq_lock);
23791 	}
23792 }
23793 
23794 /*
23795  * This is called from ip_wput_nondata to resume a deferred TCP bind.
23796  */
23797 /* ARGSUSED */
23798 void
23799 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
23800 {
23801 	conn_t *connp = (conn_t *)arg;
23802 	tcp_t	*tcp;
23803 
23804 	ASSERT(connp != NULL && connp->conn_tcp != NULL);
23805 	tcp = connp->conn_tcp;
23806 
23807 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
23808 		freemsg(mp);
23809 	else
23810 		tcp_rput_other(tcp, mp);
23811 	CONN_OPER_PENDING_DONE(connp);
23812 
23813 }
23814 
23815 /* Called from ip_wput for all non data messages */
23816 /* ARGSUSED */
23817 void
23818 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23819 {
23820 	mblk_t		*mp1;
23821 	ire_t		*ire;
23822 	ill_t		*ill;
23823 	struct iocblk	*iocp;
23824 	ip_ioctl_cmd_t	*ipip;
23825 	cred_t		*cr;
23826 	conn_t		*connp = NULL;
23827 	int		cmd, err;
23828 
23829 	if (CONN_Q(q))
23830 		connp = Q_TO_CONN(q);
23831 
23832 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
23833 
23834 	/* Check if it is a queue to /dev/sctp. */
23835 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
23836 	    connp->conn_rq == NULL) {
23837 		sctp_wput(q, mp);
23838 		return;
23839 	}
23840 
23841 	switch (DB_TYPE(mp)) {
23842 	case M_IOCTL:
23843 		/*
23844 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
23845 		 * will arrange to copy in associated control structures.
23846 		 */
23847 		ip_sioctl_copyin_setup(q, mp);
23848 		return;
23849 	case M_IOCDATA:
23850 		/*
23851 		 * Ensure that this is associated with one of our trans-
23852 		 * parent ioctls.  If it's not ours, discard it if we're
23853 		 * running as a driver, or pass it on if we're a module.
23854 		 */
23855 		iocp = (struct iocblk *)mp->b_rptr;
23856 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23857 		if (ipip == NULL) {
23858 			if (q->q_next == NULL) {
23859 				goto nak;
23860 			} else {
23861 				putnext(q, mp);
23862 			}
23863 			return;
23864 		} else if ((q->q_next != NULL) &&
23865 		    !(ipip->ipi_flags & IPI_MODOK)) {
23866 			/*
23867 			 * the ioctl is one we recognise, but is not
23868 			 * consumed by IP as a module, pass M_IOCDATA
23869 			 * for processing downstream, but only for
23870 			 * common Streams ioctls.
23871 			 */
23872 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
23873 				putnext(q, mp);
23874 				return;
23875 			} else {
23876 				goto nak;
23877 			}
23878 		}
23879 
23880 		/* IOCTL continuation following copyin or copyout. */
23881 		if (mi_copy_state(q, mp, NULL) == -1) {
23882 			/*
23883 			 * The copy operation failed.  mi_copy_state already
23884 			 * cleaned up, so we're out of here.
23885 			 */
23886 			return;
23887 		}
23888 		/*
23889 		 * If we just completed a copy in, we become writer and
23890 		 * continue processing in ip_sioctl_copyin_done.  If it
23891 		 * was a copy out, we call mi_copyout again.  If there is
23892 		 * nothing more to copy out, it will complete the IOCTL.
23893 		 */
23894 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
23895 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
23896 				mi_copy_done(q, mp, EPROTO);
23897 				return;
23898 			}
23899 			/*
23900 			 * Check for cases that need more copying.  A return
23901 			 * value of 0 means a second copyin has been started,
23902 			 * so we return; a return value of 1 means no more
23903 			 * copying is needed, so we continue.
23904 			 */
23905 			cmd = iocp->ioc_cmd;
23906 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
23907 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
23908 			    MI_COPY_COUNT(mp) == 1) {
23909 				if (ip_copyin_msfilter(q, mp) == 0)
23910 					return;
23911 			}
23912 			/*
23913 			 * Refhold the conn, till the ioctl completes. This is
23914 			 * needed in case the ioctl ends up in the pending mp
23915 			 * list. Every mp in the ill_pending_mp list and
23916 			 * the ipsq_pending_mp must have a refhold on the conn
23917 			 * to resume processing. The refhold is released when
23918 			 * the ioctl completes. (normally or abnormally)
23919 			 * In all cases ip_ioctl_finish is called to finish
23920 			 * the ioctl.
23921 			 */
23922 			if (connp != NULL) {
23923 				/* This is not a reentry */
23924 				ASSERT(ipsq == NULL);
23925 				CONN_INC_REF(connp);
23926 			} else {
23927 				if (!(ipip->ipi_flags & IPI_MODOK)) {
23928 					mi_copy_done(q, mp, EINVAL);
23929 					return;
23930 				}
23931 			}
23932 
23933 			ip_process_ioctl(ipsq, q, mp, ipip);
23934 
23935 		} else {
23936 			mi_copyout(q, mp);
23937 		}
23938 		return;
23939 nak:
23940 		iocp->ioc_error = EINVAL;
23941 		mp->b_datap->db_type = M_IOCNAK;
23942 		iocp->ioc_count = 0;
23943 		qreply(q, mp);
23944 		return;
23945 
23946 	case M_IOCNAK:
23947 		/*
23948 		 * The only way we could get here is if a resolver didn't like
23949 		 * an IOCTL we sent it.	 This shouldn't happen.
23950 		 */
23951 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
23952 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
23953 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
23954 		freemsg(mp);
23955 		return;
23956 	case M_IOCACK:
23957 		/* Finish socket ioctls passed through to ARP. */
23958 		ip_sioctl_iocack(q, mp);
23959 		return;
23960 	case M_FLUSH:
23961 		if (*mp->b_rptr & FLUSHW)
23962 			flushq(q, FLUSHALL);
23963 		if (q->q_next) {
23964 			/*
23965 			 * M_FLUSH is sent up to IP by some drivers during
23966 			 * unbind. ip_rput has already replied to it. We are
23967 			 * here for the M_FLUSH that we originated in IP
23968 			 * before sending the unbind request to the driver.
23969 			 * Just free it as we don't queue packets in IP
23970 			 * on the write side of the device instance.
23971 			 */
23972 			freemsg(mp);
23973 			return;
23974 		}
23975 		if (*mp->b_rptr & FLUSHR) {
23976 			*mp->b_rptr &= ~FLUSHW;
23977 			qreply(q, mp);
23978 			return;
23979 		}
23980 		freemsg(mp);
23981 		return;
23982 	case IRE_DB_REQ_TYPE:
23983 		/* An Upper Level Protocol wants a copy of an IRE. */
23984 		ip_ire_req(q, mp);
23985 		return;
23986 	case M_CTL:
23987 		/* M_CTL messages are used by ARP to tell us things. */
23988 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
23989 			break;
23990 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
23991 		case AR_ENTRY_SQUERY:
23992 			ip_wput_ctl(q, mp);
23993 			return;
23994 		case AR_CLIENT_NOTIFY:
23995 			ip_arp_news(q, mp);
23996 			return;
23997 		case AR_DLPIOP_DONE:
23998 			ASSERT(q->q_next != NULL);
23999 			ill = (ill_t *)q->q_ptr;
24000 			/* qwriter_ip releases the refhold */
24001 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
24002 			ill_refhold(ill);
24003 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
24004 			    CUR_OP, B_FALSE);
24005 			return;
24006 		case AR_ARP_CLOSING:
24007 			/*
24008 			 * ARP (above us) is closing. If no ARP bringup is
24009 			 * currently pending, ack the message so that ARP
24010 			 * can complete its close. Also mark ill_arp_closing
24011 			 * so that new ARP bringups will fail. If any
24012 			 * ARP bringup is currently in progress, we will
24013 			 * ack this when the current ARP bringup completes.
24014 			 */
24015 			ASSERT(q->q_next != NULL);
24016 			ill = (ill_t *)q->q_ptr;
24017 			mutex_enter(&ill->ill_lock);
24018 			ill->ill_arp_closing = 1;
24019 			if (!ill->ill_arp_bringup_pending) {
24020 				mutex_exit(&ill->ill_lock);
24021 				qreply(q, mp);
24022 			} else {
24023 				mutex_exit(&ill->ill_lock);
24024 				freemsg(mp);
24025 			}
24026 			return;
24027 		default:
24028 			break;
24029 		}
24030 		break;
24031 	case M_PROTO:
24032 	case M_PCPROTO:
24033 		/*
24034 		 * The only PROTO messages we expect are ULP binds and
24035 		 * copies of option negotiation acknowledgements.
24036 		 */
24037 		switch (((union T_primitives *)mp->b_rptr)->type) {
24038 		case O_T_BIND_REQ:
24039 		case T_BIND_REQ: {
24040 			/* Request can get queued in bind */
24041 			ASSERT(connp != NULL);
24042 			/* Don't increment refcnt if this is a re-entry */
24043 			if (ipsq == NULL)
24044 				CONN_INC_REF(connp);
24045 			mp = connp->conn_af_isv6 ?
24046 			    ip_bind_v6(q, mp, connp, NULL) :
24047 				ip_bind_v4(q, mp, connp);
24048 			if (mp != NULL) {
24049 				tcp_t	*tcp;
24050 
24051 				tcp = connp->conn_tcp;
24052 				if (tcp != NULL) {
24053 					if (ipsq == NULL) {
24054 						tcp_rput_other(tcp, mp);
24055 					} else {
24056 						CONN_INC_REF(connp);
24057 						squeue_fill(connp->conn_sqp, mp,
24058 						    ip_resume_tcp_bind,
24059 						    connp, SQTAG_TCP_RPUTOTHER);
24060 						return;
24061 					}
24062 				} else {
24063 					qreply(q, mp);
24064 				}
24065 				CONN_OPER_PENDING_DONE(connp);
24066 			}
24067 			return;
24068 		}
24069 		case T_SVR4_OPTMGMT_REQ:
24070 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24071 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24072 
24073 			ASSERT(connp != NULL);
24074 			if (!snmpcom_req(q, mp, ip_snmp_set,
24075 			    ip_snmp_get, cr)) {
24076 				/*
24077 				 * Call svr4_optcom_req so that it can
24078 				 * generate the ack. We don't come here
24079 				 * if this operation is being restarted.
24080 				 * ip_restart_optmgmt will drop the conn ref.
24081 				 * In the case of ipsec option after the ipsec
24082 				 * load is complete conn_restart_ipsec_waiter
24083 				 * drops the conn ref.
24084 				 */
24085 				ASSERT(ipsq == NULL);
24086 				CONN_INC_REF(connp);
24087 				if (ip_check_for_ipsec_opt(q, mp))
24088 					return;
24089 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24090 				if (err != EINPROGRESS) {
24091 					/* Operation is done */
24092 					CONN_OPER_PENDING_DONE(connp);
24093 				}
24094 			}
24095 			return;
24096 		case T_OPTMGMT_REQ:
24097 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24098 			/*
24099 			 * Note: No snmpcom_req support through new
24100 			 * T_OPTMGMT_REQ.
24101 			 * Call tpi_optcom_req so that it can
24102 			 * generate the ack.
24103 			 */
24104 			ASSERT(connp != NULL);
24105 			ASSERT(ipsq == NULL);
24106 			/*
24107 			 * We don't come here for restart. ip_restart_optmgmt
24108 			 * will drop the conn ref. In the case of ipsec option
24109 			 * after the ipsec load is complete
24110 			 * conn_restart_ipsec_waiter drops the conn ref.
24111 			 */
24112 			CONN_INC_REF(connp);
24113 			if (ip_check_for_ipsec_opt(q, mp))
24114 				return;
24115 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24116 			if (err != EINPROGRESS) {
24117 				/* Operation is done */
24118 				CONN_OPER_PENDING_DONE(connp);
24119 			}
24120 			return;
24121 		case T_UNBIND_REQ:
24122 			ip_unbind(q, mp);
24123 			return;
24124 		default:
24125 			/*
24126 			 * Have to drop any DLPI messages coming down from
24127 			 * arp (such as an info_req which would cause ip
24128 			 * to receive an extra info_ack if it was passed
24129 			 * through.
24130 			 */
24131 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24132 			    (int)*(uint_t *)mp->b_rptr));
24133 			freemsg(mp);
24134 			return;
24135 		}
24136 		/* NOTREACHED */
24137 	case IRE_DB_TYPE: {
24138 		nce_t		*nce;
24139 		ill_t		*ill;
24140 		in6_addr_t	gw_addr_v6;
24141 
24142 
24143 		/*
24144 		 * This is a response back from a resolver.  It
24145 		 * consists of a message chain containing:
24146 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24147 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24148 		 * The LL_HDR_MBLK is the DLPI header to use to get
24149 		 * the attached packet, and subsequent ones for the
24150 		 * same destination, transmitted.
24151 		 */
24152 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24153 			break;
24154 		/*
24155 		 * First, check to make sure the resolution succeeded.
24156 		 * If it failed, the second mblk will be empty.
24157 		 * If it is, free the chain, dropping the packet.
24158 		 * (We must ire_delete the ire; that frees the ire mblk)
24159 		 * We're doing this now to support PVCs for ATM; it's
24160 		 * a partial xresolv implementation. When we fully implement
24161 		 * xresolv interfaces, instead of freeing everything here
24162 		 * we'll initiate neighbor discovery.
24163 		 *
24164 		 * For v4 (ARP and other external resolvers) the resolver
24165 		 * frees the message, so no check is needed. This check
24166 		 * is required, though, for a full xresolve implementation.
24167 		 * Including this code here now both shows how external
24168 		 * resolvers can NACK a resolution request using an
24169 		 * existing design that has no specific provisions for NACKs,
24170 		 * and also takes into account that the current non-ARP
24171 		 * external resolver has been coded to use this method of
24172 		 * NACKing for all IPv6 (xresolv) cases,
24173 		 * whether our xresolv implementation is complete or not.
24174 		 *
24175 		 */
24176 		ire = (ire_t *)mp->b_rptr;
24177 		ill = ire_to_ill(ire);
24178 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24179 		if (mp1->b_rptr == mp1->b_wptr) {
24180 			if (ire->ire_ipversion == IPV6_VERSION) {
24181 				/*
24182 				 * XRESOLV interface.
24183 				 */
24184 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24185 				mutex_enter(&ire->ire_lock);
24186 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24187 				mutex_exit(&ire->ire_lock);
24188 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24189 					nce = ndp_lookup(ill,
24190 					    &ire->ire_addr_v6, B_FALSE);
24191 				} else {
24192 					nce = ndp_lookup(ill, &gw_addr_v6,
24193 					    B_FALSE);
24194 				}
24195 				if (nce != NULL) {
24196 					nce_resolv_failed(nce);
24197 					ndp_delete(nce);
24198 					NCE_REFRELE(nce);
24199 				}
24200 			}
24201 			mp->b_cont = NULL;
24202 			freemsg(mp1);		/* frees the pkt as well */
24203 			ire_delete((ire_t *)mp->b_rptr);
24204 			return;
24205 		}
24206 		/*
24207 		 * Split them into IRE_MBLK and pkt and feed it into
24208 		 * ire_add_then_send. Then in ire_add_then_send
24209 		 * the IRE will be added, and then the packet will be
24210 		 * run back through ip_wput. This time it will make
24211 		 * it to the wire.
24212 		 */
24213 		mp->b_cont = NULL;
24214 		mp = mp1->b_cont;		/* now, mp points to pkt */
24215 		mp1->b_cont = NULL;
24216 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24217 		if (ire->ire_ipversion == IPV6_VERSION) {
24218 			/*
24219 			 * XRESOLV interface. Find the nce and put a copy
24220 			 * of the dl_unitdata_req in nce_res_mp
24221 			 */
24222 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24223 			mutex_enter(&ire->ire_lock);
24224 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24225 			mutex_exit(&ire->ire_lock);
24226 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24227 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24228 				    B_FALSE);
24229 			} else {
24230 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24231 			}
24232 			if (nce != NULL) {
24233 				/*
24234 				 * We have to protect nce_res_mp here
24235 				 * from being accessed by other threads
24236 				 * while we change the mblk pointer.
24237 				 * Other functions will also lock the nce when
24238 				 * accessing nce_res_mp.
24239 				 *
24240 				 * The reason we change the mblk pointer
24241 				 * here rather than copying the resolved address
24242 				 * into the template is that, unlike with
24243 				 * ethernet, we have no guarantee that the
24244 				 * resolved address length will be
24245 				 * smaller than or equal to the lla length
24246 				 * with which the template was allocated,
24247 				 * (for ethernet, they're equal)
24248 				 * so we have to use the actual resolved
24249 				 * address mblk - which holds the real
24250 				 * dl_unitdata_req with the resolved address.
24251 				 *
24252 				 * Doing this is the same behavior as was
24253 				 * previously used in the v4 ARP case.
24254 				 */
24255 				mutex_enter(&nce->nce_lock);
24256 				if (nce->nce_res_mp != NULL)
24257 					freemsg(nce->nce_res_mp);
24258 				nce->nce_res_mp = mp1;
24259 				mutex_exit(&nce->nce_lock);
24260 				/*
24261 				 * We do a fastpath probe here because
24262 				 * we have resolved the address without
24263 				 * using Neighbor Discovery.
24264 				 * In the non-XRESOLV v6 case, the fastpath
24265 				 * probe is done right after neighbor
24266 				 * discovery completes.
24267 				 */
24268 				if (nce->nce_res_mp != NULL) {
24269 					int res;
24270 					nce_fastpath_list_add(nce);
24271 					res = ill_fastpath_probe(ill,
24272 					    nce->nce_res_mp);
24273 					if (res != 0 && res != EAGAIN)
24274 						nce_fastpath_list_delete(nce);
24275 				}
24276 
24277 				ire_add_then_send(q, ire, mp);
24278 				/*
24279 				 * Now we have to clean out any packets
24280 				 * that may have been queued on the nce
24281 				 * while it was waiting for address resolution
24282 				 * to complete.
24283 				 */
24284 				mutex_enter(&nce->nce_lock);
24285 				mp1 = nce->nce_qd_mp;
24286 				nce->nce_qd_mp = NULL;
24287 				mutex_exit(&nce->nce_lock);
24288 				while (mp1 != NULL) {
24289 					mblk_t *nxt_mp;
24290 					queue_t *fwdq = NULL;
24291 					ill_t   *inbound_ill;
24292 					uint_t ifindex;
24293 
24294 					nxt_mp = mp1->b_next;
24295 					mp1->b_next = NULL;
24296 					/*
24297 					 * Retrieve ifindex stored in
24298 					 * ip_rput_data_v6()
24299 					 */
24300 					ifindex =
24301 					    (uint_t)(uintptr_t)mp1->b_prev;
24302 					inbound_ill =
24303 						ill_lookup_on_ifindex(ifindex,
24304 						    B_TRUE, NULL, NULL, NULL,
24305 						    NULL);
24306 					mp1->b_prev = NULL;
24307 					if (inbound_ill != NULL)
24308 						fwdq = inbound_ill->ill_rq;
24309 
24310 					if (fwdq != NULL) {
24311 						put(fwdq, mp1);
24312 						ill_refrele(inbound_ill);
24313 					} else
24314 						put(WR(ill->ill_rq), mp1);
24315 					mp1 = nxt_mp;
24316 				}
24317 				NCE_REFRELE(nce);
24318 			} else {	/* nce is NULL; clean up */
24319 				ire_delete(ire);
24320 				freemsg(mp);
24321 				freemsg(mp1);
24322 				return;
24323 			}
24324 		} else {
24325 			ire->ire_dlureq_mp = mp1;
24326 			ire_add_then_send(q, ire, mp);
24327 		}
24328 		return;	/* All is well, the packet has been sent. */
24329 	}
24330 	default:
24331 		break;
24332 	}
24333 	if (q->q_next) {
24334 		putnext(q, mp);
24335 	} else
24336 		freemsg(mp);
24337 }
24338 
24339 /*
24340  * Process IP options in an outbound packet.  Modify the destination if there
24341  * is a source route option.
24342  * Returns non-zero if something fails in which case an ICMP error has been
24343  * sent and mp freed.
24344  */
24345 static int
24346 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24347     boolean_t mctl_present, zoneid_t zoneid)
24348 {
24349 	ipoptp_t	opts;
24350 	uchar_t		*opt;
24351 	uint8_t		optval;
24352 	uint8_t		optlen;
24353 	ipaddr_t	dst;
24354 	intptr_t	code = 0;
24355 	mblk_t		*mp;
24356 	ire_t		*ire = NULL;
24357 
24358 	ip2dbg(("ip_wput_options\n"));
24359 	mp = ipsec_mp;
24360 	if (mctl_present) {
24361 		mp = ipsec_mp->b_cont;
24362 	}
24363 
24364 	dst = ipha->ipha_dst;
24365 	for (optval = ipoptp_first(&opts, ipha);
24366 	    optval != IPOPT_EOL;
24367 	    optval = ipoptp_next(&opts)) {
24368 		opt = opts.ipoptp_cur;
24369 		optlen = opts.ipoptp_len;
24370 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24371 		    optval, optlen));
24372 		switch (optval) {
24373 			uint32_t off;
24374 		case IPOPT_SSRR:
24375 		case IPOPT_LSRR:
24376 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24377 				ip1dbg((
24378 				    "ip_wput_options: bad option offset\n"));
24379 				code = (char *)&opt[IPOPT_OLEN] -
24380 				    (char *)ipha;
24381 				goto param_prob;
24382 			}
24383 			off = opt[IPOPT_OFFSET];
24384 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24385 			    ntohl(dst)));
24386 			/*
24387 			 * For strict: verify that dst is directly
24388 			 * reachable.
24389 			 */
24390 			if (optval == IPOPT_SSRR) {
24391 				ire = ire_ftable_lookup(dst, 0, 0,
24392 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24393 				    MATCH_IRE_TYPE);
24394 				if (ire == NULL) {
24395 					ip1dbg(("ip_wput_options: SSRR not"
24396 					    " directly reachable: 0x%x\n",
24397 					    ntohl(dst)));
24398 					goto bad_src_route;
24399 				}
24400 				ire_refrele(ire);
24401 			}
24402 			break;
24403 		case IPOPT_RR:
24404 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24405 				ip1dbg((
24406 				    "ip_wput_options: bad option offset\n"));
24407 				code = (char *)&opt[IPOPT_OLEN] -
24408 				    (char *)ipha;
24409 				goto param_prob;
24410 			}
24411 			break;
24412 		case IPOPT_TS:
24413 			/*
24414 			 * Verify that length >=5 and that there is either
24415 			 * room for another timestamp or that the overflow
24416 			 * counter is not maxed out.
24417 			 */
24418 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24419 			if (optlen < IPOPT_MINLEN_IT) {
24420 				goto param_prob;
24421 			}
24422 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24423 				ip1dbg((
24424 				    "ip_wput_options: bad option offset\n"));
24425 				code = (char *)&opt[IPOPT_OFFSET] -
24426 				    (char *)ipha;
24427 				goto param_prob;
24428 			}
24429 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24430 			case IPOPT_TS_TSONLY:
24431 				off = IPOPT_TS_TIMELEN;
24432 				break;
24433 			case IPOPT_TS_TSANDADDR:
24434 			case IPOPT_TS_PRESPEC:
24435 			case IPOPT_TS_PRESPEC_RFC791:
24436 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24437 				break;
24438 			default:
24439 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24440 				    (char *)ipha;
24441 				goto param_prob;
24442 			}
24443 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24444 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24445 				/*
24446 				 * No room and the overflow counter is 15
24447 				 * already.
24448 				 */
24449 				goto param_prob;
24450 			}
24451 			break;
24452 		}
24453 	}
24454 
24455 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24456 		return (0);
24457 
24458 	ip1dbg(("ip_wput_options: error processing IP options."));
24459 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24460 
24461 param_prob:
24462 	/*
24463 	 * Since ip_wput() isn't close to finished, we fill
24464 	 * in enough of the header for credible error reporting.
24465 	 */
24466 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24467 		/* Failed */
24468 		freemsg(ipsec_mp);
24469 		return (-1);
24470 	}
24471 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24472 	return (-1);
24473 
24474 bad_src_route:
24475 	/*
24476 	 * Since ip_wput() isn't close to finished, we fill
24477 	 * in enough of the header for credible error reporting.
24478 	 */
24479 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24480 		/* Failed */
24481 		freemsg(ipsec_mp);
24482 		return (-1);
24483 	}
24484 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24485 	return (-1);
24486 }
24487 
24488 /*
24489  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
24490  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
24491  * thru /etc/system.
24492  */
24493 #define	CONN_MAXDRAINCNT	64
24494 
24495 static void
24496 conn_drain_init(void)
24497 {
24498 	int i;
24499 
24500 	conn_drain_list_cnt = conn_drain_nthreads;
24501 
24502 	if ((conn_drain_list_cnt == 0) ||
24503 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
24504 		/*
24505 		 * Default value of the number of drainers is the
24506 		 * number of cpus, subject to maximum of 8 drainers.
24507 		 */
24508 		if (boot_max_ncpus != -1)
24509 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
24510 		else
24511 			conn_drain_list_cnt = MIN(max_ncpus, 8);
24512 	}
24513 
24514 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
24515 	    KM_SLEEP);
24516 
24517 	for (i = 0; i < conn_drain_list_cnt; i++) {
24518 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
24519 		    MUTEX_DEFAULT, NULL);
24520 	}
24521 }
24522 
24523 static void
24524 conn_drain_fini(void)
24525 {
24526 	int i;
24527 
24528 	for (i = 0; i < conn_drain_list_cnt; i++)
24529 		mutex_destroy(&conn_drain_list[i].idl_lock);
24530 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
24531 	conn_drain_list = NULL;
24532 }
24533 
24534 /*
24535  * Note: For an overview of how flowcontrol is handled in IP please see the
24536  * IP Flowcontrol notes at the top of this file.
24537  *
24538  * Flow control has blocked us from proceeding. Insert the given conn in one
24539  * of the conn drain lists. These conn wq's will be qenabled later on when
24540  * STREAMS flow control does a backenable. conn_walk_drain will enable
24541  * the first conn in each of these drain lists. Each of these qenabled conns
24542  * in turn enables the next in the list, after it runs, or when it closes,
24543  * thus sustaining the drain process.
24544  *
24545  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
24546  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
24547  * running at any time, on a given conn, since there can be only 1 service proc
24548  * running on a queue at any time.
24549  */
24550 void
24551 conn_drain_insert(conn_t *connp)
24552 {
24553 	idl_t	*idl;
24554 	uint_t	index;
24555 
24556 	mutex_enter(&connp->conn_lock);
24557 	if (connp->conn_state_flags & CONN_CLOSING) {
24558 		/*
24559 		 * The conn is closing as a result of which CONN_CLOSING
24560 		 * is set. Return.
24561 		 */
24562 		mutex_exit(&connp->conn_lock);
24563 		return;
24564 	} else if (connp->conn_idl == NULL) {
24565 		/*
24566 		 * Assign the next drain list round robin. We dont' use
24567 		 * a lock, and thus it may not be strictly round robin.
24568 		 * Atomicity of load/stores is enough to make sure that
24569 		 * conn_drain_list_index is always within bounds.
24570 		 */
24571 		index = conn_drain_list_index;
24572 		ASSERT(index < conn_drain_list_cnt);
24573 		connp->conn_idl = &conn_drain_list[index];
24574 		index++;
24575 		if (index == conn_drain_list_cnt)
24576 			index = 0;
24577 		conn_drain_list_index = index;
24578 	}
24579 	mutex_exit(&connp->conn_lock);
24580 
24581 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24582 	if ((connp->conn_drain_prev != NULL) ||
24583 	    (connp->conn_state_flags & CONN_CLOSING)) {
24584 		/*
24585 		 * The conn is already in the drain list, OR
24586 		 * the conn is closing. We need to check again for
24587 		 * the closing case again since close can happen
24588 		 * after we drop the conn_lock, and before we
24589 		 * acquire the CONN_DRAIN_LIST_LOCK.
24590 		 */
24591 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24592 		return;
24593 	} else {
24594 		idl = connp->conn_idl;
24595 	}
24596 
24597 	/*
24598 	 * The conn is not in the drain list. Insert it at the
24599 	 * tail of the drain list. The drain list is circular
24600 	 * and doubly linked. idl_conn points to the 1st element
24601 	 * in the list.
24602 	 */
24603 	if (idl->idl_conn == NULL) {
24604 		idl->idl_conn = connp;
24605 		connp->conn_drain_next = connp;
24606 		connp->conn_drain_prev = connp;
24607 	} else {
24608 		conn_t *head = idl->idl_conn;
24609 
24610 		connp->conn_drain_next = head;
24611 		connp->conn_drain_prev = head->conn_drain_prev;
24612 		head->conn_drain_prev->conn_drain_next = connp;
24613 		head->conn_drain_prev = connp;
24614 	}
24615 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24616 }
24617 
24618 /*
24619  * This conn is closing, and we are called from ip_close. OR
24620  * This conn has been serviced by ip_wsrv, and we need to do the tail
24621  * processing.
24622  * If this conn is part of the drain list, we may need to sustain the drain
24623  * process by qenabling the next conn in the drain list. We may also need to
24624  * remove this conn from the list, if it is done.
24625  */
24626 static void
24627 conn_drain_tail(conn_t *connp, boolean_t closing)
24628 {
24629 	idl_t *idl;
24630 
24631 	/*
24632 	 * connp->conn_idl is stable at this point, and no lock is needed
24633 	 * to check it. If we are called from ip_close, close has already
24634 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
24635 	 * called us only because conn_idl is non-null. If we are called thru
24636 	 * service, conn_idl could be null, but it cannot change because
24637 	 * service is single-threaded per queue, and there cannot be another
24638 	 * instance of service trying to call conn_drain_insert on this conn
24639 	 * now.
24640 	 */
24641 	ASSERT(!closing || (connp->conn_idl != NULL));
24642 
24643 	/*
24644 	 * If connp->conn_idl is null, the conn has not been inserted into any
24645 	 * drain list even once since creation of the conn. Just return.
24646 	 */
24647 	if (connp->conn_idl == NULL)
24648 		return;
24649 
24650 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24651 
24652 	if (connp->conn_drain_prev == NULL) {
24653 		/* This conn is currently not in the drain list.  */
24654 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24655 		return;
24656 	}
24657 	idl = connp->conn_idl;
24658 	if (idl->idl_conn_draining == connp) {
24659 		/*
24660 		 * This conn is the current drainer. If this is the last conn
24661 		 * in the drain list, we need to do more checks, in the 'if'
24662 		 * below. Otherwwise we need to just qenable the next conn,
24663 		 * to sustain the draining, and is handled in the 'else'
24664 		 * below.
24665 		 */
24666 		if (connp->conn_drain_next == idl->idl_conn) {
24667 			/*
24668 			 * This conn is the last in this list. This round
24669 			 * of draining is complete. If idl_repeat is set,
24670 			 * it means another flow enabling has happened from
24671 			 * the driver/streams and we need to another round
24672 			 * of draining.
24673 			 * If there are more than 2 conns in the drain list,
24674 			 * do a left rotate by 1, so that all conns except the
24675 			 * conn at the head move towards the head by 1, and the
24676 			 * the conn at the head goes to the tail. This attempts
24677 			 * a more even share for all queues that are being
24678 			 * drained.
24679 			 */
24680 			if ((connp->conn_drain_next != connp) &&
24681 			    (idl->idl_conn->conn_drain_next != connp)) {
24682 				idl->idl_conn = idl->idl_conn->conn_drain_next;
24683 			}
24684 			if (idl->idl_repeat) {
24685 				qenable(idl->idl_conn->conn_wq);
24686 				idl->idl_conn_draining = idl->idl_conn;
24687 				idl->idl_repeat = 0;
24688 			} else {
24689 				idl->idl_conn_draining = NULL;
24690 			}
24691 		} else {
24692 			/*
24693 			 * If the next queue that we are now qenable'ing,
24694 			 * is closing, it will remove itself from this list
24695 			 * and qenable the subsequent queue in ip_close().
24696 			 * Serialization is acheived thru idl_lock.
24697 			 */
24698 			qenable(connp->conn_drain_next->conn_wq);
24699 			idl->idl_conn_draining = connp->conn_drain_next;
24700 		}
24701 	}
24702 	if (!connp->conn_did_putbq || closing) {
24703 		/*
24704 		 * Remove ourself from the drain list, if we did not do
24705 		 * a putbq, or if the conn is closing.
24706 		 * Note: It is possible that q->q_first is non-null. It means
24707 		 * that these messages landed after we did a enableok() in
24708 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
24709 		 * service them.
24710 		 */
24711 		if (connp->conn_drain_next == connp) {
24712 			/* Singleton in the list */
24713 			ASSERT(connp->conn_drain_prev == connp);
24714 			idl->idl_conn = NULL;
24715 			idl->idl_conn_draining = NULL;
24716 		} else {
24717 			connp->conn_drain_prev->conn_drain_next =
24718 			    connp->conn_drain_next;
24719 			connp->conn_drain_next->conn_drain_prev =
24720 			    connp->conn_drain_prev;
24721 			if (idl->idl_conn == connp)
24722 				idl->idl_conn = connp->conn_drain_next;
24723 			ASSERT(idl->idl_conn_draining != connp);
24724 
24725 		}
24726 		connp->conn_drain_next = NULL;
24727 		connp->conn_drain_prev = NULL;
24728 	}
24729 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24730 }
24731 
24732 /*
24733  * Write service routine. Shared perimeter entry point.
24734  * ip_wsrv can be called in any of the following ways.
24735  * 1. The device queue's messages has fallen below the low water mark
24736  *    and STREAMS has backenabled the ill_wq. We walk thru all the
24737  *    the drain lists and backenable the first conn in each list.
24738  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
24739  *    qenabled non-tcp upper layers. We start dequeing messages and call
24740  *    ip_wput for each message.
24741  */
24742 
24743 void
24744 ip_wsrv(queue_t *q)
24745 {
24746 	conn_t	*connp;
24747 	ill_t	*ill;
24748 	mblk_t	*mp;
24749 
24750 	if (q->q_next) {
24751 		ill = (ill_t *)q->q_ptr;
24752 		if (ill->ill_state_flags == 0) {
24753 			/*
24754 			 * The device flow control has opened up.
24755 			 * Walk through conn drain lists and qenable the
24756 			 * first conn in each list. This makes sense only
24757 			 * if the stream is fully plumbed and setup.
24758 			 * Hence the if check above.
24759 			 */
24760 			ip1dbg(("ip_wsrv: walking\n"));
24761 			conn_walk_drain();
24762 		}
24763 		return;
24764 	}
24765 
24766 	connp = Q_TO_CONN(q);
24767 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
24768 
24769 	/*
24770 	 * 1. Set conn_draining flag to signal that service is active.
24771 	 *
24772 	 * 2. ip_output determines whether it has been called from service,
24773 	 *    based on the last parameter. If it is IP_WSRV it concludes it
24774 	 *    has been called from service.
24775 	 *
24776 	 * 3. Message ordering is preserved by the following logic.
24777 	 *    i. A directly called ip_output (i.e. not thru service) will queue
24778 	 *    the message at the tail, if conn_draining is set (i.e. service
24779 	 *    is running) or if q->q_first is non-null.
24780 	 *
24781 	 *    ii. If ip_output is called from service, and if ip_output cannot
24782 	 *    putnext due to flow control, it does a putbq.
24783 	 *
24784 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
24785 	 *    (causing an infinite loop).
24786 	 */
24787 	ASSERT(!connp->conn_did_putbq);
24788 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
24789 		connp->conn_draining = 1;
24790 		noenable(q);
24791 		while ((mp = getq(q)) != NULL) {
24792 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
24793 			if (connp->conn_did_putbq) {
24794 				/* ip_wput did a putbq */
24795 				break;
24796 			}
24797 		}
24798 		/*
24799 		 * At this point, a thread coming down from top, calling
24800 		 * ip_wput, may end up queueing the message. We have not yet
24801 		 * enabled the queue, so ip_wsrv won't be called again.
24802 		 * To avoid this race, check q->q_first again (in the loop)
24803 		 * If the other thread queued the message before we call
24804 		 * enableok(), we will catch it in the q->q_first check.
24805 		 * If the other thread queues the message after we call
24806 		 * enableok(), ip_wsrv will be called again by STREAMS.
24807 		 */
24808 		connp->conn_draining = 0;
24809 		enableok(q);
24810 	}
24811 
24812 	/* Enable the next conn for draining */
24813 	conn_drain_tail(connp, B_FALSE);
24814 
24815 	connp->conn_did_putbq = 0;
24816 }
24817 
24818 /*
24819  * Walk the list of all conn's calling the function provided with the
24820  * specified argument for each.	 Note that this only walks conn's that
24821  * have been bound.
24822  * Applies to both IPv4 and IPv6.
24823  */
24824 static void
24825 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
24826 {
24827 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
24828 	    func, arg, zoneid);
24829 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
24830 	    func, arg, zoneid);
24831 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
24832 	    func, arg, zoneid);
24833 	conn_walk_fanout_table(ipcl_proto_fanout,
24834 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
24835 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
24836 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
24837 }
24838 
24839 /*
24840  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
24841  * of conns that need to be drained, check if drain is already in progress.
24842  * If so set the idl_repeat bit, indicating that the last conn in the list
24843  * needs to reinitiate the drain once again, for the list. If drain is not
24844  * in progress for the list, initiate the draining, by qenabling the 1st
24845  * conn in the list. The drain is self-sustaining, each qenabled conn will
24846  * in turn qenable the next conn, when it is done/blocked/closing.
24847  */
24848 static void
24849 conn_walk_drain(void)
24850 {
24851 	int i;
24852 	idl_t *idl;
24853 
24854 	IP_STAT(ip_conn_walk_drain);
24855 
24856 	for (i = 0; i < conn_drain_list_cnt; i++) {
24857 		idl = &conn_drain_list[i];
24858 		mutex_enter(&idl->idl_lock);
24859 		if (idl->idl_conn == NULL) {
24860 			mutex_exit(&idl->idl_lock);
24861 			continue;
24862 		}
24863 		/*
24864 		 * If this list is not being drained currently by
24865 		 * an ip_wsrv thread, start the process.
24866 		 */
24867 		if (idl->idl_conn_draining == NULL) {
24868 			ASSERT(idl->idl_repeat == 0);
24869 			qenable(idl->idl_conn->conn_wq);
24870 			idl->idl_conn_draining = idl->idl_conn;
24871 		} else {
24872 			idl->idl_repeat = 1;
24873 		}
24874 		mutex_exit(&idl->idl_lock);
24875 	}
24876 }
24877 
24878 /*
24879  * Walk an conn hash table of `count' buckets, calling func for each entry.
24880  */
24881 static void
24882 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
24883     zoneid_t zoneid)
24884 {
24885 	conn_t	*connp;
24886 
24887 	while (count-- > 0) {
24888 		mutex_enter(&connfp->connf_lock);
24889 		for (connp = connfp->connf_head; connp != NULL;
24890 		    connp = connp->conn_next) {
24891 			if (zoneid == GLOBAL_ZONEID ||
24892 			    zoneid == connp->conn_zoneid) {
24893 				CONN_INC_REF(connp);
24894 				mutex_exit(&connfp->connf_lock);
24895 				(*func)(connp, arg);
24896 				mutex_enter(&connfp->connf_lock);
24897 				CONN_DEC_REF(connp);
24898 			}
24899 		}
24900 		mutex_exit(&connfp->connf_lock);
24901 		connfp++;
24902 	}
24903 }
24904 
24905 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
24906 static void
24907 conn_report1(conn_t *connp, void *mp)
24908 {
24909 	char	buf1[INET6_ADDRSTRLEN];
24910 	char	buf2[INET6_ADDRSTRLEN];
24911 	uint_t	print_len, buf_len;
24912 
24913 	ASSERT(connp != NULL);
24914 
24915 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
24916 	if (buf_len <= 0)
24917 		return;
24918 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
24919 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
24920 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
24921 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
24922 	    "%5d %s/%05d %s/%05d\n",
24923 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
24924 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
24925 	    buf1, connp->conn_lport,
24926 	    buf2, connp->conn_fport);
24927 	if (print_len < buf_len) {
24928 		((mblk_t *)mp)->b_wptr += print_len;
24929 	} else {
24930 		((mblk_t *)mp)->b_wptr += buf_len;
24931 	}
24932 }
24933 
24934 /*
24935  * Named Dispatch routine to produce a formatted report on all conns
24936  * that are listed in one of the fanout tables.
24937  * This report is accessed by using the ndd utility to "get" ND variable
24938  * "ip_conn_status".
24939  */
24940 /* ARGSUSED */
24941 static int
24942 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
24943 {
24944 	(void) mi_mpprintf(mp,
24945 	    "CONN      " MI_COL_HDRPAD_STR
24946 	    "rfq      " MI_COL_HDRPAD_STR
24947 	    "stq      " MI_COL_HDRPAD_STR
24948 	    " zone local                 remote");
24949 
24950 	/*
24951 	 * Because of the ndd constraint, at most we can have 64K buffer
24952 	 * to put in all conn info.  So to be more efficient, just
24953 	 * allocate a 64K buffer here, assuming we need that large buffer.
24954 	 * This should be OK as only privileged processes can do ndd /dev/ip.
24955 	 */
24956 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
24957 		/* The following may work even if we cannot get a large buf. */
24958 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
24959 		return (0);
24960 	}
24961 
24962 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
24963 	return (0);
24964 }
24965 
24966 /*
24967  * Determine if the ill and multicast aspects of that packets
24968  * "matches" the conn.
24969  */
24970 boolean_t
24971 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
24972     zoneid_t zoneid)
24973 {
24974 	ill_t *in_ill;
24975 	boolean_t found;
24976 	ipif_t *ipif;
24977 	ire_t *ire;
24978 	ipaddr_t dst, src;
24979 
24980 	dst = ipha->ipha_dst;
24981 	src = ipha->ipha_src;
24982 
24983 	/*
24984 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
24985 	 * unicast, broadcast and multicast reception to
24986 	 * conn_incoming_ill. conn_wantpacket itself is called
24987 	 * only for BROADCAST and multicast.
24988 	 *
24989 	 * 1) ip_rput supresses duplicate broadcasts if the ill
24990 	 *    is part of a group. Hence, we should be receiving
24991 	 *    just one copy of broadcast for the whole group.
24992 	 *    Thus, if it is part of the group the packet could
24993 	 *    come on any ill of the group and hence we need a
24994 	 *    match on the group. Otherwise, match on ill should
24995 	 *    be sufficient.
24996 	 *
24997 	 * 2) ip_rput does not suppress duplicate multicast packets.
24998 	 *    If there are two interfaces in a ill group and we have
24999 	 *    2 applications (conns) joined a multicast group G on
25000 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
25001 	 *    will give us two packets because we join G on both the
25002 	 *    interfaces rather than nominating just one interface
25003 	 *    for receiving multicast like broadcast above. So,
25004 	 *    we have to call ilg_lookup_ill to filter out duplicate
25005 	 *    copies, if ill is part of a group.
25006 	 */
25007 	in_ill = connp->conn_incoming_ill;
25008 	if (in_ill != NULL) {
25009 		if (in_ill->ill_group == NULL) {
25010 			if (in_ill != ill)
25011 				return (B_FALSE);
25012 		} else if (in_ill->ill_group != ill->ill_group) {
25013 			return (B_FALSE);
25014 		}
25015 	}
25016 
25017 	if (!CLASSD(dst)) {
25018 		if (connp->conn_zoneid == zoneid)
25019 			return (B_TRUE);
25020 		/*
25021 		 * The conn is in a different zone; we need to check that this
25022 		 * broadcast address is configured in the application's zone and
25023 		 * on one ill in the group.
25024 		 */
25025 		ipif = ipif_get_next_ipif(NULL, ill);
25026 		if (ipif == NULL)
25027 			return (B_FALSE);
25028 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25029 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25030 		ipif_refrele(ipif);
25031 		if (ire != NULL) {
25032 			ire_refrele(ire);
25033 			return (B_TRUE);
25034 		} else {
25035 			return (B_FALSE);
25036 		}
25037 	}
25038 
25039 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25040 	    connp->conn_zoneid == zoneid) {
25041 		/*
25042 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25043 		 * disabled, therefore we don't dispatch the multicast packet to
25044 		 * the sending zone.
25045 		 */
25046 		return (B_FALSE);
25047 	}
25048 
25049 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25050 	    connp->conn_zoneid != zoneid) {
25051 		/*
25052 		 * Multicast packet on the loopback interface: we only match
25053 		 * conns who joined the group in the specified zone.
25054 		 */
25055 		return (B_FALSE);
25056 	}
25057 
25058 	if (connp->conn_multi_router) {
25059 		/* multicast packet and multicast router socket: send up */
25060 		return (B_TRUE);
25061 	}
25062 
25063 	mutex_enter(&connp->conn_lock);
25064 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25065 	mutex_exit(&connp->conn_lock);
25066 	return (found);
25067 }
25068 
25069 /*
25070  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25071  */
25072 /* ARGSUSED */
25073 static void
25074 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25075 {
25076 	ill_t *ill = (ill_t *)q->q_ptr;
25077 	mblk_t	*mp1, *mp2;
25078 	ipif_t  *ipif;
25079 	int err = 0;
25080 	conn_t *connp = NULL;
25081 	ipsq_t	*ipsq;
25082 	arc_t	*arc;
25083 
25084 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25085 
25086 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25087 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25088 
25089 	ASSERT(IAM_WRITER_ILL(ill));
25090 	mp2 = mp->b_cont;
25091 	mp->b_cont = NULL;
25092 
25093 	/*
25094 	 * We have now received the arp bringup completion message
25095 	 * from ARP. Mark the arp bringup as done. Also if the arp
25096 	 * stream has already started closing, send up the AR_ARP_CLOSING
25097 	 * ack now since ARP is waiting in close for this ack.
25098 	 */
25099 	mutex_enter(&ill->ill_lock);
25100 	ill->ill_arp_bringup_pending = 0;
25101 	if (ill->ill_arp_closing) {
25102 		mutex_exit(&ill->ill_lock);
25103 		/* Let's reuse the mp for sending the ack */
25104 		arc = (arc_t *)mp->b_rptr;
25105 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25106 		arc->arc_cmd = AR_ARP_CLOSING;
25107 		qreply(q, mp);
25108 	} else {
25109 		mutex_exit(&ill->ill_lock);
25110 		freeb(mp);
25111 	}
25112 
25113 	/* We should have an IOCTL waiting on this. */
25114 	ipsq = ill->ill_phyint->phyint_ipsq;
25115 	ipif = ipsq->ipsq_pending_ipif;
25116 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25117 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25118 	if (mp1 == NULL) {
25119 		/* bringup was aborted by the user */
25120 		freemsg(mp2);
25121 		return;
25122 	}
25123 	ASSERT(connp != NULL);
25124 	q = CONNP_TO_WQ(connp);
25125 	/*
25126 	 * If the DL_BIND_REQ fails, it is noted
25127 	 * in arc_name_offset.
25128 	 */
25129 	err = *((int *)mp2->b_rptr);
25130 	if (err == 0) {
25131 		if (ipif->ipif_isv6) {
25132 			if ((err = ipif_up_done_v6(ipif)) != 0)
25133 				ip0dbg(("ip_arp_done: init failed\n"));
25134 		} else {
25135 			if ((err = ipif_up_done(ipif)) != 0)
25136 				ip0dbg(("ip_arp_done: init failed\n"));
25137 		}
25138 	} else {
25139 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25140 	}
25141 
25142 	freemsg(mp2);
25143 
25144 	if ((err == 0) && (ill->ill_up_ipifs)) {
25145 		err = ill_up_ipifs(ill, q, mp1);
25146 		if (err == EINPROGRESS)
25147 			return;
25148 	}
25149 
25150 	if (ill->ill_up_ipifs) {
25151 		ill_group_cleanup(ill);
25152 	}
25153 
25154 	/*
25155 	 * The ioctl must complete now without EINPROGRESS
25156 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25157 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25158 	 * stuck for ever in the ipsq.
25159 	 */
25160 	ASSERT(err != EINPROGRESS);
25161 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25162 }
25163 
25164 /* Allocate the private structure */
25165 static int
25166 ip_priv_alloc(void **bufp)
25167 {
25168 	void	*buf;
25169 
25170 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25171 		return (ENOMEM);
25172 
25173 	*bufp = buf;
25174 	return (0);
25175 }
25176 
25177 /* Function to delete the private structure */
25178 void
25179 ip_priv_free(void *buf)
25180 {
25181 	ASSERT(buf != NULL);
25182 	kmem_free(buf, sizeof (ip_priv_t));
25183 }
25184 
25185 /*
25186  * The entry point for IPPF processing.
25187  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25188  * routine just returns.
25189  *
25190  * When called, ip_process generates an ipp_packet_t structure
25191  * which holds the state information for this packet and invokes the
25192  * the classifier (via ipp_packet_process). The classification, depending on
25193  * configured filters, results in a list of actions for this packet. Invoking
25194  * an action may cause the packet to be dropped, in which case the resulting
25195  * mblk (*mpp) is NULL. proc indicates the callout position for
25196  * this packet and ill_index is the interface this packet on or will leave
25197  * on (inbound and outbound resp.).
25198  */
25199 void
25200 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25201 {
25202 	mblk_t		*mp;
25203 	ip_priv_t	*priv;
25204 	ipp_action_id_t	aid;
25205 	int		rc = 0;
25206 	ipp_packet_t	*pp;
25207 #define	IP_CLASS	"ip"
25208 
25209 	/* If the classifier is not loaded, return  */
25210 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25211 		return;
25212 	}
25213 
25214 	mp = *mpp;
25215 	ASSERT(mp != NULL);
25216 
25217 	/* Allocate the packet structure */
25218 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25219 	if (rc != 0) {
25220 		*mpp = NULL;
25221 		freemsg(mp);
25222 		return;
25223 	}
25224 
25225 	/* Allocate the private structure */
25226 	rc = ip_priv_alloc((void **)&priv);
25227 	if (rc != 0) {
25228 		*mpp = NULL;
25229 		freemsg(mp);
25230 		ipp_packet_free(pp);
25231 		return;
25232 	}
25233 	priv->proc = proc;
25234 	priv->ill_index = ill_index;
25235 	ipp_packet_set_private(pp, priv, ip_priv_free);
25236 	ipp_packet_set_data(pp, mp);
25237 
25238 	/* Invoke the classifier */
25239 	rc = ipp_packet_process(&pp);
25240 	if (pp != NULL) {
25241 		mp = ipp_packet_get_data(pp);
25242 		ipp_packet_free(pp);
25243 		if (rc != 0) {
25244 			freemsg(mp);
25245 			*mpp = NULL;
25246 		}
25247 	} else {
25248 		*mpp = NULL;
25249 	}
25250 #undef	IP_CLASS
25251 }
25252 
25253 /*
25254  * Propagate a multicast group membership operation (add/drop) on
25255  * all the interfaces crossed by the related multirt routes.
25256  * The call is considered successful if the operation succeeds
25257  * on at least one interface.
25258  */
25259 static int
25260 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25261     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25262     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25263     mblk_t *first_mp)
25264 {
25265 	ire_t		*ire_gw;
25266 	irb_t		*irb;
25267 	int		error = 0;
25268 	opt_restart_t	*or;
25269 
25270 	irb = ire->ire_bucket;
25271 	ASSERT(irb != NULL);
25272 
25273 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25274 
25275 	or = (opt_restart_t *)first_mp->b_rptr;
25276 	IRB_REFHOLD(irb);
25277 	for (; ire != NULL; ire = ire->ire_next) {
25278 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25279 			continue;
25280 		if (ire->ire_addr != group)
25281 			continue;
25282 
25283 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25284 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25285 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25286 		/* No resolver exists for the gateway; skip this ire. */
25287 		if (ire_gw == NULL)
25288 			continue;
25289 
25290 		/*
25291 		 * This function can return EINPROGRESS. If so the operation
25292 		 * will be restarted from ip_restart_optmgmt which will
25293 		 * call ip_opt_set and option processing will restart for
25294 		 * this option. So we may end up calling 'fn' more than once.
25295 		 * This requires that 'fn' is idempotent except for the
25296 		 * return value. The operation is considered a success if
25297 		 * it succeeds at least once on any one interface.
25298 		 */
25299 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25300 		    NULL, fmode, src, first_mp);
25301 		if (error == 0)
25302 			or->or_private = CGTP_MCAST_SUCCESS;
25303 
25304 		if (ip_debug > 0) {
25305 			ulong_t	off;
25306 			char	*ksym;
25307 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25308 			ip2dbg(("ip_multirt_apply_membership: "
25309 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25310 			    "error %d [success %u]\n",
25311 			    ksym ? ksym : "?",
25312 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25313 			    error, or->or_private));
25314 		}
25315 
25316 		ire_refrele(ire_gw);
25317 		if (error == EINPROGRESS) {
25318 			IRB_REFRELE(irb);
25319 			return (error);
25320 		}
25321 	}
25322 	IRB_REFRELE(irb);
25323 	/*
25324 	 * Consider the call as successful if we succeeded on at least
25325 	 * one interface. Otherwise, return the last encountered error.
25326 	 */
25327 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25328 }
25329 
25330 
25331 /*
25332  * Issue a warning regarding a route crossing an interface with an
25333  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25334  * amount of time is logged.
25335  */
25336 static void
25337 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25338 {
25339 	hrtime_t	current = gethrtime();
25340 	char		buf[16];
25341 
25342 	/* Convert interval in ms to hrtime in ns */
25343 	if (multirt_bad_mtu_last_time +
25344 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25345 	    current) {
25346 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25347 		    "to %s, incorrect MTU %u (expected %u)\n",
25348 		    ip_dot_addr(ire->ire_addr, buf),
25349 		    ire->ire_max_frag, max_frag);
25350 
25351 		multirt_bad_mtu_last_time = current;
25352 	}
25353 }
25354 
25355 
25356 /*
25357  * Get the CGTP (multirouting) filtering status.
25358  * If 0, the CGTP hooks are transparent.
25359  */
25360 /* ARGSUSED */
25361 static int
25362 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25363 {
25364 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25365 
25366 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25367 	return (0);
25368 }
25369 
25370 
25371 /*
25372  * Set the CGTP (multirouting) filtering status.
25373  * If the status is changed from active to transparent
25374  * or from transparent to active, forward the new status
25375  * to the filtering module (if loaded).
25376  */
25377 /* ARGSUSED */
25378 static int
25379 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25380     cred_t *ioc_cr)
25381 {
25382 	long		new_value;
25383 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25384 
25385 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25386 	    new_value < 0 || new_value > 1) {
25387 		return (EINVAL);
25388 	}
25389 
25390 	/*
25391 	 * Do not enable CGTP filtering - thus preventing the hooks
25392 	 * from being invoked - if the version number of the
25393 	 * filtering module hooks does not match.
25394 	 */
25395 	if ((ip_cgtp_filter_ops != NULL) &&
25396 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25397 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25398 		    "(module hooks version %d, expecting %d)\n",
25399 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25400 		return (ENOTSUP);
25401 	}
25402 
25403 	if ((!*ip_cgtp_filter_value) && new_value) {
25404 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25405 		    ip_cgtp_filter_ops == NULL ?
25406 		    " (module not loaded)" : "");
25407 	}
25408 	if (*ip_cgtp_filter_value && (!new_value)) {
25409 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25410 		    ip_cgtp_filter_ops == NULL ?
25411 		    " (module not loaded)" : "");
25412 	}
25413 
25414 	if (ip_cgtp_filter_ops != NULL) {
25415 		int	res;
25416 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25417 			return (res);
25418 		}
25419 	}
25420 
25421 	*ip_cgtp_filter_value = (boolean_t)new_value;
25422 
25423 	return (0);
25424 }
25425 
25426 
25427 /*
25428  * Return the expected CGTP hooks version number.
25429  */
25430 int
25431 ip_cgtp_filter_supported(void)
25432 {
25433 	return (ip_cgtp_filter_rev);
25434 }
25435 
25436 
25437 /*
25438  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25439  * or by invoking this function. In the first case, the version number
25440  * of the registered structure is checked at hooks activation time
25441  * in ip_cgtp_filter_set().
25442  */
25443 int
25444 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25445 {
25446 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25447 		return (ENOTSUP);
25448 
25449 	ip_cgtp_filter_ops = ops;
25450 	return (0);
25451 }
25452 
25453 static squeue_func_t
25454 ip_squeue_switch(int val)
25455 {
25456 	squeue_func_t rval = squeue_fill;
25457 
25458 	switch (val) {
25459 	case IP_SQUEUE_ENTER_NODRAIN:
25460 		rval = squeue_enter_nodrain;
25461 		break;
25462 	case IP_SQUEUE_ENTER:
25463 		rval = squeue_enter;
25464 		break;
25465 	default:
25466 		break;
25467 	}
25468 	return (rval);
25469 }
25470 
25471 /* ARGSUSED */
25472 static int
25473 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25474     caddr_t addr, cred_t *cr)
25475 {
25476 	int *v = (int *)addr;
25477 	long new_value;
25478 
25479 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25480 		return (EINVAL);
25481 
25482 	ip_input_proc = ip_squeue_switch(new_value);
25483 	*v = new_value;
25484 	return (0);
25485 }
25486 
25487 /* ARGSUSED */
25488 static int
25489 ip_fanout_set(queue_t *q, mblk_t *mp, char *value,
25490     caddr_t addr, cred_t *cr)
25491 {
25492 	int *v = (int *)addr;
25493 	long new_value;
25494 
25495 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25496 		return (EINVAL);
25497 
25498 	*v = new_value;
25499 	return (0);
25500 }
25501 
25502 
25503 static void
25504 ip_kstat_init(void)
25505 {
25506 	ip_named_kstat_t template = {
25507 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
25508 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
25509 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
25510 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
25511 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
25512 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
25513 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
25514 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
25515 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
25516 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
25517 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
25518 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
25519 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
25520 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
25521 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
25522 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
25523 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
25524 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
25525 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
25526 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
25527 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
25528 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
25529 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
25530 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
25531 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
25532 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
25533 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
25534 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
25535 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
25536 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
25537 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
25538 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
25539 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
25540 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
25541 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
25542 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
25543 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
25544 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
25545 	};
25546 
25547 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
25548 					NUM_OF_FIELDS(ip_named_kstat_t),
25549 					0);
25550 	if (!ip_mibkp)
25551 		return;
25552 
25553 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
25554 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
25555 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
25556 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
25557 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
25558 
25559 	template.netToMediaEntrySize.value.i32 =
25560 		sizeof (mib2_ipNetToMediaEntry_t);
25561 
25562 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
25563 
25564 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
25565 
25566 	ip_mibkp->ks_update = ip_kstat_update;
25567 
25568 	kstat_install(ip_mibkp);
25569 }
25570 
25571 static void
25572 ip_kstat_fini(void)
25573 {
25574 
25575 	if (ip_mibkp != NULL) {
25576 		kstat_delete(ip_mibkp);
25577 		ip_mibkp = NULL;
25578 	}
25579 }
25580 
25581 static int
25582 ip_kstat_update(kstat_t *kp, int rw)
25583 {
25584 	ip_named_kstat_t *ipkp;
25585 
25586 	if (!kp || !kp->ks_data)
25587 		return (EIO);
25588 
25589 	if (rw == KSTAT_WRITE)
25590 		return (EACCES);
25591 
25592 	ipkp = (ip_named_kstat_t *)kp->ks_data;
25593 
25594 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
25595 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
25596 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
25597 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
25598 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
25599 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
25600 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
25601 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
25602 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
25603 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
25604 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
25605 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
25606 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
25607 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
25608 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
25609 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
25610 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
25611 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
25612 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
25613 
25614 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
25615 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
25616 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
25617 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
25618 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
25619 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
25620 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
25621 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
25622 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
25623 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
25624 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
25625 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
25626 
25627 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
25628 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
25629 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
25630 
25631 	return (0);
25632 }
25633 
25634 static void
25635 icmp_kstat_init(void)
25636 {
25637 	icmp_named_kstat_t template = {
25638 		{ "inMsgs",		KSTAT_DATA_UINT32 },
25639 		{ "inErrors",		KSTAT_DATA_UINT32 },
25640 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
25641 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
25642 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
25643 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
25644 		{ "inRedirects",	KSTAT_DATA_UINT32 },
25645 		{ "inEchos",		KSTAT_DATA_UINT32 },
25646 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
25647 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
25648 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
25649 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
25650 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
25651 		{ "outMsgs",		KSTAT_DATA_UINT32 },
25652 		{ "outErrors",		KSTAT_DATA_UINT32 },
25653 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
25654 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
25655 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
25656 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
25657 		{ "outRedirects",	KSTAT_DATA_UINT32 },
25658 		{ "outEchos",		KSTAT_DATA_UINT32 },
25659 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
25660 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
25661 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
25662 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
25663 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
25664 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
25665 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
25666 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
25667 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
25668 		{ "outDrops",		KSTAT_DATA_UINT32 },
25669 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
25670 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
25671 	};
25672 
25673 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
25674 					NUM_OF_FIELDS(icmp_named_kstat_t),
25675 					0);
25676 	if (icmp_mibkp == NULL)
25677 		return;
25678 
25679 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
25680 
25681 	icmp_mibkp->ks_update = icmp_kstat_update;
25682 
25683 	kstat_install(icmp_mibkp);
25684 }
25685 
25686 static void
25687 icmp_kstat_fini(void)
25688 {
25689 
25690 	if (icmp_mibkp != NULL) {
25691 		kstat_delete(icmp_mibkp);
25692 		icmp_mibkp = NULL;
25693 	}
25694 }
25695 
25696 static int
25697 icmp_kstat_update(kstat_t *kp, int rw)
25698 {
25699 	icmp_named_kstat_t *icmpkp;
25700 
25701 	if ((kp == NULL) || (kp->ks_data == NULL))
25702 		return (EIO);
25703 
25704 	if (rw == KSTAT_WRITE)
25705 		return (EACCES);
25706 
25707 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
25708 
25709 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
25710 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
25711 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
25712 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
25713 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
25714 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
25715 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
25716 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
25717 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
25718 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
25719 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
25720 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
25721 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
25722 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
25723 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
25724 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
25725 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
25726 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
25727 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
25728 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
25729 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
25730 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
25731 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
25732 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
25733 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
25734 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
25735 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
25736 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
25737 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
25738 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
25739 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
25740 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
25741 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
25742 
25743 	return (0);
25744 }
25745 
25746 /*
25747  * This is the fanout function for raw socket opened for SCTP.  Note
25748  * that it is called after SCTP checks that there is no socket which
25749  * wants a packet.  Then before SCTP handles this out of the blue packet,
25750  * this function is called to see if there is any raw socket for SCTP.
25751  * If there is and it is bound to the correct address, the packet will
25752  * be sent to that socket.  Note that only one raw socket can be bound to
25753  * a port.  This is assured in ipcl_sctp_hash_insert();
25754  */
25755 void
25756 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
25757     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
25758     uint_t ipif_seqid, zoneid_t zoneid)
25759 {
25760 	conn_t		*connp;
25761 	queue_t		*rq;
25762 	mblk_t		*first_mp;
25763 	boolean_t	secure;
25764 	ip6_t		*ip6h;
25765 
25766 	first_mp = mp;
25767 	if (mctl_present) {
25768 		mp = first_mp->b_cont;
25769 		secure = ipsec_in_is_secure(first_mp);
25770 		ASSERT(mp != NULL);
25771 	} else {
25772 		secure = B_FALSE;
25773 	}
25774 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
25775 
25776 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
25777 	if (connp == NULL) {
25778 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
25779 		    mctl_present);
25780 		return;
25781 	}
25782 	rq = connp->conn_rq;
25783 	if (!canputnext(rq)) {
25784 		CONN_DEC_REF(connp);
25785 		BUMP_MIB(&ip_mib, rawipInOverflows);
25786 		freemsg(first_mp);
25787 		return;
25788 	}
25789 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
25790 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
25791 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
25792 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
25793 		if (first_mp == NULL) {
25794 			CONN_DEC_REF(connp);
25795 			return;
25796 		}
25797 	}
25798 	/*
25799 	 * We probably should not send M_CTL message up to
25800 	 * raw socket.
25801 	 */
25802 	if (mctl_present)
25803 		freeb(first_mp);
25804 
25805 	/* Initiate IPPF processing here if needed. */
25806 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
25807 	    (!isv4 && IP6_IN_IPP(flags))) {
25808 		ip_process(IPP_LOCAL_IN, &mp,
25809 		    recv_ill->ill_phyint->phyint_ifindex);
25810 		if (mp == NULL) {
25811 			CONN_DEC_REF(connp);
25812 			return;
25813 		}
25814 	}
25815 
25816 	if (connp->conn_recvif || connp->conn_recvslla ||
25817 	    ((connp->conn_ipv6_recvpktinfo ||
25818 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
25819 	    (flags & IP_FF_IP6INFO))) {
25820 		int in_flags = 0;
25821 
25822 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
25823 			in_flags = IPF_RECVIF;
25824 		}
25825 		if (connp->conn_recvslla) {
25826 			in_flags |= IPF_RECVSLLA;
25827 		}
25828 		if (isv4) {
25829 			mp = ip_add_info(mp, recv_ill, in_flags);
25830 		} else {
25831 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
25832 			if (mp == NULL) {
25833 				CONN_DEC_REF(connp);
25834 				return;
25835 			}
25836 		}
25837 	}
25838 
25839 	BUMP_MIB(&ip_mib, ipInDelivers);
25840 	/*
25841 	 * We are sending the IPSEC_IN message also up. Refer
25842 	 * to comments above this function.
25843 	 */
25844 	putnext(rq, mp);
25845 	CONN_DEC_REF(connp);
25846 }
25847 
25848 /*
25849  * Martian Address Filtering [RFC 1812, Section 5.3.7]
25850  */
25851 static boolean_t
25852 ip_no_forward(ipha_t *ipha, ill_t *ill)
25853 {
25854 	ipaddr_t ip_src, ip_dst;
25855 	ire_t *src_ire = NULL;
25856 
25857 	ip_src = ntohl(ipha->ipha_src);
25858 	ip_dst = ntohl(ipha->ipha_dst);
25859 
25860 	if (ip_dst == INADDR_ANY)
25861 		goto dont_forward;
25862 
25863 	if (IN_CLASSD(ip_src))
25864 		goto dont_forward;
25865 
25866 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
25867 		goto dont_forward;
25868 
25869 	if (IN_BADCLASS(ip_dst))
25870 		goto dont_forward;
25871 
25872 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
25873 	    ALL_ZONES, MATCH_IRE_TYPE);
25874 	if (src_ire != NULL) {
25875 		ire_refrele(src_ire);
25876 		goto dont_forward;
25877 	}
25878 
25879 	return (B_FALSE);
25880 
25881 dont_forward:
25882 	if (ip_debug > 2) {
25883 		printf("ip_no_forward: dropping packet received on %s\n",
25884 		    ill->ill_name);
25885 		pr_addr_dbg("ip_no_forward: from src %s\n",
25886 		    AF_INET, &ipha->ipha_src);
25887 		pr_addr_dbg("ip_no_forward: to dst %s\n",
25888 		    AF_INET, &ipha->ipha_dst);
25889 	}
25890 	BUMP_MIB(&ip_mib, ipForwProhibits);
25891 	return (B_TRUE);
25892 }
25893 
25894 static boolean_t
25895 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
25896 {
25897 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
25898 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
25899 		if (ip_debug > 2) {
25900 			if (ill != NULL) {
25901 				printf("ip_loopback_src_or_dst: "
25902 				    "dropping packet received on %s\n",
25903 				    ill->ill_name);
25904 			} else {
25905 				printf("ip_loopback_src_or_dst: "
25906 				    "dropping packet\n");
25907 			}
25908 
25909 			pr_addr_dbg(
25910 			    "ip_loopback_src_or_dst: from src %s\n",
25911 			    AF_INET, &ipha->ipha_src);
25912 			pr_addr_dbg(
25913 			    "ip_loopback_src_or_dst: to dst %s\n",
25914 			    AF_INET, &ipha->ipha_dst);
25915 		}
25916 
25917 		BUMP_MIB(&ip_mib, ipInAddrErrors);
25918 		return (B_TRUE);
25919 	}
25920 	return (B_FALSE);
25921 }
25922